text:
'use strict';

+function () {
  var Vue;

  if (typeof module !== 'undefined' && typeof exports !== 'undefined') {
    Vue = require('vue');
  } else if (typeof window.Vue !== 'undefined') {
    Vue = window.Vue;
  }

  var throttle = function (fn, delay) {
    var now, lastExec, timer, context, args;

    var execute = function () {
      fn.apply(context, args);
      lastExec = now;
    };

    return function () {
      context = this;
      args = arguments;

      now = Date.now();

      if (timer) {
        clearTimeout(timer);
        timer = null;
      }

      if (!lastExec) {
        execute();
      } else {
        var diff = delay - (now - lastExec);
        if (diff < 0) {
          execute();
        } else {
          timer = setTimeout(function () {
            execute();
          }, diff);
        }
      }
    };
  };

  var getScrollTop = function (element) {
    if (element === window) {
      return Math.max(window.pageYOffset || 0, document.documentElement.scrollTop);
    }
    return element.scrollTop;
  };

  var getComputedStyle = document.defaultView.getComputedStyle;

  var getScrollEventTarget = function (element) {
    var currentNode = element;
    while (currentNode && currentNode.tagName !== 'HTML' && currentNode.nodeType === 1) {
      var overflowY = getComputedStyle(currentNode)['overflowY'];
      if (overflowY === 'scroll' || overflowY === 'auto') {
        return currentNode;
      }
      currentNode = currentNode.parentNode;
    }
    return null;
  };

  var getVisibleHeight = function (element) {
    if (element === window) {
      return document.documentElement.clientHeight;
    }

    return element.clientHeight;
  };

  var getElementTop = function (element) {
    if (element.nodeType == 1) {
      return element.getBoundingClientRect().top + getScrollTop(window) - document.documentElement.clientTop;
    } else {
      return getScrollTop(window);
    }
  };

  var isAttached = function (element) {
    var currentNode = element.parentNode;
    while (currentNode) {
      if (currentNode.tagName === 'HTML') {
        return true;
      }
      if (currentNode.nodeType === 11) {
        return false;
      }
      currentNode = currentNode.parentNode;
    }
    return false;
  };

  Vue.directive('infiniteScroll', {
    doBind: function () {
      if (this.binded) return;
      this.binded = true;

      var directive = this;
      var element = directive.el;

      directive.scrollEventTarget = window;
      directive.scrollListener = throttle(directive.doCheck.bind(directive), 200);
      directive.scrollEventTarget.addEventListener('scroll', directive.scrollListener);

      var disabledExpr = 'busy';
      var disabled = false;
      if (disabledExpr) {
        this.vm.$watch(disabledExpr, function (value) {
          directive.disabled = value;
        });
        disabled = !!directive.vm.$get(disabledExpr);
      }
      directive.disabled = disabled;

      var distanceExpr = element.getAttribute('infinite-scroll-distance') || '100';
      var distance = 0;
      if (distanceExpr) {
        distance = Number(directive.vm.$get(distanceExpr));
        if (isNaN(distance)) {
          distance = 0;
        }
      }
      directive.distance = distance;

      var immediateCheckExpr = element.getAttribute('infinite-scroll-immediate-check');
      var immediateCheck = true;
      if (immediateCheckExpr) {
        immediateCheck = !!directive.vm.$get(immediateCheckExpr);
      }

      if (immediateCheck) {
        directive.doCheck();
      }

      var eventName = element.getAttribute('infinite-scroll-listen-for-event');
      if (eventName) {
        directive.vm.$on(eventName, function () {
          directive.doCheck();
        });
      }
    },

    doCheck: function () {
      var scrollEventTarget = this.scrollEventTarget;//window
      var element = this.el;
      var distance = this.distance;
      if (this.disabled) return;
      var viewportScrollTop = getScrollTop(scrollEventTarget);
      var viewportBottom = viewportScrollTop + getVisibleHeight(scrollEventTarget);
      var shouldTrigger = false;
      if (scrollEventTarget !== element) {
        var elementBottom = getElementTop(element) - getElementTop(scrollEventTarget) + element.offsetHeight + viewportScrollTop;
        shouldTrigger = viewportBottom + distance >= elementBottom;
      } else {
        shouldTrigger = scrollEventTarget.scrollHeight - viewportBottom <= distance;
      }
      if (shouldTrigger && this.expression) {
        this.vm.$get(this.expression);
      }
    },

    bind: function () {
      var directive = this;
      var element = this.el;

      directive.vm.$on('hook:ready', function () {
        if (isAttached(element)) {
          directive.doBind();
        }
      });

      this.bindTryCount = 0;

      var tryBind = function () {
        if (directive.bindTryCount > 10) return;
        directive.bindTryCount++;
        if (isAttached(element)) {
          directive.doBind();
        } else {
          setTimeout(tryBind, 50);
        }
      };

      tryBind();
    },

    unbind() {
      this.scrollEventTarget.removeEventListener('scroll', this.scrollListener);
    }
  });
}();


text:
from __future__ import unicode_literals

from django.db import migrations, models

class Migration(migrations.Migration):

    dependencies = [
        ('applications', '0012_auto_20170113_1821'),
    ]

    operations = [
        migrations.AddField(
            model_name='theoryexamquestion',
            name='score',
            field=models.IntegerField(default=0, verbose_name='Score'),
        ),
    ]

redpajama_set_name: RedPajamaGithub


text:
package aima.core.search.problems

import aima.core.search.adversarial._

/**
  * @author Aditya Lahiri
  * @author Shawn Garner
  */
object TwoPlayerGame {

  final case class Player(name: String)
  final case class State(name: String)
  final case class Action(name: String)

  sealed trait TwoPlayerGame extends Game[Player, State, Action]

  val impl: TwoPlayerGame = new TwoPlayerGame {
    val adjacencyMat = Map(
      "A" -> List(Action("B"), Action("C"), Action("D")),
      "B" -> List(Action("E"), Action("F"), Action("G")),
      "C" -> List(Action("H"), Action("I"), Action("J")),
      "D" -> List(Action("K"), Action("L"), Action("M"))
    )
    val TwoPlyStates = Map(
      "A" -> State("A"),
      "B" -> State("B"),
      "C" -> State("C"),
      "D" -> State("D"),
      "E" -> State("E"),
      "F" -> State("F"),
      "G" -> State("G"),
      "H" -> State("H"),
      "I" -> State("I"),
      "J" -> State("J"),
      "K" -> State("K"),
      "L" -> State("L"),
      "M" -> State("M")
    )

    @Override
    def initialState: State = TwoPlyStates("A")

    @Override
    def getPlayer(state: State): Player = state.name match {
      case "B" | "C" | "D" => Player("MIN")
      case _               => Player("MAX")
    }

    @Override
    def getActions(state: State): List[Action] = adjacencyMat(state.name)

    @Override
    def result(state: State, action: Action): State = TwoPlyStates(action.name)

    @Override
    def isTerminalState(state: State): Boolean = state.name match {
      case "A" | "B" | "C" | "D" => false
      case _                     => true

    }

    @Override
    def getUtility(state: State): UtilityValue = state.name match {
      case "E" => UtilityValue(3)
      case "F" => UtilityValue(12)
      case "G" => UtilityValue(8)
      case "H" => UtilityValue(2)
      case "I" => UtilityValue(4)
      case "J" => UtilityValue(6)
      case "K" => UtilityValue(14)
      case "L" => UtilityValue(5)
      case "M" => UtilityValue(2)
    }
  }
}


text:
using System.Collections.Generic;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Mvc;
using ConfigServer.Core;
using ConfigServer.Sample.mvcApp2.Models;

namespace ConfigServer.Sample.mvcApp2.Controllers
{
    public class HomeController : Controller
    {
        private readonly IConfigServer configProvider;

        public HomeController(IConfigServer configProvider)
        {
            this.configProvider = configProvider;
        }

        // GET: /<controller>/
        public async Task<IActionResult> Index()
        {
            var config = await configProvider.GetConfigAsync<SampleConfig>();
            var options = await configProvider.GetCollectionConfigAsync<OptionFromConfigSet>();

            return View(new ConfigViewModel { Config = config, Options = options });
        }
    }

    public class ConfigViewModel
    {
        public SampleConfig Config { get; set; }
        public IEnumerable<OptionFromConfigSet> Options { get; set; }
    }
}


