text:
// Copyright 2006 The Closure Library Authors. All Rights Reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
//      http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS-IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.

/**
 * @fileoverview Constant declarations for common key codes.
 *
 * @author eae@google.com (Emil A Eklund)
 * @see ../demos/keyhandler.html
 */

goog.provide('goog.events.KeyCodes');

goog.require('goog.userAgent');

/**
 * Key codes for common characters.
 *
 * This list is not localized and therefore some of the key codes are not
 * correct for non US keyboard layouts. See comments below.
 *
 * @enum {number}
 */
goog.events.KeyCodes = {
  WIN_KEY_FF_LINUX: 0,
  MAC_ENTER: 3,
  BACKSPACE: 8,
  TAB: 9,
  NUM_CENTER: 12,  // NUMLOCK on FF/Safari Mac
  ENTER: 13,
  SHIFT: 16,
  CTRL: 17,
  ALT: 18,
  PAUSE: 19,
  CAPS_LOCK: 20,
  ESC: 27,
  SPACE: 32,
  PAGE_UP: 33,     // also NUM_NORTH_EAST
  PAGE_DOWN: 34,   // also NUM_SOUTH_EAST
  END: 35,         // also NUM_SOUTH_WEST
  HOME: 36,        // also NUM_NORTH_WEST
  LEFT: 37,        // also NUM_WEST
  UP: 38,          // also NUM_NORTH
  RIGHT: 39,       // also NUM_EAST
  DOWN: 40,        // also NUM_SOUTH
  PRINT_SCREEN: 44,
  INSERT: 45,      // also NUM_INSERT
  DELETE: 46,      // also NUM_DELETE
  ZERO: 48,
  ONE: 49,
  TWO: 50,
  THREE: 51,
  FOUR: 52,
  FIVE: 53,
  SIX: 54,
  SEVEN: 55,
  EIGHT: 56,
  NINE: 57,
  FF_SEMICOLON: 59, // Firefox (Gecko) fires this for semicolon instead of 186
  FF_EQUALS: 61, // Firefox (Gecko) fires this for equals instead of 187
  FF_DASH: 173, // Firefox (Gecko) fires this for dash instead of 189
  QUESTION_MARK: 63, // needs localization
  A: 65,
  B: 66,
  C: 67,
  D: 68,
  E: 69,
  F: 70,
  G: 71,
  H: 72,
  I: 73,
  J: 74,
  K: 75,
  L: 76,
  M: 77,
  N: 78,
  O: 79,
  P: 80,
  Q: 81,
  R: 82,
  S: 83,
  T: 84,
  U: 85,
  V: 86,
  W: 87,
  X: 88,
  Y: 89,
  Z: 90,
  META: 91, // WIN_KEY_LEFT
  WIN_KEY_RIGHT: 92,
  CONTEXT_MENU: 93,
  NUM_ZERO: 96,
  NUM_ONE: 97,
  NUM_TWO: 98,
  NUM_THREE: 99,
  NUM_FOUR: 100,
  NUM_FIVE: 101,
  NUM_SIX: 102,
  NUM_SEVEN: 103,
  NUM_EIGHT: 104,
  NUM_NINE: 105,
  NUM_MULTIPLY: 106,
  NUM_PLUS: 107,
  NUM_MINUS: 109,
  NUM_PERIOD: 110,
  NUM_DIVISION: 111,
  F1: 112,
  F2: 113,
  F3: 114,
  F4: 115,
  F5: 116,
  F6: 117,
  F7: 118,
  F8: 119,
  F9: 120,
  F10: 121,
  F11: 122,
  F12: 123,
  NUMLOCK: 144,
  SCROLL_LOCK: 145,

  // OS-specific media keys like volume controls and browser controls.
  FIRST_MEDIA_KEY: 166,
  LAST_MEDIA_KEY: 183,

  SEMICOLON: 186,            // needs localization
  DASH: 189,                 // needs localization
  EQUALS: 187,               // needs localization
  COMMA: 188,                // needs localization
  PERIOD: 190,               // needs localization
  SLASH: 191,                // needs localization
  APOSTROPHE: 192,           // needs localization
  TILDE: 192,                // needs localization
  SINGLE_QUOTE: 222,         // needs localization
  OPEN_SQUARE_BRACKET: 219,  // needs localization
  BACKSLASH: 220,            // needs localization
  CLOSE_SQUARE_BRACKET: 221, // needs localization
  WIN_KEY: 224,
  MAC_FF_META: 224, // Firefox (Gecko) fires this for the meta key instead of 91
  MAC_WK_CMD_LEFT: 91,  // WebKit Left Command key fired, same as META
  MAC_WK_CMD_RIGHT: 93, // WebKit Right Command key fired, different from META
  WIN_IME: 229,

  // We've seen users whose machines fire this keycode at regular one
  // second intervals. The common thread among these users is that
  // they're all using Dell Inspiron laptops, so we suspect that this
  // indicates a hardware/bios problem.
  // http://en.community.dell.com/support-forums/laptop/f/3518/p/19285957/19523128.aspx
  PHANTOM: 255
};

/**
 * Returns true if the event contains a text modifying key.
 * @param {goog.events.BrowserEvent} e A key event.
 * @return {boolean} Whether it's a text modifying key.
 */
goog.events.KeyCodes.isTextModifyingKeyEvent = function(e) {
  if (e.altKey && !e.ctrlKey ||
      e.metaKey ||
      // Function keys don't generate text
      e.keyCode >= goog.events.KeyCodes.F1 &&
      e.keyCode <= goog.events.KeyCodes.F12) {
    return false;
  }

  // The following keys are quite harmless, even in combination with
  // CTRL, ALT or SHIFT.
  switch (e.keyCode) {
    case goog.events.KeyCodes.ALT:
    case goog.events.KeyCodes.CAPS_LOCK:
    case goog.events.KeyCodes.CONTEXT_MENU:
    case goog.events.KeyCodes.CTRL:
    case goog.events.KeyCodes.DOWN:
    case goog.events.KeyCodes.END:
    case goog.events.KeyCodes.ESC:
    case goog.events.KeyCodes.HOME:
    case goog.events.KeyCodes.INSERT:
    case goog.events.KeyCodes.LEFT:
    case goog.events.KeyCodes.MAC_FF_META:
    case goog.events.KeyCodes.META:
    case goog.events.KeyCodes.NUMLOCK:
    case goog.events.KeyCodes.NUM_CENTER:
    case goog.events.KeyCodes.PAGE_DOWN:
    case goog.events.KeyCodes.PAGE_UP:
    case goog.events.KeyCodes.PAUSE:
    case goog.events.KeyCodes.PHANTOM:
    case goog.events.KeyCodes.PRINT_SCREEN:
    case goog.events.KeyCodes.RIGHT:
    case goog.events.KeyCodes.SCROLL_LOCK:
    case goog.events.KeyCodes.SHIFT:
    case goog.events.KeyCodes.UP:
    case goog.events.KeyCodes.WIN_KEY:
    case goog.events.KeyCodes.WIN_KEY_RIGHT:
      return false;
    case goog.events.KeyCodes.WIN_KEY_FF_LINUX:
      return !goog.userAgent.GECKO;
    default:
      return e.keyCode < goog.events.KeyCodes.FIRST_MEDIA_KEY ||
          e.keyCode > goog.events.KeyCodes.LAST_MEDIA_KEY;
  }
};

/**
 * Returns true if the key fires a keypress event in the current browser.
 *
 * Accoridng to MSDN [1] IE only fires keypress events for the following keys:
 * - Letters: A - Z (uppercase and lowercase)
 * - Numerals: 0 - 9
 * - Symbols: ! @ # $ % ^ & * ( ) _ - + = < [ ] { } , . / ? \ | ' ` " ~
 * - System: ESC, SPACEBAR, ENTER
 *
 * That's not entirely correct though, for instance there's no distinction
 * between upper and lower case letters.
 *
 * [1] http://msdn2.microsoft.com/en-us/library/ms536939(VS.85).aspx)
 *
 * Safari is similar to IE, but does not fire keypress for ESC.
 *
 * Additionally, IE6 does not fire keydown or keypress events for letters when
 * the control or alt keys are held down and the shift key is not. IE7 does
 * fire keydown in these cases, though, but not keypress.
 *
 * @param {number} keyCode A key code.
 * @param {number=} opt_heldKeyCode Key code of a currently-held key.
 * @param {boolean=} opt_shiftKey Whether the shift key is held down.
 * @param {boolean=} opt_ctrlKey Whether the control key is held down.
 * @param {boolean=} opt_altKey Whether the alt key is held down.
 * @return {boolean} Whether it's a key that fires a keypress event.
 */
goog.events.KeyCodes.firesKeyPressEvent = function(keyCode, opt_heldKeyCode,
    opt_shiftKey, opt_ctrlKey, opt_altKey) {
  if (!goog.userAgent.IE &&
      !(goog.userAgent.WEBKIT && goog.userAgent.isVersionOrHigher('525'))) {
    return true;
  }

  if (goog.userAgent.MAC && opt_altKey) {
    return goog.events.KeyCodes.isCharacterKey(keyCode);
  }

  // Alt but not AltGr which is represented as Alt+Ctrl.
  if (opt_altKey && !opt_ctrlKey) {
    return false;
  }

  // handle consequent CTRL-something combos while CTRL is left pressed
  // problem occured in webkit but it seems it is already fixed???
  if (goog.userAgent.WEBKIT && opt_ctrlKey) { return false; }

  // Saves Ctrl or Alt + key for IE and WebKit 525+, which won't fire keypress.
  // Non-IE browsers and WebKit prior to 525 won't get this far so no need to
  // check the user agent.
  if (goog.isNumber(opt_heldKeyCode)) {
    opt_heldKeyCode = goog.events.KeyCodes.normalizeKeyCode(opt_heldKeyCode);
  }
  if (!opt_shiftKey &&
      (opt_heldKeyCode == goog.events.KeyCodes.CTRL ||
       opt_heldKeyCode == goog.events.KeyCodes.ALT ||
       goog.userAgent.MAC &&
       opt_heldKeyCode == goog.events.KeyCodes.META)) {
    return false;
  }

  // Some keys with Ctrl/Shift do not issue keypress in WEBKIT.
  if (goog.userAgent.WEBKIT && opt_ctrlKey && opt_shiftKey) {
    switch (keyCode) {
      case goog.events.KeyCodes.BACKSLASH:
      case goog.events.KeyCodes.OPEN_SQUARE_BRACKET:
      case goog.events.KeyCodes.CLOSE_SQUARE_BRACKET:
      case goog.events.KeyCodes.TILDE:
      case goog.events.KeyCodes.SEMICOLON:
      case goog.events.KeyCodes.DASH:
      case goog.events.KeyCodes.EQUALS:
      case goog.events.KeyCodes.COMMA:
      case goog.events.KeyCodes.PERIOD:
      case goog.events.KeyCodes.SLASH:
      case goog.events.KeyCodes.APOSTROPHE:
      case goog.events.KeyCodes.SINGLE_QUOTE:
        return false;
    }
  }

  // When Ctrl+<somekey> is held in IE, it only fires a keypress once, but it
  // continues to fire keydown events as the event repeats.
  if (goog.userAgent.IE && opt_ctrlKey && opt_heldKeyCode == keyCode) {
    return false;
  }

  switch (keyCode) {
    case goog.events.KeyCodes.ENTER:
      // IE9 does not fire KEYPRESS on ENTER.
      return !(goog.userAgent.IE && goog.userAgent.isDocumentModeOrHigher(9));
    case goog.events.KeyCodes.ESC:
      return !goog.userAgent.WEBKIT;
  }

  return goog.events.KeyCodes.isCharacterKey(keyCode);
};

/**
 * Returns true if the key produces a character.
 * This does not cover characters on non-US keyboards (Russian, Hebrew, etc.).
 *
 * @param {number} keyCode A key code.
 * @return {boolean} Whether it's a character key.
 */
goog.events.KeyCodes.isCharacterKey = function(keyCode) {
  if (keyCode >= goog.events.KeyCodes.ZERO &&
      keyCode <= goog.events.KeyCodes.NINE) {
    return true;
  }

  if (keyCode >= goog.events.KeyCodes.NUM_ZERO &&
      keyCode <= goog.events.KeyCodes.NUM_MULTIPLY) {
    return true;
  }

  if (keyCode >= goog.events.KeyCodes.A &&
      keyCode <= goog.events.KeyCodes.Z) {
    return true;
  }

  // Safari sends zero key code for non-latin characters.
  if (goog.userAgent.WEBKIT && keyCode == 0) {
    return true;
  }

  switch (keyCode) {
    case goog.events.KeyCodes.SPACE:
    case goog.events.KeyCodes.QUESTION_MARK:
    case goog.events.KeyCodes.NUM_PLUS:
    case goog.events.KeyCodes.NUM_MINUS:
    case goog.events.KeyCodes.NUM_PERIOD:
    case goog.events.KeyCodes.NUM_DIVISION:
    case goog.events.KeyCodes.SEMICOLON:
    case goog.events.KeyCodes.FF_SEMICOLON:
    case goog.events.KeyCodes.DASH:
    case goog.events.KeyCodes.EQUALS:
    case goog.events.KeyCodes.FF_EQUALS:
    case goog.events.KeyCodes.COMMA:
    case goog.events.KeyCodes.PERIOD:
    case goog.events.KeyCodes.SLASH:
    case goog.events.KeyCodes.APOSTROPHE:
    case goog.events.KeyCodes.SINGLE_QUOTE:
    case goog.events.KeyCodes.OPEN_SQUARE_BRACKET:
    case goog.events.KeyCodes.BACKSLASH:
    case goog.events.KeyCodes.CLOSE_SQUARE_BRACKET:
      return true;
    default:
      return false;
  }
};

