text:
namespace Urho3D
{

/// Parse a bool from a string. Check for the first non-empty character (converted to lowercase) being either 't', 'y' or '1'.
URHO3D_API bool ToBool(const String& source);
/// Parse a bool from a C string. Check for the first non-empty character (converted to lowercase) being either 't', 'y' or '1'.
URHO3D_API bool ToBool(const char* source);
/// Parse a float from a string.
URHO3D_API float ToFloat(const String& source);
/// Parse a float from a C string.
URHO3D_API float ToFloat(const char* source);
/// Parse an integer from a string.
URHO3D_API int ToInt(const String& source);
/// Parse an integer from a C string.
URHO3D_API int ToInt(const char* source);
/// Parse an unsigned integer from a string.
URHO3D_API unsigned ToUInt(const String& source);
/// Parse an unsigned integer from a C string.
URHO3D_API unsigned ToUInt(const char* source);
/// Parse a Color from a string.
URHO3D_API Color ToColor(const String& source);
/// Parse a Color from a C string.
URHO3D_API Color ToColor(const char* source);
/// Parse an IntRect from a string.
URHO3D_API IntRect ToIntRect(const String& source);
/// Parse an IntRect from a C string.
URHO3D_API IntRect ToIntRect(const char* source);
/// Parse an IntVector2 from a string.
URHO3D_API IntVector2 ToIntVector2(const String& source);
/// Parse an IntVector2 from a C string.
URHO3D_API IntVector2 ToIntVector2(const char* source);
/// Parse a Quaternion from a string. If only 3 components specified, convert Euler angles (degrees) to quaternion.
URHO3D_API Quaternion ToQuaternion(const String& source);
/// Parse a Quaternion from a C string. If only 3 components specified, convert Euler angles (degrees) to quaternion.
URHO3D_API Quaternion ToQuaternion(const char* source);
/// Parse a Rect from a string.
URHO3D_API Rect ToRect(const String& source);
/// Parse a Rect from a C string.
URHO3D_API Rect ToRect(const char* source);
/// Parse a Vector2 from a string.
URHO3D_API Vector2 ToVector2(const String& source);
/// Parse a Vector2 from a C string.
URHO3D_API Vector2 ToVector2(const char* source);
/// Parse a Vector3 from a string.
URHO3D_API Vector3 ToVector3(const String& source);
/// Parse a Vector3 from a C string.
URHO3D_API Vector3 ToVector3(const char* source);
/// Parse a Vector4 from a string.
URHO3D_API Vector4 ToVector4(const String& source, bool allowMissingCoords = false);
/// Parse a Vector4 from a C string.
URHO3D_API Vector4 ToVector4(const char* source, bool allowMissingCoords = false);
/// Parse a float or Vector variant from a string.
URHO3D_API Variant ToVectorVariant(const String& source);
/// Parse a float or Vector variant from a string.
URHO3D_API Variant ToVectorVariant(const char* source);
/// Convert a pointer to string (returns hexadecimal.)
URHO3D_API String ToString(void* value);
/// Convert an unsigned integer to string as hexadecimal.
URHO3D_API String ToStringHex(unsigned value);
/// Convert a byte buffer to a string.
URHO3D_API void BufferToString(String& dest, const void* data, unsigned size);
/// Convert a string to a byte buffer.
URHO3D_API void StringToBuffer(PODVector<unsigned char>& dest, const String& source);
/// Convert a C string to a byte buffer.
URHO3D_API void StringToBuffer(PODVector<unsigned char>& dest, const char* source);
/// Return an index to a string list corresponding to the given string, or a default value if not found. The string list must be empty-terminated.
URHO3D_API unsigned GetStringListIndex(const String& value, const String* strings, unsigned defaultIndex, bool caseSensitive = false);
/// Return an index to a string list corresponding to the given C string, or a default value if not found. The string list must be empty-terminated.
URHO3D_API unsigned GetStringListIndex(const char* value, const String* strings, unsigned defaultIndex, bool caseSensitive = false);
/// Return an index to a C string list corresponding to the given C string, or a default value if not found. The string list must be empty-terminated.
URHO3D_API unsigned GetStringListIndex(const char* value, const char** strings, unsigned defaultIndex, bool caseSensitive = false);
/// Return a formatted string.
URHO3D_API String ToString(const char* formatString, ...);
/// Return whether a char is an alphabet letter.
URHO3D_API bool IsAlpha(unsigned ch);
/// Return whether a char is a digit.
URHO3D_API bool IsDigit(unsigned ch);
/// Return char in uppercase.
URHO3D_API unsigned ToUpper(unsigned ch);
/// Return char in lowercase.
URHO3D_API unsigned ToLower(unsigned ch);

}

redpajama_set_name: RedPajamaGithub


text:
<!doctype html>

  <meta charset="utf-8">

  <meta http-equiv="X-UA-Compatible" content="IE=edge,chrome=1">

  <title>CFMI: {% block title %}Imaging{% endblock %}</title>
  <meta name="description" content="CFMI Imaging Application">
  <meta name="author" content="Shawn Nock nock@nocko.org">

  <meta name="viewport" content="width=device-width, initial-scale=1.0">

  <link rel="shortcut icon" href="{{ url_for('static', filename="favicon.ico") }}">

  <link rel="stylesheet" href="{{ url_for('static', filename="css/bootstrap.min.css") }}?v=2">
  <link rel="stylesheet" href="{{ url_for('static', filename="css/style.css") }}?v=2">

  {% block header %}
  {% endblock %}
  <link href='https://fonts.googleapis.com/css?family=Cardo' rel='stylesheet' type='text/css'>

{% block name %}{% endblock %}

      {% if g.user %}

	      {% set active_nav = active_nav|default('home') %}
	      {% include "_nav.html" %}

      {% endif %}

    {% block content %}
    {% endblock %}

  {% block foot %}
  {% endblock %}
  {% with messages = get_flashed_messages() %}

  {% endwith %}


text:
import sys
import time
import pxssh
import pexpect
import subprocess
from OpTestIPMI import OpTestIPMI

class OpTestBMC():

    def __init__(self, i_bmcIP, i_bmcUser, i_bmcPasswd,i_ffdcDir=None):
        self.cv_bmcIP = i_bmcIP
        self.cv_bmcUser = i_bmcUser
        self.cv_bmcPasswd = i_bmcPasswd
        self.cv_ffdcDir = i_ffdcDir
        self.cv_IPMI = OpTestIPMI(i_bmcIP,i_bmcUser,i_bmcPasswd,i_ffdcDir)

    def _cmd_run(self, cmdStr, timeout=30, logFile=None):
        """This function runs a command on the BMC.

        :param logFile: File where the command output will be written.
            All command output files are placed in the FFDC directory as configured
            in the config file.
        :type logFile: str.
        :param timeout: Command timeout in seconds. If not specified, the
            default timeout value is 30 seconds.
        :type timeout: int.
        :returns: int -- the return code, 0: success, 1: error
        :raises: pexect timeout, eof

        """

        ''' Add -k to the SSH options '''

        hostname = self.cv_bmcIP + " -k"

        p = pxssh.pxssh()
        p.logfile = sys.stdout
        p.PROMPT = '# '

        ''' login but do not try to change the prompt since the AMI bmc
            busybox does support it '''

        # http://superuser.com/questions/839878/how-to-solve-python-bug-without-root-permission
        p.login(hostname, self.cv_bmcUser, self.cv_bmcPasswd, auto_prompt_reset=False)
        p.sendline()
        p.prompt()
        print 'At BMC %s prompt...' % self.cv_bmcIP

        p.sendline(cmdStr)
        p.prompt(timeout=timeout)

        ''' if optional argument is set, save command output to file '''

        if logFile is not None:
            fn = self.cv_ffdcDir + "/" + logFile
            with open(fn, 'w') as f:
                f.write(p.before)

        p.sendline('echo $?')
        index = p.expect(['0', pexpect.TIMEOUT])
        if index == 0:
            rc = 0
        if index == 1:
            print 'Non-zero return code detected, command failed'
            rc = p.before

        return rc

    def reboot(self):
        """This function issues the reboot command on the BMC console.  It then
        pings the BMC until it responds, which presumably means that it is done
        rebooting.  It returns the number of failed pings.  The caller should make
        returned value is greater than 1

        :returns: int -- 0 on success, non-zero on failure

        """
        retries = 0
        self._cmd_run('reboot', logFile='bmc_reboot.log')
        print 'Sent reboot command now waiting for reboot to complete...'
        time.sleep(30)
        '''  Ping the system until it reboots  '''
        while True:
            try:
                subprocess.check_call(["ping", self.cv_bmcIP, "-c1"])
                break
            except subprocess.CalledProcessError as e:
                print "Ping return code: ", e.returncode, "retrying..."
                retries += 1
                time.sleep(30)

            if retries > 5:
                print "Error. BMC is not reponding to pings"
                return -1

        print 'BMC reboot complete.'

        return 0

    def pnor_img_transfer(self,i_imageDir,i_imageName):
        """This function copies the PNOR image to the BMC /tmp dir.

        :returns: int -- the rsync command return code
        """
        pnor_path = i_imageDir + i_imageName
        rsync_cmd = 'rsync -v -e "ssh -k" %s %s@%s:/tmp' % (pnor_path,
                                                            self.cv_bmcUser,
                                                            self.cv_bmcIP)
        print rsync_cmd
        rsync = pexpect.spawn(rsync_cmd)
        rsync.logfile = sys.stdout
        rsync.expect('assword: ')
        rsync.sendline(self.cv_bmcPasswd)
        rsync.expect('total size is', timeout=60)
        rsync.expect(pexpect.EOF)
        rsync.close()
        return rsync.exitstatus

    def pnor_img_flash(self,i_imageName):
        """This function flashes the PNOR image.

        :returns: int -- the pflash command return code
        """
        cmd = '/usr/local/bin/pflash -E -f -p /tmp/%s' % i_imageName
        rc = self._cmd_run(cmd, timeout=180, logFile='pflash.log')
        return rc


text:
/**
 *
 */
package com.kant.datastructure.graphs;

import java.util.Iterator;
import java.util.LinkedList;
import java.util.Stack;

/**
 * Topological sorting for Directed Acyclic Graph (DAG) is a linear ordering of
 * vertices such that for every directed edge uv, vertex u comes before v in the
 * ordering. Topological Sorting for a graph is not possible if the graph is not
 * a DAG.

 * Time Complexity: The above algorithm is simply DFS with an extra stack. So
 * time complexity is same as DFS which is O(V+E).

 * Applications: Topological Sorting is mainly used for scheduling jobs
 * from the given dependencies among jobs. In computer science, applications of
 * this type arise in instruction scheduling, ordering of formula cell
 * evaluation when recomputing formula values in spreadsheets, logic synthesis,
 * determining the order of compilation tasks to perform in makefiles, data
 * serialization, and resolving symbol dependencies in linkers
 *
 *
 * http://www.geeksforgeeks.org/shortest-path-for-directed-acyclic-graphs/
 *
 * @author shaskant
 *
 */
public class Graph_TopoLogicalSort {
	private int V;// no. of vertices
	private LinkedList<Integer>[] adj;

	@SuppressWarnings("unchecked")
	public Graph_TopoLogicalSort(int aV) {
		this.V = aV;
		adj = new LinkedList[V];
		for (int i = 0; i < V; i++)
			adj[i] = new LinkedList<Integer>();
	}

	/**
	 * NOTE: on way edge only [FOR DAG]
	 *
	 * @param src
	 * @param des
	 */
	public void addEdge(int src, int des) {
		adj[src].add(des);
	}

	/**
	 *
	 */
	public void printGraph() {
		boolean[] visited = new boolean[V];
		for (int i = 0; i < V; i++)
			if (!visited[i])
				doDfs(i, visited);
	}

