text:
//
// Copyright (c) ZeroC, Inc. All rights reserved.
//

package com.zeroc.icebuilderplugin.builder;

import java.io.BufferedInputStream;
import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Iterator;
import java.util.LinkedHashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.StringTokenizer;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;

import org.eclipse.core.resources.IFile;
import org.eclipse.core.resources.IFolder;
import org.eclipse.core.resources.IMarker;
import org.eclipse.core.resources.IProject;
import org.eclipse.core.resources.IResource;
import org.eclipse.core.resources.IResourceDelta;
import org.eclipse.core.resources.IResourceDeltaVisitor;
import org.eclipse.core.resources.IResourceVisitor;
import org.eclipse.core.resources.IncrementalProjectBuilder;
import org.eclipse.core.runtime.CoreException;
import org.eclipse.core.runtime.IPath;
import org.eclipse.core.runtime.IProgressMonitor;
import org.eclipse.core.runtime.IStatus;
import org.eclipse.core.runtime.Path;
import org.eclipse.core.runtime.Status;
import org.eclipse.swt.SWT;
import org.eclipse.swt.widgets.Display;
import org.eclipse.ui.PlatformUI;
import org.eclipse.ui.console.ConsolePlugin;
import org.eclipse.ui.console.IConsole;
import org.eclipse.ui.console.IConsoleManager;
import org.eclipse.ui.console.MessageConsole;
import org.eclipse.ui.console.MessageConsoleStream;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;
import org.xml.sax.SAXException;

import com.zeroc.icebuilderplugin.Activator;
import com.zeroc.icebuilderplugin.internal.Configuration;
import com.zeroc.icebuilderplugin.internal.Dependencies;
import com.zeroc.icebuilderplugin.preferences.PluginPreferencePage;
import com.zeroc.icebuilderplugin.util.StreamReader;

public class Slice2JavaBuilder extends IncrementalProjectBuilder
{
    public static final String BUILDER_ID = "com.zeroc.IceBuilderPlugin.Slice2JavaBuilder";

    /*
     * (non-Javadoc)
     *
     * @see org.eclipse.core.internal.events.InternalBuilder#build(int,
     * java.util.Map, org.eclipse.core.runtime.IProgressMonitor)
     */
    protected IProject[] build(int kind, @SuppressWarnings("rawtypes")Map args, IProgressMonitor monitor)
        throws CoreException
    {
        PlatformUI.getWorkbench().getDisplay().syncExec(new Runnable()
        {
            public void run()
            {
                Configuration.verifyIceHome(Configuration.getIceHome());
            }
        });

        // Ignore auto builds issued by Eclipse if Ice auto building is off
        if((kind == AUTO_BUILD) && !Activator.getDefault().getPreferenceStore().getBoolean(PluginPreferencePage.BUILD_AUTO))
        {
            return null;
        }

        long start = System.currentTimeMillis();
        IResourceDelta delta = getDelta(getProject());
        BuildState state = new BuildState(getProject(), delta, monitor);
        state.dependencies.read();

        try
        {
            if((kind == FULL_BUILD) || (delta == null) || state.config.getExtraArguments().contains("--checksum"))
            {
                fullBuild(state, monitor);
            }
            else
            {
                incrementalBuild(state, monitor);
            }

            long end = System.currentTimeMillis();
            state.out.println("Build complete. Elapsed time: " + (end - start) / 1000 + "s.\n");
            state.dependencies.write();
        }
        catch(CoreException e)
        {
            long end = System.currentTimeMillis();
            state.dependencies.write();

            // Handle only exceptions thrown by the Slice compiler
            if(e.getStatus().getPlugin().equals(Activator.PLUGIN_ID))
            {
                if(state.err != null)
                {
                    state.err.println("Build failed. Elapsed time: " + (end - start) / 1000 + "s.");
                    state.err.println("    Reason: " + e.getStatus().getMessage() + "\n");
                }
                else
                {
                    e.printStackTrace(System.err);
                }
            }
            else
            {
                throw e;
            }
        }

        return null;
    }

    protected void clean(IProgressMonitor monitor)
        throws CoreException
    {
        BuildState state = new BuildState(getProject(), null, monitor);

        // Don't read the existing dependencies. That will have the
        // effect of trashing them.

        try
        {
            // Now, clean the generated sub-directory.
            Set<IFile> files = new HashSet<IFile>();
            getResources(files, state.generated.members());

            for(IFile file : files)
            {
                // Don't delete "." files (such as .gitignore).
                if(!file.getName().startsWith("."))
                {
                    file.delete(true, false, monitor);
                }
            }
        }
        finally
        {
            state.dependencies.write();
        }
    }

    static class BuildState
    {
        BuildState(IProject project, IResourceDelta delta, IProgressMonitor monitor) throws CoreException
        {
            config = Configuration.getConfiguration(project);

            initializeConsole();
            out = _consoleout;
            err = _consoleerr;

            generated = project.getFolder(config.getGeneratedDir());
            if(!generated.exists())
            {
                generated.create(false, true, monitor);
            }

            project.accept(new IResourceVisitor()
            {
                public boolean visit(IResource resource)
                    throws CoreException
                {
                    if(resource instanceof IFile)
                    {
                        IFile file = (IFile) resource;
                        if(filter(file))
                        {
                            _resources.add((IFile) resource);
                        }
                    }
                    return true;
                }
            });

            if(delta != null)
            {
                delta.accept(new IResourceDeltaVisitor()
                {
                    public boolean visit(IResourceDelta delta)
                        throws CoreException
                    {
                        IResource resource = delta.getResource();
                        if(resource instanceof IFile)
                        {
                            IFile file = (IFile) resource;
                            if(filter(file))
                            {
                                switch (delta.getKind())
                                {
                                case IResourceDelta.ADDED:
                                case IResourceDelta.CHANGED:
                                    _deltaCandidates.add(file);
                                    break;
                                case IResourceDelta.REMOVED:
                                    _removed.add(file);
                                    break;
                                }
                            }
                        }
                        return true;
                    }
                });
            }

            dependencies = new Dependencies(project, _resources, err);
        }

        public Set<IFile> deltas()
        {
            return _deltaCandidates;
        }

        public List<IFile> removed()
        {
            return _removed;
        }

        public Set<IFile> resources()
        {
            return _resources;
        }

        public boolean filter(IFile file)
        {
            String ext = file.getFileExtension();
            if(ext != null && ext.equals("ice"))
            {
                return true;
            }
            return false;
        }

        synchronized static private void initializeConsole()
        {
            if(_consoleout == null)
            {
                MessageConsole console = new MessageConsole("Slice2Java Compiler", null);
                IConsole[] ics = new IConsole[1];
                ics[0] = console;
                IConsoleManager csmg = ConsolePlugin.getDefault().getConsoleManager();
                csmg.addConsoles(ics);
                csmg.showConsoleView(console);

                _consoleout = console.newMessageStream();
                _consoleerr = console.newMessageStream();

                final Display display = PlatformUI.getWorkbench().getDisplay();
                display.syncExec(new Runnable() {
                    public void run() {
                        _consoleerr.setColor(display.getSystemColor(SWT.COLOR_RED));
                    }
                });
            }
        }

        Configuration config;
        Dependencies dependencies;
        IFolder generated;

        private Set<IFile> _resources = new HashSet<IFile>();
        private Set<IFile> _deltaCandidates = new HashSet<IFile>();
        private List<IFile> _removed = new ArrayList<IFile>();

        private MessageConsoleStream out;
        private MessageConsoleStream err;

        static private MessageConsoleStream _consoleout = null;
        static private MessageConsoleStream _consoleerr = null;
    }

    private int build(BuildState state, Set<IFile> files, boolean depend, StringBuffer out, StringBuffer err)
        throws CoreException
    {
        // Clear the output buffer
        out.setLength(0);
        // Clear the error buffer
        err.setLength(0);

        Set<String> cmd = new LinkedHashSet<String>();
        String compiler = state.config.getCompiler();
        if(compiler == null)
        {
            throw new CoreException(new Status(IStatus.ERROR, Activator.PLUGIN_ID, "Cannot locate slice2java compiler", null));
        }

        cmd.add(compiler);
        if(depend)
        {
            cmd.add("--depend-xml");
        }
        else
        {
            cmd.add("--output-dir=" + state.generated.getProjectRelativePath().toString());
            cmd.add("--list-generated");
        }
        cmd.addAll(state.config.getCommandLine());
        for(Iterator<IFile> p = files.iterator(); p.hasNext();)
        {
            cmd.add(p.next().getLocation().toOSString());
        }

        ProcessBuilder builder = new ProcessBuilder(cmd.toArray(new String[] {}));
        IPath rootLocation = getProject().getLocation();
        builder.directory(rootLocation.toFile());

        return runSliceCompiler(builder, state, depend, out, err);
    }

    private int
    runSliceCompiler(ProcessBuilder builder, BuildState state, boolean depend, StringBuffer out, StringBuffer err)
        throws CoreException
    {
        try
        {
            if(!depend)
            {
                state.out.println("Running Slice2Java compiler:");
                state.out.print("    ");
                for(Iterator<String> p = builder.command().iterator(); p.hasNext();)
                {
                    state.out.print(p.next());
                    state.out.print(" ");
                }
                state.out.println("");
            }

            Process proc = builder.start();

            StreamReader outThread = new StreamReader(proc.getInputStream(), out);
            outThread.start();
            StreamReader errThread = new StreamReader(proc.getErrorStream(), err);
            errThread.start();

            int status = proc.waitFor();

            outThread.join();
            errThread.join();

            if(!depend)
            {
                if(status != 0)
                {
                    state.err.println("slice2java status: " + status);
                    if(!isXML(err))
                    {
                        String reason = err.toString();
                        int helpIndex = reason.lastIndexOf(System.lineSeparator() +
                                "Options:" + System.lineSeparator());

                        if(helpIndex > -1)
                        {
                            reason = reason.substring(0, helpIndex);
                        }

                        throw new RuntimeException(reason);
                    }
                }
                else
                {
                    state.out.println("Slice2Java status: " + status);
                }
            }

            return status;
        }
        catch(Exception e)
        {
            throw new CoreException(new Status(IStatus.ERROR, Activator.PLUGIN_ID, e.getMessage(), e));
        }
    }

    private void
    createMarker(BuildState state, IFile source, IPath filename, int line, String msg)
        throws CoreException
    {
        // Process the error.
        IPath dir = getProject().getLocation();

        IFile file = null;
        if(filename != null && dir.isPrefixOf(filename))
        {
            // Locate the file within the project.
            file = getProject().getFile(filename.removeFirstSegments(dir.segmentCount()));

            // If the file is not the current source file, and the file exists in the project
            // then it must already contain a marker, so don't place another.
            if(!file.equals(source) && state.filter(file))
            {
                return;
            }
        }

        // If the message isn't contained in the source file, then identify the
        // file:line in the message itself.
        if(file == null)
        {
            if(line != -1)
            {
                msg = filename + ":" + line + ": " + msg;
            }
            else
            {
                msg = filename + ": " + msg;
            }
        }

        IMarker marker = source.createMarker(Configuration.SLICE_PROBLEM);
        marker.setAttribute(IMarker.MESSAGE, msg);
        if(msg.toLowerCase().indexOf("warning:") >= 0)
        {
            marker.setAttribute(IMarker.SEVERITY, IMarker.SEVERITY_WARNING);
        }
        else
        {
            marker.setAttribute(IMarker.SEVERITY, IMarker.SEVERITY_ERROR);
        }
        if(line != -1)
        {
            if(file != null && file.equals(source))
            {
                marker.setAttribute(IMarker.LINE_NUMBER, line);
            }
            else
            {
                marker.setAttribute(IMarker.LINE_NUMBER, 1);
            }
        }
    }

