text:
angular.module('booksAR')

.controller('userController', function($state, userService, sessionService, bookService, API, verifySession){

	//server address
	this.bookAddress = API.bookAddress;

	//user
	this.editUser = false;
	this.user = JSON.parse(sessionStorage.user);

	console.log(this.user.books);

	this.updUser = {
		name: this.user.name,
		lastName: this.user.lastName,
		username: this.user.username,
		email: this.user.email,
		password: ""
	};

	//book
	this.bookCreation = false;
	this.newBook = {};

	this.bookUpdate = false;
	this.updBook = {};

	//ALERTS
	this.alertSuccess = {
		show: false,
	 	msg: ''
	};

	this.alertDanger = {
		show: false,
	 	msg: ''
	};

	this.closeSuccessAlert = function(){
		this.alertSuccess.show = false;
		this.alertSuccess.msg = '';
	};

	this.showSuccessAlert = function(msg){
		this.alertSuccess.show = true;
		this.alertSuccess.msg = msg;
	};

	this.closeDangerAlert = function(){
		this.alertDanger.show = false;
		this.alertDanger.msg = '';
	};

	this.showDangerAlert = function(msg){
		this.alertDanger.show = true;
		this.alertDanger.msg = msg;
	};

	var showSuccessMessage = (function(msg){
		this.showSuccessAlert(msg);
	}).bind(this);

	var showDangerMessage = (function(msg){
		this.showDangerAlert(msg);
	}).bind(this);

	// User functions

	this.logOut = function(){
		sessionService.logOut();
	};

	this.changeUpdate = function(){
		this.editUser = true;
	};

	var setUser = (function(data){
		sessionStorage.user = JSON.stringify(data);
		this.user = JSON.parse(sessionStorage.user);
		this.updUser = {
			name: this.user.name,
			lastName: this.user.lastName,
			username: this.user.username,
			email: this.user.email,
			password: ""
		};
		this.editUser = false;
	}).bind(this);

	this.updateUser = function(){
		var token = sessionStorage.token,
		id = this.user.id,
		user = this.updUser;

		userService.updateUser(token, id, user).then(function successCallback(response) {

			userService.getUser(token, id).then(function successCallback(response) {

				setUser(response.data.data);
				showSuccessMessage('User has been updated!');

			}, function errorCallback(response) {
				//error
				showDangerMessage(response.data.data.message);
				console.log(response.data.data.message);
			});

		}, function errorCallback(response) {
			//error
			showDangerMessage(response.data.data.message);
			console.log(response.data.data.message);
		});

	};

	this.cancelUpdate = function(){
		this.updUser = this.user;
		this.editUser = false;
	};

	// Book functions

	this.publishBook = function(book){
		var token = sessionStorage.token,
		bookId = book.id,
		userId = this.user.id,
		bookPublish = book.publish;

		bookService.publishBook(token, bookId).then(function successCallback(response) {

			userService.getUser(token, userId).then(function successCallback(response) {

				if(bookPublish == true){
					showSuccessMessage('Book has been unpublished!');
				}else{
					showSuccessMessage('Book has been published!');
				}

				setUser(response.data.data);

			}, function errorCallback(response) {
				//error
				showDangerMessage(response.data.data.message);
				console.log(response.data.data.message);
			});

		}, function errorCallback(response) {
			//error
			showDangerMessage(response.data.data.message);
			console.log(response.data.data.message);
		});
	};

	this.deleteBook = function(book){
		var token = sessionStorage.token,
		bookId = book.id,
		userId = this.user.id;

		bookService.deleteBook(token, bookId).then(function successCallback(response) {

			userService.getUser(token, userId).then(function successCallback(response) {

				showSuccessMessage('Book has been deleted!');
				setUser(response.data.data);

			}, function errorCallback(response) {
				//error
				showDangerMessage(response.data.data.message);
				console.log(response.data.data.message);
			});

		}, function errorCallback(response) {
			//error
			showDangerMessage(response.data.data.message);
			console.log(response.data.data.message);
		});
	};

	this.uploadCover = function (file) {
        Upload.upload({
            url: '',
            data: {file: file}
        }).then(function (resp) {
            console.log('Success');
        }, function (resp) {
            console.log('Error status: ');
        }, function (evt) {
            var progressPercentage = parseInt(100.0 * evt.loaded / evt.total);
            console.log('progress: ' + progressPercentage + '% ' + evt.config.data.file.name);
        });
    };

    var bookCreated = (function(){
		this.newBook = {};
		this.bookCreation = false;
	}).bind(this);

    this.createBook = function(){
		var token = sessionStorage.token,
		id = this.user.id,
		data = new FormData();

	    data.append("title", this.newBook.title);
	    data.append('description', this.newBook.description);
	    data.append('cover', this.newBook.cover);
	    data.append('idUser', id);

		bookService.createBook(token, data).then(function successCallback(response) {

			userService.getUser(token, id).then(function successCallback(response) {

				showSuccessMessage('Book has been created!');
				setUser(response.data.data);
				bookCreated();

			}, function errorCallback(response) {
				//error
				console.log(response.data.data.message);
				console.log(response.status);
				showDangerMessage(response.data.data.message);

			});

		}, function errorCallback(response) {
			//error
			showDangerMessage(response.data.data.message);
			console.log(response.data.data.message);
		});

	};

	this.changeBookCreation = function(){
		this.bookCreation = true;
	};

	this.cancelCreateBook = function(){
		this.newBook = {};
		this.bookCreation = false;
	};

	var bookUpdated = (function(){
		this.updBook = {};
		this.bookUpdate = false;
		this.updBook.cover = "";
	}).bind(this);

	this.updateBook = function(){
		var token = sessionStorage.token,
		idUser = this.user.id,
		idBook = this.updBook.id,
		data = new FormData();

	    data.append("title", this.updBook.title);
	    data.append('description', this.updBook.description);
	    data.append('cover', this.updBook.cover);
	    data.append('idUser', idUser);

		bookService.updateBook(token, idBook, data).then(function successCallback(response) {

			userService.getUser(token, idUser).then(function successCallback(response) {

				showSuccessMessage('Book has been updated!');
				setUser(response.data.data);
				bookUpdated();

			}, function errorCallback(response) {
				//error
				showDangerMessage(response.data.data.message);
				console.log(response.data.data.message);
			});

		}, function errorCallback(response) {
			//error
			showDangerMessage(response.data.data.message);
			console.log(response.data.data.message);
		});

	};

	this.changeBookUpdate = function(book){
		this.bookUpdate = true;
		this.updBook = Object.assign({}, book);
		this.updBook.cover = API.bookAddress + book.cover;
	};

	this.cancelUpdateBook = function(){
		this.updBook = {};
		this.updBook.cover = "";
		this.bookUpdate = false;
	};
	this.downloadBook =function(book){
		var token = sessionStorage.token,
		id = book.id,
		title = book.title;
		bookService.downloadBook(token, id).then(function successCallback(response) {

			var file = new Blob([response.data], {type: 'application/pdf'});
       		//var fileURL = URL.createObjectURL(file);
       		//window.open(fileURL);
       		var blobURL = (window.URL || window.webkitURL).createObjectURL(file);
			var anchor = document.createElement("a");
			anchor.download = title+".pdf";
			anchor.href = blobURL;

			document.body.appendChild(anchor);
			anchor.click();
			showSuccessMessage('Your download should start soon!');

			setTimeout(function(){
		        document.body.removeChild(anchor);
		        window.URL.revokeObjectURL(blobURL);
		    }, 100);

		}, function errorCallback(response) {
			//error
			console.log(response.data.data.message);
		});
	};

	this.goToTypewriter = function(book){
		sessionStorage.book = JSON.stringify(book);

		$state.go('typewriter');
	};

});


text:
package org.apache.hadoop.chukwa.datacollection.adaptor.filetailer;

import org.apache.hadoop.chukwa.ChunkImpl;
import org.apache.hadoop.chukwa.datacollection.ChunkReceiver;
import java.util.ArrayList;

/**
 * A subclass of FileTailingAdaptor that reads UTF8/ascii
 * files and splits records at carriage returns.
 *
 */
public class CharFileTailingAdaptorUTF8 extends FileTailingAdaptor {

  private static final char SEPARATOR = '\n';

  private ArrayList<Integer> offsets = new ArrayList<Integer>();

  /**
   *
   * Note: this method uses a temporary ArrayList (shared across instances).
   * This means we're copying ints each time. This could be a performance issue.
   * Also, 'offsets' never shrinks, and will be of size proportional to the
   * largest number of lines ever seen in an event.
   */
  @Override
    protected int extractRecords(ChunkReceiver eq, long buffOffsetInFile, byte[] buf)
    throws InterruptedException
  {
      for(int i = 0; i < buf.length; ++i) {
        if(buf[i] == SEPARATOR) {
          offsets.add(i);
        }
      }

      if(offsets.size() > 0)  {
        int[] offsets_i = new int[offsets.size()];
        for(int i = 0; i < offsets_i.length ; ++i)
          offsets_i[i] = offsets.get(i);

        int bytesUsed = offsets_i[offsets_i.length-1]  + 1; //char at last offset uses a byte
        assert bytesUsed > 0: " shouldn't send empty events";
        ChunkImpl event = new ChunkImpl(type, toWatch.getAbsolutePath(),buffOffsetInFile + bytesUsed, buf, this );

        event.setRecordOffsets(offsets_i);
        eq.add(event);

        offsets.clear();
        return bytesUsed;
      }
      else
        return 0;

  }

}

redpajama_set_name: RedPajamaGithub


text:
#ifndef __GLES2Support_H__
#define __GLES2Support_H__

#include "OgreGLES2Prerequisites.h"
#include "OgreRenderWindow.h"
#include "OgreConfigOptionMap.h"

namespace Ogre
{
    class GLES2RenderSystem;

    class _OgreGLES2Export GLES2Support
    {
        public:
            GLES2Support() { }
            virtual ~GLES2Support() { }

            /**
            * Add any special config values to the system.
            * Must have a "Full Screen" value that is a bool and a "Video Mode" value
            * that is a string in the form of wxh
            */
            virtual void addConfig() = 0;
            virtual void setConfigOption(const String &name, const String &value);

           /**
            * Make sure all the extra options are valid
            * @return string with error message
            */
            virtual String validateConfig() = 0;
            virtual ConfigOptionMap& getConfigOptions(void);
            virtual RenderWindow* createWindow(bool autoCreateWindow,
                                               GLES2RenderSystem *renderSystem,
                                               const String& windowTitle) = 0;

            /// @copydoc RenderSystem::_createRenderWindow
            virtual RenderWindow* newWindow(const String &name,
                                            unsigned int width, unsigned int height,
                                            bool fullScreen,
                                            const NameValuePairList *miscParams = 0) = 0;

            /**
            * Get vendor information
            */
            const String& getGLVendor(void) const
            {
                return mVendor;
            }

            /**
            * Get version information
            */
            const String& getGLVersion(void) const
            {
                return mVersion;
            }

            /**
            * Get shader cache path
            */
            const String& getShaderCachePath(void) const
            {
                return mShaderCachePath;
            }

            /**
            * Get shader library path
            */
            const String& getShaderLibraryPath(void) const
            {
                return mShaderLibraryPath;
            }

            /**
            * Set shader cache path
            */
            const void setShaderCachePath(String path)
            {
                mShaderCachePath = path;
            }

