text:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Qwack.Transport.BasicTypes;
using Xunit;

namespace Qwack.Dates.Tests
{
    public class DateFunctionFacts
    {
        private static readonly Calendar EmptyCalendar = new Calendar();
        private static readonly Calendar WeekendsOnly = new Calendar() { DaysToAlwaysExclude = new List<DayOfWeek>() { DayOfWeek.Saturday, DayOfWeek.Sunday } };

        [Fact]
        public void BusinessDaysInPeriod()
        {
            var startDate = new DateTime(2016, 02, 10);
            var endDate = new DateTime(2016, 10, 13);
            Assert.Equal(247, startDate.BusinessDaysInPeriod(endDate, EmptyCalendar).Count);

            var noWeekends = startDate.BusinessDaysInPeriod(endDate, WeekendsOnly);
            Assert.Equal(177, noWeekends.Count);
            Assert.Equal(0, noWeekends.Count(d => d.DayOfWeek == DayOfWeek.Saturday || d.DayOfWeek == DayOfWeek.Sunday));

            Assert.Throws<ArgumentException>(() => endDate.BusinessDaysInPeriod(startDate, WeekendsOnly));
        }

        [Fact]
        public void CalendarDaysInPeriod()
        {
            var startDate = new DateTime(2016, 02, 10);
            var endDate = new DateTime(2016, 10, 13);
            Assert.Equal((endDate - startDate).TotalDays + 1, startDate.CalendarDaysInPeriod(endDate).Count);
            Assert.Throws<ArgumentException>(() => endDate.CalendarDaysInPeriod(startDate));
        }

        [Fact]
        public void FridaysInPeriod()
        {
            var startDate = new DateTime(2018, 08, 01);
            var endDate = new DateTime(2018, 08, 31);
            Assert.Equal(5, startDate.FridaysInPeriod(endDate, EmptyCalendar).Count);
            Assert.Throws<ArgumentException>(() => endDate.FridaysInPeriod(startDate, EmptyCalendar));
        }

        [Fact]
        public void YearFractionSingleYear()
        {
            var startDate = new DateTime(2016, 02, 10);
            var endDate = new DateTime(2016, 10, 13);
            Assert.Equal(246, startDate.CalculateYearFraction(endDate, DayCountBasis.Act360) * 360, 15);
        }

        [Fact]
        public void YearFractionAndBack()
        {
            var startDate = new DateTime(2016, 02, 10);
            var endDate = new DateTime(2016, 10, 13);
            var yf = startDate.CalculateYearFraction(endDate, DayCountBasis.Act365F);
            var date = startDate.AddYearFraction(yf, DayCountBasis.Act365F);
            Assert.Equal(endDate, date);
        }

        [Fact]
        public void FirstBusinessDayOfTheMonthIgnoresTime()
        {
            var dt = new DateTime(2016, 10, 10, 11, 54, 30);
            Assert.Equal(new DateTime(2016, 10, 1), dt.FirstBusinessDayOfMonth(EmptyCalendar));
        }

        [Fact]
        public void FirstBusinessDayOfTheMonthRespectsHolidaysAndWeekends()
        {
            var calendar = new Calendar();
            calendar.DaysToAlwaysExclude.Add(DayOfWeek.Saturday);
            calendar.DaysToAlwaysExclude.Add(DayOfWeek.Sunday);
            calendar.DaysToExclude.Add(new DateTime(2016, 07, 01));

            var dt = new DateTime(2016, 07, 20);

            Assert.Equal(new DateTime(2016, 07, 04), dt.FirstBusinessDayOfMonth(calendar));
        }

        [Fact]
        public void LastBusinessDayOfTheMonthIgnoresTime()
        {
            var dt = new DateTime(2016, 10, 10, 11, 54, 30);
            Assert.Equal(new DateTime(2016, 10, 31), dt.LastBusinessDayOfMonth(EmptyCalendar));
        }

        [Fact]
        public void FirstDayOfMonth()
        {
            var dt = new DateTime(2016, 10, 10);
            Assert.Equal(new DateTime(2016, 10, 1), dt.FirstDayOfMonth());
        }

        [Fact]
        public void LastDayOfMonthDec()
        {
            var dt = new DateTime(2016, 12, 10, 12, 10, 10);
            Assert.Equal(new DateTime(2016, 12, 31), dt.LastDayOfMonth());
        }

        [Fact]
        public void LastDayOfMonthJan()
        {
            var dt = new DateTime(2016, 01, 10, 12, 10, 10);
            Assert.Equal(new DateTime(2016, 01, 31), dt.LastDayOfMonth());
        }

        [Fact]
        public void LastBusinessDayOfTheMonthRespectsHolidaysAndWeekends()
        {
            var calendar = new Calendar();
            calendar.DaysToAlwaysExclude.Add(DayOfWeek.Saturday);
            calendar.DaysToAlwaysExclude.Add(DayOfWeek.Sunday);
            calendar.DaysToExclude.Add(new DateTime(2016, 10, 31));

            var dt = new DateTime(2016, 10, 10);
            Assert.Equal(new DateTime(2016, 10, 28), dt.LastBusinessDayOfMonth(calendar));
        }

        [Fact]
        public void NthSpecificWeekdaySameDay()
        {
            var dt = new DateTime(2016, 11, 1);
            Assert.Equal(new DateTime(2016, 11, 22), dt.NthSpecificWeekDay(DayOfWeek.Tuesday, 4));
        }

        [Fact]
        public void NthSpecificWeekdayDayBefore()
        {
            var dt = new DateTime(2016, 11, 1);
            Assert.Equal(new DateTime(2016, 11, 21), dt.NthSpecificWeekDay(DayOfWeek.Monday, 3));
        }

        [Fact]
        public void NthSpecificWeekdayDayAfter()
        {
            var dt = new DateTime(2016, 11, 1);
            Assert.Equal(new DateTime(2016, 11, 11), dt.NthSpecificWeekDay(DayOfWeek.Friday, 2));
        }

        [Fact]
        public void NthLastSpecificWeekdaySameDay()
        {
            var dt = new DateTime(2018, 7, 1);
            Assert.Equal(new DateTime(2018, 07, 31), dt.NthLastSpecificWeekDay(DayOfWeek.Tuesday, 1));
        }

        [Fact]
        public void NthLastSpecificWeekdayDayBefore()
        {
            var dt = new DateTime(2018, 7, 1);
            Assert.Equal(new DateTime(2018, 07, 17), dt.NthLastSpecificWeekDay(DayOfWeek.Tuesday, 3));
        }

        [Fact]
        public void NthLastSpecificWeekdayDayAfter()
        {
            var dt = new DateTime(2018, 7, 1);
            Assert.Equal(new DateTime(2018, 7, 20), dt.NthLastSpecificWeekDay(DayOfWeek.Friday, 2));
        }

        [Fact]
        public void ThirdWednesday()
        {
            var dt = new DateTime(2016, 11, 20, 10, 20, 10);
            Assert.Equal(new DateTime(2016, 11, 16), dt.ThirdWednesday());
        }

        [Fact]
        public void MinMax()
        {
            var dtA = new DateTime(2016, 11, 20);
            var dtB = new DateTime(2017, 11, 20);

            Assert.Equal(dtA, dtA.Min(dtB));
            Assert.Equal(dtB, dtB.Max(dtA));
        }

        [Fact]
        public void Average()
        {
            var dtA = new DateTime(2016, 11, 20);
            var dtB = new DateTime(2017, 11, 20);
            var avgTicks = (dtA.Ticks + dtB.Ticks) / 2L;
            Assert.Equal(new DateTime(avgTicks), dtA.Average(dtB));

        }

        [Fact]
        public void RollingRules()
        {
            var calendar = new Calendar();
            calendar.DaysToAlwaysExclude.Add(DayOfWeek.Saturday);
            calendar.DaysToAlwaysExclude.Add(DayOfWeek.Sunday);
            calendar.DaysToExclude.Add(new DateTime(2017, 02, 28));

            //this is a saturday
            var date = new DateTime(2017, 02, 18);

            Assert.Equal(new DateTime(2017, 02, 20), date.IfHolidayRoll(RollType.F, calendar));
            Assert.Equal(new DateTime(2017, 02, 20), date.IfHolidayRoll(RollType.MF, calendar));
            Assert.Equal(new DateTime(2017, 02, 17), date.IfHolidayRoll(RollType.P, calendar));
            Assert.Equal(new DateTime(2017, 02, 17), date.IfHolidayRoll(RollType.NearestFollow, calendar));
            Assert.Equal(new DateTime(2017, 02, 17), date.IfHolidayRoll(RollType.NearestPrev, calendar));
            Assert.Equal(new DateTime(2017, 02, 17), date.IfHolidayRoll(RollType.MP, calendar));
            Assert.Equal(new DateTime(2017, 02, 17), date.IfHolidayRoll(RollType.LME, calendar));

            //now a sunday
            date = new DateTime(2017, 02, 19);

            Assert.Equal(new DateTime(2017, 02, 20), date.IfHolidayRoll(RollType.F, calendar));
            Assert.Equal(new DateTime(2017, 02, 20), date.IfHolidayRoll(RollType.MF, calendar));
            Assert.Equal(new DateTime(2017, 02, 17), date.IfHolidayRoll(RollType.P, calendar));
            Assert.Equal(new DateTime(2017, 02, 20), date.IfHolidayRoll(RollType.NearestFollow, calendar));
            Assert.Equal(new DateTime(2017, 02, 20), date.IfHolidayRoll(RollType.NearestPrev, calendar));
            Assert.Equal(new DateTime(2017, 02, 17), date.IfHolidayRoll(RollType.MP, calendar));
            Assert.Equal(new DateTime(2017, 02, 20), date.IfHolidayRoll(RollType.LME, calendar));

            //now month-end holiday
            date = new DateTime(2017, 02, 28);

            Assert.Equal(new DateTime(2017, 03, 01), date.IfHolidayRoll(RollType.F, calendar));
            Assert.Equal(new DateTime(2017, 02, 27), date.IfHolidayRoll(RollType.MF, calendar));
            Assert.Equal(new DateTime(2017, 02, 27), date.IfHolidayRoll(RollType.P, calendar));
            Assert.Equal(new DateTime(2017, 03, 01), date.IfHolidayRoll(RollType.NearestFollow, calendar));
            Assert.Equal(new DateTime(2017, 02, 27), date.IfHolidayRoll(RollType.NearestPrev, calendar));
            Assert.Equal(new DateTime(2017, 02, 27), date.IfHolidayRoll(RollType.MP, calendar));
            Assert.Equal(new DateTime(2017, 02, 27), date.IfHolidayRoll(RollType.LME, calendar));

            //special case for LME (mod-nearest-follow)
            calendar.DaysToExclude.Add(new DateTime(2017, 02, 20));
            date = new DateTime(2017, 02, 19);
            Assert.Equal(new DateTime(2017, 02, 21), date.IfHolidayRoll(RollType.LME, calendar));
            date = new DateTime(2017, 02, 18);
            Assert.Equal(new DateTime(2017, 02, 17), date.IfHolidayRoll(RollType.LME, calendar));
        }

