text:
"""
G R A D I E N T - E N H A N C E D   N E U R A L   N E T W O R K S  (G E N N)

Author: Steven H. Berguin <steven.berguin@gtri.gatech.edu>

This package is distributed under New BSD license.
"""

from smt.surrogate_models.surrogate_model import SurrogateModel
from smt.utils.neural_net.model import Model

import numpy as np

# ------------------------------------ S U P P O R T   F U N C T I O N S -----------------------------------------------

def load_smt_data(model, xt, yt, dyt_dxt=None):
    """
    Utility function to load SMT data more easily

    :param model: SurrogateModel object for which to load training data
    :param xt: smt data points at which response is evaluated
    :param yt: response at xt
    :param dyt_dxt: gradient at xt
    """
    # Dimensionality
    if len(xt.shape) == 1:
        n_x = 1  # number of variables, x
        m = xt.size
    else:
        m, n_x = xt.shape

    if len(yt.shape) == 1:
        n_y = 1  # number of responses, y
    else:
        n_y = yt.shape[1]

    # Reshape arrays
    xt = xt.reshape((m, n_x))
    yt = yt.reshape((m, n_y))

    # Load values
    model.set_training_values(xt, yt)

    # Load partials
    if dyt_dxt is not None:
        dyt_dxt = dyt_dxt.reshape((m, n_x))
        for i in range(n_x):
            model.set_training_derivatives(xt, dyt_dxt[:, i].reshape((m, 1)), i)

def smt_to_genn(training_points):
    """
    Translate from SMT data structure to GENN data structure.

    Concretely, this neural net module works with numpy arrays in the form of (X, Y, J) as defined here-under. However,
    SMT uses a different format. Hence, we need a function that takes care of the translation.

    :param: training_points -- dict, training data in the format used by surrogate_model.py (see SMT API)

    Returns:
    :return X -- a numpy matrix of input features of shape (n_x, m) where n_x = no. of inputs, m = no. of train examples
    :return Y -- a numpy matrix of output labels of shape (n_y, m) where n_y = no. of outputs
    :return J -- a numpy array of size (n_y, n_x, m) representing the Jacobian of Y w.r.t. X:

        dY1/dX1 = J[0][0][:]
        dY1/dX2 = J[0][1][:]
        ...
        dY2/dX1 = J[1][0][:]
        dY2/dX2 = J[1][1][:]
        ...

        N.B. To retrieve the i^th example for dY2/dX1: J[1][0][i] for all i = 1,...,m

    """
    # Retrieve training data from SMT training_points
    xt, yt = training_points[None][
        0
    ]  # training_points[name][0] = [np.array(xt), np.array(yt)]

    # Deduce number of dimensions and training examples
    m, n_x = xt.shape
    _, n_y = yt.shape

    # Assign training data but transpose to match neural net implementation
    X = xt
    Y = yt

    # Loop to retrieve each partial derivative from SMT training_points
    J = np.zeros((m, n_x, n_y))
    for k in range(0, n_x):
        xt, dyt_dxt = training_points[None][k + 1]

        # assert that dimensions match
        assert xt.shape[0] == m
        assert xt.shape[1] == n_x
        assert dyt_dxt.shape[0] == m
        assert dyt_dxt.shape[1] == n_y

        # Assert that derivatives provided are for the same training points
        assert xt.all() == X.all()

        # Assign training derivative but transpose to match neural net implementation
        J[:, k, :] = dyt_dxt

    return X.T, Y.T, J.T

# ------------------------------------ C L A S S -----------------------------------------------------------------------

class GENN(SurrogateModel):
    def _initialize(self):
        """API function: set default values for user options"""
        declare = self.options.declare
        declare("alpha", 0.5, types=(int, float), desc="optimizer learning rate")
        declare(
            "beta1", 0.9, types=(int, float), desc="Adam optimizer tuning parameter"
        )
        declare(
            "beta2", 0.99, types=(int, float), desc="Adam optimizer tuning parameter"
        )
        declare("lambd", 0.1, types=(int, float), desc="regularization coefficient")
        declare(
            "gamma", 1.0, types=(int, float), desc="gradient-enhancement coefficient"
        )
        declare("deep", 2, types=int, desc="number of hidden layers")
        declare("wide", 2, types=int, desc="number of nodes per hidden layer")
        declare(
            "mini_batch_size",
            64,
            types=int,
            desc="split data into batches of specified size",
        )
        declare(
            "num_epochs", 10, types=int, desc="number of random passes through the data"
        )
        declare(
            "num_iterations",
            100,
            types=int,
            desc="number of optimizer iterations per mini-batch",
        )
        declare(
            "seed",
            None,
            types=int,
            desc="random seed to ensure repeatability of results when desired",
        )
        declare("is_print", True, types=bool, desc="print progress (or not)")

        self.supports["derivatives"] = True
        self.supports["training_derivatives"] = True
        self.name = "GENN"

        self.model = Model()

        self._is_trained = False

    def _train(self):
        """
        API function: train the neural net
        """
        # Convert training data to format expected by neural net module
        X, Y, J = smt_to_genn(self.training_points)

        # If there are no training derivatives, turn off gradient-enhancement
        if type(J) == np.ndarray and J.size == 0:
            self.options["gamma"] = 0.0

        # Get hyperparameters from SMT API
        alpha = self.options["alpha"]
        beta1 = self.options["beta1"]
        beta2 = self.options["beta2"]
        lambd = self.options["lambd"]
        gamma = self.options["gamma"]
        deep = self.options["deep"]
        wide = self.options["wide"]
        mini_batch_size = self.options["mini_batch_size"]
        num_iterations = self.options["num_iterations"]
        num_epochs = self.options["num_epochs"]
        seed = self.options["seed"]
        is_print = self.options["is_print"]

        # number of inputs and outputs
        n_x = X.shape[0]
        n_y = Y.shape[0]

        # Train neural net
        self.model = Model.initialize(n_x, n_y, deep, wide)
        self.model.train(
            X=X,
            Y=Y,
            J=J,
            num_iterations=num_iterations,
            mini_batch_size=mini_batch_size,
            num_epochs=num_epochs,
            alpha=alpha,
            beta1=beta1,
            beta2=beta2,
            lambd=lambd,
            gamma=gamma,
            seed=seed,
            silent=not is_print,
        )

        self._is_trained = True

    def _predict_values(self, x):
        """
        API method: predict values using appropriate methods from the neural_network.py module

        :param  x: np.ndarray[n, nx] -- Input values for the prediction points
        :return y: np.ndarray[n, ny] -- Output values at the prediction points
        """
        return self.model.evaluate(x.T).T

    def _predict_derivatives(self, x, kx):
        """
        API method: predict partials using appropriate methods from the neural_network.py module

        :param  x: np.ndarray[n, nx] -- Input values for the prediction points
        :param kx: int -- The 0-based index of the input variable with respect to which derivatives are desired
        :return: dy_dx: np.ndarray[n, ny] -- partial derivatives
        """
        return self.model.gradient(x.T)[:, kx, :].T

    def plot_training_history(self):
        if self._is_trained:
            self.model.plot_training_history()

    def goodness_of_fit(self, xv, yv, dyv_dxv):
        """
        Compute metrics to evaluate goodness of fit and show actual by predicted plot

        :param xv: np.ndarray[n, nx], x validation points
        :param yv: np.ndarray[n, 1], y validation response
        :param dyv_dxv: np.ndarray[n, ny], dydx validation derivatives
        """
        # Store current training points
        training_points = self.training_points

        # Replace training points with test (validation) points
        load_smt_data(self, xv, yv, dyv_dxv)

        # Convert from SMT format to a more convenient format for GENN
        X, Y, J = smt_to_genn(self.training_points)

        # Generate goodness of fit plots
        self.model.goodness_of_fit(X, Y)

        # Restore training points
        self.training_points = training_points

def run_example(is_gradient_enhancement=True):  # pragma: no cover
    """Test and demonstrate GENN using a 1D example"""
    import matplotlib.pyplot as plt

    # Test function
    f = lambda x: x * np.sin(x)
    df_dx = lambda x: np.sin(x) + x * np.cos(x)

    # Domain
    lb = -np.pi
    ub = np.pi

    # Training data
    m = 4
    xt = np.linspace(lb, ub, m)
    yt = f(xt)
    dyt_dxt = df_dx(xt)

    # Validation data
    xv = lb + np.random.rand(30, 1) * (ub - lb)
    yv = f(xv)
    dyv_dxv = df_dx(xv)

    # Initialize GENN object
    genn = GENN()
    genn.options["alpha"] = 0.1
    genn.options["beta1"] = 0.9
    genn.options["beta2"] = 0.99
    genn.options["lambd"] = 0.1
    genn.options["gamma"] = int(is_gradient_enhancement)
    genn.options["deep"] = 2
    genn.options["wide"] = 6
    genn.options["mini_batch_size"] = 64
    genn.options["num_epochs"] = 20
    genn.options["num_iterations"] = 100
    genn.options["is_print"] = True

    # Load data
    load_smt_data(genn, xt, yt, dyt_dxt)

    # Train
    genn.train()
    genn.plot_training_history()
    genn.goodness_of_fit(xv, yv, dyv_dxv)

    # Plot comparison
    if genn.options["gamma"] == 1.0:
        title = "with gradient enhancement"
    else:
        title = "without gradient enhancement"
    x = np.arange(lb, ub, 0.01)
    y = f(x)
    y_pred = genn.predict_values(x)
    fig, ax = plt.subplots()
    ax.plot(x, y_pred)
    ax.plot(x, y, "k--")
    ax.plot(xv, yv, "ro")
    ax.plot(xt, yt, "k+", mew=3, ms=10)
    ax.set(xlabel="x", ylabel="y", title=title)
    ax.legend(["Predicted", "True", "Test", "Train"])
    plt.show()

if __name__ == "__main__":  # pragma: no cover
    run_example(is_gradient_enhancement=True)


text:
<!DOCTYPE html>

		<title>Setup TOTP</title>
		<link rel="stylesheet" type="text/css" href="/css">

			<#if errMsg??>

					${errMsg?html}

			</#if>
			To enable two-factor authentication, you need an authenticator application on your smart phone. For example, the Google Authenticator app:

			Install Google Authenticator for Android.

			Install Google Authenticator for iPhone / iPad.

			Start your authenticator application on your smart phone, set up an account, and choose the 'scan a barcode' option.

			Enter the code displayed on your device to confirm the setup.

			<form class="midPageForm" action="/confirm-totp-setup" method="POST">
				<input name="code" autocomplete="off" placeholder="code" />

				<input type="hidden" name="key" value="${key}">
				<input type="submit" value="Confirm" />
			</form>

				You should obviously never give this in a real TOTP application, but as a demo, here are some TOTP codes that your phone would be telling you if you scanned the QR code:

				Correct code:  ${correctTotpCode}

				If your phone is three minutes ahead: ${threeMinutesOutCode}

				If your phone has the wrong Daylight Savings Time setting: ${hourOutCode}

				Give these a try to see what the demo app does. Also, of course, try a random code as well,
				such as 000042. We determined that one by random dice roll, we swear.

redpajama_set_name: RedPajamaGithub


text:
{% set _TWITTER_SHOW_FOLLOWER_COUNT = TWITTER_SHOW_FOLLOWER_COUNT|default(True)|string|lower %}
{% set _TWITTER_SHOW_REPLIES = TWITTER_SHOW_REPLIES|default(False)|string|lower %}

{% if TWITTER_USER %}

  {% if TWITTER_WIDGET %}

Latest Tweets

Status updating...

  {% endif %}
  {% if TWITTER_FOLLOW_BUTTON %}
    Follow @{{ TWITTER_USER }}
  {% else %}

Follow @{{ TWITTER_USER }}

  {% endif %}

