text:
package org.apache.tomcat.util.http.fileupload;

import static org.jboss.web.FileUploadMessages.MESSAGES;

import java.io.File;
import java.io.FileNotFoundException;
import java.io.IOException;

/**
 * General file manipulation utilities.
 *

 * Facilities are provided in the following areas:
 *

 *
writing to a file
 *
reading from a file
 *
make a directory including parent directories
 *
copying files and directories
 *
deleting files and directories
 *
converting to and from a URL
 *
listing files and directories by filter and extension
 *
comparing file content
 *
file last changed date
 *
calculating a checksum
 *

 *

 * Origin of code: Excalibur, Alexandria, Commons-Utils
 *
 * @author Kevin A. Burton
 * @author Scott Sanders
 * @author Daniel Rall
 * @author Christoph.Reck
 * @author Peter Donald
 * @author Jeff Turner
 * @author Matthew Hawthorne
 * @author Jeremias Maerki
 * @author Stephen Colebourne
 * @author Ian Springer
 * @author Chris Eldredge
 * @author Jim Harrington
 * @author Niall Pemberton
 * @author Sandy McArthur
 * @version $Id: FileUtils.java 881493 2009-11-17 20:30:39Z markt $
 */
public class FileUtils {

    /**
     * Instances should NOT be constructed in standard programming.
     */
    public FileUtils() {
        super();
    }

    //-----------------------------------------------------------------------
    /**
     * Deletes a directory recursively.
     *
     * @param directory  directory to delete
     * @throws IOException in case deletion is unsuccessful
     */
    public static void deleteDirectory(File directory) throws IOException {
        if (!directory.exists()) {
            return;
        }

        cleanDirectory(directory);
        if (!directory.delete()) {
            throw new IOException(MESSAGES.failedToDeleteDirectory(directory.getPath()));
        }
    }

    /**
     * Cleans a directory without deleting it.
     *
     * @param directory directory to clean
     * @throws IOException in case cleaning is unsuccessful
     */
    public static void cleanDirectory(File directory) throws IOException {
        if (!directory.exists()) {
            throw MESSAGES.missingDirectory(directory.getPath());
        }

        if (!directory.isDirectory()) {
            throw MESSAGES.notDirectory(directory.getPath());
        }

        File[] files = directory.listFiles();
        if (files == null) {  // null if security restricted
            throw new IOException(MESSAGES.failedListingDirectory(directory.getPath()));
        }

        IOException exception = null;
        for (int i = 0; i < files.length; i++) {
            File file = files[i];
            try {
                forceDelete(file);
            } catch (IOException ioe) {
                exception = ioe;
            }
        }

        if (null != exception) {
            throw exception;
        }
    }

    //-----------------------------------------------------------------------
    /**
     * Deletes a file. If file is a directory, delete it and all sub-directories.
     *

     * The difference between File.delete() and this method are:
     *

     *
A directory to be deleted does not have to be empty.

     *
You get exceptions when a file or directory cannot be deleted.
     *      (java.io.File methods returns a boolean)

     *

     *
     * @param file  file or directory to delete, must not be null
     * @throws NullPointerException if the directory is null
     * @throws FileNotFoundException if the file was not found
     * @throws IOException in case deletion is unsuccessful
     */
    public static void forceDelete(File file) throws IOException {
        if (file.isDirectory()) {
            deleteDirectory(file);
        } else {
            boolean filePresent = file.exists();
            if (!file.delete()) {
                if (!filePresent){
                    throw new FileNotFoundException(MESSAGES.missingFile(file.getPath()));
                }
                throw new IOException(MESSAGES.failedToDelete(file.getPath()));
            }
        }
    }

    /**
     * Schedules a file to be deleted when JVM exits.
     * If file is directory delete it and all sub-directories.
     *
     * @param file  file or directory to delete, must not be null
     * @throws NullPointerException if the file is null
     * @throws IOException in case deletion is unsuccessful
     */
    public static void forceDeleteOnExit(File file) throws IOException {
        if (file.isDirectory()) {
            deleteDirectoryOnExit(file);
        } else {
            file.deleteOnExit();
        }
    }

    /**
     * Schedules a directory recursively for deletion on JVM exit.
     *
     * @param directory  directory to delete, must not be null
     * @throws NullPointerException if the directory is null
     * @throws IOException in case deletion is unsuccessful
     */
    private static void deleteDirectoryOnExit(File directory) throws IOException {
        if (!directory.exists()) {
            return;
        }

        cleanDirectoryOnExit(directory);
        directory.deleteOnExit();
    }

    /**
     * Cleans a directory without deleting it.
     *
     * @param directory  directory to clean, must not be null
     * @throws NullPointerException if the directory is null
     * @throws IOException in case cleaning is unsuccessful
     */
    private static void cleanDirectoryOnExit(File directory) throws IOException {
        if (!directory.exists()) {
            throw MESSAGES.missingDirectory(directory.getPath());
        }

        if (!directory.isDirectory()) {
            throw MESSAGES.notDirectory(directory.getPath());
        }

        File[] files = directory.listFiles();
        if (files == null) {  // null if security restricted
            throw new IOException(MESSAGES.failedListingDirectory(directory.getPath()));
        }

        IOException exception = null;
        for (int i = 0; i < files.length; i++) {
            File file = files[i];
            try {
                forceDeleteOnExit(file);
            } catch (IOException ioe) {
                exception = ioe;
            }
        }

        if (null != exception) {
            throw exception;
        }
    }
}


text:
package com.socialthingy.plusf.z80.operations;

import com.socialthingy.plusf.z80.ContentionModel;
import com.socialthingy.plusf.z80.Processor;

public class OpXorAImmediate extends XorOperation {

    private final Processor processor;

    public OpXorAImmediate(final Processor processor) {
        super(processor);
        this.processor = processor;
    }

    @Override
    public void execute(ContentionModel contentionModel, int initialPcValue, int irValue) {
        contentionModel.applyContention(initialPcValue, 4);
        contentionModel.applyContention(initialPcValue + 1, 3);
        xor(processor.fetchNextByte());
    }

    @Override
    public String toString() {
        return "xor n";
    }
}

redpajama_set_name: RedPajamaGithub


text:
@class BITSDKTextView;

@protocol BITSDKTextViewDelegate <NSObject>

- (void)textView:(BITSDKTextView *)textView dragOperationWithFilename:(NSString *)filename;

@end


text:
#ifndef MITKIMAGESTATISTICSHOLDER_H
#define MITKIMAGESTATISTICSHOLDER_H

#include "mitkImage.h"
#include "mitkImageTimeSelector.h"
#include <MitkCoreExports.h>

#ifndef __itkHistogram_h
#include <itkHistogram.h>
#endif

namespace mitk
{
  /**
    @brief Class holding the statistics information about a single mitk::Image

    This computation was previously directly included in the definition and implementation of the mitk::Image class
    but for having a clear interface, all statistics computation is moved to the ImageStatisticsHolder class.

    Each mitk::Image holds a normal pointer to its StatisticsHolder object. To get access to the methods, use the
    GetStatistics() method in mitk::Image class.

    Minimum or maximum might by infinite values. 2nd minimum and maximum are guaranteed to be finite values.
    */
  class MITKCORE_EXPORT ImageStatisticsHolder
  {
  public:
    /** Constructor */
    ImageStatisticsHolder(mitk::Image *image);

    /** Destructor */
    virtual ~ImageStatisticsHolder();

    typedef itk::Statistics::Histogram<double> HistogramType;

    virtual const HistogramType *GetScalarHistogram(int t = 0, unsigned int = 0);

    //##Documentation
    //## \brief Get the minimum for scalar images. Recomputation performed only when necessary.
    virtual ScalarType GetScalarValueMin(int t = 0, unsigned int component = 0);

    //##Documentation
    //## \brief Get the maximum for scalar images. Recomputation performed only when necessary.
    virtual ScalarType GetScalarValueMax(int t = 0, unsigned int component = 0);

    //##Documentation
    //## \brief Get the second smallest value for scalar images.
    //## Recomputation performed only when necessary.
    //## \post The returned value is always a finite value.
    virtual ScalarType GetScalarValue2ndMin(int t = 0, unsigned int component = 0);

    //##Documentation
    //## \brief Get the smallest value for scalar images, but do not recompute it first
    virtual mitk::ScalarType GetScalarValueMinNoRecompute(unsigned int t = 0) const
    {
      if (t < m_ScalarMin.size())
        return m_ScalarMin[t];
      else
        return itk::NumericTraits<ScalarType>::max();
    }

    //##Documentation
    //## \brief Get the second smallest value for scalar images, but do not recompute it first
    //## \post The returned value is always a finite value.
    virtual mitk::ScalarType GetScalarValue2ndMinNoRecompute(unsigned int t = 0) const
    {
      if (t < m_Scalar2ndMin.size())
        return m_Scalar2ndMin[t];
      else
        return itk::NumericTraits<ScalarType>::max();
    }

    //##Documentation
    //## \brief Get the second largest value for scalar images
    //## \post The returned value is always a finite value.
    virtual ScalarType GetScalarValue2ndMax(int t = 0, unsigned int component = 0);

    //##Documentation
    //## \brief Get the largest value for scalar images, but do not recompute it first
    //## \post The returned value is always a finite value.
    virtual mitk::ScalarType GetScalarValueMaxNoRecompute(unsigned int t = 0)
    {
      if (t < m_ScalarMax.size())
        return m_ScalarMax[t];
      else
        return itk::NumericTraits<ScalarType>::NonpositiveMin();
    }

    //##Documentation
    //## \brief Get the second largest value for scalar images, but do not recompute it first
    virtual mitk::ScalarType GetScalarValue2ndMaxNoRecompute(unsigned int t = 0)
    {
      if (t < m_Scalar2ndMax.size())
        return m_Scalar2ndMax[t];
      else
        return itk::NumericTraits<ScalarType>::NonpositiveMin();
    }

    //##Documentation
    //## \brief Get the count of voxels with the smallest scalar value in the dataset
    mitk::ScalarType GetCountOfMinValuedVoxels(int t = 0, unsigned int component = 0);

    //##Documentation
    //## \brief Get the count of voxels with the largest scalar value in the dataset
    mitk::ScalarType GetCountOfMaxValuedVoxels(int t = 0, unsigned int component = 0);

    //##Documentation
    //## \brief Get the count of voxels with the largest scalar value in the dataset
    virtual unsigned int GetCountOfMaxValuedVoxelsNoRecompute(unsigned int t = 0)
    {
      if (t < m_CountOfMaxValuedVoxels.size())
        return m_CountOfMaxValuedVoxels[t];
      else
        return 0;
    }

    //##Documentation
    //## \brief Get the count of voxels with the smallest scalar value in the dataset
    virtual unsigned int GetCountOfMinValuedVoxelsNoRecompute(unsigned int t = 0) const
    {
      if (t < m_CountOfMinValuedVoxels.size())
        return m_CountOfMinValuedVoxels[t];
      else
        return 0;
    }

    bool IsValidTimeStep(int t) const;

    template <typename ItkImageType>
    friend void _ComputeExtremaInItkImage(const ItkImageType *itkImage,
                                          mitk::ImageStatisticsHolder *statisticsHolder,
                                          int t);

    template <typename ItkImageType>
    friend void _ComputeExtremaInItkVectorImage(const ItkImageType *itkImage,
                                                mitk::ImageStatisticsHolder *statisticsHolder,
                                                int t,
                                                unsigned int component);

  protected:
    virtual void ResetImageStatistics();

    virtual void ComputeImageStatistics(int t = 0, unsigned int component = 0);

    virtual void Expand(unsigned int timeSteps);

    ImageTimeSelector::Pointer GetTimeSelector();

    mitk::Image *m_Image;

    mutable itk::Object::Pointer m_HistogramGeneratorObject;

