text:
using System;
using System.ComponentModel.DataAnnotations;

namespace GenderPayGap.WebUI.Models.Scope
{

    [Serializable]
    public class EnterCodesViewModel
    {
        [Required(AllowEmptyStrings = false, ErrorMessage = "You must enter an employer reference")]
        [Display(Name = "Enter your employer reference")]
        public string EmployerReference { get; set; }

        [Required(AllowEmptyStrings = false, ErrorMessage = "You must enter a security code")]
        [Display(Name = "Enter your security code")]
        public string SecurityToken { get; set; }
    }

}


text:
module Wardrobe
  module Plugins
    module EditCallback
      extend Wardrobe::Plugin

      Wardrobe.register_setter(
        name: :edited,
        before: [:setter],
        use_if: ->(atr) { atr.options[:edited] },
        setter: lambda do |value, atr, instance, options|
          if value != instance.send(atr.name)
            atr.options[:edited].call(instance.send(atr.name), value, atr, instance)
          end
        end
      )

      option :edited, Proc, setter: :edited
    end
  end
  register_plugin(:edit_callback, Plugins::EditCallback)
end

redpajama_set_name: RedPajamaGithub


text:
PyExecJS (EOL)
==============

End of life
===========

This library is no longer maintananced. Bugs are not be fixed (even if
they are trivial or essential).

We suggest to use other library or to make a fork.

--------------

Run JavaScript code from Python.

PyExecJS is a porting of ExecJS from Ruby. PyExecJS **automatically**
picks the best runtime available to evaluate your JavaScript program.

A short example:

::

    >>> import execjs
    >>> execjs.eval("'red yellow blue'.split(' ')")
    ['red', 'yellow', 'blue']
    >>> ctx = execjs.compile("""
    ...     function add(x, y) {
    ...         return x + y;
    ...     }
    ... """)
    >>> ctx.call("add", 1, 2)
    3

Supported runtimes
==================

First-class support (runtime class is provided and tested)
----------------------------------------------------------

-  `PyV8 <http://code.google.com/p/pyv8/>`__ - A python wrapper for
   Google V8 engine,
-  `Node.js <http://nodejs.org/>`__
-  `PhantomJS <http://phantomjs.org/>`__
-  `Nashorn <http://docs.oracle.com/javase/8/docs/technotes/guides/scripting/nashorn/intro.html#sthref16>`__
   - Included with Oracle Java 8

Second-class support (runtime class is privided but not tested)
---------------------------------------------------------------

-  Apple JavaScriptCore - Included with Mac OS X
-  `Microsoft Windows Script
   Host <http://msdn.microsoft.com/en-us/library/9bbdkx3k.aspx>`__
   (JScript)
-  `SlimerJS <http://slimerjs.org/>`__
-  `Mozilla SpiderMonkey <http://www.mozilla.org/js/spidermonkey/>`__

Installation
============

::

    $ pip install PyExecJS

or

::

    $ easy_install PyExecJS

Details
=======

If ``EXECJS_RUNTIME`` environment variable is specified, PyExecJS pick
the JavaScript runtime as a default:

::

    >>> execjs.get().name # this value is depends on your environment.
    >>> os.environ["EXECJS_RUNTIME"] = "Node"
    >>> execjs.get().name
    'Node.js (V8)'

You can choose JavaScript runtime by ``execjs.get()``:

::

    >>> default = execjs.get() # the automatically picked runtime
    >>> default.eval("1 + 2")
    3
    >>> import execjs.runtime_names
    >>> jscript = execjs.get(execjs.runtime_names.JScript)
    >>> jscript.eval("1 + 2")
    3
    >>> import execjs.runtime_names
    >>> node = execjs.get(execjs.runtime_names.Node)
    >>> node.eval("1 + 2")
    3

The pros of PyExecJS is that you do not need take care of JavaScript
environment. Especially, it works in Windows environment without
installing extra libraries.

One of cons of PyExecJS is performance. PyExecJS communicate JavaScript
runtime by text and it is slow. The other cons is that it does not fully
support runtime specific features.

`PyV8 <https://code.google.com/p/pyv8/>`__ might be better choice for
some use case.

License
=======

Copyright (c) 2016 Omoto Kenji. Copyright (c) 2011 Sam Stephenson and
Josh Peek. (As a author of ExecJS)

Released under the MIT license. See ``LICENSE`` for details.

Changelog
=========

1.5.0
-----

-  Eased version requirement for six.

1.4.1
-----

-  Fixed arguments of module-level functions.
-  Fixed bug of execution with pipe.
-  Fixed wrong excption is raised.

1.4.0
-----

-  Fixed required libraries.
-  Fixed order of output of ``--print-available-runtimes``.
-  Execute some JavaScript runtime with pipe/stdin (without temporary
   file).

1.3.1
-----

-  Fixed ``--print-available-runtimes`` fails in Python 2.7.

1.3.0
-----

-  Added ``cwd`` argument.

1.2.0
-----

-  Supported Python 3.5
-  Supported Nashorn(Java 8 JavaScript engine) as runtime
-  Dropped support for Python 2.6 and 3.2

1.1.0
-----

-  Supported Python 3.4
-  Supported SlimerJS as runtime
-  Supported PhantomJS as runtime
-  Fixed JScript runtime on Windows 8

1.0.5
-----

-  Supported Python 3.3
-  Fixed file handle leaking
-  Fixed issue with passenger-nginx-4.0

1.0.4
-----

-  Removed "import execjs" (it prevent execution of setup.py by Python
   2.6)

1.0.3
-----

-  Javascript sources were embeded in **init**.py. 'which' command were
   reimplemented by pure python.

1.0.2
-----

-  Python 2.6.x was supported.

1.0.1
-----

-  Forgotten shell=True was added to Popen.

1.0.0
-----

-  First release.


text:
<?php

namespace AnimeDb\Bundle\PaginationBundle\Service;

use Doctrine\ORM\QueryBuilder;

class Builder
{
    /**
     * The number of pages displayed in the navigation.
     *
     * @var int
     */
    protected $max_navigate = Configuration::DEFAULT_LIST_LENGTH;

    /**
     * @param int $max_navigate
     */
    public function __construct($max_navigate)
    {
        $this->max_navigate = $max_navigate;
    }

    /**
     * @param int $total_pages
     * @param int $current_page
     *
     * @return Configuration
     */
    public function paginate($total_pages = 0, $current_page = 1)
    {
        return (new Configuration($total_pages, $current_page))
            ->setMaxNavigate($this->max_navigate);
    }

    /**
     * @param QueryBuilder $query
     * @param int $per_page
     * @param int $current_page
     *
     * @return Configuration
     */
    public function paginateQuery(QueryBuilder $query, $per_page, $current_page = 1)
    {
        $counter = clone $query;
        $total = $counter
            ->select(sprintf('COUNT(%s)', current($query->getRootAliases())))
            ->getQuery()
            ->getSingleScalarResult();

        $query
            ->setFirstResult(($current_page - 1) * $per_page)
            ->setMaxResults($per_page);

        return (new Configuration(ceil($total / $per_page), $current_page))
            ->setMaxNavigate($this->max_navigate);
    }
}


text:
<?php
namespace CodingPride\Tests\Condition;

class ChangeOldFileConditionTest extends \PHPUnit_Framework_TestCase
{

	public function testConditionIsMetWhenLastCommitWasFarIntoThePast()
	{
		$date 		= new \DateTime( '03/08/2012' );
		$far_date 	= new \DateTime( '03/08/1984' );

		$file = $this->getMock( '\CodingPride\Document\File', array( 'getPath' ) );
		$file->expects( $this->once() )->method( 'getPath' )->will( $this->returnValue( 'file_path.php' ) );
		$files = array( $file );

		$commit = $this->getMock( '\CodingPride\Document\Commit', array( 'getFiles', 'getDate' ) );
		$commit->expects( $this->once() )->method( 'getFiles' )->will( $this->returnValue( $files ) );
		$commit->expects( $this->once() )->method( 'getDate' )->will( $this->returnValue( $date ) );

		$commit_to_check_against = $this->getMock( '\CodingPride\Document\Commit', array( 'getFiles', 'getDate' ) );
		$commit_to_check_against->expects( $this->once() )->method( 'getDate' )->will( $this->returnValue( $far_date ) );

		$cursor = $this->getMock( 'Doctrine\MongoDB\Cursor', array( 'hasNext', 'getNext' ), array(), '', false );
		$cursor->expects( $this->once() )->method( 'hasNext' )->will( $this->returnValue( true ) );
		$cursor->expects( $this->once() )->method( 'getNext' )->will( $this->returnValue( $commit_to_check_against ) );

		$commit_repository 	= $this->getMock( '\CodingPride\Document\CommitRepository', array( 'findBy' ), array(), '', false );
		$commit_repository->expects( $this->once() )->method( 'findBy' )->will( $this->returnValue( $cursor ) );

		$dm = $this->getMock( '\CodingPride\Tests\DocumentManager', array( 'getRepository' ), array(), '', false );
		$dm->expects( $this->once() )->method( 'getRepository' )->will( $this->returnValue( $commit_repository ) );

		$condition 		= new \CodingPride\Condition\ChangeOldFileCondition( $dm );

		$this->assertTrue( $condition->check( $commit ), 'The condition has to be met when last commit in that file was long ago.' );
	}

	public function testConditionIsNotMetWhenLastCommitWasCloseInTime()
	{
		$date 		= new \DateTime( '1984-08-04' );
		$far_date 	= new \DateTime( '1984-08-03' );

		$file = $this->getMock( '\CodingPride\Document\File', array( 'getPath' ) );
		$file->expects( $this->once() )->method( 'getPath' )->will( $this->returnValue( 'file_path.php' ) );
		$files = array( $file );

		$commit = $this->getMock( '\CodingPride\Document\Commit', array( 'getFiles', 'getDate' ) );
		$commit->expects( $this->once() )->method( 'getFiles' )->will( $this->returnValue( $files ) );
		$commit->expects( $this->once() )->method( 'getDate' )->will( $this->returnValue( $date ) );

		$commit_to_check_against = $this->getMock( '\CodingPride\Document\Commit', array( 'getFiles', 'getDate' ) );
		$commit_to_check_against->expects( $this->once() )->method( 'getDate' )->will( $this->returnValue( $far_date ) );

		$cursor = $this->getMock( 'Doctrine\MongoDB\Cursor', array( 'hasNext', 'getNext' ), array(), '', false );
		$cursor->expects( $this->once() )->method( 'hasNext' )->will( $this->returnValue( true ) );
		$cursor->expects( $this->once() )->method( 'getNext' )->will( $this->returnValue( $commit_to_check_against ) );

		$commit_repository 	= $this->getMock( '\CodingPride\Document\CommitRepository', array( 'findBy' ), array(), '', false );
		$commit_repository->expects( $this->once() )->method( 'findBy' )->will( $this->returnValue( $cursor ) );

		$dm = $this->getMock( '\CodingPride\Tests\DocumentManager', array( 'getRepository' ), array(), '', false );
		$dm->expects( $this->once() )->method( 'getRepository' )->will( $this->returnValue( $commit_repository ) );

		$condition 		= new \CodingPride\Condition\ChangeOldFileCondition( $dm );

		$this->assertFalse( $condition->check( $commit ), 'If the last commit in the same file was a few days ago, the condition must not be met' );
	}
}


text:
<?php

class Google_Service_Sheets_InsertRangeRequest extends Google_Model
{
  protected $rangeType = 'Google_Service_Sheets_GridRange';
  protected $rangeDataType = '';
  public $shiftDimension;

  public function setRange(Google_Service_Sheets_GridRange $range)
  {
    $this->range = $range;
  }
  public function getRange()
  {
    return $this->range;
  }
  public function setShiftDimension($shiftDimension)
  {
    $this->shiftDimension = $shiftDimension;
  }
  public function getShiftDimension()
  {
    return $this->shiftDimension;
  }
}


text:
import {Actions, Effect} from '@ngrx/effects';
import 'rxjs/add/operator/switchMap';
import 'rxjs/add/operator/withLatestFrom';
import * as RecipeActions from '../store/recipe.actions';
import {HttpClient, HttpRequest} from '@angular/common/http';
import {Recipe} from '../recipe.model';
import {Injectable} from '@angular/core';
import {Store} from '@ngrx/store';
import * as fromRecipe from '../store/recipe.reducers';