{% endif %}


text:
package edu.kit.ipd.crowdcontrol.objectservice.database.transformers;

import edu.kit.ipd.crowdcontrol.objectservice.database.model.tables.records.CalibrationAnswerOptionRecord;
import edu.kit.ipd.crowdcontrol.objectservice.database.model.tables.records.CalibrationRecord;
import edu.kit.ipd.crowdcontrol.objectservice.proto.Calibration;

import java.util.List;
import java.util.stream.Collectors;

/**
 * Transforms calibration protocol buffers to database records.
 *
 * @author Niklas Keller
 */
public class CalibrationTransformer extends AbstractTransformer {
    /**
     * Converts a calibration record to its protobuf representation.
     *
     * @param record calibration record
     *
     * @return calibration.
     */
    public static Calibration toProto(CalibrationRecord record, List<CalibrationAnswerOptionRecord> options) {
        return Calibration.newBuilder()
                .setId(record.getIdCalibration())
                .setName(record.getName())
                .setQuestion(record.getProperty())
                .addAllAnswers(
                        options.stream()
                                .map(option ->
                                        Calibration.Answer.newBuilder()
                                        .setAnswer(option.getAnswer())
                                        .setId(option.getIdCalibrationAnswerOption())
                                        .build()
                                )
                                .collect(Collectors.toList()))
                .build();
    }

    /**
     * Merges a record with the set properties of a protobuf calibration.
     *
     * @param target record to merge into
     * @param calibration message to merge from
     *
     * @return Merged calibration record.
     */
    public static CalibrationRecord mergeRecord(CalibrationRecord target, Calibration calibration) {
        return merge(target, calibration, (fieldNumber, record) -> {
            switch (fieldNumber) {
                case Calibration.NAME_FIELD_NUMBER:
                    record.setName(calibration.getName());
                case Calibration.QUESTION_FIELD_NUMBER:
                    record.setProperty(calibration.getQuestion());
                    break;
            }
        });
    }
}


text:
<?php

require_once(__DIR__.'/vendor/autoload.php');

use \Arcanedev\NoCaptcha\NoCaptchaV2;

$captcha = new NoCaptchaV2(
    'your-secret-key',
    'your-site-key'
);

if ($_POST) {
    $response = $captcha->verify($_POST['g-recaptcha-response'] ?? null);

    echo $response->isSuccess()
        ? 'Yay ! You are a human.'
        : 'No ! You are a robot.';

    exit();
}

?>

<form method="POST">
    <?php echo $captcha->display(); ?>
    <button type="submit">Envoyer</button>
</form>

<?php echo $captcha->script(); ?>


text:
require 'console_tweet/cli'

module ConsoleTweet

end


text:
/*
 * @author max
 */
package com.jetbrains.python.psi.stubs;

import com.intellij.psi.stubs.NamedStub;
import com.intellij.psi.util.QualifiedName;
import com.jetbrains.python.psi.PyClass;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;

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

public interface PyClassStub extends NamedStub<PyClass> {

  /**
   * @return a {@code Map} which contains imported class names as keys and their original names as values.
   * <i>Note: the returned {@code Map} could contain nulls as keys and as values.</i>
   */
  @NotNull
  Map<QualifiedName, QualifiedName> getSuperClasses();

  @Nullable
  QualifiedName getMetaClass();

  @Nullable
  List<String> getSlots();

  @Nullable
  String getDocString();

  /**
   * @return literal text of expressions in the base classes list.
   */
  @NotNull
  List<String> getSuperClassesText();

  /**
   * @deprecated It is our internal API, try to avoid using it.
   * It is planned to be removed sooner or later, so please don't rely on this method.
   */
  @Deprecated(forRemoval = true)
  @Nullable
  default <T> T getCustomStub(@NotNull Class<T> stubClass) {
    return null;
  }
}


text:
//this is the controller for all database fetches, JSON operations on them and sending requested data to views

var mysql     =    require('mysql');
var moment    =    require('moment');

var pool      =    mysql.createPool({
    connectionLimit : 100, //important
    host     : 'drivendb.c777xq6yyhhm.ap-southeast-1.rds.amazonaws.com',
    user     : 'drivenuser',
    password : 'drivenbits',
    database : 'driven_analytics',
    timezone: 'utc',
    dateStrings : true,
    debug    :  false
});

var lat = 19.110834, lon = 72.886355;

//function dataController() {}; //creating the dataController class which will have the functions inside of it

exports.getAccelerationY = function(req,res) {

    var error = [];
    var status = [];

    var driverId = req.body.driverId;
    var tripId = req.body.tripId;

    pool.getConnection(function(err,connection){
        if (err) {
            connection.release();
            console.log("The error in getAy connecting to the db is: " + err);
            //res.json({error: "Oops! There was an error in connecting to the db."});
            res.json({error: JSON.stringify(err)});
            return;
        }
        connection.beginTransaction(function(err){
            console.log('connected as id ' + connection.threadId);

            //var query = ModelFunctionName.getAyQuery(driverId, tripId);

            //var query = "select timestamp as datetime, ay_max as high, ay_min as low, ay_avg as open, ay_avg as close from trip_details where driver_id = 0 and trip_id = 1 group by timestamp";
            var query = "select timestamp as x, ay_avg as y from trip_details where driver_id = 0 and trip_id = 1 and ay_avg between -0.42 and .74 group by timestamp";

            connection.query(query,[],function(err,rows){
                if(err) {
                    connection.rollback(function(){
                        connection.release();
                        console.log("The error in getAy retrieving from DB is: " + err);
                        res.json({error: "Oops! There was an error in retrieving the data from db."});
                        return;
                    });
                }
                else{

                    console.log("Data retrieved successfull and the data is: " + JSON.stringify(rows));

                    var newRows = fixTimeStamp(rows);

                    res.json({
                        success: 'Data for Ay sent successfully',
                        data: newRows
                    });
                }
            });

            connection.on('error', function(){
                connection.rollback(function(){
                    connection.release();
                    console.log("The error in general connection is: " + err);
                    res.json({error: "Oops! There was an error while connecting to the db."});
                    return;
                });
            });//connection.on error ends
        });//connection.beginTransaction ends
    });//pool.getConnection ends
};//exported getAccelerationY function ends

function fixTimeStamp (rows) {
    var time = (new Date).getTime();

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

        rows[i].x = time; //changing the timestamp value to current epoch based
        time = time + 1000; //increasing by 1000 milisecond for every reading
        /*rows[i].high = rows[i].open;
        rows[i].close += 0.001; //to bring about a change in open and close
        rows[i].low = rows[i].close;*/
    }

    console.log("the fixTimeStamp function changes the rows to: " + JSON.stringify(rows));

    return (rows);
}

exports.getDriverScores = function(req, res){

    var error = [];
    var status = [];

    var driverId = req.body.driverId;
    var tripId = req.body.tripId;

    /* uncomment whole block while retrieving from actual db instead of dummy data
    pool.getConnection(function(err,connection){
        if (err) {
            connection.release();
            console.log("The error in getScores connecting to the db is: " + err);
            //res.json({error: "Oops! There was an error in connecting to the db."});
            res.json({error: JSON.stringify(err)});
            return;
        }

        connection.beginTransaction(function(err){
            console.log('connected as id ' + connection.threadId);

            //use some kind of query like below to get the driver scores from the db
            var query = "select timestamp as x, overall_score as y from trip_details where driver_id = 0 and trip_id = 1 group by timestamp";

            connection.query(query,[],function(err,rows){
                if(err) {
                    connection.rollback(function(){
                        connection.release();
                        console.log("The error in getScores retrieving from DB is: " + err);
                        res.json({error: "Oops! There was an error in retrieving the data from db."});
                        return;
                    });
                }
                else{

                    console.log("Data retrieved successfully in getScores and the data is: " + JSON.stringify(rows));

                    var newRows = fixTimeStamp(rows);

                    res.json({
                        success: 'Data for Ay sent successfully',
                        data: newRows
                    });
                }
            });

            connection.on('error', function(){
                connection.rollback(function(){
                    connection.release();
                    console.log("The error in general connection is: " + err);
                    res.json({error: "Oops! There was an error while connecting to the db."});
                    return;
                });
            });//connection.on error ends
        });//connection.beginTransaction ends
    });//pool.getConnection ends

uncomment whole block while retrieving from actual db instead of dummy data */

//dummy data for now about the scores
var newRows = [
    {
      "x": 1462125381603,
      "y": 67
    },
    {
      "x": 1462126382603,
      "y": 69
    },
    {
      "x": 1462127383603,
      "y": 70
    },
    {
      "x": 1462128384603,
      "y": 70
    },
    {
      "x": 1462129385603,
      "y": 69
    },
    {
      "x": 1462130386603,
      "y": 70
    },
    {
      "x": 1462131387603,
      "y": 71
    },
    {
      "x": 1462132388603,
      "y": 72
    },
    {
      "x": 1462133389603,
      "y": 73
    },
    {
      "x": 1462134390603,
      "y": 74
    },
    {
      "x": 1462135388603,
      "y": 74
    },
    {
      "x": 1462136389603,
      "y": 75
    },
    {
      "x": 1462137390603,
      "y": 75
    },
    {
      "x": 1462138388603,
      "y": 76
    },
    {
      "x": 1462139389603,
      "y": 77
    },
    {
      "x": 1462140390603,
      "y": 77
    }
];

var avg_Score = (67+69+70+70+69+70+71+72+73+74+74+75+75+76+77+77)/16;

    res.json({
                success: 'Data for getScores sent successfully',
                data: newRows,
                over_score: avg_Score
            });

}//getDriverScores ends here

exports.getEvents = function(req, res){

    var error = [];
    var status = [];

    var driverId = req.body.driverId;
    var tripId = req.body.tripId;

    /* uncomment whole block while retrieving from actual db instead of dummy data
    pool.getConnection(function(err,connection){
        if (err) {
            connection.release();
            console.log("The error in getScores connecting to the db is: " + err);
            //res.json({error: "Oops! There was an error in connecting to the db."});
            res.json({error: JSON.stringify(err)});
            return;
        }

        connection.beginTransaction(function(err){
            console.log('connected as id ' + connection.threadId);

            //use some kind of query like below to get the driver scores from the db
            var query = "select timestamp as x, overall_score as y from trip_details where driver_id = 0 and trip_id = 1 group by timestamp";

            connection.query(query,[],function(err,rows){
                if(err) {
                    connection.rollback(function(){
                        connection.release();
                        console.log("The error in getScores retrieving from DB is: " + err);
                        res.json({error: "Oops! There was an error in retrieving the data from db."});
                        return;
                    });
                }
                else{

                    console.log("Data retrieved successfully in getScores and the data is: " + JSON.stringify(rows));

                    var newRows = fixTimeStamp(rows);

                    res.json({
                        success: 'Data for Ay sent successfully',
                        data: newRows
                    });
                }
            });

            connection.on('error', function(){
                connection.rollback(function(){
                    connection.release();
                    console.log("The error in general connection is: " + err);
                    res.json({error: "Oops! There was an error while connecting to the db."});
                    return;
                });
            });//connection.on error ends
        });//connection.beginTransaction ends
    });//pool.getConnection ends

uncomment whole block while retrieving from actual db instead of dummy data */

//dummy data for now about the scores
var newRows = [
    {
      "label": "Hard Breaking",
      "value": 11
    },
    {
      "label": "Hard Turns",
      "value": 4
    },
    {
      "label": "Rash Acceleration",
      "value": 15
    }
];

    res.json({
                success: 'Data for getEvents sent successfully',
                data: newRows
            });

}//getEvents ends here

