text:
using AutoMapper;
using Moq;
using System;
using System.Collections.Generic;
using XrmFramework.DeployUtils.Context;
using XrmFramework.DeployUtils.Model;
using XrmFramework.DeployUtils.Utils;

namespace XrmFramework.DeployUtils.Tests
{
    [TestClass]
    public class AssemblyDiffFactoryTests
    {

        private readonly AssemblyDiffFactory _diffFactory;

        private readonly Mock<ICrmComponentComparer> _mockComparer;
        private readonly Mock<IMapper> _mockMapper;

        public AssemblyDiffFactoryTests()
        {
            _mockComparer = new();
            _mockMapper = new();

            _diffFactory = new(_mockComparer.Object, _mockMapper.Object);
        }

        [TestMethod]
        public void OneComponent_Vs_Null()
        {
            // Arrange
            var from = new Mock<IAssemblyContext>();

            _mockMapper.Setup(x => x.Map<IAssemblyContext>(It.IsAny<IAssemblyContext>()))
                .Returns(from.Object);

            from.Setup(f => f.Children)
                .Returns(new List<ICrmComponent>());

            // Act
            var result = _diffFactory.ComputeDiffPatch(from.Object, null);

            // Assert
            from.VerifySet(from => from.RegistrationState = RegistrationState.ToCreate, Times.Once);
            from.VerifyGet(from => from.Children, Times.Once);
        }

        [TestMethod]
        public void TwoComponents_Vs_Null()
        {
            // Arrange
            var from = new Mock<IAssemblyContext>();

            var child = new Mock<ICrmComponent>();

            _mockMapper.Setup(x => x.Map<IAssemblyContext>(It.IsAny<IAssemblyContext>()))
                .Returns(from.Object);

            from.Setup(f => f.Children)
                .Returns(new List<ICrmComponent>() { child.Object });

            child.Setup(c => c.Children)
                .Returns(new List<ICrmComponent>());

            // Act
            var result = _diffFactory.ComputeDiffPatch(from.Object, null);

            // Assert
            from.VerifySet(from => from.RegistrationState = RegistrationState.ToCreate, Times.Once);
            from.VerifyGet(from => from.Children, Times.Once);

            child.VerifySet(from => from.RegistrationState = RegistrationState.ToCreate, Times.Once);
            child.VerifyGet(from => from.Children, Times.Once);

        }

        [TestMethod]
        public void TwoEmptyAssemblies()
        {
            // Arrange
            var from = new Mock<IAssemblyContext>();
            var target = new Mock<IAssemblyContext>();

            var targetId = Guid.NewGuid();
            var targetParentId = Guid.NewGuid();

            from.SetupProperty(m => m.RegistrationState);
            target.SetupProperty(m => m.RegistrationState);

            target.SetupProperty(m => m.Id, targetId);
            target.SetupProperty(m => m.ParentId, targetParentId);

            from.SetupProperty(m => m.Id, Guid.NewGuid());
            from.SetupProperty(m => m.ParentId, Guid.NewGuid());

            _mockMapper.Setup(x => x.Map<IAssemblyContext>(It.IsAny<IAssemblyContext>()))
                .Returns(from.Object);

            from.Setup(f => f.Children)
                .Returns(new List<ICrmComponent>());

            target.Setup(f => f.Children)
                .Returns(new List<ICrmComponent>());

            from.Setup(f => f.ComponentsOrderedPool)
                .Returns(new List<ICrmComponent>() { from.Object });

            target.Setup(f => f.ComponentsOrderedPool)
                .Returns(new List<ICrmComponent>() { target.Object });

            _mockComparer.Setup(m =>
                    m.CorrespondingComponent(It.IsAny<ICrmComponent>(), It.IsAny<IReadOnlyCollection<ICrmComponent>>()))
                .Returns(target.Object);

            _mockComparer.Setup(m => m.NeedsUpdate(It.IsAny<ICrmComponent>(), It.IsAny<ICrmComponent>()))
                .Returns(false);

            // Act
            var result = _diffFactory.ComputeDiffPatch(from.Object, target.Object);

            // Assert
            from.VerifySet(f => f.RegistrationState = RegistrationState.NotComputed, Times.Once);

            target.VerifySet(t => t.RegistrationState = RegistrationState.NotComputed, Times.Once);

            from.VerifyGet(f => f.Children, Times.Once);
            target.VerifyGet(t => t.Children, Times.Once);

            from.VerifyGet(m => m.ComponentsOrderedPool, Times.Once);
            target.VerifyGet(m => m.ComponentsOrderedPool, Times.Once);

            _mockComparer.Verify(m =>
                m.CorrespondingComponent(It.IsAny<ICrmComponent>(), It.IsAny<IReadOnlyCollection<ICrmComponent>>()), Times.Once);

            _mockComparer.Verify(m =>
                m.NeedsUpdate(It.IsAny<ICrmComponent>(), It.IsAny<ICrmComponent>()), Times.Once);

            Assert.AreEqual(RegistrationState.Ignore, from.Object.RegistrationState);
            Assert.AreEqual(RegistrationState.Computed, target.Object.RegistrationState);

            Assert.AreEqual(targetId, result.Id);
            Assert.AreEqual(targetParentId, result.ParentId);

            Assert.AreEqual(targetId, target.Object.Id);
            Assert.AreEqual(targetParentId, target.Object.ParentId);
        }

        [TestMethod]
        public void DiffTest_TwoCustomApis()
        {
            // Arrange
            var from = new Mock<IAssemblyContext>();
            var target = new Mock<IAssemblyContext>();

            var targetId = Guid.NewGuid();
            var targetParentId = Guid.NewGuid();
            var targetAssemblyId = Guid.NewGuid();

            var fromCustomApi = new CustomApi()
            {
                Id = Guid.NewGuid(),
                ParentId = Guid.NewGuid(),
                AssemblyId = Guid.NewGuid(),
            };

            var targetCustomApi = new CustomApi()
            {
                Id = targetId,
                ParentId = targetParentId,
                AssemblyId = targetAssemblyId,
            };

            _mockMapper.Setup(x => x.Map<IAssemblyContext>(It.IsAny<IAssemblyContext>()))
                .Returns(from.Object);

            from.Setup(m => m.ComponentsOrderedPool)
                .Returns(new List<ICrmComponent>() { fromCustomApi });

            target.Setup(m => m.ComponentsOrderedPool)
                .Returns(new List<ICrmComponent>() { targetCustomApi });

            _mockComparer.Setup(m =>
                    m.CorrespondingComponent(It.IsAny<ICrmComponent>(), It.IsAny<IReadOnlyCollection<ICrmComponent>>()))
                .Returns(targetCustomApi);

            _mockComparer.Setup(m => m.NeedsUpdate(It.IsAny<ICrmComponent>(), It.IsAny<ICrmComponent>()))
                .Returns(true);

            // Act
            _diffFactory.ComputeDiffPatch(from.Object, target.Object);

            // Assert
            Assert.AreEqual(RegistrationState.ToUpdate, fromCustomApi.RegistrationState);
            Assert.AreEqual(RegistrationState.Computed, targetCustomApi.RegistrationState);

            Assert.AreEqual(targetId, fromCustomApi.Id);
            Assert.AreEqual(targetParentId, fromCustomApi.ParentId);

            Assert.AreEqual(targetId, targetCustomApi.Id);
            Assert.AreEqual(targetParentId, targetCustomApi.ParentId);
        }

        [TestMethod]
        public void DiffTest_CustomApiToDelete()
        {
            // Arrange
            var from = new Mock<IAssemblyContext>();
            var target = new Mock<IAssemblyContext>();

            var targetId = Guid.NewGuid();
            var targetParentId = Guid.NewGuid();
            var targetAssemblyId = Guid.NewGuid();

            var targetCustomApi = new CustomApi()
            {
                Id = targetId,
                ParentId = targetParentId,
                AssemblyId = targetAssemblyId,
                RegistrationState = RegistrationState.NotComputed
            };

            _mockMapper.Setup(x => x.Map<IAssemblyContext>(It.IsAny<IAssemblyContext>()))
                .Returns(from.Object);

            from.Setup(m => m.ComponentsOrderedPool)
                .Returns(new List<ICrmComponent>() { from.Object });

            from.SetupProperty(f => f.RegistrationState,
                RegistrationState.NotComputed);

            from.SetupProperty(f => f.Id,
                Guid.NewGuid());

            from.SetupProperty(f => f.ParentId,
                Guid.NewGuid());

            target.Setup(m => m.ComponentsOrderedPool)
                .Returns(new List<ICrmComponent>() { target.Object, targetCustomApi });

            target.SetupProperty(f => f.RegistrationState,
                RegistrationState.NotComputed);

            target.SetupProperty(f => f.Id,
                targetAssemblyId);

            target.SetupProperty(f => f.ParentId,
                Guid.NewGuid());

            _mockComparer.Setup(m =>
                    m.CorrespondingComponent(It.IsAny<ICrmComponent>(), It.IsAny<IReadOnlyCollection<ICrmComponent>>()))
                .Returns(target.Object);

            _mockComparer.Setup(m => m.NeedsUpdate(It.IsAny<ICrmComponent>(), It.IsAny<ICrmComponent>()))
                .Returns(true);

            // Act
            _diffFactory.ComputeDiffPatch(from.Object, target.Object);

            // Assert
            Assert.AreEqual(RegistrationState.ToDelete, targetCustomApi.RegistrationState);

            Assert.AreEqual(targetId, targetCustomApi.Id);
            Assert.AreEqual(targetParentId, targetCustomApi.ParentId);

            from.VerifySet(m => m.RegistrationState = RegistrationState.ToUpdate, Times.Once);
            from.VerifySet(m => m.Id = targetAssemblyId, Times.Once);

            from.Verify(m => m.AddChild(It.IsAny<CustomApi>()), Times.Once);

        }
    }
}


text:
<?php
namespace App\Controller;

use App\Controller\AppController;

/**
 * Transactions Controller
 *
 * @property \App\Model\Table\TransactionsTable $Transactions
 *
 * @method \App\Model\Entity\Transaction[] paginate($object = null, array $settings = [])
 */
class TransactionsController extends AppController
{

    /**
     * Index method
     *
     * @return \Cake\Http\Response|void
     */
    public function index()
    {
        $transactions = $this->paginate($this->Transactions);

        $this->set(compact('transactions'));
        $this->set('_serialize', ['transactions']);
    }

    /**
     * View method
     *
     * @param string|null $id Transaction id.
     * @return \Cake\Http\Response|void
     * @throws \Cake\Datasource\Exception\RecordNotFoundException When record not found.
     */
    public function view($id = null)
    {
        $transaction = $this->Transactions->get($id, [
            'contain' => []
        ]);

        $this->set('transaction', $transaction);
        $this->set('_serialize', ['transaction']);
    }

    /**
     * Add method
     *
     * @return \Cake\Http\Response|null Redirects on successful add, renders view otherwise.
     */
    public function add()
    {
        $transaction = $this->Transactions->newEntity();
        if ($this->request->is('post')) {
            $transaction = $this->Transactions->patchEntity($transaction, $this->request->getData());
            if ($this->Transactions->save($transaction)) {
                $this->Flash->success(__('The transaction has been saved.'));

                return $this->redirect(['action' => 'index']);
            }
            $this->Flash->error(__('The transaction could not be saved. Please, try again.'));
        }
        $this->set(compact('transaction'));
        $this->set('_serialize', ['transaction']);
    }

    /**
     * Edit method
     *
     * @param string|null $id Transaction id.
     * @return \Cake\Http\Response|null Redirects on successful edit, renders view otherwise.
     * @throws \Cake\Network\Exception\NotFoundException When record not found.
     */
    public function edit($id = null)
    {
        $transaction = $this->Transactions->get($id, [
            'contain' => []
        ]);
        if ($this->request->is(['patch', 'post', 'put'])) {
            $transaction = $this->Transactions->patchEntity($transaction, $this->request->getData());
            if ($this->Transactions->save($transaction)) {
                $this->Flash->success(__('The transaction has been saved.'));

                return $this->redirect(['action' => 'index']);
            }
            $this->Flash->error(__('The transaction could not be saved. Please, try again.'));
        }
        $this->set(compact('transaction'));
        $this->set('_serialize', ['transaction']);
    }

