text:
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using Microsoft.VisualStudio.TestTools.UnitTesting;
using Utils.Structures;
using UtilsTests.FibHeap;
using UtilsTests.Helpers;

namespace UtilsTests.Matrix
{
    [TestClass]
    public class MatrixGeneratorTests
    {
        #region Fields and constants

        private const string GeneratorName = "CacheSimulator.exe";
        private const string LogFileName = "FibHeapLog";

        private readonly int[] _blockSizes = { 64, 64, 64, 512, 4096 };
        private readonly int[] _blockCounts = { 64, 1024, 4096, 512, 64 };

        private readonly string _logFolderName;

        private readonly CancellationTokenSource _cts = new CancellationTokenSource();
        private StreamWriter _log;

        public CancellationToken CancellationToken { get { return _cts.Token; } }

        #endregion

        #region Genesis

        public MatrixGeneratorTests(string logFolderName = null)
        {
            _logFolderName = logFolderName ?? @"Log";

            if (!Directory.Exists(_logFolderName))
                Directory.CreateDirectory(_logFolderName);
        }

        #endregion

        #region Logging

        private void LogLine(string message = null)
        {
            _log.WriteLine(message);
            Console.WriteLine(message);
        }

        private void LogLine(string format, params object[] arg)
        {
            LogLine(string.Format(format, arg));
        }

        private void Log(string message)
        {
            _log.Write(message);
            Console.Write(message);
        }

        private void Log(string format, params object[] arg)
        {
            Log(string.Format(format, arg));
        }

        #endregion

#if NONCLEAN
        #region Cache testing

        private void LogFilteredSimOutput(int matrixSize, string message)
        {
            if (message == null)
                return;

            const string missesPrefix = "Misses: ";

            if (!message.StartsWith(missesPrefix))
                return;

            int swapCount = (matrixSize * matrixSize - matrixSize) / 2;
            int misses = int.Parse(message.Substring(missesPrefix.Length));
            LogLine("{0}::{1}", matrixSize, misses / (float)swapCount);
        }

        public void TestCache(int matrixSize, int blockSize, int blockCount)
        {
            var cacheProcess = new MyCommandGenerator(_cts);
            Action<string> cacheSimMessageCallback = s => LogFilteredSimOutput(matrixSize, s);

            // TODO: Run the cache sim once for all the test...
            var generatorTask = cacheProcess.RunGenerator(
                Path.Combine(GeneratorTestsBase<object>.ToolsPath, GeneratorName),
                string.Format("{0} {1}", blockSize, blockCount),
                cacheSimMessageCallback,
                true, false);

            int swapCount = 0;

            Action<string> matrixOutputHandler = s =>
            {
                swapCount++;
                cacheProcess.Process.WriteLineToStdIn(s);
            };

            Matrix<int> m = new Matrix<int>(matrixOutputHandler, matrixSize, matrixSize);
            m.Transpose();
            cacheProcess.Process.WriteLineToStdIn("\0"); // Terminate the program

            swapCount -= 2; // There were two more logs -- N and E
            Assert.AreEqual(swapCount, (matrixSize * matrixSize - matrixSize) / 2);

            generatorTask.Wait(20000, _cts.Token); // Wait for 20 sec
        }

        IEnumerable<int> GetMatrixSizes()
        {
            int k = 54;

            while (k <= 13 * 9) // Run up to 256MB matrix size
            //while (k <= 14 * 9) // Run up to 1GB matrix size
            {
                int size = (int)Math.Pow(2, k++ / 9f);
                yield return size;
            }
        }

        public void TestCache(int i)
        {
            int blockSize = _blockSizes[i];
            int blockCount = _blockCounts[i];

            string suffix = string.Format("_b-{0}_c-{1}", blockSize, blockCount);
            using (_log = new StreamWriter(Path.Combine(_logFolderName, LogFileName) + suffix + ".txt"))
            {
                Console.WriteLine("\nStarting BlockSize/BlockCount: {0}/{1}", blockSize, blockCount);
                LogLine("Size::miss");

                foreach (var matrixSize in GetMatrixSizes())
                    TestCache(matrixSize, blockSize, blockCount);

                LogLine();
                Console.WriteLine("\nFinished {0}/{1}\n", blockSize, blockCount);
            }
        }

        #endregion
#endif // NONCLEAN

#if LONG_RUNNING_TESTS
        [TestMethod]
#endif
        public void TestCacheFirstHalf()
        {
#if NONCLEAN
            for (int i = 0; i < _blockSizes.Length / 2; i++)
                TestCache(i);
#else
            Assert.Fail("Nothing to test in clean mode...");
#endif // NONCLEAN

        }

#if LONG_RUNNING_TESTS
        [TestMethod]
#endif
        public void TestCacheSecondHalf()
        {
#if NONCLEAN
            for (int i = _blockSizes.Length / 2; i < _blockSizes.Length; i++)
                TestCache(i);
#else
            Assert.Fail("Nothing to test in clean mode...");
#endif // NONCLEAN
        }

#if LONG_RUNNING_TESTS
        [TestMethod]
#endif
        public void TestTime()
        {
            // TODO: move to another test class
        }
    }
}


text:
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
	xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 https://maven.apache.org/xsd/maven-4.0.0.xsd">
	<modelVersion>4.0.0</modelVersion>
	<groupId>org.springframework.boot.maven.it</groupId>
	<artifactId>build-image-war-packaging</artifactId>
	<version>0.0.1.BUILD-SNAPSHOT</version>
	<packaging>war</packaging>
	<properties>
		<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
		<maven.compiler.source>@java.version@</maven.compiler.source>
		<maven.compiler.target>@java.version@</maven.compiler.target>
	</properties>
	<build>
		<plugins>
			<plugin>
				<groupId>@project.groupId@</groupId>
				<artifactId>@project.artifactId@</artifactId>
				<version>@project.version@</version>
				<executions>
					<execution>
						<goals>
							<goal>build-image-no-fork</goal>
						</goals>
						<configuration>
							<image>
								<builder>projects.registry.vmware.com/springboot/spring-boot-cnb-builder:0.0.1</builder>
							</image>
						</configuration>
					</execution>
				</executions>
			</plugin>
			<plugin>
				<groupId>org.apache.maven.plugins</groupId>
				<artifactId>maven-war-plugin</artifactId>
				<version>@maven-war-plugin.version@</version>
				<configuration>
					<archive>
						<manifestEntries>
							<Not-Used>Foo</Not-Used>
						</manifestEntries>
					</archive>
				</configuration>
			</plugin>
		</plugins>
	</build>
	<dependencies>
		<dependency>
			<groupId>org.springframework</groupId>
			<artifactId>spring-context</artifactId>
			<version>@spring-framework.version@</version>
		</dependency>
		<dependency>
			<groupId>jakarta.servlet</groupId>
			<artifactId>jakarta.servlet-api</artifactId>
			<version>@jakarta-servlet.version@</version>
			<scope>provided</scope>
		</dependency>
	</dependencies>
</project>

redpajama_set_name: RedPajamaGithub


text:
using System.ComponentModel;
using System.ComponentModel.DataAnnotations;
using System.Runtime.Serialization;
using RESTyard.AspNetCore.Util.Repository;

namespace CarShack.Domain.Customer
{

    // Options for filtering
    public class CustomerFilter : IQueryFilter
    {
        [Range(1, 150)]
        public int? MinAge { get; set; }

        public CustomerFilter()
        {
        }

        // copy constructor
        public CustomerFilter(CustomerFilter other)
        {
            MinAge = other.MinAge;
        }

        public IQueryFilter Clone()
        {
            return new CustomerFilter(this);
        }
    }
}


text:
package java.io;

public interface Flushable {
    void flush() throws IOException;
}


text:
<html>
<head>
  <title>Ant Colony</title>
  <script language="javascript" type="text/javascript" src="https://cdnjs.cloudflare.com/ajax/libs/p5.js/0.5.7/p5.js"></script>
  <script language="javascript" type="text/javascript" src="https://cdnjs.cloudflare.com/ajax/libs/p5.js/0.4.22/addons/p5.dom.js"></script>
  <script language="javascript" type="text/javascript" src="ant-agent.js"></script>
  <script language="javascript" type="text/javascript" src="ant-flock.js"></script>
  <script language="javascript" type="text/javascript" src="ant-colony-sketch.js"></script>
</head>
<body>

</body>
</html>


text:
import {Component, Input} from "@angular/core";
import {DataTable, SortEvent} from "./DataTable";

@Component({
    selector: "mfDefaultSorter",
    template: `

            <ng-content></ng-content>

        `
})
export class DefaultSorter {
    @Input("by") private sortBy: string;

    private isSortedByMeAsc: boolean = false;
    private isSortedByMeDesc: boolean = false;

    public constructor(private mfTable: DataTable) {
        mfTable.onSortChange.subscribe((event:SortEvent) => {
            this.isSortedByMeAsc = (event.sortBy === this.sortBy && event.sortOrder === "asc");
            this.isSortedByMeDesc = (event.sortBy === this.sortBy && event.sortOrder === "desc");
        })
    }

    private sort() {
        if(this.isSortedByMeAsc) {
            this.mfTable.setSort(this.sortBy, "desc");
        } else {
            this.mfTable.setSort(this.sortBy, "asc");
        }
    }
}


text:
namespace System.Runtime
{
    using System;
    using System.Collections.ObjectModel;
    using System.Diagnostics;
    using System.Globalization;
    using System.Reflection;
    using System.Runtime.CompilerServices;
    using System.Runtime.Diagnostics;
    using System.Runtime.Interop;
    using System.Runtime.Versioning;
    using System.Security;

    class ExceptionTrace
    {
        const ushort FailFastEventLogCategory = 6;
        string eventSourceName;
        readonly EtwDiagnosticTrace diagnosticTrace;

        public ExceptionTrace(string eventSourceName, EtwDiagnosticTrace diagnosticTrace)
        {
            Fx.Assert(diagnosticTrace != null, "'diagnosticTrace' MUST NOT be NULL.");

            this.eventSourceName = eventSourceName;
            this.diagnosticTrace = diagnosticTrace;
        }

        public void AsInformation(Exception exception)
        {
            //Traces an informational trace message
            TraceCore.HandledException(this.diagnosticTrace, exception != null ? exception.ToString() : string.Empty, exception);
        }

        public void AsWarning(Exception exception)
        {
            //Traces a warning trace message
            TraceCore.HandledExceptionWarning(this.diagnosticTrace, exception != null ? exception.ToString() : string.Empty, exception);
        }

        public Exception AsError(Exception exception)
        {
            // AggregateExceptions are automatically unwrapped.
            AggregateException aggregateException = exception as AggregateException;
            if (aggregateException != null)
            {
                return AsError<Exception>(aggregateException);
            }

            // TargetInvocationExceptions are automatically unwrapped.
            TargetInvocationException targetInvocationException = exception as TargetInvocationException;
            if (targetInvocationException != null && targetInvocationException.InnerException != null)
            {
                return AsError(targetInvocationException.InnerException);
            }

            return TraceException<Exception>(exception);
        }

        public Exception AsError(Exception exception, string eventSource)
        {
            // AggregateExceptions are automatically unwrapped.
            AggregateException aggregateException = exception as AggregateException;
            if (aggregateException != null)
            {
                return AsError<Exception>(aggregateException, eventSource);
            }

            // TargetInvocationExceptions are automatically unwrapped.
            TargetInvocationException targetInvocationException = exception as TargetInvocationException;
            if (targetInvocationException != null && targetInvocationException.InnerException != null)
            {
                return AsError(targetInvocationException.InnerException, eventSource);
            }

            return TraceException<Exception>(exception, eventSource);
        }

        public Exception AsError(TargetInvocationException targetInvocationException, string eventSource)
        {
            Fx.Assert(targetInvocationException != null, "targetInvocationException cannot be null.");

            // If targetInvocationException contains any fatal exceptions, return it directly
            // without tracing it or any inner exceptions.
            if (Fx.IsFatal(targetInvocationException))
            {
                return targetInvocationException;
            }

            // A non-null inner exception could require further unwrapping in AsError.
            Exception innerException = targetInvocationException.InnerException;
            if (innerException != null)
            {
                return AsError(innerException, eventSource);
            }

            // A null inner exception is unlikely but possible.
            // In this case, trace and return the targetInvocationException itself.
            return TraceException<Exception>(targetInvocationException, eventSource);
        }

