text:
'Title:     Loop Average
'Author:    Miguel Rodriguez
'Date:      3/22/2016
'Course:    CSC 162
'Section:   001
'Description:   This program will simulate the flip of a coin 100 times. it will
'   record how many times the coin has landed in head and tails. It then displays
'   how many times that coin landed in head and and how many times the coin landed
'   in tails. The user can play multiple times if he whishes to.
'
'Initial Algorithm:
'   1.  initilize counter to zero
'   2.  for a counter is less than 100
'   3.  create a random number in range between 1 to 2
'   4.  if random number is equal to 1 increase head counter by one
'   5.  if random number is equal to 2 increase the tails counter by one
'   6.  allows the user to keep playing if he wishes to
'   7.  provides the option to exit the program
'
'Data Requirements:
'   Input:
'
'   Output:
'       Calculates how many heads and tails
'       Displays how manay heads and tails to the user
'   Additional:
'       None
'
'Formulas:
'

Public Class frmFlipCoin

    Private Sub btnFlip_Click(sender As Object, e As EventArgs) Handles btnFlip.Click
        'Refined Algorithm
        ' Initialize global variables and contants
        ' Initialize local constants and variables
        '   FOR loopCounter is less than 100
        '       create a random number in range of 1 to 2
        '       IF random number is 1
        '          increase head counter by one
        '       ELSE
        '           increase tail counter by one
        '       END IF
        '     increase loop counter by one
        '  END FOR
        'Displays the head counter and tail counter
        ' Allows the user to exit the program by pressing a button
        ' Allows the user to repeat the program and initilizes the game
        '

        'Local constants

        'Local variables
        Dim headCounter As Integer
        Dim tailCounter As Integer
        Dim RanNum As Integer
        Dim loopCounter As Integer
        Dim counter As Integer

        For loopCounter = 1 To 100 'runs the loop from 1 to 100

            RanNum = Int((2 - 1 + 1) * Rnd()) + 1 'generates a random number from 1 to 2 and stores it into RanNum

            If RanNum = 1 Then 'if random number equals to 1 is heads
                headCounter += 1 'increase heads by one
            Else
                tailCounter += 1 'if random number is 2 increase tail by 1
            End If

        Next loopCounter

        'adds the total of heads and tails to a list box
        List1.Items.Add("Heads " & headCounter & " Tails " & tailCounter & vbTab)

    End Sub

    Private Sub Button1_Click(sender As Object, e As EventArgs) Handles btnExit.Click
        Me.Close() 'closes the application
        End
    End Sub

    Private Sub btnClear_Click(sender As Object, e As EventArgs) Handles btnClear.Click
        List1.Items.Clear() ' Remove all list items

    End Sub
End Class


text:
ACCEPTED

#### According to
Index Fungorum

#### Published in
Revis. gen. pl. (Leipzig) 3: 449 (1898)

#### Original name
Uromyces bonariensis Speg.

### Remarks
null

redpajama_set_name: RedPajamaGithub


text:
import {
  extend,
  bind,
  on,
  off,
  getAttr,
  getBindAttr,
  camelize,
  hyphenate,
  nextTick,
  warn
} from './util/index'
import Watcher from './watcher'
import { parseExpression, isSimplePath } from './parsers/expression'

function noop () {}

/**
 * A directive links a DOM element with a piece of data,
 * which is the result of evaluating an expression.
 * It registers a watcher with the expression and calls
 * the DOM update function when a change is triggered.
 *
 * @param {Object} descriptor
 *                 - {String} name
 *                 - {Object} def
 *                 - {String} expression
 *                 - {Array<Object>} [filters]
 *                 - {Object} [modifiers]
 *                 - {Boolean} literal
 *                 - {String} attr
 *                 - {String} arg
 *                 - {String} raw
 *                 - {String} [ref]
 *                 - {Array<Object>} [interp]
 *                 - {Boolean} [hasOneTime]
 * @param {Vue} vm
 * @param {Node} el
 * @param {Vue} [host] - transclusion host component
 * @param {Object} [scope] - v-for scope
 * @param {Fragment} [frag] - owner fragment
 * @constructor
 */

export default function Directive (descriptor, vm, el, host, scope, frag) {
  this.vm = vm
  this.el = el
  // copy descriptor properties
  this.descriptor = descriptor
  this.name = descriptor.name
  this.expression = descriptor.expression
  this.arg = descriptor.arg
  this.modifiers = descriptor.modifiers
  this.filters = descriptor.filters
  this.literal = this.modifiers && this.modifiers.literal
  // private
  this._locked = false
  this._bound = false
  this._listeners = null
  // link context
  this._host = host
  this._scope = scope
  this._frag = frag
  // store directives on node in dev mode
  if (process.env.NODE_ENV !== 'production' && this.el) {
    this.el._vue_directives = this.el._vue_directives || []
    this.el._vue_directives.push(this)
  }
}

/**
 * Initialize the directive, mixin definition properties,
 * setup the watcher, call definition bind() and update()
 * if present.
 */