	/**
	 * The algorithm loops through each node of the graph, in an arbitrary
	 * order, initiating a depth-first search that terminates when it hits any
	 * node that has already been visited since the beginning of the topological
	 * sort or the node has no outgoing edges (i.e. a leaf node):
	 *
	 *

	 * Each node n gets prepended to the output list L only after considering
	 * all other nodes which depend on n (all descendants of n in the graph).
	 * Specifically, when the algorithm adds node n, we are guaranteed that all
	 * nodes which depend on n are already in the output list L: they were added
	 * to L either by the recursive call to visit() which ended before the call
	 * to visit n, or by a call to visit() which started even before the call to
	 * visit n. Since each edge and node is visited once, the algorithm runs in
	 * linear time
	 *
	 * @param nv
	 * @param visited
	 */
	private void doDfs(int nv, boolean[] visited) {
		visited[nv] = true;
		System.out.println(nv);

		Iterator<Integer> iterator = adj[nv].iterator();
		while (iterator.hasNext()) {
			int next = iterator.next();
			if (!visited[next]) {
				doDfs(next, visited);
			}
		}
	}

	/**
	 *
	 */
	public void topologicalTraverse() {
		boolean[] visited = new boolean[V];
		Stack<Integer> stack = new Stack<>();
		for (int i = 0; i < V; i++)
			if (!visited[i])
				doTopologicalSort(i, stack, visited);

		while (!stack.isEmpty()) {
			System.out.print(stack.pop() + " ");
		}
	}

	/**
	 *
	 * @param nv
	 * @param stack
	 * @param visited
	 */
	private void doTopologicalSort(int nv, Stack<Integer> stack,
			boolean[] visited) {
		visited[nv] = true;

		// visit all neighbors
		Iterator<Integer> iterator = adj[nv].iterator();
		while (iterator.hasNext()) {
			int next = iterator.next();
			if (!visited[next]) {
				doTopologicalSort(next, stack, visited);
			}
		}
		stack.push(nv);
	}

	public static void main(String[] args) {
		Graph_TopoLogicalSort g = new Graph_TopoLogicalSort(6);
		g.addEdge(5, 2);
		g.addEdge(5, 0);
		g.addEdge(4, 0);
		g.addEdge(4, 1);
		g.addEdge(2, 3);
		g.addEdge(3, 1);

		g.topologicalTraverse();
	}
}


text:
<?xml version="1.0" encoding="utf-8"?>

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
              android:orientation="vertical"
              android:layout_width="match_parent"
              android:layout_height="48dp"
              android:gravity="center_vertical">

    <TextView
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:textAppearance="?android:attr/textAppearanceMedium"
            android:text="Medium Text"
            android:paddingLeft="18dp"
            android:paddingRight="18dp"
            android:id="@+id/text_view_book_title"/>
</LinearLayout>


text:
package part3;

import java.awt.Color;
import java.awt.Graphics;

import javax.swing.JApplet;

public class YellowFace extends JApplet {
	private static final long serialVersionUID = 1L;

	public static final int FACE_DIAMETER = 200;
	public static final int X_FACE = 100;
	public static final int Y_FACE = 50;
	public static final int EYE_WIDTH = 10;
	public static final int EYE_HEIGHT = 20;
	public static final int X_RIGHT_EYE = 155;
	public static final int Y_RIGHT_EYE = 100;
	public static final int X_LEFT_EYE = 230;
	public static final int Y_LEFT_EYE = Y_RIGHT_EYE;
	public static final int NOSE_WIDTH = 20;
	public static final int NOSE_HEIGHT = 10;
	public static final int X_NOSE = 190; // Centre of nose will be at 200
	public static final int Y_NOSE = 150;
	public static final int MOUTH_WIDTH = 100;
	public static final int MOUTH_HEIGHT = 50;
	public static final int X_MOUTH = 150;
	public static final int Y_MOUTH = 160;
	public static final int MOUTH_START_ANGLE = 180;
	public static final int MOUTH_EXTENT_ANGLE = 180;

	public void paint(Graphics canvas) {
		// Draw face interior and outline
		canvas.setColor(Color.YELLOW);
		canvas.fillOval(X_FACE, Y_FACE, FACE_DIAMETER, FACE_DIAMETER);
		canvas.setColor(Color.BLACK);
		canvas.drawOval(X_FACE, Y_FACE, FACE_DIAMETER, FACE_DIAMETER);
		// Draw eyes
		canvas.setColor(Color.BLUE);
		canvas.fillOval(X_RIGHT_EYE, Y_RIGHT_EYE, EYE_WIDTH, EYE_HEIGHT);
		canvas.fillOval(X_LEFT_EYE, Y_LEFT_EYE, EYE_WIDTH, EYE_HEIGHT);
		// Draw nose
		canvas.setColor(Color.BLACK);
		canvas.fillOval(X_NOSE, Y_NOSE, NOSE_WIDTH, NOSE_HEIGHT);
		// Draw mouth
		canvas.setColor(Color.RED);
		canvas.drawArc(X_MOUTH, Y_MOUTH, MOUTH_WIDTH, MOUTH_HEIGHT, MOUTH_START_ANGLE, MOUTH_EXTENT_ANGLE);
	}
}


text:
# -*- coding: utf-8 -*-
"""

 This plugin provides access to openrouteservice API functionalities
 (https://openrouteservice.org), developed and
 maintained by the openrouteservice team of HeiGIT gGmbH, Germany. By using
 this plugin you agree to the ORS terms of service
 (https://openrouteservice.org/terms-of-service/).

/***************************************************************************
 *                                                                         *
 *   This program is free software; you can redistribute it and/or modify  *
 *   it under the terms of the GNU General Public License as published by  *
 *   the Free Software Foundation; either version 2 of the License, or     *
 *   (at your option) any later version.                                   *
 *                                                                         *
 ***************************************************************************/
"""

from qgis.core import (QgsWkbTypes,
                       QgsCoordinateReferenceSystem,
                       QgsProcessing,
                       QgsProcessingUtils,
                       QgsProcessingException,
                       QgsProcessingParameterField,
                       QgsProcessingParameterFeatureSource,
                       QgsProcessingParameterString,
                       QgsProcessingParameterEnum
                       )

from ORStools.common import isochrones_core, PROFILES, DIMENSIONS
from ORStools.proc.base_processing_algorithm import ORSBaseProcessingAlgorithm
from ORStools.utils import transform, exceptions, logger

# noinspection PyPep8Naming
class ORSIsochronesLayerAlgo(ORSBaseProcessingAlgorithm):
    def __init__(self):
        super().__init__()
        self.ALGO_NAME = 'isochrones_from_layer'
        self.GROUP = 'Isochrones'

        self.IN_POINTS = "INPUT_POINT_LAYER"
        self.IN_FIELD = "INPUT_FIELD"
        self.IN_PROFILE = "INPUT_PROFILE"
        self.IN_METRIC = 'INPUT_METRIC'
        self.IN_RANGES = 'INPUT_RANGES'
        self.IN_KEY = 'INPUT_APIKEY'
        self.IN_DIFFERENCE = 'INPUT_DIFFERENCE'
        self.PARAMETERS = [
            QgsProcessingParameterFeatureSource(
                name=self.IN_POINTS,
                description="Input Point layer",
                types=[QgsProcessing.TypeVectorPoint]
            ),
            # QgsProcessingParameterBoolean(
            #     name=self.IN_DIFFERENCE,
            #     description="Dissolve and calculate isochrone difference",
            # )
            QgsProcessingParameterField(
                name=self.IN_FIELD,
                description="Input layer ID Field (mutually exclusive with Point option)",
                parentLayerParameterName=self.IN_POINTS,
                optional=True
            ),
            QgsProcessingParameterEnum(
                self.IN_PROFILE,
                "Travel mode",
                PROFILES,
                defaultValue=PROFILES[0]
            ),
            QgsProcessingParameterEnum(
                name=self.IN_METRIC,
                description="Dimension",
                options=DIMENSIONS,
                defaultValue=DIMENSIONS[0]
            ),
            QgsProcessingParameterString(
                name=self.IN_RANGES,
                description="Comma-separated ranges [min or m]",
                defaultValue="5, 10"
            )
        ]

    # Save some important references
    # TODO bad style, refactor
    isochrones = isochrones_core.Isochrones()
    dest_id = None
    crs_out = QgsCoordinateReferenceSystem.fromEpsgId(4326)
    # difference = None

    # TODO: preprocess parameters to options the range cleanup below:
    # https://www.qgis.org/pyqgis/master/core/Processing/QgsProcessingAlgorithm.html#qgis.core.QgsProcessingAlgorithm.prepareAlgorithm
    def processAlgorithm(self, parameters, context, feedback):
        ors_client = self._get_ors_client_from_provider(parameters[self.IN_PROVIDER], feedback)

        profile = dict(enumerate(PROFILES))[parameters[self.IN_PROFILE]]
        dimension = dict(enumerate(DIMENSIONS))[parameters[self.IN_METRIC]]

        factor = 60 if dimension == 'time' else 1
        ranges_raw = parameters[self.IN_RANGES]
        ranges_proc = [x * factor for x in map(int, ranges_raw.split(','))]

        # self.difference = self.parameterAsBool(parameters, self.IN_DIFFERENCE, context)
        source = self.parameterAsSource(parameters, self.IN_POINTS, context)

        # Make the actual requests
        requests = []
        if source.wkbType() == 4:
            raise QgsProcessingException(
                "TypeError: Multipoint Layers are not accepted. Please convert to single geometry layer.")

        # Get ID field properties
        id_field_name = parameters[self.IN_FIELD]
        parameter_options = list()
        if id_field_name:
            id_field = source.fields().field(id_field_name)
            parameter_options = [id_field.type(), id_field_name]

        self.isochrones.set_parameters(profile, dimension, factor, *parameter_options)

        for locations, id_value in self.get_sorted_feature_parameters(source, id_field_name):
            # Stop the algorithm if cancel button has been clicked
            if feedback.isCanceled():
                break

            requests.append({
                "locations": locations,
                "range_type": dimension,
                "range": ranges_proc,
                "attributes": ['total_pop'],
                "id": id_value,
            })

        (sink, self.dest_id) = self.parameterAsSink(parameters, self.OUT, context,
                                                    self.isochrones.get_fields(),
                                                    QgsWkbTypes.Polygon,
                                                    # Needs Multipolygon if difference parameter will ever be
                                                    # reactivated
                                                    self.crs_out)

        for num, params in enumerate(requests):
            if feedback.isCanceled():
                break

            # If feature causes error, report and continue with next
            try:
                # Populate features from response
                response = ors_client.request('/v2/isochrones/' + profile, {}, post_json=params)

                for isochrone in self.isochrones.get_features(response, params['id']):
                    sink.addFeature(isochrone)

            except (exceptions.ApiError,
                    exceptions.InvalidKey,
                    exceptions.GenericServerError) as e:
                msg = f"Feature ID {params['id']} caused a {e.__class__.__name__}:\n{str(e)}"
                feedback.reportError(msg)
                logger.log(msg, 2)
                continue
            feedback.setProgress(int(100.0 / source.featureCount() * num))

        return {self.OUT: self.dest_id}

    # noinspection PyUnusedLocal
    def postProcessAlgorithm(self, context, feedback):
        """Style polygon layer in post-processing step."""
        # processed_layer = self.isochrones.calculate_difference(self.dest_id, context)
        processed_layer = QgsProcessingUtils.mapLayerFromString(self.dest_id, context)
        self.isochrones.stylePoly(processed_layer)

        return {self.OUT: self.dest_id}

    @staticmethod
    def get_sorted_feature_parameters(layer: QgsProcessingParameterFeatureSource, id_field_name: str):
        """
        Generator to yield geometry and id of features sorted by feature ID. Careful: feat.id() is not necessarily
        permanent

        :param layer: source input layer.
        :param id_field_name: layer field containing id values
        """
        # First get coordinate transformer
        x_former = transform.transformToWGS(layer.sourceCrs())

        for feat in sorted(layer.getFeatures(), key=lambda f: f.id()):
            x_point = x_former.transform(feat.geometry().asPoint())
            id_value = feat[id_field_name] if id_field_name else None

            yield [[round(x_point.x(), 6), round(x_point.y(), 6)]], id_value


text:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    android:gravity="center" >
    <TextView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="더 보기"
        android:textAppearance="?android:attr/textAppearanceLarge" />
</LinearLayout>


text:
Ti.include('../shared/default.js');

var entered = false;
var error_shown = false;
var checkwhether_signin_button_click = false;

var alertfillemailpass = Ti.UI.createAlertDialog({
	buttonNames : ["OK"],
	title : "Cheefsheet",
	message : "Please Fill Email and Password",
	cancel : 0
});

var alertwrongemailpass = Ti.UI.createAlertDialog({
	buttonNames : ["OK"],
	title : "Cheefsheet",
	message : "Email or Password is Incorrect ",
	cancel : 0
});

var alertnoInternet = Ti.UI.createAlertDialog({
	buttonNames : ["OK"],
	title : "Cheefsheet",
	message : "Please check Internet Connection",
	cancel : 0
});

var alertslowInternet = Ti.UI.createAlertDialog({
	buttonNames : ["OK"],
	title : "Cheefsheet",
	message : "Internet is Slow",
	cancel : 0
});

try {
	Ti.App.fireEvent('closeMenu');
} catch(e) {
}

//Bidyut Nath
//added code for preventing landscape mode.
win.orientationModes = [Titanium.UI.PORTRAIT];

var autoLogLabel = Ti.UI.createLabel({
	color : '#fff',
	text : 'Remember Login',
	top : heightt * 0.16,
	left : widthh * 0.25,
	height : 'auto',
	font : {
		fontSize : heightt * 0.03,
		fontWeight : 'bold'
	}

});
win.add(autoLogLabel);

var autoLogSwitch = Ti.UI.createSwitch({
	value : Boolean((Ti.App.Properties.getString('autologin'), 10)),
	top : heightt * 0.15,
	right : widthh * 0.10
});
win.add(autoLogSwitch);

try{
	if(Ti.App.Properties.getString('valueRemm')=='1'){
		autoLogSwitch.value=true;
		Ti.App.Properties.setString('autologin',true);
	}else if(Ti.App.Properties.getString('valueRemm')=='0'){
		autoLogSwitch.value=false;
		Ti.App.Properties.setString('autologin',false);
	}
}catch(e){}
var emailField = Ti.UI.createTextField({
	hintText : 'Email',
	height : heightt * 0.09,
	width : widthh * 0.80,
	top : heightt * 0.30,
	left : widthh * 0.10,
	autocorrect : false,
	keyboardType : Titanium.UI.KEYBOARD_EMAIL,
	autocapitalization : Titanium.UI.TEXT_AUTOCAPITALIZATION_NONE,
	borderStyle : Ti.UI.INPUT_BORDERSTYLE_ROUNDED
});
win.add(emailField);

var passwordField = Ti.UI.createTextField({
	hintText : 'Password',
	passwordMask : true,
	height : heightt * 0.09,
	width : widthh * 0.80,
	top : heightt * 0.40,
	left : widthh * 0.10,
	autocorrect : false,
	keyboardType : Titanium.UI.KEYBOARD_EMAIL,
	autocapitalization : Titanium.UI.TEXT_AUTOCAPITALIZATION_NONE,
	borderStyle : Ti.UI.INPUT_BORDERSTYLE_ROUNDED
});
win.add(passwordField);

var signInBtn = Ti.UI.createButton({
	title : 'Sign In',
	width : widthh * 0.30,
	height : heightt * 0.06,
	top : heightt * 0.50,
	left : widthh * 0.10,
	color : '#FFFFFF',
	borderRadius : 10,
	font : {
		fontSize : heightt * 0.03,
		fontWeight : 'bold'
	},
	backgroundGradient : {
		type : 'linear',
		colors : ['#698aaa', '#1C4E7E', '#173f6b'],
		startPoint : {
			x : 0,
			y : 0
		},
		endPoint : {
			x : 0,
			y : 36
		},
		backFillStart : false
	},
	borderWidth : 1,
	borderColor : '#112f55'

});
win.add(signInBtn);

var back_fn = Ti.Filesystem.getFile(Titanium.Filesystem.resourcesDirectory, 'images/cs-signtitle.png');
var back = Titanium.UI.createImageView({
	image : back_fn,
	top : heightt * 0.55,
	width : widthh * 0.99
});
win.add(back);

var signUpBtn = Ti.UI.createButton({
	title : 'Sign Up',
	width : widthh * 0.30,
	height : heightt * 0.06,
	top : heightt * 0.50,
	left : widthh * 0.60,
	color : '#FFFFFF',
	borderRadius : 10,
	font : {
		fontSize : heightt * 0.03,
		fontWeight : 'bold'
	},
	backgroundGradient : {
		type : 'linear',
		colors : ['#698aaa', '#1C4E7E', '#173f6b'],
		startPoint : {
			x : 0,
			y : 0
		},
		endPoint : {
			x : 0,
			y : 36
		},
		backFillStart : false
	},
	borderWidth : 1,
	borderColor : '#112f55'
});
win.add(signUpBtn);
var once=true;
//Method Updated by Amit koranne for remember me.
var flag = Ti.App.Properties.getString('autologin');
if (Ti.App.Properties.getString('autologin') == 'true') {
//	if(once){
	if(Ti.App.Properties.getString('logouted')=='777'){

	emailField.value = "";
	passwordField.value ="";
	Ti.App.Properties.setString('logouted','8888');

	}else{

		emailField.value = Ti.App.Properties.getString('session_email');
	passwordField.value = Ti.App.Properties.getString('session_pass');

	setTimeout(function() {
		loadingIndicator.show();
		//hide method call
		setTimeout(function() {
			loadingIndicator.hide();
		}, 1000);
		login();
	}, 250);

	}
//	}

}

try {
	signUpBtn.addEventListener('click', function(e) {

		e.source.width = widthh * 0.4;
		e.source.height = heightt * 0.07;
		e.source.backgroundGradient = {
			type : 'linear',
			colors : ['#000', '#ffffff'],
			startPoint : {
				x : 0,
				y : 0
			},
			endPoint : {
				x : 0,
				y : 36
			},
			backFillStart : false
		};

		setTimeout(function() {
			e.source.width = widthh * 0.30;
			e.source.height = heightt * 0.06;
			e.source.backgroundGradient = {
				type : 'linear',
				colors : ['#698aaa', '#1C4E7E', '#173f6b'],
				startPoint : {
					x : 0,
					y : 0
				},
				endPoint : {
					x : 0,
					y : 36
				},
				backFillStart : false
			};

		}, 1000);

		Titanium.Platform.openURL('http://chefsheet.com/auth/users/sign_up');
		setTimeout(function() {
			e.source.width = widthh * 0.3;
			e.source.height = heightt * 0.06;
		}, 800);
	});
} catch(e) {
}

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

try {
	signInBtn.addEventListener('click', function(e) {
		try {
			Ti.UI.Android.hideSoftKeyboard();
			setTimeout(function() {
				loadingIndicator.hide();
			}, 500);
		} catch(e) {
		}

		e.source.width = widthh * 0.4;
		e.source.height = heightt * 0.07;
		e.source.backgroundGradient = {
			type : 'linear',
			colors : ['#000', '#ffffff'],
			startPoint : {
				x : 0,
				y : 0
			},
			endPoint : {
				x : 0,
				y : 36
			},
			backFillStart : false
		};

		setTimeout(function() {
			e.source.width = widthh * 0.30;
			e.source.height = heightt * 0.06;
			e.source.backgroundGradient = {
				type : 'linear',
				colors : ['#698aaa', '#1C4E7E', '#173f6b'],
				startPoint : {
					x : 0,
					y : 0
				},
				endPoint : {
					x : 0,
					y : 36
				},
				backFillStart : false
			};

		}, 1000);

		error_shown = false;
		entered = false;
		try {

			myactivityIndicator.hide();

		} catch(exc) {
		} finally {
			if (emailField.value == 'dev' && (passwordField.value == 'true' || passwordField.value == 'false')) {
				switch (passwordField.value) {
					case 'true':
						Ti.App.Properties.setString('developer', true);
						break;
					case 'false':
						Ti.App.Properties.setString('developer', false);
						break;
				}
			} else {

				Ti.App.Properties.setString('autologin', autoLogSwitch.value);

				checkwhether_signin_button_click = true;

				if ((emailField.value.length == 0 ) || (passwordField.value.length == 0))//logic added by yogesh
				{
					alertfillemailpass.show();
				} else//logic added by yogesh
				{

					myactivityIndicator.show();

					//hide method call
					setTimeout(function() {
						myactivityIndicator.hide();
					}, 800);

					login();

				}

			}
		}
		setTimeout(function() {
			e.source.width = widthh * 0.3;
			e.source.height = heightt * 0.06;
		}, 8000);

	});
} catch(e) {
}

function login() {
	try {
		var xhr = Titanium.Network.createHTTPClient();
		xhr.onload = function(e) {
			entered = true;

			var response = JSON.parse(this.responseText);
			Ti.App.Properties.setString('token', response.token);
			Ti.App.Properties.setString('user_name', response.name);
			Ti.App.Properties.setString('user_email', emailField.value);
			Ti.App.Properties.setString('user_pass', passwordField.value);
			Ti.App.Properties.setString('session_email', emailField.value);
			Ti.App.Properties.setString('session_pass', passwordField.value);
			Ti.API.info('user name: ' + response.name);

			if (response.token != undefined) {
				//win.tabGroup.setActiveTab(0);
				setTimeout(function() {
					myactivityIndicator.hide();
					win.close({
						//transition : Titanium.UI.iPhone.AnimationStyle.CURL_UP
					});
				}, 100);
				Ti.App.fireEvent('signedIn');
			} else {
				alert("Email or Password is incorrect");
			}

		};

		xhr.onerror = function(e) {

			Ti.API.info("post error:" + e.error);

			try {
				if (checkwhether_signin_button_click) {

					myactivityIndicator.hide();
				}

			} catch(exception) {
			} finally {
				if (!error_shown) {
					error_shown = true;

					if (checkwhether_signin_button_click) {
						if (Titanium.Network.online) {
							alertwrongemailpass.show();
						} else {
							alertnoInternet.show();
						}
					}	//END logic added by yogesh for removing give alert on load of page
				} //end of if 1
			} //end of finally
		};

		var url = global_url + '/api/v1/tokens.json';
		xhr.open("POST", url);

		xhr.send({
			"email" : emailField.value,
			"password" : passwordField.value
		});

	} catch(e) {
	}

	if(autoLogSwitch.value){
		Ti.App.Properties.setString('valueRemm','1');
		Ti.App.Properties.setString('autologin',true);
	}else{
		Ti.App.Properties.setString('valueRemm','0');
		Ti.App.Properties.setString('autologin',false);
	}

}


text:
package org.keycloak.services.resources;

import org.jboss.logging.Logger;
import org.jboss.resteasy.spi.HttpRequest;
import org.keycloak.ClientConnection;
import org.keycloak.authentication.AuthenticationProcessor;
import org.keycloak.authentication.RequiredActionContext;
import org.keycloak.authentication.RequiredActionContextResult;
import org.keycloak.authentication.RequiredActionFactory;
import org.keycloak.authentication.RequiredActionProvider;
import org.keycloak.authentication.authenticators.browser.AbstractUsernameFormAuthenticator;
import org.keycloak.email.EmailException;
import org.keycloak.email.EmailProvider;
import org.keycloak.events.Details;
import org.keycloak.events.Errors;
import org.keycloak.events.EventBuilder;
import org.keycloak.events.EventType;
import org.keycloak.login.LoginFormsProvider;
import org.keycloak.models.AuthenticationFlowModel;
import org.keycloak.models.ClientModel;
import org.keycloak.models.ClientSessionModel;
import org.keycloak.models.KeycloakSession;
import org.keycloak.models.ModelException;
import org.keycloak.models.ProtocolMapperModel;
import org.keycloak.models.RealmModel;
import org.keycloak.models.RoleModel;
import org.keycloak.models.UserConsentModel;
import org.keycloak.models.UserCredentialModel;
import org.keycloak.models.UserModel;
import org.keycloak.models.UserModel.RequiredAction;
import org.keycloak.models.UserSessionModel;
import org.keycloak.models.utils.CredentialValidation;
import org.keycloak.models.utils.FormMessage;
import org.keycloak.protocol.LoginProtocol;
import org.keycloak.protocol.RestartLoginCookie;
import org.keycloak.protocol.oidc.TokenManager;
import org.keycloak.services.ErrorPage;
import org.keycloak.services.Urls;
import org.keycloak.services.managers.AuthenticationManager;
import org.keycloak.services.managers.ClientSessionCode;
import org.keycloak.services.messages.Messages;
import org.keycloak.services.util.CookieHelper;
import org.keycloak.services.validation.Validation;
import org.keycloak.util.Time;