/**
 * Normalizes key codes from OS/Browser-specific value to the general one.
 * @param {number} keyCode The native key code.
 * @return {number} The normalized key code.
 */
goog.events.KeyCodes.normalizeKeyCode = function(keyCode) {
  if (goog.userAgent.GECKO) {
    return goog.events.KeyCodes.normalizeGeckoKeyCode(keyCode);
  } else if (goog.userAgent.MAC && goog.userAgent.WEBKIT) {
    return goog.events.KeyCodes.normalizeMacWebKitKeyCode(keyCode);
  } else {
    return keyCode;
  }
};

/**
 * Normalizes key codes from their Gecko-specific value to the general one.
 * @param {number} keyCode The native key code.
 * @return {number} The normalized key code.
 */
goog.events.KeyCodes.normalizeGeckoKeyCode = function(keyCode) {
  switch (keyCode) {
    case goog.events.KeyCodes.FF_EQUALS:
      return goog.events.KeyCodes.EQUALS;
    case goog.events.KeyCodes.FF_SEMICOLON:
      return goog.events.KeyCodes.SEMICOLON;
    case goog.events.KeyCodes.FF_DASH:
      return goog.events.KeyCodes.DASH;
    case goog.events.KeyCodes.MAC_FF_META:
      return goog.events.KeyCodes.META;
    case goog.events.KeyCodes.WIN_KEY_FF_LINUX:
      return goog.events.KeyCodes.WIN_KEY;
    default:
      return keyCode;
  }
};

/**
 * Normalizes key codes from their Mac WebKit-specific value to the general one.
 * @param {number} keyCode The native key code.
 * @return {number} The normalized key code.
 */
goog.events.KeyCodes.normalizeMacWebKitKeyCode = function(keyCode) {
  switch (keyCode) {
    case goog.events.KeyCodes.MAC_WK_CMD_RIGHT:  // 93
      return goog.events.KeyCodes.META;          // 91
    default:
      return keyCode;
  }
};


text:
package Slackware::Search::ViewSerie;

use strict;
use warnings;

use base 'Slackware::Search::MainWeb';
use CGI::Application::Plugin::Routes;

sub setup {
	my $self = shift;
	$self->start_mode('view_serie');
	$self->error_mode('error');
	$self->header_props(-type => 'text/html', -charset => 'UTF-8');
	$self->routes_root('/');
	$self->routes([
			'' => 'noview',
			'/view/:slackver/:category/:serie' => 'view_serie',
	]);
} # sub setup

sub cgiapp_init {
	my $self = shift;

	$self->SUPER::cgiapp_prerun;
} # sub cgiapp_init

sub view_serie {
	my $self = shift;
	my $dbh = $self->dbh;
	my $q = $self->query;
	my $slackver = $q->param('slackver');
	my $category = $q->param('category');
	my $serie = $q->param('serie');
	my $validSlackver = $self->_validate_slackver($slackver);
	unless ($validSlackver) {
		return $self->error("Slackversion is garbage.",
			'/cgi-bin/search.cgi');
	}
	my $validCategory = $self->_validate_category($category);
	unless ($validCategory) {
		my $backLink = sprintf("/cgi-bin/slackver.cgi/view/%s", $slackver);
		return $self->error("Category is garbage.", $backLink);
	}
	my $serieDec = $self->_url_decode($serie);
	$serieDec =~ s/@+/\//g;
	my $validSerie = $self->_validate_serie($serieDec);
	unless ($validSerie) {
		my $backLink = sprintf("/cgi-bin/category.cgi/view/%s/%s",
			$slackver, $category);
		return $self->error("Serie is garbage.", $backLink);
	}
	my $idSlackver = $self->_get_slackversion_id($slackver);
	unless ($idSlackver) {
		return $self->error("Slackversion is not in DB.",
			'/cgi-bin/search.cgi');
	}
	my $idCategory = $self->_get_category_id($category);
	unless ($idCategory) {
		my $backLink = sprintf("/cgi-bin/slackver.cgi/view/%s", $slackver);
		return $self->error("Category is not in DB.", $backLink);
	}
	my $idSerie = $self->_get_serie_id($serieDec);
	unless ($idSerie) {
		my $backLink = sprintf("/cgi-bin/category.cgi/view/%s/%s",
			$slackver, $category);
		return $self->error("Serie is not in DB.", $backLink);
	}
	my $sql100 = sprintf("SELECT package_name FROM package WHERE id_package
		IN  (SELECT id_package FROM packages WHERE id_slackversion = %i AND
		id_category = %i AND id_serie = %i) ORDER BY package_name ASC;",
		$idSlackver, $idCategory,
		$idSerie);
	my $result100 = $dbh->selectall_arrayref($sql100, { Slice => {} });
	unless ($result100) {
		my $errorMsg = sprintf("Unable to select packages under '%s/%s/%s'.",
			$slackver, $category, $serie);
		my $backLink = sprintf("/cgi-bin/category.cgi/view/%s/%s",
			$slackver, $category);
		return $self->error($errorMsg, $backLink);
	}

	if (@$result100 == 0) {
		my $errorMsg = sprintf("Nothing found under '%s/%s/%s'.", $slackver,
			$category, $serie);
		my $backLink = sprintf("/cgi-bin/category.cgi/view/%s/%s",
			$slackver, $category);
		return $self->error($errorMsg, $backLink);
	}

	my @items;
	my $levelUpLink = sprintf("..
",
		$slackver, $category);
	my %levelUp = (VALUE => $levelUpLink);
	push(@items, \%levelUp);
	for my $row (@$result100) {
		my $link = sprintf("/cgi-bin/package.cgi/view/%s/%s/%s/%s",
			$slackver, $category, $serie, $row->{package_name});
		my $HTML = sprintf("%s
", $link,
			$row->{package_name});
		my %item = (VALUE => $HTML);
		push(@items, \%item);
	}
	my $template = $self->load_tmpl("index.htm");
	my $title = sprintf("Browsing %s/%s/%s", $slackver, $category, $serie);
	$template->param(TITLE => $title);
	$template->param(SLACKVERBRWS => 1);
	my $slackverLink = sprintf("%s",
		$slackver, $slackver);
	my $categoryLink = sprintf("%s",
		$slackver, $category, $category);
	my $navigation = sprintf("%s/%s/%s/", $slackverLink, $categoryLink,
		$serieDec);
	$template->param(NAVIGATION => $navigation);
	$template->param(ITEMS => \@items);
	my $idSlackverStable = $self->_get_slackversion_idStable();
	$template->param(SVERSTABLE => $idSlackverStable);
	my $slackverStable = $self->_get_slackversion_name($idSlackverStable);
	$template->param(SVERNAME => $slackverStable);
	return $template->output();
}

1;

redpajama_set_name: RedPajamaGithub


text:
using System;
using System.Globalization;
using System.Runtime.CompilerServices;
using System.Threading;

namespace UniqueIdGenerator.Net
{
    /// <summary>
    /// Generates new unique ids based on Twitter's Snowflake algorithm.
    /// This class is not thread-safe.
    /// </summary>
    public class Generator
    {
        // should be between 40 (34 years) and 42 (139 years)
        internal const int NumberOfTimeBits = 42;

        // should be between 0 (single generator) and 10 (1024 generators)
        internal const int NumberOfGeneratorIdBits = 9;

        // should be 10 at least (4096 unique ids per millisecond per generator)
        internal const int NumberOfSequenceBits = 64 - NumberOfTimeBits - NumberOfGeneratorIdBits;

        private readonly byte[] _buffer = new byte[8];
        private readonly byte[] _timeBytes = new byte[8];
        private readonly byte[] _idBytes = new byte[2];
        private readonly byte[] _sequenceBytes = new byte[2];
        private readonly int _maxSequence = (int)Math.Pow(2, NumberOfSequenceBits) - 1;
        private readonly DateTime _start;

        private short _sequence;
        private long _previousTime;

        /// <summary>
        /// Instantiate the generator. Each Generator should have its own ID, so you can
        /// use multiple Generator instances in a cluster. All generated IDs are unique
        /// provided the start date newer changes. I recommend to choose January 1, 2013.
        /// </summary>
        public Generator(short generatorId, DateTime start)
        {
            if (generatorId < 0 || generatorId >= Math.Pow(2, NumberOfGeneratorIdBits))
            {
                var msg = string.Format(
                    CultureInfo.InvariantCulture,
                    "generator id must be between 0 (inclusive) and {0} (exclusive).",
                    Math.Pow(2, NumberOfGeneratorIdBits));
                throw new ArgumentException(msg, "generatorId");
            }
            if (start > DateTime.Today)
            {
                throw new ArgumentException("start date must not be in the future.", "start");
            }

            CalculateIdBytes(generatorId);
            _start = start;
        }

        /// <summary>
        /// Can generate up to 4096 different IDs per millisecond.
        /// </summary>
        public string Next()
        {
            SpinToNextSequence();
            WriteValuesToByteArray(_buffer, _previousTime, _sequence);

            return Convert.ToBase64String(_buffer, Base64FormattingOptions.None);
        }

        public ulong NextLong()
        {
            SpinToNextSequence();
            WriteValuesToByteArray(_buffer, _previousTime, _sequence);

            Array.Reverse(_buffer);
            return BitConverter.ToUInt64(_buffer, 0);
        }

        internal unsafe void WriteValuesToByteArray(byte[] target, long time, short sequence)
        {
            fixed (byte* arrayPointer = target)
            {
                *(long*)arrayPointer = 0;
            }

            fixed (byte* arrayPointer = _timeBytes)
            {
                *(long*)arrayPointer = time << (64 - NumberOfTimeBits);
            }

            fixed (byte* arrayPointer = _sequenceBytes)
            {
                *(short*)arrayPointer = sequence;
            }

            WriteValuesToByteArray(target, _timeBytes, _idBytes, _sequenceBytes);
        }

        private unsafe void CalculateIdBytes(short id)
        {
            fixed (byte* arrayPointer = _idBytes)
            {
                *(short*)arrayPointer = (short)(id << (8 - ((64 - NumberOfSequenceBits) % 8)));
            }
        }

        [MethodImpl(MethodImplOptions.AggressiveInlining)]
        private void WriteValuesToByteArray(byte[] target, byte[] time, byte[] id, byte[] sequence)
        {
            ////                                                 1234567890123456789012
            //// time: 1111111111111111111111111111111111111111110000
            //// id:                                           0011111111110000
            //// seq:                                                  0000111111111111
            ////
            ////       000000000000000100010111101010100001000010 0000001011 000000000000
            //// pos:  0         1         2         3         4         5         6
            //// byte: 0       1       2       3       4       5       6       7

            target[0] = (byte)(target[0] | time[7]);
            target[1] = (byte)(target[1] | time[6]);
            target[2] = (byte)(target[2] | time[5]);
            target[3] = (byte)(target[3] | time[4]);
            target[4] = (byte)(target[4] | time[3]);
            target[5] = (byte)(target[5] | time[2]);
            target[6] = (byte)(target[6] | time[1]);
            target[7] = (byte)(target[7] | time[0]);

            target[5] = (byte)(target[5] | id[1]);
            target[6] = (byte)(target[6] | id[0]);

            target[6] = (byte)(target[6] | sequence[1]);
            target[7] = (byte)(target[7] | sequence[0]);
        }

        private void SpinToNextSequence()
        {
            var time = GetTime();

            while (time == _previousTime && _sequence >= _maxSequence)
            {
                Thread.Sleep(0);
                time = GetTime();
            }

            _sequence = time == _previousTime ? (short)(_sequence + 1) : (short)0;
            _previousTime = time;
        }

        [MethodImpl(MethodImplOptions.AggressiveInlining)]
        private long GetTime()
        {
            return (long)(DateTime.UtcNow - _start).TotalMilliseconds;
        }
    }
}


text:
"""The setup script."""

from setuptools import setup, find_packages

with open('README.rst') as readme_file:
    readme = readme_file.read()

with open('HISTORY.rst') as history_file:
    history = history_file.read()

requirements = [
    'Click>=6.0',
    # TODO: put package requirements here
]

setup_requirements = [
    'pytest-runner',
    # TODO: put setup requirements (distutils extensions, etc.) here
]