Directive.prototype._bind = function () {
  var name = this.name
  var descriptor = this.descriptor

  // remove attribute
  if (
    (name !== 'cloak' || this.vm._isCompiled) &&
    this.el && this.el.removeAttribute
  ) {
    var attr = descriptor.attr || ('v-' + name)
    this.el.removeAttribute(attr)
  }

  // copy def properties
  var def = descriptor.def
  if (typeof def === 'function') {
    this.update = def
  } else {
    extend(this, def)
  }

  // setup directive params
  this._setupParams()

  // initial bind
  if (this.bind) {
    this.bind()
  }
  this._bound = true

  if (this.literal) {
    this.update && this.update(descriptor.raw)
  } else if (
    (this.expression || this.modifiers) &&
    (this.update || this.twoWay) &&
    !this._checkStatement()
  ) {
    // wrapped updater for context
    var dir = this
    if (this.update) {
      this._update = function (val, oldVal) {
        if (!dir._locked) {
          dir.update(val, oldVal)
        }
      }
    } else {
      this._update = noop
    }
    var preProcess = this._preProcess
      ? bind(this._preProcess, this)
      : null
    var postProcess = this._postProcess
      ? bind(this._postProcess, this)
      : null
    var watcher = this._watcher = new Watcher(
      this.vm,
      this.expression,
      this._update, // callback
      {
        filters: this.filters,
        twoWay: this.twoWay,
        deep: this.deep,
        preProcess: preProcess,
        postProcess: postProcess,
        scope: this._scope
      }
    )
    // v-model with inital inline value need to sync back to
    // model instead of update to DOM on init. They would
    // set the afterBind hook to indicate that.
    if (this.afterBind) {
      this.afterBind()
    } else if (this.update) {
      this.update(watcher.value)
    }
  }
}

/**
 * Setup all param attributes, e.g. track-by,
 * transition-mode, etc...
 */

Directive.prototype._setupParams = function () {
  if (!this.params) {
    return
  }
  var params = this.params
  // swap the params array with a fresh object.
  this.params = Object.create(null)
  var i = params.length
  var key, val, mappedKey
  while (i--) {
    key = hyphenate(params[i])
    mappedKey = camelize(key)
    val = getBindAttr(this.el, key)
    if (val != null) {
      // dynamic
      this._setupParamWatcher(mappedKey, val)
    } else {
      // static
      val = getAttr(this.el, key)
      if (val != null) {
        this.params[mappedKey] = val === '' ? true : val
      }
    }
  }
}

/**
 * Setup a watcher for a dynamic param.
 *
 * @param {String} key
 * @param {String} expression
 */

Directive.prototype._setupParamWatcher = function (key, expression) {
  var self = this
  var called = false
  var unwatch = (this._scope || this.vm).$watch(expression, function (val, oldVal) {
    self.params[key] = val
    // since we are in immediate mode,
    // only call the param change callbacks if this is not the first update.
    if (called) {
      var cb = self.paramWatchers && self.paramWatchers[key]
      if (cb) {
        cb.call(self, val, oldVal)
      }
    } else {
      called = true
    }
  }, {
    immediate: true,
    user: false
  })
  ;(this._paramUnwatchFns || (this._paramUnwatchFns = [])).push(unwatch)
}

/**
 * Check if the directive is a function caller
 * and if the expression is a callable one. If both true,
 * we wrap up the expression and use it as the event
 * handler.
 *
 * e.g. on-click="a++"
 *
 * @return {Boolean}
 */

Directive.prototype._checkStatement = function () {
  var expression = this.expression
  if (
    expression && this.acceptStatement &&
    !isSimplePath(expression)
  ) {
    var fn = parseExpression(expression).get
    var scope = this._scope || this.vm
    var handler = function (e) {
      scope.$event = e
      fn.call(scope, scope)
      scope.$event = null
    }
    if (this.filters) {
      handler = scope._applyFilters(handler, null, this.filters)
    }
    this.update(handler)
    return true
  }
}

/**
 * Set the corresponding value with the setter.
 * This should only be used in two-way directives
 * e.g. v-model.
 *
 * @param {*} value
 * @public
 */

Directive.prototype.set = function (value) {
  /* istanbul ignore else */
  if (this.twoWay) {
    this._withLock(function () {
      this._watcher.set(value)
    })
  } else if (process.env.NODE_ENV !== 'production') {
    warn(
      'Directive.set() can only be used inside twoWay' +
      'directives.'
    )
  }
}

/**
 * Execute a function while preventing that function from
 * triggering updates on this directive instance.
 *
 * @param {Function} fn
 */

Directive.prototype._withLock = function (fn) {
  var self = this
  self._locked = true
  fn.call(self)
  nextTick(function () {
    self._locked = false
  })
}

/**
 * Convenience method that attaches a DOM event listener
 * to the directive element and autometically tears it down
 * during unbind.
 *
 * @param {String} event
 * @param {Function} handler
 * @param {Boolean} [useCapture]
 */

Directive.prototype.on = function (event, handler, useCapture) {
  on(this.el, event, handler, useCapture)
  ;(this._listeners || (this._listeners = []))
    .push([event, handler])
}

/**
 * Teardown the watcher and call unbind.
 */

Directive.prototype._teardown = function () {
  if (this._bound) {
    this._bound = false
    if (this.unbind) {
      this.unbind()
    }
    if (this._watcher) {
      this._watcher.teardown()
    }
    var listeners = this._listeners
    var i
    if (listeners) {
      i = listeners.length
      while (i--) {
        off(this.el, listeners[i][0], listeners[i][1])
      }
    }
    var unwatchFns = this._paramUnwatchFns
    if (unwatchFns) {
      i = unwatchFns.length
      while (i--) {
        unwatchFns[i]()
      }
    }
    if (process.env.NODE_ENV !== 'production' && this.el) {
      this.el._vue_directives.$remove(this)
    }
    this.vm = this.el = this._watcher = this._listeners = null
  }
}


