text:
package com.chilliworks.chillisource.googleplay.core;

import java.util.HashMap;
import java.util.Set;

import android.app.Notification;
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.content.Context;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.os.Bundle;
import android.support.v4.app.NotificationCompat;

import com.chilliworks.chillisource.core.CSActivity;
import com.chilliworks.chillisource.core.CSApplication;
import com.chilliworks.chillisource.core.ResourceHelper;

//=============================================================
/// Remote Notification Service
///
/// IntentService responsible for handling GCM messages.
//=============================================================
public class GCMService extends GCMBaseIntentService
{
	//---------------------------------------------------------
	/// Constants
	//---------------------------------------------------------
	private static String kstrSenderID = "";
	//---------------------------------------------------------
	/// Set Sender ID
	///
	/// Sets up the sender ID.
	///
	/// @param The Sender ID.
	//---------------------------------------------------------
	public static void SetSenderID(String instrSenderID)
	{
		kstrSenderID = instrSenderID;
	}
	//---------------------------------------------------------
	/// Constructor
	//---------------------------------------------------------
    public GCMService()
    {
        super(kstrSenderID);

        mNativeInterface = new GooglePlayRemoteNotificationNativeInterface();
    }
	//---------------------------------------------------------
	/// On Registered
    ///
    /// This is called when the application has successfully
    /// registered for remote notifications.
    ///
    /// @param The Context.
    /// @param The registration ID.
	//---------------------------------------------------------
    @Override protected void onRegistered(Context context, String registrationId)
    {
    	mNativeInterface.OnRemoteTokenReceived(registrationId);
    }
	//---------------------------------------------------------
	/// On Unregistered
    ///
    /// This is called when the application has successfully
    /// unregistered for remote notifications.
    ///
    /// @param The context.
    /// @param The registraton ID.
	//---------------------------------------------------------
    @Override protected void onUnregistered(Context context, String registrationId)
    {
    }
	//---------------------------------------------------------
	/// On Message
    ///
    /// This is called when a notification is received. This
    /// is processed and passed on to the engine.
    ///
    /// @param The context.
    /// @param The intent.
	//---------------------------------------------------------
    @Override protected void onMessage(Context context, Intent intent)
    {
        HashMap<String, String> params = new HashMap<String, String>();
        Bundle extras = intent.getExtras();
        Set<String> keySet = extras.keySet();
        for (String strKey : keySet)
        {
        	params.put(strKey, extras.getString(strKey));
        }
        generateNotification(context, params);
    }
	//---------------------------------------------------------
	/// On Deleted Message
    ///
    /// @param The context.
    /// @param The total.
	//---------------------------------------------------------
    @Override protected void onDeletedMessages(Context context, int total)
    {
    }
	//---------------------------------------------------------
	/// On Error
    ///
    /// @param The context.
    /// @param The error ID.
	//---------------------------------------------------------
    @Override public void onError(Context context, String errorId)
    {
    }
	//---------------------------------------------------------
	/// On Recoverable Error
    ///
    /// @param The context.
    /// @param The error ID.
	//---------------------------------------------------------
    @Override protected boolean onRecoverableError(Context context, String errorId)
    {
        return super.onRecoverableError(context, errorId);
    }
	//---------------------------------------------------------
	/// Generate Notification
    ///
    /// Issues a notification to inform the user that server
    /// has sent a message.
    ///
    /// @param The Context.
    /// @param The message.
	//---------------------------------------------------------
    private void generateNotification(Context context, HashMap<String, String> inParams)
    {
    	//if the application is active then pass this information on to the application.
        if(CSApplication.get() != null && CSApplication.get().isActive() == true)
        {
        	//build the array of keys and values
    		int dwNumEntries = inParams.size();
    		String[] astrKeys = new String[dwNumEntries];
    		String[] astrValues = new String[dwNumEntries];
    		int dwCount = 0;
    		for(String strKey : inParams.keySet())
            {
    			astrKeys[dwCount] = strKey;
    			astrValues[dwCount] = inParams.get(strKey);
    			dwCount++;
            }

    		// Send this to the native side of the engine.
    		mNativeInterface.OnRemoteNotificationReceived(astrKeys, astrValues);
        }
        // Otherwise display a notification.
        else
        {
        	String strTitle = context.getString(ResourceHelper.GetDynamicResourceIDForField(context, ResourceHelper.RESOURCE_SUBCLASS.RESOURCE_STRING, "app_name"));
        	String strMessage = inParams.get("message");

            Intent notificationIntent = new Intent(context, CSActivity.class);
            notificationIntent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP | Intent.FLAG_ACTIVITY_SINGLE_TOP);
            PendingIntent intent = PendingIntent.getActivity(context, 0, notificationIntent, 0);

			Bitmap largeIconBitmap = null;
			int largeIconID = ResourceHelper.GetDynamicResourceIDForField(context, ResourceHelper.RESOURCE_SUBCLASS.RESOURCE_DRAWABLE, "ic_stat_notify_large");

			//If no large icon then use the small icon
        	if(largeIconID == 0)
        	{
        		largeIconID = ResourceHelper.GetDynamicResourceIDForField(context, ResourceHelper.RESOURCE_SUBCLASS.RESOURCE_DRAWABLE, "ic_stat_notify");
        	}

			if(largeIconID > 0)
			{
				largeIconBitmap = BitmapFactory.decodeResource(context.getResources(), largeIconID);
			}

			Notification notification = new NotificationCompat.Builder(context)
			.setContentTitle(strTitle)
			.setContentText(strMessage)
			.setSmallIcon(ResourceHelper.GetDynamicResourceIDForField(context, ResourceHelper.RESOURCE_SUBCLASS.RESOURCE_DRAWABLE, "ic_stat_notify"))
			.setLargeIcon(largeIconBitmap)
			.setContentIntent(intent)
			.build();

			NotificationManager notificationManager = (NotificationManager)context.getSystemService(Context.NOTIFICATION_SERVICE);
			notificationManager.notify(0, notification);
        }
    }

    // Member vars
    GooglePlayRemoteNotificationNativeInterface mNativeInterface;
}


text:
"""Module for the librarian command line script.

"""

import argparse
import os
import sys
import json
import time

from . import __version__, LibrarianClient, RPCError
from . import base_store
from . import utils

# define some common help strings
_conn_name_help = "Which Librarian to talk to; as in ~/.hl_client.cfg."

def die(fmt, *args):
    """Exit the script with the specifying error string.

    This function will exit the interpreter with code 1 and print the specified
    error message.

    Parameters
    ----------
    fmt : str
        String to be appended to the error message.
    args : str
        If `fmt` contains string substitution, args are unpacked for this purpose.

    Returns
    -------
    None

    """
    if not len(args):
        text = str(fmt)
    else:
        text = fmt % args
    print("error:", text, file=sys.stderr)
    sys.exit(1)

# from https://stackoverflow.com/questions/17330139/python-printing-a-dictionary-as-a-horizontal-table-with-headers
def print_table(dict_list, col_list=None, col_names=None):
    """Pretty print a list of dictionaries as a dynamically sized table.

    Given a list of dictionaries that all contain the same keys, print a
    "pretty" table where each dictionary is a different row in said table. The
    column sizes for each key are dynamically sized based on the length of
    columns and their entries. The user may optionally specify the order of the
    columns, and the column headers that should be used.

    Parameters
    ----------
    dict_list : list of dicts
    col_list : list of str
        These are the names of the dictionary keys to be treated as columns, and
        will be printed in the order given in the list. If not specified, keys are
        printed in alphabetical order.
    col_names : list of str
        Names of column headers. Must be the same size as col_list. If not
        specified, dictionary key names are used.

    Returns
    -------
    None

    Notes
    -----
    Author: Thierry Husson - Use it as you want but don't blame me.

    """
    if col_list is None:
        col_list = sorted(list(dict_list[0].keys()) if dict_list else [])
    if col_names is None:
        myList = [col_list]  # 1st row = header
    else:
        if len(col_names) != len(col_list):
            raise ValueError("Number of column headers specified must match number of columns")
        myList = [col_names]
    for item in dict_list:
        myList.append([str(item[col] or '') for col in col_list])
    # figure out the maximum size for each column
    colSize = [max(list(map(len, col))) for col in zip(*myList)]
    formatStr = ' | '.join(["{{:<{}}}".format(i) for i in colSize])
    myList.insert(1, ['-' * i for i in colSize])  # Seperating line
    for item in myList:
        print(formatStr.format(*item))

    return

# from https://stackoverflow.com/questions/1094841/reusable-library-to-get-human-readable-version-of-file-size
def sizeof_fmt(num, suffix='B'):
    """Format the size of a file in human-readable values.

    Parameters
    ----------
    num : int
        File size in bytes.
    suffix : str
        Suffix to use.

    Returns
    -------
    output : str
        Human readable filesize.

    Notes
    -----
    Follows the Django convention of the web search where base-10 prefixes are used,
    but base-2 counting is done.
    """
    for unit in ['', 'k', 'M', 'G', 'T', 'P', 'E', 'Z']:
        if abs(num) < 1024.0:
            return "{0:3.1f} {1:}{2:}".format(num, unit, suffix)
        num /= 1024.0
    return "{0:.1f} {1:}{2:}".format(num, 'Y', suffix)

# make the base parser
def generate_parser():
    """Make a librarian ArgumentParser.

    The `ap` object returned contains subparsers for all librarian sub-commands.

    Parameters
    ----------
    None

    Returns
    -------
    ap : ArgumentParser
    """
    ap = argparse.ArgumentParser(
        description="librarian is a command for interacting with the hera_librarian"
    )
    ap.add_argument(
        "-V", "--version",
        action="version",
        version="librarian {}".format(__version__),
        help="Show the librarian version and exit."
    )

    # add subparsers
    sub_parsers = ap.add_subparsers(metavar="command", dest="cmd")
    config_add_file_event_subparser(sub_parsers)
    config_add_obs_subparser(sub_parsers)
    config_assign_session_subparser(sub_parsers)
    config_check_connections_subparser(sub_parsers)
    config_delete_files_subparser(sub_parsers)
    config_initiate_offload_subparser(sub_parsers)
    config_offload_helper_subparser(sub_parsers)
    config_launch_copy_subparser(sub_parsers)
    config_locate_file_subparser(sub_parsers)
    config_search_files_subparser(sub_parsers)
    config_set_file_deletion_policy_subparser(sub_parsers)
    config_stage_files_subparser(sub_parsers)
    config_upload_subparser(sub_parsers)

    return ap

def config_add_file_event_subparser(sub_parsers):
    # function documentation
    doc = """Add an "event" record for a File known to the Librarian. These records are
    essentially freeform. The event data are specified as "key=value" items on the
    command line after the event type. The data are parsed as JSON before being
    sent to the Librarian. This makes it possible to use data structures like
    JSON-format lists, dictionaries, and so on. However, when the data item is
    intended to simply be a string, make sure that it comes through the shell as a
    JSON string by writing it like 'foo=\\"bar\\"' (without the single quotes).

    """
    hlp = "Add an event record to a file"

    # add sub parser
    sp = sub_parsers.add_parser("add-file-event", description=doc, help=hlp)
    sp.add_argument("connection_name", metavar="CONNECTION-NAME", type=str,
                    help=_conn_name_help)
    sp.add_argument("file_path", metavar="PATH/TO/FILE", type=str,
                    help="The path to file in librarian.")
    sp.add_argument("event_type", metavar="EVENT-TYPE", type=str,
                    help="The type of event.")
    sp.add_argument("key_vals", metavar="key1=val1...", type=str, nargs="+",
                    help="key-value pairs of events.")
    sp.set_defaults(func=add_file_event)

    return

