text:
import sys, os
sys.path.append(os.path.join(os.path.dirname(__file__), '..'))

from docscrape import NumpyDocString, FunctionDoc
from docscrape_sphinx import SphinxDocString
from nose.tools import *

doc_txt = '''\
  numpy.multivariate_normal(mean, cov, shape=None)

  Draw values from a multivariate normal distribution with specified
  mean and covariance.

  The multivariate normal or Gaussian distribution is a generalisation
  of the one-dimensional normal distribution to higher dimensions.

  Parameters
  ----------
  mean : (N,) ndarray
      Mean of the N-dimensional distribution.

      .. math::

         (1+2+3)/3

  cov : (N,N) ndarray
      Covariance matrix of the distribution.
  shape : tuple of ints
      Given a shape of, for example, (m,n,k), m*n*k samples are
      generated, and packed in an m-by-n-by-k arrangement.  Because
      each sample is N-dimensional, the output shape is (m,n,k,N).

  Returns
  -------
  out : ndarray
      The drawn samples, arranged according to `shape`.  If the
      shape given is (m,n,...), then the shape of `out` is is
      (m,n,...,N).

      In other words, each entry ``out[i,j,...,:]`` is an N-dimensional
      value drawn from the distribution.

  Warnings
  --------
  Certain warnings apply.

  Notes
  -----

  Instead of specifying the full covariance matrix, popular
  approximations include:

    - Spherical covariance (`cov` is a multiple of the identity matrix)
    - Diagonal covariance (`cov` has non-negative elements only on the diagonal)

  This geometrical property can be seen in two dimensions by plotting
  generated data-points:

  >>> mean = [0,0]
  >>> cov = [[1,0],[0,100]] # diagonal covariance, points lie on x or y-axis

  >>> x,y = multivariate_normal(mean,cov,5000).T
  >>> plt.plot(x,y,'x'); plt.axis('equal'); plt.show()

  Note that the covariance matrix must be symmetric and non-negative
  definite.

  References
  ----------
  .. [1] A. Papoulis, "Probability, Random Variables, and Stochastic
         Processes," 3rd ed., McGraw-Hill Companies, 1991
  .. [2] R.O. Duda, P.E. Hart, and D.G. Stork, "Pattern Classification,"
         2nd ed., Wiley, 2001.

  See Also
  --------
  some, other, funcs
  otherfunc : relationship

  Examples
  --------
  >>> mean = (1,2)
  >>> cov = [[1,0],[1,0]]
  >>> x = multivariate_normal(mean,cov,(3,3))
  >>> print x.shape
  (3, 3, 2)

  The following is probably true, given that 0.6 is roughly twice the
  standard deviation:

  >>> print list( (x[0,0,:] - mean) < 0.6 )
  [True, True]

  .. index:: random
     :refguide: random;distributions, random;gauss

  '''
doc = NumpyDocString(doc_txt)

def test_signature():
    assert doc['Signature'].startswith('numpy.multivariate_normal(')
    assert doc['Signature'].endswith('shape=None)')

def test_summary():
    assert doc['Summary'][0].startswith('Draw values')
    assert doc['Summary'][-1].endswith('covariance.')

def test_extended_summary():
    assert doc['Extended Summary'][0].startswith('The multivariate normal')

def test_parameters():
    assert_equal(len(doc['Parameters']), 3)
    assert_equal([n for n,_,_ in doc['Parameters']], ['mean','cov','shape'])

    arg, arg_type, desc = doc['Parameters'][1]
    assert_equal(arg_type, '(N,N) ndarray')
    assert desc[0].startswith('Covariance matrix')
    assert doc['Parameters'][0][-1][-2] == '   (1+2+3)/3'

def test_returns():
    assert_equal(len(doc['Returns']), 1)
    arg, arg_type, desc = doc['Returns'][0]
    assert_equal(arg, 'out')
    assert_equal(arg_type, 'ndarray')
    assert desc[0].startswith('The drawn samples')
    assert desc[-1].endswith('distribution.')

def test_notes():
    assert doc['Notes'][0].startswith('Instead')
    assert doc['Notes'][-1].endswith('definite.')
    assert_equal(len(doc['Notes']), 17)

def test_references():
    assert doc['References'][0].startswith('..')
    assert doc['References'][-1].endswith('2001.')

def test_examples():
    assert doc['Examples'][0].startswith('>>>')
    assert doc['Examples'][-1].endswith('True]')

def test_index():
    assert_equal(doc['index']['default'], 'random')
    print doc['index']
    assert_equal(len(doc['index']), 2)
    assert_equal(len(doc['index']['refguide']), 2)

def non_blank_line_by_line_compare(a,b):
    a = [l for l in a.split('\n') if l.strip()]
    b = [l for l in b.split('\n') if l.strip()]
    for n,line in enumerate(a):
        if not line == b[n]:
            raise AssertionError("Lines %s of a and b differ: "
                                 "\n>>> %s\n<<< %s\n" %
                                 (n,line,b[n]))
def test_str():
    non_blank_line_by_line_compare(str(doc),
"""numpy.multivariate_normal(mean, cov, shape=None)

Draw values from a multivariate normal distribution with specified
mean and covariance.

The multivariate normal or Gaussian distribution is a generalisation
of the one-dimensional normal distribution to higher dimensions.

Parameters
----------
mean : (N,) ndarray
    Mean of the N-dimensional distribution.

    .. math::

       (1+2+3)/3

cov : (N,N) ndarray
    Covariance matrix of the distribution.
shape : tuple of ints
    Given a shape of, for example, (m,n,k), m*n*k samples are
    generated, and packed in an m-by-n-by-k arrangement.  Because
    each sample is N-dimensional, the output shape is (m,n,k,N).

Returns
-------
out : ndarray
    The drawn samples, arranged according to `shape`.  If the
    shape given is (m,n,...), then the shape of `out` is is
    (m,n,...,N).

    In other words, each entry ``out[i,j,...,:]`` is an N-dimensional
    value drawn from the distribution.

Warnings
--------
Certain warnings apply.

See Also
--------
`some`_, `other`_, `funcs`_

`otherfunc`_
    relationship

Notes
-----
Instead of specifying the full covariance matrix, popular
approximations include:

  - Spherical covariance (`cov` is a multiple of the identity matrix)
  - Diagonal covariance (`cov` has non-negative elements only on the diagonal)

This geometrical property can be seen in two dimensions by plotting
generated data-points:

>>> mean = [0,0]
>>> cov = [[1,0],[0,100]] # diagonal covariance, points lie on x or y-axis

>>> x,y = multivariate_normal(mean,cov,5000).T
>>> plt.plot(x,y,'x'); plt.axis('equal'); plt.show()

Note that the covariance matrix must be symmetric and non-negative
definite.

References
----------
.. [1] A. Papoulis, "Probability, Random Variables, and Stochastic
       Processes," 3rd ed., McGraw-Hill Companies, 1991
.. [2] R.O. Duda, P.E. Hart, and D.G. Stork, "Pattern Classification,"
       2nd ed., Wiley, 2001.

Examples
--------
>>> mean = (1,2)
>>> cov = [[1,0],[1,0]]
>>> x = multivariate_normal(mean,cov,(3,3))
>>> print x.shape
(3, 3, 2)

The following is probably true, given that 0.6 is roughly twice the
standard deviation:

>>> print list( (x[0,0,:] - mean) < 0.6 )
[True, True]

.. index:: random
   :refguide: random;distributions, random;gauss""")

def test_sphinx_str():
    sphinx_doc = SphinxDocString(doc_txt)
    non_blank_line_by_line_compare(str(sphinx_doc),
"""
.. index:: random
   single: random;distributions, random;gauss

Draw values from a multivariate normal distribution with specified
mean and covariance.

The multivariate normal or Gaussian distribution is a generalisation
of the one-dimensional normal distribution to higher dimensions.

:Parameters:

    **mean** : (N,) ndarray

        Mean of the N-dimensional distribution.

        .. math::

           (1+2+3)/3

    **cov** : (N,N) ndarray

        Covariance matrix of the distribution.

    **shape** : tuple of ints

        Given a shape of, for example, (m,n,k), m*n*k samples are
        generated, and packed in an m-by-n-by-k arrangement.  Because
        each sample is N-dimensional, the output shape is (m,n,k,N).

:Returns:

    **out** : ndarray

        The drawn samples, arranged according to `shape`.  If the
        shape given is (m,n,...), then the shape of `out` is is
        (m,n,...,N).

        In other words, each entry ``out[i,j,...,:]`` is an N-dimensional
        value drawn from the distribution.

.. warning::

    Certain warnings apply.

.. seealso::

    :obj:`some`, :obj:`other`, :obj:`funcs`

    :obj:`otherfunc`
        relationship

.. rubric:: Notes

Instead of specifying the full covariance matrix, popular
approximations include:

  - Spherical covariance (`cov` is a multiple of the identity matrix)
  - Diagonal covariance (`cov` has non-negative elements only on the diagonal)

This geometrical property can be seen in two dimensions by plotting
generated data-points:

>>> mean = [0,0]
>>> cov = [[1,0],[0,100]] # diagonal covariance, points lie on x or y-axis

>>> x,y = multivariate_normal(mean,cov,5000).T
>>> plt.plot(x,y,'x'); plt.axis('equal'); plt.show()

Note that the covariance matrix must be symmetric and non-negative
definite.

.. rubric:: References

.. [1] A. Papoulis, "Probability, Random Variables, and Stochastic
       Processes," 3rd ed., McGraw-Hill Companies, 1991
.. [2] R.O. Duda, P.E. Hart, and D.G. Stork, "Pattern Classification,"
       2nd ed., Wiley, 2001.

.. rubric:: Examples

>>> mean = (1,2)
>>> cov = [[1,0],[1,0]]
>>> x = multivariate_normal(mean,cov,(3,3))
>>> print x.shape
(3, 3, 2)

The following is probably true, given that 0.6 is roughly twice the
standard deviation:

>>> print list( (x[0,0,:] - mean) < 0.6 )
[True, True]
""")

doc2 = NumpyDocString("""
    Returns array of indices of the maximum values of along the given axis.

    Parameters
    ----------
    a : {array_like}
        Array to look in.
    axis : {None, integer}
        If None, the index is into the flattened array, otherwise along
        the specified axis""")

def test_parameters_without_extended_description():
    assert_equal(len(doc2['Parameters']), 2)

doc3 = NumpyDocString("""
    my_signature(*params, **kwds)

    Return this and that.
    """)

def test_escape_stars():
    signature = str(doc3).split('\n')[0]
    assert_equal(signature, 'my_signature(\*params, \*\*kwds)')

doc4 = NumpyDocString(
    """a.conj()

    Return an array with all complex-valued elements conjugated.""")

def test_empty_extended_summary():
    assert_equal(doc4['Extended Summary'], [])

doc5 = NumpyDocString(
    """
    a.something()

    Raises
    ------
    LinAlgException
        If array is singular.

    """)

