text:
var onRun = function(context) {

    var ga = require("../modules/Google_Analytics");
    ga("Library");

    var Dialog = require("../modules/Dialog").dialog;
    var ui = require("../modules/Dialog").ui;

    var sketch = require("sketch");
    var document = context.document;

    if (sketch.version.sketch < 48) {
        document.showMessage("😮 You have to update to Sketch 48+ to use this feature.");
        return;
    }

    var libraries = librariesWithConflictID();

    if (!libraries) {
        document.showMessage("You have no libraries.");
        return;
    }

    if (libraries.count() == 0) {
        document.showMessage("😀 You have no libraries with conflict ID.");
        return;
    }

    // Dialog
    var viewWidth = 550,
        viewHeight = 400,
        padding = 10,
        previewImageWidth = 100,
        previewImageHeight = 80;

    var dialog = new Dialog(
        "Fix Library ID Conflict",
        "Change the library ID, will cause symbol's auto update to break.",
        viewWidth,
        ["Close"]
    );

    var scrollView = ui.scrollView([], [0, 0, viewWidth, viewHeight]);
    dialog.addView(scrollView);

    var contentView = ui.view([0, 0, viewWidth, libraries.count() * (previewImageHeight + padding * 2) + 10]);

    var loopLibraries = libraries.objectEnumerator();
    var library;
    var i = 0;
    while (library = loopLibraries.nextObject()) {

        // List
        var itemHeight = previewImageHeight + padding * 2;
        var itemView = ui.view([0, itemHeight * i, viewWidth, itemHeight]);

        // Library full path
        var libraryPath = library.locationOnDisk().path();
        var fullPathView = ui.textLabel(libraryPath, [0, 0, 0, 0]);
        itemView.addSubview(fullPathView);

        var libraryInAppBundle = false;
        var regexBundle = new RegExp("^" + NSBundle.mainBundle().bundlePath().replace(/(\/)/g, "\\/"), "gi");
        if (regexBundle.test(libraryPath)) {
            libraryInAppBundle = true;
        }

        // Preview image
        var imageView = NSView.alloc().initWithFrame(NSMakeRect(padding, padding, previewImageWidth, previewImageHeight));
        imageView.setWantsLayer(true);
        imageView.setCornerRadius(3);
        imageView.layer().setBackgroundColor(CGColorCreateGenericRGB(1, 1, 1, 1));
        imageView.layer().setBorderWidth(1);
        imageView.layer().setBorderColor(CGColorCreateGenericRGB(0, 0, 0, 0.05));
        var imageSrc = NSImageView.alloc().initWithFrame(NSMakeRect(0, 0, previewImageWidth, previewImageHeight));
        var libraryDocument = MSDocumentReader.readerForDocumentAtURL(library.locationOnDisk());
        var image = libraryDocument.libraryPreviewImage();
        imageSrc.setImage(image);
        imageView.addSubview(imageSrc);
        itemView.addSubview(imageView);

        // Open button
        var openButtonView = NSButton.alloc().initWithFrame(NSMakeRect(padding, padding, previewImageWidth, previewImageHeight));
        openButtonView.setButtonType(NSMomentaryChangeButton);
        openButtonView.setBezelStyle(nil);
        openButtonView.setBordered("NO");
        openButtonView.setTitle("");

        if (library.libraryType() == 1 && !libraryInAppBundle) {
            openButtonView.setCOSJSTargetFunction(function(sender) {
                var targetLibraryPath = sender.superview().subviews().objectAtIndex(0).stringValue();
                var targetLibraryURL = NSURL.fileURLWithPath(targetLibraryPath);
                NSApp.stopModal();
                var welcomeWindow = MSWelcomeWindowController.alloc().init();
                welcomeWindow.openDocumentAtURL(targetLibraryURL);
            });
        } else {
            openButtonView.setCOSJSTargetFunction(function(sender) {
                document.showMessage("You can't edit this file.");
            });
        }

        itemView.addSubview(openButtonView);

        // Title
        var titleView = NSTextField.alloc().initWithFrame(NSMakeRect(previewImageWidth + padding * 2, 20, viewWidth - previewImageWidth - 100 + padding * 3, 20));
        titleView.setStringValue(library.name());
        if (!library.enabled()) {
            titleView.setStringValue(library.name() + " 🙈");
        }
        titleView.setFont(NSFont.boldSystemFontOfSize(14));
        titleView.setTextColor(NSColor.blackColor());
        titleView.setBezeled(false);
        titleView.setDrawsBackground(false);
        titleView.setEditable(false);
        titleView.setSelectable(false);
        itemView.addSubview(titleView);

        // Library ID
        var idView = NSTextField.alloc().initWithFrame(NSMakeRect(previewImageWidth + padding * 2, 40, viewWidth - previewImageWidth - 100 + padding * 3, 20));
        idView.setStringValue(library.libraryID());
        idView.setFont(NSFont.monospacedDigitSystemFontOfSize_weight(12, NSFontWeightRegular));
        idView.setTextColor(NSColor.blackColor());
        idView.setBezeled(false);
        idView.setDrawsBackground(false);
        idView.setEditable(false);
        idView.setSelectable(false);
        itemView.addSubview(idView);

        // Library URL
        var locationView = NSTextField.alloc().initWithFrame(NSMakeRect(previewImageWidth + padding * 2, 60, 100, 20));
        locationView.setTextColor(NSColor.grayColor());
        locationView.setBezeled(false);
        locationView.setDrawsBackground(false);
        locationView.setEditable(false);
        locationView.setSelectable(false);
        if (library.libraryType() == 0 || libraryInAppBundle) {
            locationView.setStringValue("Internal Library");
        }
        if (library.libraryType() == 1 && !libraryInAppBundle) {
            var libraryDir = libraryPath.stringByDeletingLastPathComponent();
            var regexHome = new RegExp("^" + NSHomeDirectory().replace(/(\/)/g, "\\/"), "gi");
            libraryDir = libraryDir.replace(regexHome, "~")
            locationView.setStringValue(libraryDir);
        }
        locationView.sizeToFit();
        itemView.addSubview(locationView);

        // Button
        if (library.libraryType() == 1 && !libraryInAppBundle) {
            var changeButton = NSButton.alloc().initWithFrame(NSMakeRect(viewWidth - 110, 35, 90, 30));
            changeButton.setBezelStyle(NSRoundedBezelStyle);
            changeButton.setTitle("Change ID");
            changeButton.setCOSJSTargetFunction(function(sender) {
                var targetLibraryPath = sender.superview().subviews().objectAtIndex(0).stringValue();
                var newID = changeDocumentID(document, targetLibraryPath);
                if (newID) {
                    var idView = sender.superview().subviews().objectAtIndex(4);
                    idView.setStringValue(newID);
                } else {
                    document.showMessage("Error: can't read data from file. You can open library file and run Development - Change Document ID");
                }
            });
            itemView.addSubview(changeButton);
        }

        var divider = NSView.alloc().initWithFrame(NSMakeRect(0, itemHeight - 1, viewWidth, 1));
        divider.setWantsLayer(true);
        divider.layer().setBackgroundColor(CGColorCreateGenericRGB(0, 0, 0, 0.1));
        itemView.addSubview(divider);

        contentView.addSubview(itemView);

        i ++;
    }

    scrollView.setDocumentView(contentView);

    dialog.run();

};

function librariesWithConflictID() {

    var assetLibraryController = AppController.sharedInstance().librariesController();
    var libraries = assetLibraryController.libraries();

    if (libraries.count() == 0) {
        return nil;
    }

    // Sort by library ID
    var librariesCopy = libraries.mutableCopy();
    var sortByID = NSSortDescriptor.sortDescriptorWithKey_ascending("libraryID", true);
    librariesCopy.sortUsingDescriptors(NSArray.arrayWithObject(sortByID));

    var librariesCopy2 = librariesCopy.mutableCopy();
    librariesCopy2.forEach(function(library, index) {
        if (library.libraryID()) {
            if (index == 0) {
                if (!library.libraryID().isEqual(librariesCopy2[index + 1].libraryID())) {
                    librariesCopy.removeObject(library);
                }
            } else if (index == librariesCopy2.count() - 1) {
                if (!library.libraryID().isEqual(librariesCopy2[index - 1].libraryID())) {
                    librariesCopy.removeObject(library);
                }
            } else {
                if (
                    !library.libraryID().isEqual(librariesCopy2[index + 1].libraryID()) &&
                    !library.libraryID().isEqual(librariesCopy2[index - 1].libraryID())
                ) {
                    librariesCopy.removeObject(library);
                }
            }
        } else {
            librariesCopy.removeObject(library);
        }
    });

    return librariesCopy;
}