text:
/**
 * Tests color palette.
 */
(function() {

  module('ColorPalette');

  /**
   * Convert rgb to hexadecimal value.
   */
  test('convertRgbToHex', function() {
    equal(bitmapper.rgbToHex('rgb(255, 102, 0)'), '#ff6600',
          'Correct rgb to hex conversion');
    equal(bitmapper.rgbToHex('rgb(0, 153, 255)'), '#0099ff',
          'Correct rgb to hex conversion');
    equal(bitmapper.rgbToHex('rgb(255, 255, 255)'), '#ffffff',
          'Correct rgb to hex conversion');
  });

  /**
   * Convert rgb to an array.
   */
  test('convertRgbaToArray', function() {
    deepEqual(bitmapper.rgbaToArray('rgba(255, 102, 0, 0.5)'),
              [255, 102, 0, 127],
              'Correct rgb to hex conversion');
    deepEqual(bitmapper.rgbaToArray('rgba(0, 153, 255, 1)'),
              [0, 153, 255, 255],
              'Correct rgb to hex conversion');
    deepEqual(bitmapper.rgbaToArray('rgba(255, 255, 255, 0)'),
              [255, 255, 255, 0],
              'Correct rgb to hex conversion');
  });

  /**
   * Check selected color.
   */
  test('selectionEvent', function(palette, colorPalette) {
    // Expect 2 assertions:
    // 1. Triggering of core-select event.
    // 2. Color set correctly on color-palette.
    expect(2);
    var colorPalette = bitmapper_test.initializeColorPalette();
    var palette = bitmapper_test.createPalette();

    // Attach the event listener.
    colorPalette.initializePalette(palette, function() {
      ok(true, 'Change selected cell color on core-select event');
    });

    // Create a clickable paper-button element, with black background to model
    // a user selection on the button.
    var paperButton = document.createElement('paper-button');
    paperButton.style.backgroundColor = '#ff0000';
    // Set the initial selection to the paperButton.
    // Note that the initial core-select event will not get triggered until
    // after the test finishes. So trigger this event manually.
    colorPalette.setSelectedCell(paperButton);

    // Create core-select event and populate with necessary properties for event
    // listener added in setup.js.
    var coreSelect = new CustomEvent('core-select', {
      'detail': {
        'item': paperButton,
        'isSelected': true
      }
    });
    // Trigger core-select on palette.
    // Expect an assertion here from calling function.
    palette.dispatchEvent(coreSelect);

    // Check button color
    equal(colorPalette.getSelectedColor(), 'rgb(255, 0, 0)',
          'Initial color set on colorPalette');

    // Test deselection of the event by triggering the event again, with
    // isSelected property set to false.
    coreSelect = new CustomEvent('core-select', {
      'detail': {
        'item': paperButton,
        'isSelected': false
      }
    });

    // Trigger core-select on palette.
    // There should be no assertion here, as for the deselection case.
    palette.dispatchEvent(coreSelect);
  });

  /**
   * Update selected cell color with selected color.
   */
  test('updateColorPalette', function() {
    var colorPalette = bitmapper_test.initializeColorPalette();
    colorPalette.updateCellColor('rgb(64, 224, 208)');
    // Check background of selected palette cell changes.
    var backgroundColor = colorPalette.getSelectedColor();
    equal(backgroundColor, 'rgb(64, 224, 208)',
          'Color palette cell updated with selected color');
  });

  /**
   * Testing adding opacity to color (rgb to rgba).
   */
  test('rgbaFormat', function() {
    var colorPalette = bitmapper_test.initializeColorPalette();
    // Change color, alter opacity and check resulting rgba.
    colorPalette.updateCellColor('#ff0000');
    colorPalette.setOpacity(1);
    equal(colorPalette.getSelectedColorWithOpacity(), 'rgba(255, 0, 0, 1)');

    colorPalette.updateCellColor('#ffff00');
    colorPalette.setOpacity(0.2);
    equal(colorPalette.getSelectedColorWithOpacity(), 'rgba(255, 255, 0, 0.2)');

    colorPalette.updateCellColor('#0000ff');
    colorPalette.setOpacity(0.053);
    equal(colorPalette.getSelectedColorWithOpacity(), 'rgba(0, 0, 255, 0.053)');

    colorPalette.updateCellColor('#ff00ff');
    colorPalette.setOpacity(0);
    equal(colorPalette.getSelectedColorWithOpacity(), 'rgba(255, 0, 255, 0)');
  });
})();


text:
namespace Xunit.AutoDisplayNameAttributes
{
    using System;
    using System.Runtime.CompilerServices;

    public static partial class Theory
    {
        public static partial class FormatDisplayName
        {
            /// <summary>
            ///     The <see cref="FactAttribute.DisplayName"/> will be set as the test method's name, but with
            ///     underscores being replaced with a space (e.g. "Test_Method()" => "Test Method").
            /// </summary>
            [AttributeUsage(AttributeTargets.Method, AllowMultiple = false)]
            [Xunit.Sdk.XunitTestCaseDiscoverer("Xunit.Sdk.TheoryDiscoverer", "xunit.execution.{Platform}")]
            public class ReplaceUnderscoresWithSpacesAttribute : Fact.FormatDisplayName.ReplaceUnderscoresWithSpacesAttribute
            {
                /// <summary>
                ///     Creates a new instance of the <see cref="ReplaceUnderscoresWithSpacesAttribute"/> class.
                /// </summary>
                /// <param name="DisplayName">
                ///     This is automatically set to the name of the current method decorated with this attribute;
                ///     there's no need to specify a value for this parameter.
                /// </param>
                /// <example>
                /// <code lang="cs">
                /// [Theory.FormatDisplayName.ReplaceUnderscoresWithSpacesAttribute, ClassData(typeof(TestData))]
                /// public void Title_Case_Method_with_Underscores()
                /// {
                ///     // Test code goes here...
                ///     // DisplayName will be set to "Title Case Method with Underscores"
                /// }
                /// </code>
                /// </example>
                public ReplaceUnderscoresWithSpacesAttribute([CallerMemberName] string DisplayName = null)
                    : base(DisplayName)
                { }
            }
        }
    }
}