@Injectable()
export class RecipeEffects {
  @Effect()
  recipeFetch = this.actions$
    .ofType(RecipeActions.FETCH_RECIPES)
    .switchMap((action: RecipeActions.FetchRecipe) => {
      return this.httpClient.get<Recipe[]>('https://ng-recipe-book-3a818.firebaseio.com/recipes.json', {
        observe: 'body',
        responseType: 'json'
      })
    })
    .map(
      (recipes) => {
        for (const recipe of recipes) {
          if (!recipe['ingredients']) {
            recipe['ingredients'] = [];
          }
        }
        return {
          type: RecipeActions.SET_RECIPES,
          payload: recipes
        };
      }
    );

  @Effect({dispatch: false})
  recipeStore = this.actions$
    .ofType(RecipeActions.STORE_RECIPES)
    .withLatestFrom(this.store.select('recipes'))
    .switchMap(([action, state]) => {
      const req = new HttpRequest(
        'PUT',
        'https://ng-recipe-book-3a818.firebaseio.com/recipes.json',
        state.recipes,
        {
          reportProgress: true
        }
      )
      return this.httpClient.request(req);
    });

  constructor(private actions$: Actions, private httpClient: HttpClient, private store: Store<fromRecipe.FeatureState>) {}
}


text:
// Dependencies:
//
//    - jquery.event.drag.js
//    - jquery.event.livehack.js
//    - jquery.lang.vector.js