            /**
            * Set shader library path
            */
            const void setShaderLibraryPath(String path)
            {
                mShaderLibraryPath = path;
            }

            /**
            * Get the address of a function
            */
            virtual void *getProcAddress(const String& procname) = 0;

            /** Initialises GL extensions, must be done AFTER the GL context has been
               established.
            */
            virtual void initialiseExtensions();

            /**
            * Check if an extension is available
            */
            virtual bool checkExtension(const String& ext) const;

	/// @copydoc RenderSystem::getDisplayMonitorCount
            virtual unsigned int getDisplayMonitorCount() const
            {
                return 1;
            }

            /**
            * Start anything special
            */
            virtual void start() = 0;
            /**
            * Stop anything special
            */
            virtual void stop() = 0;

        private:
            String mVersion;
            String mVendor;
            String mShaderCachePath;
            String mShaderLibraryPath;

        protected:
            // Stored options
            ConfigOptionMap mOptions;

            // This contains the complete list of supported extensions
            set<String>::type extensionList;
    };

};

#endif


text:
ACCEPTED

#### According to
International Plant Names Index

#### Published in
null

#### Original name
Cornus papillosa W.P.Fang & W.K Hu

### Remarks
null


text:
<?php

namespace App\Http\Controllers\Api;

use Illuminate\Http\Request;

use App\Http\Requests;
use App\Http\Controllers\Controller;
use App\Category;

class CategoryController extends Controller
{
    public function store(Request $request)
    {
        $this->validate($request, [
            'name' => 'required|string|max:255'
        ]);

        $category = Category::create([
            'name' => $request->get('name')
        ]);

        return $category->toArray();
    }
}


text:
package answers;

/**
 * Created by seok on 2017. 4. 10..
 *
 * Problem 36
 *
 * The decimal number, 585 = 1001001001 (binary),
 * is palindromic in both bases.
 * Find the sum of all numbers, less than one million,
 * which are palindromic in base 10 and base 2.
 * (Please note that the palindromic number,
 * in either base, may not include leading zeros.)
 */
public class Problem36 {
    public static void main(String[] args) {
        int result = 0;
        for (int i = 1; i <= 1000000; i += 2) {
            if (isPalindromic(i, 10) && isPalindromic(i, 2)) {
                result += i;
            }
        }
        System.out.println(result);
    }

    private static boolean isPalindromic(int num, int digit) {
        int reversed = 0;
        int original = num;
        while (original > 0) {
            reversed = reversed * digit + original % digit;
            original /= digit;
        }
        return num == reversed;
    }
}


text:
@implementation UIColor (ApplicationColors)

+ (UIColor *)navBarColor {
	return [UIColor orangeColor];
}

@end


text:
<?php

namespace FOS\UserBundle\Controller;

use FOS\UserBundle\FOSUserEvents;
use FOS\UserBundle\Event\FormEvent;
use FOS\UserBundle\Form\Type\RegistrationFormType;
use FOS\UserBundle\Event\GetResponseUserEvent;
use FOS\UserBundle\Event\FilterUserResponseEvent;
use Symfony\Bundle\FrameworkBundle\Controller\Controller;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpFoundation\RedirectResponse;
use Symfony\Component\HttpKernel\Exception\NotFoundHttpException;
use Symfony\Component\Security\Core\Exception\AccessDeniedException;
use FOS\UserBundle\Model\UserInterface;
use BackOffice\AdminBundle\Entity\User;
/**
 * Controller managing the registration
 *
 * @author Thibault Duplessis <thibault.duplessis@gmail.com>
 * @author Christophe Coevoet <stof@notk.org>
 */
class RegistrationController extends Controller
{
    public function registerAction(Request $request)
    {
        $usr= $this->get('security.context')->getToken()->getUser();
            $m=array();
            $m=$usr;
            $images = array();
         $images = base64_encode(stream_get_contents($m->getImage()));

        $formFactory = $this->get('fos_user.registration.form.factory');
        $userManager = $this->get('fos_user.user_manager');
        $dispatcher = $this->get('event_dispatcher');

        $user = $userManager->createUser();
        $user->setEnabled(true);

        $event = new GetResponseUserEvent($user, $request);
        $dispatcher->dispatch(FOSUserEvents::REGISTRATION_INITIALIZE, $event);

        if (null !== $event->getResponse()) {
            return $event->getResponse();
        }

        $form = $formFactory->createForm();

        $Request = $this->getRequest();

        if ($Request->getMethod() == 'POST')
        {
        $src = $Request->files->get('photo');

        $stream = fopen($src, 'rb');
        $user->setRoles(array($Request->get('role')));
        $user->setImage(stream_get_contents($stream));
        $form->setData($user);
        }

        $form->handleRequest($request);

        if ($form->isValid()) {
            $event = new FormEvent($form, $request);
            $dispatcher->dispatch(FOSUserEvents::REGISTRATION_SUCCESS, $event);

            $userManager->updateUser($user);

            if (null === $response = $event->getResponse()) {
                $url = $this->generateUrl('admin_listerUser');
                $response = new RedirectResponse($url);
            }

           // $dispatcher->dispatch(FOSUserEvents::REGISTRATION_COMPLETED, new FilterUserResponseEvent($user, $request, $response));

            return $response;
        }
         return $this->render('FOSUserBundle:Registration:register.html.twig', array(
            'form' => $form->createView(),'img' => $images
        ));
    }

    /**
     * Tell the user to check his email provider
     */
    public function checkEmailAction()
    {
        $email = $this->get('session')->get('fos_user_send_confirmation_email/email');
        $this->get('session')->remove('fos_user_send_confirmation_email/email');
        $user = $this->get('fos_user.user_manager')->findUserByEmail($email);

        if (null === $user) {
            throw new NotFoundHttpException(sprintf('The user with email "%s" does not exist', $email));
        }

        return $this->render('FOSUserBundle:Registration:checkEmail.html.twig', array(
            'user' => $user,
        ));
    }

    /**
     * Receive the confirmation token from user email provider, login the user
     */
    public function confirmAction(Request $request, $token)
    {
        /** @var $userManager \FOS\UserBundle\Model\UserManagerInterface */
        $userManager = $this->get('fos_user.user_manager');

        $user = $userManager->findUserByConfirmationToken($token);

        if (null === $user) {
            throw new NotFoundHttpException(sprintf('The user with confirmation token "%s" does not exist', $token));
        }

        /** @var $dispatcher \Symfony\Component\EventDispatcher\EventDispatcherInterface */
        $dispatcher = $this->get('event_dispatcher');

        $user->setConfirmationToken(null);
        $user->setEnabled(true);

        $event = new GetResponseUserEvent($user, $request);
        $dispatcher->dispatch(FOSUserEvents::REGISTRATION_CONFIRM, $event);

        $userManager->updateUser($user);

        if (null === $response = $event->getResponse()) {
            $url = $this->generateUrl('admin_listerUser');
            $response = new RedirectResponse($url);
        }

        $dispatcher->dispatch(FOSUserEvents::REGISTRATION_CONFIRMED, new FilterUserResponseEvent($user, $request, $response));

        return $response;
    }

    /**
     * Tell the user his account is now confirmed
     */
    public function confirmedAction()
    {
        $user = $this->getUser();
        if (!is_object($user) || !$user instanceof UserInterface) {
            throw new AccessDeniedException('This user does not have access to this section.');
        }

        return $this->render('FOSUserBundle:Registration:confirmed.html.twig', array(
            'user' => $user,
        ));
    }
}


text:
module CustomFields

  module Types

    module File

      module Field; end

      module Target

        extend ActiveSupport::Concern

        module ClassMethods

          # Adds a file field (using carrierwave)
          #
          # @param [ Class ] klass The class to modify
          # @param [ Hash ] rule It contains the name of the field and if it is required or not
          #
          def apply_file_custom_field(klass, rule)
            name = rule['name']

            klass.mount_uploader name, FileUploader

            if rule['localized'] == true
              klass.replace_field name, ::String, true
            end

            if rule['required']
              klass.validates_presence_of name
            end
          end

          # Build a hash storing the url for a file custom field of an instance.
          #
          # @param [ Object ] instance An instance of the class enhanced by the custom_fields
          # @param [ String ] name The name of the file custom field
          #
          # @return [ Hash ] field name => url or empty hash if no file
          #
          def file_attribute_get(instance, name)
            if instance.send(:"#{name}?") #"
              value = instance.send(name.to_sym).url
              { name => value, "#{name}_url" => value }
            else
              {}
            end
          end

          # Set the value for the instance and the file field specified by
          # the 2 params.
          #
          # @param [ Object ] instance An instance of the class enhanced by the custom_fields
          # @param [ String ] name The name of the file custom field
          # @param [ Hash ] attributes The attributes used to fetch the values
          #
          def file_attribute_set(instance, name, attributes)
            [name, "remote_#{name}_url", "remove_#{name}"].each do |_name|
              self.default_attribute_set(instance, _name, attributes)
            end.compact
          end

        end

      end

      class FileUploader < ::CarrierWave::Uploader::Base
      end

    end

  end

end


text:
package mil.nga.giat.geowave.examples.ingest.bulk;

import org.geotools.feature.AttributeTypeBuilder;
import org.geotools.feature.simple.SimpleFeatureTypeBuilder;
import org.opengis.feature.simple.SimpleFeatureType;

import com.vividsolutions.jts.geom.Geometry;

/**
 * Provides a static method to obtain an instance of a SimpleFeatureType for
 * Geonames data
 */
public class GeonamesSimpleFeatureType
{

	private static final String FEATURE_NAME = "GeonamesPoint";
	private static SimpleFeatureType simpleFeatureType;

	private GeonamesSimpleFeatureType() {
		// prevent instantiation
	}

	public static SimpleFeatureType getInstance() {
		if (simpleFeatureType == null) {
			simpleFeatureType = createGeonamesPointType();
		}
		return simpleFeatureType;
	}

	private static SimpleFeatureType createGeonamesPointType() {

		final SimpleFeatureTypeBuilder sftBuilder = new SimpleFeatureTypeBuilder();
		final AttributeTypeBuilder atBuilder = new AttributeTypeBuilder();

		sftBuilder.setName(FEATURE_NAME);

		sftBuilder.add(atBuilder.binding(
				Geometry.class).nillable(
				false).buildDescriptor(
				"geometry"));
		sftBuilder.add(atBuilder.binding(
				Double.class).nillable(
				false).buildDescriptor(
				"Latitude"));
		sftBuilder.add(atBuilder.binding(
				Double.class).nillable(
				false).buildDescriptor(
				"Longitude"));
		sftBuilder.add(atBuilder.binding(
				String.class).nillable(
				false).buildDescriptor(
				"Location"));

		return sftBuilder.buildFeatureType();
	}

}


text:
package enl.sif.path;

public class PathSegmentLogRecord extends LogRecord {
	private short fid; // flow id
	private long pid; // path segment id

	public PathSegmentLogRecord(short fid, long pid, short tid) {
		super(tid);
		this.fid = fid;
		this.pid = pid;
	}

	public short getFid() {
		return fid;
	}

	public long getPid() {
		return pid;
	}

	@Override
	public int hashCode() {
		final int prime = 31;
		int result = 1;
		result = prime * result + fid;
		result = prime * result + (int) (pid ^ (pid >>> 32));
		return result;
	}