    private void createMarkers(BuildState state, IFile source, String output)
        throws CoreException
    {
        output = output.trim();
        if(output.length() == 0)
        {
            return;
        }

        String[] lines = output.split("\n");

        IPath filename = null;
        int line = -1;
        StringBuffer msg = new StringBuffer();

        boolean continuation = false;

        for(int i = 0; i < lines.length; ++i)
        {
            if(continuation)
            {
                if(lines[i].startsWith(" "))
                {
                    // Continuation of the previous message.
                    msg.append(lines[i]);
                    continue;
                }
                else
                {
                    // Process the message.
                    createMarker(state, source, filename, line, msg.toString());
                }
            }

            // We're on a new message.
            msg.setLength(0);
            continuation = false;

            // Ignore.
            if(lines[i].contains("errors in preprocessor") || lines[i].contains("error in preprocessor"))
            {
                continue;
            }

            //
            // Parse a line of the form:
            //
            // file:[line:] message
            //
            int start = 0;
            int end;
            // Handle drive letters.
            if(lines[i].length() > 2 && lines[i].charAt(1) == ':')
            {
                end = lines[i].indexOf(':', 2);
            }
            else
            {
                end = lines[i].indexOf(':');
            }
            if(end != -1)
            {
                filename = new Path(lines[i].substring(start, end));
                start = end + 1;
                end = lines[i].indexOf(':', start);
                if(end != -1)
                {
                    try
                    {
                        line = Integer.parseInt(lines[i].substring(start, end));
                        start = end + 1;
                    }
                    catch(NumberFormatException e)
                    {
                        // The message may not have a line number.
                        line = -1;
                    }
                    msg.append(lines[i].substring(start, lines[i].length()));

                    continuation = true;
                    continue;
                }
            }
            // Unknown format.
            createMarker(state, source, null, -1, lines[i]);
        }

        if(continuation)
        {
            createMarker(state, source, filename, line, msg.toString());
        }
    }

    private void getResources(Set<IFile> files, IResource[] members)
        throws CoreException
    {
        for(int i = 0; i < members.length; ++i)
        {
            if(members[i] instanceof IFile)
            {
                files.add((IFile) members[i]);
            }
            else if(members[i] instanceof IFolder)
            {
                getResources(files, ((IFolder) members[i]).members());
            }
        }
    }

    private void fullBuild(BuildState state, final IProgressMonitor monitor)
        throws CoreException
    {
        clean(monitor);
        Set<IFile> candidates = state.resources();
        if(candidates.isEmpty())
        {
            return;
        }

        java.util.Date date = new java.util.Date();
        state.out.println("Started full build at " + new SimpleDateFormat("HH:mm:ss").format(date));

        state.out.println("Candidate list:");
        // This is a complete list of Slice files.
        for(Iterator<IFile> p = candidates.iterator(); p.hasNext();)
        {
            state.out.println("    " + p.next().getProjectRelativePath().toString());
        }
        state.out.println("Regenerating java source files.");

        Set<IFile> depends = new HashSet<IFile>();

        // Delete each marker.
        for(Iterator<IFile> p = candidates.iterator(); p.hasNext();)
        {
            IFile file = p.next();
            file.deleteMarkers(Configuration.SLICE_PROBLEM, true, IResource.DEPTH_INFINITE);
        }

        StringBuffer out = new StringBuffer();
        StringBuffer err = new StringBuffer();

        try
        {
            // Do the build.
            build(state, candidates, false, out, err);
        }
        finally
        {
            out = mergeXmls(state, out, false);
            // Refresh the generated subdirectory prior to processing the
            // generated files list.
            state.generated.refreshLocal(IResource.DEPTH_INFINITE, monitor);

            // Parse the output.
            Slice2JavaGeneratedParser parser = getGeneratedFiles(state, candidates, out, err);
            for(Map.Entry<IFile, Slice2JavaGeneratedParser.Entry> entry : parser.output.entrySet())
            {
                IFile source = entry.getKey();

                Slice2JavaGeneratedParser.Entry outputEntry = entry.getValue();
                Set<IFile> newGeneratedJavaFiles = outputEntry.files;

                for(IFile f : newGeneratedJavaFiles)
                {
                    // Mark the resource as derived.
                    f.setDerived(true, null);
                }

                if(!outputEntry.error)
                {
                    depends.add(source);
                    if(newGeneratedJavaFiles.isEmpty())
                    {
                        state.out.println(source.getProjectRelativePath().toString() + ": No java files emitted.");
                    }
                    else
                    {
                        state.out.println(source.getProjectRelativePath().toString() + ": Emitted:");
                        for(Iterator<IFile> q = newGeneratedJavaFiles.iterator(); q.hasNext();)
                        {
                            state.out.println("    " + q.next().getProjectRelativePath().toString());
                        }
                    }
                }
                else
                {
                    state.dependencies.errorSliceFiles.add(source);
                    state.out.println(source.getProjectRelativePath().toString() + ": Error.");
                }

                // Update the set of slice -> java dependencies.
                state.dependencies.sliceJavaDependencies.put(source, newGeneratedJavaFiles);

                // Create markers for each warning/error.
                createMarkers(state, source, outputEntry.output);
            }

            // Update the slice->slice dependencies.
            // Only update the dependencies for those files with no build problems.
            if(!depends.isEmpty())
            {
                if(state.out != null)
                {
                    state.out.println("Updating dependencies.");
                }

                err = new StringBuffer();
                if(build(state, depends, true, out, err) == 0)
                {
                    out = mergeXmls(state, out, true);
                    // Parse the new dependency set.
                    state.dependencies.updateDependencies(out.toString());
                }
                else if(state.err != null)
                {
                    state.err.println("Dependencies not updated due to error.");
                    state.err.println(err.toString());
                }
            }
        }
    }

    private void incrementalBuild(BuildState state, IProgressMonitor monitor)
        throws CoreException
    {
        Set<IFile> candidates = state.deltas();
        List<IFile> removed = state.removed();

        java.util.Date date = new java.util.Date();
        state.out.println("Started incremental build at " + new SimpleDateFormat("HH:mm:ss").format(date));

        state.out.println("Candidate list:");
        // This is a complete list of slice files.
        for(Iterator<IFile> p = candidates.iterator(); p.hasNext();)
        {
            state.out.println("   + " + p.next().getProjectRelativePath().toString());
        }
        for(Iterator<IFile> p = removed.iterator(); p.hasNext();)
        {
            state.out.println("   - " + p.next().getProjectRelativePath().toString());
        }

        // The orphan candidate set.
        Set<IFile> orphanCandidateSet = new HashSet<IFile>();

        // Go through the removed list, removing the dependencies.
        for(Iterator<IFile> p = removed.iterator(); p.hasNext();)
        {
            IFile f = p.next();

            // Remove the file from the error list, if necessary.
            if(state.dependencies.errorSliceFiles.contains(f))
            {
                state.dependencies.errorSliceFiles.remove(f);
            }

            Set<IFile> dependents = state.dependencies.sliceSliceDependencies.remove(f);
            if(dependents != null)
            {
                Iterator<IFile> dependentsIterator = dependents.iterator();
                while(dependentsIterator.hasNext())
                {
                    IFile dependent = dependentsIterator.next();
                    Set<IFile> files = state.dependencies.reverseSliceSliceDependencies.get(dependent);
                    if(files != null)
                    {
                        files.remove(f);
                    }
                }
            }

            Set<IFile> oldJavaFiles = state.dependencies.sliceJavaDependencies.remove(f);
            if(oldJavaFiles == null || oldJavaFiles.isEmpty())
            {
                state.out.println(f.getProjectRelativePath().toString() + ": No orphans.");
            }
            else
            {
                state.out.println(f.getProjectRelativePath().toString() + ": Orphans:");
                for(Iterator<IFile> q = oldJavaFiles.iterator(); q.hasNext();)
                {
                    state.out.println("    " + q.next().getProjectRelativePath().toString());
                }
            }

            if(oldJavaFiles != null)
            {
                orphanCandidateSet.addAll(oldJavaFiles);
            }
        }

        // Add the removed files to the candidates set
        // prior to determining additional candidates.
        candidates.addAll(removed);

        // Add to the candidate set any slice files that are in error. Clear the
        // error list.
        candidates.addAll(state.dependencies.errorSliceFiles);
        state.dependencies.errorSliceFiles.clear();

        Set<IFile> candidatesTmp = new HashSet<IFile>();

        for(Iterator<IFile> p = candidates.iterator(); p.hasNext();)
        {
            IFile f = p.next();

            Set<IFile> files = state.dependencies.reverseSliceSliceDependencies.get(f);
            if(files != null)
            {
                for(Iterator<IFile> q = files.iterator(); q.hasNext();)
                {
                    IFile potentialCandidate = q.next();
                    if(potentialCandidate.exists())
                    {
                        candidatesTmp.add(potentialCandidate);
                    }
                }
            }

            // If this is a file in the contained list, then remove the
            // dependency entry.
            if(removed.contains(f))
            {
                state.dependencies.reverseSliceSliceDependencies.remove(f);
            }
        }
        candidates.addAll(candidatesTmp);

        // Remove all the removed files from the candidates list.
        candidates.removeAll(removed);

        if(candidates.isEmpty())
        {
            state.out.println("No remaining candidates.");
        }
        else
        {
            state.out.println("Expanded candidate list:");
            // This is a complete list of slice files.
            for(Iterator<IFile> p = candidates.iterator(); p.hasNext();)
            {
                state.out.println("    " + p.next().getProjectRelativePath().toString());
            }
        }

        // The set of files that we'll generate dependencies for.
        Set<IFile> depends = new HashSet<IFile>();

        StringBuffer out = new StringBuffer();
        StringBuffer err = new StringBuffer();

        if(!candidates.isEmpty())
        {
            state.out.println("Regenerating java source files.");

            // The complete set of generated java files by this build.
            Set<IFile> generatedJavaFiles = new HashSet<IFile>();

            // Remove all markers for the candidate list.
            for(Iterator<IFile> p = candidates.iterator(); p.hasNext();)
            {
                IFile file = p.next();
                file.deleteMarkers(Configuration.SLICE_PROBLEM, true, IResource.DEPTH_INFINITE);
            }

            try
            {
                // Do the build.
                build(state, candidates, false, out, err);
            }
            finally
            {
                out = mergeXmls(state, out, false);
                // Refresh the generated directory prior to processing the generated
                // files list.
                state.generated.refreshLocal(IResource.DEPTH_INFINITE, monitor);

                // Parse the emitted XML file that describes what was produced by
                // the build.
                Slice2JavaGeneratedParser parser = getGeneratedFiles(state, candidates, out, err);
                for(Map.Entry<IFile, Slice2JavaGeneratedParser.Entry> entry : parser.output.entrySet())
                {
                    IFile source = entry.getKey();

                    Slice2JavaGeneratedParser.Entry outputEntry = entry.getValue();

                    Set<IFile> newGeneratedJavaFiles = outputEntry.files;
                    for(IFile f : newGeneratedJavaFiles)
                    {
                        // Mark the resource as derived.
                        f.setDerived(true, null);
                    }

                    // If the build of the file didn't result in an error, add to
                    // the dependencies list. Otherwise, add to the error list.
                    if(!outputEntry.error)
                    {
                        depends.add(source);
                    }
                    else
                    {
                        state.out.println(source.getProjectRelativePath().toString() + ": Error.");
                        state.dependencies.errorSliceFiles.add(source);
                    }

                    // Compute the set difference between the old set and new set
                    // of generated files. The difference should be added to the
                    // orphan candidate set.
                    Set<IFile> oldJavaFiles = state.dependencies.sliceJavaDependencies.get(source);
                    if(oldJavaFiles != null)
                    {
                        // Compute the set difference.
                        oldJavaFiles.removeAll(newGeneratedJavaFiles);
                        if(oldJavaFiles.isEmpty())
                        {
                            state.out.println(source.getProjectRelativePath().toString() + ": No orphans.");
                        }
                        else
                        {
                            state.out.println(source.getProjectRelativePath().toString() + ": Orphans:");
                            for(Iterator<IFile> q = oldJavaFiles.iterator(); q.hasNext();)
                            {
                                state.out.println("    " + q.next().getProjectRelativePath().toString());
                            }
                        }
                        orphanCandidateSet.addAll(oldJavaFiles);
                    }

                    // Update the set of slice -> java dependencies.
                    state.dependencies.sliceJavaDependencies.put(source, newGeneratedJavaFiles);

                    // If the build resulted in an error, there will be no java source files.
                    if(!outputEntry.error)
                    {
                        if(newGeneratedJavaFiles.isEmpty())
                        {
                            state.out.println(source.getProjectRelativePath().toString() + ": No java files emitted.");
                        }
                        else
                        {
                            state.out.println(source.getProjectRelativePath().toString() + ": Emitted:");
                            for(Iterator<IFile> q = newGeneratedJavaFiles.iterator(); q.hasNext();)
                            {
                                state.out.println("    " + q.next().getProjectRelativePath().toString());
                            }
                        }
                    }

                    generatedJavaFiles.addAll(newGeneratedJavaFiles);

                    // Create markers for each warning/error.
                    createMarkers(state, source, outputEntry.output);
                }

                // Do a set difference between the orphan candidate set
                // and the complete set of generated java source files.
                // Any remaining are complete orphans and should
                // be removed.
                orphanCandidateSet.removeAll(generatedJavaFiles);
            }
        }

        if(orphanCandidateSet.isEmpty())
        {
            state.out.println("No orphans from this build.");
        }
        else
        {
            state.out.println("Orphans from this build:");
            for(Iterator<IFile> p = orphanCandidateSet.iterator(); p.hasNext();)
            {
                state.out.println("    " + p.next().getProjectRelativePath().toString());
            }
        }

        //
        // Remove orphans.
        //
        for(Iterator<IFile> p = orphanCandidateSet.iterator(); p.hasNext();)
        {
            p.next().delete(true, false, monitor);
        }

        // The dependencies of any files without build errors should be updated.
        if(!depends.isEmpty())
        {
            state.out.println("Updating dependencies.");

            err = new StringBuffer();

            // We've already added markers for any errors... Only update the
            // dependencies if no problems resulted in the build.
            if(build(state, depends, true, out, err) == 0)
            {
                out = mergeXmls(state, out, true);
                // Parse the new dependency set.
                state.dependencies.updateDependencies(out.toString());
            }
            else
            {
                state.err.println("Dependencies not updated due to error.");
                state.err.println(err.toString());
            }
        }
    }

