text:
<?xml version="1.0"?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
    "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<meta charset="utf-8">
<meta http-equiv="cache-control" content="no-cache" />
<meta http-equiv="Pragma" content="no-cache" />
<meta http-equiv="Expires" content="-1" />

<title>jdk Sdiff test/java/time/tck/java/time </title>

&lt prev index next &gt

test/java/time/tck/java/time/TCKLocalDate.java

Print this page

 102 import java.time.ZoneOffset;
 103 import java.time.ZonedDateTime;
 104 import java.time.chrono.IsoChronology;
 105 import java.time.chrono.IsoEra;
 106 import java.time.format.DateTimeFormatter;
 107 import java.time.format.DateTimeParseException;
 108 import java.time.temporal.ChronoField;
 109 import java.time.temporal.ChronoUnit;
 110 import java.time.temporal.JulianFields;
 111 import java.time.temporal.Temporal;
 112 import java.time.temporal.TemporalAccessor;
 113 import java.time.temporal.TemporalAdjuster;
 114 import java.time.temporal.TemporalField;
 115 import java.time.temporal.TemporalQueries;
 116 import java.time.temporal.TemporalQuery;
 117 import java.time.temporal.TemporalUnit;
 118 import java.time.temporal.UnsupportedTemporalTypeException;
 119 import java.util.ArrayList;
 120 import java.util.Arrays;
 121 import java.util.List;

 122
 123 import org.testng.annotations.BeforeMethod;
 124 import org.testng.annotations.DataProvider;
 125 import org.testng.annotations.Test;
 126 import test.java.time.MockSimplePeriod;
 127 import test.java.time.temporal.MockFieldNoValue;
 128
 129 /**
 130  * Test LocalDate.
 131  */
 132 @Test
 133 public class TCKLocalDate extends AbstractDateTimeTest {
 134
 135     private static final ZoneOffset OFFSET_PONE = ZoneOffset.ofHours(1);
 136     private static final ZoneOffset OFFSET_PTWO = ZoneOffset.ofHours(2);
 137     private static final ZoneOffset OFFSET_MTWO = ZoneOffset.ofHours(-2);
 138     private static final ZoneId ZONE_PARIS = ZoneId.of("Europe/Paris");
 139     private static final ZoneId ZONE_GAZA = ZoneId.of("Asia/Gaza");
 140
 141     private LocalDate TEST_2007_07_15;

2343
2344     @Test(dataProvider="sampleToString")
2345     public void test_toString(int y, int m, int d, String expected) {
2346         LocalDate t = LocalDate.of(y, m, d);
2347         String str = t.toString();
2348         assertEquals(str, expected);
2349     }
2350
2351     private LocalDate date(int year, int month, int day) {
2352         return LocalDate.of(year, month, day);
2353     }
2354
2355     //-----------------------------------------------------------------
2356     // getEra()
2357     // ----------------------------------------------------------------
2358     @Test
2359     public void test_getEra() {
2360         IsoEra isoEra = LocalDate.MAX.getEra();
2361         assertSame(isoEra,IsoEra.CE);
2362         assertSame(LocalDate.MIN.getEra(),IsoEra.BCE);

2363     }
2364 }

 102 import java.time.ZoneOffset;
 103 import java.time.ZonedDateTime;
 104 import java.time.chrono.IsoChronology;
 105 import java.time.chrono.IsoEra;
 106 import java.time.format.DateTimeFormatter;
 107 import java.time.format.DateTimeParseException;
 108 import java.time.temporal.ChronoField;
 109 import java.time.temporal.ChronoUnit;
 110 import java.time.temporal.JulianFields;
 111 import java.time.temporal.Temporal;
 112 import java.time.temporal.TemporalAccessor;
 113 import java.time.temporal.TemporalAdjuster;
 114 import java.time.temporal.TemporalField;
 115 import java.time.temporal.TemporalQueries;
 116 import java.time.temporal.TemporalQuery;
 117 import java.time.temporal.TemporalUnit;
 118 import java.time.temporal.UnsupportedTemporalTypeException;
 119 import java.util.ArrayList;
 120 import java.util.Arrays;
 121 import java.util.List;
 122 import java.util.stream.Collectors;
 123
 124 import org.testng.annotations.BeforeMethod;
 125 import org.testng.annotations.DataProvider;
 126 import org.testng.annotations.Test;
 127 import test.java.time.MockSimplePeriod;
 128 import test.java.time.temporal.MockFieldNoValue;
 129
 130 /**
 131  * Test LocalDate.
 132  */
 133 @Test
 134 public class TCKLocalDate extends AbstractDateTimeTest {
 135
 136     private static final ZoneOffset OFFSET_PONE = ZoneOffset.ofHours(1);
 137     private static final ZoneOffset OFFSET_PTWO = ZoneOffset.ofHours(2);
 138     private static final ZoneOffset OFFSET_MTWO = ZoneOffset.ofHours(-2);
 139     private static final ZoneId ZONE_PARIS = ZoneId.of("Europe/Paris");
 140     private static final ZoneId ZONE_GAZA = ZoneId.of("Asia/Gaza");
 141
 142     private LocalDate TEST_2007_07_15;

2344
2345     @Test(dataProvider="sampleToString")
2346     public void test_toString(int y, int m, int d, String expected) {
2347         LocalDate t = LocalDate.of(y, m, d);
2348         String str = t.toString();
2349         assertEquals(str, expected);
2350     }
2351
2352     private LocalDate date(int year, int month, int day) {
2353         return LocalDate.of(year, month, day);
2354     }
2355
2356     //-----------------------------------------------------------------
2357     // getEra()
2358     // ----------------------------------------------------------------
2359     @Test
2360     public void test_getEra() {
2361         IsoEra isoEra = LocalDate.MAX.getEra();
2362         assertSame(isoEra,IsoEra.CE);
2363         assertSame(LocalDate.MIN.getEra(),IsoEra.BCE);
2364     }
2365
2366     //-----------------------------------------------------------------
2367     // datesUntil()
2368     // ----------------------------------------------------------------
2369     @Test
2370     public void test_datesUntil() {
2371         assertEquals(
2372                 date(2015, 9, 29).datesUntil(date(2015, 10, 3)).collect(
2373                         Collectors.toList()), Arrays.asList(date(2015, 9, 29),
2374                         date(2015, 9, 30), date(2015, 10, 1), date(2015, 10, 2)));
2375         assertEquals(date(2015, 9, 29).datesUntil(date(2015, 10, 3), Period.ofDays(2))
2376                 .collect(Collectors.toList()), Arrays.asList(date(2015, 9, 29),
2377                 date(2015, 10, 1)));
2378         assertEquals(date(2015, 1, 31).datesUntil(date(2015, 6, 1), Period.ofMonths(1))
2379                 .collect(Collectors.toList()), Arrays.asList(date(2015, 1, 31),
2380                 date(2015, 2, 28), date(2015, 3, 31), date(2015, 4, 30),
2381                 date(2015, 5, 31)));
2382     }
2383
2384     @Test(expectedExceptions=NullPointerException.class)
2385     public void test_datesUntil_nullEnd() {
2386         LocalDate date = date(2015, 1, 31);
2387         date.datesUntil(null);
2388     }
2389
2390     @Test(expectedExceptions=NullPointerException.class)
2391     public void test_datesUntil_nullEndStep() {
2392         LocalDate date = date(2015, 1, 31);
2393         date.datesUntil(null, Period.ofDays(1));
2394     }
2395
2396     @Test(expectedExceptions=NullPointerException.class)
2397     public void test_datesUntil_nullStep() {
2398         LocalDate date = date(2015, 1, 31);
2399         date.datesUntil(date, null);
2400     }
2401
2402     @Test(expectedExceptions=IllegalArgumentException.class)
2403     public void test_datesUntil_zeroStep() {
2404         LocalDate date = date(2015, 1, 31);
2405         date.datesUntil(date, Period.ZERO);
2406     }
2407
2408     @Test(expectedExceptions=IllegalArgumentException.class)
2409     public void test_datesUntil_negativeStep() {
2410         LocalDate date = date(2015, 1, 31);
2411         date.datesUntil(date, Period.of(1, 0, -1));
2412     }
2413
2414     @DataProvider(name="datesUntil")
2415     public Object[][] provider_datesUntil() {
2416         return new Object[][] {
2417                 {MIN_DATE, MIN_DATE},
2418                 {MIN_DATE, MAX_DATE},
2419                 {MAX_DATE, MAX_DATE},
2420                 {date(2015,10,1), date(2015,10,2)},
2421                 {date(2015,10,1), date(2015,11,1)},
2422                 {date(2015,10,31), date(2015,11,1)},
2423                 {date(2015,10,1), MAX_DATE},
2424                 {MIN_DATE, date(2015,10,1)}
2425         };
2426     }
2427
2428     @Test(dataProvider = "datesUntil")
2429     public void test_datesUntil_count(LocalDate start, LocalDate end) {
2430         assertEquals(end.datesUntil(start).count(), 0L);
2431         assertEquals(end.datesUntil(start, Period.ofYears(1)).count(), 0L);
2432         assertEquals(end.datesUntil(start, Period.ofMonths(1)).count(), 0L);
2433         assertEquals(end.datesUntil(start, Period.ofDays(1)).count(), 0L);
2434         assertEquals(start.datesUntil(end).count(), start.until(end, ChronoUnit.DAYS));
2435         assertEquals(start.datesUntil(end, Period.ofDays(1)).count(),
2436                 start.until(end, ChronoUnit.DAYS));
2437     }
2438
2439     @DataProvider(name="datesUntilSteps")
2440     public Object[][] provider_datesUntil_steps() {
2441         List<Object[]> data = new ArrayList<>(Arrays.asList(new Object[][] {
2442             {MIN_DATE, MAX_DATE, Period.ofYears(Year.MAX_VALUE)},
2443             {MIN_DATE, MAX_DATE, Period.ofDays(2)},
2444             {MIN_DATE, MAX_DATE, Period.of(1,2,3)},
2445             {MIN_DATE, MAX_DATE, Period.of(1,2,1000000)},
2446             {MIN_DATE, MAX_DATE, Period.of(1,1000000,3)},
2447             {MIN_DATE, MAX_DATE, Period.of(1000000,2,3)},
2448             {MIN_DATE, MAX_DATE.minusYears(1), Period.ofYears(Year.MAX_VALUE)},
2449             {MAX_DATE.minusMonths(1), MAX_DATE, Period.ofMonths(1)},
2450             {date(Year.MAX_VALUE, 2, 20), MAX_DATE, Period.of(0, 1, 1)},
2451             {date(2015,1,1), date(2016,1,1), Period.ofYears(1)},
2452             {date(2015,1,1), date(2016,1,1), Period.ofDays(365)},
2453             {date(2015,1,1), date(2016,1,1), Period.ofDays(366)},
2454             {date(2015,1,1), date(2016,1,1), Period.ofDays(4)},
2455             {date(2015,1,1), date(2016,1,1), Period.of(0,1,2)},
2456             {date(2015,1,1), date(2016,1,1), Period.ofMonths(1)},
2457             {date(2015,1,1), date(2016,1,1), Period.ofMonths(12)},
2458             {date(2015,1,1), date(2016,1,2), Period.ofMonths(12)},
2459             {date(2015,1,1), date(2016,1,1), Period.of(0, 11, 30)},
2460             {date(2015,1,1), date(2015,12,31), Period.of(0, 11, 30)},
2461             {date(2015,1,31), date(2015,12,31), Period.ofMonths(2)},
2462             {date(2015,1,31), date(2015,12,1), Period.ofMonths(2)},
2463             {date(2015,1,31), date(2015,11,30), Period.ofMonths(2)},
2464             {date(2015,1,31), date(2030,11,30), Period.of(1,30,365)},
2465             {date(2015,1,31), date(2043,1,31), Period.of(4,0,0)},
2466             {date(2015,1,31), date(2043,2,1), Period.of(4,0,0)},
2467             {date(2015,1,31), date(2043,1,31), Period.of(3,11,30)},
2468             {date(2015,1,31), date(2043,2,1), Period.of(3,11,30)},
2469             {date(2015,1,31), date(2043,1,31), Period.of(0,0,1460)},
2470             {date(2015,1,31), date(2043,1,31), Period.of(0,0,1461)},
2471             {date(2015,1,31), date(2043,2,1), Period.of(0,0,1461)},
2472             {date(2015,1,31), MAX_DATE, Period.of(10,100,1000)},
2473             {date(2015,1,31), MAX_DATE, Period.of(1000000,10000,100000)},
2474             {date(2015,1,31), MAX_DATE, Period.ofDays(10000000)},
2475             {date(2015,1,31), MAX_DATE, Period.ofDays(Integer.MAX_VALUE)},
2476             {date(2015,1,31), MAX_DATE, Period.ofMonths(Integer.MAX_VALUE)},
2477             {date(2015,1,31), MAX_DATE, Period.ofYears(Integer.MAX_VALUE)}
2478         }));
2479         LocalDate start = date(2014, 1, 15);
2480         LocalDate end = date(2015, 3, 4);
2481         for (int months : new int[] { 0, 1, 2, 6, 12, 13 }) {
2482             for (int days = 0; days < 80; days++) {
2483                 if (months > 0 || days > 0)
2484                     data.add(new Object[] { start, end, Period.of(0, months, days) });
2485             }
2486         }
2487         for (int days = 27; days < 100; days++) {
2488             data.add(new Object[] { start, start.plusDays(days), Period.ofMonths(1) });
2489         }
2490         return data.toArray(new Object[data.size()][]);
2491     }
2492
2493     @Test(dataProvider="datesUntilSteps")
2494     public void test_datesUntil_step(LocalDate start, LocalDate end, Period step) {
2495         // Reverse range: must produce empty stream
2496         assertEquals(end.datesUntil(start, step).count(), 0);
2497         long count = start.datesUntil(end, step).count();
2498         if(start.equals(end)) {
2499             assertTrue(count == 0);
2500         } else {
2501             assertTrue(count > 0);
2502             // the last value must be before the end date
2503             assertTrue(start.plusMonths(step.toTotalMonths()*(count-1))
2504                 .plusDays(step.getDays()*(count-1)).isBefore(end));
2505             try {
2506                 // the next after the last value must be either invalid
2507                 // or not before the end date
2508                 assertFalse(start.plusMonths(step.toTotalMonths()*count)
2509                     .plusDays(step.getDays()*count).isBefore(end));
2510             } catch (ArithmeticException | DateTimeException e) {
2511                 // ignore: possible overflow for the next value is ok
2512             }
2513             if(count < 1000) {
2514                 assertTrue(start.datesUntil(end, step)
2515                     .allMatch(date -> !date.isBefore(start) && date.isBefore(end)));
2516                 List<LocalDate> list = new ArrayList<>();
2517                 for(long i=0; i<count; i++) {
2518                     list.add(start.plusMonths(step.toTotalMonths()*i)
2519                         .plusDays(step.getDays()*i));
2520                 }
2521                 assertEquals(start.datesUntil(end, step)
2522                     .collect(Collectors.toList()), list);
2523             }
2524         }
2525     }
2526 }

