text:
module Rack
  class Bug

    class PanelApp
      include Rack::Bug::Render

      attr_reader :request

      def call(env)
        @request = Rack::Request.new(env)
        dispatch
      end

      def render_template(*args)
        Rack::Response.new([super]).to_a
      end

      def params
        @request.GET
      end

      def not_found
        [404, {}, []]
      end

      def validate_params
        ParamsSignature.new(request).validate!
      end

    end

  end
end

redpajama_set_name: RedPajamaGithub


text:
import omniORB
omniORB.updateModule("CosTime")

# ** 1. Stub files contributing to this module
import CosTime_idl

# ** 2. Sub-modules

# ** 3. End


text:
import { Kernel } from "oly";
import { array } from "../src";
import { field } from "../src/decorators/field";
import { ValidationException } from "../src/exceptions/ValidationException";
import { Json } from "../src/services/Json";
import { JsonValidator } from "../src/services/JsonValidator";

interface IPerson {
  name: string;
}

describe("ObjectMapper", () => {
  it("should parse an object", () => {

    class SubData {
      @field() hello: string;

      get upper() {
        return this.hello.toUpperCase();
      }
    }

    type A = "a" | "b";

    class Data {
      @array({of: String}) arr1: string[];
      @array({of: SubData}) arr2: SubData[];
      @field() bo: boolean;
      @field() num: number;
      @field str: A;
      @field sub: SubData;
      @field p: IPerson;

      get msg() {
        return "hello " + this.sub.hello + " " + this.str + this.num + this.bo;
      }
    }

    const raw = {
      arr1: ["a", "b"],
      arr2: [{hello: "test"}],
      bo: true,
      num: 1,
      str: "a",
      sub: {
        hello: "world",
      },
      p: {
        name: "ok",
      },
    };

    const json = Kernel.create().inject(Json);
    const obj = json.build(Data, JSON.stringify(raw));

    expect(obj.msg).toBe("hello world a1true");
    expect(obj.arr1.join("")).toBe("ab");
    expect(obj.arr2[0].upper).toBe("TEST");
    expect(obj.p.name).toBe("ok");

    expect(json.schema(Data)).toEqual({
      title: "Data",
      properties: {
        arr1: {items: {type: "string"}, type: "array"},
        arr2: {
          items: {
            title: "SubData",
            properties: {
              hello: {
                type: "string",
              },
            },
            required: [
              "hello",
            ],
            type: "object",
          },
          type: "array",
        },
        bo: {
          type: "boolean",
        },
        num: {
          type: "number",
        },
        str: {
          type: "string",
        },
        sub: {
          title: "SubData",
          properties: {
            hello: {
              type: "string",
            },
          },
          required: [
            "hello",
          ],
          type: "object",
        },
        p: {
          type: "object",
        },
      },
      required: [
        "arr1",
        "arr2",
        "bo",
        "num",
        "str",
        "sub",
        "p",
      ],
      type: "object",
    });
  });
  it("should display message on error", () => {

    class Credentials {
      @field() username: string;
      @field() password: string;
    }

    const json = Kernel.create().inject(JsonValidator);
    const entry = {
      username: 2,
    };

    const localize = {
      fr: require("ajv-i18n/localize/fr"),
    };

    try {
      json.validateClass(Credentials, entry);
      throw new Error("");
    } catch (e) {
      expect(e).toBeInstanceOf(ValidationException);
      const ev: ValidationException = e;
      localize.fr(ev.errors);
      expect(json.ajv.errorsText(ev.errors)).toBe("data requiert la propriété password");
      expect(ev.message).toBe("Validation has failed (data should have required property 'password')");
    }

    try {
      json.validateField({type: String, name: "username"}, 1);
      throw new Error("");
    } catch (e) {
      expect(e).toBeInstanceOf(ValidationException);
      const ev: ValidationException = e;
      localize.fr(ev.errors);
      expect(json.ajv.errorsText(ev.errors)).toBe("data doit être de type string");
      expect(ev.message).toBe("Validation has failed (data should be string)");
    }
  });
});


text:
package de.qaware.campus.secpro.msc03;

import java.io.Console;

/**
 * A simple and insecure login shell console application.
 *
 * @author mario-leander.reimer
 */
public final class InsecureLoginApp {
    /**
     * Enter username and password on the console, authenticate and loop until exit.
     *
     * @param args no arguments
     */
    public static void main(String[] args) {
        Console console = System.console();

        String username = console.readLine("Enter username: ");
        String password = console.readLine("Enter password: ");

        InsecureLogin login = new InsecureLogin(username, password);
        boolean authenticated = login.authenticated();

        if (!authenticated) {
            console.printf("Authentication failure. Exit.");
            System.exit(1);
        }

        String command = null;
        while (!"exit".equalsIgnoreCase(command)) {
            command = console.readLine("$ ");
            switch (command.toLowerCase()) {
                case "hello":
                    console.printf("world");
                    break;
                case "ping":
                    console.printf("pong");
                    break;
                case "exit":
                    break;
                default:
                    console.printf("Unknown command.");
                    break;
            }
        }
    }
}


text:
This simulator package works with the existing vC Sim. Please see [`simulator_test.go`](simulator_test.go) for an example of how to use the EAM simulator with vC Sim.

## Use Docker to Simulate Agent VMs

It is possible to run the simulator test whereby the creation of agent VMs results in the creation of containers in Docker to simulate the lifecycle of the VMs. Docker must be installed and running, but other than that, simply set the value of the `AgentConfigInfo.OvfPackageUrl` field to a:

* non-empty string,
* that does not start with `./`, `/`, or `https?:`.

If those conditions are met, then the EAM simulator treats this value as the name of a Docker image, and will create a simualted VM with `RUN.container` key set to the value, causing the core vC Simulator to simulate the VM with a container based on the specified image.

### Example of Simulated Agent VMs

There is a test that provides an example of this simulated agent VM behavior. Again, Docker must be installed and running, but otherwise just execute the following:

```shell
go test -v ./simulator/ -powerOnVMs
```

The flag `-powerOnVMs` causes the the simulator test code to create the agencies with agent configuration information that uses the `nginx` container to simulate two VMs. The presence of the flag then causes the VMs to be powered on, and the test waits for the agent runtime information to report the VMs' power state and IP addresses.