    //
    // This method merge the XML produced by multiple Slice compiler
    // invocations in a single XML. If depend argument is true, the input
    // buffer is treated as a dependencies XML, otherwise is treated as
    // a generated list XML.
    //
    private StringBuffer
    mergeXmls(BuildState state, StringBuffer input, boolean depend)
    {
        //
        // Merge depend XMLs in a single XML
        //
        String v = input.toString();
        StringTokenizer lines = new StringTokenizer(v, System.getProperty("line.separator"));
        boolean onXML = false;
        StringBuffer out = new StringBuffer("<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n");
        if(depend)
        {
            out.append("<dependencies>\n");
        }
        else
        {
            out.append("<generated>\n");
        }

        while(lines.hasMoreTokens())
        {
            String line = lines.nextToken();
            if(line.equals("<?xml version=\"1.0\" encoding=\"UTF-8\"?>"))
            {
                continue;
            }

            if(depend)
            {
                if(line.equals("<dependencies>"))
                {
                    onXML = true;
                    continue;
                }
                else if(line.equals("</dependencies>"))
                {
                    onXML = false;
                    continue;
                }
            }
            else
            {
                if(line.equals("<generated>"))
                {
                    onXML = true;
                    continue;
                }
                else if(line.equals("</generated>"))
                {
                    onXML = false;
                    continue;
                }
            }

            if(onXML)
            {
                out.append(line + '\n');
            }
            else
            {
                state.out.println(line);
            }
        }

        if(depend)
        {
            out.append("</dependencies>\n");
        }
        else
        {
            out.append("</generated>\n");
        }

        return out;
    }

    private static class Slice2JavaGeneratedParser
    {
        static class Entry
        {
            boolean error; // Did the build result in an error.
            String output; // Any warnings/errors from the build.
            Set<IFile> files; // The set of java source files associated with the source file.
        }
        Map<IFile, Entry> output = new HashMap<IFile, Entry>(); // Map of source files to build entry.

        private IFolder _generated;
        private IPath _generatedPath;
        // Map of absolute path to project location.
        Map<IPath, IFile> _sources = new HashMap<IPath, IFile>();

        Slice2JavaGeneratedParser(IFolder generated, Set<IFile> candidates)
        {
            _generated = generated;
            _generatedPath = generated.getProjectRelativePath();
            for(IFile f : candidates)
            {
                _sources.put(f.getLocation(), f);
            }
        }

        private Node findNode(Node n, String qName)
            throws SAXException
        {
            NodeList children = n.getChildNodes();
            for(int i = 0; i < children.getLength(); ++i)
            {
                Node child = children.item(i);
                if(child.getNodeType() == Node.ELEMENT_NODE && child.getNodeName().equals(qName))
                {
                    return child;
                }
            }
            throw new SAXException("no such node: " + qName);
        }

        private IFile convert(String fname)
        {
            IPath p = new Path(fname); // fname contains "generated/...".
            int match = p.matchingFirstSegments(_generatedPath);
            return _generated.getFile(p.removeFirstSegments(match));
        }

        private Set<IFile> visitSource(Node source) throws SAXException
        {
            Set<IFile> files = new HashSet<IFile>();
            NodeList sourceNodes = source.getChildNodes();
            for(int j = 0; j < sourceNodes.getLength(); ++j)
            {
                if(sourceNodes.item(j).getNodeType() == Node.ELEMENT_NODE && sourceNodes.item(j).getNodeName().equals("file"))
                {
                    Element file = (Element)sourceNodes.item(j);
                    String name = file.getAttribute("name");
                    if(name.length() == 0)
                    {
                        throw new SAXException("empty name attribute");
                    }
                    files.add(convert(name));
                }
            }
            return files;
        }

        private String getText(Node n) throws SAXException
        {
            NodeList children = n.getChildNodes();
            if(children.getLength() == 1 && children.item(0).getNodeType() == Node.TEXT_NODE)
            {
                return children.item(0).getNodeValue();
            }
            return "";
        }

        public void visit(Node doc) throws SAXException
        {
            Node n = findNode(doc, "generated");
            NodeList fileNodes = n.getChildNodes();
            for(int j = 0; j < fileNodes.getLength(); ++j)
            {
                if(fileNodes.item(j).getNodeType() == Node.ELEMENT_NODE && fileNodes.item(j).getNodeName().equals("source"))
                {
                    Element sourceElement = (Element)fileNodes.item(j);
                    String name = sourceElement.getAttribute("name");
                    if(name.length() == 0)
                    {
                        throw new SAXException("empty name attribute");
                    }

                    // The source file
                    IFile source = _sources.get(new Path(name));
                    if(source == null)
                    {
                        throw new SAXException("unknown source file: " + name);
                    }

                    Entry entry = new Entry();
                    entry.error = true;
                    entry.output = "";
                    try
                    {
                        entry.output = getText(findNode(sourceElement, "output"));
                    }
                    catch(SAXException e)
                    {
                        // Ignored
                    }

                    if(sourceElement.getAttribute("error").equals("true"))
                    {
                        entry.files = new HashSet<IFile>();
                    }
                    else
                    {
                        entry.error = false;
                        entry.files = visitSource(sourceElement);
                    }
                    output.put(source, entry);
                }
            }
        }
    }

    private boolean
    isXML(StringBuffer s)
    {
        try
        {
            InputStream in = new ByteArrayInputStream(s.toString().getBytes());
            DocumentBuilderFactory.newInstance().newDocumentBuilder().parse(new BufferedInputStream(in));
        }
        catch(SAXException e)
        {
            return false;
        }
        catch(ParserConfigurationException e)
        {
            return false;
        }
        catch(IOException e)
        {
            return false;
        }
        return true;
    }

    private Slice2JavaGeneratedParser getGeneratedFiles(BuildState state, Set<IFile> candidates, StringBuffer out, StringBuffer err)
        throws CoreException
    {
        Slice2JavaGeneratedParser parser = new Slice2JavaGeneratedParser(state.generated, candidates);
        try
        {
            if(out.length() > 0)
            {
                InputStream in = new ByteArrayInputStream(out.toString().getBytes());
                Document doc = DocumentBuilderFactory.newInstance().newDocumentBuilder().parse(new BufferedInputStream(in));
                parser.visit(doc);
            }

            Pattern pattern = Pattern.compile("(.*):[0-9]+:\\s(.*)");
            for(String line : err.toString().split("\\r?\\n"))
            {
                Matcher match = pattern.matcher(line);
                if(match.find())
                {
                    String file = match.group(1);
                    if(file.contains("/"))
                    {
                        file.substring(file.lastIndexOf('/'));
                    }

                    IFile source = parser._sources.get(new Path(file));
                    Slice2JavaGeneratedParser.Entry entry = parser.output.get(source);
                    if(entry == null)
                    {
                        entry = new Slice2JavaGeneratedParser.Entry();
                        parser.output.put(source, entry);
                        entry.files = new HashSet<IFile>();
                        entry.output = "";
                    }
                    else if(entry.output.length() > 0)
                    {
                        entry.output += '\n';
                    }
                    entry.output += line;
                    entry.error = true;
                }
                else
                {
                    state.err.println(line);
                }
            }
        }
        catch(SAXException e)
        {
            throw new CoreException(new Status(IStatus.ERROR, Activator.PLUGIN_ID,
                    "internal error reading the generated output list", e));
        }
        catch(ParserConfigurationException e)
        {
            throw new CoreException(new Status(IStatus.ERROR, Activator.PLUGIN_ID,
                    "internal error reading the generated output list", e));
        }
        catch(IOException e)
        {
            throw new CoreException(new Status(IStatus.ERROR, Activator.PLUGIN_ID,
                    "internal error reading the generated output list", e));
        }
        return parser;
    }
}