def config_add_obs_subparser(sub_parsers):
    # function documentation
    doc = """Register a list of files with the librarian.

    """
    hlp = "Register a list of files with the librarian"

    # add sub parser
    sp = sub_parsers.add_parser("add-obs", description=doc, help=hlp)
    sp.add_argument("conn_name", metavar="CONNECTION-NAME", type=str,
                    help=_conn_name_help)
    sp.add_argument("store_name", metavar="NAME",
                    help="The 'store' name under which the Librarian knows this computer.")
    sp.add_argument("paths", metavar="PATHS", nargs="+",
                    help="The paths to the files on this computer.")
    sp.add_argument("--null-obsid", dest="null_obsid", action="store_true",
                    help="Require the new file to have *no* obsid associated (for maintenance files)",
    )
    sp.set_defaults(func=add_obs)

    return

def config_assign_session_subparser(sub_parsers):
    # function documentation
    doc = """Tell the Librarian to assign any recent Observations to grouped "observing
    sessions". You should only do this if no data are currently being taken,
    because otherwise the currently-active session will be incorrectly described.
    The RTP only ingests data from observations that have been assigned to
    sessions, so this command must be run before the RTP will start working on a
    night's data.

    """
    hlp = "Group observations into sessions"

    # add sub parser
    sp = sub_parsers.add_parser("assign-sessions", description=doc, help=hlp)
    sp.add_argument("--min-start-jd", dest="minimum_start_jd", metavar="JD", type=float,
                    help="Only consider observations starting after JD.")
    sp.add_argument("--max-start-jd", dest="maximum_start_jd", metavar="JD", type=float,
                    help="Only consider observations starting before JD.")
    sp.add_argument("conn_name", metavar="CONNECTION-NAME",
                    help=_conn_name_help)
    sp.set_defaults(func=assign_sessions)

    return

def config_check_connections_subparser(sub_parsers):
    doc = """Check whether this machine can connect to all the stores of its Librarian
    peers.

    """
    hlp = "Check connectivity to remote stores"

    sp = sub_parsers.add_parser("check-connections", description=doc, help=hlp)
    sp.set_defaults(func=check_connections)

    return

def config_delete_files_subparser(sub_parsers):
    doc = """Request to delete instances of files matching a given query.

    """
    hlp = "Delete instances of files matching a query"

    # add sub parser
    sp = sub_parsers.add_parser("delete-files", description=doc, help=hlp)
    sp.add_argument("-n", "--noop", dest="noop", action="store_true",
                    help="Enable no-op mode: nothing is actually deleted.")
    sp.add_argument("--store", metavar="STORE-NAME",
                    help="Only delete instances found on the named store.")
    sp.add_argument("conn_name", metavar="CONNECTION-NAME",
                    help=_conn_name_help)
    sp.add_argument("query", metavar="QUERY",
                    help="The JSON-formatted search identifying files to delete.")
    sp.set_defaults(func=delete_files)

    return

def config_initiate_offload_subparser(sub_parsers):
    # function documentation
    doc = """Initiate an "offload": move a bunch of file instances from one store to
    another. This tool is intended for very specialized circumstances: when you
    are trying to clear out a store so that it can be shut down.

    """
    hlp = "Initiate an 'offload' operation"

    # add sub parser
    sp = sub_parsers.add_parser("initiate-offload", description=doc, help=hlp)
    sp.add_argument("conn_name", metavar="CONNECTION-NAME",
                    help=_conn_name_help)
    sp.add_argument("source_name", metavar="SOURCE-NAME",
                    help="The name of the source store.")
    sp.add_argument("dest_name", metavar="DEST-NAME",
                    help="The name of the destination store.")
    sp.set_defaults(func=initiate_offload)

    return

def config_launch_copy_subparser(sub_parsers):
    # function documentation
    doc = """Launch a copy from one Librarian to another. Note that the filename
    argument is treated just as the name of a file known to the source Librarian:
    it does NOT have to be a file that exists on this particular machine. The
    source Librarian will look up an existing instance of the file (on any
    available store) and copy it over.

    """
    hlp = "Launch a copy from one Librarian to another"

    # add sub parser
    sp = sub_parsers.add_parser("launch-copy", description=doc, help=hlp)
    sp.add_argument("--dest", type=str,
                    help="The path in which the file should be stored at the destination. "
                    "Default is the same as used locally.")
    sp.add_argument("--pre-staged", dest="pre_staged", metavar="STORENAME:SUBDIR",
                    help="Specify that the data have already been staged at the destination.")
    sp.add_argument("source_conn_name", metavar="SOURCE-CONNECTION-NAME",
                    help="Which Librarian originates the copy; as in ~/.hl_client.cfg.")
    sp.add_argument("dest_conn_name", metavar="DEST-CONNECTION-NAME",
                    help="Which Librarian receives the copy; as in ~/.hl_client.cfg.")
    sp.add_argument("file_name", metavar="FILE-NAME",
                    help="The name of the file to copy; need not be a local path.")
    sp.set_defaults(func=launch_copy)

    return

def config_locate_file_subparser(sub_parsers):
    # function documentation
    doc = """Ask the Librarian where to find a file. The file location is returned
    as an SCP-ready string of the form "<host>:<full-path-on-host>".

    """
    hlp = "Find the location of a given file"

    # add sub parser
    sp = sub_parsers.add_parser("locate-file", description=doc, help=hlp)
    sp.add_argument("conn_name", metavar="CONNECTION-NAME",
                    help=_conn_name_help)
    sp.add_argument("file_name", metavar="PATH",
                    help="The name of the file to locate.")
    sp.set_defaults(func=locate_file)

    return

def config_offload_helper_subparser(sub_parsers):
    # function documentation
    doc = """The Librarian launches this script on stores to implement the "offload"
    functionality. Regular users should never need to run it.

    """
    # add sub parser
    # purposely don't add help for this function, to prevent users from using it accidentally
    sp = sub_parsers.add_parser("offload-helper", description=doc)
    sp.add_argument("--name", required=True, help="Displayed name of the destination store.")
    sp.add_argument("--pp", required=True, help='"Path prefix" of the destination store.')
    sp.add_argument("--host", required=True, help="Target SSH host of the destination store.")
    sp.add_argument("--destrel", required=True, help="Destination path, relative to the path prefix.")
    sp.add_argument("local_path", metavar="LOCAL-PATH",
                    help="The name of the file to upload on this machine.")
    sp.set_defaults(func=offload_helper)

    return

def config_search_files_subparser(sub_parsers):
    # function documentation
    doc = """Search for files in the librarian.

    """
    example = """For documentation of the JSON search format, see
    https://github.com/HERA-Team/librarian/blob/master/librarian_packages/hera_librarian/docs/Searching.md .
    Wrap your JSON in single quotes to prevent your shell from trying to interpret the
    special characters."""
    hlp = "Search for files matching a query"

    # add sub parser
    sp = sub_parsers.add_parser("search-files", description=doc, epilog=example, help=hlp)
    sp.add_argument("conn_name", metavar="CONNECTION-NAME",
                    help=_conn_name_help)
    sp.add_argument("search", metavar="JSON-SEARCH",
                    help="A JSON search specification; files that match will be displayed.")
    sp.set_defaults(func=search_files)

    return

def config_set_file_deletion_policy_subparser(sub_parsers):
    # function documentation
    doc = """Set the "deletion policy" of one instance of this file.

    """
    hlp = "Set the 'deletion policy' of one instance of the specified file"

    # add sub parser
    sp = sub_parsers.add_parser("set-file-deletion-policy", description=doc, help=hlp)
    sp.add_argument("--store", metavar="STORE-NAME",
                    help="Only alter instances found on the named store.")
    sp.add_argument("conn_name", metavar="CONNECTION-NAME",
                    help=_conn_name_help)
    sp.add_argument("file_name", metavar="FILE-NAME",
                    help="The name of the file to modify.")
    sp.add_argument("deletion", metavar="POLICY",
                    help='The new deletion policy: "allowed" or "disallowed"')
    sp.set_defaults(func=set_file_deletion_policy)

    return

def config_stage_files_subparser(sub_parsers):
    # function documentation
    doc = """Tell the Librarian to stage files onto the local scratch disk. At NRAO,
    this is the Lustre filesystem.

    """
    example = """For documentation of the JSON search format, see
    https://github.com/HERA-Team/librarian/blob/master/librarian_packages/hera_librarian/docs/Searching.md ..
    Wrap your JSON in single quotes to prevent your shell from trying to interpret the
    special characters."""
    hlp = "Stage the files matching a query"

    # add sub parser
    sp = sub_parsers.add_parser("stage-files", description=doc, epilog=example, help=hlp)
    sp.add_argument("-w", "--wait", dest="wait", action="store_true",
                    help="If specified, do not exit until the staging is done.")
    sp.add_argument("conn_name", metavar="CONNECTION-NAME",
                    help=_conn_name_help)
    sp.add_argument("dest_dir", metavar="DEST-PATH",
                    help="What directory to put the staged files in.")
    sp.add_argument("search", metavar="JSON-SEARCH",
                    help="A JSON search specification; files that match will be staged.")
    sp.set_defaults(func=stage_files)

    return

def config_upload_subparser(sub_parsers):
    # function documentation
   doc = """Upload a file to a Librarian. Do NOT use this script if the file that you
   wish to upload is already known to the local Librarian. In that case, use the
   "librarian launch-copy" script -- it will make sure to preserve the
   associated metadata correctly.

   """

   example = """The LOCAL-PATH specifies where to find the source data on this machine, and
   can take any form. The DEST-PATH specifies where the data should be store
   in the Librarian and should look something like "2345678/data.txt". The
   'basename' of DEST-PATH gives the unique filename under which the data
   will be stored. The other pieces (the 'store path'; "2345678" in the
   example) give a subdirectory where the file will be stored on one of the
   Librarian's stores; this location is not meaningful but is helpful for
   grouping related files. Unlike the "cp" command, it is incorrect to give
   the DEST-PATH as just "2345678": that will cause the file to be ingested
   under the name "2345678" with an empty 'store path'.

   """
   hlp = "Upload files to the librarian"

   # add sub parser
   sp = sub_parsers.add_parser("upload", description=doc, epilog=example, help=hlp)
   sp.add_argument(
       "--meta",
       dest="meta",
       default="infer",
       help='How to gather metadata: "json-stdin" or "infer"',
   )
   sp.add_argument(
       "--null-obsid",
       dest="null_obsid",
       action="store_true",
       help="Require the new file to have *no* obsid associated (for maintenance files)",
   )
   sp.add_argument(
       "--deletion",
       dest="deletion",
       default="disallowed",
       help=(
           'Whether the created file instance will be deletable: "allowed" or "disallowed"'
       ),
   )
   sp.add_argument(
       "--pre-staged",
       dest="pre_staged",
       metavar="STORENAME:SUBDIR",
       help="Specify that the data have already been staged at the destination.",
   )
   sp.add_argument(
       "conn_name", metavar="CONNECTION-NAME", help=_conn_name_help,
   )
   sp.add_argument(
       "local_path", metavar="LOCAL-PATH", help="The path to the data on this machine.",
   )
   sp.add_argument(
       "dest_store_path",
       metavar="DEST-PATH",
       help='The destination location: combination of "store path" and file name.',
   )
   sp.add_argument(
       "--use_globus",
       dest="use_globus",
       action="store_true",
       help="Specify that we should try to use globus to transfer data.",
   )
   sp.add_argument(
       "--client_id",
       dest="client_id",
       metavar="CLIENT-ID",
       help="The globus client ID.",
   )
   sp.add_argument(
       "--transfer_token",
       dest="transfer_token",
       metavar="TRANSFER-TOKEN",
       help="The globus transfer token.",
   )
   sp.add_argument(
       "--source_endpoint_id",
       dest="source_endpoint_id",
       metavar="SOURCE-ENDPOINT-ID",
       help="The source endpoint ID for the globus transfer.",
   )
   sp.set_defaults(func=upload)

   return