exports.getHardAccs = function(req,res) {

    var error = [];
    var status = [];

    var driverId = req.body.driverId;
    var tripId = req.body.tripId;

    pool.getConnection(function(err,connection){
        if (err) {
            connection.release();
            console.log("The error in getHA connecting to the db is: " + err);
            //res.json({error: "Oops! There was an error in connecting to the db."});
            res.json({error: JSON.stringify(err)});
            return;
        }
        connection.beginTransaction(function(err){
            console.log('connected as id ' + connection.threadId);

            //var query = ModelFunctionName.getAyQuery(driverId, tripId);

            //var query = "select timestamp as datetime, ay_max as high, ay_min as low, ay_avg as open, ay_avg as close from trip_details where driver_id = 0 and trip_id = 1 group by timestamp";
            var query = "select timestamp as x, ay as y from trip_details where driver_id = 0 and trip_id = 1 group by timestamp";

            connection.query(query,[],function(err,rows){
                if(err) {
                    connection.rollback(function(){
                        connection.release();
                        console.log("The error in getHA retrieving from DB is: " + err);
                        res.json({error: "Oops! There was an error in retrieving the data from db."});
                        return;
                    });
                }
                else{

                    console.log("Data retrieved successfull and the data is: " + JSON.stringify(rows));

                    var HA_data = calc_HA(rows);

                    res.json({
                        success: 'Data for HA sent successfully',
                        data: HA_data
                    });
                }
            });

            connection.on('error', function(){
                connection.rollback(function(){
                    connection.release();
                    console.log("The error in general connection is: " + err);
                    res.json({error: "Oops! There was an error while connecting to the db."});
                    return;
                });
            });//connection.on error ends
        });//connection.beginTransaction ends
    });//pool.getConnection ends
};//exported getAccelerationY function ends

function calc_HA (rows) {

   // code for calculating max and min for every 3 seconds
   //more efficient - extract this in a separate function that will return a JSON object of these 4 arrays?

    max_values = []; //length will be rows.length - 3
    max_times = []; //length will be rows.length - 3
    min_values = []; //length will be rows.length - 3
    min_times = []; //length will be rows.length - 3

    max_diff = 0;
    diff=0;

    for(i=0; i<(rows.length-2); i++) {
       //say rows.y has LaY and rows.x has time
       max_values[i] = rows.y[i];
       max_times[i] = rows.x[i];
       min_values[i] = rows.y[i];
       min_times[i] = rows.x[i];

       for(j=i; j<i+3; j++) {
            if(rows.y[j]>max_values[i]) {
                max_values[i] = rows.y[j];
                max_times[i] = rows.x[j];
            }
            if(rows.y[j]<min_values[i]) {
                min_values[i] = rows.y[j];
                min_times[i] = rows.x[j];
            }

            max_diff = ((max_values[i]-min_values[i])>max_diff) ? (max_values[i]-min_values[i]) : max_diff;

       } //for j loop ends
    }//for i loop ends

ha_events = [];

for(i=0; i<(rows.length-2);i++) {

    diff = max_values[i] - min_values[i];
    if( diff>(0.66*max_diff) )
        ha_events[i] = i
}

    //write separate logic to compose JSON of data

    console.log("the calc_HA function is sending this data back: " + JSON.stringify(data));

    return (data);
}

exports.getLocation = function(req, res){

    var error = [];
    var status = [];

    var driverId = req.body.driverId;
    var tripId = req.body.tripId;

    console.log("Get location API hit");

    if(driverId!=0 || tripId!=1) {
        console.log("Wrong driver or trip ID!");
        res.json({error:'incorrect ids'});
        return;
    }

    /* uncomment whole block while retrieving from actual db instead of dummy data
    pool.getConnection(function(err,connection){
        if (err) {
            connection.release();
            console.log("The error in getScores connecting to the db is: " + err);
            //res.json({error: "Oops! There was an error in connecting to the db."});
            res.json({error: JSON.stringify(err)});
            return;
        }

        connection.beginTransaction(function(err){
            console.log('connected as id ' + connection.threadId);

            //use some kind of query like below to get the driver scores from the db
            var query = "select timestamp as x, overall_score as y from trip_details where driver_id = 0 and trip_id = 1 group by timestamp";

            connection.query(query,[],function(err,rows){
                if(err) {
                    connection.rollback(function(){
                        connection.release();
                        console.log("The error in getScores retrieving from DB is: " + err);
                        res.json({error: "Oops! There was an error in retrieving the data from db."});
                        return;
                    });
                }
                else{

                    console.log("Data retrieved successfully in getScores and the data is: " + JSON.stringify(rows));

                    var newRows = fixTimeStamp(rows);

                    res.json({
                        success: 'Data for Ay sent successfully',
                        data: newRows
                    });
                }
            });

            connection.on('error', function(){
                connection.rollback(function(){
                    connection.release();
                    console.log("The error in general connection is: " + err);
                    res.json({error: "Oops! There was an error while connecting to the db."});
                    return;
                });
            });//connection.on error ends
        });//connection.beginTransaction ends
    });//pool.getConnection ends

uncomment whole block while retrieving from actual db instead of dummy data */

    lat = lat + 0.000010;
    lon = lon + 0.000020;

    if(lat>19.999999 || lon>72.999999) {
        lat = 19.110834;
        lon = 72.886355;
    }

    var newLocation = { "location":
                        [{"latitude": lat, "longitude": lon}]
                        };

    res.json({
                success: 'Data for getLocation sent successfully',
                data: newLocation
            });
    return;

}//getLocation ends here

// for explicit based exporting - module.exports


text:
var initValuesDict = {"method" : "POST",
                      "body" : "Request's body"
};

var noBodyConsumed = new Request("");
var bodyConsumed = new Request("", initValuesDict);

test(() => {
  assert_equals(noBodyConsumed.body, null, "body's default value is null");
  assert_false(noBodyConsumed.bodyUsed , "bodyUsed is false when request is not disturbed");
  assert_not_equals(bodyConsumed.body, null, "non-null body");
  assert_true(bodyConsumed.body instanceof ReadableStream, "non-null body type");
  assert_false(noBodyConsumed.bodyUsed, "bodyUsed is false when request is not disturbed");
}, "Request's body: initial state");

noBodyConsumed.blob();
bodyConsumed.blob();

test(function() {
  assert_false(noBodyConsumed.bodyUsed , "bodyUsed is false when request is not disturbed");
  try {
    noBodyConsumed.clone();
  } catch (e) {
    assert_unreached("Can use request not disturbed for creating or cloning request");
  }
}, "Request without body cannot be disturbed");

test(function() {
  assert_true(bodyConsumed.bodyUsed , "bodyUsed is true when request is disturbed");
  assert_throws_js(TypeError, function() { bodyConsumed.clone(); });
}, "Check cloning a disturbed request");

test(function() {
  assert_true(bodyConsumed.bodyUsed , "bodyUsed is true when request is disturbed");
  assert_throws_js(TypeError, function() { new Request(bodyConsumed); });
}, "Check creating a new request from a disturbed request");

promise_test(function() {
  assert_true(bodyConsumed.bodyUsed , "bodyUsed is true when request is disturbed");
  const originalBody = bodyConsumed.body;
  const bodyReplaced = new Request(bodyConsumed, { body: "Replaced body" });
  assert_not_equals(bodyReplaced.body, originalBody, "new request's body is new");
  assert_false(bodyReplaced.bodyUsed, "bodyUsed is false when request is not disturbed");
  return bodyReplaced.text().then(text => {
    assert_equals(text, "Replaced body");
  });
}, "Check creating a new request with a new body from a disturbed request");

promise_test(function() {
  var bodyRequest = new Request("", initValuesDict);
  const originalBody = bodyRequest.body;
  assert_false(bodyRequest.bodyUsed , "bodyUsed is false when request is not disturbed");
  var requestFromRequest = new Request(bodyRequest);
  assert_true(bodyRequest.bodyUsed , "bodyUsed is true when request is disturbed");
  assert_equals(bodyRequest.body, originalBody, "body should not change");
  assert_not_equals(originalBody, undefined, "body should not be undefined");
  assert_not_equals(originalBody, null, "body should not be null");
  assert_not_equals(requestFromRequest.body, originalBody, "new request's body is new");
  return requestFromRequest.text().then(text => {
    assert_equals(text, "Request's body");
  });
}, "Input request used for creating new request became disturbed");

promise_test(() => {
  const bodyRequest = new Request("", initValuesDict);
  const originalBody = bodyRequest.body;
  assert_false(bodyRequest.bodyUsed , "bodyUsed is false when request is not disturbed");
  const requestFromRequest = new Request(bodyRequest, { body : "init body" });
  assert_true(bodyRequest.bodyUsed , "bodyUsed is true when request is disturbed");
  assert_equals(bodyRequest.body, originalBody, "body should not change");
  assert_not_equals(originalBody, undefined, "body should not be undefined");
  assert_not_equals(originalBody, null, "body should not be null");
  assert_not_equals(requestFromRequest.body, originalBody, "new request's body is new");

  return requestFromRequest.text().then(text => {
    assert_equals(text, "init body");
  });
}, "Input request used for creating new request became disturbed even if body is not used");

promise_test(function(test) {
  assert_true(bodyConsumed.bodyUsed , "bodyUsed is true when request is disturbed");
  return promise_rejects_js(test, TypeError, bodyConsumed.blob());
}, "Check consuming a disturbed request");

test(function() {
  var req = new Request(URL, {method: 'POST', body: 'hello'});
  assert_false(req.bodyUsed,
                'Request should not be flagged as used if it has not been ' +
                'consumed.');
  assert_throws_js(TypeError,
    function() { new Request(req, {method: 'GET'}); },
    'A get request may not have body.');

  assert_false(req.bodyUsed, 'After the GET case');

  assert_throws_js(TypeError,
    function() { new Request(req, {method: 'CONNECT'}); },
    'Request() with a forbidden method must throw.');

  assert_false(req.bodyUsed, 'After the forbidden method case');

  var req2 = new Request(req);
  assert_true(req.bodyUsed,
              'Request should be flagged as used if it has been consumed.');
}, 'Request construction failure should not set "bodyUsed"');


text:
/**
 * Cockpit Import module build file
 */

var gulp = require('gulp');
var pkg = require('./package.json');
var path = pkg.config.path;

/**
 * Build task
 */
gulp.task('build', function buildTask(cb) {

    // Copy vendor dist files into assets folder
    var files = [
        path.vendor + '/papaparse/papaparse.js',
        path.vendor + '/papaparse/papaparse.min.js',
    ];

    gulp.src(files)
        .pipe(gulp.dest(path.src + '/assets/3p'));
    ;
});

/**
 * Default task
 */
gulp.task('default', [
    'build'
]);


text:
"""Tests for base templates."""

import unittest

from django.test import client

from soc.modules.gci.views import base_templates
from soc.modules.gci.views.helper import request_data

from tests import profile_utils

class LoggedInAsTest(unittest.TestCase):
  """Unit tests for LoggedInAs template."""

  def testForLoggedInUser(self):
    """Tests context for a logged in user."""
    user = profile_utils.seedNDBUser()
    profile_utils.loginNDB(user)

    request = client.RequestFactory().get('http://some-unused.url.com/')

    data = request_data.RequestData(request, None, None)
    context = base_templates.LoggedInAs(data).context()

    # check that LOGOUT_LINK_LABEL is used as link label
    self.assertEqual(context['link_label'], base_templates.LOGOUT_LINK_LABEL)

    # check that logged_in_as is set to user email
    self.assertEqual(context['logged_in_as'], 'test@example.com')

  def testForNotLoggedInUser(self):
    """Tests context for a not logged in user."""
    profile_utils.logout()

    request = client.RequestFactory().get('http://some-unused.url.com/')

    data = request_data.RequestData(request, None, None)
    context = base_templates.LoggedInAs(data).context()

    # check that LOGIN_LINK_LABEL is used as link label
    self.assertEqual(context['link_label'], base_templates.LOGIN_LINK_LABEL)

    # check that logged_in_as is set to the default text for not logged users
    self.assertEqual(context['logged_in_as'], base_templates.NOT_LOGGED_IN)