    mutable itk::Object::Pointer m_TimeSelectorForExtremaObject;
    mutable std::vector<unsigned int> m_CountOfMinValuedVoxels;
    mutable std::vector<unsigned int> m_CountOfMaxValuedVoxels;
    mutable std::vector<ScalarType> m_ScalarMin;
    mutable std::vector<ScalarType> m_ScalarMax;
    mutable std::vector<ScalarType> m_Scalar2ndMin;
    mutable std::vector<ScalarType> m_Scalar2ndMax;

    itk::TimeStamp m_LastRecomputeTimeStamp;
  };

} // end namespace
#endif // MITKIMAGESTATISTICSHOLDER_H


text:
package org.unitils.easymock.core;

import org.easymock.classextension.internal.MocksClassControl;
import org.easymock.internal.MocksControl;
import org.unitils.core.annotation.Property;
import org.unitils.easymock.util.*;
import org.unitils.reflectionassert.ReflectionComparatorMode;

import java.util.ArrayList;
import java.util.List;

import static org.easymock.internal.MocksControl.MockType.DEFAULT;
import static org.easymock.internal.MocksControl.MockType.NICE;
import static org.unitils.easymock.util.InvocationOrder.STRICT;
import static org.unitils.reflectionassert.ReflectionComparatorMode.*;

/**
 * @author Tim Ducheyne
 */
public class MocksControlFactory {

    protected InvocationOrder defaultInvocationOrder;
    protected Calls defaultCalls;
    protected Order defaultOrder;
    protected Dates defaultDates;
    protected Defaults defaultsDefaults;

    public MocksControlFactory(@Property("easymock.defaultInvocationOrder") InvocationOrder defaultInvocationOrder, @Property("easymock.defaultCalls") Calls defaultCalls,
                               @Property("easymock.defaultOrder") Order defaultOrder, @Property("easymock.defaultDates") Dates defaultDates,
                               @Property("easymock.defaultDefaults") Defaults defaultsDefaults) {
        this.defaultInvocationOrder = defaultInvocationOrder;
        this.defaultCalls = defaultCalls;
        this.defaultOrder = defaultOrder;
        this.defaultDates = defaultDates;
        this.defaultsDefaults = defaultsDefaults;
    }

    /**
     * todo javadoc
     *

     * Creates an EasyMock mock instance of the given type (class/interface). The type of mock is determined
     * as follows:
     *

     * If returns is set to LENIENT, a nice mock is created, else a default mock is created
     * If arguments is lenient a lenient control is create, else an EasyMock control is created
     * If order is set to strict, invocation order checking is enabled
     *
     * @param mockType        the type of the mock, not null
     * @param invocationOrder the order setting, not null
     * @param calls           the calls setting, not null
     * @param order           todo
     * @param dates           todo
     * @param defaults        todo
     * @return a mock control for the given class or interface, not null
     */
    public MocksControl createMocksControl(Class<?> mockType, InvocationOrder invocationOrder, Calls calls, Order order, Dates dates, Defaults defaults) {
        if (invocationOrder == InvocationOrder.DEFAULT) {
            invocationOrder = defaultInvocationOrder;
        }
        if (calls == Calls.DEFAULT) {
            calls = defaultCalls;
        }
        if (order == Order.DEFAULT) {
            order = defaultOrder;
        }
        if (dates == Dates.DEFAULT) {
            dates = defaultDates;
        }
        if (defaults == Defaults.DEFAULT) {
            defaults = defaultsDefaults;
        }

        List<ReflectionComparatorMode> comparatorModes = new ArrayList<ReflectionComparatorMode>();
        if (Order.LENIENT == order) {
            comparatorModes.add(LENIENT_ORDER);
        }
        if (Dates.LENIENT == dates) {
            comparatorModes.add(LENIENT_DATES);
        }
        if (Defaults.IGNORE_DEFAULTS == defaults) {
            comparatorModes.add(IGNORE_DEFAULTS);
        }
        MocksControl.MockType type;
        if (Calls.LENIENT == calls) {
            type = NICE;
        } else {
            type = DEFAULT;
        }

        LenientMocksControl mocksControl = new LenientMocksControl(type, comparatorModes.toArray(new ReflectionComparatorMode[comparatorModes.size()]));
        if (InvocationOrder.STRICT == invocationOrder) {
            mocksControl.checkOrder(true);
        }
        return mocksControl;
    }

    /**
     * Creates an EasyMock mock object of the given type.
     *
     * @param mockType        the class type for the mock, not null
     * @param invocationOrder the order setting, not null
     * @param calls           the calls setting, not null
     * @return a mock for the given class or interface, not null
     */
    public MocksControl createRegularMocksControl(Class<?> mockType, InvocationOrder invocationOrder, Calls calls) {
        if (invocationOrder == InvocationOrder.DEFAULT) {
            invocationOrder = defaultInvocationOrder;
        }
        if (calls == Calls.DEFAULT) {
            calls = defaultCalls;
        }

        MocksControl.MockType type;
        if (Calls.LENIENT == calls) {
            type = NICE;
        } else {
            type = DEFAULT;
        }

        MocksControl mocksControl = new MocksClassControl(type);
        if (STRICT == invocationOrder) {
            mocksControl.checkOrder(true);
        }
        return mocksControl;
    }
}


text:
package org.apache.camel.component.eventadmin;

import java.util.Dictionary;
import java.util.Hashtable;

import org.apache.camel.spi.ComponentResolver;
import org.osgi.framework.BundleActivator;
import org.osgi.framework.BundleContext;
import org.osgi.framework.ServiceRegistration;

/**
 * The bundle activator registers a ServiceFactory
 * for creating a ComponentResolver.
 */
public class Activator implements BundleActivator {

    private ServiceRegistration<?> registration;

    public void start(BundleContext bundleContext) throws Exception {
        Dictionary<String, String> props = new Hashtable<String, String>();
        props.put("component", EventAdminComponent.NAME);
        registration = bundleContext.registerService(
                            ComponentResolver.class.getName(),
                            new EventAdminServiceFactory(),
                            props);
    }

    public void stop(BundleContext bundleContext) throws Exception {
        registration.unregister();
    }

}


text:
'use strict';

const _ = require('lodash');

const Request = require('./request');
const Response = require('./response');

class Route {
  constructor(url, endpoint, dataPath) {
    this.url = url;
    this.methods = {};
    this.id = _.uniqueId('route');
    this.dataPath = dataPath;

    this.init(endpoint);
  }

  init(endpoint) {
    // Allow for mime type extension in the url like /v1/users/me.json
    this.url = `${this.url}.:format?`;
    this.url = this.url.charAt(0) !== '/' ? `/${this.url}` : this.url;

    // Attach default file response for each http method
    _.each(['get', 'post', 'put', 'delete', 'head', 'patch'], method => {
      this.addMethod(method, endpoint);
    });
  }

  addMethod(method, endpoint) {
    if (!this.methods[method]) {
      // creates property get|post|put|delete... on route object
      this.methods[method] = [];
    }

    // Handle simple config that defines a file response for all methods
    //
    // EX:
    //
    // "v2/route2": {
    //   "latency": 250,
    //   "file": "example2.json"
    // }
    let response = new Response();
    response.set(endpoint);

    // Handle the syntactic sugar case where you can just define a method
    // and a file response in one line.
    //
    // EX:
    //
    // "v1/route4": {
    //   "get": "example1.json",
    //   "put": "example2.json",
    //   "post": "example3.json",
    //   "delete": "example4.json"
    // }
    if (_.isString(endpoint[method])) {
      response.file = endpoint[method];
    }

    let request = new Request();
    request.addResponse(response);
    this.methods[method].push(request);

    // "get": [
    //   {
    //     "file": "example2.json",
    //     ...
    //   }...
    if (_.isArray(endpoint[method])) {
      _.each(endpoint[method], _request => {
        // Handle default response.
        //
        // EX:
        //
        // "post": [
        //   {
        //     "file": "example2.json"
        //   }
        // ]
        if (!_request.params && !_request.headers && !_.isArray(_request.response)) {
          // If necessary, override the default response from the routes global response.
          if (this.methods[method][0]) {
            this.methods[method][0].responses[0].set(_request);
            // this.methods[method][0].responses[0].url  = _request.file;
          }

          return;
        }

        // {
        //   "file": "example3.json",
        //   "status": 202,
        //   "params": {
        //     "a": 1,
        //     "b": "sample.pdf"
        //   }
        // }
        request = new Request();
        request.params = _request.params;
        request.headers = _request.headers;
        // if a request configuration has both a file and response attribute defined, ignore the file
        // attribute and continue...this is most likely an async configuration
        if ((_request.file || _request.url || _request.status) && !_.isArray(_request.response)) {
          response = new Response(_request);
          request.responses.push(response);
        }

        // "response": [
        //   {
        //     "status": 202,
        //     "file": "example1.json"
        //   },
        //   {
        //     "status": 201,
        //     "file": "example2.json"
        //   }
        // ]...
        if (_.isArray(_request.response)) {
          _.each(_request.response, _response => {
            const __response = new Response(_request);
            __response.set(_response);
            request.responses.push(__response);
          });
        }

        this.methods[method].push(request);
      });
    }
  }
}

module.exports = Route;


text:
<menu xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto">

    <item
        android:id="@+id/id_action_add"
        android:icon="@drawable/actionbar_add_icon"
        android:orderInCategory="100"
        android:title="add"
        app:showAsAction="ifRoom"></item>
    <item
        android:id="@+id/id_action_delete"
        android:icon="@drawable/ic_menu_delete"
        android:orderInCategory="100"
        android:title="delete"
        app:showAsAction="ifRoom" />
    <item
        android:id="@+id/id_action_gridview"
        android:orderInCategory="100"
        android:title="GirdView"
        app:showAsAction="never" />
    <item
        android:id="@+id/id_action_listview"
        android:orderInCategory="100"
        android:title="ListView"
        app:showAsAction="never" />
    <item
        android:id="@+id/id_action_horizontalGridView"
        android:orderInCategory="100"
        android:title="HorizontalGridView"
        app:showAsAction="never" />

    <item
        android:id="@+id/id_action_staggeredgridview"
        android:orderInCategory="100"
        android:title="StaggeredGridView"
        app:showAsAction="never" />

</menu>


text:
#if !defined(_generic_code_H)
# define _generic_code_H

# include "entenc.h"
# include "entdec.h"

# define GENERIC_TABLES 12

typedef struct {
  /** cdf for multiple expectations of x */
  ogg_uint16_t cdf[GENERIC_TABLES][16];
  /** Frequency increment for learning the cdfs */
  int increment;
} generic_encoder;

void generic_model_init(generic_encoder *model);

void generic_encode(od_ec_enc *enc, generic_encoder *model, int x,
 int *ex_q16, int integration);

int generic_decode(od_ec_dec *dec, generic_encoder *model, int *ex_q16,
 int integration);

int log_ex(int ex_q16);

void generic_model_update(generic_encoder *model, int *ex_q16, int x, int xs,
 int id, int integration);

#endif


text:
<?php

namespace App\Tests\Improver;

use App\Improver\Reddit;
use App\Tests\AppTestCase;

class RedditTest extends AppTestCase
{
    public function dataMatch(): array
    {
        return [
            ['reddit.com', true],
            ['www.reddit.com', true],
            ['google.fr', false],
        ];
    }

    /**
     * @dataProvider dataMatch
     */
    public function testMatch(string $url, bool $expected): void
    {
        $reddit = new Reddit(self::getMockClient());

        $this->assertSame($expected, $reddit->match($url));
    }