text:
module Subscribem
  class Account < ActiveRecord::Base
    attr_accessible :name, :subdomain, :owner_attributes
    validates :subdomain, :presence => true, :uniqueness => true

    belongs_to :owner, :class_name => "Subscribem::User"
    accepts_nested_attributes_for :owner

  end
end


text:
/*
*= require spree/frontend
*= require_tree .
*/


text:
<!DOCTYPE html>

    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width, initial-scale=1">

    <title>{% block page_title %}{% endblock %}</title>
    <link rel="stylesheet" type="text/css" href="/stylesheets/app.css">
    <link rel="stylesheet" type="text/css" href="https://assets.nhs.uk/fonts/nhsuk-fonts-1.1.0.css">
    {% block html_head %}{% endblock %}

    {% include '_includes/service-alert.html' %}

    {% block header_before %}{% endblock %}

    {% include '_includes/masthead-signed-in.html' %}

      {% block content %}{% endblock %}

      {% block rightcol %}{% endblock %}

    {% include '_includes/footer.html' %}

    {% block body_after %}{% endblock %}


text:
import React from 'react'
import Button from '../../button'
import Section from '../section'
import Plugin from './plugin'
import screenSizes from '../../../lib/screen-sizes'
import CompassIcon from '../../../static/images/compass.svg'
import DownloadIcon from '../../../static/images/download-white.svg'

const Plugins = () => (

The power of open-source

The ease of use and speed you've been looking for – the functionality and extensibility you didn't know you needed.

            <Plugin title="giphy" color="#ffd500" description="Share GIFs on Giphy" href="https://github.com/wulkano/kap-giphy" />
            <Plugin
              title="now"
              color="#FFF"
              description="Deploy with ZEIT Now   "
              href="https://github.com/lucaperret/kap-now"
            />
            <Plugin title="streamable" color="#00ffbe" description="Upload to Streamable" href="https://github.com/kevva/kap-streamable" />

)

export default Plugins


text:
'''Problem 1 from project Euler: Multiples of 3 and 5
https://projecteuler.net/problem=1'''

RESULT = 233168

def solve():
    '''Main function'''

    max_num = 1000
    return sum([x for x in xrange(max_num) if x % 3 == 0 or x % 5 == 0])

if __name__ == '__main__':
    print solve()


text:
from pathlib import Path

from vnpy.trader.app import BaseApp

from .engine import AlgoEngine, APP_NAME
from .template import AlgoTemplate

class AlgoTradingApp(BaseApp):
    """"""

    app_name = APP_NAME
    app_module = __module__
    app_path = Path(__file__).parent
    display_name = "算法交易"
    engine_class = AlgoEngine
    widget_name = "AlgoManager"
    icon_name = "algo.ico"


text:
package eviction

import (
	"fmt"
	"strings"
	"sync"
	"testing"
	"time"

	gomock "github.com/golang/mock/gomock"
	"k8s.io/apimachinery/pkg/api/resource"
	statsapi "k8s.io/kubelet/pkg/apis/stats/v1alpha1"
	evictionapi "k8s.io/kubernetes/pkg/kubelet/eviction/api"
)

const testCgroupPath = "/sys/fs/cgroups/memory"

func nodeSummary(available, workingSet, usage resource.Quantity, allocatable bool) *statsapi.Summary {
	availableBytes := uint64(available.Value())
	workingSetBytes := uint64(workingSet.Value())
	usageBytes := uint64(usage.Value())
	memoryStats := statsapi.MemoryStats{
		AvailableBytes:  &availableBytes,
		WorkingSetBytes: &workingSetBytes,
		UsageBytes:      &usageBytes,
	}
	if allocatable {
		return &statsapi.Summary{
			Node: statsapi.NodeStats{
				SystemContainers: []statsapi.ContainerStats{
					{
						Name:   statsapi.SystemContainerPods,
						Memory: &memoryStats,
					},
				},
			},
		}
	}
	return &statsapi.Summary{
		Node: statsapi.NodeStats{
			Memory: &memoryStats,
		},
	}
}

func newTestMemoryThresholdNotifier(threshold evictionapi.Threshold, factory NotifierFactory, handler func(string)) *memoryThresholdNotifier {
	return &memoryThresholdNotifier{
		threshold:  threshold,
		cgroupPath: testCgroupPath,
		events:     make(chan struct{}),
		factory:    factory,
		handler:    handler,
	}
}