def test_raises():
    assert_equal(len(doc5['Raises']), 1)
    name,_,desc = doc5['Raises'][0]
    assert_equal(name,'LinAlgException')
    assert_equal(desc,['If array is singular.'])

def test_see_also():
    doc6 = NumpyDocString(
    """
    z(x,theta)

    See Also
    --------
    func_a, func_b, func_c
    func_d : some equivalent func
    foo.func_e : some other func over
             multiple lines
    func_f, func_g, :meth:`func_h`, func_j,
    func_k
    :obj:`baz.obj_q`
    :class:`class_j`: fubar
        foobar
    """)

    assert len(doc6['See Also']) == 12
    for func, desc, role in doc6['See Also']:
        if func in ('func_a', 'func_b', 'func_c', 'func_f',
                    'func_g', 'func_h', 'func_j', 'func_k', 'baz.obj_q'):
            assert(not desc)
        else:
            assert(desc)

        if func == 'func_h':
            assert role == 'meth'
        elif func == 'baz.obj_q':
            assert role == 'obj'
        elif func == 'class_j':
            assert role == 'class'
        else:
            assert role is None

        if func == 'func_d':
            assert desc == ['some equivalent func']
        elif func == 'foo.func_e':
            assert desc == ['some other func over', 'multiple lines']
        elif func == 'class_j':
            assert desc == ['fubar', 'foobar']

def test_see_also_print():
    class Dummy(object):
        """
        See Also
        --------
        func_a, func_b
        func_c : some relationship
                 goes here
        func_d
        """
        pass

    obj = Dummy()
    s = str(FunctionDoc(obj, role='func'))
    assert(':func:`func_a`, :func:`func_b`' in s)
    assert('    some relationship' in s)
    assert(':func:`func_d`' in s)

doc7 = NumpyDocString("""

        Doc starts on second line.

        """)

def test_empty_first_line():
    assert doc7['Summary'][0].startswith('Doc starts')

def test_no_summary():
    str(SphinxDocString("""
    Parameters
    ----------"""))

def test_unicode():
    doc = SphinxDocString("""
    öäöäöäöäöåååå

    öäöäöäööäååå

    Parameters
    ----------
    ååå : äää
        ööö

    Returns
    -------
    ååå : ööö
        äää

    """)
    assert doc['Summary'][0] == u'öäöäöäöäöåååå'.encode('utf-8')

def test_plot_examples():
    doc = SphinxDocString("""
    Examples
    --------
    >>> import matplotlib.pyplot as plt
    >>> plt.plot([1,2,3],[4,5,6])
    >>> plt.show()
    """)
    assert 'plot::' in str(doc), str(doc)

    doc = SphinxDocString("""
    Examples
    --------
    .. plot::

       import matplotlib.pyplot as plt
       plt.plot([1,2,3],[4,5,6])
       plt.show()
    """)
    assert str(doc).count('plot::') == 1, str(doc)


text:
package sk.mpage.androidsample.recyclerview;

import android.accounts.Account;
import android.accounts.AccountManager;
import android.app.Activity;
import android.app.Fragment;
import android.app.FragmentManager;
import android.content.Intent;
import android.content.IntentSender;
import android.location.Location;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.util.Log;
import android.view.Menu;
import android.view.MenuItem;
import android.widget.Toast;

import com.google.android.gms.common.ConnectionResult;
import com.google.android.gms.common.api.GoogleApiClient;
import com.google.android.gms.common.api.PendingResult;
import com.google.android.gms.common.api.ResultCallback;
import com.google.android.gms.common.api.Status;
import com.google.android.gms.location.LocationListener;
import com.google.android.gms.location.LocationRequest;
import com.google.android.gms.location.LocationServices;
import com.google.android.gms.location.LocationSettingsRequest;
import com.google.android.gms.location.LocationSettingsResult;
import com.google.android.gms.location.LocationSettingsStatusCodes;

import java.text.DateFormat;
import java.util.Date;

import sk.mpage.androidsample.recyclerview.helper.InfoSingleton;
import sk.mpage.androidsample.recyclerview.helper.SettingsFragment;
import sk.mpage.androidsample.recyclerview.recyclerview.POIFragment;

public class MainActivity extends AppCompatActivity
        implements GoogleApiClient.ConnectionCallbacks,
        GoogleApiClient.OnConnectionFailedListener,
        LocationListener,
        ResultCallback<LocationSettingsResult>{

    protected static final String TAG = "Lokacia";
    protected final static String KEY_REQUESTING_LOCATION_UPDATES = "requesting-location-updates";

    protected static final int REQUEST_CHECK_SETTINGS = 0x1;

    public static final long SMALLERST_DISPLACEMENT = 50;
    public static final long UPDATE_INTERVAL_IN_MILLISECONDS = 10000;

    public static final long FASTEST_UPDATE_INTERVAL_IN_MILLISECONDS =
            UPDATE_INTERVAL_IN_MILLISECONDS / 2;

    protected GoogleApiClient mGoogleApiClient;
    protected LocationRequest mLocationRequest;
    protected LocationSettingsRequest mLocationSettingsRequest;
    protected Location mCurrentLocation;

    protected String mLastUpdateTime;
    protected boolean mRequestingLocationUpdates = false;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        openPOIFragment();
        mLastUpdateTime = "";
        updateValuesFromBundle(savedInstanceState);

        buildLocation();
        checkLocationSettings();
    }

    public void openPOIFragment(){
        Fragment fragment = null;
        Bundle args = new Bundle();
        fragment = new POIFragment();
        Location location = InfoSingleton.getInstance().lastLocation;
        if (location!=null) {
            args.putDouble("lat", location == null ? 0 : location.getLatitude());
            args.putDouble("lon", location == null ? 0 : location.getLongitude());
        }
        fragment.setArguments(args);

        getFragmentManager().beginTransaction().replace(R.id.main_fragment_container, fragment).commit();

    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        // Inflate the menu; this adds items to the action bar if it is present.
        //todo: 1. pridat menu  menu_main.xml
        return true;
    }

    @Override
    public boolean onPrepareOptionsMenu(Menu menu) {
        // If the nav drawer is open, hide action items related to the content view
        return super.onPrepareOptionsMenu(menu);
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {

        //todo: 2. ak bolo vybrate nastavenia zobrazit fragment nastavenia

        return super.onOptionsItemSelected(item);
    }

    @Override
    public void onBackPressed() {
        openPOIFragment();
    }

    public void buildLocation(){
        buildGoogleApiClient();
        createLocationRequest();
        buildLocationSettingsRequest();
    }

    protected synchronized void buildGoogleApiClient() {
        Log.i(TAG, "Building GoogleApiClient");
        mGoogleApiClient = new GoogleApiClient.Builder(this)
                .addConnectionCallbacks(this)
                .addOnConnectionFailedListener(this)
                .addApi(LocationServices.API)
                .build();
    }

    protected void createLocationRequest() {
        mLocationRequest = new LocationRequest();

        mLocationRequest.setInterval(UPDATE_INTERVAL_IN_MILLISECONDS);
        mLocationRequest.setFastestInterval(FASTEST_UPDATE_INTERVAL_IN_MILLISECONDS);
        mLocationRequest.setSmallestDisplacement(SMALLERST_DISPLACEMENT);

        mLocationRequest.setPriority(LocationRequest.PRIORITY_HIGH_ACCURACY);
    }

    protected void buildLocationSettingsRequest() {
        LocationSettingsRequest.Builder builder = new LocationSettingsRequest.Builder();
        builder.addLocationRequest(mLocationRequest);
        mLocationSettingsRequest = builder.build();
    }

    protected void checkLocationSettings() {
        PendingResult<LocationSettingsResult> result =
                LocationServices.SettingsApi.checkLocationSettings(
                        mGoogleApiClient,
                        mLocationSettingsRequest
                );
        result.setResultCallback(this);
    }

    @Override
    public void onResult(LocationSettingsResult locationSettingsResult) {
        final Status status = locationSettingsResult.getStatus();
        switch (status.getStatusCode()) {
            case LocationSettingsStatusCodes.SUCCESS:
                Log.i(TAG, "All location settings are satisfied.");
                startLocationUpdates();
                break;
            case LocationSettingsStatusCodes.RESOLUTION_REQUIRED:
                Log.i(TAG, "Location settings are not satisfied. Show the user a dialog to" +
                        "upgrade location settings ");
                try {
                    // Show the dialog by calling startResolutionForResult(), and check the result
                    // in onActivityResult().
                    status.startResolutionForResult(MainActivity.this, REQUEST_CHECK_SETTINGS);
                } catch (IntentSender.SendIntentException e) {
                    Log.i(TAG, "PendingIntent unable to execute request.");
                }
                break;
            case LocationSettingsStatusCodes.SETTINGS_CHANGE_UNAVAILABLE:
                Log.i(TAG, "Location settings are inadequate, and cannot be fixed here. Dialog " +
                        "not created.");
                break;
        }

    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        switch (requestCode) {
            // Check for the integer request code originally supplied to startResolutionForResult().
            case REQUEST_CHECK_SETTINGS:
                switch (resultCode) {
                    case Activity.RESULT_OK:
                        Log.i(TAG, "User agreed to make required location settings changes.");
                        startLocationUpdates();
                        break;
                    case Activity.RESULT_CANCELED:
                        Log.i(TAG, "User chose not to make required location settings changes.");
                        break;
                }
                break;
        }

    }

    /**
     * Requests location updates from the FusedLocationApi.
     */
    protected void startLocationUpdates() {
        Log.d(TAG,"Starting location updates");
        LocationServices.FusedLocationApi.requestLocationUpdates(
                mGoogleApiClient,
                mLocationRequest,
                this
        ).setResultCallback(new ResultCallback<Status>() {
            @Override
            public void onResult(Status status) {
                Log.d(TAG,"Location updates started");
                mRequestingLocationUpdates = true;
            }
        });

    }

    /**
     * Removes location updates from the FusedLocationApi.
     */
    protected void stopLocationUpdates() {
        LocationServices.FusedLocationApi.removeLocationUpdates(
                mGoogleApiClient,
                this
        ).setResultCallback(new ResultCallback<Status>() {
            @Override
            public void onResult(Status status) {
                mRequestingLocationUpdates = false;
            }
        });
    }

    @Override
    protected void onStart() {
        super.onStart();
        if (mGoogleApiClient!=null)
            mGoogleApiClient.connect();
    }

    @Override
    public void onResume() {
        super.onResume();

        if (mGoogleApiClient==null){
            buildLocation();
        }
        if (mGoogleApiClient.isConnected()) {
            checkLocationSettings();
        } else {
            mGoogleApiClient.connect();
        }
    }

    @Override
    protected void onPause() {
        super.onPause();
        if (mGoogleApiClient==null)
            return;

        // Stop location updates to save battery, but don't disconnect the GoogleApiClient object.
        if (mGoogleApiClient.isConnected()) {
            stopLocationUpdates();
        }
    }

    @Override
    protected void onStop() {
        super.onStop();
        if (mGoogleApiClient==null)
            return;

        mGoogleApiClient.disconnect();
    }

    /**
     * Runs when a GoogleApiClient object successfully connects.
     */
    @Override
    public void onConnected(Bundle connectionHint) {
        Log.i(TAG, "Connected to GoogleApiClient");

        if (mCurrentLocation == null) {
            mCurrentLocation = LocationServices.FusedLocationApi.getLastLocation(mGoogleApiClient);
            mLastUpdateTime = DateFormat.getTimeInstance().format(new Date());
        }

        startLocationUpdates();
    }

    /**
     * Callback that fires when the location changes.
     */
    @Override
    public void onLocationChanged(Location location) {
        mCurrentLocation = location;
        mLastUpdateTime = DateFormat.getTimeInstance().format(new Date());
        Toast.makeText(this, "Nova poloha ...", Toast.LENGTH_SHORT).show();
        Log.d(TAG, "Location " + location.toString());
        InfoSingleton.getInstance().lastLocation = location;
        updateLocation();
    }

    public void updateLocation() {
        Fragment fragment = getFragmentManager().findFragmentById(R.id.main_fragment_container);
        if (fragment instanceof POIFragment) {
            if (mCurrentLocation != null)
                ((POIFragment) fragment).updatePOI(mCurrentLocation.getLatitude(), mCurrentLocation.getLongitude());
        }

    }

    @Override
    public void onConnectionSuspended(int cause) {
        Log.i(TAG, "Connection suspended");
    }

    @Override
    public void onConnectionFailed(ConnectionResult result) {
        // Refer to the javadoc for ConnectionResult to see what error codes might be returned in
        // onConnectionFailed.
        Log.i(TAG, "Connection failed: ConnectionResult.getErrorCode() = " + result.getErrorCode());
    }

    private void updateValuesFromBundle(Bundle savedInstanceState) {
        if (savedInstanceState != null) {
            if (savedInstanceState.keySet().contains(KEY_REQUESTING_LOCATION_UPDATES)) {
                mRequestingLocationUpdates = savedInstanceState.getBoolean(
                        KEY_REQUESTING_LOCATION_UPDATES);
            }
        }
    }

}

redpajama_set_name: RedPajamaGithub


text:
const cookieParser = require('cookie-parser')
const md5 = require('md5');
const session = require('express-session');

const passport = require('passport');
const FacebookStrategy = require('passport-facebook').Strategy;
const config = { clientID:'1927081114238967', clientSecret:'d8c49f0a0b8760117324380be02aeb4d',
	callbackURL: 'https://quiet-caverns-31163.herokuapp.com/facebook/callback',
	profileFields: ['emails', 'name', 'displayName', 'photos'] };

var redis = require('redis').createClient("redis://h:p17f19eda071fbb83690a1033fbcfd2304d063056786a9bd94b8360948148261a@ec2-34-206-56-163.compute-1.amazonaws.com:42059");

var User = require('./model.js').User;
var Email = require('./model.js').Email;
var Zipcode = require('./model.js').Zipcode;
var Dob = require('./model.js').Dob;
var Avatar = require('./model.js').Avatar;
var Password = require('./model.js').Password;
var Headline = require('./model.js').Headline;
var Following = require('./model.js').Following;

const cookieKey = 'sid';

const isAuthorized = (userObj, req) => {
	const salt = userObj.salt;
	const password = req.body.password;
	const h1 = md5(salt + password);
	return (h1 == userObj.h1);
}

const login = (req, res) => {
	const username = req.body.username;
	const password = req.body.password;
	if (!username || !password){
		return res.sendStatus(400);	// Bad request
	}
	User.find({username: username}, (error, docs) => {
		const userObj = docs[0];
		if (!userObj || !isAuthorized(userObj, req)){
			return res.sendStatus(401);
		}
		const sessionKey = md5("mysessionkey"+new Date().getTime());
		redis.hmset(sessionKey, userObj);
		res.cookie(cookieKey, sessionKey, {maxAge: 3600*1000, httpOnly: true});
		const msg = {username: username, result: 'success'};
		return res.status(200).send(msg);
	});
}

const register = (req, res) => {
	const username = req.body.username;
	const email = req.body.email;
	const dob = req.body.dob;
	const zipcode = req.body.zipcode;
	const avatar = "https://s0.wp.com/wp-content/mu-plugins/wpcom-smileys/twemoji/2/svg/1f61c.svg";
	const headline = "Every day is coding day!"
	const password = req.body.password;
	const salt = md5("myregistersalt"+new Date().getTime());
	const h1 = md5(salt + password);
	const newUser = {username: username, salt: salt, h1: h1};
	User.find({username: username}, (error, docs) => {
		if (error) return res.status(500).send({ error: error });
		if (docs[0]) return res.sendStatus(403); // Forbidden
		User.create(newUser, (error, doc) => {
			if (error) return res.status(500).send({ error: error });
			Email.create({username: username, email: email}, (error, doc) => {
				if (error) return res.status(500).send({ error: error });
			})
			Zipcode.create({username: username, zipcode: zipcode}, (error, doc) => {
				if (error) return res.status(500).send({ error: error });
			})
			Dob.create({username: username, dob: dob}, (error, doc) => {
				if (error) return res.status(500).send({ error: error });
			})
			Avatar.create({username: username, avatar: avatar}, (error, doc) => {
				if (error) return res.status(500).send({ error: error });
			})
			Headline.create({username: username, headline: headline}, (error, doc) => {
				if (error) return res.status(500).send({ error: error });
			})
			Following.create({username: username, following: []}, (error, doc) => {
				if (error) return res.status(500).send({ error: error });
			});

	        return res.status(200).send({result: 'success', username: doc.username});
	    });
	});
}

//use Facebook Strategy to login
let users = {};
passport.serializeUser((user, done) => {
	users[user.id] = user;
	done(null, user.id);
});

passport.deserializeUser((id, done) => {
	const user = users[id];
	done(null, user);
});

passport.use(new FacebookStrategy(config,
	(token, refreshToken, profile, done) => {
		const username = profile['_json']['first_name']+"_facebook";
		const email = profile['_json']['email'];
		const avatar = profile['_json']['picture']['data']['url'];
		User.find({username: username}, (error, docs) => {
			const userObj = docs[0];
			if(!userObj){
			User.create({username: username}, (error, doc) => {
				if (error) return res.status(500).send({ error: error });
				Email.create({username: username, email: email}, (error, doc) => {
					if (error) return res.status(500).send({ error: error });
				})
				Zipcode.create({username: username, zipcode: 12345}, (error, doc) => {
					if (error) return res.status(500).send({ error: error });
				})
				Dob.create({username: username, dob: "12/12/1994"}, (error, doc) => {
					if (error) return res.status(500).send({ error: error });
				})
				Avatar.create({username: username, avatar: avatar}, (error, doc) => {
					if (error) return res.status(500).send({ error: error });
				})
				Headline.create({username: username, headline: "Facebook login"}, (error, doc) => {
					if (error) return res.status(500).send({ error: error });
				})
				Following.create({username: username, following: []}, (error, doc) => {
					if (error) return res.status(500).send({ error: error });
				});

				})
			};
		})
		return done(null, profile);
	})
)

const isLoggedIn = (req, res, next) => {
	if (req.isAuthenticated()) {
		const username = req.user['_json']['first_name']+"_facebook";
		req.username = username;
		return next();
	}else{
		const sid = req.cookies[cookieKey];
		if (!sid){
	        return res.status(401).send('Not Authorized');
	    }
	    redis.hgetall(sid, (error, userObj) => {
	    	if(error) {
	    		console.error('Error: ${err}');
	    	}else if(userObj){
	    		console.log(sid + ' mapped to ' + userObj.username);
	    		req.username = userObj.username;
				return next();
			}else{
				return res.redirect('/login');
			}
	    })
	}
}

const logout = (req, res) => {
	if (req.isAuthenticated()) {
		req.session.destroy();
		req.logout();
		return res.status(200).send("OK");
	} else{
		const sid = req.cookies[cookieKey];
		redis.del(sid);
		res.clearCookie(cookieKey);
		return res.status(200).send("OK");
	}
}

let url

const findFrontend = (req, res, next) => {
	url = req.headers.referer;
	next();
}

const fbsuccess = (req, res) => {
	res.redirect(url);
}

module.exports = app => {
	app.use(cookieParser());
	app.use(findFrontend);
	app.post('/register', register);
	app.post('/login', login);
	app.use(session({secret:'thisismysecret', resave: false, saveUninitialized: false}));
	app.use(passport.initialize());
	app.use(passport.session());
	app.use('/facebook/login', passport.authenticate('facebook', {scope: 'email'}));
	app.use('/facebook/callback', passport.authenticate('facebook', {successRedirect: '/fbsuccess', failureRedirect:'/fail'}));
	app.use('/fbsuccess', fbsuccess);
	app.use(isLoggedIn);
	app.put('/logout', logout);
}


text:
package org.eclipse.jgit.dircache;

import static org.eclipse.jgit.lib.Constants.OBJECT_ID_LENGTH;

import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.nio.ByteBuffer;
import java.util.Arrays;
import java.util.Comparator;

import org.eclipse.jgit.errors.UnmergedPathException;
import org.eclipse.jgit.lib.Constants;
import org.eclipse.jgit.lib.FileMode;
import org.eclipse.jgit.lib.ObjectId;
import org.eclipse.jgit.lib.ObjectWriter;
import org.eclipse.jgit.util.MutableInteger;
import org.eclipse.jgit.util.RawParseUtils;

/**
 * Single tree record from the 'TREE' {@link DirCache} extension.
 *

 * A valid cache tree record contains the object id of a tree object and the
 * total number of {@link DirCacheEntry} instances (counted recursively) from
 * the DirCache contained within the tree. This information facilitates faster
 * traversal of the index and quicker generation of tree objects prior to
 * creating a new commit.
 *

 * An invalid cache tree record indicates a known subtree whose file entries
 * have changed in ways that cause the tree to no longer have a known object id.
 * Invalid cache tree records must be revalidated prior to use.
 */
public class DirCacheTree {
	private static final byte[] NO_NAME = {};

	private static final DirCacheTree[] NO_CHILDREN = {};

	private static final Comparator<DirCacheTree> TREE_CMP = new Comparator<DirCacheTree>() {
		public int compare(final DirCacheTree o1, final DirCacheTree o2) {
			final byte[] a = o1.encodedName;
			final byte[] b = o2.encodedName;
			final int aLen = a.length;
			final int bLen = b.length;
			int cPos;
			for (cPos = 0; cPos < aLen && cPos < bLen; cPos++) {
				final int cmp = (a[cPos] & 0xff) - (b[cPos] & 0xff);
				if (cmp != 0)
					return cmp;
			}
			if (aLen == bLen)
				return 0;
			if (aLen < bLen)
				return '/' - (b[cPos] & 0xff);
			return (a[cPos] & 0xff) - '/';
		}
	};

	/** Tree this tree resides in; null if we are the root. */
	private DirCacheTree parent;

	/** Name of this tree within its parent. */
	private byte[] encodedName;

	/** Number of {@link DirCacheEntry} records that belong to this tree. */
	private int entrySpan;

	/** Unique SHA-1 of this tree; null if invalid. */
	private ObjectId id;

	/** Child trees, if any, sorted by {@link #encodedName}. */
	private DirCacheTree[] children;

	/** Number of valid children in {@link #children}. */
	private int childCnt;

	DirCacheTree() {
		encodedName = NO_NAME;
		children = NO_CHILDREN;
		childCnt = 0;
		entrySpan = -1;
	}

	private DirCacheTree(final DirCacheTree myParent, final byte[] path,
			final int pathOff, final int pathLen) {
		parent = myParent;
		encodedName = new byte[pathLen];
		System.arraycopy(path, pathOff, encodedName, 0, pathLen);
		children = NO_CHILDREN;
		childCnt = 0;
		entrySpan = -1;
	}

	DirCacheTree(final byte[] in, final MutableInteger off,
			final DirCacheTree myParent) {
		parent = myParent;

		int ptr = RawParseUtils.next(in, off.value, '\0');
		final int nameLen = ptr - off.value - 1;
		if (nameLen > 0) {
			encodedName = new byte[nameLen];
			System.arraycopy(in, off.value, encodedName, 0, nameLen);
		} else
			encodedName = NO_NAME;

		entrySpan = RawParseUtils.parseBase10(in, ptr, off);
		final int subcnt = RawParseUtils.parseBase10(in, off.value, off);
		off.value = RawParseUtils.next(in, off.value, '\n');

		if (entrySpan >= 0) {
			// Valid trees have a positive entry count and an id of a
			// tree object that should exist in the object database.
			//
			id = ObjectId.fromRaw(in, off.value);
			off.value += Constants.OBJECT_ID_LENGTH;
		}

		if (subcnt > 0) {
			boolean alreadySorted = true;
			children = new DirCacheTree[subcnt];
			for (int i = 0; i < subcnt; i++) {
				children[i] = new DirCacheTree(in, off, this);

				// C Git's ordering differs from our own; it prefers to
				// sort by length first. This sometimes produces a sort
				// we do not desire. On the other hand it may have been
				// created by us, and be sorted the way we want.
				//
				if (alreadySorted && i > 0
						&& TREE_CMP.compare(children[i - 1], children[i]) > 0)
					alreadySorted = false;
			}
			if (!alreadySorted)
				Arrays.sort(children, 0, subcnt, TREE_CMP);
		} else {
			// Leaf level trees have no children, only (file) entries.
			//
			children = NO_CHILDREN;
		}
		childCnt = subcnt;
	}

	void write(final byte[] tmp, final OutputStream os) throws IOException {
		int ptr = tmp.length;
		tmp[--ptr] = '\n';
		ptr = RawParseUtils.formatBase10(tmp, ptr, childCnt);
		tmp[--ptr] = ' ';
		ptr = RawParseUtils.formatBase10(tmp, ptr, isValid() ? entrySpan : -1);
		tmp[--ptr] = 0;

		os.write(encodedName);
		os.write(tmp, ptr, tmp.length - ptr);
		if (isValid()) {
			id.copyRawTo(tmp, 0);
			os.write(tmp, 0, Constants.OBJECT_ID_LENGTH);
		}
		for (int i = 0; i < childCnt; i++)
			children[i].write(tmp, os);
	}

	/**
	 * Determine if this cache is currently valid.
	 *

	 * A valid cache tree knows how many {@link DirCacheEntry} instances from
	 * the parent {@link DirCache} reside within this tree (recursively
	 * enumerated). It also knows the object id of the tree, as the tree should
	 * be readily available from the repository's object database.
	 *
	 * @return true if this tree is knows key details about itself; false if the
	 *         tree needs to be regenerated.
	 */
	public boolean isValid() {
		return id != null;
	}

	/**
	 * Get the number of entries this tree spans within the DirCache.
	 *

	 * If this tree is not valid (see {@link #isValid()}) this method's return
	 * value is always strictly negative (less than 0) but is otherwise an
	 * undefined result.
	 *
	 * @return total number of entries (recursively) contained within this tree.
	 */
	public int getEntrySpan() {
		return entrySpan;
	}

	/**
	 * Get the number of cached subtrees contained within this tree.
	 *
	 * @return number of child trees available through this tree.
	 */
	public int getChildCount() {
		return childCnt;
	}

	/**
	 * Get the i-th child cache tree.
	 *
	 * @param i
	 *            index of the child to obtain.
	 * @return the child tree.
	 */
	public DirCacheTree getChild(final int i) {
		return children[i];
	}

	ObjectId getObjectId() {
		return id;
	}

	/**
	 * Get the tree's name within its parent.
	 *

	 * This method is not very efficient and is primarily meant for debugging
	 * and final output generation. Applications should try to avoid calling it,
	 * and if invoked do so only once per interesting entry, where the name is
	 * absolutely required for correct function.
	 *
	 * @return name of the tree. This does not contain any '/' characters.
	 */
	public String getNameString() {
		final ByteBuffer bb = ByteBuffer.wrap(encodedName);
		return Constants.CHARSET.decode(bb).toString();
	}

	/**
	 * Get the tree's path within the repository.
	 *

	 * This method is not very efficient and is primarily meant for debugging
	 * and final output generation. Applications should try to avoid calling it,
	 * and if invoked do so only once per interesting entry, where the name is
	 * absolutely required for correct function.
	 *
	 * @return path of the tree, relative to the repository root. If this is not
	 *         the root tree the path ends with '/'. The root tree's path string
	 *         is the empty string ("").
	 */
	public String getPathString() {
		final StringBuilder r = new StringBuilder();
		appendName(r);
		return r.toString();
	}

	/**
	 * Write (if necessary) this tree to the object store.
	 *
	 * @param cache
	 *            the complete cache from DirCache.
	 * @param cIdx
	 *            first position of cache that is a member of this
	 *            tree. The path of cache[cacheIdx].path for the
	 *            range [0,pathOff-1) matches the complete path of
	 *            this tree, from the root of the repository.
	 * @param pathOffset
	 *            number of bytes of cache[cacheIdx].path that
	 *            matches this tree's path. The value at array position
	 *            cache[cacheIdx].path[pathOff-1] is always '/' if
	 *            pathOff is > 0.
	 * @param ow
	 *            the writer to use when serializing to the store.
	 * @return identity of this tree.
	 * @throws UnmergedPathException
	 *             one or more paths contain higher-order stages (stage > 0),
	 *             which cannot be stored in a tree object.
	 * @throws IOException
	 *             an unexpected error occurred writing to the object store.
	 */
	ObjectId writeTree(final DirCacheEntry[] cache, int cIdx,
			final int pathOffset, final ObjectWriter ow)
			throws UnmergedPathException, IOException {
		if (id == null) {
			final int endIdx = cIdx + entrySpan;
			final int size = computeSize(cache, cIdx, pathOffset, ow);
			final ByteArrayOutputStream out = new ByteArrayOutputStream(size);
			int childIdx = 0;
			int entryIdx = cIdx;

			while (entryIdx < endIdx) {
				final DirCacheEntry e = cache[entryIdx];
				final byte[] ep = e.path;
				if (childIdx < childCnt) {
					final DirCacheTree st = children[childIdx];
					if (st.contains(ep, pathOffset, ep.length)) {
						FileMode.TREE.copyTo(out);
						out.write(' ');
						out.write(st.encodedName);
						out.write(0);
						st.id.copyRawTo(out);

						entryIdx += st.entrySpan;
						childIdx++;
						continue;
					}
				}

				e.getFileMode().copyTo(out);
				out.write(' ');
				out.write(ep, pathOffset, ep.length - pathOffset);
				out.write(0);
				out.write(e.idBuffer(), e.idOffset(), OBJECT_ID_LENGTH);
				entryIdx++;
			}

			id = ow.writeCanonicalTree(out.toByteArray());
		}
		return id;
	}

	private int computeSize(final DirCacheEntry[] cache, int cIdx,
			final int pathOffset, final ObjectWriter ow)
			throws UnmergedPathException, IOException {
		final int endIdx = cIdx + entrySpan;
		int childIdx = 0;
		int entryIdx = cIdx;
		int size = 0;

		while (entryIdx < endIdx) {
			final DirCacheEntry e = cache[entryIdx];
			if (e.getStage() != 0)
				throw new UnmergedPathException(e);

			final byte[] ep = e.path;
			if (childIdx < childCnt) {
				final DirCacheTree st = children[childIdx];
				if (st.contains(ep, pathOffset, ep.length)) {
					final int stOffset = pathOffset + st.nameLength() + 1;
					st.writeTree(cache, entryIdx, stOffset, ow);

					size += FileMode.TREE.copyToLength();
					size += st.nameLength();
					size += OBJECT_ID_LENGTH + 2;

					entryIdx += st.entrySpan;
					childIdx++;
					continue;
				}
			}

			final FileMode mode = e.getFileMode();
			if (mode.getObjectType() == Constants.OBJ_BAD)
				throw new IllegalStateException("Entry \"" + e.getPathString()
						+ "\" has incorrect mode set up.");

			size += mode.copyToLength();
			size += ep.length - pathOffset;
			size += OBJECT_ID_LENGTH + 2;
			entryIdx++;
		}

		return size;
	}

	private void appendName(final StringBuilder r) {
		if (parent != null) {
			parent.appendName(r);
			r.append(getNameString());
			r.append('/');
		} else if (nameLength() > 0) {
			r.append(getNameString());
			r.append('/');
		}
	}

	final int nameLength() {
		return encodedName.length;
	}

	final boolean contains(final byte[] a, int aOff, final int aLen) {
		final byte[] e = encodedName;
		final int eLen = e.length;
		for (int eOff = 0; eOff < eLen && aOff < aLen; eOff++, aOff++)
			if (e[eOff] != a[aOff])
				return false;
		if (aOff == aLen)
			return false;
		return a[aOff] == '/';
	}

	/**
	 * Update (if necessary) this tree's entrySpan.
	 *
	 * @param cache
	 *            the complete cache from DirCache.
	 * @param cCnt
	 *            number of entries in cache that are valid for
	 *            iteration.
	 * @param cIdx
	 *            first position of cache that is a member of this
	 *            tree. The path of cache[cacheIdx].path for the
	 *            range [0,pathOff-1) matches the complete path of
	 *            this tree, from the root of the repository.
	 * @param pathOff
	 *            number of bytes of cache[cacheIdx].path that
	 *            matches this tree's path. The value at array position
	 *            cache[cacheIdx].path[pathOff-1] is always '/' if
	 *            pathOff is > 0.
	 */
	void validate(final DirCacheEntry[] cache, final int cCnt, int cIdx,
			final int pathOff) {
		if (entrySpan >= 0) {
			// If we are valid, our children are also valid.
			// We have no need to validate them.
			//
			return;
		}

		entrySpan = 0;
		if (cCnt == 0) {
			// Special case of an empty index, and we are the root tree.
			//
			return;
		}

		final byte[] firstPath = cache[cIdx].path;
		int stIdx = 0;
		while (cIdx < cCnt) {
			final byte[] currPath = cache[cIdx].path;
			if (pathOff > 0 && !peq(firstPath, currPath, pathOff)) {
				// The current entry is no longer in this tree. Our
				// span is updated and the remainder goes elsewhere.
				//
				break;
			}

			DirCacheTree st = stIdx < childCnt ? children[stIdx] : null;
			final int cc = namecmp(currPath, pathOff, st);
			if (cc > 0) {
				// This subtree is now empty.
				//
				removeChild(stIdx);
				continue;
			}

			if (cc < 0) {
				final int p = slash(currPath, pathOff);
				if (p < 0) {
					// The entry has no '/' and thus is directly in this
					// tree. Count it as one of our own.
					//
					cIdx++;
					entrySpan++;
					continue;
				}

				// Build a new subtree for this entry.
				//
				st = new DirCacheTree(this, currPath, pathOff, p - pathOff);
				insertChild(stIdx, st);
			}

			// The entry is contained in this subtree.
			//
			st.validate(cache, cCnt, cIdx, pathOff + st.nameLength() + 1);
			cIdx += st.entrySpan;
			entrySpan += st.entrySpan;
			stIdx++;
		}

		if (stIdx < childCnt) {
			// None of our remaining children can be in this tree
			// as the current cache entry is after our own name.
			//
			final DirCacheTree[] dct = new DirCacheTree[stIdx];
			System.arraycopy(children, 0, dct, 0, stIdx);
			children = dct;
		}
	}

	private void insertChild(final int stIdx, final DirCacheTree st) {
		final DirCacheTree[] c = children;
		if (childCnt + 1 <= c.length) {
			if (stIdx < childCnt)
				System.arraycopy(c, stIdx, c, stIdx + 1, childCnt - stIdx);
			c[stIdx] = st;
			childCnt++;
			return;
		}

		final int n = c.length;
		final DirCacheTree[] a = new DirCacheTree[n + 1];
		if (stIdx > 0)
			System.arraycopy(c, 0, a, 0, stIdx);
		a[stIdx] = st;
		if (stIdx < n)
			System.arraycopy(c, stIdx, a, stIdx + 1, n - stIdx);
		children = a;
		childCnt++;
	}

	private void removeChild(final int stIdx) {
		final int n = --childCnt;
		if (stIdx < n)
			System.arraycopy(children, stIdx + 1, children, stIdx, n - stIdx);
		children[n] = null;
	}

	static boolean peq(final byte[] a, final byte[] b, int aLen) {
		if (b.length < aLen)
			return false;
		for (aLen--; aLen >= 0; aLen--)
			if (a[aLen] != b[aLen])
				return false;
		return true;
	}

	private static int namecmp(final byte[] a, int aPos, final DirCacheTree ct) {
		if (ct == null)
			return -1;
		final byte[] b = ct.encodedName;
		final int aLen = a.length;
		final int bLen = b.length;
		int bPos = 0;
		for (; aPos < aLen && bPos < bLen; aPos++, bPos++) {
			final int cmp = (a[aPos] & 0xff) - (b[bPos] & 0xff);
			if (cmp != 0)
				return cmp;
		}
		if (bPos == bLen)
			return a[aPos] == '/' ? 0 : -1;
		return aLen - bLen;
	}

	private static int slash(final byte[] a, int aPos) {
		final int aLen = a.length;
		for (; aPos < aLen; aPos++)
			if (a[aPos] == '/')
				return aPos;
		return -1;
	}
}


text:
MEDUSA_BEGIN;

class IEditBox :public INode
{
	MEDUSA_RTTI(IEditBox,INode);
public:
	IEditBox(const StringRef& name = StringRef::Empty, const IEventArg& e = IEventArg::Empty);
	virtual ~IEditBox(void);
public:
	InputMode GetInputMode() const { return mInputMode; }
	void SetInputMode(InputMode val) { mInputMode = val; }

	TextInputFlag GetInputFlag() const { return mInputFlag; }
	void SetInputFlag(TextInputFlag val) { mInputFlag = val; }

	uint MaxCharCount() const { return mMaxCharCount; }
	void SetMaxCharCount(uint val) { mMaxCharCount = val; }

	bool HasText()const;

	//////////////////////////////////////////////////////////////////////////
	WStringRef Text() const;
	void SetText(WStringRef val);

	const FontId& TextFontId()const;
	void SetTextFontId(const FontId& val);

	Alignment TextAlignment() const;
	void SetTextAlignment(Alignment val);

	const Color4F& TextColor() const;
	void SetTextColor(const Color4F& val);

	//////////////////////////////////////////////////////////////////////////
	WStringRef PlaceHolderText() const;
	void SetPlaceHolderText(WStringRef val);

	const FontId& PlaceHolderFontId()const;
	void SetPlaceHolderFontId(const FontId& val);

	Alignment PlaceHolderTextAlignment() const;
	void SetPlaceHolderTextAlignment(Alignment val);

	const Color4F& PlaceHolderColor() const;
	void SetPlaceHolderColor(const Color4F& val);
	//////////////////////////////////////////////////////////////////////////

	NineGridSprite* BackgroundSprite() const { return mBackgroundSprite; }
	void SetBackgroundSprite(NineGridSprite* val);

	CursorVisibility GetCursorVisibility() const { return mCursorVisibility; }
	void SetCursorVisibility(CursorVisibility val);

	const Color4F& CursorColor() const { return mCursorColor; }
	void SetCursorColor(const Color4F& val);

	float CursorWidth() const { return mCursorWidth; }
	void SetCursorWidth(float val);

	float CursorBlinkRate() const { return mCursorBlinkRate; }
	void SetCursorBlinkRate(float val);

public:
	virtual bool ArrangeChildren(const Rect2F& limitRect = Rect2F::Zero, NodeLayoutArrangeFlags arrangeFlags = NodeLayoutArrangeFlags::None)override;

protected:
	virtual void OnPanBegin(INode* sender, PanBeginGestureEventArg& e);
	virtual void OnPan(INode* sender, PanGestureEventArg& e);
	virtual void OnPanEnd(INode* sender, PanEndGestureEventArg& e);

	virtual void OnKeyDown(INode* sender, KeyDownEventArg& e);
	virtual void OnKeyUp(INode* sender, KeyUpEventArg& e);
	virtual void OnCharInput(INode* sender, CharInputEventArg& e);

	virtual void OnTap(INode* sender, TapGestureEventArg& e);
	virtual void OnTapFailed(INode* sender);

	virtual void OnMoveableDirty(MoveableChangedFlags changedFlags);

	virtual void OnUpdateStatus();
	virtual void OnUpdateCursor();

protected:
	InputMode mInputMode=InputMode::Any;
	TextInputFlag mInputFlag=TextInputFlag::Sensitive;
	uint mMaxCharCount= Math::UIntMaxValue;

	//text
	ILabel* mTextLabel=nullptr;
	//placeholder
	ILabel* mPlaceHolderLabel=nullptr;

	//background
	NineGridSprite* mBackgroundSprite=nullptr;

	//cursor
	CursorVisibility mCursorVisibility=CursorVisibility::Auto;
	Color4F mCursorColor;
	float mCursorWidth=1.f;
	float mCursorBlinkRate=1.f;	//the duration by seconds per blink
	uint mCursorCharOffset=0;	//target at the end aft fist

	IShape* mCursorSprite=nullptr;	//cursor height=font size

protected:
	bool mIsEditing=false;
};

MEDUSA_END;


text:
Tily.Main = (function() {
  "use strict";

  /**
   * @typedef Size
   * @type {Object}
   * @property {number} width The width.
   * @property {number} height The height.
   */
  /**
   * @callback beforeDrawFunction
   * @param {number} elapsedTime The time elapsed in seconds since the last draw call.
   */
  /**
   * @callback afterDrawFunction
   * @param {number} elapsedTime The time elapsed in seconds since the last draw call.
   */
  /**
   * @typedef TilyOptions
   * @type {Object}
   * @property {?Size} [size=null] The viewport size, or null to use the canvas element
   * dimensions.
   * @property {boolean} [handleResize=true] True if the window resize event should be handled.
   * @property {boolean} [showFPS=false] True if the FPS should be displayed.
   * @property {boolean} [renderLoop=true] True if the render loop should be started
   * automatically.
   * @property {?beforeDrawFunction} [beforeDrawFunction=null] A function that will be called
   * after clearing the context but before drawing the active buffer. In the context of the
   * function, 'this' will point to the Tily instance.
   * @property {?afterDrawFunction} [afterDrawFunction=null] A function that will be called after
   * drawing the active buffer. In the context of the function, 'this' will point to the Tily instance.
   */
  /**
   * Default Tily options, used as a fall-back for options passed to the constructor.
   * @type {TilyOptions}
   */
  const _defaultTilyOptions = {
    size: null,
    handleResize: true,
    showFPS: false,
    renderLoop: true,
    beforeDrawFunction: null,
    afterDrawFunction: null
  };

  /**
   * The main Tily object. Initialises a canvas element and starts drawing tiles.
   * @class
   * @memberof Tily
   * @param {HTMLElement} canvas The canvas element in which to draw tiles.
   * @param {TilyOptions} [options] An optional object containing options for configuring this
   * Tily instance.
   */
  function Main(canvas, options) {
    if (!window) {  // Check that we are in a browser (ie. window exists)
      console.log("Couldn't find window. Tily.Main can only be created in the browser!");
      return
    }
    if (!canvas.getContext) {  // Check for canvas support
      console.log("Canvas not supported!");
      return;
    }

    /**
     * Options for configuring this Tily instance.
     * @type {TilyOptions}
     */
    this.options = { ..._defaultTilyOptions, ...options || {} };

    /**
     * The canvas element in which to draw tiles.
     * @type {HTMLElement}
     */
    this.canvas = canvas;

    /**
     * The context on which to draw tiles.
     * @type {CanvasRenderingContext2D}
     */
    this.context = canvas.getContext("2d");

    /**
     * The viewport width.
     * @type {number}
     */
    this.width = 0;

    /**
     * The viewport height.
     * @type {number}
     */
    this.height = 0;

    /**
     * The buffer currently being rendered.
     * @type {Tily.BufferBase}
     */
    this.activeBuffer = null;

    /**
     * The currently running buffer transition or null if there is no currently running
     * transition.
     * @default null
     * @type {?Tily.BufferTransition}
     */
    this.bufferTransition = null;

    /**
     * A request id returned from window.requestAnimationFrame that uniquely identifies the
     * entry in the callback list for the main render loop.
     * @type {number}
     */
    this.loop = null;

    /**
     * The unix epoch time of the last rendered frame.
     * @type {number}
     */
    this.lastFrameTime = new Date();

    /**
     * The number of frames rendered in the last second.
     * @type {number}
     */
    this.frameCount = 0;

    /**
     * The number of milliseconds elapsed since the last framerate update.
     * @type {number}
     */
    this.frameTime = 0;

    /**
     * The number of frames rendered per second.
     * @type {number}
     */
    this.frameRate = 0;

    // Handle the window resize event to get the current viewport size or use a fixed size
    if (!this.options.size || this.options.handleResize) {
      const self = this;
      function resize() {
        self.canvas.width = self.width = canvas.clientWidth * window.devicePixelRatio;
        self.canvas.height = self.height = canvas.clientHeight * window.devicePixelRatio;
      }
      window.addEventListener("resize", resize, false);
      resize();
    } else {
      this.canvas.width = this.width = this.options.size.width;
      this.canvas.height = this.height = this.options.size.height;
    }

    // Start the render loop
    if (this.options.renderLoop) {
      loop(this);
    }
  }

  /**
   * Perform a single iteration of the render loop.
   * @param {Tily.Main} t The Tily instance being looped.
   */
  function loop(t) {
    const now = new Date(),
      elapsedTime = (now - t.lastFrameTime) / 1000;
    t.lastFrameTime = now;
    t.frameTime += elapsedTime;
    t.frameCount++;
    if (t.frameTime > 1) {
      t.frameRate = t.frameCount;
      t.frameTime = 0;
      t.frameCount = 0;
    }
    t.draw(elapsedTime);
    t.loop = window.requestAnimationFrame(function() { loop(t) });
  }

  /**
   * Render the Tily instance onto the canvas.
   * @name draw
   * @function
   * @instance
   * @memberof Tily.Main
   * @param {number} elapsedTime The time elapsed in seconds since the last draw call.
   */
  Main.prototype.draw = function(elapsedTime) {
    this.context.save();
    this.context.clearRect(0, 0, this.width, this.height);
    if (typeof this.options.beforeDrawFunction == "function") {
      this.options.beforeDrawFunction.call(this, this.canvas, this.context, this.width, this.height, elapsedTime);
    }

    // Draw the active buffer and handle buffer fade transition
    const width = this.width,
      height = this.height;
    if (this.bufferTransition) {
      const alpha = this.bufferTransition.update(elapsedTime);
      if (this.bufferTransition.start) {
        this.context.globalAlpha = 1 - alpha;
        this.bufferTransition.start.draw(this.context, elapsedTime, width, height);
      }
      if (this.bufferTransition.finish) {
        this.context.globalAlpha = alpha;
        this.bufferTransition.finish.draw(this.context, elapsedTime, width, height);
      }
      if (this.bufferTransition.finished) {  // Remove the transition when it has finished
        this.bufferTransition = null;
      }
    } else if (this.activeBuffer) {
      this.context.globalAlpha = 1;
      this.activeBuffer.draw(this.context, elapsedTime, width, height);
    }
    if (typeof this.options.afterDrawFunction == "function") {
      this.options.afterDrawFunction.call(this, this.canvas, this.context, this.width, this.height, elapsedTime);
    }
    this.context.restore();
    if (this.options.showFPS) {
      this.context.save();
      this.context.font = '20px monospace';
      this.context.fillStyle = 'rgba(0, 0, 0, 0.5)';
      this.context.fillRect(this.width - (10 + 80), 10, 80, 30);
      this.context.fillStyle = 'white';
      this.context.textBaseline = 'top';
      this.context.textAlign = 'right';
      this.context.fillText(this.frameRate, this.width - 15, 15);
      this.context.restore();
    }
  };

  /**
   * Activate a new buffer with an optional fade transition from the current buffer.
   * @name activateBuffer
   * @function
   * @instance
   * @memberof Tily.Main
   * @param {Tily.Buffer} buffer The new buffer to activate.
   * @param {TransitionOptions} [options] An optional options object.
   * @returns {Promise} A promise instance for setting a transition finished callback.
   */
  Main.prototype.activateBuffer = function(buffer, options) {
    const transition = new Tily.BufferTransition(this.activeBuffer, buffer, options);
    this.bufferTransition = transition;
    this.activeBuffer = buffer;
    return new Promise(function(resolve, reject) { transition.finishedCallback = resolve; });
  };

  /**
   * @name size
   * @description The size of this Tily element measured in pixels.
   * @instance
   * @memberof Tily.Main
   * @type {Size}
   */
  Object.defineProperty(Main.prototype, "size", {
    get: function() {
      return {
        width: this.width,
        height: this.height
      };
    }
  });
  return Main;
}());


text:
package org.kie.workbench.common.stunner.core.client.shape.impl;

import org.kie.workbench.common.stunner.core.client.shape.Shape;
import org.kie.workbench.common.stunner.core.client.shape.ShapeState;
import org.kie.workbench.common.stunner.core.client.shape.view.ShapeView;

public interface ShapeStateHandler<V extends ShapeView, S extends Shape<V>> {

    ShapeStateHandler<V, S> forShape(S shape);

    ShapeStateHandler<V, S> shapeUpdated();

    void applyState(ShapeState shapeState);

    ShapeState reset();

    ShapeState getShapeState();
}


text:
@interface TLUserStatus : NSObject <TLObject>

@end

@interface TLUserStatus$userStatusEmpty : TLUserStatus

@end

@interface TLUserStatus$userStatusOnline : TLUserStatus

@property (nonatomic) int32_t expires;

@end

@interface TLUserStatus$userStatusOffline : TLUserStatus

@property (nonatomic) int32_t was_online;

@end

@interface TLUserStatus$userStatusRecently : TLUserStatus

@end

@interface TLUserStatus$userStatusLastWeek : TLUserStatus

@end

@interface TLUserStatus$userStatusLastMonth : TLUserStatus

@end


text:
package cn.osworks.aos.system.modules.controller.masterdata;

import java.util.List;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;

import cn.osworks.aos.core.asset.AOSJson;
import cn.osworks.aos.core.asset.WebCxt;
import cn.osworks.aos.core.typewrap.Dto;
import cn.osworks.aos.core.typewrap.Dtos;
import cn.osworks.aos.system.dao.mapper.Aos_sys_catalogMapper;
import cn.osworks.aos.system.modules.service.masterdata.CatalogService;

/**
 * 分类科目控制器
 *
 * @author OSWorks-XC
 * @date 2014-05-30
 */
@Controller
@RequestMapping(value = "system/catalog")
public class CatalogController {

	@Autowired
	 private Aos_sys_catalogMapper aos_sys_catalogMapper;
	@Autowired
	private CatalogService catalogService;

	/**
	 * 页面初始化
	 *
	 * @return
	 */
	@RequestMapping(value = "init")
	public String init() {
		return "aos/masterdata/catalog.jsp";
	}

	/**
	 * 查询参数列表
	 *
	 * @param request
	 * @param response
	 */
	@RequestMapping(value = "listCatalogs")
	public void listCatalogs(HttpServletRequest request, HttpServletResponse response) {
		Dto qDto = Dtos.newDto(request);
		List<Dto> list = catalogService.listCatalogs(qDto);
		String outString = AOSJson.toJson(list);
		WebCxt.write(response, outString);
	}

	/**
	 * 保存分类科目信息
	 *
	 * @param response
	 * @param request
	 * @return
	 */
	@RequestMapping(value = "saveCatalog")
	public void saveCatalog(HttpServletRequest request, HttpServletResponse response) {
		Dto dto = Dtos.newDto(request);
		Dto outDto = catalogService.saveCatalog(dto);
		WebCxt.write(response, AOSJson.toJson(outDto));
	}

	/**
	 * 修改分类科目信息
	 *
	 * @param response
	 * @param request
	 * @return
	 */
	@RequestMapping(value = "updateCatalog")
	public void updateCatalog(HttpServletRequest request, HttpServletResponse response) {
		Dto dto = Dtos.newDto(request);
		catalogService.updateCatalog(dto);
		WebCxt.write(response, "操作完成,分类数据修改成功。");
	}

	/**
	 * 删除分类信息
	 *
	 * @param response
	 * @param request
	 * @return
	 */
	@RequestMapping(value = "deleteCatalog")
	public void deleteCatalog(HttpServletRequest request, HttpServletResponse response) {
		Dto dto = Dtos.newDto(request);
		Dto outDto = catalogService.deleteCatalog(dto);
		outDto.setAppMsg("操作完成,删除分类数据成功。");
		WebCxt.write(response, AOSJson.toJson(outDto));
	}
}


text:
namespace variations {

const base::FilePath::CharType kVariationsFilename[] =
    FILE_PATH_LITERAL("Variations");

const char kExtendedSafeModeTrial[] = "ExtendedVariationsSafeMode4";
const char kControlGroup[] = "Control4";
const char kDefaultGroup[] = "Default4";
const char kSignalAndWriteViaFileUtilGroup[] = "SignalAndWriteViaFileUtil4";

}  // namespace variations


text:
using System.Collections.Generic;
using System.Text;
using Microsoft.AnalysisServices.AdomdClient;

namespace Glimpse.Adomd.Sample.Models
{
    public class CubeBuilder
    {
        public static List<CubeViewModel> BuildViewModel(CellSet cellSet)
        {
            var model =
                new List<CubeViewModel>
                    {
                        new CubeViewModel
                            {
                                Column = BuildColums(cellSet),
                                Analytics = BuildAnalyticsRow(cellSet)
                            }
                    };
            return model;
        }

        private static string BuildAnalyticsRow(CellSet cellSet)
        {
            var result = new StringBuilder();
            if (cellSet.Axes.Count > 0)
            {
                var tuplesOnRows = cellSet.Axes[0].Set.Tuples;
                foreach (var row in tuplesOnRows)
                {
                    foreach (var t in row.Members)
                    {
                        result.Append(t.Caption + "\n");
                    }
                }
            }
            return result.ToString();
        }

        private static Column[] BuildColums(CellSet cellSet)
        {
            var result = new List<Column>();
            var tuplesOnColumns = cellSet.Axes[0].Set.Tuples;
            var i = 0;
            foreach (var column in tuplesOnColumns)
            {
                result.Add(new Column
                {
                    HeaderName = column.Members[0].Caption,
                    FormattedValue = cellSet.Cells[i].FormattedValue
                });
                i++;
            }
            return result.ToArray();
        }
    }
}


text:
#ifndef DUNE_AX1_ACME2_INITIAL_HH
#define DUNE_AX1_ACME2_INITIAL_HH

#include <valarray>

#include <dune/pdelab/common/function.hh>

#include <dune/ax1/common/constants.hh>
#include <dune/ax1/common/tools.hh>
#include <dune/ax1/acme2/common/acme2_parametertree.hh>
#include <dune/ax1/acme2/configurations/zero_potential.hh>

//! This is a generic wrapper class that internally calls the INITIAL_GF object to
//! calculate initial values
template<typename GV, typename RF, int numSpecies, typename PHYSICS, typename INITIAL_GF>
class InitialCon
  : public Dune::PDELab::GridFunctionBase<
      Dune::PDELab::GridFunctionTraits<GV,RF,numSpecies,Dune::FieldVector<RF,numSpecies> >,
    InitialCon<GV,RF,numSpecies,PHYSICS,INITIAL_GF> >
{

public:
  typedef Dune::PDELab::GridFunctionTraits<GV,RF,numSpecies,Dune::FieldVector<RF,numSpecies> > Traits;

  //! construct from grid view
  InitialCon (const GV& gv_, PHYSICS& physics_, INITIAL_GF& initialGF_)
  : gv(gv_),
    physics(physics_),
    initialGF(initialGF_),
    params(physics_.getParams()),
    time(0.0),
    initConcEx(numSpecies),
    initConcIn(numSpecies)
  {
    for(int i=0; i<numSpecies; ++i)
    {
      initConcEx[i] = params.solution_ex.get(ION_NAMES[i], -1.);
      initConcIn[i] = params.solution_in.get(ION_NAMES[i], -1.);
    }
    std::string initConcStr = params.initConc();
  }

  //! evaluate extended function on element
  inline void evaluate (const typename Traits::ElementType& e,
                        const typename Traits::DomainType& xlocal,
                              typename Traits::RangeType& y) const
  {
    /*
    bool isMembraneBoundary = (std::abs(x[1]-params.yMemb()) < 1e-12
        || std::abs(x[1] - params.yMemb() - params.dMemb()) < 1e-12);

    // No charge carriers inside the membrane!
    if(physics.isMembrane(e) && not isMembraneBoundary) // Insane in the membrane!
    {
      for(int i=0; i<numSpecies; ++i)
      {
        y[i] = 0.0;
      }
      return;
    }
    */

    int elemIndex = physics.getElementIndex(e);
    int subdomainIndex = physics.getSubdomainIndex(e);

    for(int i=0; i<numSpecies; ++i)
    {
      switch(subdomainIndex)
      {
        case CYTOSOL:
        {
          y[i] = initConcIn[i];
          break;
        }
        case ES:
        {
          y[i] = initConcEx[i];
          break;
        }
        case MEMBRANE:
        {
          // No charge carriers inside the membrane!
          y[i] = 0.0;
          return;
        }
        default:
          DUNE_THROW(Dune::Exception, "Element has an unknown group index!");
      }
    }

    // Override default behaviour by evaluating custom intitial gridfunction
    typedef typename Traits::GridViewType::Grid::ctype ctype;
    const int dim = Traits::GridViewType::Grid::dimension;
    Dune::FieldVector<ctype,dim> x = e.geometry().global(xlocal);

    initialGF.evaluateGlobal(x,y);
  }

  inline const GV& getGridView () const
  {
    return gv;
  }

  // set time for subsequent evaluation
  void setTime (double t)
  {
    time = t;
  }

private:
  PHYSICS physics;
  INITIAL_GF& initialGF;
  const GV& gv;
  const Acme2Parameters& params;
  RF time;
  std::vector<RF> initConcEx;
  std::vector<RF> initConcIn;
};

// =============== Different functions for initial concentrations ===============================

/**
 * Trivial class that does nothing; can be used to keep default 'bulk' initial values
 * (constant values for each electrolyte subdomain)
 */
template<typename GV, typename RF, int numSpecies>
class InitialVoid :
  public Dune::PDELab::AnalyticGridFunctionBase<
    Dune::PDELab::AnalyticGridFunctionTraits<GV,RF,numSpecies>,
  InitialVoid<GV,RF,numSpecies> >
{
  public:
      typedef Dune::PDELab::AnalyticGridFunctionTraits<GV,RF,numSpecies> Traits;
      typedef Dune::PDELab::AnalyticGridFunctionBase<Traits, InitialVoid<GV,RF,numSpecies> > BaseT;

      typedef typename Traits::DomainType DomainType;
      typedef typename Traits::RangeType RangeType;

      InitialVoid(const GV& gv, const Acme2Parameters& params_)
      : BaseT(gv)
      {}

      // Does nothing
      inline void evaluateGlobal(const DomainType & x, RangeType & y) const
      {
      }

  private:
};

/**
 * Step initial concentrations: constant concentrations for each domain (intra-/extracellular)
 */
template<typename GV, typename RF, int numSpecies>
class InitialStep :
  public Dune::PDELab::AnalyticGridFunctionBase<
    Dune::PDELab::AnalyticGridFunctionTraits<GV,RF,numSpecies>,
  InitialStep<GV,RF,numSpecies> >
{
  public:
    typedef Dune::PDELab::AnalyticGridFunctionTraits<GV,RF,numSpecies> Traits;
    typedef Dune::PDELab::AnalyticGridFunctionBase<Traits, InitialStep<GV,RF,numSpecies> > BaseT;

    typedef typename Traits::DomainType DomainType;
    typedef typename Traits::RangeType RangeType;

    InitialStep(const GV& gv, const Acme2Parameters& params_)
    : BaseT(gv),
      params(params_),
      initConcEx(numSpecies),
      initConcIn(numSpecies),
      smoothStep(false)
    {
      for(int i=0; i<numSpecies; ++i)
      {
        initConcEx[i] = params.solution_ex.get(ION_NAMES[i], -1.);
        initConcIn[i] = params.solution_in.get(ION_NAMES[i], -1.);
      }
      std::string initConcStr = params.initConc();
      if(initConcStr == "smoothStep")
      {
        smoothStep = true;
      }
    }

    inline void evaluateGlobal(const DomainType & x, RangeType & y) const
    {
      for ( int i=0; i<numSpecies; ++i )
      {
        // Intracellular domain
        if (x[1] < params.yMemb() || std::abs(x[1] - params.yMemb()) < 1e-12)
        {
          y[i] = initConcIn[i];
        }
        // Extracellular domain
        else if(x[1] > params.yMemb() || std::abs(x[1] - params.yMemb()) < 1e-12)
        {
          y[i] = initConcEx[i];
        // Membrane
        } else {
          // Smooth discontinuity in initial concentrations
          if(smoothStep)
          {
            typename Traits::DomainFieldType y_scale = (x[1] - params.yMemb()) / (params.dMemb());
            y[i] = initConcIn[i] + (initConcEx[i]-initConcIn[i]) * (y_scale*y_scale*(3-2*y_scale));
          // No charge carriers inside membrane
          } else {
            if (x[1] < params.yMemb() + 0.5 * params.dMemb()) y[i] = initConcIn[i];
            else                                              y[i] = initConcEx[i];
          }
        }
      }
    }

  private:
    const Acme2Parameters& params;
    std::vector<RF> initConcEx;
    std::vector<RF> initConcIn;
    bool smoothStep;
};

/**
 * SquarePulse initial concentrations: square pulse with constant concentrations for specified x-range, 0 elsewhere
 */
template<typename GV, typename RF, int numSpecies>
class InitialSquarePulse :
  public Dune::PDELab::AnalyticGridFunctionBase<
    Dune::PDELab::AnalyticGridFunctionTraits<GV,RF,numSpecies>,
  InitialSquarePulse<GV,RF,numSpecies> >
{
  public:
    typedef Dune::PDELab::AnalyticGridFunctionTraits<GV,RF,numSpecies> Traits;
    typedef Dune::PDELab::AnalyticGridFunctionBase<Traits, InitialSquarePulse<GV,RF,numSpecies> > BaseT;

    typedef typename Traits::DomainType DomainType;
    typedef typename Traits::RangeType RangeType;

    InitialSquarePulse(const GV& gv, const Acme2Parameters& params_)
    : BaseT(gv),
      params(params_)
    {}

    inline void evaluateGlobal(const DomainType & x, RangeType & y) const
    {
      double dpulse = 5.0;
      double xCenter = 0.5 * (params.xMax() - params.xMin());
      double yCenter = 0.5 * (params.yMemb() - params.yMin());
      double pulse_amplitude = 1.0;

      y = 0.0;

      // square pulse
      if ( x[0] > xCenter-dpulse and x[0] < xCenter+dpulse
          && x[1] > yCenter-dpulse and x[1] < yCenter+dpulse)
      {
        y[0] = pulse_amplitude;
      } else {
        y[0] = 1.0;
      }

      if(numSpecies > 2)
      {
        // potassium
        y[1] = 1.0;
      }
      if(numSpecies > 2)
      {
        // chloride
        y[2] = 2.0;
      }
    }

  private:
    const Acme2Parameters& params;
};

/**
 * TrianglePulse initial concentrations: triangle pulse for specified x-range, 0 elsewhere
 */
template<typename GV, typename RF, int numSpecies>
class InitialTrianglePulse :
  public Dune::PDELab::AnalyticGridFunctionBase<
    Dune::PDELab::AnalyticGridFunctionTraits<GV,RF,numSpecies>,
  InitialTrianglePulse<GV,RF,numSpecies> >
{
  public:
    typedef Dune::PDELab::AnalyticGridFunctionTraits<GV,RF,numSpecies> Traits;
    typedef Dune::PDELab::AnalyticGridFunctionBase<Traits, InitialTrianglePulse<GV,RF,numSpecies> > BaseT;

    typedef typename Traits::DomainType DomainType;
    typedef typename Traits::RangeType RangeType;

    InitialTrianglePulse(const GV & gv, const Acme2Parameters& params_)
    : BaseT(gv),
      params(params_)
    {}

    inline void evaluateGlobal(const DomainType & x, RangeType & y) const
    {
      double xpulse = 0.5 * (params.xMax() - params.dMemb());
      double pulse_amplitude = 1.0;

      // triangle pulse
      if ( x[0] == 0.0 )
      {
       y[0] = pulse_amplitude;
       if(numSpecies > 1) y[1] = y[0];
       if(numSpecies > 2) y[2] = y[0] * 2.0;
      }
      else if ( x[0] < 0.0 and x[0] > -xpulse )
      {
       y[0] = pulse_amplitude * ( 1.0 + x[0] / xpulse );
       if(numSpecies > 1) y[1] = y[0];
       if(numSpecies > 2) y[2] = y[0] * 2.0;
      }
      else if ( x[0] > 0.0 and x[0] < xpulse )
      {
       y[0] = pulse_amplitude * ( 1.0 - x[0] / xpulse );
       if(numSpecies > 1) y[1] = y[0];
       if(numSpecies > 2) y[2] = y[0] * 2.0;
      }
      else
      {
       y[0] = 0.0;
       if(numSpecies > 1) y[1] = 0.0;
       if(numSpecies > 2) y[2] = 0.0;
      }
    }

  private:
    const Acme2Parameters& params;
};

// initial potential ###############################################################################