function changeDocumentID(document, documentPath) {
    var newID = NSUUID.UUID().UUIDString();
    var documentController = NSDocumentController.sharedDocumentController();
    var fileURL = NSURL.fileURLWithPath(documentPath);

    // If library document is opened
    var libraryDocument = documentController.documentForURL(fileURL);
    if (libraryDocument) {
        libraryDocument.documentData().setObjectID(newID);
        libraryDocument.saveDocument(nil);
        return newID;
    } else {
        var error = MOPointer.alloc().init();
        var newDocument = MSDocument.alloc().init();
        newDocument.setDisplayName(documentPath.slice(documentPath.lastIndexOf("/") + 1));
        var type = "com.bohemiancoding.sketch.drawing";
        newDocument.readFromURL_ofType_error(fileURL, type, error);

        if (error.value() != null) {
            document.showMessage("Error: " + error.value());
            return;
        }

        if (newDocument.documentData().documentIsEmpty()) {
            return;
        }

        newDocument.documentData().setObjectID(newID);

        // Hack
        newDocument.addBlankPage();
        newDocument.documentData().removePage(document.pages().lastObject());

        var error2 = MOPointer.alloc().init();
        var writeToNewDocument = newDocument.writeToURL_ofType_forSaveOperation_originalContentsURL_error(
            fileURL, type, NSSaveOperation, nil, error2
        );

        if (error2.value() != null) {
            document.showMessage("Error: " + error2.value());
            return;
        }

        if (writeToNewDocument) {
            return newID;
        } else {
            return nil;
        }
    }
}


text:
package voldemort.store.routed.action;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.TimeUnit;

import org.apache.log4j.Level;

import voldemort.cluster.Node;
import voldemort.cluster.failuredetector.FailureDetector;
import voldemort.store.InsufficientOperationalNodesException;
import voldemort.store.InsufficientZoneResponsesException;
import voldemort.store.InvalidMetadataException;
import voldemort.store.UnreachableStoreException;
import voldemort.store.nonblockingstore.NonblockingStore;
import voldemort.store.nonblockingstore.NonblockingStoreCallback;
import voldemort.store.routed.BasicPipelineData;
import voldemort.store.routed.Pipeline;
import voldemort.store.routed.Pipeline.Event;
import voldemort.store.routed.Response;
import voldemort.store.slop.HintedHandoff;
import voldemort.store.slop.Slop;
import voldemort.utils.ByteArray;
import voldemort.utils.Time;
import voldemort.utils.Utils;
import voldemort.versioning.ObsoleteVersionException;
import voldemort.versioning.Version;

public class PerformParallelDeleteRequests<V, PD extends BasicPipelineData<V>> extends
        AbstractKeyBasedAction<ByteArray, V, PD> {

    private final int preferred;

    private final int required;

    private final long timeoutMs;

    private final Map<Integer, NonblockingStore> nonblockingStores;

    private final FailureDetector failureDetector;

    private final boolean enableHintedHandoff;

    private final HintedHandoff hintedHandoff;

    private final Version version;

    public PerformParallelDeleteRequests(PD pipelineData,
                                         Event completeEvent,
                                         ByteArray key,
                                         FailureDetector failureDetector,
                                         int preferred,
                                         int required,
                                         long timeoutMs,
                                         Map<Integer, NonblockingStore> nonblockingStores,
                                         HintedHandoff hintedHandoff,
                                         Version version) {
        super(pipelineData, completeEvent, key);
        this.failureDetector = failureDetector;
        this.preferred = preferred;
        this.required = required;
        this.timeoutMs = timeoutMs;
        this.nonblockingStores = nonblockingStores;
        this.enableHintedHandoff = hintedHandoff != null;
        this.version = version;
        this.hintedHandoff = hintedHandoff;
    }

    public void execute(final Pipeline pipeline) {
        List<Node> nodes = pipelineData.getNodes();
        final Map<Integer, Response<ByteArray, Object>> responses = new ConcurrentHashMap<Integer, Response<ByteArray, Object>>();
        int attempts = nodes.size();
        int blocks = Math.min(preferred, attempts);
        final CountDownLatch attemptsLatch = new CountDownLatch(attempts);
        final CountDownLatch blocksLatch = new CountDownLatch(blocks);

        if(logger.isTraceEnabled())
            logger.trace("Attempting " + attempts + " " + pipeline.getOperation().getSimpleName()
                         + " operations in parallel");

        long beginTime = System.nanoTime();

        for(int i = 0; i < attempts; i++) {
            final Node node = nodes.get(i);
            pipelineData.incrementNodeIndex();

            NonblockingStoreCallback callback = new NonblockingStoreCallback() {

                public void requestComplete(Object result, long requestTime) {
                    if(logger.isTraceEnabled())
                        logger.trace(pipeline.getOperation().getSimpleName()
                                     + " response received (" + requestTime + " ms.) from node "
                                     + node.getId());

                    Response<ByteArray, Object> response = new Response<ByteArray, Object>(node,
                                                                                key,
                                                                                result,
                                                                                requestTime);
                    responses.put(node.getId(), response);
                    if(enableHintedHandoff && pipeline.isFinished()
                       && response.getValue() instanceof UnreachableStoreException) {
                        Slop slop = new Slop(pipelineData.getStoreName(),
                                             Slop.Operation.DELETE,
                                             key,
                                             null,
                                             null,
                                             node.getId(),
                                             new Date());
                        pipelineData.addFailedNode(node);
                        hintedHandoff.sendHintSerial(node, version, slop);
                    }

                    attemptsLatch.countDown();
                    blocksLatch.countDown();

                    if(logger.isTraceEnabled())
                        logger.trace(attemptsLatch.getCount() + " attempts remaining. Will block "
                                     + " for " + blocksLatch.getCount() + " more ");

                    // Note errors that come in after the pipeline has finished.
                    // These will *not* get a chance to be called in the loop of
                    // responses below.
                    if(pipeline.isFinished() && response.getValue() instanceof Exception
                       && !(response.getValue() instanceof ObsoleteVersionException)) {
                        if(response.getValue() instanceof InvalidMetadataException) {
                            pipelineData.reportException((InvalidMetadataException) response.getValue());
                            logger.warn("Received invalid metadata problem after a successful "
                                        + pipeline.getOperation().getSimpleName()
                                        + " call on node " + node.getId() + ", store '"
                                        + pipelineData.getStoreName() + "'");
                        } else {
                            handleResponseError(response, pipeline, failureDetector);
                        }
                    }
                }
            };

            if(logger.isTraceEnabled())
                logger.info("Submitting " + pipeline.getOperation().getSimpleName()
                            + " request on node " + node.getId());

            NonblockingStore store = nonblockingStores.get(node.getId());
            store.submitDeleteRequest(key, version, callback, timeoutMs);
        }

        try {
            long ellapsedNs = System.nanoTime() - beginTime;
            long remainingNs = (timeoutMs * Time.NS_PER_MS) - ellapsedNs;
            if(remainingNs > 0) {
                blocksLatch.await(remainingNs, TimeUnit.NANOSECONDS);
            }
        } catch(InterruptedException e) {
            if(logger.isEnabledFor(Level.WARN))
                logger.warn(e, e);
        }

        for(Entry<Integer, Response<ByteArray, Object>> responseEntry: responses.entrySet()) {
            Response<ByteArray, Object> response = responseEntry.getValue();
            if(response.getValue() instanceof Exception) {
                if(response.getValue() instanceof ObsoleteVersionException) {
                    // ignore this completely here
                    // this means that a higher version was able
                    // to write on this node and should be termed as
                    // clean success.
                    responses.remove(responseEntry.getKey());
                } else if(handleResponseError(response, pipeline, failureDetector)) {
                    return;
                }
            } else {
                pipelineData.incrementSuccesses();
                failureDetector.recordSuccess(response.getNode(), response.getRequestTime());
                pipelineData.getZoneResponses().add(response.getNode().getZoneId());
                Response<ByteArray, V> rCast = Utils.uncheckedCast(response);
                pipelineData.getResponses().add(rCast);
                responses.remove(responseEntry.getKey());
            }
        }

        // wait for more responses in case we did not have enough successful
        // response to achieve the required count
        boolean quorumSatisfied = true;
        if(pipelineData.getSuccesses() < required) {
            long ellapsedNs = System.nanoTime() - beginTime;
            long remainingNs = (timeoutMs * Time.NS_PER_MS) - ellapsedNs;
            if(remainingNs > 0) {
                try {
                    attemptsLatch.await(remainingNs, TimeUnit.NANOSECONDS);
                } catch(InterruptedException e) {
                    if(logger.isEnabledFor(Level.WARN))
                        logger.warn(e, e);
                }

                for(Entry<Integer, Response<ByteArray, Object>> responseEntry: responses.entrySet()) {
                    Response<ByteArray, Object> response = responseEntry.getValue();
                    if(response.getValue() instanceof Exception) {
                        if(response.getValue() instanceof ObsoleteVersionException) {
                            // ignore this completely here
                            // this means that a higher version was able
                            // to write on this node and should be termed as
                            // clean success.
                            responses.remove(responseEntry.getKey());
                        } else if(handleResponseError(response, pipeline, failureDetector))
                            return;
                    } else {
                        pipelineData.incrementSuccesses();
                        failureDetector.recordSuccess(response.getNode(), response.getRequestTime());
                        pipelineData.getZoneResponses().add(response.getNode().getZoneId());
                        Response<ByteArray, V> rCast = Utils.uncheckedCast(response);
                        pipelineData.getResponses().add(rCast);
                        responses.remove(responseEntry.getKey());
                    }
                }
            }

            if(pipelineData.getSuccesses() < required) {
                pipelineData.setFatalError(new InsufficientOperationalNodesException(required
                                                                                + " "
                                                                                + pipeline.getOperation()
                                                                                .getSimpleName()
                                                                                + "s required, but only "
                                                                                + pipelineData.getSuccesses()
                                                                                + " succeeded",
                                                                                new ArrayList<Node>(pipelineData.getReplicationSet()),
                                                                                new ArrayList<Node>(pipelineData.getNodes()),
                                                                                new ArrayList<Node>(pipelineData.getFailedNodes()),
                                                                                pipelineData.getFailures()));
                pipeline.abort();
                quorumSatisfied = false;
            }
        }

        if(quorumSatisfied) {
            if(pipelineData.getZonesRequired() != null) {
                int zonesSatisfied = pipelineData.getZoneResponses().size();
                if(zonesSatisfied >= (pipelineData.getZonesRequired() + 1)) {
                    pipeline.addEvent(completeEvent);
                } else {
                    long timeMs = (System.nanoTime() - beginTime) / Time.NS_PER_MS;

                    if((timeoutMs - timeMs) > 0) {
                        try {
                            attemptsLatch.await(timeoutMs - timeMs, TimeUnit.MILLISECONDS);
                        } catch(InterruptedException e) {
                            if(logger.isEnabledFor(Level.WARN))
                                logger.warn(e, e);
                        }

                        for(Entry<Integer, Response<ByteArray, Object>> responseEntry: responses.entrySet()) {
                            Response<ByteArray, Object> response = responseEntry.getValue();
                            if(response.getValue() instanceof Exception) {
                                if(handleResponseError(response, pipeline, failureDetector))
                                    return;
                            } else {
                                pipelineData.incrementSuccesses();
                                failureDetector.recordSuccess(response.getNode(),
                                                              response.getRequestTime());
                                pipelineData.getZoneResponses().add(response.getNode().getZoneId());
                                Response<ByteArray, V> rCast = Utils.uncheckedCast(response);
                                pipelineData.getResponses().add(rCast);
                                responses.remove(responseEntry.getKey());
                            }
                        }
                    }

                    if(pipelineData.getZoneResponses().size() >= (pipelineData.getZonesRequired() + 1)) {
                        pipeline.addEvent(completeEvent);
                    } else {
                        pipelineData.setFatalError(new InsufficientZoneResponsesException((pipelineData.getZonesRequired() + 1)
                                                                                + " "
                                                                                + pipeline.getOperation()
                                                                                .getSimpleName()
                                                                                + "s required zone, but only "
                                                                                + zonesSatisfied
                                                                                + " succeeded"));
                        pipeline.abort();
                    }
                }

            } else {
                pipeline.addEvent(completeEvent);
            }
        }
    }
}