func TestUpdateThreshold(t *testing.T) {
	testCases := []struct {
		description        string
		available          resource.Quantity
		workingSet         resource.Quantity
		usage              resource.Quantity
		evictionThreshold  evictionapi.Threshold
		expectedThreshold  resource.Quantity
		updateThresholdErr error
		expectErr          bool
	}{
		{
			description: "node level threshold",
			available:   resource.MustParse("3Gi"),
			usage:       resource.MustParse("2Gi"),
			workingSet:  resource.MustParse("1Gi"),
			evictionThreshold: evictionapi.Threshold{
				Signal:   evictionapi.SignalMemoryAvailable,
				Operator: evictionapi.OpLessThan,
				Value: evictionapi.ThresholdValue{
					Quantity: quantityMustParse("1Gi"),
				},
			},
			expectedThreshold:  resource.MustParse("4Gi"),
			updateThresholdErr: nil,
			expectErr:          false,
		},
		{
			description: "allocatable threshold",
			available:   resource.MustParse("4Gi"),
			usage:       resource.MustParse("3Gi"),
			workingSet:  resource.MustParse("1Gi"),
			evictionThreshold: evictionapi.Threshold{
				Signal:   evictionapi.SignalAllocatableMemoryAvailable,
				Operator: evictionapi.OpLessThan,
				Value: evictionapi.ThresholdValue{
					Quantity: quantityMustParse("1Gi"),
				},
			},
			expectedThreshold:  resource.MustParse("6Gi"),
			updateThresholdErr: nil,
			expectErr:          false,
		},
		{
			description: "error updating node level threshold",
			available:   resource.MustParse("3Gi"),
			usage:       resource.MustParse("2Gi"),
			workingSet:  resource.MustParse("1Gi"),
			evictionThreshold: evictionapi.Threshold{
				Signal:   evictionapi.SignalMemoryAvailable,
				Operator: evictionapi.OpLessThan,
				Value: evictionapi.ThresholdValue{
					Quantity: quantityMustParse("1Gi"),
				},
			},
			expectedThreshold:  resource.MustParse("4Gi"),
			updateThresholdErr: fmt.Errorf("unexpected error"),
			expectErr:          true,
		},
	}

	mockCtrl := gomock.NewController(t)
	defer mockCtrl.Finish()

	for _, tc := range testCases {
		t.Run(tc.description, func(t *testing.T) {
			notifierFactory := NewMockNotifierFactory(mockCtrl)
			notifier := NewMockCgroupNotifier(mockCtrl)

			m := newTestMemoryThresholdNotifier(tc.evictionThreshold, notifierFactory, nil)
			notifierFactory.EXPECT().NewCgroupNotifier(testCgroupPath, memoryUsageAttribute, tc.expectedThreshold.Value()).Return(notifier, tc.updateThresholdErr).Times(1)
			var events chan<- struct{} = m.events
			notifier.EXPECT().Start(events).Return().AnyTimes()
			err := m.UpdateThreshold(nodeSummary(tc.available, tc.workingSet, tc.usage, isAllocatableEvictionThreshold(tc.evictionThreshold)))
			if err != nil && !tc.expectErr {
				t.Errorf("Unexpected error updating threshold: %v", err)
			} else if err == nil && tc.expectErr {
				t.Errorf("Expected error updating threshold, but got nil")
			}
		})
	}
}

func TestStart(t *testing.T) {
	noResources := resource.MustParse("0")
	threshold := evictionapi.Threshold{
		Signal:   evictionapi.SignalMemoryAvailable,
		Operator: evictionapi.OpLessThan,
		Value: evictionapi.ThresholdValue{
			Quantity: &noResources,
		},
	}
	mockCtrl := gomock.NewController(t)
	defer mockCtrl.Finish()
	notifierFactory := NewMockNotifierFactory(mockCtrl)
	notifier := NewMockCgroupNotifier(mockCtrl)

	var wg sync.WaitGroup
	wg.Add(4)
	m := newTestMemoryThresholdNotifier(threshold, notifierFactory, func(string) {
		wg.Done()
	})
	notifierFactory.EXPECT().NewCgroupNotifier(testCgroupPath, memoryUsageAttribute, int64(0)).Return(notifier, nil).Times(1)

	var events chan<- struct{} = m.events
	notifier.EXPECT().Start(events).Return()
	notifier.EXPECT().Stop().Return().AnyTimes()

	err := m.UpdateThreshold(nodeSummary(noResources, noResources, noResources, isAllocatableEvictionThreshold(threshold)))
	if err != nil {
		t.Errorf("Unexpected error updating threshold: %v", err)
	}

	go m.Start()

	for i := 0; i < 4; i++ {
		m.events <- struct{}{}
	}
	wg.Wait()
}