(function( $ ) {
	//modify live
	//steal the live handler ....
	var bind = function( object, method ) {
			var args = Array.prototype.slice.call(arguments, 2);
			return function() {
				var args2 = [this].concat(args, $.makeArray(arguments));
				return method.apply(object, args2);
			};
		},
		event = $.event,
		// function to clear the window selection if there is one
		clearSelection = window.getSelection ? function(){
			window.getSelection().removeAllRanges()
		} : function(){},

		supportTouch = "ontouchend" in document,
		// Use touch events or map it to mouse events
		startEvent = supportTouch ? "touchstart" : "mousedown",
		stopEvent = supportTouch ? "touchend" : "mouseup",
		moveEvent = supportTouch ? "touchmove" : "mousemove",
		// On touchmove events the default (scrolling) event has to be prevented
		preventTouchScroll = function(ev) {
			ev.preventDefault();
		};

	/**
	 * @class jQuery.Drag
	 * @parent jQuery.event.drag
	 * @plugin jquery/event/drag
	 * @download  http://jmvcsite.heroku.com/pluginify?plugins[]=jquery/event/drag/drag.js
	 * @test jquery/event/drag/qunit.html
	 *
	 * The `$.Drag` constructor is never called directly but an instance of `$.Drag` is passed as the second argument
	 * to the `dragdown`, `draginit`, `dragmove`, `dragend`, `dragover` and `dragout` event handlers:
	 *
	 *      $('#dragger').on('draginit', function(el, drag) {
	 *          // drag -> $.Drag
	 *      });
	 */
	$.Drag = function() {};

	/**
	 * @Static
	 */
	$.extend($.Drag, {
		lowerName: "drag",
		current: null,
		distance: 0,
		/**
		 * Called when someone mouses down on a draggable object.
		 * Gathers all callback functions and creates a new Draggable.
		 * @hide
		 */
		mousedown: function( ev, element ) {
			var isLeftButton = ev.button === 0 || ev.button == 1,
				doEvent = isLeftButton || supportTouch;

			if (!doEvent || this.current ) {
				return;
			}

			//create Drag
			var drag = new $.Drag(),
				delegate = ev.delegateTarget || element,
				selector = ev.handleObj.selector,
				self = this;
			this.current = drag;

			drag.setup({
				element: element,
				delegate: ev.delegateTarget || element,
				selector: ev.handleObj.selector,
				moved: false,
				_distance: this.distance,
				callbacks: {
					dragdown: event.find(delegate, ["dragdown"], selector),
					draginit: event.find(delegate, ["draginit"], selector),
					dragover: event.find(delegate, ["dragover"], selector),
					dragmove: event.find(delegate, ["dragmove"], selector),
					dragout: event.find(delegate, ["dragout"], selector),
					dragend: event.find(delegate, ["dragend"], selector)
				},
				destroyed: function() {
					self.current = null;
				}
			}, ev);
		}
	});

	/**
	 * @Prototype
	 */
	$.extend($.Drag.prototype, {
		setup: function( options, ev ) {
			$.extend(this, options);

			this.element = $(this.element);
			this.event = ev;
			this.moved = false;
			this.allowOtherDrags = false;
			var mousemove = bind(this, this.mousemove),
				mouseup = bind(this, this.mouseup);
			this._mousemove = mousemove;
			this._mouseup = mouseup;
			this._distance = options.distance ? options.distance : 0;

			//where the mouse is located
			this.mouseStartPosition = ev.vector();

			$(document).bind(moveEvent, mousemove);
			$(document).bind(stopEvent, mouseup);
			if(supportTouch) {
				// On touch devices we want to disable scrolling
				$(document).bind(moveEvent, preventTouchScroll);
			}

			if (!this.callEvents('down', this.element, ev) ) {
			    this.noSelection(this.delegate);
				//this is for firefox
				clearSelection();
			}
		},
		/**
		 * @attribute element
		 * A reference to the element that is being dragged. For example:
		 *
		 *      $('.draggable').on('draginit', function(ev, drag) {
		 *          drag.element.html('I am the drag element');
		 *      });
		 */

		/**
		 * Unbinds listeners and allows other drags ...
		 * @hide
		 */
		destroy: function() {
			// Unbind the mouse handlers attached for dragging
			$(document).unbind(moveEvent, this._mousemove);
			$(document).unbind(stopEvent, this._mouseup);
			if(supportTouch) {
				// Enable scrolling again for touch devices when the drag is done
				$(document).unbind(moveEvent, preventTouchScroll);
			}

			if (!this.moved ) {
				this.event = this.element = null;
			}

			if(!supportTouch) {
                this.selection(this.delegate);
			}
			this.destroyed();
		},
		mousemove: function( docEl, ev ) {
			if (!this.moved ) {
				var dist = Math.sqrt( Math.pow( ev.pageX - this.event.pageX, 2 ) + Math.pow( ev.pageY - this.event.pageY, 2 ));
				// Don't initialize the drag if it hasn't been moved the minimum distance
				if(dist < this._distance){
					return false;
				}
				// Otherwise call init and indicate that the drag has moved
				this.init(this.element, ev);
				this.moved = true;
			}

			var pointer = ev.vector();
			if ( this._start_position && this._start_position.equals(pointer) ) {
				return;
			}
			this.draw(pointer, ev);
		},

		mouseup: function( docEl, event ) {
			//if there is a current, we should call its dragstop
			if ( this.moved ) {
				this.end(event);
			}
			this.destroy();
		},

        /**
         * The `drag.noSelection(element)` method turns off text selection during a drag event.
         * This method is called by default unless a event is listening to the 'dragdown' event.
         *
         * ## Example
         *
         *      $('div.drag').bind('dragdown', function(elm,event,drag){
         *          drag.noSelection();
         *      });
         *
         * @param [elm] an element to prevent selection on.  Defaults to the dragable element.
         */
		noSelection: function(elm) {
            elm = elm || this.delegate
			document.documentElement.onselectstart = function() {
                // Disables selection
				return false;
			};
			document.documentElement.unselectable = "on";
			this.selectionDisabled = (this.selectionDisabled ? this.selectionDisabled.add(elm) : $(elm));
			this.selectionDisabled.css('-moz-user-select', '-moz-none');
		},

        /**
         * @hide
         * `drag.selection()` method turns on text selection that was previously turned off during the drag event.
         * This method is always called.
         *
         * ## Example
         *
         *     $('div.drag').bind('dragdown', function(elm,event,drag){
         *       drag.selection();
         *     });
         */
		selection: function() {
            if(this.selectionDisabled) {
                document.documentElement.onselectstart = function() {};
                document.documentElement.unselectable = "off";
                this.selectionDisabled.css('-moz-user-select', '');
            }
		},

		init: function( element, event ) {
			element = $(element);
			//the element that has been clicked on
			var startElement = (this.movingElement = (this.element = $(element)));
			//if a mousemove has come after the click
			//if the drag has been cancelled
			this._cancelled = false;
			this.event = event;

			/**
			 * @attribute mouseElementPosition
			 * The position of start of the cursor on the element
			 */
			this.mouseElementPosition = this.mouseStartPosition.minus(this.element.offsetv()); //where the mouse is on the Element
			this.callEvents('init', element, event);

			// Check what they have set and respond accordingly if they canceled
			if ( this._cancelled === true ) {
				return;
			}
			// if they set something else as the element
			this.startPosition = startElement != this.movingElement ? this.movingElement.offsetv() : this.currentDelta();

			this.makePositioned(this.movingElement);
			// Adjust the drag elements z-index to a high value
			this.oldZIndex = this.movingElement.css('zIndex');
			this.movingElement.css('zIndex', 1000);
			if (!this._only && this.constructor.responder ) {
				// calls $.Drop.prototype.compile if there is a drop element
				this.constructor.responder.compile(event, this);
			}
		},
		makePositioned: function( that ) {
			var style, pos = that.css('position');

			// Position properly, set top and left to 0px for Opera
			if (!pos || pos == 'static' ) {
				style = {
					position: 'relative'
				};

				if ( window.opera ) {
					style.top = '0px';
					style.left = '0px';
				}
				that.css(style);
			}
		},
		callEvents: function( type, element, event, drop ) {
			var i, cbs = this.callbacks[this.constructor.lowerName + type];
			for ( i = 0; i < cbs.length; i++ ) {
				cbs[i].call(element, event, this, drop);
			}
			return cbs.length;
		},
		/**
		 * Returns the position of the movingElement by taking its top and left.
		 * @hide
		 * @return {$.Vector}
		 */
		currentDelta: function() {
			return new $.Vector(parseInt(this.movingElement.css('left'), 10) || 0, parseInt(this.movingElement.css('top'), 10) || 0);
		},
		//draws the position of the dragmove object
		draw: function( pointer, event ) {
			// only drag if we haven't been cancelled;
			if ( this._cancelled ) {
				return;
			}
			clearSelection();
			/**
			 * @attribute location
			 * `drag.location` is a [jQuery.Vector] specifying where the element should be in the page.  This
			 * takes into account the start position of the cursor on the element.
			 *
			 * If the drag is going to be moved to an unacceptable location, you can call preventDefault in
			 * dragmove to prevent it from being moved there.
			 *
			 *     $('.mover').bind("dragmove", function(ev, drag){
			 *       if(drag.location.top() < 100){
			 *         ev.preventDefault()
			 *       }
			 *     });
			 *
			 * You can also set the location to where it should be on the page.
			 *
			 */
				// the offset between the mouse pointer and the representative that the user asked for
			this.location = pointer.minus(this.mouseElementPosition);

			// call move events
			this.move(event);
			if ( this._cancelled ) {
				return;
			}
			if (!event.isDefaultPrevented() ) {
				this.position(this.location);
			}

			// fill in
			if (!this._only && this.constructor.responder ) {
				this.constructor.responder.show(pointer, this, event);
			}
		},
		/**
		 * `drag.position( newOffsetVector )` sets the position of the movingElement.  This is overwritten by
		 * the [$.Drag::scrolls], [$.Drag::limit] and [$.Drag::step] plugins
		 * to make sure the moving element scrolls some element
		 * or stays within some boundary.  This function is exposed and documented so you could do the same.
		 *
		 * The following approximates how step does it:
		 *
		 *     var oldPosition = $.Drag.prototype.position;
		 *     $.Drag.prototype.position = function( offsetPositionv ) {
		 *       if(this._step){
		 *         // change offsetPositionv to be on the step value
		 *       }
		 *
		 *       oldPosition.call(this, offsetPosition)
		 *     }
		 *
		 * @param {jQuery.Vector} newOffsetv the new [$.Drag::location] of the element.
		 */
		position: function( newOffsetv ) { //should draw it on the page
			var style, dragged_element_css_offset = this.currentDelta(),
				//  the drag element's current left + top css attributes
				// the vector between the movingElement's page and css positions
				// this can be thought of as the original offset
				dragged_element_position_vector =   this.movingElement.offsetv().minus(dragged_element_css_offset);
			this.required_css_position = newOffsetv.minus(dragged_element_position_vector);

			this.offsetv = newOffsetv;
			style = this.movingElement[0].style;
			if (!this._cancelled && !this._horizontal ) {
				style.top = this.required_css_position.top() + "px";
			}
			if (!this._cancelled && !this._vertical ) {
				style.left = this.required_css_position.left() + "px";
			}
		},
		move: function( event ) {
			this.callEvents('move', this.element, event);
		},
		over: function( event, drop ) {
			this.callEvents('over', this.element, event, drop);
		},
		out: function( event, drop ) {
			this.callEvents('out', this.element, event, drop);
		},
		/**
		 * Called on drag up
		 * @hide
		 * @param {Event} event a mouseup event signalling drag/drop has completed
		 */
		end: function( event ) {
			// If canceled do nothing
			if ( this._cancelled ) {
				return;
			}
			// notify the responder - usually a $.Drop instance
			if (!this._only && this.constructor.responder ) {
				this.constructor.responder.end(event, this);
			}

			this.callEvents('end', this.element, event);

			if ( this._revert ) {
				var self = this;
				// animate moving back to original position
				this.movingElement.animate({
					top: this.startPosition.top() + "px",
					left: this.startPosition.left() + "px"
				}, function() {
					self.cleanup.apply(self, arguments);
				});
			}
			else {
				this.cleanup();
			}
			this.event = null;
		},
		/**
		 * Cleans up drag element after drag drop.
		 * @hide
		 */
		cleanup: function() {
			this.movingElement.css({
				zIndex: this.oldZIndex
			});
			if ( this.movingElement[0] !== this.element[0] &&
				!this.movingElement.has(this.element[0]).length &&
				!this.element.has(this.movingElement[0]).length ) {
				this.movingElement.css({
					display: 'none'
				});
			}
			if ( this._removeMovingElement ) {
				// Remove the element when using drag.ghost()
				this.movingElement.remove();
			}

			this.movingElement = this.element = this.event = null;
		},
		/**
		 * `drag.cancel()` stops a drag motion from from running.  This also stops any other events from firing, meaning
		 * that "dragend" will not be called.
		 *
		 *     $("#todos").on(".handle", "draginit", function( ev, drag ) {
		 *       if(drag.movingElement.hasClass("evil")){
		 *         drag.cancel();
		 *       }
		 *     })
		 *
		 */
		cancel: function() {
			this._cancelled = true;
			if (!this._only && this.constructor.responder ) {
				// clear the drops
				this.constructor.responder.clear(this.event.vector(), this, this.event);
			}
			this.destroy();

		},
		/**
		 * `drag.ghost( [parent] )` clones the element and uses it as the
		 * moving element, leaving the original dragged element in place.  The `parent` option can
		 * be used to specify where the ghost element should be temporarily added into the
		 * DOM.  This method should be called in "draginit".
		 *
		 *     $("#todos").on(".handle", "draginit", function( ev, drag ) {
		 *       drag.ghost();
		 *     })
		 *
		 * @param {HTMLElement} [parent] the parent element of the newly created ghost element. If not provided the
		 * ghost element is added after the moving element.
		 * @return {jQuery.fn} the ghost element to do whatever you want with it.
		 */
		ghost: function( parent ) {
			// create a ghost by cloning the source element and attach the clone to the dom after the source element
			var ghost = this.movingElement.clone().css('position', 'absolute');
			if( parent ) {
				$(parent).append(ghost);
			} else {
				$(this.movingElement).after(ghost)
			}
			ghost.width(this.movingElement.width()).height(this.movingElement.height());
			// put the ghost in the right location ...
			ghost.offset(this.movingElement.offset())

			// store the original element and make the ghost the dragged element
			this.movingElement = ghost;
			this.noSelection(ghost)
			this._removeMovingElement = true;
			return ghost;
		},
		/**
		 * `drag.representative( element, [offsetX], [offsetY])` tells the drag motion to use
		 * a different element than the one that began the drag motion.
		 *
		 * For example, instead of
		 * dragging an drag-icon of a todo element, you want to move some other representation of
		 * the todo element (or elements).  To do this you might:
		 *
		 *     $("#todos").on(".handle", "draginit", function( ev, drag ) {
		 *       // create what we'll drag
		 *       var rep = $('<div/>').text("todos")
		 *         .appendTo(document.body)
		 *       // indicate we want our mouse on the top-right of it
		 *       drag.representative(rep, rep.width(), 0);
		 *     })
		 *
		 * @param {HTMLElement} element the element you want to actually drag.  This should be
		 * already in the DOM.
		 * @param {Number} offsetX the x position where you want your mouse on the representative element (defaults to 0)
		 * @param {Number} offsetY the y position where you want your mouse on the representative element (defaults to 0)
		 * @return {drag} returns the drag object for chaining.
		 */
		representative: function( element, offsetX, offsetY ) {
			this._offsetX = offsetX || 0;
			this._offsetY = offsetY || 0;

			var p = this.mouseStartPosition;
			// Just set the representative as the drag element
			this.movingElement = $(element);
			this.movingElement.css({
				top: (p.y() - this._offsetY) + "px",
				left: (p.x() - this._offsetX) + "px",
				display: 'block',
				position: 'absolute'
			}).show();
			this.noSelection(this.movingElement)
			this.mouseElementPosition = new $.Vector(this._offsetX, this._offsetY);
			return this;
		},
		/**
		 * `drag.revert([val])` makes the [$.Drag::representative representative] element revert back to it
		 * original position after the drag motion has completed.  The revert is done with an animation.
		 *
		 *     $("#todos").on(".handle","dragend",function( ev, drag ) {
		 *       drag.revert();
		 *     })
		 *
		 * @param {Boolean} [val] optional, set to false if you don't want to revert.
		 * @return {drag} the drag object for chaining
		 */
		revert: function( val ) {
			this._revert = val === undefined ? true : val;
			return this;
		},
		/**
		 * `drag.vertical()` isolates the drag to vertical movement.  For example:
		 *
		 *     $("#images").on(".thumbnail","draginit", function(ev, drag){
		 *       drag.vertical();
		 *     });
		 *
		 * Call `vertical()` in "draginit" or "dragdown".
		 *
		 * @return {drag} the drag object for chaining.
		 */
		vertical: function() {
			this._vertical = true;
			return this;
		},
		/**
		 * `drag.horizontal()` isolates the drag to horizontal movement.  For example:
		 *
		 *     $("#images").on(".thumbnail","draginit", function(ev, drag){
		 *       drag.horizontal();
		 *     });
		 *
		 * Call `horizontal()` in "draginit" or "dragdown".
		 *
		 * @return {drag} the drag object for chaining.
		 */
		horizontal: function() {
			this._horizontal = true;
			return this;
		},
		/**
		 * `drag.only([only])` indicates if you __only__ want a drag motion and the drag should
		 * not notify drops.  The default value is `false`.  Call it with no arguments or pass it true
		 * to prevent drop events.
		 *
		 *     $("#images").on(".thumbnail","dragdown", function(ev, drag){
		 * 	     drag.only();
		 *     });
		 *
		 * @param {Boolean} [only] true if you want to prevent drops, false if otherwise.
		 * @return {Boolean} the current value of only.
		 */
		only: function( only ) {
			return (this._only = (only === undefined ? true : only));
		},

		/**
		 * `distance([val])` sets or reads the distance the mouse must move before a drag motion is started.  This should be set in
		 * "dragdown" and delays "draginit" being called until the distance is covered.  The distance
		 * is measured in pixels.  The default distance is 0 pixels meaning the drag motion starts on the first
		 * mousemove after a mousedown.
		 *
		 * Set this to make drag motion a little "stickier" to start.
		 *
		 *     $("#images").on(".thumbnail","dragdown", function(ev, drag){
		 *       drag.distance(10);
		 *     });
		 *
		 * @param {Number} [val] The number of pixels the mouse must move before "draginit" is called.
		 * @return {drag|Number} returns the drag instance for chaining if the drag value is being set or the
		 * distance value if the distance is being read.
		 */
		distance: function(val){
			if(val !== undefined){
				this._distance = val;
				return this;
			}else{
				return this._distance
			}
		}
	});
	/**
	 * @add jQuery.event.special
	 */
	event.setupHelper([
	/**
	 * @attribute dragdown
	 * @parent jQuery.event.drag
	 *
	 * `dragdown` is called when a drag movement has started on a mousedown.
	 * The event handler gets an instance of [jQuery.Drag] passed as the second
	 * parameter.  Listening to `dragdown` allows you to customize
	 * the behavior of a drag motion, especially when `draginit` should be called.
	 *
	 *     $(".handles").delegate("dragdown", function(ev, drag){
	 *       // call draginit only when the mouse has moved 20 px
	 *       drag.distance(20);
	 *     })
	 *
	 * Typically, when a drag motion is started, `event.preventDefault` is automatically
	 * called, preventing text selection.  However, if you listen to
	 * `dragdown`, this default behavior is not called. You are responsible for calling it
	 * if you want it (you probably do).
	 *
	 * ### Why might you not want to call `preventDefault`?
	 *
	 * You might want it if you want to allow text selection on element
	 * within the drag element.  Typically these are input elements.
	 *
	 *     $(".handles").delegate("dragdown", function(ev, drag){
	 *       if(ev.target.nodeName === "input"){
	 *         drag.cancel();
	 *       } else {
	 *         ev.preventDefault();
	 *       }
	 *     })
	 */
	'dragdown',
	/**
	 * @attribute draginit
	 * @parent jQuery.event.drag
	 *
	 * `draginit` is triggered when the drag motion starts. Use it to customize the drag behavior
	 * using the [jQuery.Drag] instance passed as the second parameter:
	 *
	 *     $(".draggable").on('draginit', function(ev, drag) {
	 *       // Only allow vertical drags
	 *       drag.vertical();
	 *       // Create a draggable copy of the element
	 *       drag.ghost();
	 *     });
	 */
	'draginit',
	/**
	 * @attribute dragover
	 * @parent jQuery.event.drag
	 *
	 * `dragover` is triggered when a drag is over a [jQuery.event.drop drop element].
	 * The event handler gets an instance of [jQuery.Drag] passed as the second
	 * parameter and an instance of [jQuery.Drop] passed as the third argument:
	 *
	 *      $('.draggable').on('dragover', function(ev, drag, drop) {
	 *          // Add the drop-here class indicating that the drag
	 *          // can be dropped here
	 *          drag.element.addClass('drop-here');
	 *      });
	 */
	'dragover',
	/**
	 * @attribute dragmove
	 * @parent jQuery.event.drag
	 *
	 * `dragmove` is triggered when the drag element moves (similar to a mousemove).
	 * The event handler gets an instance of [jQuery.Drag] passed as the second
	 * parameter.
	 * Use [jQuery.Drag::location] to determine the current position
	 * as a [jQuery.Vector vector].
	 *
	 * For example, `dragmove` can be used to create a draggable element to resize
	 * a container:
	 *
	 *      $('.resizer').on('dragmove', function(ev, drag) {
	 *          $('#container').width(drag.location.x())
	 *              .height(drag.location.y());
	 *      });
	 */
	'dragmove',
	/**
	 * @attribute dragout
	 * @parent jQuery.event.drag
	 *
	 * `dragout` is called when the drag leaves a drop point.
	 * The event handler gets an instance of [jQuery.Drag] passed as the second
	 * parameter.
	 *
	 *      $('.draggable').on('dragout', function(ev, drag) {
	 *      	 // Remove the drop-here class
	 *      	 // (e.g. crossing the drag element out indicating that it
	 *      	 // can't be dropped here
	 *          drag.element.removeClass('drop-here');
	 *      });
	 */
	'dragout',
	/**
	 * @attribute dragend
	 * @parent jQuery.event.drag
	 *
	 * `dragend` is called when the drag motion is done.
	 * The event handler gets an instance of [jQuery.Drag] passed as the second
	 * parameter.
	 *
	 *     $('.draggable').on('dragend', function(ev, drag)
	 *       // Clean up when the drag motion is done
	 *     });
	 */
	'dragend'], startEvent, function( e ) {
		$.Drag.mousedown.call($.Drag, e, this);
	});
})(jQuery)