text:
.. _news:

News and development history
============================

.. include:: ../NEWS.rst

redpajama_set_name: RedPajamaGithub


text:
const
	net = require('net'),
	windowslib = require('..');

describe('log relay', function () {
	it('namespace should be an object', function () {
		should(windowslib.LogRelay).be.an.Function;
	});

	it('start log relay, receive TCP connection, get log message, shutdown', function (done) {
		this.timeout(5000);
		this.slow(4000);

		var relay = new windowslib.LogRelay();
		var testMsg = 'Hello World!';

		relay.on('started', function () {
			var client = net.createConnection(relay.tcpPort, function (conn) {
				client.write(relay.serverToken + '\n');
				client.write(testMsg);
				client.destroy();
			});
		});

		relay.on('message', function (msg) {
			relay.stop();
			should(msg).equal(testMsg);
			done();
		});

		relay.start();
	});

	it('start log relay, receive TCP connection, get log message, wait for buffers to flush, shutdown', function (done) {
		this.timeout(5000);
		this.slow(4000);

		var relay = new windowslib.LogRelay();
		var testMsg = 'Hello World!';

		relay.on('started', function () {
			var client = net.createConnection(relay.tcpPort, function (conn) {
				client.write(relay.serverToken + '\n');
				client.write(testMsg);
			});
		});

		relay.on('message', function (msg) {
			relay.stop();
			should(msg).equal(testMsg);
			done();
		});

		relay.start();
	});
});


text:
package main

import (
	"encoding/json"
	"flag"
	"fmt"
	"log"
	"os"
	"runtime/pprof"

	"github.com/moov-io/ach"
)

var (
	fPath      = flag.String("fPath", "201805101354.ach", "File Path")
	cpuprofile = flag.String("cpuprofile", "", "write cpu profile to file")

	flagJson = flag.Bool("json", false, "Output ACH File in JSON to stdout")
)

func main() {
	flag.Parse()

	if *cpuprofile != "" {
		f, err := os.Create(*cpuprofile)
		if err != nil {
			log.Fatal(err)
		}
		pprof.StartCPUProfile(f)
		defer pprof.StopCPUProfile()
	}

	path := *fPath

	// open a file for reading. Any io.Reader Can be used
	f, err := os.Open(path)

	if err != nil {
		log.Panicf("Can not open file: %s: \n", err)
	}

	achFile, err := ach.NewReader(f).Read()
	if err != nil {
		fmt.Printf("Issue reading file: %+v \n", err)
	}

	// If you trust the file but it's formating is off building will probably resolve the malformed file.
	if err := achFile.Create(); err != nil {
		fmt.Printf("Could not create file with read properties: %v", err)
	}

	// ensure we have a validated file structure
	if err := achFile.Validate(); err != nil {
		fmt.Printf("Could not validate entire read file: %v", err)
	}

	// Output file contents
	if *flagJson {
		if err := json.NewEncoder(os.Stdout).Encode(achFile); err != nil {
			fmt.Printf("ERROR: problem writing ACH File to stdout: %v\n", err)
			os.Exit(1)
		}
	} else {
		fmt.Printf("total amount debit: %v \n", achFile.Control.TotalDebitEntryDollarAmountInFile)
		fmt.Printf("total amount credit: %v \n", achFile.Control.TotalCreditEntryDollarAmountInFile)
	}
}


text:
#ifndef _PEI_RECOVERY_FDC_H_
#define _PEI_RECOVERY_FDC_H_

//
// FDC Registers
//
#define FDC_REGISTER_DOR  2 //Digital Output Register
#define FDC_REGISTER_MSR  4 //Main Status Register
#define FDC_REGISTER_DTR  5 //Data Register
#define FDC_REGISTER_CCR  7 //Configuration Control Register(data rate select)
#define FDC_REGISTER_DIR  7 //Digital Input Register(diskchange)
//
// FDC Register Bit Definitions
//
//
// Digital Out Register(WO)
//
#define SELECT_DRV      BIT0  // Select Drive: 0=A 1=B
#define RESET_FDC       BIT2  // Reset FDC
#define INT_DMA_ENABLE  BIT3  // Enable Int & DMA
#define DRVA_MOTOR_ON   BIT4  // Turn On Drive A Motor
#define DRVB_MOTOR_ON   BIT5  // Turn On Drive B Motor
//
// Main Status Register(RO)
//
#define MSR_DAB BIT0  // Drive A Busy
#define MSR_DBB BIT1  // Drive B Busy
#define MSR_CB  BIT4  // FDC Busy
#define MSR_NDM BIT5  // Non-DMA Mode
#define MSR_DIO BIT6  // Data Input/Output
#define MSR_RQM BIT7  // Request For Master
//
// Configuration Control Register(WO)
//
#define CCR_DRC (BIT0 | BIT1) // Data Rate select
//
// Digital Input Register(RO)
//
#define DIR_DCL     BIT7  // Disk change line
#define DRC_500KBS  0x0   // 500K
#define DRC_300KBS  0x01  // 300K
#define DRC_250KBS  0x02  // 250K
//
// FDC Command Code
//
#define READ_DATA_CMD         0x06
#define SEEK_CMD              0x0F
#define RECALIBRATE_CMD       0x07
#define SENSE_INT_STATUS_CMD  0x08
#define SPECIFY_CMD           0x03
#define SENSE_DRV_STATUS_CMD  0x04

///
/// CMD_MT: Multi_Track Selector
/// when set , this flag selects the multi-track operating mode.
/// In this mode, the FDC treats a complete cylinder under head0 and 1 as a single track
///
#define CMD_MT  BIT7

///
/// CMD_MFM: MFM/FM Mode Selector
/// A one selects the double density(MFM) mode
/// A zero selects single density (FM) mode
///
#define CMD_MFM BIT6

///
/// CMD_SK: Skip Flag
/// When set to 1, sectors containing a deleted data address mark will automatically be skipped
/// during the execution of Read Data.
/// When set to 0, the sector is read or written the same as the read and write commands.
///
#define CMD_SK  BIT5

//
// FDC Status Register Bit Definitions
//
//
// Status Register 0
//
#define STS0_IC (BIT7 | BIT6) // Interrupt Code
#define STS0_SE BIT5          // Seek End: the FDC completed a seek or recalibrate command
#define STS0_EC BIT4          // Equipment Check
#define STS0_NR BIT3          // Not Ready(unused), this bit is always 0
#define STS0_HA BIT2          // Head Address: the current head address
//
// STS0_US1 & STS0_US0: Drive Select(the current selected drive)
//
#define STS0_US1  BIT1  // Unit Select1
#define STS0_US0  BIT0  // Unit Select0
//
// Status Register 1
//
#define STS1_EN BIT7  // End of Cylinder
//
// BIT6 is unused
//
#define STS1_DE BIT5  // Data Error: The FDC detected a CRC error in either the ID field or data field of a sector
#define STS1_OR BIT4  // Overrun/Underrun: Becomes set if FDC does not receive CPU or DMA service within the required time interval
//
// BIT3 is unused
//
#define STS1_ND BIT2  // No data
#define STS1_NW BIT1  // Not Writable
#define STS1_MA BIT0  // Missing Address Mark

//
// Status Register 2
//
// BIT7 is unused
//
#define STS2_CM BIT6  // Control Mark
#define STS2_DD BIT5  // Data Error in Data Field: The FDC detected a CRC error in the data field
#define STS2_WC BIT4  // Wrong Cylinder: The track address from sector ID field is different from the track address maintained inside FDC
//
// BIT3 is unused
// BIT2 is unused
//
#define STS2_BC BIT1  // Bad Cylinder
#define STS2_MD BIT0  // Missing Address Mark in DataField

//
// Status Register 3
//
// BIT7 is unused
//
#define STS3_WP BIT6  // Write Protected
//
// BIT5 is unused
//
#define STS3_T0 BIT4  // Track 0
//
// BIT3 is unused
//
#define STS3_HD BIT2  // Head Address
//
// STS3_US1 & STS3_US0 : Drive Select
//
#define STS3_US1  BIT1  // Unit Select1
#define STS3_US0  BIT0  // Unit Select0

//
// Status Register 0 Interrupt Code Description
//
#define IC_NT   0x0   // Normal Termination of Command
#define IC_AT   0x40  // Abnormal Termination of Command
#define IC_IC   0x80  // Invalid Command
#define IC_ATRC 0xC0  // Abnormal Termination caused by Polling

///
/// Table of parameters for diskette
///
typedef struct {
  UINT8 EndOfTrack;          ///< End of track
  UINT8 GapLength;           ///< Gap length
  UINT8 DataLength;          ///< Data length
  UINT8 Number;              ///< Number of bytes per sector
  UINT8 MaxTrackNum;
  UINT8 MotorStartTime;
  UINT8 MotorOffTime;
  UINT8 HeadSettlingTime;
  UINT8 DataTransferRate;
} DISKET_PARA_TABLE;

///
/// Structure for FDC Command Packet 1
///
typedef struct {
  UINT8 CommandCode;
  UINT8 DiskHeadSel;
  UINT8 Cylinder;
  UINT8 Head;
  UINT8 Sector;
  UINT8 Number;
  UINT8 EndOfTrack;
  UINT8 GapLength;
  UINT8 DataLength;
} FDC_COMMAND_PACKET1;

///
/// Structure for FDC Command Packet 2
///
typedef struct {
  UINT8 CommandCode;
  UINT8 DiskHeadSel;
} FDC_COMMAND_PACKET2;

///
/// Structure for FDC Specify Command
///
typedef struct {
  UINT8 CommandCode;
  UINT8 SrtHut;
  UINT8 HltNd;
} FDC_SPECIFY_CMD;

///
/// Structure for FDC Seek Command
///
typedef struct {
  UINT8 CommandCode;
  UINT8 DiskHeadSel;
  UINT8 NewCylinder;
} FDC_SEEK_CMD;

///
/// Structure for FDC Result Packet
///
typedef struct {
  UINT8 Status0;
  UINT8 Status1;
  UINT8 Status2;
  UINT8 CylinderNumber;
  UINT8 HeaderAddress;
  UINT8 Record;
  UINT8 Number;
} FDC_RESULT_PACKET;

#endif


text:
/*!
 * @header KMTButtonObject.h
 * @abstract 메시지 하단에 추가되는 버튼 오브젝트입니다.
 */

#import <KakaoMessageTemplate/KMTParamObject.h>

NS_ASSUME_NONNULL_BEGIN

@class KMTLinkObject;