text:
<法規>
<法規性質>命令</法規性質>
<英文法規名稱>Regulations for Subsidizing the Litigation Costs and Necessary Living Expenses of Workers Laid Off under Mass Redundancy Plan</英文法規名稱>
<中文法規名稱>大量解僱勞工訴訟及必要生活費用補助辦法</中文法規名稱>
<法規網址>https://law.moj.gov.tw/Eng/LawClass/LawAll.aspx?pcode=N0020011</法規網址>
<最新英文異動日期>20220429</最新英文異動日期>
<廢止註記>
</廢止註記>
<附件 />
<沿革內容><![CDATA[1.Promulgated on September 17, 2003
2.Modified on March 26, 2009
by the Council of Labor Affairs, the Executive Yuan; effective from May 7, 2003
3.Amended and promulgated Article 2 of the Rules by the Order of Council of Labor Affairs, Executive Yuan No.1020126389 on June 21, 2013
4.Amended on April 29, 2016
5.Amended on June 15, 2021
6.Amended and promulgated Articles 3 and 15 by the Order of Ministry of Labor, Executive Yuan No. 1110136588A on April 29, 2022]]></沿革內容>
<前言><![CDATA[]]></前言>
<法規內容>
  <條文>
    <條號>Article 1</條號>
    <條文內容><![CDATA[These regulations are enacted in accordance with Article 14 of the Protective Act for Mass Redundancy of Employees (hereinafter referred to as the "Act"). ]]></條文內容>
  </條文>
  <條文>
    <條號>Article 2</條號>
    <條文內容><![CDATA[The worker who is laid off under the circumstances provided in Article 2 of the Act is entitled to apply to the central competent authority for a subsidy for the litigation arising from the following circumstances:
1. Where the employer has failed to pay the worker the salary, severance pay and/or pension in accordance with the law.
2. Where the layoff is in violation of Paragraph 1, Article 13 of the Act or Article 11 of the Labor Standards Law.
The scope of the aforementioned litigation subsidy includes attorney fees incurred on civil litigation procedures, injunctive procedures, supervisory procedures, compulsory execution procedures, and the drafting of legal documents.]]></條文內容>
  </條文>
  <條文>
    <條號>Article 3</條號>
    <條文內容><![CDATA[A workers who is laid off according to the regulation of Article 2 of the Act and is under any of the circumstances set forth in Paragraph 1 of the preceding Article may apply to the central competent authority for the necessary living subsidy while the litigation is in process if the said worker remains unemployed and is not eligible for unemployment subsidies owing to sufficient length of insurance coverage or the employer's failure to take out employment insurance or pay insurance premiums as regulated.
Application for the living subsidy described in the preceding paragraph shall be filed within six months from the date the worker is laid off.
When applying for the subsidy provided for in Paragraph 1, the applicant shall register with a public employment service institution for employment assistance. To receive the subsidy continuously, the applicant shall submit the proof of at least two job applications per month to the public employment service institution(s).
The worker shall not apply for the subsidy provided for in Paragraph 1 of this Article while receiving any of the below benefits:
1. Unemployment benefit, Vocational training living allowances, or temporary job allowance prescribed in the Employment Insurance Act;
2. Injury or sickness benefit prescribed in the Labor Insurance Act or Labor Occupational Accident Insurance and Protection Act;
3. Living allowance or aids prescribed in the Labor Occupational Accident Insurance and Protection Act;
4. Temporary Job allowance or living allowance for vocational training prescribed in the Employment Service Act;
5. Aids of the same nature from other government agencies.]]></條文內容>
  </條文>
  <條文>
    <條號>Article 4</條號>
    <條文內容><![CDATA[The dispute of the mass redundancy suffered by the worker who applies for a litigation subsidy under these Regulations shall first be referred to the local authority in charge of administration of labor affairs for coordination or mediation. ]]></條文內容>
  </條文>
  <條文>
    <條號>Article 5</條號>
    <條文內容><![CDATA[No subsidy shall be granted if the subject litigation is obviously devoid of or of no substantial benefits. ]]></條文內容>
  </條文>
  <條文>
    <條號>Article 6</條號>
    <條文內容><![CDATA[The applications for litigation subsidy of the workers under the same mass redundancy plan shall be filed collectively, unless otherwise considered appropriate by the examination board. ]]></條文內容>
  </條文>
  <條文>
    <條號>Article 7</條號>
    <條文內容><![CDATA[An application for litigation subsidy shall be filed within 30 days after conclusion of any of the procedures detailed in Article 8. ]]></條文內容>
  </條文>
  <條文>
    <條號>Article 8</條號>
    <條文內容><![CDATA[The amount of the litigation subsidy to be granted under these Regulations is calculated as follows:
1. For an application filed by an individual applicant: The maximum amount for each instance of court is Forty Thousand New Taiwan Dollars (NTD40,000).
2. For an application collectively filed by a group of workers: The maximum amount for each instance of court is One Hundred Thousand New Taiwan Dollars (NTD100,000). In the event that the cause is deemed justifiable, up to the maximum of Two Hundred Thousand New Taiwan Dollars (NTD200,000) may be granted as the lawyer's fee subsidy for a collective application.
3. For a case under precautionary proceedings: The maximum amount is Thirty Thousand New Taiwan Dollars (NTD30,000) for each application.
4. For a case under hortatory proceedings: The maximum amount is Ten Thousand New Taiwan Dollar (NTD10,000) for each application.
5. For a case under compulsory execution procedure: The maximum amount is Forty Thousand New Taiwan Dollars (NTD40,000) for each application.
When granting the subsidies set forth in the preceding paragraph, the central competent authority may reduce the amounts already received by the applicant from the local competent authority for the same case.]]></條文內容>
  </條文>
  <條文>
    <條號>Article 9</條號>
    <條文內容><![CDATA[The application for litigation subsidy shall be attached with the relevant receipts and evidentiary documents, photocopies of the labor dispute coordination and mediation records, and any of the following supporting documents:
1. In the legal proceedings of the first instance: a photocopy of the plaintiff's complaint or the defendant's defense.
2. In the legal proceedings of the second or the third instance: photocopies of the appeal or the answer, and the court judgment of the first or second instance.
3. In the precautionary procedure: photocopies of the application for provisional attachment or provisional injunction, and the court ruling.
4. In the hortatory procedure: photocopies of the application for a payment order and the issued order.
5. In the compulsory execution procedure: photocopies of the application for compulsory execution and the relevant evidentiary documents.]]></條文內容>
  </條文>
  <條文>
    <條號>Article 10</條號>
    <條文內容><![CDATA[The amount of the necessary living expense subsidy under these Regulations shall be 60% of the grade-one salary designated for the employment insurance scheme; and the duration of subsidization shall not be more than six (6) months. ]]></條文內容>
  </條文>
  <條文>
    <條號>Article 11</條號>
    <條文內容><![CDATA[In the event that the attached documents submitted along with the application filed pursuant to Article 9 hereof are incomplete, and the applicant has been notified to make a supplemental submission within a specified period but has failed to submit within the period, the application shall be dismissed. ]]></條文內容>
  </條文>
  <條文>
    <條號>Article 12</條號>
    <條文內容><![CDATA[To review applications for subsidies, the central competent authority shall form an examination board.
The aforementioned examination board shall have three or five members, one of whom shall be appointed by the central competent authority and shall serve as the convener, while the rest shall be assumed by experts and scholars for a term of two years.
The proportion of the aforementioned board members of either gender shall not be less than one-third.
When reviewing applications, the members of the examination board shall abide by the recusal regulation of Article 32 and Article 33 of the Administrative Procedure Act.]]></條文內容>
  </條文>
  <條文>
    <條號>Article 13</條號>
    <條文內容><![CDATA[The quorum of a meeting of the examination board shall be the majority of the members.
Members of the examination board shall attend the meetings in person and shall not attend by proxy. In the event that the chairperson is unable to preside over a meeting of the examination board, he/she may appoint another member to act on his/her behalf at the meeting.
The members of the examination board shall have no remuneration, while the expert/scholar members may receive an attendance allowance.]]></條文內容>
  </條文>
  <條文>
    <條號>Article 13-1</條號>
    <條文內容><![CDATA[The central competent authority may delegate a private organization to be responsible for the subsidization function stipulated in these regulations.]]></條文內容>
  </條文>
  <條文>
    <條號>Article 14</條號>
    <條文內容><![CDATA[The format of the written application for litigation subsidy and necessary living expense subsidy shall be prescribed by the central competent authority.]]></條文內容>
  </條文>
  <條文>
    <條號>Article 15</條號>
    <條文內容><![CDATA[These Regulations shall come into force from May 7, 2003.
Except that the provisions herein amended and promulgated on April 29th, 2022 should take effect on May 1st, 2022, this amendment shall become effective on the date of promulgation.]]></條文內容>
  </條文>
</法規內容>
</法規>


text:
var gulp = require('gulp');
var mocha = require('gulp-mocha');
var should = require('should');

gulp.task('test', function () {
  return gulp.src('./test.js')
    .pipe(mocha({
      reporter: 'spec',
      globals: { should: should }
    }));
});

gulp.task('default', ['test']);


text:
using System.ComponentModel;
using osu.Framework.Localisation;
using osu.Game.Resources.Localisation.Web;

namespace osu.Game.Overlays.Login
{
    public enum UserAction
    {
        [LocalisableDescription(typeof(UsersStrings), nameof(UsersStrings.StatusOnline))]
        Online,

        [Description(@"Do not disturb")]
        DoNotDisturb,

        [Description(@"Appear offline")]
        AppearOffline,

        [Description(@"Sign out")]
        SignOut,
    }
}


text:
// Copyright 2016 The Cockroach Authors.
//
// 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.
//
// Author: Karl Southern (karl@theangryangel.co.uk)

package parser

import (
	"math"
	"strconv"
	"strings"
	"time"

	"github.com/cockroachdb/cockroach/pkg/util/duration"
	"github.com/pkg/errors"
)

type intervalLexer struct {
	str    string
	offset int
	err    error
}

// consumeNum consumes the next decimal number.
// 1st return value is the integer part.
// 2nd return value is whether a decimal part was encountered.
// 3rd return value is the decimal part as a float.
// If the number is negative, both the 1st and 3rd return
// value are negative.
// The decimal value is returned separately from the integer value so
// as to support large integer values which would not fit in a float.
func (l *intervalLexer) consumeNum() (int64, bool, float64) {
	if l.err != nil {
		return 0, false, 0
	}

	offset := l.offset

	neg := false
	if l.offset < len(l.str) && l.str[l.offset] == '-' {
		// Remember a leading negative sign. We can't use "intPart < 0"
		// below, because when the input syntax is "-0.xxxx" intPart is 0.
		neg = true
	}

	// Integer part before the decimal separator.
	intPart := l.consumeInt()

	var decPart float64
	hasDecimal := false
	if l.offset < len(l.str) && l.str[l.offset] == '.' {
		hasDecimal = true
		start := l.offset

		// Advance offset to prepare a valid argument to ParseFloat().
		l.offset++
		for ; l.offset < len(l.str) && l.str[l.offset] >= '0' && l.str[l.offset] <= '9'; l.offset++ {
		}
		// Try to convert.
		value, err := strconv.ParseFloat(l.str[start:l.offset], 64)
		if err != nil {
			l.err = errors.Errorf("interval: %v", err)
			return 0, false, 0
		}
		decPart = value
	}

	// Ensure we have something.
	if offset == l.offset {
		l.err = errors.Errorf("interval: missing number at position %d: %q", offset, l.str)
		return 0, false, 0
	}

	if neg {
		decPart = -decPart
	}
	return intPart, hasDecimal, decPart
}

// Consumes the next integer.
func (l *intervalLexer) consumeInt() int64 {
	if l.err != nil {
		return 0
	}

	start := l.offset

	// Advance offset to prepare a valid argument to ParseInt().
	if l.offset < len(l.str) && l.str[l.offset] == '-' {
		l.offset++
	}
	for ; l.offset < len(l.str) && l.str[l.offset] >= '0' && l.str[l.offset] <= '9'; l.offset++ {
	}

	x, err := strconv.ParseInt(l.str[start:l.offset], 10, 64)
	if err != nil {
		l.err = errors.Errorf("interval: %v", err)
		return 0
	}
	if start == l.offset {
		l.err = errors.Errorf("interval: missing number at position %d: %q", start, l.str)
		return 0
	}
	return x
}

// Consumes the next unit.
func (l *intervalLexer) consumeUnit(skipCharacter byte) string {
	if l.err != nil {
		return ""
	}

	offset := l.offset
	for ; l.offset < len(l.str); l.offset++ {
		if (l.str[l.offset] >= '0' && l.str[l.offset] <= '9') ||
			l.str[l.offset] == skipCharacter ||
			l.str[l.offset] == '-' {
			break
		}
	}

	if offset == l.offset {
		l.err = errors.Errorf("interval: missing unit at position %d: %q", offset, l.str)
		return ""
	}
	return l.str[offset:l.offset]
}

// Consumes any number of spaces.
func (l *intervalLexer) consumeSpaces() {
	if l.err != nil {
		return
	}
	for ; l.offset < len(l.str) && l.str[l.offset] == ' '; l.offset++ {
	}
}

// ISO Units.
var isoDateUnitMap = map[string]duration.Duration{
	"D": {Days: 1},
	"W": {Days: 7},
	"M": {Months: 1},
	"Y": {Months: 12},
}

var isoTimeUnitMap = map[string]duration.Duration{
	"S": {Nanos: time.Second.Nanoseconds()},
	"M": {Nanos: time.Minute.Nanoseconds()},
	"H": {Nanos: time.Hour.Nanoseconds()},
}

const errInvalidSQLDuration = "invalid input syntax for type interval %s"

type parsedIndex uint8

const (
	nothingParsed parsedIndex = iota
	hmsParsed
	dayParsed
	yearMonthParsed
)

// Parses a SQL standard interval string.
// See the following links for exampels:
//  - http://www.postgresql.org/docs/9.1/static/datatype-datetime.html#DATATYPE-INTERVAL-INPUT-EXAMPLES
//  - http://www.ibm.com/support/knowledgecenter/SSGU8G_12.1.0/com.ibm.esqlc.doc/ids_esqlc_0190.htm
func sqlStdToDuration(s string) (duration.Duration, error) {
	var d duration.Duration
	parts := strings.Fields(s)
	if len(parts) > 3 || len(parts) == 0 {
		return d, errors.Errorf(errInvalidSQLDuration, s)
	}
	// Index of which part(s) have been parsed for detecting bad order such as `HH:MM:SS Year-Month`.
	parsedIdx := nothingParsed
	// Both 'Day' and 'Second' can be float, but 'Day Second'::interval is invalid.
	floatParsed := false
	// Parsing backward makes it easy to distinguish 'Day' and 'Second' when encountering a single value.
	//   `1-2 5 9:` and `1-2 5`
	//        |              |
	// day ---+              |
	// second ---------------+
	for i := len(parts) - 1; i >= 0; i-- {
		// Parses leading sign
		part := parts[i]
		neg := false
		// Consumes [-+]
		if part != "" {
			c := part[0]
			if c == '-' || c == '+' {
				neg = c == '-'
				part = part[1:]
			}
		}
		if part[0] == '-' {
			return d, errors.Errorf(errInvalidSQLDuration, s)
		}

		if strings.ContainsRune(part, ':') {
			// Try to parse as HH:MM:SS
			if parsedIdx != nothingParsed {
				return d, errors.Errorf(errInvalidSQLDuration, s)
			}
			parsedIdx = hmsParsed
			// Colon-separated intervals in Postgres are odd. They have day, hour,
			// minute, or second parts depending on number of fields and if the field
			// is an int or float.
			//
			// Instead of supporting unit changing based on int or float, use the
			// following rules:
			// - One field is S.
			// - Two fields is H:M.
			// - Three fields is H:M:S.
			// - All fields support both int and float.
			hms := strings.Split(part, ":")
			var err error
			var dur time.Duration
			// Support such as `HH:` and `HH:MM:` as postgres do. Set the last part to "0".
			if hms[len(hms)-1] == "" {
				hms[len(hms)-1] = "0"
			}
			switch len(hms) {
			case 2:
				toParse := hms[0] + "h" + hms[1] + "m"
				if neg {
					toParse = "-" + toParse
				}
				dur, err = time.ParseDuration(toParse)
			case 3:
				// Support such as `HH::SS` as postgres do. Set minute part to 0.
				// TODO(hainesc): `:1:2 -> 1 hour 2 min` as postgres do?
				if hms[1] == "" {
					hms[1] = "0"
				}
				toParse := hms[0] + "h" + hms[1] + "m" + hms[2] + "s"
				if neg {
					toParse = "-" + toParse
				}
				dur, err = time.ParseDuration(toParse)
			default:
				return d, errors.Errorf(errInvalidSQLDuration, s)
			}
			if err != nil {
				return d, makeParseError(part, TypeInterval, err)
			}
			d = d.Add(duration.Duration{Nanos: dur.Nanoseconds()})
		} else if strings.ContainsRune(part, '-') {
			// Try to parse as Year-Month.
			if parsedIdx >= yearMonthParsed {
				return d, errors.Errorf(errInvalidSQLDuration, s)
			}
			parsedIdx = yearMonthParsed

			yms := strings.Split(part, "-")
			if len(yms) != 2 {
				return d, errors.Errorf(errInvalidSQLDuration, s)
			}
			year, errYear := strconv.Atoi(yms[0])
			var month int
			var errMonth error
			if yms[1] != "" {
				month, errMonth = strconv.Atoi(yms[1])
			}
			if errYear == nil && errMonth == nil {
				delta := duration.Duration{Months: 1}.Mul(int64(year)*12 + int64(month))
				if neg {
					d = d.Sub(delta)
				} else {
					d = d.Add(delta)
				}
			} else {
				return d, errors.Errorf(errInvalidSQLDuration, s)
			}

		} else if value, err := strconv.ParseFloat(part, 64); err == nil {
			// Try to parse as Day or Second.
			var dur time.Duration
			var err error
			// Make sure 'Day Second'::interval invalid.
			if floatParsed {
				return d, errors.Errorf(errInvalidSQLDuration, s)
			}
			floatParsed = true
			if parsedIdx == nothingParsed {
				// It must be 'Second' part because nothing has been parsed.
				toParse := part + "s"
				if neg {
					toParse = "-" + toParse
				}
				dur, err = time.ParseDuration(toParse)

				if err != nil {
					return d, errors.Errorf(errInvalidSQLDuration, s)
				}
				d = d.Add(duration.Duration{Nanos: dur.Nanoseconds()})
				parsedIdx = hmsParsed
			} else if parsedIdx == hmsParsed {
				// Day part.
				// TODO(hainesc): support float value in day part?
				delta := duration.Duration{Days: 1}.Mul(int64(value))
				if neg {
					d = d.Sub(delta)
				} else {
					d = d.Add(delta)
				}
				parsedIdx = dayParsed
			} else {
				return d, errors.Errorf(errInvalidSQLDuration, s)
			}
		}
	}
	return d, nil
}

// Parses an ISO8601 (with designators) string.
// See the following links for examples:
//  - http://www.postgresql.org/docs/9.1/static/datatype-datetime.html#DATATYPE-INTERVAL-INPUT-EXAMPLES
//  - https://en.wikipedia.org/wiki/ISO_8601#Time_intervals
//  - https://en.wikipedia.org/wiki/ISO_8601#Durations
func iso8601ToDuration(s string) (duration.Duration, error) {
	var d duration.Duration
	if len(s) == 0 || s[0] != 'P' {
		return d, errors.Errorf("interval: invalid iso8601 duration %s", s)
	}

	// Advance to offset 1, since we don't care about the leading P.
	l := intervalLexer{str: s, offset: 1, err: nil}
	unitMap := isoDateUnitMap

	for l.offset < len(s) {
		// Check if we're in the time part yet.
		if s[l.offset] == 'T' {
			unitMap = isoTimeUnitMap
			l.offset++
		}

		v := l.consumeInt()
		u := l.consumeUnit('T')
		if l.err != nil {
			return d, l.err
		}

		if unit, ok := unitMap[u]; ok {
			d = d.Add(unit.Mul(v))
		} else {
			return d, errors.Errorf("interval: unknown unit %s in iso8601 duration %s", u, s)
		}
	}

	return d, nil
}

// unitMap defines for each unit name what is the time duration for
// that unit.
var unitMap = func(
	units map[string]duration.Duration,
	aliases map[string][]string,
) map[string]duration.Duration {
	for a, alist := range aliases {
		// Pluralize.
		units[a+"s"] = units[a]
		for _, alias := range alist {
			// Populate the remaining aliases.
			units[alias] = units[a]
		}
	}
	return units
}(map[string]duration.Duration{
	"nanosecond":  {Nanos: time.Nanosecond.Nanoseconds()},
	"microsecond": {Nanos: time.Microsecond.Nanoseconds()},
	"millisecond": {Nanos: time.Millisecond.Nanoseconds()},
	"second":      {Nanos: time.Second.Nanoseconds()},
	"minute":      {Nanos: time.Minute.Nanoseconds()},
	"hour":        {Nanos: time.Hour.Nanoseconds()},
	"day":         {Days: 1},
	"week":        {Days: 7},
	"month":       {Months: 1},
	"year":        {Months: 12},
}, map[string][]string{
	"nanosecond": {"ns"},
	// µ = U+00B5 = micro symbol
	// μ = U+03BC = Greek letter mu
	"microsecond": {"us", "µs", "μs"},
	"millisecond": {"ms"},
	"second":      {"s"},
	"minute":      {"m"},
	"hour":        {"h"},
	"day":         {"d"},
	"week":        {"w"},
	"month":       {"mon", "mons" /* pg compat */},
	"year":        {"y"},
})

// parseDuration parses a duration in the "traditional" Postgres
// format (e.g. '1 day 2 hours', '1 day 03:02:04', etc.) or golang
// format (e.g. '1d2h', '1d3h2m4s', etc.)
func parseDuration(s string) (duration.Duration, error) {
	var d duration.Duration
	l := intervalLexer{str: s, offset: 0, err: nil}
	l.consumeSpaces()

	if l.offset == len(l.str) {
		return d, errors.Errorf("interval: invalid input syntax: %q", l.str)
	}
	for l.offset != len(l.str) {
		// Parse the next number.
		v, hasDecimal, vp := l.consumeNum()
		l.consumeSpaces()

		if l.offset < len(l.str) && l.str[l.offset] == ':' && !hasDecimal {
			// Special case: HH:MM[:SS.ffff] or MM:SS.ffff
			delta, err := l.parseShortDuration(v)
			if err != nil {
				return d, err
			}
			d = d.Add(delta)
			continue
		}

		// Parse the unit.
		u := l.consumeUnit(' ')
		l.consumeSpaces()
		if unit, ok := unitMap[strings.ToLower(u)]; ok {
			// A regular number followed by a unit, such as "9 day".
			d = d.Add(unit.Mul(v))
			if hasDecimal {
				d = addFrac(d, unit, vp)
			}
			continue
		}

		if u != "" {
			return d, errors.Errorf("interval: unknown unit %q in duration %q", u, s)
		}
		return d, errors.Errorf("interval: missing unit at position %d: %q", l.offset, s)
	}
	return d, l.err
}

func (l *intervalLexer) parseShortDuration(h int64) (duration.Duration, error) {
	sign := int64(1)
	if h < 0 {
		sign = -1
	}
	// postgresToDuration() has rewound the cursor to just after the
	// first number, so that we can check here there are no unwanted
	// spaces.
	if l.str[l.offset] != ':' {
		return duration.Duration{}, errors.Errorf("interval: invalid format %s", l.str[l.offset:])
	}
	l.offset++
	// Parse the second number.
	m, hasDecimal, mp := l.consumeNum()

	if m < 0 {
		return duration.Duration{}, errors.Errorf("interval: invalid format: %s", l.str)
	}
	// We have three possible formats:
	// - MM:SS.mmmmm
	// - HH:MM
	// - HH:MM:SS[.mmmmm]
	//
	// The top format has the "h" field parsed above actually
	// represent minutes. Get this out of the way first.
	if hasDecimal {
		l.consumeSpaces()
		return duration.Duration{
			Nanos: h*time.Minute.Nanoseconds() +
				sign*(m*time.Second.Nanoseconds()+
					int64(mp*float64(time.Second.Nanoseconds()))),
		}, nil
	}

	// Remaining formats
	var s int64
	var sp float64
	if l.offset != len(l.str) && l.str[l.offset] == ':' {
		// The last :NN part.
		l.offset++
		s, _, sp = l.consumeNum()
		if s < 0 {
			return duration.Duration{}, errors.Errorf("interval: invalid format: %s", l.str)
		}
	}

	l.consumeSpaces()
	return duration.Duration{
		Nanos: h*time.Hour.Nanoseconds() +
			sign*(m*time.Minute.Nanoseconds()+
				int64(mp*float64(time.Minute.Nanoseconds()))+
				s*time.Second.Nanoseconds()+
				int64(sp*float64(time.Second.Nanoseconds()))),
	}, nil
}

// addFrac increases the duration given as first argument by the unit
// given as second argument multiplied by the factor in the third
// argument. For computing fractions there are 30 days to a month and
// 24 hours to a day.
func addFrac(d duration.Duration, unit duration.Duration, f float64) duration.Duration {
	if unit.Months > 0 {
		f = f * float64(unit.Months)
		d.Months += int64(f)
		f = math.Mod(f, 1) * 30
		d.Days += int64(f)
		f = math.Mod(f, 1) * 24
		d.Nanos += int64(float64(time.Hour.Nanoseconds()) * f)
	} else if unit.Days > 0 {
		f = f * float64(unit.Days)
		d.Days += int64(f)
		f = math.Mod(f, 1) * 24
		d.Nanos += int64(float64(time.Hour.Nanoseconds()) * f)
	} else {
		d.Nanos += int64(float64(unit.Nanos) * f)
	}
	return d
}


text:
import isRowMajor = require( './index' );

// TESTS //

// The function returns a boolean...
{
	isRowMajor( [ 2, 1 ] ); // $ExpectType boolean
	isRowMajor( [ 1, 2 ] ); // $ExpectType boolean
}

// The compiler throws an error if the function is provided a value other than an array-like object containing numbers...
{
	isRowMajor( true ); // $ExpectError
	isRowMajor( false ); // $ExpectError
	isRowMajor( null ); // $ExpectError
	isRowMajor( undefined ); // $ExpectError
	isRowMajor( '5' ); // $ExpectError
	isRowMajor( [ '1', '2' ] ); // $ExpectError
	isRowMajor( {} ); // $ExpectError
	isRowMajor( ( x: number ): number => x ); // $ExpectError
}

// The compiler throws an error if the function is provided insufficient arguments...
{
	isRowMajor(); // $ExpectError
}


text:
package cjc.weixinmp.bean;

import javax.xml.bind.annotation.XmlAccessType;
import javax.xml.bind.annotation.XmlAccessorType;
import javax.xml.bind.annotation.XmlRootElement;

/**
 * 自定义菜单点击事件的请求<br>
 * MsgId 字段无效
 * @author jianqing.cai@qq.com, https://github.com/caijianqing/weixinmp4java/
 */
@XmlRootElement(name = "xml")
@XmlAccessorType(XmlAccessType.FIELD)
public class ClickEventRequest extends AbstractEventRequest {

    private static final long serialVersionUID = 1L;

    /** 事件KEY值,与自定义菜单接口中KEY值对应 */
    public String EventKey;

    @Override
    public String toString() {
        return "ClickEventRequest [Event=" + Event + ", ToUserName=" + ToUserName + ", FromUserName=" + FromUserName + ", CreateTime=" + CreateTime
                + ", MsgType=" + MsgType + ", MsgId=" + MsgId + ", EventKey=" + EventKey + "]";
    }

}


text:
module Cryptoexchange::Exchanges
  module Cashierest
    class Market < Cryptoexchange::Models::Market
      NAME = 'cashierest'
      API_URL = 'https://rest.cashierest.com/Public'

      def self.trade_page_url(args={})
        "https://www.cashierest.com/Stock/KrwStock"
      end
    end
  end
end


text:
import { LOGOUT_API, UNAUTHORIZED } from '../actions/auth';
import { ENV_API, SET_LANGUAGE, TOGGLE_LANGUAGE, ENV_VAR_API, SET_ENV_VARIABLE } from '../actions/env';
import { CLEAR_DATA } from '../actions/dev';
import { combineReducers } from 'redux';

const envInitialState = {
	openedFrom: '',
	clientScripts: [],
	clientComponents: [],
	filesDir: '',
	siteName: '',
	adminPath: '',
	domain: '',
	clientPath: '',
	pathCss: [],
	htmlEditorConfig: null,
	languages: [],
	defaultLanguage: '',
	isProdEnv: false,
	version: {
		needsUpdate: false,
		latestVersion: null,
		clientVersion: null,
	},
	versionInfo: null,
	ssoAdminURL: null,
	ssoApiURL: null,
};

function freestone(state = envInitialState, action) {
	// console.log(action);
	switch (action.type) {
		case ENV_API.SUCCESS: {
			// console.log(action.data);
			const data = action.data;
			return {
				...envInitialState,
				...data,
			};
		}
		case CLEAR_DATA:
		case UNAUTHORIZED:
		case LOGOUT_API.REQUEST:
		case LOGOUT_API.SUCCESS:
			return envInitialState;
		default:
			if (action.data && action.data.version) {
				return {
					...state,
					version: {
						...state.version,
						...action.data.version,
					},
				};
			}
			return state;
	}
}

const userViewSettingsInitialState = {
	language: null,
	languages: [],
};
function userViewSettings(state = userViewSettingsInitialState, action) {
	switch (action.type) {
		case ENV_API.SUCCESS: {
			if (action.data && action.data.languages) {
				return {
					...state,
					languages: action.data.languages.map(l => l.key),
				};
			}
			return state;
		}
		case TOGGLE_LANGUAGE: {
			if (state.languages.length) {
				const currentIndex = state.languages.indexOf(state.language);
				if (currentIndex === -1) return state;
				const newLang = state.languages.length === currentIndex + 1 ? state.languages[0] : state.languages[currentIndex + 1];
				return {
					...state,
					language: newLang,
				};
			}
			return state;
		}
		case SET_LANGUAGE:
			// console.log(action.data);
			return {
				...state,
				language: action.data,
			};
		default:
			// console.log('no change');
			return state;
	}
}

/**
	Variables dépendant du client (e.g. Google Analytics ID)
*/
function clientVariables(state = {}, action) {
	switch (action.type) {
		case CLEAR_DATA:
		case UNAUTHORIZED:
		case LOGOUT_API.SUCCESS:
			return {};
		case ENV_VAR_API.SUCCESS:
		case SET_ENV_VARIABLE: {
			if (!action.data) return state;
			// console.log(action.data);
			const { name, value } = action.data;
			return {
				...state,
				[name]: value,
			};
		}
		default:
			// console.log('no change');
			return state;
	}
}

export default combineReducers({
	clientVariables,
	userViewSettings,
	freestone,
});


text:
from __future__ import unicode_literals
import logging
from netaddr import IPNetwork, IPAddress
from six import text_type
import uuid

from .resource import Resource
from ..utils import timeit

from cfgm_common.exceptions import NoIdError

logger = logging.getLogger(__name__)

class VirtualNetwork(Resource):

    _VN_ID_ALLOC_PATH = "/id/virtual-networks/"
    _VN_ID_PADDING = 100000
    _RT_ID_ALLOC_PATH = "/id/bgp/route-targets/"
    _RT_ID_PADDING = 100000
    _RT_ID_ALLOC_START_IDX = 8000000 + _RT_ID_PADDING

    def __init__(self, db_manager, batch_size, zk_client, project_amount,
                 amount_per_project):
        super(VirtualNetwork, self).__init__(db_manager, batch_size, zk_client,
                                             project_amount,
                                             amount_per_project)

        # Get default global system config dict
        try:
            id = self._db_manger.fq_name_to_uuid(
                'global_system_config', ['default-global-system-config'])
        except NoIdError as e:
            logger.error("%s. Run once the VNC API server to initialize "
                         "default resources", text_type(e))
            exit(1)
        ok, obj_dicts = self._db_manger.object_read('global_system_config',
                                                    [id])
        if not ok or len(obj_dicts) != 1:
            logger.error("Cannot read the default global system config %s or "
                         "it is not unique. Reset config?")
        self._default_gsc = obj_dicts[0]

        self._vn_id_allocator = 0
        self._rt_id_allocator = 0

    @property
    def type(self):
        return 'virtual-network'

    @property
    def total_amount(self):
        return self._amount_per_project * 3 * self._project_amount

    @timeit(return_time_elapsed=True)
    def create_resources(self):
        with self._uuid_cf.batch(queue_size=self._batch_size) as uuid_batch,\
                self._fqname_cf.batch(queue_size=self._batch_size) as \
                fqname_batch:
            for project_idx in range(self._project_amount):
                for resource_idx in range(self._amount_per_project):
                    subnet = IPNetwork(self._SUBNET_CIDR)
                    fq_name = [
                        'default-domain',
                        'project-%d' % project_idx,
                        'virtual-network-%d' % resource_idx,
                    ]
                    attr = {
                        'parent_type': 'project',
                        'virtual_network_network_id': self._VN_ID_PADDING +
                        self._vn_id_allocator,
                        'router_external': False,
                        'is_shared': False,
                        'network_ipam_refs': [{
                            'to': [
                                'default-domain',
                                'default-project',
                                'default-network-ipam',
                            ],
                            'attr': {
                                'ipam_subnets': [{
                                    'subnet': {
                                        'ip_prefix': str(subnet.network),
                                        'ip_prefix_len': subnet.prefixlen
                                    },
                                    'dns_server_address':
                                    str(IPAddress(subnet.first + 2)),
                                    'enable_dhcp': True,
                                    'default_gateway':
                                    str(IPAddress(subnet.first + 1)),
                                    'dns_nameservers': [],
                                    'allocation_pools': [],
                                    'subnet_uuid': str(uuid.uuid4()),
                                    'dhcp_option_list': None,
                                    'host_routes': None,
                                    'addr_from_start': True,
                                    'subnet_name':
                                    'virtual-network-subnet-%d' % resource_idx,
                                }],
                                'host_routes': None,
                            },
                        }],
                    }
                    id_str = "%(#)010d" % {'#': self._VN_ID_PADDING +
                                           self._vn_id_allocator}
                    self._zk_client.create_node(self._VN_ID_ALLOC_PATH +
                                                id_str)
                    subnet_path = (self._SUBNET_ALLOC_PATH +
                                   ':'.join(fq_name + [str(subnet)]) + '/')
                    id_str = "%(#)010d" % {'#': subnet.first}
                    self._zk_client.create_node(subnet_path + id_str)
                    id_str = "%(#)010d" % {'#': subnet.first + 1}
                    self._zk_client.create_node(subnet_path + id_str)
                    id_str = "%(#)010d" % {'#': subnet.first + 2}
                    self._zk_client.create_node(subnet_path + id_str)
                    id_str = "%(#)010d" % {'#': subnet.last}
                    self._zk_client.create_node(subnet_path + id_str)
                    self._create_resource('virtual_network', fq_name, attr,
                                          uuid_batch, fqname_batch)
                    self._vn_id_allocator += 1

        ris = []
        with self._uuid_cf.batch(queue_size=self._batch_size) as uuid_batch,\
                self._fqname_cf.batch(queue_size=self._batch_size) as \
                fqname_batch:
            for project_idx in range(self._project_amount):
                ris.append([])
                for resource_idx in range(self._amount_per_project):
                    fq_name = [
                        'default-domain',
                        'project-%d' % project_idx,
                        'virtual-network-%d' % resource_idx,
                        'virtual-network-%d' % resource_idx,
                    ]
                    attr = {
                        'parent_type': 'virtual-network',
                        'routing_instance_has_pnf': False,
                        'routing_instance_is_default': True,
                    }
                    ris[project_idx].append(self._create_resource(
                        'routing_instance', fq_name, attr, uuid_batch,
                        fqname_batch))

        rts = []
        with self._uuid_cf.batch(queue_size=self._batch_size) as uuid_batch,\
                self._fqname_cf.batch(queue_size=self._batch_size) as \
                fqname_batch:
            for project_idx in range(self._project_amount):
                rts.append([])
                for resource_idx in range(self._amount_per_project):
                    fq_name = [
                        'target:%s:%s' %
                        (str(self._default_gsc['autonomous_system']),
                         str(self._RT_ID_ALLOC_START_IDX +
                             self._rt_id_allocator)),
                    ]
                    id_str = "%(#)010d" % {'#': self._RT_ID_ALLOC_START_IDX +
                                           self._rt_id_allocator}
                    self._zk_client.create_node(self._RT_ID_ALLOC_PATH +
                                                id_str)
                    rts[project_idx].append(self._create_resource(
                        'route_target', fq_name))
                    self._rt_id_allocator += 1

        # Update reference ri -> rt
        with self._uuid_cf.batch(queue_size=self._batch_size) as uuid_batch:
            for project_idx in range(self._project_amount):
                for resource_idx in range(self._amount_per_project):
                    ri = ris[project_idx][resource_idx]
                    rt = rts[project_idx][resource_idx]
                    ri.update({
                        'route_target_refs': [
                            {
                                'uuid': rt['uuid'],
                                'to': rt['fq_name'],
                                'attr': {
                                    'import_export': None
                                },
                            },
                        ],
                    })
                    self._update_resource('routing_instance', ri, uuid_batch)


text:
using System;
using System.Collections.Generic;
using System.ComponentModel.Composition.Hosting;
using System.Linq;
using JabbR.Models;
using JabbR.Services;

namespace JabbR.Commands
{
    public class CommandManager
    {
        private readonly string _clientId;
        private readonly string _userAgent;
        private readonly string _userId;
        private readonly string _roomName;
        private readonly INotificationService _notificationService;
        private readonly IChatService _chatService;
        private readonly ICache _cache;
        private readonly IJabbrRepository _repository;

        private static Dictionary<string, ICommand> _commandCache;
        private static readonly Lazy<IList<ICommand>> _commands = new Lazy<IList<ICommand>>(GetCommands);

        public CommandManager(string clientId,
                              string userId,
                              string roomName,
                              IChatService service,
                              IJabbrRepository repository,
                              ICache cache,
                              INotificationService notificationService)
            : this(clientId, null, userId, roomName, service, repository, cache, notificationService)
        {
        }

        public CommandManager(string clientId,
                              string userAgent,
                              string userId,
                              string roomName,
                              IChatService service,
                              IJabbrRepository repository,
                              ICache cache,
                              INotificationService notificationService)
        {
            _clientId = clientId;
            _userAgent = userAgent;
            _userId = userId;
            _roomName = roomName;
            _chatService = service;
            _repository = repository;
            _cache = cache;
            _notificationService = notificationService;
        }

        public string ParseCommand(string commandString, out string[] args)
        {
            var parts = commandString.Substring(1).Split(new[] { ' ' }, StringSplitOptions.RemoveEmptyEntries);

            if (parts.Length == 0)
            {
                args = new string[0];
                return null;
            }

            args = parts.Skip(1).ToArray();
            return parts[0];
        }
        public bool TryHandleCommand(string command)
        {
            command = command.Trim();
            if (!command.StartsWith("/"))
            {
                return false;
            }

            string[] args;
            var commandName = ParseCommand(command, out args);
            return TryHandleCommand(commandName, args);
        }

        public bool TryHandleCommand(string commandName, string[] args)
        {
            if (String.IsNullOrEmpty(commandName))
            {
                return false;
            }

            commandName = commandName.Trim();
            if (commandName.StartsWith("/"))
            {
                return false;
            }

            var context = new CommandContext
            {
                Cache = _cache,
                NotificationService = _notificationService,
                Repository = _repository,
                Service = _chatService
            };

            var callerContext = new CallerContext
            {
                ClientId = _clientId,
                UserId = _userId,
                UserAgent = _userAgent,
                RoomName = _roomName,
            };

            ICommand command;
            try
            {
                MatchCommand(commandName, out command);
            }
            catch (CommandNotFoundException)
            {
                throw new InvalidOperationException(String.Format("'{0}' is not a valid command.", commandName));
            }
            catch (CommandAmbiguityException e)
            {
                throw new InvalidOperationException(String.Format("'{0}' is ambiguous: {1}.", commandName, String.Join(", ", e.Ambiguities)));
            }

            command.Execute(context, callerContext, args);

            return true;
        }

        public void MatchCommand(string commandName, out ICommand command)
        {
            if (_commandCache == null)
            {
                var commands = from c in _commands.Value
                               let commandAttribute = c.GetType()
                                                       .GetCustomAttributes(true)
                                                       .OfType<CommandAttribute>()
                                                       .FirstOrDefault()
                               where commandAttribute != null
                               select new
                               {
                                   Name = commandAttribute.CommandName,
                                   Command = c
                               };

                _commandCache = commands.ToDictionary(c => c.Name,
                                                      c => c.Command,
                                                      StringComparer.OrdinalIgnoreCase);
            }

            IList<string> candidates = null;

            var exactMatches = _commandCache.Keys.Where(comm => comm.Equals(commandName, StringComparison.OrdinalIgnoreCase))
                                                 .ToList();

            if (exactMatches.Count == 1)
            {
                candidates = exactMatches;
            }
            else
            {
                candidates = _commandCache.Keys.Where(comm => comm.StartsWith(commandName, StringComparison.OrdinalIgnoreCase))
                                               .ToList();
            }

            switch (candidates.Count)
            {
                case 1:
                    _commandCache.TryGetValue(candidates[0], out command);
                    commandName = candidates[0];
                    break;
                case 0:
                    throw new CommandNotFoundException();
                default:
                    throw new CommandAmbiguityException(candidates);
            }
        }

        private static IList<ICommand> GetCommands()
        {
            // Use MEF to locate the content providers in this assembly
            var catalog = new AssemblyCatalog(typeof(CommandManager).Assembly);
            var compositionContainer = new CompositionContainer(catalog);
            return compositionContainer.GetExportedValues<ICommand>().ToList();
        }

        public static IEnumerable<CommandMetaData> GetCommandsMetaData()
        {
            var commands = from c in _commands.Value
                           let commandAttribute = c.GetType()
                                                   .GetCustomAttributes(true)
                                                   .OfType<CommandAttribute>()
                                                   .FirstOrDefault()
                           where commandAttribute != null
                           select new CommandMetaData
                           {
                               Name = commandAttribute.CommandName,
                               Description = commandAttribute.Description,
                               Arguments = commandAttribute.Arguments,
                               Group = commandAttribute.Group
                           };
            return commands;
        }
    }
}


text:
using System.Collections.Specialized;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Media;

namespace ExcelAddIn.Train
{
    class AutoScrollingListView : ListView
    {
        private ScrollViewer _scrollViewer;

        protected override void OnItemsSourceChanged(System.Collections.IEnumerable oldValue, System.Collections.IEnumerable newValue)
        {
            base.OnItemsSourceChanged(oldValue, newValue);

            if (oldValue as INotifyCollectionChanged != null)
                (oldValue as INotifyCollectionChanged).CollectionChanged -= ItemsCollectionChanged;

            if (newValue as INotifyCollectionChanged == null) return;

            (newValue as INotifyCollectionChanged).CollectionChanged += ItemsCollectionChanged;
        }

        public override void OnApplyTemplate()
        {
            base.OnApplyTemplate();

            // Dig out and store a reference to our internal ScrollViewer
            _scrollViewer = RecursiveVisualChildFinder<ScrollViewer>(this) as ScrollViewer;
        }

        void ItemsCollectionChanged(object sender, NotifyCollectionChangedEventArgs e)
        {
            if (_scrollViewer == null) return;

            if (!_scrollViewer.VerticalOffset.Equals(_scrollViewer.ScrollableHeight)) return;

            UpdateLayout();
            _scrollViewer.ScrollToBottom();
        }

        private static DependencyObject RecursiveVisualChildFinder<T>(DependencyObject rootObject)
        {
            var child = VisualTreeHelper.GetChild(rootObject, 0);
            if (child == null) return null;

            return child.GetType() == typeof(T) ? child : RecursiveVisualChildFinder<T>(child);
        }
    }
}


text:
function postprocessdemo(postProcStruct)
%POSTPROCESSDEMO  Example for a user-defined postprocessing function.
%   POSTPROCESSDEMO(POSTPROCSTRUCT) accepts a structure passed by function
%   STARTMULTICOREMASTER and makes some command-line outputs. The functions
%   shall demonstrate the basic use of the postprocessing function.
%
%   Markus Buehren
%   Last modified 19.06.2009
%
%   See also STARTMULTICOREMASTER.

persistent lastDisplayTime
if isempty(lastDisplayTime)
  lastDisplayTime = mbtime;
end

if strcmp(postProcStruct.state, 'initialization')
  disp(sprintf('Multicore demo started at %s', postProcStruct.userData));
end

if mbtime - lastDisplayTime > 2.0
  lastDisplayTime = mbtime;

  disp(sprintf('Current time: %s.', datestr(now)));
  disp(sprintf('Jobs done by master: %2d',     postProcStruct.nrOfFilesMaster));
  disp(sprintf('Jobs done by slave:  %2d',     postProcStruct.nrOfFilesSlaves));

end


text:
"""
Apache
======

This module provides high-level tools for installing and configuring
the `Apache HTTP Server <http://httpd.apache.org/>`_.

"""

from fabric.api import (
    abort,
    hide,
    settings,
)
from fabric.colors import red

from fabtools.apache import (
    disable_module,
    enable_module,
    disable_site,
    enable_site,
    _site_config_path,
)
from fabtools.service import reload as reload_service
from fabtools.system import UnsupportedFamily, distrib_family
from fabtools.utils import run_as_root

from fabtools.require.files import template_file
from fabtools.require.service import started as require_started

def server():
    """
    Require the Apache HTTP server to be installed and running.

    ::

        from fabtools import require

        require.apache.server()

    """
    family = distrib_family()
    if family == 'debian':
        _server_debian()
    else:
        raise UnsupportedFamily(supported=['debian'])

def _server_debian():

    from fabtools.require.deb import package as require_deb_package

    require_deb_package('apache2')
    require_started('apache2')

def module_enabled(module):
    """
    Require an Apache module to be enabled.

    This will cause Apache to reload its configuration.

    ::

        from fabtools import require

        require.apache.module_enabled('rewrite')

    """
    enable_module(module)
    reload_service('apache2')

def module_disabled(module):
    """
    Require an Apache module to be disabled.

    This will cause Apache to reload its configuration.

    ::

        from fabtools import require

        require.apache.module_disabled('rewrite')

    """
    disable_module(module)
    reload_service('apache2')

def site_enabled(config):
    """
    Require an Apache site to be enabled.

    This will cause Apache to reload its configuration.

    ::

        from fabtools import require

        require.apache.site_enabled('mysite')

    """
    enable_site(config)
    reload_service('apache2')

def site_disabled(config):
    """
    Require an Apache site to be disabled.

    This will cause Apache to reload its configuration.

    ::

        from fabtools import require

        require.apache.site_disabled('default')

    """
    disable_site(config)
    reload_service('apache2')

def site(site_name, template_contents=None, template_source=None, enabled=True,
         check_config=True, **kwargs):
    """
    Require an Apache site.

    You must provide a template for the site configuration, either as a
    string (*template_contents*) or as the path to a local template
    file (*template_source*).

    ::

        from fabtools import require

        CONFIG_TPL = '''
        <VirtualHost *:%(port)s>
            ServerName %(hostname)s

            DocumentRoot %(document_root)s

            <Directory %(document_root)s>
                Options Indexes FollowSymLinks MultiViews

                AllowOverride All

                Order allow,deny
                allow from all
            </Directory>
        </VirtualHost>
        '''

        require.apache.site(
            'example.com',
            template_contents=CONFIG_TPL,
            port=80,
            hostname='www.example.com',
            document_root='/var/www/mysite',
        )

    .. seealso:: :py:func:`fabtools.require.files.template_file`
    """
    server()

    config_path = _site_config_path(site_name)

    context = {
        'port': 80,
    }
    context.update(kwargs)
    context['config_name'] = site_name

    template_file(config_path, template_contents, template_source, context,
                  use_sudo=True)

    if enabled:
        enable_site(site_name)
    else:
        disable_site(site_name)

    if check_config:
        with settings(hide('running', 'warnings'), warn_only=True):
            if run_as_root('apache2ctl configtest').failed:
                disable_site(site_name)
                message = red("Error in %(site_name)s apache site config (disabling for safety)" % locals())
                abort(message)

    reload_service('apache2')

# backward compatibility (deprecated)
enabled = site_enabled
disabled = site_disabled

__all__ = [
    'server', 'module_enabled', 'module_disabled',
    'site_enabled', 'site_disabled', 'site',
]


text:
<?php

namespace Tlumx\Tests\Application\Fixtures;

use Tlumx\Application\Bootstrapper;

class ABootstrapper extends Bootstrapper
{
}


text:
package com.cflint.plugins.core;

import javax.swing.plaf.synth.SynthScrollBarUI;

import ro.fortsoft.pf4j.Extension;
import net.htmlparser.jericho.Element;
import cfml.parsing.cfscript.CFExpression;
import cfml.parsing.cfscript.CFFunctionExpression;
import cfml.parsing.cfscript.script.CFExpressionStatement;
import cfml.parsing.cfscript.script.CFScriptStatement;

import com.cflint.BugInfo;
import com.cflint.BugList;
import com.cflint.plugins.CFLintScannerAdapter;
import com.cflint.plugins.Context;

@Extension
public class WriteDumpChecker extends CFLintScannerAdapter {
	final String severity = "INFO";

	@Override
	public void expression(final CFExpression expression, final Context context,
			final BugList bugs) {

		if(expression instanceof CFFunctionExpression){
			final CFFunctionExpression functionExpression = (CFFunctionExpression) expression;
			if(functionExpression.getFunctionName().equalsIgnoreCase("writeDump")){
				final int lineNo = functionExpression.getLine() + context.startLine() - 1;
				writeDump(lineNo, context, bugs);
			}
		}

	}

//	@Override
//	public void expression(final CFScriptStatement expression, final Context context, final BugList bugs) {
//		if (expression instanceof CFExpressionStatement) {
//			String code = ((CFExpressionStatement) expression).getExpression().Decompile(0);
//			int lineNo = ((CFExpressionStatement) expression).getLine() + context.startLine() - 1;
//
//			if (code.toLowerCase().contains("writedump(")) {
//				writeDump(lineNo, context, bugs);
//			}
//		}
//	}

//	@Override
//	public void element(final Element element, final Context context, final BugList bugs) {
//		if (element.getName().equals("cfset")) {
//			String content = element.getStartTag().getTagContent().toString();
//			int lineNo = element.getSource().getRow(element.getBegin());
//
//			if (content.toLowerCase().contains("writedump(")) {
//				writeDump(lineNo, context, bugs);
//			}
//		}
//	}

	protected void writeDump(final int lineNo, final Context context, final BugList bugs) {
		bugs.add(new BugInfo.BugInfoBuilder().setLine(lineNo).setMessageCode("AVOID_USING_WRITEDUMP")
			.setSeverity(severity).setFilename(context.getFilename())
			.setMessage("WriteDump statement at line " + lineNo + ". Avoid using writeDump in production code.")
			.build());
	}
}


text:
set -e
FILES="testApproxQuantile.c "
FILES="${FILES} approx_quantile.c"
FILES="${FILES} Collapse.c"
FILES="${FILES} New.c"
FILES="${FILES} Output.c"
FILES="${FILES} determine_b_k.c"
FILES="${FILES} qsort_asc_I4.c"
FILES="${FILES} rs_mmap.c"

INCS=" -I. "

FLAGS=' -std=gnu99 -Wall'

OUTPUT='aq'

gcc -g ${FILES} ${INCS} ${FLAGS} -o $OUTPUT -lm

# A. Run some R program with inputs
#   (1) number of elements
#   (2) distribution parameters
#   to create a CSV file
# B. Run asc2bin to convert  CSV to binary
# C. ./aq foo.bin
# D. Verify outputs

echo "Successfully completed $0 in $PWD"


text:
package net.coding.program.project;

/**
 * Created by chenchao on 2017/12/8.
 * 项目有了改变
 */

public class EventProjectModify {

    public boolean exitProject = false;

    // 修改项目名会导致项目路径变化
    public String projectUrl = null;

    public EventProjectModify() {
    }

    public EventProjectModify setExit() {
        exitProject = true;
        return this;
    }

    public EventProjectModify setProjectUrl(String url) {
        projectUrl = url;
        return this;
    }
}


text:
<?php

namespace Phly\Mustache\Exception;

use DomainException;

/**
 * Exception raised when an invalid/unknown state is reached in the lexer.
 */
class InvalidStateException extends DomainException implements ExceptionInterface
{
}


text:
import { Emitter, Event } from 'vs/base/common/event';
import severity from 'vs/base/common/severity';
import { isObject, isString } from 'vs/base/common/types';
import { generateUuid } from 'vs/base/common/uuid';
import * as nls from 'vs/nls';
import { IConfigurationService } from 'vs/platform/configuration/common/configuration';
import { IDebugConfiguration, IDebugSession, IExpression, IReplElement, IReplElementSource, IStackFrame } from 'vs/workbench/contrib/debug/common/debug';
import { ExpressionContainer } from 'vs/workbench/contrib/debug/common/debugModel';

const MAX_REPL_LENGTH = 10000;
let topReplElementCounter = 0;
const getUniqueId = () => `topReplElement:${topReplElementCounter++}`;

export class SimpleReplElement implements IReplElement {

	private _count = 1;
	private _onDidChangeCount = new Emitter<void>();

	constructor(
		public session: IDebugSession,
		private id: string,
		public value: string,
		public severity: severity,
		public sourceData?: IReplElementSource,
	) { }

	toString(includeSource = false): string {
		let valueRespectCount = this.value;
		for (let i = 1; i < this.count; i++) {
			valueRespectCount += (valueRespectCount.endsWith('\n') ? '' : '\n') + this.value;
		}
		const sourceStr = (this.sourceData && includeSource) ? ` ${this.sourceData.source.name}` : '';
		return valueRespectCount + sourceStr;
	}

	getId(): string {
		return this.id;
	}

	set count(value: number) {
		this._count = value;
		this._onDidChangeCount.fire();
	}

	get count(): number {
		return this._count;
	}

	get onDidChangeCount(): Event<void> {
		return this._onDidChangeCount.event;
	}
}

export class RawObjectReplElement implements IExpression {

	private static readonly MAX_CHILDREN = 1000; // upper bound of children per value

	constructor(private id: string, public name: string, public valueObj: any, public sourceData?: IReplElementSource, public annotation?: string) { }

	getId(): string {
		return this.id;
	}

	get value(): string {
		if (this.valueObj === null) {
			return 'null';
		} else if (Array.isArray(this.valueObj)) {
			return `Array[${this.valueObj.length}]`;
		} else if (isObject(this.valueObj)) {
			return 'Object';
		} else if (isString(this.valueObj)) {
			return `"${this.valueObj}"`;
		}

		return String(this.valueObj) || '';
	}

	get hasChildren(): boolean {
		return (Array.isArray(this.valueObj) && this.valueObj.length > 0) || (isObject(this.valueObj) && Object.getOwnPropertyNames(this.valueObj).length > 0);
	}

	evaluateLazy(): Promise<void> {
		throw new Error('Method not implemented.');
	}

	getChildren(): Promise<IExpression[]> {
		let result: IExpression[] = [];
		if (Array.isArray(this.valueObj)) {
			result = (<any[]>this.valueObj).slice(0, RawObjectReplElement.MAX_CHILDREN)
				.map((v, index) => new RawObjectReplElement(`${this.id}:${index}`, String(index), v));
		} else if (isObject(this.valueObj)) {
			result = Object.getOwnPropertyNames(this.valueObj).slice(0, RawObjectReplElement.MAX_CHILDREN)
				.map((key, index) => new RawObjectReplElement(`${this.id}:${index}`, key, this.valueObj[key]));
		}

		return Promise.resolve(result);
	}

	toString(): string {
		return `${this.name}\n${this.value}`;
	}
}

export class ReplEvaluationInput implements IReplElement {
	private id: string;

	constructor(public value: string) {
		this.id = generateUuid();
	}

	toString(): string {
		return this.value;
	}

	getId(): string {
		return this.id;
	}
}

export class ReplEvaluationResult extends ExpressionContainer implements IReplElement {
	private _available = true;

	get available(): boolean {
		return this._available;
	}

	constructor() {
		super(undefined, undefined, 0, generateUuid());
	}

	override async evaluateExpression(expression: string, session: IDebugSession | undefined, stackFrame: IStackFrame | undefined, context: string): Promise<boolean> {
		const result = await super.evaluateExpression(expression, session, stackFrame, context);
		this._available = result;

		return result;
	}

	override toString(): string {
		return `${this.value}`;
	}
}

export class ReplGroup implements IReplElement {

	private children: IReplElement[] = [];
	private id: string;
	private ended = false;
	static COUNTER = 0;

	constructor(
		public name: string,
		public autoExpand: boolean,
		public sourceData?: IReplElementSource
	) {
		this.id = `replGroup:${ReplGroup.COUNTER++}`;
	}

	get hasChildren() {
		return true;
	}

	getId(): string {
		return this.id;
	}

	toString(includeSource = false): string {
		const sourceStr = (includeSource && this.sourceData) ? ` ${this.sourceData.source.name}` : '';
		return this.name + sourceStr;
	}

	addChild(child: IReplElement): void {
		const lastElement = this.children.length ? this.children[this.children.length - 1] : undefined;
		if (lastElement instanceof ReplGroup && !lastElement.hasEnded) {
			lastElement.addChild(child);
		} else {
			this.children.push(child);
		}
	}

	getChildren(): IReplElement[] {
		return this.children;
	}

	end(): void {
		const lastElement = this.children.length ? this.children[this.children.length - 1] : undefined;
		if (lastElement instanceof ReplGroup && !lastElement.hasEnded) {
			lastElement.end();
		} else {
			this.ended = true;
		}
	}

	get hasEnded(): boolean {
		return this.ended;
	}
}

function areSourcesEqual(first: IReplElementSource | undefined, second: IReplElementSource | undefined): boolean {
	if (!first && !second) {
		return true;
	}
	if (first && second) {
		return first.column === second.column && first.lineNumber === second.lineNumber && first.source.uri.toString() === second.source.uri.toString();
	}

	return false;
}

export class ReplModel {
	private replElements: IReplElement[] = [];
	private readonly _onDidChangeElements = new Emitter<void>();
	readonly onDidChangeElements = this._onDidChangeElements.event;

	constructor(private readonly configurationService: IConfigurationService) { }

	getReplElements(): IReplElement[] {
		return this.replElements;
	}

	async addReplExpression(session: IDebugSession, stackFrame: IStackFrame | undefined, name: string): Promise<void> {
		this.addReplElement(new ReplEvaluationInput(name));
		const result = new ReplEvaluationResult();
		await result.evaluateExpression(name, session, stackFrame, 'repl');
		this.addReplElement(result);
	}

	appendToRepl(session: IDebugSession, data: string | IExpression, sev: severity, source?: IReplElementSource): void {
		const clearAnsiSequence = '\u001b[2J';
		if (typeof data === 'string' && data.indexOf(clearAnsiSequence) >= 0) {
			// [2J is the ansi escape sequence for clearing the display http://ascii-table.com/ansi-escape-sequences.php
			this.removeReplExpressions();
			this.appendToRepl(session, nls.localize('consoleCleared', "Console was cleared"), severity.Ignore);
			data = data.substring(data.lastIndexOf(clearAnsiSequence) + clearAnsiSequence.length);
		}

		if (typeof data === 'string') {
			const previousElement = this.replElements.length ? this.replElements[this.replElements.length - 1] : undefined;
			if (previousElement instanceof SimpleReplElement && previousElement.severity === sev) {
				const config = this.configurationService.getValue<IDebugConfiguration>('debug');
				if (previousElement.value === data && areSourcesEqual(previousElement.sourceData, source) && config.console.collapseIdenticalLines) {
					previousElement.count++;
					// No need to fire an event, just the count updates and badge will adjust automatically
					return;
				}
				if (!previousElement.value.endsWith('\n') && !previousElement.value.endsWith('\r\n') && previousElement.count === 1) {
					this.replElements[this.replElements.length - 1] = new SimpleReplElement(
						session, getUniqueId(), previousElement.value + data, sev, source);
					this._onDidChangeElements.fire();
					return;
				}
			}

			const element = new SimpleReplElement(session, getUniqueId(), data, sev, source);
			this.addReplElement(element);
		} else {
			// TODO@Isidor hack, we should introduce a new type which is an output that can fetch children like an expression
			(<any>data).severity = sev;
			(<any>data).sourceData = source;
			this.addReplElement(data);
		}
	}

	startGroup(name: string, autoExpand: boolean, sourceData?: IReplElementSource): void {
		const group = new ReplGroup(name, autoExpand, sourceData);
		this.addReplElement(group);
	}

	endGroup(): void {
		const lastElement = this.replElements[this.replElements.length - 1];
		if (lastElement instanceof ReplGroup) {
			lastElement.end();
		}
	}

	private addReplElement(newElement: IReplElement): void {
		const lastElement = this.replElements.length ? this.replElements[this.replElements.length - 1] : undefined;
		if (lastElement instanceof ReplGroup && !lastElement.hasEnded) {
			lastElement.addChild(newElement);
		} else {
			this.replElements.push(newElement);
			if (this.replElements.length > MAX_REPL_LENGTH) {
				this.replElements.splice(0, this.replElements.length - MAX_REPL_LENGTH);
			}
		}

		this._onDidChangeElements.fire();
	}

	removeReplExpressions(): void {
		if (this.replElements.length > 0) {
			this.replElements = [];
			this._onDidChangeElements.fire();
		}
	}
}


text:
package com.amazonaws.services.secretsmanager.model;

import java.io.Serializable;
import javax.annotation.Generated;

/**
 *
 * @see AWS API Documentation
 */
@Generated("com.amazonaws:aws-java-sdk-code-generator")
public class StopReplicationToReplicaResult extends com.amazonaws.AmazonWebServiceResult<com.amazonaws.ResponseMetadata> implements Serializable, Cloneable {

    /**
     *

     * The ARN of the promoted secret. The ARN is the same as the original primary secret except the Region is changed.
     *

     */
    private String aRN;

    /**
     *

     * The ARN of the promoted secret. The ARN is the same as the original primary secret except the Region is changed.
     *

     *
     * @param aRN
     *        The ARN of the promoted secret. The ARN is the same as the original primary secret except the Region is
     *        changed.
     */

    public void setARN(String aRN) {
        this.aRN = aRN;
    }

    /**
     *

     * The ARN of the promoted secret. The ARN is the same as the original primary secret except the Region is changed.
     *

     *
     * @return The ARN of the promoted secret. The ARN is the same as the original primary secret except the Region is
     *         changed.
     */

    public String getARN() {
        return this.aRN;
    }

    /**
     *

     * The ARN of the promoted secret. The ARN is the same as the original primary secret except the Region is changed.
     *

     *
     * @param aRN
     *        The ARN of the promoted secret. The ARN is the same as the original primary secret except the Region is
     *        changed.
     * @return Returns a reference to this object so that method calls can be chained together.
     */

    public StopReplicationToReplicaResult withARN(String aRN) {
        setARN(aRN);
        return this;
    }

    /**
     * Returns a string representation of this object. This is useful for testing and debugging. Sensitive data will be
     * redacted from this string using a placeholder value.
     *
     * @return A string representation of this object.
     *
     * @see java.lang.Object#toString()
     */
    @Override
    public String toString() {
        StringBuilder sb = new StringBuilder();
        sb.append("{");
        if (getARN() != null)
            sb.append("ARN: ").append(getARN());
        sb.append("}");
        return sb.toString();
    }

    @Override
    public boolean equals(Object obj) {
        if (this == obj)
            return true;
        if (obj == null)
            return false;

        if (obj instanceof StopReplicationToReplicaResult == false)
            return false;
        StopReplicationToReplicaResult other = (StopReplicationToReplicaResult) obj;
        if (other.getARN() == null ^ this.getARN() == null)
            return false;
        if (other.getARN() != null && other.getARN().equals(this.getARN()) == false)
            return false;
        return true;
    }

    @Override
    public int hashCode() {
        final int prime = 31;
        int hashCode = 1;

        hashCode = prime * hashCode + ((getARN() == null) ? 0 : getARN().hashCode());
        return hashCode;
    }

    @Override
    public StopReplicationToReplicaResult clone() {
        try {
            return (StopReplicationToReplicaResult) super.clone();
        } catch (CloneNotSupportedException e) {
            throw new IllegalStateException("Got a CloneNotSupportedException from Object.clone() " + "even though we're Cloneable!", e);
        }
    }

}


text:
@implementation MUK (Array)

+ (id)array:(NSArray *)array objectAtIndex:(NSInteger)index {
    if (index >= 0 && index < [array count]) {
        return [array objectAtIndex:index];
    }

    return nil;
}

+ (NSArray *)array:(NSArray *)array map:(id (^)(id, NSInteger, BOOL *, BOOL *))block
{
    if (block == nil || [array count] == 0) return array;

    NSMutableArray *mappedArray = [NSMutableArray arrayWithCapacity:[array count]];

    [array enumerateObjectsUsingBlock:^(id obj, NSUInteger idx, BOOL *stop) {
        BOOL exclusionRequested = NO, stopRequested = NO;
        id mappedObject = block(obj, idx, &exclusionRequested, &stopRequested);

        if (stopRequested) {
            *stop = stopRequested;
        }
        else if (exclusionRequested == NO) {
            mappedObject = mappedObject ?: [NSNull null];
            [mappedArray addObject:mappedObject];
        }
    }];

    return mappedArray;
}

+ (NSArray *)array:(NSArray *)array applyingTransform:(MUKArrayTransform)transform
{
    NSArray *output = array;

    switch (transform) {
        case MUKArrayTransformReverse:
            // Elegant solution from http://stackoverflow.com/a/586529
            output = [[array reverseObjectEnumerator] allObjects];
            break;

        default:
            break;
    }

    return output;
}

@end


text:
package updater

import (
	"errors"
	"net/url"
	"strings"

	"github.com/aws/amazon-ecs-agent/agent/acs/model/ecsacs"
)

func validateUpdateInfo(updateInfo *ecsacs.UpdateInfo) error {
	if updateInfo == nil {
		return errors.New("no update info given")
	}
	if updateInfo.Location == nil {
		return errors.New("no location given")
	}
	if updateInfo.Signature == nil {
		return errors.New("no signature given")
	}

	return locationValidation(*updateInfo.Location)
}

const validUpdateHost = "s3.amazonaws.com"
const validUpdateBucket = "amazon-ecs-agent"

// locationValidation validates that the update location points to the
// amazon-ecs-agent update bucket
func locationValidation(location string) error {
	parsed, err := url.Parse(location)
	if err != nil {
		return err
	}

	if parsed.Host != validUpdateHost {
		return errors.New("invalid update host")
	}
	if !strings.HasPrefix(parsed.Path, "/"+validUpdateBucket+"/") {
		return errors.New("invalid update bucket")
	}

	return nil
}


text:
import cv2
import sys, os

def writeVideo(filename, frames, idxList):
    try:
        os.remove(filename)
    except:
        print "No such file!"

    height , width , layers =  frames[0].shape
    print width, height, layers

    fourcc = cv2.cv.CV_FOURCC(*'XVID')
    out = cv2.VideoWriter(filename, fourcc, 30.0, (width,height))

    for i in range(0, len(idxList)):
        idx = idxList[i]
        out.write(frames[idx])
    out.release()

if __name__ == "__main__":
    fourcc = cv2.cv.CV_FOURCC(*'XVID')
    cap = cv2.VideoCapture(sys.argv[1])
    ret, frame = cap.read()
    height , width , layers =  frame.shape
    out = cv2.VideoWriter(sys.argv[2], fourcc, 30.0, (width/2,height/2))
    while(cap.isOpened()):
        ret, frame = cap.read()
        if ret==True:
            #frame = cv2.flip(frame,0)
            # write the flipped frame
            frame = cv2.resize(frame,(width/2,height/2))
            out.write(frame)
            #cv2.imshow('frame',frame)
            #if cv2.waitKey(1) & 0xFF == ord('q'):
                #break
        else:
            break


text:
package com.github.benmanes.caffeine.cache.impl;

import static com.github.benmanes.caffeine.cache.CacheType.CONCURRENCY_LEVEL;
import static java.util.Objects.requireNonNull;

import com.github.benmanes.caffeine.cache.BasicCache;
import com.google.common.cache.Cache;
import com.google.common.cache.CacheBuilder;

/**
 * @author ben.manes@gmail.com (Ben Manes)
 */
public final class GuavaCache<K, V> implements BasicCache<K, V> {
  private final Cache<K, V> cache;

  public GuavaCache(int maximumSize) {
    cache = CacheBuilder.newBuilder()
        .concurrencyLevel(CONCURRENCY_LEVEL)
        .initialCapacity(maximumSize)
        .maximumSize(maximumSize)
        .build();
  }

  public GuavaCache(Cache<K, V> cache) {
    this.cache = requireNonNull(cache);
  }

  @Override
  public V get(K key) {
    return cache.getIfPresent(key);
  }

  @Override
  public void put(K key, V value) {
    cache.put(key, value);
  }

  @Override
  public void remove(K key) {
    cache.invalidate(key);
  }

  @Override
  public void clear() {
    cache.invalidateAll();
  }

  @Override
  public void cleanUp() {
    cache.cleanUp();
  }
}


text:
var bodyParser = require('body-parser');
var express = require('express');
var monoxide = require('monoxide');
var scenario = require('mongoose-scenario');

// Connect
monoxide.connect('mongodb://localhost/monoxide-test');

// Initalize models
var Widgets = monoxide.schema('widgets', {
	name: String,
	content: String,
	status: {type: String, enum: ['active', 'deleted'], default: 'active'},
	color: {type: String, enum: ['red', 'green', 'blue', 'yellow'], default: 'blue', index: true},
});

// Set up some sample data
scenario.import({
	widgets: [
		{
			_ref: 'widget-crash',
			name: 'Widget crash',
			content: 'This is the crash widget',
			// color: 'blue', // Should default to this via schema
		},
		{
			_ref: 'widget-bang',
			name: 'Widget bang',
			content: 'This is the bang widget',
			color: 'red',
		},
		{
			_ref: 'widget-whollop',
			name: 'Widget whollop',
			content: 'This is the whollop widget',
			color: 'blue',
		}
	],
}, {connection: monoxide.connection});

// Set up ExpressJS
var port = 8181;
var url = 'http://localhost:' + port;
var app = express();
app.use(bodyParser.json());

// Install the ReST server
app.use('/api/widgets/:id?', monoxide.express.middleware('widgets', {
	get: true,
	query: true,
	create: true,
	save: true,
	delete: true,
}));

// Boot the server
var server = app.listen(port, null, function(err) {
	if (err) return finish(err);
	console.log('ReST server listening on ' + url);
	console.log();
	console.log('Try some of the following:');
	console.log()
	console.log('     GET ' + url + '/api/widgets - To get a list of all widgets');
	console.log('     GET ' + url + '/api/widgets/ID - To get a specific widget');
	console.log('     GET ' + url + '/api/widgets/?color=blue - To query widgets');
	console.log('    POST ' + url + '/api/widgets - create a new widget')
	console.log('    POST ' + url + '/api/widgets/ID - save to an existing widget')
	console.log('  DELETE ' + url + '/api/widgets/ID - delete an existing widget')
	console.log();
});


text:
%   This file is part of redbKIT.
%   Copyright (c) 2016, Ecole Polytechnique Federale de Lausanne (EPFL)
%   Author: Federico Negri <federico.negri at epfl.ch>

% Before Running the script: Please generate the mesh using the generate_mesh.sh
% script in the mesh subfolder (requires gmsh software)

clc
clear all
close all

[~,~,~] = mkdir('Snapshots');
[~,~,~] = mkdir('Figures');

delete('Snapshots/SystemSnapshots.h5')
delete('Snapshots/DisplacementSnapshots.h5')

%% ========================================================================
% DATA
dim      =  2;
fem      =  'P2';

mu_bar = [];

OfflineTraining.Solution.h5_filename       = 'Snapshots/DisplacementSnapshots.h5';
OfflineTraining.Solution.h5_section        = 'Displacement';
OfflineTraining.Solution.SamplingFrequency = 1;