func TestThresholdDescription(t *testing.T) {
	testCases := []struct {
		description        string
		evictionThreshold  evictionapi.Threshold
		expectedSubstrings []string
		omittedSubstrings  []string
	}{
		{
			description: "hard node level threshold",
			evictionThreshold: evictionapi.Threshold{
				Signal:   evictionapi.SignalMemoryAvailable,
				Operator: evictionapi.OpLessThan,
				Value: evictionapi.ThresholdValue{
					Quantity: quantityMustParse("2Gi"),
				},
			},
			expectedSubstrings: []string{"hard"},
			omittedSubstrings:  []string{"allocatable", "soft"},
		},
		{
			description: "soft node level threshold",
			evictionThreshold: evictionapi.Threshold{
				Signal:   evictionapi.SignalMemoryAvailable,
				Operator: evictionapi.OpLessThan,
				Value: evictionapi.ThresholdValue{
					Quantity: quantityMustParse("2Gi"),
				},
				GracePeriod: time.Minute * 2,
			},
			expectedSubstrings: []string{"soft"},
			omittedSubstrings:  []string{"allocatable", "hard"},
		},
		{
			description: "hard allocatable threshold",
			evictionThreshold: evictionapi.Threshold{
				Signal:   evictionapi.SignalAllocatableMemoryAvailable,
				Operator: evictionapi.OpLessThan,
				Value: evictionapi.ThresholdValue{
					Quantity: quantityMustParse("2Gi"),
				},
				GracePeriod: time.Minute * 2,
			},
			expectedSubstrings: []string{"soft", "allocatable"},
			omittedSubstrings:  []string{"hard"},
		},
		{
			description: "soft allocatable threshold",
			evictionThreshold: evictionapi.Threshold{
				Signal:   evictionapi.SignalAllocatableMemoryAvailable,
				Operator: evictionapi.OpLessThan,
				Value: evictionapi.ThresholdValue{
					Quantity: quantityMustParse("2Gi"),
				},
			},
			expectedSubstrings: []string{"hard", "allocatable"},
			omittedSubstrings:  []string{"soft"},
		},
	}

	for _, tc := range testCases {
		t.Run(tc.description, func(t *testing.T) {
			m := &memoryThresholdNotifier{
				notifier:   &MockCgroupNotifier{},
				threshold:  tc.evictionThreshold,
				cgroupPath: testCgroupPath,
			}
			desc := m.Description()
			for _, expected := range tc.expectedSubstrings {
				if !strings.Contains(desc, expected) {
					t.Errorf("expected description for notifier with threshold %+v to contain %s, but it did not", tc.evictionThreshold, expected)
				}
			}
			for _, omitted := range tc.omittedSubstrings {
				if strings.Contains(desc, omitted) {
					t.Errorf("expected description for notifier with threshold %+v NOT to contain %s, but it did", tc.evictionThreshold, omitted)
				}
			}
		})
	}
}


text:
{-|

THE XOR GAME

This file implements the server for a game in which each player makes 2 choices:
which bit, zero or one, to XOR with every other player's choice of bit;
and which bit, zero or one, the player bets will be the outcome of this XOR.
The XOR takes place every twenty seconds. A player gains a point when
their bet matches the outcome. Points accumulate without limit or reward.

I chose to implement this game because it is in some sense "minimal":
each player has exactly one bit of influence on the outcome. On the other hand,
in some sense every player holds the outcome of the game in her hands!

Previously, I tried to implement this game using a simple HTTP server
but I quickly realized that the request-response model is insufficient
to model a game which takes place in real time. So I used WebSockets.
Communication with the client takes place with JSON messages.

I hope you enjoy reading it! Suggestions and pull requests welcome.

-}