&lt prev index next &gt


text:
using System.IO;
using System.Text;
using Microsoft.TemplateEngine.Core.Contracts;
using Microsoft.TemplateEngine.Core.Util;
using Microsoft.TemplateEngine.Mocks;
using Microsoft.TemplateEngine.TestHelper;
using Xunit;

namespace Microsoft.TemplateEngine.Core.UnitTests
{
    public class CommonOperationsTests : TestBase
    {
        [Fact(DisplayName = nameof(VerifyTrimWhitespaceForward))]
        public void VerifyTrimWhitespaceForward()
        {
            MockOperation o = new MockOperation(null,
                (IProcessorState state, int length, ref int position, int token, Stream target) =>
                {
                    state.TrimWhitespace(true, false, ref length, ref position);
                    return 0;
                }, true, Encoding.UTF8.GetBytes("Hello"));

            EngineConfig cfg = new EngineConfig(EnvironmentSettings, new VariableCollection());
            IProcessor processor = Processor.Create(cfg, o.Provider);
            byte[] data = Encoding.UTF8.GetBytes("Hello    \r\n    There");
            Stream d = new MemoryStream(data);
            Stream result = new MemoryStream();
            bool modified = processor.Run(d, result);

            Assert.True(modified);
            result.Position = 0;
            byte[] outcome = new byte[result.Length];
            result.Read(outcome, 0, outcome.Length);
            string outcomeString = Encoding.UTF8.GetString(outcome);
            Assert.Equal("    There", outcomeString);
        }

        [Fact(DisplayName = nameof(VerifyTrimWhitespaceBackward))]
        public void VerifyTrimWhitespaceBackward()
        {
            MockOperation o = new MockOperation(null,
                (IProcessorState state, int length, ref int position, int token, Stream target) =>
                {
                    state.TrimWhitespace(false, true, ref length, ref position);
                    return 0;
                }, true, Encoding.UTF8.GetBytes("There"));

            EngineConfig cfg = new EngineConfig(EnvironmentSettings, new VariableCollection());
            IProcessor processor = Processor.Create(cfg, o.Provider);
            byte[] data = Encoding.UTF8.GetBytes("Hello    \r\n    There");
            Stream d = new MemoryStream(data);
            Stream result = new MemoryStream();
            bool modified = processor.Run(d, result);

            Assert.True(modified);
            result.Position = 0;
            byte[] outcome = new byte[result.Length];
            result.Read(outcome, 0, outcome.Length);
            string outcomeString = Encoding.UTF8.GetString(outcome);
            Assert.Equal("Hello    \r\n", outcomeString);
        }

        [Fact(DisplayName = nameof(VerifyTrimWhitespaceBothDirections))]
        public void VerifyTrimWhitespaceBothDirections()
        {
            MockOperation o = new MockOperation(null,
                (IProcessorState state, int length, ref int position, int token, Stream target) =>
                {
                    state.TrimWhitespace(true, true, ref length, ref position);
                    return 0;
                }, true, Encoding.UTF8.GetBytes("There"));

            EngineConfig cfg = new EngineConfig(EnvironmentSettings, new VariableCollection());
            IProcessor processor = Processor.Create(cfg, o.Provider);
            byte[] data = Encoding.UTF8.GetBytes("Hello    \r\n    There    \r\n    You");
            Stream d = new MemoryStream(data);
            Stream result = new MemoryStream();
            bool modified = processor.Run(d, result);

            Assert.True(modified);
            result.Position = 0;
            byte[] outcome = new byte[result.Length];
            result.Read(outcome, 0, outcome.Length);
            string outcomeString = Encoding.UTF8.GetString(outcome);
            Assert.Equal("Hello    \r\n    You", outcomeString);
        }

        [Fact(DisplayName = nameof(VerifyTrimWhitespaceNeitherDirection))]
        public void VerifyTrimWhitespaceNeitherDirection()
        {
            MockOperation o = new MockOperation(null,
                (IProcessorState state, int length, ref int position, int token, Stream target) =>
                {
                    state.TrimWhitespace(false, false, ref length, ref position);
                    return 0;
                }, true, Encoding.UTF8.GetBytes("There"));

            EngineConfig cfg = new EngineConfig(EnvironmentSettings, new VariableCollection());
            IProcessor processor = Processor.Create(cfg, o.Provider);
            byte[] data = Encoding.UTF8.GetBytes("Hello    \r\n    There    \r\n    You");
            Stream d = new MemoryStream(data);
            Stream result = new MemoryStream();
            bool modified = processor.Run(d, result);

            Assert.True(modified);
            result.Position = 0;
            byte[] outcome = new byte[result.Length];
            result.Read(outcome, 0, outcome.Length);
            string outcomeString = Encoding.UTF8.GetString(outcome);
            Assert.Equal("Hello    \r\n        \r\n    You", outcomeString);
        }

        [Fact(DisplayName = nameof(VerifyConsumeWholeLine))]
        public void VerifyConsumeWholeLine()
        {
            MockOperation o = new MockOperation(null,
                (IProcessorState state, int length, ref int position, int token, Stream target) =>
                {
                    state.ConsumeWholeLine(ref length, ref position);
                    return 0;
                }, true, Encoding.UTF8.GetBytes("There"));

            EngineConfig cfg = new EngineConfig(EnvironmentSettings, new VariableCollection());
            IProcessor processor = Processor.Create(cfg, o.Provider);
            byte[] data = Encoding.UTF8.GetBytes("Hello    \r\n    There    \r\n    You");
            Stream d = new MemoryStream(data);
            Stream result = new MemoryStream();
            bool modified = processor.Run(d, result);

            Assert.True(modified);
            result.Position = 0;
            byte[] outcome = new byte[result.Length];
            result.Read(outcome, 0, outcome.Length);
            string outcomeString = Encoding.UTF8.GetString(outcome);
            Assert.Equal("Hello    \r\n    You", outcomeString);
        }