/*!
 * @class KMTButtonObject
 * @abstract 메시지 하단에 추가되는 버튼 오브젝트입니다.
 */
@interface KMTButtonObject : KMTParamObject

/*!
 * @property title
 * @abstract 버튼의 타이틀
 */
@property (copy, nonatomic) NSString *title;

/*!
 * @property link
 * @abstract 버튼 클릭 시 이동할 링크 정보
 */
@property (copy, nonatomic) KMTLinkObject *link;

@end

@interface KMTButtonObject (Constructor)

+ (instancetype)buttonObjectWithTitle:(NSString *)title link:(KMTLinkObject *)link;
- (instancetype)initWithTitle:(NSString *)title link:(KMTLinkObject *)link;

@end

@interface KMTButtonBuilder : NSObject

@property (copy, nonatomic) NSString *title;
@property (copy, nonatomic) KMTLinkObject *link;

- (KMTButtonObject *)build;

@end

@interface KMTButtonObject (ConstructorWithBuilder)

+ (instancetype)buttonObjectWithBuilderBlock:(void (^)(KMTButtonBuilder *buttonBuilder))builderBlock;
+ (instancetype)buttonObjectWithBuilder:(KMTButtonBuilder *)builder;
- (instancetype)initWithBuilder:(KMTButtonBuilder *)builder;

@end

NS_ASSUME_NONNULL_END


text:
<?php
/*
 * Created on Jan 13, 2009
 */

use crazedsanity\core\baseAbstract;
use crazedsanity\core\Lockfile;
use crazedsanity\core\ToolBox;
use crazedsanity\core\FileSystem;

require_once(__DIR__ .'/../src/core/FileSystem.class.php');

//=============================================================================
class TestOfCSFileSystem extends \PHPUnit_Framework_TestCase {

	//-------------------------------------------------------------------------
	public function __construct() {
		//make sure it's all clean.
		$this->_makeClasses();
		$this->tearDown();

	}//end __construct()
	//-------------------------------------------------------------------------

	//-------------------------------------------------------------------------
	protected function _makeClasses() {
		$filesDir = dirname(__FILE__) ."/files";
		$this->reader = new FileSystem($filesDir);
		$this->writer = new FileSystem($filesDir .'/rw');
	}//end _makeClasses()
	//-------------------------------------------------------------------------

	//-------------------------------------------------------------------------
	public function setUp() {
		$this->_makeClasses();

		//make a directory to write into.
		$this->writer->mkdir(__CLASS__);
		$this->writer->cd(__CLASS__);
	}//end setUp()
	//-------------------------------------------------------------------------

	//-------------------------------------------------------------------------
	public function tearDown() {
		//TODO: this should be able to RECURSIVELY delete files & folders.
		$this->writer->cd('/');
		@$this->writer->rmdir(__CLASS__);
	}//end tearDown()
	//-------------------------------------------------------------------------

	//-------------------------------------------------------------------------
	public function test_basics() {
		$fs = new _fs_testProtectedMethods(dirname(__FILE__));

		$this->assertEquals('/', $fs->cwd);
		$this->assertEquals(dirname(__FILE__), $fs->realcwd);

		// check that specifying a valid current working directory (cwd) works
		{
			//use a leading slash in CWD
			$validCwd2 = new FileSystem(dirname(__FILE__), '/files');
			$this->assertEquals(dirname(__FILE__) .'/files', $validCwd2->realcwd);
			$this->assertEquals('/files', $validCwd2->cwd);

			// just the directory name for CWD (no leading slash)
			$validCwd = new FileSystem(dirname(__FILE__), 'files');
			$this->assertEquals(dirname(__FILE__) .'/files', $validCwd->realcwd);
			$this->assertEquals('files', $validCwd->cwd);
		}

		//make sure specifying an invalid CWD works as expected
		{
			$invalidCwd = new FileSystem(dirname(__FILE__), '/xDoEsn0tEx15t');
			$this->assertEquals('/', $invalidCwd->cwd);
			$this->assertEquals(dirname(__FILE__), $invalidCwd->realcwd);
			$this->assertEquals($invalidCwd->root, $invalidCwd->realcwd);
		}

		//test that it fixes invalid modes.
		{
			$validModes = array('r', 'r+', 'w', 'w+', 'a', 'a+', 'x', 'x+', 'c', 'c+');
			$invalidModes = array('b', 'b+', 'd', 'd+', 'e', 'e+');

			foreach($validModes as $x) {
				$testMe = new FileSystem(dirname(__FILE__), null, $x);
				$this->assertEquals($x, $testMe->mode);
			}

			foreach($invalidModes as $x) {
				$testMe = new FileSystem(dirname(__FILE__), null, $x);
				$this->assertNotEquals($x, $testMe->mode);
				$this->assertEquals('r+', $testMe->mode);
			}
		}
	}
	//-------------------------------------------------------------------------

	//-------------------------------------------------------------------------
	/**
	 * @expectedException InvalidArgumentException
	 */
	public function test_exception_invalidRoot() {
		new FileSystem(null);
	}
	//-------------------------------------------------------------------------

	//-------------------------------------------------------------------------
	public function test_readWrite() {

		$this->assertEquals($this->reader->root, dirname(__FILE__) .'/files');

		$outsideLs = $this->reader->ls("templates");

		$this->reader->cd("templates");
		$insideLs = $this->reader->ls();

		$this->assertEquals($outsideLs, $insideLs);

		//okay, read all the files & make the writer create them.
		foreach($insideLs as $file=>$data) {
			if($data['type'] == 'file') {
				$this->assertEquals(1, $this->writer->create_file($file));

				$this->assertNotEquals($this->writer->realcwd, $this->reader->realcwd);

				//now read data out of one & write into the other, make sure they're the same size.
				$fileSize = $this->writer->write($this->reader->read($file), $file);
				$this->assertEquals($fileSize, $data['size']);

				//now get rid of the new file.
				$this->writer->rm($file);
			}
		}

		//lets take the contents of ALL of those files, push it into one big file, and make sure it is identical.
		$testFilename_a = 'concat_file.txt';
		$testFilename_aplus = 'concat_file2.txt';
		$this->writer->create_file($testFilename_a);
		$this->writer->create_file($testFilename_aplus);

		$totalSize = 0;
		$totalContent = "";
		$loop=0;
		foreach($insideLs as $file=>$data) {
			$totalSize += $data['size'];

			$content = $this->reader->read($file);
			$totalContent .= $content;

			$this->writer->openFile($testFilename_a, 'a');
			$this->writer->append_to_file($content, null);
			$this->writer->closeFile();

			$this->writer->openFile($testFilename_aplus, 'a+');
			$this->writer->append_to_file($content, null);
			$this->writer->closeFile();

			$loop++;
		}

		//now lets read each file & see if they have the proper content...
		$this->assertEquals($totalContent, $this->writer->read($testFilename_a));
		$this->assertEquals($totalContent, $this->writer->read($testFilename_aplus));

		//Test if it can create and then move around within a file properly
		{
			//Generated from http://www.lipsum.com/feed/html
			$fileLines = array(
				'Lorem ipsum dolor sit amet, consectetur adipiscing elit.',
				'Nam nec risus eu mauris euismod convallis eget eget mi.',
				'Morbi eget mi eu sapien mollis porttitor vitae ut augue.',
				'Pellentesque porta volutpat sem, quis facilisis nulla dictum vitae.',
				'Praesent tempus lorem sit amet tortor tempor blandit.'
			);

			$appendTestFile = 'lipsum.txt';
			$this->writer->create_file($appendTestFile);
			$this->writer->openFile($appendTestFile, 'a+');

			//now let's make the array MASSIVE by replicating the file lines over & over again.
			$finalFileLines = array();
			$replicate = 100;
			$myContent = null;
			$actualNum = 0;
			for($x=0; $x<$replicate;$x++) {
				foreach($fileLines as $x2=>$line) {
					$myLine = "line #". $actualNum ." ". $line;
					$myContent .= $myLine ."\n";

					$this->writer->append_to_file($myLine);
					$actualNum++;
				}
			}
			$this->writer->closeFile();

			//now make sure the contents of the file are as expected...
			$this->assertEquals($myContent, $this->writer->read($appendTestFile));

			unset($myContent,$finalFileLines);

			//randomly pull a line and make sure it starts with the right phrase.
			$this->writer->openFile($appendTestFile, 'r');
			$linesToTest = 10;

			for($i=0;$i<$linesToTest;$i++) {
				$randomLine = rand(0, ($actualNum -1));

				$this->writer->go_to_line($randomLine);
				$lineContents = $this->writer->get_next_line();

				$actualLine = $randomLine +1;
				$regex = "line #$randomLine";
				$error = "fetched line #$randomLine ($actualLine), should start with '$regex', but didn't... actual::: ". $lineContents;
				$this->assertTrue((bool)preg_match('/^'. $regex .' /', $lineContents), $error);
			}

			$this->writer->go_to_last_line();
			$this->writer->go_to_line(($this->writer->lineNum -2));//go back two lines because we're actually past the last line, gotta go 2 up so when we fetch "the next line", it is actually the last.
			$lineContents = $this->writer->get_next_line();
			$this->assertTrue((bool)preg_match('/^line #'. ($this->writer->lineNum -1) .' /', $lineContents));

			$this->writer->closeFile();
		}

		//now let's try moving a file.
		$newName = "movedFile.txt";
		$lsData = $this->writer->ls();
		$this->assertTrue(isset($lsData[$appendTestFile]));
		$this->writer->move_file($appendTestFile, $newName);

		//change the array and make sure it is approximately the same.
		$newLsData = $this->writer->ls();
		$tmp = $lsData[$appendTestFile];
		unset($lsData[$appendTestFile]);
		$lsData[$newName] = $tmp;
		$this->assertEquals($newLsData, $lsData);

		//now delete the files.
		foreach($this->writer->ls() as $file=>$garbage) {
			$this->assertTrue($this->writer->rm($file));
		}
	}//end test_readWrite()
	//-------------------------------------------------------------------------

	//-------------------------------------------------------------------------
	public function test_navigationAndLs() {
		$fs = new FileSystem(dirname(__FILE__));

		$thisFile = basename(__FILE__);

		$list = $fs->ls();

		$this->assertTrue(isset($thisFile, $list));
		$this->assertTrue(is_array($list[$thisFile]));
		$this->assertEquals($list[$thisFile]['type'], 'file');

		$this->assertTrue(isset($list['files']));
		$this->assertEquals($list['files']['type'], 'dir');

		$this->assertTrue((bool)$fs->cd('files'));

		$this->assertEquals($fs->cwd, '/files');
		$this->assertEquals($fs->realcwd, dirname(__FILE__) .'/files');

		$this->assertTrue($fs->cdup());
		$this->assertEquals($fs->cwd, '/');
		$this->assertEquals(preg_replace('~/$~', '', $fs->realcwd), dirname(__FILE__));

		//this should fail, because it's higher than allowed.
		$this->assertFalse($fs->cdup());
		$this->assertEquals($fs->cwd, '/');
		$this->assertEquals(preg_replace('~/$~', '', $fs->realcwd), dirname(__FILE__));

		$this->assertTrue((bool)$fs->cd('/'));
		$this->assertEquals($fs->cwd, '/');
		$this->assertEquals(preg_replace('~/$~', '', $fs->realcwd), dirname(__FILE__));

		//make sure we can still find just this file.
		$fileInfo = $fs->ls(basename(__FILE__));
		$this->assertTrue(is_array($fileInfo));

		$this->assertEquals(count($fileInfo), 1, "too many files in the array...");
		$this->assertTrue(isset($fileInfo[basename(__FILE__)]));
		$this->assertTrue(isset($fileInfo[basename(__FILE__)]['type']), "malformed array, should ONLY contain info about this file::: ". ToolBox::debug_print($fileInfo,0));
	}
	//-------------------------------------------------------------------------