def add_file_event(args):
    """
    Add a file event to a file in the librarian.
    """
    payload = {}
    for arg in args.key_vals:
        bits = arg.split("=", 1)
        if len(bits) != 2:
            die('argument {} must take the form "key=value"'.format(arg))

        # We parse each "value" as JSON ... and then re-encode it as JSON when
        # talking to the server. So this is mostly about sanity checking.
        key, text_val = bits
        try:
            value = json.loads(text_val)
        except ValueError:
            die("value {} for keyword {} does not parse as JSON".format(text_val, key))

        payload[key] = value

    path = os.path.basename(args.file_path)  # in case user provided a real filesystem path

    # Let's do it
    client = LibrarianClient(args.conn_name)

    try:
        client.create_file_event(path, event_type, **payload)
    except RPCError as e:
        die("event creation failed: {}".format(e))

    return

def add_obs(args):
    """
    Register a list of files with the librarian.
    """
    # Load the info ...
    print("Gathering information ...")
    file_info = {}

    for path in args.paths:
        path = os.path.abspath(path)
        print("  ", path)
        file_info[path] = utils.gather_info_for_path(path)

    # ... and upload what we learned
    print("Registering with Librarian.")
    client = LibrarianClient(args.conn_name)
    try:
        client.register_instances(args.store_name, file_info, null_obsid=args.null_obsid)
    except RPCError as e:
        die("RPC failed: {}".format(e))

    return

def launch_copy(args):
    """
    Launch a copy from one Librarian to another.
    """
    # Argument validation is pretty simple
    known_staging_store = None
    known_staging_subdir = None

    if args.pre_staged is not None:
        known_staging_store, known_staging_subdir = args.pre_staged.split(":", 1)

    # Let's do it
    file_name = os.path.basename(args.file_name)  # in case the user has spelled out a path
    client = LibrarianClient(args.source_conn_name)

    try:
        client.launch_file_copy(file_name, args.dest_conn_name, remote_store_path=args.dest,
                                known_staging_store=known_staging_store,
                                known_staging_subdir=known_staging_subdir)
    except RPCError as e:
        die("launch failed: {}".format(e))

    return

def assign_sessions(args):
    """
    Tell the Librarian to assign any recent Observations to grouped "observing sessions".
    """
    # Let's do it
    client = LibrarianClient(args.conn_name)
    try:
        result = client.assign_observing_sessions(
            minimum_start_jd=args.minimum_start_jd,
            maximum_start_jd=args.maximum_start_jd,
        )
    except RPCError as e:
        die("assignment failed: {}".format(e))

    try:
        n = 0

        for info in result["new_sessions"]:
            if n == 0:
                print("New sessions created:")
            print("  {id:d}: start JD {start_time_jd:f}, stop JD {stop_time_jd:f}, n_obs {n_obs:d}".format(**info))
            n += 1

        if n == 0:
            print("No new sessions created.")
    except Exception as e:
        die("sessions created, but failed to print info: {}".format(e))

    return

def check_connections(args):
    """
    Check this host's ability to connect to the other Librarians that have been configured,
    as well as their stores.

    """
    from . import all_connections

    any_failed = False

    for client in all_connections():
        print('Checking ability to establish HTTP connection to "%s" (%s) ...' % (client.conn_name, client.config['url']))

        try:
            result = client.ping()
            print('   ... OK')
        except Exception as e:
            print('   ... error: %s' % e)
            any_failed = True
            continue

        print('   Querying "%s" for its stores and how to connect to them ...' % client.conn_name)

        for store in client.stores():
            print('   Checking ability to establish SSH connection to remote store "%s" (%s:%s) ...'
                  % (store.name, store.ssh_host, store.path_prefix))

            try:
                result = store.get_space_info()
                print('   ... OK')
            except Exception as e:
                print('   ... error: %s' % e)
                any_failed = True

    if any_failed:
        sys.exit(1)

    print()
    print('Everything worked!')

def delete_files(args):
    """
    Request to delete instances of files matching a given query.
    """
    def str_or_huh(x):
        if x is None:
            return "???"
        return str(x)

    # Let's do it
    client = LibrarianClient(args.conn_name)

    if args.noop:
        print("No-op mode enabled: files will not actually be deleted.")
        print()
        itemtext = "todelete"
        summtext = "would have been deleted"
        mode = "noop"
    else:
        itemtext = "deleted"
        summtext = "were deleted"
        mode = "standard"

    try:
        result = client.delete_file_instances_matching_query(args.query,
                                                             mode=mode,
                                                             restrict_to_store=args.store)
        allstats = result["stats"]
    except RPCError as e:
        die("multi-delete failed: {}".format(e))

    n_files = 0
    n_noinst = 0
    n_deleted = 0
    n_error = 0

    for fname, stats in sorted(iter(allstats.items()), key=lambda t: t[0]):
        nd = stats.get("n_deleted", 0)
        nk = stats.get("n_kept", 0)
        ne = stats.get("n_error", 0)

        if nd + nk + ne == 0:
            # This file had no instances. Don't bother printing it.
            n_noinst += 1
            continue

        n_files += 1
        n_deleted += nd
        n_error += ne
        deltext = str_or_huh(stats.get("n_deleted"))
        kepttext = str_or_huh(stats.get("n_kept"))
        errtext = str_or_huh(stats.get("n_error"))

        print("{0}: {1}={2} kept={3} error={4}".format(fname, itemtext, deltext, kepttext, errtext))

    if n_files:
        print("")
    print("{:d} files were matched, {:d} had instances; {:d} instances {}".format(
        n_files + n_noinst, n_files, n_deleted, summtext))

    if n_error:
        print("WARNING: {:d} error(s) occurred; see server logs for information".format(n_error))
        sys.exit(1)

    return

def initiate_offload(args):
    """
    Initiate an "offload": move a bunch of file instances from one store to another.
    """
    # Let's do it
    client = LibrarianClient(args.conn_name)

    try:
        result = client.initiate_offload(args.source_name, args.dest_name)
    except RPCError as e:
        die("offload failed to launch: {}".format(e))

    if "outcome" not in result:
        die('malformed server response (no "outcome" field): {}'.format(repr(result)))

    if result["outcome"] == "store-shut-down":
        print("The store has no file instances needing offloading. It was placed offline and may now be closed out.")
    elif result["outcome"] == "task-launched":
        print("Task launched, intending to offload {} instances".format(str(result.get("instance-count", "???"))))
        print()
        print("A noop-ified command to delete offloaded instances from the store is:")
        print("  librarian delete-files --noop --store '{}' '{}' '{\"at-least-instances\": 2}'".format(
            args.source_name, args.conn_name))
    else:
        die('malformed server response (unrecognized "outcome" field): {}'.format(repr(result)))

    return

def locate_file(args):
    """
    Ask the Librarian where to find a file.
    """
    # Let's do it
    # In case the user has provided directory components:
    file_name = os.path.basename(args.file_name)
    client = LibrarianClient(args.conn_name)

    try:
        result = client.locate_file_instance(file_name)
    except RPCError as e:
        die("couldn't locate file: {}".format(e))

    print("{store_ssh_host}:{full_path_on_store}".format(**result))

    return

def offload_helper(args):
    """
    Launch this script to implement the "offload" functionality.
    """
    # Due to how the Librarian has to arrange things, it's possible that the
    # instance that we want to copy was deleted before this script got run. If so,
    # so be it -- don't signal an error.
    if not os.path.exists(args.local_path):
        print("source path {} does not exist -- doing nothing".format(args.local_path))
        sys.exit(0)

    # The rare librarian script that does not use the LibrarianClient class!
    try:
        dest = base_store.BaseStore(args.name, args.pp, args.host)
        dest.copy_to_store(args.local_path, args.destrel)
    except Exception as e:
        die(e)

    return

def search_files(args):
    """
    Search for files in the librarian.
    """
    # Let's do it
    client = LibrarianClient(args.conn_name)

    try:
        result = client.search_files(args.search)
    except RPCError as e:
        die("search failed: {}".format(e))

    nresults = len(result["results"])
    if nresults == 0:
        # we didn't get anything
        die("No files matched this search")

    print("Found {:d} matching files".format(nresults))
    # first go through entries to format file size and remove potential null obsids
    for entry in result["results"]:
        entry["size"] = sizeof_fmt(entry["size"])
        if entry["obsid"] is None:
            entry["obsid"] = "None"

    # now print the results as a table
    print_table(result["results"], ["name", "create_time", "obsid", "type", "size"],
                ["Name", "Created", "Observation", "Type", "Size"])

    return

def set_file_deletion_policy(args):
    """
    Set the "deletion policy" of one instance of this file.
    """
    # In case they gave a full path:
    file_name = os.path.basename(args.file_name)

    # Let's do it
    client = LibrarianClient(args.conn_name)
    try:
        result = client.set_one_file_deletion_policy(file_name, args.deletion_policy,
                                                     restrict_to_store=args.store)
    except RPCError as e:
        die("couldn't alter policy: {}".format(e))

    return

def stage_files(args):
    """
    Tell the Librarian to stage files onto the local scratch disk.
    """
    # Let's do it
    client = LibrarianClient(args.conn_name)

    # Get the username. We could make this a command-line option but I think it's
    # better to keep this a semi-secret. Note that the server does absolutely no
    # verification of the values that are passed in.

    import getpass
    user = getpass.getuser()

    # Resolve the destination in case the user provides, say, `.`, where the
    # server is not going to know what that means. This will need elaboration if
    # we add options for the server to come up with a destination automatically or
    # other things like that.
    our_dest = os.path.realpath(args.dest_dir)

    try:
        result = client.launch_local_disk_stage_operation(user, args.search, our_dest)
    except RPCError as e:
        die("couldn't start the stage operation: {}".format(e))

    # This is a bit of future-proofing; we might teach the Librarian to choose a
    # "reasonable" output directory on your behalf.
    dest = result["destination"]

    print("Launched operation to stage {:d} instances ({:d} bytes) to {}".format(
        result["n_instances"], result["n_bytes"], dest))

    if not args.wait:
        print("Operation is complete when {}/STAGING-IN-PROGRESS is removed.".format(dest))
    else:
        # The API call should not return until the progress-marker file is
        # created, so if we don't see that it exists, it should be the case that
        # the staging started and finished before we could check.
        if not os.path.isdir(dest):
            die("cannot wait for staging to complete: destination directory {} not "
                "visible on this machine. Missing network filesystem?".format(dest))

        marker_path = os.path.join(dest, "STAGING-IN-PROGRESS")
        t0 = time.time()
        print("Started waiting for staging to finish at:", time.asctime(time.localtime(t0)))

        while os.path.exists(marker_path):
            time.sleep(3)

        if os.path.exists(os.path.join(dest, "STAGING-SUCCEEDED")):
            print("Staging completed successfully ({:0.1f}s elapsed).".format(time.time() - t0))
            sys.exit(0)

        try:
            with open(os.path.join(dest, "STAGING-ERRORS"), "rt") as f:
                print("Staging completed WITH ERRORS ({:0.1f}s elapsed).".format(time.time() - t0),
                      file=sys.stderr)
                print("", file=sys.stderr)
                for line in f:
                    print(line.rstrip(), file=sys.stderr)
            sys.exit(1)
        except IOError as e:
            if e.errno == 2:
                die("staging finished but neiher \"success\" nor \"error\" indicator was "
                    "created (no file {})".format(dest, "STAGING-ERRORS"))
            raise

    return