    /**
     * Delete method
     *
     * @param string|null $id Transaction id.
     * @return \Cake\Http\Response|null Redirects to index.
     * @throws \Cake\Datasource\Exception\RecordNotFoundException When record not found.
     */
    public function delete($id = null)
    {
        $this->request->allowMethod(['post', 'delete']);
        $transaction = $this->Transactions->get($id);
        if ($this->Transactions->delete($transaction)) {
            $this->Flash->success(__('The transaction has been deleted.'));
        } else {
            $this->Flash->error(__('The transaction could not be deleted. Please, try again.'));
        }

        return $this->redirect(['action' => 'index']);
    }
}

redpajama_set_name: RedPajamaGithub


text:
/*
* File: overflow_force_software.c
* CVS: $Id: overflow_force_software.c,v 1.24 2009/11/11 18:47:42 bsheely Exp $
* Author: Kevin London
* london@cs.utk.edu
* Mods: Maynard Johnson
* maynardj@us.ibm.com
* Philip Mucci
* mucci@cs.utk.edu
* Haihang You
* you@cs.utk.edu
* <your name here>
* <your email address>
*/

/* This file performs the following test: overflow dispatch of an eventset
with just a single event. Using both Hardware and software overflows

The Eventset contains:
+ PAPI_FP_INS (overflow monitor)

- Start eventset 1
- Do flops
- Stop and measure eventset 1
- Set up overflow on eventset 1
- Start eventset 1
- Do flops
- Stop eventset 1
- Set up forced software overflow on eventset 1
- Start eventset 1
- Do flops
- Stop eventset 1
*/

#include "papi_test.h"

#if defined(_WIN32)
#define OVER_FMT "handler(%d) Overflow at %p! overflow_vector=0x%x!\n"
#define OUT_FMT		"%-12s : %16I64d%16d%16I64d\n"
#else
#define OVER_FMT "handler(%d) Overflow at %p overflow_vector=0x%llx!\n"
#define OUT_FMT		"%-12s : %16lld%16d%16lld\n"
#endif

#define HARD_TOLERANCE 0.25
#define SOFT_TOLERANCE 0.90
#define MY_NUM_TESTS 5

static int total[MY_NUM_TESTS] = {0,}; /* total overflows */
static int use_total=0; /* which total field to bump */
static long long values[MY_NUM_TESTS] = { 0,};

void handler(int EventSet, void *address, long long overflow_vector, void *context)
{
	if (!TESTS_QUIET) {
		fprintf(stderr, OVER_FMT, EventSet, address, overflow_vector);
	}

	total[use_total]++;
}

int main(int argc, char **argv)
{
	int EventSet=PAPI_NULL;
	long long hard_min, hard_max, soft_min, soft_max;
	int retval;
	int PAPI_event=0, mythreshold;
	char event_name[PAPI_MAX_STR_LEN];
	PAPI_option_t opt;
	PAPI_event_info_t info;
	PAPI_option_t itimer;
	const PAPI_hw_info_t *hw_info = NULL;

	tests_quiet(argc, argv); /* Set TESTS_QUIET variable */

	retval = PAPI_library_init(PAPI_VER_CURRENT);
	if (retval != PAPI_VER_CURRENT)
		test_fail(__FILE__, __LINE__, "PAPI_library_init", retval);

	/* query and set up the right instruction to monitor */
	if (PAPI_query_event(PAPI_FP_INS) == PAPI_OK) {
		if (PAPI_query_event(PAPI_FP_INS) == PAPI_OK) {
			PAPI_get_event_info(PAPI_FP_INS, &info);
			if ( info.count == 1 || !strcmp(info.derived, "DERIVED_CMPD"))
				PAPI_event = PAPI_FP_INS;
		}
	}
	if ( PAPI_event == 0 ) {
		if (PAPI_query_event(PAPI_FP_OPS) == PAPI_OK) {
			PAPI_get_event_info(PAPI_FP_OPS, &info);
			if ( info.count == 1 || !strcmp(info.derived, "DERIVED_CMPD"))
				PAPI_event = PAPI_FP_OPS;
		}
	}
	if ( PAPI_event == 0 ) {
		if (PAPI_query_event(PAPI_TOT_INS) == PAPI_OK) {
			PAPI_get_event_info(PAPI_TOT_INS, &info);
			if ( info.count == 1 || !strcmp(info.derived, "DERIVED_CMPD"))
				PAPI_event = PAPI_TOT_INS;
		}
	}

	if ( PAPI_event == 0 )
		test_skip(__FILE__, __LINE__, "No suitable event for this test found!", 0);

   hw_info = PAPI_get_hardware_info();
   if (hw_info == NULL)
     test_fail(__FILE__, __LINE__, "PAPI_get_hardware_info", 2);

   if ( PAPI_event == PAPI_FP_INS )
      mythreshold = THRESHOLD ;
   else
#if defined(linux)
      mythreshold = hw_info->mhz*10000*2;
#else
      mythreshold = THRESHOLD*2;
#endif

	retval = PAPI_create_eventset(&EventSet);
	if (retval != PAPI_OK)
		test_fail(__FILE__, __LINE__, "PAPI_create_eventset", retval);

	retval = PAPI_add_event(EventSet, PAPI_event);
	if (retval != PAPI_OK)
		test_fail(__FILE__, __LINE__, "PAPI_add_event", retval);

	retval = PAPI_get_opt(PAPI_COMPONENTINFO, &opt);
	if (retval != PAPI_OK)
		test_skip(__FILE__, __LINE__, "Platform does not support Hardware overflow", 0);

	do_stuff();

	/* Do reference count */

	retval = PAPI_start(EventSet);
	if (retval != PAPI_OK)
		test_fail(__FILE__, __LINE__, "PAPI_start", retval);

	do_stuff();

	retval = PAPI_stop(EventSet, &values[use_total]);
	if (retval != PAPI_OK)
		test_fail(__FILE__, __LINE__, "PAPI_stop", retval);
	use_total++;

	/* Now do hardware overflow reference count */

	retval = PAPI_overflow(EventSet, PAPI_event, mythreshold, 0, handler);
	if (retval != PAPI_OK)
		test_fail(__FILE__, __LINE__, "PAPI_overflow", retval);

	retval = PAPI_start(EventSet);
	if (retval != PAPI_OK)
		test_fail(__FILE__, __LINE__, "PAPI_start", retval);

	do_stuff();

	retval = PAPI_stop(EventSet, &values[use_total]);
	if (retval != PAPI_OK)
		test_fail(__FILE__, __LINE__, "PAPI_stop", retval);
	use_total++;

	retval = PAPI_overflow(EventSet, PAPI_event, 0, 0, handler);
	if (retval != PAPI_OK)
		test_fail(__FILE__, __LINE__, "PAPI_overflow", retval);

	/* Now do software overflow reference count, uses SIGPROF */

	retval = PAPI_overflow(EventSet, PAPI_event, mythreshold, PAPI_OVERFLOW_FORCE_SW, handler);
	if (retval != PAPI_OK)
		test_fail(__FILE__, __LINE__, "PAPI_overflow", retval);

	retval = PAPI_start(EventSet);
	if (retval != PAPI_OK)
		test_fail(__FILE__, __LINE__, "PAPI_start", retval);

	do_stuff();

	retval = PAPI_stop(EventSet, &values[use_total]);
	if (retval != PAPI_OK)
		test_fail(__FILE__, __LINE__, "PAPI_stop", retval);
	use_total++;

	retval = PAPI_overflow(EventSet, PAPI_event, 0, PAPI_OVERFLOW_FORCE_SW, handler);
	if (retval != PAPI_OK)
		test_fail(__FILE__, __LINE__, "PAPI_overflow", retval);

	/* Now do software overflow with SIGVTALRM */

	memset(&itimer,0,sizeof(itimer));
	itimer.itimer.itimer_num = ITIMER_VIRTUAL;
	itimer.itimer.itimer_sig = SIGVTALRM;

	if (PAPI_set_opt(PAPI_DEF_ITIMER,&itimer) != PAPI_OK)
		test_fail(__FILE__, __LINE__, "PAPI_set_opt", retval);

	retval = PAPI_overflow(EventSet, PAPI_event, mythreshold, PAPI_OVERFLOW_FORCE_SW, handler);
	if (retval != PAPI_OK)
		test_fail(__FILE__, __LINE__, "PAPI_overflow", retval);

	retval = PAPI_start(EventSet);
	if (retval != PAPI_OK)
		test_fail(__FILE__, __LINE__, "PAPI_start", retval);

	do_stuff();

	retval = PAPI_stop(EventSet, &values[use_total]);
	if (retval != PAPI_OK)
		test_fail(__FILE__, __LINE__, "PAPI_stop", retval);
	use_total++;

	retval = PAPI_overflow(EventSet, PAPI_event, 0, PAPI_OVERFLOW_FORCE_SW, handler);
	if (retval != PAPI_OK)
		test_fail(__FILE__, __LINE__, "PAPI_overflow", retval);

	/* Now do software overflow with SIGALRM */

	memset(&itimer,0,sizeof(itimer));
	itimer.itimer.itimer_num = ITIMER_REAL;
	itimer.itimer.itimer_sig = SIGALRM;
	if (PAPI_set_opt(PAPI_DEF_ITIMER,&itimer) != PAPI_OK)
		test_fail(__FILE__, __LINE__, "PAPI_set_opt", retval);

	retval = PAPI_overflow(EventSet, PAPI_event, mythreshold, PAPI_OVERFLOW_FORCE_SW, handler);
	if (retval != PAPI_OK)
		test_fail(__FILE__, __LINE__, "PAPI_overflow", retval);

	retval = PAPI_start(EventSet);
	if (retval != PAPI_OK)
		test_fail(__FILE__, __LINE__, "PAPI_start", retval);

	do_stuff();

	retval = PAPI_stop(EventSet, &values[use_total]);
	if (retval != PAPI_OK)
		test_fail(__FILE__, __LINE__, "PAPI_stop", retval);
	use_total++;

	retval = PAPI_overflow(EventSet, PAPI_event, 0, PAPI_OVERFLOW_FORCE_SW, handler);
	if (retval != PAPI_OK)
		test_fail(__FILE__, __LINE__, "PAPI_overflow", retval);

	if (!TESTS_QUIET) {
		if ((retval = PAPI_event_code_to_name(PAPI_event, event_name)) != PAPI_OK)
			test_fail(__FILE__, __LINE__, "PAPI_event_code_to_name", retval);

		printf("Test case: Software overflow of various types with 1 event in set.\n");
		printf("------------------------------------------------------------------------------\n");
		printf("Threshold for overflow is: %d\n", mythreshold);
		printf("------------------------------------------------------------------------------\n");

		printf("Test type   : %11s%13s%13s%13s%13s\n", "Reference", "Hardware", "ITIMER_PROF", "ITIMER_VIRT", "ITIMER_REAL");
		printf("%-12s: %11lld%13lld%13lld%13lld%13lld\n",info.symbol,values[0],values[1],values[2],values[3],values[4]);
		printf("Overflows   : %11d%13d%13d%13d%13d\n", total[0],total[1],total[2],total[3],total[4]);
		printf("------------------------------------------------------------------------------\n");

		printf("Verification:\n");

		printf("Overflow in Column 2 greater than or equal to overflows in Columns 3, 4, 5\n");
		printf("Overflow in Columns 3, 4, 5 greater than 0\n");
	}

	hard_min = (long long) ((values[0] * (1.0 - HARD_TOLERANCE)) / (long long) mythreshold);
	hard_max = (long long) ((values[0] * (1.0 + HARD_TOLERANCE)) / (long long) mythreshold);
	soft_min = (long long) ((values[0] * (1.0 - SOFT_TOLERANCE)) / (long long) mythreshold);
	soft_max = (long long) ((values[0] * (1.0 + SOFT_TOLERANCE)) / (long long) mythreshold);
	if (total[1] > hard_max || total[1] < hard_min)
		test_fail(__FILE__, __LINE__, "Hardware Overflows outside limits", 1);

	if (total[2] > soft_max || total[3] > soft_max || total[4] > soft_max)
		test_fail(__FILE__, __LINE__, "Software Overflows exceed theoretical maximum", 1);

	if (total[2] < soft_min || total[3] < soft_min || total[4] < soft_min)
		printf("WARNING: Software Overflow occuring but suspiciously low\n");

	if ((total[2] == 0) || (total[3] == 0) || (total[4] == 0))
		test_fail(__FILE__, __LINE__, "Software Overflows", 1);

	test_pass(__FILE__, NULL, 0);
	exit(1);
}


text:
/**
 * //TODO add comments.
 *
 * @author Denis Semikhatov (maslo111@rambler.ru)
 * @version $Id$
 * @since 0.1
 */