import javax.ws.rs.Consumes;
import javax.ws.rs.GET;
import javax.ws.rs.POST;
import javax.ws.rs.Path;
import javax.ws.rs.QueryParam;
import javax.ws.rs.WebApplicationException;
import javax.ws.rs.core.Context;
import javax.ws.rs.core.Cookie;
import javax.ws.rs.core.HttpHeaders;
import javax.ws.rs.core.MediaType;
import javax.ws.rs.core.MultivaluedMap;
import javax.ws.rs.core.Response;
import javax.ws.rs.core.UriBuilder;
import javax.ws.rs.core.UriInfo;
import javax.ws.rs.ext.Providers;
import java.util.List;
import java.util.concurrent.TimeUnit;

/**
 * @author Stian Thorgersen
 */
public class LoginActionsService {

    protected static final Logger logger = Logger.getLogger(LoginActionsService.class);

    public static final String ACTION_COOKIE = "KEYCLOAK_ACTION";
    public static final String AUTHENTICATE_PATH = "authenticate";
    public static final String REGISTRATION_PATH = "registration";
    public static final String RESET_CREDENTIALS_PATH = "reset-credentials";

    private RealmModel realm;

    @Context
    private HttpRequest request;

    @Context
    protected HttpHeaders headers;

    @Context
    private UriInfo uriInfo;

    @Context
    private ClientConnection clientConnection;

    @Context
    protected Providers providers;

    @Context
    protected KeycloakSession session;

    private AuthenticationManager authManager;

    private EventBuilder event;

    public static UriBuilder loginActionsBaseUrl(UriInfo uriInfo) {
        UriBuilder baseUriBuilder = uriInfo.getBaseUriBuilder();
        return loginActionsBaseUrl(baseUriBuilder);
    }

    public static UriBuilder authenticationFormProcessor(UriInfo uriInfo) {
        return loginActionsBaseUrl(uriInfo).path(LoginActionsService.class, "authenticateForm");
    }

    public static UriBuilder requiredActionProcessor(UriInfo uriInfo) {
        return loginActionsBaseUrl(uriInfo).path(LoginActionsService.class, "requiredActionPOST");
    }

    public static UriBuilder registrationFormProcessor(UriInfo uriInfo) {
        return loginActionsBaseUrl(uriInfo).path(LoginActionsService.class, "processRegister");
    }

    public static UriBuilder loginActionsBaseUrl(UriBuilder baseUriBuilder) {
        return baseUriBuilder.path(RealmsResource.class).path(RealmsResource.class, "getLoginActionsService");
    }

    public LoginActionsService(RealmModel realm, AuthenticationManager authManager, EventBuilder event) {
        this.realm = realm;
        this.authManager = authManager;
        this.event = event;
    }

    private boolean checkSsl() {
        if (uriInfo.getBaseUri().getScheme().equals("https")) {
            return true;
        } else {
            return !realm.getSslRequired().isRequired(clientConnection);
        }
    }

    private class Checks {
        ClientSessionCode clientCode;
        Response response;

        boolean verifyCode(String code, String requiredAction) {
            if (!verifyCode(code)) {
                return false;
            } else if (!clientCode.isValidAction(requiredAction)) {
                event.client(clientCode.getClientSession().getClient());
                event.error(Errors.INVALID_CODE);
                response = ErrorPage.error(session, Messages.INVALID_CODE);
                return false;
            } else if (!clientCode.isActionActive(requiredAction)) {
                event.client(clientCode.getClientSession().getClient());
                event.clone().error(Errors.EXPIRED_CODE);
                if (clientCode.getClientSession().getAction().equals(ClientSessionModel.Action.AUTHENTICATE.name())) {
                    AuthenticationProcessor.resetFlow(clientCode.getClientSession());
                    response = processAuthentication(null, clientCode.getClientSession(), Messages.LOGIN_TIMEOUT);
                    return false;
                }
                response = ErrorPage.error(session, Messages.EXPIRED_CODE);
                return false;
            } else {
                return true;
            }
        }

        boolean verifyCode(String code, String requiredAction, String alternativeRequiredAction) {
            if (!verifyCode(code)) {
                return false;
            } else if (!(clientCode.isValidAction(requiredAction) || clientCode.isValidAction(alternativeRequiredAction))) {
                event.client(clientCode.getClientSession().getClient());
                event.error(Errors.INVALID_CODE);
                response = ErrorPage.error(session, Messages.INVALID_CODE);
                return false;
            } else if (!(clientCode.isActionActive(requiredAction) || clientCode.isActionActive(alternativeRequiredAction))) {
                event.client(clientCode.getClientSession().getClient());
                event.clone().error(Errors.EXPIRED_CODE);
                if (clientCode.getClientSession().getAction().equals(ClientSessionModel.Action.AUTHENTICATE.name())) {
                    AuthenticationProcessor.resetFlow(clientCode.getClientSession());
                    response = processAuthentication(null, clientCode.getClientSession(), Messages.LOGIN_TIMEOUT);
                } else {
                    if (clientCode.getClientSession().getUserSession() == null) {
                        session.sessions().removeClientSession(realm, clientCode.getClientSession());
                    }
                    response = ErrorPage.error(session, Messages.EXPIRED_CODE);
                }
                return false;
            } else {
                return true;
            }
        }

        public boolean verifyCode(String code) {
            if (!checkSsl()) {
                event.error(Errors.SSL_REQUIRED);
                response = ErrorPage.error(session, Messages.HTTPS_REQUIRED);
                return false;
            }
            if (!realm.isEnabled()) {
                event.error(Errors.REALM_DISABLED);
                response = ErrorPage.error(session, Messages.REALM_NOT_ENABLED);
                return false;
            }
            ClientSessionCode.ParseResult result = ClientSessionCode.parseResult(code, session, realm);
            clientCode = result.getCode();
            if (clientCode == null) {
                if (result.isClientSessionNotFound()) { // timeout
                    try {
                        ClientSessionModel clientSession = RestartLoginCookie.restartSession(session, realm, code);
                        if (clientSession != null) {
                            event.clone().detail(Details.RESTART_AFTER_TIMEOUT, "true").error(Errors.EXPIRED_CODE);
                            response = processFlow(null, clientSession, AUTHENTICATE_PATH, realm.getBrowserFlow(), Messages.LOGIN_TIMEOUT);
                            return false;
                        }
                    } catch (Exception e) {
                        logger.error("failed to parse RestartLoginCookie", e);
                    }
                }
                event.error(Errors.INVALID_CODE);
                response = ErrorPage.error(session, Messages.INVALID_CODE);
                return false;
            }
            ClientSessionModel clientSession = clientCode.getClientSession();
            if (clientSession == null) {
                event.error(Errors.INVALID_CODE);
                response = ErrorPage.error(session, Messages.INVALID_CODE);
                return false;
            }
            event.detail(Details.CODE_ID, clientSession.getId());
            ClientModel client = clientSession.getClient();
            if (client == null) {
                event.error(Errors.CLIENT_NOT_FOUND);
                response = ErrorPage.error(session, Messages.UNKNOWN_LOGIN_REQUESTER);
                session.sessions().removeClientSession(realm, clientSession);
                return false;
            }
            if (!client.isEnabled()) {
                event.error(Errors.CLIENT_NOT_FOUND);
                response = ErrorPage.error(session, Messages.LOGIN_REQUESTER_NOT_ENABLED);
                session.sessions().removeClientSession(realm, clientSession);
                return false;
            }
            session.getContext().setClient(client);
            return true;
        }
    }

    /**
     * protocol independent login page entry point
     *
     * @param code
     * @return
     */
    @Path(AUTHENTICATE_PATH)
    @GET
    public Response authenticate(@QueryParam("code") String code,
                                 @QueryParam("execution") String execution) {
        event.event(EventType.LOGIN);
        Checks checks = new Checks();
        if (!checks.verifyCode(code, ClientSessionModel.Action.AUTHENTICATE.name())) {
            return checks.response;
        }
        event.detail(Details.CODE_ID, code);
        ClientSessionCode clientSessionCode = checks.clientCode;
        ClientSessionModel clientSession = clientSessionCode.getClientSession();

        return processAuthentication(execution, clientSession, null);
    }

    protected Response processAuthentication(String execution, ClientSessionModel clientSession, String errorMessage) {
        return processFlow(execution, clientSession, AUTHENTICATE_PATH, realm.getBrowserFlow(), errorMessage);
    }

    protected Response processFlow(String execution, ClientSessionModel clientSession, String flowPath, AuthenticationFlowModel flow, String errorMessage) {
        AuthenticationProcessor processor = new AuthenticationProcessor();
        processor.setClientSession(clientSession)
                .setFlowPath(flowPath)
                .setFlowId(flow.getId())
                .setConnection(clientConnection)
                .setEventBuilder(event)
                .setProtector(authManager.getProtector())
                .setRealm(realm)
                .setSession(session)
                .setUriInfo(uriInfo)
                .setRequest(request);
        if (errorMessage != null) processor.setForwardedErrorMessage(new FormMessage(null, errorMessage));

        try {
            if (execution != null) {
                return processor.authenticationAction(execution);
            } else {
                return processor.authenticate();
            }
        } catch (Exception e) {
            return processor.handleBrowserException(e);
        }
    }

    /**
     * URL called after login page.  YOU SHOULD NEVER INVOKE THIS DIRECTLY!
     *
     * @param code
     * @return
     */
    @Path(AUTHENTICATE_PATH)
    @POST
    public Response authenticateForm(@QueryParam("code") String code,
                                     @QueryParam("execution") String execution) {
        event.event(EventType.LOGIN);
        Checks checks = new Checks();
        if (!checks.verifyCode(code, ClientSessionModel.Action.AUTHENTICATE.name())) {
            return checks.response;
        }
        final ClientSessionCode clientCode = checks.clientCode;
        final ClientSessionModel clientSession = clientCode.getClientSession();

        return processAuthentication(execution, clientSession, null);
    }

    @Path(RESET_CREDENTIALS_PATH)
    @POST
    public Response resetCredentialsPOST(@QueryParam("code") String code,
                                         @QueryParam("execution") String execution) {
        return resetCredentials(code, execution);
    }

    @Path(RESET_CREDENTIALS_PATH)
    @GET
    public Response resetCredentialsGET(@QueryParam("code") String code,
                                         @QueryParam("execution") String execution) {
        return resetCredentials(code, execution);
    }

    protected Response resetCredentials(String code, String execution) {
        event.event(EventType.RESET_PASSWORD);
        Checks checks = new Checks();
        if (!checks.verifyCode(code, ClientSessionModel.Action.AUTHENTICATE.name())) {
            return checks.response;
        }
        final ClientSessionCode clientCode = checks.clientCode;
        final ClientSessionModel clientSession = clientCode.getClientSession();

        return processResetCredentials(execution, clientSession, null);
    }

    protected Response processResetCredentials(String execution, ClientSessionModel clientSession, String errorMessage) {
        return processFlow(execution, clientSession, RESET_CREDENTIALS_PATH, realm.getResetCredentialsFlow(), errorMessage);
    }