        public Exception AsError<TPreferredException>(AggregateException aggregateException)
        {
            return AsError<TPreferredException>(aggregateException, this.eventSourceName);
        }

        /// <summary>
        /// Extracts the first inner exception of type <typeparamref name="TPreferredException"/>
        /// from the <see cref="AggregateException"/> if one is present.
        /// </summary>
        /// <remarks>
        /// If no <typeparamref name="TPreferredException"/> inner exception is present, this
        /// method returns the first inner exception.   All inner exceptions will be traced,
        /// including the one returned.   The containing <paramref name="aggregateException"/>
        /// will not be traced unless there are no inner exceptions.
        /// </remarks>
        /// <typeparam name="TPreferredException">The preferred type of inner exception to extract.
        /// Use <c>typeof(Exception)</c> to extract the first exception regardless of type.</typeparam>
        /// <param name="aggregateException">The <see cref="AggregateException"/> to examine.</param>
        /// <param name="eventSource">The event source to trace.</param>
        /// <returns>The extracted exception.  It will not be <c>null</c>
        /// but it may not be of type <typeparamref name="TPreferredException"/>.</returns>
        public Exception AsError<TPreferredException>(AggregateException aggregateException, string eventSource)
        {
            Fx.Assert(aggregateException != null, "aggregateException cannot be null.");

            // If aggregateException contains any fatal exceptions, return it directly
            // without tracing it or any inner exceptions.
            if (Fx.IsFatal(aggregateException))
            {
                return aggregateException;
            }

            // Collapse possibly nested graph into a flat list.
            // Empty inner exception list is unlikely but possible via public api.
            ReadOnlyCollection<Exception> innerExceptions = aggregateException.Flatten().InnerExceptions;
            if (innerExceptions.Count == 0)
            {
                return TraceException(aggregateException, eventSource);
            }

            // Find the first inner exception, giving precedence to TPreferredException
            Exception favoredException = null;
            foreach (Exception nextInnerException in innerExceptions)
            {
                // AggregateException may wrap TargetInvocationException, so unwrap those as well
                TargetInvocationException targetInvocationException = nextInnerException as TargetInvocationException;

                Exception innerException = (targetInvocationException != null && targetInvocationException.InnerException != null)
                                                ? targetInvocationException.InnerException
                                                : nextInnerException;

                if (innerException is TPreferredException && favoredException == null)
                {
                    favoredException = innerException;
                }

                // All inner exceptions are traced
                TraceException<Exception>(innerException, eventSource);
            }

            if (favoredException == null)
            {
                Fx.Assert(innerExceptions.Count > 0, "InnerException.Count is known to be > 0 here.");
                favoredException = innerExceptions[0];
            }

            return favoredException;
        }

        public ArgumentException Argument(string paramName, string message)
        {
            return TraceException<ArgumentException>(new ArgumentException(message, paramName));
        }

        public ArgumentNullException ArgumentNull(string paramName)
        {
            return TraceException<ArgumentNullException>(new ArgumentNullException(paramName));
        }

        public ArgumentNullException ArgumentNull(string paramName, string message)
        {
            return TraceException<ArgumentNullException>(new ArgumentNullException(paramName, message));
        }

        public ArgumentException ArgumentNullOrEmpty(string paramName)
        {
            return this.Argument(paramName, InternalSR.ArgumentNullOrEmpty(paramName));
        }

        public ArgumentOutOfRangeException ArgumentOutOfRange(string paramName, object actualValue, string message)
        {
            return TraceException<ArgumentOutOfRangeException>(new ArgumentOutOfRangeException(paramName, actualValue, message));
        }

        // When throwing ObjectDisposedException, it is highly recommended that you use this ctor
        // [C#]
        // public ObjectDisposedException(string objectName, string message);
        // And provide null for objectName but meaningful and relevant message for message.
        // It is recommended because end user really does not care or can do anything on the disposed object, commonly an internal or private object.
        public ObjectDisposedException ObjectDisposed(string message)
        {
            // pass in null, not disposedObject.GetType().FullName as per the above guideline
            return TraceException<ObjectDisposedException>(new ObjectDisposedException(null, message));
        }

        public void TraceUnhandledException(Exception exception)
        {
            TraceCore.UnhandledException(this.diagnosticTrace, exception != null ? exception.ToString() : string.Empty, exception);
        }

        public void TraceHandledException(Exception exception, TraceEventType traceEventType)
        {
            switch (traceEventType)
            {
                case TraceEventType.Error:
                    if (TraceCore.HandledExceptionErrorIsEnabled(this.diagnosticTrace))
                    {
                        TraceCore.HandledExceptionError(this.diagnosticTrace, exception != null ? exception.ToString() : string.Empty, exception);
                    }
                    break;
                case TraceEventType.Warning:
                    if (TraceCore.HandledExceptionWarningIsEnabled(this.diagnosticTrace))
                    {
                        TraceCore.HandledExceptionWarning(this.diagnosticTrace, exception != null ? exception.ToString() : string.Empty, exception);
                    }
                    break;
                case TraceEventType.Verbose:
                    if (TraceCore.HandledExceptionVerboseIsEnabled(this.diagnosticTrace))
                    {
                        TraceCore.HandledExceptionVerbose(this.diagnosticTrace, exception != null ? exception.ToString() : string.Empty, exception);
                    }
                    break;
                default:
                    if (TraceCore.HandledExceptionIsEnabled(this.diagnosticTrace))
                    {
                        TraceCore.HandledException(this.diagnosticTrace, exception != null ? exception.ToString() : string.Empty, exception);
                    }
                    break;
            }
        }

        public void TraceEtwException(Exception exception, TraceEventType eventType)
        {
            switch (eventType)
            {
                case TraceEventType.Error:
                case TraceEventType.Warning:
                    if (TraceCore.ThrowingExceptionIsEnabled(this.diagnosticTrace))
                    {
                        TraceCore.ThrowingEtwException(this.diagnosticTrace, this.eventSourceName, exception != null ? exception.ToString() : string.Empty, exception);
                    }
                    break;
                case TraceEventType.Critical:
                    if (TraceCore.UnhandledExceptionIsEnabled(this.diagnosticTrace))
                    {
                        TraceCore.EtwUnhandledException(this.diagnosticTrace, exception != null ? exception.ToString() : string.Empty, exception);
                    }
                    break;
                default:
                    if (TraceCore.ThrowingExceptionVerboseIsEnabled(this.diagnosticTrace))
                    {
                        TraceCore.ThrowingEtwExceptionVerbose(this.diagnosticTrace, this.eventSourceName, exception != null ? exception.ToString() : string.Empty, exception);
                    }
                    break;
            }
        }

        TException TraceException<TException>(TException exception)
            where TException : Exception
        {
            return TraceException<TException>(exception, this.eventSourceName);
        }

        [ResourceConsumption(ResourceScope.Process)]
        [Fx.Tag.SecurityNote(Critical = "Calls 'System.Runtime.Interop.UnsafeNativeMethods.IsDebuggerPresent()' which is a P/Invoke method",
            Safe = "Does not leak any resource, needed for debugging")]
        [SecuritySafeCritical]
        TException TraceException<TException>(TException exception, string eventSource)
            where TException : Exception
        {
            if (TraceCore.ThrowingExceptionIsEnabled(this.diagnosticTrace))
            {
                TraceCore.ThrowingException(this.diagnosticTrace, eventSource, exception != null ? exception.ToString() : string.Empty, exception);
            }

            BreakOnException(exception);

            return exception;
        }

        [Fx.Tag.SecurityNote(Critical = "Calls into critical method UnsafeNativeMethods.IsDebuggerPresent and UnsafeNativeMethods.DebugBreak",
        Safe = "Safe because it's a no-op in retail builds.")]
        [SecuritySafeCritical]
        void BreakOnException(Exception exception)
        {
#if DEBUG
            if (Fx.BreakOnExceptionTypes != null)
            {
                foreach (Type breakType in Fx.BreakOnExceptionTypes)
                {
                    if (breakType.IsAssignableFrom(exception.GetType()))
                    {
                        // This is intended to "crash" the process so that a debugger can be attached.  If a managed
                        // debugger is already attached, it will already be able to hook these exceptions.  We don't
                        // want to simulate an unmanaged crash (DebugBreak) in that case.
                        if (!Debugger.IsAttached && !UnsafeNativeMethods.IsDebuggerPresent())
                        {
                            UnsafeNativeMethods.DebugBreak();
                        }
                    }
                }
            }
#endif
        }

        [MethodImpl(MethodImplOptions.NoInlining)]
        internal void TraceFailFast(string message)
        {
            EventLogger logger = null;
#pragma warning disable 618
            logger = new EventLogger(this.eventSourceName, this.diagnosticTrace);
#pragma warning restore 618
            TraceFailFast(message, logger);
        }

        // Generate an event Log entry for failfast purposes
        // To force a Watson on a dev machine, do the following:
        // 1. Set \HKLM\SOFTWARE\Microsoft\PCHealth\ErrorReporting ForceQueueMode = 0
        // 2. In the command environment, set COMPLUS_DbgJitDebugLaunchSetting=0
        [MethodImpl(MethodImplOptions.NoInlining)]
        internal void TraceFailFast(string message, EventLogger logger)
        {
            if (logger != null)
            {
                try
                {
                    string stackTrace = null;
                    try
                    {
                        stackTrace = new StackTrace().ToString();
                    }
                    catch (Exception exception)
                    {
                        stackTrace = exception.Message;
                        if (Fx.IsFatal(exception))
                        {
                            throw;
                        }
                    }
                    finally
                    {
                        logger.LogEvent(TraceEventType.Critical,
                            FailFastEventLogCategory,
                            (uint)System.Runtime.Diagnostics.EventLogEventId.FailFast,
                            message,
                            stackTrace);
                    }
                }
                catch (Exception ex)
                {
                    logger.LogEvent(TraceEventType.Critical,
                        FailFastEventLogCategory,
                        (uint)System.Runtime.Diagnostics.EventLogEventId.FailFastException,
                        ex.ToString());
                    if (Fx.IsFatal(ex))
                    {
                        throw;
                    }
                }
            }
        }
    }
}


text:
import json
import logging
import optparse
import sys

from mongo_connector import compat, errors
from mongo_connector.constants import __version__
from mongo_connector.compat import reraise

def default_apply_function(option, cli_values):
    first_value = list(cli_values.values())[0]
    if first_value is not None:
        option.value = first_value

class Option(object):
    """A config file option which can be overwritten on the command line.

    config_key is the corresponding field in the JSON config file.

    apply_function has the following signature:
    def apply_function(option, cli_values):
        # modify option.value ...

    When apply_function is invoked, option.value will be set to the
    value given in the config file (or the default value).

    apply_function reads the cli_values and modifies option.value accordingly
    """

    def __init__(self, config_key=None, default=None, type=None,
                 apply_function=default_apply_function):
        self.config_key = config_key
        self.value = default
        self.type = type
        self.apply_function = apply_function

        self.cli_names = []
        self.cli_options = []

    def validate_type(self):
        if self.type == str:
            return compat.is_string(self.value)
        else:
            return isinstance(self.value,
                              self.type)

    def add_cli(self, *args, **kwargs):
        """Add a command line argument.

        All of the given arguments will be passed directly to
        optparse.OptionParser().add_option
        """
        self.cli_options.append((args, kwargs))