text:
<?php

namespace Bolt\Storage\Query\Directive;

use Bolt\Storage\Query\SelectQuery;

/**
 *  Directive to add a limit modifier to the query.
 */
class OffsetDirective
{
    /**
     * @param SelectQuery $query
     * @param $page
     * @param $otherDirectives
     */
    public function __invoke(SelectQuery $query, $page, $otherDirectives)
    {
        $limit = $otherDirectives['limit'] ? $otherDirectives['limit'] : 0;
        $query->getQueryBuilder()->setFirstResult(($page - 1) * $limit);
    }
}


text:
convert MoveWheel.tif -alpha On MoveWheel.png
convert YawPitchWheel.tif -alpha On YawPitchWheel.png
convert yaw_pitch_adjust.tif -alpha On yaw_pitch_adjust.png
convert movewheel_marker.tif -alpha On movewheel_marker.png
convert minus.tif -alpha On minus.png
convert minus_over.tif -alpha On minus_over.png
convert minus_clicked.tif -alpha On minus_clicked.png
convert plus.tif -alpha On plus.png
convert plus_over.tif -alpha On plus_over.png
convert plus_clicked.tif -alpha On plus_clicked.png
convert slider.tif -alpha On slider.png
convert slider_over.tif -alpha On slider_over.png
convert slider_clicked.tif -alpha On slider_clicked.png
convert slider_rail.tif -alpha On slider_rail.png
convert crosshair.tif -alpha On crosshair.png

bin\pngcrush MoveWheel.png ..\MoveWheel.png
bin\pngcrush minus.png ..\minus.png
bin\pngcrush minus_over.png ..\minus_over.png
bin\pngcrush minus_clicked.png ..\minus_clicked.png
bin\pngcrush plus.png ..\plus.png
bin\pngcrush plus_over.png ..\plus_over.png
bin\pngcrush plus_clicked.png ..\plus_clicked.png
bin\pngcrush slider.png ..\slider.png
bin\pngcrush slider_over.png ..\slider_over.png
bin\pngcrush slider_clicked.png ..\slider_clicked.png
bin\pngcrush slider_rail.png ..\slider_rail.png
bin\pngcrush movewheel_marker.png ..\movewheel_marker.png
bin\pngcrush YawPitchWheel.png ..\YawPitchWheel.png
bin\pngcrush yaw_pitch_adjust.png ..\yaw_pitch_adjust.png
bin\pngcrush crosshair.png ..\crosshair.png

del *.png

pause


text:
layout:            post
title:             "My LeetCode Summary"
date:              2022-11-23 16:27:00 +0800
tags:              Writing skills
comments:			  true
category:          Features
catalog:    		  true
header-img: 		  "img/post-bg-e2e-ux.jpg"
header-mask:       0.3
author:            Changhao Li
---

Recently I has been crazily writing papers for previously stacked unpublished works, and today just got one paper rejected by the editor of *Nature Communications*. When I am reading the highly-cited paper on prestigous journals such as *Nature*, *Science*, *PNAS*, I am always impressed by their efforts and skills shown in writing and figures. Their wording is so clear and fine-tuned, and their figures are so rich and well-designed. I always try to imitate their styles but can not really approach their quality. However, I still observed some good characteristics shared by those impressive papers.

## Layout of Writing


text:
"""Auto-generated file, do not edit by hand. CD metadata"""
from ..phonemetadata import NumberFormat, PhoneNumberDesc, PhoneMetadata

PHONE_METADATA_CD = PhoneMetadata(id='CD', country_code=243, international_prefix='00',
    general_desc=PhoneNumberDesc(national_number_pattern='[2-6]\\d{6}|[18]\\d{6,8}|9\\d{8}', possible_number_pattern='\\d{7,9}', possible_length=(7, 9)),
    fixed_line=PhoneNumberDesc(national_number_pattern='1(?:2\\d{7}|\\d{6})|[2-6]\\d{6}', example_number='1234567', possible_length=(7, 9)),
    mobile=PhoneNumberDesc(national_number_pattern='8(?:[0-2459]\\d{2}|8)\\d{5}|9[017-9]\\d{7}', example_number='991234567', possible_length=(7, 9)),
    toll_free=PhoneNumberDesc(),
    premium_rate=PhoneNumberDesc(),
    shared_cost=PhoneNumberDesc(),
    personal_number=PhoneNumberDesc(),
    voip=PhoneNumberDesc(),
    pager=PhoneNumberDesc(),
    uan=PhoneNumberDesc(),
    voicemail=PhoneNumberDesc(),
    no_international_dialling=PhoneNumberDesc(),
    national_prefix='0',
    national_prefix_for_parsing='0',
    number_format=[NumberFormat(pattern='(\\d{2})(\\d{3})(\\d{4})', format='\\1 \\2 \\3', leading_digits_pattern=['12'], national_prefix_formatting_rule='0\\1'),
        NumberFormat(pattern='([89]\\d{2})(\\d{3})(\\d{3})', format='\\1 \\2 \\3', leading_digits_pattern=['8[0-2459]|9'], national_prefix_formatting_rule='0\\1'),
        NumberFormat(pattern='(\\d{2})(\\d{2})(\\d{3})', format='\\1 \\2 \\3', leading_digits_pattern=['88'], national_prefix_formatting_rule='0\\1'),
        NumberFormat(pattern='(\\d{2})(\\d{5})', format='\\1 \\2', leading_digits_pattern=['[1-6]'], national_prefix_formatting_rule='0\\1')])


text:
'''
KTN-project 2014
Very simple server implementation
Group 75
'''
import SocketServer
import json
import datetime
import re

class CLientHandler(SocketServer.BaseRequestHandler):
    def handle(self):
        self.connection = self.request
        self.ip = self.client_address[0]
        self.port = self.client_address[1]
        print 'Client connected @' + self.ip + ':' + str(self.port)

        while True:
            data = self.connection.recv(1024).strip()
            if data:
                data = json.loads(data)
                response = server.parse_message(data, self)
                if data['request'] == 'logout':
                    break
                else:
                    self.connection.sendall(json.dumps(response))

        print 'Client disconnected @' + self.ip + ':' + str(self.port)
        self.connection.close()

class ThreadedTCPServer(SocketServer.ThreadingMixIn, SocketServer.TCPServer):
    user_dict = {}
    messagelog = []

    def parse_message(self, message, handler):
        if message['request'] == 'login':
            return self.login(message['username'], handler)
        elif message['request'] == 'logout':
            return self.logout(handler)
        elif message['request'] == 'message':
            return self.push_chatmessage(message['message'], handler)

    def login(self, username, handler):
        response = {'response': 'login', 'username': username}
        if not re.match('^\w+$', username):
            response['error'] = 'Invalid username!'
        elif username in self.user_dict.values():
            response['error'] = 'Name already taken!'
        else:
            messagelog_string = "Previous messages:"
            for line in self.messagelog:
                messagelog_string = messagelog_string + '\n' + line

            response['messages'] = messagelog_string
            self.user_dict[handler] = username
            print username + ' has logged in!'
        return response

    def logout(self, handler):
        response = {'response': 'logout', 'username': ""}
        if not self.user_dict.has_key(handler):
            response['error'] = 'Not logged in!'
        else:
            username = self.user_dict[handler]
            response['username'] = username
            del self.user_dict[handler]
            print username + " has gone offline!"
        return response

    def push_chatmessage(self, chatmessage, handler):
        if self.user_dict.has_key(handler):
            username = self.user_dict[handler]
            message = username + ' said @ ' + datetime.datetime.now().strftime('%d/%m/%Y %H:%M:%S %Z') + ': ' + chatmessage
            self.messagelog.append(message)
            response = {'response': 'message', 'message': message}
            response = json.dumps(response)

            for addr, user in self.user_dict.iteritems():
                if username != user:
                    addr.connection.sendall(response)
            return
        else:
            response = {'response': 'message', 'error': 'You are not logged in!'}
        return response

if __name__ == "__main__":
    HOST = 'localhost'
    PORT = 9999

    # Create the server, binding to localhost on port 9999
    server = ThreadedTCPServer((HOST, PORT), CLientHandler)

    # Activate the server; this will keep running until you
    # interrupt the program with Ctrl-C
    server.serve_forever()


text:
package org.perfcake.pc4idea.impl.editor.actions;

import com.intellij.icons.AllIcons;
import org.perfcake.model.Scenario;
import org.perfcake.pc4idea.api.editor.openapi.ui.EditorDialog;
import org.perfcake.pc4idea.api.util.Messages;
import org.perfcake.pc4idea.api.util.PerfCakeModuleUtil;
import org.perfcake.pc4idea.impl.editor.editor.component.MessageEditor;
import org.perfcake.pc4idea.impl.editor.modelwrapper.component.MessagesModelWrapper;

import javax.swing.*;
import java.awt.event.ActionEvent;

/**
 * Created by Stanislav Kaleta on 3/27/15.
 */
public class AddMessageAction extends AbstractAction {
    private MessagesModelWrapper target;

    public AddMessageAction(MessagesModelWrapper target){
        super(Messages.Command.ADD + " " + Messages.Scenario.MESSAGES, AllIcons.General.Add);
        this.target = target;

    }
    @Override
    public void actionPerformed(ActionEvent e) {
        MessageEditor editor = new MessageEditor(target.getSync());
        EditorDialog dialog = new EditorDialog(editor);
        dialog.show();
        if (dialog.getExitCode() == 0) {
            Scenario.Messages.Message message = editor.getMessage();
            target.addMessage(message);
            target.commit(Messages.Command.ADD + " " + Messages.Scenario.MESSAGES);
            target.updateGui();

            if (editor.getMessage().getUri() != null) {
                PerfCakeModuleUtil.createMessageFile(editor.getMessage().getUri(), target.getContext().getModule());
            }
        }
    }
}


text:
import numpy as np
import pandas as pd
from collections import defaultdict
from bokeh.charts import Scatter, show

def dist(x, y):
    """Euclidean distance between x and y. """
    return np.linalg.norm(x-y)

def init_centroids(X, k):
    centroids = [X[np.random.randint(0, len(X)-1)]]  # First random point.
    for i in range(1, k):  # For each remaining centroid.
        D = assign_to_clusters(X, centroids)
        # Choose new centroid point (from X) according to weights in D.
        D = [d[0] for d in D]
        D_sum = sum(D)
        D = [d/D_sum for d in D]
        centroids.append(X[np.random.choice(range(len(X)), p=D)])
    return centroids

def assign_to_clusters(X, centroids):
    """For each data point, calculate the distance to the closest
    centroid, and put that distance into D. """
    D = []
    for j, x in enumerate(X):
        for m, centroid in enumerate(centroids):
            curr_dist = dist(centroid, x)
            if len(D) - 1 < j:
                D.append((curr_dist, m))
            else:
                if D[-1][0] > curr_dist:
                    D[-1] = (curr_dist, m)
    return D

def recalc_centroids(X, D):
    cluster_to_indices = defaultdict(lambda: [])
    for i, d in enumerate(D):
        cluster_to_indices[d[1]].append(i)

    centroids = []
    for cluster in cluster_to_indices:
        new_cluster = [0]*len(X[0])
        for x in cluster_to_indices[cluster]:
            x = X[x]
            for i, x_i in enumerate(x):
                new_cluster[i] += x_i
        new_cluster = [c/len(cluster_to_indices[cluster]) for c in new_cluster]
        centroids.append(new_cluster)
    return centroids