package ru.dionisius.service;


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

/** @file
    		This is the race information structures.
    @author	Eric Espie
    @version	$Id: raceman.h,v 1.28.2.2 2012/02/14 23:42:20 berniw Exp $
    @ingroup	raceinfo
*/

#ifndef _RACEMANV1_H_
#define _RACEMANV1_H_

#include <tgf.h>
#include <car.h>
#include <track.h>
#include <graphic.h>
#include <simu.h>

#define RCM_IDENT 0

struct RmInfo;

typedef int (*tfRmRunState) (struct RmInfo *);

#define RM_SYNC			0x00000001
#define RM_ASYNC		0x00000002

#define RM_END_RACE		0x00000010
#define RM_CONTINUE_RACE	0x00000020

#define RM_NEXT_STEP		0x00000100
#define RM_NEXT_RACE		0x00000200
#define RM_NEXT_EVENT		0x00000400

#define RM_ACTIVGAMESCR		0x01000000
#define RM_QUIT			0x40000000

#define RCM_MAX_DT_SIMU		0.002
//#define RCM_MAX_DT_ROBOTS	0.02
//////// by Yunzhu ////////
#define RCM_MAX_DT_ROBOTS 0.1
//////// by Yunzhu ////////

/** General info on current race */
typedef struct {
    int			ncars;		/**< number of cars */
    int			totLaps;	/**< total laps */
    int			state;
#define RM_RACE_RUNNING		0X00000001
#define RM_RACE_FINISHING	0X00000002
#define RM_RACE_ENDED		0X00000004
#define RM_RACE_STARTING	0X00000008
#define RM_RACE_PRESTART	0X00000010
#define RM_RACE_PAUSED		0X40000000
    int			type;		/**< Race type */
#define RM_TYPE_PRACTICE	0 /* Please keep the order */
#define RM_TYPE_QUALIF		1
#define RM_TYPE_RACE		2
    int                 maxDammage;
    unsigned long	fps;
} tRaceAdmInfo;

#define _ncars		raceInfo.ncars
#define _totLaps	raceInfo.totLaps
#define _raceState	raceInfo.state
#define _raceType	raceInfo.type
#define _maxDammage	raceInfo.maxDammage

/** cars situation used to inform the GUI and the drivers */
typedef struct Situation {
    tRaceAdmInfo	raceInfo;
    double		deltaTime;
    double		currentTime;	/**< current time in sec since the beginning of the simulation */
    int			nbPlayers;	/**< number of human player in local (splitted screen) */
    tCarElt		**cars;		/**< list of cars */
} tSituation;

/** Race Engine */
typedef struct
{
    tTrackItf	trackItf;
    tGraphicItf	graphicItf;
    tSimItf	simItf;
} tRaceModIft;

#define RE_STATE_CONFIG			0
#define RE_STATE_EVENT_INIT		1
#define RE_STATE_PRE_RACE		3
#define RE_STATE_RACE_START		5
#define RE_STATE_RACE			6
#define RE_STATE_RACE_STOP		7
#define RE_STATE_RACE_END		8
#define RE_STATE_POST_RACE		9
#define RE_STATE_EVENT_SHUTDOWN		11
#define RE_STATE_SHUTDOWN		12
#define RE_STATE_ERROR			13
#define RE_STATE_EXIT			14

/** Race Engine Car Information about the race */
typedef struct
{
    tTrkLocPos	prevTrkPos;
    tdble	sTime;
    int		lapFlag;
    char	*raceMsg;
    double	totalPitTime;
    double	startPitTime;
    tdble	topSpd;
    tdble	botSpd;
    tdble	fuel;
} tReCarInfo;

/** Race Engine Information.
   @image	html raceenginestate.gif
 */
typedef struct
{
    int			state;
    void		*param;
    tRaceModIft		itf;
    void		*gameScreen;
    void		*menuScreen;
    char		*filename;
    const char *name;
    const char *raceName;
    tReCarInfo		*carInfo;
    double		curTime;
    double		lastTime;
    double		timeMult;
    int			running;
#define RM_DISP_MODE_NORMAL	0
#define RM_DISP_MODE_CAPTURE	1
#define RM_DISP_MODE_NONE	2
#define RM_DISP_MODE_CONSOLE	4
    int			displayMode;
    int			refreshDisplay;
} tRaceEngineInfo;

#define _reState	raceEngineInfo.state
#define _reParam	raceEngineInfo.param
#define _reRacemanItf	raceEngineInfo.itf.racemanItf
#define _reTrackItf	raceEngineInfo.itf.trackItf
#define _reGraphicItf	raceEngineInfo.itf.graphicItf
#define _reSimItf	raceEngineInfo.itf.simItf
#define _reGameScreen	raceEngineInfo.gameScreen
#define _reMenuScreen	raceEngineInfo.menuScreen
#define _reFilename	raceEngineInfo.filename
#define _reName		raceEngineInfo.name
#define _reRaceName	raceEngineInfo.raceName
#define _reCarInfo	raceEngineInfo.carInfo
#define _reCurTime	raceEngineInfo.curTime
#define _reTimeMult	raceEngineInfo.timeMult
#define _reRunning	raceEngineInfo.running
#define _reLastTime	raceEngineInfo.lastTime
#define _displayMode	raceEngineInfo.displayMode
#define _refreshDisplay	raceEngineInfo.refreshDisplay

#define RM_PNST_DRIVETHROUGH	0x00000001
#define RM_PNST_STOPANDGO	0x00000002
#define RM_PNST_STOPANDGO_OK	0x00000004
#define RM_PNST_SPD		0x00010000
#define RM_PNST_STNGO		0x00020000

typedef struct RmCarRules
{
    int			ruleState;
} tRmCarRules;

typedef struct RmMovieCapture
{
    int		enabled;
    int		state;
    double	deltaSimu;
    double	deltaFrame;
    double	lastFrame;
    const char *outputBase;
    int		currentCapture;
    int		currentFrame;
} tRmMovieCapture;

/**
 * Race Manager General Info
 */
typedef struct RmInfo
{
    tCarElt		*carList;	/**< List of all the cars racing */
    tSituation		*s;		/**< Situation during race */
    tTrack		*track;		/**< Current track */
    void		*params;	/**< Raceman parameters */
    void		*results;	/**< Race results */
    tModList		**modList;	/**< drivers loaded */
    tRmCarRules		*rules;		/**< by car rules */
    tRaceEngineInfo	raceEngineInfo;
    tRmMovieCapture	movieCapture;
} tRmInfo;

/*
 * Parameters name definitions for Race Managers
 */
#define RM_SECT_HEADER		"Header"
#define RM_SECT_DRIVERS		"Drivers"
#define RM_SECT_STARTINGGRID	"Starting Grid"
#define RM_SECT_RACES		"Races"
#define RM_SECT_TRACKS		"Tracks"
#define RM_SECT_CONF		"Configuration"
#define RM_SECT_OPTIONS		"Options"
#define RM_SECT_POINTS		"Points"

#define RM_SECT_DRIVERS_RACING	"Drivers Start List"

#define RM_ATTR_CUR_CONF	"current configuration"
#define RM_ATTR_START_ORDER	"starting order"
#define RM_ATTR_ALLOW_RESTART	"restart"
#define RM_ATTR_MUST_COMPLETE	"must complete"
#define RM_ATTR_SPLASH_MENU	"splash menu"
#define RM_ATTR_DISP_START_GRID	"display starting grid"

#define RM_ATTR_MAXNUM		"maximum number"
#define RM_ATTR_MAX_DRV		"maximum drivers"
#define RM_ATTR_CAR		"car"

#define RM_ATTR_PRIO		"priority"
#define RM_ATTR_NAME		"name"
#define RM_ATTR_DRVNAME		"driver name"
#define RM_ATTR_CATEGORY	"category"
#define RM_ATTR_DESCR		"description"
#define RM_ATTR_BGIMG		"menu image"
#define RM_ATTR_RUNIMG		"run image"
#define RM_ATTR_STARTIMG	"start image"

#define RM_ATTR_MODULE		"module"
#define RM_ATTR_IDX		"idx"
#define RM_ATTR_FOCUSED		"focused module"
#define RM_ATTR_FOCUSEDIDX	"focused idx"
#define RM_ATTR_DISPMODE	"display mode"
#define RM_ATTR_DISPRES		"display results"

#define RM_ATTR_TIMESTEP	"time step"

#define RM_ATTR_TYPE		"type"
#define RM_ATTR_RACE		"race"
#define RM_ATTR_ROWS		"rows"
#define RM_ATTR_TOSTART		"distance to start"
#define RM_ATTR_COLDIST		"distance between columns"
#define RM_ATTR_COLOFFSET	"offset within a column"
#define RM_ATTR_INITSPEED	"initial speed"
#define RM_ATTR_INITHEIGHT	"initial height"
#define RM_ATTR_SHOW_RACE	"show race"
#define RM_ATTR_MAX_DMG		"maximum dammage"
#define RM_ATTR_DISTANCE	"distance"
#define RM_ATTR_LAPS		"laps"
#define RM_ATTR_QUAL_LAPS	"Qualification laps"
#define RM_ATTR_POLE		"pole position side"
#define RM_ATTR_CARSPERPIT	"cars per pit"

#define RM_ATTR_POINTS		"points"

#define RM_VAL_TRACKSEL		"track select"
#define RM_VAL_DRVSEL		"drivers select"
#define RM_VAL_RACECONF		"race config"
#define RM_VAL_CONFRACELEN	"race length"
#define RM_VAL_CONFDISPMODE	"display mode"

#define RM_VAL_DRV_LIST_ORDER	"drivers list"
#define RM_VAL_LAST_RACE_ORDER	"last race"
#define RM_VAL_LAST_RACE_RORDER	"last race reversed"

#define RM_VAL_RACE		"race"
#define RM_VAL_QUALIF		"qualifications"
#define RM_VAL_PRACTICE		"practice"

#define RM_VAL_YES		"yes"
#define RM_VAL_NO		"no"

#define RM_VAL_VISIBLE		"normal"
#define RM_VAL_INVISIBLE	"results only"

#define RM_SECT_MOVIE_CAPTURE	"Movie Capture"

#define RM_ATT_CAPTURE_ENABLE	"enable capture"
#define RM_ATT_CAPTURE_FPS	"fps"
#define RM_ATT_CAPTURE_OUT_DIR	"output directory"

/* RESULTS */

#define RE_SECT_HEADER		"Header"
#define RE_ATTR_DATE		"date"
#define RE_ATTR_TYPE		"race"

#define RE_SECT_CURRENT		"Current"
#define RE_ATTR_CUR_RACE	"current race"
#define RE_ATTR_CUR_TRACK	"current track"
#define RE_ATTR_CUR_DRIVER	"current driver"

#define RE_SECT_DRIVERS		"Drivers"
#define RE_SECT_DRIVER		"Driver"
#define RE_ATTR_DLL_NAME	"dll name"
#define RE_ATTR_INDEX		"index"

#define RE_SECT_STANDINGS	"Standings"

#define RE_SECT_RESULTS		"Results"
#define RE_SECT_STARTINGGRID	"Starting Grid"

#define RE_SECT_QUALIF		"Qualifications"

#define RE_SECT_FINAL		"Final"

#define RE_SECT_RANK		"Rank"

#define RE_ATTR_NAME		"name"
#define RE_ATTR_CAR		"car"
#define RE_ATTR_MODULE		"module"
#define RE_ATTR_IDX		"idx"
#define RE_ATTR_LAPS		"laps"
#define RE_ATTR_BEST_LAP_TIME	"best lap time"
#define RE_ATTR_TIME		"time"
#define RE_ATTR_TOP_SPEED	"top speed"
#define RE_ATTR_BOT_SPEED	"bottom speed"
#define RE_ATTR_DAMMAGES	"dammages"
#define RE_ATTR_NB_PIT_STOPS	"pits stops"
#define RE_ATTR_POINTS		"points"

#endif /* _RACEMANV1_H_ */


text:
@extends('layouts.app')

@section('title')
	User Profile - {{ $user->name }}
@endsection

@section('content')

		{!! avatar($user)->image()->label('Member since '.$user->present()->created('relative'))->large() !!}

	@forelse ($activities as $date => $activity)

			{{ $date }}

			@foreach ($activity as $record)
				@include ("pages.profiles.activities.{$record->type}", ['activity' => $record])
			@endforeach

	@empty
		{!! alert('warning', "No activity found.") !!}
	@endforelse
@endsection

@section('js')

@endsection