test_requirements = [
    'pytest',
    # TODO: put package test requirements here
]

setup(
    name='microbial_ai',
    version='0.1.0',
    description=("Microbial growth simulation incorporating adaptation "
                 "through reinforcement learning"),
    long_description=readme + '\n\n' + history,
    author="Dileep Kishore",
    author_email='dkishore@bu.edu',
    url='https://github.com/dileep-kishore/microbial_ai',
    packages=find_packages(include=['microbial_ai']),
    entry_points={
        'console_scripts': [
            'microbial_ai=microbial_ai.cli:main'
        ]
    },
    include_package_data=True,
    install_requires=requirements,
    license="MIT license",
    zip_safe=False,
    keywords='microbial_ai',
    classifiers=[
        'Development Status :: 2 - Pre-Alpha',
        'Intended Audience :: Developers',
        'License :: OSI Approved :: MIT License',
        'Natural Language :: English',
        'Programming Language :: Python :: 3.6',
    ],
    test_suite='tests',
    tests_require=test_requirements,
    setup_requires=setup_requirements,
)


text:
Ti=Data Sharing Agreements

Frameworks-=[S/Index/DataSharing/Frameworks.md]

Consent-=[S/Index/DataSharing/Consent.md]

Privacy-=[S/Index/DataSharing/Privacy.md]

MTA-=[S/Index/DataSharing/Bio_MaterialsTransferAgreement.md]

NDA-=[S/Index/DataSharing/NDA.md]

SaaS-=[S/Index/DataSharing/SaaS.md]

EmployeeInvention-=[S/Index/Employ/InventionAssignment.md]

=A "license" agreement shares many of the properties of a data sharing agreement, including use restrictions, even if legal theories may vary.

License-=[S/Index/DataSharing/License.md]

HackathonRules:=[G/GoogleOpenSource/Hackathon/LongForm/Form/0.md]

=Very sensitive information can be disclosed in litigation "discovery". Disclosure Agreement in US Patent Litigation:

ProtectiveOrder/=[G/AIII-v-SAS-PatentProtectiveOrder-CmA/]


text:
package com.squidtopusstudios.zerobit.input.controllers.mappings;

import com.badlogic.gdx.controllers.PovDirection;

/**
 * Xbox 360 mappings from http://www.java-gaming.org/index.php?topic=29223.0
 */
public class Xbox360 {

    /*
    * It seems there are different versions of gamepads with different ID Strings.
    * Therefore its IMO a better bet to check for:
    * if (controller.getName().toLowerCase().contains("xbox") &&
                  controller.getName().contains("360"))
    *
    * Controller (Gamepad for Xbox 360)
      Controller (XBOX 360 For Windows)
      Controller (Xbox 360 Wireless Receiver for Windows)
      Controller (Xbox wireless receiver for windows)
      XBOX 360 For Windows (Controller)
      Xbox 360 Wireless Receiver
      Xbox Receiver for Windows (Wireless Controller)
      Xbox wireless receiver for windows (Controller)
    */
    //public static final String ID = "XBOX 360 For Windows (Controller)";
    public static final int BUTTON_X = 2;
    public static final int BUTTON_Y = 3;
    public static final int BUTTON_A = 0;
    public static final int BUTTON_B = 1;
    public static final int BUTTON_BACK = 6;
    public static final int BUTTON_START = 7;
    public static final PovDirection BUTTON_DPAD_UP = PovDirection.north;
    public static final PovDirection BUTTON_DPAD_DOWN = PovDirection.south;
    public static final PovDirection BUTTON_DPAD_RIGHT = PovDirection.east;
    public static final PovDirection BUTTON_DPAD_LEFT = PovDirection.west;
    public static final int BUTTON_LB = 4;
    public static final int BUTTON_L3 = 8;
    public static final int BUTTON_RB = 5;
    public static final int BUTTON_R3 = 9;
    public static final int AXIS_LEFT_X = 1; //-1 is left | +1 is right
    public static final int AXIS_LEFT_Y = 0; //-1 is up | +1 is down
    public static final int AXIS_LEFT_TRIGGER = 4; //value 0 to 1f
    public static final int AXIS_RIGHT_X = 3; //-1 is left | +1 is right
    public static final int AXIS_RIGHT_Y = 2; //-1 is up | +1 is down
    public static final int AXIS_RIGHT_TRIGGER = 4; //value 0 to -1f
}


text:
@interface PodsDummy_MRARViewDebugger : NSObject
@end
@implementation PodsDummy_MRARViewDebugger
@end


text:
html, body, div, span, applet, object, iframe, h1, h2, h3, h4, h5, h6, p, blockquote, pre, a, abbr, acronym, address, big, cite, code, del, dfn, em, img, ins, kbd, q, s, samp, small, strike, strong, sub, sup, tt, var, b, u, i, center, dl, dt, dd, ol, ul, li, fieldset, form, label, legend, caption, article, aside, canvas, details, embed, figure, figcaption, footer, header, hgroup, menu, nav, output, ruby, section, summary, time, mark, audio, video {
margin: 0; padding: 0; border: 0; vertical-align: baseline; font-family: Arial, sans;
}
pre, code, tt, pre *, code *, tt * {
font-size: 14px;
font-family: Consolas, "Liberation Mono", Courier, monospace;
}
.clear {
clear: both;
}
.hidden {
display: none;
}
body {
background: #EBEBEB;
}
#wrapper {
width: 1000px;
margin: 0 auto;
}
#header {
position: relative;
height: 80px;
border-bottom: 1px solid #C00202;
}
#logo {
position: relative;
top: 0;
left: 0;
}
#logo a.logo {
display: block;
background: url(../images/qnnlogo.png) no-repeat;
width: 313px;
height: 48px;
text-indent: -9999px;
position: absolute;
top: 20px;
left: 0;
}
#logo h2 {
position: absolute;
top: 50px;
left: 320px;
font-size: 16px;
}
#header #menu {
position: absolute;
top: 30px;
left: 450px;
}
#header #menu ul {
list-style: none;
}
#header #menu ul li {
float: left;
display: block;
width: 80px;
height: 50px;
margin: 0 2px 0 0;
padding: 0 0 0 8px;
background: url(../images/menusep.png) no-repeat 0 5px;
overflow: hidden;
}
#header #menu ul li a {
display: block;
width: 80px;
height: 33px;
text-align: center;
font-size: 14px;
padding: 8px 0 0 0;
margin: 0;
color: #333;
border-top: 3px solid #EBEBEB;
text-decoration: none;
overflow: hidden;
letter-spacing: -1px;
}
#header #menu ul li a:hover, #header #menu ul li a.current {
border-top: 3px solid #D71920;
text-decoration: none;
}
#header #menu ul li a em {
font-style: normal;
font-size: 12px;
display: block;
letter-spacing: 0;
}
#header #menu ul li.end {
width: 7px;
margin: 0;
padding: 0;
}
#header #menu ul li.end a {
width: 7px;
}
#header #telephone {
position: absolute;
top: 5px;
left: 750px;
background: url(../images/telephone.png) no-repeat 0 0;
text-indent: 28px;
font-size: 14px;
color: #666;
height: 20px;
line-height: 20px;
}
#header #telephone a {
color: #666;
font-size: 14px;
text-decoration: none;
}
#header #telephone a:hover {
color: #000;
font-size: 14px;
text-decoration: none;
}
#main {

}
.twocols {
width: 1000px;
overflow: hidden;
}
.twocols .tc_l {
float: left;
width: 300px;
margin-right: 10px;
}
.twocols .tc_l .tc_l_block {
border-left: 1px solid #B9B9B9;
border-right: 1px solid #B9B9B9;
border-bottom: 1px solid #B9B9B9;
margin: 0 0 10px 0;
}
.bcontent {
background: #fff;
padding: 5px;
}
.bcontent p {
font-size: 13px;
text-indent: 26px;
margin: 8px 0;
line-height: 18px;
}
.contactbox {
background: #FFF;
padding: 5px;
text-align: center;
}
.contactbox p {
padding: 5px;
text-align: center;
font-size: 14px;
}
.twocols .tc_r {
float: left;
width: 690px;
}
.twocols .tc_r .tc_r_block {
border-left: 1px solid #B9B9B9;
border-right: 1px solid #B9B9B9;
border-bottom: 1px solid #B9B9B9;
margin: 0 0 10px 0;
background: #fff;
min-height: 500px;
height:auto !important;
height:500px;
overflow:visible;
}
.tc_l_block h3, .tc_r_block h3 {
background: url(../images/hbargrad.png) repeat-x 0 0;
height: 34px;
padding: 3px 0 0 8px;
overflow: hidden;
font-size: 15px;
color: #222;
}
.tc_l_block h3 em, .tc_r_block h3 em {
display: block;
font-style: normal;
font-size: 12px;
}
.tc_l_block h3 a, .tc_r_block h3 a {
display: block;
float: right;
width: 60px;
height: 34px;
text-align: right;
font-size: 13px;
text-decoration: none;
padding: 0 10px 0 0;
line-height: 34px;
color: #333;
text-indent: 0;
}
.tc_l_block h3 a:hover, .tc_r_block h3 a:hover {
font-size: 13px;
text-decoration: underline;
}
.productlist {
list-style: none;
width: 688px;
overflow: hidden;
padding-bottom: 20px;
}
.productlist li {
float: left;
width: 187px;
text-align: center;
margin: 20px 0 0 30px;
}
.productlist li img {
display: block;
width: 187px;
height: 150px;
border: 1px solid #CCC;
margin: 0 0 8px 0;
}
.productlist li a {
color: #333;
text-decoration: none;
font-size: 13px;
}
.productlist li a:hover {
text-decoration: underline;
}
#footer {
height: 50px;
background: #D71920;
text-align: center;
padding: 10px;
color: #FFF;
font-size: 13px;
line-height: 21px;
}
#footer a {
text-decoration: none;
color: #fff;
}
#footer a:hover {
text-decoration: underline;
color: #fff;
}
.copy {
font-size: 14px;
}
.copy a {
font-size: 14px;
}
.creator {
font-size: 12px;
}
.creator a {
font-size: 12px;
}
.banner {
margin: 10px 0;
border: 1px solid #aaa;
}