def upload(args):
    """
    Upload a file to a Librarian.
    """
    # Argument validation is pretty simple
    if os.path.isabs(args.dest_store_path):
        die("destination path must be relative to store top; got {}".format(args.dest_store_path))

    if args.null_obsid and args.meta != "infer":
        die('illegal to specify --null-obsid when --meta is not "infer"')

    if args.meta == "json-stdin":
        try:
            rec_info = json.load(sys.stdin)
        except Exception as e:
            die("cannot parse stdin as JSON data: {}".format(e))
        meta_mode = "direct"
    elif args.meta == "infer":
        rec_info = {}
        meta_mode = "infer"
    else:
        die("unexpected metadata-gathering method {}".format(args.meta))

    known_staging_store = None
    known_staging_subdir = None

    if args.pre_staged is not None:
        known_staging_store, known_staging_subdir = args.pre_staged.split(":", 1)

    # Let's do it
    client = LibrarianClient(args.conn_name)

    try:
        client.upload_file(
            args.local_path,
            args.dest_store_path,
            meta_mode,
            rec_info,
            deletion_policy=args.deletion,
            known_staging_store=known_staging_store,
            known_staging_subdir=known_staging_subdir,
            null_obsid=args.null_obsid,
            use_globus=args.use_globus,
            client_id=args.client_id,
            transfer_token=args.transfer_token,
            source_endpoint_id=args.source_endpoint_id,
        )
    except RPCError as e:
        die("upload failed: {}".format(e))

    return

def main():
    # make a parser and run the specified command
    parser = generate_parser()
    parsed_args = parser.parse_args()
    parsed_args.func(parsed_args)

    return

if __name__ == "__main__":
    sys.exit(main())

redpajama_set_name: RedPajamaGithub


text:
import React, {Component, PropTypes} from 'react';
import getMuiTheme from 'material-ui/styles/getMuiTheme';
import IconButton from 'material-ui/IconButton';
import IconReplay from 'material-ui/svg-icons/av/replay';
import {grey600 as grey} from 'material-ui/styles/colors';
import merge from 'lodash.merge';
import classPrefix from '../utils/classPrefix.js';

const defaultStyles = {
  fill: grey
};

class Reset extends Component {
  getChildContext() {
    /**
     * If muiTheme is defined somewhere in parents components merge it,
     * otherwise use only the default.
     */
    return {muiTheme: getMuiTheme(this.context.muiTheme)};
  }

  shouldComponentUpdate() {
    return false;
  }

  render() {
    const {resetCounter, className, style, ...other} = this.props;
    const s = merge(defaultStyles, style);

    return (
      <IconButton
        {...other}
        iconStyle={s}
        className={className}
        onClick={resetCounter}
        tooltip="Reset"
        tooltipPosition="top-center">
        <IconReplay/>
      </IconButton>
   );
  }
}

Reset.propTypes = {
  style: PropTypes.object,
  className: PropTypes.string,
  resetCounter: PropTypes.func,
  theme: PropTypes.object
};

Reset.defaultProps = {
  className: `${classPrefix}__reset`
};

Reset.contextTypes = {
  muiTheme: PropTypes.object
};

Reset.childContextTypes = {
  muiTheme: PropTypes.object.isRequired
};

export default Reset;


text:
package gameState;

import battle.Battle;
import battle.BattlePanel;
import battle.Board;
import battle.Cell;
import utils.BattlePanelButton;

import javax.swing.*;
import java.awt.event.ActionListener;
import java.util.ArrayList;
import java.util.List;

/**
 * Created by Nathan on 11/25/2015.
 */
public abstract class GameState implements ActionListener {
    static final String backStringName = "Back";

    protected Battle battle;
    protected Board board;
    protected BattlePanel battlePanel;

    public GameState(Battle battle, Board board, BattlePanel battlePanel) {
        this.battle = battle;
        this.board = board;
        this.battlePanel = battlePanel;
        onInit();
    }

    protected abstract void onInit();

    public abstract void onBoardClicked(Cell cell);

    protected JButton getBackButton() {
        JButton backButton = new BattlePanelButton(backStringName);
        backButton.addActionListener(this);
        return backButton;
    }
}


text:
(function() {
  'use strict';

  angular
    .module('app.login')
    .config(loginRouter);

  function loginRouter($routeProvider) {
    $routeProvider.
      when('/login', {
        templateUrl: 'routes/login/login.tpl',
        controller: 'LoginCtrl as vm',
        title: 'Sign Up/In',
        name: 'login',
        access: {
          restricted: false,
          isLogin: true
        }
      });
  }

})();


text:
package client

import (
	"net/http"

	"github.com/prometheus/common/model"
	"github.com/prometheus/prometheus/prompb"
)

// Client define a remote storage.
type Client interface {
	Name() string
	String() string
	Shutdown()
}

// Writer is a client that sends a batch of samples to remote.
type Writer interface {
	Write(samples model.Samples, r *http.Request, dryRun bool) ([]byte, error)
	Client
}

// Reader is a client that read samples from remote.
type Reader interface {
	Read(req *prompb.ReadRequest, r *http.Request) (*prompb.ReadResponse, error)
	Client
}


text:
<?php
/**
 * @package \axy\cli\bin
 * @author Oleg Grigoriev <go.vasac@gmail.com>
 */

namespace axy\cli\bin\io;

/**
 * Base implementation of IProcess
 */
abstract class Base implements IProcess
{
    /**
     * {@inheritdoc}
     */
    public function setStatus($status)
    {
        $this->status = $status;
    }

    /**
     * {@inheritdoc}
     */
    public function getStatus()
    {
        return $this->status;
    }

    /**
     * {@inheritdoc}
     */
    public function silentReadLine($nl = true)
    {
        $line = $this->readLine();
        $this->write(PHP_EOL, false);
        return $line;
    }

    /**
     * {@inheritdoc}
     */
    public function write($message, $nl = true)
    {
        $this->outOut($message.($nl ? PHP_EOL : ''));
    }

    /**
     * {@inheritdoc}
     */
    public function error($message, $status = null, $nl = true)
    {
        if ($status !== null) {
            $this->setStatus($status);
        }
        $this->outErr($message.($nl ? PHP_EOL : $nl));
    }

    /**
     * Writes a normal content
     *
     * @param string $content
     */
    abstract protected function outOut($content);

    /**
     * Writes an error content
     *
     * @param string $content
     */
    protected function outErr($content)
    {
        $this->outOut($content);
    }

    /**
     * @var int
     */
    protected $status = 0;
}


text:
import {
  GET_RECEIVED_INVOICES,
  GET_RECEIVED_INVOICES_SUCCESS,
} from './constants';
import { fromJS } from 'immutable';

const initialState = fromJS({
  loading: false,
  error: '',
  pageKey: '',
  invoices: fromJS([]),
});

function receivedInvoicesPageReducer(state = initialState, action) {
  switch (action.type) {
    case GET_RECEIVED_INVOICES: {
      return state
        .set('loading', true);
    }
    case GET_RECEIVED_INVOICES_SUCCESS: {
      action.invoices.sort((a, b) => b.Timestamp - a.Timestamp);
      return state
        .set('invoices', fromJS(action.invoices))
        .set('pageKey', action.pageKey)
        .set('loading', false);
    }
    default:
      return state;
  }
}

export default receivedInvoicesPageReducer;


text:
<?php

namespace Datatheke\Bundle\PagerBundle\DataGrid\Column\Guesser;

use Datatheke\Bundle\PagerBundle\DataGrid\Column\Guesser\Exception\UnableToGuessException;
use Datatheke\Bundle\PagerBundle\DataGrid\Column\StringColumn;
use Datatheke\Bundle\PagerBundle\Pager\Field;

class StringGuesser implements GuesserInterface
{
    public function guess(Field $field, $fieldAlias)
    {
        if (Field::TYPE_STRING === $field->getType()) {
            return new StringColumn($field);
        }

        throw new UnableToGuessException($field, $fieldAlias, __CLASS__);
    }
}


text:
package main

import "time"

import l4g "github.com/Innovatube/log4go"

const (
	filename = "flw.log"
)

func main() {
	// Get a new logger instance
	log.Close()
	// Create a default logger that is logging messages of FINE or higher

	/* Can also specify manually via the following: (these are the defaults) */
	flw := log.NewFileLogWriter(filename, false)
	flw.SetFormat("[%D %T] [%L] (%S) %M")
	flw.SetRotate(false)
	flw.SetRotateSize(0)
	flw.SetRotateLines(0)
	flw.SetRotateDaily(false)
	log.AddFilter("file", log.DEBUG, flw)
	// Log some experimental messages
	log.Finest("Everything is created now (notice that I will not be printing to the file)")
	log.Info("The time is now: %s", time.Now().Format("15:04:05 MST 2006/01/02"))
	log.Critical("Time to close out!")
	log.Close()
}


text:
package com.microsoft.office365.microsoftgraphvos;

public class EmailAddressVO {

    public String address;
    public String name;
}


text:
package com.davidbracewell.apollo.ml.sequence;

import com.davidbracewell.apollo.linear.NDArray;
import com.davidbracewell.apollo.linear.NDArrayFactory;
import com.davidbracewell.apollo.ml.Feature;
import com.davidbracewell.apollo.ml.classification.Classifier;
import lombok.NonNull;

import java.util.Iterator;

/**
 *
Greedy sequence labeler that wraps a standard {@link Classifier} and optimizing for local instead of global
 * structure.

 *
 * @author David B. Bracewell
 */
public class WindowedLabeler extends SequenceLabeler {
   private static final long serialVersionUID = 1L;
   /**
    * The Classifier.
    */
   Classifier classifier;

   /**
    * Instantiates a new Model.
    *
    * @param learner the learner
    */
   public WindowedLabeler(@NonNull WindowedLearner learner) {
      super(learner);
      super.setDecoder(new WindowDecoder());
   }

   @Override
   public double[] estimate(Iterator<Feature> observation, Iterator<String> transitions) {
      NDArray vector = NDArrayFactory.SPARSE_DOUBLE.zeros(numberOfFeatures());
      observation.forEachRemaining(f -> {
         int index = (int) encodeFeature(f.getFeatureName());
         if (index >= 0) {
            vector.set(index, f.getValue());
         }
      });
      transitions.forEachRemaining(t -> {
         int index = (int) encodeFeature(t);
         if (index >= 0) {
            vector.set(index, 1.0d);
         }
      });
      return classifier.classify(vector).distribution();
   }

   @Override
   public void setDecoder(@NonNull Decoder decoder) {
      throw new UnsupportedOperationException();
   }

}// END OF WindowedLabeler


text:
import * as React from 'react';
import { IconBaseProps } from 'react-icon-base';
declare class TiUpload extends React.Component<IconBaseProps> { }
export = TiUpload;