text:
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
         xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
    <parent>
        <artifactId>spring-session-Hazelcast</artifactId>
        <groupId>com.example</groupId>
        <version>1.0.0-SNAPSHOT</version>
    </parent>
    <packaging>jar</packaging>
    <modelVersion>4.0.0</modelVersion>

    <artifactId>Spring-session</artifactId>

    <dependencies>

        <dependency>
            <groupId>org.springframework.session</groupId>
            <artifactId>spring-session</artifactId>
        </dependency>

        <dependency>
            <groupId>com.hazelcast</groupId>
            <artifactId>hazelcast-client</artifactId>
            <version>${hazelcast.version}</version>
        </dependency>

        <dependency>
            <groupId>com.example</groupId>
            <artifactId>Spring-session-entity</artifactId>
            <version>1.0.0-SNAPSHOT</version>
        </dependency>

    </dependencies>
</project>


text:
<?php
namespace OpenCFP\Controller\Admin;

use Silex\Application;
use Symfony\Component\HttpFoundation\Request;
use Pagerfanta\View\TwitterBootstrap3View;

class DashboardController
{
    use AdminAccessTrait;

    private function indexAction(Request $req, Application $app)
    {
        $user_mapper = $app['spot']->mapper('OpenCFP\Entity\User');
        $speaker_total = $user_mapper->all()->count();

        $talk_mapper = $app['spot']->mapper('OpenCFP\Entity\Talk');
        $favorite_mapper = $app['spot']->mapper('OpenCFP\Entity\Favorite');
        $recent_talks = $talk_mapper->getRecent($app['sentry']->getUser()->getId());

        $template = $app['twig']->loadTemplate('admin/index.twig');
        $templateData = array(
            'speakerTotal' => $speaker_total,
            'talkTotal' => $talk_mapper->all()->count(),
            'favoriteTotal' => $favorite_mapper->all()->count(),
            'selectTotal' => $talk_mapper->all()->where(['selected' => 1])->count(),
            'talks' => $recent_talks
        );

        return $template->render($templateData);
    }
}