	@Override
	public boolean equals(Object obj) {
		if (this == obj)
			return true;
		if (obj == null)
			return false;
		if (getClass() != obj.getClass())
			return false;
		PathSegmentLogRecord other = (PathSegmentLogRecord) obj;
		if (fid != other.fid)
			return false;
		if (pid != other.pid)
			return false;
		return true;
	}

	@Override
	public String toString() {
		return "PS " + pid;
	}

}


text:
package org.apache.wicket.markup.html;

import org.apache.wicket.ajax.AjaxRequestTarget;
import org.apache.wicket.ajax.markup.html.AjaxFallbackLink;
import org.apache.wicket.markup.html.TransparentWebMarkupContainer;
import org.apache.wicket.markup.html.WebMarkupContainer;
import org.apache.wicket.markup.html.WebPage;
import org.apache.wicket.markup.html.basic.Label;

/**
 * A test page for triggering a StackOverflowError when updating a component inside a
 * {@link TransparentWebMarkupContainer} using AJAX.
 */
public class SingleNestedTransparentContainerPage extends WebPage
{
	private static final long serialVersionUID = 1L;

	/**
	 * Constructor
	 */
	public SingleNestedTransparentContainerPage()
	{
		final Label label = new Label("label", "Label");
		label.setOutputMarkupId(true);
		add(label);

		// The src attribute of the image tag inside this WebMarkupContainer is
		// essential in triggering this bug. This causes Wicket to insert an
		// autocomponent (also a TransparentWebMarkupContainer)
		add(new WebMarkupContainer("group"));

		// if you add this TransparentWebMarkupContainer as first component in
		// the page (i.e. move line 50 to line 39), the test passes
		add(new TransparentWebMarkupContainer("twmc"));

		// a non-AJAX click on this link passes the test case, an AJAX request
		// fails with a StackOverflowError
		add(new AjaxFallbackLink<Void>("link")
		{
			private static final long serialVersionUID = 1L;

			@Override
			public void onClick(AjaxRequestTarget target)
			{
				if (target != null)
					target.add(label);
			}
		});
	}
}


text:
package org.apache.cassandra.stress.operations;

import com.yammer.metrics.core.TimerContext;
import org.apache.cassandra.stress.Session;
import org.apache.cassandra.stress.util.CassandraClient;
import org.apache.cassandra.stress.util.Operation;
import org.apache.cassandra.db.ColumnFamilyType;
import org.apache.cassandra.thrift.*;

import java.io.IOException;
import java.nio.ByteBuffer;
import java.util.List;

public class CounterGetter extends Operation
{
    public CounterGetter(Session client, int index)
    {
        super(client, index);
    }

    public void run(CassandraClient client) throws IOException
    {
        SliceRange sliceRange = new SliceRange();

        // start/finish
        sliceRange.setStart(new byte[] {}).setFinish(new byte[] {});

        // reversed/count
        sliceRange.setReversed(false).setCount(session.getColumnsPerKey());

        // initialize SlicePredicate with existing SliceRange
        SlicePredicate predicate = new SlicePredicate().setSlice_range(sliceRange);

        if (session.getColumnFamilyType() == ColumnFamilyType.Super)
        {
            runSuperCounterGetter(predicate, client);
        }
        else
        {
            runCounterGetter(predicate, client);
        }
    }

    private void runSuperCounterGetter(SlicePredicate predicate, Cassandra.Client client) throws IOException
    {
        byte[] rawKey = generateKey();
        ByteBuffer key = ByteBuffer.wrap(rawKey);

        for (int j = 0; j < session.getSuperColumns(); j++)
        {
            String superColumn = 'S' + Integer.toString(j);
            ColumnParent parent = new ColumnParent("SuperCounter1").setSuper_column(superColumn.getBytes());

            TimerContext context = session.latency.time();

            boolean success = false;
            String exceptionMessage = null;

            for (int t = 0; t < session.getRetryTimes(); t++)
            {
                if (success)
                    break;

                try
                {
                    List<ColumnOrSuperColumn> counters;
                    counters = client.get_slice(key, parent, predicate, session.getConsistencyLevel());
                    success = (counters.size() != 0);
                }
                catch (Exception e)
                {
                    exceptionMessage = getExceptionMessage(e);
                    success = false;
                }
            }

            if (!success)
            {
                error(String.format("Operation [%d] retried %d times - error reading counter key %s %s%n",
                                    index,
                                    session.getRetryTimes(),
                                    new String(rawKey),
                                    (exceptionMessage == null) ? "" : "(" + exceptionMessage + ")"));
            }

            session.operations.getAndIncrement();
            session.keys.getAndIncrement();
            context.stop();
        }
    }

    private void runCounterGetter(SlicePredicate predicate, Cassandra.Client client) throws IOException
    {
        ColumnParent parent = new ColumnParent("Counter1");

        byte[] key = generateKey();
        ByteBuffer keyBuffer = ByteBuffer.wrap(key);

        TimerContext context = session.latency.time();

        boolean success = false;
        String exceptionMessage = null;

        for (int t = 0; t < session.getRetryTimes(); t++)
        {
            if (success)
                break;

            try
            {
                List<ColumnOrSuperColumn> counters;
                counters = client.get_slice(keyBuffer, parent, predicate, session.getConsistencyLevel());
                success = (counters.size() != 0);
            }
            catch (Exception e)
            {
                exceptionMessage = getExceptionMessage(e);
                success = false;
            }
        }

        if (!success)
        {
            error(String.format("Operation [%d] retried %d times - error reading counter key %s %s%n",
                                index,
                                session.getRetryTimes(),
                                new String(key),
                                (exceptionMessage == null) ? "" : "(" + exceptionMessage + ")"));
        }

        session.operations.getAndIncrement();
        session.keys.getAndIncrement();
        context.stop();
    }
}


text:
print(__doc__)

import numpy as np
import pylab as pl
from time import time

from sklearn import datasets
from sklearn.decomposition import PCA

from sklearn import svm
from sklearn import pipeline
from sklearn.kernel_approximation import RBFSampler
from sklearn.kernel_approximation import Nystroem

def loadData():

    digits = datasets.load_digits(n_class=9)

    # flatten images, to turn data in a matrix (samples, feature)
    n_samples = len(digits.data)
    data = digits.data / 16.
    data -= data.mean(axis=0)

    data_train = data[:n_samples/2]
    targets_train = digits.target[:n_samples/2]

    return data_train, targets_train

def createSVM():
    kernel_svm = svm.SVC(gamma=.2)
    linear_svm = svm.LinearSVC()
    return kernel_svm, linear_svm

def createPipeline():
    feature_map_fourier = RBFSampler(gamma=.2, random_state=1)
    feature_map_nystroem = Nystroem(gamma=.2, random_state=1)
    fourier_approx_svm = pipeline.Pipeline([('feature_map', feature_map_fourier), \
                                            ('svm', svm.LinarSVC())])
    nystroem_approx_svm = pipeline.Pipeline([('feature_map', feature_map_nystroem), \
                                             ('svm', svm.LinearSVC())])
    return fourier_approx_svm, nystroem_approx_svm

def predict(data_train, targets_train):

    kernel_svm_time = time()
    kernel_svm.fit(data_train, targets_train)
    kernel_svm_score = kernel_svm.score(data_test, targets_test)
    kernel_svm_time = time() - kernel_svm_time

    linear_svm_time = time()
    linear_svm.fit(data_train, targets_train)
    linear_svm_score = linear_svm.score(data_test, targets_test)
    linear_svm_time = time() - linear_svm_time

    sample_sizes = 30 * np.arange(1, 10)
    fourier_scores = []
    nystroem_scores = []
    fourier_times = []
    nystroem_times = []

    for D in sample_sizes:
        fourier_approx_svm.set_params(feature_map__n_components=D)
        nystroem_approx_svm.set_params(feature_map__n_components=D)
        start = time()
        nystroem_approx_svm.fit(data_train, targets_train)
        nystroem_times.append(time() - start)

        start = time()
        fourier_approx_svm.fit(data_train, targets_train)
        fourier_times.append(time() - start)

        fourier_score = fourier_approx_svm.score(data_test, targets_test)
        nystroem_score = nystroem_approx_svm.score(data_test, targets_test)
        nystroem_scores.append(nystroem_score)
        fourier_scores.append(fourier_score)

def plotResults():

    pl.figure(figsize=(8, 8))

    accuracy = pl.subplot(211)
    timescale = pl.subplot(212)

    accuracy.plot(sample_sizes, \
                  nystroem_scores, \
                  label="Nystroem approx. kernel")

    timescale.plot(sample_sizes, \
                   nystroem_times, \
                   '--', \
                   label='Nystroem approx. kernel')

    accuracy.plot(sample_sizes, fourier_scores, label="Fourier approx. kernel")
    timescale.plot(sample_sizes, fourier_times, '--',
               label='Fourier approx. kernel')

    # horizontal lines for exact rbf and linear kernels:
    accuracy.plot([sample_sizes[0], sample_sizes[-1]],
                  [linear_svm_score, linear_svm_score], label="linear svm")
    timescale.plot([sample_sizes[0], sample_sizes[-1]],
                   [linear_svm_time, linear_svm_time], '--', label='linear svm')

    accuracy.plot([sample_sizes[0], sample_sizes[-1]],
                  [kernel_svm_score, kernel_svm_score], label="rbf svm")
    timescale.plot([sample_sizes[0], sample_sizes[-1]],
                   [kernel_svm_time, kernel_svm_time], '--', label='rbf svm')

    # vertical line for dataset dimensionality = 64
    accuracy.plot([64, 64], [0.7, 1], label="n_features")

    # legends and labels
    accuracy.set_title("Classification accuracy")
    timescale.set_title("Training times")
    accuracy.set_xlim(sample_sizes[0], sample_sizes[-1])
    accuracy.set_xticks(())
    accuracy.set_ylim(np.min(fourier_scores), 1)
    timescale.set_xlabel("Sampling steps = transformed feature dimension")
    accuracy.set_ylabel("Classification accuracy")
    timescale.set_ylabel("Training time in seconds")
    accuracy.legend(loc='best')
    timescale.legend(loc='best')

    # visualize the decision surface, projected down to the first
    # two principal components of the dataset
    pca = PCA(n_components=8).fit(data_train)

    X = pca.transform(data_train)

    # Gemerate grid along first two principal components
    multiples = np.arange(-2, 2, 0.1)
    # steps along first component
    first = multiples[:, np.newaxis] * pca.components_[0, :]
    # steps along second component
    second = multiples[:, np.newaxis] * pca.components_[1, :]
    # combine
    grid = first[np.newaxis, :, :] + second[:, np.newaxis, :]
    flat_grid = grid.reshape(-1, data.shape[1])

    # title for the plots
    titles = ['SVC with rbf kernel',
              'SVC (linear kernel)\n with Fourier rbf feature map\n'
              'n_components=100',
              'SVC (linear kernel)\n with Nystroem rbf feature map\n'
              'n_components=100']

    pl.tight_layout()
    pl.figure(figsize=(12, 5))

    # predict and plot
    for i, clf in enumerate((kernel_svm, nystroem_approx_svm,
                             fourier_approx_svm)):
        # Plot the decision boundary. For that, we will assign a color to each
        # point in the mesh [x_min, m_max]x[y_min, y_max].
        pl.subplot(1, 3, i + 1)
        Z = clf.predict(flat_grid)

        # Put the result into a color plot
        Z = Z.reshape(grid.shape[:-1])
        pl.contourf(multiples, multiples, Z, cmap=pl.cm.Paired)
        pl.axis('off')

        # Plot also the training points
        pl.scatter(X[:, 0], X[:, 1], c=targets_train, cmap=pl.cm.Paired)

        pl.title(titles[i])
    pl.tight_layout()
    pl.show()