text:
namespace ui {

// Returns a Unicode character corresponding to the given |keysym|.  If the
// |keysym| doesn't represent a printable character, returns zero.  We don't
// support characters outside the Basic Plane, and this function returns zero
// in that case.
KEYCODES_X_EXPORT uint16_t GetUnicodeCharacterFromXKeySym(unsigned long keysym);

}  // namespace ui

#endif  // UI_EVENTS_KEYCODES_KEYSYM_TO_UNICODE_H_


text:
require File.dirname(__FILE__) + '/../../orawls_core'

require 'yaml'

module Puppet
  Type.newtype(:wls_setting) do
    include EasyType

    DEFAULT_FILE = '/etc/wls_setting.yaml'

    desc 'This resource allows you to set the defaults for all other wls types'

    to_get_raw_resources do
      resources_from_yaml
    end

    parameter :name
    property :user
    property :weblogic_home_dir
    property :weblogic_user
    property :connect_url
    property :weblogic_password
    property :post_classpath
    property :debug_module
    property :archive_path

    property :custom_trust
    property :trust_keystore_file
    property :trust_keystore_passphrase

    property :use_default_value_when_empty

    def self.configuration
      @configuration
    end

    private

    def self.resources_from_yaml
      Puppet.debug '0 read_from_yaml '
      @configuration = read_from_yaml
      normalize(@configuration)
    end

    def self.config_file
      Pathname.new(DEFAULT_FILE).expand_path
    end

    def self.read_from_yaml
      if File.exist?(config_file)
        open(config_file) { |f| YAML.load(f) }
      else
        {}
      end
    end

    private

    def self.normalize(content)
      normalized_content = []
      content.each do | key, value|
        value[:name] = key
        normalized_content << with_hashified_keys(value)
      end
      normalized_content
    end

    def self.with_hashified_keys(hash)
      result = {}
      hash.each do |key, value|
        result[key.to_sym] = value
      end
      result
    end

  end
end


