text:
(function($, undefined) {
    $.widget('view.vieImageSearch', {

        _create: function () {
            //extend VIE with an ontological representation of the images
            var v = this.options.vie;
			if (v.types.get("ImageObject").attributes.get("depicts") !== undefined) {
				v.types.get("ImageObject").attributes.add("depicts", ["Thing"]);
				v.types.get("Thing").attributes.get("image").range.push("ImageObject");
				v.types.add("VIEImageResult", [
				   {
				   "id"    : "query",
				   "range" : ["Text", "Thing"]
				   },
				   {
				   "id"    : "service",
				   "range" : ["Text", "Thing"]
				   },
				   {
					"id"    : "time",
					"range" : "Date"
				   },
				   {
					"id"    : "entity",
					"range" : "Thing"
				   }]
				).inherit(v.types.get("Thing"));
			}
            return this;
        },

        _init: function () {
            this.triggerSearch(this.options.entity);
        },

        render: function (data) {
            data.time = (data.time)? data.time : new Date();
            if (data.queryId === this.options.query_id) {
                for (var p = 0; p < data.objects.length; p++) {
                    this._triplifyImage(data.objects[p], data.time, data.serviceId, data.entityId, data.queryId);
                    this.options.objects.push(data.objects[p]);
                }
                delete data["objects"];
                var render = (this.options.render)? this.options.render : this._render;
                render.call(this, data);
            } else {
                //discard results as they depend on an old query
            }
        },

        _render: function (data) {
            var self = this;

            var objects = self.options.objects;
            var time = data.time;

            // clear the container element
            $(self.element).empty();

            //rendering
            for (var p = 0; p < objects.length && p < this.options.bin_size; p++) {
                var object = objects[p];
                var image = $('')
                    .append($(""));
                $(self.element).append(image);
            }
            return this;
        },

        triggerSearch: function (entityId, pageNum) {
            var self = this;

            if (this.options.timer) {
                clearTimeout(this.options.timer);
            }
            this.options.query_id++;
            var qId = this.options.query_id;
            this.options.objects = [];
            this.options.page_num = (pageNum)? pageNum : 0;

            var entity = undefined;
            if (typeof entityId === "string") {
                entity = this.options.vie.entities.get(entityId);
            } else {
                entity = entityId;
            }

            if (entity) {
                var queryPerformed = false;
                for (var s in this.options.services) {
                    var service = this.options.services[s];
                    if (service.use) {
                        this._trigger('start_query', undefined, {entity: entity, service: s, time: new Date(), queryId : qId});
                        service.query(entity, s, this, qId);
                        queryPerformed = true;
                    }
                }
                if (queryPerformed) {
                    this.options.timer = setTimeout(function (widget) {
                        return function () {
                            // discard all results that return after this timeout happened
                            widget.options.query_id++;
                        };
                    }(this), this.options.timeout, "JavaScript");
                }
            } else {
                this._trigger('error', undefined, {msg: "Entity needs to be registered in VIE.", id : entityId});
            }
            return this;
        },

        _triplifyImage: function (photo, time, serviceId, entityId, queryId) {
            var entity = this.options.vie.entities.get(entityId);

            var imageId = "<" + photo.original + ">";
            this.options.vie.entities.addOrUpdate({
                '@subject' : imageId,
                '@type'    : "ImageObject",
                "time"     : time.toUTCString(),
                "query"    : queryId,
                "service"  : serviceId,
                "entity"   : entity.id,
                "image"    : photo.original
            });
            entity.setOrAdd('image', imageId);
        },

        _getUrlMainPartFromEntity : function (entity, serviceId) {
            var service = this.options.services[serviceId];

            entity = ($.isArray(entity))? entity : [ entity ];

            for (var e = 0; e < entity.length; e++) {
                var types = entity[e].get('@type');
                types = ($.isArray(types))? types : [ types ];

                for (var t = 0; t < types.length; t++) {
                    var type = this.options.vie.types.get(types[t]);
                    if (type) {
                        var tsKeys = [];
                        for (var q in this.options.ts_url) {
                            tsKeys.push(q);
                        }
                        //sort the keys in ascending order!
                        tsKeys = this.options.vie.types.sort(tsKeys, false);
                        for (var q = 0; q < tsKeys.length; q++) {
                            var key = tsKeys[q];
                            if (type.isof(key) && this.options.ts_url[key][serviceId]) {
                                var ret = this.options.ts_url[key][serviceId].call(this, entity[e], serviceId);
                                if (ret) {
                                    return ret;
                                }
                            }
                        }
                    }
                }
            }
            return "";
        },

        options: {
            vie         : new VIE(),
            timeout     : 10000,
            bin_size  : 10,
            services    : {
                'gimage' : {
                    use       : false,
                    api_key   : undefined,
                    safe      : "active", //active,moderate,off
                    base_url  : "https://ajax.googleapis.com/ajax/services/search/images?v=1.0",
                    tail_url  : function (widget, service) {
                        var url = "&safe=" + service.safe;
                        url += "&rsz=" + widget.options.bin_size;
                        url += "&start=" + (widget.options.page_num * widget.options.bin_size);
                        url += "&callback=?";

                        return url;
                    },
                    query : function (entity, serviceId, widget, queryId) {
                        // assemble the URL

                        var mainUrl = widget._getUrlMainPartFromEntity(entity, serviceId);

                        if (mainUrl) {
                            var url = this.base_url;
                            url += mainUrl;
                            url += this.tail_url(widget, this);
                            // trigger the search & receive the data via callback
                            jQuery.getJSON(url,this.callback(widget, entity.id, serviceId, queryId));
                        } else {
                            widget._trigger("error", undefined, {
                                msg: "No type-specific URL can be acquired for entity. Please add/overwrite widget.options[<widget_type>][" + serviceId + "]!",
                                id : entity.id,
                                service : serviceId,
                                queryId : queryId});
                        }
                    },
                    callback  : function (widget, entityId, serviceId, queryId) {
                        return function (data) {
                            var objects = [];
                            if (data && data.responseStatus === 200) {
                                var rData = data.responseData.results;
                                for (var r = 0; r < rData.length; r++) {
                                    var thumnail = rData[r].tbUrl;
                                    var original = rData[r].url;

                                    var obj = {
                                        "thumbnail" : thumnail,
                                        "original" : original
                                    };
                                    objects.push(obj);
                                }
                            }
                            var data = {entityId : entityId, serviceId: serviceId, queryId : queryId, time: new Date(), objects: objects};
                            widget._trigger('end_query', undefined, data);
                            widget.render(data);
                          };
                    }
                },
                'flickr' : {
                    use       : false,
                    api_key   : undefined,
                    sort      : 'relevance',
                    safe      : 1,
                    base_url  : "http://api.flickr.com/services/rest/?method=flickr.photos.search",
                    tail_url  : function (widget, service) {
                        var url = "&sort=" + service.sort;

                        url += "&per_page=" + widget.options.bin_size;
                        url += "&page=" + widget.options.page_num;
                        url += "&api_key=" + service.api_key;
                        url += "&safe_search=" + service.safe; // safe search
                        url += "&extras=url_o&format=json&jsoncallback=?";

                        return url;
                    },
                    query : function (entity, serviceId, widget, queryId) {

                        var mainUrl = widget._getUrlMainPartFromEntity(entity, serviceId);

                        if (mainUrl) {
                            // assemble the URL
                            var url = this.base_url;
                            url += mainUrl;
                            url += this.tail_url(widget, this);
                            // trigger the search & receive the data via callback
                            jQuery.getJSON(url,this.callback(widget, entity.id, serviceId, queryId));
                        } else {
                            widget._trigger("error", undefined, {
                                msg: "No type-specific URL can be acquired for entity. Please add/overwrite widget.options[<widget_type>][" + serviceId + "]!",
                                id : entity.id,
                                service : serviceId,
                                queryId : queryId});
                        }
                    },
                    callback  : function (widget, entityId, serviceId, queryId) {
                        return function (data) {
                              var objects = [];
                              if (data.stat === 'ok' && data.photos.total > 0) {
                                  //put them into bins
                                  for (var i = 0; i < data.photos.photo.length; i++) {
                                      var photo = data.photos.photo[i];
                                      var imgS = 'http://farm' +
                                              photo.farm + '.static.flickr.com/' +
                                              photo.server + '/' +
                                              photo.id + '_' +
                                              photo.secret + '_s.jpg';

                                      var imgZ = 'http://farm' +
                                              photo.farm + '.static.flickr.com/' +
                                              photo.server + '/' +
                                              photo.id + '_' +
                                              photo.secret + '_z.jpg';

                                      var obj = {
                                              "thumbnail" : imgS,
                                              "original" : imgZ
                                      };
                                      objects.push(obj);
                                  }
                              }
                              var data = {entityId : entityId, serviceId: serviceId, queryId : queryId, time: new Date(), objects: objects};
                              widget._trigger('end_query', undefined, data);
                              widget.render(data);
                          };
                    }
                }
            },
            ts_url : {
                "Thing" : {
                    'flickr' : function (entity, serviceId) {
                        var url = "";
                        if (entity.has("name")) {
                            var name = entity.get("name");
                            if ($.isArray(name) && name.length > 0) {
                                name = name[0]; //just take the first
                            }
                            url += "&text="; // *no* type-specific keywords
                            url += name;
                        }
                        return url;
                    },
                    'gimage' : function (entity, serviceId) {
                        var url = "";
                        if (entity.has("name")) {
                            var name = entity.get("name");
                            if ($.isArray(name) && name.length > 0) {
                                name = name[0]; //just take the first
                            }
                            url += "&q="; // *no* type-specific keywords
                            url += name.replace(/ /g, '+');
                        }
                        return url;
                    }
                },
                "Person" : {
                    'flickr' : function (entity, serviceId) {
                        var url = "";

                        if (entity.has("name")) {
                            var name = entity.get("name");
                            if ($.isArray(name) && name.length > 0) {
                                name = name[0]; //just take the first
                            }
                            url += "&text=portrait "; // type-specific keywords
                            url += name;
                        } else {
                            return undefined
                        }
                        return url;
                    },
                    'gimage' : function (entity, serviceId) {
                        var url = "";
                        if (entity.has("name")) {
                            var name = entity.get("name");
                            if ($.isArray(name) && name.length > 0) {
                                name = name[0]; //just take the first
                            }
                            url += "&imgtype=face"; // type-specific search for faces
                            url += "&q=";
                            url += name.replace(/ /g, '+');
                        }
                        return url;
                    }
                },
                "GeoCoordinates" : {
                    'flickr' : function (entity, serviceId) {
                        var url = "";

                        if (entity.has('latitude') &&
                            entity.has('longitude')) {
                            var ts = Math.round((new Date()).getTime() / 1000);
                            var minUploadDate = ts - 604800 * 100; // last 100 weeks
                            var radius = 10;
                            var radiusUnits = "km";

                            var lat = entity.get("latitude");
                            if ($.isArray(lat) && lat.length > 0) {
                                lat = lat[0]; //just take the first
                            }
                            var lon = entity.get("longitude");
                            if ($.isArray(lon) && lon.length > 0) {
                                lon = lon[0]; //just take the first
                            }

                            url += "&lat=" + lat + "&lon=" + lon;
                            url += "&min_upload_date=" + minUploadDate;
                            url += "&radius=" + radius;
                            url += "&text=tourist attraction"; // type-specific keywords!
                            url += "&radius_units=" + radiusUnits;
                        } else {
                            return undefined
                        }
                        return url;
                    },
                    'gimage' : function (entity, serviceId) {
                        return undefined;
                    }
                },
                "Place" : {
                    'flickr' : function (entity, serviceId) {
                        var url = "";

                        if (entity.has('geo')) {
                            var geo = entity.get("geo");
                            return this._getUrlMainPartFromEntity(geo, serviceId);
                        } else if (entity.has('containedIn')) {
                            var containedIn = entity.get('containedIn');
                            return this._getUrlMainPartFromEntity(containedIn, serviceId);
                        } else if (entity.has('name')) {
                            var name = entity.get("name");
                            if ($.isArray(name) && name.length > 0) {
                                name = name[0]; //just take the first
                            }
                            url += "&text=tourist attraction "; // type-specific keywords
                            url += name;
                        } else {
                            return undefined
                        }
                        return url;
                    },
                    'gimage' : function (entity, serviceId) {
                        var url = "";

                        if (entity.has('name')) {
                            var name = entity.get("name");
                            if ($.isArray(name) && name.length > 0) {
                                name = name[0]; //just take the first
                            }
                            url += "&imgtype=photo"; // type-specific commands
                            url += "&q=" + name.replace(/ /g, '+');
                        } else {
                            return undefined
                        }
                        return url;
                    }
                }
            },

            // helper
            render      : undefined,
            entity      : undefined,
            objects     : [],
            timer       : undefined,
            page_num    : 1,
            query_id    : 0,

            // events
            start_query : function () {},
            end_query   : function () {},
            error       : function () {}
        }

    });
})(jQuery);