	//-------------------------------------------------------------------------
	public function test_pathFixing() {
		$fs = new _fs_testProtectedMethods(dirname(__FILE__));

		$this->assertEquals($fs->root, dirname(__FILE__));

		//make sure it comes up with the REAL path when there's dots involved...
		$this->assertEquals(
				'/real/path/to/file',
				ToolBox::resolve_path_with_dots('/path/../real/fake/../path/from/../to/./file')
		);

		$this->assertEquals(__FILE__, $fs->_2absolute('/'. basename(__FILE__)));
	}
	//-------------------------------------------------------------------------

	/**
	 * @expectedException InvalidArgumentException
	 */
	public function test_resolvePathException() {
		ToolBox::resolve_path_with_dots(NULL);
	}

}//end TestOfCSFileSystem
//=============================================================================

//=============================================================================
class _fs_testProtectedMethods extends FileSystem {
	public function __construct($rootDir=NULL, $cwd=NULL, $initialMode=NULL) {
		parent::__construct($rootDir, $cwd, $initialMode);
	}
	public function _2absolute($filename) {
		return(parent::filename2absolute($filename));
	}
}//end _fs_testProtectedMethods
//=============================================================================


text:
<?xml version="1.0" encoding="UTF-8"?>
<!-- Created by libAntimony version v2.3-beta with libSBML version 5.6.0. -->
<sbml xmlns="http://www.sbml.org/sbml/level3/version1/core" xmlns:comp="http://www.sbml.org/sbml/level3/version1/comp/version1" level="3" version="1" comp:required="true">
  <model id="CompTest" name="CompTest">
    <listOfFunctionDefinitions>
      <functionDefinition id="f">
        <math xmlns="http://www.w3.org/1998/Math/MathML">
          <lambda>
            <bvar>
              <ci> x </ci>
            </bvar>
            <apply>
              <times/>
              <cn type="integer"> 2 </cn>
              <ci> x </ci>
            </apply>
          </lambda>
        </math>
      </functionDefinition>
      <functionDefinition id="neighborQuantityLeft">
        <math xmlns="http://www.w3.org/1998/Math/MathML">
          <lambda>
            <bvar>
              <ci> a </ci>
            </bvar>
            <cn type="integer"> 0 </cn>
          </lambda>
        </math>
      </functionDefinition>
      <functionDefinition id="neighborQuantityRight">
        <math xmlns="http://www.w3.org/1998/Math/MathML">
          <lambda>
            <bvar>
              <ci> a </ci>
            </bvar>
            <cn type="integer"> 0 </cn>
          </lambda>
        </math>
      </functionDefinition>
      <functionDefinition id="neighborQuantityAbove">
        <math xmlns="http://www.w3.org/1998/Math/MathML">
          <lambda>
            <bvar>
              <ci> a </ci>
            </bvar>
            <cn type="integer"> 0 </cn>
          </lambda>
        </math>
      </functionDefinition>
      <functionDefinition id="neighborQuantityBelow">
        <math xmlns="http://www.w3.org/1998/Math/MathML">
          <lambda>
            <bvar>
              <ci> a </ci>
            </bvar>
            <cn type="integer"> 0 </cn>
          </lambda>
        </math>
      </functionDefinition>
      <functionDefinition id="getCompartmentLocationX">
        <math xmlns="http://www.w3.org/1998/Math/MathML">
          <lambda>
            <bvar>
              <ci> a </ci>
            </bvar>
            <cn type="integer"> 0 </cn>
          </lambda>
        </math>
      </functionDefinition>
      <functionDefinition id="getCompartmentLocationY">
        <math xmlns="http://www.w3.org/1998/Math/MathML">
          <lambda>
            <bvar>
              <ci> a </ci>
            </bvar>
            <cn type="integer"> 0 </cn>
          </lambda>
        </math>
      </functionDefinition>
    </listOfFunctionDefinitions>
    <listOfCompartments>
      <compartment id="Cell" spatialDimensions="3" size="1" constant="true">
        <comp:listOfReplacedElements>
          <comp:replacedElement comp:idRef="Cell" comp:submodelRef="C1"/>
        </comp:listOfReplacedElements>
      </compartment>
    </listOfCompartments>
    <listOfSpecies>
      <species id="S1" compartment="Cell" initialConcentration="0" hasOnlySubstanceUnits="false" boundaryCondition="false" constant="false">
        <comp:listOfReplacedElements>
          <comp:replacedElement comp:idRef="S2" comp:submodelRef="C1"/>
        </comp:listOfReplacedElements>
      </species>
      <species id="S2" compartment="Cell" initialConcentration="0" hasOnlySubstanceUnits="false" boundaryCondition="false" constant="false">
        <comp:listOfReplacedElements>
          <comp:replacedElement comp:idRef="S1" comp:submodelRef="C1"/>
        </comp:listOfReplacedElements>
      </species>
    </listOfSpecies>
    <listOfParameters>
      <parameter id="kr_f" name="Forward repression binding rate" value="0.5" constant="true"/>
      <parameter id="kr_r" name="Reverse repression binding rate" value="1" constant="true"/>
      <parameter id="ka_f" name="Forward activation binding rate" value="0.0033" constant="true"/>
      <parameter id="ka_r" name="Reverse activation binding rate" value="1" constant="true"/>
      <parameter id="kc_f" name="Forward complex formation rate" value="0.05" constant="true"/>
      <parameter id="kc_r" name="Reverse complex formation rate" value="1" constant="true"/>
      <parameter id="ko_f" name="Forward RNAP binding rate" value="0.033" constant="true"/>
      <parameter id="ko_r" name="Reverse RNAP binding rate" value="1" constant="true"/>
      <parameter id="kao_f" name="Forward activated RNAP binding rate" value="1" constant="true"/>
      <parameter id="kao_r" name="Reverse activated RNAP binding rate" value="1" constant="true"/>
      <parameter id="kmdiff_f" name="Forward membrane diffusion rate" value="1" constant="true"/>
      <parameter id="kmdiff_r" name="Reverse membrane diffusion rate" value="0.01" constant="true"/>
      <parameter id="kd" name="Degradation rate" value="0.0075" constant="true"/>
      <parameter id="kecd" name="Extracellular degradation rate" value="0.005" constant="true"/>
      <parameter id="nc" name="Stoichiometry of binding" value="2" constant="true"/>
      <parameter id="nr" name="Initial RNAP count" value="30" constant="true"/>
      <parameter id="ko" name="Open complex production rate" value="0.05" constant="true"/>
      <parameter id="kb" name="Basal production rate" value="0.0001" constant="true"/>
      <parameter id="ng" name="Initial promoter count" value="2" constant="true"/>
      <parameter id="np" name="Stoichiometry of production" value="10" constant="true"/>
      <parameter id="ka" name="Activated production rate" value="0.25" constant="true"/>
      <parameter id="kecdiff" name="Extracellular diffusion rate" value="1" constant="true"/>
      <parameter id="topKf" value="3" constant="true">
        <comp:listOfReplacedElements>
          <comp:replacedElement comp:idRef="R3_kf0" comp:submodelRef="C1"/>
        </comp:listOfReplacedElements>
      </parameter>
    </listOfParameters>
    <comp:listOfSubmodels>
      <comp:submodel comp:id="C1" comp:modelRef="CompModel">
        <comp:listOfDeletions>
          <comp:deletion comp:unitRef="perSecond"/>
          <comp:deletion comp:idRef="event0"/>
          <comp:deletion comp:idRef="event1"/>
        </comp:listOfDeletions>
      </comp:submodel>
    </comp:listOfSubmodels>
    <comp:listOfPorts>
      <comp:port comp:idRef="Cell" comp:id="Cell"/>
    </comp:listOfPorts>
  </model>
  <comp:listOfModelDefinitions>
    <comp:modelDefinition id="CompModel" name="CompModel">
      <listOfFunctionDefinitions>
        <functionDefinition id="f">
          <math xmlns="http://www.w3.org/1998/Math/MathML">
            <lambda>
              <bvar>
                <ci> x </ci>
              </bvar>
              <apply>
                <times/>
                <cn type="integer"> 2 </cn>
                <ci> x </ci>
              </apply>
            </lambda>
          </math>
        </functionDefinition>
        <functionDefinition id="neighborQuantityLeft">
          <math xmlns="http://www.w3.org/1998/Math/MathML">
            <lambda>
              <bvar>
                <ci> a </ci>
              </bvar>
              <cn type="integer"> 0 </cn>
            </lambda>
          </math>
        </functionDefinition>
        <functionDefinition id="neighborQuantityRight">
          <math xmlns="http://www.w3.org/1998/Math/MathML">
            <lambda>
              <bvar>
                <ci> a </ci>
              </bvar>
              <cn type="integer"> 0 </cn>
            </lambda>
          </math>
        </functionDefinition>
        <functionDefinition id="neighborQuantityAbove">
          <math xmlns="http://www.w3.org/1998/Math/MathML">
            <lambda>
              <bvar>
                <ci> a </ci>
              </bvar>
              <cn type="integer"> 0 </cn>
            </lambda>
          </math>
        </functionDefinition>
        <functionDefinition id="neighborQuantityBelow">
          <math xmlns="http://www.w3.org/1998/Math/MathML">
            <lambda>
              <bvar>
                <ci> a </ci>
              </bvar>
              <cn type="integer"> 0 </cn>
            </lambda>
          </math>
        </functionDefinition>
        <functionDefinition id="getCompartmentLocationX">
          <math xmlns="http://www.w3.org/1998/Math/MathML">
            <lambda>
              <bvar>
                <ci> a </ci>
              </bvar>
              <cn type="integer"> 0 </cn>
            </lambda>
          </math>
        </functionDefinition>
        <functionDefinition id="getCompartmentLocationY">
          <math xmlns="http://www.w3.org/1998/Math/MathML">
            <lambda>
              <bvar>
                <ci> a </ci>
              </bvar>
              <cn type="integer"> 0 </cn>
            </lambda>
          </math>
        </functionDefinition>
      </listOfFunctionDefinitions>
      <listOfUnitDefinitions>
        <unitDefinition id="perSecond">
          <listOfUnits>
            <unit kind="second" exponent="-1" scale="0" multiplier="1"/>
          </listOfUnits>
        </unitDefinition>
      </listOfUnitDefinitions>
      <listOfCompartments>
        <compartment id="Cell" spatialDimensions="3" size="1" constant="true"/>
      </listOfCompartments>
      <listOfSpecies>
        <species id="S1" compartment="Cell" initialConcentration="0" hasOnlySubstanceUnits="false" boundaryCondition="false" constant="false"/>
        <species id="S2" compartment="Cell" initialConcentration="0" hasOnlySubstanceUnits="false" boundaryCondition="false" constant="false"/>
      </listOfSpecies>
      <listOfParameters>
        <parameter id="V1" constant="false"/>
        <parameter id="V2" value="0" constant="false"/>
        <parameter id="R1_kf" value="0.1" constant="true"/>
        <parameter id="R3_kf" value="0.1" constant="true"/>
        <parameter id="kr_f" name="Forward repression binding rate" value="0.5" constant="true"/>
        <parameter id="kr_r" name="Reverse repression binding rate" value="1" constant="true"/>
        <parameter id="ka_f" name="Forward activation binding rate" value="0.0033" constant="true"/>
        <parameter id="ka_r" name="Reverse activation binding rate" value="1" constant="true"/>
        <parameter id="kc_f" name="Forward complex formation rate" value="0.05" constant="true"/>
        <parameter id="kc_r" name="Reverse complex formation rate" value="1" constant="true"/>
        <parameter id="ko_f" name="Forward RNAP binding rate" value="0.033" constant="true"/>
        <parameter id="ko_r" name="Reverse RNAP binding rate" value="1" constant="true"/>
        <parameter id="kao_f" name="Forward activated RNAP binding rate" value="1" constant="true"/>
        <parameter id="kao_r" name="Reverse activated RNAP binding rate" value="1" constant="true"/>
        <parameter id="kmdiff_f" name="Forward membrane diffusion rate" value="1" constant="true"/>
        <parameter id="kmdiff_r" name="Reverse membrane diffusion rate" value="0.01" constant="true"/>
        <parameter id="kd" name="Degradation rate" value="0.0075" constant="true"/>
        <parameter id="kecd" name="Extracellular degradation rate" value="0.005" constant="true"/>
        <parameter id="nc" name="Stoichiometry of binding" value="2" constant="true"/>
        <parameter id="nr" name="Initial RNAP count" value="30" constant="true"/>
        <parameter id="ko" name="Open complex production rate" value="0.05" constant="true"/>
        <parameter id="kb" name="Basal production rate" value="0.0001" constant="true"/>
        <parameter id="ng" name="Initial promoter count" value="2" constant="true"/>
        <parameter id="np" name="Stoichiometry of production" value="10" constant="true"/>
        <parameter id="ka" name="Activated production rate" value="0.25" constant="true"/>
        <parameter id="kecdiff" name="Extracellular diffusion rate" value="1" constant="true"/>
        <parameter id="kf" value="2" constant="true"/>
        <parameter id="R1_kr" value="1" constant="true"/>
        <parameter id="R3_kr" value="1" constant="true"/>
        <parameter id="R1_kf0" value="1" constant="true"/>
        <parameter id="R3_kf0" value="1" constant="true"/>
        <parameter id="x" constant="true"/>
      </listOfParameters>
      <listOfRules>
        <assignmentRule variable="V1">
          <math xmlns="http://www.w3.org/1998/Math/MathML">
            <apply>
              <plus/>
              <ci> S1 </ci>
              <ci> S2 </ci>
            </apply>
          </math>
        </assignmentRule>
        <rateRule variable="V2">
          <math xmlns="http://www.w3.org/1998/Math/MathML">
            <apply>
              <times/>
              <ci> S1 </ci>
              <ci> S2 </ci>
            </apply>
          </math>
        </rateRule>
      </listOfRules>
      <listOfReactions>
        <reaction id="R1" reversible="false" fast="false">
          <listOfReactants>
            <speciesReference species="S1" stoichiometry="1" constant="true"/>
          </listOfReactants>
          <listOfProducts>
            <speciesReference species="S2" stoichiometry="1" constant="true"/>
          </listOfProducts>
          <kineticLaw>
            <math xmlns="http://www.w3.org/1998/Math/MathML">
              <apply>
                <times/>
                <ci> R1_kf0 </ci>
                <ci> S1 </ci>
              </apply>
            </math>
          </kineticLaw>
        </reaction>
        <reaction id="R3" reversible="false" fast="false">
          <listOfReactants>
            <speciesReference species="S2" stoichiometry="1" constant="true"/>
          </listOfReactants>
          <listOfProducts>
            <speciesReference species="S1" stoichiometry="1" constant="true"/>
          </listOfProducts>
          <kineticLaw>
            <math xmlns="http://www.w3.org/1998/Math/MathML">
              <apply>
                <times/>
                <ci> R3_kf0 </ci>
                <ci> S2 </ci>
              </apply>
            </math>
          </kineticLaw>
        </reaction>
      </listOfReactions>
      <listOfEvents>
        <event id="event0" useValuesFromTriggerTime="false">
          <trigger initialValue="false" persistent="false">
            <math xmlns="http://www.w3.org/1998/Math/MathML">
              <apply>
                <geq/>
                <csymbol encoding="text" definitionURL="http://www.sbml.org/sbml/symbols/time"> time </csymbol>
                <cn type="integer"> 100 </cn>
              </apply>
            </math>
          </trigger>
          <delay>
            <math xmlns="http://www.w3.org/1998/Math/MathML">
              <cn type="integer"> 10 </cn>
            </math>
          </delay>
          <listOfEventAssignments>
            <eventAssignment variable="S1">
              <math xmlns="http://www.w3.org/1998/Math/MathML">
                <cn type="integer"> 10 </cn>
              </math>
            </eventAssignment>
          </listOfEventAssignments>
        </event>
        <event id="event1" useValuesFromTriggerTime="false">
          <trigger initialValue="false" persistent="false">
            <math xmlns="http://www.w3.org/1998/Math/MathML">
              <true/>
            </math>
          </trigger>
          <delay>
            <math xmlns="http://www.w3.org/1998/Math/MathML">
              <cn type="integer"> 100 </cn>
            </math>
          </delay>
          <listOfEventAssignments>
            <eventAssignment variable="S2">
              <math xmlns="http://www.w3.org/1998/Math/MathML">
                <cn type="integer"> 100 </cn>
              </math>
            </eventAssignment>
          </listOfEventAssignments>
        </event>
      </listOfEvents>
      <comp:listOfPorts>
        <comp:port comp:idRef="Cell" comp:id="Cell"/>
        <comp:port comp:idRef="R1" comp:id="R1"/>
        <comp:port comp:idRef="R3" comp:id="R3"/>
        <comp:port comp:idRef="event0" comp:id="event0"/>
        <comp:port comp:idRef="event1" comp:id="event1"/>
        <comp:port comp:idRef="R3_kf0" comp:id="R3_kf0"/>
        <comp:port comp:idRef="R1_kf0" comp:id="R1_kf0"/>
        <comp:port comp:unitRef="perSecond" comp:id="unit_perSecond"/>
        <comp:port comp:idRef="S1" comp:id="S1"/>
        <comp:port comp:idRef="S2" comp:id="S2"/>
      </comp:listOfPorts>
    </comp:modelDefinition>
  </comp:listOfModelDefinitions>