text:
package org.apache.http.impl.cookie;

import java.util.Collection;

import org.apache.http.annotation.Immutable;

import org.apache.http.cookie.CookieSpec;
import org.apache.http.cookie.CookieSpecFactory;
import org.apache.http.cookie.params.CookieSpecPNames;
import org.apache.http.params.HttpParams;

/**
 * {@link CookieSpecFactory} implementation that creates and initializes
 * {@link BestMatchSpec} instances.
 *

 * The following parameters can be used to customize the behavior of this
 * class:
 *

 *
{@link org.apache.http.cookie.params.CookieSpecPNames#DATE_PATTERNS}

 *
{@link org.apache.http.cookie.params.CookieSpecPNames#SINGLE_COOKIE_HEADER}

 *

 *
 * @since 4.0
 */
@Immutable
public class BestMatchSpecFactory implements CookieSpecFactory {

    public CookieSpec newInstance(final HttpParams params) {
        if (params != null) {

            String[] patterns = null;
            Collection<?> param = (Collection<?>) params.getParameter(
                    CookieSpecPNames.DATE_PATTERNS);
            if (param != null) {
                patterns = new String[param.size()];
                patterns = param.toArray(patterns);
            }
            boolean singleHeader = params.getBooleanParameter(
                    CookieSpecPNames.SINGLE_COOKIE_HEADER, false);

            return new BestMatchSpec(patterns, singleHeader);
        } else {
            return new BestMatchSpec();
        }
    }

}


text:
<?php declare(strict_types=1);

namespace Darvin\UserBundle\Form\Factory;

use Darvin\UserBundle\Entity\BaseUser;
use Darvin\UserBundle\Entity\PasswordResetToken;
use Darvin\UserBundle\Form\Type\Security\LoginType;
use Darvin\UserBundle\Form\Type\Security\PasswordResetType;
use Darvin\UserBundle\Form\Type\Security\RegistrationType;
use Symfony\Component\Form\FormInterface;

/**
 * Security form factory
 */
interface SecurityFormFactoryInterface
{
    /**
     * @param array       $options Options
     * @param string      $type    Type
     * @param string|null $name    Name
     *
     * @return \Symfony\Component\Form\FormInterface
     */
    public function createLoginForm(array $options = [], string $type = LoginType::class, ?string $name = null): FormInterface;

    /**
     * @param \Darvin\UserBundle\Entity\PasswordResetToken $passwordResetToken Password reset token
     * @param array                                        $options            Options
     * @param string                                       $type               Type
     * @param string|null                                  $name               Name
     *
     * @return \Symfony\Component\Form\FormInterface
     */
    public function createPasswordResetForm(PasswordResetToken $passwordResetToken, array $options = [], string $type = PasswordResetType::class, ?string $name = null): FormInterface;

    /**
     * @param \Darvin\UserBundle\Entity\BaseUser|null $user    User
     * @param array                                   $options Options
     * @param string                                  $type    Type
     * @param string|null                             $name    Name
     *
     * @return \Symfony\Component\Form\FormInterface
     */
    public function createRegistrationForm(?BaseUser $user = null, array $options = [], string $type = RegistrationType::class, ?string $name = null): FormInterface;
}


text:
//------------------------------------------------------------------------------
// <copyright file="Capture.cs" company="Microsoft">
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License.
// </copyright>
//------------------------------------------------------------------------------
using System;
using System.Diagnostics.CodeAnalysis;

namespace Microsoft.Azure.Kinect.Sensor
{
    /// <summary>
    /// A set of images captured in sync.
    /// </summary>
    public class Capture : IDisposable
    {
        // Image caches
        // These are the managed wrappers for the native images.
        // They are owned by this class and must be disposed when the capture is disposed.
        private Image cachedColor;
        private Image cachedDepth;
        private Image cachedIR;

        private NativeMethods.k4a_capture_t handle;

        private bool disposedValue = false; // To detect redundant calls

        /// <summary>
        /// Initializes a new instance of the <see cref="Capture"/> class.
        /// </summary>
        public Capture()
        {
            AzureKinectException.ThrowIfNotSuccess(() => NativeMethods.k4a_capture_create(out this.handle));

            // Hook the native allocator and register this object.
            // .Dispose() will be called on this object when the allocator is shut down.
            Allocator.Singleton.RegisterForDisposal(this);
        }

        /// <summary>
        /// Initializes a new instance of the <see cref="Capture"/> class.
        /// </summary>
        /// <param name="handle">Native handle of the Capture.</param>
        internal Capture(NativeMethods.k4a_capture_t handle)
        {
            // Hook the native allocator and register this object.
            // .Dispose() will be called on this object when the allocator is shut down.
            Allocator.Singleton.RegisterForDisposal(this);

            this.handle = handle;
        }

        /// <summary>
        /// Gets or sets the color image of this capture.
        /// </summary>
        /// <remarks>
        /// Images assigned to this capture are owned by the Capture. When the Capture is disposed, the
        /// Color Image will be disposed.
        ///
        /// By setting the Color image on a Capture, the Capture takes ownership and the Capture will
        /// dispose the Image when the Capture is disposed.
        ///
        /// To get an instance of an Image that lives longer than the capture, call Image.Reference().
        /// </remarks>
        [SuppressMessage("Design", "CA1062:Validate arguments of public methods", Justification = "SetImageWrapperAndDisposePrevious uses null to clear the stored image.")]
        public Image Color
        {
            get
            {
                this.UpdateImageWrapperAndDisposePrevious(NativeMethods.k4a_capture_get_color_image, ref this.cachedColor);

                return this.cachedColor;
            }

            set
            {
                this.SetImageWrapperAndDisposePrevious(NativeMethods.k4a_capture_set_color_image, ref this.cachedColor, value);
            }
        }

        /// <summary>
        /// Gets or sets the depth image of this capture.
        /// </summary>
        /// <remarks>
        /// Images assigned to this capture are owned by the Capture. When the Capture is disposed, the
        /// Depth Image will be disposed.
        ///
        /// By setting the Depth image on a Capture, the Capture takes ownership and the Capture will
        /// dispose the Image when the Capture is disposed.
        ///
        /// To get an instance of an Image that lives longer than the capture, call Image.Reference().
        /// </remarks>
        [SuppressMessage("Design", "CA1062:Validate arguments of public methods", Justification = "SetImageWrapperAndDisposePrevious uses null to clear the stored image.")]
        public Image Depth
        {
            get
            {
                this.UpdateImageWrapperAndDisposePrevious(NativeMethods.k4a_capture_get_depth_image, ref this.cachedDepth);

                return this.cachedDepth;
            }

            set
            {
                this.SetImageWrapperAndDisposePrevious(NativeMethods.k4a_capture_set_depth_image, ref this.cachedDepth, value);
            }
        }

        /// <summary>
        /// Gets or sets the IR image of this capture.
        /// </summary>
        /// <remarks>
        /// Images assigned to this capture are owned by the Capture. When the Capture is disposed, the
        /// IR Image will be disposed.
        ///
        /// By setting the IR image on a Capture, the Capture takes ownership and the Capture will
        /// dispose the Image when the Capture is disposed.
        ///
        /// To get an instance of an Image that lives longer than the capture, call Image.Reference().
        /// </remarks>
        [SuppressMessage("Design", "CA1062:Validate arguments of public methods", Justification = "SetImageWrapperAndDisposePrevious uses null to clear the stored image.")]
        public Image IR
        {
            get
            {
                this.UpdateImageWrapperAndDisposePrevious(NativeMethods.k4a_capture_get_ir_image, ref this.cachedIR);

                return this.cachedIR;
            }

            set
            {
                this.SetImageWrapperAndDisposePrevious(NativeMethods.k4a_capture_set_ir_image, ref this.cachedIR, value);
            }
        }

        /// <summary>
        /// Gets or sets the device temperature at the time of the capture.
        /// </summary>
        /// <remarks>
        /// Temperature is represented in degrees Celsius.
        /// </remarks>
        public float Temperature
        {
            get
            {
                lock (this)
                {
                    if (this.disposedValue)
                    {
                        throw new ObjectDisposedException(nameof(Capture));
                    }

                    return NativeMethods.k4a_capture_get_temperature_c(this.handle);
                }
            }

            set
            {
                lock (this)
                {
                    if (this.disposedValue)
                    {
                        throw new ObjectDisposedException(nameof(Capture));
                    }

                    NativeMethods.k4a_capture_set_temperature_c(this.handle, value);
                }
            }
        }

        /// <summary>
        /// Creates a duplicate reference to the same Capture.
        /// </summary>
        /// <returns>A new Capture object representing the same data.</returns>
        /// <remarks>Creating a reference to the same capture does not copy the capture,
        /// or the image data stored in the capture, but creates a new managed object representing
        /// the same capture data. Each object must be independently disposed. The lifetime of the
        /// underlying capture data will be equal or greater than all of the referenced Capture objects.</remarks>
        public Capture Reference()
        {
            lock (this)
            {
                if (this.disposedValue)
                {
                    throw new ObjectDisposedException(nameof(Capture));
                }

#pragma warning disable CA2000 // Dispose objects before losing scope
                return new Capture(this.handle.DuplicateReference());
#pragma warning restore CA2000 // Dispose objects before losing scope
            }
        }

        /// <inheritdoc/>
        public void Dispose()
        {
            this.Dispose(true);

            GC.SuppressFinalize(this);
        }

        /// <summary>
        /// Gets the native handle.
        /// </summary>
        /// <returns>The native handle that is wrapped by this capture.</returns>
        /// <remarks>The function is dangerous because there is no guarantee that the
        /// handle will not be disposed once it is retrieved. This should only be called
        /// by code that can ensure that the Capture object will not be disposed on another
        /// thread.</remarks>
        internal NativeMethods.k4a_capture_t DangerousGetHandle()
        {
            lock (this)
            {
                if (this.disposedValue)
                {
                    throw new ObjectDisposedException(nameof(Capture));
                }

                return this.handle;
            }
        }

        /// <summary>
        /// Checks two captures to determine if they represent the same native capture object.
        /// </summary>
        /// <param name="other">Another Capture to compare against.</param>
        /// <returns>true if the Captures represent the same native k4a_capture_t.</returns>
        internal bool NativeEquals(Capture other)
        {
            lock (this)
            {
                lock (other)
                {
                    if (this.disposedValue || other.disposedValue)
                    {
                        return false;
                    }

                    IntPtr myHandleValue = this.handle.DangerousGetHandle();
                    IntPtr otherHandleValue = other.handle.DangerousGetHandle();

                    // If both images represent the same native handle, consider them equal
                    return myHandleValue == otherHandleValue;
                }
            }
        }