text:
package eu.cloudwave.wp5.common.tests.assertion;

import static com.google.common.base.Preconditions.checkArgument;
import static com.google.common.base.Preconditions.checkNotNull;
import static org.fest.assertions.Assertions.assertThat;

import java.util.List;

/**
 * Provides common assert-methods.
 */
public class Asserts {

  private Asserts() {}

  /**
   * Can be used to test the equals- and hashCode-methods of a class.
   *
   * @param equalObjects
   *          a list of objects that are expected to be equal (minimum size of 2 objects is required)
   * @param differentObjects
   *          a list of objects that are expected to be different from the equal objects
   */
  public static <T extends Object> void assertEquality(final List<T> equalObjects, final List<T> differentObjects) {
    // check preconditions
    checkNotNull(equalObjects);
    checkNotNull(differentObjects);
    checkArgument(equalObjects.size() >= 2);

    // check equal objects
    for (int i = 0; i < equalObjects.size(); i++) {
      for (int j = i + 1; j < equalObjects.size(); j++) {
        assertObjectsAreEqual(equalObjects.get(i), equalObjects.get(j));
      }
    }

    // check different objects
    for (int i = 0; i < differentObjects.size(); i++) {
      assertObjectsAreNotEqual(equalObjects.get(0), differentObjects.get(i));
    }
  }

  /**
   * Asserts that two object are equal.
   *
   * @param one
   *          the first object
   * @param two
   *          the second object
   */
  public static void assertObjectsAreEqual(final Object one, final Object two) {
    assertThat(one).isEqualTo(two);
    assertThat(one.hashCode()).isEqualTo(two.hashCode());
  }

  /**
   * Asserts that two objects are not equal.
   *
   * @param one
   *          the first object
   * @param two
   *          the second object
   */
  public static void assertObjectsAreNotEqual(final Object one, final Object two) {
    assertThat(one).isNotEqualTo(two);
  }

}

redpajama_set_name: RedPajamaGithub


text:
package com.twitter.finagle.http

import org.junit.runner.RunWith
import org.scalatest.FunSuite
import org.scalatest.junit.JUnitRunner

@RunWith(classOf[JUnitRunner])
class ParamMapTest extends FunSuite {
  test("no params") {
    val request = Request("/search.json")
    assert(request.params.get("q") === None)
  }

  test("no params, just question mark") {
    val request = Request("/search.json")
    assert(request.params.get("q") === None)
  }

  test("params") {
    val request = Request("/search.json?q=twitter")
    assert(request.params.get("q") === Some("twitter"))
  }

  test("getShort") {
    assert(Request("?x=1").params.getShort("x")       === Some(1.toShort))
    assert(Request("?x=0").params.getShort("x")       === Some(0.toShort))
    assert(Request("?x=-1").params.getShort("x")      === Some((-1).toShort))
    assert(Request("?x=32767").params.getShort("x")   === Some(32767.toShort))
    assert(Request("?x=-32768").params.getShort("x")  === Some((-32768).toShort))
    assert(Request("?x=32768").params.getShort("x")   === Some(0.toShort))
    assert(Request("?x=-32769").params.getShort("x")  === Some(0.toShort))
    assert(Request("?x=garbage").params.getShort("x") === Some(0.toShort))
    assert(Request("?x=").params.getShort("x")        === Some(0.toShort))
    assert(Request("?y=2").params.getShort("x")       === None)
  }

  test("getInt") {
    assert(Request("?x=1").params.getInt("x")           === Some(1))
    assert(Request("?x=0").params.getInt("x")           === Some(0))
    assert(Request("?x=-1").params.getInt("x")          === Some(-1))
    assert(Request("?x=2147483647").params.getInt("x")  === Some(2147483647))
    assert(Request("?x=-2147483648").params.getInt("x") === Some(-2147483648))
    assert(Request("?x=2147483648").params.getInt("x")  === Some(0))
    assert(Request("?x=-2147483649").params.getInt("x") === Some(0))
    assert(Request("?x=garbage").params.getInt("x")     === Some(0))
    assert(Request("?x=").params.getInt("x")            === Some(0))
    assert(Request("?y=2").params.getInt("x")           === None)
  }

  test("getLong") {
    assert(Request("?x=1").params.getLong("x")                    === Some(1L))
    assert(Request("?x=0").params.getLong("x")                    === Some(0L))
    assert(Request("?x=-1").params.getLong("x")                   === Some(-1L))
    assert(Request("?x=9223372036854775807").params.getLong("x")  === Some(9223372036854775807L))
    assert(Request("?x=-9223372036854775808").params.getLong("x") === Some(-9223372036854775808L))
    assert(Request("?x=9223372036854775808").params.getLong("x")  === Some(0L))
    assert(Request("?x=-9223372036854775809").params.getLong("x") === Some(0L))
    assert(Request("?x=garbage").params.getLong("x")              === Some(0L))
    assert(Request("?x=").params.getLong("x")                     === Some(0L))
    assert(Request("?y=2").params.getLong("x")                    === None)
  }

  test("getBoolean") {
    assert(Request("?x=true").params.getBoolean("x")    === Some(true))
    assert(Request("?x=TRUE").params.getBoolean("x")    === Some(true))
    assert(Request("?x=True").params.getBoolean("x")    === Some(true))
    assert(Request("?x=t").params.getBoolean("x")       === Some(true))
    assert(Request("?x=1").params.getBoolean("x")       === Some(true))
    assert(Request("?x=false").params.getBoolean("x")   === Some(false))
    assert(Request("?x=").params.getBoolean("x")        === Some(false))
    assert(Request("?x=garbage").params.getBoolean("x") === Some(false))
    assert(Request("?y=2").params.getBoolean("x")       === None)
  }

  test("params encoded") {
    val request = Request("/search.json?%71=%74%77%69%74%74%65%72")
    assert(request.params.get("q") === Some("twitter"))
  }

  test("params and equals encoded") {
    val request = Request("/search.json?%71%3D%74%77%69%74%74%65%72")
    assert(request.params.get("q") === None)
  }

  test("multiple params") {
    val request = Request("/search.json?q=twitter&lang=en")
    assert(request.params.get("q")    === Some("twitter"))
    assert(request.params.get("lang") === Some("en"))
  }

  test("key, no value") {
    val request = Request("/search.json?q=")
    assert(request.params.get("q") === Some(""))
  }

  test("value, no key is ignored") {
    val request = Request("/search.json?=value")
    assert(request.params.get("") === None)
  }

  test("favor first value") {
    val request = Request("/search.json?q=twitter&q=twitter2")
    assert(request.params.get("q") === Some("twitter"))
    assert(request.params.keys.toList === List("q"))
    assert(request.params.keySet.toList === List("q"))
    assert(request.params.keysIterator.toList === List("q"))
  }

  test("getAll") {
    val request = Request("/search.json?q=twitter&q=twitter2")
    assert(request.params.getAll("q").toList === List("twitter", "twitter2"))
  }

  test("iterator") {
    val request = Request("/search.json?q=twitter&q=twitter2&lang=en")
    assert(request.params.iterator.toList.sorted === List(("lang", "en"), ("q", "twitter"), ("q", "twitter2")))
  }

  test("plus") {
    val request = Request("/search.json?q=twitter")
    val params = request.params + ("lang" -> "en")
    assert(params.get("q")    === Some("twitter"))
    assert(params.get("lang") === Some("en"))
  }

  test("minus") {
    val request = Request("/search.json?q=twitter")
    val params = request.params - "q"
    assert(params.get("q") === None)
  }

  test("empty") {
    val request = Request("/search.json?q=twitter")
    val params = request.params.empty
    assert(params.get("q") === None)
  }

  test("toString") {
    assert(Request("/search.json?q=twitter").params.toString === "?q=twitter")
    assert(Request("/search.json").params.toString           === "")
  }

  test("get, POST params") {
    testPostParams(Method.Post)
    testPostParams(Method.Put)

    def testPostParams(method: Method): Unit = {
      val request = Request(method, "/search.json")
      request.contentType = "application/x-www-form-urlencoded"
      request.contentString = "q=twitter"
      assert(request.params.get("q") === Some("twitter"))
    }
  }

  test("getAll, POST params") {
    testPostParams(Method.Post)
    testPostParams(Method.Put)

    def testPostParams(method: Method): Unit = {
      val request = Request(method, "/search.json?q=twitter2")
      request.contentType = "application/x-www-form-urlencoded"
      request.contentString = "q=twitter"
      assert(request.params.get("q") === Some("twitter")) // favor POST param
      assert(request.params.getAll("q").toList.sorted === List("twitter", "twitter2"))
    }
  }