/* sliderkit */
#slider {
margin: 10px 0;
border: 1px solid #666;
box-shadow: 0 2px 3px #666;
}
.photoslider-bullets{width:998px;height:350px;}
.photoslider-bullets img {width:998px;height:350px;}
.photoslider-bullets .sliderkit-nav{position:absolute;top:325px;left:910px;}
.photoslider-bullets .sliderkit-nav-clip ul li{float:left;margin:0 2px 0 0;}
.photoslider-bullets .sliderkit-nav-clip ul li a{width:16px;height:16px;background:#fff;}
.photoslider-bullets .sliderkit-nav-clip ul li.sliderkit-selected a{background:#DB291D;}
.sliderkit {
display:none;
position:relative;
overflow:hidden;
text-align:left
}
.sliderkit a,.sliderkit a:hover {
text-decoration:none
}
.sliderkit a:focus {
outline:1px dotted #000
}
.sliderkit img {
border:0
}
.sliderkit .sliderkit-nav {
z-index:10;
position:absolute;
text-align:center
}
.sliderkit .sliderkit-nav-clip {
position:relative;
overflow:hidden;
}
.sliderkit .sliderkit-nav-clip ul {
position:relative;
left:0;
top:0;
list-style:none;
margin:0;
padding:0
}
.sliderkit .sliderkit-nav-clip ul li {
float:left
}
.sliderkit .sliderkit-nav-clip ul li a {
display:block;
overflow:hidden
}
.sliderkit .sliderkit-btn {
z-index:10
}
.sliderkit .sliderkit-panel {
z-index:1;
position:absolute;
overflow:hidden
}
.sliderkit .sliderkit-panel-active {
z-index:5
}
.sliderkit .sliderkit-panel-old {
z-index:4
}
.sliderkit .sliderkit-panel .sliderkit-panel-textbox {
position:absolute;
z-index:1
}
.sliderkit .sliderkit-panel .sliderkit-panel-text {
position:absolute;
z-index:3;
top:0;
left:0
}
.sliderkit .sliderkit-panel .sliderkit-panel-overlay {
position:absolute;
z-index:2;
top:0;
left:0
}
.sliderkit .sliderkit-count {
position:absolute;
top:5px;
right:5px;
z-index:10;
color:#fff;
background:#000;
padding:5px
}
.sliderkit .sliderkit-timer {
position:absolute;
top:0;
left:0;
z-index:10;
height:3px;
background:#ccc
}

.pro2cols {
background: #FFF;
border: 1px solid #999;
margin: 0 0 10px 0;
}
.pro2col_l {
float: left;
width: 200px;
}
.pro2cols .pro2col_l h2.header {
text-align: center;
border-bottom: 1px solid #999;
background: #CCC;
font-size: 22px;
padding: 6px;
margin: 0 0 15px 0;
display: block;
height: 26px;
}
.pro2cols .pro2col_l h3 em {
font-size: 14px;
font-style: normal;
display: block;
text-align: center;
border-radius: 7px;
padding: 6px;
margin: 5px 10px;
border: 1px solid #CCC;
background: #FFF;
background: -moz-linear-gradient(top, rgba(255, 255, 255, 1) 0%, rgba(225, 233, 238, 1) 100%);
background: -webkit-gradient(linear, left top, left bottom, color-stop(0%,rgba(255, 255, 255, 1)), color-stop(100%,rgba(225, 233, 238, 1)));
background: -webkit-linear-gradient(top, rgba(255, 255, 255, 1) 0%,rgba(225, 233, 238, 1) 100%);
background: -o-linear-gradient(top, rgba(255, 255, 255, 1) 0%,rgba(225, 233, 238, 1) 100%);
background: -ms-linear-gradient(top, rgba(255, 255, 255, 1) 0%,rgba(225, 233, 238, 1) 100%);
background: linear-gradient(to bottom, rgba(255, 255, 255, 1) 0%,rgba(225, 233, 238, 1) 100%);
filter: progid:DXImageTransform.Microsoft.gradient( startColorstr='#ffffff', endColorstr='#e1e9ee',GradientType=0 );
}
.pro2cols .pro2col_l ul.xpro {
list-style: none;
}
.pro2cols .pro2col_l ul.xpro li {
width: 170px;
height: 30px;
background: url(../images/sepline.png) repeat-x 0 26px;
margin: 0 auto;
line-height: 25px;
text-align: center;
}
.pro2cols .pro2col_l ul.xpro li a {
display: block;
width: 170px;
height: 25px;
line-height: 25px;
overflow: hidden;
text-align: center;
color: #666;
font-size: 13px;
text-decoration: none;
}
.pro2cols .pro2col_l ul.xpro li a:hover {
font-size: 13px;
color: #D71920;
text-decoration: none;
}
.pro2col_a {
width: 998px;
min-height: 800px;
height:auto !important;
height:800px;
overflow:visible;
}
.pro2col_r {
float: left;
width: 797px;
border-left: 1px solid #999;
min-height: 800px;
height:auto !important;
height:800px;
overflow:visible;
}
.pro2cols .pro2col_r h2.header, .pro2cols .pro2col_a h2.header {
text-align: left;
border-bottom: 1px solid #999;
background: #E2E2E2;
font-size: 22px;
padding: 6px 12px;
margin: 0 0 15px 0;
display: block;
height: 26px;
}
.pro2cols .pro2col_r h2.header em, .pro2cols .pro2col_a h2.header em {
float: right;
font-size: 13px;
font-style: normal;
line-height: 27px;
color: #333;
}
.pro2cols .pro2col_r h2.header em a, .pro2cols .pro2col_a h2.header em a {
font-size: 13px;
font-style: normal;
color: #333;
text-decoration: none;
}
.pro2cols .pro2col_r h2.header em a:hover, .pro2cols .pro2col_a h2.header em a:hover {
color: #333;
text-decoration: underline;
}
.gcontent {
width: 730px;
margin: 0 auto;
}
.rtp {
float: right;
width: 450px;
margin: 0;
}
.rtp h3 {
font-size: 16px;
margin: 0 0 10px;
}
.rtpul {
list-style: none;
}
.rtpul li {
font-size: 13px;
padding: 3px 0 5px;
}
.rtpul li div {
font-size: 13px;
margin: 0 0 5px 0;
}
#etalage{
display: none;
}
#etalage .etalage_thumb{
background: white url(../images/loading.gif) center no-repeat;
-webkit-box-shadow: 0 0 7px #aaa;
-moz-box-shadow: 0 0 7px #aaa;
box-shadow: 0 0 7px #aaa;
}
#etalage .etalage_small_thumbs li{
margin: 5px;
cursor: pointer;
}
#etalage ul li.etalage_smallthumb_active{
cursor: default;
}
#etalage .etalage_zoom_area, .etalage_zoom_area{
background: url(../images/loading.gif) center no-repeat;
-webkit-box-shadow: 0 0 5px #333;
-moz-box-shadow: 0 0 5px #333;
box-shadow: 0 0 5px #333;
}
#etalage .etalage_magnifier{
background: white;
-webkit-box-shadow: 0 0 5px #000;
-moz-box-shadow: 0 0 5px #000;
}
.etalage, .etalage_thumb, .etalage_thumb_image, .etalage_source_image, .etalage_zoom_preview, .etalage_icon, .etalage_hint{ display:none }
.etalage, .etalage ul, .etalage li, .etalage img, .etalage_hint, .etalage_icon, .etalage_description{ margin:0; padding:0; border:0; list-style:none }
.etalage, .etalage_magnifier div, .etalage_magnifier div img, .etalage_small_thumbs ul, ul .etalage_small_thumbs li, .etalage_zoom_area div, .etalage_zoom_img{ position:relative }
.etalage img, .etalage li{ -webkit-user-select:none; -khtml-user-select:none; -moz-user-select:none; -o-user-select:none; user-select:none; -webkit-user-drag:none; -moz-user-drag:none; user-drag:none }
.etalage, .etalage_small_thumbs li{ float:left }
.etalage_right{ float:right }
.etalage li{ position:absolute }
.etalage img{ vertical-align:bottom }
.etalage_magnifier{ cursor:default }
.etalage_magnifier div, .etalage_small_thumbs{ overflow:hidden }
.etalage_magnifier div img{ display:none }
.etalage_icon, .etalage_hint{ cursor:default; width:0; height:0; overflow:hidden }
.etalage_small_thumbs li.vertical{ float:none }
.etalage_zoom_area div{ overflow:hidden; z-index:997 }
.etalage_zoom_preview{ position:absolute; z-index:998 }
.etalage_zoom_img, .etalage_hint{ z-index:999 }
.etalage{ direction:ltr }
div.etalage_description{ position:absolute; bottom:0; left:0; z-index:999 }
div.etalage_description.rtl{ direction:rtl }

.tabbtns {
height: 25px;
overflow: hidden;
margin: 30px 0 10px !important;
}
.tabbtns ul {
list-style: none;
}
.tabbtns li {
float: left;
width: 96px;
height: 25px;
margin: 0 5px 0 0;
}
.tabbtns a {
font-size: 13px;
color: #666;
text-decoration: none;
}
.tabbtns a:hover {
font-size: 13px;
color: #fff;
text-decoration: none;
background: #D71920;
}
.tabbtn {
width: 96px;
height: 25px;
display: block;
line-height: 25px;
text-align: center;
color: #666666;
background: #DCD9D9;
}
a.sel {
text-decoration: none;
color: #fff;
background: #D71920;
}
a.sel:hover {
text-decoration: none;
}

.mc4 h2 {
font-size: 16px;
margin: 10px 0;
}
.mc4 h3 {
font-size: 14px;
margin: 15px 0 10px;
}
.mc4 ol {
margin: 10px 10px 10px 21px;
}
.mc4 li {
font-size: 12px;
padding: 3px 0;
line-height: 20px;
}
a.otherq {
border: 1px solid #c8c9cd;
padding: 3px;
margin: 0 3px 3px 0;
display: block;
font-size: 12px;
color: #000;
text-decoration: none;
float: left;
background: #fff;
text-align: center;
height: 76px;
}
a.otherq:hover {
font-size: 12px;
color: #fff;
text-decoration: underline;
background: #D71920;
}
a.otherq img {
width: 60px;
height: 60px;
}
.otherqcur {
font-weight: bold;
color: #fff !important;
background: #D71920 !important;
}
.ucontent {
padding: 10px 20px;
}
.ucontent p {
font-size: 13px;
text-indent: 26px;
margin: 15px 0;
line-height: 25px;
}
.pcontent {
padding: 0 10px 10px 10px;
}
.pcontent h3 {
font-size: 18px;
border-bottom: 1px solid #CCC;
padding: 3px 0 10px 0;
margin: 0;
}
.pcontent h4 {
margin: 10px 0 10px 0;
padding: 0 0 8px;
font-size: 18px;
border-bottom: 1px solid #CCC;
}
.prodsublist {
list-style: none;
margin: 7px 0 10px 0;
}
.prodsublist div.psli {
float: left;
display: block;
width: 154px;
height: 180px;
text-align: center;
}
.prodsublist img {
width: 150px;
height: 150px;
display: block !important;
}
.prodsublist div.psli a {
font-size: 13px;
color: #666;
text-decoration: none;
}
.prodsublist div.psli a:hover {
color: #666;
text-decoration: underline;
}
.divone {
float: left;
width: 700px;
padding: 15px;
}
.divone h3 {
padding: 15px;
}
.divtwo {
float: left;
width: 700px;
}
.photoitem {
list-style: none;
width: 900px;
margin: 0 auto;
}
.photoitem li {
border: 1px solid #D3DBE3;
margin: 20px;
position: relative;
}
.photoitem .pimage {
float: left;
padding: 13px 30px;
}
.photoitem .pimage img {
width: 150px;
height: 100px;
}
.photoitem .pinfo {
float: left;
padding: 5px 0;
}
.photoitem .pinfo p {
font-size: 13px;
line-height: 20px;
margin: 8px 0;
}
/* thickbox */
#TB_window {
font: 12px Arial, Helvetica, sans-serif;
color: #333333;
}
#TB_secondLine {
font: 10px Arial, Helvetica, sans-serif;
color:#666666;
}
#TB_window a:link {color: #666666;}
#TB_window a:visited {color: #666666;}
#TB_window a:hover {color: #000;}
#TB_window a:active {color: #666666;}
#TB_window a:focus{color: #666666;}
#TB_overlay {
position: fixed;
z-index:100;
top: 0px;
left: 0px;
height:100%;
width:100%;
}
.TB_overlayMacFFBGHack {background: url(macFFBgHack.png) repeat;}
.TB_overlayBG {
background-color:#000;
filter:alpha(opacity=75);
-moz-opacity: 0.75;
opacity: 0.75;
}
* html #TB_overlay { /* ie6 hack */
position: absolute;
height: expression(document.body.scrollHeight > document.body.offsetHeight ? document.body.scrollHeight : document.body.offsetHeight + 'px');
}
#TB_window {
position: fixed;
background: #ffffff;
z-index: 102;
color:#000000;
display:none;
border: 4px solid #525252;
text-align:left;
top:50%;
left:50%;
}
* html #TB_window { /* ie6 hack */
position: absolute;
margin-top: expression(0 - parseInt(this.offsetHeight / 2) + (TBWindowMargin = document.documentElement && document.documentElement.scrollTop || document.body.scrollTop) + 'px');
}
#TB_window img#TB_Image {
display:block;
margin: 15px 0 0 15px;
border-right: 1px solid #ccc;
border-bottom: 1px solid #ccc;
border-top: 1px solid #666;
border-left: 1px solid #666;
}
#TB_caption{
height:25px;
padding:7px 30px 10px 25px;
float:left;
}
#TB_closeWindow{
height:25px;
padding:11px 25px 10px 0;
float:right;
}
#TB_closeAjaxWindow{
padding:7px 10px 5px 0;
margin-bottom:1px;
text-align:right;
float:right;
}
#TB_ajaxWindowTitle{
float:left;
padding:7px 0 5px 10px;
margin-bottom:1px;
}
#TB_title{
background-color:#e8e8e8;
height:27px;
}
#TB_ajaxContent{
clear:both;
padding:2px 15px 15px 15px;
overflow:auto;
text-align:left;
line-height:1.4em;
}
#TB_ajaxContent.TB_modal{
padding:15px;
}
#TB_ajaxContent p{
padding:5px 0px 5px 0px;
}
#TB_load{
position: fixed;
display:none;
height:13px;
width:208px;
z-index:103;
top: 50%;
left: 50%;
margin: -6px 0 0 -104px; /* -height/2 0 0 -width/2 */
}
* html #TB_load { /* ie6 hack */
position: absolute;
margin-top: expression(0 - parseInt(this.offsetHeight / 2) + (TBWindowMargin = document.documentElement && document.documentElement.scrollTop || document.body.scrollTop) + 'px');
}
#TB_HideSelect{
z-index:99;
position:fixed;
top: 0;
left: 0;
background-color:#fff;
border:none;
filter:alpha(opacity=0);
-moz-opacity: 0;
opacity: 0;
height:100%;
width:100%;
}
* html #TB_HideSelect { /* ie6 hack */
position: absolute;
height: expression(document.body.scrollHeight > document.body.offsetHeight ? document.body.scrollHeight : document.body.offsetHeight + 'px');
}
#TB_iframeContent{
clear:both;
border:none;
margin-bottom:-1px;
margin-top:1px;
_margin-bottom:1px;
}
/* totop */
#toTop {
display:none;
text-decoration:none;
position:fixed;
bottom:10px;
right:10px;
overflow:hidden;
width:51px;
height:51px;
border:none;
text-indent:100%;
background:url(../images/ui.totop.png) no-repeat left top;
}

#toTopHover {
background:url(../images/ui.totop.png) no-repeat left -51px;
width:51px;
height:51px;
display:block;
overflow:hidden;
float:left;
opacity: 0;
-moz-opacity: 0;
filter:alpha(opacity=0);
}