        [Theory(DisplayName = nameof(VerifyWhitespaceHandlerConsumeWholeLine))]
        [InlineData(false, false, false)]
        [InlineData(false, false, true)]
        [InlineData(false, true, false)]
        [InlineData(false, true, true)]
        [InlineData(true, false, false)]
        [InlineData(true, false, true)]
        [InlineData(true, true, false)]
        [InlineData(true, true, true)]
        public void VerifyWhitespaceHandlerConsumeWholeLine(bool trim, bool trimForward, bool trimBackward)
        {
            MockOperation o = new MockOperation(null,
                (IProcessorState state, int length, ref int position, int token, Stream target) =>
                {
                    state.WhitespaceHandler(ref length, ref position, true, trim, trimForward, trimBackward);
                    return 0;
                }, true, Encoding.UTF8.GetBytes("There"));

            EngineConfig cfg = new EngineConfig(EnvironmentSettings, new VariableCollection());
            IProcessor processor = Processor.Create(cfg, o.Provider);
            byte[] data = Encoding.UTF8.GetBytes("Hello    \r\n    There    \r\n    You");
            Stream d = new MemoryStream(data);
            Stream result = new MemoryStream();
            bool modified = processor.Run(d, result);

            Assert.True(modified);
            result.Position = 0;
            byte[] outcome = new byte[result.Length];
            result.Read(outcome, 0, outcome.Length);
            string outcomeString = Encoding.UTF8.GetString(outcome);
            Assert.Equal("Hello    \r\n    You", outcomeString);
        }

        [Theory(DisplayName = nameof(VerifyWhitespaceHandlerTrim))]
        [InlineData(false, false)]
        [InlineData(false, true)]
        [InlineData(true, false)]
        [InlineData(true, true)]
        public void VerifyWhitespaceHandlerTrim(bool trimForward, bool trimBackward)
        {
            MockOperation o = new MockOperation(null,
                (IProcessorState state, int length, ref int position, int token, Stream target) =>
                {
                    state.WhitespaceHandler(ref length, ref position, false, true, trimForward, trimBackward);
                    return 0;
                }, true, Encoding.UTF8.GetBytes("There"));

            EngineConfig cfg = new EngineConfig(EnvironmentSettings, new VariableCollection());
            IProcessor processor = Processor.Create(cfg, o.Provider);
            byte[] data = Encoding.UTF8.GetBytes("Hello    \r\n    There    \r\n    You");
            Stream d = new MemoryStream(data);
            Stream result = new MemoryStream();
            bool modified = processor.Run(d, result);

            Assert.True(modified);
            result.Position = 0;
            byte[] outcome = new byte[result.Length];
            result.Read(outcome, 0, outcome.Length);
            string outcomeString = Encoding.UTF8.GetString(outcome);
            Assert.Equal("Hello    \r\n    You", outcomeString);
        }

        [Fact(DisplayName = nameof(VerifyWhitespaceHandlerTrimForwardButNotBack))]
        public void VerifyWhitespaceHandlerTrimForwardButNotBack()
        {
            MockOperation o = new MockOperation(null,
                (IProcessorState state, int length, ref int position, int token, Stream target) =>
                {
                    state.WhitespaceHandler(ref length, ref position, false, false, true, false);
                    return 0;
                }, true, Encoding.UTF8.GetBytes("There"));

            EngineConfig cfg = new EngineConfig(EnvironmentSettings, new VariableCollection());
            IProcessor processor = Processor.Create(cfg, o.Provider);
            byte[] data = Encoding.UTF8.GetBytes("Hello    \r\n    There     \r\n    You");
            Stream d = new MemoryStream(data);
            Stream result = new MemoryStream();
            bool modified = processor.Run(d, result);

            Assert.True(modified);
            result.Position = 0;
            byte[] outcome = new byte[result.Length];
            result.Read(outcome, 0, outcome.Length);
            string outcomeString = Encoding.UTF8.GetString(outcome);
            Assert.Equal("Hello    \r\n        You", outcomeString);
        }

        [Fact(DisplayName = nameof(VerifyWhitespaceHandlerTrimBackButNotForward))]
        public void VerifyWhitespaceHandlerTrimBackButNotForward()
        {
            MockOperation o = new MockOperation(null,
                (IProcessorState state, int length, ref int position, int token, Stream target) =>
                {
                    state.WhitespaceHandler(ref length, ref position, false, false, false, true);
                    return 0;
                }, true, Encoding.UTF8.GetBytes("There"));

            EngineConfig cfg = new EngineConfig(EnvironmentSettings, new VariableCollection());
            IProcessor processor = Processor.Create(cfg, o.Provider);
            byte[] data = Encoding.UTF8.GetBytes("Hello    \r\n    There     \r\n    You");
            Stream d = new MemoryStream(data);
            Stream result = new MemoryStream();
            bool modified = processor.Run(d, result);

            Assert.True(modified);
            result.Position = 0;
            byte[] outcome = new byte[result.Length];
            result.Read(outcome, 0, outcome.Length);
            string outcomeString = Encoding.UTF8.GetString(outcome);
            Assert.Equal("Hello    \r\n     \r\n    You", outcomeString);
        }

        [Fact(DisplayName = nameof(VerifyWhitespaceHandlerTrimBackAndForward))]
        public void VerifyWhitespaceHandlerTrimBackAndForward()
        {
            MockOperation o = new MockOperation(null,
                (IProcessorState state, int length, ref int position, int token, Stream target) =>
                {
                    state.WhitespaceHandler(ref length, ref position, false, false, true, true);
                    return 0;
                }, true, Encoding.UTF8.GetBytes("There"));

            EngineConfig cfg = new EngineConfig(EnvironmentSettings, new VariableCollection());
            IProcessor processor = Processor.Create(cfg, o.Provider);
            byte[] data = Encoding.UTF8.GetBytes("Hello    \r\n    There     \r\n    You");
            Stream d = new MemoryStream(data);
            Stream result = new MemoryStream();
            bool modified = processor.Run(d, result);

            Assert.True(modified);
            result.Position = 0;
            byte[] outcome = new byte[result.Length];
            result.Read(outcome, 0, outcome.Length);
            string outcomeString = Encoding.UTF8.GetString(outcome);
            Assert.Equal("Hello    \r\n    You", outcomeString);
        }
    }
}

redpajama_set_name: RedPajamaGithub


text:
import { TestBed, inject } from '@angular/core/testing';

import { ContentService } from './content.service';
import { HttpService } from './http.service';
import { FTHelperService } from '../helper/ftHelper.service';

describe('ContentService', () => {

  let ftHelperService: any;
  let httpService: any;

  beforeEach(() => {

    ftHelperService = jasmine.createSpyObj('FTHelperService', ['version']);
    httpService = jasmine.createSpyObj('HttpService', ['']);

    TestBed.configureTestingModule({
      providers: [ContentService,
        { provide: FTHelperService, useValue: ftHelperService },
        { provide: HttpService, useValue: httpService }]
    });
  });

  it('should be created', inject([ContentService], (service: ContentService) => {
    expect(service).toBeTruthy();
  }));
});


text:
import IdeaBug.Anno;

class IdeaBug {
  @interface Anno { }
}

@Anno
public class IdeaBugUser extends IdeaBug {
}


text:
package org.apache.ctakes.jdl.data.loader;

import static org.hamcrest.CoreMatchers.is;
import static org.junit.Assert.assertThat;

import java.io.File;
import java.io.FileNotFoundException;

import javax.xml.bind.JAXBException;

import org.apache.ctakes.jdl.common.FileUtil;
import org.apache.ctakes.jdl.data.base.JdlConnection;
import org.apache.ctakes.jdl.data.loader.CsvLoader;
import org.apache.ctakes.jdl.data.xml.jaxb.ObjectFactoryUtil;
import org.apache.ctakes.jdl.schema.xdl.CsvLoadType;
import org.apache.ctakes.jdl.test.Resources;
import org.junit.BeforeClass;
import org.junit.Test;

public class CsvLoaderTest {
	private static final String CX = FileUtil.getFile(Resources.CONN_X).toString();
	private static final String D1C = FileUtil.getFile(Resources.DATA1C).toString();
	private static final String D2C = FileUtil.getFile(Resources.DATA2C).toString();
	private static final String L1C = FileUtil.getFile(Resources.LOAD1C).toString();
	private static final String L2C = FileUtil.getFile(Resources.LOAD2C).toString();
	private static final String SQL = "insert into tab_test (id,name,thekey,thevalue,code,descr) values (?,?,?,?,?,?)";

	@BeforeClass
	public static void initClass() throws JAXBException, FileNotFoundException {
		JdlConnection jdlConnection = new JdlConnection(ObjectFactoryUtil.getJdbcTypeBySrcXml(CX));
		jdlConnection.getClass();
	}

	@Test
	public void getSqlInsert() throws JAXBException, FileNotFoundException {
		CsvLoadType loader;
		CsvLoader csvLoader;
		loader = ObjectFactoryUtil.getLoadTypeBySrcXml(L1C).getCsv();
		csvLoader = new CsvLoader(loader, new File(D1C));
		assertThat(csvLoader.getSqlInsert(loader), is(SQL));
		loader = ObjectFactoryUtil.getLoadTypeBySrcXml(L2C).getCsv();
		csvLoader = new CsvLoader(loader, new File(D2C));
		assertThat(csvLoader.getSqlInsert(loader), is(SQL));
	}
}


text:
'''
## License

The MIT License (MIT)

GrovePi for the Raspberry Pi: an open source platform for connecting Grove Sensors to the Raspberry Pi.
Copyright (C) 2015  Dexter Industries

Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.
'''

import time
import grovepi
import datetime
from temboo.Library.Google.Spreadsheets import AddListRows
from temboo.core.session import TembooSession

# Connect the Grove Button to digital port D3
# SIG,NC,VCC,GND
button = 3

lastState = 0