  test("ignore body only during TRACE requests") {
    val url = "/search.json?lang=en"
    val contentType = "application/x-www-form-urlencoded"
    val contentString = "q=twitter"

    val getRequest = Request(Method.Get, url)
    getRequest.contentType = contentType
    getRequest.contentString = contentString
    assert(getRequest.params.get("q") === Some("twitter"))
    assert(getRequest.params.get("lang") === Some("en"))

    val traceRequest = Request(Method.Trace, url)
    traceRequest.contentType = contentType
    traceRequest.contentString = contentString
    assert(traceRequest.params.get("q") === None)
    assert(traceRequest.params.get("lang") === Some("en"))
  }

  test("weird encoded characters") {
    for (i <- 0x7f until 0xff) {
      val getRequest = Request("/search.json?q=%%02x".format(i))
      assert(getRequest.params.get("q").nonEmpty === true)

      val postRequest = Request(Method.Post, "/search.json")
      postRequest.contentType = "application/x-www-form-urlencoded"
      postRequest.contentString = "q=%%02x".format(i)
      assert(postRequest.params.get("q").nonEmpty === true)
    }
  }

  test("illegal hex characters") {
    val request = Request("/search.json?q=%u3")
    assert(request.params.isValid === false)
  }

  test("incomplete trailing escape") {
    val request = Request("/search.json?q=%3")
    assert(request.params.isValid === false)
  }

  test("quotes are ok") {
    // Java's URL doesn't allow this, but we do.
    val request = Request("/search.json?q=\"twitter\"")
    assert(request.params.get("q") === Some("\"twitter\""))
  }
}


text:
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="com.prahladyeri.android.droidwells"
    android:versionCode="1"
    android:versionName="5.3" >

    <uses-sdk
        android:minSdkVersion="11"
        android:targetSdkVersion="21" />

    <uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />

    <application
        android:allowBackup="true"
        android:icon="@drawable/ic_launcher"
        android:label="@string/app_name"
        android:theme="@style/AppTheme" >
        <activity
            android:name=".MainActivity"
            android:label="@string/app_name">
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />

                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>
        <activity
            android:name=".AddWellsActivity"
            android:label="@string/title_activity_add_wells"
            android:parentActivityName=".MainActivity" >
            <meta-data
                android:name="android.support.PARENT_ACTIVITY"
                android:value="com.prahladyeri.android.droidwells.MainActivity" />
        </activity>
        <activity
            android:name=".DeleteWellsActivity"
            android:label="@string/title_activity_delete_wells"
            android:parentActivityName=".MainActivity" >
            <meta-data
                android:name="android.support.PARENT_ACTIVITY"
                android:value="com.prahladyeri.android.droidwells.MainActivity" />
        </activity>
        <activity
            android:name=".NewDayActivity"
            android:label="@string/title_activity_new_day" >
        </activity>
        <activity
            android:name=".NewDayTanksActivity"
            android:label="@string/title_activity_new_day_tanks"
            android:parentActivityName=".NewDayActivity" >
            <meta-data
                android:name="android.support.PARENT_ACTIVITY"
                android:value="com.prahladyeri.android.droidwells.NewDayActivity" />
        </activity>
    </application>

</manifest>


text:
README.
---

API Rest para administración de Base de Datos en MongoDB para el uso exclusivo de la aplicacion **MyWallet**.


text:
package com.appleframework.tools.exceptions;

import com.appleframework.tools.util.StrUtil;

/**
 * 验证异常
 *
 * @author xiaoleilu
 */
public class ValidateException extends StatefulException {
	private static final long serialVersionUID = 6057602589533840889L;

	public ValidateException() {
	}

	public ValidateException(String msg) {
		super(msg);
	}

	public ValidateException(String messageTemplate, Object... params) {
		super(StrUtil.format(messageTemplate, params));
	}

	public ValidateException(Throwable throwable) {
		super(throwable);
	}

	public ValidateException(String msg, Throwable throwable) {
		super(msg, throwable);
	}

	public ValidateException(int status, String msg) {
		super(status, msg);
	}

	public ValidateException(int status, Throwable throwable) {
		super(status, throwable);
	}

	public ValidateException(int status, String msg, Throwable throwable) {
		super(status, msg, throwable);
	}
}


text:
#pragma once

#include <unordered_map>
#include <vector>

#include <folly/Range.h>

namespace folly {
struct dynamic;
} // namespace folly

namespace facebook {
namespace memcache {

class WeightedChHashFuncBase {
 public:
  /**
   * @param weights  A list of server weights.
   *                 Pool size is taken to be weights.size()
   */
  explicit WeightedChHashFuncBase(std::vector<double> weights)
      : weights_(std::move(weights)) {}

  /**
   * @param json  Json object of the following format:
   *              {
   *                "weights": [ ... ]
   *              }
   * @param n     Number of servers in the config.
   */
  WeightedChHashFuncBase(const folly::dynamic& json, size_t n)
      : weights_(parseWeights(json, n)) {}

  /**
   * @return Saved weights.
   */
  const std::vector<double>& weights() const {
    return weights_;
  }

  static std::vector<double> parseWeights(const folly::dynamic& json, size_t n);

 protected:
  static constexpr size_t kNumTries = 32;

  const std::vector<double> weights_;
};

} // namespace memcache
} // namespace facebook


text:
from bucky import create_app

app = create_app('development')

if __name__ == "__main__":
    app.run()


text:
SYNONYM

#### According to
The Catalogue of Life, 3rd January 2011

#### Published in
null

#### Original name
Melampsora sparsa G. Winter, 1881

### Remarks
null


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

  <meta http-equiv="Content-Type" content="text/html; charset=utf-8">

  <meta http-equiv="X-UA-Compatible" content="IE=EmulateIE7" >
  <title>Zooming with Point Labels</title>

  <link rel="stylesheet" type="text/css" href="../jquery.jqplot.css" />
  <link rel="stylesheet" type="text/css" href="examples.css" />

<?php include "nav.inc"; ?>

Click and drag to zoom.  Double click on plot or click "Reset Zoom" button to reset zoom.

<button value="reset" type="button" onclick="$.jqplot.Cursor.resetZoom(plot)">Reset Zoom</button>


text:
<?php
namespace TYPO3\CMS\IndexedSearch;

/**
 * Lexer class for indexed_search
 * A lexer splits the text into words
 */
class Lexer
{
    /**
     * Debugging options:
     *
     * @var bool
     */
    public $debug = false;

    /**
     * If set, the debugString is filled with HTML output highlighting search / non-search words (for backend display)
     *
     * @var string
     */
    public $debugString = '';

    /**
     * Charset class object
     *
     * @var \TYPO3\CMS\Core\Charset\CharsetConverter
     */
    public $csObj;

    /**
     * Configuration of the lexer:
     *
     * @var array
     */
    public $lexerConf = [
        //Characters: . - _ : / '
        'printjoins' => [46, 45, 95, 58, 47, 39],
        'casesensitive' => false,
        // Set, if case sensitive indexing is wanted.
        'removeChars' => [45]
    ];

    /**
     * Constructor: Initializes the charset class
     *
     */
    public function __construct()
    {
        $this->csObj = \TYPO3\CMS\Core\Utility\GeneralUtility::makeInstance(\TYPO3\CMS\Core\Charset\CharsetConverter::class);
    }

    /**
     * Splitting string into words.
     * Used for indexing, can also be used to find words in query.
     *
     * @param string String with UTF-8 content to process.
     * @return array Array of words in utf-8
     */
    public function split2Words($wordString)
    {
        // Reset debug string:
        $this->debugString = '';
        // Then convert the string to lowercase:
        if (!$this->lexerConf['casesensitive']) {
            $wordString = $this->csObj->conv_case('utf-8', $wordString, 'toLower');
        }
        // Now, splitting words:
        $len = 0;
        $start = 0;
        $pos = 0;
        $words = [];
        $this->debugString = '';
        while (1) {
            list($start, $len) = $this->get_word($wordString, $pos);
            if ($len) {
                $this->addWords($words, $wordString, $start, $len);
                if ($this->debug) {
                    $this->debugString .= '' . htmlspecialchars(substr($wordString, $pos, ($start - $pos))) . '' . htmlspecialchars(substr($wordString, $start, $len));
                }
                $pos = $start + $len;
            } else {
                break;
            }
        }
        return $words;
    }

    /**********************************
     *
     * Helper functions
     *
     ********************************/
    /**
     * Add word to word-array
     * This function should be used to make sure CJK sequences are split up in the right way
     *
     * @param array $words Array of accumulated words
     * @param string $wordString Complete Input string from where to extract word
     * @param int $start Start position of word in input string
     * @param int $len The Length of the word string from start position
     * @return void
     */
    public function addWords(&$words, &$wordString, $start, $len)
    {
        // Get word out of string:
        $theWord = substr($wordString, $start, $len);
        // Get next chars unicode number and find type:
        $bc = 0;
        $cp = $this->utf8_ord($theWord, $bc);
        list($cType) = $this->charType($cp);
        // If string is a CJK sequence we follow this algorithm:
        /*
        DESCRIPTION OF (CJK) ALGORITHMContinuous letters and numbers make up words. Spaces and symbols
        separate letters and numbers into words. This is sufficient for
        all western text.CJK doesn't use spaces or separators to separate words, so the only
        way to really find out what constitutes a word would be to have a
        dictionary and advanced heuristics. Instead, we form pairs from
        consecutive characters, in such a way that searches will find only
        characters that appear more-or-less the right sequence. For example:ABCDE => AB BC CD DEThis works okay since both the index and the search query is split
        in the same manner, and since the set of characters is huge so the
        extra matches are not significant.(Hint taken from ZOPEs chinese user group)[Kasper: As far as I can see this will only work well with or-searches!]
         */
        if ($cType == 'cjk') {
            // Find total string length:
            $strlen = $this->csObj->utf8_strlen($theWord);
            // Traverse string length and add words as pairs of two chars:
            for ($a = 0; $a < $strlen; $a++) {
                if ($strlen == 1 || $a < $strlen - 1) {
                    $words[] = $this->csObj->utf8_substr($theWord, $a, 2);
                }
            }
        } else {
            // Normal "single-byte" chars:
            // Remove chars:
            foreach ($this->lexerConf['removeChars'] as $skipJoin) {
                $theWord = str_replace($this->csObj->UnumberToChar($skipJoin), '', $theWord);
            }
            // Add word:
            $words[] = $theWord;
        }
    }

    /**
     * Get the first word in a given utf-8 string (initial non-letters will be skipped)
     *
     * @param string $str Input string (reference)
     * @param int $pos Starting position in input string
     * @return array 0: start, 1: len or FALSE if no word has been found
     */
    public function get_word(&$str, $pos = 0)
    {
        $len = 0;
        // If return is TRUE, a word was found starting at this position, so returning position and length:
        if ($this->utf8_is_letter($str, $len, $pos)) {
            return [$pos, $len];
        }
        // If the return value was FALSE it means a sequence of non-word chars were found (or blank string) - so we will start another search for the word:
        $pos += $len;
        if ($str[$pos] == '') {
            // Check end of string before looking for word of course.
            return false;
        }
        $this->utf8_is_letter($str, $len, $pos);
        return [$pos, $len];
    }