redpajama_set_name: RedPajamaGithub


text:
require "linner/version"
require "linner/command"
require "linner/asset"
require "linner/cache"
require "linner/helper"
require "linner/sprite"
require "linner/archive"
require "linner/bundler"
require "linner/reactor"
require "linner/wrapper"
require "linner/template"
require "linner/notifier"
require "linner/compressor"
require "linner/environment"

module Linner
  extend self

  attr_accessor :env, :compile, :strict

  def root
    @root ||= Pathname('.').realpath
  end

  def config_file
    linner_file = root.join("Linnerfile")
    config_file = root.join("config.yml")
    File.exist?(linner_file) ? linner_file : config_file
  end

  def env
    @env ||= Environment.new config_file
  end

  def cache
    @cache ||= Cache.new
  end

  def manifest
    @manifest ||= begin
      hash = {}
      copy_assets = []
      concat_assets = []
      template_assets = []
      sprite_assets = []
      cdn = env.revision["cdn"] || ""
      prefix = env.revision["prefix"] || ""

      env.groups.each do |config|
        concat_assets << config["concat"].keys if config["concat"]
        template_assets << config["template"].keys if config["template"]
        sprite_assets << config["sprite"].keys if config["sprite"]
        config["copy"].each do |dest, pattern|
          copy_assets << Dir.glob(pattern).map do |path|
            logical_path = Asset.new(path).logical_path
            dest_path = File.join(dest, logical_path)
          end
        end if config["copy"]
      end

      # revision sprite assets
      sprite_assets.flatten.each do |dest|
        name = File.basename(dest).sub /[^.]+\z/, "png"
        dest = File.join env.sprites["path"], name
        asset = Asset.new(File.join env.public_folder, dest)
        hash[prefix + dest] = cdn + prefix + asset.relative_digest_path
        asset.revision!

        (concat_assets + copy_assets).flatten.each do |file|
          path = File.join env.public_folder, file
          next unless Asset.new(path).stylesheet?
          url = env.sprites["url"] || env.sprites["path"]
          puts = File.read(path).gsub(File.join(url, File.basename(dest)), File.join(cdn, url, File.basename(asset.relative_digest_path)))
          File.open(path, "w") { |file| file << puts }
        end
      end

      # revision concat template and copy assets
      (concat_assets + template_assets + copy_assets).flatten.each do |dest|
        asset = Asset.new(File.join env.public_folder, dest)
        next unless asset.revable?
        hash[prefix + dest] = cdn + prefix + asset.relative_digest_path
        asset.revision!
      end

      hash
    end
  end

  def compile?
    @compile
  end

  def strict?
    @strict
  end

  def perform(*asset)
    env.groups.each do |config|
      precompile(config) if config["precompile"]
      sprite(config) if config["sprite"]
    end
    env.groups.each do |config|
      copy(config) if config["copy"]
      compile(config) if config["compile"]
      concat(config) if config["concat"]
    end
    env.groups.each do |config|
      tar(config) if config["tar"]
    end
    revision if compile? and env.revision
  end

  private
  def concat(config)
    config["concat"].each_with_index do |pair, index|
      dest, pattern, order = pair.first, pair.last, config["order"]||[]
      matches = Dir.glob(pattern).sort_by(&:downcase).order_by(order)
      next if matches.select {|path| cache.miss?(dest, path)}.empty?
      write_asset(dest, matches)
    end
  end

  def copy(config)
    config["copy"].each do |dest, pattern|
      Dir.glob(pattern).each do |path|
        asset = Asset.new(path)
        dest_path = File.join(env.public_folder, dest, asset.logical_path)
        FileUtils.mkdir_p File.dirname(dest_path)
        FileUtils.cp_r path, dest_path
      end
    end
  end

  def compile(config)
    config["compile"].each do |dest, pattern|
      Dir.glob(pattern).each do |path|
        next if not cache.miss?(dest, path)
        asset = Asset.new(path)
        dest_path = File.join(env.public_folder, dest, asset.logical_path)
        if asset.javascript? or asset.stylesheet?
          asset.content
          asset.compress if compile?
          dest_path = dest_path.sub(/[^.]+\z/, "js") if asset.javascript?
          dest_path = dest_path.sub(/[^.]+\z/, "css") if asset.stylesheet?
          asset.path = dest_path
          asset.write
        elsif asset.eruby?
          base, ext = path.split(".")
          dest_path = if ext == "erb"
            dest_path.sub(/[.]+\z/, "html")
          else
            dest_path.gsub(File.basename(dest_path), File.basename(dest_path, File.extname(dest_path)))
          end
          asset.content(config["context"])
          asset.path = dest_path
          asset.write
        else
          FileUtils.mkdir_p File.dirname(dest_path)
          FileUtils.cp_r path, dest_path
        end
      end
    end
  end

  def precompile(config)
    config["precompile"].each do |dest, pattern|
      matches = Dir.glob(pattern).sort_by(&:downcase)
      next if matches.select { |path| cache.miss?(dest, path) }.empty?
      write_template(dest, matches)
    end
  end

  def sprite(config)
    config["sprite"].each do |dest, pattern|
      matches = Dir.glob(pattern).sort_by(&:downcase)
      next if matches.select { |path| cache.miss?(dest, path) }.empty?
      paint_sprite(dest, matches)
    end
  end

  def tar(config)
    config["tar"].each do |dest, pattern|
      path = File.join(env.public_folder, dest)
      FileUtils.mkdir_p File.dirname(path)
      Archive.tar(pattern, path)
    end
  end

  def revision
    dump_manifest
    files = env.revision["files"] || []
    files.flatten.each do |rev|
      file = File.join env.public_folder, rev.to_s
      next if not File.exist?(file)
      replace_attributes file
    end
  end

  def paint_sprite(dest, images)
    images = images.map do |path|
      ImageProxy.new(path, ChunkyPNG::Image.from_file(path))
    end
    sprite = Sprite.new(images).pack!
    map = ChunkyPNG::Image.new(sprite.root[:w], sprite.root[:h], ChunkyPNG::Color::TRANSPARENT)

    sprite.images.each do |image|
      map.compose!(image.image, image.left, image.top)
    end

    name = File.basename(dest).sub(/[^.]+\z/, "png")
    path = File.join(env.public_folder, env.sprites["path"], name)
    FileUtils.mkdir_p File.dirname(path)
    map.save path

    asset = Asset.new(File.join env.public_folder, dest)
    asset.content = sprite.generate_style(env.sprites, name)
    asset.write
  end

  def write_template(dest, child_assets)
    asset = Asset.new(File.join env.public_folder, dest)
    content = child_assets.inject("") {|s, m| s << cache["#{dest}:#{m}"].content}
    asset.content = Wrapper::Template.definition(content)
    asset.compress if compile?
    asset.write
  end

  def write_asset(dest, child_assets)
    asset = Asset.new(File.join env.public_folder, dest)
    definition = (asset.path == env.definition ? Wrapper::Module.definition : "")
    asset.content = child_assets.inject(definition) {|s, m| s << cache["#{dest}:#{m}"].content}
    asset.compress if compile?
    asset.write
  end

  def replace_attributes file
    doc = File.read file
    if strict?
      doc.gsub!(/(<script.+src=['"])([^"']+)(["'])/) do |m|
        if p = manifest[$2] then $1 << p << $3 else m end
      end

      doc.gsub!(/(<link[^\>]+href=['"])([^"']+)(["'])/) do |m|
        if p = manifest[$2] then $1 << p << $3 else m end
      end
    else
      manifest.each do |k, v|
        doc.gsub!(k, v)
      end
    end
    File.open(file, "w") {|f| f.write doc}
  end

  def dump_manifest
    manifest_file = env.revision["manifest"] || "manifest.yml"
    File.open(File.join(env.public_folder, manifest_file), "w") do |f|
      YAML.dump(manifest, f)
    end
  end
end


text:
onnodecreate = function(e) {

	var node = e.node;
	node.buffers = [];

	//console.log(node);

	if (node.context == undefined || node.context == null) {
		if (node.__target__ != undefined && node.__target__ != null)
			node.context = node.__target__.context;
	}

	node.audioErrorLogFlag = 0;
	node.mediaInfo = "undefined";

	node.inputChannelCount = 2;
	node.audioCurrentRemains = null;

	node.audioDataQueueSize = 128; // audio cache size
	node.audioDataBlockSize = 128; // block-size is defined to be 128 sample-frames (see https://www.w3.org/TR/webaudio)

	node.bufferToArray = function(buffer) { // incoming data is an ArrayBuffer
		var u8arrayData = new Uint8Array(buffer);
		var outputArrayData = new Float32Array(u8arrayData.length);
		for (var i = 0; i < u8arrayData.length; i++) {
			outputArrayData[i] = (u8arrayData[i] - 128) / 128.0; // convert audio to float
		}
		return outputArrayData; // return the Float32Array
	};

	node.setupBuffers = function(intputBuffer, remainBuffer, outputBuffers, outputBufferSize) {

		var totalInput = new Float32Array(intputBuffer.length + remainBuffer.length);
		totalInput.set(intputBuffer);
		if (remainBuffer.length > 0) totalInput.set(remainBuffer, intputBuffer.length);

		var outputRemainSize = totalInput.length % outputBufferSize;
		var outputBufferCount = (totalInput.length - outputRemainSize) / outputBufferSize;

		var beginPos = 0;
		var totalCurrentInput = Array.prototype.slice.call(totalInput); // ios need this...
		for (var i=0; i<outputBufferCount; i++) {
			outputBuffers[outputBuffers.length] = totalCurrentInput.slice(beginPos, beginPos+outputBufferSize);
			beginPos = beginPos+outputBufferSize;
		}

		var finalRemain = null;
		if (outputRemainSize > 0) finalRemain = totalCurrentInput.slice(beginPos);
		else finalRemain = new Float32Array(0);

		return finalRemain;
	};

	node.prepareAudioBuffer = function(buffer, channelCount) {

		try {

			this.inputChannelCount = channelCount <= 0 ? buffer.numberOfChannels : channelCount;

			var newbuffer = [];

			if (this.audioCurrentRemains == null) {
				this.audioCurrentRemains = new Array();
				for (var i=0; i<this.inputChannelCount; i++)
					this.audioCurrentRemains[this.audioCurrentRemains.length] = new Float32Array(0);
			}

			for (var i=0; i<this.inputChannelCount; i++) {

				var intputBuffer = channelCount <= 0 ? buffer.getChannelData(i) : buffer;

				var remainBuffer = this.audioCurrentRemains[i];
				var outputBuffers = new Array();

				var finalRemain = this.setupBuffers(intputBuffer, remainBuffer, outputBuffers, this.audioDataBlockSize);

				this.audioCurrentRemains[i] = finalRemain;
				newbuffer[newbuffer.length] = outputBuffers;
			}

			if (newbuffer.length > 0) {

				var audioBuffers = [];
				var foundEmpty = false;
				while (!foundEmpty) {
					var usefulbuffers = [];
					for (var i=0; i<this.inputChannelCount; i++) {
						if (newbuffer[i].length <= 0) {
							foundEmpty = true;
							break;
						}
						usefulbuffers[usefulbuffers.length] = newbuffer[i].shift();
					}
					if (usefulbuffers.length == this.inputChannelCount)
						audioBuffers[audioBuffers.length] = usefulbuffers;

				}

				if (this.audioDataQueueSize > 0 && this.buffers.length > this.audioDataQueueSize)
					this.buffers.splice((this.buffers.length - 1) / 2, this.buffers.length / 2);
				for (var idx=0; idx<audioBuffers.length; idx++) {
					this.buffers[this.buffers.length] = audioBuffers[idx];
				}

			}

		} catch (bufferingerror) {
			if (this.audioErrorLogFlag > 0) console.log("audio buffering error: " + bufferingerror);
		}

	}

	node.onmessage = function(evt) {

		node.mediaInfo = evt.data.mediaDesc;
		node.audioErrorLogFlag = evt.data.errorLogFlag;
		node.audioDataQueueSize = evt.data.maxQueueSize;

		if (node.mediaInfo.indexOf('pcm') >= 0) {
			node.prepareAudioBuffer(node.bufferToArray(evt.data.streamData), node.inputChannelCount);
		} else {
			node.context.decodeAudioData(evt.data.streamData, function(buffer) {
				node.prepareAudioBuffer(buffer, 0);
			},
			function(err) {
				if (node.audioErrorLogFlag > 0) console.log("decode audio error: " + err);
			});
		}
	};

};

onaudioprocess = function(e) {

	var node = e.node;
	var bufferData = null;

	if (node.buffers != null && node.buffers.length > 0) bufferData = node.buffers.shift();

	if (bufferData == null) {
		for (var channel=0; channel<e.outputs[0].length; channel++) {
			e.outputs[0][channel].fill(0);
		}
		//console.log('GAP!');
		return;
	} else {
		var validAudioChannelCount = e.outputs[0].length > bufferData.length ? bufferData.length : e.outputs[0].length;
		for (var channel=0; channel<validAudioChannelCount; channel++) {
			e.outputs[0][channel].set(bufferData[channel]);
		}
	}
};


text:
/**
 * @file blocks.h
 *
 * Controller library code
 */

#pragma once

#include <px4_defines.h>
#include <assert.h>
#include <time.h>
#include <stdlib.h>
#include <math.h>
#include <mathlib/math/test/test.hpp>
#include <mathlib/math/filter/LowPassFilter2p.hpp>

#include "block/Block.hpp"
#include "block/BlockParam.hpp"

#include "matrix/math.hpp"

namespace control
{

/**
 * A trapezoidal integrator.
 * http://en.wikipedia.org/wiki/Trapezoidal_rule
 * A limiter is built into the class to bound the
 * integral's internal state. This is important
 * for windup protection.
 * @see Limit
 */
class __EXPORT BlockIntegralTrap : public SuperBlock
{
public:
// methods
	BlockIntegralTrap(SuperBlock *parent, const char *name) :
		SuperBlock(parent, name),
		_u(0),
		_y(0),
		_limit(this, "") {}
	virtual ~BlockIntegralTrap() {}
	float update(float input);
// accessors
	float getU() {return _u;}
	float getY() {return _y;}
	float getMax() {return _limit.getMax();}
	void setU(float u) {_u = u;}
	void setY(float y) {_y = y;}
protected:
// attributes
	float _u; /**< previous input */
	float _y; /**< previous output */
	BlockLimitSym _limit; /**< limiter */
};

} // namespace control


text:
//+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
//
// Information about all kind of framed tags tagged files
//
//+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++

//---------------------------------------------------------------------------
#ifndef MediaInfo_File__TagsH
#define MediaInfo_File__TagsH
//---------------------------------------------------------------------------

//---------------------------------------------------------------------------
#include "MediaInfo/File__Analyze.h"
//---------------------------------------------------------------------------

namespace MediaInfoLib
{

//***************************************************************************
// Class File__UnCompressedSize_Helper
//***************************************************************************
class File__UnCompressedSize_Helper
{
    protected:
        int64u Duration;
        int64u UncompressedSize;
    public:
        File__UnCompressedSize_Helper() :Duration(0), UncompressedSize(0) {}
        bool CalcDurationUncompressedSize(int64u Samples, int32u SampleRate, int8u BitsPerSample, int8u Channels)
        {
            if (SampleRate == 0)
                return false;
            Duration = Samples * 1000 / SampleRate;
            if (Duration == 0)
                return false;
            UncompressedSize = Samples * Channels * BitsPerSample  / 8;
            if (UncompressedSize == 0)
                return false;
            return true;
        }
};

//***************************************************************************
// Class File__Tags_Helper
//***************************************************************************

class File__Tags_Helper
{
public :
    //In
    File__Analyze* Base;

    //Out
    int64u TagsSize;
    int64u File_BeginTagSize;
    int64u File_EndTagSize;

    //Constructor/Destructor
    File__Tags_Helper();
    ~File__Tags_Helper();

    //Streams management
    void Streams_Fill();
    void Streams_Finish();

    //Buffer - File header
    bool FileHeader_Begin() {return Synched_Test();}

    //Buffer - Synchro
    bool Synchronize(bool &Tag_Found, size_t Synchro_Offset=0);
    bool Synched_Test();

    //Buffer - Global
    bool Read_Buffer_Continue ();

    //Per element
    bool Header_Begin() {return Synched_Test();}

    //Streams
    size_t Stream_Prepare(stream_t StreamKind);

    //End
    void GoTo           (int64u GoTo, const char* ParserName=NULL);
    void GoToFromEnd    (int64u GoToFromEnd=0, const char* ParserName=NULL);
    void Accept         (const char* ParserName=NULL);
    void Reject         (const char* ParserName=NULL);
    void Finish         (const char* ParserName=NULL);

private :
    //Temp
    File__Analyze* Parser;
    vector<File__Analyze*> Parser_Streams_Fill; //Parser to merge when filling
    #ifdef MEDIAINFO_ID3V2_YES
        vector<bool> Parser_Streams_Fill_Priority; //Parser to merge when filling
    #endif
    size_t         Parser_Buffer_Size;
    int64u Id3v1_Offset;
    int64u Lyrics3_Offset;
    int64u Lyrics3v2_Offset;
    int64u ApeTag_Offset;
    int64u JumpTo_WantedByParser;
    int64u Id3v1_Size;
    int64u Lyrics3_Size;
    int64u Lyrics3v2_Size;
    int64u ApeTag_Size;
    bool TagSizeIsFinal;
    bool SearchingForEndTags;

    //Helpers
    bool DetectBeginOfEndTags();        //return true if we can continue, false if want return
    bool DetectBeginOfEndTags_Test();

};} //NameSpace

#endif


text:
PRJ=webclient
#
PROGS=$(PRJ)
FILES=client_src/main.cpp client_src/ISocket.cpp client_src/IHttpRequest.cpp client_src/IHttpResponse.cpp client_src/IHttpClient.cpp client_src/IException.cpp
CC=g++
CFLAGS=-Wall -W -Wextra -g -pedantic

all: $(PROGS)

$(PRJ): $(FILES)
	$(CC) $(CFLAGS) -o $@ $(FILES) -lm

clean:
	rm -f *.o *.out $(PROGS)


text:
module Risk::Game

  describe InitialPlaceState do

    before :each do
      @state = InitialPlaceState.new
    end

    describe ".allows?" do

      it "returns true to PlaceAction" do
        action = PlaceAction.new(1, :kamchatka, 4)
        expect(@state.allows? action).to be true
      end

      it "returns false to any other action" do
        action = NoMoveAction.new
        expect(@state.allows? action).to be false
      end

    end

    describe ".update" do

      before :each do
        @game = Game.create_with_players [1,2,3,4]
        @game.max_place =  10
      end

      context "player still has more armies to place" do

        before :each do
          @action = PlaceAction.new(1,:kamchatka, 5)
        end

        it "returns InitialPlaceState" do
          expect(@state.update(@action, @game)).to be_kind_of(InitialPlaceState)
        end

        it "the game's current_player is unchanged" do
          current_player = @game.current_player
          @state.update(@action, @game)
          expect(@game.current_player).to be current_player
        end

      end

      context "player has played all armies" do

        before :each do
          @action = PlaceAction.new(1,:kamchatka, 10)
          @game.max_place = 0
        end

        it "the game's current_player is changed" do
          current_player = @game.current_player
          @state.update(@action, @game)
          expect(@game.current_player).to_not be current_player
        end

        context "another player remains to place" do

          it "returns InitialPlaceState" do
            expect(@state.update(@action, @game)).to be_kind_of(InitialPlaceState)
          end

          it "decrements players_to_setup in game" do
            players_left = @game.players_to_setup
            @state.update(@action, @game)
            expect(@game.players_to_setup).to be (players_left - 1)
          end

          it "sets max_place to INITIAL_ARMIES" do
            @state.update(@action, @game)
            expect(@game.max_place).to be Game::INITIAL_ARMIES
          end

        end

        context "no more players remain to place" do

          it "returns TurnStartState" do
            @game.players_to_setup = 1
            expect(@state.update(@action, @game)).to be_kind_of(TurnStartState)
          end

        end

      end

    end

  end

end


text:
@interface EvstUserSettingsLegalViewController : EvstUserSettingsBaseViewController

@end


text:
<!DOCTYPE html>

    <title>Vertical and Horizontal Bar Charts</title>

    <link class="include" rel="stylesheet" type="text/css" href="jquery.jqplot.min.css" />

Click on a bar in the plot below to update the text box.

You Clicked:
    Nothing yet.


text:
package org.batfish.representation.juniper;

import static org.batfish.representation.juniper.GroupWildcard.toJavaRegex;
import static org.hamcrest.MatcherAssert.assertThat;
import static org.hamcrest.Matchers.equalTo;

import org.junit.Test;

/** Tests of {@link GroupWildcard} */
public class GroupWildcardTest {

  @Test
  public void testToJavaRegex() {
    assertThat(toJavaRegex("*"), equalTo(".*"));
    assertThat(toJavaRegex("*.*"), equalTo(".*\\..*"));
    assertThat(toJavaRegex("Foo*"), equalTo("Foo.*"));
    assertThat(toJavaRegex("Foo?"), equalTo("Foo\\w"));
    assertThat(toJavaRegex("DC?-suffix-*.*"), equalTo("DC\\w-suffix-.*\\..*"));
  }

  @Test
  public void testToJavaRegexWithUnmatchedBrackets() {
    assertThat(toJavaRegex("["), equalTo("\\["));
    assertThat(toJavaRegex("Literal["), equalTo("Literal\\["));
    assertThat(toJavaRegex("Literal]"), equalTo("Literal\\]"));
  }

  @Test
  public void testToJavaRegexWithCharacterClasses() {
    assertThat(toJavaRegex("[a-c]"), equalTo("[a-c]"));
    assertThat(toJavaRegex("Foo[bar]"), equalTo("Foo[bar]"));
    assertThat(toJavaRegex("[0-9]"), equalTo("[0-9]"));
    assertThat(toJavaRegex("[A-D]"), equalTo("[A-D]"));
    assertThat(toJavaRegex("border-[0-9]-DC?-*"), equalTo("border-[0-9]-DC\\w-.*"));
    assertThat(toJavaRegex("ge-1/2/[5-8]"), equalTo("ge-1/2/[5-8]"));
    assertThat(toJavaRegex("12.1[23]4.*.*/2[89]"), equalTo("12\\.1[23]4\\..*\\..*/2[89]"));
  }

  @Test
  public void testToJavaRegexWithCharacterClassNegation() {
    assertThat(toJavaRegex("[!a-c]"), equalTo("[^a-c]"));
    assertThat(toJavaRegex("[!qwerty]"), equalTo("[^qwerty]"));
    assertThat(toJavaRegex("test[!4]"), equalTo("test[^4]"));
    assertThat(toJavaRegex("*[^/][^0]"), equalTo(".*[^/][^0]"));
  }
}


text:
import React, { Component } from 'react';
import './Home.css';

import {Link} from 'react-router';

class Home extends Component {
  render() {
    return (

Home Page

Todo Client here

        <Link to="display"><button className="btn btn-default">Display</button></Link>
        <Link to="todo"><button className="btn btn-default">Todo</button></Link>

    );
  }
}

export default Home;


text: <!DOCTYPE html>


text:
using System;
using System.Windows;
using AlertManager.viewmodel;

namespace AlertManager.view
{
    /// <summary>
    /// Interaction logic for MainWindow.xaml
    /// </summary>
    public partial class MainWindow : Window
    {
        private MainViewModel ViewModel => DataContext as MainViewModel;

        public MainWindow()
        {
            InitializeComponent();
            this.DataContext = new MainViewModel();
        }

        private void CleanUp_OnClick(object sender, RoutedEventArgs e)
        {
            try
            {
                ViewModel.CleanUp();
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message, "Error!", MessageBoxButton.OK, MessageBoxImage.Error);
            }
        }

        private void Connect_OnClick(object sender, RoutedEventArgs e)
        {
            try
            {
                if (ViewModel.IsConnected)
                    ViewModel.Disconnect();
                else
                    ViewModel.Connect(txtUser.Text, txtPassword.Password, false, txtServer.Text);
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message, "Error!", MessageBoxButton.OK, MessageBoxImage.Error);
            }
        }
    }
}


text:
{% extends "frontend/page.html" %}

{% block page_title %}Legal Disclaimer{% endblock %}

{% block page_content %}

Since I live and publish in Germany, I have to do this to comply with German legislation:

        Jesco Freund

        Dinkelweg 36

        21641 Apensen

        Germany

        Phone: +49 4167 6993424

        Email: mail (at) stormrose (dot) org

Verantwortlicher im Sinne von § 55 Abs. 2 RStV:

        Jesco Freund (Anschrift wie oben)

        Einer Verwendung der oben gemachten Angaben zu einem anderen Zweck als den der Kontaktaufnahme bezüglich dieser
        Internetseiten wird ausdrücklich nicht zugestimmt. Insbesondere der dauerhaften Speicherung dieser Daten sowie
        ihrer Verwendung zu Werbezwecken oder sonstigen nicht ausdrücklich autorisierten Zwecken wird aufs schärfste
        widersprochen. Zuwiderhandlungen gegen diese Bestimmungen werden im Rahmen der zivil- und strafrechtlichen
        Möglichkeiten geahndet.

{% endblock %}


text:
namespace aura {
class Window;
}

namespace ui {
class Event;
class MenuModel;
}

namespace ash {

class ShelfMenuModel;

// Delegate for the ShelfItem.
class ASH_EXPORT ShelfItemDelegate {
 public:
  // The return type for the ShelfItemDelegate::ItemSelected method.
  enum PerformedAction {
    // No action was taken.
    kNoAction,
    // A new window was created.
    kNewWindowCreated,
    // An existing window which was not currently active was activated.
    kExistingWindowActivated,
    // The currently active window was minimized.
    kExistingWindowMinimized,
    // The app list launcher menu was shown.
    kAppListMenuShown,
  };

  virtual ~ShelfItemDelegate() {}

  // Invoked when the user clicks on a window entry in the launcher.
  // |event| is the click event. The |event| is dispatched by a view
  // and has an instance of |views::View| as the event target
  // but not |aura::Window|. If the |event| is of type KeyEvent, it is assumed
  // that this was triggered by keyboard action (Alt+<number>) and special
  // handling might happen.
  // Returns the action performed by selecting the item.
  virtual PerformedAction ItemSelected(const ui::Event& event) = 0;

  // Returns the title to display.
  virtual base::string16 GetTitle() = 0;

  // Returns the context menumodel for the specified item on
  // |root_window|.  Return NULL if there should be no context
  // menu. The caller takes ownership of the returned model.
  virtual ui::MenuModel* CreateContextMenu(aura::Window* root_window) = 0;

  // Returns the application menu model for the specified item. There are three
  // possible return values:
  //  - A return of NULL indicates that no menu is wanted for this item.
  //  - A return of a menu with one item means that only the name of the
  //    application/item was added and there are no active applications.
  //    Note: This is useful for hover menus which also show context help.
  //  - A list containing the title and the active list of items.
  // The caller takes ownership of the returned model.
  // |event_flags| specifies the flags of the event which triggered this menu.
  virtual ShelfMenuModel* CreateApplicationMenu(int event_flags) = 0;

  // Whether the launcher item is draggable.
  virtual bool IsDraggable() = 0;

  // Returns true if a tooltip should be shown.
  virtual bool ShouldShowTooltip() = 0;

  // Closes all windows associated with this item.
  virtual void Close() = 0;

};

}  // namespace ash

#endif  // ASH_SHELF_SHELF_ITEM_DELEGATE_H_


text:
<?php
namespace test\flow;
/**
 *
 * @author tokushima
 * @login @['type'=>'test\model\Member1']
 */
class LoginRequestAction1 extends \ebi\flow\AutomapLoginRequest{
	/**
	 * @automap
	 */
	public function aaa(){
		return ['abc'=>123];
	}
	/**
	 * @automap
	 */
	public function bbb(){
		if(!$this->is_user_logged_in()){
			throw new \LogicException('login required');
		}
		return ['abc'=>123];
	}
}


text:
@interface FLEXExplorerToolbarItem ()

@property (nonatomic) FLEXExplorerToolbarItem *sibling;
@property (nonatomic, copy) NSString *title;
@property (nonatomic) UIImage *image;

@property (nonatomic, readonly, class) UIColor *defaultBackgroundColor;
@property (nonatomic, readonly, class) UIColor *highlightedBackgroundColor;
@property (nonatomic, readonly, class) UIColor *selectedBackgroundColor;

@end

@implementation FLEXExplorerToolbarItem

#pragma mark - Public

+ (instancetype)itemWithTitle:(NSString *)title image:(UIImage *)image {
    return [self itemWithTitle:title image:image sibling:nil];
}

+ (instancetype)itemWithTitle:(NSString *)title image:(UIImage *)image sibling:(FLEXExplorerToolbarItem *)backupItem {
    NSParameterAssert(title); NSParameterAssert(image);

    FLEXExplorerToolbarItem *toolbarItem = [self buttonWithType:UIButtonTypeSystem];
    toolbarItem.sibling = backupItem;
    toolbarItem.title = title;
    toolbarItem.image = image;
    toolbarItem.tintColor = FLEXColor.iconColor;
    toolbarItem.backgroundColor = self.defaultBackgroundColor;
    toolbarItem.titleLabel.font = [UIFont systemFontOfSize:12.0];
    [toolbarItem setTitle:title forState:UIControlStateNormal];
    [toolbarItem setImage:image forState:UIControlStateNormal];
    [toolbarItem setTitleColor:FLEXColor.primaryTextColor forState:UIControlStateNormal];
    [toolbarItem setTitleColor:FLEXColor.deemphasizedTextColor forState:UIControlStateDisabled];
    return toolbarItem;
}

- (FLEXExplorerToolbarItem *)currentItem {
    if (!self.enabled && self.sibling) {
        return self.sibling.currentItem;
    }

    return self;
}

#pragma mark - Display Defaults

+ (NSDictionary<NSString *, id> *)titleAttributes {
    return @{ NSFontAttributeName : [UIFont systemFontOfSize:12.0] };
}

+ (UIColor *)highlightedBackgroundColor {
    return FLEXColor.toolbarItemHighlightedColor;
}

+ (UIColor *)selectedBackgroundColor {
    return FLEXColor.toolbarItemSelectedColor;
}

+ (UIColor *)defaultBackgroundColor {
    return UIColor.clearColor;
}

+ (CGFloat)topMargin {
    return 2.0;
}

#pragma mark - State Changes

- (void)setHighlighted:(BOOL)highlighted {
    super.highlighted = highlighted;
    [self updateColors];
}

- (void)setSelected:(BOOL)selected {
    super.selected = selected;
    [self updateColors];
}

- (void)setEnabled:(BOOL)enabled {
    if (self.enabled != enabled) {
        if (self.sibling) {
            if (enabled) { // Replace sibling with myself
                UIView *superview = self.sibling.superview;
                [self.sibling removeFromSuperview];
                self.frame = self.sibling.frame;
                [superview addSubview:self];
            } else { // Replace myself with sibling
                UIView *superview = self.superview;
                [self removeFromSuperview];
                self.sibling.frame = self.frame;
                [superview addSubview:self.sibling];
            }
        }

        super.enabled = enabled;
    }
}

+ (id)_selectedIndicatorImage { return nil; }

- (void)updateColors {
    // Background color
    if (self.highlighted) {
        self.backgroundColor = self.class.highlightedBackgroundColor;
    } else if (self.selected) {
        self.backgroundColor = self.class.selectedBackgroundColor;
    } else {
        self.backgroundColor = self.class.defaultBackgroundColor;
    }
}

#pragma mark - UIButton Layout Overrides

- (CGRect)titleRectForContentRect:(CGRect)contentRect {
    NSDictionary *attrs = [[self class] titleAttributes];
    // Bottom aligned and centered.
    CGRect titleRect = CGRectZero;
    CGSize titleSize = [self.title boundingRectWithSize:contentRect.size
                                                options:0
                                             attributes:attrs
                                                context:nil].size;
    titleSize = CGSizeMake(ceil(titleSize.width), ceil(titleSize.height));
    titleRect.size = titleSize;
    titleRect.origin.y = contentRect.origin.y + CGRectGetMaxY(contentRect) - titleSize.height;
    titleRect.origin.x = contentRect.origin.x + FLEXFloor((contentRect.size.width - titleSize.width) / 2.0);
    return titleRect;
}

- (CGRect)imageRectForContentRect:(CGRect)contentRect {
    CGSize imageSize = self.image.size;
    CGRect titleRect = [self titleRectForContentRect:contentRect];
    CGFloat availableHeight = contentRect.size.height - titleRect.size.height - [[self class] topMargin];
    CGFloat originY = [[self class] topMargin] + FLEXFloor((availableHeight - imageSize.height) / 2.0);
    CGFloat originX = FLEXFloor((contentRect.size.width - imageSize.width) / 2.0);
    CGRect imageRect = CGRectMake(originX, originY, imageSize.width, imageSize.height);
    return imageRect;
}

@end


text:
.. Licensed to the Apache Software Foundation (ASF) under one
.. or more contributor license agreements.  See the NOTICE file
.. distributed with this work for additional information
.. regarding copyright ownership.  The ASF licenses this file
.. to you under the Apache License, Version 2.0 (the
.. "License"); you may not use this file except in compliance
.. with the License.  You may obtain a copy of the License at

..   http://www.apache.org/licenses/LICENSE-2.0

.. Unless required by applicable law or agreed to in writing,
.. software distributed under the License is distributed on an
.. "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
.. KIND, either express or implied.  See the License for the
.. specific language governing permissions and limitations
.. under the License.

.. _api.compute:
.. currentmodule:: pyarrow.compute

Compute Functions
=================

Aggregations
------------

.. autosummary::
   :toctree: ../generated/

   count
   mean
   min_max
   mode
   stddev
   sum
   variance

Arithmetic Functions
--------------------

By default these functions do not detect overflow. Each function is also
available in an overflow-checking variant, suffixed ``_checked``, which
throws an ``ArrowInvalid`` exception when overflow is detected.

.. autosummary::
   :toctree: ../generated/

   add
   add_checked
   divide
   divide_checked
   multiply
   multiply_checked
   subtract
   subtract_checked

Comparisons
-----------

These functions expect two inputs of the same type. If one of the inputs is `null`
they return ``null``.

.. autosummary::
   :toctree: ../generated/

   equal
   greater
   greater_equal
   less
   less_equal
   not_equal

Logical Functions
-----------------

These functions normally emit a null when one of the inputs is null. However, Kleene
logic variants are provided (suffixed ``_kleene``). See User Guide for details.

.. autosummary::
   :toctree: ../generated/

   and_
   and_kleene
   invert
   or_
   or_kleene
   xor

String Predicates
-----------------

In these functions an empty string emits false in the output. For ASCII
variants (prefixed ``ascii_``) a string element with non-ASCII characters
emits false in the output.

The first set of functions emit true if the input contains only
characters of a given class.

.. autosummary::
   :toctree: ../generated/

   ascii_is_alnum
   ascii_is_alpha
   ascii_is_decimal
   ascii_is_lower
   ascii_is_printable
   ascii_is_space
   ascii_is_upper
   utf8_is_alnum
   utf8_is_alpha
   utf8_is_decimal
   utf8_is_digit
   utf8_is_lower
   utf8_is_numeric
   utf8_is_printable
   utf8_is_space
   utf8_is_upper

The second set of functions also consider the order of characters
in the string element.

.. autosummary::
   :toctree: ../generated/

   ascii_is_title
   utf8_is_title

The third set of functions examines string elements on
a byte-by-byte basis.

.. autosummary::
   :toctree: ../generated/

   string_is_ascii

String Transforms
-----------------

.. autosummary::
   :toctree: ../generated/

   ascii_lower
   ascii_upper
   utf8_lower
   utf8_upper

Containment tests
-----------------

.. autosummary::
   :toctree: ../generated/

   index_in
   is_in
   match_substring

Conversions
-----------

.. autosummary::
   :toctree: ../generated/

   cast
   strptime

Selections
----------

.. autosummary::
   :toctree: ../generated/

   filter
   take

Associative transforms
----------------------

.. autosummary::
   :toctree: ../generated/

   dictionary_encode
   unique
   value_counts

Sorts and partitions
--------------------

.. autosummary::
   :toctree: ../generated/

   partition_nth_indices
   sort_indices

Structural Transforms
---------------------

.. autosummary::
   :toctree: ../generated/

   binary_length
   fill_null
   is_null
   is_valid
   list_value_length
   list_flatten
   list_parent_indices


text:
//---------------------------------------------------------------------
// <copyright file="RelationshipTypeAnnotation.cs" company="Microsoft">
//      Copyright (C) Microsoft Corporation. All rights reserved. See License.txt in the project root for license information.
// </copyright>
//---------------------------------------------------------------------

namespace Microsoft.Test.Taupo.Contracts.EntityModel
{
    using Microsoft.Test.Taupo.Common;

    /// <summary>
    /// An annotation applied to <see cref="AssociationSet"/>s, which caches the
    /// information retrieved by the <see cref="GlobalExtensionMethods.RelationshipType"/>
    /// extension method.
    /// </summary>
    internal sealed class RelationshipTypeAnnotation : Annotation
    {
        /// <summary>
        /// Initializes a new instance of the <see cref="RelationshipTypeAnnotation"/> class.
        /// </summary>
        /// <param name="relationshipType">The <see cref="RelationshipType"/> associated with the
        /// <see cref="AssociationSet"/> to which this <see cref="RelationshipTypeAnnotation"/> is applied.</param>
        public RelationshipTypeAnnotation(RelationshipType relationshipType)
        {
            ExceptionUtilities.Assert(relationshipType != null, "The Relationship argument to the RelationshipAnnotation constructor should never be null.");
            this.RelationshipType = relationshipType;
        }

        /// <summary>
        /// Gets the <see cref="RelationshipType"/> object cached for a particular <see cref="AssociationSet"/>.
        /// </summary>
        public RelationshipType RelationshipType { get; private set; }
    }
}


text:
package org.serverbuilder;

import org.eclipse.jetty.server.Server;
import org.serverbuilder.jetty7.Jetty7ServerBuilders;
import org.serverbuilder.jetty8.Jetty8ServerBuilders;

public class Servers {
    public static ServerBuilders<Server> jetty7() {
        return new Jetty7ServerBuilders();
    }

    public static ServerBuilders<Server> jetty8() {
        return new Jetty8ServerBuilders();
    }
}


text:
require 'yaml'

module Wire
  module Config
    def self.read_config_dir(dir, callback)
      configs = {}
      Dir[File.join(dir, '*.yaml')].each do |entry|
        name   = File.basename(entry, '.yaml')
        config = YAML.load_file(entry)
        if callback
          config = callback.call(config)
        end
        configs[name] = config
      end
      configs
    end
  end
end


text:
<?xml version='1.0' encoding='utf-8'?>
<widget id="it.matisweb.calcoliresine" version="0.0.1" xmlns="http://www.w3.org/ns/widgets"  xmlns:gap="http://phonegap.com/ns/1.0">
    <name>calcoli resine</name>
    <description>
        Calcoli pratici per la posa di pavimenti in resina e ripristino giunti.
    </description>
      <author href="http://matisweb.it" email="info@matisweb.it">Matisweb</author>
    <content src="index.html" />
    <plugin name="cordova-plugin-whitelist" spec="1" />
    <access origin="*" />
    <allow-intent href="http://*/*" />
    <allow-intent href="https://*/*" />
    <allow-intent href="tel:*" />
    <allow-intent href="sms:*" />
    <allow-intent href="mailto:*" />
    <allow-intent href="geo:*" />
    <platform name="android">
        <allow-intent href="market:*" />
    </platform>
    <platform name="ios">
        <allow-intent href="itms:*" />
        <allow-intent href="itms-apps:*" />
    </platform>
</widget>


text:
#include "ParseTreeListener.h"

antlr4::tree::ParseTreeListener::~ParseTreeListener() {
}


text:
<?php

namespace Sendsay\Client;

use GuzzleHttp\Client;
use Sendsay\Credentials;
use Sendsay\Exception\TooManyRedirectsException;
use Sendsay\Message\Message;
use Sendsay\Message\MessageInterface;

class Transport implements TransportInterface
{
    const REDIRECT_LIMIT = 10;

    /**
     * @var Client
     */
    protected $client;

    /**
     * @var array
     */
    private $defaultRequestParams = [
        'apiversion' => 100,
        'json' => 1,
    ];

    /**
     * @var array
     */
    private $credentials;

    /**
     * @var string
     */
    private $session;

    /**
     * @param Credentials $credentials
     * @param Client $client
     */
    public function __construct(Credentials $credentials, Client $client)
    {
        $this->credentials = $credentials;
        $this->client = $client;

        $this->login();
    }

    /**
     * @throws \InvalidArgumentException
     */
    private function login()
    {
        if (!isset($this->session)) {
            $message = $this->request('login');
            $data = $message->getData();
            if (!isset($data['session'])) {
                throw new \InvalidArgumentException($message->getError());
            }
            $this->session = $data['session'];
        }
    }

    /**
     * @param string $action
     * @param array $data
     * @return MessageInterface
     *
     * @throws TooManyRedirectsException
     */
    public function request($action, array $data = null)
    {
        $message = new Message();

        if ($data === null) {
            $data = $this->credentials->getData();
        }

        try {
            $data['action'] = $action;

            $params = $this->buildRequestParams($data);

            $redirectCount = 0;
            $redirectPath = '/';

            do {
                $response = $this->sendRequest($redirectPath, $params);
                if (isset($response['REDIRECT'])){
                    $redirectPath = $response['REDIRECT'];
                }
                $redirectCount++;
                if ($redirectCount > self::REDIRECT_LIMIT){
                    throw new TooManyRedirectsException('Too many redirects');
                }
            } while (isset($response['REDIRECT']));

            if (isset($response['errors'])) {
                $errorMessage = $this->getErrorMessageFromResponse($response);
                return $message->setError($errorMessage);
            }

            $message->setData(isset($response['obj']) ? $response['obj'] : $response);
        } catch (\Exception $e){
            $message->setError($e->getMessage());
        }
        return $message;
    }

    /**
     * @param array $response
     * @return string
     */
    private function getErrorMessageFromResponse(array $response)
    {
        $error = reset($response['errors']);
        if (!isset($error['explain'])) {
            return $error['id'];
        }
        return is_string($error['explain']) ? $error['explain'] : serialize($error['explain']);
    }

    /**
     * @param string $url
     * @param array $params
     * @return array|null
     */
    private function sendRequest($url, array $params = [])
    {
        $response = $this->client->post($url, [
            'verify' => false,
            'form_params' => $params
        ]);

        return json_decode($response->getBody(), true);
    }

    /**
     * @param array $data
     * @return array
     */
    private function buildRequestParams(array $data)
    {
        if ($this->session !== null && !isset($data['session'])) {
            $data['session'] = $this->session;
        }

        return array_merge(
            $this->defaultRequestParams,
            ['request' => json_encode($data)]
        );
    }
}