text:
'use strict';

/**
 * @ngdoc function
 * @name testAngularApp.controller:ModalInstanceCtrl
 * @description
 * # ModalInstanceCtrl
 * Controller of the testAngularApp
 */
angular.module('testAngularApp')
  .controller('ModalInstanceCtrl', function($scope, $modalInstance, show) {
  	$scope.awesomeThings = [
      'HTML5 Boilerplate',
      'AngularJS',
      'Karma'
    ];

    $scope.show = show;

    $scope.ok = function() {
      $modalInstance.close($scope.show);
    };

    $scope.cancel = function() {
      $modalInstance.dismiss('cancel');
    };
  });


text:
<lift:surround with="default" at="content">

Lift allows you to create model objects that
map themselves to and from the database.  Here's an example of
a "User" model object.

	There are <database:count ></database:count> records in the "Person" table.  The first one is <database:first></database:first>.
	Press <database:submit></database:submit> to create more records.

/**
 * The singleton that has methods for accessing the database
 */
object User extends User with KeyedMetaMapper[Long, User] {
  override def dbTableName = "users" // define the DB table name

  // define the order fields will appear in forms and output
  override lazy val fieldOrder = List(id, firstName, lastName,
                                      email, password, textArea)
}

/**
 * An O-R mapped "User" class that includes first name, last name,
 * password and we add a "Personal Essay" to it
 */
class User extends ProtoUser[User] {
  def getSingleton = User

  // define an additional field for a personal essay
  object textArea extends MappedTextarea(this, 2048) {
    override def textareaRows  = 10
    override def textareaCols = 50
    override def displayName = "Personal Essay"
  }
}

For this little bit of work, we get a complete user with
first name, last name, password, email, and a personal essay.

Each of the fields knows how to validate itself.  The
User (and any other "Mapped" class) knows how to Create,
Update, Read, and Delete itself from the database.  It knows
how to convert itself to a string, to XML, and even generate
HTML forms for itself.

</lift:surround>


text:
About Openlabs Technologies and Consulting Private Limited
##########################################################

    Openlabs Technologies and Consulting Private Limited is a global Information Technology and Management Consulting Company that helps small and medium businesses achieve high efficiency with cost effective business solutions. With customers and partners in four continents, Openlabs designs and delivers technology enabled innovative business solutions that addresses the needs of small and medium enterprises. Openlabs provides end to end solutions to businessess using a range of Free and Opensource Solutions (FOSS) Implemented by a team of highly skilled workforce comprising of domain and business experts.

    The software division of Openlabs is a specialised division of Rapid Application Development of business application with a proven expertise in OpenERP (and OpenObject). Tryton and Django.

Technical Support
"""""""""""""""""

    Asia Pacific and Middle East +91 9999775161 (India)

    America and Europe +1 786 247 1317 (USA)

    Email: support@openlabs.co.in


text:
package org.biopax.paxtools.pattern.miner;

import org.biopax.paxtools.controller.PathAccessor;
import org.biopax.paxtools.model.BioPAXElement;
import org.biopax.paxtools.model.level3.Pathway;
import org.biopax.paxtools.model.level3.PublicationXref;

import java.util.*;

/**
 * @author Ozgun Babur
 */
public class SIFInteraction implements Comparable
{
	public Set<BioPAXElement> sourceERs;
	public Set<BioPAXElement> targetERs;
	public Set<BioPAXElement> sourcePEs;
	public Set<BioPAXElement> targetPEs;
	public String sourceID;
	public String targetID;
	public SIFType type;
	public Set<BioPAXElement> mediators;

	public SIFInteraction(BioPAXElement sourceER, BioPAXElement targetER, SIFType type,
		Set<BioPAXElement> mediators, Set<BioPAXElement> sourcePEs, Set<BioPAXElement> targetPEs,
		IDFetcher fetcher)
	{
		sourceID = fetcher.fetchID(sourceER);
		targetID = fetcher.fetchID(targetER);

		this.sourceERs = new HashSet<BioPAXElement>();
		this.targetERs = new HashSet<BioPAXElement>();

		if (!type.isDirected())
		{
			if (sourceID != null && targetID != null && sourceID.compareTo(targetID) > 0)
			{
				String tempID = sourceID;
				sourceID = targetID;
				targetID = tempID;

				BioPAXElement temp = sourceER;
				sourceER = targetER;
				targetER = temp;
			}
		}

		this.sourceERs.add(sourceER);
		this.targetERs.add(targetER);
		this.type = type;

		this.mediators = mediators;
		this.sourcePEs = sourcePEs;
		this.targetPEs = targetPEs;
	}

	public boolean hasIDs()
	{
		return sourceID != null && targetID != null;
	}

	@Override
	public int hashCode()
	{
		return sourceID.hashCode() + targetID.hashCode() + type.hashCode();
	}

	@Override
	public boolean equals(Object obj)
	{
		if (obj instanceof SIFInteraction)
		{
			SIFInteraction i = (SIFInteraction) obj;

			return i.type.equals(type) && i.sourceID.equals(sourceID) && i.targetID.equals(targetID);
		}

		return false;
	}

	@Override
	public int compareTo(Object o)
	{
		if (o instanceof SIFInteraction)
		{
			SIFInteraction i = (SIFInteraction) o;

			return (sourceID + targetID + type.getTag()).compareTo(
				i.sourceID + i.targetID + i.type.getTag());
		}

		return 0;
	}

	/**
	 * Merges publications of the parameter equivalent sif with this one.
	 * @param equivalent the equivalent sif interaction to get its publications.
	 */
	public void mergeWith(SIFInteraction equivalent)
	{
		if (!this.equals(equivalent))
			throw new IllegalArgumentException("SIF interactions are not equivalent.");

		sourceERs.addAll(equivalent.sourceERs);
		targetERs.addAll(equivalent.targetERs);

		sourcePEs.addAll(equivalent.sourcePEs);
		targetPEs.addAll(equivalent.targetPEs);

		if (mediators == null) mediators = equivalent.mediators;
		else if (equivalent.mediators != null)
		{
			mediators.addAll(equivalent.mediators);
		}
	}

	@Override
	public String toString()
	{
		return toString(false);
	}

	public String toString(boolean withMediators)
	{
		String s = sourceID + "\t" + type.getTag() + "\t" + targetID;

		if (withMediators)
		{
			String m = getMediatorsInString();
			if (!m.isEmpty()) s += "\t" + m;
		}

		return s;
	}

	/**
	 * Collects IDs of mediators.
	 * @return mediator IDs
	 */
	public List<String> getMediatorIDs()
	{
		List<String> ids = new ArrayList<String>(mediators.size());

		for (BioPAXElement ele : mediators)
		{
			ids.add(ele.getRDFId());
		}
		return ids;
	}

	/**
	 * Gets the mediator IDs in a String with a space between each ID.
	 */
	public String getMediatorsInString()
	{
		String m = "";
		for (String mid : getMediatorIDs())
		{
			m+= " " + mid;
		}
		return m.trim();
	}

	/**
	 * Collects PMIDs from mediators.
	 * @return PMIDs
	 */
	public List<String> getPubmedIDs()
	{
		if (mediators == null) return Collections.emptyList();

		Set<String> set = harvestPMIDs(harvestPublicationXrefs(
			mediators.toArray(new BioPAXElement[mediators.size()])));

		List<String> list = new ArrayList<String>(set);
		Collections.sort(list);

		return list;
	}

	private static final PathAccessor xrefAcc = new PathAccessor("XReferrable/xref:PublicationXref");
	private static final PathAccessor evidAcc = new PathAccessor("Observable/evidence/xref:PublicationXref");

	/**
	 * Collects publication xrefs of the given elements.
	 * @param ele element array
	 * @return publication xrefs
	 */
	private Set<PublicationXref> harvestPublicationXrefs(BioPAXElement... ele)
	{
		Set<PublicationXref> set = new HashSet<PublicationXref>();

		for (Object o : xrefAcc.getValueFromBeans(Arrays.asList(ele)))
		{
			set.add((PublicationXref) o);
		}
		for (Object o : evidAcc.getValueFromBeans(Arrays.asList(ele)))
		{
			set.add((PublicationXref) o);
		}
		return set;
	}

	/**
	 * Collects PubMed IDs fromt the given publication xrefs.
	 * @param xrefs publication xrefs
	 * @return PMIDs
	 */
	private Set<String> harvestPMIDs(Set<PublicationXref> xrefs)
	{
		Set<String> set = new HashSet<String>();

		for (PublicationXref xref : xrefs)
		{
			if (xref.getDb() != null && xref.getDb().equalsIgnoreCase("pubmed"))
				if (xref.getId() != null && !xref.getId().isEmpty())
					set.add(xref.getId());
		}
		return set;
	}

	private static final PathAccessor pathwayAcc1 = new PathAccessor("Interaction/pathwayComponentOf*");
	private static final PathAccessor pathwayAcc2 = new PathAccessor("Interaction/stepProcessOf/pathwayOrderOf");

	/**
	 * Collects Pathway objects that the Interactions among the mediators are members.
	 * @return related pathways
	 */
	public Set<Pathway> getPathways()
	{
		Set<Pathway> set = new HashSet<Pathway>();

		for (Object o : pathwayAcc1.getValueFromBeans(mediators))
		{
			set.add((Pathway) o);
		}
		for (Object o : pathwayAcc2.getValueFromBeans(mediators))
		{
			set.add((Pathway) o);
		}

		return set;
	}

	/**
	 * Collects the names of the related pathways.
	 * @return pathway names
	 */
	public List<String> getPathwayNames()
	{
		Set<Pathway> set = getPathways();
		List<String> names = new ArrayList<String>();

		for (Pathway p : set)
		{
			String name = p.getDisplayName();
			if (!names.contains(name)) names.add(name);
		}

		Collections.sort(names);
		return names;
	}

	private static final PathAccessor dataSourceAcc = new PathAccessor("Entity/dataSource/displayName");

	/**
	 * Collects data source names (Provenance display names) of mediators.
	 * @return related data sources
	 */
	public Set<String> getDataSources()
	{
		Set<String> set = new HashSet<String>();

		for (Object o : dataSourceAcc.getValueFromBeans(mediators))
		{
			set.add((String) o);
		}

		return set;
	}

	private static final PathAccessor locAcc = new PathAccessor("PhysicalEntity/cellularLocation/term");

	/**
	 * Collects cellular location terms of target objects.
	 * @return cellular locations
	 */
	public Set<String> getCellularLocationsOfTarget()
	{
		return getCellularLocations(targetPEs);
	}

	/**
	 * Collects cellular location terms of source objects.
	 * @return cellular locations
	 */
	public Set<String> getCellularLocationsOfSource()
	{
		return getCellularLocations(sourcePEs);
	}

	/**
	 * Collects cellular location terms of related objects.
	 * @return cellular locations
	 */
	private Set<String> getCellularLocations(Set<BioPAXElement> eles)
	{
		Set<String> set = new HashSet<String>();

		for (Object o : locAcc.getValueFromBeans(eles))
		{
			set.add((String) o);
		}

		return set;
	}

	//---- Section: Static methods ----------------------------------------------------------------|

	/**
	 * Collects and sorts sourceID and targetID of the given collection of sif interactions.
	 * @param sifInts interactions to consider
	 * @param type types of interest, all types accepted if empty
	 * @return sorted source and target IDS
	 */
	public static List<String> getSortedGeneNames(Collection<SIFInteraction> sifInts,
		SIFType... type)
	{
		Set<String> genes = new HashSet<String>();
		Set<SIFType> types = new HashSet<SIFType>(Arrays.asList(type));

		// collect gene names

		for (SIFInteraction sifInt : sifInts)
		{
			if (!types.isEmpty() && !types.contains(sifInt.type)) continue;

			genes.add(sifInt.sourceID);
			genes.add(sifInt.targetID);
		}

		// sort all gene names

		List<String> names = new ArrayList<String>(genes);
		Collections.sort(names);

		return names;
	}

	/**
	 * Converts the given collection of interactions into an adjacency matrix.
	 * @param sifInts interactions to consider
	 * @param type types of interest, all types accepted if empty
	 * @return the sif network as adjacency matrix
	 */
	public static boolean[][] convertToAdjacencyMatrix(Collection<SIFInteraction> sifInts,
		SIFType... type)
	{
		Set<SIFType> types = new HashSet<SIFType>(Arrays.asList(type));

		// collect gene names
		List<String> names = getSortedGeneNames(sifInts, type);

		// record name indexes for efficient lookup

		Map<String, Integer> name2ind = new HashMap<String, Integer>();
		int i = 0;
		for (String name : names)
		{
			name2ind.put(name, i++);
		}

		// generate adjacency matrix

		boolean[][] matrix = new boolean[names.size()][names.size()];
		for (boolean[] m : matrix) Arrays.fill(m, false);

		for (SIFInteraction sifInt : sifInts)
		{
			if (!types.isEmpty() && !types.contains(sifInt.type)) continue;

			matrix[name2ind.get(sifInt.sourceID)][name2ind.get(sifInt.targetID)] = true;

			if (!sifInt.type.isDirected())
			{
				matrix[name2ind.get(sifInt.targetID)][name2ind.get(sifInt.sourceID)] = true;
			}
		}

		return matrix;
	}
}


text:
<template>

Edit Article Material

    <require from="./data-form"></require>
    <block>
        <data-form data.bind="data" error.bind="error"></data-form>

            <button class="btn btn-default" click.delegate="view()">Back</button>
            <button class="btn btn-success" click.delegate="save()">Save</button>

    </block>
</template>


text:
import res_users
import crm_stage
import crm_lead
import sales_team
import models
import calendar_event
import report
import wizard
import res_partner
import res_config
import base_partner_merge
import web_planner


text:
require 'spec_helper'

module Philographer
  class Client
    describe URLBuilder do

      let(:config) {
        Configuration.new
      }

      let(:builder) { URLBuilder.new(config, Class.new) }

      describe '.login_url(config)' do
        let(:url) { URLBuilder.login_url(config) }

        it 'must return the login information for the specified environment' do
          url.must_equal "https://demo.docusign.net/restapi/v2/login_information"
        end
      end

      describe '#base_url' do
        describe "when the account id is unknown" do
          before do
            # load up our credentials excluding the account_id
            URLBuilder.base_url = nil
            load_credentials(false)
          end

          it "must ask the login info for the default account's id" do
            url = VCR.use_cassette('login_information') {
              builder.base_url
            }
            url.must_match /\/accounts\/1234\/$/
          end

          it "must set the config object's account_id attribute with the found value" do
            url = VCR.use_cassette('login_information') {
              builder.base_url
            }
            config.account_id.must_equal '1234'
          end
        end

        describe 'with a known account id' do
          before do
            URLBuilder.base_url = nil
            config.account_id = 'REGEX_ME'
          end

          it 'must return a url with the correct domain' do
            builder.base_url.must_match /^https:\/\/demo.docusign.net\//
          end

          it 'must return a url with the specified account number' do
            builder.base_url.must_match /\/accounts\/REGEX_ME\/$/
          end

          it 'must include the api specification' do
            builder.base_url.must_match /\/restapi\/v2\//
          end
        end
      end

      describe '#build!' do
        before do
          config.account_id = '12345'
        end

        it 'must return the correct url for an envelope' do
          builder = URLBuilder.new(config, Philographer::Envelope)
          url = builder.build!
          url.must_match /\/envelopes$/
        end

        it 'must return the correct url for a template' do
          builder = URLBuilder.new(config, Philographer::Template)
          url = builder.build!
          url.must_match /\/templates$/
        end
      end
    end
  end
end


text:
@implementation ReadCommentCell

- (instancetype)initWithStyle:(UITableViewCellStyle)style reuseIdentifier:(NSString *)reuseIdentifier
{
    if ([super initWithStyle:style reuseIdentifier:reuseIdentifier]) {
        self.headImage = [[UIImageView alloc]initWithFrame:CGRectMake(20, 15, 60, 60)];
        self.headImage.image = [UIImage imageNamed:@"icon"];
        [self.contentView addSubview:_headImage];

        self.nameLabel = [[UILabel alloc]initWithFrame:CGRectMake(20 + 60 + 10, 15 + 5, 250 * Fit, 20)];
        self.nameLabel.text = @"摄心";
        [self.contentView addSubview:_nameLabel];

        self.timeLabel = [[UILabel alloc]initWithFrame:CGRectMake(20 + 60 + 10, 15 + 5 + 20 + 10, 200 * Fit, 20)];
        self.timeLabel.font = [UIFont systemFontOfSize:14 * Fit];
        self.timeLabel.textColor = [UIColor lightGrayColor];
        self.timeLabel.text = @"15:15";
        [self.contentView addSubview:_timeLabel];

        self.detailLabel = [[UILabel alloc]initWithFrame:CGRectMake(20, 15 + 60 + 15, KScreenWidth - 40, 40)];
        self.detailLabel.font = [UIFont systemFontOfSize:15 * Fit];
        self.detailLabel.textColor = [UIColor grayColor];
        self.detailLabel.text = @"fahkfhalkhfklwhlfhsdjkfhklahlkshfl";
        self.detailLabel.numberOfLines = 0;
        [self.contentView addSubview:_detailLabel];

        self.line = [[UIView alloc]initWithFrame:CGRectMake(0, 15 + 60 + 15 + 40 + 22, KScreenWidth, 1)];
        self.line.backgroundColor = [UIColor grayColor];
        [self.contentView addSubview:_line];

        self.deleteButton = [UIButton buttonWithType:UIButtonTypeSystem];
        [self.deleteButton setTitle:@"删除" forState:UIControlStateNormal];
        self.deleteButton.frame = CGRectMake(20 + 60 + 10 + 10 + 200 * Fit, 15 + 5 + 20 + 10, 40 * Fit, 20);
        self.deleteButton.hidden = YES;
        [self.contentView addSubview:_deleteButton];
    }
    return self;
}

- (void)cellConfigureModel:(ReadCommentModel *)model
{
    [self.headImage sd_setImageWithURL:[NSURL URLWithString:model.icon]];
    self.nameLabel.text = model.uname;
    self.timeLabel.text = model.addtime_f;
    CGRect bounds = [model.content boundingRectWithSize:CGSizeMake(KScreenWidth - 40, 1000) options:NSStringDrawingUsesLineFragmentOrigin attributes:[NSDictionary dictionaryWithObject:[UIFont systemFontOfSize:15 * Fit] forKey:NSFontAttributeName] context:nil];
    self.detailLabel.frame = CGRectMake(20, 15 + 60 + 15, KScreenWidth - 40, bounds.size.height);
    self.detailLabel.text = model.content;
    self.line.frame = CGRectMake(0, 15 + 60 + 15 + bounds.size.height + 22, KScreenWidth, 1);
    NSString *name = [[NSUserDefaults standardUserDefaults] stringForKey:@"user"];
    LandingModel *model1 = [LandingDB findUserInfoWithName:name];
    if ([model1.uname isEqualToString:model.uname]) {
        self.deleteButton.hidden = NO;
    }
    else {
        self.deleteButton.hidden = YES;
    }
}

+ (CGFloat)heightOfRowWithModel:(ReadCommentModel *)model
{
    CGRect bounds = [model.content boundingRectWithSize:CGSizeMake(KScreenWidth - 40, 1000) options:NSStringDrawingUsesLineFragmentOrigin attributes:[NSDictionary dictionaryWithObject:[UIFont systemFontOfSize:15 * Fit] forKey:NSFontAttributeName] context:nil];
    return 15 + 60 + 15 + bounds.size.height + 22 + 1;
}

- (void)awakeFromNib {
    // Initialization code
}

- (void)setSelected:(BOOL)selected animated:(BOOL)animated {
    [super setSelected:selected animated:animated];

    // Configure the view for the selected state
}

@end


text:
package org.gluecoders.library.config;

import org.junit.Test;
import org.junit.runner.RunWith;
import org.junit.runners.BlockJUnit4ClassRunner;

import static org.junit.Assert.assertNotNull;

/**
 * Created by Anand_Rajneesh on 6/16/2017.
 */
@RunWith(BlockJUnit4ClassRunner.class)
public class OvalTest {

    @Test
    public void testValidator(){
        assertNotNull(new Oval().ovalValidator());
    }
}


text:
//== SMTConstraintManager.h -------------------------------------*- C++ -*--==//
//
// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
// See https://llvm.org/LICENSE.txt for license information.
// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
//
//===----------------------------------------------------------------------===//
//
//  This file defines a SMT generic API, which will be the base class for
//  every SMT solver specific class.
//
//===----------------------------------------------------------------------===//

#ifndef LLVM_CLANG_STATICANALYZER_CORE_PATHSENSITIVE_SMTCONSTRAINTMANAGER_H
#define LLVM_CLANG_STATICANALYZER_CORE_PATHSENSITIVE_SMTCONSTRAINTMANAGER_H

#include "clang/Basic/JsonSupport.h"
#include "clang/Basic/TargetInfo.h"
#include "clang/StaticAnalyzer/Core/PathSensitive/RangedConstraintManager.h"
#include "clang/StaticAnalyzer/Core/PathSensitive/SMTConv.h"

typedef llvm::ImmutableSet<
    std::pair<clang::ento::SymbolRef, const llvm::SMTExpr *>>
    ConstraintSMTType;
REGISTER_TRAIT_WITH_PROGRAMSTATE(ConstraintSMT, ConstraintSMTType)

namespace clang {
namespace ento {

class SMTConstraintManager : public clang::ento::SimpleConstraintManager {
  mutable llvm::SMTSolverRef Solver = llvm::CreateZ3Solver();

public:
  SMTConstraintManager(clang::ento::SubEngine *SE, clang::ento::SValBuilder &SB)
      : SimpleConstraintManager(SE, SB) {}
  virtual ~SMTConstraintManager() = default;

  //===------------------------------------------------------------------===//
  // Implementation for interface from SimpleConstraintManager.
  //===------------------------------------------------------------------===//

  ProgramStateRef assumeSym(ProgramStateRef State, SymbolRef Sym,
                            bool Assumption) override {
    ASTContext &Ctx = getBasicVals().getContext();

    QualType RetTy;
    bool hasComparison;

    llvm::SMTExprRef Exp =
        SMTConv::getExpr(Solver, Ctx, Sym, &RetTy, &hasComparison);

    // Create zero comparison for implicit boolean cast, with reversed
    // assumption
    if (!hasComparison && !RetTy->isBooleanType())
      return assumeExpr(
          State, Sym,
          SMTConv::getZeroExpr(Solver, Ctx, Exp, RetTy, !Assumption));

    return assumeExpr(State, Sym, Assumption ? Exp : Solver->mkNot(Exp));
  }

  ProgramStateRef assumeSymInclusiveRange(ProgramStateRef State, SymbolRef Sym,
                                          const llvm::APSInt &From,
                                          const llvm::APSInt &To,
                                          bool InRange) override {
    ASTContext &Ctx = getBasicVals().getContext();
    return assumeExpr(
        State, Sym, SMTConv::getRangeExpr(Solver, Ctx, Sym, From, To, InRange));
  }

  ProgramStateRef assumeSymUnsupported(ProgramStateRef State, SymbolRef Sym,
                                       bool Assumption) override {
    // Skip anything that is unsupported
    return State;
  }

  //===------------------------------------------------------------------===//
  // Implementation for interface from ConstraintManager.
  //===------------------------------------------------------------------===//

  ConditionTruthVal checkNull(ProgramStateRef State, SymbolRef Sym) override {
    ASTContext &Ctx = getBasicVals().getContext();

    QualType RetTy;
    // The expression may be casted, so we cannot call getZ3DataExpr() directly
    llvm::SMTExprRef VarExp = SMTConv::getExpr(Solver, Ctx, Sym, &RetTy);
    llvm::SMTExprRef Exp =
        SMTConv::getZeroExpr(Solver, Ctx, VarExp, RetTy, /*Assumption=*/true);

    // Negate the constraint
    llvm::SMTExprRef NotExp =
        SMTConv::getZeroExpr(Solver, Ctx, VarExp, RetTy, /*Assumption=*/false);

    ConditionTruthVal isSat = checkModel(State, Sym, Exp);
    ConditionTruthVal isNotSat = checkModel(State, Sym, NotExp);

    // Zero is the only possible solution
    if (isSat.isConstrainedTrue() && isNotSat.isConstrainedFalse())
      return true;

    // Zero is not a solution
    if (isSat.isConstrainedFalse() && isNotSat.isConstrainedTrue())
      return false;

    // Zero may be a solution
    return ConditionTruthVal();
  }

  const llvm::APSInt *getSymVal(ProgramStateRef State,
                                SymbolRef Sym) const override {
    BasicValueFactory &BVF = getBasicVals();
    ASTContext &Ctx = BVF.getContext();

    if (const SymbolData *SD = dyn_cast<SymbolData>(Sym)) {
      QualType Ty = Sym->getType();
      assert(!Ty->isRealFloatingType());
      llvm::APSInt Value(Ctx.getTypeSize(Ty),
                         !Ty->isSignedIntegerOrEnumerationType());

      // TODO: this should call checkModel so we can use the cache, however,
      // this method tries to get the interpretation (the actual value) from
      // the solver, which is currently not cached.

      llvm::SMTExprRef Exp =
          SMTConv::fromData(Solver, SD->getSymbolID(), Ty, Ctx.getTypeSize(Ty));

      Solver->reset();
      addStateConstraints(State);

      // Constraints are unsatisfiable
      Optional<bool> isSat = Solver->check();
      if (!isSat.hasValue() || !isSat.getValue())
        return nullptr;

      // Model does not assign interpretation
      if (!Solver->getInterpretation(Exp, Value))
        return nullptr;

      // A value has been obtained, check if it is the only value
      llvm::SMTExprRef NotExp = SMTConv::fromBinOp(
          Solver, Exp, BO_NE,
          Ty->isBooleanType() ? Solver->mkBoolean(Value.getBoolValue())
                              : Solver->mkBitvector(Value, Value.getBitWidth()),
          /*isSigned=*/false);

      Solver->addConstraint(NotExp);

      Optional<bool> isNotSat = Solver->check();
      if (!isSat.hasValue() || isNotSat.getValue())
        return nullptr;

      // This is the only solution, store it
      return &BVF.getValue(Value);
    }

    if (const SymbolCast *SC = dyn_cast<SymbolCast>(Sym)) {
      SymbolRef CastSym = SC->getOperand();
      QualType CastTy = SC->getType();
      // Skip the void type
      if (CastTy->isVoidType())
        return nullptr;

      const llvm::APSInt *Value;
      if (!(Value = getSymVal(State, CastSym)))
        return nullptr;
      return &BVF.Convert(SC->getType(), *Value);
    }

    if (const BinarySymExpr *BSE = dyn_cast<BinarySymExpr>(Sym)) {
      const llvm::APSInt *LHS, *RHS;
      if (const SymIntExpr *SIE = dyn_cast<SymIntExpr>(BSE)) {
        LHS = getSymVal(State, SIE->getLHS());
        RHS = &SIE->getRHS();
      } else if (const IntSymExpr *ISE = dyn_cast<IntSymExpr>(BSE)) {
        LHS = &ISE->getLHS();
        RHS = getSymVal(State, ISE->getRHS());
      } else if (const SymSymExpr *SSM = dyn_cast<SymSymExpr>(BSE)) {
        // Early termination to avoid expensive call
        LHS = getSymVal(State, SSM->getLHS());
        RHS = LHS ? getSymVal(State, SSM->getRHS()) : nullptr;
      } else {
        llvm_unreachable("Unsupported binary expression to get symbol value!");
      }

      if (!LHS || !RHS)
        return nullptr;

      llvm::APSInt ConvertedLHS, ConvertedRHS;
      QualType LTy, RTy;
      std::tie(ConvertedLHS, LTy) = SMTConv::fixAPSInt(Ctx, *LHS);
      std::tie(ConvertedRHS, RTy) = SMTConv::fixAPSInt(Ctx, *RHS);
      SMTConv::doIntTypeConversion<llvm::APSInt, &SMTConv::castAPSInt>(
          Solver, Ctx, ConvertedLHS, LTy, ConvertedRHS, RTy);
      return BVF.evalAPSInt(BSE->getOpcode(), ConvertedLHS, ConvertedRHS);
    }

    llvm_unreachable("Unsupported expression to get symbol value!");
  }

  ProgramStateRef removeDeadBindings(ProgramStateRef State,
                                     SymbolReaper &SymReaper) override {
    auto CZ = State->get<ConstraintSMT>();
    auto &CZFactory = State->get_context<ConstraintSMT>();

    for (auto I = CZ.begin(), E = CZ.end(); I != E; ++I) {
      if (SymReaper.isDead(I->first))
        CZ = CZFactory.remove(CZ, *I);
    }

    return State->set<ConstraintSMT>(CZ);
  }

  void printJson(raw_ostream &Out, ProgramStateRef State, const char *NL = "\n",
                 unsigned int Space = 0, bool IsDot = false) const override {
    ConstraintSMTType Constraints = State->get<ConstraintSMT>();

    Indent(Out, Space, IsDot) << "\"constraints\": ";
    if (Constraints.isEmpty()) {
      Out << "null," << NL;
      return;
    }

    ++Space;
    Out << '[' << NL;
    for (ConstraintSMTType::iterator I = Constraints.begin();
         I != Constraints.end(); ++I) {
      Indent(Out, Space, IsDot)
          << "{ \"symbol\": \"" << I->first << "\", \"range\": \"";
      I->second->print(Out);
      Out << "\" }";

      if (std::next(I) != Constraints.end())
        Out << ',';
      Out << NL;
    }

    --Space;
    Indent(Out, Space, IsDot) << "],";
  }

  bool haveEqualConstraints(ProgramStateRef S1,
                            ProgramStateRef S2) const override {
    return S1->get<ConstraintSMT>() == S2->get<ConstraintSMT>();
  }

  bool canReasonAbout(SVal X) const override {
    const TargetInfo &TI = getBasicVals().getContext().getTargetInfo();

    Optional<nonloc::SymbolVal> SymVal = X.getAs<nonloc::SymbolVal>();
    if (!SymVal)
      return true;

    const SymExpr *Sym = SymVal->getSymbol();
    QualType Ty = Sym->getType();

    // Complex types are not modeled
    if (Ty->isComplexType() || Ty->isComplexIntegerType())
      return false;

    // Non-IEEE 754 floating-point types are not modeled
    if ((Ty->isSpecificBuiltinType(BuiltinType::LongDouble) &&
         (&TI.getLongDoubleFormat() == &llvm::APFloat::x87DoubleExtended() ||
          &TI.getLongDoubleFormat() == &llvm::APFloat::PPCDoubleDouble())))
      return false;

    if (Ty->isRealFloatingType())
      return Solver->isFPSupported();

    if (isa<SymbolData>(Sym))
      return true;

    SValBuilder &SVB = getSValBuilder();

    if (const SymbolCast *SC = dyn_cast<SymbolCast>(Sym))
      return canReasonAbout(SVB.makeSymbolVal(SC->getOperand()));

    if (const BinarySymExpr *BSE = dyn_cast<BinarySymExpr>(Sym)) {
      if (const SymIntExpr *SIE = dyn_cast<SymIntExpr>(BSE))
        return canReasonAbout(SVB.makeSymbolVal(SIE->getLHS()));

      if (const IntSymExpr *ISE = dyn_cast<IntSymExpr>(BSE))
        return canReasonAbout(SVB.makeSymbolVal(ISE->getRHS()));

      if (const SymSymExpr *SSE = dyn_cast<SymSymExpr>(BSE))
        return canReasonAbout(SVB.makeSymbolVal(SSE->getLHS())) &&
               canReasonAbout(SVB.makeSymbolVal(SSE->getRHS()));
    }

    llvm_unreachable("Unsupported expression to reason about!");
  }

  /// Dumps SMT formula
  LLVM_DUMP_METHOD void dump() const { Solver->dump(); }

protected:
  // Check whether a new model is satisfiable, and update the program state.
  virtual ProgramStateRef assumeExpr(ProgramStateRef State, SymbolRef Sym,
                                     const llvm::SMTExprRef &Exp) {
    // Check the model, avoid simplifying AST to save time
    if (checkModel(State, Sym, Exp).isConstrainedTrue())
      return State->add<ConstraintSMT>(std::make_pair(Sym, Exp));

    return nullptr;
  }

  /// Given a program state, construct the logical conjunction and add it to
  /// the solver
  virtual void addStateConstraints(ProgramStateRef State) const {
    // TODO: Don't add all the constraints, only the relevant ones
    auto CZ = State->get<ConstraintSMT>();
    auto I = CZ.begin(), IE = CZ.end();

    // Construct the logical AND of all the constraints
    if (I != IE) {
      std::vector<llvm::SMTExprRef> ASTs;

      llvm::SMTExprRef Constraint = I++->second;
      while (I != IE) {
        Constraint = Solver->mkAnd(Constraint, I++->second);
      }

      Solver->addConstraint(Constraint);
    }
  }

  // Generate and check a Z3 model, using the given constraint.
  ConditionTruthVal checkModel(ProgramStateRef State, SymbolRef Sym,
                               const llvm::SMTExprRef &Exp) const {
    ProgramStateRef NewState =
        State->add<ConstraintSMT>(std::make_pair(Sym, Exp));

    llvm::FoldingSetNodeID ID;
    NewState->get<ConstraintSMT>().Profile(ID);

    unsigned hash = ID.ComputeHash();
    auto I = Cached.find(hash);
    if (I != Cached.end())
      return I->second;

    Solver->reset();
    addStateConstraints(NewState);

    Optional<bool> res = Solver->check();
    if (!res.hasValue())
      Cached[hash] = ConditionTruthVal();
    else
      Cached[hash] = ConditionTruthVal(res.getValue());

    return Cached[hash];
  }

  // Cache the result of an SMT query (true, false, unknown). The key is the
  // hash of the constraints in a state
  mutable llvm::DenseMap<unsigned, ConditionTruthVal> Cached;
}; // end class SMTConstraintManager

} // namespace ento
} // namespace clang

#endif


text:
extern const int32 kSVNRevision;

#endif // SVN_REVISION_H


text:
"""
NLTK corpus readers.  The modules in this package provide functions
that can be used to read corpus files in a variety of formats.  These
functions can be used to read both the corpus files that are
distributed in the NLTK corpus package, and corpus files that are part
of external corpora.