def kmeanspp(X, k, num_iter=100):
    centroids = init_centroids(X, k)

    for _ in range(num_iter):
        D = assign_to_clusters(X, centroids)
        centroids = recalc_centroids(X, D)

    df = pd.DataFrame(X)
    D = [d[1] for d in D]
    df = pd.concat([df, pd.Series(D)], axis=1)
    df.columns = ['x', 'y', 'cluster']

    p = Scatter(df, x='x', y='y', color='cluster')

    show(p)

if __name__ == '__main__':
    X = [np.array([np.random.uniform(0, 100), np.random.uniform(0, 100)])
         for _ in range(500)]

    kmeanspp(X, k=5)


text:
package com.hoszu.spark

import java.text.SimpleDateFormat
import java.util.Date
import java.util.concurrent.TimeUnit

// ATM
case class ATM(atmId: String, name: String, town: String, address: String, latitude: Double, longitude: Double) {
  def this(csv: Array[String]) = this(csv(0), csv(1), csv(2), csv(3), csv(4).toDouble, csv(5).toDouble)
}

object ATM {
  def apply(csv: Array[String]) = new ATM(csv)
}

//TRX
case class TRX(trxId: String, atmId: String, cardId: String, cardType: String, amount: Double, time: Date) {
  def this(csv: Array[String]) = {
    this(csv(0), csv(1), csv(2), csv(3), csv(4).toDouble, (new SimpleDateFormat("yyyy/MM/dd HH:mm")).parse(csv(6) + " " + csv(5)))
  }

  def mkString(s: String): String = {
    return trxId + s + atmId + s + cardId + s + cardType + s + amount + s + (new SimpleDateFormat("yyyy/MM/dd HH:mm")).format(time)
  }

  def mkString: String = mkString(";")
}

object TRX {
  def apply(csv: Array[String]) = new TRX(csv)
}

// TRXwithATM
case class TRXwithATM(trx: TRX, atm: Option[ATM])

// TransactionDifference
case class TransactionDifference(id: String, t1: TRX, t2: TRX, timeDiff: Long, distance: Double, fraudability: Double) {
  def mkString(s: String): String = {
    return timeDiff + s + distance.toFloat + s + fraudability.toFloat + s + t1.mkString(s) + s + t2.mkString(s)
  }

  def mkString: String = mkString(";")
}

object TransactionDifference {
  def apply(ta1: TRXwithATM, ta2: TRXwithATM): TransactionDifference = {
    val timeDiff = getTimeDifference(ta1.trx, ta2.trx)
    val locDist = getLocationDistance(ta1.atm, ta2.atm)
    val fraudability = locDist / (timeDiff.toDouble / 60.0)    //distance / minutes / minutes-in-hour
    new TransactionDifference(ta1.trx.trxId +"-"+ ta2.trx.trxId, ta1.trx, ta2.trx, timeDiff, locDist, fraudability)
  }

  private def getLocationDistance(oa1: Option[ATM], oa2: Option[ATM]): Double = {
    if (oa1.nonEmpty && oa2.nonEmpty) {
      val a1 = oa1.get
      val a2 = oa2.get
      val dLat = (a2.latitude - a1.latitude).toRadians
      val dLon = (a2.longitude - a1.longitude).toRadians
      val a = Math.sin(dLat / 2.0) * Math.sin(dLat / 2.0) +
        Math.cos(a1.latitude.toRadians) * Math.cos(a2.latitude.toRadians) * Math.sin(dLon / 2.0) * Math.sin(dLon / 2.0);
      val c = 2 * Math.atan2(Math.sqrt(a), Math.sqrt(1 - a));
      return 6371 * c; // Distance in km
    }
    return Double.NaN
  }

  private def getTimeDifference(t1: TRX, t2: TRX): Long = {
    return Math.abs(TimeUnit.MINUTES.convert(t1.time.getTime() - t2.time.getTime(), TimeUnit.MILLISECONDS))
  }
}


text: from ijson.parse import JSONError, basic_parse, parse, ObjectBuilder, items


text:
$(document).ready(function() {
  semanticInitializers();
});

$( document ).on('page:load',function() {
  semanticInitializers();
});

function semanticInitializers() {
  $('.ui.dropdown').dropdown();
  $('img.contributor').popup();
  $('.button').popup();
  $('.menu .item').tab();
  $('.message .close')
    .on('click', function() {
      $(this)
        .closest('.message')
        .transition('fade');
    });
  $('.launch-modal').on('click', function(){
    // Get the data-modal attribute containing the id of the modal
    // we want to launch.
    modal_id = $(this).attr('data-modal');
    $('#' + modal_id + '.modal').modal('show');
  });
}


text:
<?php

namespace utest\orm\mock\collections;

/**
 * Тестовый Object
 * @property int $id
 * @property string $login логин пользователя
 * @property string $password пароль пользователя
 * @property bool $isActive активность
 */
class Supervisor extends User
{

}


text:
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd">

    <modelVersion>4.0.0</modelVersion>

    <groupId>jp.co.flect</groupId>
    <artifactId>odata-producer</artifactId>
    <name>odata-odata-producer</name>
    <version>1.0-SNAPSHOT</version>
    <packaging>war</packaging>

    <dependencies>
        <dependency>
            <groupId>javax.servlet</groupId>
            <artifactId>javax.servlet-api</artifactId>
            <version>3.0.1</version>
            <scope>provided</scope>
        </dependency>
        <dependency>
            <groupId>org.projectlombok</groupId>
            <artifactId>lombok</artifactId>
            <version>1.14.8</version>
            <scope>provided</scope>
        </dependency>
        <dependency>
            <groupId>org.apache.cxf</groupId>
            <artifactId>cxf-rt-frontend-jaxrs</artifactId>
            <version>2.7.14</version>
        </dependency>
        <dependency>
            <groupId>com.github.jsimone</groupId>
            <artifactId>webapp-runner</artifactId>
            <version>7.0.40.0</version>
            <scope>provided</scope>
        </dependency>
        <dependency>
            <groupId>postgresql</groupId>
            <artifactId>postgresql</artifactId>
            <version>9.1-901-1.jdbc4</version>
        </dependency>
        <dependency>
            <groupId>org.hibernate</groupId>
            <artifactId>hibernate-entitymanager</artifactId>
            <version>4.3.7.Final</version>
        </dependency>
        <dependency>
            <groupId>org.apache.olingo</groupId>
            <artifactId>olingo-odata2-core</artifactId>
            <version>2.0.1</version>
        </dependency>
        <dependency>
            <groupId>org.apache.olingo</groupId>
            <artifactId>olingo-odata2-api</artifactId>
            <version>2.0.1</version>
        </dependency>
        <dependency>
            <groupId>org.apache.olingo</groupId>
            <artifactId>olingo-odata2-jpa-processor-api</artifactId>
            <version>2.0.1</version>
        </dependency>
        <dependency>
            <groupId>org.apache.olingo</groupId>
            <artifactId>olingo-odata2-jpa-processor-core</artifactId>
            <version>2.0.1</version>
        </dependency>
        <dependency>
            <groupId>org.apache.olingo</groupId>
            <artifactId>olingo-odata2-jpa-processor-ref</artifactId>
            <version>2.0.1</version>
        </dependency>
    </dependencies>

    <build>
        <plugins>
	   <plugin>
		<artifactId>maven-compiler-plugin</artifactId>
		<version>3.1</version>
		<configuration>
			<source>1.7</source>
			<target>1.7</target>
            <encoding>UTF-8</encoding>
		</configuration>
	   </plugin>
           <plugin>
               <groupId>org.apache.tomcat.maven</groupId>
               <artifactId>tomcat7-maven-plugin</artifactId>
               <version>2.2</version>
               <configuration>
                   <port>8090</port>
                   <path>/</path>
                   <update>true</update>
               </configuration>
           </plugin>
           <plugin>
                <groupId>org.apache.maven.plugins</groupId>
                <artifactId>maven-war-plugin</artifactId>
                <version>2.4</version>
                <configuration>
                    <failOnMissingWebXml>false</failOnMissingWebXml>
                    <webappDirectory>${project.build.directory}/${project.artifactId}</webappDirectory>
                    <warName>${project.artifactId}</warName>
                    <webXml>src/web.xml</webXml>
                </configuration>
            </plugin>
            <plugin>
                <groupId>org.apache.maven.plugins</groupId>
                <artifactId>maven-dependency-plugin</artifactId>
                <version>2.8</version>
                <executions>
                    <execution>
                        <phase>package</phase>
                        <goals><goal>copy-dependencies</goal></goals>
                        <configuration>
                            <includeArtifactIds>webapp-runner</includeArtifactIds>
                        </configuration>
                    </execution>
                </executions>
            </plugin>
        </plugins>
    </build>
</project>


text:
"""
A dependency management system for items.
"""

from __future__ import print_function
import sys, itertools

from zope.interface.advice import addClassAdvisor

import attr

from axiom.item import Item
from axiom.attributes import reference, boolean, AND
from axiom.errors import ItemNotFound, DependencyError, UnsatisfiedRequirement
import six
from six.moves import map, zip

# There is probably a cleaner way to do this.
_globalDependencyMap = {
    # map depending-class: (depended-upon-class,
    # callable-to-customize-creation, reference-attribute)
}

def dependentsOf(cls):
    deps = _globalDependencyMap.get(cls, None)
    if deps is None:
        return []
    else:
        return [d[0] for d in deps]

##Totally ripping off z.i

def dependsOn(itemType, itemCustomizer=None, doc='',
              indexed=True, whenDeleted=reference.NULLIFY):
    """
    This function behaves like L{axiom.attributes.reference} but with
    an extra behaviour: when this item is installed (via
    L{axiom.dependency.installOn} on a target item, the
    type named here will be instantiated and installed on the target
    as well.

    For example::

      class Foo(Item):
          counter = integer()
          thingIDependOn = dependsOn(Baz, lambda baz: baz.setup())

    @param itemType: The Item class to instantiate and install.
    @param itemCustomizer: A callable that accepts the item installed
    as a dependency as its first argument. It will be called only if
    an item is created to satisfy this dependency.

    @return: An L{axiom.attributes.reference} instance.
    """

    frame = sys._getframe(1)
    locals = frame.f_locals

    # Try to make sure we were called from a class def.
    if (locals is frame.f_globals) or ('__module__' not in locals):
        raise TypeError("dependsOn can be used only from a class definition.")
    ref = reference(reftype=itemType, doc=doc, indexed=indexed, allowNone=True,
                    whenDeleted=whenDeleted)
    if "__dependsOn_advice_data__" not in locals and six.PY2:
        addClassAdvisor(dependable)
    locals.setdefault('__dependsOn_advice_data__', []).append(
        (itemType, itemCustomizer, ref)
    )
    return ref

def dependable(cls):
    """
    Classes that use `dependsOn` in their bodies should be decorated with this
    as a class decorator, like so::

        @dependable
        class A(Item):
            b = dependsOn(B)
    """
    if cls in _globalDependencyMap:
        # bail if we end up here twice, somehow
        return cls
    for itemType, itemCustomizer, ref in cls.__dict__[
        '__dependsOn_advice_data__'
    ]:
        classDependsOn(cls, itemType, itemCustomizer, ref)
    del cls.__dependsOn_advice_data__
    return cls

def classDependsOn(cls, itemType, itemCustomizer, ref):
    _globalDependencyMap.setdefault(cls, []).append(
        (itemType, itemCustomizer, ref))

class _DependencyConnector(Item):
    """
    I am a connector between installed items and their targets.
    """
    installee = reference(doc="The item installed.")
    target = reference(doc="The item installed upon.")
    explicitlyInstalled = boolean(doc="Whether this item was installed"
                                  "explicitly (and thus whether or not it"
                                  "should be automatically uninstalled when"
                                  "nothing depends on it)")

def installOn(self, target):
    """
    Install this object on the target along with any powerup
    interfaces it declares. Also track that the object now depends on
    the target, and the object was explicitly installed (and therefore
    should not be uninstalled by subsequent uninstallation operations
    unless it is explicitly removed).
    """
    _installOn(self, target, True)