text:
package cn.jsprun.dao.impl;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;
import org.hibernate.HibernateException;
import org.hibernate.Query;
import org.hibernate.Session;
import org.hibernate.Transaction;
import cn.jsprun.dao.MembersDao;
import cn.jsprun.domain.Access;
import cn.jsprun.domain.Forums;
import cn.jsprun.domain.Medals;
import cn.jsprun.domain.Memberfields;
import cn.jsprun.domain.Members;
import cn.jsprun.domain.Onlinetime;
import cn.jsprun.domain.Pms;
import cn.jsprun.domain.Profilefields;
import cn.jsprun.domain.Ranks;
import cn.jsprun.domain.Styles;
import cn.jsprun.domain.Usergroups;
import cn.jsprun.domain.Validating;
import cn.jsprun.utils.HibernateUtil;
public class MembersDaoImpl implements MembersDao {
	public Members findMemberById(int memberId) {
		Session session = HibernateUtil.getSessionFactory().getCurrentSession();
		Transaction tr = null;
		try{
			tr = session.beginTransaction();
			Members member = (Members) session.get(Members.class, memberId);
			tr.commit();
			return member;
		}catch(HibernateException e){
			if (tr != null) {
				tr.rollback();
			}
			e.printStackTrace();
		}
		return null;
	}
	public Members findMemberByName(String username) {
		Session session = HibernateUtil.getSessionFactory().getCurrentSession();
		Transaction tr = null;
		try{
			tr = session.beginTransaction();
			Query query = session.createQuery("from Members m where m.username =?");
			query.setString(0, username);
			Members member=(Members)query.uniqueResult();
			tr.commit();
			return member;
		}catch(HibernateException e){
			if (tr != null) {
				tr.rollback();
			}
			e.printStackTrace();
		}
		return null;
	}
	public Members findByNameAndGroups(String memberName, String groupIds) {
		Session session = HibernateUtil.getSessionFactory().getCurrentSession();
		Transaction tr = null;
		try{
			tr = session.beginTransaction();
			Query query = session
					.createQuery("from Members m where m.username = :memberName and m.groupid in ("
							+ groupIds + ")");
			query.setString("memberName", memberName);
			List<Members> list = query.list();
			tr.commit();
			if (list != null && list.size() == 1) {
				return list.get(0);
			}
		}catch(HibernateException e){
			if (tr != null) {
				tr.rollback();
			}
			e.printStackTrace();
		}
		return null;
	}
	public boolean insertMember(Members member) {
		Session session = HibernateUtil.getSessionFactory().getCurrentSession();
		Transaction tr = null;
		try{
			tr = session.beginTransaction();
			session.save(member);
			session.flush();
			tr.commit();
			return true;
		}catch(HibernateException e){
			if (tr != null) {
				tr.rollback();
			}
			e.printStackTrace();
		}
		return false;
	}
	public boolean modifyMember(Members member) {
		Session session = HibernateUtil.getSessionFactory().getCurrentSession();
		Transaction tr = null;
		try{
			tr = session.beginTransaction();
			session.update(member);
			session.flush();
			tr.commit();
			return true;
		}catch(HibernateException e){
			if (tr != null) {
				tr.rollback();
			}
			e.printStackTrace();
		}
		return false;
	}
	public boolean deleteMember(Members member) {
		Session session = HibernateUtil.getSessionFactory().getCurrentSession();
		Transaction tr = null;
		try{
			tr = session.beginTransaction();
			session.delete(member);
			session.flush();
			tr.commit();
			return true;
		}catch(HibernateException e){
			if (tr != null) {
				tr.rollback();
			}
			e.printStackTrace();
		}
		return false;
	}
	public boolean deleteValidating(short id) {
		Session session = HibernateUtil.getSessionFactory().getCurrentSession();
		Transaction tr = null;
		try{
			tr = session.beginTransaction();
			Query query = session.createQuery("delete from Validating where uid = ?");
			query.setShort(0, id);
			query.executeUpdate();
			tr.commit();
			return true;
		}catch(HibernateException e){
			if (tr != null) {
				tr.rollback();
			}
			e.printStackTrace();
		}
		return false;
	}
	public List<Validating> findAllValidatings() {
		Session session = HibernateUtil.getSessionFactory().getCurrentSession();
		Transaction tr = null;
		try{
			tr = session.beginTransaction();
			Query query = session.createQuery("from Validating as v where v.status=0");
			List<Validating> validatingList = query.list();
			tr.commit();
			return validatingList;
		}catch(HibernateException e){
			if (tr != null) {
				tr.rollback();
			}
			e.printStackTrace();
		}
		return null;
	}
	public Validating findValidatingById(int id) {
		Session session = HibernateUtil.getSessionFactory().getCurrentSession();
		Transaction tr = null;
		try{
			tr = session.beginTransaction();
			Validating validating = (Validating) session.get(Validating.class, id);
			tr.commit();
			return validating;
		}catch(HibernateException e){
			if (tr != null) {
				tr.rollback();
			}
			e.printStackTrace();
		}
		return null;
	}
	public boolean insertValidating(Validating validating) {
		Session session = HibernateUtil.getSessionFactory().getCurrentSession();
		Transaction tr = null;
		try{
			tr = session.beginTransaction();
			session.save(validating);
			session.flush();
			tr.commit();
			return true;
		}catch(HibernateException e){
			if (tr != null) {
				tr.rollback();
			}
			e.printStackTrace();
		}
		return false;
	}
	public int modifyAllValidating(byte status) {
		Session session = HibernateUtil.getSessionFactory().getCurrentSession();
		Transaction tr = null;
		try{
			tr = session.beginTransaction();
			Query query = session.createQuery("update Validating set status = ?");
			query.setByte(0, status);
			int count = query.executeUpdate();
			tr.commit();
			return count;
		}catch(HibernateException e){
			if (tr != null) {
				tr.rollback();
			}
			e.printStackTrace();
		}
		return 0;
	}
	public boolean modifyValidating(Validating validating) {
		Session session = HibernateUtil.getSessionFactory().getCurrentSession();
		Transaction tr = null;
		try{
			tr = session.beginTransaction();
			session.update(validating);
			tr.commit();
			return true;
		}catch(HibernateException e){
			if (tr != null) {
				tr.rollback();
			}
			e.printStackTrace();
		}
		return false;
	}
	public boolean deleteProfile(Short filedId) {
		Session session = HibernateUtil.getSessionFactory().getCurrentSession();
		Transaction tr = null;
		try{
			tr = session.beginTransaction();
			Query query = session
					.createQuery("delete from Profilefields p where p.fieldid = ?");
			query.setShort(0, filedId);
			query.executeUpdate();
			tr.commit();
			return true;
		}catch(HibernateException e){
			if (tr != null) {
				tr.rollback();
			}
			e.printStackTrace();
		}
		return false;
	}
	public List<Profilefields> findAllProfilefields() {
		Session session = HibernateUtil.getSessionFactory().getCurrentSession();
		Transaction tr = null;
		try{
			tr = session.beginTransaction();
			Query query = session.createQuery("from Profilefields");
			List<Profilefields> profileList = query.list();
			tr.commit();
			return profileList;
		}catch(HibernateException e){
			if (tr != null) {
				tr.rollback();
			}
			e.printStackTrace();
		}
		return null;
	}
	public boolean insertProfile(Profilefields profile) {
		Session session = HibernateUtil.getSessionFactory().getCurrentSession();
		Transaction tr = null;
		try{
			tr = session.beginTransaction();
			session.save(profile);
			session.flush();
			tr.commit();
			return true;
		}catch(HibernateException e){
			if (tr != null) {
				tr.rollback();
			}
			e.printStackTrace();
		}
		return false;
	}
	public boolean modifyProfile(Profilefields profile) {
		Session session = HibernateUtil.getSessionFactory().getCurrentSession();
		Transaction tr = null;
		try{
			tr = session.beginTransaction();
			session.update(profile);
			session.flush();
			tr.commit();
			return true;
		}catch(HibernateException e){
			if (tr != null) {
				tr.rollback();
			}
			e.printStackTrace();
		}
		return false;
	}
	public Profilefields findProfileById(Short filedId) {
		Session session = HibernateUtil.getSessionFactory().getCurrentSession();
		Transaction tr = null;
		try{
			tr = session.beginTransaction();
			Profilefields profile = (Profilefields) session.get(
					Profilefields.class, filedId);
			tr.commit();
			return profile;
		}catch(HibernateException e){
			if (tr != null) {
				tr.rollback();
			}
			e.printStackTrace();
		}
		return null;
	}
	public boolean deleteRanks(Ranks rank) {
		Session session = HibernateUtil.getSessionFactory().getCurrentSession();
		Transaction tr = null;
		try{
			tr = session.beginTransaction();
			session.delete(rank);
			session.flush();
			tr.commit();
			return true;
		}catch(HibernateException e){
			if (tr != null) {
				tr.rollback();
			}
			e.printStackTrace();
		}
		return false;
	}
	public List<Ranks> findAllRanks() {
		Session session = HibernateUtil.getSessionFactory().getCurrentSession();
		Transaction tr = null;
		try{
			tr = session.beginTransaction();
			Query query = session.createQuery("from Ranks order by postshigher");
			List<Ranks> list = query.list();
			tr.commit();
			return list;
		}catch(HibernateException e){
			if (tr != null) {
				tr.rollback();
			}
			e.printStackTrace();
		}
		return null;
	}
	public Ranks findRanksById(short rankId) {
		Session session = HibernateUtil.getSessionFactory().getCurrentSession();
		Transaction tr = null;
		try{
			tr = session.beginTransaction();
			Ranks rank = (Ranks) session.get(Ranks.class, rankId);
			tr.commit();
			return rank;
		}catch(HibernateException e){
			if (tr != null) {
				tr.rollback();
			}
			e.printStackTrace();
		}
		return null;
	}
	public boolean insertRanks(Ranks rank) {
		Session session = HibernateUtil.getSessionFactory().getCurrentSession();
		Transaction tr = null;
		try{
			tr = session.beginTransaction();
			session.save(rank);
			tr.commit();
			return true;
		}catch(HibernateException e){
			if (tr != null) {
				tr.rollback();
			}
			e.printStackTrace();
		}
		return false;
	}
	public boolean modifyRanks(Ranks rank) {
		Session session = HibernateUtil.getSessionFactory().getCurrentSession();
		Transaction tr = null;
		try{
			tr = session.beginTransaction();
			session.update(rank);
			tr.commit();
			return true;
		}catch(HibernateException e){
			if (tr != null) {
				tr.rollback();
			}
			e.printStackTrace();
		}
		return false;
	}
	public boolean deleteAccess(Access access) {
		Session session = HibernateUtil.getSessionFactory().getCurrentSession();
		Transaction tr = null;
		try{
			tr = session.beginTransaction();
			session.delete(access);
			tr.commit();
			return true;
		}catch(HibernateException e){
			if (tr != null) {
				tr.rollback();
			}
			e.printStackTrace();
		}
		return false;
	}
	public List<Access> findAccessByUserId(int userId) {
		Session session = HibernateUtil.getSessionFactory().getCurrentSession();
		Transaction tr = null;
		try{
			tr = session.beginTransaction();
			Query query = session.createQuery("from Access as a where a.uid=?");
			query.setParameter(0, userId);
			List<Access> list = query.list();
			tr.commit();
			return list;
		}catch(HibernateException e){
			if (tr != null) {
				tr.rollback();
			}
			e.printStackTrace();
		}
		return null;
	}
	public boolean insertAccess(Access access) {
		Session session = HibernateUtil.getSessionFactory().getCurrentSession();
		Transaction tr = null;
		try{
			tr = session.beginTransaction();
			session.save(access);
			tr.commit();
			return true;
		}catch(HibernateException e){
			if (tr != null) {
				tr.rollback();
			}
			e.printStackTrace();
		}
		return false;
	}
	public boolean modifyAccess(Access access) {
		Session session = HibernateUtil.getSessionFactory().getCurrentSession();
		Transaction tr = null;
		try{
			tr = session.beginTransaction();
			session.saveOrUpdate(access);
			tr.commit();
			return true;
		}catch(HibernateException e){
			if (tr != null) {
				tr.rollback();
			}
			e.printStackTrace();
		}
		return false;
	}
	public boolean deleteMemberfields(Memberfields memberfields) {
		Session session = HibernateUtil.getSessionFactory().getCurrentSession();
		Transaction tr = null;
		try{
			tr = session.beginTransaction();
			session.delete(memberfields);
			tr.commit();
			return true;
		}catch(HibernateException e){
			if (tr != null) {
				tr.rollback();
			}
			e.printStackTrace();
		}
		return false;
	}
	public Memberfields findMemberfieldsById(int memberFieldsId) {
		Session session = HibernateUtil.getSessionFactory().getCurrentSession();
		Transaction tr = null;
		try{
			tr = session.beginTransaction();
			Memberfields memberFields = (Memberfields) session.get(Memberfields.class, memberFieldsId);
			tr.commit();
			return memberFields;
		}catch(HibernateException e){
			if(tr!=null){
				tr.rollback();
			}
			e.printStackTrace();
		}
		return null;
	}
	public boolean insertMemberfields(Memberfields memberfields) {
		Session session = HibernateUtil.getSessionFactory().getCurrentSession();
		Transaction tr = null;
		try{
			tr = session.beginTransaction();
			session.save(memberfields);
			tr.commit();
			return true;
		}catch(HibernateException e){
			if(tr!=null){
				tr.rollback();
			}
			e.printStackTrace();
		}
		return false;
	}
	public boolean modifyMemberfields(Memberfields memberfields) {
		Session session = HibernateUtil.getSessionFactory().getCurrentSession();
		Transaction tr = null;
		try{
			tr = session.beginTransaction();
			session.saveOrUpdate(memberfields);
			tr.commit();
			return true;
		}catch(HibernateException e){
			if(tr!=null){
				tr.rollback();
			}
			e.printStackTrace();
		}
		return false;
	}
	public boolean deleteOnlineTime(Onlinetime onlinetime) {
		Session session = HibernateUtil.getSessionFactory().getCurrentSession();
		Transaction tr = null;
		try{
			tr = session.beginTransaction();
			session.delete(onlinetime);
			tr.commit();
			return true;
		}catch(HibernateException e){
			if(tr!=null){
				tr.rollback();
			}
			e.printStackTrace();
		}
		return false;
	}
	public Onlinetime findOnlinetimeById(int onlinetimeId) {
		Session session = HibernateUtil.getSessionFactory().getCurrentSession();
		Transaction tr = null;
		try{
			tr = session.beginTransaction();
			Onlinetime onlinetime = (Onlinetime) session.get(Onlinetime.class,
					onlinetimeId);
			tr.commit();
			return onlinetime;
		}catch(HibernateException e){
			if(tr!=null){
				tr.rollback();
			}
			e.printStackTrace();
		}
		return null;
	}
	public boolean insertOnlineTime(Onlinetime onlinetime) {
		Session session = HibernateUtil.getSessionFactory().getCurrentSession();
		Transaction tr = null;
		try{
			tr = session.beginTransaction();
			session.save(onlinetime);
			session.flush();
			tr.commit();
			return true;
		}catch(HibernateException e){
			if(tr!=null){
				tr.rollback();
			}
			e.printStackTrace();
		}
		return false;
	}
	public boolean modifyOnlineTime(Onlinetime onlinetime) {
		Session session = HibernateUtil.getSessionFactory().getCurrentSession();
		Transaction tr = null;
		try{
			tr = session.beginTransaction();
			session.saveOrUpdate(onlinetime);
			session.flush();
			tr.commit();
			return true;
		}catch(HibernateException e){
			if(tr!=null){
				tr.rollback();
			}
			e.printStackTrace();
		}
		return false;
	}
	public List<Styles> findAllStyles() {
		Session session = HibernateUtil.getSessionFactory().getCurrentSession();
		Transaction tr = null;
		try{
			tr = session.beginTransaction();
			Query query = session.createQuery("from Styles");
			List<Styles> list = query.list();
			tr.commit();
			return list;
		}catch(HibernateException e){
			if(tr!=null){
				tr.rollback();
			}
			e.printStackTrace();
		}
		return null;
	}
	public boolean insertPms(Pms pms) {
		Session session = HibernateUtil.getSessionFactory().getCurrentSession();
		Transaction tr = null;
		try{
			tr = session.beginTransaction();
			session.save(pms);
			session.flush();
			tr.commit();
			return true;
		}catch(HibernateException e){
			if(tr!=null){
				tr.rollback();
			}
			e.printStackTrace();
		}
		return false;
	}
	@SuppressWarnings("unchecked")
	public List<Forums> findForumsByType() {
		Session session = HibernateUtil.getSessionFactory().getCurrentSession();
		Transaction tr = null;
		try{
			tr = session.beginTransaction();
			Query query = session.createQuery("from Forums as f where f.type<>'group' and f.status=1");
			List<Forums> list = query.list();
			tr.commit();
			return list;
		}catch(HibernateException e){
			if(tr!=null){
				tr.rollback();
			}
			e.printStackTrace();
		}
		return null;
	}
	public Access findAccessByFid(short fid, int uid) {
		Session session = HibernateUtil.getSessionFactory().getCurrentSession();
		Transaction tr = null;
		try{
			tr = session.beginTransaction();
			Query query = session
					.createQuery("from Access as a where a.id.fid=? and a.id.uid=?");
			query.setParameter(0, fid);
			query.setParameter(1, uid);
			List<Access> accessList = query.list();
			tr.commit();
			if (accessList != null && accessList.size() == 1) {
				return accessList.get(0);
			}
		}catch(HibernateException e){
			if(tr!=null){
				tr.rollback();
			}
			e.printStackTrace();
		}
		return null;
	}
	public boolean deleteSpacecaches(int uid) {
		Session session = HibernateUtil.getSessionFactory().getCurrentSession();
		Transaction tr = null;
		try{
			tr = session.beginTransaction();
			Query query = session
					.createQuery("delete from Spacecaches s where s.id.uid=?");
			query.setParameter(0, uid);
			query.executeUpdate();
			tr.commit();
			return true;
		}catch(HibernateException e){
			if(tr!=null){
				tr.rollback();
			}
			e.printStackTrace();
		}
		return false;
	}
	public List<Medals> findMedalsByAvailable(byte available) {
		Session session = HibernateUtil.getSessionFactory().getCurrentSession();
		Transaction tr = null;
		try{
			tr = session.beginTransaction();
			Query query = session.createQuery("from Medals where available=? order by medalid");
			query.setParameter(0, available);
			List<Medals> list = query.list();
			tr.commit();
			return list;
		}catch(HibernateException e){
			if(tr!=null && tr.isActive()){
				tr.rollback();
			}
			e.printStackTrace();
		}
		return null;
	}
	public List<Usergroups> findUsergroupByExt() {
		Session session = HibernateUtil.getSessionFactory().getCurrentSession();
		Transaction tr = null;
		try{
			tr = session.beginTransaction();
			Query query = session.createQuery("from Usergroups as u where u.type=? or u.radminid<>0 order by u.groupid");
			query.setParameter(0, "special");
			List<Usergroups> list = query.list();
			tr.commit();
			return list;
		}catch(HibernateException e){
			if(tr!=null){
				tr.rollback();
			}
			e.printStackTrace();
		}
		return null;
	}
	public boolean deleteValidating(Validating validate) {
		Session session = HibernateUtil.getSessionFactory().getCurrentSession();
		Transaction tr = null;
		try{
			tr = session.beginTransaction();
			session.delete(validate);
			tr.commit();
			return true;
		}catch(HibernateException e){
			if(tr!=null){
				tr.rollback();
			}
			e.printStackTrace();
		}
		return false;
	}
	@SuppressWarnings("unchecked")
	public List<Members> findMembersByGroupid(Short groupid) {
		Session session = HibernateUtil.getSessionFactory().getCurrentSession();
		Transaction tr = null;
		try{
			tr = session.beginTransaction();
			Query query = session.createQuery("from Members as m where m.groupid = ?");
			query.setParameter(0, groupid);
			List<Members> memberlist = query.list();
			tr.commit();
			return memberlist;
		}catch(HibernateException e){
			if(tr!=null){
				tr.rollback();
			}
			e.printStackTrace();
		}
		return null;
	}
	@SuppressWarnings("unchecked")
	public List findMembersByInId(int lowerId, int upperId) {
		Session session = HibernateUtil.getSessionFactory().getCurrentSession();
		Transaction tr = null;
		try{
			tr = session.beginTransaction();
			Query query = session.createQuery("SELECT m.uid from Members as m where m.uid>=? and m.uid<=?");
			query.setParameter(0,lowerId);
			query.setParameter(1,upperId);
			List memberlist = query.list();
			tr.commit();
			return memberlist;
		}catch(HibernateException e){
			if(tr!=null){
				tr.rollback();
			}
			e.printStackTrace();
		}
		return null;
	}
	public boolean insertMemberByJDBC(Members member) {
		Session session = HibernateUtil.getSessionFactory().getCurrentSession();
		Transaction tr = null;
		String sql = "insert into jrun_members(uid,username,password,email,groupid) values(?,?,?,?,?)";
		PreparedStatement pstmt=null;
		Connection conn =null;
		try {
			tr = session.beginTransaction();
			conn = session.connection();
			pstmt = conn.prepareStatement(sql);
			pstmt.setInt(1, member.getUid());
			pstmt.setString(2, member.getUsername());
			pstmt.setString(3, member.getPassword());
			pstmt.setString(4, member.getEmail());
			pstmt.setShort(5, member.getGroupid());
			pstmt.executeUpdate();
			tr.commit();
			return true;
		} catch (SQLException e) {
			if(tr!=null){
				tr.rollback();
			}
			e.printStackTrace();
		}finally {
			try {
				if(tr!=null){
					tr=null;
				}
				if(pstmt!=null){
					pstmt.close();
					pstmt=null;
				}
				if(conn!=null){
					conn.close();
					conn=null;
				}
			} catch (SQLException e) {
				e.printStackTrace();
			}
		}
		return false;
	}
	public void resetUserCredits(String columeName, Integer resetValue) throws Exception {
		Session session = HibernateUtil.getSessionFactory().getCurrentSession();
		Transaction tr =  session.beginTransaction();
		String hql = "from Members";
		try {
			Query query = session.createQuery(hql);
			List<Members> membersListFormDB = query.list();
			for (int i = 0; i < membersListFormDB.size(); i++) {
				Members member = membersListFormDB.get(i);
				if (columeName.equals("extcredits1")) {
					member.setExtcredits1(resetValue);
				} else if (columeName.equals("extcredits2")) {
					member.setExtcredits2(resetValue);
				} else if (columeName.equals("extcredits3")) {
					member.setExtcredits3(resetValue);
				} else if (columeName.equals("extcredits4")) {
					member.setExtcredits4(resetValue);
				} else if (columeName.equals("extcredits5")) {
					member.setExtcredits5(resetValue);
				} else if (columeName.equals("extcredits6")) {
					member.setExtcredits6(resetValue);
				} else if (columeName.equals("extcredits7")) {
					member.setExtcredits7(resetValue);
				} else if (columeName.equals("extcredits8")) {
					member.setExtcredits8(resetValue);
				} else {
					throw new Exception(
							"columeName NOT IN ( " +
							"extcredits1, extcredits2, extcredits3,extcredits4, " +
							"extcredits5, extcredits6, extcredits7,extcredits8 )");
				}
				session.update(member);
			}
			tr.commit();
		} catch (Exception e) {
			e.printStackTrace();
			if(tr!=null){
				tr.rollback();
			}
			throw new Exception("DATA ERROR");
		}
	}
	@SuppressWarnings("unchecked")
	public List<Members> findMembersByHql(String hql,int startrow,int maxrows) {
		Session session = HibernateUtil.getSessionFactory().getCurrentSession();
		Transaction tr = null;
		try{
			tr = session.beginTransaction();
			Query query = session.createQuery(hql);
			query.setFirstResult(startrow);
			query.setMaxResults(maxrows);
			List<Members> list = query.list();
			tr.commit();
			return list;
		}catch(HibernateException e){
			if(tr!=null){
				tr.rollback();
			}
			e.printStackTrace();
		}
		return null;
	}
	public int findMembersCount() {
		Session session = HibernateUtil.getSessionFactory().getCurrentSession();
		Transaction tr = null;
		try{
			tr = session.beginTransaction();
			Query query = session.createQuery("select count(*) from Members");
			List list = query.list();
			tr.commit();
			if(list!=null && list.size()>0){
				return Integer.valueOf(list.get(0)+"");
			}
		}catch(HibernateException e){
			if(tr!=null){
				tr.rollback();
			}
			e.printStackTrace();
		}
		return 0;
	}
	public boolean updateMembersByHql(String hql) {
		Session session = HibernateUtil.getSessionFactory().getCurrentSession();
		Transaction tr = null;
		try{
			tr = session.beginTransaction();
			Query query = session.createQuery(hql);
			query.executeUpdate();
			tr.commit();
			return true;
		}catch(HibernateException e){
			if(tr!=null){
				tr.rollback();
			}
			e.printStackTrace();
		}
		return false;
	}
	@SuppressWarnings("unchecked")
	public List<Profilefields> findprofilefieldByAvaliable(byte avaliable) {
		Session session = HibernateUtil.getSessionFactory().getCurrentSession();
		Transaction tr = null;
		try{
			tr = session.beginTransaction();
			Query query = session.createQuery("from Profilefields as p where p.available=?");
			query.setParameter(0, avaliable);
			List<Profilefields> profilelist = query.list();
			tr.commit();
			return profilelist;
		}catch(HibernateException e){
			if(tr!=null){
				tr.rollback();
			}
			e.printStackTrace();
		}
		return null;
	}
	@SuppressWarnings("unchecked")
	public List<Members> findByProperty(String propertyName, Object value) {
		Session session = null;
		Transaction tran = null;
		Query query = null;
		List<Members> members = null;
		try {
			members = new ArrayList<Members>();
			session = HibernateUtil.getSessionFactory().getCurrentSession();
			tran = session.beginTransaction();
			query = session.createQuery("from Members as m where m."+ propertyName + "=?");
			query.setString(0, value.toString());
			members = query.list();
			tran.commit();
		} catch (HibernateException e) {
			if(tran!=null){
				tran.rollback();
			}
			e.printStackTrace();
		}
		return members;
	}
	public List<Members> getMemberListWithMemberIdList(List<Integer> memberIdList) {
		if(memberIdList.size()<1){
			return null;
		}
		StringBuffer hqlBuffer = new StringBuffer("FROM Members AS m WHERE m.uid IN (");
		for(int i : memberIdList){
			hqlBuffer.append(i+",");
		}
		hqlBuffer.replace(hqlBuffer.length()-1, hqlBuffer.length(), ")");
		Transaction transaction = null;
		try{
			Session session = HibernateUtil.getSessionFactory().getCurrentSession();
			transaction = session.beginTransaction();
			Query query = session.createQuery(hqlBuffer.toString());
			List<Members> list = query.list();
			transaction.commit();
			return list;
		}catch(Exception exception){
			exception.printStackTrace();
			if(transaction!=null){
				transaction.rollback();
			}
			return null;
		}
	}
	public int findMemberCountByHql(String hql) {
		Session session = HibernateUtil.getSessionFactory().getCurrentSession();
		Transaction tr = null;
		try{
			tr = session.beginTransaction();
			Query query = session.createQuery(hql);
			List list = query.list();
			tr.commit();
			if(list!=null && list.size()>0){
				return (Integer)list.get(0);
			}
		}catch(HibernateException e){
			if(tr!=null){
				tr.rollback();
			}
			e.printStackTrace();
		}
		return 0;
	}
	public Integer getAdminCount() {
		Transaction transaction = null;
		try{
			Session session = HibernateUtil.getSessionFactory().getCurrentSession();
			transaction = session.beginTransaction();
			String hql = "SELECT COUNT(*) FROM Members WHERE adminid>?";
			Query query = session.createQuery(hql);
			query.setByte(0, (byte)0);
			List list = query.list();
			if(list.size()<=0){
				throw new Exception();
			}
			transaction.commit();
			return (Integer)list.get(0);
		}catch(Exception exception){
			exception.printStackTrace();
			if(transaction!=null){
				transaction.rollback();
			}
			return null;
		}
	}
	public Integer getMembersCount(){
		Transaction transaction = null;
		try{
			Session session = HibernateUtil.getSessionFactory().getCurrentSession();
			transaction = session.beginTransaction();
			String hql = "SELECT COUNT(*) FROM Members";
			Query query = session.createQuery(hql);
			List list = query.list();
			if(list.size()<=0){
				throw new Exception();
			}
			transaction.commit();
			return (Integer)list.get(0);
		}catch(Exception exception){
			exception.printStackTrace();
			if(transaction!=null){
				transaction.rollback();
			}
			return null;
		}
	}
	public Integer getMembersaddtoday(){
		Transaction transaction = null;
		try{
			Session session = HibernateUtil.getSessionFactory().getCurrentSession();
			transaction = session.beginTransaction();
			String hql = "SELECT COUNT(*) FROM Members WHERE regdate>=?";
			Query query = session.createQuery(hql);
			Integer nowTime = (int)(System.currentTimeMillis()/1000);
			query.setInteger(0, nowTime-86400);
			List list = query.list();
			if(list.size()<=0){
				throw new Exception();
			}
			transaction.commit();
			return (Integer)list.get(0);
		}catch(Exception exception){
			exception.printStackTrace();
			if(transaction!=null){
				transaction.rollback();
			}
			return null;
		}
	}
	public Integer getMemnonpost(){
		Transaction transaction = null;
		try{
			Session session = HibernateUtil.getSessionFactory().getCurrentSession();
			transaction = session.beginTransaction();
			String hql = "SELECT COUNT(*) FROM Members WHERE posts=?";
			Query query = session.createQuery(hql);
			query.setInteger(0, 0);
			List list = query.list();
			if(list.size()<=0){
				throw new Exception();
			}
			transaction.commit();
			return (Integer)list.get(0);
		}catch(Exception exception){
			exception.printStackTrace();
			if(transaction!=null){
				transaction.rollback();
			}
			return null;
		}
	}
	public Members getLastMember() {
		Transaction transaction = null;
		try{
			Session session = HibernateUtil.getSessionFactory().getCurrentSession();
			transaction  = session.beginTransaction();
			String hql = "FROM Members ORDER BY uid DESC";
			Query query  = session.createQuery(hql);
			query.setMaxResults(1);
			List<Members> members = query.list();
			transaction.commit();
			if(members!=null&&members.size()>0){
				return members.get(0);
			}
		}catch (Exception e) {
			e.printStackTrace();
			if(transaction!=null){
				transaction.rollback();
			}
		}
		return null;
	}
	public List<Members> getMembersByNames(List<String> membersNames) {
		Transaction transaction = null;
		try{
			Session session = HibernateUtil.getSessionFactory().getCurrentSession();
			transaction = session.beginTransaction();
			String hql = "FROM Members as m WHERE m.username=?";
			Query query = session.createQuery(hql);
			List<Members> memberList = new ArrayList<Members>();
			for(int i = 0;i<membersNames.size();i++){
				String membersName = membersNames.get(i);
				if(membersName!=null){
					query.setString(0, membersName);
					List<Members> listTemp = query.list();
					if(listTemp.size()>0){
						Members members = listTemp.get(0);
						memberList.add(members);
					}
				}
			}
			transaction.commit();
			return memberList;
		}catch(Exception exception){
			exception.printStackTrace();
			if(transaction!=null){
				transaction.rollback();
			}
			return null;
		}
	}
	public List<Members> getAllMembers() {
		Transaction transaction = null;
		try{
			Session session = HibernateUtil.getSessionFactory().getCurrentSession();
			transaction = session.beginTransaction();
			String hql =  "FROM Members";
			Query query = session.createQuery(hql);
			List<Members> resultList = query.list();
			transaction.commit();
			return resultList;
		}catch(Exception exception){
			exception.printStackTrace();
			if(transaction!=null){
				transaction.rollback();
			}
			return null;
		}
	}
	public void updateMembers(List<Members> memberList) {
		Transaction transaction = null;
		try{
			Session session = HibernateUtil.getSessionFactory().getCurrentSession();
			transaction = session.beginTransaction();
			for(int i = 0;i<memberList.size();i++){
				Members members = memberList.get(i);
				if(members!=null){
					session.update(members);
				}
			}
			transaction.commit();
		}catch(Exception exception){
			exception.printStackTrace();
			if(transaction!=null){
				transaction.rollback();
			}
		}
	}
	public void updateMembers(String hql) {
		Transaction transaction = null;
		try{
			Session session = HibernateUtil.getSessionFactory().getCurrentSession();
			transaction = session.beginTransaction();
			Query query = session.createQuery(hql);
			query.executeUpdate();
			transaction.commit();
		}catch(Exception exception){
			if(transaction!=null){
				transaction.rollback();
			}
			exception.printStackTrace();
		}
	}
}