    protected Response processRegistration(String execution, ClientSessionModel clientSession, String errorMessage) {
        return processFlow(execution, clientSession, REGISTRATION_PATH, realm.getRegistrationFlow(), errorMessage);
    }

    /**
     * protocol independent registration page entry point
     *
     * @param code
     * @return
     */
    @Path(REGISTRATION_PATH)
    @GET
    public Response registerPage(@QueryParam("code") String code,
                                 @QueryParam("execution") String execution) {
        event.event(EventType.REGISTER);
        if (!realm.isRegistrationAllowed()) {
            event.error(Errors.REGISTRATION_DISABLED);
            return ErrorPage.error(session, Messages.REGISTRATION_NOT_ALLOWED);
        }

        Checks checks = new Checks();
        if (!checks.verifyCode(code, ClientSessionModel.Action.AUTHENTICATE.name())) {
            return checks.response;
        }
        event.detail(Details.CODE_ID, code);
        ClientSessionCode clientSessionCode = checks.clientCode;
        ClientSessionModel clientSession = clientSessionCode.getClientSession();

        authManager.expireIdentityCookie(realm, uriInfo, clientConnection);

        return processRegistration(execution, clientSession, null);
    }

    /**
     * Registration
     *
     * @param code
     * @return
     */
    @Path(REGISTRATION_PATH)
    @POST
    public Response processRegister(@QueryParam("code") String code,
                                    @QueryParam("execution") String execution) {
        event.event(EventType.REGISTER);
        if (!realm.isRegistrationAllowed()) {
            event.error(Errors.REGISTRATION_DISABLED);
            return ErrorPage.error(session, Messages.REGISTRATION_NOT_ALLOWED);
        }
        Checks checks = new Checks();
        if (!checks.verifyCode(code, ClientSessionModel.Action.AUTHENTICATE.name())) {
            return checks.response;
        }

        ClientSessionCode clientCode = checks.clientCode;
        ClientSessionModel clientSession = clientCode.getClientSession();

        return processRegistration(execution, clientSession, null);
    }

    /**
     * OAuth grant page.  You should not invoked this directly!
     *
     * @param formData
     * @return
     */
    @Path("consent")
    @POST
    @Consumes(MediaType.APPLICATION_FORM_URLENCODED)
    public Response processConsent(final MultivaluedMap<String, String> formData) {
        event.event(EventType.LOGIN).detail(Details.RESPONSE_TYPE, "code");

        if (!checkSsl()) {
            return ErrorPage.error(session, Messages.HTTPS_REQUIRED);
        }

        String code = formData.getFirst("code");

        ClientSessionCode accessCode = ClientSessionCode.parse(code, session, realm);
        if (accessCode == null || !accessCode.isValid(ClientSessionModel.Action.OAUTH_GRANT.name())) {
            event.error(Errors.INVALID_CODE);
            return ErrorPage.error(session, Messages.INVALID_ACCESS_CODE);
        }
        ClientSessionModel clientSession = accessCode.getClientSession();
        event.detail(Details.CODE_ID, clientSession.getId());

        String redirect = clientSession.getRedirectUri();
        UserSessionModel userSession = clientSession.getUserSession();
        UserModel user = userSession.getUser();
        ClientModel client = clientSession.getClient();

        event.client(client)
                .user(user)
                .detail(Details.RESPONSE_TYPE, "code")
                .detail(Details.REDIRECT_URI, redirect);

        event.detail(Details.AUTH_METHOD, userSession.getAuthMethod());
        event.detail(Details.USERNAME, userSession.getLoginUsername());
        if (userSession.isRememberMe()) {
            event.detail(Details.REMEMBER_ME, "true");
        }

        if (!AuthenticationManager.isSessionValid(realm, userSession)) {
            AuthenticationManager.backchannelLogout(session, realm, userSession, uriInfo, clientConnection, headers, true);
            event.error(Errors.INVALID_CODE);
            return ErrorPage.error(session, Messages.SESSION_NOT_ACTIVE);
        }
        event.session(userSession);

        if (formData.containsKey("cancel")) {
            LoginProtocol protocol = session.getProvider(LoginProtocol.class, clientSession.getAuthMethod());
            protocol.setRealm(realm)
                    .setHttpHeaders(headers)
                    .setUriInfo(uriInfo);
            event.error(Errors.REJECTED_BY_USER);
            return protocol.consentDenied(clientSession);
        }

        UserConsentModel grantedConsent = user.getConsentByClient(client.getId());
        if (grantedConsent == null) {
            grantedConsent = new UserConsentModel(client);
            user.addConsent(grantedConsent);
        }
        for (RoleModel role : accessCode.getRequestedRoles()) {
            grantedConsent.addGrantedRole(role);
        }
        for (ProtocolMapperModel protocolMapper : accessCode.getRequestedProtocolMappers()) {
            if (protocolMapper.isConsentRequired() && protocolMapper.getConsentText() != null) {
                grantedConsent.addGrantedProtocolMapper(protocolMapper);
            }
        }
        user.updateConsent(grantedConsent);

        event.detail(Details.CONSENT, Details.CONSENT_VALUE_CONSENT_GRANTED);
        event.success();

        return authManager.redirectAfterSuccessfulFlow(session, realm, userSession, clientSession, request, uriInfo, clientConnection);
    }

    @Path("email-verification")
    @GET
    public Response emailVerification(@QueryParam("code") String code, @QueryParam("key") String key) {
        event.event(EventType.VERIFY_EMAIL);
        if (key != null) {
            Checks checks = new Checks();
            if (!checks.verifyCode(key, ClientSessionModel.Action.VERIFY_EMAIL.name())) {
                return checks.response;
            }
            ClientSessionCode accessCode = checks.clientCode;
            ClientSessionModel clientSession = accessCode.getClientSession();
            UserSessionModel userSession = clientSession.getUserSession();
            UserModel user = userSession.getUser();
            initEvent(clientSession);
            user.setEmailVerified(true);

            user.removeRequiredAction(RequiredAction.VERIFY_EMAIL);

            event.event(EventType.VERIFY_EMAIL).detail(Details.EMAIL, user.getEmail()).success();

            String actionCookieValue = getActionCookie();
            if (actionCookieValue == null || !actionCookieValue.equals(userSession.getId())) {
                session.sessions().removeClientSession(realm, clientSession);
                return session.getProvider(LoginFormsProvider.class)
                        .setSuccess(Messages.EMAIL_VERIFIED)
                        .createInfoPage();
            }

            event = event.clone().removeDetail(Details.EMAIL).event(EventType.LOGIN);

            return AuthenticationManager.nextActionAfterAuthentication(session, userSession, clientSession, clientConnection, request, uriInfo, event);
        } else {
            Checks checks = new Checks();
            if (!checks.verifyCode(code, ClientSessionModel.Action.VERIFY_EMAIL.name())) {
                return checks.response;
            }
            ClientSessionCode accessCode = checks.clientCode;
            ClientSessionModel clientSession = accessCode.getClientSession();
            UserSessionModel userSession = clientSession.getUserSession();
            initEvent(clientSession);

            createActionCookie(realm, uriInfo, clientConnection, userSession.getId());

            return session.getProvider(LoginFormsProvider.class)
                    .setClientSessionCode(accessCode.getCode())
                    .setUser(userSession.getUser())
                    .createResponse(RequiredAction.VERIFY_EMAIL);
        }
    }

    /**
     * Initiated by admin, not the user on login
     *
     * @param key
     * @return
     */
    @Path("execute-actions")
    @GET
    public Response executeActions(@QueryParam("key") String key) {
        event.event(EventType.EXECUTE_ACTIONS);
        if (key != null) {
            Checks checks = new Checks();
            if (!checks.verifyCode(key, ClientSessionModel.Action.EXECUTE_ACTIONS.name())) {
                return checks.response;
            }
            ClientSessionModel clientSession = checks.clientCode.getClientSession();
            clientSession.setNote("END_AFTER_REQUIRED_ACTIONS", "true");
            clientSession.setNote(ClientSessionModel.Action.EXECUTE_ACTIONS.name(), "true");
            return AuthenticationManager.nextActionAfterAuthentication(session, clientSession.getUserSession(), clientSession, clientConnection, request, uriInfo, event);
        } else {
            event.error(Errors.INVALID_CODE);
            return ErrorPage.error(session, Messages.INVALID_CODE);
        }
    }

    private String getActionCookie() {
        Cookie cookie = headers.getCookies().get(ACTION_COOKIE);
        AuthenticationManager.expireCookie(realm, ACTION_COOKIE, AuthenticationManager.getRealmCookiePath(realm, uriInfo), realm.getSslRequired().isRequired(clientConnection), clientConnection);
        return cookie != null ? cookie.getValue() : null;
    }

    public static void createActionCookie(RealmModel realm, UriInfo uriInfo, ClientConnection clientConnection, String sessionId) {
        CookieHelper.addCookie(ACTION_COOKIE, sessionId, AuthenticationManager.getRealmCookiePath(realm, uriInfo), null, null, -1, realm.getSslRequired().isRequired(clientConnection), true);
    }

    private void initEvent(ClientSessionModel clientSession) {
        event.event(EventType.LOGIN).client(clientSession.getClient())
                .user(clientSession.getUserSession().getUser())
                .session(clientSession.getUserSession().getId())
                .detail(Details.CODE_ID, clientSession.getId())
                .detail(Details.REDIRECT_URI, clientSession.getRedirectUri())
                .detail(Details.USERNAME, clientSession.getNote(AbstractUsernameFormAuthenticator.ATTEMPTED_USERNAME))
                .detail(Details.RESPONSE_TYPE, "code");

        UserSessionModel userSession = clientSession.getUserSession();

        if (userSession != null) {
            event.detail(Details.AUTH_METHOD, userSession.getAuthMethod());
            event.detail(Details.USERNAME, userSession.getLoginUsername());
            if (userSession.isRememberMe()) {
                event.detail(Details.REMEMBER_ME, "true");
            }
        }
    }

    @Path("required-action")
    @POST
    public Response requiredActionPOST(@QueryParam("code") final String code,
                                       @QueryParam("action") String action) {
        return processRequireAction(code, action);

    }

    @Path("required-action")
    @GET
    public Response requiredActionGET(@QueryParam("code") final String code,
                                       @QueryParam("action") String action) {
        return processRequireAction(code, action);
    }

    public Response processRequireAction(final String code, String action) {
        event.event(EventType.CUSTOM_REQUIRED_ACTION);
        event.detail(Details.CUSTOM_REQUIRED_ACTION, action);
        if (action == null) {
            logger.error("required action query param was null");
            event.error(Errors.INVALID_CODE);
            throw new WebApplicationException(ErrorPage.error(session, Messages.INVALID_CODE));

        }

        RequiredActionFactory factory = (RequiredActionFactory)session.getKeycloakSessionFactory().getProviderFactory(RequiredActionProvider.class, action);
        if (factory == null) {
            logger.error("required action provider was null");
            event.error(Errors.INVALID_CODE);
            throw new WebApplicationException(ErrorPage.error(session, Messages.INVALID_CODE));
        }
        RequiredActionProvider provider = factory.create(session);
        Checks checks = new Checks();
        if (!checks.verifyCode(code, action)) {
            return checks.response;
        }
        final ClientSessionCode clientCode = checks.clientCode;
        final ClientSessionModel clientSession = clientCode.getClientSession();

        if (clientSession.getUserSession() == null) {
            logger.error("user session was null");
            event.error(Errors.USER_SESSION_NOT_FOUND);
            throw new WebApplicationException(ErrorPage.error(session, Messages.SESSION_NOT_ACTIVE));
        }

        initEvent(clientSession);
        event.event(EventType.CUSTOM_REQUIRED_ACTION);

        RequiredActionContextResult context = new RequiredActionContextResult(clientSession.getUserSession(), clientSession, realm, event, session, request, clientSession.getUserSession().getUser(), factory) {
             @Override
            public String generateAccessCode(String action) {
                String clientSessionAction = clientSession.getAction();
                if (action.equals(clientSessionAction)) {
                    clientSession.setTimestamp(Time.currentTime());
                    return code;
                }
                ClientSessionCode code = new ClientSessionCode(getRealm(), getClientSession());
                code.setAction(action);
                return code.getCode();
            }

            @Override
            public void ignore() {
                throw new RuntimeException("Cannot call ignore within processAction()");
            }
        };
        provider.processAction(context);
        if (context.getStatus() == RequiredActionContext.Status.SUCCESS) {
            event.clone().success();
            // do both
            clientSession.removeRequiredAction(factory.getId());
            clientSession.getUserSession().getUser().removeRequiredAction(factory.getId());
            event.event(EventType.LOGIN);
            return AuthenticationManager.nextActionAfterAuthentication(session, clientSession.getUserSession(), clientSession, clientConnection, request, uriInfo, event);
        }
        if (context.getStatus() == RequiredActionContext.Status.CHALLENGE) {
            return context.getChallenge();
        }
        if (context.getStatus() == RequiredActionContext.Status.FAILURE) {
            LoginProtocol protocol = context.getSession().getProvider(LoginProtocol.class, context.getClientSession().getAuthMethod());
            protocol.setRealm(context.getRealm())
                    .setHttpHeaders(context.getHttpRequest().getHttpHeaders())
                    .setUriInfo(context.getUriInfo());
            event.detail(Details.CUSTOM_REQUIRED_ACTION, action).error(Errors.REJECTED_BY_USER);
            return protocol.consentDenied(context.getClientSession());
        }

        throw new RuntimeException("Unreachable");
    }

}