        /// <summary>
        /// Handle the disposing of the object.
        /// </summary>
        /// <param name="disposing">true when called by Dispose(), false when called by the finalizer.</param>
        protected virtual void Dispose(bool disposing)
        {
            lock (this)
            {
                if (!this.disposedValue && disposing)
                {
                    this.cachedColor?.Dispose();
                    this.cachedDepth?.Dispose();
                    this.cachedIR?.Dispose();

                    this.cachedColor = null;
                    this.cachedDepth = null;
                    this.cachedIR = null;

                    this.handle.Close();
                    this.handle = null;

                    Allocator.Singleton.UnregisterForDisposal(this);
                }

                this.disposedValue = true;
            }
        }

        /// <summary>
        /// Retrieves a native image handle from the native API.
        /// </summary>
        /// <param name="nativeMethod">Native method to retrieve the image.</param>
        /// <param name="cachedImage">A cached instance of the Image that we return to callers. (Callers may dispose this image, although they shouldn't).</param>
        /// <remarks>
        /// If this is the first time calling the property, we construct a new wrapper.
        /// If the handle is for an Image we have already constructed a wrapper for, we return the existing wrapper.
        /// If the handle is for a different Image, we construct a new wrapper and dispose the old one.
        /// If existing wrapper has been disposed, we throw an exception.
        /// </remarks>
        private void UpdateImageWrapperAndDisposePrevious(
            Func<NativeMethods.k4a_capture_t, NativeMethods.k4a_image_t> nativeMethod,
            ref Image cachedImage)
        {
            // Lock must be held to ensure the Image in cache is not replaced while we are inspecting it
            // It is still possible for that Image to be accessed or Disposed while this lock is held
            lock (this)
            {
                if (this.disposedValue)
                {
                    throw new ObjectDisposedException(nameof(Capture));
                }

                // Get the image object from the native SDK
                // We now own a reference on this image and must eventually release it.
                NativeMethods.k4a_image_t nativeImageHandle = nativeMethod(this.handle);

                // This try block ensures that we close image (and release our reference) if we fail
                // to create a new Image.
                try
                {
                    // If this Capture previously had an image
                    if (cachedImage != null)
                    {
                        // Get the native pointer
                        IntPtr imageHandleValue = nativeImageHandle.DangerousGetHandle();

                        // Get the handle value from the cached image. If it has been disposed, this
                        // will throw an exception, which will be passed to the caller.

                        // Take an extra reference on the cachedImage to ensure it doesn't get disposed
                        // after getting the IntPtr from the handle.
                        using (Image reference = cachedImage.Reference())
                        {
                            if (reference.DangerousGetHandle().DangerousGetHandle() != imageHandleValue)
                            {
                                // The image has changed, invalidate the current image and construct new wrappers
                                cachedImage.Dispose();
                                cachedImage = null;
                            }
                        }
                    }

                    if (cachedImage == null && !nativeImageHandle.IsInvalid)
                    {
                        // Construct a new wrapper and return it
                        // The native function may have returned
#pragma warning disable CA2000 // Dispose objects before losing scope
                        cachedImage = new Image(nativeImageHandle);
#pragma warning restore CA2000 // Dispose objects before losing scope

                        // Since we have wrapped image, it is now owned by Image and we should no longer close it
                        nativeImageHandle = null;
                    }
                }
                finally
                {
                    // Ensure the native handle is closed if we have a failure creating the Image object
                    if (nativeImageHandle != null)
                    {
                        nativeImageHandle.Close();
                    }
                }
            }
        }

        /// <summary>
        /// Sets the image wrapper provided to a property.
        /// </summary>
        /// <param name="nativeMethod">Native set method.</param>
        /// <param name="cachedImage">Reference to the cached image wrapper used by this class.</param>
        /// <param name="value">Value to assign the image wrapper to.</param>
        /// <remarks>
        /// This function takes ownership of the wrapper and stores it in the class. If there was
        /// a previous wrapper owned by the class, this function will dispose it.
        /// </remarks>
        private void SetImageWrapperAndDisposePrevious(
            Action<NativeMethods.k4a_capture_t, NativeMethods.k4a_image_t> nativeMethod,
            ref Image cachedImage,
            Image value)
        {
            lock (this)
            {
                if (this.disposedValue)
                {
                    throw new ObjectDisposedException(nameof(Capture));
                }

                // If the assignment is a new managed wrapper we need
                // to release the reference to the old wrapper.
                // If it is the same object though, we should not dispose it.
                if (cachedImage != null && !object.ReferenceEquals(
                    cachedImage, value))
                {
                    cachedImage.Dispose();
                }

                cachedImage = value;

                // Take an extra reference on the image to ensure it isn't disposed
                // prior while we have the handle.
                using (Image reference = cachedImage.Reference())
                {
                    nativeMethod(this.handle, cachedImage.DangerousGetHandle());
                }
            }
        }
    }
}


text:
layout: post
date:	2012-04-10 10:54:00
title:  Politics and politicians...both ARE jokes...
tags: [archived-posts]
categories: archives
permalink: /:categories/:year/:month/:day/:title/
---
The problem with political jokes is
they get elected.
~ Henry Cate, VII
We hang the petty thieves
and appoint the great ones to public office.
~ Aesop
If we got one-tenth of what was promised to us
in these acceptance speeches
there wouldn't be any inducement to go to heaven.
~ Will Rogers
Those who are too smart to engage in politics
are punished by being governed
by those who are dumber.
~ Plato
Politicians are the same all over.
They promise to build a bridge
even where there is no river.
~ Nikita Khrushchev
When I was a boy I was told
that anybody could become President;
I'm beginning to believe it
~ Clarence Darrow
Why pay money to have your family tree traced;
go into politics and
your opponents will do it for you.
~ Author Unknown
If God wanted us to vote,
he would have given us candidates.
~ Jay Leno
Politicians are people who,
when they see light at the end of the tunnel,
go out and buy some more tunnel.
~ John Quinton
Politics is the gentle art of
getting votes from the poor
and campaign funds from the rich,
by promising to protect each from the other.
~ Oscar Ameringer
I offer my opponents a bargain:
if they will stop telling lies about us,
I will stop telling the truth about them.
~ Adlai Stevenson
Campaign Speech, 1952
A politician is a fellow who
will lay down your life for his country.
~ Texas Guinan
Any American who is prepared to run for president
should automatically, by definition,
be disqualified from ever doing so.
~ Gore Vidal
I have come to the conclusion
that politics is too serious a matter
to be left to the politicians.
~ Charles de Gaulle
Politics is supposed to be the second-oldest profession .
I have come to realize that it
bears a very close resemblance to the first.
~ Ronald Reagan
Politics:
[Poly "many" + tics "blood-sucking parasites"]
~ Larry Hardiman
Instead of giving a politician the keys to the city,
it might be better to change the locks.
~ Doug Larson
Don't vote, it only encourages them.
~ Author Unknown
There ought to be one day
-- just one --
when there is open season on senators.
~ Will Rogers