text:
package net.glowstone.io.entity;

import net.glowstone.entity.AttributeManager;
import net.glowstone.entity.GlowLivingEntity;
import net.glowstone.io.nbt.NbtSerialization;
import net.glowstone.util.nbt.CompoundTag;
import net.glowstone.util.nbt.TagType;
import org.bukkit.inventory.EntityEquipment;
import org.bukkit.potion.PotionEffect;
import org.bukkit.potion.PotionEffectType;

import java.util.*;

abstract class LivingEntityStore<T extends GlowLivingEntity> extends EntityStore<T> {

    public LivingEntityStore(Class<T> clazz, String id) {
        super(clazz, id);
    }

    // these tags that apply to living entities only are documented as global:
    // - short "Air"
    // - string "CustomName"
    // - bool "CustomNameVisible"

    // todo: the following tags
    // - float "AbsorptionAmount"
    // - short "HurtTime"
    // - int "HurtByTimestamp"
    // - short "DeathTime"
    // - bool "PersistenceRequired"
    // - bool "Leashed"
    // - compound "Leash"
    // on ActiveEffects, bool "ShowParticles"

    @Override
    public void load(T entity, CompoundTag compound) {
        super.load(entity, compound);

        if (compound.isShort("Air")) {
            entity.setRemainingAir(compound.getShort("Air"));
        }
        if (compound.isString("CustomName")) {
            entity.setCustomName(compound.getString("CustomName"));
        }
        if (compound.isByte("CustomNameVisible")) {
            entity.setCustomNameVisible(compound.getBool("CustomNameVisible"));
        }

        if (compound.isFloat("HealF")) {
            entity.setHealth(compound.getFloat("HealF"));
        } else if (compound.isShort("Health")) {
            entity.setHealth(compound.getShort("Health"));
        }
        if (compound.isShort("AttackTime")) {
            entity.setNoDamageTicks(compound.getShort("AttackTime"));
        }

        if (compound.isList("ActiveEffects", TagType.COMPOUND)) {
            for (CompoundTag effect : compound.getCompoundList("ActiveEffects")) {
                // should really always have every field, but be forgiving if possible
                if (!effect.isByte("Id") || !effect.isInt("Duration")) {
                    continue;
                }

                PotionEffectType type = PotionEffectType.getById(effect.getByte("Id"));
                int duration = effect.getInt("Duration");
                if (type == null || duration < 0) {
                    continue;
                }
                int amplifier = 0;
                boolean ambient = false;

                if (compound.isByte("Amplifier")) {
                    amplifier = compound.getByte("Amplifier");
                }
                if (compound.isByte("Ambient")) {
                    ambient = compound.getBool("Ambient");
                }
                // bool "ShowParticles"

                entity.addPotionEffect(new PotionEffect(type, duration, amplifier, ambient), true);
            }
        }

        EntityEquipment equip = entity.getEquipment();
        if (equip != null) {
            if (compound.isList("Equipment", TagType.COMPOUND)) {
                List<CompoundTag> list = compound.getCompoundList("Equipment");
                if (list.size() == 5) {
                    equip.setItemInHand(NbtSerialization.readItem(list.get(0)));
                    equip.setBoots(NbtSerialization.readItem(list.get(1)));
                    equip.setLeggings(NbtSerialization.readItem(list.get(2)));
                    equip.setChestplate(NbtSerialization.readItem(list.get(3)));
                    equip.setHelmet(NbtSerialization.readItem(list.get(4)));
                }
            }
            if (compound.isList("DropChances", TagType.FLOAT)) {
                List<Float> list = compound.getList("DropChances", TagType.FLOAT);
                if (list.size() == 5) {
                    equip.setItemInHandDropChance(list.get(0));
                    equip.setBootsDropChance(list.get(1));
                    equip.setLeggingsDropChance(list.get(2));
                    equip.setChestplateDropChance(list.get(3));
                    equip.setHelmetDropChance(list.get(4));
                }
            }
        }
        if (compound.isByte("CanPickUpLoot")) {
            entity.setCanPickupItems(compound.getBool("CanPickUpLoot"));
        }

        if (compound.isList("Attributes", TagType.COMPOUND)) {
            List<CompoundTag> attributes = compound.getCompoundList("Attributes");
            AttributeManager am = entity.getAttributeManager();

            for (CompoundTag tag : attributes) {
                if (tag.isString("Name") && tag.isDouble("Base")) {
                    List<AttributeManager.Modifier> modifiers = null;
                    if (tag.isList("Modifiers", TagType.COMPOUND)) {
                        modifiers = new ArrayList<>();

                        List<CompoundTag> modifierTags = tag.getCompoundList("Modifiers");
                        for (CompoundTag modifierTag : modifierTags) {
                            if (modifierTag.isDouble("Amount") && modifierTag.isString("Name") &&
                                    modifierTag.isInt("Operation") && modifierTag.isLong("UUIDLeast") &&
                                    modifierTag.isLong("UUIDMost")) {
                                modifiers.add(new AttributeManager.Modifier(
                                        modifierTag.getString("Name"), new UUID(modifierTag.getLong("UUIDLeast"), modifierTag.getLong("UUIDMost")),
                                        modifierTag.getDouble("Amount"), (byte) modifierTag.getInt("Operation")));
                            }
                        }
                    }

                    am.setProperty(tag.getString("Name"), tag.getDouble("Base"), modifiers);
                }
            }
        }
    }