</sbml>


text:
package org.alljoyn.ioe.controlpanelservice.communication.interfaces;

import java.util.Map;

import org.alljoyn.bus.BusException;
import org.alljoyn.bus.Variant;
import org.alljoyn.bus.annotation.BusInterface;
import org.alljoyn.bus.annotation.BusProperty;
import org.alljoyn.bus.annotation.BusSignal;
import org.alljoyn.ioe.controlpanelservice.ControlPanelService;

/**
 * UIContainer interface
 */
@BusInterface (name = Container.IFNAME)
public interface Container extends ContainerSuper {
	public static final String IFNAME = ControlPanelService.INTERFACE_PREFIX + ".Container";

	public static final short VERSION = 1;

	/**
	 * @return Interface version
	 */
	@BusProperty(signature="q")
	public short getVersion() throws BusException;

	/**
	 * @return States bitmask
	 * @throws BusException
	 */
	@BusProperty(signature="u")
	public int getStates() throws BusException;

	/**
	 * @return Optional parameters
	 * @throws BusException
	 */
	@BusProperty(signature="a{qv}")
	public Map<Short,Variant> getOptParams() throws BusException;

	/**
	 * Signal is sent when the UI container metadata changed
	 * @param metadata
	 */
	@BusSignal
	public void MetadataChanged() throws BusException;
}


text:
import React from 'react';
import { Col, Button, ButtonGroup, FormGroup } from 'react-bootstrap';

import Switch from '../../src/js/index';

export class OnColor extends React.Component {

  constructor(props){
    super(props);

    this.state = {
      color: "info"
    };
  }

  _clickPrimary(){
    this.setState({
      color: "primary"
    });
  }

  _clickInfo(){
    this.setState({
      color: "info"
    });
  }

  _clickSuccess(){
    this.setState({
      color: "success"
    });
  }

  _clickWarning(){
    this.setState({
      color: "warning"
    });
  }

  _clickDefault(){
    this.setState({
      color: "default"
    });
  }

  render(){
    return (
      <Col xs={6} md={4}>

On Color

        <form>
          <FormGroup>
            <Switch onColor={this.state.color} />
          </FormGroup>

          <FormGroup>
            <ButtonGroup>
              <Button onClick={this._clickPrimary.bind(this)} >Primary</Button>
              <Button onClick={this._clickInfo.bind(this)} >Info</Button>
              <Button onClick={this._clickSuccess.bind(this)} >Success</Button>
              <Button onClick={this._clickWarning.bind(this)} >Warning</Button>
              <Button onClick={this._clickDefault.bind(this)} >Default</Button>
            </ButtonGroup>
          </FormGroup>
        </form>
      </Col>
    );
  }
}


text:
namespace Octokit.Reactive
{
    ///
    /// A client for GitHub's Repository Actions API.
    ///
    /// <remarks>
    /// See the Repository Actions API documentation for more details.
    /// </remarks>
    public class ObservableRepositoryActionsClient : IObservableRepositoryActionsClient
    {
        readonly IRepositoryActionsClient _client;
        readonly IConnection _connection;

        public ObservableRepositoryActionsClient(IGitHubClient client)
        {
            Ensure.ArgumentNotNull(client, nameof(client));

            _client = client.Repository.Actions;
            _connection = client.Connection;

            Secrets = new ObservableRepositorySecretsClient(client);
        }

        ///
        /// Client for GitHub's Repository Actions API
        ///
        /// <remarks>
        /// See the Deployments API documentation for more details
        /// </remarks>
        public IObservableRepositorySecretsClient Secrets { get; private set; }
    }
}


text:
var _ = require('lodash');

var self = module.exports = {
  __module: {
    properties: {
      use_stylesheets: 'svc!resources/use_stylesheets',
      util: 'assetmanager/util',
      staticUrlRoot: 'config!resources.staticUrlRoot'
    },
    provides: {"assetmanager/build/sources/define_sources": {}}
  },

  define_sources: function(definitions) {
    return self.use_stylesheets().then(function(styles) {
      definitions.resources.styles = {
        namespaces: self.util.groupResources(
          _.compact(_.flatten(styles, true))
        ),
        options: {
          injectFilter: "**/*.jade",
          injectOptions: {
            urlPrefix: self.staticUrlRoot,
            defaultExtension: "css"
          }
        }
      };
      return definitions;
    });
  }
};