class Config(object):
    """Manages command line application configuration.

    conf = Config(options)
    conf.parse_args()
    value = conf['key']
    value2 = conf['key1.key2'] # same as conf['key1']['key2']
    """

    def __init__(self, options):
        self.options = options

        self.config_key_to_option = dict(
            [(option.config_key, option) for option in self.options])

    def parse_args(self, argv=None):
        """Parses command line arguments from stdin (or given argv).

        Does the following:
        1. Parses command line arguments
        2. Loads config file into options (if config file specified)
        3. calls option.apply_function with the parsed cli_values
        """

        # parse the command line options
        parser = optparse.OptionParser(
            version='%prog version: ' + __version__)
        for option in self.options:
            for args, kwargs in option.cli_options:
                cli_option = parser.add_option(*args, **kwargs)
                option.cli_names.append(cli_option.dest)
        parsed_options, args = parser.parse_args(argv)
        if args:
            raise errors.InvalidConfiguration(
                'The following command line arguments are not recognized: '
                + ', '.join(args))

        # load the config file
        if parsed_options.config_file:
            try:
                with open(parsed_options.config_file) as f:
                    self.load_json(f.read())
            except (OSError, IOError, ValueError):
                reraise(errors.InvalidConfiguration, *sys.exc_info()[1:])

        # apply the command line arguments
        values = parsed_options.__dict__
        for option in self.options:
            option.apply_function(
                option, dict((k, values.get(k)) for k in option.cli_names))

    def __getitem__(self, key):
        keys = key.split('.')
        cur = self.config_key_to_option[keys[0]].value
        for k in keys[1:]:
            if cur is not None:
                if isinstance(cur, dict):
                    cur = cur.get(k)
                else:
                    cur = None
        return cur

    def load_json(self, text):
        parsed_config = json.loads(text)
        for k in parsed_config:
            option = self.config_key_to_option.get(k)
            if option:
                # load into option.value
                if isinstance(parsed_config[k], dict):
                    for k2 in parsed_config[k]:
                        option.value[k2] = parsed_config[k][k2]
                else:
                    option.value = parsed_config[k]

                # type check
                if not option.validate_type():
                    raise errors.InvalidConfiguration(
                        "%s should be a %r, %r was given!" %
                        (option.config_key,
                         option.type.__name__,
                         type(option.value).__name__))
            else:
                if not k.startswith("__"):
                    logging.warning("Unrecognized option: %s" % k)


text:
import ctypes as ct
import platform

try:
    if genGL:
        _generation = True
except NameError:
    _generation = False

# currently in order to properly fully generat
if platform.system() == "Linux" or _generation:
    from .x11 import *
elif platform.system == "Windows" or _generation:
    from .win32 import *

# private non gl types
_c_ptrdiff_t = ct.c_ssize_t

class _Opaque(ct.Structure):
    pass

GLenum = ct.c_uint
GLbitfield = ct.c_uint
GLuint = ct.c_uint
GLint = ct.c_int
GLsizei = ct.c_int
GLboolean = ct.c_ubyte
GLbyte = ct.c_char
GLshort = ct.c_short
GLubyte = ct.c_ubyte
GLushort = ct.c_ushort
GLulong = ct.c_ulong
GLfloat = ct.c_float
GLclampf = ct.c_float
GLclampx = ct.c_int
GLdouble = ct.c_double
GLclampd = ct.c_double
void = None
GLvoid = None
GLchar = ct.c_char
GLfixed = GLint

GLintptr = _c_ptrdiff_t
GLintptrARB = _c_ptrdiff_t
GLsizeiptrARB = _c_ptrdiff_t
GLsizeiptr = _c_ptrdiff_t

GLvdpauSurfaceNV = GLintptr

GLuint64EXT = ct.c_ulonglong
GLint64EXT = ct.c_longlong

GLuint64 = ct.c_ulonglong
GLint64 = ct.c_longlong

GLhandleARB = ct.c_uint
GLcharARB = ct.c_char

GLeglImageOES = ct.c_void_p

GLhalfARB = ct.c_ushort
GLhalfNV = ct.c_ushort
GLsync = ct.POINTER(_Opaque)

__all__ = ['GLenum',
        'GLbitfield',
        'GLuint',
        'GLint',
        'GLsizei',
        'GLboolean',
        'GLbyte',
        'GLshort',
        'GLubyte',
        'GLushort',
        'GLulong',
        'GLfloat',
        'GLclampf',
        'GLdouble',
        'GLclampd',
        'void',
        'GLvoid',
        'GLchar',
        'GLintptr',
        'GLsizeiptr',
        'GLhandleARB',
        'GLcharARB',
        'GLhalfARB',
        'GLhalfNV',
        'GLsync']


text:
<?php

namespace GoldenPlanet\WebpackBundle\Service;

use ArrayObject;
use GoldenPlanet\WebpackBundle\Provider\AssetProvider\AssetsFromFileProviderInterface;
use GoldenPlanet\WebpackBundle\Model\AssetItemModel;
use GoldenPlanet\WebpackBundle\Model\AssetCollectionModel;
use GoldenPlanet\WebpackBundle\ErrorHandler\ErrorHandlerInterface;
use GoldenPlanet\WebpackBundle\Exception\ResourceParsingException;

class AssetCollector
{
	/**
	 * @var AssetsFromFileProviderInterface[]
	 */
	private $assetProviders = [];
	private $errorHandler;

	public function __construct(
		ErrorHandlerInterface $errorHandler
	) {
		$this->errorHandler = $errorHandler;
	}

	/**
	 * This method is called for each service tagged with `gp_webpack.asset_provider`
	 *
	 * A compiler pass is added in the root `GoldenPlanetWebpackBundle->build()` method
	 * for all services that are tagged with `tags: - { name: gp_webpack.asset_provider }`
	 *
	 * @param AssetsFromFileProviderInterface $assetProvider
	 */
	public function addAssetProvider($assetProvider)
	{
		$this->assetProviders[] = $assetProvider;
	}

	/**
	 * @param null|mixed $previousContext
	 *
	 * @return AssetCollectionModel
	 */
	public function getAssets($previousContext = null)
	{
		$contexts = [];
		$groupedAssets = new ArrayObject();

		foreach ($this->assetProviders as $i => $assetProvider) {

			$assetProviderContext = isset($previousContext[$i]) ? $previousContext[$i] : null;
			$assetCollection = $assetProvider->getAssets($assetProviderContext);
			$contexts[$i] = $assetCollection->getContext();
			$assetProviderAssets = $assetCollection->getAssets();

			$this->mergeAssets($groupedAssets, $assetProviderAssets);
		}

		return $this->buildCollection($groupedAssets, $contexts);
	}

	/**
	 * @param ArrayObject      $groupedAssets
	 * @param AssetItemModel[] $assets
	 */
	private function mergeAssets(ArrayObject $groupedAssets, $assets)
	{
		foreach ($assets as $asset) {

			$assetResource = $asset->getResource();

			if (isset($groupedAssets[$assetResource])) {

				$this->checkSameGroup($groupedAssets[$assetResource], $asset);
				continue;
			}

			$groupedAssets[$assetResource] = $asset;
		}
	}

	/**
	 * Ensure that an asset does not belong to multiple groups
	 * It must be a part of a single commons chunk
	 *
	 * @param AssetItemModel $assetOne
	 * @param AssetItemModel $assetTwo
	 */
	private function checkSameGroup(AssetItemModel $assetOne, AssetItemModel $assetTwo)
	{
		if ($assetOne->getGroup() !== $assetTwo->getGroup()) {

			$this->errorHandler
				->processException(new ResourceParsingException(sprintf(
						'Same assets must have same groups. Different groups (%s and %s) found for asset "%s"',
						$assetOne->getGroup() === null ? 'none' : '"' . $assetOne->getGroup() . '"',
						$assetTwo->getGroup() === null ? 'none' : '"' . $assetTwo->getGroup() . '"',
						$assetOne->getResource()
					))
				);
		}
	}

	private function buildCollection(ArrayObject $groupedAssets, $context)
	{
		$assetCollection = new AssetCollectionModel();
		$assetCollection->setAssets(array_values((array) $groupedAssets));
		$assetCollection->setContext($context);

		return $assetCollection;
	}
}


text:
const webpack = require('webpack')

module.exports = {
  output: {
    library: 'ReactRouterConfig',
    libraryTarget: 'umd'
  },

  externals: {
    'react-router': {
      root: 'ReactRouter',
      commonjs2: 'react-router',
      commonjs: 'react-router',
      amd: 'react-router'
    },
    react: {
      root: 'React',
      commonjs2: 'react',
      commonjs: 'react',
      amd: 'react'
    }
  },

  module: {
    loaders: [
      { test: /\.js$/, exclude: /node_modules/, loader: 'babel' }
    ]
  },

  plugins: [
    new webpack.DefinePlugin({
      'process.env.NODE_ENV': JSON.stringify(process.env.NODE_ENV || 'development')
    })
  ]
}


text:
class Event(object):
    _observers = []
    def __init__(self, subject):
        self.subject = subject

    @classmethod
    def register(cls, observer):
        if observer not in cls._observers:
            cls._observers.append(observer)

    @classmethod
    def unregister(cls, observer):
        if observer in cls._observers:
            cls._observers.remove(observer)

    @classmethod
    def notify(cls, subject):
        event = cls(subject)
        for observer in cls._observers:
            observer(event)

class WriteEvent(Event):
    _observers = []
    def __repr__(self):
        return 'WriteEvent'

def log(event):
    print '%s was written' % event.subject

WriteEvent.register(log)

class AnotherObserver(object):
    def __call__(self, event):
        print 'Yeah %s told me !' % event

WriteEvent.register(AnotherObserver())

WriteEvent.notify('a given file')


text:
function init(virtual)
  if not virtual then
    if storage.state == nil then
      storage.state = false
    end

    if storage.timer == nil then
      storage.timer = 0
    end

    self.detectCooldown = entity.configParameter("detectCooldown")

    updateAnimationState()

    self.connectionMap = {}
    self.connectionMap[1] = 2
    self.connectionMap[2] = 1
    self.connectionMap[3] = 4
    self.connectionMap[4] = 3

    pipes.init({liquidPipe,itemPipe})
    datawire.init()
  end
end

function onNodeConnectionChange()
  datawire.onNodeConnectionChange()
end

--------------------------------------------------------------------------------
function main(args)
  datawire.update()
  pipes.update(entity.dt())

  if storage.timer > 0 then
    storage.timer = storage.timer - entity.dt()

    if storage.timer <= 0 then
      deactivate()
    end
  end
end

function updateAnimationState()
  if storage.state then
    entity.setAnimationState("switchState", "on")
  else
    entity.setAnimationState("switchState", "off")
  end
end

function activate()
  storage.timer = self.detectCooldown
  storage.state = true
  entity.setAllOutboundNodes(true)
  updateAnimationState()
end

function deactivate()
  storage.state = false
  updateAnimationState()
  entity.setAllOutboundNodes(false)
end

function output(item)
  if item.count then
    datawire.sendData(item.count, "number", "all")
  end
end

function beforeLiquidGet(filter, nodeId)
  --world.logInfo("passing liquid peek get from %s to %s", nodeId, self.connectionMap[nodeId])
  return peekPullLiquid(self.connectionMap[nodeId], liquid)
end

function onLiquidGet(filter, nodeId)
  --world.logInfo("passing liquid get from %s to %s", nodeId, self.connectionMap[nodeId])
  return pullLiquid(self.connectionMap[nodeId], filter)
end

function beforeLiquidPut(liquid, nodeId)
  --world.logInfo("passing liquid peek from %s to %s", nodeId, self.connectionMap[nodeId])
  return peekPushLiquid(self.connectionMap[nodeId], liquid)
end

function onLiquidPut(liquid, nodeId)
  --world.logInfo("passing liquid from %s to %s", nodeId, self.connectionMap[nodeId])
  return pushLiquid(self.connectionMap[nodeId], liquid)
end

function beforeItemPut(item, nodeId)
  --world.logInfo("passing item peek from %s to %s", nodeId, self.connectionMap[nodeId])
  return peekPushItem(self.connectionMap[nodeId], item)
end

function onItemPut(item, nodeId)
  --world.logInfo("passing item from %s to %s", nodeId, self.connectionMap[nodeId])
  local result = pushItem(self.connectionMap[nodeId], item)
  if result then
    activate()
    output(item)
  end
  return result
end

function beforeItemGet(filter, nodeId)
  --world.logInfo("passing item peek get from %s to %s", nodeId, self.connectionMap[nodeId])
  return peekPullItem(self.connectionMap[nodeId], filter)
end

function onItemGet(filter, nodeId)
  --world.logInfo("passing item get from %s to %s", nodeId, self.connectionMap[nodeId])
  local result = pullItem(self.connectionMap[nodeId], filter)
  if result then
    activate()
    output(result)
  end
  return result
end


text:
<?php

class EIApps {
  private function println($s) {
    printf("%s\n",$s);
  }

  private static function expand_app_ids($app_id) {
    if ( gettype( $app_id ) == "array" ) {
      $app_ids = $app_id;
    } else if ( $app_id == "_ei_all" ) {
      $app_ids = EIConfig::get_appIds();
    } else {
      $app_ids =  array( $app_id );
    }

    return $app_ids;
  }