Available Corpora
=================

Please see http://nltk.googlecode.com/svn/trunk/nltk_data/index.xml
for a complete list.  Install corpora using nltk.download().

Corpus Reader Functions
=======================
Each corpus module defines one or more X{corpus reader functions},
which can be used to read documents from that corpus.  These functions
take an argument, C{item}, which is used to indicate which document
should be read from the corpus:

  - If C{item} is one of the unique identifiers listed in the corpus
    module's C{items} variable, then the corresponding document will
    be loaded from the NLTK corpus package.

  - If C{item} is a filename, then that file will be read.

Additionally, corpus reader functions can be given lists of item
names; in which case, they will return a concatenation of the
corresponding documents.

Corpus reader functions are named based on the type of information
they return.  Some common examples, and their return types, are:

  - I{corpus}.words(): list of str
  - I{corpus}.sents(): list of (list of str)
  - I{corpus}.paras(): list of (list of (list of str))
  - I{corpus}.tagged_words(): list of (str,str) tuple
  - I{corpus}.tagged_sents(): list of (list of (str,str))
  - I{corpus}.tagged_paras(): list of (list of (list of (str,str)))
  - I{corpus}.chunked_sents(): list of (Tree w/ (str,str) leaves)
  - I{corpus}.parsed_sents(): list of (Tree with str leaves)
  - I{corpus}.parsed_paras(): list of (list of (Tree with str leaves))
  - I{corpus}.xml(): A single xml ElementTree
  - I{corpus}.raw(): unprocessed corpus contents

For example, to read a list of the words in the Brown Corpus, use
C{nltk.corpus.brown.words()}:

    >>> from nltk.corpus import brown
    >>> print brown.words()
    ['The', 'Fulton', 'County', 'Grand', 'Jury', 'said', ...]