    @Override
    public void save(T entity, CompoundTag tag) {
        super.save(entity, tag);

        tag.putShort("Air", entity.getRemainingAir());
        if (entity.getCustomName() != null && !entity.getCustomName().isEmpty()) {
            tag.putString("CustomName", entity.getCustomName());
            tag.putBool("CustomNameVisible", entity.isCustomNameVisible());
        }

        tag.putFloat("HealF", entity.getHealth());
        tag.putShort("Health", (int) entity.getHealth());
        tag.putShort("AttackTime", entity.getNoDamageTicks());

        AttributeManager am = entity.getAttributeManager();
        Map<String, AttributeManager.Property> properties = am.getAllProperties();
        if (!properties.isEmpty()) {
            List<CompoundTag> attributes = new ArrayList<>();

            for (Map.Entry<String, AttributeManager.Property> property : properties.entrySet()) {
                CompoundTag attribute = new CompoundTag();
                attribute.putString("Name", property.getKey());

                AttributeManager.Property p = property.getValue();
                attribute.putDouble("Base", p.getValue());
                if (p.getModifiers() != null && !p.getModifiers().isEmpty()) {
                    List<CompoundTag> modifiers = new ArrayList<>();
                    for (AttributeManager.Modifier modifier : p.getModifiers()) {
                        CompoundTag modifierTag = new CompoundTag();
                        modifierTag.putDouble("Amount", modifier.getAmount());
                        modifierTag.putString("Name", modifier.getName());
                        modifierTag.putInt("Operation", modifier.getOperation());
                        modifierTag.putLong("UUIDLeast", modifier.getUuid().getLeastSignificantBits());
                        modifierTag.putLong("UUIDMost", modifier.getUuid().getMostSignificantBits());
                        modifiers.add(modifierTag);
                    }
                    attribute.putCompoundList("Modifiers", modifiers);
                }

                attributes.add(attribute);
            }

            tag.putCompoundList("Attributes", attributes);
        }

        List<CompoundTag> effects = new LinkedList<>();
        for (PotionEffect effect : entity.getActivePotionEffects()) {
            CompoundTag effectTag = new CompoundTag();
            effectTag.putByte("Id", effect.getType().getId());
            effectTag.putByte("Amplifier", effect.getAmplifier());
            effectTag.putInt("Duration", effect.getDuration());
            effectTag.putBool("Ambient", effect.isAmbient());
            effectTag.putBool("ShowParticles", true);
            effects.add(effectTag);
        }
        tag.putCompoundList("ActiveEffects", effects);

        EntityEquipment equip = entity.getEquipment();
        if (equip != null) {
            tag.putCompoundList("Equipment", Arrays.asList(
                    NbtSerialization.writeItem(equip.getItemInHand(), -1),
                    NbtSerialization.writeItem(equip.getBoots(), -1),
                    NbtSerialization.writeItem(equip.getLeggings(), -1),
                    NbtSerialization.writeItem(equip.getChestplate(), -1),
                    NbtSerialization.writeItem(equip.getHelmet(), -1)
            ));
            tag.putList("DropChances", TagType.FLOAT, Arrays.asList(
                    equip.getItemInHandDropChance(),
                    equip.getBootsDropChance(),
                    equip.getLeggingsDropChance(),
                    equip.getChestplateDropChance(),
                    equip.getHelmetDropChance()
            ));
        }
        tag.putBool("CanPickUpLoot", entity.getCanPickupItems());
    }
}


text:
Create a Github clone of SharpBrowser using [our tutorial](Compilation.md).

#### Step 2: Open BrowserConfig.cs

Open the Solution explorer, and navigate to `Model > BrowserConfig.cs`.