text:
//package com.kit.example;
//
//import java.io.File;
//import java.io.FileInputStream;
//import java.io.IOException;
//import java.util.ArrayList;
//import java.util.List;
//
//import org.apache.hadoop.io.Text;
//import org.apache.hadoop.conf.Configuration;
//import org.apache.hadoop.fs.Path;
//import org.apache.hadoop.hbase.HBaseConfiguration;
//import org.apache.hadoop.hbase.HConstants;
//import org.apache.hadoop.hbase.client.Scan;
//import org.apache.hadoop.hbase.mapreduce.IdentityTableMapper;
//import org.apache.hadoop.hbase.mapreduce.TableMapReduceUtil;
//import org.apache.hadoop.hbase.io.ImmutableBytesWritable;
//import org.apache.hadoop.mapreduce.Job;
//import org.apache.hadoop.mapreduce.lib.output.FileOutputFormat;
//import org.apache.hadoop.mapred.JobConf;
//import org.apache.hadoop.util.GenericOptionsParser;
//
//import org.apache.hadoop.hbase.filter.SingleColumnValueFilter;
//import org.apache.hadoop.hbase.filter.CompareFilter;
//import org.apache.hadoop.hbase.filter.CompareFilter.CompareOp;
//import org.apache.hadoop.hbase.filter.BinaryComparator;
//import org.apache.hadoop.hbase.util.Bytes;
//
//
//public class ExportHbase {
//    private static final String INFOCATEGORY = "info:storecategory";
//
//    private static final String USAGE = "Usage: ExportHbase " +
//        "-r <numReduceTasks> -indexConf <iconfFile>\n" +
//        "-indexDir <indexDir> -webSite <amazon> [-needupdate <true> -isVisible -startTime <long>] -table <tableName> -columns <columnName1> " +
//        "[<columnName2> ...]";
//
//    /**
//     * Prints the usage message and exists the program.
//     *
//     * @param message  The message to print first.
//     */
//    private static void printUsage(String message) {
//        System.err.println(message);
//        System.err.println(USAGE);
//        throw new RuntimeException(USAGE);
//    }
//
//    /**
//     * Creates a new job.
//     * @param conf
//     *
//     * @param args  The command line arguments.
//     * @throws IOException When reading the configuration fails.
//     */
//    public static Job createSubmittableJob(Configuration conf, String[] args)
//        throws IOException {
//        if (args.length < 7) {
//            printUsage("Too few arguments");
//        }
//
//        int numReduceTasks = 1;
//        String iconfFile = null;
//        String indexDir = null;
//        String tableName = null;
//        String website = null;
//        String needupdate = "";
//        String expectShopGrade = "";
//        String dino = "6";
//        String isdebug = "0";
//        long debugThreshold = 10000;
//        String debugThresholdStr = Long.toString(debugThreshold);
//        String queue = "offline";
//
//        long endTime =  Long.MAX_VALUE;
//        int maxversions = 1;
//        long startTime = System.currentTimeMillis() - 28*24*60*60*1000l;
//        long distartTime = System.currentTimeMillis() - 30*24*60*60*1000l;
//        long diusedTime = System.currentTimeMillis() - 30*24*60*60*1000l;
//        String startTimeStr = Long.toString(startTime);
//        String diusedTimeStr = Long.toString(diusedTime);
//        String quorum = null;
//
//        String isVisible = "";
//        List<String> columns = new ArrayList<String>() ;
//
//        boolean bFilter = false;
//
//        // parse args
//        for (int i = 0; i < args.length - 1; i++) {
//            if ("-r".equals(args[i])) {
//                numReduceTasks = Integer.parseInt(args[++i]);
//            } else if ("-indexConf".equals(args[i])) {
//                iconfFile = args[++i];
//            } else if ("-indexDir".equals(args[i])) {
//                indexDir = args[++i];
//            } else if ("-table".equals(args[i])) {
//                tableName = args[++i];
//            } else if ("-webSite".equals(args[i])) {
//                website = args[++i];
//            } else if ("-startTime".equals(args[i])) {
//                startTimeStr = args[++i];
//                startTime = Long.parseLong(startTimeStr);
//            } else if ("-needupdate".equals(args[i])) {
//                needupdate = args[++i];
//            } else if ("-isVisible".equals(args[i])) {
//                isVisible = "true";
//            } else if ("-shopgrade".equals(args[i])) {
//                expectShopGrade = args[++i];
//            } else if ("-queue".equals(args[i])) {
//                queue = args[++i];
//            } else if ("-dino".equals(args[i])) {
//                dino = args[++i];
//            } else if ("-maxversions".equals(args[i])) {
//                maxversions = Integer.parseInt(args[++i]);
//            } else if ("-distartTime".equals(args[i])) {
//                distartTime = Long.parseLong(args[++i]);
//            } else if ("-diendTime".equals(args[i])) {
//                endTime = Long.parseLong(args[++i]);
//            } else if ("-diusedTime".equals(args[i])) {
//                diusedTimeStr = args[++i];
//                diusedTime = Long.parseLong(diusedTimeStr);
//            } else if ("-quorum".equals(args[i])) {
//                quorum = args[++i];
//            } else if ("-filter".equals(args[i])) {
//                bFilter = true;
//            } else if ("-columns".equals(args[i])) {
//                columns.add(args[++i]);
//                while (i + 1 < args.length && !args[i + 1].startsWith("-")) {
//                    String columnname = args[++i];
//                    columns.add(columnname);
//                    System.out.println("args column----: " + columnname);
//                }
//            } else if ("-debugThreshold".equals(args[i])) {
//                isdebug = "1";
//                debugThresholdStr = args[++i];
//                debugThreshold =  Long.parseLong( debugThresholdStr );
//            }
//            else {
//                printUsage("Unsupported option " + args[i]);
//            }
//        }
//
//        if (distartTime > endTime) {
//            printUsage("distartTime must <= diendTime");
//        }
//
//        if (indexDir == null || tableName == null || columns.isEmpty()) {
//            printUsage("Index directory, table name and at least one column must " +
//                    "be specified");
//        }
//
//        if (iconfFile != null) {
//            // set index configuration content from a file
//            String content = readContent(iconfFile);
//            conf.set("hbase.index.conf", content);
//            conf.set("hbase.website.name", website);
//            conf.set("hbase.needupdate.productDB", needupdate);
//            conf.set("hbase.expect.shopgrade", expectShopGrade);
//            conf.set("hbase.di.no", dino);
//            conf.set("hbase.expect.item.visible", isVisible);
//            conf.set("hbase.index.startTime", startTimeStr);
//            conf.set("hbase.index.diusedTime", diusedTimeStr);
//            conf.set("hbase.index.debugThreshold", debugThresholdStr);
//            conf.set("hbase.index.debug", isdebug);
//            if (quorum != null) {
//                conf.set("hbase.zookeeper.quorum", quorum);
//            }
//            String temp = "";
//            for (String column : columns) {
//                temp = temp + column + "|";
//            }
//            temp = temp.substring(0, temp.length() - 1);
//            conf.set("hbase.index.column", temp);
//            System.out.println("hbase.index.column: " + temp);
//        }
//
//
//        Job job = new Job(conf, "export data from table " + tableName);
//        ((JobConf) job.getConfiguration()).setQueueName(queue);
//
//        // number of indexes to partition into
//        job.setNumReduceTasks(numReduceTasks);
//        Scan scan = new Scan();
//        scan.setCacheBlocks(false);
//
//        // limit scan range
//        scan.setTimeRange(distartTime, endTime);
//        //  scan.setMaxVersions(maxversions);
//        scan.setMaxVersions(1);
//
//        /* limit scan columns */
//        for (String column : columns) {
//            scan.addColumn(ColumnUtils.getFamily(column), ColumnUtils.getQualifier(column));
//            scan.addFamily(ColumnUtils.getFamily(column));
//        }
//
//        // set filter
//        if( bFilter ){
//            System.out.println("only export guangtaobao data. ");
//            SingleColumnValueFilter filter = new SingleColumnValueFilter(
//                    Bytes.toBytes("info"),
//                    Bytes.toBytes("producttype"),
//                    CompareFilter.CompareOp.EQUAL,
//                    new BinaryComparator(Bytes.toBytes("guangtaobao")) );
//            filter.setFilterIfMissing(true);
//            scan.setFilter(filter);
//        }
//
//        TableMapReduceUtil.initTableMapperJob(tableName, scan, ExportHbaseMapper.class,
//                Text.class, Text.class, job);
//        // job.setReducerClass(ExportHbaseReducer.class);
//        FileOutputFormat.setOutputPath(job, new Path(indexDir));
//
//
//        return job;
//    }
//
//    /**
//     * Reads xml file of indexing configurations.  The xml format is similar to
//     * hbase-default.xml and hadoop-default.xml. For an example configuration,
//     * see the createIndexConfContent method in TestTableIndex.
//     *
//     * @param fileName  The file to read.
//     * @return XML configuration read from file.
//     * @throws IOException When the XML is broken.
//     */
//    private static String readContent(String fileName) throws IOException {
//        File file = new File(fileName);
//        int length = (int) file.length();
//        if (length == 0) {
//            printUsage("Index configuration file " + fileName + " does not exist");
//        }
//
//        int bytesRead = 0;
//        byte[] bytes = new byte[length];
//        FileInputStream fis = new FileInputStream(file);
//
//        try {
//            // read entire file into content
//            while (bytesRead < length) {
//                int read = fis.read(bytes, bytesRead, length - bytesRead);
//                if (read > 0) {
//                    bytesRead += read;
//                } else {
//                    break;
//                }
//            }
//        } finally {
//            fis.close();
//        }
//
//        return new String(bytes, 0, bytesRead, HConstants.UTF8_ENCODING);
//    }
//
//    /**
//     * The main entry point.
//     *
//     * @param args  The command line arguments.
//     * @throws Exception When running the job fails.
//     */
//    public static void main(String[] args) throws Exception {
//        Configuration conf = HBaseConfiguration.create();
//        String[] otherArgs =
//            new GenericOptionsParser(conf, args).getRemainingArgs();
//        Job job = createSubmittableJob(conf, otherArgs);
//        System.exit(job.waitForCompletion(true) ? 0 : 1);
//    }
//
//}


text:
'''
Created on 12 Oct 2016

This script is used to run samtools depth on a BAM file

@author: ernesto
'''
from BamQC import BamQC,SDepth
from pprint import pprint

import argparse

#get command line arguments

#RESEQTRACK DB conn params
parser = argparse.ArgumentParser(description='Script to calculate different QC metrics on the WGS BAMs')

parser.add_argument('--samtools', type=str, required=True, help='Folder containing the SAMtools binary' )
parser.add_argument('--filename', type=str, required=True, help='Path to the file that will be analysed' )
parser.add_argument('--list', type=argparse.FileType('r'), required=True, help='File with a list of chros to be analysed (comma-separated)' )

args = parser.parse_args()

if __name__ == '__main__':

    #list of chros to analyse
    list_chros=[]
    for line in args.list:
        line=line.strip("\n")
        list_chros=line.split(',')

    bam = BamQC(args.filename,args.samtools)

    stats=bam.get_simple_stats()
    for k,v in stats.items(): print(k+":"+str(v))
    cov_list=bam.run_samtools_depth(chros=list_chros)
    aggr_cov=bam.aggregate_stats(cov_list)
    print("contig: %s" % aggr_cov.contig)
    print("breadth: %f" % aggr_cov.breadth)
    print("depth: %f" % aggr_cov.depth)
    print("max: %f" % aggr_cov.max)
    pass


text:
YAML mailer, written in Python 3.3, parses a YAML file and
uses SMTP to email many people _different_ messages.
YAML mailer is different than typical mass mailers because it is
not meant for emailing many people identical messages.

This is useful to help organize email composition if you want
to email a lot of people similar messages and add
notes of individualization to each message.

# Configuration.
By default, configuration is expected to be in `~/.mailer.yaml`,
but can be changed with the `--config` flag.
See the [example configuration][example-conf].

# Example.
See [example-messages.yaml][example-messages] for an example to
get started with!

```
$ ./yaml-mailer.py example-messages.yaml

Sending message.
  To: bdamos@vt.edu
  Subject: yaml-mailer: Hi Brandon.
  Attach: yaml-mailer.py
Sending message.
  To: bdamos@vt.edu,bdamos+other-to@vt.edu
  CC: bdamos+cc@vt.edu
  BCC: bdamos+bcc@vt.edu
  Subject: yaml-mailer: Testing CC/BCC.
All messages sent successfully.
```

[example-messages]: https://github.com/bamos/yaml-mailer/blob/master/example-messages.yaml
[example-conf]: https://github.com/bamos/yaml-mailer/blob/master/example-conf.yaml


text:
var shouldClear = false;

document.addEventListener('DOMContentLoaded', function() {
    // Pincode verification code
    $('.check-button').on('click', function(){
        var code = $('.code').val();
        var checkBox = $('.check-box').is(':checked');

        console.log(checkBox);

        if (!(code.length != 6 || /^\d+$/.test(code))) {
            console.log('Invalid Code');
            appendToResults('Invalid Code, Try again', 'high');
            return;
        }

        if (!checkBox) {
            console.log('Needs to check Privacy Policy');
            appendToResults('Please agree to the Privacy Policy', 'medium');
            return;
        }

        var qs = getUrlVars();
        var uid = qs.uid;
        var pin = code;

        $.post(
            'http://pixelverify.tk:8080/auth',
            {
                'uid': uid,
                'pin': pin
            },
            function(data, status) {
                data = JSON.parse(data);
                console.log(data, status);
                if (data.status == 'success') {
                    appendToResults('Success, you will be verified momentarily!', 'low');
                } else {
                    appendToResults('Error: ' + data.error, 'high');
                }
            }
        );
    });
});

function appendToResults(text, importance) {
    if (shouldClear) {
        $('.results').children().fadeOut('slow');
        $('.results').empty();
        shouldClear = false;
    }

    var data = '
' + text + '
';
    $(data).appendTo('.results').hide().fadeIn('slow');
    shouldClear = true;
}

function getUrlVars() {
    var vars = [], hash;
    var hashes = window.location.href.slice(window.location.href.indexOf('?') + 1).split('&');
    for(var i = 0; i < hashes.length; i++) {
        hash = hashes[i].split('=');
        vars.push(hash[0]);
        vars[hash[0]] = hash[1];
    }
    return vars;
}


text:
pyfarm.master.user_interface.statistics.index module
====================================================

.. automodule:: pyfarm.master.user_interface.statistics.index
    :members:
    :undoc-members:
    :show-inheritance:


text:
const Store = require('electron-store');

module.exports = new Store({
  defaults: {
    autoLaunch: false,
    hideIcon: false,
    mode: 'screen-saver',
    hotkey: 'Control+Shift+L',
  },
});


text:
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
	xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
	xmlns:context="http://www.springframework.org/schema/context"
	xsi:schemaLocation="
  http://www.springframework.org/schema/beans
  http://www.springframework.org/schema/beans/spring-beans-3.0.xsd
  http://www.springframework.org/schema/context
  http://www.springframework.org/schema/context/spring-context-3.0.xsd">

<context:property-placeholder location="classpath:serviceconfig/olat.properties, classpath:olat.local.properties" />

<bean id="org.olat.admin.sysinfo.InfoMessageManager"
	class="org.olat.admin.sysinfo.InfoMessageManager">
	<constructor-arg index="0"  ref="coordinatorManager"/>
	<constructor-arg index="1" value="${node.id}" />
	<property name="actionController">
	<!-- there are two versions of the infoMessageController (singleVM or Cluster versions). Dynamic creation based on the value in olat.properties-->
		<bean class="org.olat.core.gui.control.creator.AutoCreator" scope="prototype">
			<property name="className" value="org.olat.admin.sysinfo.InfoMessageController${cluster.mode}"/>
		</bean>
	</property>
</bean>

</beans>


text:
require 'hanami/action/cache'