    public function testUpdateUrl(): void
    {
        $reddit = new Reddit(self::getMockClient());

        $reddit->setItemContent('

  	 submitted by  drepicgames  to  mildlyinteresting
 [link] [254 commentaires]

');
        $this->assertSame('http://i.imgur.com/dvtXt1p.jpg', $reddit->updateUrl('http://0.0.0.0/content'));
    }

    public function testUpdateUrlFail(): void
    {
        $reddit = new Reddit(self::getMockClient());

        $reddit->setItemContent('empty');
        $this->assertSame('http://0.0.0.0/content', $reddit->updateUrl('http://0.0.0.0/content'));
    }

    public function testUpdateContent(): void
    {
        $reddit = new Reddit(self::getMockClient());

        $reddit->setItemContent('empty');
        $this->assertSame('empty

readable', $reddit->updateContent('readable'));
    }
}


text:
using Microsoft.VisualStudio.TestTools.UnitTesting;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace Yort.OnlineEftpos.Net40.Tests
{
	[TestClass]
	public class KnownBanksTests
	{
		[TestMethod]
		public void KnownBanks_LoadsDefaultList()
		{
			Assert.IsTrue(KnownBanks.All.Count() > 0);
		}

		[TestMethod]
		public void KnownBanks_LoadsAsbBank()
		{
			Assert.IsNotNull(KnownBanks.GetBank("ASB"));
		}

		[TestMethod]
		public void KnownBanks_LoadsCooperativeBank()
		{
			Assert.IsNotNull(KnownBanks.GetBank("Cooperative"));
		}

		[TestMethod]
		public void KnownBanks_LoadsWestpacBank()
		{
			Assert.IsNotNull(KnownBanks.GetBank("Westpac"));
		}

		[TestMethod]
		public void KnownBanks_IdLookupIsCaseInsensitive()
		{
			Assert.IsNotNull(KnownBanks.GetBank("ASB"));
			Assert.IsNotNull(KnownBanks.GetBank("Asb"));
			Assert.IsNotNull(KnownBanks.GetBank("aSB"));
			Assert.IsNotNull(KnownBanks.GetBank("aSb"));
			Assert.IsNotNull(KnownBanks.GetBank("westpac"));
			Assert.IsNotNull(KnownBanks.GetBank("Westpac"));
			Assert.IsNotNull(KnownBanks.GetBank("WESTPAC"));
			Assert.IsNotNull(KnownBanks.GetBank("cooperative"));
			Assert.IsNotNull(KnownBanks.GetBank("Cooperative"));
			Assert.IsNotNull(KnownBanks.GetBank("COOPERATIVE"));
		}

		#region AddBank Tests

		[TestMethod]
		public void KnownBanks_AddBank_AddsValidBankDefinition()
		{
			var id = System.Guid.NewGuid().ToString();
			var newBank = new BankDefinition(id, new List<string>(1) { "Mobile" });

			var oldCount = KnownBanks.All.Count();
			Assert.IsTrue(KnownBanks.AddBank(newBank));
			Assert.AreEqual(oldCount + 1, KnownBanks.All.Count());
			Assert.IsNotNull(KnownBanks.GetBank(id));
		}

		[TestMethod]
		[ExpectedException(typeof(ArgumentNullException))]
		public void KnownBanks_AddBank_ThrownOnNullBank()
		{
			KnownBanks.AddBank(null);
		}

		#endregion

		#region AddBank Tests

		[TestMethod]
		public void KnownBanks_RemoveBank_RemovesBankById()
		{
			var id = System.Guid.NewGuid().ToString();
			var newBank = new BankDefinition(id, new List<string>(1) { "Mobile" });
			KnownBanks.AddBank(newBank);

			var oldCount = KnownBanks.All.Count();
			Assert.IsTrue(KnownBanks.RemoveBank(id));

			Assert.AreEqual(oldCount - 1, KnownBanks.All.Count());
			Assert.IsNull(KnownBanks.GetBank(id));
		}

		[TestMethod]
		[ExpectedException(typeof(ArgumentNullException))]
		public void KnownBanks_AddBank_ThrownOnNullBankId()
		{
			KnownBanks.RemoveBank(null);
		}

		[TestMethod]
		[ExpectedException(typeof(ArgumentException))]
		public void KnownBanks_AddBank_ThrownOnEmptyBankId()
		{
			KnownBanks.RemoveBank(String.Empty);
		}

		[TestMethod]
		[ExpectedException(typeof(ArgumentException))]
		public void KnownBanks_AddBank_ThrownOnWhitespaceBankId()
		{
			KnownBanks.RemoveBank("   ");
		}

		#endregion

	}
}


text:
using System;
using System.Collections.Generic;
using System.Linq;
using osu.Framework;
using osu.Framework.Graphics;

namespace osu.Game.Beatmaps.Drawables
{
    public class BeatmapGroup : IStateful<BeatmapGroupState>
    {
        public event Action<BeatmapGroupState> StateChanged;

        public BeatmapPanel SelectedPanel;

        /// <summary>
        /// Fires when one of our difficulties was selected. Will fire on first expand.
        /// </summary>
        public Action<BeatmapGroup, BeatmapPanel> SelectionChanged;

        /// <summary>
        /// Fires when one of our difficulties is clicked when already selected. Should start playing the map.
        /// </summary>
        public Action<BeatmapInfo> StartRequested;

        public Action<BeatmapSetInfo> DeleteRequested;

        public Action<BeatmapSetInfo> RestoreHiddenRequested;

        public Action<BeatmapInfo> HideDifficultyRequested;

        public Action<BeatmapInfo> EditRequested;

        public BeatmapSetHeader Header;

        public List<BeatmapPanel> BeatmapPanels;

        public BeatmapSetInfo BeatmapSet;

        private BeatmapGroupState state;
        public BeatmapGroupState State
        {
            get { return state; }
            set
            {
                state = value;

                switch (value)
                {
                    case BeatmapGroupState.Expanded:
                        Header.State = PanelSelectedState.Selected;
                        foreach (BeatmapPanel panel in BeatmapPanels)
                            panel.State = panel == SelectedPanel ? PanelSelectedState.Selected : PanelSelectedState.NotSelected;
                        break;
                    case BeatmapGroupState.Collapsed:
                        Header.State = PanelSelectedState.NotSelected;
                        foreach (BeatmapPanel panel in BeatmapPanels)
                            panel.State = PanelSelectedState.Hidden;
                        break;
                    case BeatmapGroupState.Hidden:
                        Header.State = PanelSelectedState.Hidden;
                        foreach (BeatmapPanel panel in BeatmapPanels)
                            panel.State = PanelSelectedState.Hidden;
                        break;
                }

                StateChanged?.Invoke(state);
            }
        }

        public BeatmapGroup(BeatmapSetInfo beatmapSet, BeatmapManager manager)
        {
            BeatmapSet = beatmapSet;
            WorkingBeatmap beatmap = manager.GetWorkingBeatmap(BeatmapSet.Beatmaps.FirstOrDefault());

            Header = new BeatmapSetHeader(beatmap)
            {
                GainedSelection = headerGainedSelection,
                DeleteRequested = b => DeleteRequested(b),
                RestoreHiddenRequested = b => RestoreHiddenRequested(b),
                RelativeSizeAxes = Axes.X,
            };

            BeatmapPanels = BeatmapSet.Beatmaps.Where(b => !b.Hidden).OrderBy(b => b.StarDifficulty).Select(b => new BeatmapPanel(b)
            {
                Alpha = 0,
                GainedSelection = panelGainedSelection,
                HideRequested = p => HideDifficultyRequested?.Invoke(p),
                StartRequested = p => StartRequested?.Invoke(p.Beatmap),
                EditRequested = p => EditRequested?.Invoke(p.Beatmap),
                RelativeSizeAxes = Axes.X,
            }).ToList();

            Header.AddDifficultyIcons(BeatmapPanels);
        }

        private void headerGainedSelection(BeatmapSetHeader panel)
        {
            State = BeatmapGroupState.Expanded;

            //we want to make sure one of our children is selected in the case none have been selected yet.
            if (SelectedPanel == null)
                BeatmapPanels.First().State = PanelSelectedState.Selected;
        }

        private void panelGainedSelection(BeatmapPanel panel)
        {
            try
            {
                if (SelectedPanel == panel) return;

                if (SelectedPanel != null)
                    SelectedPanel.State = PanelSelectedState.NotSelected;
                SelectedPanel = panel;
            }
            finally
            {
                State = BeatmapGroupState.Expanded;
                SelectionChanged?.Invoke(this, SelectedPanel);
            }
        }
    }

    public enum BeatmapGroupState
    {
        Collapsed,
        Expanded,
        Hidden,
    }
}


text:
Videogular Autohide-Cursor plugin

## How to install

Install [Videogular](http://www.videogular.com/) `Hide Cursor` plugin with Bower:

`bower install --save videogular-autohide-cursor`

Add the plugin and ng-debounce (installed by the command above as well) to your loaded scripts:

```html
<script src="bower_components/ng-debounce/angular-debounce.js"></script>
<script src="bower_components/videogular-autohide-cursor/hide-cursor.js"></script>
```

## How to use

Add the `vg-autohide-cursor` directive to your `videogular` element:

```html
<videogular vg-autohide-cursor="{{ config.autohideCursor.enabled }}"
            vg-autohide-cursor-time="{{ config.autohideCursor.time }}">
  <video class='videoPlayer' preload='metadata'>
    <source type="video/type" src="path/to/video" />
  </video>
</videogular>
```

Use the optional `vg-autohide-cursor-time` attribute to customise the delay
for hiding the cursor. The default is 1 second.

If you are using a theme, you might need to use `vg-autohide-cursor-target` to specify
via a class which child element(s) cursors to hide.

```html
<videogular vg-autohide-cursor="{{ config.autohideCursor.enabled }}"
            vg-autohide-cursor-time="{{ config.autohideCursor.time }}"
            vg-autohide-cursor-target="overlayPlayContainer"
            vg-stretch="config.stretch" vg-autoplay="config.autoPlay" vg-theme="config.theme.url">
    <video class="videoPlayer" preload="auto">
        <source ng-src="{{ video.src }}" type="{{ video.type }}">
    </video>
    <vg-overlay-play vg-play-icon="config.theme.playIcon">
      <div vg-autohide-cursor="{{ config.autohideCursor.enabled }}"
           vg-autohide-cursor-time="{{ config.autohideCursor.time }}"
           class="overlayPlayContainer">
        <div class="iconButton ng-binding"></div>
      </div>
    </vg-overlay-play>
</videogular>
```

Additionally, you will need to add the plugin as a dependency of your application:

```js
angular.module("myVideogularApp", [
  "com.2fdevs.videogular",
  "com.javiercejudo.videogular.plugins.autohide-cursor"
]);
```


text:
import os
from setuptools import setup

LONG_DESCRIPTION = """
Django confirmaction is a battery for confirm actions via email, sms etc.
"""

def long_description():
    try:
        return open(
            os.path.join(os.path.dirname(__file__), "README.md")
        ).read()
    except IOError:
        return LONG_DESCRIPTION

setup(
    name = "django-confirmaction",
    version = "0.0.3",
    author = "Aleksandr Aibulatov",
    author_email = "zap.aibulatov@gmail.com",
    description = "Django battery for confirm some action via email, sms, etc",
    license = "BSD",
    keywords = "django, battery, confirm action",
    url = "https://github.com/Zapix/django-confirmaction",
    packages=[
        'confirmaction',
        'confirmaction.migrations'
    ],
    long_description=long_description(),
    install_requires=[
        'django>=1.6',
        'south>=0.8.4',
        'pycrypto'
    ],
    classifiers=[
        "Development Status :: 2 - Pre-Alpha",
        "Framework :: Django",
        "Programming Language :: Python :: 2.7",
        "Topic :: Utilities",
        "License :: OSI Approved :: BSD License",
    ],
)


text:
//
using System;

namespace BD2.Core.NetworkKeyValueStorage
{
	public class EnumerateResponseMessage
	{
		public EnumerateResponseMessage ()
		{
		}
	}
}


text:
/* This file was generated by upbc (the upb compiler) from the input
 * file:
 *
 *     envoy/config/listener/v3/listener_components.proto
 *
 * Do not edit -- your changes will be discarded when the file is
 * regenerated. */

#include <stddef.h>
#include "upb/msg.h"
#include "envoy/config/listener/v3/listener_components.upb.h"
#include "envoy/config/core/v3/address.upb.h"
#include "envoy/config/core/v3/base.upb.h"
#include "envoy/type/v3/range.upb.h"
#include "google/protobuf/any.upb.h"
#include "google/protobuf/struct.upb.h"
#include "google/protobuf/wrappers.upb.h"
#include "udpa/annotations/status.upb.h"
#include "udpa/annotations/versioning.upb.h"
#include "validate/validate.upb.h"

#include "upb/port_def.inc"

static const upb_msglayout *const envoy_config_listener_v3_Filter_submsgs[1] = {
  &google_protobuf_Any_msginit,
};

static const upb_msglayout_field envoy_config_listener_v3_Filter__fields[2] = {
  {1, UPB_SIZE(0, 0), 0, 0, 9, 1},
  {4, UPB_SIZE(8, 16), UPB_SIZE(-13, -25), 0, 11, 1},
};

const upb_msglayout envoy_config_listener_v3_Filter_msginit = {
  &envoy_config_listener_v3_Filter_submsgs[0],
  &envoy_config_listener_v3_Filter__fields[0],
  UPB_SIZE(16, 32), 2, false,
};

static const upb_msglayout *const envoy_config_listener_v3_FilterChainMatch_submsgs[4] = {
  &envoy_config_core_v3_CidrRange_msginit,
  &google_protobuf_UInt32Value_msginit,
};

static const upb_msglayout_field envoy_config_listener_v3_FilterChainMatch__fields[10] = {
  {3, UPB_SIZE(32, 56), 0, 0, 11, 3},
  {4, UPB_SIZE(8, 8), 0, 0, 9, 1},
  {5, UPB_SIZE(24, 40), 0, 1, 11, 1},
  {6, UPB_SIZE(36, 64), 0, 0, 11, 3},
  {7, UPB_SIZE(40, 72), 0, 0, 13, _UPB_LABEL_PACKED},
  {8, UPB_SIZE(28, 48), 0, 1, 11, 1},
  {9, UPB_SIZE(16, 24), 0, 0, 9, 1},
  {10, UPB_SIZE(44, 80), 0, 0, 9, 3},
  {11, UPB_SIZE(48, 88), 0, 0, 9, 3},
  {12, UPB_SIZE(0, 0), 0, 0, 14, 1},
};

const upb_msglayout envoy_config_listener_v3_FilterChainMatch_msginit = {
  &envoy_config_listener_v3_FilterChainMatch_submsgs[0],
  &envoy_config_listener_v3_FilterChainMatch__fields[0],
  UPB_SIZE(56, 96), 10, false,
};

static const upb_msglayout *const envoy_config_listener_v3_FilterChain_submsgs[5] = {
  &envoy_config_core_v3_Metadata_msginit,
  &envoy_config_core_v3_TransportSocket_msginit,
  &envoy_config_listener_v3_Filter_msginit,
  &envoy_config_listener_v3_FilterChainMatch_msginit,
  &google_protobuf_BoolValue_msginit,
};

static const upb_msglayout_field envoy_config_listener_v3_FilterChain__fields[6] = {
  {1, UPB_SIZE(8, 16), 0, 3, 11, 1},
  {3, UPB_SIZE(24, 48), 0, 2, 11, 3},
  {4, UPB_SIZE(12, 24), 0, 4, 11, 1},
  {5, UPB_SIZE(16, 32), 0, 0, 11, 1},
  {6, UPB_SIZE(20, 40), 0, 1, 11, 1},
  {7, UPB_SIZE(0, 0), 0, 0, 9, 1},
};

const upb_msglayout envoy_config_listener_v3_FilterChain_msginit = {
  &envoy_config_listener_v3_FilterChain_submsgs[0],
  &envoy_config_listener_v3_FilterChain__fields[0],
  UPB_SIZE(32, 64), 6, false,
};

static const upb_msglayout *const envoy_config_listener_v3_ListenerFilterChainMatchPredicate_submsgs[4] = {
  &envoy_config_listener_v3_ListenerFilterChainMatchPredicate_msginit,
  &envoy_config_listener_v3_ListenerFilterChainMatchPredicate_MatchSet_msginit,
  &envoy_type_v3_Int32Range_msginit,
};

static const upb_msglayout_field envoy_config_listener_v3_ListenerFilterChainMatchPredicate__fields[5] = {
  {1, UPB_SIZE(0, 0), UPB_SIZE(-5, -9), 1, 11, 1},
  {2, UPB_SIZE(0, 0), UPB_SIZE(-5, -9), 1, 11, 1},
  {3, UPB_SIZE(0, 0), UPB_SIZE(-5, -9), 0, 11, 1},
  {4, UPB_SIZE(0, 0), UPB_SIZE(-5, -9), 0, 8, 1},
  {5, UPB_SIZE(0, 0), UPB_SIZE(-5, -9), 2, 11, 1},
};

const upb_msglayout envoy_config_listener_v3_ListenerFilterChainMatchPredicate_msginit = {
  &envoy_config_listener_v3_ListenerFilterChainMatchPredicate_submsgs[0],
  &envoy_config_listener_v3_ListenerFilterChainMatchPredicate__fields[0],
  UPB_SIZE(8, 16), 5, false,
};

static const upb_msglayout *const envoy_config_listener_v3_ListenerFilterChainMatchPredicate_MatchSet_submsgs[1] = {
  &envoy_config_listener_v3_ListenerFilterChainMatchPredicate_msginit,
};

static const upb_msglayout_field envoy_config_listener_v3_ListenerFilterChainMatchPredicate_MatchSet__fields[1] = {
  {1, UPB_SIZE(0, 0), 0, 0, 11, 3},
};

const upb_msglayout envoy_config_listener_v3_ListenerFilterChainMatchPredicate_MatchSet_msginit = {
  &envoy_config_listener_v3_ListenerFilterChainMatchPredicate_MatchSet_submsgs[0],
  &envoy_config_listener_v3_ListenerFilterChainMatchPredicate_MatchSet__fields[0],
  UPB_SIZE(4, 8), 1, false,
};

static const upb_msglayout *const envoy_config_listener_v3_ListenerFilter_submsgs[2] = {
  &envoy_config_listener_v3_ListenerFilterChainMatchPredicate_msginit,
  &google_protobuf_Any_msginit,
};

static const upb_msglayout_field envoy_config_listener_v3_ListenerFilter__fields[3] = {
  {1, UPB_SIZE(0, 0), 0, 0, 9, 1},
  {3, UPB_SIZE(12, 24), UPB_SIZE(-17, -33), 1, 11, 1},
  {4, UPB_SIZE(8, 16), 0, 0, 11, 1},
};

const upb_msglayout envoy_config_listener_v3_ListenerFilter_msginit = {
  &envoy_config_listener_v3_ListenerFilter_submsgs[0],
  &envoy_config_listener_v3_ListenerFilter__fields[0],
  UPB_SIZE(24, 48), 3, false,
};

#include "upb/port_undef.inc"


text:
CVER=2.2.7
YCSBVER=0.10.0

sudo apt-get -y update
sudo apt-get -y install build-essential

# install java 8
#sudo add-apt-repository ppa:webupd8team/java
#sudo apt-get -y update
#sudo apt-get -y install oracle-java8-installer
#sudo apt-get -y install oracle-java8-set-default
sudo apt-get install openjdk-8-jdk
# test
java -version
sudo apt-get -y install ntp

# install python and cassandra driver
sudo apt-get -y install python
sudo apt-get install -y python-pip
sudo pip install cqlsh

# install cassandra
mkdir -p ~/cassandra
cd  ~/cassandra
wget http://archive.apache.org/dist/cassandra/$CVER/apache-cassandra-$CVER-bin.tar.gz
tar -xzvf apache-cassandra-$CVER-bin.tar.gz
sudo mkdir /var/lib/cassandra
sudo mkdir /var/log/cassandra
sudo chown -R $USER:$GROUP /var/lib/cassandra
sudo chown -R $USER:$GROUP /var/log/cassandra
cd ~/cassandra
unlink current-version
ln -s apache-cassandra-$CVER current-version

export CASSANDRA_HOME=~/cassandra/current-version
export PATH=$PATH:$CASSANDRA_HOME/bin
# test
sh current-version/bin/cassandra
sh current-version/bin/cqlsh

# install YCSB
mkdir -p ~/ycsb
cd  ~/ycsb
curl -O --location https://github.com/brianfrankcooper/YCSB/releases/download/$YCSBVER/ycsb-$YCSBVER.tar.gz
tar xfvz ycsb-$YCSBVER.tar.gz
unlink current-version
ln -s ycsb-$YCSBVER current-version


text:
package terraform

import (
	"github.com/hashicorp/terraform/addrs"
	"github.com/hashicorp/terraform/configs"
)

// RootVariableTransformer is a GraphTransformer that adds all the root
// variables to the graph.
//
// Root variables are currently no-ops but they must be added to the
// graph since downstream things that depend on them must be able to
// reach them.
type RootVariableTransformer struct {
	Config *configs.Config
}

func (t *RootVariableTransformer) Transform(g *Graph) error {
	// We can have no variables if we have no config.
	if t.Config == nil {
		return nil
	}

	// We're only considering root module variables here, since child
	// module variables are handled by ModuleVariableTransformer.
	vars := t.Config.Module.Variables

	// Add all variables here
	for _, v := range vars {
		node := &NodeRootVariable{
			Addr: addrs.InputVariable{
				Name: v.Name,
			},
			Config: v,
		}
		g.Add(node)
	}

	return nil
}


text:
$(function() {
    var animationValue = 10;
    var SpeedAnimation = 220;

    $(document).on('mouseenter', '.tooltip', function() {
        var tooltipContent = $(this).find('.tooltip-content');
        var tooltipVisibility = $(this).attr('data-visibility');
        var tooltipClickable = $(this).attr('data-clickable');
        var tooltipPosition = $(this).attr('data-position');

        if (tooltipVisibility != 'none'){
          tooltipContent.addClass('tooltip-content-' + tooltipPosition);
          tooltipContent.css({
              'opacity': ''
          });
        if (tooltipClickable != 'none') {
          tooltipContent.addClass('tooltip-content-clickable-' + tooltipPosition);
        }

        switch (tooltipPosition) {
            case 'top':
               if ($(this).css('position') == 'relative') {
                 var positionVertical = tooltipContent.innerHeight() - (tooltipContent.innerHeight() * 2);
                 var positionHorizontal = ($(this).outerWidth(true) - tooltipContent.outerWidth(true)) / 2;
               }
                 else {
                  var positionVertical = $(this).position().top - tooltipContent.innerHeight() + parseInt($(this).css('margin-top'));
                  var positionHorizontal = $(this).position().left + ($(this).outerWidth(true) - tooltipContent.outerWidth(true)) / 2;
            }

                var positionVerticalAnimation = positionVertical - animationValue;

                break
            case 'bottom':
            if ($(this).css('position') == 'relative') {
              var positionVertical = $(this).innerHeight();
              var positionHorizontal = ($(this).outerWidth(true) - tooltipContent.outerWidth(true)) / 2;
            } else {
              var positionVertical = $(this).position().top + $(this).innerHeight() + parseInt($(this).css('margin-top'));
              var positionHorizontal = $(this).position().left + ($(this).outerWidth(true) - tooltipContent.outerWidth(true)) / 2;
            }

                var positionVerticalAnimation = positionVertical + animationValue;
                break
            case 'left':
                if ($(this).css('position') == 'relative') {
                  var positionHorizontal = tooltipContent.outerWidth(true) - (tooltipContent.outerWidth(true)*2);
                  var positionVertical = (($(this).innerHeight() - tooltipContent.innerHeight()) / 2);
                }
                else {
                  var positionHorizontal = $(this).position().left - tooltipContent.outerWidth(true) + parseInt($(this).css('margin-left'));
                  var positionVertical = $(this).position().top + ($(this).innerHeight() - tooltipContent.innerHeight()) / 2 + parseInt($(this).css('margin-top'));
                }
                var positionHorizontalAnimation = positionHorizontal - animationValue;
                break
            case 'right':
                if ($(this).css('position') == 'relative') {
                  var positionVertical = (($(this).innerHeight() - tooltipContent.innerHeight()) / 2);
                  var positionHorizontal = $(this).outerWidth(true);
                }
                else {
                  var positionVertical = $(this).position().top + ($(this).innerHeight() - tooltipContent.innerHeight()) / 2 + parseInt($(this).css('margin-top'));
                  var positionHorizontal = $(this).position().left + $(this).outerWidth(true) - parseInt($(this).css('margin-right'));
                }
                var positionHorizontalAnimation = positionHorizontal + animationValue;

                break
        }

        tooltipContent.css({
            'top': +positionVertical + 'px',
            'left': +positionHorizontal + 'px'
        }).fadeIn({
            queue: false,
            duration: SpeedAnimation
        }).animate({
            'top': +positionVerticalAnimation + 'px',
            'left': +positionHorizontalAnimation + 'px'
        }, SpeedAnimation);

    }});
          $(document).on('mouseleave', '.tooltip', function() {
        var tooltipContent = $(this).find('.tooltip-content');

        switch ($(this).attr('data-position')) {
            case 'top':
                var positionVerticalAnimation = parseInt($(tooltipContent).css("top")) + animationValue;
                break
            case 'bottom':
                var positionVerticalAnimation = parseInt($(tooltipContent).css("top")) - animationValue;
                break
            case 'left':
                var positionHorizontalAnimation = parseInt($(tooltipContent).css("left")) + animationValue;
                break
            case 'right':
                var positionHorizontalAnimation = parseInt($(tooltipContent).css("left")) - animationValue;
                break
        }
        tooltipContent.fadeOut({
            queue: false,
            duration: SpeedAnimation
        }).animate({
            'top': +positionVerticalAnimation + 'px',
            'left': +positionHorizontalAnimation + 'px'
        }, SpeedAnimation);

    });
})


text:
package decorator

import (
	"io"
	"testing"

	"github.com/docker/libtrust"

	"github.com/docker/distribution/digest"
	"github.com/docker/distribution/manifest"
	"github.com/docker/distribution/storage"
	"github.com/docker/distribution/storagedriver/inmemory"
	"github.com/docker/distribution/testutil"
)

func TestRegistryDecorator(t *testing.T) {
	// Initialize the expected decorations. Call counting is a horrible way to
	// test this but should keep this code from being atrocious.
	expected := map[string]int{
		"repository":      1,
		"manifestservice": 1,
		"layerservice":    1,
		"layer":           4,
		"layerupload":     4,
	}
	decorated := map[string]int{}

	decorator := Func(func(v interface{}) interface{} {
		switch v := v.(type) {
		case storage.Repository:
			t.Logf("decorate repository: %T", v)
			decorated["repository"]++
		case storage.ManifestService:
			t.Logf("decorate manifestservice: %T", v)
			decorated["manifestservice"]++
		case storage.LayerService:
			t.Logf("decorate layerservice: %T", v)
			decorated["layerservice"]++
		case storage.Layer:
			t.Logf("decorate layer: %T", v)
			decorated["layer"]++
		case storage.LayerUpload:
			t.Logf("decorate layerupload: %T", v)
			decorated["layerupload"]++
		default:
			t.Fatalf("unexpected object decorated: %v", v)
		}

		return v
	})

	registry := storage.NewRegistryWithDriver(inmemory.New())
	registry = DecorateRegistry(registry, decorator)

	// Now take the registry through a number of operations
	checkExerciseRegistry(t, registry)

	for component, calls := range expected {
		if decorated[component] != calls {
			t.Fatalf("%v was not decorated expected number of times: %d != %d", component, decorated[component], calls)
		}
	}

}

// checkExerciseRegistry takes the registry through all of its operations,
// carrying out generic checks.
func checkExerciseRegistry(t *testing.T, registry storage.Registry) {
	name := "foo/bar"
	tag := "thetag"
	repository := registry.Repository(name)
	m := manifest.Manifest{
		Versioned: manifest.Versioned{
			SchemaVersion: 1,
		},
		Name: name,
		Tag:  tag,
	}

	layers := repository.Layers()
	for i := 0; i < 2; i++ {
		rs, ds, err := testutil.CreateRandomTarFile()
		if err != nil {
			t.Fatalf("error creating test layer: %v", err)
		}
		dgst := digest.Digest(ds)
		upload, err := layers.Upload()
		if err != nil {
			t.Fatalf("error creating layer upload: %v", err)
		}

		// Use the resumes, as well!
		upload, err = layers.Resume(upload.UUID())
		if err != nil {
			t.Fatalf("error resuming layer upload: %v", err)
		}

		io.Copy(upload, rs)

		if _, err := upload.Finish(dgst); err != nil {
			t.Fatalf("unexpected error finishing upload: %v", err)
		}

		m.FSLayers = append(m.FSLayers, manifest.FSLayer{
			BlobSum: dgst,
		})

		// Then fetch the layers
		if _, err := layers.Fetch(dgst); err != nil {
			t.Fatalf("error fetching layer: %v", err)
		}
	}

	pk, err := libtrust.GenerateECP256PrivateKey()
	if err != nil {
		t.Fatalf("unexpected error generating key: %v", err)
	}

	sm, err := manifest.Sign(&m, pk)
	if err != nil {
		t.Fatalf("unexpected error signing manifest: %v", err)
	}

	manifests := repository.Manifests()

	if err := manifests.Put(tag, sm); err != nil {
		t.Fatalf("unexpected error putting the manifest: %v", err)
	}

	fetched, err := manifests.Get(tag)
	if err != nil {
		t.Fatalf("unexpected error fetching manifest: %v", err)
	}

	if fetched.Tag != fetched.Tag {
		t.Fatalf("retrieved unexpected manifest: %v", err)
	}
}


text:
class IMU
{
  public:
    enum tOrientation {eOther, eUp, eLeft, eRight, eDown, eFaceUp, eFaceDown};

    void Init(bool UseEXTERNAL, bool LowG);
    int ReadCentiG(int Pin);
    int ReadRaw(int Pin);
    char* AsBar(int CentiG, char* Buffer, char Axis);

    tOrientation GetOrientation(int PinX, int PinY, int PinZ);

  private:
    bool m_bUseEXTERNAL;
    bool m_bLowG;
};

extern IMU imu;

#endif


text:
package org.dyndns.buefield.vmm.service;

import java.util.Date;
import java.util.List;

import javax.annotation.Resource;

import org.dyndns.buefield.vmm.entity.PjRoom;
import org.seasar.extension.jdbc.JdbcManager;

public class PjRoomService {
	@Resource protected JdbcManager jdbcManager;

	public List<PjRoom> findAll() {
		return jdbcManager.from(PjRoom.class).orderBy("pjNo").getResultList();
	}

	public PjRoom findById(Object id) {
		if (id == null) return null;
		return jdbcManager.from(PjRoom.class).where("id=?", id).getSingleResult();
	}

	public void update(PjRoom pjr) {
		pjr.updateDt = new Date();
		jdbcManager.update(pjr).execute();
	}

	public void insert(PjRoom pjr) {
		pjr.updateDt = new Date();
		jdbcManager.insert(pjr).execute();
	}
}


text:
/*
 * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except
 * in compliance with the License. You may obtain a copy of the License at
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software distributed under the License
 * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express
 * or implied. See the License for the specific language governing permissions and limitations under
 * the License.
 */
/*
 * This code was generated by https://github.com/googleapis/google-api-java-client-services/
 * Modify at your own risk.
 */

package com.google.api.services.eventarc.v1beta1.model;

/**
 * Represents a Cloud Run service destination.
 *
 *
 This is the Java data model class that specifies how to parse/serialize into the JSON that is
 * transmitted over HTTP when working with the Eventarc API. For a detailed explanation see:
 * https://developers.google.com/api-client-library/java/google-http-java-client/json
 *

 *
 * @author Google, Inc.
 */
@SuppressWarnings("javadoc")
public final class CloudRunService extends com.google.api.client.json.GenericJson {

  /**
   * Optional. The relative path on the Cloud Run service the events should be sent to. The value
   * must conform to the definition of URI path segment (section 3.3 of RFC2396). Examples:
   * "/route", "route", "route/subroute".
   * The value may be {@code null}.
   */
  @com.google.api.client.util.Key
  private java.lang.String path;

  /**
   * Required. The region the Cloud Run service is deployed in.
   * The value may be {@code null}.
   */
  @com.google.api.client.util.Key
  private java.lang.String region;

  /**
   * Required. The name of the Cloud run service being addressed (see
   * https://cloud.google.com/run/docs/reference/rest/v1/namespaces.services). Only services located
   * in the same project of the trigger object can be addressed.
   * The value may be {@code null}.
   */
  @com.google.api.client.util.Key
  private java.lang.String service;

  /**
   * Optional. The relative path on the Cloud Run service the events should be sent to. The value
   * must conform to the definition of URI path segment (section 3.3 of RFC2396). Examples:
   * "/route", "route", "route/subroute".
   * @return value or {@code null} for none
   */
  public java.lang.String getPath() {
    return path;
  }

  /**
   * Optional. The relative path on the Cloud Run service the events should be sent to. The value
   * must conform to the definition of URI path segment (section 3.3 of RFC2396). Examples:
   * "/route", "route", "route/subroute".
   * @param path path or {@code null} for none
   */
  public CloudRunService setPath(java.lang.String path) {
    this.path = path;
    return this;
  }

  /**
   * Required. The region the Cloud Run service is deployed in.
   * @return value or {@code null} for none
   */
  public java.lang.String getRegion() {
    return region;
  }

  /**
   * Required. The region the Cloud Run service is deployed in.
   * @param region region or {@code null} for none
   */
  public CloudRunService setRegion(java.lang.String region) {
    this.region = region;
    return this;
  }

  /**
   * Required. The name of the Cloud run service being addressed (see
   * https://cloud.google.com/run/docs/reference/rest/v1/namespaces.services). Only services located
   * in the same project of the trigger object can be addressed.
   * @return value or {@code null} for none
   */
  public java.lang.String getService() {
    return service;
  }

  /**
   * Required. The name of the Cloud run service being addressed (see
   * https://cloud.google.com/run/docs/reference/rest/v1/namespaces.services). Only services located
   * in the same project of the trigger object can be addressed.
   * @param service service or {@code null} for none
   */
  public CloudRunService setService(java.lang.String service) {
    this.service = service;
    return this;
  }

  @Override
  public CloudRunService set(String fieldName, Object value) {
    return (CloudRunService) super.set(fieldName, value);
  }

  @Override
  public CloudRunService clone() {
    return (CloudRunService) super.clone();
  }

}


text:
package pv.com.pvcloudgo.vc.adapter;

import android.content.Context;

import java.util.List;

import pv.com.pvcloudgo.R;
import pv.com.pvcloudgo.model.bean.ChargeRule;

/**
 */
public class ChargeItemAdapter extends SimpleAdapter<ChargeRule> {

    public ChargeItemAdapter(Context context, List<ChargeRule> datas) {
        super(context, R.layout.item_charge_phone, datas);
    }

    @Override
    protected void convert(BaseViewHolder viewHoder, ChargeRule item) {

        viewHoder.getTextView(R.id.item_c_price_tv).setText(String.valueOf(item.getChongzhiPrice()));
        viewHoder.getTextView(R.id.item_c_saleprice_tv).setText("售价 ¥"+item.getPrice());
        viewHoder.getTextView(R.id.item_c_v_tv).setText("V值 "+item.getV()+"V");
    }

}


text:
module Cldr
  module Export
    module Data
      class Lists < Base
        def initialize(locale)
          super
          update(lists: lists)
        end

        def lists
          select("listPatterns/listPattern").each_with_object({}) do |list_pattern, list_pattern_ret|
            pattern_type = if (attribute = list_pattern.attribute("type"))
              attribute.value.to_sym
            else
              :default
            end

            list_pattern_ret[pattern_type] = select(list_pattern, "listPatternPart").each_with_object({}) do |part, part_ret|
              part_ret[part.attribute("type").value.to_sym] = part.content
            end
          end
        end
      end
    end
  end
end


text:
<!DOCTYPE html>

<meta charset=utf-8>
<title>213 nips-2013-Nonparametric Multi-group Membership Model for Dynamic Networks</title>

nips nips2013 nips2013-213 nips2013-213-reference knowledge-graph by maker-knowledge-mining

213 nips-2013-Nonparametric Multi-group Membership Model for Dynamic Networks

Source: pdf

Author: Myunghwan Kim, Jure Leskovec

Abstract: unkown-abstract

reference text

[1] E. M. Airoldi, D. M. Blei, S. E. Fienberg, and E. P. Xing. Mixed membership stochastic blockmodels. JMLR, 9, 2008.

[2] L. Backstrom and J. Leskovec. Supervised random walks: Predicting and recommending links in social networks. In WSDM, 2011.  8

[3] S. Duane, A. Kennedy, B. J. Pendleton, and D. Roweth. 195(2):216–222, 1987.  Hybrid monte carlo.  Physics Letter B,

[4] J. Foulds, A. U. Asuncion, C. DuBois, C. T. Butts, and P. Smyth. A dynamic relational infinite feature model for longitudinal social networks. In AISTATS, 2011.

[5] W. Fu, L. Song, and E. P. Xing. Dynamic mixed membership blockmodel for evolving networks. In ICML, 2009.

[6] J. V. Gael, Y. W. Teh, , and Z. Ghahramani. The infinite factorial hidden markov model. In NIPS, 2009.

[7] S. J. Gershman, P. I. Frazier, and D. M. Blei. arXiv:1110.5454, 2012.  Distance dependent infinite latent feature models.

[8] Z. Ghahramani and M. I. Jordan. Factorial hidden markov models. Machine Learning, 29(2-3):245–273, 1997.

[9] F. Guo, S. Hanneke, W. Fu, and E. P. Xing. Recovering temporally rewiring networks: a model-based approach. In ICML, 2007.

[10] S. Hanneke, W. Fu, and E. P. Xing. Discrete temporal models of social networks. Electron. J. Statist., 4:585–605, 2010.

[11] C. Heaukulani and Z. Ghahramani. Dynamic probabilistic models for latent feature propagation in social networks. In ICML, 2013.

[12] Q. Ho, L. Song, and E. P. Xing. Evolving cluster mixed-membership blockmodel for time-varying networks. In AISTATS, 2011.

[13] P. D. Hoff, A. E. Raftery, and M. S. Handcock. Latent space approaches to social network analysis. JASA, 97(460):1090 – 1098, 2002.

[14] K. Ishiguro, T. Iwata, N. Ueda, and J. Tenenbaum. Dynamic infinite relational model for time-varying relational data analysis. In NIPS, 2010.

[15] S. Kairam, D. Wang, and J. Leskovec. The life and death of online groups: Predicting group growth and longevity. In WSDM, 2012.

[16] M. Kim and J. Leskovec. Modeling social networks with node attributes using the multiplicative attribute graph model. In UAI, 2011.

[17] M. Kim and J. Leskovec. Latent multi-group membership graph model. In ICML, 2012.

[18] M. Kim and J. Leskovec. Multiplicative attribute graph model of real-world networks. Internet Mathematics, 8(1-2):113–160, 2012.

[19] M. Kim and J. Leskovec. arXiv:1311.2079, 2013.  Nonparametric multi-group membership model for dynamic networks.

[20] J. R. Lloyd, P. Orbanz, Z. Ghahramani, and D. M. Roy. Random function priors for exchangeable arrays with applications to graphs and relational data. In NIPS, 2012.

[21] K. T. Miller, T. L. Grifths, and M. I. Jordan. Nonparametric latent feature models for link prediction. In NIPS, 2009.

[22] M. Mørup, M. N. Schmidt, and L. K. Hansen. Infinite multiple membership relational modeling for complex networks. In MLSP, 2011.

[23] K. Palla, D. A. Knowles, and Z. Ghahramani. An infinite latent attribute model for network data. In ICML, 2012.

[24] P. Sarkar and A. W. Moore. Dynamic social network analysis using latent space models. In NIPS, 2005.

[25] J. Scott, R. Gass, J. Crowcroft, P. Hui, C. Diot, and A. Chaintreau. CRAWDAD data set cambridge/haggle (v. 2009-05-29), May 2009.

[26] S. L. Scott. Bayesian methods for hidden markov models. JASA, 97(457):337–351, 2002.

[27] T. A. B. Snijders, G. G. van de Bunt, and C. E. G. Steglich. Introduction to stochastic actor-based models for network dynamics. Social Networks, 32(1):44–60, 2010.

[28] J. Tang, J. Zhang, L. Yao, J. Li, L. Zhang, and Z. Su. Arnetminer: Extraction and mining of academic social networks. In KDD'08, 2008.

[29] J. Yang and J. Leskovec. Community-affiliation graph model for overlapping community detection. In ICDM, 2012.  9


text:
package bigqueryexport;

// [START securitycenter_update_bigquery_export]

import com.google.cloud.securitycenter.v1.BigQueryExport;
import com.google.cloud.securitycenter.v1.SecurityCenterClient;
import com.google.cloud.securitycenter.v1.UpdateBigQueryExportRequest;
import com.google.protobuf.FieldMask;
import java.io.IOException;

public class UpdateBigQueryExport {

  public static void main(String[] args) throws IOException {
    // TODO(Developer): Modify the following variable values.

    // parent: Use any one of the following resource paths:
    //              - organizations/{organization_id}
    //              - folders/{folder_id}
    //              - projects/{project_id}
    String parent = String.format("projects/%s", "your-google-cloud-project-id");

    // filter: Expression that defines the filter to apply across create/update events of findings.
    String filter =
        "severity=\"LOW\" OR severity=\"MEDIUM\" AND "
            + "category=\"Persistence: IAM Anomalous Grant\" AND "
            + "-resource.type:\"compute\"";

    // bigQueryExportId: Unique identifier provided by the client.
    // For more info, see:
    // https://cloud.google.com/security-command-center/docs/how-to-analyze-findings-in-big-query#export_findings_from_to
    String bigQueryExportId = "big-query-export-id";

    updateBigQueryExport(parent, filter, bigQueryExportId);
  }

  // Updates an existing BigQuery export.
  public static void updateBigQueryExport(String parent, String filter, String bigQueryExportId)
      throws IOException {
    // Initialize client that will be used to send requests. This client only needs to be created
    // once, and can be reused for multiple requests. After completing all of your requests, call
    // the "close" method on the client to safely clean up any remaining background resources.
    try (SecurityCenterClient client = SecurityCenterClient.create()) {

      //  Set the new values for export configuration.
      BigQueryExport bigQueryExport =
          BigQueryExport.newBuilder()
              .setName(String.format("%s/bigQueryExports/%s", parent, bigQueryExportId))
              .setFilter(filter)
              .build();

      UpdateBigQueryExportRequest request =
          UpdateBigQueryExportRequest.newBuilder()
              .setBigQueryExport(bigQueryExport)
              // Set the update mask to specify which properties should be updated.
              // If empty, all mutable fields will be updated.
              // For more info on constructing field mask path, see the proto or:
              // https://cloud.google.com/java/docs/reference/protobuf/latest/com.google.protobuf.FieldMask
              .setUpdateMask(FieldMask.newBuilder().addPaths("filter").build())
              .build();

      BigQueryExport response = client.updateBigQueryExport(request);
      if (!response.getFilter().equalsIgnoreCase(filter)) {
        System.out.println("Failed to update BigQueryExport!");
        return;
      }
      System.out.println("BigQueryExport updated successfully!");
    }
  }
}
// [END securitycenter_update_bigquery_export]


text:
<?php
namespace Chamilo\Application\Weblcms\Bridge\Assignment\Storage\DataClass;

/**
 *
 * @package Chamilo\Application\Weblcms\Bridge\Assignment\Storage\DataClass
 * @author Hans De Bisschop <hans.de.bisschop@ehb.be>
 * @author Magali Gillard <magali.gillard@ehb.be>
 * @author Eduard Vossen <eduard.vossen@ehb.be>
 */
class EntryPlagiarismResult extends \Chamilo\Core\Repository\ContentObject\Assignment\Extension\Plagiarism\Bridge\Storage\DataClass\EntryPlagiarismResult
{
    public static function get_table_name()
    {
        return 'tracking_weblcms_assignment_entry_plagiarism_result';
    }
}


text:
package org.apache.hadoop.hdfs.server.federation.store.protocol;

import java.io.IOException;

import org.apache.hadoop.classification.InterfaceAudience.Public;
import org.apache.hadoop.classification.InterfaceStability.Unstable;
import org.apache.hadoop.hdfs.server.federation.store.driver.StateStoreSerializer;

/**
 * API request for removing a mount table path present in the state store.
 */
public abstract class RemoveMountTableEntryRequest {

  public static RemoveMountTableEntryRequest newInstance() throws IOException {
    return StateStoreSerializer.newRecord(RemoveMountTableEntryRequest.class);
  }

  public static RemoveMountTableEntryRequest newInstance(String path)
      throws IOException {
    RemoveMountTableEntryRequest request = newInstance();
    request.setSrcPath(path);
    return request;
  }

  @Public
  @Unstable
  public abstract String getSrcPath();

  @Public
  @Unstable
  public abstract void setSrcPath(String path);
}


text:
Backbone Overview
============================
Backbone is a clientside mv* javascript web framework. In fact it's really the
oldest client side mv* javascript framework. The initial release for backbone was
back in the ancient times of 2010. Backbone ushered in the new era of web
applications with an mv* framework that sits in the browser and communicates to a server that is primarily in charge of data persistence.

Backbone is loosely based off of the Model/View/Controller pattern which was created by
smalltalk developers and became massively popular for web development due primarily
 to the Ruby on Rails framework. Backbone and
 many other frameworks like it tend to have an explicit model and view and something
 of their own design that roughly approximates a controller.

Model
--------------
The Backbone model provides the interaction with the data of a Backbone web
application. It is the way that Backbone communicate with a server and provides
both built in and programmer defined methods for manipulating data.

View
---------------
The backbone views define the way that a Backbone application displays the data
gathered from the models. This is the way that Backbone interacts directly with
 the browser. The main difference between Backbone and other mv* client side
javascript frameworks is that Backbone doesn't have built in interactions between
the view and the model. All interactions have to be defined by the programmer.

And the rest
------------------
The last major component in Backbone is the router. Backbone routers define what
happens when a user navigates to a certain route. It really defines the
interactivity of the application. It acts both as a traditional router and in many
cases a controller. The backbone router will determine which models a route should
grab data from and which views should be rendered to the screen.

Now you may be asking yourself "WTF would I want to learn Backbone when EmbAngular
has all the magics?" Well, Ember/Angular have do make it very easy to create a
single page web application but it does a lot of the interaction under the hood
and learning one doesn't really give that much insight into the other. Backbone
provides a great learning platform because it doesn't provide the programmer with
a lot of magic. Once a developer learns Backbone it makes it very easy to learn
another more complex framework.


text:
from Axon.Component import component, scheduler, linkage, newComponent
from Axon.Ipc import producerFinished
import Kamaelia.KamaeliaIPC
import string, os, time

try:
   import pygame
   pygame.init()
except:
   pass

class ClientProtocolHandler(component):
   Inboxes = ["inbox","control", "_displayFinished"]
   Outboxes = ["outbox","signal", "_filteredControlMessages"]

   def __init__(self, tempDir, initialsendmessage, delay, demo_mode=False):
      super(ClientProtocolHandler, self).__init__()

      self.requestmessage = initialsendmessage
      self.tempDir = tempDir
      self.delay = delay
      self.demo_mode = demo_mode

   def initialiseComponent(self):

      if self.requestmessage == ".mpg":
         self.requestmessage = ".jpg"

      myPacketCombiner = combinePackets()
      myFile = createFile(self.tempDir, self.requestmessage)
      myDisplay = show(self.requestmessage, self.tempDir, self.delay, self.demo_mode)

      "Linkages for myPacketCombiner"
      self.link(source=(self, "inbox"), sink=(myPacketCombiner, "inbox"), passthrough=1)
      self.link(source=(self, "_filteredControlMessages"), sink=(myPacketCombiner, "control"), passthrough=0)

      "Linkages for myFile"
      self.link(source=(myPacketCombiner, "outbox"), sink=(myFile, "inbox"), passthrough=0)
      self.link(source=(myPacketCombiner, "signal"), sink=(myFile, "control"), passthrough=0)

      "Linkages for myDisplay"
      self.link(source=(myFile, "outbox"), sink=(myDisplay, "inbox"), passthrough=0)
      self.link(source=(myFile, "signal"), sink=(myDisplay, "control"), passthrough=0)

      self.link(source=(myDisplay, "signal"), sink=(self, "_displayFinished"), passthrough=0)

      self.addChildren(myPacketCombiner, myFile, myDisplay)
      return newComponent(myPacketCombiner, myFile, myDisplay)

   def mainBody(self):
#      print "ClientProtocolHandler: Checking mail..."

      if self.dataReady("_displayFinished"):
         print "ClientProtocolHandler: Message received! (_displayFinished)"
         self.message = self.recv("_displayFinished")

         if isinstance(self.message, producerFinished):
            self.send(producerFinished("Done"),"signal")
            return 0
         else:
            print "ClientProtocolHandler: Message from _displayFinished is..."
            print self.message

      if self.dataReady("control"):
          print "ClientProtocolHandler: Message received! (control)"
          self.controlMessage = self.recv("control")

          if isinstance(self.controlMessage, Kamaelia.KamaeliaIPC.socketShutdown) or self.controlMessage == "StoppedThread":
              self.send(self.controlMessage, "_filteredControlMessages")
          else:
              print "ClientProtocolHandler: Message from control is..."
              print self.controlMessage
      return 1

   def closeDownComponent(self):
      print "ClientProtocolHandler: Shutting down"

class combinePackets(component):
   """
   Checks messages on inbox then control. If a message is received in the component's inbox it is appended to a list/buffer.

   take chunk from buffer list
   add chunk to a new buffer
   search new buffer for "\n" and get it's index
   get what comes before the "\n" (by using it's index)
   what came before the \n should be the number of characters the file should contain
   """
   def __init__(self):
      super(combinePackets, self).__init__()

      self.list_packets = []
      self.buffer = ""
      self.buffers = []

   def mainBody(self):
#      print "combinePackets: Checking mail..."

      if  self.dataReady("inbox"):
#         print "combinePackets: Message received! (inbox)"
         self.data = self.recv("inbox")
         self.buffers.append(self.data)

      while len(self.buffer)>0 or len(self.buffers)>0:
         if len(self.buffers) > 0:
            self.chunk = self.buffers[0]
            del self.buffers[0]
         else:
            self.chunk = ""
         self.buffer = self.buffer + self.chunk
#         print "combinePackets: BUFF:",repr(self.buffer)
         self.end_of_length = self.buffer.find("\n")
         if self.end_of_length != -1:
#            print "combinePackets: EOL:", self.end_of_length
            try:
               self.length_of_picture = int(self.buffer[:self.end_of_length])
            except Exception,e:
               print e
               print "buffer:", self.buffer
               print "EOL:", self.end_of_length
               print "LOP:", self.length_of_picture
#            print "combinePackets: LEN:", self.length_of_picture
            if len(self.buffer) >= self.end_of_length + self.length_of_picture + 1:
               self.picture = self.buffer[self.end_of_length + 1: self.end_of_length + self.length_of_picture + 1]
               self.send(self.picture,"outbox")
#               print "combinePackets: CONSUMED:", repr(self.picture)
               self.buffer = self.buffer[self.end_of_length + self.length_of_picture + 1:]
            else:
               pass
#               print "combinePackets: buffer needs data"
         return 1

      if self.dataReady("control"):
         print "combinePackets: Message received! (control)"
         self.controlMessage = self.recv("control")

         print "combinePackets: Message from control is..."
         print self.controlMessage

         if isinstance(self.controlMessage, Kamaelia.KamaeliaIPC.socketShutdown) or self.controlMessage == "StoppedThread":
            self.send(producerFinished("Done"),"signal")
            return 0
      return 1

   def closeDownComponent(self):
      print "combinePackets: Shutting down"

class createFile(component):
   """
   Get file contents from inbox
   create a name for the file using arugments tempDir and file_type
   write contents to the file
   close file
   send filename to outbox
   check control for a message that is an instance of producerFinished, shutdown if true
   """
   Inboxes = ["inbox","control"]
   Outboxes = ["outbox","signal"]

   def __init__(self, tempDir, file_type):
      super(createFile, self).__init__()
      self.tempDir = tempDir
      self.file_type = file_type

      self.fileNumber = 0

   def mainBody(self):
#      print "createFile: Checking mail..."
      if self.dataReady("inbox"):
         print "createFile: Message received! (inbox)"
         self.filecontents = self.recv("inbox")

         self.fullfilename = self.create_TempFilename(self.tempDir, file_type=self.file_type)

         try:
#            print "createFile: creating file object"
            self.file_object = open(self.fullfilename,"wb")
            print "createFile: writing contents to file"
            self.file_object.write(self.filecontents)
#            print "createFile: closing file object"
            self.file_object.close()
         except Exception, e:
            print "createFile: Exception..."
            print e

         self.send(self.fullfilename, "outbox")

      if self.dataReady("control"):
         print "createFile: Message received! (control)"
         self.controlMessage = self.recv("control")

         if isinstance(self.controlMessage, producerFinished):
            self.send(producerFinished("Done"), "signal")
            return 0
      return 1

   def closeDownComponent(self):
      print "createFile: Shutting down"

   def create_TempFilename(self, tempDirectory, filename_without_ext=None, file_type=".bmp"):
      """
      Creates a new, unique full filename each time it is called by incrementing the digit at the
      end of the filename.
      """
      if filename_without_ext == None:
         filename_without_ext = "TempFile"

      filename = filename_without_ext + str(self.fileNumber) + file_type
      self.fileNumber = self.fileNumber + 1

      fullfilename = os.path.join(tempDirectory, filename)
#      print "createFile: Temp file will be...", fullfilename
      return fullfilename

class show(component):
   Inboxes = ["inbox","control"]
   Outboxes = ["outbox","signal"]

   def __init__(self, file_type, tempDir, delay, demo_mode=False):
      super(show, self).__init__()

      self.file_type = file_type
      self.tempDir = tempDir ##used to check if using phone or PC
      self.delay = delay
      self.demo_mode = demo_mode

      self.tempFiles = []
      self.filesToDisplay = []
      self.timeOfDisplay = 0
      self.controlMessage = ""
      self.hadAFile = False

   def mainBody(self):
#      print "show: Checking mail..."
      if self.dataReady("inbox"):
         print "show: Message received (inbox)"
         self.fullfilename = self.recv("inbox")
         print "show: Message from inbox is...", self.fullfilename
         self.tempFiles.append(self.fullfilename)
         self.filesToDisplay.append(self.fullfilename)
         self.hadAFile = True

      if self.dataReady("control"):
         print "show: Message received (control)"
         self.controlMessage = self.recv("control")

      if len(self.filesToDisplay) > 0:
         if (time.time() - self.timeOfDisplay) > self.delay:

            self.file = self.filesToDisplay[0]
            del self.filesToDisplay[0]
            if self.file_type == ".txt":
               print "show: preparing to display text"
               self.file_object = open(self.fullfilename, "r")
               self.text = self.file_object.read()

               if self.tempDir == "C:\\ClientContent\\":
                  import pygame
                  pygame.init()
                  self.display_pygame_text_string(self.text)  #display string in Pygame Window
               else:
                  self.display_text_string(self.text)

            elif self.file_type == ".jpg":
               print "show: preparing to display a picture"

               if self.tempDir == "C:\\ClientContent\\":
                   import pygame
                   pygame.init()
                   self.display_pygame_image_file(self.fullfilename) # display image using pygame
               else:
                   self.display_nokia6600(self.fullfilename)         # display image on nokia6600

            self.timeOfDisplay = time.time()
            return 1

      if isinstance(self.controlMessage, producerFinished) and len(self.filesToDisplay) == 0:
         if self.tempDir == "C:\\ClientContent\\" and self.hadAFile == True:
            if self.demo_mode == False:
                self.pygame_eventHandler_2()
            else:
                IP_toConnectTo = "132.185.133.36"
                IP_toConnectTo = "127.0.0.1"
                print IP_toConnectTo
                serverport = 1616
                delay = 5
                windows_ClientContentDir = "C:\\ClientContent\\"
                mac_ClientContentDir = "/temp/"
                phone_ClientContentDir = "E:\\Ciaran's Files\\Temp"
                ClientContentDir = [windows_ClientContentDir, mac_ClientContentDir, phone_ClientContentDir]
                demo_mode = True

                t = UserInterface(IP_toConnectTo, serverport, delay, ClientContentDir, demo_mode)
                t.activate()
#                scheduler.run.runThreads(slowmo=0)
                return 0
         elif self.file_type == ".jpg" and self.hadAFile == True:
            self.display_nokia6600_2(self.fullfilename)      # display image on nokia6600

         self.send(producerFinished("Done"), "signal")
         return 0
      return 1

   def closeDownComponent(self):
      for file in self.tempFiles:
         try:
            print "show: Removing", file
            os.remove(file)
         except Exception, e:
            print "show: ", e
      print "show: Shutting down"

   def display_text_string(self, filecontents):
      """
      Takes a string in filecontents argument and displays it in the Python Shell. It then waits
      for keyboard return carriage. When user does push return key a producerFinished message is
      sent to signal box.
      """
      print "display_text: the message is..."
      print filecontents
      raw_input()

   def display_pygame_text_string(self,
                                  filecontents,
                                  font_size=20,
                                  screensize=[800,600],
                                  back_colour=(0,0,0),
                                  font_colour=(255,255,255)):
      if filecontents != "":
#         print "display_pygame_text_string: Preparing display"
         font = pygame.font.Font(None,font_size)                   #Font
         text_surface = font.render(filecontents, 1, font_colour)  #Surface
#         print "display_pygame_text_string: creating display"
         self.pygame_displayHandler(text_surface, screensize, back_colour)
         self.pygame_eventHandler()

   def display_pygame_image_file(self,
                                 image_location,
                                 screensize=[800,600],
                                 back_colour=(0,0,0)):

#      print "display_pygame_image_file: creating image surface"
      image_surface = pygame.image.load(image_location)
#      print "display_pygame_image_file: creating display"
      self.pygame_displayHandler(image_surface, screensize, back_colour)
      self.pygame_eventHandler()

   def display_pygame_image_string(self,
                                   image_string,
                                   format,
                                   resolution,
                                   screensize=[800,600],
                                   back_colour=(0,0,0)):
#      print "display_pygame_image_string: creating image surface"
      image_surface = pygame.image.fromstring(image_string, resolution, format)
#      print "display_pygame_image_string: creating display"
      self.pygame_displayHandler(image_surface, screensize, back_colour)
      self.pygame_eventHandler()

   def pygame_displayHandler(self,
                             surface,
                             screensize=[800,600],
                             back_colour=(0,0,0)):
#      print "pygame_displayHandler: getting dimensions"
      width = surface.get_width()
      height = surface.get_height()

      horizonal_to_move = (screensize[0] - width)/2
      vertical_to_move = (screensize[1] - height)/2

#      print "pygame_displayHandler: moving rect"
      rect = surface.get_rect()
      rect = rect.move([horizonal_to_move,vertical_to_move])

#      print "pygame_displayHandler: creating display"
      FULLSCREEN = pygame.constants.FULLSCREEN
      screen_surface = pygame.display.set_mode(screensize)
  #    screen_surface = pygame.display.set_mode(screensize,FULLSCREEN)

#      print "display_pygame_image: display"
      screen_surface.fill(back_colour)
      screen_surface.blit(surface, rect)
      pygame.display.flip()

   def pygame_eventHandler(self):
      while 1:
         for event in pygame.event.get():
            if event.type == pygame.QUIT:
               print "pygame_eventHandler: User closed window, shutting down"
               pygame.quit()
               return 0
            if event.type == pygame.KEYDOWN:
               print "pygame_eventHandler: User pushed a button, shutting down"
               pygame.quit()
               return 0
         return 1

   def pygame_eventHandler_2(self):
      print "pygame_eventHandler_2: Waiting for user response..."
      while 1:
         for event in pygame.event.get():
            if event.type == pygame.QUIT:
               print "pygame_eventHandler_2: User closed window, shutting down"
               pygame.quit()
               return 0
            if event.type == pygame.KEYDOWN:
               print "pygame_eventHandler_2: User pushed a button, shutting down"
               pygame.quit()
               return 0

   def display_nokia6600(self, fullfilename):
      try:
         print "display_nokia6600_2: Opening file..."
         appuifw.Content_handler().open(fullfilename)
         print "display_nokia6600_2: opened it"
         return 1
      except IOError:
         print "display_nokia6600_2: Could not fetch the image."
      except Exception, e:
         print e
         print "display_nokia6600_2: Could not open data received."

   def display_nokia6600_2(self, fullfilename):
      try:
         print "display_nokia6600: Opening file..."
         lock=e32.Ao_lock()
         content_handler = appuifw.Content_handler(lock.signal)
         content_handler.open(fullfilename)
         # Wait for the user to exit the image viewer.
         lock.wait()
         print "display_nokia6600: Image viewer finished."
         return 0
      except IOError:
         print "display_nokia6600: Could not fetch the image."
      except Exception, e:
         print e
         print "display_nokia6600: Could not open data received."

   def display_nokia6600_eventHandler(self):
      e32.Ao_lock().wait()
      print "display_nokia6600: Image viewer finished."
      return 0

class Client(component):
   def __init__(self,
                IP_toConnectTo,
                serverport,
                delay,
                requestmessage,
                tempDir,
                demo_mode=False):

      super(Client, self).__init__()

      self.IP_toConnectTo = IP_toConnectTo
      self.serverport = serverport
      self.delay = delay
      self.requestmessage = requestmessage
      self.tempDir = tempDir
      self.demo_mode = demo_mode

   def initialiseComponent(self):

      self.client = ThreadedTCPClient.ThreadedTCPClient(self.IP_toConnectTo,self.serverport, delay=1, initialsendmessage=self.requestmessage)
      self.display = ClientProtocolHandler(self.tempDir, self.requestmessage, self.delay, self.demo_mode)

      self.addChildren(self.client, self.display)

      self.link((self.client,"outbox"), (self.display,"inbox") )
      self.link((self.display,"outbox"), (self.client,"inbox") )
      self.link((self.client,"signal"), (self.display,"control") )
      self.link((self.display,"signal"), (self,"control") )

      return newComponent( self.client, self.display)

   def mainBody(self):
      if self.dataReady("control"):
         something = self.recv("control")
         return 0
      return 1

   def closeDownComponent(self):
      print "ALL DONE! GOODBYE"

class UserInterface(component):
   def __init__(self,
                IP_toConnectTo,
                serverport,
                delay,
                ClientContentDir,
                demo_mode):

      super(UserInterface, self).__init__()

      self.IP_toConnectTo = IP_toConnectTo
      self.serverport = serverport
      self.delay = delay
      self.ClientContentDir = ClientContentDir
      self.demo_mode = demo_mode

      self.displaySet = False
      self.size = width, height = 800, 600
      self.black = 0, 0, 0
      FULLSCREEN = pygame.constants.FULLSCREEN

   #   self.screen = pygame.display.set_mode(self.size,FULLSCREEN)
      self.screen = pygame.display.set_mode(self.size)

   def mainBody(self):
      self.setTempDir()
      #UserInterface
      if self.tempDir != "E:\\Ciaran's Files\\Temp":
         if self.demo_mode == True:
             if self.displaySet == False:
                try: text_button = pygame.image.load("UI_Pics\\Text button.jpg")
                except: raise "ErrorLoadingImage", "couldn't load text button"

                try: image_button = pygame.image.load("UI_Pics\Image button.jpg")
                except: raise "ErrorLoadingImage", "couldn't load image button"

                try: movie_button = pygame.image.load("UI_Pics\\Movie button.jpg")
                except: raise "ErrorLoadingImage", "couldn't load movie button"

                self.textRect = text_button.get_rect()
                self.imageRect = image_button.get_rect()
                self.movieRect = movie_button.get_rect()

                self.textRect = self.textRect.move(100, 200)
                self.imageRect = self.imageRect.move(350, 200)
                self.movieRect = self.movieRect.move(600, 200)

                font = pygame.font.Font(None,18)
                self.string_surface = font.render("What request would you like to make?", 1, [255,255,255])
                self.string_rect = self.string_surface.get_rect()

                self.string_rect = self.string_rect.move(300, 150)

                self.screen.fill(self.black)
                self.screen.blit(self.string_surface, self.string_rect)
                self.screen.blit(text_button, self.textRect)
                self.screen.blit(image_button, self.imageRect)
                self.screen.blit(movie_button, self.movieRect)

                pygame.display.flip()
                self.displaySet = True

             for event in pygame.event.get():
               if event.type == pygame.QUIT:
                  pygame.quit()
                  return 0
               if event.type == pygame.MOUSEBUTTONDOWN:
                  pos = pygame.mouse.get_pos()
                  mouseRect = [[pos[0],pos[1]],[5,5]]
                  mouseRect = pygame.Rect(mouseRect)

                  if pygame.mouse.get_pressed() == (1,0,0):
                     clickedText = mouseRect.colliderect(self.textRect)
                     clickedImage = mouseRect.colliderect(self.imageRect)
                     clickedMovie = mouseRect.colliderect(self.movieRect)

                     if clickedText == True:
                        self.screen.fill(self.black)
                        pygame.display.flip()
                        self.requestmessage = ".txt"
                        self.client = Client(self.IP_toConnectTo, self.serverport, self.delay, self.requestmessage, self.tempDir, self.demo_mode)
                        self.addChildren(self.client)
                        return newComponent(self.client)

                     if clickedImage == True:
                        self.screen.fill(self.black)
                        pygame.display.flip()
                        self.requestmessage = ".jpg"
                        self.client = Client(self.IP_toConnectTo, self.serverport, self.delay, self.requestmessage, self.tempDir, self.demo_mode)
                        self.addChildren(self.client)
                        return newComponent(self.client)

                     if clickedMovie == True:
                        self.screen.fill(self.black)
                        pygame.display.flip()
                        self.requestmessage = ".mpg"
                        self.client = Client(self.IP_toConnectTo, self.serverport, self.delay, self.requestmessage, self.tempDir, self.demo_mode)
                        self.addChildren(self.client)
                        return newComponent(self.client)

                  if pygame.mouse.get_pressed() == (0,0,1):
                     clickedFont = mouseRect.colliderect(self.string_rect)
                     pygame.quit()
                     return 0

         elif self.demo_mode == False:
            print "Enter Server IP"
            self.IP_toConnectTo = raw_input()

            print "Enter port (1616)"
            self.serverport = raw_input()

            print "Enter delay value"
            self.delay = raw_input()

            print "Enter request (.txt .jpg or .mpg)"
            self.requestmessage = raw_input()
      else:
         self.IP_toConnectTo = appuifw.query(u"Enter Server IP", "text", u"132.185.133.36")
         self.serverport = appuifw.query(u"Enter port", "number")
         self.delay = appuifw.query(u"Enter delay value.", "number")
         self.requestmessage = appuifw.query(u"Enter request ('.txt', '.jpg' or '.mpg')", "text", u".")

      return 1

   def setTempDir(self):
      #Set tempDir appropriate to OS
      if os.name == "nt":
         if os.path.exists(self.ClientContentDir[0]) == True: #Windows based machine
            self.tempDir = self.ClientContentDir[0]
         else:
            raise "tempDir_Error", "Invalid directory (win)"
      elif os.name == "posix":
         if os.path.exists(self.ClientContentDir[1]) == True: #Mac based machine
            self.tempDir = self.ClientContentDir[1]
         else:
            raise "tempDir_Error", "Invalid directory (mac)"
      elif phoneLibs == True:
         if os.path.exists(self.ClientContentDir[2]) == True: #Phone based
            self.tempDir = self.ClientContentDir[2]
         else:
            raise "tempDir_Error", "Invalid directory (phone)"
      else:
         raise "tempDir_Error", "Don't reconise OS"

if __name__ == "__main__":
   from Kamaelia.Internet import ThreadedTCPClient
   from Axon.Component import component, scheduler, linkage
   from Axon.Ipc import newComponent
   try:
       import e32, appuifw   #nokia6600 libs
       phoneLibs = True
   except:
       phoneLibs = False

 #  IP_toConnectTo = "132.185.133.36"
   IP_toConnectTo = "127.0.0.1"
   print IP_toConnectTo
   serverport = 1616
   delay = 5
   windows_ClientContentDir = "C:\\ClientContent\\"
   mac_ClientContentDir = "/temp/"
   phone_ClientContentDir = "E:\\Ciaran's Files\\Temp"
   ClientContentDir = [windows_ClientContentDir, mac_ClientContentDir, phone_ClientContentDir]
   demo_mode = True

   import sys
   sys.path.append("..\Layout")
   from Introspector import Introspector
   from Kamaelia.Internet.TCPClient import TCPClient
   from Kamaelia.Util.PipelineComponent import pipeline

   pipeline( Introspector(),
             TCPClient("132.185.133.29",1500)
            ).activate()

   t = UserInterface(IP_toConnectTo, serverport, delay, ClientContentDir, demo_mode)
   t.activate()
   scheduler.run.runThreads(slowmo=0)

#   t = Client()
#   t.activate()
#   scheduler.run.runThreads(slowmo=0)


text:
// Read the info about a company and its manager and print it back on the console
using System;

class PrintCompanyInformation
{
    static void Main()
    {
        Console.Write("Please enter a company name: ");
        string name = Console.ReadLine();
        Console.Write("Please enter a company address: ");
        string address = Console.ReadLine();
        Console.Write("Please enter a company phone number: ");
        string compPhoneNum = Console.ReadLine();
        Console.Write("Please enter company fax number: ");
        string faxNum = Console.ReadLine();
        Console.Write("Please enter a company web site: ");
        string webSite = Console.ReadLine();
        Console.Write("Please enter a manager's first name: ");
        string firstName = Console.ReadLine();
        Console.Write("Please enter a manager's last name: ");
        string lastName = Console.ReadLine();
        Console.Write("Please enter a manager's age: ");
        byte age = byte.Parse(Console.ReadLine());
        Console.Write("Please enter a manager's phone number: ");
        string manPhoneNum = Console.ReadLine();

        Console.WriteLine(name);
        Console.WriteLine("Address: " + address);
        Console.WriteLine("Tel. " + compPhoneNum);
        Console.Write("Fax: ");
        if (faxNum != "")
        {
            Console.WriteLine(faxNum);
        }
        else
        {
            Console.WriteLine("(no fax)");
        }
        Console.WriteLine("Web site: " + webSite);
        Console.WriteLine("Manager: " + firstName + " " + lastName + " (age: " + age + ", " + "tel. " + manPhoneNum + ")");
    }
}