while True:
    try:
        # Get the current timestamp.
        now = datetime.datetime.now()
        timestamp = str(now)

        # Get button state, which should be either 0 (released) or 1 (pressed).
        state = grovepi.digitalRead(button)

        # Ignore state 255, which may be a read conflict with send_sensor_data.py.
        if state == 255:
            continue

        # Show the state for debugging.
        #print ("state=", state)

        # If state has changed, send the state to Google Spreadsheet through Temboo.
        if state != lastState:
            lastState = state
            if state == 0:
                stateText = "Released"
            else:
                stateText = "Pressed"
            print ("Sending stateText=", stateText)

            # Send the state to the Google Spreadsheet through Temboo.
            # Create a session with your Temboo account details
            session = TembooSession("lupyuen", "myFirstApp", "2e0421546ea248d4a5cd2029f2979e23")

            # Instantiate the Choreo
            addListRowsChoreo = AddListRows(session)

            # Get an InputSet object for the Choreo
            addListRowsInputs = addListRowsChoreo.new_input_set()

            # Set credential to use for execution
            addListRowsInputs.set_credential('SensorData')

            # Set the data to be added
            addListRowsInputs.set_RowsetXML("""
            <rowset>
            <row>
            <Timestamp>{0}</Timestamp>
            <Button>{1}</Button>
            </row>
            </rowset>
            """.format(timestamp, stateText))

            # Execute the Choreo
            addListRowsResults = addListRowsChoreo.execute_with_results(addListRowsInputs)

            # Print the Choreo outputs
            print("Response: " + addListRowsResults.get_Response())
            print("NewAccessToken: " + addListRowsResults.get_NewAccessToken())
        else:
            time.sleep(.5)

    except KeyboardInterrupt:
        break
    except IOError:
        print ("Error")


text:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
              xmlns:tools="http://schemas.android.com/tools"
              android:orientation="vertical"
              android:layout_marginBottom="16dp"
              android:layout_width="match_parent"
              android:layout_height="match_parent">

    <TextView
        android:id="@+id/include_word_section_title"
        android:layout_marginBottom="8dp"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        tools:text="This is a title"
        style="@style/TextAppearance.AppCompat.Title" />

    <TextView
        android:id="@+id/include_word_section_content"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        tools:text="This is content"
        style="@style/TextAppearance.AppCompat.Body1" />

</LinearLayout>


text:
using System;
using System.Collections.Generic;
using System.Linq;
using Hyak.Common;
using Microsoft.Azure;
using Microsoft.Azure.Management.Insights.Models;

namespace Microsoft.Azure.Management.Insights.Models
{
    /// <summary>
    /// A standard service response including an HTTP status code and request
    /// ID.
    /// </summary>
    public partial class SkuListResponse : AzureOperationResponse, IEnumerable<SkuDefinition>
    {
        private IList<SkuDefinition> _value;

        /// <summary>
        /// Optional. The values for the sku definition.
        /// </summary>
        public IList<SkuDefinition> Value
        {
            get { return this._value; }
            set { this._value = value; }
        }

        /// <summary>
        /// Initializes a new instance of the SkuListResponse class.
        /// </summary>
        public SkuListResponse()
        {
            this.Value = new LazyList<SkuDefinition>();
        }

        /// <summary>
        /// Gets the sequence of Value.
        /// </summary>
        public IEnumerator<SkuDefinition> GetEnumerator()
        {
            return this.Value.GetEnumerator();
        }

        /// <summary>
        /// Gets the sequence of Value.
        /// </summary>
        System.Collections.IEnumerator System.Collections.IEnumerable.GetEnumerator()
        {
            return this.GetEnumerator();
        }
    }
}


text:
#include "getXmsgTicket.h"
#include "procApiRequest.h"
#include "apiNumber.h"

/**
 * \fn rcGetXmsgTicket( rcComm_t *conn, getXmsgTicketInp_t *getXmsgTicketInp, xmsgTicketInfo_t **outXmsgTicketInfo )
 *
 * \brief Get an XMessage ticket.
 *
 * \user client
 *
 * \ingroup xmessage
 *
 * \since 1.0
 *
 * \author Arcot Rajasekar
 *
 * \remark none
 *
 * \note none
 *
 * \param[in] conn - A rcComm_t connection handle to the server.
 * \param[in] getXmsgTicketInp
 * \param[out] outXmsgTicketInfo
 *
 * \return integer
 * \retval 0 on success.
 * \sideeffect none
 * \pre none
 * \post none
 * \sa none
**/
int
rcGetXmsgTicket( rcComm_t *conn, getXmsgTicketInp_t *getXmsgTicketInp,
                 xmsgTicketInfo_t **outXmsgTicketInfo ) {
    int status;
    status = procApiRequest( conn, GET_XMSG_TICKET_AN, getXmsgTicketInp, NULL,
                             ( void ** ) outXmsgTicketInfo, NULL );

    return status;
}