![image](https://user-images.githubusercontent.com/104514709/183605344-97a50c0f-666a-4132-bf30-760525dc253e.png)

#### Step 3: Edit the configuration strings

![image](https://user-images.githubusercontent.com/104514709/183605417-67f274b2-fe9d-47b7-9d4e-1722387d2fb8.png)

#### Step 4: Compile the application

Make sure you select `Release` mode and then compile the application using the Build or Start button.

![image](https://user-images.githubusercontent.com/104514709/183605667-47ce966c-3167-4d34-9bd5-7feadf0710e5.png)

#### Step 5: Create a new installer package
To recreate the setup file, install [InnoSetup](https://jrsoftware.org/isinfo.php) and run the InnoSetup script in the `setup` folder.

#### Step 6: Share your installer package
Share the newly generated installer package with your friends!


text:
#pragma once
#include <aws/config/ConfigService_EXPORTS.h>
#include <aws/core/utils/memory/stl/AWSString.h>

namespace Aws
{
namespace ConfigService
{
namespace Model
{
  enum class EventSource
  {
    NOT_SET,
    aws_config
  };

namespace EventSourceMapper
{
AWS_CONFIGSERVICE_API EventSource GetEventSourceForName(const Aws::String& name);

AWS_CONFIGSERVICE_API Aws::String GetNameForEventSource(EventSource value);
} // namespace EventSourceMapper
} // namespace Model
} // namespace ConfigService
} // namespace Aws


text:
public class AssertMessageNotString {

  void f(int i) {
    assert true : "yup";
    assert false;
    assert true : <warning descr="'assert' message of type 'int'">i</warning>;
    assert i > 10 : <warning descr="'assert' message of type 'boolean'">true</warning>;
    assert i < 0 : <warning descr="'assert' message of type 'Boolean'">Boolean.TRUE</warning>;
  }
}


text:
<?php

namespace PhpCodeHints;

use PhpParser\Node;
use PhpParser\Comment;
use PhpParser\NodeVisitor;
use PhpParser\NodeVisitorAbstract;
use PhpCodeHints\ClassHint;
use PhpCodeHints\NamespaceHint;
use PhpCodeHints\ConstantHint;
use PhpCodeHints\FunctionHint;

class HintVisitor extends NodeVisitorAbstract
{
    public $fileStmts = [];

    private $namespace = "";

    public function beforeTraverse(array $nodes)
    {
        return null;
    }

    public function enterNode(Node $node)
    {
        $blah = "";
        if ($node instanceof Node\Stmt\Namespace_) {
            $this->handleNamespace($node);
        } elseif ($node instanceof Node\Stmt\Class_) {
            $this->handleClass($node);
        } elseif ($node instanceof Node\Stmt\Function_) {
            $this->handleFunction($node);
        } elseif ($node instanceof Node\Stmt\Const_) {
            $this->handleConstant($node);
        } elseif ($node instanceof Node\Expr\FuncCall
                 && $node->name instanceof Node\Name
                 && $node->name == 'define') {
            $this->handleDefine($node);
        }
        return null;
    }

    public function leaveNode(Node $node)
    {
        return null;
    }

    public function afterTraverse(array $nodes)
    {
        return null;
    }

    private function handleClass(Node\Stmt\Class_ $class)
    {
        $classHint = new ClassHint;

        if (!$class->isAbstract()) {
            $classHint->setStmtType("Class");
            $classHint->setName($class->name);
            $classHint->setFqn($this->namespace . "\\" . $class->name);
            $classHint->setClassType($class->type);
            if ($class->extends instanceof Node) {
                $classHint->setExtends($class->extends->toString());
            }

            foreach ($class->stmts as $stmt) {
                $paramNames = [];
                $docComment = null;
                if ($stmt instanceof Node\Stmt\ClassMethod && ($stmt->isPublic() || $stmt->isProtected())) {
                    $docComment = $stmt->getDocComment();
                    if ($docComment !== null) {
                        $docComment = $docComment->getReformattedText();
                    }
                    $classHint->addMethod($stmt->name, $stmt->type, $stmt->byRef, $stmt->params, $docComment);
                }
                if ($stmt instanceof Node\Stmt\Property && ($stmt->isPublic() || $stmt->isProtected())) {
                    $docComment = $stmt->getDocComment();
                    if ($docComment !== null) {
                        $docComment = $docComment->getReformattedText();
                    }
                    $classHint->addProperty($stmt->props, $stmt->type, $docComment);
                }
                if ($stmt instanceof Node\Stmt\ClassConst) {
                    $docComment = $stmt->getDocComment();
                    if ($docComment !== null) {
                        $docComment = $docComment->getReformattedText();
                    }
                    $classHint->addConstant($stmt->consts, $docComment);
                }
            }

            $this->fileStmts[] = ['stmtType'=>$classHint->getStmtType(), 'name'=>$classHint->getName(),
                                  'fqn'=>$classHint->getFqn(),
                                  'type'=>$classHint->getClassType(), 'extendsClass'=>$classHint->getExtends(),
                                  'methods'=>$classHint->getMethods(), 'properties'=>$classHint->getProperties(),
                                  'constants'=>$classHint->getConstants()];
        }
    }

    private function handleFunction(Node\Stmt\Function_ $function)
    {
        $functionHint = new FunctionHint;

        $functionHint->setStmtType("Function");
        $functionHint->setName($function->name);
        $functionHint->setParams($function->params);

        $this->fileStmts[] = ['stmtType'=>$functionHint->getStmtType(), 'name'=>$functionHint->getName(),
                              'params'=>$functionHint->getParams()];
    }

    private function handleNamespace(Node\Stmt\Namespace_ $namespace)
    {
        $this->namespace = $namespace->name->toString();
        $namespaceHint = new NamespaceHint;

        $namespaceHint->setStmtType("Namespace");
        $namespaceHint->setName($namespace->name->toString());

        $this->fileStmts[] = ['stmtType'=>$namespaceHint->getStmtType(), 'name'=>$namespaceHint->getName()];
    }

    private function handleConstant(Node\Stmt\Const_ $constants)
    {
        $consts = $constants->consts;
        foreach ($consts as $constant) {
            $constantHint = new ConstantHint;
            $constantHint->setStmtType("Constant");
            $constantHint->setName($constant->name);
            $constantHint->setValue($constant->value->value);
            $this->fileStmts[] = ['stmtType'=>$constantHint->getStmtType(), 'name'=>$constantHint->getName(),
                                 'value'=>$constantHint->getValue()];
        }
    }

    private function handleDefine(Node\Expr\FuncCall $define)
    {
        $constantHint = new ConstantHint;
        $constantHint->setStmtType("Constant");
        $constantHint->setName($define->args[0]->value->value);
        $constantHint->setValue($define->args[1]->value->value);
        $this->fileStmts[] = ['stmtType'=>$constantHint->getStmtType(), 'name'=>$constantHint->getName(),
                             'value'=>$constantHint->getValue()];
    }
}


text:
#import "ABI10_0_0RCTImageEditingManager.h"

#import <UIKit/UIKit.h>

#import "ABI10_0_0RCTConvert.h"
#import "ABI10_0_0RCTLog.h"
#import "ABI10_0_0RCTUtils.h"
#import "ABI10_0_0RCTImageUtils.h"

#import "ABI10_0_0RCTImageStoreManager.h"
#import "ABI10_0_0RCTImageLoader.h"

@implementation ABI10_0_0RCTImageEditingManager

ABI10_0_0RCT_EXPORT_MODULE()

@synthesize bridge = _bridge;

/**
 * Crops an image and adds the result to the image store.
 *
 * @param imageRequest An image URL
 * @param cropData Dictionary with `offset`, `size` and `displaySize`.
 *        `offset` and `size` are relative to the full-resolution image size.
 *        `displaySize` is an optimization - if specified, the image will
 *        be scaled down to `displaySize` rather than `size`.
 *        All units are in px (not points).
 */
ABI10_0_0RCT_EXPORT_METHOD(cropImage:(NSURLRequest *)imageRequest
                  cropData:(NSDictionary *)cropData
                  successCallback:(ABI10_0_0RCTResponseSenderBlock)successCallback
                  errorCallback:(ABI10_0_0RCTResponseErrorBlock)errorCallback)
{
  CGRect rect = {
    [ABI10_0_0RCTConvert CGPoint:cropData[@"offset"]],
    [ABI10_0_0RCTConvert CGSize:cropData[@"size"]]
  };

  [_bridge.imageLoader loadImageWithURLRequest:imageRequest callback:^(NSError *error, UIImage *image) {
    if (error) {
      errorCallback(error);
      return;
    }

    // Crop image
    CGSize targetSize = rect.size;
    CGRect targetRect = {{-rect.origin.x, -rect.origin.y}, image.size};
    CGAffineTransform transform = ABI10_0_0RCTTransformFromTargetRect(image.size, targetRect);
    UIImage *croppedImage = ABI10_0_0RCTTransformImage(image, targetSize, image.scale, transform);

    // Scale image
    if (cropData[@"displaySize"]) {
      targetSize = [ABI10_0_0RCTConvert CGSize:cropData[@"displaySize"]]; // in pixels
      ABI10_0_0RCTResizeMode resizeMode = [ABI10_0_0RCTConvert ABI10_0_0RCTResizeMode:cropData[@"resizeMode"] ?: @"contain"];
      targetRect = ABI10_0_0RCTTargetRect(croppedImage.size, targetSize, 1, resizeMode);
      transform = ABI10_0_0RCTTransformFromTargetRect(croppedImage.size, targetRect);
      croppedImage = ABI10_0_0RCTTransformImage(croppedImage, targetSize, image.scale, transform);
    }

    // Store image
    [self->_bridge.imageStoreManager storeImage:croppedImage withBlock:^(NSString *croppedImageTag) {
      if (!croppedImageTag) {
        NSString *errorMessage = @"Error storing cropped image in ABI10_0_0RCTImageStoreManager";
        ABI10_0_0RCTLogWarn(@"%@", errorMessage);
        errorCallback(ABI10_0_0RCTErrorWithMessage(errorMessage));
        return;
      }
      successCallback(@[croppedImageTag]);
    }];
  }];
}

@end


text:
<TITLE>Review for Kiss the Girls (1997)</TITLE>
<LINK REL="STYLESHEET" TYPE="text/css" HREF="/ramr.css">

Kiss the Girls (1997)

reviewed by
James Brundage

Kiss the Girls

As reviewed by James Brundage

In "Loaded Weapon 1", William Shattner said : "Irony can be pretty ironic,
can't it?". Before, it was simply a statement that lodged itself in my mind
because of its utter absurdity. Now it has entered my repertoire of
quotations that can actually be used for something.

What possible use can something that stupid have? Good question, with a
mediocre answer. The only use I could come up with was to help describe my
loathing for a movie a million times more idiotic than the … unique quote.
And what idiotic movie is it that I describe? The one that evoked such pity
for having to put that on an actor's resume?
The movie, without further ado, is "Kiss The Girls", a new serial killer
movie on the market. Its just your standard killer-sees-girl,
killer-stalks-girl, killer-abducts, tortures, and murders-girl story that
we've seen a million times before, and, believe me, this ain't "Silence of
the Lambs".

Question number two : why all the irony? The fact is, I had every reason to
love this movie : I lived in the area where it was filmed, I read and loved
the book, and I respect and admire the actors, actresses, and director. But,
hey, its just the death throes of this years Summer of Irony (movies that we
all thought would be good but were really horrible). The simple fact is that
this is a movie that I wouldn't see again if it was on HBO on a summer
Saturday (and I'll watch anything on TV on a summer Saturday).

What made it so bad? Was it the cliché? The complete failure to make
characters who I cared about? The dearth of a villain I either hated or
liked? Or was it the fact that the movie was so downplayed that it annoyed
me completely? It was actually a combination of all of these wretched
attributes that made me focus my antipathy through the lens of rhetoric and
set my target sight on writing a disparaging review of this idiotic movie.

The movie opens nice, actually, giving an eerie title sequence in which the
killer talks to one of his victims about his first three murders, a sequence
so well done that you can't help feel a chill down your spine (looking back,
however, the newest preview of "Titanic" sent more of a chill, buy, what can
you do?). This single sequence, if placed in the middle of the movie, could
have turned around my opinion and made me pack up my sniper's rifle.

Sadly, this is the beginning and from there it degrades into nothingness,
going well past zero. It has great action sequences (kudos to the
cinematographer, Aaron Schnieder) and good performances from the actors
(Morgan Freeman as Alex Cross, Ashley Judd as Kate McTiernan), but that's
all it has to offer me as a viewer.

But then there was the worst part, the absolute zero of the movie. The fact
prevails that it downplays the sensationalism that ran rampant in the book:
one of the only things that just shocks you into continuing reading. That's
the final straw, the bullet loaded and the safety off. Ready. Aim. Fire.

http://fly.to/criticsheaven

The review above was posted to the
rec.arts.movies.reviews newsgroup (de.rec.film.kritiken for German reviews).

The Internet Movie Database accepts no responsibility for the contents of the
review and has no editorial control. Unless stated otherwise, the copyright
belongs to the author.

Please direct comments/criticisms of the review to relevant newsgroups.

Broken URLs inthe reviews are the responsibility of the author.

The formatting of the review is likely to differ from the original due
to ASCII to HTML conversion.

Related links: index of all rec.arts.movies.reviews reviews


text:
<meta http-equiv="Content-Type" content="text/html; charset=US-ASCII">
<title>ssl::context_base::~context_base</title>
<link rel="stylesheet" href="../../../boostbook.css" type="text/css">
<meta name="generator" content="DocBook XSL Stylesheets V1.75.2">
<link rel="home" href="../../../index.html" title="Asio">
<link rel="up" href="../ssl__context_base.html" title="ssl::context_base">
<link rel="prev" href="single_dh_use.html" title="ssl::context_base::single_dh_use">
<link rel="next" href="../ssl__rfc2818_verification.html" title="ssl::rfc2818_verification">

ssl::context_base::~context_base

Protected destructor to prevent deletion
          through this type.

~context_base();

Copyright © 2003-2015 Christopher M.
      Kohlhoff

        Distributed under the Boost Software License, Version 1.0. (See accompanying
        file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt)