text:
/*jshint node:true globalstrict:true*/
"use strict";

var qs = require('querystring'),
    fs = require('fs'),
    url = require('url'),
    ejs = require('ejs'),
    queue = require('queue'),
    express = require('express'),
    everyauth = require('everyauth'),
    RedisStore = require('connect-redis')(express),
    Dropbox = require('./lib/dropbox'),
    RunKeeper = require('./lib/runkeeper');

var template = ejs.compile(fs.readFileSync('views/kml.ejs', 'utf8'));

var dropbox = new Dropbox({
    hostName: process.env.SERVER_URL,
    consumerKey: process.env.DROPBOX_KEY,
    consumerSecret: process.env.DROPBOX_SECRET,
    sandbox: true
});

var runkeeper = new RunKeeper({
    client_id: process.env.RUNKEEPER_KEY,
    client_secret: process.env.RUNKEEPER_SECRET,
    auth_url: process.env.RUNKEEPER_AUTH_URL,
    access_token_url: process.env.RUNKEEPER_TOKEN_URL,
    redirect_uri: process.env.SERVER_URL + '/auth/runkeeper',
    api_domain: 'api.runkeeper.com'
});

var app = express.createServer();

// Configuration

var redisUrl = url.parse(process.env.REDISTOGO_URL),
    redisOptions = {
        port: redisUrl.port,
        host: redisUrl.hostname,
        pass: redisUrl.auth && redisUrl.auth.split(":")[1] // just the password
    };

app.configure(function(){
    app.set('views', __dirname + '/views');
    app.set('view engine', 'ejs');
    app.use(express.bodyParser());
    app.use(express.methodOverride());
    app.use(express.cookieParser());
    app.use(express.session({ store: new RedisStore(redisOptions), secret: process.env.SESSION_SECRET }));
    app.use(everyauth.middleware());
    app.use(app.router);
    app.use(express['static'](__dirname + '/public'));
});

app.configure('development', function(){
    app.use(express.errorHandler({ dumpExceptions: true, showStack: true }));
});

app.configure('production', function(){
    app.use(express.errorHandler());
});

// Routes

app.get('/', function(req,res){
    var runkeeperAuth = req.session.auth && req.session.auth.runkeeper,
        dropboxAuth = req.session.auth && req.session.auth.dropbox,
        hasAuth = (runkeeperAuth && dropboxAuth) ? true : false,
        compoundId = hasAuth ? runkeeperAuth.user.userID + '-' + dropboxAuth.user.uid : null;
    res.render('index', {
        locals: {
            title: 'RunBoxer',
            hasRunKeeper: Boolean(runkeeperAuth),
            runkeeper: runkeeperAuth,
            hasDropbox: Boolean(dropboxAuth),
            dropbox: dropboxAuth,
            jobQueued: compoundId && (compoundId in jobs)
        }
    });
});

// protect API
function requireAuth(name) {
    return function(req,res,next) {
        console.log('checking for %s auth', name);
        var serviceAuth = req.session.auth && req.session.auth[name];
        if (serviceAuth) {
            req[name] = serviceAuth;
            next();
        } else {
            res.send(name + " needs authorizing first.", 403);
        }
    };
}

app.all('/api/runkeeper/*', requireAuth('runkeeper'));
app.all('/api/dropbox/*', requireAuth('dropbox'));

app.get('/api/runkeeper/profile', runkeeper.profileRoute());
// app.get('/api/runkeeper/user', runkeeper.userRoute());
// app.get('/api/runkeeper/fitness-activities', runkeeper.fitnessActivityFeedRoute());
app.get('/auth/runkeeper', runkeeper.authRoute());

// app.get(/^\/api\/runkeeper(\/.*)/, function(req, res, next) {
//   var uri = req.params[0],
//       accept = req.query.media_type || 'application/json',
//       token = req.runkeeper.access_token;
//   if (uri && uri.length) {
//       runkeeper.get(uri, accept, token, function(err,data) {
//           if (err) {
//               return next(err);
//           }
//           console.log(data);
//           res.send(data);
//       });
//   } else {
//       next();
//   }
// });

var jobs = {};

function processJob(id) {
    var job = jobs[id],
        token = job.runkeeper.access_token,
        feedQueue = queue(1);
    function getNextFeed(uri){
        return function(callback){
            var accept = 'application/vnd.com.runkeeper.FitnessActivityFeed+json';
            runkeeper.get(uri, accept, token, function(err,feed) {
                if (feed && feed.next) {
                    console.log('queueing next feed for job %s', id);
                    feedQueue.defer(getNextFeed(feed.next));
                }
                callback(err,feed);
            });
        };
    }
    console.log('queueing first feed for job %s', id);
    feedQueue.defer(getNextFeed(job.runkeeper.user.fitness_activities))
        .await(function(err,feeds){
            if (err || !feeds || !feeds.length) {
                console.error('job %s failed to get activity feeds', id);
                // TODO: mark job as failed in queue?
                console.error((err && err.stack) || 'Received empty feeds - not sure why.');
                delete jobs[id];
            } else {
                if (!Array.isArray(feeds)) {
                    feeds = [ feeds ];
                }
                console.log('job %s got feeds', id);
                var q = queue(5),
                    size = feeds[0].size,
                    offset = 0;
                feeds.forEach(function(feed){
                    var adjust = offset;
                    feed.items.forEach(function(item,i) {
                        var uri = item.uri,
                            accept = 'application/vnd.com.runkeeper.FitnessActivity+json';
                        q.defer(function(callback){
                            console.log('job %s fetching %d of %d items', id, adjust+i, size)
                            runkeeper.get(uri, accept, token, callback);
                        });
                    });
                    offset += feed.items.length;
                });
                q.await(function(error, results) {
                    console.log('job %s got %d results', id, results.length);
                    if (err || !results) {
                        console.error('job %s failed to get activity item', id);
                        // TODO: mark job as failed in queue?
                        console.error((err && err.stack) || 'Received empty results - not sure why.');
                        delete jobs[id];
                    } else {
                        var data = {
                            name: 'Test Runboxer Export',
                            description: 'Test Runboxer Description',
                            items: results
                        };
                        dropbox.filesPut('/test.kml', template(data), "application/vnd.google-earth.kml+xml", job.dropbox, function(err, data) {
                            if (err || !data) {
                                console.error('Failed to put final KML into Dropbox');
                                console.error((err && err.stack) || 'Received empty response from Dropbox - not sure why.');
                            } else {
                                console.log('job %s complete', id);
                            }
                            delete jobs[id];
                        });
                    }
                });
            }
        });
}

app.post('/api/runboxer/job', requireAuth('runkeeper'), requireAuth('dropbox'), function(req, res, next) {
    var compoundId = req.runkeeper.user.userID + '-' + req.dropbox.user.uid;
    if (compoundId in jobs) {
        res.send(418);
    } else {
        jobs[compoundId] = { runkeeper: req.runkeeper, dropbox: req.dropbox, items: [] };
        res.redirect('/');
        // TODO: proper queue (kue?)
        processJob(compoundId);
    }
});

// app.post('/api/dropbox/put-test', function(req,res){
//     dropbox.filesPut('/test.txt', "I am a test file.", "text/plain", req.dropbox, function(err, data) {
//         if (err) {
//             console.log(err);
//             res.send('oauth client error',500);
//         } else {
//             res.send(data);
//         }
//     });
// });

app.listen(process.env.PORT, function() {
    console.log("Express server listening on port %d in %s mode", app.address().port, app.settings.env);
});


text:
set -x
trap read debug
#
# Copyright (c) 2013 Charles H Martin, PhD
#
#  Calculated Content
#  http://calculatedcontent.com
#  charles@calculatedcontent.com
#
#Pre-requisites:
#You must create a security group with a rule allowing port 443 (HTTPS) and port 22(SSH) as this is
#what chef server >=11.x now uses, in the script below that security group is called chefami
#the security group can be created from the AWS web console or using the amazon supplied ec2-api-tools
#
# TDDO:
#	- convert to ruby script and suppress useless output (chef package download, chef tests, ...) (redirect verbose output to a log file)
#	- check environment variables are present and provide a meaningful help if not (and stop the script)
#

CHEF_USER=$CHEF_USER
KEY_NAME=$CHEF_KEY #the name shown under "Key Pairs" in AWS console
KEY_FILE=$CHEF_PEM #the path to your AWS key

SECURITY_GROUPS="chefami" #group you created with port 22 and 443 open
INSTANCE_TYPE="m1.small" #Note that at least a small is recommended currently
AMI_ID="ami-696e652c"
#AMI_ID=$CHEF_AMI_ID #AMI you wish to use- must be available in your region
NODE_NAME="chefami" #A descriptive name that will appear in knife ec2 server list output

echo "NOTE: Pay attention as this script runs- you will be prompted to enter a password at one point"

echo "Chef Server config:"
echo "        AMI            $AMI_ID"
echo "        INSTANCE_TYPE  $INSTANCE_TYPE"
echo "        KEY_NAME       $KEY_NAME"
echo "        KEY_FILE       $KEY_FILE"
echo ""

echo -n "Checking if knife is installed and in the PATH ... "
if ! command -v knife > /dev/null
then
	echo "NOK [knife command not installed or not in the path. Run 'gem install knife-ec2 --no-rdoc --no-ri']"
	exit
else
	echo "OK"
fi

echo -n "Checking AWS keys are properly set for knife by listing your instances:"
knife ec2 server list
if [ $? != 0 ]
then
	echo "ERROR: knife did NOT work. AWS key not properly configured?"
fi
#see here for how to create a security group in ruby:
#https://github.com/fnichol/knife-server/blob/master/lib/knife/server/ec2_security_group.rb
#knife server plugin would allow us to do everything with just this command, but it doesn't work, I've filed an issue on github already
#knife server bootstrap ec2 -I $AMI_ID -k $KEY_NAME --ssh-key $KEY_FILE --ssh-user ubuntu -f $INSTANCE_TYPE --node-name $NODE_NAME

if [ -f instance_info ]
then
    echo "removing old instance_info file"
    rm "instance_info"
fi

#
##Create an instance on which to run chef server and store the generated public IP in a hacky way
echo "trying to create instance of chef-server"
knife ec2 server create -N "chef-server" -x ubuntu -I $AMI_ID  -f $INSTANCE_TYPE -k $KEY_NAME --ssh-key $KEY_FILE  -G $SECURITY_GROUPS --hint ec2 -a public_ip_address     | tee instance_info
ip_address=`cat instance_info | awk -F : '/Public IP/{gsub(/[ \t]/,"",$2);print $2 }' | tail -n 1`
host_name=`cat instance_info | awk -F : '/Public DNS/{gsub(/[ \t]/,"",$2);print $2 }' | tail -n 1`
cat instance_info

if [ -f instance_info ]
then
    rm "instance_info"
else
    echo "ERROR: There was a problem creating the Chef instance, exiting now"
    exit
fi

if [ -z $ip_address ]
then
	echo "ERROR: Chef IP address is empty"
	exit
else
	echo "Chef IP address is '$ip_address'"
fi

if [ -z $host_name ]
then
	echo "ERROR: Chef IP public host name is empty"
	exit
else
	echo "Chef public host name is '$host_name'"
fi

if [ ! -d .chef ]
then
	mkdir .chef
else
	# TODO: version this (avoids losing the keys), maybe back it up with a serial number at the end of the script so it never gets deleted
	cp -r .chef .chef.bak
    rm -rf .chef
    echo "INFO: your existing .chef/ has been moved to .chef.bak/"
    mkdir .chef
fi

#set the FQDN to the amazon public DNS name- if you don't do this knife cookbook will try to reference the internal DNS name
#NOTE: the FQDN must be set properly before you do chef-server-ctl reconfigure
#disable StrictHostKeyChecking on the first connection attempt to avoid (yes/no) prompt
ssh -oStrictHostKeyChecking=no -i $KEY_FILE ubuntu@$ip_address "echo $host_name > /etc/hostname"
echo "TODO (bug with Ubuntu 14.04): modifying hostname above might have failed. Log on the server and change it by hand (use root, sudo will not work)"

ssh -i $KEY_FILE ubuntu@$ip_address "sudo hostname -F /etc/hostname"
ssh -i $KEY_FILE ubuntu@$ip_address "sudo echo $ip_address $host_name >> /etc/hosts"

#Download chef server on your new instance and install/test it
ssh -i $KEY_FILE ubuntu@$ip_address 'wget https://opscode-omnitruck-release.s3.amazonaws.com/ubuntu/12.04/x86_64/chef-server_11.0.6-1.ubuntu.12.04_amd64.deb'
ssh -i $KEY_FILE ubuntu@$ip_address 'sudo dpkg -i chef-server_11.0.6-1.ubuntu.12.04_amd64.deb'
ssh -i $KEY_FILE ubuntu@$ip_address 'sudo chef-server-ctl reconfigure'
ssh -i $KEY_FILE ubuntu@$ip_address 'sudo chef-server-ctl test'

#copy the keys you need and change ownership so ubuntu can access them since
#you cannot directly SSH as root
ssh -i $KEY_FILE ubuntu@$ip_address 'sudo cp /etc/chef-server/admin.pem /home/ubuntu/'
ssh -i $KEY_FILE ubuntu@$ip_address 'sudo cp /etc/chef-server/chef-validator.pem /home/ubuntu/'
ssh -i $KEY_FILE ubuntu@$ip_address 'sudo chown ubuntu /home/ubuntu/admin.pem'
ssh -i $KEY_FILE ubuntu@$ip_address 'sudo chown ubuntu /home/ubuntu/chef-validator.pem'

scp -i $KEY_FILE ubuntu@$ip_address:/home/ubuntu/admin.pem .chef/
scp -i $KEY_FILE ubuntu@$ip_address:/home/ubuntu/chef-validator.pem .chef/

#clean up the temp copies of the keys
ssh -i $KEY_FILE ubuntu@$ip_address 'rm /home/ubuntu/admin.pem'
ssh -i $KEY_FILE ubuntu@$ip_address 'rm /home/ubuntu/chef-validator.pem'

#this will create a new knife.rb and "node_name".pem
touch .chef/knife.rb
echo "The password you enter cannot be empty and must be at least 6 characters long"
knife configure  -i -u $CHEF_USER -y -s "https://$ip_address" -k ".chef/$USER.pem"  --admin-client-key .chef/admin.pem --admin-client-name "admin" --validation-client-name chef-validator --validation-key .chef/chef-validator.pem --repository . -c .chef/knife.rb

echo -n "Configuring knife in .chef/knife.rb ... "
echo "knife[:aws_ssh_key_id] = \"$KEY_NAME\"" >> .chef/knife.rb
echo "knife[:identity_file] =\"$CHEF_PEM\"" >> .chef/knife.rb
echo "knife[:aws_access_key_id]=\"#{ENV['AWS_ACCESS_KEY_ID']}\"" >> .chef/knife.rb
echo "knife[:aws_secret_access_key]=\"#{ENV['AWS_SECRET_ACCESS_KEY']}\"" >> .chef/knife.rb
echo "knife[:availability_zone]=\"#{ENV['EC2_AVAILABILITY_ZONE']}\"" >> .chef/knife.rb
echo "knife[:region]=\"#{ENV['EC2_REGION']}\"" >> .chef/knife.rb
echo "OK"

echo "Uploading all existing cookbooks and roles:"
knife cookbook upload -a
for z in roles/*rb; do knife role from file $z;done

echo "You should now be able to bootstrap new nodes with 'knife ec2 server create' directly from the shell"
echo "Login to the chef server webUI at https://$ip_address using username admin and password p@ssw0rd1 and immediately change the password"
echo "You can also login using $CHEF_USER as your username and the password you entered earlier"

redpajama_set_name: RedPajamaGithub


text:
<?xml version="1.0" encoding="UTF-8"?>
<sponge xmlns="https://sponge.openksavi.org" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xsi:schemaLocation="https://sponge.openksavi.org https://sponge.openksavi.org/schema/config.xsd">
    <properties>
        <property name="sponge.home">.</property>
    </properties>

    <knowledgeBases>
        <knowledgeBase name="kb">
            <file>plugins_java.kts</file>
        </knowledgeBase>
    </knowledgeBases>

    <plugins>
        <plugin name="connectionPlugin" class="org.openksavi.sponge.examples.ConnectionPlugin">
            <configuration>
                <connection>
                    <name>Example connection</name>
                </connection>
            </configuration>
        </plugin>
        <plugin name="echoPlugin" class="org.openksavi.sponge.examples.EchoPlugin">
            <configuration>
                <echo>Echo test!</echo>
                <count>2</count>
            </configuration>
        </plugin>
    </plugins>
</sponge>


text:
import Action from "../../../src/model/js/Action.js";
import Agent from "../../../src/model/js/Agent.js";
import CombatDealShadowCardsTask from "../../../src/model/js/CombatDealShadowCardsTask.js";
import Game from "../../../src/model/js/Game.js";
import PlayerDeckBuilder from "../../../src/model/js/PlayerDeckBuilder.js";
import Reducer from "../../../src/model/js/Reducer.js";
import ScenarioDeckBuilder from "../../../src/model/js/ScenarioDeckBuilder.js";

QUnit.module("CombatDealShadowCardsTask");

QUnit.test("doIt()", function(assert)
{
   // Setup.
   var game = createGame();
   var environment = game.engine().environment();
   var store = environment.store();
   var agent1 = environment.agents()[0];
   var task = new CombatDealShadowCardsTask(store, agent1);
   var callback = function()
   {
      // Verify.
      assert.equal(store.getState().encounterDiscard.length, 0);
      assert.ok(Object.keys(store.getState().cardShadowCards).length >= 0);
   };

   // Run.
   task.doIt(callback);
});

function createGame()
{
   var store = Redux.createStore(Reducer.root);
   store.dispatch(Action.setDelay(10));
   var scenarioDeck = ScenarioDeckBuilder.PassageThroughMirkwoodDeckBuilder.buildDeck(store);
   var agent1 = new Agent(store, "agent1");
   var agent2 = new Agent(store, "agent2");
   var playerData = [
      {
         agent: agent1,
         playerDeck: PlayerDeckBuilder.CoreLeadershipDeckBuilder.buildDeck(store),
    },
      {
         agent: agent2,
         playerDeck: PlayerDeckBuilder.CoreLoreDeckBuilder.buildDeck(store),
    }, ];

   return new Game(store, scenarioDeck, playerData);
}

var CombatDealShadowCardsTaskTest = {};
export default CombatDealShadowCardsTaskTest;


text:
namespace am
{
// Row major 1x4
struct AM_ALIGN(16) Vector4
{
	enum ZeroType { Zero };
	enum OneType { One };
	enum UnitXType { UnitX };
	enum UnitYType { UnitY };
	enum UnitZType { UnitZ };
	enum UnitWType { UnitW };

	__forceinline Vector4();
	__forceinline Vector4(float value);
	__forceinline Vector4(float x, float y, float z, float w);
	__forceinline Vector4(const Vector4& v);
	__forceinline Vector4(ZeroType);
	__forceinline Vector4(OneType);
	__forceinline Vector4(UnitXType);
	__forceinline Vector4(UnitYType);
	__forceinline Vector4(UnitZType);
	__forceinline Vector4(UnitWType);

	#if defined AM_SSE
	__forceinline Vector4(__m128 m);
	#endif

	__forceinline Vector4 operator+(const Vector4& v) const;
	__forceinline Vector4 operator-(const Vector4& v) const;
	__forceinline Vector4 operator*(const Vector4& v) const;
	__forceinline Vector4 operator*(float value) const;
	__forceinline Vector4 operator/(float value) const;

	__forceinline Vector4& operator+=(const Vector4& v);
	__forceinline Vector4& operator-=(const Vector4& v);
	__forceinline Vector4& operator*=(const Vector4& v);
	__forceinline Vector4& operator*=(float value);
	__forceinline Vector4& operator/=(float value);

	__forceinline bool operator==(const Vector4& v) const;
	__forceinline bool operator!=(const Vector4& v) const;
	__forceinline float& operator[] (size_t i);
	__forceinline const float& operator[] (size_t i) const;

	union
	{
		struct { float x; float y; float z; float w; };
		struct { float r; float g; float b; float a; };
		float element[4];

		#if defined AM_SSE
		__m128 m128;
		#endif
	};
};

__forceinline std::ostream& operator<< (std::ostream& out, const Vector4& v);
__forceinline Vector4 operator*(float value, const Vector4& v);
__forceinline Vector4 lerp(const Vector4& start, const Vector4& end, float t);
__forceinline Vector4 normalize(const Vector4& v);
__forceinline float dot(const Vector4& lhs, const Vector4& rhs);
__forceinline float length(const Vector4& v);
__forceinline float lengthSq(const Vector4& v);
__forceinline float distance(const Vector4& lhs, const Vector4& rhs);
__forceinline float distanceSq(const Vector4& lhs, const Vector4& rhs);

}

#if defined AM_SSE
#include <Engine/Core/Math/SSE/Vector4.inl>
#else
#include <Engine/Core/Math/Std/Vector4.inl>
#endif


text:
<?php $this->displayReviewTitle($review); ?>

        <?php $this->displayReviewContent($review); ?>

<?php echo BOSS_BY; ?> <?php $this->displayReviewDate($review); ?>

        <?php $this->displayButDelete($content, $directory, $review); ?>


text:
"""Test the SENZ config flow."""
from unittest.mock import patch

from aiosenz import AUTHORIZATION_ENDPOINT, TOKEN_ENDPOINT

from homeassistant import config_entries
from homeassistant.components.application_credentials import (
    ClientCredential,
    async_import_client_credential,
)
from homeassistant.components.senz.const import DOMAIN
from homeassistant.core import HomeAssistant
from homeassistant.helpers import config_entry_oauth2_flow
from homeassistant.setup import async_setup_component

CLIENT_ID = "1234"
CLIENT_SECRET = "5678"

async def test_full_flow(
    hass: HomeAssistant,
    hass_client_no_auth,
    aioclient_mock,
    current_request_with_host,
) -> None:
    """Check full flow."""
    await async_setup_component(hass, DOMAIN, {})
    await hass.async_block_till_done()

    await async_import_client_credential(
        hass, DOMAIN, ClientCredential(CLIENT_ID, CLIENT_SECRET), "cred"
    )

    result = await hass.config_entries.flow.async_init(
        "senz", context={"source": config_entries.SOURCE_USER}
    )
    state = config_entry_oauth2_flow._encode_jwt(
        hass,
        {
            "flow_id": result["flow_id"],
            "redirect_uri": "https://example.com/auth/external/callback",
        },
    )

    assert result["url"] == (
        f"{AUTHORIZATION_ENDPOINT}?response_type=code&client_id={CLIENT_ID}"
        "&redirect_uri=https://example.com/auth/external/callback"
        f"&state={state}&scope=restapi+offline_access"
    )

    client = await hass_client_no_auth()
    resp = await client.get(f"/auth/external/callback?code=abcd&state={state}")
    assert resp.status == 200
    assert resp.headers["content-type"] == "text/html; charset=utf-8"

    aioclient_mock.post(
        TOKEN_ENDPOINT,
        json={
            "refresh_token": "mock-refresh-token",
            "access_token": "mock-access-token",
            "type": "Bearer",
            "expires_in": 60,
        },
    )

    with patch(
        "homeassistant.components.senz.async_setup_entry", return_value=True
    ) as mock_setup:
        await hass.config_entries.flow.async_configure(result["flow_id"])

    assert len(hass.config_entries.async_entries(DOMAIN)) == 1
    assert len(mock_setup.mock_calls) == 1


text:
#import <UIKit/UIKit.h>

@interface UIBarButtonItem (Item)
// 快速创建UIBarButtonItem
/**
 *  不带标题,高亮
 *
 *  @param image
 *  @param highImage
 *  @param target
 *  @param action
 *
 *  @return
 */
+ (UIBarButtonItem *)itemWithimage:(UIImage *)image highImage:(UIImage *)highImage target:(id)target action:(SEL)action;

/**
 *  带标题,高亮
 *
 *  @param image
 *  @param highImage
 *  @param target
 *  @param action
 *  @param title
 *
 *  @return
 */
+ (UIBarButtonItem *)backItemWithimage:(UIImage *)image highImage:(UIImage *)highImage target:(id)target action:(SEL)action title:(NSString *)title;

/**
 *  不带标题,选中
 *
 *  @param image
 *  @param selImage
 *  @param target
 *  @param action
 *
 *  @return
 */
+ (UIBarButtonItem *)itemWithimage:(UIImage *)image selImage:(UIImage *)selImage target:(id)target action:(SEL)action;

@end


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

    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_marginLeft="5dp"
        android:layout_marginRight="5dp"
        android:background="@color/white"
        android:orientation="vertical">

        <RelativeLayout
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:paddingBottom="20dp"
            android:paddingLeft="10dp"
            android:paddingRight="10dp"
            android:paddingTop="20dp">

            <ImageView
                android:id="@+id/iv_runningAppInfos_icon"
                android:layout_width="45dp"
                android:layout_height="45dp"
                android:layout_centerVertical="true"
                android:src="@drawable/app_logo" />

            <TextView
                android:id="@+id/tv_runningAppInfos_appName"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:layout_marginLeft="10dp"
                android:layout_toRightOf="@+id/iv_runningAppInfos_icon"
                android:maxLength="10"
                android:text="手机卫士"
                android:textColor="@color/black"
                android:textSize="20sp" />

            <TextView
                android:id="@+id/tv_runningAppInfos_PID"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:layout_alignBottom="@+id/iv_runningAppInfos_icon"
                android:layout_below="@id/tv_appInfos_appName"
                android:layout_marginLeft="10dp"
                android:layout_toRightOf="@id/iv_runningAppInfos_icon"
                android:gravity="bottom"
                android:maxLength="15"
                android:text="手机内存"
                android:textColor="@color/black"
                android:textSize="13sp" />

            <!-- 这里为CheckBox设置了选择器,需要注意的是:CheckBox用的需求属性是android:button=""-->
            <CheckBox
                android:id="@+id/iv_runningAppInfos_selector"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:layout_alignParentRight="true"
                android:layout_centerVertical="true"
                android:button="@drawable/btn_check"
                android:clickable="false"
                android:focusable="false"
                android:focusableInTouchMode="false" />

            <TextView
                android:id="@+id/tv_runningAppInfos_memoSize"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:layout_alignBottom="@+id/iv_runningAppInfos_icon"
                android:layout_below="@id/tv_appInfos_appName"
                android:layout_marginRight="15sp"
                android:layout_toLeftOf="@id/iv_runningAppInfos_selector"
                android:gravity="bottom"
                android:maxLength="15"
                android:text="28.0K"
                android:textColor="@color/black"
                android:textSize="13sp" />

        </RelativeLayout>

    </LinearLayout>
</LinearLayout>


text:
<?xml version="1.0" encoding="ascii"?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
          "DTD/xhtml1-transitional.dtd">

  <title>eicpy.elf</title>
  <link rel="stylesheet" href="epydoc.css" type="text/css" />

         Trees

         Indices

         Help

EIC Site-packages

        Package eicpy ::
        Module elf

[hide private]

[frames] | no frames]

Module elf

source code

Base classes for eLink currently only used for endorsements
  (endorsement/edriver.py, etc.)

        Classes
        [hide private]

        Vehicle

      A vehicle class intended to be extended

        Driver

      A driver class intended to be extended

        Policy

      A policy class intended to be extended

        Functions
        [hide private]

          conv2out(state,
        value)

      Converts from legacy values to eLink values.

            source code

        Variables
        [hide private]

        __package__ = 'eicpy'

        Function Details
        [hide private]

conv2out(state,
        value)

  	source code

Converts from legacy values to eLink values. Usually this is for 1
  char values --> 2 char values. Ex. Towing '5' -> '50'

Parameters:

value - characters to be converted

         Trees

         Indices

         Help

EIC Site-packages

    Generated by Epydoc
    3.0.1 on Mon Oct  8 11:15:35 2012

      http://epydoc.sourceforge.net


text:
int lsb_open(struct stegger **stegger, struct sampler *sampler, int bits);

#endif


text:
using System;
using System.Collections;
using System.Text;
using System.Xml;
using System.Xml.Serialization;

namespace ScanMaster.Acquire.Plugin
{
	/// <summary>
	/// This class holds the settings for a plugin. It knows how (with some difficulty, using
	/// an undocumented interface in the .NET framework) to serialize itself as xml.
	///
	/// The class is mainly a wrapper to a hashtable. The exception is that it knows to check
	/// the default settings store for a value that overrides the current setting.
	/// </summary>
	[Serializable]
	public class PluginSettings : IXmlSerializable
	{
		private Hashtable settings = new Hashtable();

		public PluginSettings()
		{
		}

		public void Add(String key, object value)
		{
			settings.Add(key, value);
		}

		public object this[String key]
		{
			get
			{
				ParameterHelper ph = Controller.GetController().ParameterHelper;
				if (ph.HasParameter(key))
				{
					object val = ph.GetParameter(key);
					return Convert.ChangeType(val, settings[key].GetType());
				}
				else return settings[key];
			}
			set
			{
				settings.Remove(key);
				settings[key] = value;
			}
		}

		[XmlIgnore]
		public ICollection Keys
		{
			get
			{
				return settings.Keys;
			}
		}

		//public override string ToString()
		//{
		//	StringBuilder sb = new StringBuilder();
		//	ICollection keys = settings.Keys;
		//	foreach (String key in keys)
		//		sb.Append(settings[key].GetType().ToString() + " " + key +
		//					" = " + settings[key] + Environment.NewLine);
		//	return sb.ToString();
		//}

		///// Now sorting the settings alphabetically
		public override string ToString()
		{
			StringBuilder sb = new StringBuilder();
			ICollection keys = settings.Keys;
			ArrayList OrderedKeys = new ArrayList();

			foreach (String key in keys)
				OrderedKeys.Add(key);

			OrderedKeys.Sort();

			foreach (String key in OrderedKeys)
				sb.Append(settings[key].GetType().ToString() + " " + key +
							" = " + settings[key] + Environment.NewLine);
			return sb.ToString();
		}

            #region IXmlSerializable Members

            const string NS = "";//"http://j-star.org/xml/serialization";

		public void WriteXml(XmlWriter w)
		{
			w.WriteStartElement("dictionary", NS);
			foreach (object key in settings.Keys)
			{
				object value = settings[key];
				w.WriteStartElement("item", NS);
				w.WriteElementString("key", NS, key.ToString());
				w.WriteElementString("value", NS, value.ToString());
				w.WriteElementString("type", NS, value.GetType().ToString());
				w.WriteEndElement();
			}
			w.WriteEndElement();
		}

		public System.Xml.Schema.XmlSchema GetSchema()
		{
			return null;
		}

		public void ReadXml(XmlReader r)
		{
			r.Read(); // move past container
			r.ReadStartElement("dictionary");
			while (r.NodeType != XmlNodeType.EndElement)
			{
				r.ReadStartElement("item", NS);
				string key = r.ReadElementString("key", NS);
				string value = r.ReadElementString("value", NS);
				string type = r.ReadElementString("type", NS);
				r.ReadEndElement();
				object convertedValue = null;
				try
				{
					convertedValue = Convert.ChangeType(value, Type.GetType(type));
				}
				catch (FormatException e)
				{
					Console.Error.Write("Format error in xml dictionary deserializer");
					Console.Error.Write(e.Message + e.StackTrace);
				}

				settings.Add(key, convertedValue);
			}
			r.ReadEndElement();
			r.ReadEndElement();
		}

		#endregion
	}

}


text:
package org.eclipse.cloudplatform.service.device.api;

import java.util.Map;

public class LinkObject {

    private String url;

    private Map<String, Object> attributes;

    private Integer objectId;

    private Integer objectInstanceId;

    private Integer resourceId;

    public LinkObject(String url, Map<String, Object> attributes, Integer objectId, Integer objectInstanceId, Integer resourceId) {
        this.url = url;
        this.attributes = attributes;
        this.objectId = objectId;
        this.objectInstanceId = objectInstanceId;
        this.resourceId = resourceId;
    }

    public LinkObject() {
    }

    public String getUrl() {
        return url;
    }

    public void setUrl(String url) {
        this.url = url;
    }

    public Map<String, Object> getAttributes() {
        return attributes;
    }

    public void setAttributes(Map<String, Object> attributes) {
        this.attributes = attributes;
    }

    public Integer getObjectId() {
        return objectId;
    }

    public void setObjectId(Integer objectId) {
        this.objectId = objectId;
    }

    public Integer getObjectInstanceId() {
        return objectInstanceId;
    }

    public void setObjectInstanceId(Integer objectInstanceId) {
        this.objectInstanceId = objectInstanceId;
    }

    public Integer getResourceId() {
        return resourceId;
    }

    public void setResourceId(Integer resourceId) {
        this.resourceId = resourceId;
    }

}


text:
class HAlign
{
	public static CENTER = "center";
	public static LEFT = "left";
	public static RIGHT = "right";
}

export = HAlign;


text:
package com.alibaba.dubbo.demo.consumer;

public class DemoConsumer {

    public static void main(String[] args) {
        com.alibaba.dubbo.container.Main.main(args);
//        com.alibaba.dubbo.container.Http.main(args);
    }

}


text:
<!DOCTYPE html>

	<title>Rent A Car !!!</title>
	<link rel="stylesheet" href="views/css/bootstrap.min.css">
	<link rel="stylesheet" href="views/css/rentacar.global.css">

            <button type="button" class="navbar-toggle" data-toggle="collapse" data-target="#topNavBar">
                Toggle navigation

            </button>
            Rent A car

Home

Find A Car

Dealers

login

                    Pages

logout

about us

Privacy Policy

Terms of Use

Blog

Contact


text:
layout: sieutv
title: lang_son
tags: ["VN-local"]
thumb: lang_son
---
{% include tvadv key="lang_son" %}


text:
package lista;

import java.util.Arrays;

/*
 * Escreva um programa que gere um array de n.ºs inteiros (entre 0 e 100)
 * e ordene este array por ordem crescente.
 */
public class Ordenacao {

	public static void main(String[] args) {
		int[] array = {10, 32, 21, 100, 34, 42, 12, 54, 99, 23};

		Arrays.sort(array);

		for(int numero : array) {
			System.out.println(numero);
		}

	}

}


text:
package org.apache.hadoop.hbase;

import java.io.IOException;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.apache.hadoop.conf.Configuration;
import org.apache.hadoop.hbase.client.TestMetaWithReplicas;
import org.apache.hadoop.hbase.protobuf.ProtobufUtil;
import org.apache.hadoop.hbase.regionserver.StorefileRefresherChore;
import org.apache.hadoop.hbase.testclassification.IntegrationTests;
import org.apache.hadoop.hbase.zookeeper.ZKUtil;
import org.apache.hadoop.hbase.zookeeper.ZooKeeperWatcher;
import org.junit.AfterClass;
import org.junit.BeforeClass;
import org.junit.Test;
import org.junit.experimental.categories.Category;

/**
 * An integration test that starts the cluster with three replicas for the meta
 * It then creates a table, flushes the meta, kills the server holding the primary.
 * After that a client issues put/get requests on the created table - the other
 * replicas of the meta would be used to get the location of the region of the created
 * table.
 */
@Category(IntegrationTests.class)
public class IntegrationTestMetaReplicas {
  private static final Log LOG = LogFactory.getLog(IntegrationTestMetaReplicas.class);
  /**
   * Util to get at the cluster.
   */
  private static IntegrationTestingUtility util;

  @BeforeClass
  public static void setUp() throws Exception {
    // Set up the integration test util
    if (util == null) {
      util = new IntegrationTestingUtility();
    }
    util.getConfiguration().setInt(HConstants.META_REPLICAS_NUM, 3);
    util.getConfiguration().setInt(
        StorefileRefresherChore.REGIONSERVER_STOREFILE_REFRESH_PERIOD, 1000);
    // Make sure there are three servers.
    util.initializeCluster(3);
    ZooKeeperWatcher zkw = util.getZooKeeperWatcher();
    Configuration conf = util.getConfiguration();
    String baseZNode = conf.get(HConstants.ZOOKEEPER_ZNODE_PARENT,
        HConstants.DEFAULT_ZOOKEEPER_ZNODE_PARENT);
    String primaryMetaZnode = ZKUtil.joinZNode(baseZNode,
        conf.get("zookeeper.znode.metaserver", "meta-region-server"));
    // check that the data in the znode is parseable (this would also mean the znode exists)
    byte[] data = ZKUtil.getData(zkw, primaryMetaZnode);
    ProtobufUtil.toServerName(data);
    waitUntilZnodeAvailable(1);
    waitUntilZnodeAvailable(2);
  }

  @AfterClass
  public static void teardown() throws Exception {
    //Clean everything up.
    util.restoreCluster();
    util = null;
  }

  private static void waitUntilZnodeAvailable(int replicaId) throws Exception {
    String znode = util.getZooKeeperWatcher().znodePaths.getZNodeForReplica(replicaId);
    int i = 0;
    while (i < 1000) {
      if (ZKUtil.checkExists(util.getZooKeeperWatcher(), znode) == -1) {
        Thread.sleep(100);
        i++;
      } else break;
    }
    if (i == 1000) throw new IOException("znode for meta replica " + replicaId + " not available");
  }

  @Test
  public void testShutdownHandling() throws Exception {
    // This test creates a table, flushes the meta (with 3 replicas), kills the
    // server holding the primary meta replica. Then it does a put/get into/from
    // the test table. The put/get operations would use the replicas to locate the
    // location of the test table's region
    TestMetaWithReplicas.shutdownMetaAndDoValidations(util);
  }

  public static void main(String[] args) throws Exception {
    setUp();
    new IntegrationTestMetaReplicas().testShutdownHandling();
    teardown();
  }
}


text:
package com.hp.hpl.jena.db.impl;

import com.hp.hpl.jena.db.*;

/**
 *  Implementation of Reifier for graphs stored in a database.
 *
 * @author csayers based in part on SimpleReifier by kers.
*/

import java.util.List;

import com.hp.hpl.jena.graph.*;
import com.hp.hpl.jena.util.iterator.*;
import com.hp.hpl.jena.shared.*;

public class DBReifier implements Reifier
    {
    protected GraphRDB m_parent = null;
    protected Graph m_hiddenTriples = null;
	protected List<SpecializedGraphReifier> m_reifiers = null;
	protected List<SpecializedGraphReifier> m_hidden_reifiers = null;

	// For now, we just deal with a single specializedGraphReifier,
	// but in the future we could replace this with a list of
	// those and operate much as the GraphRDB implementation
	// does with it's list of SpecializedGraphs.
	protected SpecializedGraphReifier m_reifier = null;

    protected ReificationStyle m_style;

	/**
	 *  Construct a reifier for GraphRDB's.
	 *
	 *  @param parent the Graph for which we will expose reified triples.
	 *  @param allReifiers a List of SpecializedGraphReifiers which reifiy triples in that graph.
	 *  @param hiddenReifiers the subset of allReifiers whose triples are hidden when querying the parent graph.
	 */
	public DBReifier(GraphRDB parent, ReificationStyle style,
	                 List<SpecializedGraphReifier> allReifiers,
	                 List<SpecializedGraphReifier> hiddenReifiers ) {
		m_parent = parent;
		m_reifiers = allReifiers;
		m_hidden_reifiers = hiddenReifiers;
        m_style = style;

		// For now, just take the first specializedGraphReifier
		if (m_reifiers.size() != 1)
			throw new BrokenException("Internal error - DBReifier requires exactly one SpecializedGraphReifier");
		m_reifier = m_reifiers.get(0);
	}

    /* (non-Javadoc)
	 * @see com.hp.hpl.jena.graph.Reifier#getParentGraph()
	 */
	public Graph getParentGraph() {
    	return m_parent; }

    public ReificationStyle getStyle()
        { return m_style; }

	/* (non-Javadoc)
	 * @see com.hp.hpl.jena.graph.Reifier#getHiddenTriples()
	 */
	private Graph getReificationTriples() {
		if( m_hiddenTriples == null)
            m_hiddenTriples = new DBReifierGraph(m_parent, m_hidden_reifiers);
		return m_hiddenTriples;
	}

    public ExtendedIterator<Triple> find( TripleMatch m )
        { return getReificationTriples().find( m ); }

    public ExtendedIterator<Triple> findExposed( TripleMatch m )
        { return getReificationTriples().find( m ); }

    public ExtendedIterator<Triple> findEither( TripleMatch m, boolean showHidden )
        { return showHidden == m_style.conceals() ? getReificationTriples().find( m ) : Triple.None; }

    public int size()
        { return m_style.conceals() ? 0 : getReificationTriples().size(); }

    /**
        Utility method useful for its short name: answer a new CompletionFlag
        initialised to false.
    */
    protected static SpecializedGraph.CompletionFlag newComplete()
        { return new SpecializedGraph.CompletionFlag(); }

	/* (non-Javadoc)
	 * @see com.hp.hpl.jena.graph.Reifier#reifyAs(com.hp.hpl.jena.graph.Node, com.hp.hpl.jena.graph.Triple)
	 */
	public Node reifyAs( Node n, Triple t ) {
		m_reifier.add( n, t, newComplete() );
		return n;
	}

	/* (non-Javadoc)
	 * @see com.hp.hpl.jena.graph.Reifier#hasTriple(com.hp.hpl.jena.graph.Node)
	 */
	public boolean hasTriple(Node n) {
		return m_reifier.findReifiedTriple( n, newComplete() ) != null;
	}

	/* (non-Javadoc)
	 * @see com.hp.hpl.jena.graph.Reifier#hasTriple(com.hp.hpl.jena.graph.Triple)
	 */
	public boolean hasTriple( Triple t ) {
		return m_reifier.findReifiedNodes(t, newComplete() ).hasNext();
	}

	/* (non-Javadoc)
	 * @see com.hp.hpl.jena.graph.Reifier#allNodes()
	 */
	public ExtendedIterator<Node> allNodes() {
		return m_reifier.findReifiedNodes( null, newComplete() );
	}

    /**
        All the nodes reifying triple t, using the matching code
        from SimpleReifier.
    */
    public ExtendedIterator<Node> allNodes( Triple t )
        { return m_reifier.findReifiedNodes( t, newComplete() ); }

	/* (non-Javadoc)
	 * @see com.hp.hpl.jena.graph.Reifier#remove(com.hp.hpl.jena.graph.Node, com.hp.hpl.jena.graph.Triple)
	 */
	public void remove( Node n, Triple t ) {
		m_reifier.delete( n, t, newComplete() );
	}

	/* (non-Javadoc)
	 * @see com.hp.hpl.jena.graph.Reifier#remove(com.hp.hpl.jena.graph.Triple)
	 */
	public void remove( Triple t ) {
		m_reifier.delete(null,t, newComplete() );
	}

	/* (non-Javadoc)
	 * @see com.hp.hpl.jena.graph.Reifier#handledAdd(com.hp.hpl.jena.graph.Triple)
	 */
	public boolean handledAdd(Triple t) {
		SpecializedGraph.CompletionFlag complete = newComplete();
		m_reifier.add(t, complete);
		return complete.isDone();
	}

	/* (non-Javadoc)
	 * @see com.hp.hpl.jena.graph.Reifier#handledRemove(com.hp.hpl.jena.graph.Triple)
	 */
	public boolean handledRemove(Triple t) {
		SpecializedGraph.CompletionFlag complete = newComplete();
		m_reifier.delete(t, complete);
		return complete.isDone();
	}

	/* (non-Javadoc)
	 * @see com.hp.hpl.jena.graph.GetTriple#getTriple(com.hp.hpl.jena.graph.Node)
	 */
	public Triple getTriple(Node n) {
		return m_reifier.findReifiedTriple(n, newComplete() );
	}

    public void close() {
        // TODO anything useful for a close operation
    }

}

/*
    (c) Copyright 2002, 2003, 2004, 2005, 2006, 2007, 2008, 2009 Hewlett-Packard Development Company, LP
    All rights reserved.

    Redistribution and use in source and binary forms, with or without
    modification, are permitted provided that the following conditions
    are met:

    1. Redistributions of source code must retain the above copyright
       notice, this list of conditions and the following disclaimer.

    2. Redistributions in binary form must reproduce the above copyright
       notice, this list of conditions and the following disclaimer in the
       documentation and/or other materials provided with the distribution.

    3. The name of the author may not be used to endorse or promote products
       derived from this software without specific prior written permission.

    THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR
    IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
    OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
    IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT,
    INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
    NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
    DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
    THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
    (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
    THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/


text:
package org.shepherd.recall.glass.settings;

import java.util.List;

import org.shepherd.recall.glass.App;

import android.app.Activity;
import android.content.Context;
import android.content.SharedPreferences;
import android.media.AudioManager;
import android.os.Bundle;
import android.preference.PreferenceManager;
import android.speech.tts.TextToSpeech;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;

import com.google.android.glass.media.Sounds;
import com.google.android.glass.widget.CardScrollView;
import org.shepherd.recall.glass.settings.adapter.CardPreferenceAdapter;
import org.shepherd.recall.glass.settings.option.PreferenceOption;
import org.shepherd.recall.glass.settings.types.AbstractPreference;
import org.shepherd.recall.glass.settings.types.ChooserPreference;
import org.shepherd.recall.glass.settings.types.TogglePreference;
import org.shepherd.recall.glass.settings.types.ActivityPreference;

public class GlassPreferenceActivity extends Activity implements OnItemClickListener {

	private CardScrollView mScrollView;
	private CardPreferenceAdapter mAdapter;

	private SharedPreferences mPrefs;

	// These are used for Preferences like ChooserPreference
	// that return false for onSelected() and make
	// the OptionsMenu open with options
	private List<PreferenceOption> mCurrentOptions;
	private AbstractPreference mCurrentPreference;
	private int mCurrentPreferenceIndex;

    private TextToSpeech mSpeech;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);

		mPrefs = PreferenceManager.getDefaultSharedPreferences(this);

		mScrollView = new CardScrollView(this);
		mAdapter = new CardPreferenceAdapter(this);

		mScrollView.setOnItemClickListener(this);
        mSpeech = new TextToSpeech(this, new TextToSpeech.OnInitListener() {
            @Override
            public void onInit(int status) {
                // Do nothing.

            }
        });
	}

    @Override
    protected void onDestroy()
    {
        mSpeech.shutdown();
        mSpeech = null;
        super.onDestroy();
    }

    protected void buildAndShowOptions() {
		mAdapter.buildCards();
		mScrollView.setAdapter(mAdapter);
		mScrollView.activate();
		setContentView(mScrollView);
	}

	@Override
	public boolean onCreateOptionsMenu(Menu menu) {
		for (int i = 0; i < mCurrentOptions.size(); i++) {
			menu.add(Menu.NONE, i, i, mCurrentOptions.get(i).getTitle());
		}

		return super.onCreateOptionsMenu(menu);
	}

	@Override
	public boolean onOptionsItemSelected(MenuItem item) {
		mCurrentPreference.onOptionSelected(item.getItemId());

        String key= mCurrentPreference.getKey();
        String value = mCurrentPreference.getValue();
        ((App) this.getApplication()).trackView("settings/" + key + "/" + value);
		// Update the View for this AbstractPreference
		// in case the View changed
		mAdapter.buildCard(mCurrentPreferenceIndex);
		mAdapter.notifyDataSetChanged();

		return true;
	}

	@Override
	public void onItemClick(AdapterView<?> view, View clicked, int index, long id) {
		AbstractPreference preference = (AbstractPreference) mAdapter.getItem(index);
		if (preference.onSelect()) {
			// True: the AbstractPreference handled everything

			if(preference.playSuccessSoundOnSelect()){
				playSuccessSound();
			}else{
				playClickSound();
			}

            String key= preference.getKey();
            String value = preference.getValue();
            ((App) this.getApplication()).trackView("settings/" + key + "/" + value);
			// Update the View for this AbstractPreference
			// in case the View changed
			mAdapter.buildCard(index);
			mAdapter.notifyDataSetChanged();
		} else {
			// False: show the AbstractPreference's options as a Menu

			playClickSound();

			if (preference instanceof ChooserPreference) {
                // speak
                if (preference.getSpeech() != null )
                {
                    mSpeech.speak(preference.getSpeech(), TextToSpeech.QUEUE_ADD, null);
                }

				mCurrentOptions = ((ChooserPreference) preference).getOptions();
				mCurrentPreference = preference;
				mCurrentPreferenceIndex = index;

				invalidateOptionsMenu();
				openOptionsMenu();
			}
		}
	}

	/**
	 * Add a Preference that can be on or off
	 */
	protected void addTogglePreference(String key, String title) {
		mAdapter.addPreference(new TogglePreference(mPrefs, key, title));
	}

	/**
	 * Add a Preference that can be on or off
	 */
	protected void addTogglePreference(String key, String title, boolean defaultValue) {
		mAdapter.addPreference(new TogglePreference(mPrefs, key, title, defaultValue));
	}

	/**
	 * Add a Preference that gives a list of options. The index of the chosen option is saved.
	 */
	protected void addChoicePreference(String key, String title, String speech, List<PreferenceOption> options) {
		mAdapter.addPreference(new ChooserPreference(mPrefs, key, title, speech, options));
	}

	/**
	 * Add a Preference that gives a list of options. The index of the chosen option is saved.
	 */
	protected void addChoicePreference(String key, String title, List<PreferenceOption> options, int defaultValueIndex) {
		mAdapter.addPreference(new ChooserPreference(mPrefs, key, title, options, defaultValueIndex));
	}

	/**
	 * Add a Preference that launches a specified Activity, passing in the preference key as an extra.
	 * For ease of use, extend AbstractPreferenceActivity for the Activity to launch
	 */
	protected void addActivityPreference(String key, String title, Class<?> activityClass){
		mAdapter.addPreference(new ActivityPreference(this, mPrefs, key, title, activityClass));
	}

	/**
	 * Add a Preference that launches a specified Activity, passing in the preference key as an extra.
	 * For ease of use, extend AbstractPreferenceActivity for the Activity to launch
	 */
	protected void addActivityPreference(String key, String title, int imageResource, Class<?> activityClass){
		mAdapter.addPreference(new ActivityPreference(this, mPrefs, key, title, imageResource, activityClass));
	}

	/**
	 * Add a generic Preference
	 */
	protected void addPreference(AbstractPreference preference) {
		mAdapter.addPreference(preference);
	}

	/**
	 * Play the standard Glass success sound
	 */
	protected void playSuccessSound() {
		AudioManager audio = (AudioManager) getSystemService(Context.AUDIO_SERVICE);
		audio.playSoundEffect(Sounds.SUCCESS);
	}

	/**
	 * Play the standard Glass tap sound
	 */
	protected void playClickSound() {
		AudioManager audio = (AudioManager) getSystemService(Context.AUDIO_SERVICE);
		audio.playSoundEffect(Sounds.TAP);
	}

}


text:
package com.sculture;

import com.google.gson.Gson;
import com.mashape.unirest.http.HttpResponse;
import com.mashape.unirest.http.JsonNode;
import com.mashape.unirest.http.Unirest;
import com.mashape.unirest.http.exceptions.UnirestException;
import com.sculture.model.response.StoriesResponse;
import com.sculture.util.MyGson;
import org.json.JSONObject;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

@WebServlet(name = "search")
public class Search extends HttpServlet {

    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        request.setAttribute("isLoggedIn", false);
        request.setAttribute("username", "");
        if (request.getSession().getAttribute("username") != null) {
            request.setAttribute("username", request.getSession().getAttribute("username"));
            request.setAttribute("isLoggedIn", true);
        }
        String requestURL = request.getRequestURL().toString();
        String query = requestURL.substring(requestURL.lastIndexOf('/') + 1);
        JSONObject jsonObject = new JSONObject();
        jsonObject.put("query", query);
        jsonObject.put("size", 20);
        HttpResponse<JsonNode> searchJsonResponse = null;
        try {
            searchJsonResponse = Unirest.post(Const.REST_BASE_URL + Const.Api.SEARCH)
                    .header("Content-Type", "application/json")
                    .body(new JsonNode(jsonObject.toString()))
                    .asJson();
        } catch (UnirestException e) {
            e.printStackTrace();
        }

        if (searchJsonResponse != null && !searchJsonResponse.getBody().getObject().has("error")) {
            Gson gson = MyGson.create();
            StoriesResponse storiesResponse = gson.fromJson(searchJsonResponse.getBody().toString(), StoriesResponse.class);
            request.setAttribute("results", storiesResponse);
            request.getRequestDispatcher("/search_result.jsp").forward(request, response);
        } else {
            request.setAttribute("errormsg", "Something went wrong editing your story, please try again.");
            request.getRequestDispatcher("/error.jsp").forward(request, response);
        }
    }

    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        request.setAttribute("isLoggedIn", false);
        request.setAttribute("username", "");
        if (request.getSession().getAttribute("username") != null) {
            request.setAttribute("username", request.getSession().getAttribute("username"));
            request.setAttribute("isLoggedIn", true);
        }

        JSONObject jsonObject = new JSONObject();
        jsonObject.put("query", request.getParameter("main-search"));

        HttpResponse<JsonNode> searchJsonResponse = null;
        try {
            searchJsonResponse = Unirest.post(Const.REST_BASE_URL + Const.Api.SEARCH)
                    .header("Content-Type", "application/json")
                    .body(new JsonNode(jsonObject.toString()))
                    .asJson();
        } catch (UnirestException e) {
            e.printStackTrace();
        }

        if (searchJsonResponse != null && !searchJsonResponse.getBody().getObject().has("exception")) {
            Gson gson = MyGson.create();
            StoriesResponse storiesResponse = gson.fromJson(searchJsonResponse.getBody().toString(), StoriesResponse.class);
            request.setAttribute("results", storiesResponse);
            request.getRequestDispatcher("/search_result.jsp").forward(request, response);
        } else {
            request.setAttribute("errormsg", "Something went wrong getting the results of your query, please try again.");
            request.getRequestDispatcher("/error.jsp").forward(request, response);
        }
    }

}


text:
import ParticleEditorFacade from './ParticleEditorFacade'
import { Facade } from 'pure-mvc'

export default class ParticleEditor {
  constructor () {
    Facade.getInstance = ParticleEditorFacade.getInstance
    this.facade = Facade.getInstance(ParticleEditorFacade.KEY)
  }

  init () {
    this.facade.startup()
  }
}

window.particleEditor = new ParticleEditor()
window.particleEditor.init()


text:
from redis_wrap import (
        get_redis,
        get_list,
        get_hash,
        get_set,
        setup_redis,
        get_key,
        set_key,
        get_queue,
        get_dict,
        ConnectionError,
        ResponseError
        )

from task import (
        task_registry,
        register,
        push_task,
        has_task,
        pop_task,
        pop_error,
        push_runtime_error,
        gen_task,
        push_runtime_task
        )

from model import *

from cron import add_cron, has_cron, remove_cron, start_cron

from async import async, enable_transaction, ping_task, prepare_task


text:
#include "Analytics.h"

#include "json/writer.h"
#include "cocos2d.h"
#include "network/HttpClient.h"

USING_NS_UBA;
USING_NS_CC;

using namespace cocos2d::network;

const int SEND_REQUEST_INTERVAL = 0;
const std::string ANALYTICS_CACHE_PATH = "analytics.json";
const std::string SERVER_URL = "http://150.216.56.172:80/api/Activities";
//const std::string SERVER_URL = "http://255.216.56.172:80/api/Activities";

Analytics& Analytics::getInstance()
{
	static Analytics instance;
	return instance;
}

::Analytics::Analytics()
	:_timer(SEND_REQUEST_INTERVAL)
	, _sendingRequest(false)
{

}

void uba::Analytics::loadCacheFromStorage()
{
	_queue.empty();

	Director::getInstance()->getScheduler()->schedule(CC_CALLBACK_1(Analytics::oneSecondUpdate, this), this, 0.01, CC_REPEAT_FOREVER, 0, false, "analytics_cache_one_sec_update");

	std::string fullPath = FileUtils::getInstance()->getWritablePath().append(ANALYTICS_CACHE_PATH.c_str());
	try
	{
		if (!FileUtils::getInstance()->isFileExist(fullPath))
		{
			return;
		}

		unsigned char* pBuffer = NULL;
		ssize_t bufferSize = 0;
		pBuffer = FileUtils::getInstance()->getFileData(fullPath.c_str(), "r", &bufferSize);
		std::string jsonStr(pBuffer, pBuffer + bufferSize);

		rapidjson::Document d;
		d.Parse<0>(jsonStr.c_str());

		if (d.HasParseError())
		{
			throw;
		}

		if (d.GetType() == rapidjson::kArrayType)
		{
			for (unsigned int i = 0; i < d.Size(); i++)
			{
				auto& analyticsJson = d[i];

				if (analyticsJson.GetType() == rapidjson::kObjectType)
				{
					auto analytics = createAnalyticsData(analyticsJson);
					addAnalyticsData(std::move(analytics), false);
				}
			}
		}

	}
	catch (...)
	{
		FileUtils::getInstance()->removeFile(fullPath);
	}

}

void uba::Analytics::addAnalyticsData(AnalyticsData analyticsData, bool cache /*= true*/)
{
	try
	{
		auto data = std::unique_ptr<AnalyticsData>(new AnalyticsData(analyticsData));
		if (data)
		{
			data->id = _queue.size();
			addAnalyticsData(std::move(data), cache);
		}
	}
	catch (...)
	{

	}
}

void uba::Analytics::addAnalyticsData(std::unique_ptr<AnalyticsData> data, bool cache /*= true*/)
{
	if (cache)
	{
		//cacheAnalyticsData(data.get());
	}

	_queue.push(std::move(data));
}

void Analytics::oneSecondUpdate(float dt)
{
	if (_timer < SEND_REQUEST_INTERVAL)
	{
		_timer += dt;
	}

	if (_timer >= SEND_REQUEST_INTERVAL && _queue.size() > 0 && !_sendingRequest)
	{
		_timer = 0;
        auto obj = _queue.front().get();
        if (obj) {
            sendRequest(_queue.front().get());
        }
        else
        {
            _queue.pop();
        }

	}
}

void uba::Analytics::sendRequest(AnalyticsData* analyticsData)
{
	_sendingRequest = true;

	rapidjson::Document doc;
	auto dataObject = getAnalyticsDataJson(analyticsData, doc);

	rapidjson::GenericStringBuffer<rapidjson::UTF8<>> buffer;
	rapidjson::Writer<rapidjson::GenericStringBuffer<rapidjson::UTF8<>>> writer(buffer);
	dataObject.Accept(writer);

	auto serialized = buffer.GetString();

	HttpRequest* request = new (std::nothrow) HttpRequest();
	request->setUrl(SERVER_URL);
	request->setRequestType(HttpRequest::Type::POST);
	request->setResponseCallback(CC_CALLBACK_2(Analytics::onHttpRequestCompleted, this));

	std::vector<std::string> headers;
	auto contentTypeHeader = "Content-Type: application/json";
	headers.push_back(contentTypeHeader);
	request->setHeaders(headers);

	request->setRequestData(serialized, strlen(serialized));
	request->setUserData(analyticsData);
	HttpClient::getInstance()->sendImmediate(request);
	request->release();

}

void uba::Analytics::cacheAnalyticsData(AnalyticsData* analyticsData)
{
	std::string fullPath = FileUtils::getInstance()->getWritablePath().append(ANALYTICS_CACHE_PATH.c_str());
	try
	{
		rapidjson::Document doc;
		if (FileUtils::getInstance()->isFileExist(fullPath))
		{
			unsigned char* pBuffer = NULL;
			ssize_t bufferSize = 0;
			pBuffer = FileUtils::getInstance()->getFileData(fullPath.c_str(), "r", &bufferSize);
			std::string jsonStr(pBuffer, pBuffer + bufferSize);

			doc.Parse<0>(jsonStr.c_str());

			if (doc.HasParseError())
			{
				throw;
			}
		}
		else
		{
			doc.SetArray();
		}

		if (doc.GetType() == rapidjson::kArrayType)
		{

			auto dataObject = getAnalyticsDataJson(analyticsData, doc);

			doc.PushBack(dataObject, doc.GetAllocator());

			rapidjson::GenericStringBuffer<rapidjson::UTF8<>> buffer;
			rapidjson::Writer<rapidjson::GenericStringBuffer<rapidjson::UTF8<>>> writer(buffer);
			doc.Accept(writer);

			auto serialized = buffer.GetString();
			FileUtils::getInstance()->writeStringToFile(serialized, fullPath);
		}

	}
	catch (...)
	{
		FileUtils::getInstance()->isFileExist(fullPath);
	}
}

void uba::Analytics::onHttpRequestCompleted(cocos2d::network::HttpClient* sender, cocos2d::network::HttpResponse* response)
{
	try
	{
		_sendingRequest = false;

		if (!response)
		{
			return;
		}

		if (response->isSucceed())
		{
			auto analyticsData = static_cast<AnalyticsData*>(response->getHttpRequest()->getUserData());
			auto id = analyticsData->id;

            if(_queue.size() != 0)
                _queue.pop();

			auto responseData = response->getResponseData();
			auto responseString = std::string(responseData->begin(), responseData->end());

			std::string fullPath = FileUtils::getInstance()->getWritablePath().append(ANALYTICS_CACHE_PATH.c_str());
			if (FileUtils::getInstance()->isFileExist(fullPath))
			{
				rapidjson::Document doc;
				unsigned char* pBuffer = NULL;
				ssize_t bufferSize = 0;
				pBuffer = FileUtils::getInstance()->getFileData(fullPath.c_str(), "r", &bufferSize);
				std::string jsonStr(pBuffer, pBuffer + bufferSize);

				doc.Parse<0>(jsonStr.c_str());

				if (doc.HasParseError())
				{
					throw;
				}

				auto it = doc.Begin();

				while (it != doc.End())
				{
					auto& obj = *it;

					auto jsonId = obj["id"].GetInt();

					if (jsonId == id)
					{
						it = doc.Erase(it);
					}
					else
					{
						++it;
					}
				}

				if (doc.Size() == 0)
				{
					FileUtils::getInstance()->removeFile(fullPath);
				}
				else
				{
					rapidjson::GenericStringBuffer<rapidjson::UTF8<>> buffer;
					rapidjson::Writer<rapidjson::GenericStringBuffer<rapidjson::UTF8<>>> writer(buffer);
					doc.Accept(writer);

					auto serialized = buffer.GetString();
					FileUtils::getInstance()->writeStringToFile(serialized, fullPath);
				}

			}

		}
	}
	catch (...)
	{
	}
}

std::unique_ptr<AnalyticsData> uba::Analytics::createAnalyticsData(const rapidjson::Value& data)
{
	auto result = std::unique_ptr<AnalyticsData>(new AnalyticsData());

	result->category = data["Category"].GetInt();
	result->username = data["Username"].GetString();
	result->gender = data["Gender"].GetInt();
	result->ageGroup = data["AgeGroup"].GetInt();
	result->direction = data["Direction"].GetInt();
	result->id = data["Id"].GetInt();

	result->totalLength = data["Total_length"].GetDouble();

	result->maxSpeed = data["Maxima_speed"].GetDouble();
	result->totalTime = data["Total_time"].GetDouble();
	result->averageSpeed = data["Average_speed"].GetDouble();
	result->width = data["Width"].GetDouble();
	result->height = data["Height"].GetDouble();
	result->maxAccel = data["Maxima_acceleration"].GetDouble();
	result->avgAccel = data["Average_acceleration"].GetDouble();
	result->vecAngle = data["Angle_start_to_end"].GetDouble();

	result->startAccX = data["Starting_acceleration_x"].GetDouble();
	result->startAccY = data["Starting_acceleration_y"].GetDouble();
	result->startAccZ = data["Starting_acceleration_z"].GetDouble();

	result->startAccVX = data["Starting_acceleration_vx"].GetDouble();
	result->startAccVY = data["Starting_acceleration_vy"].GetDouble();
	result->startAccVZ = data["Starting_acceleration_vz"].GetDouble();

	result->endAccX = data["Ending_acceleration_x"].GetDouble();
	result->endAccY = data["Ending_acceleration_y"].GetDouble();
	result->endAccZ = data["Ending_acceleration_z"].GetDouble();

	result->endAccVX = data["Ending_acceleration_vx"].GetDouble();
	result->endAccVY = data["Ending_acceleration_vy"].GetDouble();
	result->endAccVZ = data["Ending_acceleration_vz"].GetDouble();

	/*
	float maxSpeed;
	float totalTime;
	float averageSpeed;
	float width;
	float height;
	float maxAcc;
	float avgAcc;
	float vecAngle;
	*/

	return result;
}

rapidjson::Value uba::Analytics::getAnalyticsDataJson(AnalyticsData* analyticsData, rapidjson::Document& doc)
{
	rapidjson::Value dataObject;
	dataObject.SetObject();

	dataObject.AddMember("Category", analyticsData->category, doc.GetAllocator());
	dataObject.AddMember("Username", rapidjson::StringRef(analyticsData->username.c_str(), analyticsData->username.length()), doc.GetAllocator());
	dataObject.AddMember("Gender", analyticsData->gender, doc.GetAllocator());
	dataObject.AddMember("AgeGroup", analyticsData->ageGroup, doc.GetAllocator());
	dataObject.AddMember("Direction", analyticsData->direction, doc.GetAllocator());
	dataObject.AddMember("Id", analyticsData->id, doc.GetAllocator());

	dataObject.AddMember("Total_length", analyticsData->totalLength, doc.GetAllocator());
	dataObject.AddMember("Maxima_speed", analyticsData->maxSpeed, doc.GetAllocator());
	dataObject.AddMember("Total_time", analyticsData->totalTime, doc.GetAllocator());
	dataObject.AddMember("Average_speed", analyticsData->averageSpeed, doc.GetAllocator());
	dataObject.AddMember("Width", analyticsData->width, doc.GetAllocator());
	dataObject.AddMember("Height", analyticsData->height, doc.GetAllocator());
	dataObject.AddMember("Maxima_acceleration", analyticsData->maxAccel, doc.GetAllocator());
	dataObject.AddMember("Average_acceleration", analyticsData->avgAccel, doc.GetAllocator());
	dataObject.AddMember("Angle_start_to_end", analyticsData->vecAngle, doc.GetAllocator());

	dataObject.AddMember("Starting_acceleration_x", analyticsData->startAccX, doc.GetAllocator());
	dataObject.AddMember("Starting_acceleration_y", analyticsData->startAccY, doc.GetAllocator());
	dataObject.AddMember("Starting_acceleration_z", analyticsData->startAccZ, doc.GetAllocator());
	dataObject.AddMember("Starting_acceleration_vx", analyticsData->startAccVX, doc.GetAllocator());
	dataObject.AddMember("Starting_acceleration_vy", analyticsData->startAccVY, doc.GetAllocator());
	dataObject.AddMember("Starting_acceleration_vz", analyticsData->startAccVZ, doc.GetAllocator());

	dataObject.AddMember("Ending_acceleration_x", analyticsData->endAccX, doc.GetAllocator());
	dataObject.AddMember("Ending_acceleration_y", analyticsData->endAccY, doc.GetAllocator());
	dataObject.AddMember("Ending_acceleration_z", analyticsData->endAccZ, doc.GetAllocator());
	dataObject.AddMember("Ending_acceleration_vx", analyticsData->endAccVX, doc.GetAllocator());
	dataObject.AddMember("Ending_acceleration_vy", analyticsData->endAccVY, doc.GetAllocator());
	dataObject.AddMember("Ending_acceleration_vz", analyticsData->endAccVZ, doc.GetAllocator());

	return dataObject;
}


text:
import React from 'react'

class Button extends React.Component {
    render() {
        return(<button id={this.props.id} className="button">{this.props.value}</button>);
    }
}

export default Button


text:
package org.pentaho.di.job.entries.columnsexist;

import static org.pentaho.di.job.entry.validator.AndValidator.putValidators;
import static org.pentaho.di.job.entry.validator.JobEntryValidatorUtils.andValidator;
import static org.pentaho.di.job.entry.validator.JobEntryValidatorUtils.notBlankValidator;

import java.util.List;

import org.pentaho.di.cluster.SlaveServer;
import org.pentaho.di.core.CheckResultInterface;
import org.pentaho.di.core.Const;
import org.pentaho.di.core.Result;
import org.pentaho.di.core.database.Database;
import org.pentaho.di.core.database.DatabaseMeta;
import org.pentaho.di.core.exception.KettleDatabaseException;
import org.pentaho.di.core.exception.KettleException;
import org.pentaho.di.core.exception.KettleXMLException;
import org.pentaho.di.core.xml.XMLHandler;
import org.pentaho.di.i18n.BaseMessages;
import org.pentaho.di.job.JobMeta;
import org.pentaho.di.job.entry.JobEntryBase;
import org.pentaho.di.job.entry.JobEntryInterface;
import org.pentaho.di.repository.ObjectId;
import org.pentaho.di.repository.Repository;
import org.pentaho.di.resource.ResourceEntry;
import org.pentaho.di.resource.ResourceReference;
import org.pentaho.di.resource.ResourceEntry.ResourceType;
import org.w3c.dom.Node;

/**
 * This defines a column exists job entry.
 *
 * @author Samatar
 * @since 16-06-2008
 *
 */

public class JobEntryColumnsExist extends JobEntryBase implements Cloneable, JobEntryInterface
{
	private static Class<?> PKG = JobEntryColumnsExist.class; // for i18n purposes, needed by Translator2!!   $NON-NLS-1$
	private String schemaname;
	private String tablename;
	private DatabaseMeta connection;
	public String arguments[];

	public JobEntryColumnsExist(String n)
	{
	    super(n, "");
	    schemaname=null;
		tablename=null;
		connection=null;
		setID(-1L);
	}

	public JobEntryColumnsExist()
	{
		this("");
	}

    public Object clone()
    {
        JobEntryColumnsExist je = (JobEntryColumnsExist) super.clone();
        return je;
    }

	public String getXML()
	{
        StringBuffer retval = new StringBuffer(200);

		retval.append(super.getXML());

		retval.append("      ").append(XMLHandler.addTagValue("tablename",  tablename));
		retval.append("      ").append(XMLHandler.addTagValue("schemaname",  schemaname));
		retval.append("      ").append(XMLHandler.addTagValue("connection", connection==null?null:connection.getName()));

		 retval.append("      <fields>").append(Const.CR); //$NON-NLS-1$
		    if (arguments != null) {
		      for (int i = 0; i < arguments.length; i++) {
		        retval.append("        <field>").append(Const.CR); //$NON-NLS-1$
		        retval.append("          ").append(XMLHandler.addTagValue("name", arguments[i]));
		        retval.append("        </field>").append(Const.CR); //$NON-NLS-1$
		      }
		    }
		    retval.append("      </fields>").append(Const.CR); //$NON-NLS-1$

		return retval.toString();
	}

	public void loadXML(Node entrynode, List<DatabaseMeta>  databases, List<SlaveServer> slaveServers, Repository rep) throws KettleXMLException
	{
		try
		{
			super.loadXML(entrynode, databases, slaveServers);
			tablename     = XMLHandler.getTagValue(entrynode, "tablename");
			schemaname     = XMLHandler.getTagValue(entrynode, "schemaname");

			String dbname = XMLHandler.getTagValue(entrynode, "connection");
			connection    = DatabaseMeta.findDatabase(databases, dbname);

		    Node fields = XMLHandler.getSubNode(entrynode, "fields"); //$NON-NLS-1$

	        // How many field arguments?
	        int nrFields = XMLHandler.countNodes(fields, "field"); //$NON-NLS-1$
	        arguments = new String[nrFields];

	        // Read them all...
	        for (int i = 0; i < nrFields; i++) {
	        	Node fnode = XMLHandler.getSubNodeByNr(fields, "field", i); //$NON-NLS-1$
	        	arguments[i] = XMLHandler.getTagValue(fnode, "name"); //$NON-NLS-1$
	        }

		}
		catch(KettleException e)
		{
			throw new KettleXMLException(BaseMessages.getString(PKG, "JobEntryColumnsExist.Meta.UnableLoadXml"), e);
		}
	}

	public void loadRep(Repository rep, ObjectId id_jobentry, List<DatabaseMeta> databases, List<SlaveServer> slaveServers) throws KettleException
	{
		try
		{
			tablename  = rep.getJobEntryAttributeString(id_jobentry, "tablename");
			schemaname  = rep.getJobEntryAttributeString(id_jobentry, "schemaname");

			connection = rep.loadDatabaseMetaFromJobEntryAttribute(id_jobentry, "connection", "id_database", databases);

			 // How many arguments?
	        int argnr = rep.countNrJobEntryAttributes(id_jobentry, "name"); //$NON-NLS-1$
	        arguments = new String[argnr];

	        // Read them all...
	        for (int a = 0; a < argnr; a++)
	        {
	          arguments[a] = rep.getJobEntryAttributeString(id_jobentry, a, "name");
	        }

		}
		catch(KettleDatabaseException dbe)
		{
			throw new KettleException(BaseMessages.getString(PKG, "JobEntryColumnsExist.Meta.UnableLoadRep",""+id_jobentry), dbe);
		}
	}

	public void saveRep(Repository rep, ObjectId id_job) throws KettleException
	{
		try
		{
			rep.saveJobEntryAttribute(id_job, getObjectId(), "tablename", tablename);
			rep.saveJobEntryAttribute(id_job, getObjectId(), "schemaname", schemaname);

			rep.saveDatabaseMetaJobEntryAttribute(id_job, getObjectId(), "connection", "id_database", connection);

			   // save the arguments...
		      if (arguments != null) {
		        for (int i = 0; i < arguments.length; i++) {
		          rep.saveJobEntryAttribute(id_job, getObjectId(), i, "name", arguments[i]);
		        }
		      }
		}
		catch(KettleDatabaseException dbe)
		{
			throw new KettleException(BaseMessages.getString(PKG, "JobEntryColumnsExist.Meta.UnableSaveRep",""+id_job), dbe);
		}
	}

	public void setTablename(String tablename)
	{
		this.tablename = tablename;
	}

	public String getTablename()
	{
		return tablename;
	}

	public void setSchemaname(String schemaname)
	{
		this.schemaname = schemaname;
	}

	public String getSchemaname()
	{
		return schemaname;
	}

	public void setDatabase(DatabaseMeta database)
	{
		this.connection = database;
	}

	public DatabaseMeta getDatabase()
	{
		return connection;
	}

	public boolean evaluates()
	{
		return true;
	}

	public boolean isUnconditional()
	{
		return false;
	}

	public Result execute(Result previousResult, int nr)
	{
		Result result = previousResult;
		result.setResult(false);
		result.setNrErrors(1);

		int nrexistcolums=0;
		int nrnotexistcolums=0;

		if(Const.isEmpty(tablename))
		{
			logError(BaseMessages.getString(PKG, "JobEntryColumnsExist.Error.TablenameEmpty"));
			return result;
		}
		if(arguments == null)
		{
			logError(BaseMessages.getString(PKG, "JobEntryColumnsExist.Error.ColumnameEmpty"));
			return result;
		}
		if (connection!=null)
		{
			Database db = new Database(this, connection);
			db.shareVariablesWith(this);
			try
			{
				String realSchemaname = environmentSubstitute(schemaname);
                String realTablename = environmentSubstitute(tablename);

                if(!Const.isEmpty(realSchemaname))
                	realTablename = db.getDatabaseMeta().getQuotedSchemaTableCombination(realSchemaname, realTablename);
                else
                	realTablename = db.getDatabaseMeta().quoteField(realTablename);

				db.connect();

				if (db.checkTableExists(realTablename))
				{
					if(log.isDetailed()) logDetailed(BaseMessages.getString(PKG, "JobEntryColumnsExist.Log.TableExists",realTablename));

					for (int i = 0; i < arguments.length && !parentJob.isStopped(); i++)
				     {
						 String realColumnname = environmentSubstitute(arguments[i]);
						 realColumnname=db.getDatabaseMeta().quoteField(realColumnname);

						 if (db.checkColumnExists(realColumnname,realTablename))
						 {
							if(log.isDetailed()) logDetailed(BaseMessages.getString(PKG, "JobEntryColumnsExist.Log.ColumnExists",realColumnname,realTablename));
							nrexistcolums++;
						 }else
						 {
							logError(BaseMessages.getString(PKG, "JobEntryColumnsExist.Log.ColumnNotExists",realColumnname,realTablename));
							nrnotexistcolums++;
						 }
				     }
				}
				else
				{
					logError(BaseMessages.getString(PKG, "JobEntryColumnsExist.Log.TableNotExists",realTablename));
				}
			}
			catch(KettleDatabaseException dbe)
			{
				logError(BaseMessages.getString(PKG, "JobEntryColumnsExist.Error.UnexpectedError",dbe.getMessage()));
			}finally
			{
				if(db!=null) try{db.disconnect();}catch(Exception e){};
			}
		}
		else
		{
			logError(BaseMessages.getString(PKG, "JobEntryColumnsExist.Error.NoDbConnection"));
		}

		result.setEntryNr(nrnotexistcolums);
		result.setNrLinesWritten(nrexistcolums);
		if(nrnotexistcolums==0)	result.setResult(true);
		return result;
	}

    public DatabaseMeta[] getUsedDatabaseConnections()
    {
        return new DatabaseMeta[] { connection, };
    }
    public List<ResourceReference> getResourceDependencies(JobMeta jobMeta) {
        List<ResourceReference> references = super.getResourceDependencies(jobMeta);
        if (connection != null) {
          ResourceReference reference = new ResourceReference(this);
          reference.getEntries().add( new ResourceEntry(connection.getHostname(), ResourceType.SERVER));
          reference.getEntries().add( new ResourceEntry(connection.getDatabaseName(), ResourceType.DATABASENAME));
          references.add(reference);
        }
        return references;
      }

      @Override
      public void check(List<CheckResultInterface> remarks, JobMeta jobMeta)
      {
        andValidator().validate(this, "tablename", remarks, putValidators(notBlankValidator())); //$NON-NLS-1$
        andValidator().validate(this, "columnname", remarks, putValidators(notBlankValidator())); //$NON-NLS-1$
      }

}


text:
<Record>
<Term>Histiocytic Necrotizing Lymphadenitis</Term>
<SemanticType>Disease or Syndrome</SemanticType>
<ParentTerm>Lymphadenitis</ParentTerm>
<ClassificationPath>Hemic and Lymphatic Diseases/Lymphatic Diseases/Lymphadenitis/Histiocytic Necrotizing Lymphadenitis</ClassificationPath>
<ClassificationPath>Lymphadenitis/Histiocytic Necrotizing Lymphadenitis</ClassificationPath>
<BroaderTerm>Histiocytic Necrotizing Lymphadenitis</BroaderTerm>
<BroaderTerm>Hemic and Lymphatic Diseases</BroaderTerm>
<BroaderTerm>Lymphadenitis</BroaderTerm>
<BroaderTerm>Lymphatic Diseases</BroaderTerm>
<Synonym>Kikuchi-Fujimoto Disease</Synonym>
<Synonym>Kikuchi Fujimoto Disease</Synonym>
<Synonym>Kikuchi-Fujimotos Disease</Synonym>
<Synonym>Histiocytic Necrotising Lymphadenitis</Synonym>
<Synonym>Kikuchi-Fujimoto's Disease</Synonym>
<Synonym>Kikuchis Disease</Synonym>
<Synonym>Kikuchi Necrotizing Lymphadenitis</Synonym>
<Synonym>Histiocytic Necrotizing Lymphadenitis</Synonym>
<Synonym>Kikuchi's Disease</Synonym>
<Synonym>Histiocytic Necrotising Lymphadenitides</Synonym>
<Synonym>Nosocomial Kikuchi Disease</Synonym>
<Synonym>Kikuchi Fujimoto's Disease</Synonym>
<Synonym>Kikuchi Disease</Synonym>
<Synonym>Nosocomial Kikuchis Disease</Synonym>
<Synonym>Nosocomial Kikuchi's Disease</Synonym>
<Description>Development of lesions in the lymph node characterized by infiltration of the cortex or paracortex by large collections of proliferating histiocytes and complete or, more often, incomplete necrosis of lymphoid tissue.</Description>
<Source>NCI Thesaurus</Source>
<Source>MeSH</Source>
</Record>


text:
# <Route>

The Route component is perhaps the most important component in React
Router to understand and learn to use well. Its most basic
responsibility is to render some UI when a [location](./location.md)
matches the route's `path`.

Consider the following code:

```jsx
import { BrowserRouter as Router, Route } from 'react-router-dom'

<Router>
  <div>
    <Route exact path="/" component={Home}/>
    <Route path="/news" component={NewsFeed}/>
  </div>
</Router>
```

If the location of the app is `/` then the UI hierarchy will be something like:

```html
<div>
  <Home/>
  <!-- react-empty: 2 -->
</div>
```

And if the location of the app is `/news` then the UI hierarchy will be:

```html
<div>
  <!-- react-empty: 1 -->
  <NewsFeed/>
</div>
```

The "react-empty" comments are just implementation details of React's `null` rendering. But for our purposes, it is instructive. A Route is always technically "rendered" even though its rendering `null`. As soon as the app location matches the route's path, your component will be rendered.

## Route render methods

There are 3 ways to render something with a `<Route>`:

- [`<Route component>`](#component)
- [`<Route render>`](#render-func)
- [`<Route children>`](#children-func)

Each is useful in different circumstances. You should use only one of these props on a given `<Route>`. See their explanations below to understand why you have 3 options. Most of the time you'll use `component`.

## Route props

All three [render methods](#route-render-methods) will be passed the same three route props

- [match](./match.md)
- [location](./location.md)
- [history](./history.md)

## component

A React component to render only when the location matches. It will be
rendered with [route props](#route-props).

```jsx
<Route path="/user/:username" component={User}/>

const User = ({ match }) => {
  return <h1>Hello {match.params.username}!</h1>
}
```

When you use `component` (instead of `render` or `children`, below) the router uses [`React.createElement`](https://facebook.github.io/react/docs/react-api.html#createelement) to create a new [React element](https://facebook.github.io/react/docs/rendering-elements.html) from the given component. That means if you provide an inline function to the `component` prop, you would create a new component every render. This results in the existing component unmounting and the new component mounting instead of just updating the existing component. When using an inline function for inline rendering, use the `render` or the `children` prop (below).

## render: func

This allows for convenient inline rendering and wrapping without the undesired remounting explained above.

Instead of having a new [React element](https://facebook.github.io/react/docs/rendering-elements.html) created for you using the [`component`](#component) prop, you can pass in a function to be called when the location matches. The `render` prop receives all the same [route props](#route-props) as the `component` render prop.

```jsx
// convenient inline rendering
<Route path="/home" render={() => <div>Home</div>}/>

// wrapping/composing
const FadingRoute = ({ component: Component, ...rest }) => (
  <Route {...rest} render={props => (
    <FadeIn>
      <Component {...props}/>
    </FadeIn>
  )}/>
)

<FadingRoute path="/cool" component={Something}/>
```

**Warning:** `<Route component>` takes precedence over `<Route render>` so don't use both in the same `<Route>`.

## children: func

Sometimes you need to render whether the path matches the location or not. In these cases, you can use the function `children` prop. It works exactly like `render` except that it gets called whether there is a match or not.

The `children` render prop receives all the same [route props](#route-props) as the `component` and `render` methods, except when a route fails to match the URL, then `match` is `null`. This allows you to dynamically adjust your UI based on whether or not the route matches. Here we're adding an `active` class if the route matches

```jsx
<ul>
  <ListItemLink to="/somewhere"/>
  <ListItemLink to="/somewhere-else"/>
</ul>

const ListItemLink = ({ to, ...rest }) => (
  <Route path={to} children={({ match }) => (
    <li className={match ? 'active' : ''}>
      <Link to={to} {...rest}/>
    </li>
  )}/>
)
```

This could also be useful for animations:

```jsx
<Route children={({ match, ...rest }) => (
  {/* Animate will always render, so you can use lifecycles
      to animate its child in and out */}
  <Animate>
    {match && <Something {...rest}/>}
  </Animate>
)}/>
```

**Warning:** Both `<Route component>` and `<Route render>` take precedence over `<Route children>` so don't use more than one in the same `<Route>`.

## path: string

Any valid URL path that [`path-to-regexp@^1.7.0`](https://github.com/pillarjs/path-to-regexp/tree/v1.7.0) understands.

```jsx
<Route path="/users/:id" component={User}/>
```

Routes without a `path` _always_ match.

## exact: bool

When `true`, will only match if the path matches the `location.pathname` _exactly_.

```jsx
<Route exact path="/one" component={About}/>
```

| path | location.pathname | exact | matches? |
| --- | --- | --- | --- |
| `/one`  | `/one/two`  | `true` | no |
| `/one`  | `/one/two`  | `false` | yes |

## strict: bool

When `true`, a `path` that has a trailing slash will only match a `location.pathname` with a trailing slash. This has no effect when there are additional URL segments in the `location.pathname`.

```jsx
<Route strict path="/one/" component={About}/>
```

| path | location.pathname | matches? |
| --- | --- | --- |
| `/one/` | `/one` | no |
| `/one/` | `/one/` | yes |
| `/one/` | `/one/two` | yes |

**Warning:** `strict` can be used to enforce that a `location.pathname` has no trailing slash, but in order to do this both `strict` and `exact` must be `true`.

```jsx
<Route exact strict path="/one" component={About}/>
```

| path | location.pathname | matches? |
| --- | --- | --- |
| `/one` | `/one` | yes |
| `/one` | `/one/` | no |
| `/one` | `/one/two` | no |

## location: object

A `<Route>` element tries to match its `path` to the current history location (usually the current browser URL).
However, a [`location`](location.md) with a different `pathname` can also be passed for matching.

This is useful in cases when you need to match a `<Route>` to a location other than the current history location, as shown in the [Animated Transitions](https://reacttraining.com/react-router/web/example/animated-transitions) example.

If a `<Route>` element is wrapped in a `<Switch>` and matches the location passed to the `<Switch>` (or the current history location), then the `location` prop passed to `<Route>` will be overridden by the one used by the `<Switch>` (given [here](https://github.com/ReactTraining/react-router/blob/master/packages/react-router/modules/Switch.js#L51)).

## sensitive: bool

When `true`, will match if the path is __case sensitive__.

```jsx
<Route sensitive path="/one" component={About}/>
```

| path | location.pathname | sensitive | matches? |
| --- | --- | --- | --- |
| `/one`  | `/one`  | `true` | yes |
| `/One`  | `/one`  | `true` | no |
| `/One`  | `/one`  | `false`| yes |


text:
ENT.Type                        = "anim"
ENT.PrintName           = ""
ENT.Author                      = ""
ENT.Contact                     = ""
ENT.Purpose                     = ""
ENT.Instructions        = ""

function ENT:OnRemove()
end

function ENT:PhysicsUpdate()
end

function ENT:PhysicsCollide(data, phys)
        if data.Speed > 50 then
                self.Entity:EmitSound(Sound("SmokeGrenade.Bounce"))
        end
end


text:
require 'spec_helper'

describe Gitlab::UserExtractor do
  let(:text) do
    <<~TXT
    This is a long texth that mentions some users.
    @user-1, @user-2 and user@gitlab.org take a walk in the park.
    There they meet @user-4 that was out with other-user@gitlab.org.
    @user-1 thought it was late, so went home straight away
    TXT
  end
  subject(:extractor) { described_class.new(text) }

  describe '#users' do
    it 'returns an empty relation when nil was passed' do
      extractor = described_class.new(nil)

      expect(extractor.users).to be_empty
      expect(extractor.users).to be_a(ActiveRecord::Relation)
    end

    it 'returns the user case insensitive for usernames' do
      user = create(:user, username: "USER-4")

      expect(extractor.users).to include(user)
    end

    it 'returns users by primary email' do
      user = create(:user, email: 'user@gitlab.org')

      expect(extractor.users).to include(user)
    end

    it 'returns users by secondary email' do
      user = create(:email, email: 'other-user@gitlab.org').user

      expect(extractor.users).to include(user)
    end
  end

  describe '#matches' do
    it 'includes all mentioned email adresses' do
      expect(extractor.matches[:emails]).to contain_exactly('user@gitlab.org', 'other-user@gitlab.org')
    end

    it 'includes all mentioned usernames' do
      expect(extractor.matches[:usernames]).to contain_exactly('user-1', 'user-2', 'user-4')
    end
  end

  describe '#references' do
    it 'includes all user-references once' do
      expect(extractor.references).to contain_exactly('user-1', 'user-2', 'user@gitlab.org', 'user-4', 'other-user@gitlab.org')
    end
  end
end


text:
Antecedentes

	El 3 de noviembre de 1977 se constituye, en la ciudad de Puebla, la Universidad Cuauhtémoc
	en una Asociación Civil dedicada, exclusivamente a la educación superior misma que no persigue fines de lucro ni partidismo político
	o religioso alguno.

		<img src="<?=base_url()?>application/assets/images/nosotros/antecedentes.jpg" class = "img-responsive" alt="" />

		<img src="<?=base_url()?>application/assets/images/nosotros/antecedentes_movil.jpg" class = "img-responsive" alt="" />

	En la ciudad de Aguascalientes la Universidad Cuauhtémoc inicia sus actividades en agosto de 1993, en Av. Convención de 1914
	No. 808 Colonia Circunvalación de la Cd. de Aguascalientes, ofreciendo 8 licenciaturas y Bachillerato. Debido a la creciente demanda
	de alumnos por los servicios educativos que proporciona la universidad, el 12 de abril de 1996, inaugura su campus universitario en
	Av. Independencia No. 100, Col. Trojes de Alonso.


text:
using System;
using CommonDomain.Persistence;
using NEventStoreExample.Infrastructure;
using NEventStoreExample.Command;
using NEventStoreExample.Model;

namespace NEventStoreExample.CommandHandler
{
    public class AccountHolderMovedCommandHandler : ICommandHandler<AccountHolderMovedCommand>
    {
        private IRepository eventstore;

        public AccountHolderMovedCommandHandler(IRepository eventstore)
        {
            this.eventstore = eventstore;
        }

        public void Handle(AccountHolderMovedCommand command)
        {
            var account = eventstore.GetById<Account>(command.AccountId);
            account.MoveToNewAddress(command.Address, command.City);
            eventstore.Save(account, Guid.NewGuid());
        }
    }
}


text:
<?php

namespace Kunstmaan\AdminBundle\DependencyInjection;

use FOS\UserBundle\Form\Type\ResettingFormType;
use InvalidArgumentException;
use Symfony\Component\Config\FileLocator;
use Symfony\Component\DependencyInjection\ContainerBuilder;
use Symfony\Component\DependencyInjection\Definition;
use Symfony\Component\DependencyInjection\Extension\PrependExtensionInterface;
use Symfony\Component\DependencyInjection\Loader;
use Symfony\Component\DependencyInjection\Reference;
use Symfony\Component\HttpKernel\DependencyInjection\Extension;

/**
 * This is the class that loads and manages your bundle configuration.
 *
 * To learn more see {@link http://symfony.com/doc/current/cookbook/bundles/extension.html}
 */
class KunstmaanAdminExtension extends Extension implements PrependExtensionInterface
{
    /**
     * Loads a specific configuration.
     *
     * @param array            $configs   An array of configuration values
     * @param ContainerBuilder $container A ContainerBuilder instance
     *
     * @throws InvalidArgumentException When provided tag is not defined in this extension
     */
    public function load(array $configs, ContainerBuilder $container)
    {
        $container->setParameter('version_checker.url', 'https://bundles.kunstmaan.be/version-check');
        $container->setParameter('version_checker.timeframe', 60 * 60 * 24);
        $container->setParameter('version_checker.enabled', true);

        $configuration = new Configuration();
        $config = $this->processConfiguration($configuration, $configs);

        if (array_key_exists('dashboard_route', $config)) {
            $container->setParameter('kunstmaan_admin.dashboard_route', $config['dashboard_route']);
        }
        if (array_key_exists('admin_password', $config)) {
            $container->setParameter('kunstmaan_admin.admin_password', $config['admin_password']);
        }
        $container->setParameter('kunstmaan_admin.admin_locales', $config['admin_locales']);
        $container->setParameter('kunstmaan_admin.default_admin_locale', $config['default_admin_locale']);

        $container->setParameter('kunstmaan_admin.session_security.ip_check', $config['session_security']['ip_check']);
        $container->setParameter('kunstmaan_admin.session_security.user_agent_check', $config['session_security']['user_agent_check']);

        $container->setParameter('kunstmaan_admin.admin_prefix', $this->normalizeUrlSlice($config['admin_prefix']));

        $container->setParameter('kunstmaan_admin.google_signin.enabled', $config['google_signin']['enabled']);
        $container->setParameter('kunstmaan_admin.google_signin.client_id', $config['google_signin']['client_id']);
        $container->setParameter('kunstmaan_admin.google_signin.client_secret', $config['google_signin']['client_secret']);
        $container->setParameter('kunstmaan_admin.google_signin.hosted_domains', $config['google_signin']['hosted_domains']);

        $container->setParameter('kunstmaan_admin.password_restrictions.min_digits', $config['password_restrictions']['min_digits']);
        $container->setParameter('kunstmaan_admin.password_restrictions.min_uppercase', $config['password_restrictions']['min_uppercase']);
        $container->setParameter('kunstmaan_admin.password_restrictions.min_special_characters', $config['password_restrictions']['min_special_characters']);
        $container->setParameter('kunstmaan_admin.password_restrictions.min_length', $config['password_restrictions']['min_length']);
        $container->setParameter('kunstmaan_admin.password_restrictions.max_length', $config['password_restrictions']['max_length']);

        $loader = new Loader\YamlFileLoader($container, new FileLocator(__DIR__.'/../Resources/config'));
        $loader->load('services.yml');

        if (!empty($config['enable_console_exception_listener']) && $config['enable_console_exception_listener']) {
            $loader->load('console_listener.yml');
        }

        if (0 !== count($config['menu_items'])) {
            $this->addSimpleMenuAdaptor($container, $config['menu_items']);
        }
    }

    public function prepend(ContainerBuilder $container)
    {
        $knpMenuConfig['twig'] = true; // set to false to disable the Twig extension and the TwigRenderer
        $knpMenuConfig['templating'] = false; // if true, enables the helper for PHP templates
        $knpMenuConfig['default_renderer'] = 'twig'; // The renderer to use, list is also available by default
        $container->prependExtensionConfig('knp_menu', $knpMenuConfig);

        $fosUserConfig['db_driver'] = 'orm'; // other valid values are 'mongodb', 'couchdb'
        $fosUserConfig['firewall_name'] = 'main';
        $fosUserConfig['user_class'] = 'Kunstmaan\AdminBundle\Entity\User';
        $fosUserConfig['group']['group_class'] = 'Kunstmaan\AdminBundle\Entity\Group';
        $fosUserConfig['resetting']['token_ttl'] = 86400;
        // Use this node only if you don't want the global email address for the resetting email
        $fosUserConfig['resetting']['email']['from_email']['address'] = 'admin@kunstmaan.be';
        $fosUserConfig['resetting']['email']['from_email']['sender_name'] = 'admin';
        $fosUserConfig['resetting']['email']['template'] = 'FOSUserBundle:Resetting:email.txt.twig';
        $fosUserConfig['resetting']['form']['type'] = ResettingFormType::class;
        $fosUserConfig['resetting']['form']['name'] = 'fos_user_resetting_form';
        $fosUserConfig['resetting']['form']['validation_groups'] = ['ResetPassword'];
        $container->prependExtensionConfig('fos_user', $fosUserConfig);

        $monologConfig['handlers']['main']['type'] = 'rotating_file';
        $monologConfig['handlers']['main']['path'] = sprintf('%s/%s', $container->getParameter('kernel.logs_dir'), $container->getParameter('kernel.environment'));
        $monologConfig['handlers']['main']['level'] = 'debug';
        $container->prependExtensionConfig('monolog', $monologConfig);

        $configs = $container->getExtensionConfig($this->getAlias());
        $this->processConfiguration(new Configuration(), $configs);
    }

    /**
     * {@inheritdoc}
     */
    public function getNamespace()
    {
        return 'http://bundles.kunstmaan.be/schema/dic/admin';
    }

    /**
     * {@inheritdoc}
     */
    public function getXsdValidationBasePath()
    {
        return __DIR__.'/../Resources/config/schema';
    }

    /**
     * @param string $urlSlice
     *
     * @return string
     */
    protected function normalizeUrlSlice($urlSlice)
    {
        // Get rid of exotic characters that would break the url
        $urlSlice = filter_var($urlSlice, FILTER_SANITIZE_URL);

        // Remove leading and trailing slashes
        $urlSlice = trim($urlSlice, '/');

        // Make sure our $urlSlice is literally used in our regex
        $urlSlice = preg_quote($urlSlice);

        return $urlSlice;
    }

    private function addSimpleMenuAdaptor(ContainerBuilder $container, array $menuItems)
    {
        $definition = new Definition('Kunstmaan\AdminBundle\Helper\Menu\SimpleMenuAdaptor', [
            new Reference('security.authorization_checker'),
            $menuItems,
        ]);
        $definition->addTag('kunstmaan_admin.menu.adaptor');

        $container->setDefinition('kunstmaan_admin.menu.adaptor.simple', $definition);
    }
}