        [Fact]
        public void LME3mRule()
        {
            var calendar = new Calendar();
            calendar.DaysToAlwaysExclude.Add(DayOfWeek.Saturday);
            calendar.DaysToAlwaysExclude.Add(DayOfWeek.Sunday);

            var date = new DateTime(2017, 01, 30);
            var lme3mDate = date.AddPeriod(RollType.LME, calendar, new Frequency("3m"));
            Assert.Equal(new DateTime(2017, 04, 28), lme3mDate);

            //easter 2017
            calendar.DaysToExclude.Add(new DateTime(2017, 04, 14));
            calendar.DaysToExclude.Add(new DateTime(2017, 04, 17));

            date = new DateTime(2017, 01, 14);
            lme3mDate = date.AddPeriod(RollType.LME, calendar, new Frequency("3m"));
            Assert.Equal(new DateTime(2017, 04, 13), lme3mDate);

            date = new DateTime(2017, 01, 15);
            lme3mDate = date.AddPeriod(RollType.LME, calendar, new Frequency("3m"));
            Assert.Equal(new DateTime(2017, 04, 13), lme3mDate);

            date = new DateTime(2017, 01, 16);
            lme3mDate = date.AddPeriod(RollType.LME, calendar, new Frequency("3m"));
            Assert.Equal(new DateTime(2017, 04, 18), lme3mDate);
        }

        [Fact]
        public void PeriodParser()
        {
            var (startDate, endDate) = "CAL19".ParsePeriod();
            Assert.Equal(new DateTime(2019, 1, 1), startDate);
            Assert.Equal(new DateTime(2019, 12, 31), endDate);

            (startDate, endDate) = "CAL-30".ParsePeriod();
            Assert.Equal(new DateTime(2030, 1, 1), startDate);
            Assert.Equal(new DateTime(2030, 12, 31), endDate);

            (startDate, endDate) = "Q4-22".ParsePeriod();
            Assert.Equal(new DateTime(2022, 10, 1), startDate);
            Assert.Equal(new DateTime(2022, 12, 31), endDate);

            (startDate, endDate) = "Q422".ParsePeriod();
            Assert.Equal(new DateTime(2022, 10, 1), startDate);
            Assert.Equal(new DateTime(2022, 12, 31), endDate);

            (startDate, endDate) = "Q1-22".ParsePeriod();
            Assert.Equal(new DateTime(2022, 1, 1), startDate);
            Assert.Equal(new DateTime(2022, 3, 31), endDate);

            (startDate, endDate) = "H122".ParsePeriod();
            Assert.Equal(new DateTime(2022, 1, 1), startDate);
            Assert.Equal(new DateTime(2022, 6, 30), endDate);

            (startDate, endDate) = "H2-22".ParsePeriod();
            Assert.Equal(new DateTime(2022, 7, 1), startDate);
            Assert.Equal(new DateTime(2022, 12, 31), endDate);

            (startDate, endDate) = "FEB-22".ParsePeriod();
            Assert.Equal(new DateTime(2022, 2, 1), startDate);
            Assert.Equal(new DateTime(2022, 2, 28), endDate);

            (startDate, endDate) = "FEB 22".ParsePeriod();
            Assert.Equal(new DateTime(2022, 2, 1), startDate);
            Assert.Equal(new DateTime(2022, 2, 28), endDate);

            (startDate, endDate) = "FEB22".ParsePeriod();
            Assert.Equal(new DateTime(2022, 2, 1), startDate);
            Assert.Equal(new DateTime(2022, 2, 28), endDate);
        }

        [Fact]
        public void NextWeekday()
        {
            var d = DateTime.Parse("2018-08-24"); //Friday 24th Aug 2018
            Assert.Equal(new DateTime(2018, 08, 29), d.GetNextWeekday(DayOfWeek.Wednesday));
            Assert.Equal(new DateTime(2018, 08, 30), d.GetNextWeekday(DayOfWeek.Thursday));
            Assert.Equal(new DateTime(2018, 08, 31), d.GetNextWeekday(DayOfWeek.Friday));
            Assert.Equal(new DateTime(2018, 08, 27), d.GetNextWeekday(DayOfWeek.Monday));

            d = DateTime.Parse("2018-08-20"); //Monday 20th Aug 2018
            Assert.Equal(new DateTime(2018, 08, 22), d.GetNextWeekday(DayOfWeek.Wednesday));
            Assert.Equal(new DateTime(2018, 08, 23), d.GetNextWeekday(DayOfWeek.Thursday));
        }

        [Fact]
        public void NextPrevIMMDate()
        {
            Assert.Equal(new DateTime(2018, 09, 19), DateTime.Parse("2018-08-24").GetNextImmDate());
            Assert.Equal(new DateTime(2018, 09, 19), DateTime.Parse("2018-09-10").GetNextImmDate());
            Assert.Equal(new DateTime(2018, 12, 19), DateTime.Parse("2018-09-19").GetNextImmDate());
            Assert.Equal(new DateTime(2019, 03, 20), DateTime.Parse("2018-12-20").GetNextImmDate());

            Assert.Equal(new DateTime(2018, 06, 20), DateTime.Parse("2018-08-24").GetPrevImmDate());
            Assert.Equal(new DateTime(2018, 06, 20), DateTime.Parse("2018-09-19").GetPrevImmDate());
            Assert.Equal(new DateTime(2018, 09, 19), DateTime.Parse("2018-09-20").GetPrevImmDate());
            Assert.Equal(new DateTime(2018, 12, 19), DateTime.Parse("2019-03-19").GetPrevImmDate());
        }

        [Theory]
        [MemberData(nameof(GetYFExamples))]
        public void YearFraction(DateTime startDate, DateTime endDate, DayCountBasis basis, double yf) => Assert.Equal(yf, startDate.CalculateYearFraction(endDate, basis));

        public static IEnumerable<object[]> GetYFExamples()
        {
            var holidays = new List<object[]>()
            {
                new object[] { new DateTime(2015,07,04), new DateTime(2015, 08, 04), DayCountBasis.Act_Act, 31.0/365.0 }, //year is not leap
                new object[] { new DateTime(2016,07,04), new DateTime(2016, 08, 04), DayCountBasis.Act_Act, 31.0/366.0 }, //year is leap
                new object[] { new DateTime(2016,07,04), new DateTime(2017, 07, 04), DayCountBasis.Act_Act, 180/366.0 + 185/365.0 },  //cross years

                new object[] { new DateTime(2015,07,04), new DateTime(2015, 08, 04), DayCountBasis._30_360, 1.0/12 },
                new object[] { new DateTime(2016,07,04), new DateTime(2016, 08, 04), DayCountBasis._30_360, 1.0/12 },
                new object[] { new DateTime(2016,07,04), new DateTime(2017, 07, 04), DayCountBasis._30_360, 1.0 },

                new object[] { new DateTime(2016,03,04), new DateTime(2017, 09, 04), DayCountBasis.Unity, 1.0 },

            };

            return holidays;
        }

        [Fact]
        public void xDigitYear()
        {
            Assert.Equal(18, DateExtensions.DoubleDigitYear(2018));
            Assert.Equal(8, DateExtensions.SingleDigitYear(2018));

            Assert.Equal(28, DateExtensions.DoubleDigitYear(2028));
            Assert.Equal(8, DateExtensions.SingleDigitYear(2028));
        }

        [Theory]
        //https://en.wikipedia.org/wiki/List_of_dates_for_Easter
        [InlineData(1999, "1999-04-04")]
        [InlineData(2001, "2001-04-15")]
        [InlineData(2002, "2002-03-31")]
        [InlineData(2005, "2005-03-27")]
        [InlineData(2010, "2010-04-04")]
        [InlineData(2019, "2019-04-21")]
        [InlineData(2020, "2020-04-12")]
        [InlineData(2024, "2024-03-31")]
        public void GaussEaster(int year, string expected)
        {
            var e = DateTime.Parse(expected);
            Assert.Equal(e, DateExtensions.EasterGauss(year));
        }

    }
}


text:
package ankel.seniorsky.bridle.http.codec.response;

import java.util.Map;

/**
 * @author Binh Tran
 */
public class HttpBadRequest extends AbstractHttpResponse
{
  public HttpBadRequest(final Map<String, String> headers, final byte[] body)
  {
    super(400, "Bad Request", headers, body);
  }
}

redpajama_set_name: RedPajamaGithub


text:
namespace FourSquare.SharpSquare.Entities
{
    public class Link : FourSquareEntity
    {
        /// <summary>
        /// For now just contains an id of a provider, e.g. nymag.
        /// </summary>
        public string provider
        {
            get;
            set;
        }

        /// <summary>
        /// optional If present, a URL for additional information about this venue from this provider.
        /// </summary>
        public string url
        {
            get;
            set;
        }

        /// <summary>
        /// optional If present, the identifer used by this provider to identify this venue.
        /// </summary>
        public string linkedId
        {
            get;
            set;
        }
    }
}


text:
  Beauvoisin est
      une ville géographiquement positionnée dans le département de Gard en Languedoc-Roussillon. Elle comptait 3 308 habitants en 2008.

À coté de Beauvoisin sont situées les communes de
Codognan située à 8 km, 2 492 habitants,
Bernis localisée à 6 km, 2 975 habitants,
Vestric-et-Candiac située à 5 km, 1 328 habitants,
Générac à 2 km, 3 629 habitants,
Milhaud à 8 km, 5 485 habitants,
Aubord située à 4 km, 2 303 habitants,
 entre autres. De plus, Beauvoisin est située à seulement treize km de Nîmes.

Le nombre d'habitations, à Beauvoisin, se décomposait en 2011 en 211 appartements et 1 446 maisons soit
 un marché plutôt équilibré.

À Beauvoisin, la valeur moyenne à la vente d'un appartement s'évalue à 2 287 € du m² en vente. la valorisation moyenne d'une maison à l'achat se situe à 2 213 € du m². À la location la valeur moyenne se situe à 7,53 € du m² par mois.

La commune propose de nombreux  équipements sportifs, elle dispose, entre autres, de un terrain de tennis, deux terrains de sport, une salle de combat et une boucle de randonnée.

À Beauvoisin le salaire moyen par mois par personne se situe à approximativement 2 079 €  net. Ceci est inférieur à la moyenne nationale.


text:
<md-sidenav-layout [class.m2app-dark]="isDarkTheme">
   <md-sidenav #sidenav mode="side" class="app-sidenav">
      <md-card-header>

        <md-card-title>{{ (user | async)?.isAnonymous ? 'Anònim' : (user | async)?.displayName }}</md-card-title>
        <md-card-subtitle>{{ (user | async)?.email }} </md-card-subtitle>
      </md-card-header>

      <md-card-content>
        <md-list>
          <md-list-item *ngIf="isAdministrator | async">
            <button md-button [routerLink]="['/admin']" routerLinkActive="active" [routerLinkActiveOptions]="{exact: true}">ADMIN</button>
          </md-list-item>
          <md-list-item>
            <button md-button [routerLink]="['/secured']" routerLinkActive="active" [routerLinkActiveOptions]="{exact: true}">INICI</button>
          </md-list-item>
          <md-list-item>
            <button md-button [routerLink]="['/secured/songs']" routerLinkActive="active" [routerLinkActiveOptions]="{exact: true}">CANÇONS</button>
          </md-list-item>
          <md-list-item>
             <button md-button [routerLink]="['/secured/pos']" routerLinkActive="active" [routerLinkActiveOptions]="{exact: true}">CLASSIFICACIÓ</button>
          </md-list-item>
        </md-list>
      </md-card-content>
  </md-sidenav>

  <md-toolbar color="primary">
    <button class="app-icon-button" (click)="sidenav.toggle()">
      menu
    </button>

    LCD v.3

    <button md-raised-button color="accent" (click)="logout()">Logout {{ (user | async)?.isAnonymous ? 'Anònim' :(user | async)?.displayName }}</button>
  </md-toolbar>

    <router-outlet></router-outlet>

</md-sidenav-layout>

  <button md-fab><md-icon>check circle</md-icon></button>


text:
package com.github.javaparser.symbolsolver.javaparser;

import com.github.javaparser.ast.CompilationUnit;
import com.github.javaparser.ast.Node;
import com.github.javaparser.ast.body.*;
import com.github.javaparser.ast.expr.MethodCallExpr;
import com.github.javaparser.ast.expr.NameExpr;
import com.github.javaparser.ast.expr.SimpleName;
import com.github.javaparser.ast.stmt.ReturnStmt;
import com.github.javaparser.ast.stmt.SwitchStmt;

import java.util.LinkedList;
import java.util.List;
import java.util.Optional;

/**
 * This class can be used to easily retrieve nodes from a JavaParser AST.
 *
 * @author Federico Tomassetti
 */
public final class Navigator {

    private Navigator() {
        // prevent instantiation
    }

    public static Node getParentNode(Node node) {
        Node parent = node.getParentNode().orElse(null);
        return parent;
    }

    public static Optional<TypeDeclaration<?>> findType(CompilationUnit cu, String qualifiedName) {
        if (cu.getTypes().isEmpty()) {
            return Optional.empty();
        }

        final String typeName = getOuterTypeName(qualifiedName);
        Optional<TypeDeclaration<?>> type = cu.getTypes().stream().filter((t) -> t.getName().getId().equals(typeName)).findFirst();

        final String innerTypeName = getInnerTypeName(qualifiedName);
        if (type.isPresent() && !innerTypeName.isEmpty()) {
            return findType(type.get(), innerTypeName);
        }
        return type;
    }

    public static Optional<TypeDeclaration<?>> findType(TypeDeclaration<?> td, String qualifiedName) {
        final String typeName = getOuterTypeName(qualifiedName);

        Optional<TypeDeclaration<?>> type = Optional.empty();
        for (Node n : td.getMembers()) {
            if (n instanceof TypeDeclaration && ((TypeDeclaration<?>) n).getName().getId().equals(typeName)) {
                type = Optional.of((TypeDeclaration<?>) n);
                break;
            }
        }
        final String innerTypeName = getInnerTypeName(qualifiedName);
        if (type.isPresent() && !innerTypeName.isEmpty()) {
            return findType(type.get(), innerTypeName);
        }
        return type;
    }

    public static ClassOrInterfaceDeclaration demandClass(CompilationUnit cu, String qualifiedName) {
        ClassOrInterfaceDeclaration cd = demandClassOrInterface(cu, qualifiedName);
        if (cd.isInterface()) {
            throw new IllegalStateException("Type is not a class");
        }
        return cd;
    }

    public static EnumDeclaration demandEnum(CompilationUnit cu, String qualifiedName) {
        Optional<TypeDeclaration<?>> res = findType(cu, qualifiedName);
        if (!res.isPresent()) {
            throw new IllegalStateException("No type found");
        }
        if (!(res.get() instanceof EnumDeclaration)) {
            throw new IllegalStateException("Type is not an enum");
        }
        return (EnumDeclaration) res.get();
    }

    public static MethodDeclaration demandMethod(TypeDeclaration<?> cd, String name) {
        MethodDeclaration found = null;
        for (BodyDeclaration<?> bd : cd.getMembers()) {
            if (bd instanceof MethodDeclaration) {
                MethodDeclaration md = (MethodDeclaration) bd;
                if (md.getName().getId().equals(name)) {
                    if (found != null) {
                        throw new IllegalStateException("Ambiguous getName");
                    }
                    found = md;
                }
            }
        }
        if (found == null) {
            throw new IllegalStateException("No method with given name");
        }
        return found;
    }

    public static VariableDeclarator demandField(ClassOrInterfaceDeclaration cd, String name) {
        for (BodyDeclaration<?> bd : cd.getMembers()) {
            if (bd instanceof FieldDeclaration) {
                FieldDeclaration fd = (FieldDeclaration) bd;
                for (VariableDeclarator vd : fd.getVariables()) {
                    if (vd.getName().getId().equals(name)) {
                        return vd;
                    }
                }
            }
        }
        throw new IllegalStateException("No field with given name");
    }

    public static NameExpr findNameExpression(Node node, String name) {
        if (node instanceof NameExpr) {
            NameExpr nameExpr = (NameExpr) node;
            if (nameExpr.getName() != null && nameExpr.getName().getId().equals(name)) {
                return nameExpr;
            }
        }
        for (Node child : node.getChildNodes()) {
            NameExpr res = findNameExpression(child, name);
            if (res != null) {
                return res;
            }
        }
        return null;
    }

    public static SimpleName findSimpleName(Node node, String name) {
        if (node instanceof SimpleName) {
            SimpleName nameExpr = (SimpleName) node;
            if (nameExpr.getId() != null && nameExpr.getId().equals(name)) {
                return nameExpr;
            }
        }
        for (Node child : node.getChildNodes()) {
            SimpleName res = findSimpleName(child, name);
            if (res != null) {
                return res;
            }
        }
        return null;
    }

    public static MethodCallExpr findMethodCall(Node node, String methodName) {
        if (node instanceof MethodCallExpr) {
            MethodCallExpr methodCallExpr = (MethodCallExpr) node;
            if (methodCallExpr.getName().getId().equals(methodName)) {
                return methodCallExpr;
            }
        }
        for (Node child : node.getChildNodes()) {
            MethodCallExpr res = findMethodCall(child, methodName);
            if (res != null) {
                return res;
            }
        }
        return null;
    }

    public static VariableDeclarator demandVariableDeclaration(Node node, String name) {
        if (node instanceof VariableDeclarator) {
            VariableDeclarator variableDeclarator = (VariableDeclarator) node;
            if (variableDeclarator.getName().getId().equals(name)) {
                return variableDeclarator;
            }
        }
        for (Node child : node.getChildNodes()) {
            VariableDeclarator res = demandVariableDeclaration(child, name);
            if (res != null) {
                return res;
            }
        }
        return null;
    }

    public static ClassOrInterfaceDeclaration demandClassOrInterface(CompilationUnit compilationUnit, String qualifiedName) {
        Optional<TypeDeclaration<?>> res = findType(compilationUnit, qualifiedName);
        if (!res.isPresent()) {
            throw new IllegalStateException("No type named '" + qualifiedName + "'found");
        }
        if (!(res.get() instanceof ClassOrInterfaceDeclaration)) {
            throw new IllegalStateException("Type is not a class or an interface, it is " + res.get().getClass().getCanonicalName());
        }
        ClassOrInterfaceDeclaration cd = (ClassOrInterfaceDeclaration) res.get();
        return cd;
    }

    public static SwitchStmt findSwitch(Node node) {
        SwitchStmt res = findSwitchHelper(node);
        if (res == null) {
            throw new IllegalArgumentException();
        } else {
            return res;
        }
    }

    public static <N> N findNodeOfGivenClass(Node node, Class<N> clazz) {
        N res = findNodeOfGivenClassHelper(node, clazz);
        if (res == null) {
            throw new IllegalArgumentException();
        } else {
            return res;
        }
    }

    public static <N> List<N> findAllNodesOfGivenClass(Node node, Class<N> clazz) {
        List<N> res = new LinkedList<>();
        findAllNodesOfGivenClassHelper(node, clazz, res);
        return res;
    }

    public static ReturnStmt findReturnStmt(MethodDeclaration method) {
        return findNodeOfGivenClass(method, ReturnStmt.class);
    }

    public static <N extends Node> Optional<N> findAncestor(Node node, Class<N> clazz) {
        if (!node.getParentNode().isPresent()) {
            return Optional.empty();
        } else if (clazz.isInstance(node.getParentNode().get())) {
            return Optional.of(clazz.cast(node.getParentNode().get()));
        } else {
            return findAncestor(node.getParentNode().get(), clazz);
        }
    }

    ///
    /// Private methods
    ///

    private static String getOuterTypeName(String qualifiedName) {
        return qualifiedName.split("\\.", 2)[0];
    }

    private static String getInnerTypeName(String qualifiedName) {
        if (qualifiedName.contains(".")) {
            return qualifiedName.split("\\.", 2)[1];
        }
        return "";
    }

    private static SwitchStmt findSwitchHelper(Node node) {
        if (node instanceof SwitchStmt) {
            return (SwitchStmt) node;
        }
        for (Node child : node.getChildNodes()) {
            SwitchStmt resChild = findSwitchHelper(child);
            if (resChild != null) {
                return resChild;
            }
        }
        return null;
    }

    private static <N> N findNodeOfGivenClassHelper(Node node, Class<N> clazz) {
        if (clazz.isInstance(node)) {
            return clazz.cast(node);
        }
        for (Node child : node.getChildNodes()) {
            N resChild = findNodeOfGivenClassHelper(child, clazz);
            if (resChild != null) {
                return resChild;
            }
        }
        return null;
    }

    private static <N> void findAllNodesOfGivenClassHelper(Node node, Class<N> clazz, List<N> collector) {
        if (clazz.isInstance(node)) {
            collector.add(clazz.cast(node));
        }
        for (Node child : node.getChildNodes()) {
            findAllNodesOfGivenClassHelper(child, clazz, collector);
        }
    }
}


text:
package libdokan

import (
	"github.com/keybase/client/go/kbfs/dokan"
	"github.com/keybase/client/go/kbfs/libkbfs"
	"golang.org/x/net/context"
)

// Symlink represents KBFS symlinks.
type Symlink struct {
	// The directory this symlink is in. This should be safe to store
	// here, without fear of Renames etc making it stale, because we
	// never persist a Symlink into Folder.nodes; it has no
	// libkbfs.Node, so that's impossible. This should make FUSE
	// Lookup etc always get new nodes, limiting the lifetime of a
	// single Symlink value.
	parent *Dir
	// isTargetADirectory - Some Windows programs want to know.
	isTargetADirectory bool
	name               string
	emptyFile
}

// GetFileInformation does stat for dokan.
func (s *Symlink) GetFileInformation(ctx context.Context, fi *dokan.FileInfo) (a *dokan.Stat, err error) {
	s.parent.folder.fs.logEnter(ctx, "Symlink GetFileInformation")
	defer func() { s.parent.folder.reportErr(ctx, libkbfs.ReadMode, err) }()

	_, _, err = s.parent.folder.fs.config.KBFSOps().Lookup(
		ctx, s.parent.node, s.parent.node.ChildName(s.name))
	if err != nil {
		return nil, errToDokan(err)
	}

	if s.isTargetADirectory {
		return defaultSymlinkDirInformation()
	}
	return defaultSymlinkFileInformation()
}


text:
import RpmMeter, { PULSE_EVENT } from "spin-bike-rpm-meter";

const rpmMeter = new RpmMeter();

// Start listening to the "pulses". Asks for permission to the microphone. Run start() before
// starting to cycle on the spin bike.
rpmMeter.start().then((stop) => {
	console.log('Starting listening to pulses...');

	// After each revolution on the bike, a PULSE_EVENT is emitted containing some useful data about it.
	rpmMeter.on(PULSE_EVENT, (pulseData) => {
		console.log(pulseData);

		// This is how the pulseData might look
		//pulseData = {
		//	'timestamp': 1454060831,
		//	'secondsBetweenPulses': 0.8,
		//	'rpm': 75
		//};

	});

	// Stop listening to the "pulses" after 10 seconds.
	setTimeout(() => {
		stop();

		console.log('Stopped listening to pulses...');
	}, 10000);
});


text:
package de.danoeh.antennapod.core.glide;

import android.content.Context;

import com.bumptech.glide.Glide;
import com.bumptech.glide.GlideBuilder;
import com.bumptech.glide.load.DecodeFormat;
import com.bumptech.glide.load.engine.cache.InternalCacheDiskCacheFactory;
import com.bumptech.glide.load.model.GlideUrl;
import com.bumptech.glide.module.GlideModule;

import java.io.InputStream;

import de.danoeh.antennapod.core.preferences.UserPreferences;

/**
 * {@see com.bumptech.glide.integration.okhttp.OkHttpGlideModule}
 */
public class ApGlideModule implements GlideModule {

    @Override
    public void applyOptions(Context context, GlideBuilder builder) {
        builder.setDecodeFormat(DecodeFormat.PREFER_ARGB_8888);
        builder.setDiskCache(new InternalCacheDiskCacheFactory(context,
                UserPreferences.getImageCacheSize()));
    }

    @Override
    public void registerComponents(Context context, Glide glide) {
        glide.register(GlideUrl.class, InputStream.class, new ApOkHttpUrlLoader.Factory());
    }

}


text:
% Test file for ADCHEBFUN CUMPROD() and PROD()

function pass = test_cumprodProd

% List of trigonometric functions to test.
funcList = {@cumprod, @prod};

% Call the ADCHEBFUN testUnary() method to do the tests.
pass = adchebfun.testUnary(funcList);

end


text:
from future.utils import python_2_unicode_compatible

from django.db import models
from django.utils.translation import ugettext_lazy as _

from fluent_contents.extensions import (
    PluginHtmlField, PluginImageField, PluginUrlField)
from fluent_contents.models.db import ContentItem

from django_wysiwyg.utils import clean_html, sanitize_html

from . import appsettings

@python_2_unicode_compatible
class TeaserItem(ContentItem):

    title = models.CharField(_("title"), max_length=256)
    image = PluginImageField(_("image"), upload_to=appsettings.FLUENTCMS_TEASER_UPLOAD_TO, blank=True, null=True)
    url = PluginUrlField(_("URL"), null=True, blank=True,
        help_text=_("If present image will be clickable."))
    url_title = models.CharField(_("URL title"), max_length=200, blank=True, null=True)

    description = PluginHtmlField(_("description"), blank=True, null=True)

    target = models.CharField(_("target"), blank=True, max_length=100, choices=((
        ("", _("same window")),
        ("_blank", _("new window")),
        ("_parent", _("parent window")),
        ("_top", _("topmost frame")),
    )))

    class Meta:
        verbose_name = _("Teaser")
        verbose_name_plural = _("Teasers")

    def __str__(self):
        return self.title

    def save(self, *args, **kwargs):
        if appsettings.FLUENTCMS_TEASER_CLEAN_HTML:
            self.description = clean_html(self.description)

        # Remove unwanted tags if requested
        if appsettings.FLUENTCMS_TEASER_SANITIZE_HTML:
            self.description = sanitize_html(self.description)

        super(TeaserItem, self).save(*args, **kwargs)


text:
layout: page
title: Pink Warden Technologies Dinner
date: 2016-05-24
author: Lawrence Pittman
tags: weekly links, java
status: published
summary: Maecenas molestie malesuada mauris, dignissim auctor nibh.
banner: images/banner/meeting-01.jpg
booking:
  startDate: 01/19/2018
  endDate: 01/23/2018
  ctyhocn: LPLJLHX
  groupCode: PWTD
published: true
---
Fusce sodales, enim nec mollis pulvinar, nulla velit rutrum est, id placerat ante nisi nec urna. Integer at quam nulla. Morbi odio tortor, feugiat a porttitor mollis, efficitur vel enim. Ut sollicitudin odio sit amet justo fermentum consectetur. Donec ornare tortor vitae erat convallis, eu scelerisque quam ornare. Aliquam ut ante id felis aliquet mollis. Phasellus dolor quam, semper non nisl eget, suscipit fermentum lorem. Donec faucibus risus at lacus egestas, ac condimentum arcu dapibus. Curabitur dignissim, ex id cursus euismod, turpis elit egestas purus, nec posuere purus erat quis purus. Integer consectetur nisi sit amet sodales aliquet. Sed vulputate eu urna faucibus placerat. Etiam non eleifend tortor. Aliquam at nunc quis erat bibendum dapibus vitae at odio. Donec rutrum nunc eget pulvinar ornare.

* Aliquam egestas dui sed magna sollicitudin, quis feugiat leo sollicitudin
* Fusce nec mi nec tortor dictum dictum at laoreet odio
* Sed venenatis ex imperdiet, cursus tellus eget, imperdiet orci
* Curabitur id enim dignissim, egestas justo eget, ultricies nibh
* Nam consectetur dolor hendrerit, aliquet diam sed, congue risus.

Sed molestie erat sit amet gravida consectetur. Maecenas maximus eu est et interdum. Ut sed est eget nunc venenatis accumsan. Maecenas commodo odio vitae ante finibus, ac vehicula justo pellentesque. In scelerisque risus a ex dignissim congue. Quisque vel turpis facilisis, volutpat enim eget, gravida dolor. Proin condimentum, lectus a interdum pellentesque, erat enim luctus ligula, non luctus odio lacus quis sem. Pellentesque faucibus eleifend odio, quis accumsan tortor dapibus eu.
Aenean non rhoncus tortor. Praesent viverra luctus ante, quis feugiat nulla auctor commodo. Mauris et ex sem. Fusce tempus purus ut felis semper, non interdum sapien pretium. Lorem ipsum dolor sit amet, consectetur adipiscing elit. Curabitur eget turpis quis mauris posuere consectetur sed quis ligula. Fusce quis nunc id ipsum pellentesque sagittis. Mauris id dolor leo. Sed nunc augue, venenatis et volutpat ac, ullamcorper non elit.


text:
package io.github.biezhi.wechat.utils;

import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
import com.google.gson.reflect.TypeToken;
import com.vdurmont.emoji.EmojiParser;
import io.github.biezhi.wechat.exception.WeChatException;
import lombok.extern.slf4j.Slf4j;

import java.io.*;
import java.lang.reflect.Type;
import java.net.FileNameMap;
import java.net.URLConnection;
import java.util.Random;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

/**
 * 微信公共静态方法
 *
 * @author biezhi
 * @date 2018/1/19
 */
@Slf4j
public class WeChatUtils {

    private static final Gson GSON        = new Gson();
    private static final Gson PRETTY_GSON = new GsonBuilder().setPrettyPrinting().create();

    /**
     * 正则匹配
     *
     * @param reg
     * @param text
     * @return
     */
    public static String match(String reg, String text) {
        Pattern pattern = Pattern.compile(reg);
        Matcher m       = pattern.matcher(text);
        if (m.find()) {
            return m.group(1);
        }
        return null;
    }

    public static Matcher matcher(String reg, String text) {
        Pattern pattern = Pattern.compile(reg);
        return pattern.matcher(text);
    }

    /**
     * 格式化微信消息
     *

     * 处理emoji表情、HTML转义符
     *
     * @param msg
     * @return
     */
    public static String formatMsg(String msg) {
        msg = msg.replace("<", "<")
                .replace(">", ">")
                .replace("
", "\n");
        return emojiParse(msg);
    }

    /**
     * 获取文件 MimeType
     *
     * @param fileUrl
     * @return
     */
    public static String getMimeType(String fileUrl) {
        FileNameMap fileNameMap = URLConnection.getFileNameMap();
        String      type        = fileNameMap.getContentTypeFor(fileUrl);
        return type;
    }

    public static String emojiParse(String text) {
        Matcher       m         = matcher("", text);
        StringBuilder sb        = new StringBuilder();
        int           lastStart = 0;
        while (m.find()) {
            String str = m.group(1);
            if (str.length() == 6) {

            } else if (str.length() == 10) {

            } else {
                str = "&#x" + str + ";";
                String tmp = text.substring(lastStart, m.start());
                sb.append(tmp + str);
                lastStart = m.end();
            }
        }
        if (lastStart < text.length()) {
            sb.append(text.substring(lastStart));
        }
        if (sb.length() > 0) {
            return EmojiParser.parseToUnicode(sb.toString());
        }
        return text;
    }

    public static String toPrettyJson(Object bean) {
        return PRETTY_GSON.toJson(bean);
    }

    public static String toJson(Object bean) {
        return GSON.toJson(bean);
    }

    public static <T> T fromJson(String json, Class<T> from) {
        return GSON.fromJson(json, from);
    }

    public static <T> T fromJson(String json, Type from) {
        return GSON.fromJson(json, from);
    }

    public static <T> T fromJson(FileReader fileReader, Type from) {
        return GSON.fromJson(fileReader, from);
    }

    public static <T> T fromJson(String json, TypeToken<T> typeToken) {
        return GSON.fromJson(json, typeToken.getType());
    }

    public static File saveFile(InputStream inputStream, String dirPath, String id) {
        return saveFileByDay(inputStream, dirPath, id, false);
    }

    public static File saveFileByDay(InputStream inputStream, String dirPath, String id, boolean byDay) {
        OutputStream outputStream = null;
        try {
            if (byDay) {
                dirPath = dirPath + "/" + DateUtils.getDateString();
            }
            File dir = new File(dirPath);
            if (!dir.isDirectory()) {
                dir.mkdirs();
            }
            File path = new File(dir, id);
            if (path.exists()) {
                path.delete();
            }
            outputStream = new FileOutputStream(path);

            byte[] buffer = new byte[1024];
            int    len    = 0;
            while ((len = inputStream.read(buffer)) != -1) {
                outputStream.write(buffer, 0, len);
            }
            outputStream.flush();
            return path;
        } catch (Exception e) {
            throw new WeChatException(e);
        } finally {
            try {
                if (inputStream != null) {
                    inputStream.close();
                }
                if (outputStream != null) {
                    outputStream.close();
                }
            } catch (IOException e) {
            }
        }
    }

    public static <T> void writeJson(String file, T data) {
        try {
            FileWriter writer = new FileWriter(file);
            GSON.toJson(data, writer);
            writer.close();
        } catch (Exception e) {
            log.warn("写入JSON到文件: {} 失败", file, e);
        }
    }

    public static int random(int min, int max) {
        Random random = new Random();
        return random.nextInt(max) % (max - min + 1) + min;
    }

}


text:
class GLDynamicBitmap:public RefCount
{
public:
    GLDynamicBitmap(GPPtr<GLBmp> backgroud);
    virtual ~GLDynamicBitmap();
    void addFrames(GPPtr<GLBmp> frame, int l, int t);
    void clearFrames();
    void render(GLBmp* display, size_t n, bool render_dirty) const;
    inline int width() const {return mBackGround->width();}
    inline int height() const {return mBackGround->height();}

    inline size_t getFrames() const {return mDynamics.size();}
private:
    GPPtr<GLBmp> mBackGround;
    std::vector<std::pair<GPPtr<GLBmp>, GLRect>> mDynamics;
};
#endif


text:
package edu.jhu.hlt.alnc;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.UncheckedIOException;
import java.nio.charset.StandardCharsets;
import java.nio.file.Files;
import java.nio.file.Path;
import java.util.stream.Stream;

import com.fasterxml.jackson.databind.ObjectMapper;

/**
 * Class that can be used to convert ALNC files to {@link ALNCArticleBean} objects.
 *

 *

 * Each file, as of 2015/2/23, contain one JSON object per line.
 */
public class ALNCFileConverter implements AutoCloseable {

  private static final ObjectMapper om = new ObjectMapper();

  private final InputStream is;
  private final InputStreamReader isr;
  private final BufferedReader br;

  /**
   * Wrap an {@link InputStream} that represents ALNC JSON, one JSON object per line.
   *
   * @param is an {@link InputStream} over properly formed ALNC JSON data
   */
  public ALNCFileConverter(InputStream is) {
    this.is = is;
    this.isr = new InputStreamReader(is, StandardCharsets.UTF_8);
    this.br = new BufferedReader(this.isr, 1024 * 8 * 8 * 4);
  }

  public ALNCFileConverter(Path path) throws IOException {
    this(Files.newInputStream(path));
  }

  /**
   * Return a {@link Stream} of {@link ALNCArticleBean} objects. This stream should be
   * closed when processing is complete.
   *

   *

   * This method can throw an unchecked exception. This will
   * occur when the underlying InputStream does not represent ALNC JSON data.
   *
   * @return a {@link Stream} of {@link ALNCArticleBean} objects.
   * @throws IOException if there is an issue reading the underlying archive.
   * @throws UncheckedIOException if there is an issue with the conversion.
   */
  public Stream<ALNCArticleBean> stream() throws IOException {
    return this.br.lines()
        .sequential()
        .map(l -> {
          try {
            // unlikely to throw, provided stream is corrent JSON objects.
            return om.readValue(l, ALNCArticleBean.class);
          } catch (IOException e) {
            throw new UncheckedIOException(e);
          }
        });
  }

  @Override
  public void close() throws IOException {
    this.br.close();
    this.isr.close();
    this.is.close();
  }
}


text:
<?xml version="1.0" ?>
<tei>
	<teiHeader>
		<fileDesc xml:id="55011166"/>
	</teiHeader>
	<text xml:lang="en">
		<front>
<lb/>
	<docTitle>
	<titlePart>Macsolvers' Blog<lb/></titlePart>
	</docTitle>

	<note type="other">An online tech resource for Mac users<lb/> Contact Us<lb/> FAQs<lb/> Posted by: admin |</note>

	<date>January 5, 2008<lb/></date>

	<docTitle>
	<titlePart>Attaching iPhone to a Mac doesn't auto-launch iTunes<lb/></titlePart>
	</docTitle>

		</front>
	</text>
</tei>


text:
/****** Object:  Table [dbo].[Operations]    Script Date: 08/22/2013 22:14:59 ******/
SET ANSI_NULLS ON

SET QUOTED_IDENTIFIER ON

CREATE TABLE [dbo].[Operations](
	[OperationId] [int] NOT NULL,
	[Name] [nvarchar](25) NULL,
 CONSTRAINT [PK_Operations] PRIMARY KEY CLUSTERED
(
	[OperationId] ASC
)WITH (PAD_INDEX  = OFF, STATISTICS_NORECOMPUTE  = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS  = ON, ALLOW_PAGE_LOCKS  = ON) ON [PRIMARY]
) ON [PRIMARY]


text:
var laserConfig = require("../LaserApiConfig").default;
var MainCanvas = require("../MasterCanvas").default;

var GPU = require("gpu.js").GPU;
var lastResolution = -1;

const gpu = new GPU();

var kernel;
var gridBuffer
var lastGridResolution

const handler = function (laserGrid) {

  const ctx = MainCanvas.get2dContext();
  // console.log("render debug", laserConfig);
  if (!kernel) {
    kernel = gpu
      .createKernel(function (gameRect, gridResolution, outWidth, outHeight) {
        var xpos = Math.floor((this.thread.x / outWidth) * gridResolution);
        var ypos = Math.floor(
          ((outHeight - this.thread.y) / outHeight) * gridResolution
        );
        var value = gameRect[xpos + ypos * gridResolution];

        this.color(value, value, value, value);
      })
      .setOutput([
        laserConfig.canvasResolution.width,
        laserConfig.canvasResolution.height,
      ])
      .setGraphical(true);
  }
  kernel(
    laserGrid,
    laserConfig.gridResolution,
    laserConfig.canvasResolution.width,
    laserConfig.canvasResolution.height
  );
  ctx.drawImage(kernel.canvas, 0, 0);
};

export default {
  name: "Debug Grid",
  init:()=>{},
  handle: function (grid) {
    handler(grid);
  },
};


text:
<?xml version="1.0" encoding="UTF-8"?><!--
  ~ Copyright (c) 2001-2009, TIBCO Software Inc.
  ~ Use, modification, and distribution subject to terms of license.
  --><serialization xmlns="urn:tibco.com/v3.0">
 <name><![CDATA[Column - Stacked 100%]]></name>
 <icon><![CDATA[icons/stacked100Column.gif]]></icon>
 <description><![CDATA[a sample column chart of type 'Stacked 100%']]></description>
 <onBeforeDeserialize/>
 <onAfterDeserialize/>
  <object type="jsx3.chart.ColumnChart">
   <dynamics/>
   <variants alpha="1" borderAlpha="1" borderWidth="1" categoryCoverage="1" jsxheight="300" jsxleft="0" jsxrelativeposition="1" jsxtop="0" jsxwidth="400" loadState="1"/>
   <strings borderColor="#999999" dataPadding="14 10 6 6" jsxbgcolor="#FFFFFF" jsxname="stacked100ColumnChart" jsxxml="<data jsxid="jsxroot"><record cat="CA" s1="20" s2="15"/> <record cat="OR" s1="30" s2="35"/> <record cat="WA" s1="10" s2="30"/> <record cat="NV" s1="4" s2="3"/> <record cat="AZ" s1="65" s2="15"/> <record cat="NM" s1="55" s2="20"/> <record cat="UT" s1="15" s2="25"/> </data>" legendPlacement="right" titlePlacement="top" type="stacked100"/>
    <object type="jsx3.chart.ChartLabel">
     <dynamics/>
     <variants jsxfontsize="14" labelRotation="0"/>
     <strings jsxbgcolor="#666666" jsxcolor="#FFFFFF" jsxfontname="Arial" jsxfontweight="bold" jsxname="title" jsxpadding="4 0 0 0" jsxtext="Stacked 100% Column Chart" jsxtextalign="center"/>
    </object>
    <object type="jsx3.chart.CategoryAxis">
     <dynamics/>
     <variants horizontal="1" labelGap="3" minorTickDivisions="4" minorTickLength="3" numCategories="7" numSeries="2" primary="1" showAxis="1" showLabels="1" tickLength="3"/>
     <strings axisStroke="#000000 1 1" categoryField="cat" jsxname="xAxis" labelPlacement="low" labelStyle="font-size: 8px; font-family: Verdana;" minorTickPlacement="none" minorTickStroke="#000000 1 1" tickAlignment="between" tickPlacement="outside" tickStroke="#000000 1 1"/>
      <object type="jsx3.chart.ChartLabel">
       <dynamics/>
       <variants jsxfontsize="12" labelRotation="0"/>
       <strings jsxfontname="Arial" jsxfontweight="bold" jsxname="xLabel" jsxtext="State" jsxtextalign="center"/>
      </object>
    </object>
    <object type="jsx3.chart.LinearAxis">
     <dynamics/>
     <variants autoAdjust="1" baseAtZero="1" displayWidth="25" horizontal="0" labelGap="3" max="105" minorTickDivisions="4" minorTickLength="2" primary="1" showAxis="1" showLabels="1" tickLength="3"/>
     <strings axisStroke="#000000 1 1" jsxname="yAxis" labelFunction="jsx3.chart.Axis.percent" labelPlacement="axis" labelStyle="font-size: 8px; font-family: Verdana; text-align: right;" minorTickPlacement="outside" minorTickStroke="#666666 1" tickAlignment="aligned" tickPlacement="cross" tickStroke="#000000 1 1"/>
      <object type="jsx3.chart.ChartLabel">
       <dynamics/>
       <variants jsxfontsize="12" labelRotation="270"/>
       <strings jsxfontname="Arial" jsxfontweight="bold" jsxname="yTitle" jsxtext="Property Damage" jsxtextalign="center"/>
      </object>
    </object>
    <object type="jsx3.chart.GridLines">
     <dynamics/>
     <variants horizontalAbove="1" inForeground="0" strokeMajorH="['#CCCCCC']" useXPrimary="1" useYPrimary="1"/>
     <strings jsxname="bgGrid"/>
    </object>
    <object type="jsx3.chart.ColumnSeries">
     <dynamics/>
     <variants index="0" usePrimaryX="1" usePrimaryY="1"/>
     <strings fill="#FFFF00" fillGradient="#FF0000" jsxname="series1" seriesName="Fires" stroke="#FF9900" tooltipFunction="jsx3.chart.ColumnSeries.tooltip" yField="s1"/>
    </object>
    <object type="jsx3.chart.ColumnSeries">
     <dynamics/>
     <variants index="1" usePrimaryX="1" usePrimaryY="1"/>
     <strings fill="#6699FF" fillGradient="#FFFFFF" jsxname="series2" seriesName="Storms" stroke="#6699FF" tooltipFunction="jsx3.chart.ColumnSeries.tooltip" yField="s2"/>
    </object>
    <object type="jsx3.chart.Legend">
     <dynamics/>
     <variants boxHeight="10" boxSpace="6" lineHeight="22" preferredWidth="85" titleSpace="8"/>
     <strings backgroundStroke="#BBBBBB" jsxmargin="10 10 10 4" jsxname="legend" jsxpadding="4 4 0 4" labelStyle="font-size: 10px; font-weight: bold;"/>
      <object type="jsx3.chart.ChartLabel">
       <dynamics/>
       <variants jsxfontsize="12" labelRotation="0"/>
       <strings jsxfontname="Arial" jsxfontweight="bold" jsxname="legendTitle" jsxtext="Legend" jsxtextalign="center"/>
      </object>
    </object>
  </object>
</serialization>


text:
package com.javaclinic.hsqldbrunner.run;

import org.hsqldb.cmdline.SqlTool;
import org.hsqldb.cmdline.SqlTool.SqlToolException;

import com.javaclinic.hsqldbrunner.settings.Configuration;

/**
 * Re-initializes the HyperSQL database instance. Drops and re-creates all tables as
 * defined in src/main/resources/database/schema.sql file.
 *
 * @author neven
 *
 */
public class ReInitializeDatabaseTables {

    public static void main(String[] args) throws SqlToolException {

        System.out.println("Run SQL script file: " + Configuration.getProperty("database.schema"));

        SqlTool.objectMain(
            new String[] {
                "--inlineRc=url=" + Configuration.getProperty("database.url") + ",user=" + Configuration.getProperty("database.username"),
                "--driver=" + Configuration.getProperty("database.driver"),
                "--noAutofile",
                "--autoCommit",
                Configuration.getProperty("database.schema")
            }
        );
        System.out.println("Done.");

    }

}


text:
<menu xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    tools:context=".TabActivity" >

    <!-- Profile menu item -->
    <item android:id="@+id/action_profile"
        android:title="@+string/action_profile"
        android:orderInCategory="99"
        app:showAsAction="never" />

    <!-- Filter menu item -->
    <item android:id="@+id/action_filter"
        android:title="@+string/action_filter"
        android:orderInCategory="100"
        app:showAsAction="never" />

    <!-- Logout menu item -->
    <item android:id="@+id/action_logout"
        android:title="@+string/action_logout"
        android:orderInCategory="100"
        app:showAsAction="never" />

</menu>


text:
(function() {
  var extend = function(child, parent) { for (var key in parent) { if (hasProp.call(parent, key)) child[key] = parent[key]; } function ctor() { this.constructor = child; } ctor.prototype = parent.prototype; child.prototype = new ctor(); child.__super__ = parent.prototype; return child; },
    hasProp = {}.hasOwnProperty;

  module.exports = function(BasePlugin) {
    var SitemapPlugin, extendr, pathUtil, safefs, sm;
    extendr = require('extendr');
    pathUtil = require('path');
    safefs = require('safefs');
    sm = require('sitemap');
    return SitemapPlugin = (function(superClass) {
      extend(SitemapPlugin, superClass);

      function SitemapPlugin() {
        return SitemapPlugin.__super__.constructor.apply(this, arguments);
      }

      SitemapPlugin.prototype.name = 'sitemap';

      SitemapPlugin.prototype.config = {
        cachetime: 10 * 60 * 1000,
        changefreq: 'weekly',
        priority: 0.5,
        filePath: 'sitemap.xml',
        collectionName: 'html',
        optimize: true,
        sortByURL: false
      };

      SitemapPlugin.prototype.sortByURL = function(a, b) {
        if (a.url < b.url) {
          return -1;
        }
        if (a.url > b.url) {
          return 1;
        }
        return 0;
      };

      SitemapPlugin.prototype.writeAfter = function(opts, next) {
        var docpad, docpadConfig, err, sitemap, sitemapData, sitemapPath, templateData;
        docpad = this.docpad;
        templateData = docpad.getTemplateData();
        docpadConfig = docpad.getConfig();
        sitemapData = extendr.extend({
          hostname: templateData.site.url,
          cachetime: null,
          urls: []
        }, this.getConfig());
        if (!sitemapData.hostname) {
          err = new Error('You must specify templateData.site.url in your docpad configuration file');
          return next(err);
        }
        sitemapPath = pathUtil.resolve(docpadConfig.outPath, sitemapData.filePath);
        docpad.log('debug', 'Creating sitemap in ' + sitemapPath);
        docpad.getCollection(sitemapData.collectionName).sortCollection({
          date: 1
        }).forEach(function(document) {
          var data, ref, ref1;
          if ((document.get('sitemap') !== false) && (document.get('write') !== false) && (document.get('ignored') !== true)) {
            data = {
              url: document.get('url'),
              changefreq: (ref = document.get('changefreq')) != null ? ref : sitemapData.changefreq,
              priority: (ref1 = document.get('priority')) != null ? ref1 : sitemapData.priority,
              lastmodISO: document.get('mtime').toISOString().slice(0, 10)
            };
            if (sitemapData.optimize) {
              data.url = data.url.replace(/\/index\.html$/i, '/');
            }
            docpad.log("debug", data);
            return sitemapData.urls.push(data);
          }
        });
        if (sitemapData.sortByURL) {
          sitemapData.urls.sort(this.sortByURL);
        }
        sitemap = sm.createSitemap(sitemapData);
        safefs.writeFile(sitemapPath, sitemap.toString(), function(err) {
          if (err) {
            return typeof next === "function" ? next(err) : void 0;
          }
          docpad.log('debug', "Wrote the " + sitemapData.filePath + " file to: " + sitemapPath);
          return next();
        });
        return this;
      };

      return SitemapPlugin;

    })(BasePlugin);
  };

}).call(this);


text:
@interface DVTDiffCharacterDataSource : DVTDiffDataSource
{
}

+ (void)initialize;
- (long long)numberOfDiffTokensInDiffDescriptor:(id)arg1;
- (struct _DVTDiffToken)diffTokenInDiffDescriptor:(id)arg1 atIndex:(long long)arg2;

@end


text:
{% extends path+"/_layout-case-simple-baseline-f2f.html" %}

{% block actioncolumn %}

Current case statusBooked appointment

{% endblock %}

{% block citizen_detail %}
Bobby Henderson
{% endblock %}

{% block citizen_content %}

Back

        <form class="form" method="post" action="/{{path}}/scenario3/appointment-tab">

Add a note

                                            Add a note
                                            <textarea name="reason" class="form-control " style="height: 150px; width:100%; max-width:650px;">{{reason}}</textarea>

                                                <fieldset class="inline">

                                                  <legend>

                                                      Is this update because of inbound contact?

                                                  </legend>

                                                    <input id="radio-inline-1" type="radio" name="contact" value="yes">
                                                    Yes

                                                    <input id="radio-inline-2" type="radio" name="contact" value="no">
                                                    No

                                                </fieldset>

								</fieldset>

<button class="button">Save and continue</button>

				</form>

{% endblock %}

{# {% block page_script %}

{% endblock %} #}


text:
package com.intellij.openapi.diagnostic;

import com.intellij.openapi.Disposable;
import com.intellij.openapi.util.Disposer;
import com.intellij.util.ExceptionUtil;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;

import java.util.LinkedHashMap;
import java.util.Map;
import java.util.concurrent.atomic.AtomicInteger;

/**
 * @author peter
 */
public class FrequentEventDetector {
  private static final Logger LOG = Logger.getInstance("#com.intellij.openapi.diagnostic.FrequentEventDetector");

  public enum Level {INFO, WARN, ERROR}

  private long myStartedCounting = System.currentTimeMillis();
  private final AtomicInteger myEventsPosted = new AtomicInteger();
  private final AtomicInteger myLastTraceId = new AtomicInteger();
  private final Map<String, Integer> myRecentTraces = new LinkedHashMap<String, Integer>() {
    @Override
    protected boolean removeEldestEntry(Map.Entry<String, Integer> eldest) {
      return size() > 50;
    }
  };
  private final int myEventCountThreshold;
  private final int myTimeSpanMs;
  private final Level myLevel;
  private static boolean enabled = true;

  public FrequentEventDetector(int eventCountThreshold, int timeSpanMs) {
    this(eventCountThreshold, timeSpanMs, Level.INFO);
  }

  public FrequentEventDetector(int eventCountThreshold, int timeSpanMs, @NotNull Level level) {
    myEventCountThreshold = eventCountThreshold;
    myTimeSpanMs = timeSpanMs;
    myLevel = level;
  }

  /**
   * @return an error message to be logged, if the current event is a part of a "frequent"-series, null otherwise
   */
  @Nullable
  public String getMessageOnEvent(@NotNull Object event) {
    if (!enabled) return null;
    if (myEventsPosted.incrementAndGet() > myEventCountThreshold) {
      boolean shouldLog = false;

      synchronized (myEventsPosted) {
        if (myEventsPosted.get() > myEventCountThreshold) {
          long timeNow = System.currentTimeMillis();
          shouldLog = timeNow - myStartedCounting < myTimeSpanMs;
          myEventsPosted.set(0);
          myStartedCounting = timeNow;
        }
      }

      if (shouldLog) {
        String trace = ExceptionUtil.getThrowableText(new Throwable());
        boolean logTrace;
        int traceId;
        synchronized (myEventsPosted) {
          Integer existingTraceId = myRecentTraces.get(trace);
          logTrace = existingTraceId == null;
          if (logTrace) {
            myRecentTraces.put(trace, traceId = myLastTraceId.incrementAndGet());
          }
          else {
            traceId = existingTraceId;
          }
        }

        return "Too many events posted, #" + traceId + ". Event: " + event + (logTrace ? "\n" + trace : "");
      }
    }
    return null;
  }

  public void logMessage(@NotNull String message) {
    if (myLevel == Level.INFO) {
      LOG.info(message);
    }
    else if (myLevel == Level.WARN) {
      LOG.warn(message);
    }
    else {
      LOG.error(message);
    }
  }

  /**
   * Logs a message if the given event is part of a "frequent" series. To just return the message without logging, use {@link #getMessageOnEvent(Object)}
   */
  public void eventHappened(@NotNull Object event) {
    String message = getMessageOnEvent(event);
    if (message != null) {
      logMessage(message);
    }
  }

  public static void disableUntil(@NotNull Disposable reenable) {
    enabled = false;
    Disposer.register(reenable, new Disposable() {
      @Override
      public void dispose() {
        enabled = true;
      }
    });
  }
}


text:
<!DOCTYPE html>

  <meta charset="utf-8">
  <meta http-equiv="X-UA-Compatible" content="IE=edge">
  <meta name="viewport" content="width=device-width, initial-scale=1">
  <meta name="description" content="Sitio personal de Luis Guillermo Gallo Hernández.">
  <meta name="author" content="Luis Guillermo Gallo Hernández">
  <meta name="keywords" content="gallo, hernández, luis, guillermo, ggallohernandez, personal, sitio, cv, curriculum">
  <link rel="canonical" href="/admin-messages/2015/06/27/seccion_en_construccion.html">

  <title>ggallohernandez  | Seccion en construccion</title>

  <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.5/css/bootstrap.min.css">

  <link href="/css/grayscale.css" rel="stylesheet">
  <link href="/css/timeline.css" rel="stylesheet">

  <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/font-awesome/4.4.0/css/font-awesome.min.css">
  <link href="//fonts.googleapis.com/css?family=Lora:400,700,400italic,700italic" rel="stylesheet" type="text/css">
  <link href="//fonts.googleapis.com/css?family=Montserrat:400,700" rel="stylesheet" type="text/css">

    <link rel="shortcut icon" type="image/x-icon" href="/img/favicon.ico">

            <button type="button" class="navbar-toggle" data-toggle="collapse" data-target=".navbar-main-collapse">

            </button>

  ggallohernandez

                         Acerca de mi

                         Experiencia

                         Estudios

                         Servicios

                         Contacto

Seccion en construccion

27 Jun 2015
             . admin-messages . Comments

              #admin-messages

Esta seccion esta construccion por el momento!

  Please enable JavaScript to view the comments powered by Disqus.

Copyright © Luis Guillermo Gallo Hernández 2015


text:
package org.apache.asterix.translator;

import java.util.Arrays;
import java.util.HashSet;
import java.util.Map;
import java.util.Map.Entry;
import java.util.Set;
import java.util.concurrent.TimeUnit;

import org.apache.asterix.common.api.IClusterManagementWork.ClusterState;
import org.apache.asterix.common.cluster.ClusterPartition;
import org.apache.asterix.common.cluster.IClusterStateManager;
import org.apache.asterix.common.cluster.IGlobalRecoveryManager;
import org.apache.asterix.common.dataflow.ICcApplicationContext;
import org.apache.asterix.common.exceptions.AsterixException;
import org.apache.asterix.common.exceptions.CompilationException;
import org.apache.asterix.common.exceptions.ErrorCode;
import org.apache.asterix.common.functions.FunctionConstants;
import org.apache.asterix.common.metadata.DataverseName;
import org.apache.asterix.lang.common.base.Statement;
import org.apache.asterix.lang.common.statement.CreateDataverseStatement;
import org.apache.asterix.lang.common.statement.DatasetDecl;
import org.apache.asterix.lang.common.statement.DataverseDropStatement;
import org.apache.asterix.lang.common.statement.DeleteStatement;
import org.apache.asterix.lang.common.statement.DropDatasetStatement;
import org.apache.asterix.lang.common.statement.InsertStatement;
import org.apache.asterix.metadata.dataset.hints.DatasetHints;
import org.apache.asterix.metadata.entities.Dataverse;
import org.apache.asterix.metadata.utils.MetadataConstants;
import org.apache.hyracks.algebricks.common.exceptions.AlgebricksException;
import org.apache.hyracks.algebricks.common.utils.Pair;
import org.apache.hyracks.api.exceptions.HyracksDataException;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;

/**
 * Base class for language translators. Contains the common validation logic for language
 * statements.
 */
public abstract class AbstractLangTranslator {

    private static final Logger LOGGER = LogManager.getLogger();

    public void validateOperation(ICcApplicationContext appCtx, Dataverse defaultDataverse, Statement stmt)
            throws AlgebricksException {

        final IClusterStateManager clusterStateManager = appCtx.getClusterStateManager();
        final IGlobalRecoveryManager globalRecoveryManager = appCtx.getGlobalRecoveryManager();
        if (!(clusterStateManager.getState().equals(ClusterState.ACTIVE)
                && globalRecoveryManager.isRecoveryCompleted())) {
            int maxWaitCycles = appCtx.getExternalProperties().getMaxWaitClusterActive();
            try {
                clusterStateManager.waitForState(ClusterState.ACTIVE, maxWaitCycles, TimeUnit.SECONDS);
            } catch (HyracksDataException e) {
                throw new AsterixException(e);
            } catch (InterruptedException e) {
                if (LOGGER.isWarnEnabled()) {
                    LOGGER.warn("Thread interrupted while waiting for cluster to be " + ClusterState.ACTIVE);
                }
                Thread.currentThread().interrupt();
            }
            synchronized (clusterStateManager) {
                if (!clusterStateManager.getState().equals(ClusterState.ACTIVE)) {
                    ClusterPartition[] configuredPartitions = clusterStateManager.getClusterPartitons();
                    Set<String> inactiveNodes = new HashSet<>();
                    for (ClusterPartition cp : configuredPartitions) {
                        if (!cp.isActive()) {
                            inactiveNodes.add(cp.getNodeId());
                        }
                    }
                    throw AsterixException.create(ErrorCode.CLUSTER_STATE_UNUSABLE,
                            Arrays.toString(inactiveNodes.toArray()));
                } else {
                    if (LOGGER.isInfoEnabled()) {
                        LOGGER.info("Cluster is now " + ClusterState.ACTIVE);
                    }
                }
            }
        }

        if (!globalRecoveryManager.isRecoveryCompleted()) {
            int maxWaitCycles = appCtx.getExternalProperties().getMaxWaitClusterActive();
            int waitCycleCount = 0;
            try {
                while (!globalRecoveryManager.isRecoveryCompleted() && waitCycleCount < maxWaitCycles) {
                    Thread.sleep(1000);
                    waitCycleCount++;
                }
            } catch (InterruptedException e) {
                if (LOGGER.isWarnEnabled()) {
                    LOGGER.warn("Thread interrupted while waiting for cluster to complete global recovery ");
                }
                Thread.currentThread().interrupt();
            }
            if (!globalRecoveryManager.isRecoveryCompleted()) {
                throw new AsterixException("Cluster Global recovery is not yet complete and the system is in "
                        + ClusterState.ACTIVE + " state");
            }
        }

        boolean invalidOperation = false;
        String message = null;
        DataverseName dataverseName = defaultDataverse != null ? defaultDataverse.getDataverseName() : null;
        switch (stmt.getKind()) {
            case INSERT:
                InsertStatement insertStmt = (InsertStatement) stmt;
                if (insertStmt.getDataverseName() != null) {
                    dataverseName = insertStmt.getDataverseName();
                }
                invalidOperation = MetadataConstants.METADATA_DATAVERSE_NAME.equals(dataverseName);
                if (invalidOperation) {
                    message = "Insert operation is not permitted in dataverse "
                            + MetadataConstants.METADATA_DATAVERSE_NAME;
                }
                break;

            case DELETE:
                DeleteStatement deleteStmt = (DeleteStatement) stmt;
                if (deleteStmt.getDataverseName() != null) {
                    dataverseName = deleteStmt.getDataverseName();
                }
                invalidOperation = MetadataConstants.METADATA_DATAVERSE_NAME.equals(dataverseName);
                if (invalidOperation) {
                    message = "Delete operation is not permitted in dataverse "
                            + MetadataConstants.METADATA_DATAVERSE_NAME;
                }
                break;

            case CREATE_DATAVERSE:
                CreateDataverseStatement dvCreateStmt = (CreateDataverseStatement) stmt;
                dataverseName = dvCreateStmt.getDataverseName();
                invalidOperation = FunctionConstants.ASTERIX_DV.equals(dataverseName)
                        || FunctionConstants.ALGEBRICKS_DV.equals(dataverseName);
                if (invalidOperation) {
                    message = "Cannot create dataverse: " + dataverseName;
                }
                break;

            case DATAVERSE_DROP:
                DataverseDropStatement dvDropStmt = (DataverseDropStatement) stmt;
                dataverseName = dvDropStmt.getDataverseName();
                invalidOperation = MetadataConstants.METADATA_DATAVERSE_NAME.equals(dataverseName);
                if (invalidOperation) {
                    message = "Cannot drop dataverse: " + dataverseName;
                }
                break;

            case DATASET_DROP:
                DropDatasetStatement dropStmt = (DropDatasetStatement) stmt;
                if (dropStmt.getDataverseName() != null) {
                    dataverseName = dropStmt.getDataverseName();
                }
                invalidOperation = MetadataConstants.METADATA_DATAVERSE_NAME.equals(dataverseName);
                if (invalidOperation) {
                    message = "Cannot drop a dataset belonging to the dataverse: "
                            + MetadataConstants.METADATA_DATAVERSE_NAME;
                }
                break;

            case DATASET_DECL:
                DatasetDecl datasetStmt = (DatasetDecl) stmt;
                Map<String, String> hints = datasetStmt.getHints();
                if (hints != null && !hints.isEmpty()) {
                    StringBuilder errorMsgBuffer = new StringBuilder();
                    for (Entry<String, String> hint : hints.entrySet()) {
                        Pair<Boolean, String> validationResult =
                                DatasetHints.validate(appCtx, hint.getKey(), hint.getValue());
                        if (!validationResult.first) {
                            errorMsgBuffer.append("Dataset: ").append(datasetStmt.getName().getValue())
                                    .append(" error in processing hint: ").append(hint.getKey()).append(" ")
                                    .append(validationResult.second);
                            errorMsgBuffer.append(" \n");
                        }
                    }
                    invalidOperation = errorMsgBuffer.length() > 0;
                    if (invalidOperation) {
                        message = errorMsgBuffer.toString();
                    }
                }
                break;
        }

        if (invalidOperation) {
            throw new CompilationException(ErrorCode.COMPILATION_ERROR, stmt.getSourceLocation(),
                    "Invalid operation - " + message);
        }
    }
}


text:
/* $Id$ */

/* This file gets included in plugbase.h when it is integrated into the rest
 * of the program.  Sometime in The Future, I'll whip up a bad ass Perl script
 * to handle automatically loading all the required info into the plugbase.*
 * files.
 */

#ifndef __SPO_CSV_H__
#define __SPO_CSV_H__

void AlertCSVSetup(void);

#endif  /* __SPO_CSV_H__ */


text:
package com.infinityraider.infinitylib.entity;

import com.infinityraider.infinitylib.render.entity.RenderEntityEmpty;
import net.minecraft.client.renderer.entity.EntityRendererProvider;
import net.minecraft.world.entity.Entity;
import net.minecraftforge.api.distmarker.Dist;
import net.minecraftforge.api.distmarker.OnlyIn;

import java.util.function.Supplier;

public class EmptyEntityRenderSupplier<T extends Entity> implements IEntityRenderSupplier<T> {
    private static final EmptyEntityRenderSupplier<?> INSTANCE = new EmptyEntityRenderSupplier<>();

    @SuppressWarnings("unchecked")
    public static <T extends Entity> IEntityRenderSupplier<T> getInstance() {
        return (EmptyEntityRenderSupplier<T>) INSTANCE;
    }

    private EmptyEntityRenderSupplier() {}

    @Override
    @OnlyIn(Dist.CLIENT)
    public Supplier<EntityRendererProvider<T>> supplyRenderer() {
        return () -> RenderEntityEmpty::new;
    }
}


text:
package cmd

import (
	"flag"
	"fmt"
	"os"
	"path/filepath"

	"github.com/google/zoekt"
	"github.com/google/zoekt/build"
)

var (
	version = flag.Bool("version", false, "Print version number")
	opts    = &build.Options{}
)

func init() {
	opts.Flags(flag.CommandLine)
}

func OptionsFromFlags() *build.Options {
	if *version {
		name := filepath.Base(os.Args[0])
		fmt.Printf("%s version %q\n", name, zoekt.Version)
		os.Exit(0)
	}

	opts.SetDefaults()
	return opts
}


text:
package tachyon.examples;

import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.io.IOException;
import java.util.concurrent.Callable;

import tachyon.TachyonURI;
import tachyon.Version;
import tachyon.client.ReadType;
import tachyon.client.TachyonFile;
import tachyon.client.TachyonFS;
import tachyon.client.WriteType;

/**
 * Basic example of using the TachyonFS and TachyonFile for writing to and reading from files.
 *

 * This class is different from {@link tachyon.examples.BasicOperations} in the way writes happen.
 * Over there {@link java.nio.ByteBuffer} is used directly, where as here byte data is done via
 * input/output streams.
 *

 * This example also let users play around with how to work with files a bit more. The
 * {@link tachyon.client.ReadType} is something that can be set, as well as ability to delete file
 * if exists.
 */
public final class BasicNonByteBufferOperations implements Callable<Boolean> {
  private final TachyonURI mMasterLocation;
  private final TachyonURI mFilePath;
  private final WriteType mWriteType;
  private final ReadType mReadType;
  private final boolean mDeleteIfExists;
  private final int mLength;

  public BasicNonByteBufferOperations(TachyonURI masterLocation, TachyonURI filePath,
      WriteType writeType, ReadType readType, boolean deleteIfExists, int length) {
    mMasterLocation = masterLocation;
    mFilePath = filePath;
    mWriteType = writeType;
    mReadType = readType;
    mDeleteIfExists = deleteIfExists;
    mLength = length;
  }

  @Override
  public Boolean call() throws Exception {
    TachyonFS client = TachyonFS.get(mMasterLocation);

    write(client, mFilePath, mWriteType, mDeleteIfExists, mLength);
    return read(client, mFilePath, mReadType);
  }

  private void write(TachyonFS client, TachyonURI filePath, WriteType writeType,
      boolean deleteIfExists, int length) throws IOException {
    // If the file exists already, we will override it.
    TachyonFile file = getOrCreate(client, filePath, deleteIfExists);
    DataOutputStream os = new DataOutputStream(file.getOutStream(writeType));
    try {
      os.writeInt(length);
      for (int i = 0; i < length; i ++) {
        os.writeInt(i);
      }
    } finally {
      os.close();
    }
  }

  private TachyonFile getOrCreate(TachyonFS client, TachyonURI filePath, boolean deleteIfExists)
      throws IOException {
    TachyonFile file = client.getFile(filePath);
    if (file == null) {
      // file doesn't exist yet, so create it
      int fileId = client.createFile(filePath);
      file = client.getFile(fileId);
    } else if (deleteIfExists) {
      // file exists, so delete it and recreate
      client.delete(new TachyonURI(file.getPath()), false);

      int fileId = client.createFile(filePath);
      file = client.getFile(fileId);
    }
    return file;
  }

  private boolean read(TachyonFS client, TachyonURI filePath, ReadType readType)
      throws IOException {
    TachyonFile file = client.getFile(filePath);
    DataInputStream input = new DataInputStream(file.getInStream(readType));
    boolean passes = true;
    try {
      int length = input.readInt();
      for (int i = 0; i < length; i ++) {
        passes &= (input.readInt() == i);
      }
    } finally {
      input.close();
    }
    return passes;
  }

  public static void main(final String[] args) throws IOException {
    if (args.length < 2 || args.length > 6) {
      usage();
    }

    Utils.runExample(new BasicNonByteBufferOperations(new TachyonURI(args[0]), new TachyonURI(
        args[1]), Utils.option(args, 2, WriteType.MUST_CACHE), Utils.option(args, 3,
        ReadType.NO_CACHE), Utils.option(args, 4, true), Utils.option(args, 5, 20)));
  }

  private static void usage() {
    System.out.println("java -cp target/tachyon-" + Version.VERSION + "-jar-with-dependencies.jar "
        + BasicNonByteBufferOperations.class.getName()
        + " <master address> <file path> [write type] [read type] [delete file] [num writes]");
    System.exit(-1);
  }
}


text:
package com.github.cirorizzo.whitsquare.presenter;

import android.content.Context;

import com.github.cirorizzo.whitsquare.view.MainViewInterface;

public interface WhitSquarePresenter {
    void connect(MainViewInterface mainViewInterface);
    void getExplore(final Context context, String place);
}


text:
/**
 * @file Unit tests for src/keywords/descending.js.
 */

'use strict';

// Require Node modules and perform setup.
const chai = require('chai');
chai.should();

// Require internal modules.
const descending = require('../../../src/keywords/descending.js');

// Define local constants.
const table = {
  name: 'tableName',
  ns: '',
  columns: {
    col1: 'col1',
    col2: 'col2',
    col3: 'col3'
  }
};
const query = '';

// Describe tests.
describe('descending', function() {
  var descendingObj;

  beforeEach(function() {
    descendingObj = descending(table, query);
  });

  describe('#toString', function() {
    it('should return a string', function() {
      descendingObj.toString().should.be.a.string;
    });

    it('should add DESC keyword', function() {
      descendingObj.toString().should.equal(' DESC');
    });
  });
});