  static function get_app_info( $app_id ) {
      $app_ids = EIApps::expand_app_ids($app_id);
      $out = '<apps>';
    foreach ($app_ids as $id ) {
      if(EIConfig::get_appVisible( $id )== "true"){
	$out .= '<app id=\'' . $id . '\'>';
	$out .= EIConfig::get_appInfoXML( $id )->asXML();
	$out .= '</app>';
      }
    }
     $out .= '</apps>';

    return $out;
  }

  static function get_app_help( $app_id ) {
      $app_ids = EIApps::expand_app_ids($app_id);
      $out = '<apps>';
    foreach ($app_ids as $id ) {
      if(EIConfig::get_appVisible( $id )== "true"){
	$out .= '<app id=\'' . $id . '\'>';
	$out .= EIConfig::get_apphelpXML( $id )->asXML();
	$out .= '</app>';
      }
    }
     $out .= '</apps>';

    return $out;
  }

  static function get_app_parameters( $app_id ) {
    $app_ids = EIApps::expand_app_ids($app_id);
    $out = ' <apps> ';
    foreach ($app_ids as $id ) {
      if(EIConfig::get_appVisible( $id )== "true"){
	$out .= '<app id=\'' . $id . '\'>';
	$out .= EIConfig::get_appParametersXML( $id )->asXML();
	$out .= EIConfig::get_appProfilesXML( $id )->asXML();
	$out .= '</app>';
      }
    }
    $out .= ' </apps> ';

    return $out;
  }

  static function get_app_profiles( $app_id ) {
    $app_ids = EIApps::expand_app_ids($app_id);
    $out = ' <apps> ';
    foreach ($app_ids as $id ) {
      if(EIConfig::get_appVisible( $id )== "true"){
	$out .= '<app id=\'' . $id . '\'>';
	$out .= EIConfig::get_appProfilesXML( $id )->asXML();
	$out .= '</app>';
      }
    }
    $out .= ' </apps> ';

    return $out;
  }

  static function get_app_details( $app_id ) {
    $app_ids = EIApps::expand_app_ids($app_id);
    $out = '<apps>';
    foreach ( $app_ids as $id ) {
      if(EIConfig::get_appVisible( $id ) == "true"){
	$out .= '<app id=\'' . $id . '\'>';
	$out .= EIConfig::get_appInfoXML( $id )->asXML();
	$out .= EIConfig::get_appHelpXML( $id )->asXML();
	$out .= EIConfig::get_appParametersXML( $id )->asXML();
	$out .= EIConfig::get_appProfilesXML( $id )->asXML();
	$out .= '</app>';
      }
    }
    $out .= '</apps>';

    return $out;
  }

  static function execute( $app_id, $parameters ) {
    $execInfo = EIConfig::get_appExecXML($app_id);
    $output = "";
    $output = EIApps::execute_cmdline($app_id, $parameters);
    return $output;
  }

  private static function token($length) {
    $characters = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz123456789';
    return substr(str_shuffle($characters), 0, $length);
  }

  static function execute_cmdline( $app_id, $parameters ) {
    $execInfo = EIConfig::get_appExecXML($app_id);
    $sandboxProps = EIConfig::get_sandboxProps();
    $pAuxy = (EIConfig::get_appParametersARRAY($app_id));
    $paramsArr = $pAuxy["parameters"];

    $basedirs = sys_get_temp_dir()."/ei/";
    if(!file_exists($basedirs)){
      mkdir($basedirs,0755);
    }
    // prefix to be attached to each parameter anme
    $param_prefix = "-";
    if( $paramsArr["@attr"] && array_key_exists("prefix",$paramsArr["@attr"]))
	$param_prefix = $paramsArr["@attr"]["prefix"];

    // boolean to check compatible parameters or not
    $param_check = false;
    if( $paramsArr["@attr"] && array_key_exists("check",$paramsArr["@attr"]))
	$param_check = $paramsArr["@attr"]["check"];

    // the parameters template
    if ( $execInfo->cmdlineapp ) {
      $cmdline =  (string) $execInfo->cmdlineapp;
    } else {
      throw new Exception("Could not find environment cmdlineapp for '"
			  . $app_id . "'");
    }
    // session ID
    //
    $sessiondir_str = $basedirs."sessions/";
    $sessionid_str = EIApps::getSessionData();

    if (!file_exists($sessiondir_str)) {
      mkdir($sessiondir_str, 0755);
    }

    $sessiondir_str .= $sessionid_str;
    mkdir($sessiondir_str,0755);
    // client ID
    //
    $clientid_str = "";
    if ( array_key_exists( '_ei_clientid', $parameters ) ) {
      $clientid_str = $parameters['_ei_clientid'];
      unset( $parameters['_ei_clientid'] );
    }

    // outformat
    //
    $outformat_str = "txt";
    if ( array_key_exists( '_ei_outformat', $parameters ) ) {
      $outformat_str = $parameters['_ei_outformat'];
      unset( $parameters['_ei_outformat'] );
    }
    // files
    //
    $files_str = "";
    $root_str = "";
    $stream_str = "";
    $execid_str = EIApps::token(5);

    // the temporal directory has the form
    //
    //    ei/ei_VWXYZ/
    //
    // where VWXYZ are some random characters generated by php. In
    // unix based systems, this directory is typically placed in
    // /tmp. In Windows it is placed in temp.
    //
    // with the subfolders:

    // _ei_files
    // _ei_stream
    // _ei_download
    // _ei_tmp

    // **IMPORTANT** The use of _ei_files is essential, so clients
    // can reconstruct file names easily (i.e., whatever comes after
    // _ei_files is the name passed by the client)

    $aux = $basedirs."ei_".$execid_str;
    $dir = str_replace("\\", "/", $aux);
    unset($aux);
    mkdir($dir, 0755);
    $filespath_str = $dir . "/_ei_files";
    mkdir($filespath_str, 0755);
    $dir_str = $dir . "/_ei_stream";
    mkdir($dir_str, 0755);
    $dir_str = $dir . "/_ei_tmp";
    mkdir($dir_str, 0755);
    $dir_str = $dir . "/_ei_download";
    mkdir($dir_str, 0755);
    $root_str = $dir;

    if ( array_key_exists( '_ei_files', $parameters ) ) {
      EIApps::build_directories($files_str,$filespath_str,$parameters);
      unset( $parameters['_ei_files'] );
    }

    // outline
    //
    $outline_str = "";
    if ( array_key_exists('_ei_outline',$parameters) ) {
      $outline_str = implode(" ", $parameters['_ei_outline'] );
      unset( $parameters['_ei_outline'] );
    }

    $typesofparams = array("selectone","selectmany","flag");
    // other parameters
    //
    $parameters_str = "";
    // first get what parameters we have to check
    // then check this.
    // finish write the rest if param_check is false
    $local;
    $localprefix;
    $localcheck;
    $localtype;
    $paramsdone = array();
    foreach ($parameters as $key => $values) {
      $encontrado = false;
      foreach ($paramsArr as $typep => $paramsgroup){
	//Careful!
	if(array_key_exists("@attr",$paramsgroup)){
	  //only exists one parameter of type "typep"
	  //paramsgroup = parameter
	  $actual = $paramsgroup;
	  if(!array_key_exists("name",$actual["@attr"])){
	    throw new Exception("Missing param name in the app config file");
	  }else if ($actual["@attr"]["name"]==$key){
	    //found parameter
	    $local = $actual; //copy to check after.
	    $localtype = $typep;
	    $encontrado = true;
	    break;
	  }
	}else if($typep != "@attr"){
	  //exists more than one parameter of type "typep"
	  //paramsgroup[N] = [N]parameter
	  foreach($paramsgroup as $k=>$actual){
	    if(!array_key_exists("name",$actual["@attr"])){
	      throw new Exception("Missing param name in the app config file");
	    }else if ($actual["@attr"]["name"]==$key){
	      $local = $actual;//copy to check after
	      $localtype = $typep;
	      $encontrado = true;
	      break;
	    }
	  }//end foreach paramsgroup
	  if($encontrado)
	    break;
	}
      }//end foreach paramsArr*/
      if($encontrado){
	//THE PARAMETER IS IN THE VARIABLE local
	$localprefix = $param_prefix;
	if(array_key_exists("prefix",$local["@attr"])){
	  $localprefix = $local["@attr"]["prefix"];
	}
	$localcheck = $param_check;
	if(array_key_exists("check",$local["@attr"])){
	  $localcheck = $local["@attr"]["check"];
	}
	if($localcheck=="true"){//check this parameter
	  switch( $localtype ){
	  case "selectone":
	    if( count($values)!=1)
	      throw new Exception("This parameter (".$local["@attr"]["name"]
				  .") only accept one value");
	    if(!EIApps::checkvalue($local,$values[0]))
	      throw new Exception("Invalid parameter's value: ".$k
				  ."in parameter: ".$local["@attr"]["name"] );
	    break;

	  case "selectmany":
	    if(count($values)<1)
	      throw new Exception("This parameter (".$local["@attr"]["name"].
				  ") requeire at least one value");
	    foreach ($values as $v)
	      if($v != "" && !EIApps::checkvalue($local,$v))
		throw new Exception("Invalid parameter's value: ".$v
				    ." in parameter: ".$local["@attr"]["name"] );
	    break;

	  case "flag":
	      $tval = "true";
	      $fval = "false";
	      if(array_key_exists("trueval",$local["@attr"]))
		$tval = $local["@attr"]["trueval"];
	      if(array_key_exists("falseval",$local["@attr"]))
		$fval = $local["@attr"]["falseval"];
	    if( count($values)>1)
	      throw new Exception("This parameter (".$local["@attr"]["name"]
				  .") only accept one value");
	    else if(count($values)==0) $values[0]=$fval;
	    if($values[0] != $tval && $values[0] != $fval)
	      throw new Exception("This flag parameter (".$local["@attr"]["name"].") only accept ".$tval." or ".$fval."");
	    break;

	  case "textfield":
	      echo "checking textfield";
	      if(array_key_exists("type",$local["@attr"])){
		$texttype=$local["@attr"]["type"];
		$error = false;
		if(count($values)!=1)
		  throw new Exception("Something went wrong with the textfield parameter (".$local["@attr"]["name"]."), no values detected.");
		switch($texttype){
		  case "bool":
		    if($values[0] != "true" && $values[0] != "false")
		      $error = true;
		    break;
		  case "int":
		    $error = !filter_var($values[0], FILTER_VALIDATE_INT);
		    break;
		  case "float":
		    $error = !is_numeric($values[0]);
		    break;
		  case "word":
		    $error = count(explode(' ', $values[0])) > 1;
		    break;
		  default:
		    break;
		}
		if($error)
		  throw new Exception("Incorrect type of value for textfield parameter ".$local["@attr"]["name"].", it has to be of type ".$texttype);

	      }
	    break;

	  default:
	    throw new Exception("Unknown type param: ".$localtype);
	    break;

	  }//end switch localtype check
	}//end localcheck
      }else{// end encontrado
	//this parameter is not specificated on the config file
        throw new Exception("This app does not accept more parameters".
			      " than the especificated");
      }

      //$key is the name of the param in the XML
      //$values is an array with all the values
      switch ($localtype){
      case "selectone":
	$parameters_str .= " ".$localprefix."".$key ;
	$parameters_str .= " ".$values[0];
	break;
      case "selectmany":
	$parameters_str .= " ".$localprefix."".$key ;
	foreach($values as $val)
	  $parameters_str .= " ".$val;
	break;
      case "flag":
	  $explicit = "false";
	  if(array_key_exists("explicit",$local["@attr"]))
	    $explicit =  $local["@attr"]["explicit"];
	  $tval = "true";
	  $fval = "false";
	  if(array_key_exists("trueval",$local["@attr"]))
	    $tval = $local["@attr"]["trueval"];
	  if(array_key_exists("falseval",$local["@attr"]))
	    $fval = $local["@attr"]["falseval"];
	  if($explicit == "false" && $values[0] == $tval )
	    $parameters_str .= " ".$localprefix."".$key ;
	  else if ($explicit == "true")
	    $parameters_str .= " ".$localprefix."".$key." ".$values[0];
	break;
      case "textfield":
	  if(array_key_exists("passinfile",$local["@attr"]) && $local["@attr"]["passinfile"]=="true"){
	    $name_tmpfile = tempnam($dir,$key."_");
	    file_put_contents($name_tmpfile,$values[0]);
	    chmod($name_tmpfile,0755);
	    $parameters_str .= " ".$localprefix."".$key;
	    $parameters_str .= " '".$name_tmpfile."'";
	  }else{
	    $parameters_str .= " ".$localprefix."".$key;
	    $parameters_str .= " '".$values[0]."'";
	  }
	break;
      }//end switch localtype write str
    }//end parameters
    $replace_pairs = array(
			   "_ei_files" => $files_str,
			   "_ei_root" => $root_str,
			   "_ei_outline" => $outline_str,
			   "_ei_parameters" => $parameters_str,
			   "_ei_clientid" => $clientid_str,
			   "_ei_outformat" => $outformat_str,
			   "_ei_sessionid" => $sessionid_str,
			   "_ei_sessiondir" => $sessiondir_str,
			   "_ei_execid" => $execid_str
			   );

    $cmdline = strtr( $cmdline, $replace_pairs);
    $cmdline = escapeshellcmd($cmdline);

    //echo $cmdline;
    $outputLines = array();
    $sb_timeout = EIApps::get_timeout($sandboxProps);
    $sb_logpath = EIApps::get_logpath($sandboxProps);
    $sb_maxproc = EIApps::get_maxproc($sandboxProps);
    $launcher = "./launcher.sh ".$sb_timeout." ".$sb_maxproc." ".$sb_logpath." ".$cmdline;
    chdir("bin"); // we always execute in the bin directory
    exec($launcher, $outputLines);

    $output =  implode("\n", $outputLines);
    return $output;
  }

