text:
package dht

import (
	"fmt"

	"github.com/sakshamsharma/sarga/common/iface"
)

// DHT is a common interface to be satisfied by
// all implementations to be used with sarga.
type DHT interface {
	Init(addr iface.Address, seeds []iface.Address, net iface.Net) error
	FindValue(key string) ([]byte, error)
	StoreValue(key string, data []byte) error
	Shutdown()

	// Respond consumes a path and data, and returns the serialized response.
	// Helpful for unit tests.
	Respond(string, []byte) []byte
}

type FakeDHT struct {
	data map[string][]byte
}

var _ DHT = &FakeDHT{}

func (f *FakeDHT) Init(addr iface.Address, seeds []iface.Address, net iface.Net) error {
	f.data = map[string][]byte{}
	return nil
}

func (f *FakeDHT) FindValue(key string) ([]byte, error) {
	if val, ok := f.data[key]; ok {
		return val, nil
	}
	return nil, fmt.Errorf("Key %q not found in FakeDHT", key)
}

func (f *FakeDHT) StoreValue(key string, data []byte) error {
	f.data[key] = data
	return nil
}

func (f *FakeDHT) Shutdown() {}

func (f *FakeDHT) Respond(string, []byte) []byte {
	return nil
}


text:
/**
 * @file
 * Contains the definition of the behaviour jsTestRedWeight.
 */