text:
"use strict";
import { BrainWallet } from "./brain-wallet";
import { NonceManager } from "./nonce-manager";
import { Eip1193Bridge } from "./eip1193-bridge";
export { BrainWallet, Eip1193Bridge, NonceManager };
//# sourceMappingURL=index.js.map


text:
import wx
import wx.adv

#----------------------------------------------------------------------
# This ComboBox class graphically displays the various pen styles that
# are available, making it easy for the user to choose the style they
# want.

class PenStyleComboBox(wx.adv.OwnerDrawnComboBox):

    # Overridden from OwnerDrawnComboBox, called to draw each
    # item in the list
    def OnDrawItem(self, dc, rect, item, flags):
        if item == wx.NOT_FOUND:
            # painting the control, but there is no valid item selected yet
            return

        r = wx.Rect(*rect)  # make a copy
        r.Deflate(3, 5)

        penStyle = wx.PENSTYLE_SOLID
        if item == 1:
            penStyle = wx.PENSTYLE_TRANSPARENT
        elif item == 2:
            penStyle = wx.PENSTYLE_DOT
        elif item == 3:
            penStyle = wx.PENSTYLE_LONG_DASH
        elif item == 4:
            penStyle = wx.PENSTYLE_SHORT_DASH
        elif item == 5:
            penStyle = wx.PENSTYLE_DOT_DASH
        elif item == 6:
            penStyle = wx.PENSTYLE_BDIAGONAL_HATCH
        elif item == 7:
            penStyle = wx.PENSTYLE_CROSSDIAG_HATCH
        elif item == 8:
            penStyle = wx.PENSTYLE_FDIAGONAL_HATCH
        elif item == 9:
            penStyle = wx.PENSTYLE_CROSS_HATCH
        elif item == 10:
            penStyle = wx.PENSTYLE_HORIZONTAL_HATCH
        elif item == 11:
            penStyle = wx.PENSTYLE_VERTICAL_HATCH

        pen = wx.Pen(dc.GetTextForeground(), 3, penStyle)
        dc.SetPen(pen)

        if flags & wx.adv.ODCB_PAINTING_CONTROL:
            # for painting the control itself
            dc.DrawLine( r.x+5, r.y+r.height/2, r.x+r.width - 5, r.y+r.height/2 )

        else:
            # for painting the items in the popup
            dc.DrawText(self.GetString( item ),
                        r.x + 3,
                        (r.y + 0) + ( (r.height/2) - dc.GetCharHeight() )/2
                        )
            dc.DrawLine( r.x+5, r.y+((r.height/4)*3)+1, r.x+r.width - 5, r.y+((r.height/4)*3)+1 )

    # Overridden from OwnerDrawnComboBox, called for drawing the
    # background area of each item.
    def OnDrawBackground(self, dc, rect, item, flags):
        # If the item is selected, or its item # iseven, or we are painting the
        # combo control itself, then use the default rendering.
        if (item & 1 == 0 or flags & (wx.adv.ODCB_PAINTING_CONTROL |
                                      wx.adv.ODCB_PAINTING_SELECTED)):
            wx.adv.OwnerDrawnComboBox.OnDrawBackground(self, dc, rect, item, flags)
            return

        # Otherwise, draw every other background with different colour.
        bgCol = wx.Colour(240,240,250)
        dc.SetBrush(wx.Brush(bgCol))
        dc.SetPen(wx.Pen(bgCol))
        dc.DrawRectangle(rect);

    # Overridden from OwnerDrawnComboBox, should return the height
    # needed to display an item in the popup, or -1 for default
    def OnMeasureItem(self, item):
        # Simply demonstrate the ability to have variable-height items
        if item & 1:
            return 36
        else:
            return 24

    # Overridden from OwnerDrawnComboBox.  Callback for item width, or
    # -1 for default/undetermined
    def OnMeasureItemWidth(self, item):
        return -1; # default - will be measured from text width

#----------------------------------------------------------------------

class TestPanel(wx.Panel):
    def __init__(self, parent, log):
        self.log = log
        wx.Panel.__init__(self, parent, -1)

        penStyles = [
            "Solid",
            "Transparent",
            "Dot",
            "Long Dash",
            "Short Dash",
            "Dot Dash",
            "Backward Diagonal Hatch",
            "Cross-diagonal Hatch",
            "Forward Diagonal Hatch",
            "Cross Hatch",
            "Horizontal Hatch",
            "Vertical Hatch",
            ]

        wx.StaticText(self, -1, "Pen Styles:", (20, 20))
        pscb = PenStyleComboBox(self, choices=penStyles, style=wx.CB_READONLY,
                                pos=(20,40), size=(250, -1))

        self.pscb = pscb

#----------------------------------------------------------------------

def runTest(frame, nb, log):
    win = TestPanel(nb, log)
    return win

#----------------------------------------------------------------------

overview = """

wx.combo.OwnerDrawnComboBox

wx.combo.OwnerDrawnComboBox is a combobox with owner-drawn list
items. In essence, it is a wx.combo.ComboCtrl with wx.VListBox popup and
wx.ControlWithItems interface.

"""

if __name__ == '__main__':
    import sys,os
    import run
    run.main(['', os.path.basename(sys.argv[0])] + sys.argv[1:])


text:
namespace Icu.Collation
{

	/// <summary>
	/// Attribute for direction of secondary weights - used in French.
	/// </summary>
	public enum FrenchCollation
	{
		/// <summary>
		/// Default value, does nothing.
		/// </summary>
		Default = -1,
		/// <summary>
		/// treats secondary weights in the order they appear
		/// </summary>
		Off = 16,
		/// <summary>
		/// secondary weights are considered backwards
		/// </summary>
		On = 17
	}
}


text:
'use strict';

require('es6-promise').polyfill();
require('isomorphic-fetch');

var sendgrid = require("sendgrid")(process.env.SENDGRID_KEY);
var email = new sendgrid.Email();

const redis = require("redis");
const client = redis.createClient({url: process.env.REDISTOGO_URL});

const npmUrl = 'https://www.npmjs.com/package/';

const versionRegex = /(\d{1,2}\.\d{1,2}\.\d{1,2})/;
const npmVersionRegex = /(\d{1,2}\.\d{1,2}\.\d{1,2})\<\/strong\>\s+is the latest/;
const majorVersionRegex = /(\d{1,2})\.\d{1,2}\.\d{1,2}/;
const minorVersionRegex = /\d{1,2}\.(\d{1,2})\.\d{1,2}/;

const minorDependencies = process.env.MINOR_DEPENDENCIES ? process.env.MINOR_DEPENDENCIES.split(/[ ,]+/) : [];
const packageJsonUrls = process.env.PACKAGE_JSON_URLS ? process.env.PACKAGE_JSON_URLS.split(/[ ,]+/) : [];

client.on("error", function (err) {
  console.error("Error " + err);
});

packageJsonUrls.forEach(packageJsonUrl => {
  fetch(packageJsonUrl)
  .then(response => {
    return response.text();
  })
  .then(text => {
    let parsedText = JSON.parse(text);
    let dependencies = parsedText.dependencies;
    let devDependencies = parsedText.devDependencies;
    let allDependencies = Object.assign(dependencies, devDependencies);

    let allDependenciesArray = Object.keys(allDependencies);

    allDependenciesArray.forEach(dependency => {
      let dependencyPackageJsonVersion = allDependencies[dependency].match(versionRegex)[1];
      client.set(dependency, dependencyPackageJsonVersion);
      getLastVersion(dependency).then(lastVersion => {
        if (lastVersion) {
          client.get(dependency, (err, dependencyPackageJsonVersion) => {
            if (err) console.error('error setting the package json version');
            detectMajorVersion(dependency, dependencyPackageJsonVersion, lastVersion, packageJsonUrl);
          })
        }
      });
    });
  })
  .catch(error => {
    console.error(error);
  });
})

let getLastVersion = (dependency) => {
  return fetch(npmUrl + dependency)
  .then(response => {
    return response.text();
  })
  .then(text => {
    let match = text.match(npmVersionRegex);
    if (match) {
      return match[1];
    } else {
      return false;
    }
  })
  .catch(error => {
    console.error('error: ' + error);
  });
}

let detectMajorVersion = (dependency, dependencyPackageJsonVersion, lastVersion, packageJsonUrl) => {
  let dependencyPackageJsonVersionMajorVersion = dependencyPackageJsonVersion.match(majorVersionRegex)[1];
  let dependencyPackageJsonVersionMinorVersion = dependencyPackageJsonVersion.match(minorVersionRegex)[1];

  let lastVersionMajorVersion = lastVersion.match(majorVersionRegex)[1];
  let lastVersionMinorVersion = lastVersion.match(minorVersionRegex)[1];

  if (parseInt(dependencyPackageJsonVersionMajorVersion) < parseInt(lastVersionMajorVersion)) {
    client.get(dependency + '-' + lastVersion + '-notification', (err, reply) => {
      if (err) console.error('error getting dependency version notification (for major)');
      if (!reply) {
        notify(dependency, dependencyPackageJsonVersion, lastVersion, packageJsonUrl, true);
      }
    })
  } else if ((parseInt(dependencyPackageJsonVersionMinorVersion) < parseInt(lastVersionMinorVersion))  && contains(minorDependencies, dependency)) {
    client.get(dependency + '-' + lastVersion + '-notification', (err, reply) => {
      if (err) console.error('error getting dependency version notification (for minor)');
      if (!reply) {
        notify(dependency, dependencyPackageJsonVersion, lastVersion, packageJsonUrl, false);
      }
    })
  }
}

let notify = (dependency, dependencyPackageJsonVersion, lastVersion, packageJsonUrl, isMajor) => {
  var email = new sendgrid.Email(generateMessage(dependency, dependencyPackageJsonVersion, lastVersion, packageJsonUrl, isMajor));

  email.setTos(process.env.EMAILS.split(/[ ,]+/));

  sendgrid.send(email, function(err, json) {
    if (err) { return console.error(err); }
    console.log(json);
    client.set(dependency + '-' + lastVersion + '-notification', 'true');
  });
}

let generateMessage = (dependency, dependencyPackageJsonVersion, lastVersion, packageJsonUrl, isMajor) => {
  let grade = isMajor ? 'MAJOR' : 'MINOR';
  return {
    'html': '
I have detected that in the package.json ' + packageJsonUrl + ' the dependency ' + dependency + ' has the version ' + dependencyPackageJsonVersion + ' selected and the last one available is the ' + lastVersion + '.
' + '
Go and check out the last changes!: ' + npmUrl + dependency + '.
',
    'subject': '[' + grade + '] ' + dependency + ' ' + lastVersion,
    'from': process.env.SENDER_EMAIL,
    'fromname': process.env.SENDER_NAME
  }
}

function contains(a, obj) {
  for (var i = 0; i < a.length; i++) {
    if (a[i] === obj) {
      return true;
    }
  }
  return false;
}