text:
<?xml version="1.0" encoding="utf-8"?>
<!--
~ Copyright (c) 2017, WSO2 Inc. (http://www.wso2.org) All Rights Reserved.
~
~ Licensed under the Apache License, Version 2.0 (the "License");
~ you may not use this file except in compliance with the License.
~ You may obtain a copy of the License at
~
~ http://www.apache.org/licenses/LICENSE-2.0
~
~ Unless required by applicable law or agreed to in writing, software
~ distributed under the License is distributed on an "AS IS" BASIS,
~ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
~ See the License for the specific language governing permissions and
~ limitations under the License.
-->

<!DOCTYPE suite SYSTEM "http://testng.org/testng-1.0.dtd" >

<suite name="User-Endpoint-Test-Suite">
    <test name="Util-Tests" preserve-order="true" parallel="false">
        <classes>
            <class name="org.wso2.carbon.identity.recovery.endpoint.ClaimsApiServiceImplTest"/>
            <class name="org.wso2.carbon.identity.recovery.endpoint.SecurityQuestionApiServiceImplTest"/>
            <class name="org.wso2.carbon.identity.recovery.endpoint.ValidateAnswerApiServiceImplTest"/>
            <class name="org.wso2.carbon.identity.recovery.endpoint.RecoverPasswordApiServiceImplTest"/>
            <class name="org.wso2.carbon.identity.recovery.endpoint.ValidateCodeApiServiceImplTest"/>
            <class name="org.wso2.carbon.identity.recovery.endpoint.impl.CaptchaApiServiceImplTest"/>
            <class name="org.wso2.carbon.identity.recovery.endpoint.Utils.RecoveryUtilsTest"/>
        </classes>
    </test>
</suite>


text:
<?php
/**
 * This controller currently carries actions which are too generic to go into
 * any of the others. It could be argued that some of these are too generic to
 * even be in this place... but they are here for now and like it (page related
 * actions).
 *
 * @author Matt Turner - tmatt95@gmail.com
 * @version 0.1
 */
class IndexController extends Controller
{
	/**
	 * Specifies the access control rules.
	 * This method is used by the 'accessControl' filter.
	 *
	 * @return array access control rules
	 */
	public function accessRules(){
		return array(
			array(
				'allow',
				'actions'=>array(
					'index',
					'Page'
				),
				'users'=>array('*')
			),
			array(
				'allow',
				'actions'=>array(
					'updatePage',
					'expression'=>'Users::model()->isAdmin()'
				),
			),
			array(
				'deny',
				'users'=>array('*')
			),
		);
	}

	/**
	 * The "home page" of the application. This is where the app goes if no
	 * route is specified.
	 *
	 * @todo The Films button should be highlighted but is not when on this page.
	 */
	public function actionIndex(){
		$model=new VwShowings('search');
		$model->unsetAttributes();  // clear any default values
		if(isset($_GET['VwShowings']))
			$model->attributes=$_GET['VwShowings'];

		$search = $model->futureSearch();
		$search->pagination = array('pageSize'=>12);
		$this->render('index',array('model'=>$model,'search'=>$search));
	}

	/**
	 * There are lots of pages on this website which are made up of just static
	 * text. This provides a generic methood of viewing them.
	 *
	 * @param int The id of the static content
	 * @todo This should not be in the showings controller as it is a generic
	 * function
	 */
	public function actionPage($id){
		$content = StaticSections::model()->findByPk($id);
		$this->pageTitle = 'Wotton Cinema - '. CHtml::encode($content->title);
		$this->render(
			'page',
			array(
				'content'=>$content,
			)
		);
	}

	/**
	 * Through this function, the user can update content on a static page
	 * @param type $id
	 */
	public function actionUpdatePage($id){
		$content = StaticSections::model()->findByPk($id);

		$this->layout = '//layouts/column1';
		$this->hideMainMenu = true;

		if(isset($_POST['StaticSections'])){
			$content->attributes=$_POST['StaticSections'];
			$content->save();
		}
		$this->pageTitle = 'Wotton Cinema - '. CHtml::encode($content->title);
		$this->render(
			'updatePage',
			array(
				'content'=>$content,
			)
		);
	}
}


text:
date: 2009-08-09 10:04:09+00:00
title: Jokhang Monastery and Barkhor Street
wordpress_id: 173
locations:
- Tibet
- Lhasa
redirect_from:
  - /tibet/lhasa/china-2009/jokhang-monastery-and-barkhor-street/
---

Today we had a half day tour at the Jokhang Monastery and Barkhor Street market. When we arrived at the Monastery, it was raining, but there were still numerous pilgrims outside prostrating for the end of suffering to all beings. There was no time limit on the tour of this Monastery, but it only houses about 110 monks so it isn't all that big. The Monastery had an thick air of Juniper smoke and many pilgrims were filling butter lamps and reciting mantras as they walked around.

From the roof of the Jokhang Monastery, there was an amazing view of the Potala Palace, only slightly dampened by the rain. Once we left the Monastery, we visited the Barkhor Street market, which lines the streets all the way around the Monastery. After our tour guide had taken us to the shops she was required to, we parted ways only to meet up with her again at lunch. The rest of the day has been another lazy day with neither of us feeling one hundred percent. Hopefully we will feel better tomorrow.


text:
'use strict'

var _ = require('underscore');
var promisify = require('bluebird').promisify;
var exec = promisify(require('child_process').exec);

// var access = require('object-path').get;
// var createVmstats = require('vmstat-s');

// https://unix.stackexchange.com/questions/243484/how-do-i-convert-the-output-of-ps1-to-json
var cmd = 'ps -o "%p %x %a"| jq -sR \'[sub("\n$";"") | splits("\n") | sub("^ +";"") | [splits(" +")]] | .[0] as $header | .[1:] | [.[] | [. as $x | range($header | length) | {"key": $header[.], "value": $x[.]}] | from_entries]\'';

function ps_cpu() {
  return exec(cmd).then(function (stdout, stderr) {
    // console.log("ps_cpu=" + stdout);
    return JSON.parse(stdout);
  });
}

var cmd_mem = 'ps xu| jq -sR \'[sub("\n$";"") | splits("\n") | sub("^ +";"") | [splits(" +")]] | .[0] as $header | .[1:] | [.[] | [. as $x | range($header | length) | {"key": $header[.], "value": $x[.]}] | from_entries]\'';
function ps_mem() {
  return exec(cmd_mem).then(function (stdout, stderr) {
    // console.log("ps_mem=" + stdout);
    return JSON.parse(stdout);
  });
}

// '00:01:02' => 62
function parseTimeToSeconds(timeStr) {
  if (!timeStr) {
    return 0;
  }
  var split = timeStr.split(':');
  var val = 0;
  for (var idx in split) {
    val = val * 60;
    val += parseInt(split[idx]);
  }
  return val;
}

// console.log(parseTimeToSeconds('01:02:03'));

function arrayToDict(array, func) {
  var map = {};
  for (var idx in array) {
    var key = func(array[idx]);
    map[key] = array[idx];
  }
  return map;
}

var dict = {}; // key is PID, value is object {PID, TIME, COMMAND, etc...}
function getCpuSecondsSinceLastCall() {
  return ps_cpu().then(function (result) {
    var totalTimeSec = 0;
    var newItems = arrayToDict(result, function (item) {return parseInt(item.PID);});
    for (var pid in newItems) {
      var item = newItems[pid];
      item.timeInSec = parseTimeToSeconds(item.TIME);
      if (pid in dict) {
        var oldItem = dict[pid];
        totalTimeSec += item.timeInSec - oldItem.timeInSec;
      } else {
        totalTimeSec += item.timeInSec;
        dict[pid] = item;
      }
    }
    dict = newItems;
    return totalTimeSec;
  });
}

var lastMemMap = {};
var vszKbArray = [];
var rssKbArray = [];
function getMemUsage() {
  return ps_mem().then(function (memResult) {
    var memMap = arrayToDict(memResult, function (item) {return parseInt(item.PID);});
    lastMemMap = memMap;
    var vsz = 0;
    var rss = 0;
    for (var pid in dict) {
      if (pid in memMap) {
        vsz += parseInt(memMap[pid].VSZ);
        rss += parseInt(memMap[pid].RSS);
      }
    }
    vszKbArray.push(vsz);
    rssKbArray.push(rss);
  });
}

var cpuUsedArray = [];
var intervalSec = 10; // 10s
function timeout() {
  getCpuSecondsSinceLastCall().then(function (cpuSecond) {
    cpuUsedArray.push(cpuSecond);
  }).then(getMemUsage)
  .finally(function() {
    setTimeout(timeout, intervalSec * 1000);
  });
}
timeout();

// return data object
function getCpuInfo() {
  var data = {};
  if (cpuUsedArray.length > 0) {
      // cpuUsed
      var total = _.reduce(cpuUsedArray, function(memo, num) { return memo + num;}, 0);
      var counts = cpuUsedArray.length;
      data.cpu = Math.round(total * 100 / (counts*intervalSec));
      data.cpuDetail = cpuUsedArray.join(',');

      cpuUsedArray = [];
  }
  if (vszKbArray.length > 0) {
    // console.log('vszKbArray=' + vszKbArray);
    data.vszMb = Math.round(_.last(vszKbArray)/1024.0);
    // data.vszKb = _.last(vszKbArray);
    vszKbArray = [];
  }
  if (rssKbArray.length > 0) {
    // console.log('rssKbArray=' + rssKbArray);
    data.rssMb = Math.round(_.last(rssKbArray)/1024.0);
    // data.rssKb = _.last(rssKbArray);
    data.rssDetail = rssKbArray.map(val => Math.round(val/1024)).join(',');
    rssKbArray = [];
  }
  // data.processDetail = JSON.stringify(dict);
  data.psxu = JSON.stringify(lastMemMap);
  return data;
}

module.exports = getCpuInfo;


text:
/*global tinymce:true */
/*eslint consistent-this:0 */

tinymce.PluginManager.add('textcolor', function(editor) {
	var cols, rows;

	rows = editor.settings.textcolor_rows || 5;
	cols = editor.settings.textcolor_cols || 8;

	function getCurrentColor(format) {
		var color;

		editor.dom.getParents(editor.selection.getStart(), function(elm) {
			var value;

			if ((value = elm.style[format == 'forecolor' ? 'color' : 'background-color'])) {
				color = value;
			}
		});

		return color;
	}

	function mapColors() {
		var i, colors = [], colorMap;

		colorMap = editor.settings.textcolor_map || [
			"000000", "Black",
			"993300", "Burnt orange",
			"333300", "Dark olive",
			"003300", "Dark green",
			"003366", "Dark azure",
			"000080", "Navy Blue",
			"333399", "Indigo",
			"333333", "Very dark gray",
			"800000", "Maroon",
			"FF6600", "Orange",
			"808000", "Olive",
			"008000", "Green",
			"008080", "Teal",
			"0000FF", "Blue",
			"666699", "Grayish blue",
			"808080", "Gray",
			"FF0000", "Red",
			"FF9900", "Amber",
			"99CC00", "Yellow green",
			"339966", "Sea green",
			"33CCCC", "Turquoise",
			"3366FF", "Royal blue",
			"800080", "Purple",
			"999999", "Medium gray",
			"FF00FF", "Magenta",
			"FFCC00", "Gold",
			"FFFF00", "Yellow",
			"00FF00", "Lime",
			"00FFFF", "Aqua",
			"00CCFF", "Sky blue",
			"993366", "Red violet",
			"FFFFFF", "White",
			"FF99CC", "Pink",
			"FFCC99", "Peach",
			"FFFF99", "Light yellow",
			"CCFFCC", "Pale green",
			"CCFFFF", "Pale cyan",
			"99CCFF", "Light sky blue",
			"CC99FF", "Plum"
		];

		for (i = 0; i < colorMap.length; i += 2) {
			colors.push({
				text: colorMap[i + 1],
				color: '#' + colorMap[i]
			});
		}

		return colors;
	}

	function renderColorPicker() {
		var ctrl = this, colors, color, html, last, x, y, i, id = ctrl._id, count = 0;

		function getColorCellHtml(color, title) {
			var isNoColor = color == 'transparent';

			return (
				'' +
					'
' +
						(isNoColor ? '×' : '') +
					'
' +
				'	'
			);
		}

		colors = mapColors();
		colors.push({
			text: tinymce.translate("No color"),
			color: "transparent"
		});

		html = '

';
		last = colors.length - 1;

		for (y = 0; y < rows; y++) {
			html += '
';

			for (x = 0; x < cols; x++) {
				i = y * cols + x;

				if (i > last) {
					html += '	';
				} else {
					color = colors[i];
					html += getColorCellHtml(color.color, color.text);
				}
			}

			html += '
';
		}

		if (editor.settings.color_picker_callback) {
			html += (
				'
' +
					'' +
						'
' +
							'<button type="button" role="presentation" tabindex="-1">' + tinymce.translate('Custom...') + '</button>' +
						'
' +
					'	' +
				'
'
			);

			html += '
';

			for (x = 0; x < cols; x++) {
				html += getColorCellHtml('', 'Custom color');
			}

			html += '
';
		}

		html += '

';

		return html;
	}

	function applyFormat(format, value) {
		editor.undoManager.transact(function() {
			editor.focus();
			editor.formatter.apply(format, {value: value});
			editor.nodeChanged();
		});
	}

	function removeFormat(format) {
		editor.undoManager.transact(function() {
			editor.focus();
			editor.formatter.remove(format, {value: null}, null, true);
			editor.nodeChanged();
		});
	}

	function onPanelClick(e) {
		var buttonCtrl = this.parent(), value;

		function selectColor(value) {
			buttonCtrl.hidePanel();
			buttonCtrl.color(value);
			applyFormat(buttonCtrl.settings.format, value);
		}

		function resetColor() {
			buttonCtrl.hidePanel();
			buttonCtrl.resetColor();
			removeFormat(buttonCtrl.settings.format);
		}

		function setDivColor(div, value) {
			div.style.background = value;
			div.setAttribute('data-mce-color', value);
		}

		if (tinymce.DOM.getParent(e.target, '.mce-custom-color-btn')) {
			buttonCtrl.hidePanel();

			editor.settings.color_picker_callback.call(editor, function(value) {
				var tableElm = buttonCtrl.panel.getEl().getElementsByTagName('table')[0];
				var customColorCells, div, i;

				customColorCells = tinymce.map(tableElm.rows[tableElm.rows.length - 1].childNodes, function(elm) {
					return elm.firstChild;
				});

				for (i = 0; i < customColorCells.length; i++) {
					div = customColorCells[i];
					if (!div.getAttribute('data-mce-color')) {
						break;
					}
				}

				// Shift colors to the right
				// TODO: Might need to be the left on RTL
				if (i == cols) {
					for (i = 0; i < cols - 1; i++) {
						setDivColor(customColorCells[i], customColorCells[i + 1].getAttribute('data-mce-color'));
					}
				}

				setDivColor(div, value);
				selectColor(value);
			}, getCurrentColor(buttonCtrl.settings.format));
		}

		value = e.target.getAttribute('data-mce-color');
		if (value) {
			if (this.lastId) {
				document.getElementById(this.lastId).setAttribute('aria-selected', false);
			}

			e.target.setAttribute('aria-selected', true);
			this.lastId = e.target.id;

			if (value == 'transparent') {
				resetColor();
			} else {
				selectColor(value);
			}
		} else if (value !== null) {
			buttonCtrl.hidePanel();
		}
	}

	function onButtonClick() {
		var self = this;

		if (self._color) {
			applyFormat(self.settings.format, self._color);
		} else {
			removeFormat(self.settings.format);
		}
	}

	editor.addButton('forecolor', {
		type: 'colorbutton',
		tooltip: 'Text color',
		format: 'forecolor',
		panel: {
			role: 'application',
			ariaRemember: true,
			html: renderColorPicker,
			onclick: onPanelClick
		},
		onclick: onButtonClick
	});

	editor.addButton('backcolor', {
		type: 'colorbutton',
		tooltip: 'Background color',
		format: 'hilitecolor',
		panel: {
			role: 'application',
			ariaRemember: true,
			html: renderColorPicker,
			onclick: onPanelClick
		},
		onclick: onButtonClick
	});
});


text:
package org.apache.asterix.om.typecomputer.impl;

import org.apache.asterix.om.exceptions.TypeMismatchException;
import org.apache.asterix.om.typecomputer.base.AbstractResultTypeComputer;
import org.apache.asterix.om.types.ATypeTag;
import org.apache.asterix.om.types.BuiltinType;
import org.apache.asterix.om.types.IAType;
import org.apache.hyracks.algebricks.common.exceptions.AlgebricksException;
import org.apache.hyracks.algebricks.core.algebra.base.ILogicalExpression;

public class SubstringTypeComputer extends AbstractResultTypeComputer {
    public static final SubstringTypeComputer INSTANCE = new SubstringTypeComputer();

    @Override
    public void checkArgType(String funcName, int argIndex, IAType type) throws AlgebricksException {
        ATypeTag tag = type.getTypeTag();
        if (argIndex == 0 && tag != ATypeTag.STRING) {
            throw new TypeMismatchException(funcName, argIndex, tag, ATypeTag.STRING);
        }
        if (argIndex > 0 && argIndex <= 2) {
            switch (tag) {
                case INT8:
                case INT16:
                case INT32:
                case INT64:
                    break;
                default:
                    throw new TypeMismatchException(funcName, argIndex, tag, ATypeTag.INT8, ATypeTag.INT16,
                            ATypeTag.INT32, ATypeTag.INT64);
            }
        }
    }

    @Override
    public IAType getResultType(ILogicalExpression expr, IAType... types) throws AlgebricksException {
        return BuiltinType.ASTRING;
    }
}


text:
#include "parser.h"

//The list of keywords to be blocked.
std::list<std::string> keywords = {"norrk\x94ping","norrkoping",
"spongebob","britney","spears","hilton","eller"};

/*
* Custom comparator to map to handle lower/upper-case discrepancies.
*/

struct comp {
    bool operator() (const std::string& lhs, const std::string& rhs) const {
        return strcasecmp(lhs.c_str(), rhs.c_str()) < 0;
    }
};

/*
* prints a string with special characters visible.
*/

void printString(std::string s){

  for(char& c : s) {
    printchar((unsigned char)c);
  }
  std::cout << std::endl;
}

//
// Thanks to:
// http://stackoverflow.com/questions/1079748/how-to-print-n-instead-of-a-newline
//

void printchar(unsigned char theChar){

  switch (theChar) {

    case '\n':
    printf("\\n\n");
    break;
    case '\r':
    printf("\\r");
    break;
    case '\t':
    printf("\\t");
    break;
    default:
    if ((theChar < 0x20) || (theChar > 0x7f)) {
      printf("\\%03o", (unsigned char)theChar);
    } else {
      printf("%c", theChar);
    }
    break;
  }
}

/*
* save the first line as URL
* extract every colon seperated data into key and content.
*/

std::map<std::string,std::string,comp> parseHttp(std::string s){
  std::map<std::string, std::string,comp> m;

  std::istringstream resp(s);
  std::string header;
  std::string::size_type index;
  bool firstLine = true;
  while (std::getline(resp, header) && header != "\r") {
    if(firstLine){
      m.insert(std::make_pair("URL",header.substr(4,header.length())));
      firstLine = false;
      continue;
    }
    index = header.find(':', 0);
    if(index != std::string::npos) {
      m.insert(std::make_pair(
        boost::algorithm::trim_copy(header.substr(0, index)),
        boost::algorithm::trim_copy(header.substr(index + 1))
      ));
    }
  }
  return m;
}

/*
* Check URL for inapropriate substrings.
*/

bool censorURL(std::map<std::string, std::string,comp> m){
  std::string url = m.find("URL")->second;
  std::transform(url.begin(), url.end(), url.begin(), ::tolower);
  for (std::list<std::string>::iterator it=keywords.begin(); it != keywords.end(); ++it){
    std::size_t found = url.find(*it);
    if (found!=std::string::npos){
      return true;
    }
  }
  return false;
}

/*
* Check complete content for inappropriate substrings.
*/

bool censorContent(std::string content){
  std::transform(content.begin(), content.end(), content.begin(), ::tolower);
  for (std::list<std::string>::iterator it=keywords.begin(); it != keywords.end(); ++it){
    std::size_t found = content.find(*it);

    if (found!=std::string::npos){
      return true;
    }
  }
  return false;
}

/*
* Remove line about encoding in header to ensure unencoded messages.
*/

std::string removeEnc(std::string content){
  std::istringstream resp(content);
  std::string newContent;
  std::string line;
  std::string::size_type index;
  while (std::getline(resp, line)) {
    boost::algorithm::to_lower(line);
    index = line.find("accept-encoding:",0);
    if(index != std::string::npos){
      continue;
    }else if(line == "\r"){
    	newContent.append(line+"\n");
    	continue;
    }
    else{
      newContent.append(line+"\n");
    }
  }
  return newContent;
}

/*
* change connection to connection: close, to work faster with our recv.
*/

std::string modifyConn(std::string content){
  std::istringstream resp(content);
  std::string newContent;
  std::string line;
  std::string::size_type index;
  while (std::getline(resp, line)) {
    index = line.find("onnection:",0);
    if(index != std::string::npos){
      newContent.append("connection: close \r\n");
      continue;
    }else if(line == "\r"){
    	newContent.append(line+"\n");
    	continue;
    }
    else{
      newContent.append(line+"\n");
    }
  }
  return newContent;
}


text:
/**
 */
package org_eclipse_smarthome_schemas_config_description_v1__0Simplified;

import org.eclipse.emf.common.util.EList;

import org.eclipse.emf.ecore.EObject;

/**
 *
 * A representation of the model object 'Filter'.
 *
 *
 *

 * The following features are supported:
 *

 *

 *
{@link org_eclipse_smarthome_schemas_config_description_v1__0Simplified.Filter#getCriterias Criterias}

 *

 *
 * @see org_eclipse_smarthome_schemas_config_description_v1__0Simplified.org_eclipse_smarthome_schemas_config_description_v1__0SimplifiedPackage#getFilter()
 * @model
 * @generated
 */
public interface Filter extends EObject {
	/**
	 * Returns the value of the 'Criterias' containment reference list.
	 * The list contents are of type {@link org_eclipse_smarthome_schemas_config_description_v1__0Simplified.Criteria}.
	 *
	 *

	 * If the meaning of the 'Criterias' containment reference list isn't clear,
	 * there really should be more of a description here...
	 *

	 *
	 * @return the value of the 'Criterias' containment reference list.
	 * @see org_eclipse_smarthome_schemas_config_description_v1__0Simplified.org_eclipse_smarthome_schemas_config_description_v1__0SimplifiedPackage#getFilter_Criterias()
	 * @model containment="true"
	 * @generated
	 */
	EList<Criteria> getCriterias();

} // Filter


text: Github repository: [github.com/Armael/stone](https://github.com/Armael/stone)


text:
"The Nepali Style" Magazine

The Nepali Style Magazine is a visionary organization dedicated towards enhancing lifestyle Journalism in Nepal. With a young and dynamic team of committed individuals we are striving to offer our readers international standards in literature and photography with insights that are purely local.

            <a class="btn btn-lg btn-primary" href="<?php echo base_url('user/login');?>" role="button">Click to suscribe »

                    <img class="img-responsive" src="<?php echo base_url('assets/img/post_Images/3.jpg');?>" alt="">

Trekking in Nepal Overview

                    A trek in Nepal is a special and rewarding mountain holiday. If you have the time and energy to trek don't miss the opportunity to leave Kathmandu and see the country's spectacular beauty and unique culture. Fortunately for the visitor, there are still only a few roads extending ...

                <a class="btn btn-primary" href="<?php echo base_url('welcome/download_file');?>">Download this issuse

                    <img class="img-responsive" src="<?php echo base_url('assets/img/post_Images/7.jpg');?>" alt="">

Tibet Tour with Everest Base Camp Overview

                    This adventure takes you to the historical city of Lhasa – the roof of the world – and then overland across the spectacular Tibetan Plateau to Mount Everest Base Camp. You will begin by exploring the magnificent city of Lhasa, situated in a stunning valley surrounded by mountains...

                <a class="btn btn-primary" href="<?php echo base_url('welcome/download_file');?>">Download this issuse

                    <img class="img-responsive" src="<?php echo base_url('assets/img/post_Images/6.jpg');?>" alt="">

Nepal Cooking Schools in Nepal Overview

                    Your guide to the best online cooking schools and " hands on" cooking classes. If you want to really understand a countries culture... take a cooking class! Book online for a great selection  of cooking classes, food and general interest tours with knowlegeable local tour guides...

                <a class="btn btn-primary" href="<?php echo base_url('welcome/download_file');?>">Download this issuse

                    <img class="img-responsive" src="<?php echo base_url('assets/img/post_Images/1.jpg');?>" alt="">

5 Reasons Why Choosing Healthy Food Seems Hard Overview

                    Most people want to eat better, feel better, and live longer. However, it seems that manufactured food is geared toward convenience and taste, regardless of the nutrient value. According to www.worldheart.org,...

                <a class="btn btn-primary" href="<?php echo base_url('welcome/download_file');?>">Download this issuse

                        «

                        1

                        2

                        3

                        4

                        5

                        »


text:
<?xml version="1.0" encoding="utf-8"?>
<selector
  xmlns:android="http://schemas.android.com/apk/res/android">
    <item android:state_pressed="true" android:drawable="@color/category_left_onclick_bg" />
    <item android:state_focused="true" android:drawable="@color/category_left_onclick_bg" />
    <item android:state_enabled="false" android:drawable="@drawable/left_list" />
    <item android:drawable="@drawable/left_list" />
</selector>


text:
=======
LatLon3
=======
--------
Features
--------
Methods for representing geographic coordinates (latitude and longitude) including the ability to:

* Convert lat/lon strings from almost any format into a *LatLon* object (analogous to the datetime
  library's *stptime* method)
* Automatically store decimal degrees, decimal minutes, and degree, minute, second information in
  a *LatLon* object
* Output lat/lon information into a formatted string (analogous to the datetime library's *strftime*
  method)
* Project lat/lon coordinates into some other proj projection
* Calculate distance and heading between lat/lon pairs using either the FAI or WGS84 approximation
* Create a new *LatLon* object by offsetting an initial coordinate by a distance and heading
* Subtracting one *LatLon* object from another creates a *GeoVector* object with distance and heading
  attributes (analogous to the datetime library's *timedelta* object)
* Adding or subtracting a *Latlon* object and a *GeoVector* object creates a new *LatLon* object with
  the coordinates adjusted by the *GeoVector* object's distance and heading
* *GeoVector* objects can be added, subtracted, multiplied or divided
* The module name is called LatLon3 as it is an upgrade of the LatLon package at pypi for Python 3.8.
  The original Author of LatLon is not maintaining the pypi package anymore, so we needed to change the name

------------
Installation
------------
*LatLon3* has only been tested in Python 3.8

Installation through pip::

    $ pip install LatLon3

Requires the following non-standard libraries:

	* *pyproj*
	* *future*

-----------
Usage Notes
-----------
Usage of *LatLon* is primarily through the class *LatLon*, which is designed to hold a single pair of
*Latitude* and *Longitude* objects. Strings can be converted to *LatLon* objects using the method
*string2latlon*, and to *Latitude* or *Longitude* objects using *string2geocoord*. Alternatively, a LatLon
object can be constructed by subtracting two *LatLon* objects, or adding or subtracting a *Latlon* object
and a *GeoVector* object.

Latitude or Longitude Construction
==================================
Latitude of longitude construction is through the classes *Latitude* and *Longitude*, respectively. You can
pass a latitude or longitude coordinate in any combination of decimal degrees, degrees and minutes, or
degrees minutes and seconds. Alternatively, you can pass a formatted string using the function *string2geocoord*
for a string containing a single latitude or longitude, or *string2latlon* for a pair of strings representing
the latitude and longitude.

String formatting:
==================
*string2latlon* and *string2geocoord* both take a *formatter* string which is loosely modeled on the *format*
keyword used in *datetime's* *strftime* function. Indicator characters (e.g. *H* or *D*) are placed between
a specific separator character (*%*) to specify the way in which a coordinate string is formatted. Possible
values are as follows:

          *H* is a hemisphere identifier (e.g. N, S, E or W)

          *D* is a coordinate in decimal degrees notation (e.g. 5.833)

          *d* is a coordinate in degrees notation (e.g. 5)

          *M* is a coordinate in decimal minutes notation (e.g. 54.35)

          *m* is a coordinate in minutes notation (e.g. 54)

          *S* is a coordinate in seconds notation (e.g. 28.93)

          Any other characters (e.g. ' ' or ', ') will be treated as a separator between the above components.

          All components should be separated by the *%* character. For example, if the coord_str is '5, 52,
          59.88_N', the format_str would be 'd%, %m%, %S%_%H'

*Important*
===========
One format that will not currently work is one where the hemisphere identifier and a degree or decimal degree
are not separated by any characters. For example  '5 52 59.88 N' is valid whereas '5 52 59.88N' is not.

String output:
==============
Both *LatLon* and *Latitude* and *Longitude* objects include a *to_string()* method for outputting a formatted
coordinate.

Projection:
===========
Use *LatLon.project* to transform geographical coordinates into a chosen projection. Requires that you pass it a
*pyproj* or *basemap* projection.

Distance and Heading Calculation:
=================================
*LatLon* objects have a *distance()* method which accepts a 2nd *LatLon* object as an argument. *distance()* will
calculate the great-circle distance between the two coordinates using the WGS84 ellipsoid by default. To use the
more approximate FAI sphere, set *ellipse* to 'sphere'. Initial and reverse headings (in degrees) can be calculated
in a similar way using the *heading_initial()* and *heading_reverse()* methods. Alternatively, subtracting one
*LatLon* object from another will return a *GeoVector* object with the attributes heading and distance.

Creating a New LatLon Object by Offset from Another One:
========================================================
Use the *offset()* method of *LatLon* objects, which takes an initial heading (in degrees) and distance (in km) to
return a new *LatLon* object at the offset coordinates. Also, you can perform the same operation by adding or
subtracting a LatLon object with a GeoVector object.

--------
Examples
--------
Create a *LatLon* object from coordinates::

    >> palmyra = LatLon(Latitude(5.8833), Longitude(-162.0833)) # Location of Palmyra Atoll in decimal degrees
    >> palmyra = LatLon(5.8833, -162.0833) # Same thing but simpler!
    >> palmyra = LatLon(Latitude(degree = 5, minute = 52, second = 59.88),
    >>                  Longitude(degree = -162, minute = -4.998) # or more complicated!
    >> print palmyra.to_string('d% %m% %S% %H') # Print coordinates to degree minute second
    ('5 52 59.88 N', '162 4 59.88 W')

Create a *Latlon* object from a formatted string::

    >> palmyra = string2latlon('5 52 59.88 N', '162 4 59.88 W', 'd% %m% %S% %H')
    >> print palmyra.to_string('d%_%M') # Print coordinates as degree minutes separated by underscore
    ('5_52.998', '-162_4.998')

Perform some calculations::

    >> palmyra = LatLon(Latitude(5.8833), Longitude(-162.0833)) # Location of Palmyra Atoll
    >> honolulu = LatLon(Latitude(21.3), Longitude(-157.8167)) # Location of Honolulu, HI
    >> distance = palmyra.distance(honolulu) # WGS84 distance in km
    >> print distance
    1766.69130376
    >> print palmyra.distance(honolulu, ellipse = 'sphere') # FAI distance in km
    1774.77188181
    >> initial_heading = palmyra.heading_initial(honolulu) # Heading from Palmyra to Honolulu on WGS84 ellipsoid
    >> print initial_heading
    14.6907922022
    >> hnl = palmyra.offset(initial_heading, distance) # Reconstruct Honolulu based on offset from Palmyra
    >> print hnl.to_string('D') # Coordinates of Honolulu
    ('21.3', '-157.8167')

Manipulate *LatLon* objects using *GeoVectors*::

    >> vector = (honolulu - palmyra) * 2 # A GeoVector with 2x the magnitude of a vector from palmyra to honolulu
    >> print vector # Print heading and magnitude
    14.6907922022 3533.38260751
    print palmyra + (vector/2.0) # Recreate the coordinates of Honolulu by adding half of vector to palmyra
    21.3, -157.8167

Note
====

This project has been set up using PyScaffold 2.5.6. For details and usage
information on PyScaffold see http://pyscaffold.readthedocs.org/.


text:
class QMainWindow;

void centerWindow(QMainWindow& window);

#endif // @@PROJECT_DEFINE@@_UTIL_HEADER


text:
class AddImageToCuisines < ActiveRecord::Migration[5.1]
  def change
    add_column :cuisines, :image, :string
  end
end


text:
#ifndef InspectorRuntimeAgent_h
#define InspectorRuntimeAgent_h

#include "core/CoreExport.h"
#include "core/InspectorFrontend.h"
#include "core/inspector/InspectorBaseAgent.h"
#include "wtf/Forward.h"
#include "wtf/Noncopyable.h"

namespace blink {

class InjectedScript;
class InjectedScriptManager;
class JSONArray;
class ScriptState;
class V8Debugger;
class V8RuntimeAgent;

typedef String ErrorString;

class CORE_EXPORT InspectorRuntimeAgent
    : public InspectorBaseAgent<InspectorRuntimeAgent, InspectorFrontend::Runtime>
    , public InspectorBackendDispatcher::RuntimeCommandHandler {
    WTF_MAKE_NONCOPYABLE(InspectorRuntimeAgent);
public:
    class Client {
    public:
        virtual ~Client() { }

        virtual void resumeStartup() { }
        virtual bool isRunRequired() { return false; }
    };

    ~InspectorRuntimeAgent() override;
    DECLARE_VIRTUAL_TRACE();

    // InspectorBaseAgent overrides.
    void init() override;
    void setFrontend(InspectorFrontend*) override;
    void clearFrontend() override;
    void restore() override;

    // Part of the protocol.
    void enable(ErrorString*) override;
    void disable(ErrorString*) override;

    void evaluate(ErrorString*,
        const String& expression,
        const String* objectGroup,
        const bool* includeCommandLineAPI,
        const bool* doNotPauseOnExceptionsAndMuteConsole,
        const int* executionContextId,
        const bool* returnByValue,
        const bool* generatePreview,
        RefPtr<TypeBuilder::Runtime::RemoteObject>& result,
        TypeBuilder::OptOutput<bool>* wasThrown,
        RefPtr<TypeBuilder::Debugger::ExceptionDetails>&) final;
    void callFunctionOn(ErrorString*,
                        const String& objectId,
                        const String& expression,
                        const RefPtr<JSONArray>* optionalArguments,
                        const bool* doNotPauseOnExceptionsAndMuteConsole,
                        const bool* returnByValue,
                        const bool* generatePreview,
                        RefPtr<TypeBuilder::Runtime::RemoteObject>& result,
                        TypeBuilder::OptOutput<bool>* wasThrown) final;
    void releaseObject(ErrorString*, const String& objectId) final;
    void getProperties(ErrorString*, const String& objectId, const bool* ownProperties, const bool* accessorPropertiesOnly, const bool* generatePreview, RefPtr<TypeBuilder::Array<TypeBuilder::Runtime::PropertyDescriptor>>& result, RefPtr<TypeBuilder::Array<TypeBuilder::Runtime::InternalPropertyDescriptor>>& internalProperties, RefPtr<TypeBuilder::Debugger::ExceptionDetails>&) final;
    void releaseObjectGroup(ErrorString*, const String& objectGroup) final;
    void run(ErrorString*) override;
    void isRunRequired(ErrorString*, bool* out_result) override;
    void setCustomObjectFormatterEnabled(ErrorString*, bool) final;

    virtual void muteConsole() = 0;
    virtual void unmuteConsole() = 0;

protected:
    InspectorRuntimeAgent(InjectedScriptManager*, V8Debugger*, Client*);
    virtual ScriptState* defaultScriptState() = 0;

    InjectedScriptManager* injectedScriptManager() { return m_injectedScriptManager; }
    void addExecutionContextToFrontend(int executionContextId, const String& type, const String& origin, const String& humanReadableName, const String& frameId);

    bool m_enabled;

private:

    OwnPtr<V8RuntimeAgent> m_v8RuntimeAgent;
    RawPtrWillBeMember<InjectedScriptManager> m_injectedScriptManager;
    Client* m_client;
};

} // namespace blink

#endif // InspectorRuntimeAgent_h


text:
define(
"dijit/nls/sl/loading", //begin v1.x content
({
	loadingState: "Nalaganje ...",
	errorState: "Oprostite, prišlo je do napake."
})
//end v1.x content
);


text:
export default function mapType() {
  console.group('map');
  {
    const map = new Map();

    const stringKey = 'string';
    const objectKey = { a: 'object' };
    const funcKey = () => 'function';

    map.set(stringKey, 'string'); console.log('string key =>', stringKey);
    map.set(objectKey, 'object'); console.log('object key =>', objectKey);
    map.set(funcKey, 'function'); console.log('func key =>', funcKey);

    console.log('map.size =>', map.size);

    console.log('map.get(stringKey) =>', map.get(stringKey));
    console.log('map.get(objectKey) =>', map.get(objectKey));
    console.log('map.get(funcKey) =>', map.get(funcKey));
  }
  console.groupEnd();
}


text:
package de.kaiserpfalzedv.paladinsinn.commons.paging;

import java.util.ArrayList;

import de.kaiserpfalzedv.paladinsinn.commons.api.BuilderValidationException;
import de.kaiserpfalzedv.paladinsinn.commons.api.paging.Page;
import de.kaiserpfalzedv.paladinsinn.commons.api.paging.PageBuilder;
import org.junit.Test;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import static org.junit.Assert.assertArrayEquals;
import static org.junit.Assert.assertEquals;

/**
 * @author klenkes {@literal <rlichti@kaiserpfalz-edv.de>}
 * @version 1.0.0
 * @since 2017-03-17
 */
public class PageTest {
    private static final Logger LOG = LoggerFactory.getLogger(PageTest.class);

    private static final long TOTAL_ELEMENTS = 9;
    private static final ArrayList<String> DATA = new ArrayList<>((int) TOTAL_ELEMENTS);
    private static final long PAGE_SIZE = 2;
    private static final long TOTAL_PAGES = TOTAL_ELEMENTS / PAGE_SIZE + ((TOTAL_ELEMENTS % PAGE_SIZE != 0) ? 1 : 1);

    static {
        DATA.add("ABC");
        DATA.add("DEF");
        DATA.add("GHI");
        DATA.add("JKL");
        DATA.add("MNO");
        DATA.add("PQR");
        DATA.add("STU");
        DATA.add("VWX");
        DATA.add("YZ");
    }

    @Test
    public void shouldReturnThirdPageWhenAskedForIt() throws BuilderValidationException {
        Page<String> service = generatePage(3);

        String[] data = new String[]{service.getData().get(0), service.getData().get(1)};
        String[] expected = new String[]{DATA.get(4), DATA.get(5)};

        assertArrayEquals("Wrong elements in result set", expected, data);

        assertEquals("Wrong current page", 3, service.getCurrentPageNumber());
        assertEquals("Wrong current page size", PAGE_SIZE, service.getCurrentPageSize());
        assertEquals("Wrong default page size", PAGE_SIZE, service.getPageSize());
        assertEquals("Wrong number of total elements", TOTAL_ELEMENTS, service.getTotalElements());
        assertEquals("Wrong number of total pages", TOTAL_PAGES, service.getTotalPages());
    }

    private Page<String> generatePage(long page) throws BuilderValidationException {
        return new PageBuilder<String>()
                .withPage(DATA, page, PAGE_SIZE)
                .build();
    }

    @Test
    public void shouldReturnFirstPageRequestWhenAskedWithSecondPageForIt() throws BuilderValidationException {
        Page<String> service = generatePage(2);

        assertEquals("Wrong page request found!", service.getFirstPageRequest(), service.getPreviousPageRequest());
    }

    @Test
    public void shouldReturnFirstPageRequestWhenAskedWithFirstPageRequestForIt() throws BuilderValidationException {
        Page<String> service = generatePage(1);

        assertEquals("Wrong page request found!", service.getCurrentRequest(), service.getFirstPageRequest());
    }

    @Test
    public void shouldReturnLastPageRequestWhenAskedWithForthPageForIt() throws BuilderValidationException {
        Page<String> service = generatePage(4);

        assertEquals("Wrong page request found!", service.getLastPageRequest(), service.getNextPageRequest());
    }

    @Test
    public void shouldReturnLastPageRequestWhenAskedWithLastPageRequestForIt() throws BuilderValidationException {
        Page<String> service = generatePage(5);

        assertEquals("Wrong page request found!", service.getCurrentRequest(), service.getLastPageRequest());
    }
}


text:
import os from 'os';

import { expect } from 'chai';
import sinon from 'sinon';
import { toArray } from 'rxjs/operators';
import { testInjector } from '@stryker-mutator/test-helpers';

import { lastValueFrom } from 'rxjs';

import { ConcurrencyTokenProvider } from '../../../src/concurrent';
import { createCpuInfo } from '../../helpers/producers';

describe(ConcurrencyTokenProvider.name, () => {
  function createSut() {
    return testInjector.injector.injectClass(ConcurrencyTokenProvider);
  }

  it('should log about processes', async () => {
    testInjector.options.concurrency = 9;
    const sut = createSut();
    expect(testInjector.logger.info).calledWith('Creating %s test runner process(es).', 9);
    sut.dispose();
  });

  it('should log about processes created inc checkers', async () => {
    testInjector.options.concurrency = 9;
    testInjector.options.checkers = ['typescript'];
    const sut = createSut();
    expect(testInjector.logger.info).calledWith('Creating %s checker process(es) and %s test runner process(es).', 5, 4);
    sut.dispose();
  });

  describe('testRunnerToken$', () => {
    it('should use cpuCount if concurrency is not set and CPU count <= 4', async () => {
      sinon.stub(os, 'cpus').returns([createCpuInfo(), createCpuInfo(), createCpuInfo(), createCpuInfo()]);
      const sut = createSut();
      const actualTokens = await actAllTestRunnerTokens(sut);
      expect(actualTokens).deep.eq([0, 1, 2, 3]);
    });

    it('should use cpuCount - 1 if concurrency is not set and CPU count > 4', async () => {
      sinon.stub(os, 'cpus').returns([createCpuInfo(), createCpuInfo(), createCpuInfo(), createCpuInfo(), createCpuInfo()]);
      const sut = createSut();
      const actualTokens = await actAllTestRunnerTokens(sut);
      expect(actualTokens).deep.eq([0, 1, 2, 3]);
    });

    it('should allow half of the concurrency when there are checkers configured', async () => {
      testInjector.options.concurrency = 8;
      testInjector.options.checkers = ['typescript'];
      const sut = createSut();
      const actualTokens = await actAllTestRunnerTokens(sut);
      expect(actualTokens).deep.eq([0, 1, 2, 3]);
    });

    it('should allow floor half of the concurrency when there are checkers configured', async () => {
      testInjector.options.concurrency = 9;
      testInjector.options.checkers = ['typescript'];
      const sut = createSut();
      const actualTokens = await actAllTestRunnerTokens(sut);
      expect(actualTokens).deep.eq([0, 1, 2, 3]);
    });

    it('should emit 4 more tokens when the checkers are freed', async () => {
      testInjector.options.concurrency = 8;
      testInjector.options.checkers = ['typescript'];
      const sut = createSut();
      const allTokens: number[] = [];
      sut.testRunnerToken$.subscribe((token) => allTokens.push(token));
      expect(allTokens).lengthOf(4);
      sut.freeCheckers();
      expect(allTokens).lengthOf(8);
      sut.dispose();
    });

    function actAllTestRunnerTokens(sut: ConcurrencyTokenProvider): Promise<number[]> {
      const tokens = lastValueFrom(sut.testRunnerToken$.pipe(toArray()));
      sut.dispose();
      return tokens;
    }
  });

  describe('checkerToken$', () => {
    it('should emit one value when there are no checkers configured (no actual process will be created in that case)', async () => {
      testInjector.options.checkers = [];
      const sut = createSut();
      const tokens = await lastValueFrom(sut.checkerToken$.pipe(toArray()));
      expect(tokens).deep.eq([0]);
      sut.dispose();
    });

    it('should emit 3 values if concurrency is 6', async () => {
      testInjector.options.checkers = ['typescript'];
      testInjector.options.concurrency = 6;
      const sut = createSut();
      const tokens = await lastValueFrom(sut.checkerToken$.pipe(toArray()));
      expect(tokens).deep.eq([0, 1, 2]);
      sut.dispose();
    });

    it('should emit 4 values if concurrency is 7', async () => {
      testInjector.options.checkers = ['typescript'];
      testInjector.options.concurrency = 7;
      const sut = createSut();
      const tokens = await lastValueFrom(sut.checkerToken$.pipe(toArray()));
      expect(tokens).deep.eq([0, 1, 2, 3]);
      sut.dispose();
    });
  });

  describe('dispose', () => {
    it('should complete the subject(s)', () => {
      // Arrange
      testInjector.options.checkers = ['typescript'];
      testInjector.options.concurrency = 6;
      const sut = createSut();
      const allCheckerTokens: number[] = [];
      const allTestRunnerTokens: number[] = [];
      let checkersCompleted = false;
      let testRunnersCompleted = false;
      sut.checkerToken$.subscribe({
        next(n) {
          allCheckerTokens.push(n);
        },
        complete() {
          checkersCompleted = true;
        },
      });
      sut.testRunnerToken$.subscribe({
        next(n) {
          allTestRunnerTokens.push(n);
        },
        complete() {
          testRunnersCompleted = true;
        },
      });

      // Act & assert
      expect(allTestRunnerTokens).deep.eq([0, 1, 2]);
      expect(allCheckerTokens).deep.eq([0, 1, 2]);
      expect(checkersCompleted).true;
      expect(testRunnersCompleted).false;
      sut.dispose();
      expect(checkersCompleted).true;
      expect(testRunnersCompleted).true;
    });
  });
});


text:
FOUNDATION_EXPORT double IQAudioRecorderControllerVersionNumber;
FOUNDATION_EXPORT const unsigned char IQAudioRecorderControllerVersionString[];