Corpus Metadata
===============
Metadata about the NLTK corpora, and their individual documents, is
stored using U{Open Language Archives Community (OLAC)
<http://www.language-archives.org/>} metadata records.  These records
can be accessed using C{nltk.corpus.I{corpus}.olac()}.
"""

import re

from nltk.tokenize import RegexpTokenizer
from nltk.tag import simplify_brown_tag, simplify_wsj_tag,\
                     simplify_alpino_tag, simplify_indian_tag,\
                     simplify_tag

from util import LazyCorpusLoader
from reader import *

abc = LazyCorpusLoader(
    'abc', PlaintextCorpusReader, r'(?!\.).*\.txt')
alpino = LazyCorpusLoader(
    'alpino', AlpinoCorpusReader, tag_mapping_function=simplify_alpino_tag)
brown = LazyCorpusLoader(
    'brown', CategorizedTaggedCorpusReader, r'c[a-z]\d\d',
    cat_file='cats.txt', tag_mapping_function=simplify_brown_tag)
cess_cat = LazyCorpusLoader(
    'cess_cat', BracketParseCorpusReader, r'(?!\.).*\.tbf',
    tag_mapping_function=simplify_tag)
cess_esp = LazyCorpusLoader(
    'cess_esp', BracketParseCorpusReader, r'(?!\.).*\.tbf',
    tag_mapping_function=simplify_tag)
cmudict = LazyCorpusLoader(
    'cmudict', CMUDictCorpusReader, ['cmudict'])
comtrans = LazyCorpusLoader(
    'comtrans', AlignedCorpusReader, r'(?!\.).*\.txt')
conll2000 = LazyCorpusLoader(
    'conll2000', ConllChunkCorpusReader,
    ['train.txt', 'test.txt'], ('NP','VP','PP'),
    tag_mapping_function=simplify_wsj_tag)
conll2002 = LazyCorpusLoader(
    'conll2002', ConllChunkCorpusReader, '.*\.(test|train).*',
    ('LOC', 'PER', 'ORG', 'MISC'), encoding='utf-8')
conll2007 = LazyCorpusLoader(
    'conll2007', DependencyCorpusReader, '.*\.(test|train).*',
    encoding='utf-8')
dependency_treebank = LazyCorpusLoader(
    'dependency_treebank', DependencyCorpusReader, '.*\.dp')
floresta = LazyCorpusLoader(
    'floresta', BracketParseCorpusReader, r'(?!\.).*\.ptb', '#',
    tag_mapping_function=simplify_tag)
gazetteers = LazyCorpusLoader(
    'gazetteers', WordListCorpusReader, r'(?!LICENSE|\.).*\.txt')
genesis = LazyCorpusLoader(
    'genesis', PlaintextCorpusReader, r'(?!\.).*\.txt', encoding=[
        ('finnish|french|german', 'latin_1'),
        ('swedish', 'cp865'),
        ('.*', 'utf_8')])
gutenberg = LazyCorpusLoader(
    'gutenberg', PlaintextCorpusReader, r'(?!\.).*\.txt')
# corpus not available with NLTK; these lines caused help(nltk.corpus) to break
#hebrew_treebank = LazyCorpusLoader(
#    'hebrew_treebank', BracketParseCorpusReader, r'.*\.txt')
ieer = LazyCorpusLoader(
    'ieer', IEERCorpusReader, r'(?!README|\.).*')
inaugural = LazyCorpusLoader(
    'inaugural', PlaintextCorpusReader, r'(?!\.).*\.txt')
# [XX] This should probably just use TaggedCorpusReader:
indian = LazyCorpusLoader(
    'indian', IndianCorpusReader, r'(?!\.).*\.pos',
    tag_mapping_function=simplify_indian_tag)
ipipan = LazyCorpusLoader(
    'ipipan', IPIPANCorpusReader, r'(?!\.).*morph\.xml')
jeita = LazyCorpusLoader(
    'jeita', ChasenCorpusReader, r'.*\.chasen', encoding='utf-8')
knbc = LazyCorpusLoader(
    'knbc/corpus1', KNBCorpusReader, r'.*/KN.*', encoding='euc-jp')
mac_morpho = LazyCorpusLoader(
    'mac_morpho', MacMorphoCorpusReader, r'(?!\.).*\.txt',
    tag_mapping_function=simplify_tag, encoding='latin-1')
machado = LazyCorpusLoader(
    'machado', PortugueseCategorizedPlaintextCorpusReader,
    r'(?!\.).*\.txt', cat_pattern=r'([a-z]*)/.*', encoding='latin-1')
movie_reviews = LazyCorpusLoader(
    'movie_reviews', CategorizedPlaintextCorpusReader,
    r'(?!\.).*\.txt', cat_pattern=r'(neg|pos)/.*')
names = LazyCorpusLoader(
    'names', WordListCorpusReader, r'(?!\.).*\.txt')
nps_chat = LazyCorpusLoader(
    'nps_chat', NPSChatCorpusReader, r'(?!README|\.).*\.xml',
    tag_mapping_function=simplify_wsj_tag)
pl196x = LazyCorpusLoader(
    'pl196x', Pl196xCorpusReader, r'[a-z]-.*\.xml',
    cat_file='cats.txt', textid_file='textids.txt')
ppattach = LazyCorpusLoader(
    'ppattach', PPAttachmentCorpusReader, ['training', 'test', 'devset'])
# ptb = LazyCorpusLoader( # Penn Treebank v3: WSJ and Brown portions
#    'ptb3', CategorizedBracketParseCorpusReader, r'(WSJ/\d\d/WSJ_\d\d|BROWN/C[A-Z]/C[A-Z])\d\d.MRG',
#    cat_file='allcats.txt', tag_mapping_function=simplify_wsj_tag)
qc = LazyCorpusLoader(
    'qc', StringCategoryCorpusReader, ['train.txt', 'test.txt'])
reuters = LazyCorpusLoader(
    'reuters', CategorizedPlaintextCorpusReader, '(training|test).*',
    cat_file='cats.txt')
rte = LazyCorpusLoader(
    'rte', RTECorpusReader, r'(?!\.).*\.xml')
semcor = LazyCorpusLoader(
    'semcor', XMLCorpusReader, r'brown./tagfiles/br-.*\.xml')
senseval = LazyCorpusLoader(
    'senseval', SensevalCorpusReader, r'(?!\.).*\.pos')
shakespeare = LazyCorpusLoader(
    'shakespeare', XMLCorpusReader, r'(?!\.).*\.xml')
sinica_treebank = LazyCorpusLoader(
    'sinica_treebank', SinicaTreebankCorpusReader, ['parsed'],
    tag_mapping_function=simplify_tag)
state_union = LazyCorpusLoader(
    'state_union', PlaintextCorpusReader, r'(?!\.).*\.txt')
stopwords = LazyCorpusLoader(
    'stopwords', WordListCorpusReader, r'(?!README|\.).*')
swadesh = LazyCorpusLoader(
    'swadesh', SwadeshCorpusReader, r'(?!README|\.).*')
switchboard = LazyCorpusLoader(
    'switchboard', SwitchboardCorpusReader,
    tag_mapping_function=simplify_wsj_tag)
timit = LazyCorpusLoader(
    'timit', TimitCorpusReader)
timit_tagged = LazyCorpusLoader(
    'timit', TimitTaggedCorpusReader, '.+\.tags',
    tag_mapping_function=simplify_wsj_tag)
toolbox = LazyCorpusLoader(
    'toolbox', ToolboxCorpusReader, r'(?!.*(README|\.)).*\.(dic|txt)')
treebank = LazyCorpusLoader(
    'treebank/combined', BracketParseCorpusReader, r'wsj_.*\.mrg',
    tag_mapping_function=simplify_wsj_tag)
treebank_chunk = LazyCorpusLoader(
    'treebank/tagged', ChunkedCorpusReader, r'wsj_.*\.pos',
    sent_tokenizer=RegexpTokenizer(r'(?<=/\.)\s*(?![^\[]*\])', gaps=True),
    para_block_reader=tagged_treebank_para_block_reader)
treebank_raw = LazyCorpusLoader(
    'treebank/raw', PlaintextCorpusReader, r'wsj_.*')
udhr = LazyCorpusLoader(
    'udhr', PlaintextCorpusReader, r'(?!README|\.).*',
    # Encodings specified in filenames but not mapped to anything:
    # DallakHelv, VIQR, Cyrillic+Abkh, WinResearcher, font,
    # Afenegus6..60375, VG2Main, VPS, Turkish, TCVN, Az.Times.Lat0117,
    # EUC, Baltic, err, Az.Times.Cyr.Normal0117, T61, Amahuaca, Agra
    encoding=[('.*-UTF8$', 'utf-8'), ('.*-Latin1$', 'latin-1'),
              ('.*-Hebrew$', 'hebrew'), ('.*-Arabic$', 'arabic'),
              ('.*-Cyrillic$', 'cyrillic'), ('.*-SJIS$', 'SJIS'),
              ('.*-GB2312$', 'GB2312'), ('.*-Latin2$', 'ISO-8859-2'),
              ('.*-Greek$', 'greek'), ('.*-UFT8$', 'utf-8'),
              ('Hungarian_Magyar-Unicode', 'utf-16-le')]
    )
verbnet = LazyCorpusLoader(
    'verbnet', VerbnetCorpusReader, r'(?!\.).*\.xml')
webtext = LazyCorpusLoader(
    'webtext', PlaintextCorpusReader, r'(?!README|\.).*\.txt')
wordnet = LazyCorpusLoader(
    'wordnet', WordNetCorpusReader)
wordnet_ic = LazyCorpusLoader(
    'wordnet_ic', WordNetICCorpusReader, '.*\.dat')
words = LazyCorpusLoader(
    'words', WordListCorpusReader, r'(?!README|\.).*')
ycoe = LazyCorpusLoader(
    'ycoe', YCOECorpusReader)
# defined after treebank
propbank = LazyCorpusLoader(
    'propbank', PropbankCorpusReader,
    'prop.txt', 'frames/.*\.xml', 'verbs.txt',
    lambda filename: re.sub(r'^wsj/\d\d/', '', filename),
    treebank) # Must be defined *after* treebank corpus.
nombank = LazyCorpusLoader(
    'nombank.1.0', NombankCorpusReader,
    'nombank.1.0', 'frames/.*\.xml', 'nombank.1.0.words',
    lambda filename: re.sub(r'^wsj/\d\d/', '', filename),
    treebank) # Must be defined *after* treebank corpus.

def demo():
    # This is out-of-date:
    abc.demo()
    brown.demo()
#    chat80.demo()
    cmudict.demo()
    conll2000.demo()
    conll2002.demo()
    genesis.demo()
    gutenberg.demo()
    ieer.demo()
    inaugural.demo()
    indian.demo()
    names.demo()
    ppattach.demo()
    senseval.demo()
    shakespeare.demo()
    sinica_treebank.demo()
    state_union.demo()
    stopwords.demo()
    timit.demo()
    toolbox.demo()
    treebank.demo()
    udhr.demo()
    webtext.demo()
    words.demo()
#    ycoe.demo()

if __name__ == '__main__':
    #demo()
    pass


text:
<?php

namespace Behance\NBD\Cache;

use Behance\NBD\Cache\Test\IntegrationTest;

class AdapterTest extends IntegrationTest
{

    private $_key   = 'abcdef';
    private $_value = 12345;

  /**
   * @test
   * @dataProvider typeProvider
   */
    public function addRemove($type)
    {

        $adapter = $this->_getLiveAdapter($type);

        $this->assertFalse($adapter->get($this->_key));

        $adapter->set($this->_key, $this->_value);

        $this->assertEquals($this->_value, $adapter->get($this->_key));

        $this->assertTrue($adapter->delete($this->_key));

        $this->assertFalse($adapter->get($this->_key));
    } // addRemove

  /**
   * @test
   * @dataProvider typeProvider
   */
    public function getMulti($type)
    {

        $adapter = $this->_getLiveAdapter($type);
        $data    = [
        'abc' => 123,
        'def' => 456,
        'ghi' => 789
        ];

        foreach ($data as $key => $value) {
            $adapter->set($key, $value);
        }

        $keys    = array_keys($data);
        $results = $adapter->getMulti($keys);

        $this->assertSame($data, $results);
    } // getMulti

  /**
   * Place values into cache in one order, retrieve them in another order.
   * Ensure order is preserved
   *
   * @test
   * @dataProvider typeProvider
   */
    public function getMultiInOrder($type)
    {

        $adapter = $this->_getLiveAdapter($type);
        $data    = [
        'abc' => 123,
        'def' => 456,
        'ghi' => 789
        ];

        $reversed = array_reverse($data);

        // Place values in cache backwards from how they will be requested
        foreach ($reversed as $key => $value) {
            $adapter->set($key, $value);
        }

        $keys    = array_keys($data);
        $results = $adapter->getMulti($keys);

        $this->assertSame($data, $results);
    } // getMultiInOrder

  /**
   * @test
   * @dataProvider typeProvider
   */
    public function failedConnection($type)
    {

        $bad_server = [
        'host' => '127.0.0.1',
        'port' => 11211
        ];

        $failed  = false;
        $adapter = Factory::create([ $bad_server ], $type);

        // Ensure failure events are propegated
        $adapter->bindEvent(AdapterInterface::EVENT_QUERY_FAIL, function () use (&$failed) {
            $failed = true;
        });

        $this->assertFalse($adapter->get($this->_key));
        $this->assertTrue($failed);
    } // failedConnection

  /**
   * @test
   * @dataProvider typeProvider
   */
    public function getAllKeys($type)
    {

        $adapter = $this->_getLiveAdapter($type);
        $data    = [
        'abc' => 123,
        'def' => 456,
        'ghi' => 789
        ];

        foreach ($data as $key => $value) {
            $adapter->set($key, $value);
        }

        $cache_keys = $adapter->getAllKeys();
        $all_keys   = array_keys($data);

        foreach ($all_keys as $key) {
            $this->assertContains($key, $cache_keys);
        }
    } // getAllKeys
} // AdapterTest


text:
package com.dumu.housego.presenter;

public interface ISubmitRentingListpresenter {
	void SubmitRentingList(String username, String userid, String table);
}


text:
using System;
using System.Collections;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Web;
using System.Web.SessionState;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.HtmlControls;
using umbraco.cms.presentation.Trees;

namespace umbraco.dialogs
{
	[Obsolete("Use the TreeControl instead. This does however get used by the TreeService when requesting the tree init url.")]
	public partial class treePicker : BasePages.UmbracoEnsuredPage
	{
		protected override void OnLoad(EventArgs e)
		{
			base.OnLoad(e);
			TreeParams = TreeRequestParams.FromQueryStrings().CreateTreeService();
			DataBind();

            if(Request.QueryString["selected"] != null && TreeParams.TreeType == "content")
            {
                var currContent = Services.ContentService.GetById(int.Parse(Request.QueryString["selected"]));
                if (currContent != null)
                {
                    if (currContent.ParentId > 0)
                        DialogTree.SelectedNodePath = currContent.Path;
                }
            }
		}

		protected TreeService TreeParams { get; private set; }

		/// <summary>
		/// DialogTree control.
		/// </summary>
		/// <remarks>
		/// Auto-generated field.
		/// To modify move field declaration from designer file to code-behind file.
		/// </remarks>
		protected global::umbraco.controls.Tree.TreeControl DialogTree;

	}
}


text:
{% extends "foreign/foreign_base.html" %}
{% load humanize %}
{% load static %}

{% block js %}

{% endblock %}

{% block main_content %}

Registered agents are hired by foreign entities to represent them in influencing US policy.

		 Registered Agent
		 Payments

		{% for d in data %}

				{{ d.reg_name }}
				{{ d.payments2013|floatformat:2|intcomma }}

		{% endfor %}

{% endblock %}


text:
import warnings
warnings.filterwarnings("ignore", category = UserWarning, module = "matplotlib")
#
# Display inline matplotlib plots with IPython
from IPython import get_ipython
get_ipython().run_line_magic('matplotlib', 'inline')
###########################################

import matplotlib.pyplot as pl
import matplotlib.patches as mpatches
import numpy as np
import pandas as pd
from time import time
from sklearn.metrics import f1_score, accuracy_score

def distribution(data, transformed = False):
    """
    Visualization code for displaying skewed distributions of features
    """

    # Create figure
    fig = pl.figure(figsize = (11,5));

    # Skewed feature plotting
    for i, feature in enumerate(['capital-gain','capital-loss']):
        ax = fig.add_subplot(1, 2, i+1)
        ax.hist(data[feature], bins = 25, color = '#00A0A0')
        ax.set_title("'%s' Feature Distribution"%(feature), fontsize = 14)
        ax.set_xlabel("Value")
        ax.set_ylabel("Number of Records")
        ax.set_ylim((0, 2000))
        ax.set_yticks([0, 500, 1000, 1500, 2000])
        ax.set_yticklabels([0, 500, 1000, 1500, ">2000"])

    # Plot aesthetics
    if transformed:
        fig.suptitle("Log-transformed Distributions of Continuous Census Data Features", \
            fontsize = 16, y = 1.03)
    else:
        fig.suptitle("Skewed Distributions of Continuous Census Data Features", \
            fontsize = 16, y = 1.03)

    fig.tight_layout()
    fig.show()

def evaluate(results, accuracy, f1):
    """
    Visualization code to display results of various learners.

    inputs:
      - learners: a list of supervised learners
      - stats: a list of dictionaries of the statistic results from 'train_predict()'
      - accuracy: The score for the naive predictor
      - f1: The score for the naive predictor
    """

    # Create figure
    fig, ax = pl.subplots(2, 3, figsize = (11,7))

    # Constants
    bar_width = 0.3
    colors = ['#A00000','#00A0A0','#00A000']

    # Super loop to plot four panels of data
    for k, learner in enumerate(results.keys()):
        for j, metric in enumerate(['train_time', 'acc_train', 'f_train', 'pred_time', 'acc_test', 'f_test']):
            for i in np.arange(3):

                # Creative plot code
                ax[j/3, j%3].bar(i+k*bar_width, results[learner][i][metric], width = bar_width, color = colors[k])
                ax[j/3, j%3].set_xticks([0.45, 1.45, 2.45])
                ax[j/3, j%3].set_xticklabels(["1%", "10%", "100%"])
                ax[j/3, j%3].set_xlabel("Training Set Size")
                ax[j/3, j%3].set_xlim((-0.1, 3.0))

    # Add unique y-labels
    ax[0, 0].set_ylabel("Time (in seconds)")
    ax[0, 1].set_ylabel("Accuracy Score")
    ax[0, 2].set_ylabel("F-score")
    ax[1, 0].set_ylabel("Time (in seconds)")
    ax[1, 1].set_ylabel("Accuracy Score")
    ax[1, 2].set_ylabel("F-score")

    # Add titles
    ax[0, 0].set_title("Model Training")
    ax[0, 1].set_title("Accuracy Score on Training Subset")
    ax[0, 2].set_title("F-score on Training Subset")
    ax[1, 0].set_title("Model Predicting")
    ax[1, 1].set_title("Accuracy Score on Testing Set")
    ax[1, 2].set_title("F-score on Testing Set")

    # Add horizontal lines for naive predictors
    ax[0, 1].axhline(y = accuracy, xmin = -0.1, xmax = 3.0, linewidth = 1, color = 'k', linestyle = 'dashed')
    ax[1, 1].axhline(y = accuracy, xmin = -0.1, xmax = 3.0, linewidth = 1, color = 'k', linestyle = 'dashed')
    ax[0, 2].axhline(y = f1, xmin = -0.1, xmax = 3.0, linewidth = 1, color = 'k', linestyle = 'dashed')
    ax[1, 2].axhline(y = f1, xmin = -0.1, xmax = 3.0, linewidth = 1, color = 'k', linestyle = 'dashed')

    # Set y-limits for score panels
    ax[0, 1].set_ylim((0, 1))
    ax[0, 2].set_ylim((0, 1))
    ax[1, 1].set_ylim((0, 1))
    ax[1, 2].set_ylim((0, 1))

    # Create patches for the legend
    patches = []
    for i, learner in enumerate(results.keys()):
        patches.append(mpatches.Patch(color = colors[i], label = learner))
    pl.legend(handles = patches, bbox_to_anchor = (-.80, 2.53), \
               loc = 'upper center', borderaxespad = 0., ncol = 3, fontsize = 'x-large')

    # Aesthetics
    pl.suptitle("Performance Metrics for Three Supervised Learning Models", fontsize = 16, y = 1.10)
    pl.tight_layout()
    pl.show()

def feature_plot(importances, X_train, y_train):

    # Display the five most important features
    indices = np.argsort(importances)[::-1]
    columns = X_train.columns.values[indices[:5]]
    values = importances[indices][:5]

    # Creat the plot
    fig = pl.figure(figsize = (9,5))
    pl.title("Normalized Weights for First Five Most Predictive Features", fontsize = 16)
    pl.bar(np.arange(5), values, width = 0.6, align="center", color = '#00A000', \
          label = "Feature Weight")
    pl.bar(np.arange(5) - 0.3, np.cumsum(values), width = 0.2, align = "center", color = '#00A0A0', \
          label = "Cumulative Feature Weight")
    pl.xticks(np.arange(5), columns)
    pl.xlim((-0.5, 4.5))
    pl.ylabel("Weight", fontsize = 12)
    pl.xlabel("Feature", fontsize = 12)

    pl.legend(loc = 'upper center')
    pl.tight_layout()
    pl.show()


text:
import json

from tempest.api_schema.response.compute.v2_1 import floating_ips as schema
from tempest.common import service_client

class FloatingIpsBulkClient(service_client.ServiceClient):

    def create_floating_ips_bulk(self, ip_range, pool, interface):
        """Allocate floating IPs in bulk."""
        post_body = {
            'ip_range': ip_range,
            'pool': pool,
            'interface': interface
        }
        post_body = json.dumps({'floating_ips_bulk_create': post_body})
        resp, body = self.post('os-floating-ips-bulk', post_body)
        body = json.loads(body)
        self.validate_response(schema.create_floating_ips_bulk, resp, body)
        return service_client.ResponseBody(resp,
                                           body['floating_ips_bulk_create'])

    def list_floating_ips_bulk(self):
        """Returns a list of all floating IPs bulk."""
        resp, body = self.get('os-floating-ips-bulk')
        body = json.loads(body)
        self.validate_response(schema.list_floating_ips_bulk, resp, body)
        return service_client.ResponseBodyList(resp, body['floating_ip_info'])

    def delete_floating_ips_bulk(self, ip_range):
        """Deletes the provided floating IPs bulk."""
        post_body = json.dumps({'ip_range': ip_range})
        resp, body = self.put('os-floating-ips-bulk/delete', post_body)
        body = json.loads(body)
        self.validate_response(schema.delete_floating_ips_bulk, resp, body)
        data = body['floating_ips_bulk_delete']
        return service_client.ResponseBodyData(resp, data)


text:
layout: post
date: '2016-10-21'
title: "Sheath V Neckline Floor Length Brocade Satin Wedding Dress"
category: A-Line
tags: ["floor","length","brocade","sheath","dress"]
image: http://www.starbrideapparel.com/10131-thickbox_default/sheath-v-neckline-floor-length-brocade-satin-wedding-dress.jpg
---
Sheath V Neckline Floor Length Brocade Satin Wedding Dress

On Sales: **$337.794**
<amp-img layout="responsive" width="600" height="600" src="//www.starbrideapparel.com/10131-thickbox_default/sheath-v-neckline-floor-length-brocade-satin-wedding-dress.jpg" alt="Sheath V Neckline Floor Length Brocade Satin Wedding Dress 0" />

Buy it: [Sheath V Neckline Floor Length Brocade Satin Wedding Dress](https://www.starbrideapparel.com/aline-wedding-dresses/4706-sheath-v-neckline-floor-length-brocade-satin-wedding-dress-1463394428006.html "Sheath V Neckline Floor Length Brocade Satin Wedding Dress")

View more: [A-Line](https://www.starbrideapparel.com/2-aline-wedding-dresses "A-Line")


text: java -cp "/var/lib/elasticsearch-shell/bin/*" com.antonjohansson.elasticsearchshell.EntryPoint


text:
using BTCPayServer.Data;
using Microsoft.EntityFrameworkCore.Infrastructure;
using Microsoft.EntityFrameworkCore.Migrations;

namespace BTCPayServer.Migrations
{
    [DbContext(typeof(ApplicationDbContext))]
    [Migration("20171006013443_AddressMapping")]
    public partial class AddressMapping : Migration
    {
        protected override void Up(MigrationBuilder migrationBuilder)
        {
            int? maxLength = this.IsMySql(migrationBuilder.ActiveProvider) ? (int?)255 : null;
            migrationBuilder.CreateTable(
                name: "AddressInvoices",
                columns: table => new
                {
                    Address = table.Column<string>(nullable: false, maxLength: this.IsMySql(migrationBuilder.ActiveProvider) ? (int?)512 : null),
                    InvoiceDataId = table.Column<string>(nullable: true, maxLength: maxLength)
                },
                constraints: table =>
                {
                    table.PrimaryKey("PK_AddressInvoices", x => x.Address);
                    table.ForeignKey(
                        name: "FK_AddressInvoices_Invoices_InvoiceDataId",
                        column: x => x.InvoiceDataId,
                        principalTable: "Invoices",
                        principalColumn: "Id",
                        onDelete: ReferentialAction.Restrict);
                });

            migrationBuilder.CreateIndex(
                name: "IX_AddressInvoices_InvoiceDataId",
                table: "AddressInvoices",
                column: "InvoiceDataId");
        }

        protected override void Down(MigrationBuilder migrationBuilder)
        {
            migrationBuilder.DropTable(
                name: "AddressInvoices");
        }
    }
}