    /**
     * See if a character is a letter (or a string of letters or non-letters).
     *
     * @param string $str Input string (reference)
     * @param int $len Byte-length of character sequence (reference, return value)
     * @param int $pos Starting position in input string
     * @return bool letter (or word) found
     */
    public function utf8_is_letter(&$str, &$len, $pos = 0)
    {
        $len = 0;
        $bc = 0;
        $cp = 0;
        $printJoinLgd = 0;
        $cType = ($cType_prev = false);
        // Letter type
        $letter = true;
        // looking for a letter?
        if ($str[$pos] == '') {
            // Return FALSE on end-of-string at this stage
            return false;
        }
        while (1) {
            // If characters has been obtained we will know whether the string starts as a sequence of letters or not:
            if ($len) {
                if ($letter) {
                    // We are in a sequence of words
                    if (
                        !$cType
                        || $cType_prev == 'cjk' && ($cType === 'num' || $cType === 'alpha')
                        || $cType == 'cjk' && ($cType_prev === 'num' || $cType_prev === 'alpha')
                    ) {
                        // Check if the non-letter char is NOT a print-join char because then it signifies the end of the word.
                        if (!in_array($cp, $this->lexerConf['printjoins'])) {
                            // If a printjoin start length has been recorded, set that back now so the length is right (filtering out multiple end chars)
                            if ($printJoinLgd) {
                                $len = $printJoinLgd;
                            }
                            return true;
                        } else {
                            // If a printJoin char is found, record the length if it has not been recorded already:
                            if (!$printJoinLgd) {
                                $printJoinLgd = $len;
                            }
                        }
                    } else {
                        // When a true letter is found, reset printJoinLgd counter:
                        $printJoinLgd = 0;
                    }
                } elseif (!$letter && $cType) {
                    // end of non-word reached
                    return false;
                }
            }
            $len += $bc;
            // add byte-length of last found character
            if ($str[$pos] == '') {
                // End of string; return status of string till now
                return $letter;
            }
            // Get next chars unicode number:
            $cp = $this->utf8_ord($str, $bc, $pos);
            $pos += $bc;
            // Determine the type:
            $cType_prev = $cType;
            list($cType) = $this->charType($cp);
            if ($cType) {
                continue;
            }
            // Setting letter to FALSE if the first char was not a letter!
            if (!$len) {
                $letter = false;
            }
        }
        return false;
    }

    /**
     * Determine the type of character
     *
     * @param int $cp Unicode number to evaluate
     * @return array Type of char; index-0: the main type: num, alpha or CJK (Chinese / Japanese / Korean)
     */
    public function charType($cp)
    {
        // Numeric?
        if ($cp >= 48 && $cp <= 57) {
            return ['num'];
        }
        // LOOKING for Alpha chars (Latin, Cyrillic, Greek, Hebrew and Arabic):
        if ($cp >= 65 && $cp <= 90 || $cp >= 97 && $cp <= 122 || $cp >= 192 && $cp <= 255 && $cp != 215 && $cp != 247 || $cp >= 256 && $cp < 640 || ($cp == 902 || $cp >= 904 && $cp < 1024) || ($cp >= 1024 && $cp < 1154 || $cp >= 1162 && $cp < 1328) || ($cp >= 1424 && $cp < 1456 || $cp >= 1488 && $cp < 1523) || ($cp >= 1569 && $cp <= 1624 || $cp >= 1646 && $cp <= 1747) || $cp >= 7680 && $cp < 8192) {
            return ['alpha'];
        }
        // Looking for CJK (Chinese / Japanese / Korean)
        // Ranges are not certain - deducted from the translation tables in typo3/sysext/core/Resources/Private/Charsets/csconvtbl/
        // Verified with http://www.unicode.org/charts/ (16/2) - may still not be complete.
        if ($cp >= 12352 && $cp <= 12543 || $cp >= 12592 && $cp <= 12687 || $cp >= 13312 && $cp <= 19903 || $cp >= 19968 && $cp <= 40879 || $cp >= 44032 && $cp <= 55215 || $cp >= 131072 && $cp <= 195103) {
            return ['cjk'];
        }
    }

    /**
     * Converts a UTF-8 multibyte character to a UNICODE codepoint
     *
     * @param string $str UTF-8 multibyte character string (reference)
     * @param int $len The length of the character (reference, return value)
     * @param int $pos Starting position in input string
     * @param bool $hex If set, then a hex. number is returned
     * @return int UNICODE codepoint
     */
    public function utf8_ord(&$str, &$len, $pos = 0, $hex = false)
    {
        $ord = ord($str[$pos]);
        $len = 1;
        if ($ord > 128) {
            for ($bc = -1, $mbs = $ord; $mbs & 128; $mbs = $mbs << 1) {
                // calculate number of extra bytes
                $bc++;
            }
            $len += $bc;
            $ord = $ord & (1 << 6 - $bc) - 1;
            // mask utf-8 lead-in bytes
            // "bring in" data bytes
            for ($i = $pos + 1; $bc; $bc--, $i++) {
                $ord = $ord << 6 | ord($str[$i]) & 63;
            }
        }
        return $hex ? 'x' . dechex($ord) : $ord;
    }
}


text:
@extends ('backend.layouts.master')

@section ('title', trans('labels.backend.access.users.management') . ' | ' . trans('labels.backend.access.users.change_password'))

@section('page-header')

        {{ trans('labels.backend.access.users.management') }}
        {{ trans('labels.backend.access.users.change_password') }}

@endsection

@section('content')
    {{ Form::open(['route' => ['admin.access.user.change-password', $user], 'class' => 'form-horizontal', 'role' => 'form', 'method' => 'post']) }}

{{ trans('labels.backend.access.users.change_password_for', ['user' => $user->name]) }}

                    @include('backend.access.includes.partials.header-buttons')

                    {{ Form::label('password', trans('validation.attributes.backend.access.users.password'), ['class' => 'col-lg-2 control-label', 'placeholder' => trans('validation.attributes.backend.access.users.password')]) }}

                        {{ Form::password('password', ['class' => 'form-control']) }}

                    {{ Form::label('password_confirmation', trans('validation.attributes.backend.access.users.password_confirmation'), ['class' => 'col-lg-2 control-label', 'placeholder' => trans('validation.attributes.backend.access.users.password_confirmation')]) }}

                        {{ Form::password('password_confirmation', ['class' => 'form-control']) }}

                    {{ link_to_route('admin.access.user.index', trans('buttons.general.cancel'), [], ['class' => 'btn btn-danger btn-xs']) }}

                    {{ Form::submit(trans('buttons.general.crud.update'), ['class' => 'btn btn-success btn-xs']) }}

    {{ Form::close() }}
@stop


text:
package com.interviews.algo;

import java.util.*;

public class Backtrack {

    /**
     * Pick a starting point.
     * while(Problem is not solved)
     * For each path from the starting point.
     * check if selected path is safe,
     * if yes select it
     * and make recursive call to rest of the problem
     * before which undo the current move.
     * End For
     * <p>
     * If none of the move works out, return false, NO SOLUTON.
     */

    //*****************************************************************************************
    // Subsets : https://leetcode.com/problems/subsets/
    // Combinations
    //*****************************************************************************************

    public List<List<Integer>> subsets(int[] array) {
        List<List<Integer>> list = new ArrayList<>();
        subsetBacktrack(list, new ArrayList<>(), array, 0);
        return list;
    }

    private void subsetBacktrack(List<List<Integer>> result, List<Integer> tempList, int[] array, int start) {

        result.add(new ArrayList<>(tempList));

        for (int i = start; i < array.length; i++) {

            tempList.add(array[i]);
            subsetBacktrack(result, tempList, array, i + 1);
            tempList.remove(tempList.size() - 1);

        }
    }

    //*****************************************************************************************
    // Generate all subsets of size k
    // Subsets : https://leetcode.com/problems/subsets/
    // Combinations
    //*****************************************************************************************

    public List<List<Integer>> subsetsOfSizeK(int[] array, int K) {
        List<List<Integer>> list = new ArrayList<>();
        subsetSizeKBacktrack(list, new ArrayList<>(), K, array, 0);
        return list;
    }

    private void subsetSizeKBacktrack(List<List<Integer>> result, List<Integer> tempList,
                                      int K, int[] array, int start) {

        if (tempList.size() == K) {
            result.add(new ArrayList<>(tempList));
        } else {

            for (int i = start; i < array.length; i++) {

                tempList.add(array[i]);
                subsetSizeKBacktrack(result, tempList, K, array, i + 1);
                tempList.remove(tempList.size() - 1);

            }
        }
    }

    //*****************************************************************************************
    // Subsets II (contains duplicates) : https://leetcode.com/problems/subsets-ii/
    // Combinations
    //*****************************************************************************************

    public List<List<Integer>> subsetsWithDup(int[] nums) {

        List<List<Integer>> list = new ArrayList<>();
        Arrays.sort(nums);
        subsetsWithDupBacktrack(list, new ArrayList<>(), nums, 0);
        return list;

    }

    private void subsetsWithDupBacktrack(List<List<Integer>> list, List<Integer> tempList,
                                         int[] nums, int start) {

        list.add(new ArrayList<>(tempList));

        for (int i = start; i < nums.length; i++) {

            //    if (i > start && nums[i] == nums[i - 1]) continue; // skip duplicates
            if (i > start && nums[i] != nums[i - 1]) {
                tempList.add(nums[i]);
                subsetsWithDupBacktrack(list, tempList, nums, i + 1);
                tempList.remove(tempList.size() - 1);
            }
        }

    }

    //*****************************************************************************************
    // Permutations : https://leetcode.com/problems/permutations/
    //*****************************************************************************************

    public List<List<Integer>> permutate(int[] array) {
        List<List<Integer>> list = new ArrayList<>();
        // Arrays.sort(nums); // not necessary
        permutateBacktrack(list, new ArrayList<>(), array);
        return list;
    }

    private void permutateBacktrack(List<List<Integer>> result, List<Integer> tempList, int[] array) {

        if (tempList.size() == array.length) {
            result.add(new ArrayList<>(tempList));
        } else {

            for (int i = 0; i < array.length; i++) {

                if (tempList.contains(array[i])) continue; // element already exists, skip
                tempList.add(array[i]);
                permutateBacktrack(result, tempList, array);
                tempList.remove(tempList.size() - 1);
            }
        }
    }

    //*****************************************************************************************
    // Permutations : https://leetcode.com/problems/permutations/  Swap method
    //*****************************************************************************************

    public List<List<Integer>> permutateSwapMethod(Integer[] array) {
        List<List<Integer>> result = new ArrayList<>();
        List<Integer> srcList = Arrays.asList(array);
        permutateSwapBacktrack(result, srcList, 0);
        return result;
    }

    private void permutateSwapBacktrack(List<List<Integer>> result, List<Integer> A, int i) {

        if (i == A.size() - 1) {
            result.add(new ArrayList<Integer>(A));
            return;
        } else {

            for (int j = i; j < A.size(); ++j) {

                Collections.swap(A, i, j);
                permutateSwapBacktrack(result, A, i + 1);
                Collections.swap(A, i, j);
            }
        }

    }