text:
package org.elasticsearch.xpack.ml.filestructurefinder;

import org.elasticsearch.ElasticsearchTimeoutException;
import org.elasticsearch.common.unit.TimeValue;
import org.elasticsearch.grok.Grok;
import org.elasticsearch.threadpool.Scheduler;
import org.joni.Matcher;
import org.junit.After;
import org.junit.Before;

import java.util.concurrent.ScheduledExecutorService;

import static org.hamcrest.Matchers.equalTo;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.verify;

public class TimeoutCheckerTests extends FileStructureTestCase {

    private ScheduledExecutorService scheduler;

    @Before
    public void createScheduler() {
        scheduler = new Scheduler.SafeScheduledThreadPoolExecutor(1);
    }

    @After
    public void shutdownScheduler() {
        scheduler.shutdown();
    }

    public void testCheckNoTimeout() {
        NOOP_TIMEOUT_CHECKER.check("should never happen");
    }

    public void testCheckTimeoutNotExceeded() throws InterruptedException {
        TimeValue timeout = TimeValue.timeValueSeconds(10);
        try (TimeoutChecker timeoutChecker = new TimeoutChecker("timeout not exceeded test", timeout, scheduler)) {
            for (int count = 0; count < 10; ++count) {
                timeoutChecker.check("should not timeout");
                Thread.sleep(randomIntBetween(1, 10));
            }
        }
    }

    public void testCheckTimeoutExceeded() throws Exception {
        TimeValue timeout = TimeValue.timeValueMillis(10);
        try (TimeoutChecker timeoutChecker = new TimeoutChecker("timeout exceeded test", timeout, scheduler)) {
            assertBusy(() -> {
                ElasticsearchTimeoutException e = expectThrows(ElasticsearchTimeoutException.class,
                    () -> timeoutChecker.check("should timeout"));
                assertEquals("Aborting timeout exceeded test during [should timeout] as it has taken longer than the timeout of [" +
                    timeout + "]", e.getMessage());
            });
        }
    }

    @AwaitsFix(bugUrl = "https://github.com/elastic/elasticsearch/issues/48861")
    public void testWatchdog() throws Exception {
        TimeValue timeout = TimeValue.timeValueMillis(500);
        try (TimeoutChecker timeoutChecker = new TimeoutChecker("watchdog test", timeout, scheduler)) {
            TimeoutChecker.TimeoutCheckerWatchdog watchdog = (TimeoutChecker.TimeoutCheckerWatchdog) TimeoutChecker.watchdog;

            Matcher matcher = mock(Matcher.class);
            TimeoutChecker.watchdog.register(matcher);
            assertThat(watchdog.registry.get(Thread.currentThread()).matchers.size(), equalTo(1));
            try {
                assertBusy(() -> {
                    verify(matcher).interrupt();
                });
            } finally {
                TimeoutChecker.watchdog.unregister(matcher);
                assertThat(watchdog.registry.get(Thread.currentThread()).matchers.size(), equalTo(0));
            }
        }
    }

    public void testGrokCaptures() throws Exception {
        Grok grok = new Grok(Grok.getBuiltinPatterns(), "{%DATA:data}{%GREEDYDATA:greedydata}", TimeoutChecker.watchdog, logger::warn);
        TimeValue timeout = TimeValue.timeValueMillis(1);
        try (TimeoutChecker timeoutChecker = new TimeoutChecker("grok captures test", timeout, scheduler)) {

            assertBusy(() -> {
                ElasticsearchTimeoutException e = expectThrows(ElasticsearchTimeoutException.class,
                    () -> timeoutChecker.grokCaptures(grok, randomAlphaOfLength(1000000), "should timeout"));
                assertEquals("Aborting grok captures test during [should timeout] as it has taken longer than the timeout of [" +
                    timeout + "]", e.getMessage());
            });
        }
    }
}


text:
.class final Lcom/android/server/notification/NotificationManagerService$RankingWorkerHandler;
.super Landroid/os/Handler;
.source "NotificationManagerService.java"

# annotations
.annotation system Ldalvik/annotation/EnclosingClass;
    value = Lcom/android/server/notification/NotificationManagerService;
.end annotation

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

# instance fields
.field final synthetic this$0:Lcom/android/server/notification/NotificationManagerService;

# direct methods
.method public constructor <init>(Lcom/android/server/notification/NotificationManagerService;Landroid/os/Looper;)V
    .locals 0
    .param p1, "this$0"    # Lcom/android/server/notification/NotificationManagerService;
    .param p2, "looper"    # Landroid/os/Looper;

    .prologue
    .line 2723
    iput-object p1, p0, Lcom/android/server/notification/NotificationManagerService$RankingWorkerHandler;->this$0:Lcom/android/server/notification/NotificationManagerService;

    .line 2724
    invoke-direct {p0, p2}, Landroid/os/Handler;-><init>(Landroid/os/Looper;)V

    .line 2723
    return-void
.end method

# virtual methods
.method public handleMessage(Landroid/os/Message;)V
    .locals 1
    .param p1, "msg"    # Landroid/os/Message;

    .prologue
    .line 2729
    iget v0, p1, Landroid/os/Message;->what:I

    packed-switch v0, :pswitch_data_0

    .line 2728
    :goto_0
    return-void

    .line 2731
    :pswitch_0
    iget-object v0, p0, Lcom/android/server/notification/NotificationManagerService$RankingWorkerHandler;->this$0:Lcom/android/server/notification/NotificationManagerService;

    invoke-static {v0, p1}, Lcom/android/server/notification/NotificationManagerService;->-wrap19(Lcom/android/server/notification/NotificationManagerService;Landroid/os/Message;)V

    goto :goto_0

    .line 2734
    :pswitch_1
    iget-object v0, p0, Lcom/android/server/notification/NotificationManagerService$RankingWorkerHandler;->this$0:Lcom/android/server/notification/NotificationManagerService;

    invoke-static {v0}, Lcom/android/server/notification/NotificationManagerService;->-wrap18(Lcom/android/server/notification/NotificationManagerService;)V

    goto :goto_0

    .line 2729
    :pswitch_data_0
    .packed-switch 0x4
        :pswitch_0
        :pswitch_1
    .end packed-switch
.end method


text:
package com.caucho.hessian.io.java8;

import java.time.LocalDate;

/**
 * author: Zhang Li
 * created on 15-3-24.
 */
public class LocalDateHandle extends Java8TimeHandle<LocalDate> {
    private static final long serialVersionUID = 166018689500019951L;

    /**
     * The year.
     */
    private int year;
    /**
     * The month-of-year.
     */
    private short month;
    /**
     * The day-of-month.
     */
    private short day;

    public LocalDateHandle() {
    }

    public LocalDateHandle(LocalDate localDate) {
        init(localDate);
    }

    @Override
    public void init(LocalDate localDate) {
        if(localDate == null) {
        }
        this.year = localDate.getYear();
        this.month = (short) localDate.getMonthValue();
        this.day = (short) localDate.getDayOfMonth();
    }

    public LocalDate readResolve() {
        return LocalDate.of(year, month, day);
    }
}


text:
import server from './server'

server('./tmp/tests/apps/app.js')


text:
var forEach = require('../array/virtual/for-each');
var ArrayPrototype = Array.prototype;

module.exports = function (it) {
  var own = it.forEach;
  return it === ArrayPrototype || (it instanceof Array && own === ArrayPrototype.forEach) ? forEach : own;
};


text:
use ::{BroadcastMode, Instruction, MaskReg, MergeMode, Mnemonic, OperandSize, Reg, RoundingMode};
use ::RegType::*;
use ::instruction_def::*;
use ::Operand::*;
use ::Reg::*;
use ::RegScale::*;

fn vpmovqw_1() {
    run_test(&Instruction { mnemonic: Mnemonic::VPMOVQW, operand1: Some(Direct(XMM5)), operand2: Some(Direct(XMM7)), operand3: None, operand4: None, lock: false, rounding_mode: None, merge_mode: Some(MergeMode::Zero), sae: false, mask: Some(MaskReg::K4), broadcast: None }, &[98, 242, 126, 140, 52, 253], OperandSize::Dword)
}

fn vpmovqw_2() {
    run_test(&Instruction { mnemonic: Mnemonic::VPMOVQW, operand1: Some(IndirectScaledIndexed(ESI, ESI, Two, Some(OperandSize::Dword), None)), operand2: Some(Direct(XMM5)), operand3: None, operand4: None, lock: false, rounding_mode: None, merge_mode: None, sae: false, mask: None, broadcast: None }, &[98, 242, 126, 8, 52, 44, 118], OperandSize::Dword)
}

fn vpmovqw_3() {
    run_test(&Instruction { mnemonic: Mnemonic::VPMOVQW, operand1: Some(Direct(XMM21)), operand2: Some(Direct(XMM19)), operand3: None, operand4: None, lock: false, rounding_mode: None, merge_mode: Some(MergeMode::Zero), sae: false, mask: Some(MaskReg::K4), broadcast: None }, &[98, 162, 126, 140, 52, 221], OperandSize::Qword)
}

fn vpmovqw_4() {
    run_test(&Instruction { mnemonic: Mnemonic::VPMOVQW, operand1: Some(Indirect(RDX, Some(OperandSize::Dword), None)), operand2: Some(Direct(XMM4)), operand3: None, operand4: None, lock: false, rounding_mode: None, merge_mode: None, sae: false, mask: None, broadcast: None }, &[98, 242, 126, 8, 52, 34], OperandSize::Qword)
}

fn vpmovqw_5() {
    run_test(&Instruction { mnemonic: Mnemonic::VPMOVQW, operand1: Some(Direct(XMM6)), operand2: Some(Direct(YMM5)), operand3: None, operand4: None, lock: false, rounding_mode: None, merge_mode: Some(MergeMode::Zero), sae: false, mask: Some(MaskReg::K3), broadcast: None }, &[98, 242, 126, 171, 52, 238], OperandSize::Dword)
}

fn vpmovqw_6() {
    run_test(&Instruction { mnemonic: Mnemonic::VPMOVQW, operand1: Some(Indirect(ESI, Some(OperandSize::Qword), None)), operand2: Some(Direct(YMM5)), operand3: None, operand4: None, lock: false, rounding_mode: None, merge_mode: None, sae: false, mask: None, broadcast: None }, &[98, 242, 126, 40, 52, 46], OperandSize::Dword)
}