text:
Elegant Chat is a free web-based chat software, heavily inspired by [blueimp's AJAX Chat](http://frug.github.io/AJAX-Chat/). The first public release will be sometime in December 2015.

Elegant Chat is mostly compatible with AJAX Chat and will add support for some new features:
* A tabbed interface allowing simultaneous opening of multiple channels (incl. private channels)
* A flexible plugin architecture to easily change or enhance the chat's behavior and appearance
* Integrations with popular forum or CMS software — WordPress, Joomla, and the already existing in AJAX Chat: phpBB3, SMF, PunBB, MyBB. Proprietary third party software will not be officially supported.
* WebSockets as an alternative to polling; Ratchet/PHP used for the socket server
* HTML5 based sounds with a Flash fallback
* Multiple database support on server side — MySQL, PostgreSQL, SQLite
* Database storage of users and channels in the standalone version

Elegant Chat is implemented in PHP on the server and in Javascript on the client side. The minimum PHP version required is 5.4.

Elegant Chat sits on the shoulders of giants and is developed with following libraries and components:
* [Silex](http://silex.sensiolabs.org/)
* [Symfony components](http://symfony.com/components)
* [Doctrine DBAL](http://doctrine-project.org/projects/dbal.html)
* [Twig](http://twig.sensiolabs.org/)
* [Ratchet](http://socketo.me/)
* [React](http://reactphp.org/)
* [Assetic](https://github.com/kriswallsmith/assetic)
* [jQuery](http://jquery.com/)
* [Twitter Bootstrap](http://twitter.github.io/bootstrap/)
* [Font Awesome](http://fortawesome.github.io/Font-Awesome/)
* [Soundmanager 2](http://schillmania.com/projects/soundmanager2/)


text:
#ifndef COM_NO_WINDOWS_H
#include "windows.h"
#include "ole2.h"
#endif

#ifndef __iadmext_h__
#define __iadmext_h__

#ifdef __cplusplus
extern "C"{
#endif

#include "unknwn.h"
#include "objidl.h"
#include "ocidl.h"

  DEFINE_GUID(IID_IADMEXT,0x51dfe970,0xf6f2,0x11d0,0xb9,0xbd,0x0,0xa0,0xc9,0x22,0xe7,0x50);

#define IISADMIN_EXTENSIONS_REG_KEYA "SOFTWARE\\Microsoft\\InetStp\\Extensions"
#define IISADMIN_EXTENSIONS_REG_KEYW L"SOFTWARE\\Microsoft\\InetStp\\Extensions"
#define IISADMIN_EXTENSIONS_REG_KEY TEXT("SOFTWARE\\Microsoft\\InetStp\\Extensions")
#define IISADMIN_EXTENSIONS_CLSID_MD_KEYA "LM/IISADMIN/EXTENSIONS/DCOMCLSIDS"
#define IISADMIN_EXTENSIONS_CLSID_MD_KEYW L"LM/IISADMIN/EXTENSIONS/DCOMCLSIDS"
#define IISADMIN_EXTENSIONS_CLSID_MD_KEY TEXT("LM/IISADMIN/EXTENSIONS/DCOMCLSIDS")
#define IISADMIN_EXTENSIONS_CLSID_MD_ID MD_IISADMIN_EXTENSIONS

#ifndef __IADMEXT_INTERFACE_DEFINED__
#define __IADMEXT_INTERFACE_DEFINED__
  EXTERN_C const IID IID_IADMEXT;
#if defined(__cplusplus) && !defined(CINTERFACE)
  struct IADMEXT : public IUnknown {
public:
  virtual HRESULT WINAPI Initialize(void) = 0;
  virtual HRESULT WINAPI EnumDcomCLSIDs(CLSID *pclsidDcom,DWORD dwEnumIndex) = 0;
  virtual HRESULT WINAPI Terminate(void) = 0;
  };
#endif
#endif

#ifdef __cplusplus
}
#endif
#endif


text:
package example_app;

public class MessageGenerator {

    public String generateMessage() {
        return "Hello world!";
    }
}


text:
package org.eclipse.californium.examples;

import java.net.Inet4Address;
import java.net.InetAddress;
import java.net.InetSocketAddress;
import java.net.SocketException;
import java.util.List;
import java.util.logging.Level;
import java.net.URI;
import java.net.URISyntaxException;
import java.util.concurrent.TimeUnit;
import java.lang.InterruptedException;
import java.lang.Thread;

import org.eclipse.californium.core.CoapClient;
import org.eclipse.californium.core.CaliforniumLogger;
import org.eclipse.californium.core.CoapResponse;
import org.eclipse.californium.core.CoapResource;
import org.eclipse.californium.core.CoapServer;
import org.eclipse.californium.core.network.CoapEndpoint;
import org.eclipse.californium.core.network.EndpointManager;
import org.eclipse.californium.core.network.config.NetworkConfig;
import org.eclipse.californium.core.server.resources.CoapExchange;
import org.eclipse.californium.core.Utils;

import org.eclipse.californium.examples.T4RPiClientThread;

public class T4RPiServer extends CoapServer {

	static {
            CaliforniumLogger.initialize();
            CaliforniumLogger.setLevel(Level.CONFIG);
	}
	private static final int COAP_PORT = NetworkConfig.getStandard().getInt(NetworkConfig.Keys.COAP_PORT);
	public static Integer PORT ;
        public static String device_payload;
    /*
     * Application entry point.
     */
    public static void main(String[] args) {

        try {

            // create server
            T4RPiServer server = new T4RPiServer();
            // add endpoints on all IP addresses
            server.addEndpoints();
            PORT = COAP_PORT;//5683;//non secure port
            T4RPiClientThread clientthread = new T4RPiClientThread();
            clientthread.start();
            server.start();

        } catch (SocketException e) {
            System.err.println("Failed to initialize server: " + e.getMessage());
        }
    }

    /**
     * Add individual endpoints listening on default CoAP port on all IPv4 addresses of all network interfaces.
     */
    private void addEndpoints() {
    	for (InetAddress addr : EndpointManager.getEndpointManager().getNetworkInterfaces()) {
            // only binds to IPv4 addresses and localhost
            if (addr instanceof Inet4Address || addr.isLoopbackAddress()) {
                InetSocketAddress bindToAddress = new InetSocketAddress(addr, COAP_PORT);
                addEndpoint(new CoapEndpoint(bindToAddress));
            }
	}
    }

    /*
     * Constructor for a new Hello-World server. Here, the resources
     * of the server are initialized.
     */
    public T4RPiServer() throws SocketException {

        // provide an instance of a notify resource
        add(new NotifyResource());
        add(new DeviceResource());
        add(new ModeResource());
        add(new FetchitHealthResource());
        add(new GatewayHealthResource());
    }

    /*
     * Definition of the Notify Resource
     */
    class NotifyResource extends CoapResource {

        public NotifyResource() {

            // set resource identifier
            super("raspberry");

            // set display name
            getAttributes().setTitle("Raspberry Resource");
        }

	public void handlePOST(final CoapExchange exchange) {

            List<String> path = exchange.advanced().getRequest().getOptions().getUriPath();
            String ip_addr = exchange.getSourceAddress().getHostAddress();
            System.out.println("DeviceStatusResouce POST------------ : from " + ip_addr + ":" + " payload ");
            String data = new String(exchange.getRequestPayload());
            System.out.println("DeviceStatusResouce POST------------ : payload " + data);

            System.err.println("DeviceStatusResouce POST : " + path.toString() + " from " + ip_addr);
            exchange.respond("{\"result\":\"OK\"}");
            //todo - invoke raspberry pi device control
	}

        @Override
        public void handleGET(CoapExchange exchange) {

            // respond to the request
            exchange.respond("Raspberry");
        }
    }

    /*
     * Definition of the Device Resource
     */
    class DeviceResource extends CoapResource {
	public DeviceResource() {
            super("device");
            getAttributes().setTitle("Device Resource");
	}

	@Override
	public void handleGET(CoapExchange exchange) {
            exchange.respond(device_payload);
	}

	@Override
	public void handlePOST(CoapExchange exchange) {
            List<String> path = exchange.advanced().getRequest().getOptions().getUriPath();
            String ip_addr = exchange.getSourceAddress().getHostAddress();
            System.out.println("DeviceStatusResouce POST------------ : from " + ip_addr + ":" + " payload ");
            String data = new String(exchange.getRequestPayload());
            System.out.println("DeviceStatusResouce POST------------ : payload " + data);
            device_payload = data;
            System.err.println("DeviceStatusResouce POST : " + path.toString() + " from " + ip_addr);
            exchange.respond("{\"result\":\"OK\"}");
	}
    }

    /*
     * Definition of the Mode Resource
     */
    class ModeResource extends CoapResource {
	public ModeResource() {
            super("mode");
            getAttributes().setTitle("Mode Resource");
	}

	@Override
	public void handleGET(CoapExchange exchange) {
            exchange.respond("mode");
	}

	@Override
	public void handlePOST(CoapExchange exchange) {
            List<String> path = exchange.advanced().getRequest().getOptions().getUriPath();
            String ip_addr = exchange.getSourceAddress().getHostAddress();
            System.out.println("DeviceStatusResouce POST------------ : from " + ip_addr + ":" + " payload ");
            String data = new String(exchange.getRequestPayload());
            System.out.println("DeviceStatusResouce POST------------ : payload " + data);
            System.err.println("DeviceStatusResouce POST : " + path.toString() + " from " + ip_addr);
            exchange.respond("{\"result\":\"OK\"}");
	}
    }

    /*
     * Definition of the Fetchit Health Resource
     */
    class FetchitHealthResource extends CoapResource {
	public FetchitHealthResource() {
            super("fetchit_health");
            getAttributes().setTitle("Fetchit Health Resource");
	}

	@Override
	public void handleGET(CoapExchange exchange) {
            exchange.respond("fetchit_health");
	}

	@Override
	public void handlePOST(CoapExchange exchange) {
            List<String> path = exchange.advanced().getRequest().getOptions().getUriPath();
            String ip_addr = exchange.getSourceAddress().getHostAddress();
            System.out.println("DeviceStatusResouce POST------------ : from " + ip_addr + ":" + " payload ");
            String data = new String(exchange.getRequestPayload());
            System.out.println("DeviceStatusResouce POST------------ : payload " + data);
            System.err.println("DeviceStatusResouce POST : " + path.toString() + " from " + ip_addr);
            exchange.respond("{\"result\":\"OK\"}");
	}
    }

    /*
     * Definition of the Gateway Health Resource
     */
    class GatewayHealthResource extends CoapResource {
	public GatewayHealthResource() {
            super("gateway_health");
            getAttributes().setTitle("Gateway Health Resource");
	}

	@Override
	public void handleGET(CoapExchange exchange) {
            exchange.respond("gateway_health");
	}

	@Override
	public void handlePOST(CoapExchange exchange) {
            List<String> path = exchange.advanced().getRequest().getOptions().getUriPath();
            String ip_addr = exchange.getSourceAddress().getHostAddress();
            System.out.println("DeviceStatusResouce POST------------ : from " + ip_addr + ":" + " payload ");
            String data = new String(exchange.getRequestPayload());
            System.out.println("DeviceStatusResouce POST------------ : payload " + data);
            System.err.println("DeviceStatusResouce POST : " + path.toString() + " from " + ip_addr);
            exchange.respond("{\"result\":\"OK\"}");
	}
    }

}


text:
layout: page
title: Rowland Group Executive Retreat
date: 2016-05-24
author: Raymond Vaughan
tags: weekly links, java
status: published
summary: Nam ultricies sem sit amet ipsum convallis.
banner: images/banner/leisure-02.jpg
booking:
  startDate: 02/25/2016
  endDate: 02/28/2016
  ctyhocn: SELNCHX
  groupCode: RGER
published: true
---
Class aptent taciti sociosqu ad litora torquent per conubia nostra, per inceptos himenaeos. In et nibh vel lacus rhoncus eleifend. Duis enim nibh, ornare eu justo ut, pellentesque vehicula felis. Mauris a viverra enim, sed ultrices eros. Sed blandit efficitur augue. Donec dictum bibendum ex, quis sagittis neque aliquet sit amet. Integer luctus feugiat augue a fringilla. Cras eu nibh congue justo mollis pulvinar nec ut dolor. Donec auctor lorem eu nulla sagittis rutrum. Nullam sapien erat, euismod sit amet leo quis, aliquet eleifend justo. Ut sapien arcu, facilisis id molestie quis, gravida vel lacus. In finibus commodo sagittis.
Nulla mattis ante eget est ultricies pellentesque. Vestibulum commodo semper justo, eget imperdiet sapien finibus sed. Aliquam feugiat ipsum ac arcu dictum, at ultrices tortor vulputate. Nulla facilisi. Vestibulum ante ipsum primis in faucibus orci luctus et ultrices posuere cubilia Curae; Pellentesque sodales dui tortor, sit amet euismod odio laoreet nec. Curabitur consectetur leo a pretium imperdiet. Class aptent taciti sociosqu ad litora torquent per conubia nostra, per inceptos himenaeos. Cras sagittis augue eu euismod hendrerit. Curabitur rhoncus mi posuere ligula accumsan ultricies. Sed ultrices, nisl ut molestie vestibulum, sem lectus interdum dui, in efficitur arcu nibh in erat. Aenean auctor leo in ligula semper fermentum. Nam id viverra nisl.

* Etiam eu nunc at mauris bibendum luctus
* Aenean vehicula odio non pretium feugiat
* Nulla pulvinar velit nec dignissim maximus
* Aenean facilisis ligula ut nibh vulputate eleifend
* Aliquam at nibh sed neque faucibus lacinia eu ut nibh
* Etiam vitae nunc blandit, malesuada nunc non, vestibulum tortor.

In nunc tellus, venenatis eu ligula a, interdum porta eros. Nullam neque turpis, molestie nec nisi a, porttitor suscipit risus. Donec cursus, odio eget viverra faucibus, arcu nulla cursus libero, id finibus lectus ipsum in libero. Cras rhoncus purus vel tincidunt mollis. Suspendisse dapibus, libero eget dapibus placerat, dolor tortor tempus ante, sed accumsan odio quam vel lorem. Vestibulum ut sodales risus. Suspendisse ultricies leo eu varius commodo.


text:
FROM hhvm/hhvm-proxygen:latest

RUN apt-get update -y && apt-get install -y curl

# Install composer
RUN mkdir /opt/composer
RUN curl -sS https://getcomposer.org/installer | hhvm --php -- --install-dir=/opt/composer

# Install app
RUN rm -rf /var/www/app
ADD . /var/www/app
RUN cd /var/www/app && hhvm /opt/composer/composer.phar install

# Reconfigure HHVM
ADD hhvm/site.ini /etc/hhvm/site.ini

EXPOSE 80


text:
RSpec.describe "cassie:schema:dump rake task" do
  let(:object){ Rake::Task["cassie:schema:dump"] }
  let(:argv){ [] }
  let(:buffer){ StringIO.new }
  let(:process){ double(stop: true) }

  before(:each) do
    allow_any_instance_of(Cassie::Tasks::IO).to receive(:io){ buffer }
    allow_any_instance_of(Cassie::Tasks::IO).to receive(:argv){ argv }
    allow(Cassie::Schema).to receive(:version)
  end

  describe "#invoke" do
    it "dumps Schema" do
      expect_any_instance_of(Cassie::Schema::SchemaDumper).to receive(:dump)
      object.invoke
    end
  end
end


text:
require_relative '../spec_helper'

describe "register_block/clock_reset" do
  include_context 'configuration common'
  include_context 'register_map common'
  include_context 'rtl common'

  before(:all) do
    RgGen.enable(:register_block, :name       )
    RgGen.enable(:register_block, :clock_reset)
    configuration = dummy_configuration
    register_map  = create_register_map(
      @configuration,
      "block_0" => [
        [nil, nil, "block_0"]
      ]
    )
    @rtl  = build_rtl_factory.create(configuration, register_map)
  end

  after(:all) do
    clear_enabled_items
  end

  it "クロック入力ポートを持つ" do
    expect(@rtl.register_blocks[0]).to have_input(:register_block, :clock, name: "clk", data_type: :logic, width:1)
  end

  it "リセット入力ポートを持つ" do
    expect(@rtl.register_blocks[0]).to have_input(:register_block, :reset, name: "rst_n", data_type: :logic, width:1)
  end
end


text:
// Copyright Yahoo. Licensed under the terms of the Apache 2.0 license. See LICENSE in the project root.
/**
 * A cache for an ideal nodes implementation. Making it cheap for localized
 * access, regardless of real implementation.
 */
#pragma once

#include "idealnodecalculator.h"

namespace storage::lib {

class IdealNodeCalculatorImpl : public IdealNodeCalculatorConfigurable {
    std::vector<const char*> _upStates;
    const Distribution* _distribution;
    const ClusterState* _clusterState;

public:
    IdealNodeCalculatorImpl();
    ~IdealNodeCalculatorImpl();

    void setDistribution(const Distribution& d) override;
    void setClusterState(const ClusterState& cs) override;

    IdealNodeList getIdealNodes(const NodeType& nodeType,
                                const document::BucketId& bucket,
                                UpStates upStates) const override;
private:
    void initUpStateMapping();
};

}


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

/* jslint browser: true, node: true, white: true, forin: true, nomen: true, unparam: true, sloppy: false, vars: true */
this.xtrim = this.xtrim || {};
(function(global, xtrim) {
  'use strict';

	var mIDs = {},
		uid = {};

	/**
	 * Generates a string that can be assigned to an instance as its unique identifier.
	 *
	 * @returns {string} the unique id.
	 */
	var generateUniqueID = function(sId) {
		sId = sId && typeof sId === "string" ? sId : (Date.now().toString(36) + Math.random().toString(36).replace("0.", ""));
		while (mIDs.hasOwnProperty(sId)) {
			sId = (Date.now().toString(36) + Math.random().toString(36).replace("0.", ""));
		}
		return sId;
	};

	/**
	 * Sets a unique identifier to the given instance. If the explicit identifier is not available it will generate a new one.
	 *
	 * @param {object} oObj  the instance to which to set the identifier.
	 * @param {string} sId  an explicit id which will be applied only if it is not a duplicate.
	 * @returns {string} the instance.
	 */
	uid.setId = function(oObj, sId) {
		sId = typeof sId === "string" ? sId : generateUniqueID(sId);
		while (mIDs.hasOwnProperty(sId)) {
			sId = generateUniqueID();
		}
		mIDs[sId] = oObj;
		Object.defineProperty(oObj, "_sId", {
			value: sId
		});
		return oObj;
	};

	/**
	 * Returns a string which is the unique identifier of this instance.
	 *
	 * @param {object} oObj  the instance whose identifier to return.
	 * @returns {string} the unique identifier of this instance if it exists, or undefined otherwise.
	 */
	uid.getIdOf = function(oObj) {
		return oObj && oObj._sId ? oObj._sId : undefined;
	};

	/**
	 * Returns the instance identified by the given parameter, if it is a unique identifier of an instance, or undefined otherwise.
	 *
	 * @param {string} sId the instance identifier
	 * @returns {string} the unique identifier of this instance or undefined if not found.
	 */
	uid.getInstanceById = function(sId) {
		return mIDs[sId];
	};

	/**
	 * Returns the instance identified by the given parameter, if it is a unique identifier of an instance, or undefined otherwise.
	 *
	 * @param {string} sId the instance identifier
	 * @returns {string} the unique identifier of this instance or undefined if not found.
	 */
	uid.deleteId = function(sId) {
		var o = mIDs[sId];
		if (o && typeof o._sId === "string") {
			delete o._sId;
		}
		return delete mIDs[sId];
	};

  if (typeof define === 'function' && define.amd) {
    define(function () {
      return uid;
    });
  } else if (typeof exports === 'object') {
    module.exports = uid;
  } else {
	  xtrim.uid = uid;
  }
})(this, this.xtrim);


text:
import * as React from 'react';

interface NumberPickerProps extends React.Props<NumberPickerClass>{
    /**
     * The current value of the NumberPicker.
     */
    value?: number;
    /**
     * Default Value.
     */
    defaultValue?: number;
    /**
     * Change event Handler that is called when the value is changed. The handler is called with
     * the current numeric value or null.
     */
    onChange?: (value?: number) => void;
    /**
     * A format string used to display the number value. Localizer dependent, read localization
     * for more info.
     * @see http://jquense.github.io/react-widgets/docs/#i18n
     */
    format?: any;
    /**
     * Determines how the NumberPicker parses a number from the localized string representation.
     * You can also provide a parser Function to pair with a custom format.
     */
    parse?: string[] | ((str: string, culture: string) => number);
    /**
     * The minimum number that the NumberPicker value.
     * @default -Infinity
     */
    min?: number;
    /**
     * The maximum number that the NumberPicker value.
     * @default Infinity
     */
    max?: number;
    /**
     * Amount to increase or decrease value when using the spinner buttons.
     * @default 1
     */
    step?: number;
    /**
     * Specify how precise the value should be when typing, incrementing, or decrementing the
     * value. When empty, precision is parsed from the current format and culture.
     */
    precision?: number;
    /**
     * Mark whether the widget should render right-to-left. This property can also be implicitly
     * passed to the widget through a childContext prop (isRtl) this allows higher level
     * application components to specify the direction.
     * @default false
     */
    isRtl?: boolean;
    /**
     * Object hash containing display text and/or text for screen readers. Use the messages
     * object to localize widget text and increase accessibility.
     */
    messages?: NumberPickerMessages;
}

interface NumberPickerMessages {
    /**
     * Number picker spinner up button text for screen readers.
     * @default "increment value"
     */
    increment?: string;
    /**
     * Number picker spinner down button text for screen readers.
     * @default "decrement value"
     */
    decrement?: string;
}

interface NumberPicker extends React.ReactElement<NumberPickerProps> {}
interface NumberPickerClass extends React.ComponentClass<NumberPickerProps> {}
declare var NumberPicker: NumberPickerClass;
export = NumberPicker;


text:
/* ************************************************************************** */
/*                                                                            */
/*                                                        :::      ::::::::   */
/*   serialize_workunit.c                               :+:      :+:    :+:   */
/*                                                    +:+ +:+         +:+     */
/*   By: ssmith <marvin@42.fr>                      +#+  +:+       +#+        */
/*                                                +#+#+#+#+#+   +#+           */
/*   Created: 2017/05/17 17:21:10 by ssmith            #+#    #+#             */
/*   Updated: 2017/05/31 14:21:28 by ssmith           ###   ########.fr       */
/*                                                                            */
/* ************************************************************************** */

#include "dispatcher.h"
#include "lz4.h"
#include "transpose.h"

char *compress_locals(t_workunit w, int *loclen)
{
	//fill a buffer with all the local bodies.
	char *uncompressed = malloc(w.localcount * sizeof(t_body));
	int offset = 0;
	for (int i = 0; i < w.localcount; i++, offset += sizeof(t_body))
		memcpy(uncompressed + offset, w.local_bodies[i], sizeof(t_body));

	//byte transpose using TurboTranspose
	char *transposed = malloc(w.localcount * sizeof(t_body));
	tpenc((unsigned char *)uncompressed, w.localcount * sizeof(t_body), (unsigned char *)transposed, sizeof(t_body));

	//we cannot predict exactly how big the compressed result will be til we do it. LZ4_compressBound gives an upper bound.
	//allocate that much, compress into it. It returns an int representing how big the result actually was.
	int max_compressed_size = LZ4_compressBound(w.localcount * sizeof(t_body));
	char *compressed = malloc(max_compressed_size);
	//compress with LZ4
	int result_compressed_size = LZ4_compress_default(transposed, compressed, w.localcount * sizeof(t_body), max_compressed_size);
	*loclen = result_compressed_size;
	//printf("locals compressed to %d from %lu, %.f%% of original size\n", result_compressed_size, w.localcount * sizeof(t_body), (float)result_compressed_size * 100.0  / ((float)w.localcount * sizeof(t_body)));
	free(transposed);
	free(uncompressed);
	return(compressed);
}

char *compress_neighbors(t_workunit w, int *neighblen)
{
	//fill a buffer with all the neighbor positions.
	char *uncompressed = malloc(w.neighborcount * sizeof(cl_float4));
	int offset = 0;
	for (int i = 0; i < w.neighborcount; i++, offset += sizeof(cl_float4))
		memcpy(uncompressed + offset, &(w.neighborhood[i]->position), sizeof(cl_float4));

	//byte transpose using TurboTranspose
	char *transposed = malloc(w.neighborcount * sizeof(cl_float4));
	tpenc((unsigned char *)uncompressed, w.neighborcount * sizeof(cl_float4), (unsigned char *)transposed, sizeof(cl_float4));

	//we cannot predict exactly how big the compressed result will be til we do it. LZ4_compressBound gives an upper bound.
	//allocate that much, compress into it. It returns an int representing how big the result actually was.
	int max_compressed_size = LZ4_compressBound(w.neighborcount * sizeof(cl_float4));
	char *compressed = malloc(max_compressed_size);
	//compress with LZ4
	int result_compressed_size = LZ4_compress_default(transposed, compressed, w.neighborcount * sizeof(cl_float4), max_compressed_size);
	//printf("max_c_s %d vs result_c_s %d\n", max_compressed_size, result_compressed_size);
	*neighblen = result_compressed_size;
	//printf("neighbors compressed to %d bytes, originally %lu bytes, %.f%% of original size\n", result_compressed_size, w.neighborcount * sizeof(cl_float4), (float)result_compressed_size * 100.0  / ((float)w.neighborcount * sizeof(cl_float4)));
	free(transposed);
	free(uncompressed);
	return(compressed);
}

t_msg serialize_workunit(t_workunit w)
{
	t_msg msg;

	int local_compressed_size;
	char *localblob = compress_locals(w, &local_compressed_size);

	int neighborhood_compressed_size;
	char *neighborblob = compress_neighbors(w, &neighborhood_compressed_size);

	msg.size = sizeof(int) * 5 + local_compressed_size + neighborhood_compressed_size;
	msg.data = malloc(msg.size);
	int offset = 0;

	memcpy(msg.data, &(w.id), sizeof(int));
	offset += sizeof(int);

	memcpy(msg.data + offset, &(w.localcount), sizeof(int));
	offset += sizeof(int);

	memcpy(msg.data + offset, &(local_compressed_size), sizeof(int));
	offset += sizeof(int);

	memcpy(msg.data + offset, &(w.neighborcount), sizeof(int));
	offset += sizeof(int);

	memcpy(msg.data + offset, &(neighborhood_compressed_size), sizeof(int));
	offset += sizeof(int);

	memcpy(msg.data + offset, localblob, local_compressed_size);
	offset += local_compressed_size;

	memcpy(msg.data + offset, neighborblob, neighborhood_compressed_size);
	offset += neighborhood_compressed_size;
	G_workunit_size += offset;

	// if (offset == msg.size)
	// 	printf("sizes matched as expected\n");
	// else
	// 	printf("size mismatch, wtf\n");
	int origsize = w.localcount * sizeof(t_body) + w.neighborcount *sizeof(cl_float4) + 5 * sizeof(int);
	free(localblob);
	free(neighborblob);
	return (msg);
}


text:
package com.streamsets.pipeline.stage.origin.mongodb;

import com.mongodb.CursorType;
import com.mongodb.MongoClientException;
import com.mongodb.client.model.Filters;
import com.mongodb.client.model.Sorts;
import com.streamsets.pipeline.api.BatchMaker;
import com.streamsets.pipeline.api.Field;
import com.streamsets.pipeline.api.Record;
import com.streamsets.pipeline.api.StageException;
import com.streamsets.pipeline.api.impl.Utils;
import com.streamsets.pipeline.lib.event.NoMoreDataEvent;
import com.streamsets.pipeline.lib.util.ThreadUtil;
import com.streamsets.pipeline.stage.common.mongodb.Errors;
import com.streamsets.pipeline.stage.common.mongodb.Groups;
import com.streamsets.pipeline.stage.common.mongodb.MongoDBConfig;
import com.streamsets.pipeline.stage.common.mongodb.MongoDBUtil;
import org.bson.Document;
import org.bson.types.ObjectId;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.IOException;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;
import java.util.Map;

public class MongoDBSource extends AbstractMongoDBSource {
  private static final Logger LOG = LoggerFactory.getLogger(MongoDBSource.class);
  private static final String TIMESTAMP_FORMAT = "yyyy-MM-dd HH:mm:ss";

  private ObjectId initialObjectId;
  private String initialId; // Used only when Offset Field is String type
  private Date initialDate; // MongoDB does not support LocalDateTime yet
  private boolean EOSreached = false; //end of stream reached
  private long recordsSinceLastNMREvent = 0;
  private long errorRecordsSinceLastNMREvent = 0;
  private final SimpleDateFormat dateFormatter = new SimpleDateFormat(TIMESTAMP_FORMAT);

  private boolean checkBatchSize = true;

  public MongoDBSource(MongoSourceConfigBean configBean) {
    super(configBean);
  }

  @Override
  protected List<ConfigIssue> init() {
    List<ConfigIssue> issues = super.init();

    if (configBean.offsetType == OffsetFieldType.STRING) {
      initialId = configBean.initialOffset; // Ok to be empty
    } else {
      // Initial offset is required if offset type is ObjectId or Date.
      if (configBean.initialOffset == null || configBean.initialOffset.isEmpty()) {
        issues.add(
            getContext().createConfigIssue(
                Groups.MONGODB.name(),
                MongoDBConfig.CONFIG_PREFIX + "initialOffset",
                Errors.MONGODB_19,
                configBean.initialOffset
            )
        );
        return issues;
      }
      try {
        initialObjectId = new ObjectId(new SimpleDateFormat(TIMESTAMP_FORMAT).parse(configBean.initialOffset));
        initialDate = dateFormatter.parse(configBean.initialOffset);
      } catch (ParseException e) {
        issues.add(
            getContext().createConfigIssue(
                Groups.MONGODB.name(),
                MongoDBConfig.CONFIG_PREFIX + "initialOffset",
                Errors.MONGODB_05,
                configBean.initialOffset,
                configBean.offsetType.getLabel()
            )
        );
      }
    }
    return issues;
  }
  @Override
  public String produce(String lastSourceOffset, int maxBatchSize, BatchMaker batchMaker) throws StageException {
    // do not return null in the case where the table is empty on startup
    lastSourceOffset = lastSourceOffset == null ? "" : lastSourceOffset;
    String nextSourceOffset = lastSourceOffset;
    int numRecords = 0;

    prepareCursor(maxBatchSize, configBean.offsetField, lastSourceOffset);
    long batchWaitTime = System.currentTimeMillis() + (configBean.maxBatchWaitTime * 1000);

    try {
      int batchSize = Math.min(configBean.batchSize, maxBatchSize);
      if (!getContext().isPreview() && checkBatchSize && configBean.batchSize > maxBatchSize) {
        getContext().reportError(Errors.MONGODB_43, maxBatchSize);
        checkBatchSize = false;
      }

      while (numRecords < batchSize && System.currentTimeMillis() < batchWaitTime) {
        LOG.trace("Trying to get next doc from cursor");
        Document doc = cursor.tryNext();
        if (null == doc) {
          LOG.trace("Doc was null");
          if (!configBean.isCapped) {
            LOG.trace("Collection is not capped.");
            // If this is not a capped collection, then this means we've reached the end of the data.
            // and should get a new cursor.
            LOG.trace("Closing cursor.");
            cursor.close();
            cursor = null;
            // Wait the remaining time we have for this batch before trying again.
            long waitTime = Math.max(0, batchWaitTime - System.currentTimeMillis());
            LOG.trace("Sleeping for: {}", waitTime);
            ThreadUtil.sleep(waitTime);
            conditionallyGenerateNoMoreDataEvent();
            return nextSourceOffset;
          }
          continue;
        }

        // validate the date type of offset field is ObjectId or Date
        Object offsetFieldObject;
        if (configBean.offsetField.indexOf('.') == -1) {
          offsetFieldObject = doc.get(configBean.offsetField);
        } else {
          offsetFieldObject = getNestedFieldObject(doc);
        }
        if (offsetFieldObject == null
            || (configBean.offsetType == OffsetFieldType.OBJECTID && !(offsetFieldObject instanceof ObjectId))
            || (configBean.offsetType == OffsetFieldType.STRING && !(offsetFieldObject instanceof String))
            || (configBean.offsetType == OffsetFieldType.DATE && !(offsetFieldObject instanceof Date))) {
          LOG.debug(Errors.MONGODB_05.getMessage(), doc.toString(), configBean.offsetType.getLabel());
          errorRecordHandler.onError(Errors.MONGODB_05, doc, configBean.offsetType.getLabel());
          ++errorRecordsSinceLastNMREvent;
          continue;
        }

        Map<String, Field> fields;
        try {
          fields = MongoDBUtil.createFieldFromDocument(doc);
        } catch (IOException e) {
          LOG.debug(Utils.format(Errors.MONGODB_10.name(), e.toString()), e);
          errorRecordHandler.onError(Errors.MONGODB_10, e.toString(), e);
          ++errorRecordsSinceLastNMREvent;
          continue;
        }

        // get the offsetField
        nextSourceOffset = getNextSourceOffset(doc);

        final String recordContext =
            MongoDBUtil.getSourceRecordId(
                configBean.mongoConfig.connectionString,
                configBean.mongoConfig.database,
                configBean.mongoConfig.collection,
                nextSourceOffset
            );

        Record record = getContext().createRecord(recordContext);
        record.set(Field.create(fields));
        batchMaker.addRecord(record);
        ++numRecords;
        ++recordsSinceLastNMREvent;
      }
    } catch (MongoClientException e) {
      throw new StageException(Errors.MONGODB_12, e.toString(), e);
    }

    // if 2 cursors in a row have no data, we hit the end of the data stream
    if(EOSreached) {
      conditionallyGenerateNoMoreDataEvent();
    }
    EOSreached = nextSourceOffset.equals(lastSourceOffset);

    return nextSourceOffset;
  }

  private Object getNestedFieldObject(Document doc) throws StageException {
    String[] keys = configBean.offsetField.split("\\.");
    return getNestedFieldObject(doc, keys, 0);
  }

  private Object getNestedFieldObject(Document doc, String[] keys, int i) throws StageException {
    if (keys.length-1 == i) {
      return doc.get(keys[i]);
    }

    if (!doc.containsKey(keys[i])) {
      errorRecordHandler.onError(Errors.MONGODB_11, configBean.offsetField, doc.toString());
      ++errorRecordsSinceLastNMREvent;
    }

    return getNestedFieldObject((Document)doc.get(keys[i]), keys, i+1);
  }

  private String getNextSourceOffset(Document doc) throws StageException {
    String[] keys = configBean.offsetField.split("\\.");
    return parseSourceOffset(doc, keys, 0);
  }

  private String parseSourceOffset(Document doc, String[] keys, int i) throws StageException {
    if (keys.length-1 == i) {
      if (configBean.offsetType == OffsetFieldType.STRING) {
        return doc.get(keys[i]).toString();
      }
      else if(configBean.offsetType == OffsetFieldType.OBJECTID) {
        return doc.getObjectId(keys[i]).toHexString();
      }
      else if(configBean.offsetType == OffsetFieldType.DATE){
        return dateFormatter.format(doc.getDate(keys[i]));
      }
      else {
        throw new StageException(Errors.MONGODB_20, configBean.offsetType);
      }
    }

    if (!doc.containsKey(keys[i])) {
      errorRecordHandler.onError(Errors.MONGODB_11, configBean.offsetField, doc.toString());
      ++errorRecordsSinceLastNMREvent;
    }

    return parseSourceOffset((Document)doc.get(keys[i]), keys, i+1);
  }

  private void prepareCursor(int maxBatchSize, String offsetField, String lastSourceOffset) throws StageException {
    String stringOffset = "";
    ObjectId objectIdOffset = null;
    Date dateOffset = null;
    if (null == cursor) {
      if (null == lastSourceOffset || lastSourceOffset.isEmpty()) {
        objectIdOffset = initialObjectId;
        stringOffset = initialId;
        dateOffset = initialDate;
      } else {
        if (configBean.offsetType == OffsetFieldType.STRING)
          stringOffset = lastSourceOffset;
        else if (configBean.offsetType == OffsetFieldType.OBJECTID)
          objectIdOffset = new ObjectId(lastSourceOffset);
        else if (configBean.offsetType == OffsetFieldType.DATE) {
          try {
            dateOffset = dateFormatter.parse(lastSourceOffset);
          } catch (ParseException ex) {
            throw new StageException(Errors.MONGODB_21, lastSourceOffset);
          }
        }
      }
      LOG.debug("Getting new cursor with params: {} {} {}",
          maxBatchSize,
          offsetField,
          configBean.offsetType == OffsetFieldType.STRING ? stringOffset : configBean.offsetType == OffsetFieldType.OBJECTID ? objectIdOffset : dateOffset);

      if (configBean.isCapped) {
        cursor = mongoCollection
            .find(Filters.gt(
                offsetField,
                configBean.offsetType ==  OffsetFieldType.STRING ? stringOffset : configBean.offsetType == OffsetFieldType.OBJECTID ? objectIdOffset : dateOffset
            ))
            .cursorType(CursorType.TailableAwait)
            .batchSize(maxBatchSize)
            .iterator();
      } else {
        cursor = mongoCollection
            .find(Filters.gt(
                offsetField,
                configBean.offsetType ==  OffsetFieldType.STRING ? stringOffset : configBean.offsetType == OffsetFieldType.OBJECTID ? objectIdOffset : dateOffset
            ))
            .sort(Sorts.ascending(offsetField))
            .cursorType(CursorType.NonTailable)
            .batchSize(maxBatchSize)
            .iterator();
      }
    }
  }

  private void conditionallyGenerateNoMoreDataEvent() {
    if(recordsSinceLastNMREvent != 0 || errorRecordsSinceLastNMREvent != 0) {
      NoMoreDataEvent.EVENT_CREATOR.create(getContext())
          .with(NoMoreDataEvent.RECORD_COUNT, recordsSinceLastNMREvent)
          .with(NoMoreDataEvent.ERROR_COUNT, errorRecordsSinceLastNMREvent)
          .createAndSend();
      recordsSinceLastNMREvent = 0;
      errorRecordsSinceLastNMREvent = 0;
    }
  }
}


text:
.class final Lcom/android/server/dreams/DreamController$DreamRecord;
.super Ljava/lang/Object;
.source "DreamController.java"

# interfaces
.implements Landroid/os/IBinder$DeathRecipient;
.implements Landroid/content/ServiceConnection;

# annotations
.annotation system Ldalvik/annotation/EnclosingClass;
    value = Lcom/android/server/dreams/DreamController;
.end annotation

.annotation system Ldalvik/annotation/InnerClass;
    accessFlags = 0x12
    name = "DreamRecord"
.end annotation

# instance fields
.field public mBound:Z

.field public mConnected:Z

.field public final mIsTest:Z

.field public final mName:Landroid/content/ComponentName;

.field public mSentStartBroadcast:Z

.field public mService:Landroid/service/dreams/IDreamService;

.field public final mToken:Landroid/os/Binder;

.field public final mUserId:I

.field final synthetic this$0:Lcom/android/server/dreams/DreamController;

# direct methods
.method public constructor <init>(Lcom/android/server/dreams/DreamController;Landroid/os/Binder;Landroid/content/ComponentName;ZI)V
    .locals 0
    .parameter
    .parameter "token"
    .parameter "name"
    .parameter "isTest"
    .parameter "userId"

    .prologue
    .line 224
    iput-object p1, p0, Lcom/android/server/dreams/DreamController$DreamRecord;->this$0:Lcom/android/server/dreams/DreamController;

    invoke-direct/range {p0 .. p0}, Ljava/lang/Object;-><init>()V

    .line 225
    iput-object p2, p0, Lcom/android/server/dreams/DreamController$DreamRecord;->mToken:Landroid/os/Binder;

    .line 226
    iput-object p3, p0, Lcom/android/server/dreams/DreamController$DreamRecord;->mName:Landroid/content/ComponentName;

    .line 227
    iput-boolean p4, p0, Lcom/android/server/dreams/DreamController$DreamRecord;->mIsTest:Z

    .line 228
    iput p5, p0, Lcom/android/server/dreams/DreamController$DreamRecord;->mUserId:I

    .line 229
    return-void
.end method

# virtual methods
.method public binderDied()V
    .locals 2

    .prologue
    .line 234
    iget-object v0, p0, Lcom/android/server/dreams/DreamController$DreamRecord;->this$0:Lcom/android/server/dreams/DreamController;

    #getter for: Lcom/android/server/dreams/DreamController;->mHandler:Landroid/os/Handler;
    invoke-static {v0}, Lcom/android/server/dreams/DreamController;->access$200(Lcom/android/server/dreams/DreamController;)Landroid/os/Handler;

    move-result-object v0

    new-instance v1, Lcom/android/server/dreams/DreamController$DreamRecord$1;

    invoke-direct {v1, p0}, Lcom/android/server/dreams/DreamController$DreamRecord$1;-><init>(Lcom/android/server/dreams/DreamController$DreamRecord;)V

    invoke-virtual {v0, v1}, Landroid/os/Handler;->post(Ljava/lang/Runnable;)Z

    .line 243
    return-void
.end method

.method public onServiceConnected(Landroid/content/ComponentName;Landroid/os/IBinder;)V
    .locals 2
    .parameter "name"
    .parameter "service"

    .prologue
    .line 248
    iget-object v0, p0, Lcom/android/server/dreams/DreamController$DreamRecord;->this$0:Lcom/android/server/dreams/DreamController;

    #getter for: Lcom/android/server/dreams/DreamController;->mHandler:Landroid/os/Handler;
    invoke-static {v0}, Lcom/android/server/dreams/DreamController;->access$200(Lcom/android/server/dreams/DreamController;)Landroid/os/Handler;

    move-result-object v0

    new-instance v1, Lcom/android/server/dreams/DreamController$DreamRecord$2;

    invoke-direct {v1, p0, p2}, Lcom/android/server/dreams/DreamController$DreamRecord$2;-><init>(Lcom/android/server/dreams/DreamController$DreamRecord;Landroid/os/IBinder;)V

    invoke-virtual {v0, v1}, Landroid/os/Handler;->post(Ljava/lang/Runnable;)Z

    .line 257
    return-void
.end method

.method public onServiceDisconnected(Landroid/content/ComponentName;)V
    .locals 2
    .parameter "name"

    .prologue
    .line 262
    iget-object v0, p0, Lcom/android/server/dreams/DreamController$DreamRecord;->this$0:Lcom/android/server/dreams/DreamController;

    #getter for: Lcom/android/server/dreams/DreamController;->mHandler:Landroid/os/Handler;
    invoke-static {v0}, Lcom/android/server/dreams/DreamController;->access$200(Lcom/android/server/dreams/DreamController;)Landroid/os/Handler;

    move-result-object v0

    new-instance v1, Lcom/android/server/dreams/DreamController$DreamRecord$3;

    invoke-direct {v1, p0}, Lcom/android/server/dreams/DreamController$DreamRecord$3;-><init>(Lcom/android/server/dreams/DreamController$DreamRecord;)V

    invoke-virtual {v0, v1}, Landroid/os/Handler;->post(Ljava/lang/Runnable;)Z

    .line 271
    return-void
.end method


text:
all: push

# Keep this one version ahead, so no one accidentally blows away the latest published version.
TAG = 1.1

explorer: explorer.go
	CGO_ENABLED=0 GOOS=linux go build -a -installsuffix cgo -ldflags '-w' ./explorer.go

container: explorer
	docker build --pull -t staging-k8s.gcr.io/explorer:$(TAG) .

push: container
	gcloud docker -- push staging-k8s.gcr.io/explorer:$(TAG)

clean:
	rm -f explorer


text:
<?php

require_once 'Sitengine/Db/TableWithFiles.php';

class Sitengine_Newsletter_Campaigns_Table extends Sitengine_Db_TableWithFiles
{

    const VALUE_NONESELECTED = 'noneSelected';

    protected $_newsletterPackage = null;

    public function __construct(array $config = array())
    {
    	if(
    		isset($config['newsletterPackage']) &&
    		$config['newsletterPackage'] instanceof Sitengine_Newsletter
    	) {
    		$this->_newsletterPackage = $config['newsletterPackage'];
    		$this->_name = $this->_newsletterPackage->getCampaignsTableName();
    		$this->_primary = 'id';
    		parent::__construct($config);
    	}
    	else {
			require_once 'Sitengine/Newsletter/Exception.php';
			throw new Sitengine_Newsletter_Exception('campaigns table class init error');
		}
    }

    public function getNewsletterPackage()
    {
    	return $this->_newsletterPackage;
    }

    public function complementRow(Sitengine_Newsletter_Campaigns_Row $row)
    {
		$data = $row->toArray();
		return $data;
    }

    public function getDefaultPermissionData(Sitengine_Permiso $permiso, $ownerGroup)
    {
    	$gid = $permiso->getDirectory()->getGroupId($ownerGroup);
		$gid = (!is_null($gid)) ? $gid : Sitengine_Permiso::GID_ADMINISTRATORS;

		return array(
			Sitengine_Permiso::FIELD_UID => $permiso->getAuth()->getId(),
			Sitengine_Permiso::FIELD_GID => $gid,
			Sitengine_Permiso::FIELD_RAG => 1,
			Sitengine_Permiso::FIELD_RAW => 1,
			Sitengine_Permiso::FIELD_UAG => 1,
			Sitengine_Permiso::FIELD_UAW => 0,
			Sitengine_Permiso::FIELD_DAG => 1,
			Sitengine_Permiso::FIELD_DAW => 0
		);
    }

	public function delete($where)
    {
    	try {
    		$deleted = 0;
    		$campaigns = $this->selectRowsAndFiles($where);

    		foreach($campaigns as $campaign)
    		{
				$where = $this->getAdapter()->quoteInto('campaignId = ?', $campaign->id);
				$deleted += $this->_newsletterPackage->getAttachmentsTable()->delete($where);
				$deleted += $this->deleteRowAndFiles($campaign);
    		}
    		return $deleted;
		}
		catch (Exception $exception) {
			require_once 'Sitengine/Newsletter/Exception.php';
        	throw new Sitengine_Newsletter_Exception('campaign delete error', $exception);
		}
    }

    /*
    $params = array(
    	'type' => '',
    	'find' => '',
    	'reset' => ''
    );
    */
    public function getFilterInstance(
    	Sitengine_Controller_Request_Http $request,
    	array $params,
    	Zend_Session_Namespace $namespace
    )
    {
    	require_once 'Sitengine/Grid/Search.php';
    	$filter = new Sitengine_Grid_Search();
		$reset = ($request->get($params['reset']));

		### filter element ###
		if($reset) { $filter->resetSessionVal($params['type'], $namespace); }
		$filter->registerSessionVal(
			$namespace,
			$request,
			$params['type'],
			self::VALUE_NONESELECTED
		);
		# set clause
		if($filter->getVal($params['type'])) {
			$value = $this->getAdapter()->quote($filter->getVal($params['type']));
			$clause = "$campaigns.type = $value";
			$filter->setClause($params['type'], $clause);
		}

		### filter element ###
		if($reset) { $filter->resetSessionVal($params['find'], $namespace); }
		$filter->registerSessionVal(
			$namespace,
			$request,
			$params['find'],
			self::VALUE_NONESELECTED
		);
		# set clause
		if($filter->getVal($params['find'])) {
			$value = $this->getAdapter()->quote($filter->getVal($params['find']));
			$value = preg_replace('/\s+/', ' ', $value);
			$value = preg_replace('/.(.*)./', "$1", trim($value)); # remove quote delimiters
			$clause  = "(";
			$clause .= "LOWER({$this->_name}.title) LIKE LOWER('%$value%')";
			$clause .= " OR LOWER({$this->_name}.body) LIKE LOWER('%$value%')";
			$clause .= ")";
			$filter->setClause($params['find'], $clause);
		}
		return $filter;
    }

    public function getSortingInstance($currentRule, $currentOrder)
    {
    	require_once 'Sitengine/Grid/Sorting.php';
    	$sorting = new Sitengine_Grid_Sorting($currentRule, $currentOrder);
		$sorting
			->addRule('cdate', 'desc', "{$this->_name}.cdate asc", "{$this->_name}.cdate desc")
			->addRule('mdate', 'desc', "{$this->_name}.mdate asc", "{$this->_name}.mdate desc")
			->addRule('publish', 'asc', "{$this->_name}.publish asc", "{$this->_name}.publish desc")
			->addRule('type', 'asc', "{$this->_name}.type asc", "{$this->_name}.type desc")
			->addRule('title', 'asc', "title asc", "title desc")
			->addRule('body', 'asc', "body asc", "body desc")
			->setDefaultRule('cdate')
		;
		return $sorting;
    }

}

?>


text:
<?php

namespace Amadeus\Client\Struct\Air\RetrieveSeatMap;

/**
 * ProcessIndicators
 *
 * @package Amadeus\Client\Struct\Air\RetrieveSeatMap
 * @author Dieter Devlieghere <dermikagh@gmail.com>
 */
class ProcessIndicators
{
    /**
     * @var StatusInformation[]
     */
    public $statusInformation = [];

    /**
     * ProcessIndicators constructor.
     *
     * @param string $action
     */
    public function __construct($action)
    {
        $this->statusInformation[] = new StatusInformation($action);
    }
}


text:
<?php
namespace meteor\endpoints\login;

use common\core\Endpoint;
use common\data\Token;
use common\exceptions\InvalidTokenException;
use meteor\database\Backend;
use meteor\database\backend\TokenBackend;
use meteor\database\backend\UserBackend;
use meteor\exceptions\InvalidUserException;

class RefreshEndpoint extends Endpoint
{
    public function handle($data)
    {
        $this->validate_request(["user", "refresh-token"]);

        $profile = UserBackend::fetch_user_profile($data->{"user"});
        $refresh = Token::decode($data->{"refresh-token"});

        if (!$refresh->getUserSecret() == $profile->getUserId()->getUserSecret()) {
            throw new InvalidUserException("User provided and token do not match");
        }

        if (!TokenBackend::validate_token($this->clientid, $profile->getUserId(), $refresh)) {
            throw new InvalidTokenException("Invalid refresh token or userid provided");
        }

        TokenBackend::clear_tokens($this->clientid, $profile->getUserId(), TOKEN_ACCESS);
        $access = TokenBackend::create_token($this->clientid, $profile->getUserId(), TOKEN_ACCESS, "1 HOUR");

        return [
            "user-profile" => $profile->toExternalForm(),
            "access-token" => ["token" => $access->toString(), "expires" => 3600]
        ];
    }
}


text:
puts "Seeding #{__FILE__} from Spina::Engine"

Spina::User.destroy_all
Spina::User.create name: "Bram", email: "bram@denkgroot.com", password: "spina", password_confirmation: "spina", admin: true

Spina::Account.destroy_all
Spina::Account.create name: "Website"

Spina::Page.destroy_all

Spina::Photo.destroy_all
['after sun 2', 'after sun', 'amygdalus', 'at sunset-1', 'colorfull', 'nature tree', 'orchid', 'smooth', 'soft', 'spring memory', 'spring purple', 'spring', 'yew-tree'].each do |image|
  Spina::Photo.create({ file:  File.open(File.join(Spina::Engine.root, "test/support/images/#{image}.jpg")) })
end


text:
ComplexType Sequence
--FILE--
<?php

// PHP classes corresponding to the data types in defined in WSDL

class myDemo {
    public $demo1; // int
    public $demo2; // string
}

// define the class map
$class_map = array(
 "anyType" => "anyType", "myDemo" => "myDemo");

try {

    // create client in WSDL mode
    $client = new WSClient(array ("wsdl" =>"http://localhost/services/wsdl_mode/ComplexTypeSequenceService.php?wsdl",
        "classmap" => $class_map,
                            ));

    // get proxy object reference form client
    $proxy = $client->getProxy();

    // create input object and set values
    $input = new myDemo();
    //TODO: fill in the class fields of $input to match your business logic
    $input->demo1 = 3;
    $input->demo2 = "test";

    // call the operation
    $response = $proxy->myDemo($input);
    //TODO: Implement business logic to consume $response, which is of type string

    echo $response."\n";

} catch (Exception $e) {
    // in case of an error, process the fault
    if ($e instanceof WSFault) {
        printf("Soap Fault: %s\n", $e->Reason);
    } else {
        printf("Message = %s\n", $e->getMessage());
    }
}
?>
--EXPECT--
myDemo Object
(
    [demo1] => 3
    [demo2] => test
)


text:
// ----------------------------------------------------------------------
// This code is developed as part of the Java CoG Kit project
// The terms of the license can be found at http://www.cogkit.org/license
// This message may not be removed or altered.
// ----------------------------------------------------------------------

package org.globus.cog.abstraction.impl.common;

import java.util.ArrayList;
import java.util.Collection;
import java.util.HashMap;
import java.util.Map;

import org.globus.cog.abstraction.impl.common.task.ActiveTaskException;
import org.globus.cog.abstraction.impl.common.task.IllegalSpecException;
import org.globus.cog.abstraction.impl.common.task.InvalidSecurityContextException;
import org.globus.cog.abstraction.impl.common.task.InvalidServiceContactException;
import org.globus.cog.abstraction.impl.common.task.TaskSubmissionException;
import org.globus.cog.abstraction.interfaces.DelegatedTaskHandler;
import org.globus.cog.abstraction.interfaces.Status;
import org.globus.cog.abstraction.interfaces.Task;
import org.globus.cog.abstraction.interfaces.TaskHandler;

/**
 * Provides an abstract TaskHandler.
 */
public abstract class AbstractTaskHandler extends TaskHandlerSkeleton {
	private Map<Task, DelegatedTaskHandler> handleMap;

	public AbstractTaskHandler() {
		this.handleMap = new HashMap<Task, DelegatedTaskHandler>();
		setType(TaskHandler.GENERIC);
	}

	public void submit(Task task) throws IllegalSpecException, InvalidSecurityContextException,
			InvalidServiceContactException, TaskSubmissionException {
		if (task.getStatus().getStatusCode() != Status.UNSUBMITTED) {
			throw new TaskSubmissionException("TaskHandler can only handle unsubmitted tasks");
		}
		int type = task.getType();
		DelegatedTaskHandler dth = newDelegatedTaskHandler(type);
		synchronized(this.handleMap) {
		    this.handleMap.put(task, dth);
		}
		dth.submit(task);
	}

	protected abstract DelegatedTaskHandler newDelegatedTaskHandler(int type) throws TaskSubmissionException;

	public abstract String getName();

	public void setName(String name) {
	    // ignored for most handlers
	}

	public void suspend(Task task) throws InvalidSecurityContextException, TaskSubmissionException {
		DelegatedTaskHandler dth = this.handleMap.get(task);
		if (dth != null) {
			dth.suspend();
		}
	}

	public void resume(Task task) throws InvalidSecurityContextException, TaskSubmissionException {
		DelegatedTaskHandler dth = this.handleMap.get(task);
		if (dth != null) {
			dth.resume();
		}
	}

	public void cancel(Task task, String message) throws InvalidSecurityContextException, TaskSubmissionException {
		DelegatedTaskHandler dth = this.handleMap.get(task);
		if (dth != null) {
			dth.cancel(message);
		}
		else {
			task.setStatus(new StatusImpl(Status.CANCELED, message, null));
		}
	}

	public void remove(Task task) throws ActiveTaskException {
		if (!handleMap.containsKey(task)) {
			return;
		}
		int status = task.getStatus().getStatusCode();
		if ((status == Status.ACTIVE)) {
			throw new ActiveTaskException("Cannot remove an active or suspended Task");
		}
		else {
		    synchronized(this.handleMap) {
		        this.handleMap.remove(task);
		    }
		}
	}

	/** return a collection of all tasks submitted to the handler */
	public Collection<Task> getAllTasks() {
		try {
			return new ArrayList<Task>(handleMap.keySet());
		}
		catch (Exception e) {
			return null;
		}
	}

	protected Collection<Task> getTasksWithStatus(int code) {
        Collection<Task> list = new ArrayList<Task>();
        synchronized(handleMap) {
            for (Task task : handleMap.keySet()) {
                if (task.getStatus().getStatusCode() == code) {
                	list.add(task);
                }
            }
        }
        return list;
    }

	/** return a collection of active tasks */
	public Collection<Task> getActiveTasks() {
	    return getTasksWithStatus(Status.ACTIVE);
	}

	/** return a collection of failed tasks */
	public Collection<Task> getFailedTasks() {
	    return getTasksWithStatus(Status.FAILED);
	}

	/** return a collection of completed tasks */
	public Collection<Task> getCompletedTasks() {
	    return getTasksWithStatus(Status.COMPLETED);
	}

	/** return a collection of suspended tasks */
	public Collection<Task> getSuspendedTasks() {
	    return getTasksWithStatus(Status.SUSPENDED);
	}

	/** return a collection of resumed tasks */
	public Collection<Task> getResumedTasks() {
	    return getTasksWithStatus(Status.RESUMED);
	}

	/** return a collection of canceled tasks */
	public Collection<Task> getCanceledTasks() {
	    return getTasksWithStatus(Status.CANCELED);
	}
}


text:
package de.conterra.babelfish.plugin;

/**
 * describes a {@link Plugin}, which could loaded from a JAR
 *
 * @author ChrissW-R1
 * @version 0.1.0
 * @since 0.1.0
 */
public interface Plugin {
	/**
	 * gives the name
	 *
	 * @return the name
	 *
	 * @since 0.1.0
	 */
	public String getName();

	/**
	 * initialize the {@link Plugin} (e.g. registers all {@link RestService}s)
	 *
	 * @return {@code true}, if the {@link Plugin} initialized successfully
	 *
	 * @since 0.1.0
	 */
	public boolean init();

	/**
	 * Called, when the {@link Plugin} is unload
	 *
	 * @return {@code true}, if the shutdown was successfully finished
	 *
	 * @since 0.1.0
	 */
	public boolean shutdown();
}


text:
void exposeOSG ();

void exposeGV ();

void exposeGG ();


text:
import { Product } from './../../core/models/product';
import { AppState } from './../../interfaces';
import { ProductState } from './product-state';
import { createSelector } from 'reselect';
import { Map, List, fromJS } from 'immutable';

// Base product state selector function
export function getProductState(state: AppState): ProductState {
  return state.products;
}

export function fetchProducts(state:ProductState) {
    const ids = state.productIds.toJS();
    const productEntities = state.productEntities.toJS();
    return ids.map(id => productEntities[id]);
}

const fetchSelectedProduct = function (state): Product {
  return state.selectedProduct;
};

//**** PUBLIC API ****/
export const getProducts = createSelector(getProductState, fetchProducts);


text:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;

namespace WMSURFIDSYS.ViewModel
{
    public class ImportViewModelData
    {
        public List<ImportViewModel> StudentList { get; set; }
    }

    public class ImportViewModel
    {
        public int StudentID { get; set; }
        public string LastName { get; set; }
        public string FirstName { get; set; }
        public DateTime EnrollmentDate { get; set; }
        //public List<ImportViewModelData> StudentList { get; set; }
    }
}


text:
#ifndef _ASM_X86_HYPERVISOR_H
#define _ASM_X86_HYPERVISOR_H

#ifdef CONFIG_HYPERVISOR_GUEST

#include <asm/kvm_para.h>
#include <asm/xen/hypervisor.h>

/*
 * x86 hypervisor information
 */
struct hypervisor_x86 {
	/* Hypervisor name */
	const char	*name;

	/* Detection routine */
	uint32_t	(*detect)(void);

	/* Adjust CPU feature bits (run once per CPU) */
	void		(*set_cpu_features)(struct cpuinfo_x86 *);

	/* Platform setup (run once per boot) */
	void		(*init_platform)(void);

	/* X2APIC detection (run once per boot) */
	bool		(*x2apic_available)(void);
};

extern const struct hypervisor_x86 *x86_hyper;

/* Recognized hypervisors */
extern const struct hypervisor_x86 x86_hyper_vmware;
extern const struct hypervisor_x86 x86_hyper_ms_hyperv;
extern const struct hypervisor_x86 x86_hyper_xen;
extern const struct hypervisor_x86 x86_hyper_kvm;

extern void init_hypervisor(struct cpuinfo_x86 *c);
extern void init_hypervisor_platform(void);
extern bool hypervisor_x2apic_available(void);
#else
static inline void init_hypervisor(struct cpuinfo_x86 *c) { }
static inline void init_hypervisor_platform(void) { }
static inline bool hypervisor_x2apic_available(void) { return false; }
#endif /* CONFIG_HYPERVISOR_GUEST */
#endif /* _ASM_X86_HYPERVISOR_H */


text:
"""example python spouts"""
__all__ = ['consume_bolt', 'count_bolt', 'half_ack_bolt',
           'stream_aggregate_bolt', 'window_size_bolt']

from .consume_bolt import ConsumeBolt
from .count_bolt import CountBolt
from .stateful_count_bolt import StatefulCountBolt
from .half_ack_bolt import HalfAckBolt
from .stream_aggregate_bolt import StreamAggregateBolt
from .window_size_bolt import WindowSizeBolt


text:
import FileLibrary_Keywords
import json
import os
import sys
import time
import inspect
import uuid
import datetime
import tempfile

from robot.libraries.BuiltIn import BuiltIn
from robot.utils.normalizing import NormalizedDict
from robot.libraries.Remote import Remote
from robot.libraries.Process import Process
from robot.api import logger

class FileLibrary:

  ROBOT_LIBRARY_SCOPE = 'TEST SUITE'
  AGENT_PATH = os.path.abspath(os.path.dirname(__file__))
  KEYWORDS = ['get_file_library_server_pid' , 'get_random_UUID']

  def __init__(self, path='', debug=False):
    self.driverPath = path
    self.debug = debug
    self.remoteLib = None
    self.started = datetime.datetime.now()
    self.process = Process()

  def __init_remote_process__(self):
    debugArg = '-agentlib:jdwp=transport=dt_socket,address=8001,server=y,suspend=n'
    jars = set(filter(lambda k: k.endswith('.jar'), sys.path))
    jars.add(self.driverPath)
    jars.add(FileLibrary.AGENT_PATH)
    jars.add(os.environ.get('CLASSPATH',''))
    jars.add(os.environ.get('PYTHONPATH',''))
    jars.add(os.environ.get('JYTHONPATH',''))
    jarSet = set(filter (None, jars ))
    classPath = os.pathsep.join(jars)
    mainClass = 'io.github.dvanherbergen.filelibrary.remote.RPCServer'
    pidFilename = os.path.join(tempfile.gettempdir(), (str(uuid.uuid4()) + '.pid'))
    logFile = os.path.join(tempfile.gettempdir(), 'filelibrary-' + (str(uuid.uuid4())) + '.log')
    print("Logging to " + logFile)
    if self.debug:
      print("starting process ", 'java', debugArg, "-cp", classPath, mainClass, pidFilename)
      self.process.start_process('java', debugArg, "-cp", classPath, mainClass, pidFilename, shell=True, cwd='', alias='rpcServer', stdout=logFile, stderr=None)
    else:
      print("starting process ", 'java', "-cp", classPath, mainClass, pidFilename)
      self.process.start_process('java', "-cp", classPath, mainClass, pidFilename, shell=True, cwd='', alias='rpcServer', stdout=logFile, stderr=None)
    i = 0
    # Wait till file is created max wait = 10 seconds
    while not os.path.exists(pidFilename) and i < 400:
      time.sleep(.05)
      i += 1
    # Wait some more to make sure the port is written to the file
    time.sleep(.1)
    pid_file = open(pidFilename, "r")
    port = pid_file.read()
    print("Received file library port: " + port + ", waited " + str(i*0.05)  +" s")
    pid_file.close()
    os.remove(pidFilename)
    self.remoteLib = Remote('http://127.0.0.1:' + port)

  def get_robot_variables(self):
    values = []
    for name, value in BuiltIn().get_variables(no_decoration=True).items():
      item = name, value
      if not isinstance(value, NormalizedDict):
        values.append(item)
    return json.dumps(dict(values), ensure_ascii=False)

  def get_keyword_names(self):
     return FileLibrary.KEYWORDS + [kw for kw in FileLibrary_Keywords.keywords]

  def get_file_library_server_pid(self):
    if self.process and self.remoteLib:
      return self.process.get_process_id('rpcServer')
    return None

  def get_random_UUID(self):
    return str(uuid.uuid4())

  def get_keyword_arguments(self, name):
    if name in FileLibrary.KEYWORDS:
      return self._get_args(name)
    return FileLibrary_Keywords.keyword_arguments[name]

  def _get_args(self, method_name):
    spec = inspect.getargspec(getattr(self, method_name))
    args = spec[0][1:]
    if spec[3]:
      for i, item in enumerate(reversed(spec[3])):
        args[-i-1] = args[-i-1]+'='+str(item)
    if spec[1]:
      args += ['*'+spec[1]]
    if spec[2]:
      args += ['**'+spec[2]]
    return args

  def get_keyword_documentation(self, name):
    if name == '__init__':
      return FileLibrary_Keywords.keyword_documentation['__intro__']
    if name in FileLibrary.KEYWORDS:
      return getattr(self, name).__doc__
    return FileLibrary_Keywords.keyword_documentation[name]

  def run_keyword(self, name, arguments, kwargs):
    if ( name == 'stop' or  name == 'disconnect' ) and  self.remoteLib == None:
      return
    if (self.remoteLib == None):
      self.__init_remote_process__()
    if name in FileLibrary.KEYWORDS:
      return getattr(self, name)(*arguments, **kwargs)
    if name == 'resetTemplateData':
      if (len(arguments) > 0 and arguments[0].lower() == 'true'):
        # inject all variables from the test case context
        self.remoteLib.run_keyword(name, (self.get_robot_variables(),), kwargs)
      else:
        self.remoteLib.run_keyword(name, (), kwargs)
    else:
      return self.remoteLib.run_keyword(name, arguments, kwargs)


text:
package java.lang.reflect;
public class InvocationTargetException extends java.lang.Exception {
	protected InvocationTargetException() { }
	public InvocationTargetException(java.lang.Throwable var0) { }
	public InvocationTargetException(java.lang.Throwable var0, java.lang.String var1) { }
	public java.lang.Throwable getTargetException() { return null; }
	public void printStackTrace() { }
	public void printStackTrace(java.io.PrintStream var0) { }
	public void printStackTrace(java.io.PrintWriter var0) { }
}


text:
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools" android:layout_width="match_parent"
    android:layout_height="match_parent" android:paddingLeft="@dimen/activity_horizontal_margin"
    android:paddingRight="@dimen/activity_horizontal_margin"
    android:paddingTop="@dimen/activity_vertical_margin"
    android:paddingBottom="@dimen/activity_vertical_margin"
    tools:context="com.opensource.trafficrush.SplashScreen">

    <Button
        android:id="@+id/Login"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="Login with Google"
        android:layout_below="@+id/editText"
        android:layout_centerHorizontal="true"
        android:layout_marginTop="33dp" />

    <TextView
        android:id="@+id/ID"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:text="ID:"
        android:textAppearance="@style/TextAppearance.AppCompat.Medium"
        tools:ignore="HardcodedText"
        android:layout_alignParentLeft="true"
        android:layout_alignParentStart="true" />

    <TextView
        android:id="@+id/Password"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:text="Password:"
        android:textAppearance="@style/TextAppearance.AppCompat.Medium"
        tools:ignore="HardcodedText"
        android:layout_below="@+id/editText2"
        android:layout_centerHorizontal="true"
        android:layout_marginTop="32dp" />

    <Button
        android:id="@+id/Register"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="Register with Google"
        android:layout_alignParentBottom="true"
        android:layout_centerHorizontal="true"
        android:layout_marginBottom="164dp" />

    <TextView
        android:id="@+id/textView"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="If you don't have a Google account, you have to first register and then come back to the Traffic Rush app and then login using your Google account details."
        android:textAppearance="@style/TextAppearance.AppCompat"
        android:layout_above="@+id/Register"
        android:layout_alignParentLeft="true"
        android:layout_alignParentStart="true"
        android:layout_marginBottom="60dp" />

    <EditText
        android:id="@+id/editText"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:ems="10"
        android:inputType="textPassword"
        android:layout_below="@+id/Password"
        android:layout_alignParentLeft="true"
        android:layout_alignParentStart="true"
        android:layout_alignParentRight="true"
        android:layout_alignParentEnd="true" />

    <EditText
        android:id="@+id/editText2"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:ems="10"
        android:inputType="textEmailAddress"
        android:layout_below="@+id/ID"
        android:layout_alignParentLeft="true"
        android:layout_alignParentStart="true"
        android:layout_alignParentRight="true"
        android:layout_alignParentEnd="true" />
</RelativeLayout>


text:
require 'google/protobuf'

require 'google/api/annotations_pb'
require 'google/api/client_pb'
require 'google/api/field_behavior_pb'
require 'google/api/resource_pb'
require 'google/cloud/essentialcontacts/v1/enums_pb'
require 'google/protobuf/empty_pb'
require 'google/protobuf/field_mask_pb'
require 'google/protobuf/timestamp_pb'

Google::Protobuf::DescriptorPool.generated_pool.build do
  add_file("google/cloud/essentialcontacts/v1/service.proto", :syntax => :proto3) do
    add_message "google.cloud.essentialcontacts.v1.Contact" do
      optional :name, :string, 1
      optional :email, :string, 2
      repeated :notification_category_subscriptions, :enum, 3, "google.cloud.essentialcontacts.v1.NotificationCategory"
      optional :language_tag, :string, 4
      optional :validation_state, :enum, 8, "google.cloud.essentialcontacts.v1.ValidationState"
      optional :validate_time, :message, 9, "google.protobuf.Timestamp"
    end
    add_message "google.cloud.essentialcontacts.v1.ListContactsRequest" do
      optional :parent, :string, 1
      optional :page_size, :int32, 2
      optional :page_token, :string, 3
    end
    add_message "google.cloud.essentialcontacts.v1.ListContactsResponse" do
      repeated :contacts, :message, 1, "google.cloud.essentialcontacts.v1.Contact"
      optional :next_page_token, :string, 2
    end
    add_message "google.cloud.essentialcontacts.v1.GetContactRequest" do
      optional :name, :string, 1
    end
    add_message "google.cloud.essentialcontacts.v1.DeleteContactRequest" do
      optional :name, :string, 1
    end
    add_message "google.cloud.essentialcontacts.v1.CreateContactRequest" do
      optional :parent, :string, 1
      optional :contact, :message, 2, "google.cloud.essentialcontacts.v1.Contact"
    end
    add_message "google.cloud.essentialcontacts.v1.UpdateContactRequest" do
      optional :contact, :message, 2, "google.cloud.essentialcontacts.v1.Contact"
      optional :update_mask, :message, 3, "google.protobuf.FieldMask"
    end
    add_message "google.cloud.essentialcontacts.v1.ComputeContactsRequest" do
      optional :parent, :string, 1
      repeated :notification_categories, :enum, 6, "google.cloud.essentialcontacts.v1.NotificationCategory"
      optional :page_size, :int32, 3
      optional :page_token, :string, 4
    end
    add_message "google.cloud.essentialcontacts.v1.ComputeContactsResponse" do
      repeated :contacts, :message, 1, "google.cloud.essentialcontacts.v1.Contact"
      optional :next_page_token, :string, 2
    end
    add_message "google.cloud.essentialcontacts.v1.SendTestMessageRequest" do
      repeated :contacts, :string, 1
      optional :resource, :string, 2
      optional :notification_category, :enum, 3, "google.cloud.essentialcontacts.v1.NotificationCategory"
    end
  end
end

module Google
  module Cloud
    module EssentialContacts
      module V1
        Contact = ::Google::Protobuf::DescriptorPool.generated_pool.lookup("google.cloud.essentialcontacts.v1.Contact").msgclass
        ListContactsRequest = ::Google::Protobuf::DescriptorPool.generated_pool.lookup("google.cloud.essentialcontacts.v1.ListContactsRequest").msgclass
        ListContactsResponse = ::Google::Protobuf::DescriptorPool.generated_pool.lookup("google.cloud.essentialcontacts.v1.ListContactsResponse").msgclass
        GetContactRequest = ::Google::Protobuf::DescriptorPool.generated_pool.lookup("google.cloud.essentialcontacts.v1.GetContactRequest").msgclass
        DeleteContactRequest = ::Google::Protobuf::DescriptorPool.generated_pool.lookup("google.cloud.essentialcontacts.v1.DeleteContactRequest").msgclass
        CreateContactRequest = ::Google::Protobuf::DescriptorPool.generated_pool.lookup("google.cloud.essentialcontacts.v1.CreateContactRequest").msgclass
        UpdateContactRequest = ::Google::Protobuf::DescriptorPool.generated_pool.lookup("google.cloud.essentialcontacts.v1.UpdateContactRequest").msgclass
        ComputeContactsRequest = ::Google::Protobuf::DescriptorPool.generated_pool.lookup("google.cloud.essentialcontacts.v1.ComputeContactsRequest").msgclass
        ComputeContactsResponse = ::Google::Protobuf::DescriptorPool.generated_pool.lookup("google.cloud.essentialcontacts.v1.ComputeContactsResponse").msgclass
        SendTestMessageRequest = ::Google::Protobuf::DescriptorPool.generated_pool.lookup("google.cloud.essentialcontacts.v1.SendTestMessageRequest").msgclass
      end
    end
  end
end


text:
__source__ = ''
# Time:  O()
# Space: O()
#
# Description:
#http://www.geeksforgeeks.org/find-smallest-range-containing-elements-from-k-lists/
# 1. # You have k lists of sorted integers.
# Find the smallest range that includes at least one number from each of the k lists.
# For example,
# List 1: [4, 10, 15, 24,26]
# List 2: [0, 9, 12, 20] num = 9 index[1] = 1
# List 3: [5, 18, 22, 30]index[2] = 0 num = 5
# output = [20,24]]
# The idea is to use min heap. Below are the steps:
# Create a min heap of size k and insert first elements of all k lists into the heap.
# Maintain two variables min and max to store minimum and maximum values present in the heap at any point.
# Note min will always contain value of the root of the heap.
# Repeat following steps
# Get minimum element from heap (minimum is always at root) and compute the range.
# Replace heap root with next element of the list from which the min element is extracted.
# After replacing the root, heapify the tree.
# Update max if next element is greater. If the list doesn't have any more elements, break the loop.
# #
# Android:
# 电面: running length encoding, android experience, memory leak
# onsite:
# 1.print matrix in spiral order. codepad.io
# 2. 写一个简单的custom view  现场上机。
# 3. 设计一个司机和乘客的mapping 系统,一个m*n的二维数组,有很多司机和乘客(乘客远多于司机),
# int【x,y]代表所处的坐标,任务是给设计算法,保证每个司机都拉到一个乘客,并且所有的pickup话费的路程和最小
# 4.unit test 一个google distance api 的函数。上机
#
# 2)
# boolean allowDriverMode(shifts, current):
# shifts 就是一个的interval,按照顺时间顺序排好的,比如[[0-8], [10-12], [25,33]]
# current就是当前时间。
# 时间不是24小时制的,可以是任意大于0的数字,比如 40或100.
#
# 给一个shifts,给一个当前时间,求司机是否能进入驾驶模式。
# 在最近一次至少8小时休息后(必须是连续的休息时间)。
# 如果司机已经驾驶过12个小时,则不能进入驾驶模式。否则返回可以。
# function to determine whether the driver is allowed to enter driver mode
# * drivers are not allowed to drive a total of 12 hours without an 8 hour break
# the function inputs are:
# - a list of driver shifts as start/end integers, the integer is relative to lyft launch
# - the current time since lyft launch as integer
# def can_drive(history, current_time):
#
#     Returns true if the driver has driven less than 12 hours since their last 8 hour break
#     history: array - Shifts, e.g. [(0, 12), (13, 19)]
#     current_time:int - Current timestamp as hour since Lyft launch, e.g. 50
#     (i)can_drive = True example
#     # 9 hour break, 1 hour shift, 2 hour break, 10 hour shift
#     history = [(9, 10), (12, 22)]
#     current_time = 24
#
#     (ii)can_drive = False example:
#     history = [(0, 4), (5, 9), (10, 14), (15, 19), (20, 24)]
#     current_time = 24
#
#
# 4) print diagonal numbers
# // # Input:
# // # 1 2 3
# // # 4 5 6.
# // # 7 8 9.
#
# // # Print Output:
# // # 3
# // # 2 6
# // # 1 5 9
# // # 4 8
# // # 7
#
# # Phone screening
# 5). reverse integer leetcode #7
# 321 -> 123
# 8765 -> 5678
# bigO and what if negative number
#
# 6)
# Question1: Find second largest element in BST or leetcode 230
# http://www.geeksforgeeks.org/second-largest-element-in-binary-search-tree-bst/
#
# Question2: leetcode 238 Product of Array Except Self
# input:   [1, 2, 3, 4]
# output: [24, 12, 8, 6]
# The product of the all elements in the array except the current one
# (dp 2 array saving the cumulative product from beginning and from end)
#
# Quesion3: Find the most frequent element in a binary search tree
# left child <= root <= right child
# inorder, or use hashmap
#
# 1) Implement iterator for BST
# 2) Reverse words in a string (Leetcode 151)
#

Java = '''
Thought:

'''