    //*****************************************************************************************
    // Permutations II (contains duplicates) : https://leetcode.com/problems/permutations-ii/
    //*****************************************************************************************

    public List<List<Integer>> permutateUnique(int[] array) {
        List<List<Integer>> list = new ArrayList<>();
        Arrays.sort(array);
        permutateUniqueBacktrack(list, new ArrayList<>(), array, new boolean[array.length]);
        return list;
    }

    private void permutateUniqueBacktrack(List<List<Integer>> result, List<Integer> tempList,
                                          int[] array, boolean[] used) {

        if (tempList.size() == array.length) {
            result.add(new ArrayList<>(tempList));
        } else {

            for (int i = 0; i < array.length; i++) {

                if (used[i] || i > 0 && array[i] == array[i - 1] && !used[i - 1]) continue;

                used[i] = true;
                tempList.add(array[i]);
                permutateUniqueBacktrack(result, tempList, array, used);
                used[i] = false;
                tempList.remove(tempList.size() - 1);
            }

        }
    }

    //*****************************************************************************************
    // Combination Sum : https://leetcode.com/problems/combination-sum/
    //*****************************************************************************************

    public List<List<Integer>> combinationSum(int[] nums, int target) {
        List<List<Integer>> list = new ArrayList<>();
        Arrays.sort(nums);
        combinationSumBacktrack(list, new ArrayList<>(), nums, target, 0);
        return list;
    }

    private void combinationSumBacktrack(List<List<Integer>> result, List<Integer> tempList, int[] nums,
                                         int remain, int start) {

        if (remain < 0)
            return;
        else if (remain == 0)
            result.add(new ArrayList<>(tempList));

        else {

            for (int i = start; i < nums.length; i++) {
                tempList.add(nums[i]);
                // not i + 1 because we can reuse same elements
                combinationSumBacktrack(result, tempList, nums, remain - nums[i], i);
                tempList.remove(tempList.size() - 1);
            }

        }

    }

    //****************************************************************************************************************
    //Combination Sum II (can't reuse same element) : https://leetcode.com/problems/combination-sum-ii/
    //****************************************************************************************************************

    public List<List<Integer>> combinationSum2(int[] nums, int target) {
        List<List<Integer>> list = new ArrayList<>();
        Arrays.sort(nums);
        combinationSum2Backtrack(list, new ArrayList<>(), nums, target, 0);
        return list;

    }

    private void combinationSum2Backtrack(List<List<Integer>> result, List<Integer> tempList, int[] nums, int remain, int start) {

        if (remain < 0)
            return;
        else if (remain == 0)
            result.add(new ArrayList<>(tempList));

        else {

            for (int i = start; i < nums.length; i++) {

                if (i > start && nums[i] == nums[i - 1]) continue; // skip duplicates

                tempList.add(nums[i]);
                combinationSum2Backtrack(result, tempList, nums, remain - nums[i], i + 1);
                tempList.remove(tempList.size() - 1);
            }

        }
    }

    //****************************************************************************************************************
    // Generate Parentheses
    //****************************************************************************************************************

    public List<String> generateParentheses(int n) {

        List<String> result = new ArrayList<>();
        generateParen(n, n, result, "");
        return result;
    }

    public void generateParen(int left, int right, List<String> result, String temp) {

        if (left == 0 && right == 0)
            result.add(temp);

        if (left > 0) {
            generateParen(left - 1, right, result, temp + "(");
        }

        if (left < right) {
            generateParen(left, right - 1, result, temp + ")");
        }

    }

    //*****************************************************************************************
    // Palindrome Partitioning : https://leetcode.com/problems/palindrome-partitioning/
    //*****************************************************************************************

    public List<List<String>> partition(String s) {
        List<List<String>> list = new ArrayList<>();
        partitionBacktrack(list, new ArrayList<>(), s, 0);
        return list;
    }

    public void partitionBacktrack(List<List<String>> list, List<String> tempList, String s, int start) {

        if (start == s.length())
            list.add(new ArrayList<>(tempList));
        else {

            for (int i = start; i < s.length(); i++) {

                if (isPalindrome(s, start, i)) {
                    tempList.add(s.substring(start, i + 1));
                    partitionBacktrack(list, tempList, s, i + 1);
                    tempList.remove(tempList.size() - 1);
                }
            }

        }
    }

    public boolean isPalindrome(String s, int low, int high) {
        while (low < high)
            if (s.charAt(low++) != s.charAt(high--)) return false;
        return true;
    }

    //****************************************************************************************************************
    // n Queens
    //****************************************************************************************************************

    public static List<List<Integer>> nQueens(int n) {
        List<List<Integer>> result = new ArrayList<>();
        solveNQueens(n, 0, new ArrayList<Integer>(), result);
        return result;
    }

    private static void solveNQueens(int n, int row, List<Integer> colPlacement,
                                     List<List<Integer>> result) {
        if (row == n) {
            // All queens are legally placed.
            result.add(new ArrayList<>(colPlacement));
        } else {
            for (int col = 0; col < n; ++col) {
                colPlacement.add(col);
                if (isValid(colPlacement)) {
                    solveNQueens(n, row + 1, colPlacement, result);
                }
                colPlacement.remove(colPlacement.size() - 1);
            }
        }
    }

    // Test if a newly placed queen will conflict any earlier queens placed before.
    private static boolean isValid(List<Integer> colPlacement) {
        int rowID = colPlacement.size() - 1;
        for (int i = 0; i < rowID; ++i) {
            int diff = Math.abs(colPlacement.get(i) - colPlacement.get(rowID));
            if (diff == 0 || diff == rowID - i) {
                return false;
            }
        }
        return true;
    }

    //****************************************************************************************************************
    // Word search
    //****************************************************************************************************************

    boolean[][] visited;

    public boolean wordExists(char[][] board, String word) {

        visited = new boolean[board.length][board[0].length];

        for (int i = 0; i < board.length; i++) {
            for (int j = 0; j < board[i].length; j++) {
                if (word.charAt(0) == board[i][j]) {
                    if (search(board, word, i, j, 0)) {
                        return true;
                    } else continue;
                }
            }
        }

        return false;
    }

    private boolean search(char[][] board, String word, int i, int j, int index) {
        if (index == word.length()) {
            return true;
        }

        if (i >= board.length || i < 0 || j >= board[i].length || j < 0 || board[i][j] != word.charAt(index) || visited[i][j]) {
            return false;
        }

        visited[i][j] = true;
        if (search(board, word, i - 1, j, index + 1) ||
                search(board, word, i + 1, j, index + 1) ||
                search(board, word, i, j - 1, index + 1) ||
                search(board, word, i, j + 1, index + 1)) {
            return true;
        }

        visited[i][j] = false;
        return false;
    }

    //****************************************************************************************************************
    // Word  pattern
    // https://leetcode.com/problems/word-pattern-ii/
    //****************************************************************************************************************

    public boolean wordPatternMatch(String pattern, String str) {
        Map<Character, String> map = new HashMap<>();
        Set<String> set = new HashSet<>();

        return isMatch(str, 0, pattern, 0, map, set);
    }

    boolean isMatch(String str, int i, String pat, int j, Map<Character, String> map, Set<String> set) {
        // base case
        if (i == str.length() && j == pat.length()) return true;
        if (i == str.length() || j == pat.length()) return false;

        // get current pattern character
        char c = pat.charAt(j);

        // if the pattern character exists
        if (map.containsKey(c)) {
            String s = map.get(c);

            // then check if we can use it to match str[i...i+s.length()]
            if (!str.startsWith(s, i)) {
                return false;
            }

            // if it can match, great, continue to match the rest
            return isMatch(str, i + s.length(), pat, j + 1, map, set);
        }

        // pattern character does not exist in the map
        for (int k = i; k < str.length(); k++) {
            String p = str.substring(i, k + 1);

            if (set.contains(p)) {
                continue;
            }

            // create or update it
            map.put(c, p);
            set.add(p);

            // continue to match the rest
            if (isMatch(str, k + 1, pat, j + 1, map, set)) {
                return true;
            }

            // backtracking
            map.remove(c);
            set.remove(p);
        }

        // we've tried our best but still no luck
        return false;
    }

    // https://leetcode.com/problems/sudoku-solver/

    public void solveSudoku(char[][] board) {
        if(board == null || board.length == 0)
            return;
        solve(board);
    }

    public boolean solve(char[][] board){
        for(int i = 0; i < board.length; i++){
            for(int j = 0; j < board[0].length; j++){
                if(board[i][j] == '.'){
                    for(char c = '1'; c <= '9'; c++){
                        //trial. Try 1 through 9
                        if(isValid(board, i, j, c)){
                            board[i][j] = c; //Put c for this cell

                            if(solve(board))
                                return true; //If it's the solution return true
                            else
                                board[i][j] = '.'; //Otherwise go back
                        }
                    }

                    return false;
                }
            }
        }
        return true;
    }

    private boolean isValid(char[][] board, int row, int col, char c){
        for(int i = 0; i < 9; i++) {
            if(board[i][col] != '.' && board[i][col] == c) return false; //check row
            if(board[row][i] != '.' && board[row][i] == c) return false; //check column
            if(board[3 * (row / 3) + i / 3][ 3 * (col / 3) + i % 3] != '.' &&
                    board[3 * (row / 3) + i / 3][3 * (col / 3) + i % 3] == c) return false; //check 3*3 block
        }
        return true;
    }

    // https://leetcode.com/problems/factor-combinations/
    // Write a function that takes an integer n and return all possible combinations of its factors.

    /*
    input: 32
        output:
        [
          [2, 16],
          [2, 2, 8],
          [2, 2, 2, 4],
          [2, 2, 2, 2, 2],
          [2, 4, 4],
          [4, 8]
        ]
     */

    public List<List<Integer>> getFactors(int n) {
        List<List<Integer>> result = new ArrayList<List<Integer>>();
        helper(result, new ArrayList<Integer>(), n, 2);
        return result;
    }

    public void helper(List<List<Integer>> result, List<Integer> item, int n, int start){
        if (n <= 1) {
            if (item.size() > 1) {
                result.add(new ArrayList<Integer>(item));
            }
            return;
        }

        for (int i = start; i <= n; ++i) {
            if (n % i == 0) {
                item.add(i);
                helper(result, item, n/i, i);
                item.remove(item.size()-1);
            }
        }
    }

    //***********************************************************************************************
    //***********************************************************************************************
    //***********************************************************************************************
    //***********************************************************************************************
    //***********************************************************************************************

    public static void main(String[] args) {

        Backtrack backtrackTemplate = new Backtrack();

        char[] charA = {'a', 'c', 'e', 'd'};
        char[] charB = {'b', 'a', 'd', 'w'};
        char[] charC = {'e', 's', 'a', 'e'};

        char[][] charAB = {charA, charB, charC};

        boolean resu = backtrackTemplate.wordExists(charAB, "edas");
        System.out.println(resu);

    /*
        List<String> result = backtrackTemplate.generateParentheses(3);
        Iterator iter = result.iterator();

        while (iter.hasNext()) System.out.println(iter.next());

        List<List<String>> list = backtrackTemplate.partition("aabba");

        Iterator<List<String>> iter = list.iterator();
        while (iter.hasNext()) {
            List<String> innerList = iter.next();
            Iterator<String> innerIter = innerList.iterator();

            while (innerIter.hasNext()) System.out.println(innerIter.next());
        }

        List<List<Integer>> intList = new ArrayList<>();

        int[] intArray = {2,6,5};

        int[] intArray1 = {2,5,5};

        intList = backtrackTemplate.subsetsOfSizeK(intArray, 3);

        System.out.println("Combinations / Subsets of the set {2,6,5} of Size 3 ");

        Iterator<List<Integer>> intIter = intList.iterator();

        while (intIter.hasNext()) {
            List<Integer> innerList = intIter.next();
            System.out.println(Arrays.toString(innerList.toArray()));
        }

        intList = backtrackTemplate.subsetsWithDup(intArray1);

        System.out.println(" Subsets with duplicates of the set {2,5,5} ");

        intIter = intList.iterator();

        while (intIter.hasNext()) {
            List<Integer> innerList = intIter.next();
            System.out.println(Arrays.toString(innerList.toArray()));
        }

        System.out.println("Permutations of the set {2,6,5}");

        intList = backtrackTemplate.permutate(intArray);

        intIter = intList.iterator();

        while (intIter.hasNext()) {
            List<Integer> innerList = intIter.next();
            System.out.println(Arrays.toString(innerList.toArray()));
        }

        System.out.println("Permutations of the set {2,5,5}");

        intList = backtrackTemplate.permutateUnique(intArray1);

        intIter = intList.iterator();

        while (intIter.hasNext()) {
            List<Integer> innerList = intIter.next();
            System.out.println(Arrays.toString(innerList.toArray()));
        }
    */

    }

}


text:
#ifndef _EVENT_WRAPPER_H
#define _EVENT_WRAPPER_H

#include "log.h"
#include "detect.h"
#include "decode.h"
#include "rules.h"
#include "treenodes.h"

/*
 * this has been upgarded to reroute traffic to fpLogEvent()
 * to add support for thresholding, and other rule behaviors
 * like drop,alert.  This has been updated to allow decoder events
 * which call it to be filtered through fpLogEvent.  This of course
 * requires a rule be writen for each decoder event, and preprocssor event,
 * although preprocessors don't seem to use this much.
 */
uint32_t GenerateSnortEvent(Packet *p,
                            uint32_t gen_id,
                            uint32_t sig_id,
                            uint32_t sig_rev,
                            uint32_t classification,
                            uint32_t priority,
                            char *msg);

OptTreeNode * GenerateSnortEventOtn(
                            uint32_t gen_id,
                            uint32_t sig_id,
                            uint32_t sig_rev,
                            uint32_t classification,
                            uint32_t priority,
                            char *msg );

RuleTreeNode* GenerateSnortEventRtn(OptTreeNode*, tSfPolicyId);

int LogTagData(Packet *p,
               uint32_t gen_id,
               uint32_t sig_id,
               uint32_t sig_rev,
               uint32_t classification,
               uint32_t priority,
               uint32_t event_ref,
               time_t ref_sec,
               char *msg);

#endif /* _EVENT_WRAPPER_H */


text:
```bash
USERNAME=username

# Switch to root

cd
git clone https://github.com/ipython-contrib/IPython-notebook-extensions.git
cd IPython-notebook-extensions
source activate py3
./setup.py install

# Switch back to user

cp -r /root/.local/share/jupyter/templates /home/$USERNAME/.local/share/jupyter/templates
cp -r /root/.local/share/jupyter/extensions /home/$USERNAME/.local/share/jupyter/extensions
cp -r /root/.local/share/jupyter/nbextensions /home/$USERNAME/.local/share/jupyter/nbextensions
echo "from jupyter_core.paths import jupyter_config_dir, jupyter_data_dir \n import os.path \n import sys \n \n sys.path.append(os.path.join(jupyter_data_dir(), 'extensions')) \n \n c = get_config() \n \n c.NotebookApp.extra_template_paths = [os.path.join(jupyter_data_dir(), 'templates') ] \n c.NotebookApp.server_extensions = ['nbextensions'] \n" > /root/.jupyter/jupyter_notebook_config.py
cp /root/.jupyter/jupyter_notebook_config.py /home/$USERNAME/.jupyter/jupyter_notebook_config.py
```

Stop/restart server then navigate to: http://192.168.106.106:8000/user/username/nbextensions


text:
package discv5

import (
	"container/heap"
	"fmt"
	"math"
	"math/rand"
	"time"

	"github.com/lab2528/go-oneTime/common/mclock"
)

const (
	maxEntries         = 10000
	maxEntriesPerTopic = 50

	fallbackRegistrationExpiry = 1 * time.Hour
)

type Topic string

type topicEntry struct {
	topic   Topic
	fifoIdx uint64
	node    *Node
	expire  mclock.AbsTime
}

type topicInfo struct {
	entries            map[uint64]*topicEntry
	fifoHead, fifoTail uint64
	rqItem             *topicRequestQueueItem
	wcl                waitControlLoop
}

// removes tail element from the fifo
func (t *topicInfo) getFifoTail() *topicEntry {
	for t.entries[t.fifoTail] == nil {
		t.fifoTail++
	}
	tail := t.entries[t.fifoTail]
	t.fifoTail++
	return tail
}

type nodeInfo struct {
	entries                          map[Topic]*topicEntry
	lastIssuedTicket, lastUsedTicket uint32
	// you can't register a ticket newer than lastUsedTicket before noRegUntil (absolute time)
	noRegUntil mclock.AbsTime
}

type topicTable struct {
	db                    *nodeDB
	self                  *Node
	nodes                 map[*Node]*nodeInfo
	topics                map[Topic]*topicInfo
	globalEntries         uint64
	requested             topicRequestQueue
	requestCnt            uint64
	lastGarbageCollection mclock.AbsTime
}

func newTopicTable(db *nodeDB, self *Node) *topicTable {
	if printTestImgLogs {
		fmt.Printf("*N %016x\n", self.sha[:8])
	}
	return &topicTable{
		db:     db,
		nodes:  make(map[*Node]*nodeInfo),
		topics: make(map[Topic]*topicInfo),
		self:   self,
	}
}

func (t *topicTable) getOrNewTopic(topic Topic) *topicInfo {
	ti := t.topics[topic]
	if ti == nil {
		rqItem := &topicRequestQueueItem{
			topic:    topic,
			priority: t.requestCnt,
		}
		ti = &topicInfo{
			entries: make(map[uint64]*topicEntry),
			rqItem:  rqItem,
		}
		t.topics[topic] = ti
		heap.Push(&t.requested, rqItem)
	}
	return ti
}

func (t *topicTable) checkDeleteTopic(topic Topic) {
	ti := t.topics[topic]
	if ti == nil {
		return
	}
	if len(ti.entries) == 0 && ti.wcl.hasMinimumWaitPeriod() {
		delete(t.topics, topic)
		heap.Remove(&t.requested, ti.rqItem.index)
	}
}

func (t *topicTable) getOrNewNode(node *Node) *nodeInfo {
	n := t.nodes[node]
	if n == nil {
		//fmt.Printf("newNode %016x %016x\n", t.self.sha[:8], node.sha[:8])
		var issued, used uint32
		if t.db != nil {
			issued, used = t.db.fetchTopicRegTickets(node.ID)
		}
		n = &nodeInfo{
			entries:          make(map[Topic]*topicEntry),
			lastIssuedTicket: issued,
			lastUsedTicket:   used,
		}
		t.nodes[node] = n
	}
	return n
}

func (t *topicTable) checkDeleteNode(node *Node) {
	if n, ok := t.nodes[node]; ok && len(n.entries) == 0 && n.noRegUntil < mclock.Now() {
		//fmt.Printf("deleteNode %016x %016x\n", t.self.sha[:8], node.sha[:8])
		delete(t.nodes, node)
	}
}

func (t *topicTable) storeTicketCounters(node *Node) {
	n := t.getOrNewNode(node)
	if t.db != nil {
		t.db.updateTopicRegTickets(node.ID, n.lastIssuedTicket, n.lastUsedTicket)
	}
}

func (t *topicTable) getEntries(topic Topic) []*Node {
	t.collectGarbage()

	te := t.topics[topic]
	if te == nil {
		return nil
	}
	nodes := make([]*Node, len(te.entries))
	i := 0
	for _, e := range te.entries {
		nodes[i] = e.node
		i++
	}
	t.requestCnt++
	t.requested.update(te.rqItem, t.requestCnt)
	return nodes
}

func (t *topicTable) addEntry(node *Node, topic Topic) {
	n := t.getOrNewNode(node)
	// clear previous entries by the same node
	for _, e := range n.entries {
		t.deleteEntry(e)
	}
	// ***
	n = t.getOrNewNode(node)

	tm := mclock.Now()
	te := t.getOrNewTopic(topic)

	if len(te.entries) == maxEntriesPerTopic {
		t.deleteEntry(te.getFifoTail())
	}

	if t.globalEntries == maxEntries {
		t.deleteEntry(t.leastRequested()) // not empty, no need to check for nil
	}

	fifoIdx := te.fifoHead
	te.fifoHead++
	entry := &topicEntry{
		topic:   topic,
		fifoIdx: fifoIdx,
		node:    node,
		expire:  tm + mclock.AbsTime(fallbackRegistrationExpiry),
	}
	if printTestImgLogs {
		fmt.Printf("*+ %d %v %016x %016x\n", tm/1000000, topic, t.self.sha[:8], node.sha[:8])
	}
	te.entries[fifoIdx] = entry
	n.entries[topic] = entry
	t.globalEntries++
	te.wcl.registered(tm)
}

// removes least requested element from the fifo
func (t *topicTable) leastRequested() *topicEntry {
	for t.requested.Len() > 0 && t.topics[t.requested[0].topic] == nil {
		heap.Pop(&t.requested)
	}
	if t.requested.Len() == 0 {
		return nil
	}
	return t.topics[t.requested[0].topic].getFifoTail()
}

// entry should exist
func (t *topicTable) deleteEntry(e *topicEntry) {
	if printTestImgLogs {
		fmt.Printf("*- %d %v %016x %016x\n", mclock.Now()/1000000, e.topic, t.self.sha[:8], e.node.sha[:8])
	}
	ne := t.nodes[e.node].entries
	delete(ne, e.topic)
	if len(ne) == 0 {
		t.checkDeleteNode(e.node)
	}
	te := t.topics[e.topic]
	delete(te.entries, e.fifoIdx)
	if len(te.entries) == 0 {
		t.checkDeleteTopic(e.topic)
	}
	t.globalEntries--
}

// It is assumed that topics and waitPeriods have the same length.
func (t *topicTable) useTicket(node *Node, serialNo uint32, topics []Topic, idx int, issueTime uint64, waitPeriods []uint32) (registered bool) {
	debugLog(fmt.Sprintf("useTicket %v %v %v", serialNo, topics, waitPeriods))
	//fmt.Println("useTicket", serialNo, topics, waitPeriods)
	t.collectGarbage()

	n := t.getOrNewNode(node)
	if serialNo < n.lastUsedTicket {
		return false
	}

	tm := mclock.Now()
	if serialNo > n.lastUsedTicket && tm < n.noRegUntil {
		return false
	}
	if serialNo != n.lastUsedTicket {
		n.lastUsedTicket = serialNo
		n.noRegUntil = tm + mclock.AbsTime(noRegTimeout())
		t.storeTicketCounters(node)
	}

	currTime := uint64(tm / mclock.AbsTime(time.Second))
	regTime := issueTime + uint64(waitPeriods[idx])
	relTime := int64(currTime - regTime)
	if relTime >= -1 && relTime <= regTimeWindow+1 { // give clients a little security margin on both ends
		if e := n.entries[topics[idx]]; e == nil {
			t.addEntry(node, topics[idx])
		} else {
			// if there is an active entry, don't move to the front of the FIFO but prolong expire time
			e.expire = tm + mclock.AbsTime(fallbackRegistrationExpiry)
		}
		return true
	}

	return false
}

func (topictab *topicTable) getTicket(node *Node, topics []Topic) *ticket {
	topictab.collectGarbage()

	now := mclock.Now()
	n := topictab.getOrNewNode(node)
	n.lastIssuedTicket++
	topictab.storeTicketCounters(node)

	t := &ticket{
		issueTime: now,
		topics:    topics,
		serial:    n.lastIssuedTicket,
		regTime:   make([]mclock.AbsTime, len(topics)),
	}
	for i, topic := range topics {
		var waitPeriod time.Duration
		if topic := topictab.topics[topic]; topic != nil {
			waitPeriod = topic.wcl.waitPeriod
		} else {
			waitPeriod = minWaitPeriod
		}

		t.regTime[i] = now + mclock.AbsTime(waitPeriod)
	}
	return t
}

const gcInterval = time.Minute

func (t *topicTable) collectGarbage() {
	tm := mclock.Now()
	if time.Duration(tm-t.lastGarbageCollection) < gcInterval {
		return
	}
	t.lastGarbageCollection = tm

	for node, n := range t.nodes {
		for _, e := range n.entries {
			if e.expire <= tm {
				t.deleteEntry(e)
			}
		}

		t.checkDeleteNode(node)
	}

	for topic := range t.topics {
		t.checkDeleteTopic(topic)
	}
}

const (
	minWaitPeriod   = time.Minute
	regTimeWindow   = 10 // seconds
	avgnoRegTimeout = time.Minute * 10
	// target average interval between two incoming ad requests
	wcTargetRegInterval = time.Minute * 10 / maxEntriesPerTopic
	//
	wcTimeConst = time.Minute * 10
)

// initialization is not required, will set to minWaitPeriod at first registration
type waitControlLoop struct {
	lastIncoming mclock.AbsTime
	waitPeriod   time.Duration
}

func (w *waitControlLoop) registered(tm mclock.AbsTime) {
	w.waitPeriod = w.nextWaitPeriod(tm)
	w.lastIncoming = tm
}

func (w *waitControlLoop) nextWaitPeriod(tm mclock.AbsTime) time.Duration {
	period := tm - w.lastIncoming
	wp := time.Duration(float64(w.waitPeriod) * math.Exp((float64(wcTargetRegInterval)-float64(period))/float64(wcTimeConst)))
	if wp < minWaitPeriod {
		wp = minWaitPeriod
	}
	return wp
}

func (w *waitControlLoop) hasMinimumWaitPeriod() bool {
	return w.nextWaitPeriod(mclock.Now()) == minWaitPeriod
}

func noRegTimeout() time.Duration {
	e := rand.ExpFloat64()
	if e > 100 {
		e = 100
	}
	return time.Duration(float64(avgnoRegTimeout) * e)
}

type topicRequestQueueItem struct {
	topic    Topic
	priority uint64
	index    int
}

// A topicRequestQueue implements heap.Interface and holds topicRequestQueueItems.
type topicRequestQueue []*topicRequestQueueItem

func (tq topicRequestQueue) Len() int { return len(tq) }

func (tq topicRequestQueue) Less(i, j int) bool {
	return tq[i].priority < tq[j].priority
}

func (tq topicRequestQueue) Swap(i, j int) {
	tq[i], tq[j] = tq[j], tq[i]
	tq[i].index = i
	tq[j].index = j
}

func (tq *topicRequestQueue) Push(x interface{}) {
	n := len(*tq)
	item := x.(*topicRequestQueueItem)
	item.index = n
	*tq = append(*tq, item)
}

func (tq *topicRequestQueue) Pop() interface{} {
	old := *tq
	n := len(old)
	item := old[n-1]
	item.index = -1
	*tq = old[0 : n-1]
	return item
}

func (tq *topicRequestQueue) update(item *topicRequestQueueItem, priority uint64) {
	item.priority = priority
	heap.Fix(tq, item.index)
}


text:
package org.apache.cassandra.cql3.restrictions;

import java.util.Set;

import org.apache.cassandra.config.ColumnDefinition;

/**
 * Sets of restrictions
 */
public interface Restrictions extends Restriction
{
    /**
     * Returns the restrictions applied to the specified column.
     *
     * @param columnDef the column definition
     * @return the restrictions applied to the specified column
     */
    Set<Restriction> getRestrictions(ColumnDefinition columnDef);

    /**
     * Checks if this Restrictions is empty or not.
     *
     * @return true if this Restrictions is empty, false otherwise.
     */
    boolean isEmpty();

    /**
     * Returns the number of columns that have a restriction.
     *
     * @return the number of columns that have a restriction.
     */
    public int size();

    /**
     * Checks if any of the underlying restriction is an IN.
     * @return true if any of the underlying restriction is an IN, false otherwise
     */
    public boolean hasIN();

    /**
     * Checks if any of the underlying restrictions is a slice.
     * @return true if any of the underlying restrictions is a slice, false otherwise
     */
    public boolean hasSlice();

    /**
     * Checks if all of the underlying restrictions are EQ or IN restrictions.
     *
     * @return true if all of the underlying restrictions are EQ or IN restrictions,
     * false otherwise
     */
    public boolean hasOnlyEqualityRestrictions();
}


text:
'use strict';

var livereload = require('gulp-livereload');

module.exports = function (gulp) {
  gulp.task('livereload', function () {
    livereload.listen();
  });
};


text:
<?php
require_once '../../lib/DataSourceResult.php';
require_once '../../lib/Kendo/Autoload.php';

if ($_SERVER['REQUEST_METHOD'] == 'POST') {
    header('Content-Type: application/json');

    $request = json_decode(file_get_contents('php://input'));

    $result = new DataSourceResult('sqlite:../../sample.db');

    $type = $_GET['type'];

    $columns = array('ProductID', 'ProductName', 'UnitPrice', 'UnitsInStock', 'Discontinued');

    switch($type) {
        case 'create':
            $result = $result->create('Products', $columns, $request->models, 'ProductID');
            break;
        case 'read':
            $result = $result->read('Products', $columns, $request);
            break;
        case 'update':
            $result = $result->update('Products', $columns, $request->models, 'ProductID');
            break;
        case 'destroy':
            $result = $result->destroy('Products', $request->models, 'ProductID');
            break;
    }

    echo json_encode($result, JSON_NUMERIC_CHECK);

    exit;
}

require_once '../../include/header.php';

$transport = new \Kendo\Data\DataSourceTransport();

$create = new \Kendo\Data\DataSourceTransportCreate();

$create->url('editing-inline.php?type=create')
     ->contentType('application/json')
     ->type('POST');

$read = new \Kendo\Data\DataSourceTransportRead();

$read->url('editing-inline.php?type=read')
     ->contentType('application/json')
     ->type('POST');

$update = new \Kendo\Data\DataSourceTransportUpdate();

$update->url('editing-inline.php?type=update')
     ->contentType('application/json')
     ->type('POST');

$destroy = new \Kendo\Data\DataSourceTransportDestroy();

$destroy->url('editing-inline.php?type=destroy')
     ->contentType('application/json')
     ->type('POST');

$transport->create($create)
          ->read($read)
          ->update($update)
          ->destroy($destroy)
          ->parameterMap('function(data) {
              return kendo.stringify(data);
          }');

$model = new \Kendo\Data\DataSourceSchemaModel();

$productIDField = new \Kendo\Data\DataSourceSchemaModelField('ProductID');
$productIDField->type('number')
               ->editable(false)
               ->nullable(true);

$productNameField = new \Kendo\Data\DataSourceSchemaModelField('ProductName');
$productNameField->type('string')
                 ->validation(array('required' => true));

$unitPriceValidation = new \Kendo\Data\DataSourceSchemaModelFieldValidation();
$unitPriceValidation->required(true)
                    ->min(1);

$unitPriceField = new \Kendo\Data\DataSourceSchemaModelField('UnitPrice');
$unitPriceField->type('number')
               ->validation($unitPriceValidation);

$unitsInStockField = new \Kendo\Data\DataSourceSchemaModelField('UnitsInStock');
$unitsInStockField->type('number');

$discontinuedField = new \Kendo\Data\DataSourceSchemaModelField('Discontinued');
$discontinuedField->type('boolean');

$model->id('ProductID')
    ->addField($productIDField)
    ->addField($productNameField)
    ->addField($unitPriceField)
    ->addField($unitsInStockField)
    ->addField($discontinuedField);

$schema = new \Kendo\Data\DataSourceSchema();
$schema->data('data')
       ->errors('errors')
       ->model($model)
       ->total('total');

$dataSource = new \Kendo\Data\DataSource();

$dataSource->transport($transport)
           ->batch(true)
           ->pageSize(20)
           ->schema($schema);

$grid = new \Kendo\UI\Grid('grid');

$productName = new \Kendo\UI\GridColumn();
$productName->field('ProductName')
            ->title('Product Name');

$unitPrice = new \Kendo\UI\GridColumn();
$unitPrice->field('UnitPrice')
          ->format('{0:c}')
          ->width(100)
          ->title('Unit Price');

$unitsInStock = new \Kendo\UI\GridColumn();
$unitsInStock->field('UnitsInStock')
          ->width(100)
          ->title('Units In Stock');

$discontinued = new \Kendo\UI\GridColumn();
$discontinued->field('Discontinued')
          ->width(100);

$command = new \Kendo\UI\GridColumn();
$command->addCommandItem('edit')
        ->addCommandItem('destroy')
        ->title(' ')
        ->width(172);