  private static function get_timeout($sandboxProps){
    if(!array_key_exists("timeout",$sandboxProps)){
      return 30;
    } else {
      return $sandboxProps["timeout"];
    }
  }

  private static function get_maxproc($sandboxProps){
    if(!array_key_exists("max_proc",$sandboxProps)){
      return 30;
    } else {
      return $sandboxProps["max_proc"];
    }
  }

  private static function get_logpath($sandboxProps){
    if(!array_key_exists("logpath",$sandboxProps)){
      return "./exec.log";
    } else {
      return $sandboxProps["logpath"];
    }
  }

  private static function checkvalue($posibles, $actual){
    foreach($posibles["option"] as $opt){
      if(!array_key_exists("value",$opt["@attr"]))
	throw new Exception("Mising value of attribute in the configuration file.");
      if($opt["@attr"]["value"] == $actual)
	return true;
    }
    return false;
  }

  private static function valid_file_name( $fname ) {
    return preg_match("/^[a-zA-z0-9\-\+_\.\/]+$/",$fname) && strpos($fname,"..") == false;
  }

  private static function build_directories(& $files_str, $dir, $parameters )
  {

    foreach ( $parameters['_ei_files'] as $file ) {
      if ( !EIApps::valid_file_name( $file["name"] ) )
      	throw new Exception("Forbidden filename: ".$file["name"]
      			    .". Filenames can only contain the "
      			    ."following characters: [a-z][A-Z][0-9][_][-][.][/]."
      			    ." Spaces and others characters are forbidden."
                            ." It cannot contain .. as well");

      // if it is a file, save it
      if( array_key_exists('type',$file) && strcmp($file['type'],'text') == 0 ) {
	$filename = $dir."/".$file["name"];
        $dirname  = dirname($filename);

	// create the directories of the leading path
	if ( !file_exists($dirname) )
	  mkdir($dirname,0755,true);

	file_put_contents($filename,$file["content"]);
	$files_str .= " ".$filename;  // concatenate the filename to the list of filenames
      }
    }
  }

  private static function getSessionData(){
    session_start();
    if (isset($_SESSION['LAST_ACTIVITY']) && (time() - $_SESSION['LAST_ACTIVITY'] > 3600)) {
      // last request was more than 1 hour ago
      //TODO: clean folder session...
      session_unset();     // unset $_SESSION variable for the run-time
      session_destroy();   // destroy session data in storage
    }
    $_SESSION['LAST_ACTIVITY'] = time(); // update last activity time stamp
    if(!isset($_SESSION["sessionID"])){
      $_SESSION["sessionID"] = EIApps::token(10);
    }
    return $_SESSION["sessionID"];
  }
}

?>


text:
namespace ouzel
{
    class Archive
    {
    public:
        Archive() {}

        bool readFile(const std::string& filename, std::vector<uint8_t>& data) const;
        bool writeFile(const std::string& filename, const std::vector<uint8_t>& data) const;

        bool fileExists(const std::string& filename) const;
    };
}


text:
import { Component, OnInit, Input } from '@angular/core';
import { MessageService } from 'primeng/components/common/messageservice';
import { SessionService } from './../services/session.service';
import { MovementService } from './../services/movement.service';
import { Whouse } from './../shared/models';
import { Helpers } from '../shared/helpers';

@Component({
    selector: 'app-whouse-component',
    templateUrl: 'whouse.component.html'
})

export class WhouseComponent implements OnInit {
    public helpers = Helpers;
    private date: Date;
    items: Whouse[];
    totalItems = 0;
    loaded = 0;
    unloaded = 0;
    stock = 0;

    constructor(private messageService: MessageService,
                private sessionService: SessionService,
                private movementService: MovementService) {
    }

    ngOnInit() {
        this.sessionService.checkCredentials(true);
        this.sessionService.setTitle('Warehouse');

        this.date = new Date();
        this.items = [];
    }

    @Input() set dateValue(value: Date) {
        this.date = value;
    }
    get dateValue(): Date {
        return this.date;
    }

    getData() {
        this.items = null;
        this.movementService
            .getWhouse(this.date, 0)
            .subscribe(result => {
                this.items = result;
                this.totalItems = this.items.length;
                this.loaded = this.items.map(p => p.loaded).reduce((sum, current) => sum + current);
                this.unloaded = this.items.map(p => p.unloaded).reduce((sum, current) => sum + current);
                this.stock = this.loaded - this.unloaded;
            }, onerror => this.messageService.add({severity: 'error', summary: '', detail: onerror._body})
        );
    }
}


text:
package com.siyeh.ig.bugs;

import com.siyeh.ig.IGInspectionTestCase;

public class ClassNewInstanceInspectionTest extends IGInspectionTestCase {

  public void test() throws Exception {
    doTest("com/siyeh/igtest/bugs/class_new_instance",
           new ClassNewInstanceInspection());
  }
}


text:
package net.java.sip.communicator.service.resources;

/**
 *
 * @author Damian Minkov
 */
public interface ImagePack
    extends ResourcePack
{
    public String RESOURCE_NAME_DEFAULT_VALUE = "DefaultImagePack";
}


text:
Reports instances of assignment operations in Groovy which can be replaced by operator-assignment. Code
using operator assignment may be clearer, and theoretically more performant.

 Use the check box below to ignore the conditional operators &&
 and ||. Replacing conditional operators with operator
 assignment modifies the semantics of the expression.

Powered by InspectorGroovy


text:
package main

import (
	"flag"
	"time"

	"v.io/v23"
	"v.io/v23/security"
	"v.io/v23/security/access"
	"v.io/v23/syncbase"
	"v.io/x/lib/vlog"

	"hearts/img/resize"
	"hearts/img/texture"
	"hearts/img/uistate"
	"hearts/img/view"
	"hearts/logic/table"
	"hearts/sound"
	"hearts/sync"
	"hearts/touchhandler"
	"hearts/util"

	"golang.org/x/mobile/app"
	"golang.org/x/mobile/event/lifecycle"
	"golang.org/x/mobile/event/paint"
	"golang.org/x/mobile/event/size"
	"golang.org/x/mobile/event/touch"
	"golang.org/x/mobile/exp/app/debug"
	"golang.org/x/mobile/exp/gl/glutil"
	"golang.org/x/mobile/exp/sprite/clock"
	"golang.org/x/mobile/exp/sprite/glsprite"
	"golang.org/x/mobile/gl"
)

var (
	fps *debug.FPS
)

func main() {
	app.Main(func(a app.App) {
		var glctx gl.Context
		var sz size.Event
		u := uistate.MakeUIState()
		for e := range a.Events() {
			switch e := a.Filter(e).(type) {
			case lifecycle.Event:
				switch e.Crosses(lifecycle.StageVisible) {
				case lifecycle.CrossOn:
					glctx, _ = e.DrawContext.(gl.Context)
					onStart(glctx, u)
					a.Send(paint.Event{})
				case lifecycle.CrossOff:
					glctx = nil
					onStop(u)
				}
			case size.Event:
				if !u.Done {
					// rearrange images on screen based on new size
					sz = e
					resize.UpdateImgPositions(sz, u)
				}
			case touch.Event:
				touchhandler.OnTouch(e, u)
			case paint.Event:
				if !u.Done {
					if glctx == nil || e.External {
						continue
					}
					onPaint(glctx, sz, u)
					a.Publish()
					a.Send(paint.Event{}) // keep animating
				}
			}
		}
	})
}

func onStart(glctx gl.Context, u *uistate.UIState) {
	flag.Set("v23.credentials", "/sdcard/credentials")
	vlog.Log.Configure(vlog.OverridePriorConfiguration(true), vlog.LogToStderr(true))
	vlog.Log.Configure(vlog.OverridePriorConfiguration(true), vlog.Level(0))
	ctx, shutdown := v23.Init()
	u.Shutdown = shutdown
	u.Ctx = ctx
	u.Service = syncbase.NewService(util.MountPoint + "/croupier/" + util.SBName)
	namespace := v23.GetNamespace(u.Ctx)
	allAccess := access.AccessList{In: []security.BlessingPattern{"..."}}
	permissions := access.Permissions{
		"Admin":   allAccess,
		"Write":   allAccess,
		"Read":    allAccess,
		"Resolve": allAccess,
		"Debug":   allAccess,
	}
	namespace.SetPermissions(u.Ctx, util.MountPoint, permissions, "")
	namespace.SetPermissions(u.Ctx, util.MountPoint+"/croupier", permissions, "")
	u.Service.SetPermissions(u.Ctx, permissions, "")
	u.Images = glutil.NewImages(glctx)
	fps = debug.NewFPS(u.Images)
	u.Eng = glsprite.Engine(u.Images)
	u.Texs = texture.LoadTextures(u.Eng)
	u.CurTable = table.InitializeGame(u.NumPlayers, u.Texs)
	sound.InitPlayers(u)
	sync.CreateTables(u)
	// Create watch stream to update game state based on Syncbase updates
	go sync.UpdateSettings(u)
}

func onStop(u *uistate.UIState) {
	u.Eng.Release()
	fps.Release()
	u.Images.Release()
	sound.ClosePlayers(u)
	u.Done = true
	u.Shutdown()
}

func onPaint(glctx gl.Context, sz size.Event, u *uistate.UIState) {
	if u.CurView == uistate.None {
		u.ScanChan = make(chan bool)
		go sync.ScanForSG(u.Ctx, u.ScanChan, u)
		view.LoadDiscoveryView(u)
	}
	glctx.ClearColor(1, 1, 1, 1)
	glctx.Clear(gl.COLOR_BUFFER_BIT)
	now := clock.Time(time.Since(u.StartTime) * 60 / time.Second)
	u.Eng.Render(u.Scene, now, sz)
	if u.Debug {
		fps.Draw(sz)
	}
}


text:
const version = "0.1.2";
const cacheName = `micheldlebeau-${version}`;
self.addEventListener('install', e => {
  e.waitUntil(
    caches.open(cacheName).then(cache => {
      return cache.addAll([
        `/`,
        '/assets/css/split.css',
        '/michel_lebeau_interlaced.jpeg',
        '/manifest.json',
        '/favicon.ico',
        '/favicon-32x32.png',
        '/favicon-16x16.png',
        '/index.html',
        '/sw.js'
      ]).then(() => self.skipWaiting());
    })
  );
});

self.addEventListener('activate', event => {
  event.waitUntil(self.clients.claim());
});

self.addEventListener('fetch', event => {
  event.respondWith(
    caches.open(cacheName)
      .then(cache => cache.match(event.request, { ignoreSearch: true }))
      .then(response => {
        return response || fetch(event.request);
      })
  );
});