template<typename GV, typename RF, typename Physics, typename GF_CD, typename INITIAL_GF>
class InitialPot
  : public Dune::PDELab::GridFunctionBase<Dune::PDELab::GridFunctionTraits<GV,RF,1,Dune::FieldVector<RF,1> >,
    InitialPot<GV,RF,Physics,GF_CD,INITIAL_GF> >
{

public:
  typedef Dune::PDELab::GridFunctionTraits<GV,RF,1,Dune::FieldVector<RF,1> > Traits;

  //! construct from grid view
  InitialPot (const GV& gv_, Physics& physics_, GF_CD& gfChargeDensity_, INITIAL_GF& initialGF_, int intorder_=2) :
    gv(gv_), physics(physics_), gfChargeDensity(gfChargeDensity_), initialGF(initialGF_), intorder(intorder_),
    xmax(physics.getParams().xMax()), xmin(physics.getParams().xMin()),
    calculateAll(false)
  {}

  //! evaluate extended function on element
  inline void evaluate (const typename Traits::ElementType& e,
                        const typename Traits::DomainType& xlocal,
                        typename Traits::RangeType& y) const
  {
    const int dim = Traits::GridViewType::Grid::dimension;
    typedef typename Traits::GridViewType::Grid::ctype ctype;
    Dune::FieldVector<ctype,dim> x = e.geometry().global(xlocal);

    //if(physics.getSubdomainIndex(e) == CYTOSOL)
    //{
    //  y = physics.convertFrom_mV(-65.);
    //} else {
      initialGF.evaluate(e,xlocal,y);
    //}

    /*
    // We are on the boundary
    if (x[0] < xmin+1.0e-6 || x[0] >  xmax-1.0e-6)
    {
      //std::valarray<RF> source;
      //std::valarray<RF> pos;
      //Tools::getSolutionVectorDG(gfChargeDensity, 0, pos, source);
      //source = source*physics.getPoissonConstant();

      y = calculateExactPotential(x);

      // Left boundary: Cytosol
      if (x[0] < xmin+1.0e-6 )
      {
        //y=Tools::multipoleExpansion1D(physics.position, source, physics.permittivity, -4.0, 3);
        //y=Tools::potentialExact(physics.getPosition(), source, physics.getPermittivity(), xmin);
        //debug_verb << "### [left] boundary potential values: " << y << std::endl;
        //y = 0.0;
      }

      // Right boundary: Extracellular fluid
      if ( x[0] >  xmax-1.0e-6 )
      {
        //y=Tools::multipoleExpansion1D(physics.position, source, physics.permittivity, 4.0, 3);
        //y=Tools::potentialExact(physics.getPosition(), source, physics.getPermittivity(), xmax);
        //debug_verb << "### [right] boundary potential values: " << y << std::endl;
        y = 0.0;
      }

      // for testing: set potential to zero
      //y = 0.0;
    }
    // We are not on the boundary
    else
    {
      if(not calculateAll)
      {
        y = 0.0;
      } else {
        // Calculate potential values also in interior!
        y = calculateExactPotential(x);
      }

    }
    //y = ( 500.0 + x[0] ) / 100.0;

    y = 0.0;
    */

  }

  inline RF calculateExactPotential(const typename Traits::DomainType& x) const
  {
    const int dim = GV::dimension;
    assert(dim == 1);

    typedef typename GV::template Codim<0>::Iterator ElementIterator;
    typedef typename Dune::SingleCodimSingleGeomTypeMapper<GV, 0> ElementMapper;
    typedef typename GF_CD::Traits::DomainType DT;
    typedef typename GF_CD::Traits::DomainFieldType DF;
    typedef typename GF_CD::Traits::RangeType RT;

    ElementMapper elementMapper(gv);
    RF potExact = 0.0;
    for (ElementIterator eit=gv.template begin<0>(); eit!=gv.template end<0>(); ++eit)
    {
      int elemIndex = elementMapper.map(*eit);

      RF permittivity = physics.getPermittivity(physics.getSubdomainIndex(elemIndex));

      // select quadrature rule
      Dune::GeometryType gt = eit->geometry().type();
      const Dune::QuadratureRule<DF,dim>& rule = Dune::QuadratureRules<DF,dim>::rule(gt,intorder);

      for (typename Dune::QuadratureRule<DF,dim>::const_iterator it=rule.begin(); it!=rule.end(); ++it)
      {
        RF weight = it->weight();
        RF integrationElement = eit->geometry().integrationElement(it->position());

        RT chargeDensity(0.0);
        gfChargeDensity.evaluate(*eit, it->position(), chargeDensity);
        //debug_verb << "cd = " << chargeDensity << std::endl;

        RF source = 0.0;
        source = chargeDensity[0]*physics.getPoissonConstant();

        source *= (-0.5/permittivity) * std::abs(x - eit->geometry().global(it->position()));

        potExact += (source * weight * integrationElement);
      }
    }
    return potExact;
  }

  inline const GV& getGridView() const
  {
    return gv;
  }

  //! set time for subsequent evaluation
  void setTime (double t)
  {
    time = t;
  }

  void setCalculateAll(bool calculateAll_)
  {
    calculateAll = calculateAll_;
  }

private:
  const GV& gv;
  Physics & physics;
  GF_CD& gfChargeDensity;
  INITIAL_GF& initialGF;
  const int intorder;
  RF time;
  RF xmax;
  RF xmin;
  bool calculateAll;

};
#endif /* DUNE_AX1_ACME2_INITIAL_HH */


text:
/**
 * Express middlewares for @oada/id-client
 *
 * @packageDocumentation
 */

import type express from 'express';

import {
  Options,
  getAccessToken as coreGetAccessToken,
  getIDToken as coreGetIDToken,
  handleRedirect as coreHandleRedirect,
} from './core.js';

// Add our stuff to the request interface?
import type { IncomingMessage } from 'http';
import type { ParsedQs } from 'qs';
export type Token = Resolves<ReturnType<typeof coreHandleRedirect>>;
declare module 'express-serve-static-core' {
  export interface Request<
    // eslint-disable-next-line @typescript-eslint/no-unused-vars
    P = ParamsDictionary,
    // eslint-disable-next-line @typescript-eslint/no-unused-vars, unicorn/prevent-abbreviations, @typescript-eslint/no-explicit-any
    ResBody = any,
    // eslint-disable-next-line @typescript-eslint/no-unused-vars, unicorn/prevent-abbreviations, @typescript-eslint/no-explicit-any
    ReqBody = any,
    // eslint-disable-next-line @typescript-eslint/no-unused-vars, unicorn/prevent-abbreviations
    ReqQuery = ParsedQs,
    // eslint-disable-next-line @typescript-eslint/no-unused-vars, @typescript-eslint/no-explicit-any
    Locals extends Record<string, any> = Record<string, any>
  > extends IncomingMessage {
    token?: Token;
  }
}

type Resolves<T> = T extends Promise<infer V> ? V : T;

function middlewareify(
  method: typeof coreGetAccessToken | typeof coreGetIDToken
) {
  return ({
      domain,
      options,
    }: {
      domain?: string;
      options: Options;
    }): express.RequestHandler =>
    async (request, response) => {
      await method(
        request.param('domain') ?? domain,
        { ...options, scope: request.param('scope') ?? options.scope },
        (uri) => {
          response.redirect(uri);
        }
      );
    };
}

/**
 * Create a middleware for handling an ID token endpoint
 * @param domain
 * @param options
 * @returns Express middleware
 */
export const getIDToken = middlewareify(coreGetIDToken);

/**
 * Create a middleware for handling an access token endpoint
 * @param domain
 * @param options
 * @returns Express middleware
 */
export const getAccessToken = middlewareify(coreGetAccessToken);

/**
 * Middleware for handling redirects after OAuth flow
 */
export const handleRedirect: express.RequestHandler = async (request) => {
  const token = await coreHandleRedirect(request.query);
  if (token) {
    request.token = token;
  }
};


text:
#import <Foundation/Foundation.h>
@class doSingletonModule;
@protocol  doIScriptEngine;
@interface doSingletonModuleHelper : NSObject
+ (NSData*) HttpDownloadData:(NSString*) _url;
@end


text:
Ruby-driven IPTables

## Installation

Add this line to your application's Gemfile:

    gem 'ipscriptables'

And then execute:

    $ bundle

Or install it yourself as:

    $ gem install ipscriptables

## Usage

TODO: write real instructions.

Write a script a bit like this (ip6tables work too):

```ruby
family :inet do
  table :nat do
    inherit(:DOCKER)
    inherit(:PREROUTING, :OUTPUT) { |rule| rule.target == 'DOCKER' }
    inherit(:POSTROUTING) { |rule| rule.target == 'MASQUERADE' }
  end

  table :filter do
    inherit(:INPUT) { |rule| rule.target == 'FWR' || rule.target == 'LXC' }
    inherit(:FORWARD) { |rule| rule[:i] == 'docker0' || rule[:o] == 'docker0' }
    inherit(:LXC)
    chain :FWR do
      rule :i => ['lo', 'docker0'], :j => 'ACCEPT'
      rule '-m state --state RELATED,ESTABLISHED -j ACCEPT'
      rule '-p icmp -j ACCEPT'
      rule '-p tcp -m tcp --dport', [22, 80, 443], '-j ACCEPT'
      rule '-p tcp -m tcp --tcp-flags SYN,RST,ACK SYN -j REJECT --reject-with icmp-port-unreachable'
      rule '-p udp -j REJECT --reject-with icmp-port-unreachable'
    end
  end
end
```

Run `ipscriptables path/to/script.rb`, review diff, run `ipscriptables
--apply path/to/script.rb`.

## Contributing

See the [CONTRIBUTING.md](CONTRIBUTING.md) file


text:
package net.sf.mmm.client.ui.api.handler.event;

import net.sf.mmm.client.ui.api.event.EventType;
import net.sf.mmm.client.ui.api.event.UiEvent;
import net.sf.mmm.client.ui.api.event.UiEventFocusGain;
import net.sf.mmm.client.ui.api.event.UiEventFocusLoss;

/**
 * This is the {@link UiHandlerEvent} for the actions {@link #onFocusGain(UiEventFocusGain)} and
 * {@link #onFocusGain(UiEventFocusGain)}. There will always be two events:
 *

 *
The object that previously had the focus will receive an event that its focus has been lost.

 *
The object that has been focused will receive and event that its has gained the focus.

 *

 *
 * @author Joerg Hohwiller (hohwille at users.sourceforge.net)
 * @since 1.0.0
 */
// TODO hohwille We need Java8 support for GWT!
// public interface UiHandlerEventFocus extends UiHandlerEvent {
public abstract class UiHandlerEventFocus implements UiHandlerEvent {

  /**
   * {@inheritDoc}
   */
  @Override
  public void onEvent(UiEvent event) {

    if (event.getType() == EventType.FOCUS_GAIN) {
      onFocusGain((UiEventFocusGain) event);
    } else if (event.getType() == EventType.FOCUS_LOSS) {
      onFocusLoss((UiEventFocusLoss) event);
    }
  }

  /**
   * This method is invoked if an UI object (a text input, etc.) has gained focus.
   *
   * @param event is the {@link UiEventFocusGain focus gain event}.
   */
  public abstract void onFocusGain(UiEventFocusGain event);

  /**
   * This method is invoked if an UI object (a text input, etc.) has lost focus (blur).
   *
   * @param event is the {@link UiEventFocusLoss focus gain event}.
   */
  public abstract void onFocusLoss(UiEventFocusLoss event);

}