module Web::Controllers::Main
  class Index
    include Web::Action
    include Hanami::Action::Cache
    expose :tasks

    # TODO: move to operations
    def call(params)
      @tasks = TaskRepository.new.only_approved.first(3)
      fresh last_modified: @tasks.first&.created_at
    end
  end
end


text:
package peersim.util;

import java.util.Random;
import java.lang.Math;

/**
 * Extends the functionality of java.util.Random.
 */
public class ExtendedRandom extends Random {

private long lastSeed;

// -------------------------------------------------------------------------

/** Calls super constructor. Also stores the seed to be returned by
{@link #getLastSeed}. */
public ExtendedRandom(long seed) {

	super(seed);
	lastSeed = seed;
}

// -------------------------------------------------------------------------

/**
 * Extracts the next integer, according to a Poisson distribution.
 *
 * @param mean The mean of the Poisson distribution.
 * @return An integer Poisson extraction.
 */
public int nextPoisson(double mean) {

	double emean = Math.exp(-1 * mean);
	double product = 1;
	int count = 0;
	int result = 0;
	while (product >= emean) {
		product *= nextDouble();
		result = count;
		count++; // keep result one behind
	}
	return result;
}

// -------------------------------------------------------------------------

/**
* Implements nextLong(long) the same way nexInt(int) is implemented in
* java.util.Random.
* @param n the bound on the random number to be returned. Must be positive.
* @return a pseudorandom, uniformly distributed long value between 0
* (inclusive) and n (exclusive).
*/
public long nextLong(long n) {

	if (n<=0)
		throw new IllegalArgumentException("n must be positive");

	if ((n & -n) == n)  // i.e., n is a power of 2
	{
		return nextLong()&(n-1);
	}

	long bits, val;
	do
	{
		bits = (nextLong()>>>1);
		val = bits % n;
	}
	while(bits - val + (n-1) < 0);

	return val;
}

// -------------------------------------------------------------------------

/** Sets random seed. Calls super method but also stores the seed to be
returned by {@link #getLastSeed}. */
public void setSeed( long seed ) {

	super.setSeed(seed);
	lastSeed = seed;
}

// -------------------------------------------------------------------------

/**
* Returns the last random seed that was set explicitly. Either at
* construction time or through {@link #setSeed}.
*/
public long getLastSeed() { return lastSeed; }

// -------------------------------------------------------------------------

/*
public static void main(String[] args) {

	ExtendedRandom er = new ExtendedRandom(12345678);
	for(int i=0; i<100; ++i)
		System.out.println(er.nextLong(Long.parseLong(args[0])));

}
*/
}


text:
import util from 'util';
import mocha from 'mocha';
import { Result } from './result';
import { ReportWriter } from './writer';

/**
 * TextReporter
 *
 * options.reporterOptions
 * satisfactory - Satisfactory code coverage of value
 * critical - Critical code coverage of value
 */
export default class TextReporter extends mocha.reporters.Base {
  constructor(runner, options) {
    let opts = options || {};
    super(runner);
    this.writer = new ReportWriter(opts);
    runner.on('end', this.end.bind(this));
  }
  end() {
    let coverages = this.getCoverages();
    let result = Result.createFrom(coverages);
    result.sendTo(this.writer);
    this.result = result;
  }
  getCoverages() {
    return global._$jscoverage || {};
  }
  getFiles() {
    return this.result.files;
  }
}


text:
import org.apache.spark.SparkContext

// register case class external to main
case class Order(OrderID : String, CustomerID : String, EmployeeID : String,
OrderDate : String, ShipCountry : String)
//
case class OrderDetails(OrderID : String, ProductID : String, UnitPrice : Float,
Qty : Int, Discount : Float)
//
val filePath = "/Users/ksankar/fdps-v3/"
println(s"Running Spark Version ${sc.version}")
//
val sqlContext = new org.apache.spark.sql.SQLContext(sc)
import sqlContext._
import sqlContext.implicits._
//
val ordersFile = sc.textFile(filePath + "data/NW-Orders-NoHdr.csv")
println("Orders File has %d Lines.".format(ordersFile.count()))
val orders = ordersFile.map(_.split(",")).
map(e => Order( e(0), e(1), e(2),e(3), e(4) ))
println(orders.count)
orders.toDF().registerTempTable("Orders")
var count = sqlContext.sql("SELECT COUNT(*) from Orders")
count.show()
var result = sqlContext.sql("SELECT * from Orders")
// result.take(10).foreach(println) - no need for ugly println. show() does a good job !
result.show(10)
result.head(3)
//
val orderDetFile = sc.textFile(filePath + "data/NW-Order-Details-NoHdr.csv")
println("Order Details File has %d Lines.".format(orderDetFile.count()))
val orderDetails = orderDetFile.map(_.split(",")).
map(e => OrderDetails( e(0), e(1), e(2).trim.toFloat,e(3).trim.toInt, e(4).trim.toFloat ))
println(orderDetails.count)
orderDetails.toDF().registerTempTable("OrderDetails")
result = sqlContext.sql("SELECT * from OrderDetails")
//result.take(10).foreach(println)
result.show(10)
result.head(3)
//
// Now the interesting part
//
result = sqlContext.sql("SELECT OrderDetails.OrderID,ShipCountry,UnitPrice,Qty,Discount FROM Orders INNER JOIN OrderDetails ON Orders.OrderID = OrderDetails.OrderID")
//No need to elaborate println(). SHow() does a good job!
//result.take(10).foreach(println)
//result.take(10).foreach(e=>println("%s | %15s | %5.2f | %d | %5.2f |".format(e(0),e(1),e(2),e(3),e(4))))
result.show(10)
result.head(3)
//
// Sales By Country
//
result = sqlContext.sql("SELECT ShipCountry, SUM(OrderDetails.UnitPrice * Qty * Discount) AS ProductSales FROM Orders INNER JOIN OrderDetails ON Orders.OrderID = OrderDetails.OrderID GROUP BY ShipCountry")
result.count()
//result.take(10).foreach(println)
//result.take(30).foreach(e=>println("%15s | %9.2f |".format(e(0),e(1))))
result.show(10)
result.head(3)
//
println("** Done **");


text:
cask "grandtotal" do
  version "6.1.8"
  sha256 "c0aa7a5a61922600565b60ca17a0f2f82ace099882bd0a68c862a2cfda1794df"

  url "https://mediaatelier.com/GrandTotal#{version.major}/GrandTotal_#{version}.zip"
  appcast "https://mediaatelier.com/GrandTotal#{version.major}/feed.php"
  name "GrandTotal"
  homepage "https://www.mediaatelier.com/GrandTotal#{version.major}/"

  app "GrandTotal.app"
end


text:
module child {
    module common at 'fixtures/recursive/useCase2/common.js';
	export common, whatever;
}
// -s6d
console.log('running CHILD.JS', common);
var whatever = 'some value';


text:
<?xml version="1.0" encoding="UTF-8"?>

<beans xmlns="http://www.springframework.org/schema/beans" xmlns:mvc="http://www.springframework.org/schema/mvc"
	xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:context="http://www.springframework.org/schema/context"
	xmlns:tx="http://www.springframework.org/schema/tx"
	xsi:schemaLocation="http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc.xsd
		http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd
		http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx.xsd
		http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context.xsd">

	<mvc:annotation-driven />
	<mvc:default-servlet-handler/>

	<!-- 自动扫描且只扫描@Controller -->
	<context:component-scan base-package="cn.hybris" use-default-filters="false">
		<context:include-filter type="annotation" expression="org.springframework.stereotype.Controller" />
		<context:include-filter type="annotation" expression="org.springframework.web.bind.annotation.ControllerAdvice" />
	</context:component-scan>

	<bean id="viewResolver" class="org.springframework.web.servlet.view.InternalResourceViewResolver">
		<property name="viewClass" value="org.springframework.web.servlet.view.JstlView" />
		<property name="prefix" value="/WEB-INF/jsp/" />
		<property name="suffix" value=".jsp" />
	</bean>
</beans>


text:
<!DOCTYPE html><meta charset="UTF-8">

All movement should be at the same speed.


text:
std::optional<Average::averageValue>
    Average::getAverageValue(const Average::averageKey& sensorKey) const
{
    const auto it = _previousAverageMap.find(sensorKey);
    if (it == _previousAverageMap.end())
    {
        return {};
    }

    return std::optional(it->second);
}

void Average::setAverageValue(const Average::averageKey& sensorKey,
                              const Average::averageValue& sensorValue)
{
    _previousAverageMap[sensorKey] = sensorValue;
}

std::optional<int64_t> Average::calcAverage(int64_t preAverage,
                                            int64_t preInterval,
                                            int64_t curAverage,
                                            int64_t curInterval)
{
    int64_t value = 0;
    // Estimate that the interval will overflow about 292471
    // years after it starts counting, so consider it won't
    // overflow
    int64_t delta = curInterval - preInterval;

    assert(delta >= 0);
    // 0 means the delta interval is too short, the value of
    // power*_average_interval is not changed yet
    if (delta == 0)
    {
        return {};
    }
    // Change formula (a2*i2-a1*i1)/(i2-i1) to be the
    // following formula, to avoid multiplication overflow.
    // (a2*i2-a1*i1)/(i2-i1) =
    // (a2*(i1+delta)-a1*i1)/delta =
    // (a2-a1)(i1/delta)+a2
    value =
        (curAverage - preAverage) * (static_cast<double>(preInterval) / delta) +
        curAverage;

    return value;
}


text:
'use strict';

/**
 * Module dependencies.
 */
var users = require('../../app/controllers/users.server.controller'),
    courses = require('../../app/controllers/courses.server.controller'),
    schools = require('../../app/controllers/schools.server.controller'),
    uoftapi = require('../../app/controllers/uoftapi.server.controller');

module.exports = function(app) {
    // Course Routes
    app.route('/courses')
        .get(courses.listByCode, courses.listBySchool)
        // TODO: used for testing. Course to be added via scraper
        .post(users.isAdmin, courses.create);

    app.route('/courses/user')
        .get(users.requiresLogin, courses.getUserCourses);

    app.route('/courses/user/:courseId')
        .post(users.requiresLogin, courses.addToUser) //courses.hasAuthorization,
        .delete(users.requiresLogin, courses.removeFromUser); //courses.hasAuthorization,

    app.route('/courses/:courseId')
        .get(courses.read)
        .delete(users.isAdmin, courses.remove);

    app.route('/courses/update/:schoolId')
        .get(users.isAdmin, uoftapi.addCourses);

    app.param('courseId', courses.courseById);
    app.param('schoolId', schools.schoolById);
};


text:
package com.untzuntz.ustackserverapi.version;

public enum Versions implements VersionInt {

	Version100("1.0.0", "1/1/1900");

	private String versionId;
	private String releaseDate;
	private Versions(String versionId, String releaseDate) {
		this.versionId = versionId;
		this.releaseDate = releaseDate;
	}

	public String getVersionId() {
		return versionId;
	}

	public String getReleaseDate() {
		return releaseDate;
	}

}


text:
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
//# sourceMappingURL=TokenizationResponse.js.map


text:
package util

import breeze.linalg.DenseMatrix
import io.flatmap.ml.som.NeighborhoodKernel
import io.flatmap.ml.som.SelfOrganizingMap.Parameters

trait FakeNeighborhoodKernel extends NeighborhoodKernel {