$grid->addColumn($productName, $unitPrice, $unitsInStock, $discontinued, $command)
     ->dataSource($dataSource)
     ->addToolbarItem(new \Kendo\UI\GridToolbarItem('create'))
     ->height(430)
     ->editable('inline')
     ->pageable(true);

echo $grid->render();
?>

<?php require_once '../../include/footer.php'; ?>


text:
import Gtk

function GTKdrawingwindow(name, w, h, closecb=nothing)
    win = Gtk.Window(name, w, h)
    c = Gtk.Canvas(win)
    if closecb !== nothing
        Gtk.on_signal_destroy(win, closecb, win)
    end
    c, win
end

_saved_gtk_renderer = nothing
function _saved_gtk_destroyed(::Ptr, widget::Gtk.GTKWidget)
    global _saved_gtk_renderer = nothing
    nothing
end
function gtk(self::PlotContainer, args...)
    global _saved_gtk_renderer, _saved_gtk_win
    opts = Winston.args2dict(args...)
    width = get(opts, :width, Winston.config_value("window","width"))
    height = get(opts, :height, Winston.config_value("window","height"))
    reuse_window = isinteractive() #&& Winston.config_value("window","reuse")
    device = _saved_gtk_renderer
    if device === nothing || !reuse_window
        device, win = GTKdrawingwindow("Julia", width, height, _saved_gtk_destroyed)
        _saved_gtk_renderer = device
    end
    display(device, self)
    self
end

function display(c::Gtk.Canvas, pc::PlotContainer)
    c.draw = function(_)
        ctx = getgc(c)
        set_source_rgb(ctx, 1, 1, 1)
        paint(ctx)
        Winston.page_compose(pc, Gtk.cairo_surface(c))
    end
    Gtk.draw(c)
end


text:
(function () {
  function UserModalInstanceFunction($scope,$uibModalInstance,$cookieStore){
      $scope.addUser = function (username) {
        $cookieStore.put("blocChatCurrentUser",username);
        $uibModalInstance.close();
      };
  }

  angular
    .module('blocChat')
    .controller('UserModalInstanceCtrl', ['$scope','$uibModalInstance','$cookieStore', UserModalInstanceFunction])
})();


text:
import Ember from 'ember';

import { moduleForComponent, test } from 'ember-qunit';
import hbs from 'htmlbars-inline-precompile';

moduleForComponent('em-table-tasks-log-link-cell', 'Integration | Component | em table tasks log link cell', {
  integration: true
});

test('Basic render test', function(assert) {
  this.render(hbs`{{em-table-tasks-log-link-cell}}`);

  assert.equal(this.$().text().trim(), 'Not Available!');

  // Template block usage:" + EOL +
  this.render(hbs`
    {{#em-table-tasks-log-link-cell}}
      template block text
    {{/em-table-tasks-log-link-cell}}
  `);

  assert.equal(this.$().text().trim(), 'Not Available!');
});

test('Test with content', function(assert) {
  let attemptID = "attempt_1";

  this.set("content", attemptID);
  this.render(hbs`{{em-table-tasks-log-link-cell content=content}}`);

  let tags = this.$().find("a");
  assert.equal(tags.length, 2);
  assert.equal(Ember.$(tags[0]).text().trim(), 'View');
  assert.equal(Ember.$(tags[1]).text().trim(), 'Download');
});


text:
'use strict';
var uniqueRandomArray = require('unique-random-array');
var yes = require('./yes.json');
var no = require('./no.json');
var all = yes.concat(no).sort();

exports.yes = yes;
exports.no = no;
exports.all = all;
exports.yesRandom = uniqueRandomArray(yes);
exports.noRandom = uniqueRandomArray(no);
exports.allRandom = uniqueRandomArray(all);


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

<title>Constant Field Values</title>
<meta name="date" content="2015-07-26">
<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

Next

Frames

No Frames

All Classes

Constant Field Values

Contents

bge.core.*

bge.core.*

bge.core.ShaderPart

Modifier and Type
Constant Field
Value

public static final int
COMPUTE_TYPE
37305

public static final int
FRAGMENT_TYPE
35632

public static final int
GEOMETRY_TYPE
36313

public static final int
TESSELLATION_CONTROL_TYPE
36488

public static final int
TESSELLATION_EVALUATION_TYPE
36487

public static final int
VERTEX_TYPE
35633

bge.core.Vertex

Modifier and Type
Constant Field
Value

public static final short
SIZE
3

Skip navigation links

Overview

Package

Class

Tree

Deprecated

Index

Help

Prev

Next

Frames

No Frames

All Classes


text:
package com.github.blackrush.acara;

import org.junit.runner.RunWith;
import org.junit.runners.Suite;

@RunWith(Suite.class)
@Suite.SuiteClasses({
})
public class AcaraApiTestSuite {
}


text:
class WocLocalSearch : public FrLocalSearch
{
    public:
        WocLocalSearch();
        WocLocalSearch(int, std::string,int);
        virtual ~WocLocalSearch();
        void propagateAverageRewards(double* );
        int performAction(double*, int, bool);

    protected:
    private:
};

#endif // WOCLOCALSEARCH_H


text:
package fetchmetadata

import (
	"log"

	"github.com/google/go-safeweb/safehttp"
	"github.com/google/go-safeweb/safehttp/plugins/fetchmetadata/internalunsafefetchmetadata"
)

var (
	navigationalDests = map[string]bool{
		"document":        true,
		"nested-document": true,
	}
	statePreservingMethods = map[string]bool{
		safehttp.MethodGet:  true,
		safehttp.MethodHead: true,
	}
)

// ResourceIsolationPolicy protects resources.
//
// See https://web.dev/fetch-metadata/ for more details.
func ResourceIsolationPolicy() *Policy {
	return &Policy{
		isAllowed: func(r *safehttp.IncomingRequest) bool {
			h := r.Header
			if h.Get("Sec-Fetch-Site") != "cross-site" {
				// The request is allowed to pass because one of the following applies:
				// - Fetch Metadata is not supported by the browser
				// - the request is same-origin, same-site or caused by the user
				// explicitly interacting with the user-agent
				return true
			}

			method := r.Method()
			mode := h.Get("Sec-Fetch-Mode")
			dest := h.Get("Sec-Fetch-Dest")
			// Allow CORS options requests if neither Mode nor Dest is set.
			// https://github.com/w3c/webappsec-fetch-metadata/issues/35
			// https://bugs.chromium.org/p/chromium/issues/detail?id=979946
			if mode == "" && dest == "" && method == safehttp.MethodOptions {
				return true
			}

			if navigationalModes[mode] && navigationalDests[dest] && statePreservingMethods[method] {
				// The request is cross-site, but a simple top-level navigation from a
				// safe destination so we allow it to pass.
				return true
			}
			if safehttp.IsLocalDev() {
				log.Println("fetchmetadata plugin resource protection detected a potentially malicious request")
			}
			return false
		},
		match: func(cfg safehttp.InterceptorConfig) bool {
			_, ok := cfg.(internalunsafefetchmetadata.DisableResourceIsolationPolicy)
			return ok
		},
		skip: func(cfg safehttp.InterceptorConfig) (skip, skipReports bool) {
			if override, ok := cfg.(internalunsafefetchmetadata.DisableResourceIsolationPolicy); ok {
				return true, override.SkipReports
			}
			return false, false
		},
		signal: "RESOURCE_ISOLATION",
	}
}


text:
<?xml version="1.0" encoding="UTF-8"?>
<!--   Copyright (C) 2013-2015 Computer Sciences Corporation
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License. --><project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>

    <parent>
        <groupId>ezbake</groupId>
        <artifactId>warehaus-parent</artifactId>
        <version>2.1</version>
    </parent>

    <artifactId>warehaus-service</artifactId>
    <name>EzBake Data Warehaus Service</name>

    <dependencies>
        <!-- Third-Party dependencies -->
        <dependency>
            <groupId>ch.qos.logback</groupId>
            <artifactId>logback-classic</artifactId>
        </dependency>
        <dependency>
            <groupId>org.apache.accumulo</groupId>
            <artifactId>accumulo-core</artifactId>
        </dependency>

        <!-- EzBake dependencies -->
        <dependency>
            <groupId>ezbake</groupId>
            <artifactId>thrift-utils</artifactId>
        </dependency>
        <dependency>
            <groupId>ezbake</groupId>
            <artifactId>ezbake-base-thrift-service</artifactId>
        </dependency>
        <dependency>
            <groupId>ezbake</groupId>
            <artifactId>ezbake-permission-utils</artifactId>
        </dependency>
        <dependency>
            <groupId>ezbake</groupId>
            <artifactId>ezbake-audit-auditlogger</artifactId>
        </dependency>
        <dependency>
            <groupId>ezbake</groupId>
            <artifactId>ezbake-permission-iterator</artifactId>
        </dependency>
        <dependency>
            <groupId>ezbake.data</groupId>
            <artifactId>common-utils</artifactId>
            <exclusions>
                <exclusion>
                    <groupId>org.slf4j</groupId>
                    <artifactId>slf4j-log4j12</artifactId>
                </exclusion>
                <exclusion>
                    <groupId>log4j</groupId>
                    <artifactId>log4j</artifactId>
                </exclusion>
            </exclusions>
        </dependency>
        <dependency>
            <groupId>ezbakehelpers</groupId>
            <artifactId>accumuloutils</artifactId>
        </dependency>
        <dependency>
            <groupId>ezbake</groupId>
            <artifactId>ezcentralpurge-thrift</artifactId>
        </dependency>
        <dependency>
            <groupId>ezbake</groupId>
            <artifactId>provenance-thrift</artifactId>
        </dependency>
        <dependency>
            <groupId>ezbake</groupId>
            <artifactId>warehaus-thrift</artifactId>
        </dependency>
        <dependency>
            <groupId>ezbake</groupId>
            <artifactId>warehaus-common</artifactId>
            <version>2.1</version>
        </dependency>

        <!-- Test dependencies -->
        <dependency>
            <groupId>junit</groupId>
            <artifactId>junit</artifactId>
            <scope>test</scope>
        </dependency>
        <dependency>
            <groupId>ezbake.data</groupId>
            <artifactId>test-utils</artifactId>
            <scope>test</scope>
        </dependency>
    </dependencies>

    <build>
        <plugins>
            <plugin>
                <groupId>org.apache.maven.plugins</groupId>
                <artifactId>maven-shade-plugin</artifactId>
                <configuration>
                    <transformers>
                        <transformer implementation="org.apache.maven.plugins.shade.resource.ManifestResourceTransformer">
                            <mainClass>ezbake.warehaus.WarehausServer</mainClass>
                        </transformer>
                    </transformers>
                </configuration>
            </plugin>
        </plugins>
    </build>

    <profiles>
        <profile>
            <id>rpmbuild</id>
            <build>
                <plugins>
                    <plugin>
                        <groupId>org.codehaus.mojo</groupId>
                        <artifactId>rpm-maven-plugin</artifactId>
                    </plugin>
                </plugins>
            </build>
        </profile>
    </profiles>
</project>