def _installOn(self, target, __explicitlyInstalled=False):
    depBlob = _globalDependencyMap.get(self.__class__, [])
    dependencies, itemCustomizers, refs = (list(map(list, zip(*depBlob)))
                                         or ([], [], []))
    #See if any of our dependencies have been installed already
    for dc in self.store.query(_DependencyConnector,
                               _DependencyConnector.target == target):
        if dc.installee.__class__ in dependencies:
            i = dependencies.index(dc.installee.__class__)
            refs[i].__set__(self, dc.installee)
            del dependencies[i], itemCustomizers[i], refs[i]
        if (dc.installee.__class__ == self.__class__
            and self.__class__ in set(
            itertools.chain([blob[0][0] for blob in
                             list(_globalDependencyMap.values())]))):
            #Somebody got here before we did... let's punt
            raise DependencyError("An instance of %r is already "
                                  "installed on %r." % (self.__class__,
                                                        target))
    #The rest we'll install
    for i, cls in enumerate(dependencies):
        it = cls(store=self.store)
        if itemCustomizers[i] is not None:
            itemCustomizers[i](it)
        _installOn(it, target, False)
        refs[i].__set__(self, it)
    #And now the connector for our own dependency.

    dc = self.store.findUnique(
        _DependencyConnector,
        AND(_DependencyConnector.target==target,
            _DependencyConnector.installee==self,
            _DependencyConnector.explicitlyInstalled==__explicitlyInstalled),
        None)
    assert dc is None, "Dependency connector already exists, wtf are you doing?"
    _DependencyConnector(store=self.store, target=target,
                         installee=self,
                         explicitlyInstalled=__explicitlyInstalled)

    target.powerUp(self)

    callback = getattr(self, "installed", None)
    if callback is not None:
        callback()

def uninstallFrom(self, target):
    """
    Remove this object from the target, as well as any dependencies
    that it automatically installed which were not explicitly
    "pinned" by calling "install", and raising an exception if
    anything still depends on this.
    """

    #did this class powerup on any interfaces? powerdown if so.
    target.powerDown(self)

    for dc in self.store.query(_DependencyConnector,
                               _DependencyConnector.target==target):
        if dc.installee is self:
            dc.deleteFromStore()

    for item in installedUniqueRequirements(self, target):
        uninstallFrom(item, target)

    callback = getattr(self, "uninstalled", None)
    if callback is not None:
        callback()

def installedOn(self):
    """
    If this item is installed on another item, return the install
    target. Otherwise return None.
    """
    try:
        return self.store.findUnique(_DependencyConnector,
                                     _DependencyConnector.installee == self
                                     ).target
    except ItemNotFound:
        return None

def installedDependents(self, target):
    """
    Return an iterable of things installed on the target that
    require this item.
    """
    for dc in self.store.query(_DependencyConnector,
                               _DependencyConnector.target == target):
        depends = dependentsOf(dc.installee.__class__)
        if self.__class__ in depends:
            yield dc.installee

def installedUniqueRequirements(self, target):
    """
    Return an iterable of things installed on the target that this item
    requires and are not required by anything else.
    """

    myDepends = dependentsOf(self.__class__)
    #XXX optimize?
    for dc in self.store.query(_DependencyConnector,
                               _DependencyConnector.target==target):
        if dc.installee is self:
            #we're checking all the others not ourself
            continue
        depends = dependentsOf(dc.installee.__class__)
        if self.__class__ in depends:
            raise DependencyError(
                "%r cannot be uninstalled from %r, "
                "%r still depends on it" % (self, target, dc.installee))

        for cls in myDepends[:]:
            #If one of my dependencies is required by somebody
            #else, leave it alone
            if cls in depends:
                myDepends.remove(cls)

    for dc in self.store.query(_DependencyConnector,
                               _DependencyConnector.target==target):
        if (dc.installee.__class__ in myDepends
            and not dc.explicitlyInstalled):
            yield dc.installee

def installedRequirements(self, target):
    """
    Return an iterable of things installed on the target that this
    item requires.
    """
    myDepends = dependentsOf(self.__class__)
    for dc in self.store.query(_DependencyConnector,
                               _DependencyConnector.target == target):
        if dc.installee.__class__ in myDepends:
            yield dc.installee

def onlyInstallPowerups(self, target):
    """
    Deprecated - L{Item.powerUp} now has this functionality.
    """
    target.powerUp(self)

@attr.s(eq=False)
class requiresFromSite(object):
    """
    A read-only descriptor that will return the site store's powerup for a
    given item.

    @ivar powerupInterface: an L{Interface} describing the powerup that the
    site store should be adapted to.

    @ivar defaultFactory: a 1-argument callable that takes the site store and
    returns a value for this descriptor.  This is invoked in cases where the
    site store does not provide a default factory of its own, and this
    descriptor is retrieved from an item in a store with a parent.

    @ivar siteDefaultFactory: a 1-argument callable that takes the site store
    and returns a value for this descriptor.  This is invoked in cases where
    this descriptor is retrieved from an item in a store without a parent.
    """
    powerupInterface = attr.ib()
    defaultFactory = attr.ib(default=None)
    siteDefaultFactory = attr.ib(default=None)

    def _invokeFactory(self, defaultFactory, siteStore):
        if defaultFactory is None:
            raise UnsatisfiedRequirement()
        return defaultFactory(siteStore)

    def __get__(self, oself, type=None):
        """
        Retrieve the value of this dependency from the site store.
        """
        siteStore = oself.store.parent
        if siteStore is not None:
            pi = self.powerupInterface(siteStore, None)
            if pi is None:
                pi = self._invokeFactory(self.defaultFactory, siteStore)
        else:
            pi = self._invokeFactory(self.siteDefaultFactory, oself.store)
        return pi


text:
#include <Arduino.h>
#include "HardwareSerial.h"

uint8_t _serialEvent1_default __attribute__((weak)) PROGMEM = 0 ;

HardwareSerial Serial1(&serialEvent1);

void HardwareSerial::begin(uint32_t baud) {
	serial_begin(BAUD2DIV(baud));
	if (!_serialEvent1_default) addToSerialEventsList();
}


text:
module Models
  class Card
    include Comparable

    SUITS = %w(C D H S)
    SCORES = %w(2 3 4 5 6 7 8 9 T J Q K A)

    attr_accessor :value, :score, :suit

    def initialize(card_representation)
      @score, @suit = card_representation.split('')
      raise NotValidSuite unless SUITS.include? @suit
      raise NotValidValue unless SCORES.include? @score
      @value = SCORES.index(@score)+2 #for matching the real value
    end

    def <=>(card)
      @value <=> card.value
    end

    def to_s
      "#{@score}#{@suit}"
    end

    class NotValidSuite < StandardError ; end
    class NotValidValue < StandardError ; end

  end
end


text:
[Cloud Tasks API][Product Documentation]:
Manages the execution of large numbers of distributed requests. Cloud Tasks
is in Alpha.
- [Client Library Documentation][]
- [Product Documentation][]

## Quick Start
In order to use this library, you first need to go through the following
steps:

1. [Select or create a Cloud Platform project.](https://console.cloud.google.com/project)
2. [Enable billing for your project.](https://cloud.google.com/billing/docs/how-to/modify-project#enable_billing_for_a_project)
3. [Enable the Cloud Tasks API.](https://console.cloud.google.com/apis/api/cloudtasks)
4. [Setup Authentication.](https://googlecloudplatform.github.io/google-cloud-ruby/#/docs/google-cloud/master/guides/authentication)

### Installation
```
$ gem install google-cloud-tasks
```

### Next Steps
- Read the [Client Library Documentation][] for Cloud Tasks API
  to see other available methods on the client.
- Read the [Cloud Tasks API Product documentation][Product Documentation]
  to learn more about the product and see How-to Guides.
- View this [repository's main README](https://github.com/GoogleCloudPlatform/google-cloud-ruby/blob/master/README.md)
  to see the full list of Cloud APIs that we cover.

[Client Library Documentation]: https://googlecloudplatform.github.io/google-cloud-ruby/#/docs/google-cloud-tasks/latest/google/cloud/tasks/v2beta2
[Product Documentation]: https://cloud.google.com/cloudtasks


text:
namespace vr
{
  class OpenGLException : public VRException
  {
  public:
    OpenGLException(const std::string& glFunction, GLenum errorCode, const char *file, int line);

  private:
    std::string createMessage(const std::string& function, GLenum errorCode);
  };

}

#endif


text:
package org.apache.ode.bpel.o;

import javax.wsdl.Operation;
import javax.wsdl.PortType;
import javax.xml.namespace.QName;
import java.util.Collections;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Set;

/**
 * Compiled representation of a BPEL partnerLink.
 */
public class OPartnerLink extends OBase {
    static final long serialVersionUID = -1L  ;
    /** partnerLink name. */
    public String name;

    /** Scope in which this partnerLink is declared. */
    public OScope declaringScope;

    /** The type of this partnerLink. */
    public QName partnerLinkType;

    public String partnerRoleName;

    public String myRoleName;

    public PortType myRolePortType;

    public PortType partnerRolePortType;

    public boolean initializePartnerRole;

    /** The set of CorrelationSets that may be used as a match criteria, organized by {@link Operation} */
    private final HashMap<String,Set<OScope.CorrelationSet>> _nonIntitiatingCorrelationSets = new HashMap<String,Set<OScope.CorrelationSet>>();

    /** The set of {@link Operation}s that can be used to create a process instance. */
    private final HashSet<String> _createInstanceOperations = new HashSet<String>();

    public OPartnerLink(OProcess owner) {
        super(owner);
    }

    public String getName() {
        return name;
    }

    public boolean hasMyRole() {
        return myRolePortType != null;
    }

    public boolean hasPartnerRole() {
        return partnerRolePortType != null;
    }

    public boolean isCreateInstanceOperation(Operation op) {
        return _createInstanceOperations.contains(op.getName());
    }

    public void addCreateInstanceOperation(Operation operation) {
        _createInstanceOperations.add(operation.getName());
    }

    /**
     * Add a {@link org.apache.ode.bpel.o.OScope.CorrelationSet} to an {@link Operation}'s list
     * of "non-initiating" correlation sets. The non-initiating correlation sets are those
     * sets that are used (along with the operation) to "match" incoming messages.
     * We need to know which correlation sets are used with which operation in order to
     * pre-compute correlation keys at the time of message receipt.
     * @param operation WSDL {@link Operation}
     * @param cset non-initiating correlation used in this operation
     */
    public void addCorrelationSetForOperation(Operation operation, OScope.CorrelationSet cset) {
        Set<OScope.CorrelationSet> ret = _nonIntitiatingCorrelationSets.get(operation.getName());
        if (ret == null) {
            ret = new HashSet<OScope.CorrelationSet>();
            _nonIntitiatingCorrelationSets.put(operation.getName(), ret);
        }
        ret.add(cset);

    }

    /**
     * Get all non-initiating correlation sets that are ever used to qualify a receive for a the given
     * operation.
     * @param operation the operation
     * @return all non-initiating correlation sets used in the given operation
     */
    @SuppressWarnings("unchecked")
    public Set<OScope.CorrelationSet> getCorrelationSetsForOperation(Operation operation) {
        Set<OScope.CorrelationSet> ret = _nonIntitiatingCorrelationSets.get(operation.getName());
        if (ret == null) {
            return Collections.EMPTY_SET;
        }
        return Collections.unmodifiableSet(ret);
    }

    @SuppressWarnings("unchecked")
    public Operation getMyRoleOperation(String name) {
        for (Operation op : (List<Operation>)myRolePortType.getOperations())
            if (op.getName().equals(name))
                return op;
        return null;
    }

    @SuppressWarnings("unchecked")
    public Operation getPartnerRoleOperation(String name) {
        for (Operation op : (List<Operation>)partnerRolePortType.getOperations())
            if (op.getName().equals(name))
                return op;
        return null;
    }
}


text:
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">

<title>FrenchStemmer</title>
<meta name="date" content="2013-10-16">
<link rel="stylesheet" type="text/css" href="../stylesheet.css" title="Style">

JavaScript is disabled on your browser.

Package

Class

Use

Tree

Deprecated

Index

Help

Prev Class

Next Class

Frames

No Frames

All Classes

Summary:

Nested |

Field |

Constr |

Method

Detail:

Field |

Constr |

Method

tools

Class FrenchStemmer

java.lang.Object

org.tartarus.snowball.SnowballProgram

org.tartarus.snowball.SnowballStemmer

org.tartarus.snowball.ext.frenchStemmer

tools.FrenchStemmer

All Implemented Interfaces:

Normalizer

public class FrenchStemmer
extends org.tartarus.snowball.ext.frenchStemmer
implements Normalizer

Classe de racinisation (stemming) des mots en français. Modification légère
 du package SnowBall http://snowball.tartarus.org/download.php

Author:

xtannier

Constructor Summary

Constructors

Constructor and Description

FrenchStemmer()

Method Summary

Methods

Modifier and Type
Method and Description

static java.util.ArrayList<java.lang.String>
getStopWords()

static void
main(java.lang.String[] args)

java.util.ArrayList<java.lang.String>
normalize(java.io.File file)

Give lexical units in the file.

java.util.ArrayList<java.lang.String>
normalize(java.lang.String text)

Give lexical units in the file.

java.util.ArrayList<java.lang.String>
normalize(java.lang.String fileName,
         boolean removeStopWords)

Give lexical units in the file.

Methods inherited from class org.tartarus.snowball.ext.frenchStemmer

stem

Methods inherited from class org.tartarus.snowball.SnowballProgram

getCurrent, setCurrent

Methods inherited from class java.lang.Object

equals, getClass, hashCode, notify, notifyAll, toString, wait, wait, wait

Constructor Detail

FrenchStemmer

public FrenchStemmer()

Method Detail

normalize

public java.util.ArrayList<java.lang.String> normalize(java.io.File file)
                                                throws java.io.IOException

Description copied from interface: Normalizer

Give lexical units in the file. Equivalent normalize(file, false)

Specified by:

normalize in interface Normalizer

Parameters:

file - input file

Returns:

<unit token>

Throws:

java.io.IOException

normalize

public java.util.ArrayList<java.lang.String> normalize(java.lang.String text)

Description copied from interface: Normalizer

Give lexical units in the file. Equivalent normalize(file, false)

Specified by:

normalize in interface Normalizer

Parameters:

text - input Text

Returns:

<unit token>

normalize

public java.util.ArrayList<java.lang.String> normalize(java.lang.String fileName,
                                              boolean removeStopWords)
                                                throws java.io.IOException

Description copied from interface: Normalizer

Give lexical units in the file. Equivalent normalize(file, false)
 . It can or not supress stop words

Specified by:

normalize in interface Normalizer

Parameters:

fileName - input file name

removeStopWords - true : remove too usual words

Returns:

<unit token>

Throws:

java.io.IOException

getStopWords

public static java.util.ArrayList<java.lang.String> getStopWords()
                                                          throws java.io.IOException

Throws:

java.io.IOException

main

public static void main(java.lang.String[] args)

Package

Class

Use

Tree

Deprecated

Index

Help

Prev Class

Next Class

Frames

No Frames

All Classes

Summary:

Nested |

Field |

Constr |

Method

Detail:

Field |

Constr |

Method


text:
//
//  NSUnderscore.h
//  NSUnderscore
//
//  Created by Ryan Gerard on 10/18/15.
//  Copyright © 2015 Ryan Gerard. All rights reserved.
//

#import <Foundation/Foundation.h>

@interface NSDictionary (NSUnderscoreAdditions)

/*
 * Iterates over a list of elements, yielding each in turn to an action function.
 */
- (void)each:(void(^)(id))action;

/*
 * Produces a new array of values by mapping each value in list through a transformation function (action).
 */
- (NSArray *)map:(id(^)(id))action;

/*
 * Reduce boils down a list of values into a single value. Each successive step of it should be returned by action.
 */
- (id)reduce:(id(^)(id, id))action;

/*
 * Looks through each value in the list, returning an array of all the values that pass a truth test
 */
- (NSArray *)filter:(bool(^)(id))action;

/*
 * Returns the values in list without the elements that the truth test (predicate) passes. The opposite of filter.
 */
- (NSArray *)reject:(bool(^)(id))action;

/*
 * Returns true if all of the values in the list pass the predicate truth test.
 */
- (BOOL)every:(BOOL(^)(id))action;

/*
 * Returns true if any of the values in the list pass the predicate truth test. Short-circuits and stops traversing the list if a true element is found.
 */
- (BOOL)some:(BOOL(^)(id))action;

/*
 * A convenient version of what is perhaps the most common use-case for map: extracting a list of property values.
 */
- (NSArray *)pluck:(NSString *)propertyName;

/*
 * Returns the maximum value in list.
 */
- (id)max:(NSInteger(^)(id))action;

/*
 * Returns the minimum value in list.
 */
- (id)min:(NSInteger(^)(id))action;

/*
 * Splits a collection into sets, grouped by the result of running each value through action.
 */
- (NSDictionary *)groupBy:(id(^)(id))action;

/*
 * Given a list, and an action function that returns a key for each element in the list, returns an object with an index of each item.
 * Just like groupBy, but for when you know your keys are unique.
 */
- (NSDictionary *)indexBy:(id(^)(id))action;

/*
 * Sorts a list into groups and returns a count for the number of objects in each group.
 * Similar to groupBy, but instead of returning a list of values, returns a count for the number of values in that group.
 */
- (NSDictionary *)countBy:(id(^)(id))action;

/*
 * Split array into two arrays: one whose elements all satisfy action and one whose elements all do not satisfy action.
 */
- (NSArray *)partition:(BOOL(^)(id))action;

@end


text:
// Generated by CoffeeScript 1.7.1

/*
usage:

mainApp = angular.module("MainApp", [... 'saltApiSrvc'])

mainApp.controller 'MyCtlr', ['$scope', ...,'SaltApiSrvc',
    ($scope,...,SaltApiSrvc) ->

    $scope.saltApiCallPromise = SaltApiSrvc.act $scope, [{'name':'John'}]
    $scope.saltApiCallPromise.success (data, status, headers, config) ->
        console.log("SaltApi call success")
        $scope.result = data
        return true

    $scope.saltApiLoginPromise = SaltApiSrvc.login $scope, 'usernamestring', 'passwordstring'
    $scope.saltApiLoginPromise.success (data, status, headers, config) ->
        console.log("SaltApi login success")
        $scope.result = data
        return true
 */

(function() {
  var saltApiSrvc;

  saltApiSrvc = angular.module("saltApiSrvc", ['appConfigSrvc', 'appPrefSrvc', 'appStoreSrvc', 'errorReportingSrvc']);

  saltApiSrvc.factory("SaltApiSrvc", [
    '$http', 'Configuration', 'AppPref', 'SessionStore', function($http, Configuration, AppPref, SessionStore) {
      var base, saltApi, servicer;
      saltApi = AppPref.get('saltApi');
      if (saltApi.scheme || saltApi.host || saltApi.port) {
        if (!saltApi.scheme) {
          saltApi.scheme = "http";
        }
        if (!saltApi.host) {
          saltApi.host = "localhost";
        }
        if (saltApi.port) {
          saltApi.port = ":" + saltApi.port;
        }
        base = "" + saltApi.scheme + "://" + saltApi.host + saltApi.port + saltApi.prefix;
      } else {
        base = "" + saltApi.prefix;
      }
      delete $http.defaults.headers.common['X-Requested-With'];
      $http.defaults.useXDomain = true;
      servicer = {
        signature: function($scope, cmds) {
          var config, headers, url, _ref;
          headers = {
            "X-Auth-Token": (_ref = SessionStore.get('saltApiAuth')) != null ? _ref.token : void 0
          };
          config = {
            headers: headers
          };
          url = "" + base + "/signature";
          return $http.post(url, cmds, config).success(function(data, status, headers, config) {
            return true;
          }).error(function(data, status, headers, config) {
            var error;
            error = data != null ? data.error : void 0;
            if (status === 401) {
              $scope.errorMsg = "Please Login! " + error;
            } else {
              $scope.errorMsg = "Argspec call Failed! " + error;
            }
            return true;
          });
        },
        run: function($scope, cmds) {
          var config, headers, url, _ref;
          headers = {
            "X-Auth-Token": (_ref = SessionStore.get('saltApiAuth')) != null ? _ref.token : void 0
          };
          config = {
            headers: headers
          };
          url = "" + base + "/run";
          return $http.post(url, cmds, config).success(function(data, status, headers, config) {
            return true;
          }).error(function(data, status, headers, config) {
            var error;
            error = data != null ? data.error : void 0;
            if (status === 401) {
              $scope.errorMsg = "Please Login! " + error;
            } else {
              $scope.errorMsg = "Run Failed! " + error;
            }
            return true;
          });
        },
        action: function($scope, cmds) {
          var config, headers, url, _ref;
          headers = {
            "X-Auth-Token": (_ref = SessionStore.get('saltApiAuth')) != null ? _ref.token : void 0
          };
          config = {
            headers: headers
          };
          url = "" + base + "/run";
          $scope.command.lastCmds = cmds;
          if (!angular.isArray(cmds)) {
            cmds = [cmds];
          }
          return $http.post(url, cmds, config).success(function(data, status, headers, config) {
            $scope.command.history[$scope.command.humanize($scope.command.lastCmds)] = $scope.command.lastCmds;
            return true;
          }).error(function(data, status, headers, config) {
            var error;
            error = data != null ? data.error : void 0;
            if (status === 401) {
              $scope.errorMsg = "Please Login! " + error;
            } else {
              $scope.errorMsg = "Action Failed! " + error;
            }
            return true;
          });
        },
        login: function($scope, username, password) {
          var reqData, url;
          reqData = {
            "username": username,
            "password": password,
            "eauth": saltApi.eauth
          };
          url = "" + base + "/login";
          return $http.post(url, reqData).success(function(data, status, headers, config) {
            return true;
          }).error(function(data, status, headers, config) {
            $scope.errorMsg = "Login Failed!";
            return true;
          });
        },
        logout: function($scope) {
          var config, headers, url, _ref;
          headers = {
            "X-Auth-Token": (_ref = SessionStore.get('saltApiAuth')) != null ? _ref.token : void 0
          };
          config = {
            headers: headers
          };
          url = "" + base + "/logout";
          return $http.post(url, {}, config).success(function(data, status, headers, config) {
            return true;
          }).error(function(data, status, headers, config) {
            $scope.errorMsg = "Logout Failed!";
            return true;
          });
        }
      };
      return servicer;
    }
  ]);

  /*
  usage:

  mainApp = angular.module("MainApp", [... 'saltApiSrvc'])

  mainApp.controller 'MyCtlr', ['$scope', ...,'SaltApiEvtSrvc',
      ($scope,...,SaltApiEvtSrvc) ->

      $scope.saltApiCallPromise = SaltApiSrvc.act $scope, [{'name':'John'}]
      $scope.saltApiCallPromise.success (data, status, headers, config) ->
          console.log("SaltApi call success")
          $scope.result = data
          return true

      $scope.saltApiLoginPromise = SaltApiSrvc.login $scope, 'usernamestring', 'passwordstring'
      $scope.saltApiLoginPromise.success (data, status, headers, config) ->
          console.log("SaltApi login success")
          $scope.result = data
          return true
   */

  saltApiSrvc.factory("SaltApiEvtSrvc", [
    '$rootScope', '$http', 'AppPref', 'SessionStore', '$q', 'ErrorReporter', function($rootScope, $http, AppPref, SessionStore, $q, ErrorReporter) {
      var base, counter, defer, onError, onMessage, onOpen, saltApi, servicer, sse;
      saltApi = AppPref.get('saltApi');
      if (saltApi.scheme || saltApi.host || saltApi.port) {
        if (!saltApi.scheme) {
          saltApi.scheme = "http";
        }
        if (!saltApi.host) {
          saltApi.host = "localhost";
        }
        if (saltApi.port) {
          saltApi.port = ":" + saltApi.port;
        }
        base = "" + saltApi.scheme + "://" + saltApi.host + saltApi.port + saltApi.prefix;
      } else {
        base = "" + saltApi.prefix;
      }
      delete $http.defaults.headers.common['X-Requested-With'];
      $http.defaults.useXDomain = true;
      defer = null;
      sse = null;
      counter = 0;
      onError = function(event) {
        var retries;
        counter = counter + 1;
        retries = AppPref.get('SseRetries') || 50;
        if (counter > retries) {
          ErrorReporter.addAlert('danger', "Event Stream Connection Lost! Please check server connection and refresh the page.");
          servicer.close();
          $rootScope.$apply();
        }
        if (defer != null) {
          console.log("SSE Open Error");
          $rootScope.$apply(defer.reject("SSE Errored"));
          defer = null;
        }
        return true;
      };
      onOpen = function(event) {
        if (defer != null) {
          $rootScope.$apply(defer.resolve(event));
          defer = null;
        }
        return true;
      };
      onMessage = function(event) {
        var data;
        data = angular.fromJson(event.data);
        $rootScope.$apply(typeof servicer.process === "function" ? servicer.process(data) : void 0);
        return true;
      };
      servicer = {
        close: function($scope) {
          if (sse != null) {
            sse.close();
          }
          sse = null;
          return this.active = false;
        },
        events: function($scope, process, tag) {
          var token, url, _ref;
          token = (_ref = SessionStore.get('saltApiAuth')) != null ? _ref.token : void 0;
          tag = tag != null ? encodeURIComponent(tag) : "";
          url = "" + base + "/event/" + token;
          sse = new EventSource(url);
          sse.onerror = onError;
          sse.onopen = onOpen;
          sse.onmessage = onMessage;
          this.process = process;
          this.active = true;
          defer = $q.defer();
          return defer.promise;
        }
      };
      return servicer;
    }
  ]);

}).call(this);


text:
class DateManager
  VERSION = "0.0.1"
end


text:
	#define CMP_OPENCL 1
#elif defined(__CUDACC__)
	#define CMP_CUDA 1
#elif defined(__cplusplus)
	#define CMP_CPP 1
#elif defined(D3DX_VERSION)
	#define CMP_HLSL 1
#endif

// Prologue check
#if defined(CMP_CPP) || defined(CMP_HLSL) || defined(CMP_WITHIN_PROLOGUE)

//
// Include the necessary platform header
//
#if defined(CMP_OPENCL)
	#include "Platform_OpenCL.h"
#elif defined(CMP_CUDA)
	#include "Platform_CUDA.h"
#elif defined(CMP_CPP)
	#include "Platform_CPlusPlus.h"
#endif

// Temporary location until HLSL gets its own file
#ifdef CMP_HLSL
	#define cmp_out out
	#define cmp_device_fn
#else
	#define cmp_out
#endif

#endif	// Prologue check

#endif	// INCLUDED_CBPP_PLATFORM_H


text:
import org.lwjgl.opengl.GL11;
import org.newdawn.slick.Color;
import org.newdawn.slick.TrueTypeFont;

import java.awt.Font;

/**
 * @author Chris Jenkins
 * @date 24/02/2014
 * @brief extends the AbstractGameInfo class to set fonts and board messages
 * @details draws the messages on the board which are rendered. including the player state and scoring
 * Created by Chris on 24/02/14.
 */
public class OthGameInfo extends AbstractGameInfo{

    private TrueTypeFont m_fontX;
    private TrueTypeFont m_fontError;
    private Font m_font;
    private String m_p1Counters;
    private String m_p2Counters;
    private static final int FONT_SIZE = 30;
    private static final int PLAYER_1 = 1;
    private static final int X_PIXEL_130 = 130;
    private static final int Y_PIXEL_10 = 10;
    private static final int X_PIXEL_200 = 200;
    private static final int Y_PIXEL_380 = 380;
    private static final int X_PIXEL_400 = 400;
    private static final int Y_PIXEL_200 = 200;
    private static final int Y_PIXEL_150 = 150;
    private static final int Y_PIXEL_100 = 100;
    private static final int PLAYER_2 = 2;

    public OthGameInfo(){
        m_font = new Font("Arial", Font.BOLD, FONT_SIZE);

    }

    public void setInvalidMoveMessage(){
        m_fontError = new TrueTypeFont(m_font, false);
        m_fontError.drawString(X_PIXEL_130, Y_PIXEL_10, "Invalid move");
    }

    public void setP1WinsMessage(){
        GL11.glEnable(GL11.GL_TEXTURE_2D);
        m_fontX = new TrueTypeFont(m_font, false);
        m_fontX.drawString(X_PIXEL_200, Y_PIXEL_380, "Black Wins!");
        GL11.glDisable(GL11.GL_TEXTURE_2D);
    }

    public void setP2WinsMessage(){
        GL11.glEnable(GL11.GL_TEXTURE_2D);
        m_fontX = new TrueTypeFont(m_font, false);
        m_fontX.drawString(X_PIXEL_200, Y_PIXEL_380, "White Wins!");
        GL11.glDisable(GL11.GL_TEXTURE_2D);
    }

    public void draw(AbstractGame game){

    	m_p1Counters = Integer.toString(game.getCounters1());
    	m_p2Counters = Integer.toString(game.getCounters2());
        String turnText = "";
        GL11.glEnable(GL11.GL_TEXTURE_2D);
        Color.white.bind();
        m_fontX = new TrueTypeFont(m_font, false);

        if(game.getTurn() == PLAYER_1){
           turnText = "Black's turn";
        }else if(game.getTurn() == PLAYER_2){
           turnText = "White's turn";
        }
        m_fontX.drawString(X_PIXEL_400, Y_PIXEL_200, turnText);

        m_fontX.drawString(X_PIXEL_400, Y_PIXEL_100, "Black: " + m_p1Counters);
        m_fontX.drawString(X_PIXEL_400, Y_PIXEL_150, "White: " + m_p2Counters);

        GL11.glDisable(GL11.GL_TEXTURE_2D);

    }

}


text:
Download Handouts:
 - Products__hw1.2_m102_529e39a8e2d42347509fb3f0.json

Download the handout. Take a look at its content.

Now, import its contents into MongoDB, into a database called "pcat" and a collection called "products". Use the mongoimport utility to do this.

When done, run this query in the mongo shell:

    db.products.find( { type : "case" } ).count()

What's the result?

Enter answer here:

  Click here for the solution

3


text:
using System.Reflection;

[assembly: AssemblyTitle("Affecto.IdentityManagement.Store.Mocking")]
[assembly: AssemblyDescription("Identity Management store layer using Effort mock database.")]
[assembly: AssemblyProduct("Affecto.IdentityManagement")]
[assembly: AssemblyCompany("Affecto")]

[assembly: AssemblyVersion("8.0.4.0")]
[assembly: AssemblyFileVersion("8.0.4.0")]

// This version is used by NuGet:
[assembly: AssemblyInformationalVersion("8.0.4")]


text:
import numpy
from numpy.testing import assert_almost_equal
from keras.layers import Input
from keras.models import Model

from deep_qa.layers.backend import AddMask, ReplaceMaskedValues

class TestReplaceMaskedValues:
    def test_call_works_on_simple_input(self):
        input_length = 3
        input_layer = Input(shape=(input_length,), dtype='float32')
        masked = AddMask(2)(input_layer)
        replaced = ReplaceMaskedValues(4)(masked)
        model = Model(inputs=[input_layer], outputs=[replaced])
        input_tensor = numpy.asarray([[2, 5, 2], [2, -4, -2]])
        replaced_tensor = model.predict([input_tensor])
        assert_almost_equal(replaced_tensor, numpy.asarray([[4, 5, 4], [4, -4, -2]]))


text:
alias dl="docker ps -l -q"
PROJECT_CODE=$1;

mkdir -p containers/$PROJECT_CODE
cp supervisord.conf containers/$PROJECT_CODE/
#docker build -t odhk.dev.code4.hk:0.1 - < Dockerfile_project

#TODO
#build base iamge if not exists
# docker build -t open-platform-hk/bootstrap:0.1 - < Dockerfile_base

#idealy shoudl genearte from host and inject to container, but docker insert don't support yet
#https://github.com/dotcloud/docker/issues/905

#create docker project
ssh-keygen -f ./containers/$PROJECT_CODE/id_rsa_$PROJECT_CODE -N ''
cd ./containers/$PROJECT_CODE
../../create_docker.py --code $PROJECT_CODE

chown -R ubuntu .

service nginx reload

##For Ops
##Distribute the key

##Ensure Amazon open 2222

##For Devs
#ssh -i /path/to/id_rsa root@demo.dev.code4.hk -p 2222


text:
package be.ehb.model.mail;

/**
 * @author Patrick Van den Bussche
 * @since 2017
 */
public class PrefillTimeSheetMailBean extends BaseMailBean {

    private String userName;
    private String prefillWorklog;

    public String getUserName() {
        return userName;
    }

    public void setUserName(String userName) {
        this.userName = userName;
    }

    public String getPrefillWorklog() {
        return prefillWorklog;
    }

    public void setPrefillWorklog(String prefillWorklog) {
        this.prefillWorklog = prefillWorklog;
    }

    @Override
    public String toString() {
        return "PrefillTimeSheetMailBean{" +
                "prefillWorklog='" + prefillWorklog + '\'' +
                '}';
    }
}


text:
package org.chai.kevin.survey;

import java.util.HashMap;
import java.util.Map;

import org.chai.kevin.form.FormSkipRule;
import org.chai.kevin.form.FormValidationRule;

public class SurveyCopy<T> {

	private T copy;
	private Map<FormValidationRule, Long> unchangedValidationRules = new HashMap<FormValidationRule, Long>();
	private Map<FormSkipRule, Long> unchangedSkipRules = new HashMap<FormSkipRule, Long>();

	public SurveyCopy(T copy) {
		this.copy = copy;
	}

	public SurveyCopy(T copy, Map<FormValidationRule, Long> unchangedValidationRules, Map<FormSkipRule, Long> unchangedSkipRules) {
		this.copy = copy;
		this.unchangedValidationRules = unchangedValidationRules;
		this.unchangedSkipRules = unchangedSkipRules;
	}

	public T getCopy() {
		return copy;
	}

	public Map<FormValidationRule, Long> getUnchangedValidationRules() {
		return unchangedValidationRules;
	}

	public Map<FormSkipRule, Long> getUnchangedSkipRules() {
		return unchangedSkipRules;
	}

}


text:
package gwt.material.design.client.custom;

import gwt.material.design.client.ui.MaterialLabel;
import gwt.material.design.client.ui.MaterialLink;
import gwt.material.design.client.ui.MaterialModal;
import gwt.material.design.client.ui.MaterialPanel;

import com.google.gwt.core.client.GWT;
import com.google.gwt.event.dom.client.ClickEvent;
import com.google.gwt.uibinder.client.UiBinder;
import com.google.gwt.uibinder.client.UiField;
import com.google.gwt.uibinder.client.UiHandler;
import com.google.gwt.user.client.ui.Composite;
import com.google.gwt.user.client.ui.HTMLPanel;
import com.google.gwt.user.client.ui.Widget;

public class MaterialWindowHeader extends Composite {

	private static MaterialWindowHeaderUiBinder uiBinder = GWT.create(MaterialWindowHeaderUiBinder.class);

	interface MaterialWindowHeaderUiBinder extends UiBinder<Widget, MaterialWindowHeader> {
	}

	private HTMLPanel windowPanel;
	@UiField MaterialLabel lblTitle;
	@UiField MaterialPanel headerPanel;
	@UiField MaterialLink btnRestore, btnMaximize, btnClose;

	public MaterialWindowHeader(HTMLPanel windowPanel, String title, String headerColor) {
		initWidget(uiBinder.createAndBindUi(this));
		this.windowPanel = windowPanel;
		lblTitle.setText(title);
		headerPanel.addStyleName(headerColor);
		btnRestore.setVisible(false);
	}

	@UiHandler("btnMaximize")
	public void onMaximize(ClickEvent e){
		windowPanel.addStyleName("material-window-maximize");
		btnMaximize.setVisible(false);
		btnRestore.setVisible(true);
	}

	@UiHandler("btnRestore")
	public void onRestore(ClickEvent e){
		windowPanel.removeStyleName("material-window-maximize");
		btnMaximize.setVisible(true);
		btnRestore.setVisible(false);
	}

	@UiHandler("btnClose")
	public void onClose(ClickEvent e){
		MaterialModal.closeModal();
	}
}