fn vpmovqw_7() {
    run_test(&Instruction { mnemonic: Mnemonic::VPMOVQW, operand1: Some(Direct(XMM25)), operand2: Some(Direct(YMM3)), operand3: None, operand4: None, lock: false, rounding_mode: None, merge_mode: Some(MergeMode::Zero), sae: false, mask: Some(MaskReg::K3), broadcast: None }, &[98, 146, 126, 171, 52, 217], OperandSize::Qword)
}

fn vpmovqw_8() {
    run_test(&Instruction { mnemonic: Mnemonic::VPMOVQW, operand1: Some(Indirect(RDI, Some(OperandSize::Qword), None)), operand2: Some(Direct(YMM0)), operand3: None, operand4: None, lock: false, rounding_mode: None, merge_mode: None, sae: false, mask: None, broadcast: None }, &[98, 242, 126, 40, 52, 7], OperandSize::Qword)
}

fn vpmovqw_9() {
    run_test(&Instruction { mnemonic: Mnemonic::VPMOVQW, operand1: Some(Direct(XMM5)), operand2: Some(Direct(ZMM6)), operand3: None, operand4: None, lock: false, rounding_mode: None, merge_mode: Some(MergeMode::Zero), sae: false, mask: Some(MaskReg::K3), broadcast: None }, &[98, 242, 126, 203, 52, 245], OperandSize::Dword)
}

fn vpmovqw_10() {
    run_test(&Instruction { mnemonic: Mnemonic::VPMOVQW, operand1: Some(Indirect(EDI, Some(OperandSize::Xmmword), None)), operand2: Some(Direct(ZMM1)), operand3: None, operand4: None, lock: false, rounding_mode: None, merge_mode: None, sae: false, mask: None, broadcast: None }, &[98, 242, 126, 72, 52, 15], OperandSize::Dword)
}

fn vpmovqw_11() {
    run_test(&Instruction { mnemonic: Mnemonic::VPMOVQW, operand1: Some(Direct(XMM9)), operand2: Some(Direct(ZMM20)), operand3: None, operand4: None, lock: false, rounding_mode: None, merge_mode: Some(MergeMode::Zero), sae: false, mask: Some(MaskReg::K1), broadcast: None }, &[98, 194, 126, 201, 52, 225], OperandSize::Qword)
}

fn vpmovqw_12() {
    run_test(&Instruction { mnemonic: Mnemonic::VPMOVQW, operand1: Some(IndirectScaledIndexedDisplaced(RBX, RAX, Four, 1128586651, Some(OperandSize::Xmmword), None)), operand2: Some(Direct(ZMM12)), operand3: None, operand4: None, lock: false, rounding_mode: None, merge_mode: None, sae: false, mask: None, broadcast: None }, &[98, 114, 126, 72, 52, 164, 131, 155, 221, 68, 67], OperandSize::Qword)
}


text:
<?php
/**
 *   @file AzListSubjects.php
 *   @brief
 *   @author little9 (Jamie Little)
 *   @date Auguest 2015
 */
namespace SubjectsPlus\Control\Databases;

class AzListSubjects extends AzList {

	public function toArray() {

		$connection = $this->connection;

		$statement = $connection->prepare ( "SELECT subject, subject_id FROM subject WHERE active = '1' ORDER BY subject" );

		$statement->bindParam ( ":qualifer", $letter );
		$statement->execute ();
		$r = $statement->fetchAll ( $this->default_fetch );

		return $r;
	}

	public function toJSON() {
		return json_encode ( self::outputArray() );

	}

}


text:
class WebBinder
  module Downloading
    DEFAULT_EACH_SLEEP_TIME = 5

    def download
      clear! if get(:clear_before_downloading)
      get(:sources).each.with_index(0) do |source, idx|
        open(save_path(source), "wb").write(connection.get(source).body)
        if idx < get(:sources).size
          sleep get(:each_sleep_time) || DEFAULT_EACH_SLEEP_TIME
        end
      end
    end

    def clear!
      FileUtils.rm_rf(get(:download_directory))
      @yet = false
    end

    private

    UNSAFE_FILENAME_CHARS = /<|>|:|"|\\|\||\?|\*/

    def connection
      return @connection if @connection
      @connection = Faraday.new do |builder|
        builder.use FaradayMiddleware::FollowRedirects
        builder.adapter :net_http
      end
      @connection.headers = { "User-Agent" => get(:user_agent) } if get(:user_agent)
      @connection
    end

    def save_directory(source)
      split = URI.split(source)
      File.join(get(:download_directory), split[2], split[5].gsub(UNSAFE_FILENAME_CHARS, "_"))
    end

    def save_filename(source)
      uri = URI.parse(source)
      basename = File.basename(source)
      basename = "index.html" if uri.host == basename
      basename += ".html" if basename !~ /\./
      basename.gsub(UNSAFE_FILENAME_CHARS, "_")
    end

    def save_path(source)
      _ = File.join(save_directory(source), save_filename(source))
      filename = FileName.new(_[0, 100], :add => :auto, :type => :time, :directory => :parent)
      filename.create
    end
  end
end


text:
var LegendViewBase = require('../../../../../../src/geo/ui/legends/base/legend-view-base.js');
var LegendModelBase = require('../../../../../../src/geo/map/legends/legend-model-base.js');
var MockFactory = require('../../../../../helpers/mockFactory');

var MyLegendModel = LegendModelBase.extend({
  TYPE: 'something',

  isAvailable: function () {
    return true;
  }
});

var MyLegendView = LegendViewBase.extend({
  _getCompiledTemplate: function () {
    return '
It Works!
';
  }
});