(function ($, Drupal, drupalSettings) {

  'use strict';

  /**
   * Attaches the JS test behavior to weight div.
   */
  Drupal.behaviors.jsTestRedWeight = {
    attach: function (context, settings) {
      var weight = drupalSettings.js_example.js_weights.red;
      var newDiv = $('

').css('color', 'red').html('I have a weight of ' + weight);
      $('#js-weights').append(newDiv);
    }
  };
})(jQuery, Drupal, drupalSettings);

redpajama_set_name: RedPajamaGithub


text:
<?php

namespace Concrete\Controller\SinglePage\Dashboard\System\Files;

use Concrete\Core\Entity\File\Image\Editor;
use Concrete\Core\ImageEditor\ImageEditorService;
use Concrete\Core\Page\Controller\DashboardPageController;

class ImageEditor extends DashboardPageController
{
    /** @var ImageEditorService */
    protected $editorService;

    public function on_start()
    {
        parent::on_start();

        $this->editorService = $this->app->make(ImageEditorService::class);
    }

    public function view()
    {
        if ($this->request->getMethod() === "POST") {
            if ($this->token->validate("save_editor_settings")) {
                $editor = $this->editorService->getEditorByHandle($this->request->request->get("activeEditor"));

                if ($editor instanceof Editor) {
                    $this->editorService->setActiveEditor($editor);
                }

                $this->set('success', t("The default editor has been successfully changed."));
            } else {
                $this->error->add("Invalid Token.");
            }
        }

        $this->set('editorList', $this->editorService->getEditorList());
        $this->set('activeEditor', $this->editorService->getActiveEditor());
    }
}


text:
// Code generated by go-swagger; DO NOT EDIT.

// Copyright Prometheus Team
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
//

package alertgroup

// This file was generated by the swagger tool.
// Editing this file might prove futile when you re-run the swagger generate command

import (
	"net/http"

	"github.com/go-openapi/runtime"

	"github.com/prometheus/alertmanager/api/v2/models"
)

// GetAlertGroupsOKCode is the HTTP code returned for type GetAlertGroupsOK
const GetAlertGroupsOKCode int = 200

/*GetAlertGroupsOK Get alert groups response

swagger:response getAlertGroupsOK
*/
type GetAlertGroupsOK struct {

	/*
	  In: Body
	*/
	Payload models.AlertGroups `json:"body,omitempty"`
}

// NewGetAlertGroupsOK creates GetAlertGroupsOK with default headers values
func NewGetAlertGroupsOK() *GetAlertGroupsOK {

	return &GetAlertGroupsOK{}
}

// WithPayload adds the payload to the get alert groups o k response
func (o *GetAlertGroupsOK) WithPayload(payload models.AlertGroups) *GetAlertGroupsOK {
	o.Payload = payload
	return o
}

// SetPayload sets the payload to the get alert groups o k response
func (o *GetAlertGroupsOK) SetPayload(payload models.AlertGroups) {
	o.Payload = payload
}

// WriteResponse to the client
func (o *GetAlertGroupsOK) WriteResponse(rw http.ResponseWriter, producer runtime.Producer) {

	rw.WriteHeader(200)
	payload := o.Payload
	if payload == nil {
		// return empty array
		payload = models.AlertGroups{}
	}

	if err := producer.Produce(rw, payload); err != nil {
		panic(err) // let the recovery middleware deal with this
	}
}

// GetAlertGroupsBadRequestCode is the HTTP code returned for type GetAlertGroupsBadRequest
const GetAlertGroupsBadRequestCode int = 400

/*GetAlertGroupsBadRequest Bad request

swagger:response getAlertGroupsBadRequest
*/
type GetAlertGroupsBadRequest struct {

	/*
	  In: Body
	*/
	Payload string `json:"body,omitempty"`
}

// NewGetAlertGroupsBadRequest creates GetAlertGroupsBadRequest with default headers values
func NewGetAlertGroupsBadRequest() *GetAlertGroupsBadRequest {

	return &GetAlertGroupsBadRequest{}
}

// WithPayload adds the payload to the get alert groups bad request response
func (o *GetAlertGroupsBadRequest) WithPayload(payload string) *GetAlertGroupsBadRequest {
	o.Payload = payload
	return o
}

// SetPayload sets the payload to the get alert groups bad request response
func (o *GetAlertGroupsBadRequest) SetPayload(payload string) {
	o.Payload = payload
}

// WriteResponse to the client
func (o *GetAlertGroupsBadRequest) WriteResponse(rw http.ResponseWriter, producer runtime.Producer) {

	rw.WriteHeader(400)
	payload := o.Payload
	if err := producer.Produce(rw, payload); err != nil {
		panic(err) // let the recovery middleware deal with this
	}
}

// GetAlertGroupsInternalServerErrorCode is the HTTP code returned for type GetAlertGroupsInternalServerError
const GetAlertGroupsInternalServerErrorCode int = 500

/*GetAlertGroupsInternalServerError Internal server error

swagger:response getAlertGroupsInternalServerError
*/
type GetAlertGroupsInternalServerError struct {

	/*
	  In: Body
	*/
	Payload string `json:"body,omitempty"`
}

// NewGetAlertGroupsInternalServerError creates GetAlertGroupsInternalServerError with default headers values
func NewGetAlertGroupsInternalServerError() *GetAlertGroupsInternalServerError {

	return &GetAlertGroupsInternalServerError{}
}

// WithPayload adds the payload to the get alert groups internal server error response
func (o *GetAlertGroupsInternalServerError) WithPayload(payload string) *GetAlertGroupsInternalServerError {
	o.Payload = payload
	return o
}

// SetPayload sets the payload to the get alert groups internal server error response
func (o *GetAlertGroupsInternalServerError) SetPayload(payload string) {
	o.Payload = payload
}

// WriteResponse to the client
func (o *GetAlertGroupsInternalServerError) WriteResponse(rw http.ResponseWriter, producer runtime.Producer) {

	rw.WriteHeader(500)
	payload := o.Payload
	if err := producer.Produce(rw, payload); err != nil {
		panic(err) // let the recovery middleware deal with this
	}
}


text:
app.Book = Backbone.Model.extend({

	defaults: {
		coverImage: "public/placeholder.png",
		title: "Untitled",
		author: "unknown",
		releaseDate: "n/a",
		keywords: "n/a"
	},
	/*
	The below parse() method is native to Backbone Models and will allow you to make changes to the requested server data before it's received on the frontend.

	Since we want our Book Models to sync properly by id, we have to account for the fact that MongoDB saves each in the database with that id attribute precluded by an _, but Backbone wants that id to display without the _.

	You must reassign the property without an _ before returning the data to the client to retain changes that you make on the server (e.g.: deleting a book) and avoid accidental duplication (e.g.: the book still displaying despite deletion).

	Alternatively and preferably, you could also assign the idAttribute of the Model to _id.
	*/
	parse: function( res ){
		res.id = res._id;
		return res;
	},

});


text:
<button v-on:click='warn("Form cannot be submitted yet.", (Event) $event)'>
  Submit
</button>


text:
require "spec_helper"

describe SimpleBlockchain do
  it "has a version number" do
    expect(SimpleBlockchain::VERSION).not_to be nil
  end
end

describe Block do
  describe 'initialize' do
    let!(:blockchain){ Blockchain.new(no_genesis: true) }
    let!(:block){Block.new(prev: 0,timestamp: 1489908099,data: "genesis",blockchain: blockchain)}

    it '#index' do
      expect(block.index).to eq(0)
    end

    it '#prev of genesis block should be nil',focus: true do
      expect(block.prev).to eq(nil)
    end

    it '#timestamp' do
      expect(block.timestamp).to eq(1489908099)
    end

    it '#data' do
      expect(block.data).to eq("genesis")
    end

    it '#mining' do
      block.mining
      expect(block.valid_hash?).to eq(true)
    end

    it '#valid_hash?' do
      expect(block.valid_hash?).to eq(false)
      block.mining
      expect(block.valid_hash?).to eq(true)
    end
  end
end


text:
#import "IDEInspectorViewController.h"

@class DVTTableView, NSArrayController, SKEStaticTableViewInspectorContainerView;

@interface SKEGeometryElementsInspector : IDEInspectorViewController
{
    NSArrayController *arrayController;
    SKEStaticTableViewInspectorContainerView *containerView;
    DVTTableView *tableView;
}

- (void).cxx_destruct;
- (void)tableView:(id)arg1 willDisplayCell:(id)arg2 forTableColumn:(id)arg3 row:(long long)arg4;
- (void)loadView;
- (void)viewDidInstall;
- (void)setContent:(id)arg1;

@end


text:
import mongoose, { Document, Model, Types } from 'mongoose';

import { IQuestion } from './Question';

export interface ImcqQuestion extends IQuestion
{
    options: string[];
}

export interface ImcqQuestionDocument extends Document, ImcqQuestion
{
    // mention method function here as well
    toJSON: () => Partial<ImcqQuestionDocument>
}

export interface ImcqQuestionModel extends Model<ImcqQuestionDocument>
{
    // mention static function here as well
}


text:
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function

import numpy as np
from skimage.io import imsave
import matplotlib.pyplot as plt

import tensorflow as tf
import tensorflow.contrib.slim as slim

from datasets.config import cfg

_D_MAX = 50.0
_D_MIN = 2.0

# Product of quaternions
def qprod(q_a,q_b):
    assert np.shape(q_a) == (4,),\
            "!! Size of q_a should be 4"
    assert np.shape(q_b) == (4,),\
            "!! Size of q_b should be 4"

    out = np.zeros(np.shape(q_a))
    out[0] = q_a[0]*q_b[0] - np.dot(q_a[1:],q_b[1:])
    out[1:] = q_a[0]*q_b[1:] + q_b[0]*q_a[1:] + np.cross(q_a[1:],q_b[1:])
    return out

# Conjugate of a quaternion
def qconj(q_a):
    assert np.shape(q_a) == (4,),\
            "!! Size of q_a should be 4"

    out = q_a.copy()
    out[1:] = -out[1:]
    return out

def quat_to_transmat(q_r,t_vec):
    """
    Quaternion & Translation to 4x4 homogenous transform matrix
        q_r: unit quaternion for rotation
        t_vec: 3D translation vector
    * Note: Used quaternion istead of dual quaternion for simplicity
            in parameter learning
    """
    assert np.shape(q_r) == (4,),\
            "!! Size of q_r should be 4: {}".format(np.shape(q_r))
    assert np.shape(t_vec) == (3,),\
            "!! Size of t_vec should be 3: {}".format(np.shape(t_vec))

    # Normalize quaternion (Just in case)
    if np.linalg.norm(q_r) != 1:
        q_r = q_r/np.linalg.norm(q_r)

    Rt = np.zeros((4,4))
    Rt[3,3] = 1
    w,x,y,z = q_r

    Rt[0,0] = w**2 + x**2 - y**2 - z**2
    Rt[0,1] = 2*(x*y - w*z)
    Rt[0,2] = 2*(x*z + w*y)
    Rt[1,0] = 2*(x*y + w*z)
    Rt[1,1] = w**2 - x**2 + y**2 - z**2
    Rt[1,2] = 2*(y*z - w*x)
    Rt[2,0] = 2*(x*z - w*y)
    Rt[2,1] = 2*(y*z + w*x)
    Rt[2,2] = w**2 - x**2 - y**2 + z**2

    Rt[:3,3] = t_vec
    return Rt

def minmax_scale(x,i_min,i_max,o_min,o_max):
    # MinMax scaling of x
    # i_min<= x <= i_max to o_min<= x_new <= o_max
    return (x-i_min)/float(i_max-i_min)*(o_max-o_min)+o_min

def qr_to_yr(q_r,max_theta):
    # Normalize q_r (rotation quaternion) to [-1,1]
    assert (max_theta>0) & (max_theta<180),\
            "Maximum value of max_theta(degree) must be in (0,180)"
    y_r = np.zeros(4)
    y_r[0] = minmax_scale(q_r[0],np.cos(max_theta*np.pi/360.0),1,-1,1)
    y_r[1] = minmax_scale(q_r[1],
                          np.sin(max_theta*np.pi/360.0),
                         -np.sin(max_theta*np.pi/360.0),
                         -1,1)
    y_r[2] = minmax_scale(q_r[2],
                          np.sin(max_theta*np.pi/360.0),
                         -np.sin(max_theta*np.pi/360.0),
                         -1,1)
    y_r[3] = minmax_scale(q_r[3],
                          np.sin(max_theta*np.pi/360.0),
                         -np.sin(max_theta*np.pi/360.0),
                         -1,1)
    return y_r

def yr_to_qr(y_r,max_theta):
    # Scale y_r back to q_r(rotation quaternion)
    assert (max_theta>0) & (max_theta<180),\
            "Maximum value of max_theta(degree) must be in (0,180)"
    q_r = np.zeros(4)
    q_r[0] = minmax_scale(y_r[0],-1,1,np.cos(max_theta*np.pi/360.0),1)
    q_r[1] = minmax_scale(y_r[1],-1,1,
                          np.sin(max_theta*np.pi/360.0),
                          -np.sin(max_theta*np.pi/360.0))
    q_r[2] = minmax_scale(y_r[2],-1,1,
                          np.sin(max_theta*np.pi/360.0),
                          -np.sin(max_theta*np.pi/360.0))
    q_r[3] = minmax_scale(y_r[3],-1,1,
                          np.sin(max_theta*np.pi/360.0),
                          -np.sin(max_theta*np.pi/360.0))
    return q_r

def gen_ran_decalib(max_theta, max_dist, num_gen):
    param_rands = {}
    # Rotation angle
    param_rands['rot'] = np.random.uniform(-max_theta,max_theta,num_gen)

    # Rotation axis (unit vectors)
    a_vecs = np.random.standard_normal((3,num_gen))
    a_vecs = (a_vecs/np.linalg.norm(a_vecs,axis=0)).T
    param_rands['a_vec'] = [a_vecs[i] for i in xrange(num_gen)]

    # Translation vector
    dists = np.random.uniform(0,max_dist,num_gen)
    t_vecs = np.random.standard_normal((3,num_gen))
    t_vecs = (dists*(t_vecs/np.linalg.norm(t_vecs,axis=0))).T
    param_rands['t_vec'] = [t_vecs[i] for i in xrange(num_gen)]

    return param_rands

def gen_decalib(max_theta, max_dist, param_rands, i_ran):
    assert (max_theta>0) & (max_dist>0),\
            "Maximum values of angle (degree) and distance (m) must be positive"
    assert max_theta<=30,\
            "Support angle from -30 ~ 30"
    param_decalib = {}

    # Rotation angle
    param_decalib['rot'] = param_rands['rot'][i_ran]

    # Rotation axis (unit vector)
    param_decalib['a_vec'] = param_rands['a_vec'][i_ran]

    # Translation vector
    param_decalib['t_vec'] = param_rands['t_vec'][i_ran]

    # Quaternion for rotation
    q_r = np.zeros(4)
    q_r[0] = np.cos(param_decalib['rot']*np.pi/360.0)
    q_r[1:] = np.sin(param_decalib['rot']*np.pi/360.0)*param_decalib['a_vec']
    param_decalib['q_r'] = q_r

    param_decalib['y'] = np.concatenate((qr_to_yr(q_r,max_theta),
                                         param_decalib['t_vec']))

    return param_decalib

# Fuctions from TF-Slim dataset_utils
def int64_feature(values):
    """Returns a TF-Feature of int64s.
    Args:
        values: A scalar or list of values.
    Returns:
        a TF-Feature.
    """
    if isinstance(values,np.ndarray):
        values = list(values)
    elif not isinstance(values, (tuple, list)):
        values = [values]
    return tf.train.Feature(int64_list=tf.train.Int64List(value=values))

def float_feature(values):
    """Returns a TF-Feature of floats.
    Args:
        values: A scalar or list of values.
    Returns:
        a TF-Feature.
    """
    if isinstance(values,np.ndarray):
        values = values.tolist()
    elif not isinstance(values, (tuple, list)):
        values = [values]
    return tf.train.Feature(float_list=tf.train.FloatList(value=values))

def bytes_feature(values):
    """Returns a TF-Feature of bytes.
    Args:
        values: A string.
    Returns:
        a TF-Feature.
    """
    return tf.train.Feature(bytes_list=tf.train.BytesList(value=[values]))

def calib_to_tfexample_train(im_data, im_format, height, width,
                             points, mat_intrinsic, mat_rect, mat_extrinsic):
    return tf.train.Example(features=tf.train.Features(feature={
            'image/encoded': bytes_feature(im_data),
            'image/format': bytes_feature(im_format),
            'image/height': int64_feature(height),
            'image/width': int64_feature(width),
            'lidar/points': float_feature(points),
            'calib/mat_intrinsic': float_feature(mat_intrinsic),
            'calib/mat_rect': float_feature(mat_rect),
            'calib/mat_extrinsic': float_feature(mat_extrinsic)
            }))

def calib_to_tfexample_test(im_data, im_data_depth, im_format, height, width,
                            y_true, rot, a_vec, params_crop):
    return tf.train.Example(features=tf.train.Features(feature={
            'image/encoded': bytes_feature(im_data),
            'image/format': bytes_feature(im_format),
            'image/height': int64_feature(height),
            'image/width': int64_feature(width),
            'lidar/encoded': bytes_feature(im_data_depth),
            'param/y_calib': float_feature(y_true),
            'param/rot_angle': float_feature(rot),
            'param/a_vec': float_feature(a_vec),
            'param/params_crop': int64_feature(params_crop)
            }))

def coord_transform(points, t_mat):
    # Change to homogeneous form
    points = np.hstack([points,np.ones((np.shape(points)[0],1))])
    t_points = np.dot(points,t_mat.T)
    # Normalize
    t_points = t_points[:,:-1]/t_points[:,[-1]]
    return t_points

def project_lidar_to_img(dict_calib,points,im_height,im_width):
    # Extract depth data first before projection to 2d image space
    trans_mat = np.dot(dict_calib[cfg._SET_CALIB[1]],dict_calib[cfg._SET_CALIB[2]])
    points3D = coord_transform(points,trans_mat)
    pointsDist = points3D[:,2]

    # Project to image space
    trans_mat = np.dot(dict_calib[cfg._SET_CALIB[0]],trans_mat)
    points2D = coord_transform(points,trans_mat)

    # Find only feasible points
    idx1 = (points2D[:,0]>=0) & (points2D[:,0] <=im_width-1)
    idx2 = (points2D[:,1]>=0) & (points2D[:,1] <=im_height-1)
    idx3 = (pointsDist>=0)
    idx_in = idx1 & idx2 & idx3
    points2D_fin = points2D[idx_in,:]
    pointsDist_fin = pointsDist[idx_in]

    return points2D_fin, pointsDist_fin

def dist_to_pixel(val_dist, mode='inverse', d_max=_D_MAX, d_min=_D_MIN):
    """ Returns pixel value from distance measurment
    Args:
        val_dist: distance value (m)
        mode: 'inverse' vs 'standard'
        d_max: maximum distance to consider
        d_min: minimum distance to consider
    Returns:
        pixel value in 'uint8' format
    """
    val_dist = d_max if val_dist>d_max else val_dist if val_dist>d_min else d_min
    if mode == 'standard':
        return np.round(minmax_scale(val_dist,
                                     d_min,d_max,
                                     1,255)).astype('uint8')
    elif mode == 'inverse':
        return np.round(minmax_scale(1.0/val_dist,
                                     1.0/d_max,1.0/d_min,
                                     1,255)).astype('uint8')
    else:
        # Default is inverse
        return np.round(minmax_scale(1.0/val_dist,
                                     1.0/d_max,1.0/d_min,
                                     1,255)).astype('uint8')

def points_to_img(points2D,pointsDist,im_height,im_width,mode='inverse'):
    points2D = np.round(points2D).astype('int')
    im_depth = np.zeros((im_height,im_width),dtype=np.uint8)
    for i in xrange(np.shape(points2D)[0]):
        x,y = points2D[i,:]
        im_depth[y,x] = dist_to_pixel(pointsDist[i],mode=mode)

    # Find LIDAR sensed region
    yx_max = np.max(points2D,axis=0)
    yx_min = np.min(points2D,axis=0)

    offset_height = yx_min[1]
    offset_width = yx_min[0]
    crop_height = yx_max[1]-yx_min[1]
    crop_width = yx_max[0]-yx_min[0]

    return [im_depth.reshape(im_height,im_width,1),
            [offset_height,offset_width,crop_height,crop_width]]

def tf_coord_transform(points, t_mat):
    # Change to homogeneous form
    points = tf.concat([points,tf.ones([tf.shape(points)[0],1],tf.float32)], 1)
    t_points = tf.matmul(points,tf.transpose(t_mat))
    # Normalize
    t_points = tf.div(t_points[:,:-1],tf.expand_dims(t_points[:,-1],1))
    return t_points

def tf_project_lidar_to_img(dict_calib,points,im_height,im_width):
    # Extract depth data first before projection to 2d image space
    trans_mat = tf.matmul(dict_calib[cfg._SET_CALIB[1]],
                          dict_calib[cfg._SET_CALIB[2]])
    points3D = tf_coord_transform(points,trans_mat)
    pointsDist = points3D[:,2]

    # Project to image space
    trans_mat = tf.matmul(dict_calib[cfg._SET_CALIB[0]],trans_mat)
    points2D = tf_coord_transform(points,trans_mat)

    # Find only feasible points
    idx1 = (points2D[:,0]>=0) & (points2D[:,0] <=tf.to_float(im_width)-1)
    idx2 = (points2D[:,1]>=0) & (points2D[:,1] <=tf.to_float(im_height)-1)
    idx3 = (pointsDist>=0)
    idx_in = idx1 & idx2 & idx3
    points2D_fin = tf.boolean_mask(points2D,idx_in)
    pointsDist_fin = tf.boolean_mask(pointsDist,idx_in)

    return points2D_fin, pointsDist_fin

def tf_dist_to_pixel(val_dist, mode='inverse', d_max=_D_MAX, d_min=_D_MIN):
    """ Returns pixel value from distance measurment
    Args:
        val_dist: distance value (m)
        mode: 'inverse' vs 'standard'
        d_max: maximum distance to consider
        d_min: minimum distance to consider
    Returns:
        pixel value in 'uint8' format
    """
    val_dist = tf.maximum(val_dist,d_min)
    val_dist = tf.minimum(val_dist,d_max)
    if mode == 'standard':
        return tf.cast(tf.round(minmax_scale(val_dist,
                                             d_min,d_max,
                                             1,255)),tf.uint8)
    elif mode == 'inverse':
        return tf.cast(tf.round(minmax_scale(1.0/val_dist,
                                             1.0/d_max,1.0/d_min,
                                             1,255)),tf.uint8)
    else:
        # Default is inverse
        return tf.cast(tf.round(minmax_scale(1.0/val_dist,
                                             1.0/d_max,1.0/d_min,
                                             1,255)),tf.uint8)

def tf_points_to_img(points2D,pointsDist,im_height,im_width,mode='inverse'):
    pointsPixel = tf_dist_to_pixel(pointsDist,mode=mode)
    points2D_yx = tf.cast(tf.round(tf.reverse(points2D,axis=[1])),tf.int32)
    img = tf.scatter_nd(points2D_yx,pointsPixel,[im_height,im_width])

    # Find LIDAR sensed region
    yx_max = tf.reduce_max(points2D_yx,axis=0)
    yx_min = tf.reduce_min(points2D_yx,axis=0)

    offset_height = yx_min[0]
    offset_width = yx_min[1]
    crop_height = yx_max[0]-yx_min[0]
    crop_width = yx_max[1]-yx_min[1]

    return [tf.expand_dims(img, 2),
            [offset_height,offset_width,crop_height,crop_width]]

def _crop(image, offset_height, offset_width, crop_height, crop_width):
    """Crops the given image using the provided offsets and sizes.

    Note that the method doesn't assume we know the input image size but it does
    assume we know the input image rank.

    Args:
    image: an image of shape [height, width, channels].
    offset_height: a scalar tensor indicating the height offset.
    offset_width: a scalar tensor indicating the width offset.
    crop_height: the height of the cropped image.
    crop_width: the width of the cropped image.

    Returns:
    the cropped (and resized) image.

    Raises:
    InvalidArgumentError: if the rank is not 3 or if the image dimensions are
        less than the crop size.
    """
    original_shape = tf.shape(image)

    rank_assertion = tf.Assert(
        tf.equal(tf.rank(image), 3),
        ['Rank of image must be equal to 3.'])
    with tf.control_dependencies([rank_assertion]):
        cropped_shape = tf.stack([crop_height, crop_width, original_shape[2]])

    size_assertion = tf.Assert(
        tf.logical_and(
            tf.greater_equal(original_shape[0], crop_height),
            tf.greater_equal(original_shape[1], crop_width)),
        ['Crop size greater than the image size.'])

    offsets = tf.to_int32(tf.stack([offset_height, offset_width, 0]))

    # Use tf.slice instead of crop_to_bounding box as it accepts tensors to
    # define the crop size.
    with tf.control_dependencies([size_assertion]):
        image = tf.slice(image, offsets, cropped_shape)
    return tf.reshape(image, cropped_shape)

def tf_crop_lidar_image(image,lidar,params_crop):
    """Crop RGB image and LIDAR image to consider only
        LIDAR-sensed region
    Return:
        cropped image and lidar
    """
    params_crop = tf.cast(params_crop,tf.int32)
    offset_height = params_crop[0]
    offset_width = params_crop[1]
    crop_height = params_crop[2]
    crop_width = params_crop[3]
    image = _crop(image,offset_height,offset_width,crop_height,crop_width)
    lidar = _crop(lidar,offset_height,offset_width,crop_height,crop_width)

    image.set_shape([None, None, 3])
    lidar.set_shape([None, None, 1])

    return image, lidar

def tf_prepare_train(image,points,
                     mat_intrinsic,mat_rect,mat_extrinsic,
                     max_theta,max_dist):
    # Prepare image and lidar image for training
    im_shape = tf.shape(image)
    im_height = im_shape[0]
    im_width = im_shape[1]

    param_rands = gen_ran_decalib(max_theta,max_dist,1)

    param_decalib = gen_decalib(max_theta,max_dist,param_rands,0)
    y_true = tf.constant(param_decalib['y'],dtype=tf.float32)

    # Intrinsic parameters and rotation matrix (for reference cam)
    ran_dict = {}
    ran_dict[cfg._SET_CALIB[0]] = mat_intrinsic
    ran_dict[cfg._SET_CALIB[1]] = mat_rect
    # Extrinsic parameters to decalibrated ones
    ran_dict[cfg._SET_CALIB[2]] = tf.matmul(
           mat_extrinsic,
           tf.constant(quat_to_transmat(param_decalib['q_r'],
                                        param_decalib['t_vec']),
                       dtype=tf.float32))

    points2D_ran, pointsDist_ran = tf_project_lidar_to_img(ran_dict,
                                                           points,
                                                           im_height,
                                                           im_width)
    lidar,params_crop = tf_points_to_img(
                        points2D_ran,pointsDist_ran,im_height,im_width)
    image,lidar = tf_crop_lidar_image(image,lidar,params_crop)

    return image,lidar,y_true

def tf_prepare_test(image,lidar,params_crop):
    return tf_crop_lidar_image(image,lidar,params_crop)

def imlidarwrite(fname,im,im_depth):
    """Write image with RGB and depth
    Args:
        fname: file name
        im: RGB image array (h x w x 3)
        im_depth: depth image array (h x w)
    """
    im_out = im.copy()
    im_depth = np.squeeze(im_depth,axis=2)
    idx_h, idx_w = np.nonzero(im_depth)
    cmap = plt.get_cmap('jet')
    for i in xrange(len(idx_h)):
        im_out[idx_h[i],idx_w[i],:] = (255*np.array(
                        cmap(im_depth[idx_h[i],idx_w[i]]/255.0)[:3]))\
                        .astype(np.uint8)
    imsave(fname,im_out)
    print("   ... Write:{}".format(fname))


text:
This script allows to read STAT format from file or from stream and produce number of failing and warnings.

This explains how you can use the STAT library to consume STAT output (which is streaming JSON) and it will print output as follows:

Default output:
![img](https://i.gyazo.com/5c33108b3bf2430c0baf6878a730cd16.png)

Output with -s (simple output) option:
![img](https://i.gyazo.com/86038451b7eb18ca95d263690fa183c9.png)


text:
package org.jkiss.dbeaver.ext.postgresql.model;

import org.jkiss.code.NotNull;
import org.jkiss.code.Nullable;
import org.jkiss.dbeaver.DBException;
import org.jkiss.dbeaver.Log;
import org.jkiss.dbeaver.ext.postgresql.PostgreUtils;
import org.jkiss.dbeaver.ext.postgresql.model.data.type.PostgreGeometryTypeHandler;
import org.jkiss.dbeaver.model.exec.DBCException;
import org.jkiss.dbeaver.model.exec.jdbc.JDBCResultSet;
import org.jkiss.dbeaver.model.gis.DBGeometryDimension;
import org.jkiss.dbeaver.model.gis.GisAttribute;
import org.jkiss.dbeaver.model.impl.jdbc.struct.JDBCColumnKeyType;
import org.jkiss.dbeaver.model.runtime.DBRProgressMonitor;
import org.jkiss.dbeaver.model.runtime.VoidProgressMonitor;
import org.jkiss.dbeaver.model.struct.DBSEntityConstraintType;
import org.jkiss.dbeaver.model.struct.DBStructUtils;
import org.jkiss.utils.CommonUtils;

import java.util.Collection;
import java.util.List;
import java.util.Map;

/**
 * PostgreTableColumn
 */
public class PostgreTableColumn extends PostgreAttribute<PostgreTableBase> implements PostgrePrivilegeOwner, PostgreScriptObject, GisAttribute, JDBCColumnKeyType {
    private static final Log log = Log.getLog(PostgreTableColumn.class);

    public PostgreTableColumn(DBRProgressMonitor monitor, PostgreTableBase table, PostgreTableColumn source) throws DBException {
        super(monitor, table, source);
    }

    public PostgreTableColumn(PostgreTableBase table) {
        super(table);
    }

    public PostgreTableColumn(DBRProgressMonitor monitor, PostgreTableBase table, JDBCResultSet dbResult) throws DBException {
        super(monitor, table, dbResult);
    }

    @NotNull
    @Override
    public PostgreSchema getSchema() {
        return getTable().getSchema();
    }

    @Override
    public PostgreRole getOwner(DBRProgressMonitor monitor) throws DBException {
        return getTable().getOwner(monitor);
    }

    @Override
    public Collection<PostgrePrivilege> getPrivileges(DBRProgressMonitor monitor, boolean includeNestedObjects) throws DBException {
        return PostgreUtils.extractPermissionsFromACL(monitor, this, getAcl());
    }

    @Override
    public String generateChangeOwnerQuery(String owner) {
        return null;
    }

    @Override
    public int getAttributeGeometrySRID(DBRProgressMonitor monitor) throws DBCException {
        return PostgreGeometryTypeHandler.getGeometrySRID(getTypeMod());
    }

    @NotNull
    @Override
    public DBGeometryDimension getAttributeGeometryDimension(DBRProgressMonitor monitor) throws DBCException {
        return PostgreGeometryTypeHandler.getGeometryDimension(getTypeMod());
    }

    @Nullable
    @Override
    public String getAttributeGeometryType(DBRProgressMonitor monitor) throws DBCException {
        return PostgreGeometryTypeHandler.getGeometryType(getTypeMod());
    }

    @Override
    public String getObjectDefinitionText(DBRProgressMonitor monitor, Map<String, Object> options) throws DBException {
        return DBStructUtils.generateObjectDDL(monitor, this, options, false);
    }

    @Override
    public void setObjectDefinitionText(String sourceText) throws DBException {

    }

    @Nullable
    @Override
    protected JDBCColumnKeyType getKeyType() {
        return this;
    }

    @Override
    public boolean isInUniqueKey() {
        final List<PostgreTableConstraintBase> cCache = getTable().getSchema().getConstraintCache().getCachedObjects(getTable());
        if (!CommonUtils.isEmpty(cCache)) {
            for (PostgreTableConstraintBase key : cCache) {
                if (key instanceof PostgreTableConstraint && key.getConstraintType() == DBSEntityConstraintType.PRIMARY_KEY) {
                    List<PostgreTableConstraintColumn> cColumns = ((PostgreTableConstraint) key).getColumns();
                    if (!CommonUtils.isEmpty(cColumns)) {
                        for (PostgreTableConstraintColumn cCol : cColumns) {
                            if (cCol.getAttribute() == this) {
                                return true;
                            }
                        }
                    }
                }
            }
        }
        return false;
    }

    @Override
    public boolean isInReferenceKey() {
        return false;
    }

}


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

/// <summary>
/// Summary description for Auction
/// </summary>
public abstract class Auction
{
    //fields
    int auctionID;
    DateTime start_Date;
    string end_Date;
    Voluntary_association vol_asc;
    UserT seller, buyer;
    int score;
    int itemCode;
    City location;
    string catDesc;
    string[] images;
    int percentage;
    string prodName;
    string prodDesc;

    //props
    #region
    public DateTime Start_Date
    {
        get
        {
            return start_Date;
        }

        set
        {
            start_Date = value;
        }
    }

    public string End_Date
    {
        get
        {
            return end_Date;
        }

        set
        {
            end_Date = value;
        }
    }

    public Voluntary_association Vol_asc
    {
        get
        {
            return vol_asc;
        }

        set
        {
            vol_asc = value;
        }
    }

    public UserT Seller
    {
        get
        {
            return seller;
        }

        set
        {
            seller = value;
        }
    }

    public UserT Buyer
    {
        get
        {
            return buyer;
        }

        set
        {
            buyer = value;
        }
    }

    public int Score
    {
        get
        {
            return score;
        }

        set
        {
            score = value;
        }
    }

    public int AuctionID
    {
        get
        {
            return auctionID;
        }

        set
        {
            auctionID = value;
        }
    }

    public int Percentage
    {
        get
        {
            return percentage;
        }

        set
        {
            percentage = value;
        }
    }

    public string ProdDesc
    {
        get
        {
            return prodDesc;
        }

        set
        {
            prodDesc = value;
        }
    }

    public string ProdName
    {
        get
        {
            return prodName;
        }

        set
        {
            prodName = value;
        }
    }

    public int ItemCode
    {
        get
        {
            return itemCode;
        }

        set
        {
            itemCode = value;
        }
    }

    public string CatDesc
    {
        get
        {
            return catDesc;
        }

        set
        {
            catDesc = value;
        }
    }

    public string[] Images
    {
        get
        {
            return images;
        }

        set
        {
            images = value;
        }
    }

    public City Location
    {
        get
        {
            return location;
        }

        set
        {
            location = value;
        }
    }

    #endregion

    //ctor
    public Auction()
    {

    }

    /// <summary>
    /// הבאת כל המכרזים הפעילים
    /// </summary>
    /// <param name="date">תאריך לבדיקה</param>
    /// <returns>תחזיר את כל הקודים של המכרזים הפעילים ואת סכום הביד הנוכחי הגבוה ביותר</returns>
    public static int[] GetAllAuctionsByDates(DateTime date)
    {
        int[] li_rtn = new int[2];
        string sql = @"SELECT ISNULL(dbo.auction.auction_code, - 1) AS auction_code, MAX(ISNULL(dbo.bid.price, 0)) * dbo.auction.donation_percentage / 100 AS maxBid
                        FROM dbo.auction  LEFT OUTER JOIN
                         dbo.bid ON dbo.auction.auction_code = dbo.bid.auction_code
                        GROUP BY dbo.auction.auction_code, dbo.auction.start_date, dbo.auction.end_date, dbo.auction.donation_percentage
                        HAVING        (dbo.auction.start_date <= CONVERT(DATETIME, @date, 102)) AND (dbo.auction.end_date >= CONVERT(DATETIME, @date, 102))";
        SqlParameter parDate = new SqlParameter("@date", date);
        DbService db = new DbService();
        DataTable dt = db.GetDataSetByQuery(sql, CommandType.Text, parDate).Tables[0];

        int count = 0;
        int sum = 0;
        foreach (DataRow row in dt.Rows)
        {
            string code = row["auction_code"].ToString();
            if (code != "-1")
            {
                count++;
                sum += int.Parse(row["maxBid"].ToString());
            }

        }
        li_rtn[0] = count;
        li_rtn[1] = sum;
        return li_rtn;
    }

    /// <summary>
    /// הבאת סך התרומות בין 2 תאריכים
    /// </summary>
    /// <param name="start">תאריך התחלה לבדיקה</param>
    /// <param name="end">תאריך סיום לבדיקה</param>
    /// <returns>תחזיר את הסכום</returns>
    public static int GetDonationSumByDates(DateTime start, DateTime end)
    {
        string sql = @"SELECT SUM(final_price * donation_percentage / 100)  AS donation_sum
                        FROM  dbo.auction
                        WHERE (end_date >= CONVERT(DATETIME, @startDate, 102)) AND (final_price * donation_percentage / 100 > 0) and
                        (end_date <= CONVERT(DATETIME, @endDate, 102))";
        SqlParameter parStart = new SqlParameter("@startDate", start);
        SqlParameter parEnd = new SqlParameter("@endDate", end);
        DbService db = new DbService();
        return db.GetScalarByQuery(sql, CommandType.Text, parStart, parEnd);
    }

    /// <summary>
    ///
    /// </summary>
    /// <param name="start">תאריך התחלה לבדיקה</param>
    /// <param name="end">תאריך סיום לבדיקה</param>
    /// <returns>תחזיר רשימה של מערכים המכילים שם עמותה, סך הכסף במכרזים וסך התרומות לכל עמותה,</returns>
    public static List<string[]> GetAssocNameTotalSumDonationSumByDates(DateTime start, DateTime end)
    {
        string sql = @"SELECT association_name, sum(final_price) AS total_sum ,SUM(final_price * donation_percentage / 100)  AS donation_sum
                        FROM  dbo.auction, association
						where auction.association_code = association.association_code and (end_date >= CONVERT(DATETIME, @startDate, 102)) AND (final_price * donation_percentage / 100 > 0) and
                        (end_date <= CONVERT(DATETIME, @endDate, 102))
						group by association_name
                        order by SUM(final_price * donation_percentage / 100) desc ";
        SqlParameter parStart = new SqlParameter("@startDate", start);
        SqlParameter parEnd = new SqlParameter("@endDate", end);
        DbService db = new DbService();
        DataTable dt = new DataTable();

        try
        {
            dt = db.GetDataSetByQuery(sql, CommandType.Text, parStart, parEnd).Tables[0];

            List<string[]> dlist = new List<string[]>();
            string[] arr = new string[] { "עמותה", "סך הכל לתרומה", "סכום מכרזים" };
            dlist.Add(arr);

            foreach (DataRow row in dt.Rows)
            {
                string asc = row[0].ToString() != null ? row[0].ToString() : "";
                string sum = row[1].ToString() != null ? row[2].ToString() : "";
                string sum2 = row[2].ToString() != null ? row[1].ToString() : "";
                arr = new string[] { asc, sum, sum2 };
                //object obj = new object[row[0].ToString()];

                dlist.Add(arr);
            }

            return dlist;
        }

        catch (Exception ex)
        {
            throw ex;
        }

    }

    //public static List<string[]> GetAssocNameTotalSumDonationSumByDates(DateTime start, DateTime end)
    //{
    //    string sql = @"SELECT association_name, sum(final_price) AS total_sum ,SUM(final_price * donation_percentage / 100)  AS donation_sum
    //                    FROM  dbo.auction, association
				//		where auction.association_code = association.association_code and (end_date >= CONVERT(DATETIME, @startDate, 102)) AND (final_price * donation_percentage / 100 > 0) and
    //                    (end_date <= CONVERT(DATETIME, @endDate, 102))
				//		group by association_name ";
    //    SqlParameter parStart = new SqlParameter("@startDate", start);
    //    SqlParameter parEnd = new SqlParameter("@endDate", end);
    //    DbService db = new DbService();
    //    DataTable dt = new DataTable();

    //    try
    //    {
    //        dt = db.GetDataSetByQuery(sql, CommandType.Text, parStart, parEnd).Tables[0];

    //        List<string[]> dlist = new List<string[]>();
    //        string[] arr = new string[] { "עמותה", "סכום מכרזים", "סך הכל לתרומה" };
    //        dlist.Add(arr);

    //        foreach (DataRow row in dt.Rows)
    //        {
    //            string asc = row[0].ToString() != null ? row[0].ToString() : "";
    //            string sum = row[1].ToString() != null ? row[1].ToString() : "";
    //            string sum2 = row[2].ToString() != null ? row[2].ToString() : "";
    //            arr = new string[] { asc, sum, sum2 };
    //            //object obj = new object[row[0].ToString()];

    //            dlist.Add(arr);
    //        }

    //        return dlist;
    //    }

    //    catch (Exception ex)
    //    {
    //        throw ex;
    //    }

    //}

    //methods
    #region
    public void CalculateAuctionTime()
    {

    }

    public void updateScore()
    {

    }

    public void ShowAuctionQa()
    {
        throw new System.Exception("Not implemented");
    }
    public abstract int CalculateUserScore();

    public void GetAuctionBids()
    {
        throw new System.Exception("Not implemented");
    }
    public virtual void PostBid()
    {
        throw new System.Exception("Not implemented");
    }
    public void GetAuctionUsers()
    {
        throw new System.Exception("Not implemented");
    }
    public void ShowAuction()
    {
        throw new System.Exception("Not implemented");
    }
    public void ShowSellerScore()
    {
        throw new System.Exception("Not implemented");
    }
    public void SendPush()
    {
        throw new System.Exception("Not implemented");
    }
    public void CreateAuction()
    {
        throw new System.Exception("Not implemented");
    }
    public void GetAuctionCode()
    {
        throw new System.Exception("Not implemented");
    }
    public void ShowHighBids()
    {
        throw new System.Exception("Not implemented");
    }
    public void ShowAuctionDetails()
    {
        throw new System.Exception("Not implemented");
    }
    public void ShowAuctionIMG()
    {
        throw new System.Exception("Not implemented");
    }
    public void ShowFAQ()
    {
        throw new System.Exception("Not implemented");
    }
    #endregion

}


text:
using System;
using System.Collections.Generic;
using System.Threading;
using System.Threading.Tasks;
using $safeprojectname$.Data.Entities;

namespace $safeprojectname$.Data.Repositories
{
    public interface ITrackRepository : IDisposable
    {
        Task<List<Track>> GetAllAsync(CancellationToken ct = default(CancellationToken));
        Task<Track> GetByIdAsync(int id, CancellationToken ct = default(CancellationToken));
        Task<List<Track>> GetByAlbumIdAsync(int id, CancellationToken ct = default(CancellationToken));
        Task<List<Track>> GetByGenreIdAsync(int id, CancellationToken ct = default(CancellationToken));
        Task<List<Track>> GetByMediaTypeIdAsync(int id, CancellationToken ct = default(CancellationToken));
        Task<Track> AddAsync(Track newTrack, CancellationToken ct = default(CancellationToken));
        Task<bool> UpdateAsync(Track track, CancellationToken ct = default(CancellationToken));
        Task<bool> DeleteAsync(int id, CancellationToken ct = default(CancellationToken));
    }
}


text:
from __future__ import unicode_literals

import django.contrib.postgres.fields
from django.db import migrations, models

class Migration(migrations.Migration):

    dependencies = [
        ('aggregator', '0025_auto_20181122_1736'),
    ]

    operations = [
        migrations.AlterField(
            model_name='variable',
            name='cell_methods',
            field=django.contrib.postgres.fields.ArrayField(base_field=models.TextField(), null=True, size=None),
        ),
    ]


text:
<?xml version="1.0" encoding="utf-8"?>
<ScrollView xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical" >

    <RelativeLayout
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:orientation="vertical" >

        <View
            android:id="@+id/view_divider"
            android:layout_width="match_parent"
            android:layout_height="1dp"
            android:layout_marginTop="10dp"
            android:background="@color/divider_color" />

        <LinearLayout
            android:id="@+id/ll_line1"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:layout_below="@id/view_divider"
            android:orientation="horizontal" >

            <RelativeLayout
                android:id="@+id/rl_time_container"
                android:layout_width="0dp"
                android:layout_height="wrap_content"
                android:layout_weight="1" >

                <RelativeLayout
                    android:id="@+id/rl_time"
                    android:layout_width="match_parent"
                    android:layout_height="110dp"
                    android:background="#8806A250"
                    android:gravity="center" >

                    <com.qc4w.ilocker.ui.view.SpanDigitalClock
                        android:id="@+id/sdc_clock"
                        android:layout_width="wrap_content"
                        android:layout_height="wrap_content"
                        android:layout_centerHorizontal="true"
                        android:textColor="@color/white"
                        android:textSize="25sp" />

                    <TextView
                        android:id="@+id/tv_date"
                        android:layout_width="wrap_content"
                        android:layout_height="wrap_content"
                        android:layout_below="@id/sdc_clock"
                        android:layout_centerHorizontal="true"
                        android:layout_marginTop="5dp"
                        android:textColor="@color/white"
                        android:textSize="14sp" />

                    <TextView
                        android:id="@+id/tv_week"
                        android:layout_width="wrap_content"
                        android:layout_height="wrap_content"
                        android:layout_below="@id/tv_date"
                        android:layout_centerHorizontal="true"
                        android:layout_marginTop="3dp"
                        android:textColor="@color/white"
                        android:textSize="14sp" />
                </RelativeLayout>

                <RelativeLayout
                    android:layout_width="match_parent"
                    android:layout_height="wrap_content"
                    android:layout_below="@id/rl_time"
                    android:padding="5dp" >

                    <TextView
                        android:id="@+id/tv_label_time"
                        android:layout_width="wrap_content"
                        android:layout_height="wrap_content"
                        android:layout_centerVertical="true"
                        android:text="@string/widget_label_time"
                        android:textColor="@color/drak_gray"
                        android:textSize="14sp" />

                    <ImageView
                        android:id="@+id/iv_time_flag"
                        android:layout_width="20dp"
                        android:layout_height="20dp"
                        android:layout_alignParentRight="true"
                        android:layout_centerVertical="true"
                        android:src="@drawable/ic_selected" />
                </RelativeLayout>
            </RelativeLayout>

            <View
                android:layout_width="1dp"
                android:layout_height="match_parent"
                android:background="@color/divider_color" />

            <RelativeLayout
                android:id="@+id/rl_sentence_container"
                android:layout_width="0dp"
                android:layout_height="wrap_content"
                android:layout_weight="1" >

                <RelativeLayout
                    android:id="@+id/rl_sentence"
                    android:layout_width="match_parent"
                    android:layout_height="110dp"
                    android:background="#88095BC1"
                    android:gravity="center" >

                    <TextView
                        android:id="@+id/tv_sentence_content"
                        android:layout_width="wrap_content"
                        android:layout_height="wrap_content"
                        android:layout_centerHorizontal="true"
                        android:textColor="@color/white"
                        android:textSize="20sp" />
                </RelativeLayout>

                <RelativeLayout
                    android:layout_width="match_parent"
                    android:layout_height="wrap_content"
                    android:layout_below="@id/rl_sentence"
                    android:padding="5dp" >

                    <TextView
                        android:id="@+id/tv_label_sentence"
                        android:layout_width="wrap_content"
                        android:layout_height="wrap_content"
                        android:layout_centerVertical="true"
                        android:text="@string/widget_label_sentence"
                        android:textColor="@color/drak_gray"
                        android:textSize="14sp" />

                    <ImageView
                        android:id="@+id/iv_sentence_flag"
                        android:layout_width="20dp"
                        android:layout_height="20dp"
                        android:layout_alignParentRight="true"
                        android:layout_centerVertical="true"
                        android:src="@drawable/ic_selected" />
                </RelativeLayout>
            </RelativeLayout>
        </LinearLayout>

        <View
            android:id="@+id/view_divider1"
            android:layout_width="match_parent"
            android:layout_height="1dp"
            android:layout_below="@id/ll_line1"
            android:background="@color/divider_color" />

        <LinearLayout
            android:id="@+id/ll_line2"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:layout_below="@id/view_divider1"
            android:orientation="horizontal" >

            <RelativeLayout
                android:id="@+id/rl_countdown_container"
                android:layout_width="0dp"
                android:layout_height="wrap_content"
                android:layout_weight="1" >

                <RelativeLayout
                    android:id="@+id/rl_countdown"
                    android:layout_width="match_parent"
                    android:layout_height="110dp"
                    android:background="#88C109B6"
                    android:gravity="center" >

                    <TextView
                        android:id="@+id/tv_countdown_content"
                        android:layout_width="wrap_content"
                        android:layout_height="wrap_content"
                        android:layout_centerHorizontal="true"
                        android:textColor="@color/white"
                        android:textSize="20sp" />

                    <com.qc4w.ilocker.ui.view.CountdownTextView
                        android:id="@+id/tv_countdown_time"
                        android:layout_width="wrap_content"
                        android:layout_height="wrap_content"
                        android:layout_below="@id/tv_countdown_content"
                        android:layout_centerHorizontal="true"
                        android:layout_marginTop="5dp"
                        android:textColor="@color/white"
                        android:textSize="14sp" />
                </RelativeLayout>

                <RelativeLayout
                    android:layout_width="match_parent"
                    android:layout_height="wrap_content"
                    android:layout_below="@id/rl_countdown"
                    android:padding="5dp" >

                    <TextView
                        android:id="@+id/tv_label_countdown"
                        android:layout_width="wrap_content"
                        android:layout_height="wrap_content"
                        android:layout_centerVertical="true"
                        android:text="@string/widget_label_countdown"
                        android:textColor="@color/drak_gray"
                        android:textSize="14sp" />

                    <ImageView
                        android:id="@+id/iv_countdown_flag"
                        android:layout_width="20dp"
                        android:layout_height="20dp"
                        android:layout_alignParentRight="true"
                        android:layout_centerVertical="true"
                        android:src="@drawable/ic_selected" />
                </RelativeLayout>
            </RelativeLayout>

            <View
                android:layout_width="1dp"
                android:layout_height="match_parent"
                android:background="@color/divider_color" />

            <RelativeLayout
                android:id="@+id/rl_timing_container"
                android:layout_width="0dp"
                android:layout_height="wrap_content"
                android:layout_weight="1" >

                <RelativeLayout
                    android:id="@+id/rl_timing"
                    android:layout_width="match_parent"
                    android:layout_height="110dp"
                    android:background="#88AF7F0D"
                    android:gravity="center" >

                    <TextView
                        android:id="@+id/tv_timing_content"
                        android:layout_width="wrap_content"
                        android:layout_height="wrap_content"
                        android:layout_centerHorizontal="true"
                        android:textColor="@color/white"
                        android:textSize="20sp" />

                    <com.qc4w.ilocker.ui.view.TimingTextView
                        android:id="@+id/tv_timing_time"
                        android:layout_width="wrap_content"
                        android:layout_height="wrap_content"
                        android:layout_below="@id/tv_timing_content"
                        android:layout_centerHorizontal="true"
                        android:layout_marginTop="5dp"
                        android:textColor="@color/white"
                        android:textSize="14sp" />
                </RelativeLayout>

                <RelativeLayout
                    android:layout_width="match_parent"
                    android:layout_height="wrap_content"
                    android:layout_below="@id/rl_timing"
                    android:padding="5dp" >

                    <TextView
                        android:id="@+id/tv_label_timing"
                        android:layout_width="wrap_content"
                        android:layout_height="wrap_content"
                        android:layout_centerVertical="true"
                        android:text="@string/widget_label_timing"
                        android:textColor="@color/drak_gray"
                        android:textSize="14sp" />

                    <ImageView
                        android:id="@+id/iv_timing_flag"
                        android:layout_width="20dp"
                        android:layout_height="20dp"
                        android:layout_alignParentRight="true"
                        android:layout_centerVertical="true"
                        android:src="@drawable/ic_selected" />
                </RelativeLayout>
            </RelativeLayout>
        </LinearLayout>

        <View
            android:id="@+id/view_divider2"
            android:layout_width="match_parent"
            android:layout_height="1dp"
            android:layout_below="@id/ll_line2"
            android:background="@color/divider_color" />

        <LinearLayout
            android:id="@+id/ll_line3"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:layout_below="@id/view_divider2"
            android:orientation="horizontal" >

            <RelativeLayout
                android:id="@+id/rl_notification_container"
                android:layout_width="0dp"
                android:layout_height="wrap_content"
                android:layout_weight="1" >

                <RelativeLayout
                    android:id="@+id/rl_notification"
                    android:layout_width="match_parent"
                    android:layout_height="110dp"
                    android:background="#88CCDE36"
                    android:gravity="center_vertical"
                    android:padding="5dp" >

                    <RelativeLayout
                        android:id="@+id/rl_notification_line1"
                        android:layout_width="match_parent"
                        android:layout_height="wrap_content"
                        android:background="@color/half_transparent"
                        android:padding="5dp" >

                        <ImageView
                            android:id="@+id/iv_app_icon"
                            android:layout_width="30dp"
                            android:layout_height="30dp"
                            android:layout_centerVertical="true"
                            android:src="@drawable/android_mms" />

                        <TextView
                            android:id="@+id/tv_app_name"
                            android:layout_width="match_parent"
                            android:layout_height="wrap_content"
                            android:layout_marginLeft="5dp"
                            android:layout_toRightOf="@id/iv_app_icon"
                            android:singleLine="true"
                            android:text="SMS"
                            android:textColor="@color/white"
                            android:textSize="14sp" />

                        <TextView
                            android:id="@+id/tv_notification_content"
                            android:layout_width="match_parent"
                            android:layout_height="wrap_content"
                            android:layout_below="@id/tv_app_name"
                            android:layout_marginLeft="5dp"
                            android:layout_marginTop="3dp"
                            android:layout_toRightOf="@id/iv_app_icon"
                            android:singleLine="true"
                            android:text="Jone: Yeah, i'm playing ……"
                            android:textColor="@color/white"
                            android:textSize="10sp" />
                    </RelativeLayout>

                    <RelativeLayout
                        android:layout_width="match_parent"
                        android:layout_height="wrap_content"
                        android:layout_below="@id/rl_notification_line1"
                        android:layout_marginTop="5dp"
                        android:background="@color/half_transparent"
                        android:padding="5dp" >

                        <ImageView
                            android:id="@+id/iv_app_icon1"
                            android:layout_width="30dp"
                            android:layout_height="30dp"
                            android:layout_centerVertical="true"
                            android:src="@drawable/android_phone" />

                        <TextView
                            android:id="@+id/tv_app_name1"
                            android:layout_width="match_parent"
                            android:layout_height="wrap_content"
                            android:layout_marginLeft="5dp"
                            android:layout_toRightOf="@id/iv_app_icon1"
                            android:singleLine="true"
                            android:text="Phone"
                            android:textColor="@color/white"
                            android:textSize="14sp" />

                        <TextView
                            android:id="@+id/tv_notification_content1"
                            android:layout_width="match_parent"
                            android:layout_height="wrap_content"
                            android:layout_below="@id/tv_app_name1"
                            android:layout_marginLeft="5dp"
                            android:layout_marginTop="3dp"
                            android:layout_toRightOf="@id/iv_app_icon1"
                            android:singleLine="true"
                            android:text="Husband of missed calls"
                            android:textColor="@color/white"
                            android:textSize="10sp" />
                    </RelativeLayout>
                </RelativeLayout>

                <RelativeLayout
                    android:layout_width="match_parent"
                    android:layout_height="wrap_content"
                    android:layout_below="@id/rl_notification"
                    android:padding="5dp" >

                    <TextView
                        android:id="@+id/tv_label_notification"
                        android:layout_width="wrap_content"
                        android:layout_height="wrap_content"
                        android:layout_centerVertical="true"
                        android:text="@string/widget_label_notification"
                        android:textColor="@color/drak_gray"
                        android:textSize="14sp" />

                    <ImageView
                        android:id="@+id/iv_notification_flag"
                        android:layout_width="20dp"
                        android:layout_height="20dp"
                        android:layout_alignParentRight="true"
                        android:layout_centerVertical="true"
                        android:src="@drawable/ic_selected" />
                </RelativeLayout>
            </RelativeLayout>

            <View
                android:layout_width="1dp"
                android:layout_height="match_parent"
                android:background="@color/divider_color" />

            <RelativeLayout
                android:id="@+id/rl_camera_container"
                android:layout_width="0dp"
                android:layout_height="wrap_content"
                android:layout_weight="1" >

                <RelativeLayout
                    android:id="@+id/rl_camera"
                    android:layout_width="match_parent"
                    android:layout_height="110dp"
                    android:background="#8800A8C2" >

                    <ImageView
                        android:id="@+id/iv_camera"
                        android:layout_width="wrap_content"
                        android:layout_height="wrap_content"
                        android:layout_centerInParent="true"
                        android:src="@drawable/ic_camera" />
                </RelativeLayout>

                <RelativeLayout
                    android:layout_width="match_parent"
                    android:layout_height="wrap_content"
                    android:layout_below="@id/rl_camera"
                    android:padding="5dp" >

                    <TextView
                        android:id="@+id/tv_label_camera"
                        android:layout_width="wrap_content"
                        android:layout_height="wrap_content"
                        android:layout_centerVertical="true"
                        android:text="@string/widget_label_camera"
                        android:textColor="@color/drak_gray"
                        android:textSize="14sp" />

                    <ImageView
                        android:id="@+id/iv_camera_flag"
                        android:layout_width="20dp"
                        android:layout_height="20dp"
                        android:layout_alignParentRight="true"
                        android:layout_centerVertical="true"
                        android:src="@drawable/ic_selected" />
                </RelativeLayout>
            </RelativeLayout>
        </LinearLayout>

        <View
            android:id="@+id/view_divider3"
            android:layout_width="match_parent"
            android:layout_height="1dp"
            android:layout_below="@id/ll_line3"
            android:background="@color/divider_color" />
    </RelativeLayout>

</ScrollView>


text:
using System;

namespace Gem.Gui.Aggregation
{
    /// <summary>
    /// AggregationTarget shows which input capabilties the Gui is targeting
    /// </summary>
    [Flags]
    public enum AggregationTarget
    {
        None = 0,
        Mouse = 1,
        Keyboard = 2,
        GamePad = 4,
        Touch = 8,
        All = Mouse | Keyboard | GamePad | Touch
    }

    public static class AggregationTargetExtensions
    {
        /// <summary>
        /// Helper extension for AggregationTarget enum for checking if an instance has a specific flag.
        /// This is a Enum.HasFlag duplicate, but AggregationTarget specific, because HasFlag is has performance costs
        /// </summary>
        public static bool HasTargetFlag(this AggregationTarget target, AggregationTarget flag)
        {
            return ((target & flag) != 0);
        }
    }
}


text:
const path = require('path');
const fs = require('fs');
const mkdirp = require('mkdirp');
const parser = require('ua-parser-js');
const config = require('../../../config/config');

function getUserAgentString() {
  return browser.execute(() => {
    return window.navigator.userAgent;
  }).value;
}

function getUserAgent() {
  return parser(getUserAgentString());
}

function saveErrorshot(test) {
  const agent = getUserAgent();
  const filename = `${agent.browser.name}-${agent.browser.major}-${agent.os.name}.png`;
  const testdir = path.resolve(config.webdriver.screenshotPath, test.parent, test.title);
  const filepath = path.resolve(testdir, filename);

  try {
    fs.accessSync(testdir, fs.F_OK);
  } catch (e) {
    mkdirp.sync(testdir);
  }

  browser.saveScreenshot(filepath);
}

module.exports = {
  getUserAgentString,
  getUserAgent,
  saveErrorshot,
};


text:
package io.tilde.moneta.annotations;

import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;

@Retention(RetentionPolicy.RUNTIME)
@Target({ElementType.TYPE, ElementType.FIELD})
public @interface PrimaryKey {

  public String value() default "-";

}


text:
package org.wiztools.restclient.ui;

import java.awt.AWTEvent;

import java.awt.BorderLayout;
import java.awt.Dimension;
import java.awt.FlowLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;

import javax.swing.BorderFactory;
import javax.swing.JButton;
import javax.swing.JDialog;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.JTextArea;
import org.wiztools.commons.Charsets;
import org.wiztools.commons.FileUtil;
import org.wiztools.restclient.MessageI18N;
import org.wiztools.restclient.Util;

/**
 *
 * @author Subhash
 */
class KeyValMultiEntryDialog extends EscapableDialog {

    private JButton jb_file = new JButton(UIUtil.getIconFromClasspath(RCFileView.iconBasePath + "load_from_file.png"));
    private JButton jb_help = new JButton(UIUtil.getIconFromClasspath(RCFileView.iconBasePath + "question.png"));
    private JButton jb_add = new JButton("Add");
    private JButton jb_cancel = new JButton("Cancel");
    private JScrollPane jsp_in;
    private JTextArea jta_in = new JTextArea(18, 35);
    private JDialog me;
    private RESTUserInterface ui;
    private MultiEntryAdd callback;

    public KeyValMultiEntryDialog(RESTUserInterface ui, MultiEntryAdd callback) {
        super(ui.getFrame(), true);
        this.ui = ui;
        me = this;
        setTitle("Multi-entry");
        this.callback = callback;

        init();
    }

    private void init() {
        JPanel jp = new JPanel();
        jp.setLayout(new BorderLayout());

        JPanel jp_north = new JPanel();
        jp_north.setLayout(new FlowLayout(FlowLayout.LEFT));
        jb_file.setToolTipText("Load from file");
        jb_file.addActionListener(new ActionListener() {
            public void actionPerformed(ActionEvent e) {
                loadFromFile();
            }
        });
        jp_north.add(jb_file);
        jb_help.setToolTipText("Help");
        jb_help.addActionListener(new ActionListener() {
            public void actionPerformed(ActionEvent e) {
                JOptionPane.showMessageDialog(me,
                        MessageI18N.getMessage("help.keyval.multi"),
                        "Help", JOptionPane.INFORMATION_MESSAGE);
            }
        });
        jp_north.add(jb_help);

        jp.add(jp_north, BorderLayout.NORTH);

        jsp_in = new JScrollPane(jta_in);
        jp.add(jsp_in, BorderLayout.CENTER);

        JPanel jp_south = new JPanel();
        jp_south.setLayout(new FlowLayout());
        jb_add.setMnemonic('a');
        jb_add.addActionListener(new ActionListener() {
            public void actionPerformed(ActionEvent event) {
                add();
            }
        });
        jp_south.add(jb_add);
        jb_cancel.setMnemonic('c');
        jb_cancel.addActionListener(new ActionListener() {
            public void actionPerformed(ActionEvent event) {
                me.setVisible(false);
            }
        });
        jp_south.add(jb_cancel);

        jp.add(jp_south, BorderLayout.SOUTH);

        jp.setBorder(BorderFactory.createEmptyBorder(RESTView.BORDER_WIDTH,
                RESTView.BORDER_WIDTH, RESTView.BORDER_WIDTH, RESTView.BORDER_WIDTH));
        setContentPane(jp);
        pack();

        // By default have the focus on the text area:
        jta_in.requestFocus();
    }

    private void loadFromFile(){
        File f = ui.getOpenFile(FileChooserType.OPEN_TEST_SCRIPT, me);
        if(f != null){
            try{
                String content = FileUtil.getContentAsString(f, Charsets.UTF_8);
                Dimension d = jsp_in.getPreferredSize();
                jta_in.setText(content);
                jta_in.setCaretPosition(0);
                jsp_in.setPreferredSize(d);
            }
            catch(IOException ex){
                ui.getView().showError(Util.getStackTrace(ex));
            }
        }
    }

    private void add() {
        String str = jta_in.getText();
        if ("".equals(str.trim())) {
            JOptionPane.showMessageDialog(me, "Please enter input text!", "No Input", JOptionPane.ERROR_MESSAGE);
            return;
        }
        String[] line_arr = str.split("\\n");

        List<String> linesNotMatching = new ArrayList<String>();
        Map<String, String> keyValMap = new LinkedHashMap<String, String>();

        for (String line : line_arr) {
            int index = line.indexOf(':');
            if ((index > -1) && (index != 0) && (index != (line.length() - 1))) {
                String key = line.substring(0, index);
                String value = line.substring(index + 1);
                key = key.trim();
                value = value.trim();
                if ("".equals(key) || "".equals(value)) {
                    linesNotMatching.add(line);
                } else {
                    keyValMap.put(key, value);
                }
            } else {
                if (!"".equals(line.trim())) { // Add only non-blank line
                    linesNotMatching.add(line);
                }
            }
        }

        me.setVisible(false);
        callback.add(keyValMap, linesNotMatching);
    }

    @Override
    public void setVisible(boolean boo){
        super.setVisible(boo);
        if(boo == true){
            jta_in.requestFocus();
        }
    }

    @Override
    public void doEscape(AWTEvent event) {
        me.setVisible(false);
    }
}


text:
using System;
using Microsoft.TeamFoundation.WorkItemTracking.Client.Metadata;

namespace Microsoft.TeamFoundation.WorkItemTracking.Client.Objects
{
    public class StoredQuery
    {
        [TableFieldName("ID")]
        public Guid Id { get; set; }

        [TableFieldName("ProjectID")]
        public int ProjectId { get; set; }

        [TableFieldName("fPublic")]
        public bool IsPublic { get; set; }

        [TableFieldName("Owner")]
        public string Owner { get; set; }

        [TableFieldName("QueryName")]
        public string QueryName { get; set; }

        [TableFieldName("QueryText")]
        public string QueryText { get; set; }

        [TableFieldName("Description")]
        public string Description { get; set; }

        [TableFieldName("CreateTime")]
        public DateTime CreateTime { get; set; }

        [TableFieldName("LastWriteTime")]
        public DateTime LastWriteTime { get; set; }

        [TableFieldName("fDeleted")]
        public bool IsDeleted { get; set; }

        [TableFieldName("ParentID")]
        public Guid ParentId { get; set; }
    }
}


text:
@interface ViewController : UITableViewController

@property (nonatomic, weak) IBOutlet UISwitch *showTouchesToggle;
@property (nonatomic, weak) IBOutlet UISwitch *dynamicTouchesToggle;

@property (nonatomic, weak) IBOutlet UISlider *redSlider;
@property (nonatomic, weak) IBOutlet UISlider *greenSlider;
@property (nonatomic, weak) IBOutlet UISlider *blueSlider;
@property (nonatomic, weak) IBOutlet UISlider *alphaSlider;

- (IBAction) toggleShowTouches:(UISwitch *)toggle;
- (IBAction) toggleDynamicTouches:(UISwitch *)toggle;

- (IBAction) changedRed:(UISlider *)slider;
- (IBAction) changedGreen:(UISlider *)slider;
- (IBAction) changedBlue:(UISlider *)slider;
- (IBAction) changedAlpha:(UISlider *)slider;

- (IBAction) showAlert:(id)sender;
- (IBAction) showSheet:(id)sender;

@end


text:
USE ${hiveconf:my.schema};

CREATE EXTERNAL TABLE foo (i int, s string)
  ROW FORMAT DELIMITED FIELDS TERMINATED BY ','
  STORED AS TEXTFILE
  LOCATION '${hiveconf:MY.HDFS.DIR}/foo/';


text:
import { EventEmitter } from 'events';

export const config: Homenet.IConfig = {
  instances: [
    {
      id: 'one',
      class: 'power',
      type: 'test',
      options: {id: 1}
    },
    {
      id: 'two',
      class: 'power',
      type: 'test',
      options: {id: 2}
    },
    {
      id: 'three',
      class: 'power',
      type: 'test',
      options: {id: 3}
    }
  ]
}

export function create() : Homenet.IClassTypeFactory<Homenet.ISettable> {
  return (id : string, opts : any): Homenet.ISettable => {
    return new TesPower(id, opts);
  };
}

class TesPower extends EventEmitter implements Homenet.ISettable {
  public calls: string[] = [];
  public state: string = 'unknown';
  public id: string;
  public opts: any;

  constructor(id : string, opts : any) {
    super();
    this.id = id;
    this.opts = opts;
  }

  get() : string {
    this.calls.push('get');
    return this.state;
  }

  set(value: string|boolean) : void {
    this.calls.push('set');
    const newState: string = <string> (value === true ? 'on' : value === false ? 'off' : value);
    this.state = newState;
    this.emit('update', newState);
  }
}


text:
/*
 * aria2 - The high speed download utility
 *
 * Copyright (C) 2012 Tatsuhiro Tsujikawa
 *
 * 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.
 *
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with this program; if not, write to the Free Software
 * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
 *
 * In addition, as a special exception, the copyright holders give
 * permission to link the code of portions of this program with the
 * OpenSSL library under certain conditions as described in each
 * individual source file, and distribute linked combinations
 * including the two.
 * You must obey the GNU General Public License in all respects
 * for all of the code used other than OpenSSL.  If you modify
 * file(s) with this exception, you may extend this exception to your
 * version of the file(s), but you are not obligated to do so.  If you
 * do not wish to do so, delete this exception statement from your
 * version.  If you delete this exception statement from all source
 * files in the program, then also delete it here.
 */
/* copyright --> */
#include "ChunkedDecodingStreamFilter.h"

#include <cassert>

#include "util.h"
#include "message.h"
#include "DlAbortEx.h"
#include "A2STR.h"

namespace aria2 {

const std::string ChunkedDecodingStreamFilter::NAME
("ChunkedDecodingStreamFilter");

namespace {
enum {
  PREV_CHUNK_SIZE,
  CHUNK_SIZE,
  CHUNK_EXTENSION,
  PREV_CHUNK_SIZE_LF,
  CHUNK,
  PREV_CHUNK_CR,
  PREV_CHUNK_LF,
  PREV_TRAILER,
  TRAILER,
  PREV_TRAILER_LF,
  PREV_END_CR,
  PREV_END_LF,
  CHUNKS_COMPLETE
};
} // namespace

ChunkedDecodingStreamFilter::ChunkedDecodingStreamFilter
(std::unique_ptr<StreamFilter> delegate)
  : StreamFilter{std::move(delegate)},
    state_{PREV_CHUNK_SIZE},
    chunkSize_{0},
    chunkRemaining_{0},
    bytesProcessed_{0}
{}

ChunkedDecodingStreamFilter::~ChunkedDecodingStreamFilter() {}

void ChunkedDecodingStreamFilter::init() {}

ssize_t ChunkedDecodingStreamFilter::transform
(const std::shared_ptr<BinaryStream>& out,
 const std::shared_ptr<Segment>& segment,
 const unsigned char* inbuf, size_t inlen)
{
  ssize_t outlen = 0;
  size_t i;
  bytesProcessed_ = 0;
  for(i = 0; i < inlen; ++i) {
    unsigned char c = inbuf[i];
    switch(state_) {
    case PREV_CHUNK_SIZE:
      if(util::isHexDigit(c)) {
        chunkSize_ = util::hexCharToUInt(c);
        state_ = CHUNK_SIZE;
      } else {
        throw DL_ABORT_EX("Bad chunk size: not hex string");
      }
      break;
    case CHUNK_SIZE:
      if(util::isHexDigit(c)) {
        if(chunkSize_ & 0x7800000000000000LL) {
          throw DL_ABORT_EX("Too big chunk size");
        }
        chunkSize_ <<= 4;
        chunkSize_ += util::hexCharToUInt(c);
      } else if(c == ';') {
        state_ = CHUNK_EXTENSION;
      } else if(c == '\r') {
        state_ = PREV_CHUNK_SIZE_LF;
      } else {
        throw DL_ABORT_EX("Bad chunk size: not hex string");
      }
      break;
    case CHUNK_EXTENSION:
      if(c == '\r') {
        state_ = PREV_CHUNK_SIZE_LF;
      }
      break;
    case PREV_CHUNK_SIZE_LF:
      if(c == '\n') {
        chunkRemaining_ = chunkSize_;
        if(chunkSize_ == 0) {
          state_ = PREV_TRAILER;
        } else {
          state_ = CHUNK;
        }
      } else {
        throw DL_ABORT_EX("Bad chunk encoding: "
                          "missing LF at the end of chunk size");
      }
      break;
    case CHUNK: {
      int64_t readlen = std::min(chunkRemaining_,
                                 static_cast<int64_t>(inlen-i));
      outlen += getDelegate()->transform(out, segment, inbuf+i, readlen);
      chunkRemaining_ -= readlen;
      i += readlen-1;
      if(chunkRemaining_ == 0) {
        state_ = PREV_CHUNK_CR;
      }
      break;
    }
    case PREV_CHUNK_CR:
      if(c == '\r') {
        state_ = PREV_CHUNK_LF;
      } else {
        throw DL_ABORT_EX("Bad chunk encoding: "
                          "missing CR at the end of chunk");
      }
      break;
    case PREV_CHUNK_LF:
      if(c == '\n') {
        if(chunkSize_ == 0) {
          state_ = PREV_TRAILER;
        } else {
          chunkSize_ = chunkRemaining_ = 0;
          state_ = PREV_CHUNK_SIZE;
        }
      } else {
        throw DL_ABORT_EX("Bad chunk encoding: "
                          "missing LF at the end of chunk");
      }
      break;
    case PREV_TRAILER:
      if(c == '\r') {
        // No trailer
        state_ = PREV_END_LF;
      } else {
        state_= TRAILER;
      }
      break;
    case TRAILER:
      if(c == '\r') {
        state_ = PREV_TRAILER_LF;
      }
      break;
    case PREV_TRAILER_LF:
      if(c == '\n') {
        state_ = PREV_TRAILER;
      } else {
        throw DL_ABORT_EX("Bad chunk encoding: "
                          "missing LF at the end of trailer");
      }
      break;
    case PREV_END_LF:
      if(c == '\n') {
        state_ = CHUNKS_COMPLETE;
      } else {
        throw DL_ABORT_EX("Bad chunk encoding: "
                          "missing LF at the end of chunks");
      }
      break;
    case CHUNKS_COMPLETE:
      goto fin;
    default:
      // unreachable
      assert(0);
    }
  }
 fin:
  bytesProcessed_ += i;
  return outlen;
}

bool ChunkedDecodingStreamFilter::finished()
{
  return state_ == CHUNKS_COMPLETE && getDelegate()->finished();
}

void ChunkedDecodingStreamFilter::release() {}

const std::string& ChunkedDecodingStreamFilter::getName() const
{
  return NAME;
}

} // namespace aria2


text:
<?php

  $xx_mins_ago = (time() - 900);

  require('includes/application_top.php');

  require(DIR_WS_CLASSES . 'currencies.php');
  $currencies = new currencies();

// remove entries that have expired
  tep_db_query("delete from " . TABLE_WHOS_ONLINE . " where time_last_click < '" . $xx_mins_ago . "'");

  require(DIR_WS_INCLUDES . 'template_top.php');
?>

            <?php echo HEADING_TITLE; ?>
            <?php echo tep_draw_separator('pixel_trans.gif', HEADING_IMAGE_WIDTH, HEADING_IMAGE_HEIGHT); ?>

                <?php echo TABLE_HEADING_ONLINE; ?>
                <?php echo TABLE_HEADING_CUSTOMER_ID; ?>
                <?php echo TABLE_HEADING_FULL_NAME; ?>
                <?php echo TABLE_HEADING_IP_ADDRESS; ?>
                <?php echo TABLE_HEADING_ENTRY_TIME; ?>
                <?php echo TABLE_HEADING_LAST_CLICK; ?>
                <?php echo TABLE_HEADING_LAST_PAGE_URL; ?>

<?php
  $whos_online_query = tep_db_query("select customer_id, full_name, ip_address, time_entry, time_last_click, last_page_url, session_id from " . TABLE_WHOS_ONLINE);
  while ($whos_online = tep_db_fetch_array($whos_online_query)) {
    $time_online = (time() - $whos_online['time_entry']);
    if ((!isset($HTTP_GET_VARS['info']) || (isset($HTTP_GET_VARS['info']) && ($HTTP_GET_VARS['info'] == $whos_online['session_id']))) && !isset($info)) {
      $info = new ObjectInfo($whos_online);
    }

    if (isset($info) && ($whos_online['session_id'] == $info->session_id)) {
      echo '
' . "\n";
    } else {
      echo '
' . "\n";
    }
?>
                <?php echo gmdate('H:i:s', $time_online); ?>
                <?php echo $whos_online['customer_id']; ?>
                <?php echo $whos_online['full_name']; ?>
                <?php echo $whos_online['ip_address']; ?>
                <?php echo date('H:i:s', $whos_online['time_entry']); ?>
                <?php echo date('H:i:s', $whos_online['time_last_click']); ?>
                <?php if (preg_match('/^(.*)osCsid=[A-Z0-9,-]+[&]*(.*)/i', $whos_online['last_page_url'], $array)) { echo $array[1] . $array[2]; } else { echo $whos_online['last_page_url']; } ?>

<?php
  }
?>

                <?php echo sprintf(TEXT_NUMBER_OF_CUSTOMERS, tep_db_num_rows($whos_online_query)); ?>

<?php
  $heading = array();
  $contents = array();

  if (isset($info)) {
    $heading[] = array('text' => '' . TABLE_HEADING_SHOPPING_CART . '');

    if ( $info->customer_id > 0 ) {
      $products_query = tep_db_query("select cb.customers_basket_quantity, cb.products_id, pd.products_name from " . TABLE_CUSTOMERS_BASKET . " cb, " . TABLE_PRODUCTS_DESCRIPTION . " pd where cb.customers_id = '" . (int)$info->customer_id . "' and cb.products_id = pd.products_id and pd.language_id = '" . (int)$languages_id . "'");

      if ( tep_db_num_rows($products_query) ) {
        $shoppingCart = new shoppingCart();

        while ( $products = tep_db_fetch_array($products_query) ) {
          $contents[] = array('text' => $products['customers_basket_quantity'] . ' x ' . $products['products_name']);

          $attributes = array();

          if ( strpos($products['products_id'], '{') !== false ) {
            $combos = array();
            preg_match_all('/(\{[0-9]+\}[0-9]+){1}/', $products['products_id'], $combos);

            foreach ( $combos[0] as $combo ) {
              $att = array();
              preg_match('/\{([0-9]+)\}([0-9]+)/', $combo, $att);

              $attributes[$att[1]] = $att[2];
            }
          }

          $shoppingCart->add_cart(tep_get_prid($products['products_id']), $products['customers_basket_quantity'], $attributes);
        }

        $contents[] = array('text' => tep_draw_separator('pixel_black.gif', '100%', '1'));
        $contents[] = array('align' => 'right', 'text'  => TEXT_SHOPPING_CART_SUBTOTAL . ' ' . $currencies->format($shoppingCart->show_total()));
      } else {
        $contents[] = array('text' => ' ');
      }
    } else {
      $contents[] = array('text' => 'N/A');
    }
  }

  if ( (tep_not_null($heading)) && (tep_not_null($contents)) ) {
    echo '            ' . "\n";

    $box = new box;
    echo $box->infoBox($heading, $contents);

    echo '            	' . "\n";
  }
?>

<?php
  require(DIR_WS_INCLUDES . 'template_bottom.php');
  require(DIR_WS_INCLUDES . 'application_bottom.php');
?>


text:
<?php

namespace Olitaz\HomeBundle\Entity;

use Symfony\Component\Validator\Constraints as Assert;

class Contact
{

    /**
     * @Assert\NotBlank(
     *     message = "Renseignez votre nom."
     * )
     * @Assert\MinLength(
     *     limit = 3,
     *     message = "Nom trop court!"
     * )
     */
    protected $name;
    /**
     * @Assert\NotBlank(
     *     message = "Renseignez votre adresse mail."
     * )
     * @Assert\Email(
     *     message = "Adresse email incorrecte."
     * )
     */
    protected $mail;
    /**
     * @Assert\NotBlank(
     *     message = "Quel-est le sujet de votre message?"
     * )
     * @Assert\MinLength(
     *     limit = 3,
     *     message = "Renseignez un sujet plus explicite!"
     * )
     */
    protected $subject;
    /**
     * @Assert\NotBlank(
     *     message = "Spécifiez votre demande."
     * )
     * @Assert\MinLength(
     *     limit = 20,
     *     message = "C'est tout ce que vous avez à dire? Un petit effort! :)"
     * )
     */
    protected $content;

    public function getName() {
        return $this->name;
    }
    public function setName($name) {
        $this->name = $name;
    }
    public function getMail() {
        return $this->mail;
    }
    public function setMail($mail) {
        $this->mail = $mail;
    }
    public function getSubject() {
        return $this->subject;
    }
    public function setSubject($subject) {
        $this->subject = $subject;
    }
    public function getContent() {
        return $this->content;
    }
    public function setContent($content) {
        $this->content = $content;
    }
}


text:
<?php

namespace Admin\Controller;

use Zend\Mvc\Controller\AbstractActionController;
use Zend\Session\Container;

use Admin\Form\LoginForm;

use Application\Database\TableModel\User;
use Application\Helper\Messenger;

class LoginController extends AbstractActionController
{
    protected $logged;

    public function indexAction()
    {
        $this->layout( "layout/empty" );
        $this->logged = new Container('user');
        $table = $this->getUserTable();
        $form = new LoginForm();

        if( !$this->logged->boolLogged )
        {
            $messenger = new Messenger;
            /*
             *  if user has chosen the option 'remember me on this PC', then load
             *  info from DB a redirect to admin
             */
            if( isset( $_COOKIE[ 'sleanded_admin' ] ) && $_COOKIE[ 'sleanded_admin' ] != '' )
            {
                $credentials = explode( ";" , $_COOKIE[ 'sleanded_admin' ] );
                $user = $table->autologin( $credentials[ 0 ], $credentials[ 1 ] );
                /*
                 * check, if the credentials in COOKIE are same as those in DB
                 */
                if( count( $user ) == 1 )
                {
                    $user = $user[0];
                    $this->registerSession($user, $this->logged);
                    return $this->redirect()->toRoute('admin', array(
                                        'controller' => 'index'
                    ));
                }
                /*
                 * otherwise unset cookie and display login form
                 */
                else
                {

                    unset( $_COOKIE['sleanded_admin'] );
                    setcookie('sleanded_admin', '', time() - 3600);
                    $message = [ "Autologin failed, please log in" , Messenger::ERROR ];
                }
            }

            $request = $this->getRequest();
            if( $request->isPost( ) )
            {
                $form->addInputFilter();
                $form->setData( $request->getPost( ) );
                if( $form->isValid( ) )
                {
                    /*
                     * checks, if a pass & name are OK
                     */
                    $u = new User( );
                    $u->exchangeArray( $request->getPost( ) );
                    $user = $table->login( $u->name, $u->password );

                    if( count( $user ) == 1 )
                    {
                        /* registering session
                         * ----------------
                         * if option 'remember me on this PC' is selected:
                         * save cookie + set param to DB
                         */
                        $user = $user[0];
                        $this->registerSession($user, $this->logged);
                        if( $u->remember == 1 )
                        {
                            setcookie (
                                'sleanded_admin',
                                $user['name'].';'.$user['password'],
                                time() + ( 3600*24*15 )
                            );
                            $table->edit( $user['id'], [ 'ip' => $_SERVER['REMOTE_ADDR'], 'remember' => 1 ] );
                        }
                        /*
                         * redirecting to admin index page
                         */
                        return $this->redirect()->toRoute('admin', array(
                            'controller' => 'index'
                        ));
                    }
                    else
                    {
                        $message = [ "Invalid name/email or password. Please, try to log in again!" , Messenger::ERROR ];
                    }
                }
                else
                {
                    $message = [ "All form fields have to be filled!" , Messenger::NOTICE ];
                }
            }
        }
        else
        {
            $this->logout( );
        }

        return [
            'message'       => isset( $message ) ? $message : null,
            'loginForm'     => $form,
        ];
    }

    /*************************************************************************\
     | Private functions                                                          |
    \*************************************************************************/

    /**
     * Returns an isntance of users table
     * @return Admin\Database\UserTable
     */
    private function getUserTable()
    {
        return $this->getServiceLocator()->get('Application\Database\UserTable');
    }

    /**
     * Registers a session for logged user
     * @return void
     */
    private function registerSession( $data, $container ) {
        $container->name = $data[ 'name' ];
        $container->id = $data[ 'id' ];
        $container->fullName = $data[ 'full_name' ];
        $container->boolLogged = true;
    }

    /**
     * Logout function
     * @return void
     */
    private function logout( )
    {
        /*
         * cleaning cookies
         */
        unset( $_COOKIE['sleanded_admin'] );
        setcookie('sleanded_admin', '', time() - 3600);

        /*
         * turning off remember in db
         */
        $table = $this->getUserTable();
        $u = $table->select( [ 'name' => $this->logged->name ] )->toArray();
        $table->edit( $u[0]['id'], [ 'remember' => 0 ] );

        /*
         * cleaning session
         */
        $this->logged->getManager()->getStorage()->clear('user');

        /*
         * redirect
         */
        return $this->redirect()->toRoute('admin', array(
            'controller' => 'index'
        ));
    }
}