  override def neighborhood(winner: (Int, Int))(implicit p: Parameters): DenseMatrix[Double] = ???

}


text:
import unittest
import numpy as np
from op_test import OpTest
import paddle
import paddle.fluid as fluid

class TestExpandAsBasic(OpTest):
    def setUp(self):
        self.op_type = "expand_as_v2"
        self.python_api = paddle.expand_as
        x = np.random.rand(100).astype("float64")
        target_tensor = np.random.rand(2, 100).astype("float64")
        self.inputs = {'X': x, "Y": target_tensor}
        self.attrs = {'target_shape': target_tensor.shape}
        bcast_dims = [2, 1]
        output = np.tile(self.inputs['X'], bcast_dims)
        self.outputs = {'Out': output}

    def test_check_output(self):
        self.check_output(check_eager=True)

    def test_check_grad(self):
        self.check_grad(['X'], 'Out', check_eager=True)

class TestExpandAsOpRank2(TestExpandAsBasic):
    def setUp(self):
        self.op_type = "expand_as_v2"
        self.python_api = paddle.expand_as
        x = np.random.rand(10, 12).astype("float64")
        target_tensor = np.random.rand(10, 12).astype("float64")
        self.inputs = {'X': x, "Y": target_tensor}
        self.attrs = {'target_shape': target_tensor.shape}
        bcast_dims = [1, 1]
        output = np.tile(self.inputs['X'], bcast_dims)
        self.outputs = {'Out': output}

class TestExpandAsOpRank3(TestExpandAsBasic):
    def setUp(self):
        self.op_type = "expand_as_v2"
        self.python_api = paddle.expand_as
        x = np.random.rand(2, 3, 20).astype("float64")
        target_tensor = np.random.rand(2, 3, 20).astype("float64")
        self.inputs = {'X': x, "Y": target_tensor}
        self.attrs = {'target_shape': target_tensor.shape}
        bcast_dims = [1, 1, 1]
        output = np.tile(self.inputs['X'], bcast_dims)
        self.outputs = {'Out': output}

class TestExpandAsOpRank4(TestExpandAsBasic):
    def setUp(self):
        self.op_type = "expand_as_v2"
        self.python_api = paddle.expand_as
        x = np.random.rand(1, 1, 7, 16).astype("float64")
        target_tensor = np.random.rand(4, 6, 7, 16).astype("float64")
        self.inputs = {'X': x, "Y": target_tensor}
        self.attrs = {'target_shape': target_tensor.shape}
        bcast_dims = [4, 6, 1, 1]
        output = np.tile(self.inputs['X'], bcast_dims)
        self.outputs = {'Out': output}

class TestExpandAsOpRank5(TestExpandAsBasic):
    no_need_check_grad = True

    def setUp(self):
        self.op_type = "expand_as_v2"
        self.python_api = paddle.expand_as
        x = np.random.rand(1, 1, 7, 16).astype("int64")
        target_tensor = np.random.rand(4, 6, 7, 16).astype("float64")
        self.inputs = {'X': x, "Y": target_tensor}
        self.attrs = {'target_shape': target_tensor.shape}
        bcast_dims = [4, 6, 1, 1]
        output = np.tile(self.inputs['X'], bcast_dims)
        self.outputs = {'Out': output}

    def test_check_grad(self):
        pass

class TestExpandAsV2Error(unittest.TestCase):
    def test_errors(self):
        with fluid.program_guard(fluid.Program(), fluid.Program()):
            x1 = fluid.layers.data(name='x1', shape=[4], dtype="uint8")
            x2 = fluid.layers.data(name='x2', shape=[4], dtype="int32")
            self.assertRaises(TypeError, paddle.tensor.expand_as, x1, x2)
            x3 = fluid.layers.data(name='x3', shape=[4], dtype="bool")
            x3.stop_gradient = False
            self.assertRaises(ValueError, paddle.tensor.expand_as, x3, x2)

# Test python API
class TestExpandAsV2API(unittest.TestCase):
    def test_api(self):
        input1 = np.random.random([12, 14]).astype("float32")
        input2 = np.random.random([2, 12, 14]).astype("float32")
        x = fluid.layers.data(
            name='x', shape=[12, 14], append_batch_size=False, dtype="float32"
        )

        y = fluid.layers.data(
            name='target_tensor',
            shape=[2, 12, 14],
            append_batch_size=False,
            dtype="float32",
        )

        out_1 = paddle.expand_as(x, y=y)

        exe = fluid.Executor(place=fluid.CPUPlace())
        res_1 = exe.run(
            fluid.default_main_program(),
            feed={"x": input1, "target_tensor": input2},
            fetch_list=[out_1],
        )
        assert np.array_equal(res_1[0], np.tile(input1, (2, 1, 1)))

if __name__ == "__main__":
    paddle.enable_static()
    unittest.main()


text:
#ifndef QUICK_COLOR_PICKER_H_
#define QUICK_COLOR_PICKER_H_

#include <QWidget>

#include <Core/Math/Vector.h>

class QGridLayout;
class QVBoxLayout;
class QGroupBox;
class QLabel;
class QPushButton;

namespace QtToolbox
{

class HueSaturationWidget;
class GradientWidget;

class LM_API_QTB QuickColorPicker : public QWidget
{
    Q_OBJECT
public:
    QuickColorPicker(   QWidget *parent = 0,
                        const QString & name = "",
                        const QColor & color = Qt::white,
                        bool showAlpha = true);
    virtual ~QuickColorPicker();

    void setupUi();
    void setColor(const QColor & color);

    void getColorLinear(float & r, float & g, float & b, float & a);
    void setColorLinear(float r, float g, float b, float a);
    void getColorLinear(Core::Vector4f& c) const;
    void setColorLinear(const Core::Vector4f& c);

    void getColorSRGB(float & r, float & g, float & b, float & a);
    void setColorSRGB(float r, float g, float b, float a);
    void getColorSRGB(Core::Vector4f& c) const;
    void setColorSRGB(const Core::Vector4f& c);

private Q_SLOTS:
    void valueChanged(float value);
    void alphaChanged(float value);
    void hueSatChanged(float hue, float sat);
    void openQColorDialog();
    void widgetHolding();
    void widgetReleasing();

Q_SIGNALS:
    void colorUpdated(float r, float g, float b, float a);
    void signalWidgetHeld();
    void signalWidgetReleased();

private:
    void setTextFromColor();

protected:
    QString            _name;

    QLabel              *   _r;
    QLabel              *   _g;
    QLabel              *   _b;
    QLabel              *   _a;
    QPushButton         *   _preview;
    HueSaturationWidget *   _hueSaturation;
    GradientWidget      *   _value;
    GradientWidget      *   _alpha;
    QGridLayout         *   _gridLayout;
    QGroupBox           *   _groupBox;
    QVBoxLayout         *   _layout;
    QColor                  _color;

    long            _width;
    long            _height;
    bool            _showAlpha;
};

}//namespace QtToolbox

#endif/*QUICK_COLOR_PICKER_H_*/


text:
<?php

declare(strict_types=1);

namespace Novactive\Tests;

use Novactive\Collection\Factory;

class ShiftCollectionTest extends UnitTestCase
{
    public function testShiftInCollection(): void
    {
        $coll        = Factory::create($this->fixtures['names']);
        $currentSize = $coll->count();
        $pulled      = $coll->shift();
        $this->assertEquals('Chelsea', $pulled);
        $this->assertEquals($currentSize - 1, $coll->count());

        $pulled = $coll->shift();

        $this->assertEquals('Adella', $pulled);
        $this->assertEquals($currentSize - 2, $coll->count());
    }
}


text:
package com.squareup.spoon.html;

import com.squareup.spoon.DeviceDetails;
import com.squareup.spoon.DeviceResult;
import com.squareup.spoon.DeviceTest;
import com.squareup.spoon.DeviceTestResult;
import com.squareup.spoon.SpoonSummary;
import java.io.File;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

import static com.squareup.spoon.DeviceTestResult.Status;
import static java.util.stream.Collectors.toList;

/** Model for representing a {@code test.html} page. */
final class HtmlTest {
  public static HtmlTest from(DeviceTest test, SpoonSummary summary, File output) {
    int deviceCount = 0;
    int testsPassed = 0;
    int duration = 0;
    List<TestResult> devices = new ArrayList<>();
    for (Map.Entry<String, DeviceResult> entry : summary.getResults().entrySet()) {
      DeviceResult deviceResult = entry.getValue();
      DeviceTestResult testResult = deviceResult.getTestResults().get(test);
      if (testResult != null) {
        deviceCount += 1;
        if (testResult.getStatus() == Status.PASS) {
          testsPassed += 1;
          duration += testResult.getDuration();
        }
        String serial = entry.getKey();
        DeviceDetails details = deviceResult.getDeviceDetails();
        String name = (details != null) ? details.getName() : serial;
        devices.add(TestResult.from(serial, name, testResult, output));
      }
    }

    int testsFailed = deviceCount - testsPassed;
    String totalDevices = deviceCount + " device" + (deviceCount != 1 ? "s" : "");
    String title = test.getMethodName();

    StringBuilder subtitle = new StringBuilder();
    subtitle.append("Ran on ")
        .append(totalDevices)
        .append(" with ")
        .append(testsPassed)
        .append(" passing and ")
        .append(testsFailed)
        .append(" failing");
    if (testsPassed > 0) {
      subtitle.append(" in an average of ")
        .append(HtmlUtils.humanReadableDuration(duration / testsPassed));
    }

    String className = test.getClassName();
    String methodName = test.getMethodName();

    return new HtmlTest(title, subtitle.toString(), className, methodName, devices);
  }

  public final String title;
  public final String subtitle;
  public final String className;
  public final String methodName;
  public final List<TestResult> devices;

  HtmlTest(String title, String subtitle, String className, String methodName,
      List<TestResult> devices) {
    this.title = title;
    this.subtitle = subtitle;
    this.className = className;
    this.methodName = methodName;
    this.devices = devices;
  }

  static final class TestResult implements Comparable<TestResult> {
    static TestResult from(String serial, String name, DeviceTestResult result, File output) {
      String status = HtmlUtils.getStatusCssClass(result);

      List<HtmlUtils.Screenshot> screenshots = result.getScreenshots()
          .stream()
          .map(screenshot -> HtmlUtils.getScreenshot(screenshot, output))
          .collect(toList());
      String animatedGif = HtmlUtils.createRelativeUri(result.getAnimatedGif(), output);
      HtmlUtils.ExceptionInfo exception = HtmlUtils.processStackTrace(result.getException());

      return new TestResult(name, serial, status, screenshots, animatedGif, exception);
    }

    public final String name;
    public final String serial;
    public final String status;
    public final boolean hasScreenshots;
    public final List<HtmlUtils.Screenshot> screenshots;
    public final String animatedGif;
    public final HtmlUtils.ExceptionInfo exception;

    TestResult(String name, String serial, String status, List<HtmlUtils.Screenshot> screenshots,
        String animatedGif, HtmlUtils.ExceptionInfo exception) {
      this.name = name;
      this.serial = serial;
      this.status = status;
      this.hasScreenshots = !screenshots.isEmpty();
      this.screenshots = screenshots;
      this.animatedGif = animatedGif;
      this.exception = exception;
    }

    @Override public int compareTo(TestResult other) {
      return name.compareTo(other.name);
    }
  }
}