describe('geo/ui/legends/legend-view-base.js', function () {
  var engineMock;
  beforeEach(function () {
    engineMock = MockFactory.createEngine();
    this.model = new MyLegendModel({
      title: 'My Beautiful Legend',
      preHTMLSnippet: '
before
',
      postHTMLSnippet: '
after
',
      visible: true
    }, {
      engine: engineMock
    });

    this.myLegend = new MyLegendView({
      model: this.model,
      placeholderTemplate: function () {
        return '
Placeholder
';
      }
    });
  });

  describe('if model is loading', function () {
    beforeEach(function () {
      this.model.set('state', 'loading');
      this.myLegend.render();
    });

    it('should mark legend as loading', function () {
      expect(this.myLegend.$el.hasClass('is-loading')).toBeTruthy();
    });

    it('should only render a placeholder', function () {
      expect(this.myLegend.$el.html()).toEqual('
Placeholder
');
    });
  });

  describe('if model has errors', function () {
    beforeEach(function () {
      this.model.set('state', 'error');
      this.myLegend.render();
    });

    it('should NOT mark legend as loading', function () {
      expect(this.myLegend.$el.hasClass('is-loading')).toBeFalsy();
    });

    it('should render a placeholder', function () {
      expect(this.myLegend.$el.html()).toMatch('Placeholder');
    });

    it('should render an error', function () {
      expect(this.myLegend.$el.html()).toMatch('Something went wrong');
    });
  });

  describe('if model has been loaded and has no data', function () {
    beforeEach(function () {
      this.model.set('state', 'success');
      spyOn(this.model, 'isAvailable').and.returnValue(false);
      this.myLegend.render();
    });

    it('should NOT mark legend as loading', function () {
      expect(this.myLegend.$el.hasClass('is-loading')).toBeFalsy();
    });

    it('should render a placeholder', function () {
      expect(this.myLegend.$el.html()).toMatch('Placeholder');
    });

    it('should render a warning', function () {
      expect(this.myLegend.$el.html()).toMatch('No data available');
    });
  });

  describe('if model has been loaded and has data', function () {
    beforeEach(function () {
      this.model.set('state', 'success');
      this.myLegend.render();
    });

    it('should NOT mark legend as loading', function () {
      expect(this.myLegend.$el.hasClass('is-loading')).toBeFalsy();
    });

    it('should NOT render a placeholder', function () {
      expect(this.myLegend.$el.html()).not.toMatch('Placeholder');
    });

    it('should render properly', function () {
      var html = this.myLegend.$el.html().split('\n');
      expect(html[0]).toMatch('My Beautiful Legend');
      expect(html[1]).toEqual('
before
');
      expect(html[2]).toEqual('
It Works!
');
      expect(html[3]).toEqual('
after
');
    });

    it('should sanitize preHTMLSnippet, compiled template and postHTMLSnippet', function () {
      this.model.set({
        preHTMLSnippet: '
before
',
        postHTMLSnippet: '
after
'
      });

      spyOn(this.myLegend, '_getCompiledTemplate').and.returnValue('
It Works!
');

      this.myLegend.render();

      var html = this.myLegend.$el.html().split('\n');
      expect(html[1]).toEqual('
before
');
      expect(html[2]).toEqual('
It Works!
');
      expect(html[3]).toEqual('
after
');
    });
  });
});


text:
import time
import smtplib
import logging

from mailer.lockfile import FileLock, AlreadyLocked, LockTimeout
from socket import error as socket_error

from django.conf import settings
from django.core.mail import send_mail as core_send_mail
try:
    # Django 1.2
    from django.core.mail import get_connection
except ImportError:
    # ImportError: cannot import name get_connection
    from django.core.mail import SMTPConnection
    get_connection = lambda backend=None, fail_silently=False, **kwds: SMTPConnection(fail_silently=fail_silently)

from mailer.models import Message, DontSendEntry, MessageLog

# when queue is empty, how long to wait (in seconds) before checking again
EMPTY_QUEUE_SLEEP = getattr(settings, "MAILER_EMPTY_QUEUE_SLEEP", 30)

# lock timeout value. how long to wait for the lock to become available.
# default behavior is to never wait for the lock to be available.
LOCK_WAIT_TIMEOUT = getattr(settings, "MAILER_LOCK_WAIT_TIMEOUT", -1)

def prioritize():
    """
    Yield the messages in the queue in the order they should be sent.
    """

    while True:
        while Message.objects.high_priority().using('default').count() or Message.objects.medium_priority().using('default').count():
            while Message.objects.high_priority().using('default').count():
                for message in Message.objects.high_priority().using('default').order_by("when_added"):
                    yield message
            while Message.objects.high_priority().using('default').count() == 0 and Message.objects.medium_priority().using('default').count():
                yield Message.objects.medium_priority().using('default').order_by("when_added")[0]
        while Message.objects.high_priority().using('default').count() == 0 and Message.objects.medium_priority().using('default').count() == 0 and Message.objects.low_priority().using('default').count():
            yield Message.objects.low_priority().using('default').order_by("when_added")[0]
        if Message.objects.non_deferred().using('default').count() == 0:
            break

def send_all():
    """
    Send all eligible messages in the queue.
    """
    # The actual backend to use for sending, defaulting to the Django default.
    # To make testing easier this is not stored at module level.
    EMAIL_BACKEND = getattr(settings, "MAILER_EMAIL_BACKEND", "django.core.mail.backends.smtp.EmailBackend")

    lock = FileLock(getattr(settings, "MAILER_SEND_MAIL_LOCK", "send_mail"))

    logging.debug("acquiring lock...")
    try:
        lock.acquire(LOCK_WAIT_TIMEOUT)
    except AlreadyLocked:
        logging.debug("lock already in place. quitting.")
        return
    except LockTimeout:
        logging.debug("waiting for the lock timed out. quitting.")
        return
    logging.debug("acquired.")

    start_time = time.time()

    dont_send = 0
    deferred = 0
    sent = 0

    try:
        connection = None
        for message in prioritize():
            try:
                if connection is None:
                    connection = get_connection(backend=EMAIL_BACKEND)
                logging.info("sending message '%s' to %s" % (message.subject.encode("utf-8"), u", ".join(message.to_addresses).encode("utf-8")))
                if message.subject.encode("utf-8").find("edit-tweet") > 0:
                    print "skipped"
                else:
                    email = message.email
                    email.connection = connection
                    email.send()
                    MessageLog.objects.log(message, 1) # @@@ avoid using literal result code
                    sent += 1

                message.delete()

            except (socket_error, smtplib.SMTPSenderRefused, smtplib.SMTPRecipientsRefused, smtplib.SMTPAuthenticationError) as err:
                message.defer()
                logging.info("message deferred due to failure: %s" % err)
                MessageLog.objects.log(message, 3, log_message=str(err)) # @@@ avoid using literal result code
                deferred += 1
                # Get new connection, it case the connection itself has an error.
                connection = None
    finally:
        logging.debug("releasing lock...")
        lock.release()
        logging.debug("released.")

    logging.info("")
    logging.info("%s sent; %s deferred;" % (sent, deferred))
    logging.info("done in %.2f seconds" % (time.time() - start_time))

def send_loop():
    """
    Loop indefinitely, checking queue at intervals of EMPTY_QUEUE_SLEEP and
    sending messages if any are on queue.
    """

    while True:
        while not Message.objects.all():
            logging.debug("sleeping for %s seconds before checking queue again" % EMPTY_QUEUE_SLEEP)
            time.sleep(EMPTY_QUEUE_SLEEP)
        send_all()


text:
package org.apache.solr.schema;

import org.apache.solr.SolrTestCaseJ4;
import org.junit.BeforeClass;

public class TestOmitPositions extends SolrTestCaseJ4 {
  @BeforeClass
  public static void beforeClass() throws Exception {
    initCore("solrconfig.xml", "schema.xml");
    // add some docs
    assertU(
        adoc(
            "id",
            "1",
            "nopositionstext",
            "this is a test this is only a test",
            "text",
            "just another test"));
    assertU(
        adoc(
            "id",
            "2",
            "nopositionstext",
            "test test test test test test test test test test test test test",
            "text",
            "have a nice day"));
    assertU(commit());
  }

  public void testFrequencies() {
    // doc 2 should be ranked above doc 1
    assertQ(
        "term query: ",
        req("fl", "id", "q", "nopositionstext:test"),
        "//*[@numFound='2']",
        "//result/doc[1]/str[@name='id'][.=2]",
        "//result/doc[2]/str[@name='id'][.=1]");
  }

  public void testPositions() {
    // no results should be found:
    // lucene 3.x: silent failure
    // lucene 4.x: illegal state exception, field was indexed without positions

    ignoreException("was indexed without position data");
    try {
      assertQ(
          "phrase query: ",
          req("fl", "id", "q", "nopositionstext:\"test test\""),
          "//*[@numFound='0']");
    } catch (Exception expected) {
      assertTrue(expected.getCause() instanceof IllegalStateException);
      // in lucene 4.0, queries don't silently fail
    }
    resetExceptionIgnores();
  }
}


text:
release:
	cp install_src install
	echo 'rm -- "$$0"' >> install
	tar -cvf sshall.tar.gz install ec2sshpanes terminator-split/terminator-split requirements.txt
	rm install


text:
from .integration_account_resource import IntegrationAccountResource

class IntegrationAccountSchema(IntegrationAccountResource):
    """IntegrationAccountSchema.

    Variables are only populated by the server, and will be ignored when
    sending a request.

    :param id: The resource id.
    :type id: str
    :param name: The resource name.
    :type name: str
    :param type: The resource type.
    :type type: str
    :param location: The resource location.
    :type location: str
    :param tags: The resource tags.
    :type tags: dict
    :param schema_type: The schema type. Possible values include:
     'NotSpecified', 'Xml'
    :type schema_type: str or :class:`SchemaType
     <azure.mgmt.logic.models.SchemaType>`
    :param target_namespace: The target namespace.
    :type target_namespace: str
    :ivar created_time: The created time.
    :vartype created_time: datetime
    :ivar changed_time: The changed time.
    :vartype changed_time: datetime
    :param content: The content.
    :type content: object
    :param content_type: The content type.
    :type content_type: str
    :ivar content_link: The content link.
    :vartype content_link: :class:`IntegrationAccountContentLink
     <azure.mgmt.logic.models.IntegrationAccountContentLink>`
    :param metadata: The metadata.
    :type metadata: object
    """

    _validation = {
        'created_time': {'readonly': True},
        'changed_time': {'readonly': True},
        'content_link': {'readonly': True},
    }

    _attribute_map = {
        'id': {'key': 'id', 'type': 'str'},
        'name': {'key': 'name', 'type': 'str'},
        'type': {'key': 'type', 'type': 'str'},
        'location': {'key': 'location', 'type': 'str'},
        'tags': {'key': 'tags', 'type': '{str}'},
        'schema_type': {'key': 'properties.schemaType', 'type': 'SchemaType'},
        'target_namespace': {'key': 'properties.targetNamespace', 'type': 'str'},
        'created_time': {'key': 'properties.createdTime', 'type': 'iso-8601'},
        'changed_time': {'key': 'properties.changedTime', 'type': 'iso-8601'},
        'content': {'key': 'properties.content', 'type': 'object'},
        'content_type': {'key': 'properties.contentType', 'type': 'str'},
        'content_link': {'key': 'properties.contentLink', 'type': 'IntegrationAccountContentLink'},
        'metadata': {'key': 'properties.metadata', 'type': 'object'},
    }

    def __init__(self, id=None, name=None, type=None, location=None, tags=None, schema_type=None, target_namespace=None, content=None, content_type=None, metadata=None):
        super(IntegrationAccountSchema, self).__init__(id=id, name=name, type=type, location=location, tags=tags)
        self.schema_type = schema_type
        self.target_namespace = target_namespace
        self.created_time = None
        self.changed_time = None
        self.content = content
        self.content_type = content_type
        self.content_link = None
        self.metadata = metadata


text:
package sts

import (
	"github.com/aws/aws-sdk-go/internal/features/shared"
	"github.com/aws/aws-sdk-go/service/sts"
	. "github.com/lsegal/gucumber"
)

var _ = shared.Imported

func init() {
	Before("@sts", func() {
		World["client"] = sts.New(nil)
	})
}


text:
What is Coding?
===============

It can be hard to describe what coding is -- it covers everything from
working with punch cards, to machine code, to assembler, to C, to
dynamic languages like Python, and to complex spreadsheets and
workflows.

Start by simply answering "What is coding?" off the top of your
head. Discuss your answers and then look for more answers.

Answers seen at dojo sessions so far
------------------------------------

* Writing instructions to execute a task that is not humanly possible.
* Things humans can't do:
* Interogating databases with millions of rows.
* Making things faster.
* More exact.
* A tool.
* Using words to tell the computer what to do.
* Code is like a rulebook.
* Commands are stored in a library.
* Programming is like inventing a language.
* Code as a craft (like woodworking).
* Code as writing a recipe (like baking).

Is coding just about writing code? Or also about reading it?


text:
% bup-ftp(1) Bup %BUP_VERSION%
% Avery Pennarun <apenwarr@gmail.com>
% %BUP_DATE%

# NAME

bup-ftp - ftp-like client for navigating bup repositories

# SYNOPSIS

bup ftp

# DESCRIPTION

`bup ftp` is a command-line tool for navigating bup
repositories.  It has commands similar to the Unix `ftp`(1)
command.  The file hierarchy is the same as that shown by
`bup-fuse`(1) and `bup-ls`(1).

Note: if your system has the python-readline library
installed, you can use the \<tab\> key to complete filenames
while navigating your backup data.  This will save you a
lot of typing.

# COMMANDS

The following commands are available inside `bup ftp`:

ls [-s] [-a] [*path*]
:   print the contents of a directory. If no path argument
    is given, the current directory's contents are listed.
    If -a is given, also include hidden files (files which
    start with a `.` character). If -s is given, each file
    is displayed with its hash from the bup archive to its
    left.

cd *dirname*
:   change to a different working directory

pwd
:   print the path of the current working directory

cat *filenames...*
:   print the contents of one or more files to stdout

get *filename* *localname*
:   download the contents of *filename* and save it to disk
    as *localname*.  If *localname* is omitted, uses
    *filename* as the local name.

mget *filenames...*
:   download the contents of the given *filenames* and
    stores them to disk under the same names.  The
    filenames may contain Unix filename globs (`*`, `?`,
    etc.)

help
:   print a list of available commands

quit
:   exit the `bup ftp` client

# EXAMPLE

    $ bup ftp
    bup> ls
    mybackup/    yourbackup/

    bup> cd mybackup/
    bup> ls
    2010-02-05-185507@   2010-02-05-185508@    latest@

    bup> cd latest/
    bup> ls
      (...etc...)

    bup> get myfile
    Saving 'myfile'
    bup> quit

# SEE ALSO

`bup-fuse`(1), `bup-ls`(1), `bup-save`(1), `bup-restore`(1)

# BUP

Part of the `bup`(1) suite.


text:
@implementation PXBackgroundTableHeader

- (id)initWithFrame:(NSRect)frameRect {
	if ((self = [super initWithFrame:frameRect])) {
		[self setButtonType:NSMomentaryChangeButton];
		self.bezelStyle = NSThickSquareBezelStyle;
	}
	return self;
}

- (void)mouseDown:(NSEvent *)event
{
	// don't make the button highlight
}

- (void)_windowChangedKeyState
{
	// don't make the color change
}

@end


text:
package com.microsoft.azure.management.appservice.implementation;

import com.microsoft.azure.management.appservice.ResourceMetricName;
import org.joda.time.DateTime;
import java.util.List;
import com.microsoft.azure.management.appservice.ResourceMetricValue;
import com.microsoft.azure.management.appservice.ResourceMetricProperty;
import com.fasterxml.jackson.annotation.JsonProperty;

/**
 * Object representing a metric for any resource .
 */
public class ResourceMetricInner {
    /**
     * Name of metric.
     */
    @JsonProperty(access = JsonProperty.Access.WRITE_ONLY)
    private ResourceMetricName name;

    /**
     * Metric unit.
     */
    @JsonProperty(access = JsonProperty.Access.WRITE_ONLY)
    private String unit;

    /**
     * Metric granularity. E.g PT1H, PT5M, P1D.
     */
    @JsonProperty(access = JsonProperty.Access.WRITE_ONLY)
    private String timeGrain;

    /**
     * Metric start time.
     */
    @JsonProperty(access = JsonProperty.Access.WRITE_ONLY)
    private DateTime startTime;

    /**
     * Metric end time.
     */
    @JsonProperty(access = JsonProperty.Access.WRITE_ONLY)
    private DateTime endTime;

    /**
     * Metric resource Id.
     */
    @JsonProperty(access = JsonProperty.Access.WRITE_ONLY)
    private String resourceId;

    /**
     * Resource Id.
     */
    @JsonProperty(access = JsonProperty.Access.WRITE_ONLY)
    private String id;

    /**
     * Metric values.
     */
    @JsonProperty(access = JsonProperty.Access.WRITE_ONLY)
    private List<ResourceMetricValue> metricValues;

    /**
     * Properties.
     */
    @JsonProperty(access = JsonProperty.Access.WRITE_ONLY)
    private List<ResourceMetricProperty> properties;

    /**
     * Get the name value.
     *
     * @return the name value
     */
    public ResourceMetricName name() {
        return this.name;
    }

    /**
     * Get the unit value.
     *
     * @return the unit value
     */
    public String unit() {
        return this.unit;
    }

    /**
     * Get the timeGrain value.
     *
     * @return the timeGrain value
     */
    public String timeGrain() {
        return this.timeGrain;
    }

    /**
     * Get the startTime value.
     *
     * @return the startTime value
     */
    public DateTime startTime() {
        return this.startTime;
    }

    /**
     * Get the endTime value.
     *
     * @return the endTime value
     */
    public DateTime endTime() {
        return this.endTime;
    }

    /**
     * Get the resourceId value.
     *
     * @return the resourceId value
     */
    public String resourceId() {
        return this.resourceId;
    }

    /**
     * Get the id value.
     *
     * @return the id value
     */
    public String id() {
        return this.id;
    }

    /**
     * Get the metricValues value.
     *
     * @return the metricValues value
     */
    public List<ResourceMetricValue> metricValues() {
        return this.metricValues;
    }

    /**
     * Get the properties value.
     *
     * @return the properties value
     */
    public List<ResourceMetricProperty> properties() {
        return this.properties;
    }

}