#toTop:active, #toTop:focus {
outline:none;
}

.enterprise_qq, .individual_qq {
background: url(../images/qqtalk.png) no-repeat 9px 0;
display: block;
width: 92px;
height: 22px;
text-indent: -9999px;
float: left;
margin: 0 0 15px 0;
}

.zxkf {
width: 183px;
display: none;
overflow: hidden;
height: 270px;
}
.zxkfbtn {
cursor: pointer;
position: absolute;
background: url(../images/qq_1.png) no-repeat;
width: 33px;
height: 158px;
top: 60px;
left: 0;
}
.zxkfpanel {
position: absolute;
left: 33px;
top: 0;
}
.zxkfpanel_h {
display: none;
}
.zxkfpanel_c {
background: url(../images/qq_2.png) repeat-y;
width: 100px;
height: 360px;
position: relative;
}
.zxkfpanel_c_1 {
position: absolute;
font-size: 13px;
padding: 10px;
top: 68px;
left: -5px;
color: white;
line-height: 20px;
}
.zxkfpanel_c_2 {
position: absolute;
top: 84px;
left: 5px;
font-size: 13px;
color: white;
}
.zxkfpanel_f {
display: none;
}


text:
<?php
	require_once('config.php');

	$inflorescence = $_GET["inflorescence_characteristic"];

	$results = $db->query("
		select distinct plant_properties.id, binomial, common_name, image
		from plants, plant_properties
		where plants.id = plant_properties.id
		and case
				when '" . $inflorescence . "' != ''
				then plant_properties.characteristic = '" . $inflorescence . "'
					and plant_properties.property = 'Inflorescence'
		        else
					plant_properties.property = 'Inflorescence'
		        end");

	while($plant_data = $results->fetch_assoc()) {
		$results_list[] = $plant_data;
	}

	echo json_encode($results_list);

	$db->close();
?>


text:
var test = require('tap').test,
    log = require('../lib/log'),
    Html5app = require('../lib/html5app'),
    writer,
    store;

log.pause();

writer = {
    read: function() {},
    write: function() {},
    writeJson: function() {},
    copy: function() {},
    copydir: function() {},
    rmrf: function() {}
};

store = {
    getAllURLs: function() {
    },
    getResourceVersions: function() {
        return [];
    }
};

function getConf() {
    return {
        mojitodir: '/Users/isao/Repos/mojito/myfork/',
        app: {
            name: 'staticpf',
            version: '0.0.1',
            specs: {
                frame: {},
                tunnelProxy: {}
            },
            dir: '/path/to/app'
        },
        snapshot: {
            name: '',
            tag: '',
            packages: {}
        },
        build: {
            attachManifest: false,
            forceRelativePaths: false,
            insertCharset: 'UTF-8',
            port: 1111,
            dir: '/path/to/build/dir',
            type: 'html5app',
            uris: ['p1', 'p2']
        },
        context: {
            device: 'iphone'
        },
        contextqs: '?device=iphone',
        tunnelpf: '/tunnel',
        staticpf: 'staticpf'
    };
}

test('zz', function(t) {
    var conf = getConf(),
        done = function done() {},
        scraper = {
            on: function(event_name, cb) {
                // this function is called twice
                t.ok(event_name.match(/scraped-one|scraping-done/));
                t.equal(typeof cb, 'function', 'cb is a function');

                // on success, cb is called by scraping-done event
                if (event_name === 'scraping-done') {
                	t.same(done, cb);
                }
                return scraper;
            },
            start: function(obj) {
                t.same(obj,{port: conf.build.port, context: conf.context});
                return scraper;
            },
            fetch: function(obj, cb) {
                expected = {
                    '/?device=iphone': '/index.html',
                    'p1?device=iphone': 'p1',
                    'p2?device=iphone': 'p2',
                    '/tunnel/staticpf/frame/specs/default.json?device=iphone': '/staticpf/frame/specs/default.json',
                    '/tunnel/staticpf/tunnelProxy/specs/default.json?device=iphone': '/staticpf/tunnelProxy/specs/default.json'
                }
                t.same(obj, expected);
            }
        },
        html5app = new Html5app(writer, scraper);

    t.plan(7);

    html5app.exec(conf, store, done);

    t.end();
});


text:
class LeagueTeam < ActiveRecord::Base
end


text:
package projects.PIF.nodes.nodeImplementations;
import java.awt.Color;
import java.awt.Graphics;
import java.text.DecimalFormat;
import java.util.ArrayList;
import java.util.List;

import projects.PIF.nodes.messages.FEEDBACKMessage;
import projects.PIF.nodes.messages.INFMessage;
import projects.PIF.nodes.timers.PIF_FeedbackTimer;
import projects.PIF.nodes.timers.MessageTimer;
import sinalgo.configuration.WrongConfigurationException;
import sinalgo.gui.transformation.PositionTransformation;
import sinalgo.nodes.Node;
import sinalgo.nodes.messages.Inbox;
import sinalgo.nodes.messages.Message;
import sinalgo.runtime.Global;
import sinalgo.tools.Tools;

public class PIFNode extends Node {
	//private boolean reached = false;
	private int nextHopToSource;
	private int nodeLevel = 99999;
	public static int higherLevel = 0;
	public static int sentINF = 0;
	public static int sentFeedback = 0;
	public static int receivedFeedback = 0;

	public enum TNO {TNO_FEEDBACK, RESET_FEEDBACK, CANCEL_FEEDBACK }; //TNO_FEEDBACK: vai ter que passar pelo verificador de cancel, e se for aprovado, se torna RESET_FEEDBACK;
	//RESET_FEEDBACK: enum que determina se o broadcast irá ocorrer ou não.
//	Condições para o broadcast ocorrer:
//		Se o grau do nó atual for igual ao grau do maior nó de todos;
//		Se eu tiver recebido uma mensagem, e apenas uma, de algum filho de grau maior do que o meu.
	private PIF_FeedbackTimer feedbackTimer;

	DecimalFormat deci = new DecimalFormat("0.0000");
	//Listas de mensagens criadas por nós -> Elas são correspondentes
	public List<INFMessage> reachedMessageList = new ArrayList<INFMessage>(); //Array que é listado o index das mensagens distintas.
	public List<FEEDBACKMessage> reachedFeedList = new ArrayList<FEEDBACKMessage>(); //Array que é listado o index da mensagem distinta, e se ele tem o menor level no grafo.
	@Override
	public void handleMessages(Inbox inbox) {
		// TODO Auto-generated method stub
		int sender;

//		while(inbox.hasNext()) {
//			Message msg = inbox.next();
//			sender = inbox.getSender().ID;
//
//			//N� recebeu uma mensagem INF
//			if(msg instanceof INFMessage) {
//				System.out.println("Node: "+this.ID+" recebeu INF do Node  "+sender);
//				INFMessage msgINF = (INFMessage) msg;
//
//				//Setting node level with msg information
//				if(this.nodeLevel > msgINF.getLevel()+1){
//					this.nodeLevel = msgINF.getLevel()+1;
//				}
//
//				if(!this.reachedList.contains((INFMessage) msg))
//				{
//					this.setColor(Color.GREEN);
//					reachedList.add(msgINF);
//					//this.reached = true;
//					this.nextHopToSource = msgINF.getSenderID();
//					msgINF.setSenderID(this.ID);
//					//Modify the level carried by the message
//					msgINF.setLevel(this.nodeLevel+1);
//					MessageTimer infMSG = new MessageTimer(msgINF);
//					infMSG.startRelative(0.1,this);
//
//					//Agenda o FEEDBACK
//					feedbackTimer = new PIF_FeedbackTimer(this, TNO.TNO_FEEDBACK);
//					feedbackTimer.tnoStartRelative(10, this, TNO.TNO_FEEDBACK);
//				}else{
//					//Agenda o FEEDBACK
//					feedbackTimer = new PIF_FeedbackTimer(this, TNO.TNO_FEEDBACK);
//					feedbackTimer.tnoStartRelative(0.1, this, TNO.TNO_FEEDBACK);
//				}
//			}
//
//			//Mensagem de Confirma��o
//			if(msg instanceof FEEDBACKMessage) {
//				FEEDBACKMessage msgFeedback = (FEEDBACKMessage) msg;
//				if (this.ID != 1){
//					if(msgFeedback.getDestinationID() == this.ID){
//						msgFeedback.setDestinationID(this.nextHopToSource);
//						MessageTimer feedbackMSG = new MessageTimer(msgFeedback);
//						feedbackMSG.startRelative(0.1,this);
//						System.out.println("Node: "+this.ID+" Recebeu Feedback do Node "+ msgFeedback.getSourceFeedbackID() + " encaminhada pelo Node " +msgFeedback.getSenderID());
//					}
//				}else{
//					System.out.println("Source node recebeu Feedback do Node "+ msgFeedback.getSourceFeedbackID());
//					receivedFeedback = receivedFeedback + 1;
//				}
//			}
//		}
		//Primeira parte do PIFNode: Ele verifica se tem visinhos pra ele mandar a msg (inboc.hasnext).
		while(inbox.hasNext()) {
			Tools.appendToOutput("\n n neighboors:"+this.outgoingConnections.size());
			Message msg = inbox.next();
			sender = inbox.getSender().ID;
			//Tools.appendToOutput("\n ID : "+ inbox.getReceiver().ID + "\n");
			//N� recebeu uma mensagem INF

			//Verifica��o de tipo de mensagem: Inf
				//Se for do tipo inf, ele se comporta
			if(msg instanceof INFMessage) {
				System.out.println("Node: "+this.ID+" recebeu INF do Node  "+sender);
					INFMessage msgINF = (INFMessage) msg;

					//Setting node level with msg information
					if(this.nodeLevel > msgINF.getLevel()+1){
						this.nodeLevel = msgINF.getLevel()+1;	//Atualiza o level do node atual
						this.nextHopToSource = msgINF.getSenderID(); //Atualiza quem � o pai.

					}
					//Setting the higherLevel -> Parameter to determine the level of the higher node.
					if(this.nodeLevel > higherLevel){
						higherLevel = this.nodeLevel;
					}

					//Verifica��o: V� se ele envia ou n�o a mensagem de informa��o na rede.
					//Primeiro caso: Ele envia a mensagem de informa��o na rede.
					if(!this.reachedMessageList.contains((INFMessage) msg) && this.ID % 3 == 1) //novo pi, para msg
					{
						this.changeColorMessage(msgINF.getMessageID());
						reachedMessageList.add(msgINF);
						msgINF.setSenderID(this.ID);

						//Modify the level carried by the message
//						msgINF.setLevel(this.nodeLevel + 1); //Antes: incluia +1 no nodeLevel. Comentei isso pq acho desnecessario, visto que o nodeLevel ja eh atualizado anteriormente,
						msgINF.setLevel(this.nodeLevel); //Agora: nao incrementa adicionalmente o nodeLevel.
						MessageTimer infMSG = new MessageTimer(msgINF); //timer da msg. Já tinha no antigo pi
						infMSG.startRelative(0.1,this);

						//Agenda o FEEDBACK
						feedbackTimer = new PIF_FeedbackTimer(this, TNO.TNO_FEEDBACK,((INFMessage) msg).getMessageID());
						feedbackTimer.tnoStartRelative(10, this, TNO.TNO_FEEDBACK, ((INFMessage) msg).getMessageID());
					}
					//Segundo caso: ele n�o envia a mensagem de informa��o na rede. Ele temporariza o timer do feedback.
					else if(!this.reachedMessageList.contains((INFMessage) msg) && this.ID % 3 != 1){ //negação -> nao envia msg.
						//Agenda o FEEDBACK
						this.changeColorMessage(msgINF.getMessageID());
						reachedMessageList.add(msgINF);

						feedbackTimer = new PIF_FeedbackTimer(this, TNO.TNO_FEEDBACK, ((INFMessage) msg).getMessageID());
						feedbackTimer.tnoStartRelative(10, this, TNO.TNO_FEEDBACK, ((INFMessage) msg).getMessageID());
					}
				}

			//Mensagem de Confirmacao
			if(msg instanceof FEEDBACKMessage) {
				FEEDBACKMessage msgFeedback = (FEEDBACKMessage) msg;
				if (this.ID != 1){ //Metodo para reencaminhar o feedback para cima do grafo.

					if(msgFeedback.getLevel() ==this.nodeLevel + 1 ){
						if(!reachedFeedList.contains(msgFeedback)){
							reachedFeedList.add(msgFeedback);
							feedbackTimer = new PIF_FeedbackTimer(this, TNO.RESET_FEEDBACK,msgFeedback.getMessageID());
							feedbackTimer.tnoStartRelative(1, this, TNO.RESET_FEEDBACK, msgFeedback.getMessageID());
						}
					}
					if(msgFeedback.getDestinationID() == this.ID){
						msgFeedback.setDestinationID(this.nextHopToSource);
						MessageTimer feedbackMSG = new MessageTimer(msgFeedback);
						feedbackMSG.startRelative(0.1,this);
						System.out.println("Node: "+this.ID+" Recebeu Feedback do Node "+ msgFeedback.getSourceFeedbackID() + " encaminhada pelo Node " +msgFeedback.getSenderID());
					}
				}else{
					System.out.println("Source node recebeu Feedback do Node "+ msgFeedback.getSourceFeedbackID());
					receivedFeedback = receivedFeedback + 1;
				}
			}

		}
	}

	public void feedbackStart(){ //Aki tá o comportamento do inicio do broadcast. Aparentemente...

		MessageTimer feedbackMSG = new MessageTimer (new FEEDBACKMessage(this.ID, this.ID, this.nextHopToSource, this.nodeLevel)); //construct correto
	  	feedbackMSG.startRelative(0.1, this);
	}
	public void feedbackStart(int index){ //Aki tá o comportamento do inicio do broadcast. Aparentemente...

		MessageTimer feedbackMSG = new MessageTimer (new FEEDBACKMessage(this.ID, this.ID, this.nextHopToSource, index ,this.nodeLevel)); //construct correto
	  	feedbackMSG.startRelative(0.1, this);
	  	this.changeColorFeedback(index);
	}

	public void timeout(TNO tno, int index){ //metodo que zera o contador, e inicia o Feedback Start. eh aqui que o fire do feedback timer manda.
		//TNO_FEEDBACK é usado para criar casos de quando iniciar o broadcast do feedback, baseado neste switch.
		//Dá pra criar uma arvore de casos diferente, e chamar um novo método, ignorando este timeout
		if(tno == TNO.TNO_FEEDBACK){
			tno = this.cancel(tno);
		}
		switch(tno){
			case TNO_FEEDBACK:
//				if(this.nodeLevel == higherLevel){ //Ele só vai começar o broadcast se for o nó de maior grau.
//					//agora falta criar a condição que se eu recebi uma mensagem de um nó de grau maior em 1 do que o meu,
//					//eu iniciar o meu broadcast, e somente 1 vez. (pq pode ter mais de um broadcast de um nó de grau nodelevel+1)
				feedbackTimer = new PIF_FeedbackTimer(this, TNO.TNO_FEEDBACK, index);
				feedbackTimer.tnoStartRelative(5, this, TNO.TNO_FEEDBACK, index);

//				}
				break;
			case RESET_FEEDBACK: //nome incoerente. Ele vai inicializar o feedback, não resetar ele.
				feedbackStart(index);

				break;
			case CANCEL_FEEDBACK:

				break;
		}
	}
	public TNO cancel(TNO tno){
		if(this.nodeLevel == higherLevel ){
			return TNO.RESET_FEEDBACK;
		}
		else
			return TNO.CANCEL_FEEDBACK;

	}
    @Override
	public void init() {
		//Considerando que o n� 1 tem a mensagem inf

//		if (this.ID==1){
//			for(int i=0; i<1000; i++){
//				this.setColor(Color.RED);
//				this.nextHopToSource = this.ID;
//
//				INFMessage msg = new INFMessage(this.ID, i, 0);
//				MessageTimer infMSG = new MessageTimer (msg);
//				reachedList.add(msg);
//		  		infMSG.startRelative(0.1, this);
//			}
//		}

    	if (this.ID==1){
    		this.nextHopToSource = this.ID;
    		this.nodeLevel = 0;
			for(int i=0; i<1000; i++){
				this.setColor(Color.RED);
				INFMessage msg = new INFMessage(this.ID, i, this.nodeLevel);
				MessageTimer infMSG = new MessageTimer (msg);
				reachedMessageList.add(msg);
		  		infMSG.startRelative(0.1 + 5*i, this);
			}
    	}

	}

	@Override
	public void postStep() {
		// TODO Auto-generated method stub
	}

	@Override
	public void preStep() {
		// TODO Auto-generated method stub
	}

	@Override
	public void draw(Graphics g, PositionTransformation pt, boolean highlight) {
		// TODO Auto-generated method stub
		//if (this.ID == 1) highlight = true;
		super.drawNodeAsDiskWithText(g, pt, highlight, Integer.toString(this.ID), 6, Color.WHITE);

	}

	@Override
	public void neighborhoodChange() {
		// TODO Auto-generated method stub

	}

	@Override
	public void checkRequirements() throws WrongConfigurationException {
		// TODO Auto-generated method stub

	}
	public void changeColorMessage(int ID) {
		switch (ID % 5) {
		case 0:
			this.setColor(Color.GREEN);
			break;
		case 1:
			this.setColor(Color.BLUE);
			break;
		case 2:
			this.setColor(Color.YELLOW);
			break;
		case 3:
			this.setColor(Color.CYAN);
			break;
		case 4:
			this.setColor(Color.MAGENTA);
			break;
		}
	}
	public void changeColorFeedback(int ID) {
			switch (ID % 5) {
			case 0:
				this.setColor(Color.ORANGE);
				break;
			case 1:
				this.setColor(Color.BLACK);
				break;
			case 2:
				this.setColor(Color.DARK_GRAY);
				break;
			case 3:
				this.setColor(Color.LIGHT_GRAY);
				break;
			case 4:
				this.setColor(Color.PINK);
				break;
			}
		}

}


text:
//=============================================================================================================

#include "globalobj.h"

//--- Global Queue for IPC (socket )
QQueue<Eigen::MatrixXf *> g_queue;
int g_maxlen = 40;
QMutex g_mutex;
QWaitCondition g_queueNotFull;
QWaitCondition g_queueNotEmpty;

//--- Global Var for Triggers
PROAvg m_OnlineAvg;
int AvgBufLen;

//--- Global Buffer for Avgeraged Data
QList <Eigen::MatrixXf> AvgBinSum;
QList <int> AvgBufCounts;
QMutex g_mutex_avg;

//--- Global Queue for online averaging
QQueue<Eigen::MatrixXf > g_queue_avg;
int g_maxlen_avg = 40;
QMutex g_mutex_avg1;
QWaitCondition g_queueNotFull_avg;
QWaitCondition g_queueNotEmpty_avg;

//--- Global Queue for online display
QQueue<Eigen::MatrixXf > g_queue_disp;
int g_maxlen_disp = 40;
QMutex g_mutex_disp;
QWaitCondition g_queueNotFull_disp;
QWaitCondition g_queueNotEmpty_disp;

//--- Global Queue for SQUID Control
QQueue<Eigen::MatrixXf > g_queue_squidctrl;
int g_maxlen_squidctrl = 40;
QMutex g_mutex_squidctrl;
QWaitCondition g_queueNotFull_squidctrl;
QWaitCondition g_queueNotEmpty_squidctrl;

//--- Global Queue for File Saving
QQueue<Eigen::MatrixXf > g_queue_filesave;
int g_maxlen_filesave = 40;
QMutex g_mutex_filesave;
QWaitCondition g_queueNotFull_filesave;
QWaitCondition g_queueNotEmpty_filesave;

float  fs;
int    nChn;
float pscale;

//--- Global Filter Setting
gFilter m_gFilter;


text:
"""
File: savings_views.py
Author: Zachary King

Implements views/handlers for Savings-related requests
"""

from django.shortcuts import render, reverse, redirect
from datetime import date, datetime
from django.utils import timezone
from django.contrib.auth.decorators import login_required
import decimal

from ..models import Wallet, Budget, Transaction, Savings
from ..utils import notifications

@login_required(login_url='/pynny/login')
def savings(request):
    """Displays savings for a user"""
    # GET = display user's savings
    data = dict()
    if request.method == 'GET':
        # Get the savings for this user
        data['savings'] = Savings.objects.filter(user=request.user)

        return render(request, 'pynny/savings/savings.html', context=data)
    # POST = update a Saving
    elif request.method == 'POST':
        # Get the form data from the request
        name = request.POST['name']
        goal = float(request.POST['goal'])
        due_date = request.POST.get('due_date', '')
        if due_date:
            due_date = datetime.strptime(due_date, '%Y-%m-%d').date()
        notify = True if 'notify' in request.POST else False
        delete = True if 'delete' in request.POST else False

        # Check if the Saving name exists already
        if Savings.objects.filter(user=request.user, name=name):
            data['alerts'] = {'errors': ['A Saving already exists with that name']}
            data['savings'] = Savings.objects.filter(user=request.user)
            return render(request, 'pynny/savings/savings.html', context=data)

        # Create the new Saving
        Savings(name=name, goal=goal, balance=decimal.Decimal('0'),
                due_date=due_date if due_date else None,
                delete_on_completion=delete,
                notify_on_completion=notify, completed=False, hidden=False, user=request.user).save()

        data['alerts'] = {'success': ['Done! New Saving created successfully!']}
        if notify:
            data['alerts']['info'] = [
                'Nice! Since you asked to be notified, you\'ll receive an email when this Saving is fulfilled']
        data['savings'] = Savings.objects.filter(user=request.user)
        return render(request, 'pynny/savings/savings.html', context=data, status=201)

@login_required(login_url='/pynny/login')
def one_saving(request, savings_id):
    """Used for requests to a single saving (i.e. /savings/3)"""
    data = dict()
    # Authorize access to the saving
    try:
        saving = Savings.objects.get(id=savings_id)
    except Savings.DoesNotExist:
        data['alerts'] = {'errors': ['Oh Snap! That Saving does not exist']}
        data['savings'] = Savings.objects.filter(user=request.user)
        return render(request, 'pynny/savings/savings.html', context=data, status=404)

    if saving.user != request.user:
        data['savings'] = Savings.objects.filter(user=request.user)
        data['alerts'] = {'errors': ['Oh Snap! That Saving does not exist']}
        return render(request, 'pynny/savings/savings.html', context=data, status=403)

    if request.method == 'GET':
        # TODO - Create single Saving page and implement the view here
        pass
    elif request.method == 'POST':
        action = request.POST['action'].lower()

        if action == 'edit_complete':
            name = request.POST['name']
            goal = float(request.POST['goal'])
            due_date = request.POST.get('due_date', None)
            if due_date:
                due_date = datetime.strptime(due_date, '%Y-%m-%d').date()
            notify = True if 'notify' in request.POST else False
            delete = True if 'delete' in request.POST else False

            # Make sure the new name doesn't already exist
            if name != saving.name and Savings.objects.filter(user=request.user, name=name):
                data['alerts'] = {'errors': ['Oh Snap! A Saving already exists with that name']}
                data['savings'] = Savings.objects.filter(user=request.user)
                return render(request, 'pynny/savings/savings.html', context=data, status=200)

            # Data is fine, update the Saving
            saving.name = name
            saving.goal = goal
            saving.due_date = due_date
            saving.notify_on_completion = notify
            saving.delete_on_completion = delete
            if saving.goal <= saving.balance:
                complete_saving(saving)
                data['alerts'] = {'success': ['Congratulations! You met your Savings goal for "{}"'.format(saving.name)]}
                data['alerts']['success'].append('Done! Saving updated successfully')
            else:
                saving.save()

            data['savings'] = Savings.objects.filter(user=request.user)
            return render(request, 'pynny/savings/savings.html', context=data, status=200)

        elif action == 'delete':
            saving.delete()
            data['alerts'] = {'success': ['Done! Saving deleted successfully']}
            return render(request, 'pynny/savings/savings.html', context=data)

def complete_saving(saving):
    saving.completed = True
    saving.save()

    if saving.notify_on_completion:
        notifications.notify_saving_complete(saving)
    if saving.delete_on_completion:
        saving.delete()


text:
package ronin;

import gw.lang.reflect.IType;
import gw.lang.reflect.TypeSystem;
import gw.lang.reflect.gs.IGosuClass;
import org.junit.Test;
import org.junit.internal.TextListener;
import org.junit.runner.JUnitCore;
import org.junit.runner.Result;

import java.io.File;
import java.lang.reflect.Method;
import java.util.ArrayList;
import java.util.List;

public class TestScanner {

  private File[] _dirsToScan;

  public static void main(String[] args) {
    File[] files = new File[args.length];
    for (int i = 0, argsLength = args.length; i < argsLength; i++) {
      files[i] = new File(args[i]);
    }
    DevServer.initGosuWithSystemClasspath();
    Result result = new TestScanner(files).runTests(false, true);
    System.exit(result.wasSuccessful() ? 0 : -1);
  }

  public TestScanner(File... dirsToScan) {
    _dirsToScan = dirsToScan;
  }

  public Result runUITests(boolean parallelClasses, boolean parallelMethods) {
    return runTests(parallelClasses, parallelMethods, true);
  }

  public Result runTests(boolean parallelClasses, boolean parallelMethods) {
    return runTests(parallelClasses, parallelMethods, false);
  }

  private Result runTests(boolean parallelClasses, boolean parallelMethods, boolean uiTests) {
    ArrayList<Class> tests = new ArrayList<Class>();
    for (File root : _dirsToScan) {
      addTests(tests, root, root, uiTests);
    }
    JUnitCore core = new JUnitCore();
    core.addListener(new TextListener(System.out));
    //TODO cgross - restore new ParallelComputer(parallelClasses, parallelMethods),
    Result result = core.run(tests.toArray(new Class[tests.size()]));
    return result;
  }

  private static void addTests(List<Class> tests, File testDir, File possibleTest, boolean uiTests) {
    if (possibleTest.exists()) {
      if (possibleTest.isDirectory()) {
        for (File child : possibleTest.listFiles()) {
          addTests(tests, testDir, child, uiTests);
        }
      } else {
        String relativeName = possibleTest.getAbsolutePath().substring(testDir.getAbsolutePath().length() + 1);
        int lastDot = relativeName.lastIndexOf(".");
        if (lastDot > 0) {
          relativeName = relativeName.substring(0, lastDot);
          String typeName = relativeName.replace(File.separator, ".");
          IType type = TypeSystem.getByFullNameIfValid(typeName);
          if (type instanceof IGosuClass && !type.isAbstract()) {
            IGosuClass gosuClass = (IGosuClass) type;
            if((gosuClass.getTypeInfo().getAnnotation(TypeSystem.getByFullName("ronin.test.UITest")) != null) == uiTests) {
              Class backingClass = gosuClass.getBackingClass();
              if (junit.framework.Test.class.isAssignableFrom(backingClass)) {
                tests.add(backingClass);
              } else if (isJUnit4Test(backingClass)) {
                tests.add(backingClass);
              }
            }
          }
        }
      }
    }
  }

  private static boolean isJUnit4Test(Class clazz) {
    for (Method m : clazz.getMethods()) {
      if (m.getAnnotation(Test.class) != null) {
        return true;
      }
    }
    return false;
  }
}


text:
using System;
using System.Collections.Generic;

namespace LambdaConverters
{
    partial struct TemplateSelectorArgs<T> : IEquatable<TemplateSelectorArgs<T>>
    {
        /// <summary>
        /// Implements the operator <c>==</c>.
        /// </summary>
        /// <param name="x">The left operand.</param>
        /// <param name="y">The right operand.</param>
        /// <returns>The result of the operator.</returns>
        public static bool operator ==(TemplateSelectorArgs<T> x, TemplateSelectorArgs<T> y)
            => EqualityComparer<T>.Default.Equals(x.Item, y.Item) && x.Container == y.Container;

        /// <summary>
        /// Implements the operator <c>!=</c>.
        /// </summary>
        /// <param name="x">The left operand.</param>
        /// <param name="y">The right operand.</param>
        /// <returns>The result of the operator.</returns>
        public static bool operator !=(TemplateSelectorArgs<T> x, TemplateSelectorArgs<T> y) => !(x == y);

        /// <inheritdoc />
        public override int GetHashCode() => (Item is { } ? EqualityComparer<T>.Default.GetHashCode(Item) : 0) ^ (Container?.GetHashCode() ?? 0);

        /// <inheritdoc />
        public override bool Equals(object? obj) => obj is TemplateSelectorArgs<T> args && Equals(args);

        /// <inheritdoc />
        public bool Equals(TemplateSelectorArgs<T> other) => this == other;
    }
}


text:
var _ = require('lodash'),
    EventEmitter = require('events'),
    inherit = require('./utils/inherit'),
    Envelope = require('./models/envelope');

/**
 * Represents a base adapter for all adapters
 * @param {Bot}     bot     The current {Bot} instance
 * @constructor
 */
var BaseAdapter = function(bot) {
    this.bot = bot;
    this.db = require('./utils/db');
};

BaseAdapter.prototype = {
    /**
     * Initialises a new instance of an `Envelope` passing the same arguments
     * provided to this function to its constructor.
     * @return {Envelope}       A new envelope with the given arguments.
     */
    makeEnvelope: function() {
        var args = Array.prototype.slice.apply(arguments, []);
        args.unshift(undefined);
        return new (Function.prototype.bind.apply(Envelope, args)); // jshint ignore:line
    },

    /**
     * Sets up this adapter.
     * @return {Promise}   A Promise that will be resolved whenever this adapter is done setting up
     *                     itself. This promise can be rejected if the operation fails.
     */
    setup: function() { return Promise.resolve(); },

    /**
     * Sends a contextless message to the chat source
     * @param  {AnyObject}  target  Destination of the message
     * @param  {String}     string  Message contents
     * @param  {Array|null} attachments Array of attachments of the message
     * @return {undefined}          Nothing
     */
    contextlessSend: function(target, string, attachments) { },

    /**
     * Sends an answer of an envelope
     * @param  {Envelope}   envelope    Envelope being answered
     * @param  {String}     string      Message contents
     * @param  {Array|null} attachments Array of attachments of the message
     * @return {undefined}              Nothing
     */
    send: function(envelope, string, attachments) { return Promise.reject(); },

    /**
     * Replies an envelope
     * @param  {Envelope}   envelope    Envelope being replied
     * @param  {String}     string      Message contents
     * @param  {Array|null} attachments Array of attachments of the message
     * @return {undefined}              Nothing
     */
    reply: function(envelope, string, attachments) { return this.send(envelope, string, attachments); },

    /**
     * Executes the adapter
     * @return {undefined}      Nothing
     */
    run: function() { this.ready(); },

    /**
     * Shutdowns the adapter
     * @return {undefined}      Nothing
     */
    shutdown: function() { },

    /**
     * Receives an message from the chat source
     * @param  {AnyObject}  message     Message being received
     * @return {undefined}              Nothing
     */
    receive: function(message) { this.bot.inputManager.process(message); },

    /**
     * Adds an event subscriber to a given event name
     * @param  {String}   event         Event name to be subscribed to
     * @param  {Function} callback      Callback function to be called whenever the event is emitted
     * @return {BaseAdapter}            This very same instance
     * @chainable
     */
    on: function(event, callback) {
        this.events.on(event, callback);
        return this;
    },

    /**
     * Gets a mention tag for the given user.
     * @param  {User}   user    User object to generate the tag from.
     * @return {String}         A string representing the tag that mentions the
     *                          user, considering the current adapter mechanics.
     */
    getMentionTagForUser: function(user) {
        return '@' + user.username;
    },

    /**
     * Removes a given message from the message log. This method depends on the current
     * adapter's implementation and capabilities. This implementation can also accept
     * other parameters and depends on the used adapter's mechanics.
     * @param  {String}     messageId   ID of the message to be removed.
     * @return {Promise}                A Promise that will be resolved whenever the message
     *                                  is removed from the log.
     */
    removeMessage: function(messageId) {
        return Promise.reject();
    },

    /**
     * Courtesy method. Used by the Context subsystem to determine if an incoming `Envelope` message
     * should mention the bot considering it's state.
     * @param  {Envelope}   envelope    Envelope instance to be analised.
     * @return {Boolean}                Whether to exepect this incoming message to mention the bot.
     */
    messageShouldBeUsedInContext: function(envelope) {
        return true;
    },

    /**
     * Searches a channel with the given name or ID, where the ID must be a identifier used by
     * the current Adapter to internally represent known channels.
     * @param {String}      nameOrId            Name or ID of the channel to be found.
     * @return {Promise}                        A promise that will be resolved whenever the channel
     *                                          is found. It will be rejected whenever the channel
     *                                          cannot be found or there's an underlying problem
     *                                          during the search process.
     */
    searchChannel: function(nameOrId) {
        return new Promise((resolve, reject) => {
            this.db.Channel.findOne({ $or: [{ name: nameOrId }, { id: nameOrId }] })
            .then((c) => {
                if(c) {
                    resolve(c);
                } else {
                    reject(new Error('Channel not found.'));
                }
            })
            .catch(reject);
        });
    },

    /**
     * Searches an user with the given name or ID, where the ID must be a identifier used by
     * the current Adapter to internally represent known channels.
     * @param {String}      nameOrId            Name or ID of the user to be found.
     * @return {Promise}                        A promise that will be resolved whenever the user
     *                                          is found. It will be rejected whenever the user
     *                                          cannot be found or there's an underlying problem
     *                                          during the search process.
     */
    searchUser: function(nameOrId) {
        return new Promise((resolve, reject) => {
            this.db.User.findOne({ $or: [{ username: nameOrId }, { id: nameOrId }] })
            .then((u) => {
                if(u) {
                    resolve(u);
                } else {
                    reject(new Error('User not found.'));
                }
            })
            .catch(reject);
        });
    },

    /**
     * Searches for users that belongs to a given role.
     * @param  {String} role Role name
     * @return {Promise}      Promise that will be resolved when the search
     *                        procedure is completed.
     * @since  2.1.5
     */
    searchUsersInRole: function(role) {
        return new Promise((resolve) => {
            this.db.User.find({ roles: role })
            .then((u) => {
                resolve(u);
            });
        });
    },

    /**
     * Sends a notification to the adapter source indicating that the bot is typing something.
     * @param {Response}   envelope         The object being responded by the bot. Used to identify
     *                                      the target channel.
     * @return {undefined}                    Nothing.
     */
    sendTypingState: function(envelope) { },

    /**
     * Adds an reaction to a given message. This feature depends on the current adapter implementation
     * and will be rejected by default.
     * @param {Envelope}    envelope    Envelope containing the message that will be reacted to.
     * @param {String}      reaction    Emoji name to be added to the message.
     * @return {Promise}                A Promise that will be resolved after the reaction has been
     *                                  added to the target message. Again, notice that this feature
     *                                  depends on the current Adapter being used and will be rejected
     *                                  by default.
     */
    addReaction: function(envelope, reaction) { return Promise.reject(); },

    /**
     * Gets a channel ID for a given user identifier. If not overriden, returns the same
     * input ID. Useful if the chat source uses a diferent identifier to direct messages.
     * @param  {AnyObject}  userID  User identifier to be crossed against the possible adapter
     *                              DM list source.
     * @return {AnyObject}          An object that represents the channel ID for a user direct
     *                              message channel.
     */
    dmForUser: function(userID) { return userId; }
};

/**
 * Extends an given type to this type
 * @param  {Type}   type    Type to be extended
 * @return {undefined}      Nothing
 */
BaseAdapter.setup = (type) => {
    inherit(type, BaseAdapter);
};

module.exports = BaseAdapter;


text:
require 'pathname'
require Pathname(__FILE__).dirname.expand_path.parent + 'spec_helper'

if HAS_SQLITE3 || HAS_MYSQL || HAS_POSTGRES

  describe DataMapper::Is::Cloneable do

    include ModelSetup

    # --------------------------------------------------------------------------------------------------
    # --------------------------------------------------------------------------------------------------

    describe "every cloneable", :shared => true do

      it "should define a #clone_resource instance method" do
        @i1.respond_to?(:clone_resource).should be_true
      end

      it "should define a #master_resource instance method" do
        @i1.respond_to?(:master_resource).should be_true
      end

      it "should define a #cloned_resources instance method" do
        @i1.respond_to?(:cloned_resources).should be_true
      end

      it "should define a #has_backlink_to_master? instance method" do
        @i1.respond_to?(:has_backlink_to_master?).should be_true
      end

      it "should define a #has_clone_specs? instance method" do
        @i1.respond_to?(:has_clone_specs?).should be_true
      end

      # TODO extract these since they depend on the remixed class name

      it "should define a remixed model that can be auto_migrated" do
        # once it's migrated it stays in the database and can be used by the other specs
        Object.const_defined?("ItemCloneSpec").should be_true
        lambda { ItemCloneSpec.auto_migrate! }.should_not raise_error
      end

      it "should define a 'cloneable_class_name' class_level reader on the remixing model" do
        Item.respond_to?(:cloneable_class_name).should be_true
        Item.cloneable_class_name.should == "ItemCloneSpec"
      end

      it "should define a 'clone_spec_reader' class_level reader on the remixing model" do
        Item.respond_to?(:clone_spec_reader).should be_true
        Item.clone_spec_reader.should == :item_clone_specs
      end

      it "should define a 'clone_spec_writer' class_level reader on the remixing model" do
        Item.respond_to?(:clone_spec_writer).should be_true
        Item.clone_spec_writer.should == :item_clone_specs=
      end

      it "should respond_to?(:item_clone_specs)" do
        @i1.respond_to?(:item_clone_specs).should be_true
      end

      it "should store a collection of clone_specs" do
        @i1.item_clone_specs.should be_empty
      end

      it "should keep track of timestamps" do
        @i1.item_clone_specs.create(:name => "foo", :attributes_to_clone => [ :name, :description ])
        @i1.item_clone_specs[0].should respond_to(:created_at)
        @i1.item_clone_specs[0].should respond_to(:updated_at)
        @i1.item_clone_specs[0].should respond_to(:deleted_at)
      end

    end

    # --------------------------------------------------------------------------------------------------
    # --------------------------------------------------------------------------------------------------

    describe "every cloneable that has an alias on the cloneable association", :shared => true do

      it "should set the specified alias on the default 'clone_specs' reader" do
        @i1.respond_to?(:my_item_clone_specs).should be_true
      end

    end

    describe "every cloneable that has no alias on the cloneable association", :shared => true do

      it "should respond to the default 'clone_specs' reader" do
        @i1.respond_to?(:item_clone_specs).should be_true
      end

    end

    # --------------------------------------------------------------------------------------------------
    # --------------------------------------------------------------------------------------------------
    # --------------------------------------------------------------------------------------------------
    # --------------------------------------------------------------------------------------------------

    describe "Item.is(:cloneable)" do

      before do

        unload_testing_models "ItemCloneSpec", "Item"

        class Item

          include DataMapper::Resource

          property :id,          Serial

          property :name,        String
          property :description, String

          is :cloneable

        end

        Item.auto_migrate!
        ItemCloneSpec.auto_migrate!

        @i1 = Item.create(:id => 1)

      end

      it_should_behave_like "every cloneable"
      it_should_behave_like "every cloneable that has no alias on the cloneable association"

    end

    # --------------------------------------------------------------------------------------------------
    # --------------------------------------------------------------------------------------------------

    describe "Item.is(:cloneable, :as => :my_item_clone_specs)" do

      before do

        unload_testing_models "ItemCloneSpec", "Item"

        class Item

          include DataMapper::Resource

          property :id,          Serial

          property :name,        String
          property :description, String

          is :cloneable, :as => :my_item_clone_specs

        end

        Item.auto_migrate!
        ItemCloneSpec.auto_migrate!

        @i1 = Item.create(:id => 1)

      end

      it_should_behave_like "every cloneable"
      it_should_behave_like "every cloneable that has an alias on the cloneable association"

    end

    describe "Item#clone" do

      before do

        unload_testing_models "ItemCloneSpec", "Item"

        class Item

          include DataMapper::Resource

          property :id,          Serial

          property :name,        String
          property :description, String

          is :cloneable

        end

        Item.auto_migrate!
        ItemCloneSpec.auto_migrate!

      end

      describe "with no parameters" do

        it "should produce one clone with all public properties copied over" do

          i = Item.create(:id => 1, :name => "name", :description => "description")
          Item.all.size.should == 1

          clones = i.clone_resource

          Item.all.size.should == 2
          clones[0].name.should == 'name'
          clones[0].description.should == 'description'

        end

      end

      describe "with one parameter" do

        it "should produce the given number of clones with all public properties copied over" do

          i = Item.create(:id => 1, :name => "name", :description => "description")
          Item.all.size.should == 1

          clones = i.clone_resource(2)

          Item.all.size.should == 3
          (0..1).each do |idx|
            clones[idx].name.should == 'name'
            clones[idx].description.should == 'description'
          end

        end

      end

      describe "with two parameters, the last being an instance of ItemCloneSpec" do

        it "should produce the given number of clones with all given properties copied over" do

          i = Item.create(:id => 1, :name => "name", :description => "description")

          s = i.item_clone_specs.create :name => "test clone spec", :attributes_to_clone => [ :name ]

          Item.all.size.should == 1
          ItemCloneSpec.all.size.should == 1

          clones = i.clone_resource(2, s)

          Item.all.size.should == 3
          (0..1).each do |idx|
            clones[idx].name.should == 'name'
            clones[idx].description.should be_nil
          end

        end

      end

      describe "with two parameters, the last being an instance of Array" do

        it "should produce the given number of clones with all given properties copied over" do

          i = Item.create(:id => 1, :name => "name", :description => "description")
          s = i.item_clone_specs.create :name => "test clone spec", :attributes_to_clone => [ :name ]
          Item.all.size.should == 1
          ItemCloneSpec.all.size.should == 1

          clones = i.clone_resource(2, i.item_clone_specs.first.attributes_to_clone)

          Item.all.size.should == 3
          (0..1).each do |idx|
            clones[idx].name.should == 'name'
            clones[idx].description.should be_nil
          end

        end

      end

      describe "with two parameters, the last being an instance of String" do

        it "should produce the given number of clones with all given properties copied over" do

          i = Item.create(:id => 1, :name => "name", :description => "description")
          s = i.item_clone_specs.create :name => "test clone spec", :attributes_to_clone => [ :name ]
          Item.all.size.should == 1
          ItemCloneSpec.all.size.should == 1

          clones = i.clone_resource(2, "name")

          Item.all.size.should == 3
          (0..1).each do |idx|
            clones[idx].name.should == 'name'
            clones[idx].description.should be_nil
          end

        end

      end

      describe "with two parameters, the last being an instance of an unrecognized type" do

        it "should produce the given number of clones with all given properties copied over" do

          i = Item.create(:id => 1, :name => "name", :description => "description")
          Item.all.size.should == 1
          lambda { i.clone_resource(2, { :foo => :bar }) }.should raise_error(ArgumentError)
          Item.all.size.should == 1

        end

      end

      describe "with two parameters, the last being an unknown property" do

        it "should produce the given number of clones with all given properties copied over" do

          i = Item.create(:id => 1, :name => "name", :description => "description")
          Item.all.size.should == 1
          lambda { i.clone_resource(2, "foo") }.should raise_error(ArgumentError)
          Item.all.size.should == 1

        end

      end

    end

    describe "Item#has_clone_specs?" do

      before do

        unload_testing_models "ItemCloneSpec", "Item"

        class Item

          include DataMapper::Resource

          property :id,          Serial

          property :name,        String
          property :description, String

          is :cloneable

        end

        Item.auto_migrate!
        ItemCloneSpec.auto_migrate!

        @i = Item.create

      end

      it "should return false if no clone_specs are present" do
        @i.has_clone_specs?.should be_false
      end

      it "should return true if at least one clone_spec is present" do
        @i.item_clone_specs.create :name => "test clone spec", :attributes_to_clone => [ :name ]
        @i.has_clone_specs?.should be_true
      end

    end

    describe "Item#has_backlink_to_master?" do

      describe "with backlink id property defined" do

        before do

          unload_testing_models "ItemCloneSpec", "Item"

          class Item

            include DataMapper::Resource

            property :id,             Serial
            property :master_item_id, Integer

            property :name,           String
            property :description,    String

            is :cloneable

          end

          Item.auto_migrate!
          ItemCloneSpec.auto_migrate!

          @i = Item.create

        end

        it "should return true" do
          @i.has_backlink_to_master?.should be_true
        end

      end

      describe "without backlink id property defined" do

        before do

          unload_testing_models "ItemCloneSpec", "Item"

          class Item

            include DataMapper::Resource

            property :id,             Serial

            property :name,           String
            property :description,    String

            is :cloneable

          end

          Item.auto_migrate!
          ItemCloneSpec.auto_migrate!

          @i = Item.create

        end

        it "should return false" do
          @i.has_backlink_to_master?.should be_false
        end

      end

    end

    describe "Item#master_resource" do

      describe "when sent to an object which is no clone" do

        before do

          unload_testing_models "ItemCloneSpec", "Item"

          class Item

            include DataMapper::Resource

            property :id,             Serial
            property :master_item_id, Integer

            property :name,           String
            property :description,    String

            is :cloneable

          end

          Item.auto_migrate!
          ItemCloneSpec.auto_migrate!

          @i = Item.create

        end

        it "should return nil" do
          @i.master_resource.should be_nil
        end

      end

      describe "when sent to an object which is a clone" do

        before do

          unload_testing_models "ItemCloneSpec", "Item"

          class Item

            include DataMapper::Resource

            property :id,             Serial
            property :master_item_id, Integer

            property :name,           String
            property :description,    String

            is :cloneable

          end

          Item.auto_migrate!
          ItemCloneSpec.auto_migrate!

        end

        it "should return the correct master object" do
          i = Item.create
          c = i.clone_resource.first
          i.has_backlink_to_master?.should be_true
          c.master_resource.should == i
        end

      end

    end

    describe "Item#cloned_resources" do

      describe "when sent to an object which has no clones" do

        before do

          unload_testing_models "ItemCloneSpec", "Item"

          class Item

            include DataMapper::Resource

            property :id,             Serial
            property :master_item_id, Integer

            property :name,           String
            property :description,    String

            is :cloneable

          end

          Item.auto_migrate!
          ItemCloneSpec.auto_migrate!

        end

        it "should return an empty Array" do
          Item.create.cloned_resources.should be_empty
        end

      end

      describe "when sent to an object which has one or more clones" do

        before do

          unload_testing_models "ItemCloneSpec", "Item"

          class Item

            include DataMapper::Resource

            property :id,             Serial
            property :master_item_id, Integer

            property :name,           String
            property :description,    String

            is :cloneable

          end

          Item.auto_migrate!
          ItemCloneSpec.auto_migrate!

        end

        it "should return an array of all cloned objects" do
          i = Item.create
          i.cloned_resources.should be_empty

          c = i.clone_resource.first

          i.cloned_resources.should have(1).item
          i.cloned_resources.first.should == c
        end

      end

    end

  end

end


text:
package de.bwaldvogel.liblinear;

import static org.fest.assertions.Assertions.assertThat;
import static org.junit.Assert.fail;

import org.junit.Before;
import org.junit.Test;

public class ParameterTest {

    private Parameter _param;

    @Before
    public void setUp() {
        _param = new Parameter(SolverType.L2R_L1LOSS_SVC_DUAL, 100, 1e-3);
    }

    @Test
    public void testDefaults() {
        Parameter parameters = new Parameter(SolverType.L1R_LR, 1, 0.1);
        assertThat(parameters.getP()).isEqualTo(0.1);
        assertThat(parameters.getMaxIters()).isEqualTo(1000);
    }

    @Test
    public void testSetWeights() {

        assertThat(_param.weight).isNull();
        assertThat(_param.getNumWeights()).isEqualTo(0);

        double[] weights = new double[] {0, 1, 2, 3, 4, 5};
        int[] weightLabels = new int[] {1, 1, 1, 1, 2, 3};
        _param.setWeights(weights, weightLabels);

        assertThat(_param.getNumWeights()).isEqualTo(6);

        // assert parameter uses a copy
        weights[0]++;
        assertThat(_param.getWeights()[0]).isEqualTo(0);
        weightLabels[0]++;
        assertThat(_param.getWeightLabels()[0]).isEqualTo(1);

        weights = new double[] {0, 1, 2, 3, 4, 5};
        weightLabels = new int[] {1};
        try {
            _param.setWeights(weights, weightLabels);
            fail("IllegalArgumentException expected");
        } catch (IllegalArgumentException e) {
            assertThat(e.getMessage()).contains("same").contains("length");
        }
    }

    @Test
    public void testGetWeights() {
        double[] weights = new double[] {0, 1, 2, 3, 4, 5};
        int[] weightLabels = new int[] {1, 1, 1, 1, 2, 3};
        _param.setWeights(weights, weightLabels);

        assertThat(_param.getWeights()).isEqualTo(weights);
        _param.getWeights()[0]++; // shouldn't change the parameter as we should get a copy
        assertThat(_param.getWeights()).isEqualTo(weights);

        assertThat(_param.getWeightLabels()).isEqualTo(weightLabels);
        _param.getWeightLabels()[0]++; // shouldn't change the parameter as we should get a copy
        assertThat(_param.getWeightLabels()[0]).isEqualTo(1);
    }

    @Test
    public void testSetC() {
        _param.setC(0.0001);
        assertThat(_param.getC()).isEqualTo(0.0001);
        _param.setC(1);
        _param.setC(100);
        assertThat(_param.getC()).isEqualTo(100);
        _param.setC(Double.MAX_VALUE);

        try {
            _param.setC(-1);
            fail("IllegalArgumentException expected");
        } catch (IllegalArgumentException e) {
            assertThat(e.getMessage()).contains("must").contains("not").contains("<= 0");
        }

        try {
            _param.setC(0);
            fail("IllegalArgumentException expected");
        } catch (IllegalArgumentException e) {
            assertThat(e.getMessage()).contains("must").contains("not").contains("<= 0");
        }
    }

    @Test
    public void testSetEps() {
        _param.setEps(0.0001);
        assertThat(_param.getEps()).isEqualTo(0.0001);
        _param.setEps(1);
        _param.setEps(100);
        assertThat(_param.getEps()).isEqualTo(100);
        _param.setEps(Double.MAX_VALUE);

        try {
            _param.setEps(-1);
            fail("IllegalArgumentException expected");
        } catch (IllegalArgumentException e) {
            assertThat(e.getMessage()).contains("must").contains("not").contains("<= 0");
        }

        try {
            _param.setEps(0);
            fail("IllegalArgumentException expected");
        } catch (IllegalArgumentException e) {
            assertThat(e.getMessage()).contains("must").contains("not").contains("<= 0");
        }
    }

    @Test
    public void testSetSolverType() {
        for (SolverType type : SolverType.values()) {
            _param.setSolverType(type);
            assertThat(_param.getSolverType()).isEqualTo(type);
        }
        try {
            _param.setSolverType(null);
            fail("IllegalArgumentException expected");
        } catch (IllegalArgumentException e) {
            assertThat(e.getMessage()).contains("must").contains("not").contains("null");
        }
    }

}


text:
module IpsHelper
end