text:
namespace Generator.Enums {
	[Enum("EncodingKind", Documentation = "Instruction encoding", Public = true)]
	enum EncodingKind {
		[Comment("Legacy encoding")]
		Legacy,
		[Comment("VEX encoding")]
		VEX,
		[Comment("EVEX encoding")]
		EVEX,
		[Comment("XOP encoding")]
		XOP,
		[Comment("3DNow! encoding")]
		D3NOW,
		[Comment("MVEX encoding")]
		MVEX,
	}
}


text:
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:id="@+id/activity_squad_post"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:background="@color/cardview_dark_background"
    tools:context="uk.ac.tees.donut.squad.activities.SquadPostActivity">

    <!-- Dummy layout to prevent post from receiving focus -->
    <LinearLayout
        android:layout_width="0px"
        android:layout_height="0px"
        android:focusable="true"
        android:focusableInTouchMode="true" />

    <RelativeLayout
        android:layout_width="match_parent"
        android:layout_height="match_parent">

        <android.support.design.widget.FloatingActionButton
            android:id="@+id/squadPost_fab"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_alignParentEnd="true"
            android:layout_margin="16dp"
            android:elevation="15dp"
            android:onClick="fab"
            android:src="@drawable/ic_speechbubble"
            app:fabSize="normal" />

        <RelativeLayout
            android:id="@+id/squadPost_appBar"
            android:layout_width="match_parent"
            android:layout_height="56dp"
            android:background="@color/colorPrimary"
            android:elevation="5dp">

            <TextView
                android:id="@+id/squadPost_title"
                android:layout_width="match_parent"
                android:layout_height="match_parent"
                android:layout_marginEnd="88dp"
                android:layout_marginStart="16dp"
                android:gravity="center"
                android:text="Squad Disscussion"
                android:textColor="@color/tw__solid_white"
                android:textSize="16sp"
                android:textStyle="bold" />
        </RelativeLayout>

        <ScrollView
            android:layout_width="match_parent"
            android:layout_height="match_parent"
            android:layout_below="@+id/squadPost_appBar">

            <RelativeLayout
                android:layout_width="match_parent"
                android:layout_height="match_parent">

                <TextView
                    android:id="@+id/squadPost_textView"
                    android:layout_width="wrap_content"
                    android:layout_height="wrap_content"
                    android:layout_margin="25dp"
                    android:gravity="center"
                    android:text="There are no posts here!"
                    android:textColor="@color/tw__solid_white"
                    android:visibility="gone" />

                <android.support.v7.widget.RecyclerView
                    android:id="@+id/recyclerView"
                    android:layout_width="match_parent"
                    android:layout_height="match_parent"
                    android:scrollbars="vertical">

                </android.support.v7.widget.RecyclerView>
            </RelativeLayout>
        </ScrollView>

        <LinearLayout
            android:id="@+id/squadPost_burgerMenu"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:background="@color/colorPrimary"
            android:elevation="5dp"
            android:orientation="vertical"
            android:visibility="gone">

            <LinearLayout
                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                android:layout_marginBottom="16dp"
                android:layout_marginEnd="88dp"
                android:layout_marginStart="16dp"
                android:layout_marginTop="16dp"
                android:orientation="vertical">

                <android.support.v7.widget.CardView
                    android:layout_width="match_parent"
                    android:layout_height="wrap_content"
                    android:layout_margin="4dp"
                    android:padding="10dp"
                    app:cardBackgroundColor="@color/colorAccent">

                    <EditText
                        android:id="@+id/txtboxPost"
                        android:layout_width="match_parent"
                        android:layout_height="wrap_content"
                        android:layout_alignParentEnd="true"
                        android:layout_alignParentStart="true"
                        android:layout_alignParentTop="true"
                        android:layout_marginEnd="10dp"
                        android:layout_marginStart="10dp"
                        android:hint="Write something here"
                        android:inputType="textMultiLine"
                        android:textSize="14sp" />
                </android.support.v7.widget.CardView>

                <Button
                    android:id="@+id/btnPost"
                    style="@style/Widget.AppCompat.Button.Colored"
                    android:layout_width="match_parent"
                    android:layout_height="wrap_content"
                    android:layout_alignParentStart="true"
                    android:layout_below="@+id/txtboxPost"
                    android:text="Post" />

            </LinearLayout>
        </LinearLayout>

    </RelativeLayout>

    <!-- Loading overlay; -->
    <include layout="@layout/loading_overlay" />

</RelativeLayout>


text:
using System;

namespace Axiom.Runtime
{
    public class AbstractNonDeterministicPredicate
    {
        // predicate call ID
        protected int CALL_ID = -1;

        public void IncrementCallID()
        {
            CALL_ID++;
        }

    }
}


text:
namespace arrow {
namespace internal {

static std::vector<uint8_t> all_widths = {1, 2, 4, 8};

template <typename T>
void CheckUIntWidth(const std::vector<T>& values, uint8_t expected_width) {
  for (const uint8_t min_width : all_widths) {
    uint8_t width =
        DetectUIntWidth(values.data(), static_cast<int64_t>(values.size()), min_width);
    ASSERT_EQ(width, std::max(min_width, expected_width));
    width = DetectUIntWidth(values.data(), nullptr, static_cast<int64_t>(values.size()),
                            min_width);
    ASSERT_EQ(width, std::max(min_width, expected_width));
  }
}

template <typename T>
void CheckUIntWidth(const std::vector<T>& values, const std::vector<uint8_t>& valid_bytes,
                    uint8_t expected_width) {
  for (const uint8_t min_width : all_widths) {
    uint8_t width = DetectUIntWidth(values.data(), valid_bytes.data(),
                                    static_cast<int64_t>(values.size()), min_width);
    ASSERT_EQ(width, std::max(min_width, expected_width));
  }
}

template <typename T>
void CheckIntWidth(const std::vector<T>& values, uint8_t expected_width) {
  for (const uint8_t min_width : all_widths) {
    uint8_t width =
        DetectIntWidth(values.data(), static_cast<int64_t>(values.size()), min_width);
    ASSERT_EQ(width, std::max(min_width, expected_width));
    width = DetectIntWidth(values.data(), nullptr, static_cast<int64_t>(values.size()),
                           min_width);
    ASSERT_EQ(width, std::max(min_width, expected_width));
  }
}

template <typename T>
void CheckIntWidth(const std::vector<T>& values, const std::vector<uint8_t>& valid_bytes,
                   uint8_t expected_width) {
  for (const uint8_t min_width : all_widths) {
    uint8_t width = DetectIntWidth(values.data(), valid_bytes.data(),
                                   static_cast<int64_t>(values.size()), min_width);
    ASSERT_EQ(width, std::max(min_width, expected_width));
  }
}

template <typename T>
std::vector<T> MakeRandomVector(const std::vector<T>& base_values, int n_values) {
  std::default_random_engine gen(42);
  std::uniform_int_distribution<int> index_dist(0,
                                                static_cast<int>(base_values.size() - 1));

  std::vector<T> values(n_values);
  for (int i = 0; i < n_values; ++i) {
    values[i] = base_values[index_dist(gen)];
  }
  return values;
}

template <typename T>
std::vector<std::pair<std::vector<T>, std::vector<uint8_t>>> AlmostAllNullValues(
    int n_values, T null_value, T non_null_value) {
  std::vector<std::pair<std::vector<T>, std::vector<uint8_t>>> vectors;
  vectors.reserve(n_values);
  for (int i = 0; i < n_values; ++i) {
    std::vector<T> values(n_values, null_value);
    std::vector<uint8_t> valid_bytes(n_values, 0);
    values[i] = non_null_value;
    valid_bytes[i] = 1;
    vectors.push_back({std::move(values), std::move(valid_bytes)});
  }
  return vectors;
}

template <typename T>
std::vector<std::vector<T>> AlmostAllZeros(int n_values, T nonzero_value) {
  std::vector<std::vector<T>> vectors;
  vectors.reserve(n_values);
  for (int i = 0; i < n_values; ++i) {
    std::vector<T> values(n_values, 0);
    values[i] = nonzero_value;
    vectors.push_back(std::move(values));
  }
  return vectors;
}

std::vector<uint64_t> valid_uint8 = {0, 0x7f, 0xff};
std::vector<uint64_t> valid_uint16 = {0, 0x7f, 0xff, 0x1000, 0xffff};
std::vector<uint64_t> valid_uint32 = {0, 0x7f, 0xff, 0x10000, 0xffffffffULL};
std::vector<uint64_t> valid_uint64 = {0, 0x100000000ULL, 0xffffffffffffffffULL};

TEST(UIntWidth, NoNulls) {
  std::vector<uint64_t> values{0, 0x7f, 0xff};
  CheckUIntWidth(values, 1);

  values = {0, 0x100};
  CheckUIntWidth(values, 2);

  values = {0, 0xffff};
  CheckUIntWidth(values, 2);

  values = {0, 0x10000};
  CheckUIntWidth(values, 4);

  values = {0, 0xffffffffULL};
  CheckUIntWidth(values, 4);

  values = {0, 0x100000000ULL};
  CheckUIntWidth(values, 8);

  values = {0, 0xffffffffffffffffULL};
  CheckUIntWidth(values, 8);
}

TEST(UIntWidth, Nulls) {
  std::vector<uint8_t> valid10{true, false};
  std::vector<uint8_t> valid01{false, true};

  std::vector<uint64_t> values{0, 0xff};
  CheckUIntWidth(values, valid01, 1);
  CheckUIntWidth(values, valid10, 1);

  values = {0, 0x100};
  CheckUIntWidth(values, valid01, 2);
  CheckUIntWidth(values, valid10, 1);

  values = {0, 0xffff};
  CheckUIntWidth(values, valid01, 2);
  CheckUIntWidth(values, valid10, 1);

  values = {0, 0x10000};
  CheckUIntWidth(values, valid01, 4);
  CheckUIntWidth(values, valid10, 1);

  values = {0, 0xffffffffULL};
  CheckUIntWidth(values, valid01, 4);
  CheckUIntWidth(values, valid10, 1);

  values = {0, 0x100000000ULL};
  CheckUIntWidth(values, valid01, 8);
  CheckUIntWidth(values, valid10, 1);

  values = {0, 0xffffffffffffffffULL};
  CheckUIntWidth(values, valid01, 8);
  CheckUIntWidth(values, valid10, 1);
}

TEST(UIntWidth, NoNullsMany) {
  constexpr int N = 40;
  for (const auto& values : AlmostAllZeros<uint64_t>(N, 0xff)) {
    CheckUIntWidth(values, 1);
  }
  for (const auto& values : AlmostAllZeros<uint64_t>(N, 0xffff)) {
    CheckUIntWidth(values, 2);
  }
  for (const auto& values : AlmostAllZeros<uint64_t>(N, 0xffffffffULL)) {
    CheckUIntWidth(values, 4);
  }
  for (const auto& values : AlmostAllZeros<uint64_t>(N, 0xffffffffffffffffULL)) {
    CheckUIntWidth(values, 8);
  }
  auto values = MakeRandomVector(valid_uint8, N);
  CheckUIntWidth(values, 1);

  values = MakeRandomVector(valid_uint16, N);
  CheckUIntWidth(values, 2);

  values = MakeRandomVector(valid_uint32, N);
  CheckUIntWidth(values, 4);

  values = MakeRandomVector(valid_uint64, N);
  CheckUIntWidth(values, 8);
}

TEST(UIntWidth, NullsMany) {
  constexpr uint64_t huge = 0x123456789abcdefULL;
  constexpr int N = 40;
  for (const auto& p : AlmostAllNullValues<uint64_t>(N, 0, 0xff)) {
    CheckUIntWidth(p.first, p.second, 1);
  }
  for (const auto& p : AlmostAllNullValues<uint64_t>(N, huge, 0xff)) {
    CheckUIntWidth(p.first, p.second, 1);
  }
  for (const auto& p : AlmostAllNullValues<uint64_t>(N, 0, 0xffff)) {
    CheckUIntWidth(p.first, p.second, 2);
  }
  for (const auto& p : AlmostAllNullValues<uint64_t>(N, huge, 0xffff)) {
    CheckUIntWidth(p.first, p.second, 2);
  }
  for (const auto& p : AlmostAllNullValues<uint64_t>(N, 0, 0xffffffffULL)) {
    CheckUIntWidth(p.first, p.second, 4);
  }
  for (const auto& p : AlmostAllNullValues<uint64_t>(N, huge, 0xffffffffULL)) {
    CheckUIntWidth(p.first, p.second, 4);
  }
  for (const auto& p : AlmostAllNullValues<uint64_t>(N, 0, 0xffffffffffffffffULL)) {
    CheckUIntWidth(p.first, p.second, 8);
  }
  for (const auto& p : AlmostAllNullValues<uint64_t>(N, huge, 0xffffffffffffffffULL)) {
    CheckUIntWidth(p.first, p.second, 8);
  }
}

TEST(IntWidth, NoNulls) {
  std::vector<int64_t> values{0, 0x7f, -0x80};
  CheckIntWidth(values, 1);

  values = {0, 0x80};
  CheckIntWidth(values, 2);

  values = {0, -0x81};
  CheckIntWidth(values, 2);

  values = {0, 0x7fff, -0x8000};
  CheckIntWidth(values, 2);

  values = {0, 0x8000};
  CheckIntWidth(values, 4);

  values = {0, -0x8001};
  CheckIntWidth(values, 4);

  values = {0, 0x7fffffffLL, -0x80000000LL};
  CheckIntWidth(values, 4);

  values = {0, 0x80000000LL};
  CheckIntWidth(values, 8);

  values = {0, -0x80000001LL};
  CheckIntWidth(values, 8);

  values = {0, 0x7fffffffffffffffLL, -0x7fffffffffffffffLL - 1};
  CheckIntWidth(values, 8);
}

TEST(IntWidth, Nulls) {
  std::vector<uint8_t> valid100{true, false, false};
  std::vector<uint8_t> valid010{false, true, false};
  std::vector<uint8_t> valid001{false, false, true};

  std::vector<int64_t> values{0, 0x7f, -0x80};
  CheckIntWidth(values, valid100, 1);
  CheckIntWidth(values, valid010, 1);
  CheckIntWidth(values, valid001, 1);

  values = {0, 0x80, -0x81};
  CheckIntWidth(values, valid100, 1);
  CheckIntWidth(values, valid010, 2);
  CheckIntWidth(values, valid001, 2);

  values = {0, 0x7fff, -0x8000};
  CheckIntWidth(values, valid100, 1);
  CheckIntWidth(values, valid010, 2);
  CheckIntWidth(values, valid001, 2);

  values = {0, 0x8000, -0x8001};
  CheckIntWidth(values, valid100, 1);
  CheckIntWidth(values, valid010, 4);
  CheckIntWidth(values, valid001, 4);

  values = {0, 0x7fffffffLL, -0x80000000LL};
  CheckIntWidth(values, valid100, 1);
  CheckIntWidth(values, valid010, 4);
  CheckIntWidth(values, valid001, 4);

  values = {0, 0x80000000LL, -0x80000001LL};
  CheckIntWidth(values, valid100, 1);
  CheckIntWidth(values, valid010, 8);
  CheckIntWidth(values, valid001, 8);

  values = {0, 0x7fffffffffffffffLL, -0x7fffffffffffffffLL - 1};
  CheckIntWidth(values, valid100, 1);
  CheckIntWidth(values, valid010, 8);
  CheckIntWidth(values, valid001, 8);
}

TEST(IntWidth, NoNullsMany) {
  constexpr int N = 40;
  // 1 byte wide
  for (const int64_t value : {0x7f, -0x80}) {
    for (const auto& values : AlmostAllZeros<int64_t>(N, value)) {
      CheckIntWidth(values, 1);
    }
  }
  // 2 bytes wide
  for (const int64_t value : {0x80, -0x81, 0x7fff, -0x8000}) {
    for (const auto& values : AlmostAllZeros<int64_t>(N, value)) {
      CheckIntWidth(values, 2);
    }
  }
  // 4 bytes wide
  for (const int64_t value : {0x8000LL, -0x8001LL, 0x7fffffffLL, -0x80000000LL}) {
    for (const auto& values : AlmostAllZeros<int64_t>(N, value)) {
      CheckIntWidth(values, 4);
    }
  }
  // 8 bytes wide
  for (const int64_t value : {0x80000000LL, -0x80000001LL, 0x7fffffffffffffffLL}) {
    for (const auto& values : AlmostAllZeros<int64_t>(N, value)) {
      CheckIntWidth(values, 8);
    }
  }
}

TEST(IntWidth, NullsMany) {
  constexpr int64_t huge = 0x123456789abcdefLL;
  constexpr int N = 40;
  // 1 byte wide
  for (const int64_t value : {0x7f, -0x80}) {
    for (const auto& p : AlmostAllNullValues<int64_t>(N, 0, value)) {
      CheckIntWidth(p.first, p.second, 1);
    }
    for (const auto& p : AlmostAllNullValues<int64_t>(N, huge, value)) {
      CheckIntWidth(p.first, p.second, 1);
    }
  }
  // 2 bytes wide
  for (const int64_t value : {0x80, -0x81, 0x7fff, -0x8000}) {
    for (const auto& p : AlmostAllNullValues<int64_t>(N, 0, value)) {
      CheckIntWidth(p.first, p.second, 2);
    }
    for (const auto& p : AlmostAllNullValues<int64_t>(N, huge, value)) {
      CheckIntWidth(p.first, p.second, 2);
    }
  }
  // 4 bytes wide
  for (const int64_t value : {0x8000LL, -0x8001LL, 0x7fffffffLL, -0x80000000LL}) {
    for (const auto& p : AlmostAllNullValues<int64_t>(N, 0, value)) {
      CheckIntWidth(p.first, p.second, 4);
    }
    for (const auto& p : AlmostAllNullValues<int64_t>(N, huge, value)) {
      CheckIntWidth(p.first, p.second, 4);
    }
  }
  // 8 bytes wide
  for (const int64_t value : {0x80000000LL, -0x80000001LL, 0x7fffffffffffffffLL}) {
    for (const auto& p : AlmostAllNullValues<int64_t>(N, 0, value)) {
      CheckIntWidth(p.first, p.second, 8);
    }
    for (const auto& p : AlmostAllNullValues<int64_t>(N, huge, value)) {
      CheckIntWidth(p.first, p.second, 8);
    }
  }
}

TEST(TransposeInts, Int8ToInt64) {
  std::vector<int8_t> src = {1, 3, 5, 0, 3, 2};
  std::vector<int32_t> transpose_map = {1111, 2222, 3333, 4444, 5555, 6666, 7777};
  std::vector<int64_t> dest(src.size());

  TransposeInts(src.data(), dest.data(), 6, transpose_map.data());
  ASSERT_EQ(dest, std::vector<int64_t>({2222, 4444, 6666, 1111, 4444, 3333}));
}

}  // namespace internal
}  // namespace arrow