OfflineTraining.System.h5_filename                      = 'Snapshots/SystemSnapshots.h5';
OfflineTraining.System.InternalForces.h5_section        = 'F_int';
OfflineTraining.System.InternalForces.SamplingFrequency = 1;
OfflineTraining.System.ExternalForces.h5_section        = 'F_ext';
OfflineTraining.System.ExternalForces.SamplingFrequency = 1;

tol_POD_U    = 1e-3;
tol_POD_Fext = 1e-3;
tol_POD_Fint = 1e-3;
%% ========================================================================
% Solve High-Fidelity Models and Collect solution Snapshots

% load P1 mesh
[vertices, boundaries, elements] = msh_to_Mmesh('mesh/Turek_mesh_Solid', dim);

[U, FE_SPACE, MESH, DATA] = CSMt_Solver(dim, elements, vertices, boundaries, fem, 'CSM3_data', ...
    [], [], true, OfflineTraining.Solution);

% PostProcessing
indexA = find(ismember(MESH.vertices(1:2,:)',[0.6 0.2],'rows'));

load ReferenceValues/csm3_l4_t0p005.point;

t = DATA.time.t0:DATA.time.dt:DATA.time.tf;

handle = figure;
subplot(2,1,1)
plot(t,U(indexA,1:length(t)))
hold on
plot(csm3_l4_t0p005(:,1),csm3_l4_t0p005(:,11),'--r')
legend('Test', 'Reference value')
xlabel('time [s]')
ylabel('x-Displacement [m]')
grid on

subplot(2,1,2)
plot(t,U(indexA+FE_SPACE.numDofScalar,1:length(t)))
hold on
plot(csm3_l4_t0p005(:,1),csm3_l4_t0p005(:,12),'--r')
legend('Test', 'Reference value')
xlabel('time [s]')
ylabel('y-Displacement [m]')
hold on
grid on

saveas(handle,'Figures/FOM_Adisplacement','epsc');
saveas(handle,'Figures/FOM_Adisplacement','fig');

%% ========================================================================
% Generate POD basis for the solution
DispSnap_HDF5  = HDF5_DenseMultiCVector(OfflineTraining.Solution.h5_filename, OfflineTraining.Solution.h5_section);
S_u            = DispSnap_HDF5.readValues();
[V,    ~,    Sigma_sol]  = VPOD_basis_computation(S_u, [], tol_POD_U, 1);

figure
loglog(Sigma_sol./Sigma_sol(1),'-or');
hold on
cut_line_x = [1 : size(V,2)];
cut_line_y = Sigma_sol(size(V,2))./Sigma_sol(1) * ones(1,size(V,2));
loglog(cut_line_x, cut_line_y,'--k');
grid on
xlim([1  size(S_u,2)])
title('Solution snapshots spectrum')

clear S_u;

ROM.V = V;

%% ========================================================================
% Solve POD-Galerkin ROM and Collect System Snapshots

[U_POD, Mass] = CSMt_POD_Solver(dim, elements, vertices, boundaries, fem, 'CSM3_data', ...
    [], [], true, OfflineTraining.System, ROM.V);

% PostProcessing
indexA = find(ismember(MESH.vertices(1:2,:)',[0.6 0.2],'rows'));

load ReferenceValues/csm3_l4_t0p005.point;

t = DATA.time.t0:DATA.time.dt:DATA.time.tf;

handle = figure;
subplot(2,1,1)
plot(t,U_POD(indexA,1:length(t)))
hold on
plot(csm3_l4_t0p005(:,1),csm3_l4_t0p005(:,11),'--r')
legend('Test', 'Reference value')
xlabel('time [s]')
ylabel('x-Displacement [m]')
grid on

subplot(2,1,2)
plot(t,U_POD(indexA+FE_SPACE.numDofScalar,1:length(t)))
hold on
plot(csm3_l4_t0p005(:,1),csm3_l4_t0p005(:,12),'--r')
legend('Test', 'Reference value')
xlabel('time [s]')
ylabel('y-Displacement [m]')
hold on
grid on

saveas(handle,'Figures/PODG_ROM_Adisplacement','epsc');
saveas(handle,'Figures/PODG_ROM_Adisplacement','fig');

%% ========================================================================
% Run POD-DEIM on nonlinear Snapshots
Fint_Reader  = HDF5_DenseMultiCVector(OfflineTraining.System.h5_filename, OfflineTraining.System.InternalForces.h5_section);
S_int        = Fint_Reader.readValues();
[Phi_int,    ~,    Sigma_int]  = VPOD_basis_computation(S_int, [], tol_POD_Fint, 1);
[IDEIM_int, P_int] = DEIM( Phi_int );

Fext_Reader  = HDF5_DenseMultiCVector(OfflineTraining.System.h5_filename, OfflineTraining.System.ExternalForces.h5_section);
S_ext        = Fext_Reader.readValues();
[Phi_ext,    ~,    Sigma_ext]  = VPOD_basis_computation(S_ext, [], tol_POD_Fext, 1);
[IDEIM_ext, P_ext] = DEIM( Phi_ext );

figure
subplot(1,2,1)
loglog(Sigma_int./Sigma_int(1),'-or');
hold on
cut_line_x = [1 : size(Phi_int,2)];
cut_line_y = Sigma_int(size(Phi_int,2))./Sigma_int(1) * ones(1,size(Phi_int,2));
loglog(cut_line_x, cut_line_y,'--k');
grid on
xlim([1  size(S_int,2)])
title('Fint snapshots spectrum')

subplot(1,2,2)
loglog(Sigma_ext./Sigma_ext(1),'-or');
hold on
cut_line_x = [1 : size(Phi_ext,2)];
cut_line_y = Phi_ext(size(Phi_ext,2))./Sigma_ext(1) * ones(1,size(Phi_ext,2));
loglog(cut_line_x, cut_line_y,'--k');
grid on
xlim([1  size(S_ext,2)])
title('Fext snapshots spectrum')

clear S_ext S_int;

ROM.Phi_int_IDEIM = Phi_int(IDEIM_int, :);
ROM.Phi_ext_IDEIM = Phi_ext(IDEIM_ext, :);
ROM.IDEIM_ext = IDEIM_ext;
ROM.IDEIM_in  = IDEIM_int;

ROM.LeftProjection_int = ( ROM.V' * Phi_int ) / ( ROM.Phi_int_IDEIM );
ROM.LeftProjection_ext = ( ROM.V' * Phi_ext ) / ( ROM.Phi_ext_IDEIM );

ROM.M = ROM.V' * (Mass(MESH.internal_dof, MESH.internal_dof) * ROM.V);

DATA       = CSM_read_DataFile('CSM3_data', dim, mu_bar);

RedMeshObject =  ReducedMesh( MESH, fem, 'CSM' );
RedMeshObject.AppendInternalDoFs( IDEIM_int );
RedMeshObject.AppendInternalDoFs( IDEIM_ext );
RedMeshObject.Build( DATA );
RedMeshObject.ExportToVtk( 'Figures/', 'Turek2D');

ROM.Red_Mesh = RedMeshObject.M_Red_Mesh;

%% ========================================================================
% Solve POD-DEIM ROM

[U_PODDEIM, ~, ~, DATA_R] = CSMt_PODDEIM_Solver(dim, elements, vertices, boundaries, fem, 'CSM3_data', ...
    [], [], true, ROM);

% PostProcessing
indexA = find(ismember(MESH.vertices(1:2,:)',[0.6 0.2],'rows'));

load ReferenceValues/csm3_l4_t0p005.point;

t = DATA_R.time.t0:DATA_R.time.dt:DATA_R.time.tf;

handle = figure;
subplot(2,1,1)
plot(t,U_PODDEIM(indexA,1:length(t)))
hold on
plot(csm3_l4_t0p005(:,1),csm3_l4_t0p005(:,11),'--r')
legend('Test', 'Reference value')
xlabel('time [s]')
ylabel('x-Displacement [m]')
grid on

subplot(2,1,2)
plot(t,U_PODDEIM(indexA+FE_SPACE.numDofScalar,1:length(t)))
hold on
plot(csm3_l4_t0p005(:,1),csm3_l4_t0p005(:,12),'--r')
legend('Test', 'Reference value')
xlabel('time [s]')
ylabel('y-Displacement [m]')
hold on
grid on

saveas(handle,'Figures/PODDEIM_ROM_Adisplacement','epsc');
saveas(handle,'Figures/PODDEIM_ROM_Adisplacement','fig');

%% ========================================================================


text:
class LegacyRouter(object):
    def db_for_read(self, model, **hints):
        if model._meta.app_label == "legacy":
            return "legacy"
        return None

    def db_for_write(self, model, **hints):
        if model._meta.app_label == "legacy":
            return "legacy"
        return None

    def allow_relation(self, obj1, obj2, **hints):
        return False

    def allow_syncdb(self, db, model):
        return False


text:
package org.apache.commons.digester3.examples.xmlrules.addressbook;

import java.io.PrintStream;

/**
 * See Main.java.
 */
public class Address
{

    private String type;

    private String street;

    private String city;

    private String state;

    private String zip;

    private String country;

    @Override
    public String toString()
    {
        final StringBuilder sb = new StringBuilder();
        sb.append( " address (type " + type + ")\n" );
        sb.append( "       " + street + "\n" );
        sb.append( "       " + city + " " + state + " " + zip + "\n" );
        sb.append( "       " + country + "\n" );
        return sb.toString();
    }

    public void print( final PrintStream out, int indentAmount )
    {
        final StringBuilder indentStr = new StringBuilder( indentAmount );
        for ( ; indentAmount > 0; --indentAmount )
        {
            indentStr.append( ' ' );
        }

        out.print( indentStr );
        out.print( "address type: " );
        out.println( type );

        out.print( indentStr );
        out.println( "  " + street );

        out.print( indentStr );
        out.println( "  " + city + " " + state + " " + zip );

        out.print( indentStr );
        out.println( "  " + country );
    }

    /**
     * Returns the value of street.
     */
    public String getStreet()
    {
        return street;
    }

    /**
     * Sets the value of street.
     *
     * @param street The value to assign to street.
     */
    public void setStreet( final String street )
    {
        this.street = street;
    }

    /**
     * Returns the value of city.
     */
    public String getCity()
    {
        return city;
    }

    /**
     * Sets the value of city.
     *
     * @param city The value to assign to city.
     */
    public void setCity( final String city )
    {
        this.city = city;
    }

    /**
     * Returns the value of state.
     */
    public String getState()
    {
        return state;
    }

    /**
     * Sets the value of state.
     *
     * @param state The value to assign to state.
     */
    public void setState( final String state )
    {
        this.state = state;
    }

    /**
     * Returns the value of zip.
     */
    public String getZip()
    {
        return zip;
    }

    /**
     * Sets the value of zip.
     *
     * @param zip The value to assign to zip.
     */
    public void setZip( final String zip )
    {
        this.zip = zip;
    }

    /**
     * Returns the value of country.
     */
    public String getCountry()
    {
        return country;
    }

    /**
     * Sets the value of country.
     *
     * @param country The value to assign to country.
     */
    public void setCountry( final String country )
    {
        this.country = country;
    }

    /**
     * Returns the value of type.
     */
    public String getType()
    {
        return type;
    }

    /**
     * Sets the value of type.
     *
     * @param type The value to assign to type.
     */
    public void setType( final String type )
    {
        this.type = type;
    }

}


text:
package com.yuffie.util.thread;

/**
 * 多线程-线程模板
 *
 * @author Yuffie
 *
 */
public class ThreadTemplate extends Thread {

    private Object args;

    public ThreadTemplate(Object args) {

        this.args = args;

    }

    public void run() {
        // TODO add function here
    	System.out.println(args);
    	return ;
    }
}