{-# LANGUAGE OverloadedStrings #-}
{-# LANGUAGE TemplateHaskell   #-}

import Prelude                 hiding (putStrLn)
import Control.Applicative            ((<$>), (<*>))
import Control.Concurrent             (forkIO, threadDelay,
                                       MVar, newMVar, modifyMVar_, readMVar)
import Control.Exception              (fromException)
import Control.Lens                   (makeLenses, over, view, set)
import Control.Monad                  (forever, forM, forM_)
import Control.Monad.IO.Class         (liftIO)
import Data.Aeson                     (Value(Number, Object), ToJSON, FromJSON,
                                       (.=), (.:?), object, toJSON, parseJSON,
                                       decode)
import Data.Aeson.Encode              (fromValue)
import Data.Attoparsec.Number         (Number(I))
import Data.ByteString.Lazy           (fromStrict)
import Data.Text                      (Text, append, pack)
import Data.Text.Encoding             (encodeUtf8)
import Data.Text.IO                   (putStrLn)
import Data.Text.Lazy                 (toStrict)
import Data.Text.Lazy.Builder         (toLazyText)
import Web.Scotty                     (file, get, header, scotty)
import qualified Network.WebSockets as WS

-- data types and their instances

data Bit = Zero | One deriving (Show, Read, Eq, Ord)

instance Num Bit where
  x + y         = if x == y then Zero else One
  One * One     = One
  _   * _       = Zero
  abs           = id
  signum        = id
  fromInteger n = if even n then Zero else One

instance ToJSON Bit where
  toJSON Zero = Number 0
  toJSON One  = Number 1

instance FromJSON Bit where
  parseJSON (Number (I k)) = return $ fromInteger k
  parseJSON _              = fail "not a bit"

data Update = Update {
    updatePlay :: Maybe Bit
  , updateBet  :: Maybe Bit
  } deriving Show

-- ugly!
instance ToJSON Update where
  toJSON update = case (updatePlay update, updateBet update) of
    (Just playBit, Just betBit) -> object ["play" .= playBit, "bet" .= betBit]
    (Just playBit, Nothing    ) -> object ["play" .= playBit]
    (Nothing     , Just betBit) -> object ["bet"  .= betBit ]
    (Nothing     , Nothing    ) -> object []

instance FromJSON Update where
  -- All fields are optional, so we accept ANY object. Reject other JSON types.
  parseJSON (Object v) = Update <$> v .:? "play" <*> v .:? "bet"
  parseJSON _          = fail "invalid update"

type ServerState = [Client]

data Client = Client {
    _nick    :: Text
  , _score   :: Int
  , _play    :: Bit
  , _bet     :: Bit
  , _channel :: WS.Sink WS.Hybi00
  }

$(makeLenses ''Client)

-- { "name": _nick, "score": _score }
instance ToJSON Client where
  toJSON client =
    object ["name"  .= view nick client,
            "score" .= Number (fromIntegral $ view score client)]

instance Show Client where
  show = show . toJSON

-- Client helper functions

newClient :: Text -> WS.Sink WS.Hybi00 -> Client
newClient    name    chan               = Client {
    _nick    = name
  , _score   = 0
  , _play    = 0
  , _bet     = 0
  , _channel = chan
  }

nameUnique :: Text -> ServerState -> Bool
nameUnique    name  = notElem name . map (view nick)

-- main loop uses nameUnique before this function can be reached
addClient :: Client -> ServerState -> ServerState
addClient  = (:)

-- remove clients by name, ignoring other fields
removeClient :: Client -> ServerState -> ServerState
removeClient    client  = filter $ \c -> view nick c /= view nick client

incrementScore :: Client -> Client
incrementScore  = score `over` (+1)

-- ugly!
updateClient :: Update -> Client -> Client
updateClient    update    client = case (updatePlay update, updateBet update) of
  (Just playBit, Just betBit) -> set play playBit $ set bet betBit client
  (Just playBit, Nothing    ) -> set play playBit client
  (Nothing     , Just betBit) -> set bet  betBit client
  (Nothing     , Nothing    ) -> client

-- game mechanic
xor :: ServerState -> Bit
xor  = sum . map (view bet)

-- client-server communication

-- Any Object is parsed into a Right Update; all keys except "play" and "bet"
-- are ignored. The value should be a 0 or 1 in either case.
-- Anything else (String, Number, etc.) is transmitted as chat (Left Text)
parseMessage :: Text -> Either Text Update
parseMessage    msg =
  maybe (Left msg) Right (decode . fromStrict $ encodeUtf8 msg)

-- helper functions below ensure msg has correct JSON encoding
broadcast :: Text -> ServerState -> IO ()
broadcast    msg     clients      = do
  putStrLn $ "BROADCAST: " `append` msg -- log to console
  forM_ clients $ \client ->
    WS.sendSink (view channel client) (WS.textData msg)

-- for these next functions, cf. client.js's onMessage

encodeObject :: ToJSON a => Text     -> a -> Text
encodeObject                typename    obj =
  toStrict . toLazyText . fromValue $ object ["type" .= typename, "data" .= obj]

warning :: Text -> Text
warning    msg   = encodeObject "warning" $ object ["warning" .= msg]

initialize :: ServerState -> Text
initialize    clients      = encodeObject "initialize" $
  object ["play" .= Zero, "bet" .= Zero, "scoreboard" .= clients]

confirmUpdate :: Update -> Text
confirmUpdate  = encodeObject "update"

scoreboard :: ServerState -> Text
scoreboard    clients      = encodeObject "scoreboard" $
  object ["scoreboard" .= clients, "result" .= xor clients]

joined :: Client -> Text
joined    client  = encodeObject "joined" $ object ["name" .= view nick client]

left :: Client -> Text
left    client  = encodeObject "left" $ object ["name" .= view nick client]

chat :: Client -> Text -> Text
chat    client    msg   = encodeObject "chat" $
  object ["message" .= (view nick client `append` ": " `append` msg)]

-- main logic
main :: IO ()
main  = do
  state <- newMVar []
  _     <- forkIO static
  _     <- forkIO $ xorAndUpdate state
  putStrLn "opened XOR game chat room..."
  WS.runServer "0.0.0.0" 8080 (game state)

static :: IO ()
static = scotty 80 $ do
  let prefix = "/vagrant/client/"

  get "/" $ do
    header "content-type" "text/html"
    file $ prefix ++ "index.html"

  get "/screen.css" $ do
    header "content-type" "text/css"
    file $ prefix ++ "screen.css"

  get "/client.js" $ do
    header "content-type" "text/JavaScript"
    file $ prefix ++ "client.js"

-- Every delay microseconds, compare each connected client's bet to the xor of
-- all the clients' plays: if it is different, the client's state is unaltered;
--                         if it is the same, the client's score is incremented
xorAndUpdate :: MVar ServerState -> IO ()
xorAndUpdate    state             = forever $ do
    threadDelay delay
    modifyMVar_ state $ \clients -> do
        updatedClients <- forM clients $ \client ->
            return $ if xor clients == view bet client
                     then incrementScore client
                     else client
        broadcast (scoreboard updatedClients) updatedClients
        return updatedClients
    where
      delay = 2 * 10^7 -- twenty seconds

-- possibility of subtle races, resulting in two people with same name?
getName :: MVar ServerState -> WS.WebSockets WS.Hybi00 Text
getName    state             = do
  name    <- WS.receiveData
  clients <- liftIO $ readMVar state
  if nameUnique name clients
    then return name
    else do WS.sendTextData $ warning "That nickname is taken. Choose another"
            getName state

game :: MVar ServerState -> WS.Request -> WS.WebSockets WS.Hybi00 ()
game    state               req         = do
  WS.acceptRequest req
  sink <- WS.getSink
  name <- getName state
  let client = newClient name sink
  liftIO $ modifyMVar_ state $ \clients -> do
      WS.sendSink sink $ WS.textData $ initialize clients
      broadcast (joined client) clients
      return $ addClient client clients
  talk state client

talk :: MVar ServerState -> Client -> WS.WebSockets WS.Hybi00 ()
talk    state               player  =
  flip WS.catchWsError catchDisconnect $ forever $ do
      input <- WS.receiveData
      case parseMessage input of
        Left  msg    -> liftIO $ readMVar state >>= broadcast (chat player msg)
        Right update -> do
            liftIO $ modifyMVar_ state $ \clients ->
                let newPlayer = updateClient update player
                in  return $ addClient newPlayer $ removeClient player clients
            WS.sendTextData $ confirmUpdate update
  where
    catchDisconnect e = case fromException e of
      Just WS.ConnectionClosed -> liftIO $ modifyMVar_ state $ \s -> do
          let s' = removeClient player s
          broadcast (left player) s'
          return s'
      _  -> liftIO . putStrLn $ "unexpected error: " `append`
            pack (show player)  `append` " encountered "  `append` pack (show e)


text:
/**
 * This package is not annotated.
 */
package given.reflect.root.branch1.foo.sub2;


text:
var video = document.querySelector("video"),
    isPlay = document.querySelector(".switch"),
    togglePlay = document.querySelector(".playPause"),
    expand = document.querySelector(".expand"),
    progress = document.querySelector(".progress"),
    loaded = document.querySelector(".progress > .loaded"),
    currPlayTime = document.querySelector(".timer > .current"),
    totalTime = document.querySelector(".timer > .total");

//当视频可播放的时候
video.oncanplay = function(){
    //显示视频
    this.style.display = "block";
    //显示播放与暂停按钮
    togglePlay.classList.remove("loadingVideo");
    //显示视频总时长
    totalTime.innerHTML = getFormatTime(this.duration);
};
//设置点击屏幕就让其播放或暂停
video.onclick = function(){
    var videoToggleIcon = document.querySelector(".playPause > .fa-SwitchVideo");
    if(video.paused) {
        video.play();
        videoToggleIcon.classList.add("videoPause");
        //videoToggleIcon.classList.toggle("fa-pause") //可以切换播放与暂停按钮,暂时没用
    } else {
        video.pause();
        videoToggleIcon.classList.toggle("videoPause");
    }
    isPlay.classList.toggle("fa-pause");
};

//视频中间按钮切换播放与暂停
togglePlay.onclick = function(){
    video.onclick();
};

//下栏播放按钮控制
isPlay.onclick = function(){
    var videoToggleIcon = document.querySelector(".playPause > .fa-SwitchVideo");
    if(video.paused) {
        video.play();
        videoToggleIcon.classList.add("videoPause");
    } else {
        video.pause();
        videoToggleIcon.classList.remove("videoPause");
        this.classList.toggle("fa-plause");
    }
    this.classList.toggle("fa-pause");
};

//全屏
expand.onclick = function(){
    video.webkitRequestFullScreen();
};

//播放进度
video.ontimeupdate = function(){
    var currTime = this.currentTime,    //当前播放时间
        duration = this.duration;       // 视频总时长
    //百分比
    var pre = currTime / duration * 100 + "%";
    //显示进度条
    loaded.style.width = pre;

    //显示当前播放进度时间
    currPlayTime.innerHTML = getFormatTime(currTime);
};

//跳跃播放
progress.onclick = function(e){
    var event = e || window.event;
    video.currentTime = (event.offsetX / this.offsetWidth) * video.duration;
};

//播放完毕还原设置
video.onended = function(){
    //切换播放按钮状态
    isPlay.classList.remove("fa-pause");
    isPlay.classList.add("fa-play");
    //进度条为0
    loaded.style.width = 0;
    //还原当前播放时间
    currPlayTime.innerHTML = getFormatTime();
    //视频恢复到播放开始状态
    video.currentTime = 0;
};
//时间进度处理
function getFormatTime(time) {
    var time = time || 0;

    var h = parseInt(time/3600),
        m = parseInt(time%3600/60),
        s = parseInt(time%60);
    h = h < 10 ? "0"+h : h;
    m = m < 10 ? "0"+m : m;
    s = s < 10 ? "0"+s : s;

    return h+":"+m+":"+s;
}


text:
using BeyondEarthApp.Web.Api.Models;
using BeyondEarthApp.Web.Api.Models.Precis;

namespace BeyondEarthApp.Web.Api.LinkServices.Precis
{
    public interface IUnitPrecisLinkService
    {
        void AddSelfLink(UnitPrecis unit);

        Link GetAllUnitsLink();
    }
}


text:
<?php
error_reporting(E_ALL);
ini_set('display_errors', 1);

define('PROJECT_ROOT', realpath(__DIR__ . '/..'));

require_once PROJECT_ROOT . '/vendor/autoload.php';


text:
<!DOCTYPE html>

		<meta name="viewport" content="width=device-width, initial-scale=1.0">
		<link href="/css/bootstrap.min.css" rel="stylesheet" media="screen">

		<link href="/css/styles.css" rel="stylesheet">
        <meta name="viewport" content="width-device-width, initial-scale=1.0">
		{% if title %}
			<title>{{ title }}</title>
			{% else %}
			<title>Welcome to My Movie DB</title>
		{% endif %}

					<button type="button" class="navbar-toggle collapsed" data-toggle="collapse" data-target="#home" aria-expanded="false">
						Toggle navigation

					</button>

Genres

Recent Adds

3D

Top Rated

Random Movies

Movie List

<form class="navbar-form" role="search" action="/search" method=post>
                            {{ form.hidden_tag() }}
								<input type="search" class="form-control" name="search" placeholder="Search Movie Titles">
							<button type="submit" class="btn btn-default"></button>
						</form>

		{% block content %}{% endblock %}