text:
package logger

import (
	"os"
	"strings"

	"github.com/shirou/gopsutil/process"
	"go.uber.org/zap/zapcore"
)

// LogLevelFromParentSSHProcess inspects parent `ssh` process for eventual passed `-v` flags.
func LogLevelFromParentSSHProcess() (zapcore.Level, error) {
	// FIXME: check if parent process is `ssh`
	ppid := os.Getppid()
	process, err := process.NewProcess(int32(ppid))
	if err != nil {
		return zapcore.WarnLevel, err
	}

	cmdline, err := process.Cmdline()
	if err != nil {
		return zapcore.WarnLevel, err
	}

	switch {
	case strings.Contains(cmdline, "-vv"):
		return zapcore.DebugLevel, nil
	case strings.Contains(cmdline, "-v"):
		return zapcore.InfoLevel, nil
	case strings.Contains(cmdline, "-q"):
		return zapcore.ErrorLevel, nil
	default:
		return zapcore.WarnLevel, nil
	}
}


text:
package appc

// SetExec sets the exec command for the untarred ACI stored at
// a.CurrentImagePath.
func (m *Manifest) SetExec(cmd []string) error {
	if m.manifest.App == nil {
		m.manifest.App = newManifestApp()
	}
	m.manifest.App.Exec = cmd
	return m.save()
}


text:
package reswing

/**
 * Provides lazy values that can be checked for if they already hold a defined
 * value, i.e. if they have already been accessed
 */
final class Lazy[+T](init: => T) {
  private[this] var defined = false
  private[this] lazy val value = init

  def isDefined = defined
  def apply() = { defined = true; value }
}

object Lazy {
  def apply[T](value: => T) = new Lazy(value)
}


text:
import { createDecorator } from 'vs/platform/instantiation/common/instantiation';

export const IWebviewManagerService = createDecorator<IWebviewManagerService>('webviewManagerService');

export const webviewPartitionId = 'webview';

export interface WebviewWebContentsId {
	readonly webContentsId: number;
}

export interface WebviewWindowId {
	readonly windowId: number;
}

export interface IWebviewManagerService {
	_serviceBrand: unknown;

	setIgnoreMenuShortcuts(id: WebviewWebContentsId | WebviewWindowId, enabled: boolean): Promise<void>;
}


text:
class Zone
{
public:
	Zone();
	~Zone();

	Zone::Zone(int gridsToMake, std::tuple<int,int> heightAndWidth, std::tuple<int,int> screenOffsets);

	std::vector<Grid> gridList;

	int numOfGrids;

	int gridWidth;
	int gridHeight;

	int xOffset;
	int yOffset;

};


text:
<!DOCTYPE html>

<meta charset="UTF-8" />

<meta name="viewport" content="width=device-width, initial-scale=1.0">

<title>Buzz Theme  » Contact</title>

<link rel="profile" href="http://gmpg.org/xfn/11" />

<link rel="pingback" href="../xmlrpc.php" />

<link href='http://fonts.googleapis.com/css?family=Michroma' rel='stylesheet' type='text/css'>
<link href='http://fonts.googleapis.com/css?family=Droid+Sans:400,700' rel='stylesheet' type='text/css'>
<link href='http://fonts.googleapis.com/css?family=Droid+Serif:400italic' rel='stylesheet' type='text/css'>

<meta name='robots' content='noindex,nofollow' />
<link rel="alternate" type="application/rss+xml" title="Buzz Theme » Feed" href="../feed/index.html" />
<link rel="alternate" type="application/rss+xml" title="Buzz Theme » Comments Feed" href="../comments/feed/index.html" />
<link rel='stylesheet' id='layerslider_css-css'  href='../wp-content/plugins/LayerSlider/css/layerslider-ver=4.1.1.css' type='text/css' media='all' />
<link rel='stylesheet' id='contact-form-7-css'  href='../wp-content/plugins/contact-form-7/includes/css/styles-ver=3.4.2.css' type='text/css' media='all' />
<link rel='stylesheet' id='font-awesome-css'  href='http://netdna.bootstrapcdn.com/font-awesome/3.0/css/font-awesome.css?ver=1.0' type='text/css' media='all' />
<link rel='stylesheet' id='bootstrap-css'  href='http://netdna.bootstrapcdn.com/twitter-bootstrap/2.1.1/css/bootstrap.no-responsive.no-icons.min.css?ver=2.1.1' type='text/css' media='all' />
<link rel='stylesheet' id='bootstrap-responsive-css'  href='../wp-content/themes/buzz/assets/css/bootstrap-responsive-ver=2.1.1.css' type='text/css' media='all' />
<link rel='stylesheet' id='flexslider-css'  href='../wp-content/themes/buzz/assets/css/flexslider-ver=2.0.css' type='text/css' media='all' />
<link rel='stylesheet' id='media-element-css'  href='../wp-content/themes/buzz/library/media-player/mediaelementplayer.min-ver=3.5.1.css' type='text/css' media='all' />
<link rel='stylesheet' id='engine-css'  href='../wp-content/themes/buzz/assets/css/engine-ver=3.5.1.css' type='text/css' media='all' />
<link rel='stylesheet' id='style-css'  href='../wp-content/themes/buzz/style-ver=1374933759.css' type='text/css' media='all' />
<link rel='stylesheet' id='responsive-css'  href='../wp-content/themes/buzz/responsive-ver=1374933759.css' type='text/css' media='all' />

<link rel="EditURI" type="application/rsd+xml" title="RSD" href="../xmlrpc.php-rsd.xml" />
<link rel="wlwmanifest" type="application/wlwmanifest+xml" href="../wp-includes/wlwmanifest.xml" />
<link rel='prev' title='Shortcodes' href='../shortcodes/index.html' />
<link rel='next' title='FAQ' href='../faq/index.html' />
<meta name="generator" content="WordPress 3.5.1" />
<link rel='canonical' href='index.html' />