text:
var person_template = Graph.Component.extend({
  name: 'dude_gen',
  render: function(obj){
    var _$output = $('
');
    for (var i in obj.entity()){
      switch(i){
        case 'image':
            _$output.prepend('');
            break;
        default:
            _$output.append(i+': ' + obj[i] + '
');
      }
    }
    return _$output;
  },
  events: {
    onchange: function(changes){
      for (var i = 0, len = changes.length; i < len; i++)
        $('span#graph_component_dude_gen_' + changes[i].property).text(changes[i].newValue);
    }
  }
});


text:
//
// Copyright (c) Microsoft. All rights reserved.
// Licensed under the MIT license.
//
// Microsoft Cognitive Services (formerly Project Oxford): https://www.microsoft.com/cognitive-services
//
// Microsoft Cognitive Services (formerly Project Oxford) GitHub:
// https://github.com/Microsoft/ProjectOxford-ClientSDK
//
// Copyright (c) Microsoft Corporation
// All rights reserved.
//
// MIT License:
// 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.
//

using System;
using System.Collections.Generic;
using System.Linq;
using System.Runtime.Serialization;
using Microsoft.ProjectOxford.Common;

namespace Microsoft.ProjectOxford.EntityLinking.Contract
{
    /// <summary>
    /// Container of response.
    /// </summary>
    [DataContract]
    internal class EntityLinkResponse
    {
        /// <summary>
        /// Gets or sets EntityLinks.
        /// </summary>
        [DataMember(EmitDefaultValue = false, Name = "entities")]
        public EntityLink[] EntityLinks { get; set; }
    }

    /// <summary>
    /// Represents name of the entity, wikipedia id, matches and score.
    /// </summary>
    [DataContract]
    public class EntityLink
    {
        /// <summary>
        /// Name of the entity.
        /// </summary>
        [DataMember(Name = "name")]
        public string Name { get; set; }

        /// <summary>
        /// Id of the wikipedia linked entity.
        /// </summary>
        [DataMember(Name = "wikipediaId")]
        public string WikipediaID { get; set; }

        /// <summary>
        /// Matches text of the entity within the given paragraph.
        /// </summary>
        [DataMember(Name = "matches")]
        public IList<Match> Matches { get; set; }

        /// <summary>
        /// Confidence score of the linking.
        /// </summary>
        [DataMember(Name = "score")]
        public double Score { get; set; }
    }

    /// <summary>
    /// The match text of the knowledge base linked entity.
    /// </summary>
    [DataContract]
    public class Match
    {
        /// <summary>
        /// The matched text.
        /// </summary>
        [DataMember(Name = "text")]
        public string Text { get; set; }

        /// <summary>
        /// Matched entries within the given paragraph.
        /// </summary>
        [DataMember(Name = "entries")]
        public IList<Entry> Entries { get; set; }
    }

    /// <summary>
    /// Represents the entry offset and score.
    /// </summary>
    [DataContract]
    public class Entry
    {
        /// <summary>
        /// Offset of the entry.
        /// </summary>
        [DataMember(Name = "offset")]
        public int Offset { get; set; }

        /// <summary>
        /// The score of the entry.
        /// </summary>
        [DataMember(Name = "score")]
        public double Score { get; set; }
    }

}


text:
/*!
 * V4Fire Client Core
 * https://github.com/V4Fire/Client
 *
 * Released under the MIT license
 * https://github.com/V4Fire/Client/blob/master/LICENSE
 */

import type { WebServerConfig } from '@playwright/test';
import { build } from '@config/config';

const webServerConfig: WebServerConfig = {
	port: build.testPort,
	reuseExistingServer: true,
	command: 'npm run test:server',
	cwd: process.cwd()
};

export default webServerConfig;


text:
/* This software is released under the MIT License, see LICENSE */

module.exports = function () {

	var clayConfig = this;

	function setupToggle(switchName, switchTarget) {
		var toggle = clayConfig.getItemByMessageKey(switchName);
		var handler = function () {
			clayConfig.getItemByMessageKey(switchTarget)[this.get() ? 'show' : 'hide']();
		};
		toggle.on('change', handler);
		handler.call(toggle);
	}

	clayConfig.on(clayConfig.EVENTS.AFTER_BUILD, function() {
		setupToggle('ShowStatusPanel', 'PowerReserveColor');
	});

};


text:
package ml.combust.bundle

import java.io.{Closeable, File}
import java.net.URI
import java.nio.file.{FileSystem, FileSystems, Files, Path}
import java.util.stream.Collectors

import ml.combust.bundle.dsl.{Bundle, BundleInfo}
import ml.combust.bundle.fs.BundleFileSystem
import ml.combust.bundle.serializer.BundleSerializer
import ml.combust.bundle.json.JsonSupport._
import spray.json._
import resource._

import scala.collection.JavaConverters._
import scala.language.implicitConversions
import scala.util.Try

/**
  * Created by hollinwilkins on 12/24/16.
  */
object BundleFile {
  def load[Context <: HasBundleRegistry](uri: String)
                                        (implicit context: Context): BundleFile = {
    load(new URI(uri))
  }

  def load[Context <: HasBundleRegistry](uri: URI)
                                        (implicit context: Context): BundleFile = {
      uri.getScheme match {
        case "file" => apply(uri)
        case "jar" => apply(uri)
        case _ =>
          // look in the bundle registry for a file system
          apply(context.bundleRegistry.fileSystemForUri(uri).load(uri).get)
      }
  }

  implicit def apply(uri: String): BundleFile = {
    apply(new URI(unbackslash(uri)))
  }

  implicit def apply(file: File): BundleFile = {
    val uri: String = if (file.getPath.endsWith(".zip")) {
      s"jar:${file.toURI.toString}"
    } else {
      file.toURI.toString
    }

    apply(uri)
  }

  implicit def apply(uri: URI): BundleFile = {
    val env = Map("create" -> "true").asJava
    val uriSafe = new URI(unbackslash(uri.toString))

    uriSafe.getScheme match {
      case "file" =>
        apply(FileSystems.getDefault, FileSystems.getDefault.getPath(uriSafe.getPath))
      case "jar" =>
        // handle resource in JAR path
        val (filesystemUri: URI, path: String) = if (uriSafe.toString.contains("!")) {
          val uriParts: Array[String] = uriSafe.toString.split("!")
          (new URI(uriParts(0)), uriParts(1))
        }
        else {
          (uriSafe, "/")
        }

        val zfs = FileSystems.newFileSystem(filesystemUri, env)
        apply(zfs, zfs.getPath(path))
    }
  }

  def apply[Context <: HasBundleRegistry](fs: BundleFileSystem, uri: URI): BundleFile = {
    // Copy contents from the bundle file system to the local file system
    apply(fs.load(uri).get)
  }

  /** Replace all backslashes with forward slashes, to handle Windows file paths in URI construction
    *
    * @param uri String representing a URI
    * @return String containing no backslashes.
    */
  private def unbackslash(uri: String): String = {
    uri.replace('\\', '/')
  }
}

case class BundleFile(fs: FileSystem,
                      path: Path) extends Closeable {
  /** Read bundle definition from the path.
    *
    * @return bundle definition
    */
  def readInfo(): Try[BundleInfo] = {
    val bundleJson = fs.getPath(path.toString, Bundle.bundleJson)
    Try(new String(Files.readAllBytes(bundleJson), "UTF-8").parseJson.convertTo[ml.bundle.Bundle]).
      map(BundleInfo.fromBundle)
  }

  def writeNote(name: String, note: String): Try[String] = {
    Files.createDirectories(fs.getPath(path.toString, "notes"))
    (for(out <- managed(Files.newOutputStream(fs.getPath(path.toString, "notes", name)))) yield {
      out.write(note.getBytes)
      note
    }).tried
  }

  def readNote(name: String): String = {
    new String(Files.readAllBytes(fs.getPath(path.toString, "notes", name)))
  }

  def listNotes(): Set[String] = {
    Files.list(fs.getPath(path.toString, "notes")).
      collect(Collectors.toList()).asScala.
      map(_.getFileName.toString).
      toSet
  }

  def load[Context <: HasBundleRegistry, Transformer <: AnyRef]()
                                                               (implicit context: Context): Try[Bundle[Transformer]] = {
    BundleSerializer(context, this).read[Transformer]()
  }

  override def finalize(): Unit = {
    super.finalize()
    close()
  }

  override def close(): Unit = {
    // closing some file systems, like Unix, raises an
    // unsupported operation error
    Try(fs.close())
  }
}


text:
<?xml version="1.0" encoding="utf-8"?>
<manifest package="com.adrian.hackmyphone"
          xmlns:android="http://schemas.android.com/apk/res/android">

    <uses-permission android:name="android.permission.ACCESS_FINE_LOCATION"/>
    <uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION"/>
    <uses-permission android:name="android.permission.ACCESS_WIFI_STATE"/>
    <uses-permission android:name="android.permission.BLUETOOTH"/>
    <uses-permission android:name="android.permission.BLUETOOTH_ADMIN"/>
    <uses-permission android:name="android.permission.CHANGE_WIFI_STATE"/>
    <uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/>
    <uses-permission android:name="android.permission.INTERNET"/>
    <uses-permission android:name="android.permission.ACCESS_NETWORK_STATE"/>
    <uses-permission android:name="android.permission.READ_PHONE_STATE"/>
    <uses-permission android:name="android.permission.READ_CONTACTS"/>
    <uses-permission android:name="android.permission.READ_SMS"/>

    <uses-feature
        android:glEsVersion="0x00020000"
        android:required="true"/>

    <application
        android:allowBackup="true"
        android:icon="@mipmap/ic_launcher"
        android:label="@string/app_name"
        android:supportsRtl="true"
        android:theme="@style/AppTheme">
        <meta-data
            android:name="com.google.android.gms.version"
            android:value="@integer/google_play_services_version"/>
        <meta-data
            android:name="com.google.android.geo.API_KEY"
            android:value="AIzaSyCsWwmaWEj913httkR6Doonwfi9v069zTE"/>

        <activity android:name=".MainActivity">
            <intent-filter>
                <action android:name="android.intent.action.MAIN"/>

                <category android:name="android.intent.category.LAUNCHER"/>
            </intent-filter>
        </activity>
        <activity android:name=".GpsActivity"/>
        <activity android:name=".CompassActivity">
        </activity>
        <activity android:name=".AccelerometerActivity">
        </activity>
    </application>

</manifest>


text:
import { Emitter } from 'vs/base/common/event';
import { IExtensionDescription } from 'vs/platform/extensions/common/extensions';
import { ExtHostNotebookRenderersShape, IMainContext, MainContext, MainThreadNotebookRenderersShape } from 'vs/workbench/api/common/extHost.protocol';
import { ExtHostNotebookController } from 'vs/workbench/api/common/extHostNotebook';
import { ExtHostNotebookEditor } from 'vs/workbench/api/common/extHostNotebookEditor';
import * as vscode from 'vscode';

export class ExtHostNotebookRenderers implements ExtHostNotebookRenderersShape {
	private readonly _rendererMessageEmitters = new Map<string /* rendererId */, Emitter<{ editor: vscode.NotebookEditor; message: any }>>();
	private readonly proxy: MainThreadNotebookRenderersShape;

	constructor(mainContext: IMainContext, private readonly _extHostNotebook: ExtHostNotebookController) {
		this.proxy = mainContext.getProxy(MainContext.MainThreadNotebookRenderers);
	}

	public $postRendererMessage(editorId: string, rendererId: string, message: unknown): void {
		const editor = this._extHostNotebook.getEditorById(editorId);
		this._rendererMessageEmitters.get(rendererId)?.fire({ editor: editor.apiEditor, message });
	}

	public createRendererMessaging(manifest: IExtensionDescription, rendererId: string): vscode.NotebookRendererMessaging {
		if (!manifest.contributes?.notebookRenderer?.some(r => r.id === rendererId)) {
			throw new Error(`Extensions may only call createRendererMessaging() for renderers they contribute (got ${rendererId})`);
		}

		const messaging: vscode.NotebookRendererMessaging = {
			onDidReceiveMessage: (listener, thisArg, disposables) => {
				return this.getOrCreateEmitterFor(rendererId).event(listener, thisArg, disposables);
			},
			postMessage: (message, editorOrAlias) => {
				if (ExtHostNotebookEditor.apiEditorsToExtHost.has(message)) { // back compat for swapped args
					[message, editorOrAlias] = [editorOrAlias, message];
				}

				const extHostEditor = editorOrAlias && ExtHostNotebookEditor.apiEditorsToExtHost.get(editorOrAlias);
				return this.proxy.$postMessage(extHostEditor?.id, rendererId, message);
			},
		};

		return messaging;
	}

	private getOrCreateEmitterFor(rendererId: string) {
		let emitter = this._rendererMessageEmitters.get(rendererId);
		if (emitter) {
			return emitter;
		}

		emitter = new Emitter({
			onDidRemoveLastListener: () => {
				emitter?.dispose();
				this._rendererMessageEmitters.delete(rendererId);
			}
		});

		this._rendererMessageEmitters.set(rendererId, emitter);

		return emitter;
	}
}


text:
using namespace std;

//////////////////////////////////////////////////////////////////////
// Construction/Destruction
//////////////////////////////////////////////////////////////////////

MessageBroadcaster::~MessageBroadcaster()
{

}

void MessageBroadcaster::SetTime(float time)
{
	this->time+= time;
}

void MessageBroadcaster::Render()
{
	while(message_queue.size() > 5)
		message_queue.pop_front();

	if(time > 4)
	{
		message_queue.pop_front();
		time = 0;
	}

	graphics_engine->Position(10,10);
	int dy = 10;

	for(list<BroadcastMessage*>::iterator i = message_queue.begin(); i != message_queue.end(); i++)
	{
		(*graphics_engine) << (*i)->GetMessage();

		if((*i)->IsImage())
		{
			(*i)->GetImage()->Render();

		}

		graphics_engine->Position(10,dy+=12);
	}

}


text:
/**
 *
 */
package com.wmci.util;

import java.sql.Timestamp;
import java.text.SimpleDateFormat;
import java.util.Date;

/**
 * Java back-end to support Utility JavaServices on WebMethods Integration Server
 *
 * @author cecheverria
 *
 */
public class Util {

	/**
	 *
	 */
	public Util() {
	}

	/**
	 * A clone from SQL Nvl function.
	 *
	 * @param input				The input parameter
	 * @param defaultValue		The value to be returned in case that input parameter is considered null
	 * @param treatEmptyAsNull	Set as true if you want to treat the Empty values as a null values.
	 * @return
	 */
	public static String nvl(String input, String defaultValue, boolean treatEmptyAsNull) {

		return	input == null ?
				defaultValue :
				treatEmptyAsNull && input.trim().equals("") ?
				defaultValue :
				input
				;
	}

	/**
	 * A clone from SQL Decode function.
	 *
	 * @param input				The input parameter
	 * @param conditions		The key-pair conditions to be evaluated
	 * @param defaultValue		The value to be returned in case that input parameter does not match any key-pair condition
	 * @return
	 */
	public static String decode(String input, String[] conditions, String defaultValue) {

		String match = null;
		int totalComparations = conditions.length/2,
			i = 0;

		while (match == null && i < totalComparations) {
			String value = conditions[i*2+0];
			String returnValue = conditions[i*2+1];

			if(input != null) {
				//System.out.printf("value[%s] - compare[%s] - [%s]\n", value, returnValue, (input.equals(value)));
				match = input.equals(value) ? returnValue : null;
			}
			else
				//Compare when input is send as null
				match = null == value ? returnValue : null;

			i++;
		}

		return	match != null ?
				match :
				defaultValue //If there is not match on compared values, then return default value
				;
	}

	/**
	 * Evaluates if input parameter can be returned as it, otherwise it will be returned as null.
	 *
	 * This back-end will easy the work doing mappings on Integration Server, when you want to
	 * map an object only if exist and contains a value different than empty. In that way you will
	 * be able to avoid doing branches to ask for an object and then mapping if it exists.
	 *
	 * @param input		The input parameter
	 * @return
	 */
	public static String doNotMapNullOrBlanks(String input) {

		return input != null && !input.trim().equals("") ? input.trim() : null;
	}

	/**
	 * Builds an string array to hold pair conditions like you does on SQL Decode function.
	 *
	 * @param input		The input parameter
	 * @return
	 */
	public static String[] buildPairConditionsArray(String input) {

		String[] array = {},
				 tmp = input == null || input.trim().equals("") ?
					   new String[]{} :
					   input.split(",")
				;
		array = new String[tmp.length];

		for (int i = 0; i < tmp.length; i++) {
			String item = tmp[i];
			array[i] = item.equals("{null}") ? null : item;
		}

		return  array;
	}

	/**
	 * Get current time stamp casted to String
	 * @return
	 */
	public static String getTimeStamp() {
		return (new Timestamp(System.currentTimeMillis())).toString();
	}
}


text:
function clickTrigger(thisfield, defaulttext) {
if (thisfield.value == defaulttext) {
thisfield.value = "";
}
}

function blurTrigger(thisfield, defaulttext) {
if (thisfield.value == "") {
thisfield.value = defaulttext;
}
}


text:
import os
import subprocess
import sys

HERE = os.path.abspath(__file__)

frag = os.path.splitext(sys.argv[1])[0] + ".frag"
print(frag)

cmd = os.path.join(os.path.dirname(HERE), "fake_compiler") + " " + frag

p = subprocess.run(
    cmd,
    shell=True,
    stdout=subprocess.PIPE,
    stderr=subprocess.PIPE,
    universal_newlines=True,
)

if p.returncode != 0:
    # Interesting: the compiler failed.
    exit(0)

# Boring: the compiler succeeded.
exit(1)


text:
import EventEmitter from 'eventemitter3';

/**
 * Wrapping the WebWorker in an event emitter
 * (Because removeAllListeners() is quite a nice feature...)
 */
export default class WorkerWrapper extends EventEmitter {
  constructor(url) {
    super();

    const worker = new Worker(url);
    this.worker = worker;

    worker.addEventListener('message', this.emit.bind(this, 'message'));
    worker.addEventListener('error', this.emit.bind(this, 'error'));
  }

  postMessage(...args) {
    this.worker.postMessage.apply(this.worker, args);
  }

  terminate() {
    return this.worker.terminate();
  }
}


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

namespace CallingOriginal
{
    public class Route
    {
        public Route(int identifier)
        {
            Identifier = identifier;
            TotalDistance = int.MaxValue;
            Roads = Enumerable.Empty<FarmRoad>();
        }

        public int Identifier { get; private set; }
        public int TotalDistance { get; internal set; }
        public IEnumerable<FarmRoad> Roads { get; internal set; }

        public override string ToString()
        {
            var sb = new StringBuilder();
            sb.AppendLine(string.Format("Route: {0}, Total Distance: {1}", Identifier.ToString("D3"), TotalDistance));
            foreach (var road in Roads)
                sb.AppendLine(string.Format("    {0}", road));
            return sb.ToString();
        }
    }
}


text:
package org.locationtech.geowave.core.cli.exceptions;

public class TargetNotFoundException extends Exception {

  /**
   *
   */
  private static final long serialVersionUID = 1L;

  public TargetNotFoundException() {
    super();
  }

  public TargetNotFoundException(final String message) {
    super(message);
  }
}


text:
<?php
/*

+
| Field    | Type         | Null | Key | Default | Extra          |
+----------+--------------+------+-----+---------+----------------+
| id       | int(11)      | NO   | PRI | NULL    | auto_increment |
| author   | varchar(255) | YES  |     | NULL    |                |
| filename | varchar(255) | NO   |     | NULL    |                |
| filepath | varchar(255) | NO   |     | NULL    |                |
| username | varchar(255) | YES  |     | NULL    |                |
| original | datetime     | YES  |     | NULL    |                |
+----------+--------------+------+-----+---------+----------------+

*/

namespace Application\Entity;

use Doctrine\ORM\Mapping as ORM;

use Zend\InputFilter\Factory as InputFactory;
use Zend\InputFilter\InputFilter;
use Zend\InputFilter\InputFilterAwareInterface;
use Zend\InputFilter\InputFilterInterface;
use Zend\Validator\Date;

/**
 * @ORM\Entity
 * @ORM\Table(name="File")
 */
class File implements InputFilterAwareInterface
{
    private $columnsize;

    protected $inputFilter;

    public function exchangeArray($data)
    {
        $this->id = (isset($data['id'])) ? $data['id'] : null;
        $this->binder_id = (isset($data['binder_id'])) ? $data['binder_id'] : null;
        $this->username = (isset($data['username'])) ? $data['username'] : null;
        $this->original = (isset($data['original'])) ? $data['original'] : null;
        $this->author= (isset($data['author'])) ? $data['author'] : null;
        $this->filename = (isset($data['filename'])) ? $data['filename'] : null;
        $this->filepath = (isset($data['filepath'])) ? $data['filepath'] : null;
    }
    public function getInputFilter()
    {
        if (!$this->inputFilter) {
            $inputFilter = new InputFilter();
			$factory = new InputFactory();

            $inputFilter->add(
            	$factory->createInput(array(
                'name' => 'id',
                'required' => false,
            )));

            $inputFilter->add(
            	$factory->createInput(array(
                'name' => 'binder_id',
                'required' => false,
            )));

            $inputFilter->add(
            	$factory->createInput(array(
                'name' => 'username',
                'required' => false,
            )));

            $inputFilter->add(
            	$factory->createInput(array(
                'name' => 'original',
                'required' => false,
                'options' => array(
                	'format' => 'Ymd'
				)
            ))
			);

            $inputFilter->add(
            	$factory->createInput(array(
                'name' => 'author',
                'required' => false,
            )));

            $inputFilter->add(
            	$factory->createInput(array(
                'name' => 'filename',
                'required' => false,
            )));

            $inputFilter->add(
            	$factory->createInput(array(
                'name' => 'filepath',
                'required' => false,
            )));

            $this->inputFilter = $inputFilter;
        }
        return $this->inputFilter;
    }
    public function setInputFilter(InputFilterInterface $inputFilter)
    {
        throw new \Exception("Not Used");
    }
    public function getArrayCopy()
    {
        return get_object_vars($this);
    }

    /**
     * @var integer
     *
     * @ORM\Column(name="id", type="integer", nullable=false)
     * @ORM\Id
     * @ORM\GeneratedValue(strategy="IDENTITY")
     */
    private $id;

    /**
     *
	 *
     * @ORM\Column(name="binder_id", type="integer", length=255, nullable=false)
     * @var integer
     */
    private $binder_id;

    /**
     * @var string
     *
     * @ORM\Column(name="author", type="string", length=255, nullable=false)
     */
    private $author;

    /**
     * @var string
     *
     * @ORM\Column(name="filename", type="string", length=255, nullable=false)
     */
    private $filename;

    /**
     * @var string
     *
     * @ORM\Column(name="filepath", type="string", length=255, nullable=false)
     */
    private $filepath;

    /**
     * @var string
	 *
	 * @ORM\Column(name="username", type="string", length=255, nullable=false)
    	 *
	 **/
    private $username;

    /**
     * @var string
     *
     * @ORM\Column(name="original", type="string", length=255, nullable=false)
     */
    private $original;

    /**
     * Get id
     *
     * @return integer
     */
    public function getId()
    {
        return $this->id;
    }

    /*
     * Set id
     * @param integer $id
     * @return File
     */
    public function setId($id)
    {
	$this->id = $id;

	return $this;
    }

    /**
     * Set username
     *
     * @param string $username
     * @return File
     */
    public function setUsername($username)
    {
        $this->username = $username;

        return $this;
    }

    /**
     * Get username
     *
     * @return string
     */
    public function getUsername()
    {
        return $this->username;
    }

    /**
     * Set original_date
     *
     * @param \DateTime $original
     * @return File
     */
    public function setOriginal($originalDate)
    {
        $this->original = $originalDate;

        return $this;
    }

    /**
     * Get original_date
     *
     * @return DateTime
     */
    public function getOriginal()
    {
        return $this->original;
    }

    /**
     * Set author
     *
     * @param string $author
     * @return File
     */
    public function setAuthor($author)
    {
        $this->author = $author;

        return $author;
    }

    /**
     * Get author
     *
     * @return string
     */
    public function getAuthor()
    {
        return $this->author;
    }

    /**
     * Set filename
     *
     * @param string $filename
     * @return Filename
     */
    public function setFilename($filename)
    {
        $this->filename = $filename;

        return $this;
    }

    /**
     * Get filename
     *
     * @return string
     */
    public function getFilename()
    {
        return $this->filename;
    }

    /**
     * Set filepath
     *
     * @param string $filepath
     * @return Filepath
     */
    public function setFilepath($filepath)
    {
        $this->filepath = $filepath;

        return $this;
    }

    /**
     * Get filepath
     *
     * @return string
     */
    public function getFilepath()
    {
        return $this->filepath;
    }

    /**
     * Set binder_id
     *
     * @param integer $binder_id
     * @return File
     */
    public function setBinderId($binder_id)
    {
        $this->binder_id = $binder_id;

        return $this;
    }

    /**
     * Get binder_id
     *
     * @return integer
     */
    public function getBinderId()
    {
        return $this->binder_id;
    }
}


text:
package org.zstack.test.virtualrouter;

import junit.framework.Assert;
import org.junit.Before;
import org.junit.Test;
import org.zstack.core.cloudbus.CloudBus;
import org.zstack.core.componentloader.ComponentLoader;
import org.zstack.core.db.DatabaseFacade;
import org.zstack.header.identity.*;
import org.zstack.header.network.l3.L3NetworkInventory;
import org.zstack.network.service.portforwarding.PortForwardingProtocolType;
import org.zstack.network.service.portforwarding.PortForwardingQuotaConstant;
import org.zstack.network.service.portforwarding.PortForwardingRuleInventory;
import org.zstack.network.service.vip.VipInventory;
import org.zstack.simulator.kvm.KVMSimulatorConfig;
import org.zstack.simulator.virtualrouter.VirtualRouterSimulatorConfig;
import org.zstack.test.Api;
import org.zstack.test.ApiSenderException;
import org.zstack.test.DBUtil;
import org.zstack.test.WebBeanConstructor;
import org.zstack.test.deployer.Deployer;
import org.zstack.test.identity.IdentityCreator;
import org.zstack.utils.CollectionUtils;
import org.zstack.utils.function.Function;

import java.util.List;

/**
 * test quota
 */
public class TestPolicyForPortForwarding1 {
    Deployer deployer;
    Api api;
    ComponentLoader loader;
    CloudBus bus;
    DatabaseFacade dbf;
    SessionInventory session;
    VirtualRouterSimulatorConfig vconfig;
    KVMSimulatorConfig kconfig;

    @Before
    public void setUp() throws Exception {
        DBUtil.reDeployDB();
        WebBeanConstructor con = new WebBeanConstructor();
        deployer = new Deployer("deployerXml/virtualRouter/TestPolicyForPortForwarding.xml", con);
        deployer.addSpringConfig("VirtualRouter.xml");
        deployer.addSpringConfig("VirtualRouterSimulator.xml");
        deployer.addSpringConfig("KVMRelated.xml");
        deployer.addSpringConfig("vip.xml");
        deployer.addSpringConfig("PortForwarding.xml");
        deployer.build();
        api = deployer.getApi();
        loader = deployer.getComponentLoader();
        vconfig = loader.getComponent(VirtualRouterSimulatorConfig.class);
        kconfig = loader.getComponent(KVMSimulatorConfig.class);
        bus = loader.getComponent(CloudBus.class);
        dbf = loader.getComponent(DatabaseFacade.class);
        session = api.loginAsAdmin();
    }

    PortForwardingRuleInventory createPortForwarding(String l3Uuid, SessionInventory session) throws ApiSenderException {
        PortForwardingRuleInventory rule1 = new PortForwardingRuleInventory();
        VipInventory vip = api.acquireIp(l3Uuid, session);
        rule1.setName("pfRule1");
        rule1.setVipUuid(vip.getUuid());
        rule1.setVipPortStart(22);
        rule1.setVipPortEnd(100);
        rule1.setPrivatePortStart(22);
        rule1.setPrivatePortEnd(100);
        rule1.setProtocolType(PortForwardingProtocolType.TCP.toString());
        return api.createPortForwardingRuleByFullConfig(rule1, session);
    }

    @Test
    public void test() throws ApiSenderException {
        L3NetworkInventory vipNw = deployer.l3Networks.get("PublicNetwork");

        IdentityCreator identityCreator = new IdentityCreator(api);
        AccountInventory test = identityCreator.useAccount("test");
        SessionInventory session = identityCreator.getAccountSession();

        createPortForwarding(vipNw.getUuid(), session);

        List<Quota.QuotaUsage> usages = api.getQuotaUsage(test.getUuid(), session);
        Quota.QuotaUsage u = CollectionUtils.find(usages, new Function<Quota.QuotaUsage, Quota.QuotaUsage>() {
            @Override
            public Quota.QuotaUsage call(Quota.QuotaUsage arg) {
                return arg.getName().equals(PortForwardingQuotaConstant.PF_NUM) ? arg : null;
            }
        });
        QuotaInventory q = api.getQuota(PortForwardingQuotaConstant.PF_NUM, test.getUuid(), session);
        Assert.assertEquals(1, u.getUsed().longValue());
        Assert.assertEquals(q.getValue(), u.getTotal().longValue());

        api.updateQuota(test.getUuid(), PortForwardingQuotaConstant.PF_NUM, 1);

        boolean s = false;
        try {
            createPortForwarding(vipNw.getUuid(), session);
        } catch (ApiSenderException e) {
            if (IdentityErrors.QUOTA_EXCEEDING.toString().equals(e.getError().getCode())) {
                s = true;
            }
        }
        Assert.assertTrue(s);
    }
}


text:
package org.elasticsearch.painless.ir;

import org.elasticsearch.painless.ClassWriter;
import org.elasticsearch.painless.Location;
import org.elasticsearch.painless.MethodWriter;
import org.elasticsearch.painless.ScriptClassInfo;
import org.elasticsearch.painless.symbol.ScopeTable;
import org.elasticsearch.painless.symbol.ScriptRoot;
import org.objectweb.asm.ClassVisitor;
import org.objectweb.asm.Opcodes;
import org.objectweb.asm.Type;
import org.objectweb.asm.commons.Method;
import org.objectweb.asm.util.Printer;

import java.lang.invoke.MethodType;
import java.util.ArrayList;
import java.util.BitSet;
import java.util.List;

import static org.elasticsearch.painless.WriterConstants.BASE_INTERFACE_TYPE;
import static org.elasticsearch.painless.WriterConstants.CLASS_TYPE;

public class ClassNode extends IRNode {

    /* ---- begin tree structure ---- */

    private final List<FieldNode> fieldNodes = new ArrayList<>();
    private final List<FunctionNode> functionNodes = new ArrayList<>();
    private final BlockNode clinitBlockNode;

    public void addFieldNode(FieldNode fieldNode) {
        fieldNodes.add(fieldNode);
    }

    public List<FieldNode> getFieldsNodes() {
        return fieldNodes;
    }

    public void addFunctionNode(FunctionNode functionNode) {
        functionNodes.add(functionNode);
    }

    public List<FunctionNode> getFunctionsNodes() {
        return functionNodes;
    }

    public BlockNode getClinitBlockNode() {
        return clinitBlockNode;
    }

    /* ---- end tree structure, begin node data ---- */

    private Printer debugStream;
    private ScriptRoot scriptRoot;

    public void setDebugStream(Printer debugStream) {
        this.debugStream = debugStream;
    }

    public Printer getDebugStream() {
        return debugStream;
    }

    public void setScriptRoot(ScriptRoot scriptRoot) {
        this.scriptRoot = scriptRoot;
    }

    public ScriptRoot getScriptRoot() {
        return scriptRoot;
    }

    /* ---- end node data ---- */

    public ClassNode() {
        clinitBlockNode = new BlockNode();
        clinitBlockNode.setLocation(new Location("internal$clinit$blocknode", 0));
        clinitBlockNode.setAllEscape(true);
        clinitBlockNode.setStatementCount(1);
    }

    public byte[] write() {
        ScriptClassInfo scriptClassInfo = scriptRoot.getScriptClassInfo();
        BitSet statements = new BitSet(scriptRoot.getScriptSource().length());
        scriptRoot.addStaticConstant("$STATEMENTS", statements);

        // Create the ClassWriter.

        int classFrames = org.objectweb.asm.ClassWriter.COMPUTE_FRAMES | org.objectweb.asm.ClassWriter.COMPUTE_MAXS;
        int classAccess = Opcodes.ACC_PUBLIC | Opcodes.ACC_SUPER | Opcodes.ACC_FINAL;
        String interfaceBase = BASE_INTERFACE_TYPE.getInternalName();
        String className = CLASS_TYPE.getInternalName();
        String[] classInterfaces = new String[] { interfaceBase };

        ClassWriter classWriter = new ClassWriter(scriptRoot.getCompilerSettings(), statements, debugStream,
                scriptClassInfo.getBaseClass(), classFrames, classAccess, className, classInterfaces);
        ClassVisitor classVisitor = classWriter.getClassVisitor();
        classVisitor.visitSource(Location.computeSourceName(scriptRoot.getScriptName()), null);

        org.objectweb.asm.commons.Method init;

        if (scriptClassInfo.getBaseClass().getConstructors().length == 0) {
            init = new org.objectweb.asm.commons.Method("<init>", MethodType.methodType(void.class).toMethodDescriptorString());
        } else {
            init = new org.objectweb.asm.commons.Method("<init>", MethodType.methodType(void.class,
                scriptClassInfo.getBaseClass().getConstructors()[0].getParameterTypes()).toMethodDescriptorString());
        }

        // Write the constructor:
        MethodWriter constructor = classWriter.newMethodWriter(Opcodes.ACC_PUBLIC, init);
        constructor.visitCode();
        constructor.loadThis();
        constructor.loadArgs();
        constructor.invokeConstructor(Type.getType(scriptClassInfo.getBaseClass()), init);
        constructor.returnValue();
        constructor.endMethod();

        if (clinitBlockNode.getStatementsNodes().isEmpty() == false) {
            MethodWriter methodWriter = classWriter.newMethodWriter(
                    Opcodes.ACC_PUBLIC | Opcodes.ACC_STATIC,
                    new Method("<clinit>", Type.getType(void.class), new Type[0]));
            clinitBlockNode.write(classWriter, methodWriter, new ScopeTable());
            methodWriter.returnValue();
            methodWriter.endMethod();
        }

        // Write all fields:
        for (FieldNode fieldNode : fieldNodes) {
            fieldNode.write(classWriter, null, null);
        }

        // Write all functions:
        for (FunctionNode functionNode : functionNodes) {
            functionNode.write(classWriter, null, new ScopeTable());
        }

        // End writing the class and store the generated bytes.
        classVisitor.visitEnd();
        return classWriter.getClassBytes();
    }
}


text:
package Telas;

import ConexaoBanco.DAO;
import java.awt.event.KeyEvent;
import java.util.Random;

public class TelaRolarCustomizado extends javax.swing.JDialog {

    DAO dao = new DAO();
    public int dado;

    public TelaRolarCustomizado(java.awt.Frame parent, boolean modal) {
        super(parent, modal);
        initComponents();
    }

    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {

        botaoRolar = new javax.swing.JButton();
        jLabel2 = new javax.swing.JLabel();
        jLabel3 = new javax.swing.JLabel();
        jLabel4 = new javax.swing.JLabel();
        campoRolarMenos = new javax.swing.JTextField();
        campoRolarMais = new javax.swing.JTextField();
        jLabel5 = new javax.swing.JLabel();
        campoValorCustumizado = new javax.swing.JTextField();

        setTitle("Double Damage - Rolar dado");
        setBackground(new java.awt.Color(255, 255, 255));
        setLocationByPlatform(true);
        setMaximumSize(new java.awt.Dimension(290, 200));
        setMinimumSize(new java.awt.Dimension(290, 200));
        setPreferredSize(new java.awt.Dimension(290, 200));
        setResizable(false);
        getContentPane().setLayout(null);

        botaoRolar.setFont(new java.awt.Font("Tahoma", 1, 16)); // NOI18N
        botaoRolar.setText("ROLAR!");
        botaoRolar.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                botaoRolarActionPerformed(evt);
            }
        });
        botaoRolar.addKeyListener(new java.awt.event.KeyAdapter() {
            public void keyPressed(java.awt.event.KeyEvent evt) {
                botaoRolarKeyPressed(evt);
            }
        });
        getContentPane().add(botaoRolar);
        botaoRolar.setBounds(170, 120, 100, 30);

        jLabel2.setFont(new java.awt.Font("Tahoma", 1, 14)); // NOI18N
        jLabel2.setText("MODIFICADORES:");
        getContentPane().add(jLabel2);
        jLabel2.setBounds(30, 10, 140, 20);

        jLabel3.setFont(new java.awt.Font("The Bold Font", 1, 24)); // NOI18N
        jLabel3.setHorizontalAlignment(javax.swing.SwingConstants.CENTER);
        jLabel3.setText("+");
        getContentPane().add(jLabel3);
        jLabel3.setBounds(20, 30, 20, 30);

        jLabel4.setFont(new java.awt.Font("The Bold Font", 1, 24)); // NOI18N
        jLabel4.setHorizontalAlignment(javax.swing.SwingConstants.CENTER);
        jLabel4.setText("-");
        getContentPane().add(jLabel4);
        jLabel4.setBounds(20, 70, 20, 30);

        campoRolarMenos.setText("0");
        campoRolarMenos.addKeyListener(new java.awt.event.KeyAdapter() {
            public void keyPressed(java.awt.event.KeyEvent evt) {
                campoRolarMenosKeyPressed(evt);
            }
        });
        getContentPane().add(campoRolarMenos);
        campoRolarMenos.setBounds(40, 70, 120, 30);

        campoRolarMais.setText("0");
        campoRolarMais.addKeyListener(new java.awt.event.KeyAdapter() {
            public void keyPressed(java.awt.event.KeyEvent evt) {
                campoRolarMaisKeyPressed(evt);
            }
        });
        getContentPane().add(campoRolarMais);
        campoRolarMais.setBounds(40, 30, 120, 30);

        jLabel5.setFont(new java.awt.Font("Tahoma", 1, 14)); // NOI18N
        jLabel5.setText("VALOR DADO:");
        getContentPane().add(jLabel5);
        jLabel5.setBounds(40, 100, 120, 20);

        campoValorCustumizado.setText("0");
        getContentPane().add(campoValorCustumizado);
        campoValorCustumizado.setBounds(40, 120, 120, 30);

        pack();
        setLocationRelativeTo(null);
    }// </editor-fold>//GEN-END:initComponents

    public int rodar() {
        Random random = new Random();
        int numero = 0;
        do {
            numero = random.nextInt(dado + 1);
        } while (numero == 0);
        return numero;
    }

    public int converterCampoModificadorMaisEmInt() {
        String valorModificadorMais = campoRolarMais.getText();
        return Integer.parseInt(valorModificadorMais);
    }

    public int converterCampoModificadorMenosEmInt() {
        String valorModificadorMenos = campoRolarMenos.getText();
        return Integer.parseInt(valorModificadorMenos);
    }

    public int converterCampoValorPersonalizar() {
        String valorModificadorMais = campoValorCustumizado.getText();
        return Integer.parseInt(valorModificadorMais);
    }

    public void rolarDado() {
        dado = converterCampoValorPersonalizar();
        if (dado == 0) {

        } else {
            int modificadorMais = converterCampoModificadorMaisEmInt();
            int modificadorMenos = converterCampoModificadorMenosEmInt();
            if (modificadorMais > 0) {
                int numero = rodar();
                int numeroModificado = numero + modificadorMais;
                dao.enviarDadoBanco(dado, numeroModificado, numero, modificadorMais, modificadorMenos, 1);
                this.dispose();
            } else if (modificadorMenos > 0) {
                int numero = rodar();
                int numeroModificado = numero - modificadorMenos;
                dao.enviarDadoBanco(dado, numeroModificado, numero, modificadorMais, modificadorMenos, 2);
                this.dispose();
            } else {
                int numero = rodar();
                int numeroModificado = 0;
                dao.enviarDadoBanco(dado, numeroModificado, numero, modificadorMais, modificadorMenos, 3);
                this.dispose();
            }
        }

    }
    private void botaoRolarActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_botaoRolarActionPerformed
        rolarDado();
    }//GEN-LAST:event_botaoRolarActionPerformed

    private void botaoRolarKeyPressed(java.awt.event.KeyEvent evt) {//GEN-FIRST:event_botaoRolarKeyPressed
        if (evt.getKeyCode() == KeyEvent.VK_ENTER) {
            rolarDado();
        } else if (evt.getKeyCode() == KeyEvent.VK_ESCAPE) {
            this.dispose();
        }
    }//GEN-LAST:event_botaoRolarKeyPressed

    private void campoRolarMaisKeyPressed(java.awt.event.KeyEvent evt) {//GEN-FIRST:event_campoRolarMaisKeyPressed
        if (evt.getKeyCode() == KeyEvent.VK_ENTER) {
            rolarDado();
        } else if (evt.getKeyCode() == KeyEvent.VK_ESCAPE) {
            this.dispose();
        }
    }//GEN-LAST:event_campoRolarMaisKeyPressed

    private void campoRolarMenosKeyPressed(java.awt.event.KeyEvent evt) {//GEN-FIRST:event_campoRolarMenosKeyPressed
        if (evt.getKeyCode() == KeyEvent.VK_ENTER) {
            rolarDado();
        } else if (evt.getKeyCode() == KeyEvent.VK_ESCAPE) {
            this.dispose();
        }
    }//GEN-LAST:event_campoRolarMenosKeyPressed

    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JButton botaoRolar;
    private javax.swing.JTextField campoRolarMais;
    private javax.swing.JTextField campoRolarMenos;
    private javax.swing.JTextField campoValorCustumizado;
    private javax.swing.JLabel jLabel2;
    private javax.swing.JLabel jLabel3;
    private javax.swing.JLabel jLabel4;
    private javax.swing.JLabel jLabel5;
    // End of variables declaration//GEN-END:variables
}


text:
include "pugixml"
include "spdlog"


text:
package csv

import (
	"basic/csv"
	"io/ioutil"
	"os"

	"github.com/golang/glog"
)

var bankruptMap map[uint32]CsvBankrupt

type CsvBankrupt struct {
	Id        uint32 `csv:"id"`
	Coin      uint32 `csv:"coin"`
	Condition uint32 `csv:"condition"`
}

var bankruptList []CsvBankrupt

func GetBankruptListLen() int {
	return len(bankruptList)
}

func GetBankrupt(id uint32) *CsvBankrupt {
	data := bankruptMap[id]
	return &data
}
func init() {
	f, err := os.Open("./csv/bankrupt.csv")
	if err != nil {
		panic(err)
	}
	defer f.Close()

	data, err := ioutil.ReadAll(f)
	if err != nil {
		panic(err)
	}
	err = csv.Unmarshal(data, &bankruptList)
	if err != nil {
		panic(err)
	}

	bankruptMap = make(map[uint32]CsvBankrupt)
	for _, v := range bankruptList {
		bankruptMap[v.Id] = v
	}
	glog.Infoln("破产表:", len(bankruptList), len(bankruptMap))
}