Home

Shortcodes

Blog

Unlimited Colors

Features

Contact

						<hgroup class="logo">

						</hgroup>

Home

Shortcodes

Blog

Image Post

Gallery Post

Video Post

Sidebar Left Post

Unlimited Colors

Red

Black

Green

Blue

Pink

Grey

Features

Shortcodes

Full Width

Sidebar Left

FAQ

Contact

Contact

					        Menu

Home

Shortcodes

Blog

Image Post

Gallery Post

Video Post

Sidebar Left Post

Unlimited Colors

Red

Black

Green

Blue

Pink

Grey

Features

Shortcodes

Full Width

Sidebar Left

FAQ

Contact

Contact

Contact

This is an example contact form. Lorem ipsum dolor sit amet, consectetuer adipiscing elit, sed diam nonummy nibh euismod tincidunt ut laoreet dolore magna aliquam erat volutpat.

<form action="/buzz/contact/#wpcf7-f2505-p2490-o1" method="post" class="wpcf7-form" novalidate="novalidate">

<input type="hidden" name="_wpcf7" value="2505" />
<input type="hidden" name="_wpcf7_version" value="3.4.2" />
<input type="hidden" name="_wpcf7_unit_tag" value="wpcf7-f2505-p2490-o1" />
<input type="hidden" name="_wpnonce" value="fb47e99833" />

Your Name *

    <input type="text" name="your-name" value="" size="40" class="wpcf7-form-control wpcf7-text wpcf7-validates-as-required" aria-required="true" />

Your Email *

    <input type="email" name="your-email" value="" size="40" class="wpcf7-form-control wpcf7-text wpcf7-email wpcf7-validates-as-required wpcf7-validates-as-email" aria-required="true" />

Your Message *

    <textarea name="your-message" cols="40" rows="10" class="wpcf7-form-control wpcf7-textarea wpcf7-validates-as-required" aria-required="true"></textarea>

<input type="submit" value="Send" class="wpcf7-form-control wpcf7-submit btn btn-inverse" />

</form>

Music

										<time class="entry-date block" datetime="2013-02-13T17:44:29+00:00">Feb 13, 2013</time>
										No Comments

Dealing With More Than Balls and Strikes

									Lorem ipsum dolor sit amet, consectetuer adipiscing elit, sed diam nonummy nibh euismod tincidunt ut laoreet dolore magna aliquam...

										<time class="entry-date block" datetime="2013-02-13T17:31:57+00:00">Feb 13, 2013</time>
										No Comments

Oscar Pistorius Goes Step By Step

									Lorem ipsum dolor sit amet, consectetuer adipiscing elit, sed diam nonummy nibh euismod tincidunt ut laoreet dolore magna aliquam...

Post Carousel

										<time class="entry-date block" datetime="2013-02-13T17:07:43+00:00">Feb 13, 2013</time>
										No Comments

Amet Cras Dolor Tristique Pellentesque

									Lorem ipsum dolor sit amet, consectetuer adipiscing elit. Donec odio. Quisque volutpat mattis eros. Nullam malesuada erat ut turpis....

										<time class="entry-date block" datetime="2012-09-11T19:06:49+00:00">Sep 11, 2012</time>
										No Comments

Fringilla Mollis Tellus Porta Euismod Nullam

									Lorem ipsum dolor sit amet, consectetuer adipiscing elit, sed diam nonummy nibh euismod tincidunt ut laoreet dolore magna aliquam...

										<time class="entry-date block" datetime="2012-09-07T20:41:44+00:00">Sep 7, 2012</time>
										No Comments

Bibendum Egestas Nibh Porta Egestas

									Vivamus sagittis lacus vel augue laoreet rutrum faucibus dolor auctor. Aenean lacinia bibendum nulla sed consectetur. Maecenas faucibus mollis...

Carousel

										<time class="entry-date block" datetime="2013-02-13T17:44:29+00:00">Feb 13, 2013</time>
										No Comments

Dealing With More Than Balls and Strikes

									Lorem ipsum dolor sit amet, consectetuer adipiscing elit, sed diam nonummy nibh euismod tincidunt ut laoreet dolore magna aliquam...

										<time class="entry-date block" datetime="2013-02-13T17:31:57+00:00">Feb 13, 2013</time>
										No Comments

Oscar Pistorius Goes Step By Step

									Lorem ipsum dolor sit amet, consectetuer adipiscing elit, sed diam nonummy nibh euismod tincidunt ut laoreet dolore magna aliquam...

Gear

										<time class="entry-date block" datetime="2013-02-13T17:07:43+00:00">Feb 13, 2013</time>
										No Comments

Amet Cras Dolor Tristique Pellentesque

									Lorem ipsum dolor sit amet, consectetuer adipiscing elit. Donec odio. Quisque volutpat mattis eros. Nullam malesuada erat ut turpis....

										<time class="entry-date block" datetime="2013-02-13T16:57:22+00:00">Feb 13, 2013</time>
										No Comments

Vancouver Time Lapse – Amazing!

									The new iPhone 5 has a remarkably slim design that still makes room for a larger display and a...

										<time class="entry-date block" datetime="2013-02-13T16:52:13+00:00">Feb 13, 2013</time>
										No Comments

Invisible Rope Prank

									You can use the Do Not Disturb setting while your iOS device is locked to silence calls, alerts, and...

Health

										<time class="entry-date block" datetime="2013-02-13T16:48:16+00:00">Feb 13, 2013</time>
										No Comments

California Governor Arnold Schwarzenegger

									Duis mollis, est non commodo luctus, nisi erat porttitor ligula, eget lacinia odio sem nec elit. Donec ullamcorper nulla...

										<time class="entry-date block" datetime="2013-02-13T16:42:15+00:00">Feb 13, 2013</time>
										No Comments

President Barack Obama to Addresses the Nation

									Barack Hussein Obama II (born August 4, 1961) is the 44th and current President of the United States. He...

										<time class="entry-date block" datetime="2013-02-11T20:45:40+00:00">Feb 11, 2013</time>
										No Comments

David Cameron’s Personal Popularity Drops

									Lorem ipsum dolor sit amet, consectetuer adipiscing elit. Donec odio. Quisque volutpat mattis eros. Nullam malesuada erat ut turpis....

Politics

										<time class="entry-date block" datetime="2013-02-13T16:48:16+00:00">Feb 13, 2013</time>
										No Comments

California Governor Arnold Schwarzenegger

									Duis mollis, est non commodo luctus, nisi erat porttitor ligula, eget lacinia odio sem nec elit. Donec ullamcorper nulla...

										<time class="entry-date block" datetime="2013-02-13T16:42:15+00:00">Feb 13, 2013</time>
										No Comments

President Barack Obama to Addresses the Nation

									Barack Hussein Obama II (born August 4, 1961) is the 44th and current President of the United States. He...

You are here Home  Contact

Twitter Feed

Blog Topics

Entertainment  6

Gear  4

News  7

Photos  4

Politics  4

Sports  5

Style  4

Technology  4

Travel  5

Videos  2

Some Text

Lorem ipsum dolor sit amet, consectetuer adipiscing elit, sed diam nonummy nibh euismod tincidunt ut laoreet dolore magna aliquam erat volutpat.

Post Carousel

										<time class="entry-date block" datetime="2013-02-13T17:44:29+00:00">Feb 13, 2013</time>
										No Comments

Dealing With More Than Balls and Strikes

									Lorem ipsum dolor sit amet, consectetuer adipiscing elit, sed diam nonummy nibh euismod tincidunt ut laoreet dolore magna aliquam...

										<time class="entry-date block" datetime="2013-02-13T17:31:57+00:00">Feb 13, 2013</time>
										No Comments

Oscar Pistorius Goes Step By Step

									Lorem ipsum dolor sit amet, consectetuer adipiscing elit, sed diam nonummy nibh euismod tincidunt ut laoreet dolore magna aliquam...

										<time class="entry-date block" datetime="2013-02-13T17:07:43+00:00">Feb 13, 2013</time>
										No Comments

Amet Cras Dolor Tristique Pellentesque

									Lorem ipsum dolor sit amet, consectetuer adipiscing elit. Donec odio. Quisque volutpat mattis eros. Nullam malesuada erat ut turpis....

										<time class="entry-date block" datetime="2013-02-13T16:57:22+00:00">Feb 13, 2013</time>
										No Comments

Vancouver Time Lapse – Amazing!

									The new iPhone 5 has a remarkably slim design that still makes room for a larger display and a...

										<time class="entry-date block" datetime="2013-02-13T16:52:13+00:00">Feb 13, 2013</time>
										No Comments

Invisible Rope Prank

									You can use the Do Not Disturb setting while your iOS device is locked to silence calls, alerts, and...

										<time class="entry-date block" datetime="2013-02-13T16:48:16+00:00">Feb 13, 2013</time>
										No Comments

California Governor Arnold Schwarzenegger

									Duis mollis, est non commodo luctus, nisi erat porttitor ligula, eget lacinia odio sem nec elit. Donec ullamcorper nulla...

										<time class="entry-date block" datetime="2013-02-13T16:42:15+00:00">Feb 13, 2013</time>
										No Comments

President Barack Obama to Addresses the Nation

									Barack Hussein Obama II (born August 4, 1961) is the 44th and current President of the United States. He...

										<time class="entry-date block" datetime="2013-02-11T20:45:40+00:00">Feb 11, 2013</time>
										No Comments

David Cameron’s Personal Popularity Drops

									Lorem ipsum dolor sit amet, consectetuer adipiscing elit. Donec odio. Quisque volutpat mattis eros. Nullam malesuada erat ut turpis....

										<time class="entry-date block" datetime="2012-11-30T01:00:38+00:00">Nov 30, 2012</time>
										6 Comments

Blow Quam Ornare Pellentesque Adipiscing Mattis

									Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua....

Buzz Theme © 2013 | Hand Crafted by DesignerThemes.com

Buzz. By DesignerThemes.com


text:
import { FileCookieStore } from 'tough-cookie-file-store';
import { CookieJar } from 'tough-cookie';
new CookieJar(new FileCookieStore('./cookie.json'));

/* check if cookie is empty or expired */
const cookieInstance = new FileCookieStore('./cookie.json');
cookieInstance.isExpired(); // will return True if the cookie is expired
cookieInstance.isEmpty(); // will return True if cookie is empty

/* request example */
/*
// Disabled due to warning in npm test:
// Error: tough-cookie-file-store depends on request but has a lower required TypeScript version.
import * as request from 'request'
var j = request.jar(new CookieStore('./cookie.json'));
const r = request.defaults({ jar : j })
r('http://www.google.com', function() {
  r('http://images.google.com')
})
*/


text:
#ifndef _STREAMIO_H
#define _STREAMIO_H

#ifndef NULL
#define NULL   ((void *) 0)
#endif

#ifdef __cplusplus
extern "C"
{
#endif

typedef struct StreamIO
{
    /* Read data from stream at current position. Return number of bytes read. */
    int (*read)( struct StreamIO *stream, char *buf, int numBytes );
    /* Write data to stream at current position. Return number of bytes read. */
    int (*write)( struct StreamIO *stream, char *buf, int numBytes );
    /* Seek to a certain position in the stream. */
    int (*setPosition)( struct StreamIO *stream,  int offset );
    /* Tell current position in stream. */
    int (*getPosition)( struct StreamIO *stream );
    /* Close stream. */
    void (*close)( struct StreamIO *stream );
    /* Get address if an in-memory stream, or return NULL. */
    char *(*getAddress)( struct StreamIO *stream );
}
StreamIO;

StreamIO *Stream_OpenImage( char *dataPtr, int numBytes );

/**
 * Create a stream object for reading a file wuth stdio.
 * This function is in "spmidi/util/streamio_file.c".
 * @param fileName Name or path of the file.
 * @param mode Generally "r", "rb", "w", "wb".
 */
StreamIO *Stream_OpenFile( char *fileName, char *mode );

int Stream_Read( StreamIO *sio, char *buffer, int numBytes );
int Stream_Write( StreamIO *sio, char *buffer, int numBytes );
int Stream_SetPosition( StreamIO *sio, int offset );
int Stream_GetPosition( StreamIO *sio );
void Stream_Close( StreamIO *sio );

#define Stream_GetAddress(sio)  ((sio)->getAddress(sio))

#ifdef __cplusplus
};
#endif

#endif