text:
$(document).ready(function(){
  let from;
  let to;
  let subject;
  let text;

  $("#send_email").click(function(){
    to=$("#to").val();
    // subject=$("#subject").val();
    // text=$("#content").val();
    $("#message").text("Sending a shitty random apology to the person you wronged...Please wait...");

    $.get("/send",{to:to,subject:subject,text:text},function(data){
      if(data=="sent")
      {
        $("#message").empty().html("
Your shitty apology has been sent to " + to + " . Please check inbox!
");
      }
    });

  });
});

redpajama_set_name: RedPajamaGithub


text:
#include "common/stl_serialization.h"
#include "node_prog/node_prog_type.h"
#include "node_prog/edge_count_program.h"

using node_prog::search_type;
using node_prog::edge_count_params;
using node_prog::cache_response;

// params
uint64_t
edge_count_params :: size() const
{
    uint64_t toRet = message::size(edges_props)
        + message::size(edge_count);
    return toRet;
}

void edge_count_params :: pack(e::packer& packer) const
{
    message::pack_buffer(packer, edges_props);
    message::pack_buffer(packer, edge_count);
}

void edge_count_params :: unpack(e::unpacker& unpacker)
{
    message::unpack_buffer(unpacker, edges_props);
    message::unpack_buffer(unpacker, edge_count);
}

// node prog code
std::pair<search_type, std::vector<std::pair<db::remote_node, edge_count_params>>>
node_prog :: edge_count_node_program(
    node &n,
    db::remote_node &,
    edge_count_params &params,
    std::function<edge_count_state&()>,
    std::function<void(std::shared_ptr<node_prog::Cache_Value_Base>,
        std::shared_ptr<std::vector<db::remote_node>>, cache_key_t)>&,
    cache_response<Cache_Value_Base>*)
{
    auto elist = n.get_edges();
    params.edge_count = 0;
    for (edge &e: elist) {
        if (e.has_all_properties(params.edges_props)) {
            params.edge_count++;
        }
    }

    return std::make_pair(search_type::DEPTH_FIRST, std::vector<std::pair<db::remote_node, edge_count_params>>
            (1, std::make_pair(db::coordinator, std::move(params))));
}


text:
<!--

    Copyright © 2013, Masih H. Derkani
    All rights reserved.

    Redistribution and use in source and binary forms, with or without
    modification, are permitted provided that the following conditions are met:
        * Redistributions of source code must retain the above copyright
          notice, this list of conditions and the following disclaimer.
        * Redistributions in binary form must reproduce the above copyright
          notice, this list of conditions and the following disclaimer in the
          documentation and/or other materials provided with the distribution.
        * Neither the name of the <organization> nor the
          names of its contributors may be used to endorse or promote products
          derived from this software without specific prior written permission.

    THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
    ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
    WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
    DISCLAIMED. IN NO EVENT SHALL <COPYRIGHT HOLDER> BE LIABLE FOR ANY
    DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
    (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
    LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
    ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
    (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
    SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.

-->
<project xmlns="http://maven.apache.org/POM/4.0.0"
         xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>

    <parent>
        <groupId>org.derkani</groupId>
        <artifactId>parent-pom</artifactId>
        <version>1.0-SNAPSHOT</version>
    </parent>

    <artifactId>sina</artifactId>
    <version>1.0-SNAPSHOT</version>
    <description>A lightweight statistics and probability distributions library</description>
    <inceptionYear>2013</inceptionYear>

    <dependencies>
        <dependency>
            <groupId>org.apache.commons</groupId>
            <artifactId>commons-math3</artifactId>
            <version>3.3</version>
            <scope>test</scope>
        </dependency>
    </dependencies>

    <repositories>
        <repository>
            <id>org.derkani.maven</id>
            <name>Masih's Maven Repository</name>
            <url>http://maven.derkani.org</url>
            <snapshots>
                <updatePolicy>always</updatePolicy>
            </snapshots>
        </repository>
    </repositories>
</project>


text:
<?xml version="1.0" encoding="utf-8"?>
<manifest package="net.youmi.ads.nativead.demo"
          xmlns:android="http://schemas.android.com/apk/res/android" >

	<application
		android:name=".MainApplication"
		android:allowBackup="true"
		android:icon="@mipmap/ic_launcher"
		android:label="@string/app_name"
		android:roundIcon="@mipmap/ic_launcher_round"
		android:supportsRtl="true"
		android:theme="@style/AppTheme" >
		<activity
			android:name=".PermissionCheckActivity"
			android:configChanges="keyboard|keyboardHidden|orientation|screenSize"
			android:theme="@style/AppTheme.NoActionBar" >
			<intent-filter >
				<action android:name="android.intent.action.MAIN" />

				<category android:name="android.intent.category.LAUNCHER" />
			</intent-filter >
		</activity >
		<activity
			android:name=".ad.splash.SplashActivity"
			android:configChanges="keyboard|keyboardHidden|orientation|screenSize"
			android:theme="@style/AppTheme.NoActionBar" >
		</activity >

		<activity
			android:name=".MainActivity"
			android:configChanges="keyboard|keyboardHidden|orientation|screenSize"
			android:label="@string/app_name"
			android:theme="@style/AppTheme.NoActionBar" >
		</activity >

		<!--兼容Android N 安装apk-->
		<provider
			android:name="android.support.v4.content.FileProvider"
			android:authorities="${APPLICATION_ID}.fileprovider"
			android:exported="false"
			android:grantUriPermissions="true" >

			<meta-data
				android:name="android.support.FILE_PROVIDER_PATHS"
				android:resource="@xml/file_provider" />
		</provider >
	</application >

</manifest >


text:
import os.path as op
import warnings
from nose.tools import assert_raises

import numpy as np
from numpy.testing import assert_equal

from mne import io, read_events, Epochs
from mne import pick_types
from mne.utils import run_tests_if_main, requires_version
from mne.channels import read_layout

from mne.viz import plot_drop_log, plot_epochs_image
from mne.viz.utils import _fake_click

# Set our plotters to test mode
import matplotlib
matplotlib.use('Agg')  # for testing don't use X server

warnings.simplefilter('always')  # enable b/c these tests throw warnings

base_dir = op.join(op.dirname(__file__), '..', '..', 'io', 'tests', 'data')
evoked_fname = op.join(base_dir, 'test-ave.fif')
raw_fname = op.join(base_dir, 'test_raw.fif')
cov_fname = op.join(base_dir, 'test-cov.fif')
event_name = op.join(base_dir, 'test-eve.fif')
event_id, tmin, tmax = 1, -0.1, 1.0
n_chan = 15
layout = read_layout('Vectorview-all')

def _get_raw():
    return io.Raw(raw_fname, preload=False)

def _get_events():
    return read_events(event_name)

def _get_picks(raw):
    return pick_types(raw.info, meg=True, eeg=False, stim=False,
                      ecg=False, eog=False, exclude='bads')

def _get_epochs():
    raw = _get_raw()
    events = _get_events()
    picks = _get_picks(raw)
    # Use a subset of channels for plotting speed
    picks = np.round(np.linspace(0, len(picks) + 1, n_chan)).astype(int)
    epochs = Epochs(raw, events[:5], event_id, tmin, tmax, picks=picks,
                    baseline=(None, 0))
    return epochs

def _get_epochs_delayed_ssp():
    raw = _get_raw()
    events = _get_events()
    picks = _get_picks(raw)
    reject = dict(mag=4e-12)
    epochs_delayed_ssp = Epochs(raw, events[:10], event_id, tmin, tmax,
                                picks=picks, baseline=(None, 0),
                                proj='delayed', reject=reject)
    return epochs_delayed_ssp

def test_plot_epochs():
    """Test epoch plotting"""
    import matplotlib.pyplot as plt
    epochs = _get_epochs()
    epochs.plot(scalings=None, title='Epochs')
    plt.close('all')
    fig = epochs[0].plot(picks=[0, 2, 3], scalings=None)
    fig.canvas.key_press_event('escape')
    plt.close('all')
    fig = epochs.plot()
    fig.canvas.key_press_event('left')
    fig.canvas.key_press_event('right')
    fig.canvas.scroll_event(0.5, 0.5, -0.5)  # scroll down
    fig.canvas.scroll_event(0.5, 0.5, 0.5)  # scroll up
    fig.canvas.key_press_event('up')
    fig.canvas.key_press_event('down')
    fig.canvas.key_press_event('pageup')
    fig.canvas.key_press_event('pagedown')
    fig.canvas.key_press_event('-')
    fig.canvas.key_press_event('+')
    fig.canvas.key_press_event('=')
    fig.canvas.key_press_event('b')
    fig.canvas.key_press_event('f11')
    fig.canvas.key_press_event('home')
    fig.canvas.key_press_event('?')
    fig.canvas.key_press_event('h')
    fig.canvas.key_press_event('o')
    fig.canvas.key_press_event('end')
    fig.canvas.resize_event()
    fig.canvas.close_event()  # closing and epoch dropping
    plt.close('all')
    assert_raises(RuntimeError, epochs.plot, picks=[])
    plt.close('all')
    with warnings.catch_warnings(record=True):
        fig = epochs.plot()
        # test mouse clicks
        x = fig.get_axes()[0].get_xlim()[1] / 2
        y = fig.get_axes()[0].get_ylim()[0] / 2
        data_ax = fig.get_axes()[0]
        n_epochs = len(epochs)
        _fake_click(fig, data_ax, [x, y], xform='data')  # mark a bad epoch
        _fake_click(fig, data_ax, [x, y], xform='data')  # unmark a bad epoch
        _fake_click(fig, data_ax, [0.5, 0.999])  # click elsewhere in 1st axes
        _fake_click(fig, data_ax, [-0.1, 0.9])  # click on y-label
        _fake_click(fig, data_ax, [-0.1, 0.9], button=3)
        _fake_click(fig, fig.get_axes()[2], [0.5, 0.5])  # change epochs
        _fake_click(fig, fig.get_axes()[3], [0.5, 0.5])  # change channels
        fig.canvas.close_event()  # closing and epoch dropping
        assert(n_epochs - 1 == len(epochs))
        plt.close('all')

def test_plot_epochs_image():
    """Test plotting of epochs image
    """
    import matplotlib.pyplot as plt
    epochs = _get_epochs()
    plot_epochs_image(epochs, picks=[1, 2])
    overlay_times = [0.1]
    plot_epochs_image(epochs, order=[0], overlay_times=overlay_times)
    plot_epochs_image(epochs, overlay_times=overlay_times)
    assert_raises(ValueError, plot_epochs_image, epochs,
                  overlay_times=[0.1, 0.2])
    assert_raises(ValueError, plot_epochs_image, epochs,
                  order=[0, 1])
    with warnings.catch_warnings(record=True) as w:
        plot_epochs_image(epochs, overlay_times=[1.1])
        warnings.simplefilter('always')
    assert_equal(len(w), 1)

    plt.close('all')

def test_plot_drop_log():
    """Test plotting a drop log
    """
    import matplotlib.pyplot as plt
    epochs = _get_epochs()
    assert_raises(ValueError, epochs.plot_drop_log)
    epochs.drop_bad_epochs()

    warnings.simplefilter('always', UserWarning)
    with warnings.catch_warnings(record=True):
        epochs.plot_drop_log()

        plot_drop_log([['One'], [], []])
        plot_drop_log([['One'], ['Two'], []])
        plot_drop_log([['One'], ['One', 'Two'], []])
    plt.close('all')

@requires_version('scipy', '0.12')
def test_plot_psd_epochs():
    """Test plotting epochs psd (+topomap)
    """
    import matplotlib.pyplot as plt
    epochs = _get_epochs()
    epochs.plot_psd()
    assert_raises(RuntimeError, epochs.plot_psd_topomap,
                  bands=[(0, 0.01, 'foo')])  # no freqs in range
    epochs.plot_psd_topomap()
    plt.close('all')

run_tests_if_main()


text:
package com.intellij.codeInsight.template;

import com.intellij.codeInsight.template.impl.TemplateImpl;
import com.intellij.codeInsight.template.impl.Variable;
import com.intellij.openapi.application.ApplicationManager;
import com.intellij.openapi.diagnostic.Logger;
import com.intellij.openapi.util.Ref;
import com.intellij.openapi.util.registry.Registry;
import com.intellij.openapi.util.text.StringUtil;
import com.intellij.util.containers.HashMap;
import com.intellij.util.containers.HashSet;
import org.jetbrains.annotations.NonNls;
import org.jetbrains.annotations.NotNull;

import java.util.*;
import java.util.function.Function;
import java.util.stream.Collectors;

/**
 * @author Eugene.Kudelevsky
 */
public class LiveTemplateBuilder {
  @NonNls private static final String END_PREFIX = "____END";
  private static final Logger LOGGER = Logger.getInstance(LiveTemplateBuilder.class);

  private final StringBuilder myText = new StringBuilder();
  private final List<Variable> myVariables = new ArrayList<>();
  private final Set<String> myVarNames = new HashSet<>();
  private final List<VarOccurence> myVariableOccurrences = new ArrayList<>();
  private final List<Marker> myMarkers = new ArrayList<>();
  private final int mySegmentLimit;
  private final boolean myAddEndVariableAtTheEndOfTemplate;
  private String myLastEndVarName;
  private boolean myIsToReformat = false;

  @SuppressWarnings("UnusedDeclaration")
  public LiveTemplateBuilder() {
    this(false, Registry.intValue("emmet.segments.limit"));
  }

  public LiveTemplateBuilder(boolean addEndVariableAtTheEndOfTemplate, int segmentLimit) {
    mySegmentLimit = segmentLimit;
    myAddEndVariableAtTheEndOfTemplate = addEndVariableAtTheEndOfTemplate;
  }

  public void setIsToReformat(boolean isToReformat) {
    myIsToReformat = isToReformat;
  }

  public CharSequence getText() {
    return myText;
  }

  @NotNull
  public String getTextForPreview() {
    if (myVariables.isEmpty()) return myText.toString();
    final StringBuilder sb = new StringBuilder(myText);
    final Ref<Integer> offset = new Ref<>(0);
    final Map<String, Variable> map = myVariables.stream().collect(Collectors.toMap(Variable::getName, Function.identity()));
    myVariableOccurrences.forEach(vo -> {
      final Variable variable = map.get(vo.myName);
      if (variable == null) return;
      String varReplacement = StringUtil.unquoteString(variable.getDefaultValueString());
      varReplacement = StringUtil.isEmptyOrSpaces(varReplacement) ? vo.myName : varReplacement;
      sb.replace(vo.myOffset + offset.get(), vo.myOffset + offset.get(), varReplacement);
      offset.set(offset.get() + varReplacement.length());
    });
    return sb.toString();
  }

  public static boolean isEndVariable(@NotNull String name) {
    return name.startsWith(END_PREFIX);
  }

  private static class VarOccurence {
    String myName;
    int myOffset;

    private VarOccurence(String name, int offset) {
      myName = name;
      myOffset = offset;
    }
  }

  public boolean findVarOccurence(String name) {
    for (VarOccurence occurence : myVariableOccurrences) {
      if (occurence.myName.equals(name)) {
        return true;
      }
    }
    return false;
  }

  @NotNull
  public TemplateImpl buildTemplate() {
    List<Variable> variables = getListWithLimit(myVariables);
    if (!findVarOccurence(TemplateImpl.END)) {
      if (myLastEndVarName == null) {
        for (Variable variable : variables) {
          if (isEndVariable(variable.getName())) {
            myLastEndVarName = variable.getName();
            break;
          }
        }
      }
      if (myLastEndVarName != null) {
        int endOffset = -1;
        if (myAddEndVariableAtTheEndOfTemplate) {
          endOffset = myText.length();
        }
        else {
          Iterator<VarOccurence> it = myVariableOccurrences.iterator();
          while (it.hasNext()) {
            VarOccurence occurence = it.next();
            if (occurence.myName.equals(myLastEndVarName)) {
              endOffset = occurence.myOffset;
              break;
            }
          }
          if (endOffset >= 0) {
            for (Iterator<Variable> it1 = variables.iterator(); it1.hasNext(); ) {
              Variable variable = it1.next();
              if (myLastEndVarName.equals(variable.getName()) && variable.isAlwaysStopAt()) {
                it.remove();
                it1.remove();
              }
            }
          }
        }
        if (endOffset >= 0) {
          myVariableOccurrences.add(new VarOccurence(TemplateImpl.END, endOffset));
        }
      }
    }
    TemplateImpl template = new TemplateImpl("", "");
    for (Variable variable : variables) {
      template.addVariable(variable.getName(), variable.getExpressionString(), variable.getDefaultValueString(), variable.isAlwaysStopAt());
    }

    List<VarOccurence> variableOccurrences = getListWithLimit(myVariableOccurrences);
    Collections.sort(variableOccurrences, (o1, o2) -> {
      if (o1.myOffset < o2.myOffset) {
        return -1;
      }
      if (o1.myOffset > o2.myOffset) {
        return 1;
      }
      return 0;
    });
    int last = 0;
    for (VarOccurence occurence : variableOccurrences) {
      template.addTextSegment(myText.substring(last, occurence.myOffset));
      template.addVariableSegment(occurence.myName);
      last = occurence.myOffset;
    }
    template.addTextSegment(myText.substring(last));
    template.setToReformat(myIsToReformat);
    return template;
  }

  private <T> List<T> getListWithLimit(List<T> list) {
    if (ApplicationManager.getApplication().isUnitTestMode()) {
      return list;
    }
    if (mySegmentLimit == 0) {
      return Collections.emptyList();
    }
    if (mySegmentLimit > 0 && list.size() > mySegmentLimit) {
      LOGGER.warn("Template with more than " + mySegmentLimit + " segments had been build (" + list.size() + "). Text: " + myText);
      return list.subList(0, Math.min(list.size(), mySegmentLimit));
    }
    return list;
  }

  public void insertText(int offset, String text, boolean disableEndVariable) {
    if (disableEndVariable) {
      String varName = null;
      for (VarOccurence occurence : myVariableOccurrences) {
        if (!isEndVariable(occurence.myName)) {
          continue;
        }
        if (occurence.myOffset == offset) {
          varName = occurence.myName;
          break;
        }
      }
      if (varName != null) {
        for (Variable variable : myVariables) {
          if (varName.equals(variable.getName())) {
            variable.setAlwaysStopAt(false);
            variable.setDefaultValueString("\"\"");
            break;
          }
        }
      }
    }
    int delta = text.length();
    for (VarOccurence occurence : myVariableOccurrences) {
      if (occurence.myOffset > offset || !disableEndVariable && occurence.myOffset == offset) {
        occurence.myOffset += delta;
      }
    }
    myText.insert(offset, text);
    updateMarkers(offset, text);
  }

  public int length() {
    return myText.length();
  }

  private void updateMarkers(int offset, String text) {
    for (Marker marker : myMarkers) {
      if (offset < marker.getStartOffset()) {
        marker.myStartOffset += text.length();
      }
      else if (offset <= marker.getEndOffset()) {
        marker.myEndOffset += text.length();
      }
    }
  }

  private String generateUniqueVarName(Set<String> existingNames, boolean end) {
    String prefix = end ? END_PREFIX : "VAR";
    int i = 0;
    while (myVarNames.contains(prefix + i) || existingNames.contains(prefix + i)) {
      i++;
    }
    return prefix + i;
  }

  public int insertTemplate(int offset, TemplateImpl template, Map<String, String> predefinedVarValues) {
    myIsToReformat = myText.length() > 0 || template.isToReformat();
    removeEndVarAtOffset(offset);

    String text = template.getTemplateText();
    insertText(offset, text, false);
    Map<String, String> newVarNames = new HashMap<>();
    Set<String> oldVarNames = new HashSet<>();
    for (int i = 0; i < template.getVariableCount(); i++) {
      String varName = template.getVariableNameAt(i);
      oldVarNames.add(varName);
    }
    for (int i = 0; i < template.getVariableCount(); i++) {
      String varName = template.getVariableNameAt(i);
      if (!TemplateImpl.INTERNAL_VARS_SET.contains(varName)) {
        if (predefinedVarValues != null && predefinedVarValues.containsKey(varName)) {
          continue;
        }
        String newVarName;
        if (myVarNames.contains(varName)) {
          oldVarNames.remove(varName);
          newVarName = generateUniqueVarName(oldVarNames, isEndVariable(varName));
          newVarNames.put(varName, newVarName);
          if (varName.equals(myLastEndVarName)) {
            myLastEndVarName = newVarName;
          }
        }
        else {
          newVarName = varName;
        }
        Variable var = new Variable(newVarName, template.getExpressionStringAt(i), template.getDefaultValueStringAt(i), template.isAlwaysStopAt(i));
        if (mySegmentLimit >= 0 && myVariables.size() >= mySegmentLimit) {
          if (mySegmentLimit > 0) {
            LOGGER.warn("Template with more than " + mySegmentLimit + " segments had been build. Text: " + myText);
          }
          break;
        }
        myVariables.add(var);
        myVarNames.add(newVarName);
      }
    }
    int end = -1;

    for (int i = 0; i < template.getSegmentsCount(); i++) {
      String segmentName = template.getSegmentName(i);
      int localOffset = template.getSegmentOffset(i);
      if (TemplateImpl.END.equals(segmentName)) {
        end = offset + localOffset;
      }
      else {
        if (predefinedVarValues != null && predefinedVarValues.containsKey(segmentName)) {
          String value = predefinedVarValues.get(segmentName);
          insertText(offset + localOffset, value, false);
          offset += value.length();
          continue;
        }
        if (newVarNames.containsKey(segmentName)) {
          segmentName = newVarNames.get(segmentName);
        }
        myVariableOccurrences.add(new VarOccurence(segmentName, offset + localOffset));
      }
    }
    int endOffset = end >= 0 ? end : offset + text.length();
    if (endOffset > 0 &&
        endOffset != offset + text.length() &&
        endOffset < myText.length() &&
        !hasVarAtOffset(endOffset)) {
      myLastEndVarName = generateUniqueVarName(myVarNames, true);
      myVariables.add(new Variable(myLastEndVarName, "", "", true));
      myVarNames.add(myLastEndVarName);
      myVariableOccurrences.add(new VarOccurence(myLastEndVarName, endOffset));
    }
    return endOffset;
  }

  private void removeEndVarAtOffset(int offset) {
    for (Iterator<VarOccurence> it = myVariableOccurrences.iterator(); it.hasNext();) {
      VarOccurence occurence = it.next();
      if (!isEndVariable(occurence.myName)) {
        continue;
      }
      if (occurence.myOffset == offset) {
        it.remove();
        for (Iterator<Variable> it1 = myVariables.iterator(); it1.hasNext();) {
          Variable variable = it1.next();
          if (occurence.myName.equals(variable.getName())) {
            it1.remove();
          }
        }
      }
    }
  }

  private boolean hasVarAtOffset(int offset) {
    boolean flag = false;
    for (VarOccurence occurence : myVariableOccurrences) {
      if (occurence.myOffset == offset) {
        flag = true;
      }
    }
    return flag;
  }

  public Marker createMarker(int offset) {
    Marker marker = new Marker(offset, offset);
    myMarkers.add(marker);
    return marker;
  }

  public static class Marker {
    int myStartOffset;
    int myEndOffset;

    private Marker(int startOffset, int endOffset) {
      myStartOffset = startOffset;
      myEndOffset = endOffset;
    }

    public int getStartOffset() {
      return myStartOffset;
    }

    public int getEndOffset() {
      return myEndOffset;
    }
  }
}


text:
'use strict';

/**
@module ember-cli
*/
var FileInfo      = require('./file-info');
var Promise       = require('../ext/promise');
var chalk         = require('chalk');
var MarkdownColor = require('../../lib/utilities/markdown-color');
var fs            = require('fs-extra');
var existsSync    = require('exists-sync');
var inflector     = require('inflection');
var minimatch     = require('minimatch');
var path          = require('path');
var sequence      = require('../utilities/sequence');
var stat          = Promise.denodeify(fs.stat);
var stringUtils   = require('../utilities/string');
var compact       = require('lodash/array/compact');
var intersect     = require('lodash/array/intersection');
var uniq          = require('lodash/array/uniq');
var zipObject     = require('lodash/array/zipObject');
var contains      = require('lodash/collection/contains');
var any           = require('lodash/collection/some');
var keys          = require('lodash/object/keys');
var merge         = require('lodash/object/merge');
var values        = require('lodash/object/values');
var walkSync      = require('walk-sync');
var writeFile     = Promise.denodeify(fs.outputFile);
var removeFile    = Promise.denodeify(fs.remove);
var SilentError   = require('silent-error');
var CoreObject    = require('core-object');
var EOL           = require('os').EOL;
var deprecateUI   = require('../utilities/deprecate').deprecateUI;
var bowEpParser   = require('bower-endpoint-parser');
var debug         = require('debug')('ember-cli:blueprint');
module.exports = Blueprint;

/**
  A blueprint is a bundle of template files with optional install
  logic.

  Blueprints follow a simple structure. Let's take the built-in
  `controller` blueprint as an example:

  ```
  blueprints/controller
  ├── files
  │   ├── app
  │   │   └── __path__
  │   │       └── __name__.js
  └── index.js

  blueprints/controller-test
  ├── files
  │   └── tests
  │       └── unit
  │           └── controllers
  │               └── __test__.js
  └── index.js
  ```

  ## Files

  `files` contains templates for the all the files to be
  installed into the target directory.

  The `__name__` token is subtituted with the dasherized
  entity name at install time. For example, when the user
  invokes `ember generate controller foo` then `__name__` becomes
  `foo`. When the `--pod` flag is used, for example `ember
  generate controller foo --pod` then `__name__` becomes
  `controller`.

  The `__path__` token is substituted with the blueprint
  name at install time. For example, when the user invokes
  `ember generate controller foo` then `__path__` becomes
  `controller`. When the `--pod` flag is used, for example
  `ember generate controller foo --pod` then `__path__`
  becomes `foo` (or `<podModulePrefix>/foo` if the
  podModulePrefix is defined). This token is primarily for
  pod support, and is only necessary if the blueprint can be
  used in pod structure. If the blueprint does not require pod
  support, simply use the blueprint name instead of the
  `__path__` token.

  The `__test__` token is substituted with the dasherized
  entity name and appended with `-test` at install time.
  This token is primarily for pod support and only necessary
  if the blueprint requires support for a pod structure. If
  the blueprint does not require pod support, simply use the
  `__name__` token instead.

  ## Template Variables (AKA Locals)

  Variables can be inserted into templates with
  `<%= someVariableName %>`.

  For example, the built-in `util` blueprint
  `files/app/utils/__name__.js` looks like this:

  ```js
  export default function <%= camelizedModuleName %>() {
    return true;
  }
  ```

  `<%= camelizedModuleName %>` is replaced with the real
  value at install time.

  The following template variables are provided by default:

  - `dasherizedPackageName`
  - `classifiedPackageName`
  - `dasherizedModuleName`
  - `classifiedModuleName`
  - `camelizedModuleName`

  `packageName` is the project name as found in the project's
  `package.json`.

  `moduleName` is the name of the entity being generated.

  The mechanism for providing custom template variables is
  described below.

  ## Index.js

  Custom installation and uninstallation behaviour can be added
  by overriding the hooks documented below. `index.js` should
  export a plain object, which will extend the prototype of the
  `Blueprint` class. If needed, the original `Blueprint` prototype
  can be accessed through the `_super` property.

  ```js
  module.exports = {
    locals: function(options) {
      // Return custom template variables here.
      return {};
    },

    normalizeEntityName: function(entityName) {
      // Normalize and validate entity name here.
      return entityName;
    },

    fileMapTokens: function(options) (
      // Return custom tokens to be replaced in your files
      return {
        __token__: function(options){
          // logic to determine value goes here
          return 'value';
        }
      }
    },

    beforeInstall: function(options) {},
    afterInstall: function(options) {},
    beforeUninstall: function(options) {},
    afterUninstall: function(options) {}

  };
  ```

  ## Blueprint Hooks

  As shown above, the following hooks are available to
  blueprint authors:

  - `locals`
  - `normalizeEntityName`
  - `fileMapTokens`
  - `beforeInstall`
  - `afterInstall`
  - `beforeUninstall`
  - `afterUninstall`

  ### locals

  Use `locals` to add custom tempate variables. The method
  receives one argument: `options`. Options is an object
  containing general and entity-specific options.

  When the following is called on the command line:

  ```sh
  ember generate controller foo --type=array --dry-run
  ```

  The object passed to `locals` looks like this:

  ```js
  {
    entity: {
      name: 'foo',
      options: {
        type: 'array'
      }
    },
    dryRun: true
  }
  ```

  This hook must return an object. It will be merged with the
  aforementioned default locals.

  ### normalizeEntityName

  Use the `normalizeEntityName` hook to add custom normalization and
  validation of the provided entity name. The default hook does not
  make any changes to the entity name, but makes sure an entity name
  is present and that it doesn't have a trailing slash.

  This hook receives the entity name as its first argument. The string
  returned by this hook will be used as the new entity name.

  ### fileMapTokens

  Use `fileMapTokens` to add custom fileMap tokens for use
  in the `mapFile` method. The hook must return an object in the
  following pattern:

  ```js
  {
    __token__: function(options){
      // logic to determine value goes here
      return 'value';
    }
  }
  ```

  It will be merged with the default `fileMapTokens`, and can be used
  to override any of the default tokens.

  Tokens are used in the files folder (see `files`), and get replaced with
  values when the `mapFile` method is called.

  ### beforeInstall & beforeUninstall

  Called before any of the template files are processed and receives
  the the `options` and `locals` hashes as parameters. Typically used for
  validating any additional command line options or for any asynchronous
  setup that is needed.   As an example, the `controller` blueprint validates
  its `--type` option in this hook.  If you need to run any asynchronous code,
  wrap it in a promise and return that promise from these hooks.  This will
  ensure that your code is executed correctly.

  ### afterInstall & afterUninstall

  The `afterInstall` and `afterUninstall` hooks receives the same
  arguments as `locals`. Use it to perform any custom work after the
  files are processed. For example, the built-in `route` blueprint
  uses these hooks to add and remove relevant route declarations in
  `app/router.js`.

  ### Overriding Install

  If you don't want your blueprint to install the contents of
  `files` you can override the `install` method. It receives the
  same `options` object described above and must return a promise.
  See the built-in `resource` blueprint for an example of this.

  @class Blueprint
  @constructor
  @extends CoreObject
  @param {String} [blueprintPath]
*/
function Blueprint(blueprintPath) {
  this.path = blueprintPath;
  this.name = path.basename(blueprintPath);
}

Blueprint.__proto__ = CoreObject;
Blueprint.prototype.constructor = Blueprint;

Blueprint.prototype.availableOptions = [];
Blueprint.prototype.anonymousOptions = ['name'];

/**
  Used to retrieve files for blueprint. The `file` param is an
  optional string that is turned into a glob.

  @method files
  @return {Array} Contents of the blueprint's files directory
*/
Blueprint.prototype.files = function() {
  if (this._files) { return this._files; }

  var filesPath = path.join(this.path, 'files');
  if (existsSync(filesPath)) {
    this._files = walkSync(path.join(this.path, 'files'));
  } else {
    this._files = [];
  }

  return this._files;
};

/**
  @method srcPath
  @param {String} file
  @return {String} Resolved path to the file
*/
Blueprint.prototype.srcPath = function(file) {
  return path.resolve(this.path, 'files', file);
};

/**
  Hook for normalizing entity name
  @method normalizeEntityName
  @param {String} entityName
  @return {null}
*/
Blueprint.prototype.normalizeEntityName = function(entityName) {
  if (!entityName) {
    throw new SilentError('The `ember generate` command requires an ' +
                          'entity name to be specified. ' +
                          'For more details, use `ember help`.');
  }

  var trailingSlash = /(\/$|\\$)/;
  if(trailingSlash.test(entityName)) {
    throw new SilentError('You specified "' + entityName + '", but you can\'t use a ' +
                          'trailing slash as an entity name with generators. Please ' +
                          're-run the command with "' + entityName.replace(trailingSlash, '') + '".');
  }

  return entityName;
};

/**
  Write a status and message to the UI
  @private
  @method _writeStatusToUI
  @param {Function} chalkColor
  @param {String} keyword
  @param {String} message
*/
Blueprint.prototype._writeStatusToUI = function(chalkColor, keyword, message) {
  if (this.ui) {
    this.ui.writeLine('  ' + chalkColor(keyword) + ' ' + message);
  }
};

/**
  @private
  @method _writeFile
  @param {Object} info
  @return {Promise}
*/
Blueprint.prototype._writeFile = function(info) {
  if (!this.dryRun) {
    return writeFile(info.outputPath, info.render());
  }
};

/**
  Actions lookup
  @private
*/

Blueprint.prototype._actions = {
  write: function(info) {
    this._writeStatusToUI(chalk.green, 'create', info.displayPath);
    return this._writeFile(info);
  },
  skip: function(info) {
    var label = 'skip';

    if (info.resolution === 'identical') {
      label = 'identical';
    }

    this._writeStatusToUI(chalk.yellow, label, info.displayPath);
  },

  overwrite: function(info) {
    this._writeStatusToUI(chalk.yellow, 'overwrite', info.displayPath);
    return this._writeFile(info);
  },

  edit: function(info) {
    this._writeStatusToUI(chalk.green, 'edited', info.displayPath);
  },

  remove: function(info) {
    this._writeStatusToUI(chalk.red, 'remove', info.displayPath);
    if (!this.dryRun) {
      return removeFile(info.outputPath);
    }
  }
};

/**
  Calls an action.
  @private
  @method _commit
  @param {Object} result
  @return {Promise}
  @throws {Error} Action doesn't exist.
*/
Blueprint.prototype._commit = function(result) {
  var action = this._actions[result.action];

  if (action) {
    return action.call(this, result);
  } else {
    throw new Error('Tried to call action \"' + result.action + '\" but it does not exist');
  }
};

/**
  Prints warning for pod unsupported.
  @private
  @method _checkForPod
*/
Blueprint.prototype._checkForPod = function(verbose) {
  if (!this.hasPathToken && this.pod && verbose) {
    this.ui.writeLine(chalk.yellow('You specified the pod flag, but this' +
      ' blueprint does not support pod structure. It will be generated with' +
      ' the default structure.'));
  }
};

/**
  @private
  @method _normalizeEntityName
  @param {Object} entity
*/
Blueprint.prototype._normalizeEntityName = function(entity) {
  if (entity) {
    entity.name = this.normalizeEntityName(entity.name);
  }
};

/**
  @private
  @method _checkInRepoAddonExists
  @param {String} inRepoAddon
*/
Blueprint.prototype._checkInRepoAddonExists = function(inRepoAddon) {
  if (inRepoAddon) {
    if (!inRepoAddonExists(inRepoAddon, this.project.root)) {
      throw new SilentError('You specified the in-repo-addon flag, but the' +
        ' in-repo-addon \'' + inRepoAddon + '\' does not exist. Please' +
        ' check the name and try again.');
    }
  }
};

/**
  @private
  @method _process
  @param {Object} options
  @param {Function} beforeHook
  @param {Function} process
  @param {Function} afterHook
*/
Blueprint.prototype._process = function(options, beforeHook, process, afterHook) {
  var intoDir = options.target;
  var locals  = this._locals(options);

  return Promise.resolve()
    .then(beforeHook.bind(this, options, locals))
    .then(process.bind(this, intoDir, locals)).map(this._commit.bind(this))
    .then(afterHook.bind(this, options));
};

/**
  @method install
  @param {Object} options
  @return {Promise}
*/
Blueprint.prototype.install = function(options) {
  var ui       = this.ui     = options.ui;
  var dryRun   = this.dryRun = options.dryRun;
  this.project = options.project;
  this.pod     = options.pod;
  this.hasPathToken = hasPathToken(this.files());

  podDeprecations(this.project.config(), ui);

  ui.writeLine('installing ' + this.name);

  if (dryRun) {
    ui.writeLine(chalk.yellow('You specified the dry-run flag, so no' +
      ' changes will be written.'));
  }

  this._normalizeEntityName(options.entity);
  this._checkForPod(options.verbose);
  this._checkInRepoAddonExists(options.inRepoAddon);

  debug('START: processing blueprint: `%s`', this.name);
  var start = new Date();
  return this._process(
    options,
    this.beforeInstall,
    this.processFiles,
    this.afterInstall).finally(function() {
      debug('END: processing blueprint: `%s` in (%dms)', this.name, new Date() - start);
    }.bind(this));
};

/**
  @method uninstall
  @param {Object} options
  @return {Promise}
*/
Blueprint.prototype.uninstall = function(options) {
  var ui       = this.ui     = options.ui;
  var dryRun   = this.dryRun = options.dryRun;
  this.project = options.project;
  this.pod     = options.pod;
  this.hasPathToken = hasPathToken(this.files());

  podDeprecations(this.project.config(), ui);

  ui.writeLine('uninstalling ' + this.name);

  if (dryRun) {
    ui.writeLine(chalk.yellow('You specified the dry-run flag, so no' +
      ' files will be deleted.'));
  }

  this._normalizeEntityName(options.entity);
  this._checkForPod(options.verbose);

  return this._process(
    options,
    this.beforeUninstall,
    this.processFilesForUninstall,
    this.afterUninstall);
};

/**
  Hook for running operations before install.
  @method beforeInstall
  @return {Promise|null}
*/
Blueprint.prototype.beforeInstall = function() {};

/**
  Hook for running operations after install.
  @method afterInstall
  @return {Promise|null}
*/
Blueprint.prototype.afterInstall = function() {};

/**
  Hook for running operations before uninstall.
  @method beforeUninstall
  @return {Promise|null}
*/
Blueprint.prototype.beforeUninstall = function() {};

/**
  Hook for running operations after uninstall.
  @method afterUninstall
  @return {Promise|null}
*/
Blueprint.prototype.afterUninstall = function() {};

/**
  Hook for adding additional locals
  @method locals
  @return {Object|null}
*/
Blueprint.prototype.locals = function() {};

/**
  Hook to add additional or override existing fileMapTokens.
  @method fileMapTokens
  @return {Object|null}
*/
Blueprint.prototype.fileMapTokens = function() {
};

/**
  @private
  @method _fileMapTokens
  @param {Object} options
  @return {Object}
*/
Blueprint.prototype._fileMapTokens = function(options) {
  var standardTokens = {
    __name__: function(options) {
      if (options.pod && options.hasPathToken) {
        return options.blueprintName;
      }
      return options.dasherizedModuleName;
    },
    __path__: function(options) {
      var blueprintName = options.blueprintName;

      if(blueprintName.match(/-test/)) {
        blueprintName = options.blueprintName.slice(0, options.blueprintName.indexOf('-test'));
      }
      if (options.pod && options.hasPathToken) {
        return path.join(options.podPath, options.dasherizedModuleName);
      }
      return inflector.pluralize(blueprintName);
    },
    __root__: function(options) {
      if (options.inRepoAddon) {
        return path.join('lib',options.inRepoAddon, 'addon');
      }
      if (options.inDummy) {
        return path.join('tests','dummy','app');
      }
      if (options.inAddon) {
        return 'addon';
      }
      return 'app';
    },
    __test__: function(options) {
      if (options.pod && options.hasPathToken) {
        return options.blueprintName;
      }
      return options.dasherizedModuleName + '-test';
    }
  };

  var customTokens = this.fileMapTokens(options) || options.fileMapTokens || {};
  return merge(standardTokens, customTokens);
};

/**
  Used to generate fileMap tokens for mapFile.

  @method generateFileMap
  @param {Object} fileMapVariables
  @return {Object}
*/
Blueprint.prototype.generateFileMap = function(fileMapVariables){
  var tokens        = this._fileMapTokens(fileMapVariables);
  var fileMapValues = values(tokens);
  var tokenValues   = fileMapValues.map(function(token) { return token(fileMapVariables); });
  var tokenKeys     = keys(tokens);
  return zipObject(tokenKeys,tokenValues);
};

/**
  @method buildFileInfo
  @param {Function} destPath
  @param {Object} templateVariables
  @param {String} file
  @return {FileInfo}
*/
Blueprint.prototype.buildFileInfo = function(destPath, templateVariables, file) {
  var mappedPath = this.mapFile(file, templateVariables);

  return new FileInfo({
    action: 'write',
    outputPath: destPath(mappedPath),
    displayPath: path.normalize(mappedPath),
    inputPath: this.srcPath(file),
    templateVariables: templateVariables,
    ui: this.ui
  });
};

/**
  @method isUpdate
  @return {Boolean}
*/
Blueprint.prototype.isUpdate = function() {
  if (this.project && this.project.isEmberCLIProject) {
    return this.project.isEmberCLIProject();
  }
};

/**
  @private
  @method _getFileInfos
  @param {Array} files
  @param {String} intoDir
  @param {Object} templateVariables
  @return {Array} file infos
*/
Blueprint.prototype._getFileInfos = function(files, intoDir, templateVariables) {
  return files.map(this.buildFileInfo.bind(this, destPath.bind(null, intoDir), templateVariables));
};

/**
  Add update files to ignored files
  @private
  @method _ignoreUpdateFiles
*/
Blueprint.prototype._ignoreUpdateFiles = function() {
  if (this.isUpdate()) {
    Blueprint.ignoredFiles = Blueprint.ignoredFiles.concat(Blueprint.ignoredUpdateFiles);
  }
};

/**
  @private
  @method _getFilesForInstall
  @param {Array} targetFiles
  @return {Array} files
*/
Blueprint.prototype._getFilesForInstall = function(targetFiles) {
  var files = this.files();

  // if we've defined targetFiles, get file info on ones that match
  return targetFiles && targetFiles.length > 0 && intersect(files, targetFiles) || files;
};

/**
  @private
  @method _checkForNoMatch
  @param {Array} fileInfos
  @param {String} rawArgs
*/
Blueprint.prototype._checkForNoMatch = function(fileInfos, rawArgs) {
  if (fileInfos.filter(isFilePath).length < 1 && rawArgs) {
    this.ui.writeLine(chalk.yellow('The globPattern \"' + rawArgs +
      '\" did not match any files, so no file updates will be made.'));
  }
};

function finishProcessingForInstall(infos) {
  infos.forEach(markIdenticalToBeSkipped);

  var infosNeedingConfirmation = infos.reduce(gatherConfirmationMessages, []);

  return sequence(infosNeedingConfirmation).returns(infos);
}

function finishProcessingForUninstall(infos) {
  infos.forEach(markToBeRemoved);
  return infos;
}

/**
  @method processFiles
  @param {String} intoDir
  @param {Object} templateVariables
*/
Blueprint.prototype.processFiles = function(intoDir, templateVariables) {
  var files = this._getFilesForInstall(templateVariables.targetFiles);
  var fileInfos = this._getFileInfos(files, intoDir, templateVariables);

  this._checkForNoMatch(fileInfos, templateVariables.rawArgs);

  this._ignoreUpdateFiles();

  return Promise.filter(fileInfos, isValidFile).
    map(prepareConfirm).
    then(finishProcessingForInstall);
};

/**
  @method processFilesForUninstall
  @param {String} intoDir
  @param {Object} templateVariables
*/
Blueprint.prototype.processFilesForUninstall = function(intoDir, templateVariables) {
  var fileInfos = this._getFileInfos(this.files(), intoDir, templateVariables);

  this._ignoreUpdateFiles();

  return Promise.filter(fileInfos, isValidFile).
    then(finishProcessingForUninstall);
};

/**
  @method mapFile
  @param {String} file
  @return {String}
*/
Blueprint.prototype.mapFile = function(file, locals) {
  var pattern, i;
  var fileMap = locals.fileMap || { __name__: locals.dasherizedModuleName };
  file = Blueprint.renamedFiles[file] || file;
  for (i in fileMap) {
    pattern = new RegExp(i, 'g');
    file = file.replace(pattern, fileMap[i]);
  }
  return file;
};

/**
  Looks for a __root__ token in the files folder. Must be present for
  the blueprint to support addon tokens. The `server`, `blueprints`, and `test`

  @private
  @method supportsAddon
  @return {Boolean}
*/
Blueprint.prototype.supportsAddon = function() {
  return this.files().join().match(/__root__/);
};

/**
  @private
  @method _generateFileMapVariables
  @param {Object} options
  @return {Object}
*/
Blueprint.prototype._generateFileMapVariables = function(moduleName, locals, options) {
  var originBlueprintName = options.originBlueprintName || this.name;
  var podModulePrefix = this.project.config().podModulePrefix || '';
  var podPath = podModulePrefix.substr(podModulePrefix.lastIndexOf('/') + 1);
  var inAddon = this.project.isEmberCLIAddon() || !!options.inRepoAddon;
  var inDummy = this.project.isEmberCLIAddon() ? options.dummy : false;

  return {
    pod: this.pod,
    podPath: podPath,
    hasPathToken: this.hasPathToken,
    inAddon: inAddon,
    inRepoAddon: options.inRepoAddon,
    inDummy: inDummy,
    blueprintName: this.name,
    originBlueprintName: originBlueprintName,
    dasherizedModuleName: stringUtils.dasherize(moduleName),
    locals: locals
  };
};

/**
  @private
  @method _locals
  @param {Object} options
  @return {Object}
*/
Blueprint.prototype._locals = function(options) {
  var packageName = options.project.name();
  var moduleName = options.entity && options.entity.name || packageName;
  var sanitizedModuleName = moduleName.replace(/\//g, '-');
  var customLocals = this.locals(options);
  var fileMapVariables = this._generateFileMapVariables(moduleName, customLocals, options);
  var fileMap = this.generateFileMap(fileMapVariables);

  var standardLocals = {
    dasherizedPackageName: stringUtils.dasherize(packageName),
    classifiedPackageName: stringUtils.classify(packageName),
    dasherizedModuleName: stringUtils.dasherize(moduleName),
    classifiedModuleName: stringUtils.classify(sanitizedModuleName),
    camelizedModuleName: stringUtils.camelize(sanitizedModuleName),
    decamelizedModuleName: stringUtils.decamelize(sanitizedModuleName),
    fileMap: fileMap,
    hasPathToken: this.hasPathToken,
    targetFiles: options.targetFiles,
    rawArgs: options.rawArgs
  };

  return merge({}, standardLocals, customLocals);
};

/**
  Used to add a package to the projects `package.json`.

  Generally, this would be done from the `afterInstall` hook, to
  ensure that a package that is required by a given blueprint is
  available.

  @method addPackageToProject
  @param {String} packageName
  @param {String} target
  @return {Promise}
*/
Blueprint.prototype.addPackageToProject = function(packageName, target) {
  var packageObject = {name: packageName};

  if (target) {
    packageObject.target = target;
  }

  return this.addPackagesToProject([packageObject]);
};

/**
  Used to add multiple packages to the projects `package.json`.

  Generally, this would be done from the `afterInstall` hook, to
  ensure that a package that is required by a given blueprint is
  available.

  Expects each array item to be an object with a `name`.  Each object
  may optionally have a `target` to specify a specific version.

  @method addPackagesToProject
  @param {Array} packages
  @return {Promise}
*/
Blueprint.prototype.addPackagesToProject = function(packages) {
  var task         = this.taskFor('npm-install');
  var install      = (packages.length > 1) ? 'install packages' : 'install package';
  var packageNames = [];
  var packageArray = [];

  for (var i = 0; i < packages.length; i++) {
    packageNames.push(packages[i].name);

    var packageNameAndVersion = packages[i].name;

    if (packages[i].target) {
      packageNameAndVersion += '@' + packages[i].target;
    }

    packageArray.push(packageNameAndVersion);
  }

  this._writeStatusToUI(chalk.green, install, packageNames.join(', '));

  return task.run({
    'save-dev': true,
    verbose: false,
    packages: packageArray
  });
};

/**
  Used to remove a package from the projects `package.json`.

  Generally, this would be done from the `afterInstall` hook, to
  ensure that any package conflicts can be resolved before the
  addon is used.

  @method removePackageFromProject
  @param {String} packageName
  @return {Promise}
*/
Blueprint.prototype.removePackageFromProject = function(packageName) {
  var packageObject = {name: packageName};

  return this.removePackagesFromProject([packageObject]);
};

/**
  Used to remove multiple packages from the projects `package.json`.

  Generally, this would be done from the `afterInstall` hook, to
  ensure that any package conflicts can be resolved before the
  addon is used.

  Expects each array item to be an object with a `name` property.

  @method removePackagesFromProject
  @param {Array} packages
  @return {Promise}
*/
Blueprint.prototype.removePackagesFromProject = function(packages) {
  var task         = this.taskFor('npm-uninstall');
  var install      = (packages.length > 1) ? 'uninstall packages' : 'uninstall package';
  var packageNames = [];
  var packageArray = [];

  for (var i = 0; i < packages.length; i++) {
    packageNames.push(packages[i].name);

    var packageNameAndVersion = packages[i].name;

    packageArray.push(packageNameAndVersion);
  }

  this._writeStatusToUI(chalk.green, install, packageNames.join(', '));

  return task.run({
    'save-dev': true,
    verbose: false,
    packages: packageArray
  });
};

/**
  Used to add a package to the projects `bower.json`.

  Generally, this would be done from the `afterInstall` hook, to
  ensure that a package that is required by a given blueprint is
  available.

  `localPackageName` and `target` may be thought of as equivalent
  to the key-value pairs in the `dependency` or `devDepencency`
  objects contained within a bower.json file.

  Examples:

  addBowerPackageToProject('jquery', '~1.11.1');
  addBowerPackageToProject('old_jquery', 'jquery#~1.9.1');
  addBowerPackageToProject('bootstrap-3', 'http://twitter.github.io/bootstrap/assets/bootstrap');

  @method addBowerPackageToProject
  @param {String} localPackageName
  @param {String} target
  @param {Object} installOptions
  @return {Promise}
*/
Blueprint.prototype.addBowerPackageToProject = function(localPackageName, target, installOptions) {
  var lpn = localPackageName;
  var tar = target;
  if (localPackageName.indexOf('#') >= 0) {
    if (arguments.length === 1) {
      var parts = localPackageName.split('#');
      lpn = parts[0];
      tar = parts[1];
      deprecateUI(this.ui)('passing ' + localPackageName +
        ' directly to `addBowerPackageToProject` will soon be unsupported. \n' +
        'You may want to replace this with ' +
        '`addBowerPackageToProject(\'' + lpn +'\', \'' + tar + '\')`', true);
    } else {
      deprecateUI(this.ui)('passing ' + localPackageName +
        ' directly to `addBowerPackageToProject` will soon be unsupported', true);
    }
  }
  var packageObject = bowEpParser.json2decomposed(lpn, tar);
  return this.addBowerPackagesToProject([packageObject], installOptions);
};

/**
  Used to add an array of packages to the projects `bower.json`.

  Generally, this would be done from the `afterInstall` hook, to
  ensure that a package that is required by a given blueprint is
  available.

  Expects each array item to be an object with a `name`.  Each object
  may optionally have a `target` to specify a specific version.

  @method addBowerPackagesToProject
  @param {Array} packages
  @param {Object} installOptions
  @return {Promise}
*/
Blueprint.prototype.addBowerPackagesToProject = function(packages, installOptions) {
  var task = this.taskFor('bower-install');
  var packageNamesAndVersions = packages
    .map(function(pkg) {
      pkg.source = pkg.source || pkg.name;
      return pkg;
    })
    .map(bowEpParser.compose);

  return task.run({
    verbose: true,
    packages: packageNamesAndVersions,
    installOptions: installOptions
  });
};

/**
  Used to add an addon to the projects `package.json` and run it's
  `defaultBlueprint` if it provides one.

  Generally, this would be done from the `afterInstall` hook, to
  ensure that a package that is required by a given blueprint is
  available.

  @method addAddonToProject
  @param {Object} options
  @return {Promise}
*/
Blueprint.prototype.addAddonToProject = function(options) {
  var taskOptions = {};

  if (typeof options === 'string') {
    taskOptions['packages'] = [options];
  } else {
    if (!options.name) {
      throw new SilentError('You must provide a `name` to addAddonToProject');
    }

    if (options.target) {
      options.name += '@' + options.target;
    }

    taskOptions['packages']      = [options.name];
    taskOptions.extraArgs        = options.extraArgs || [];
    taskOptions.blueprintOptions = options.blueprintOptions || {};
  }

  var task = this.taskFor('addon-install');

  this._writeStatusToUI(chalk.green, 'install addon', taskOptions['packages']);

  return task.run(taskOptions);
};

/**
  Used to retrieve a task with the given name. Passes the new task
  the standard information available (like `ui`, `analytics`, `project`, etc).

  @method taskFor
  @param dasherizedName
  @public
*/
Blueprint.prototype.taskFor = function(dasherizedName) {
  var Task = require('../tasks/' + dasherizedName);

  return new Task({
    ui: this.ui,
    project: this.project,
    analytics: this.analytics
  });
};

/*

  Inserts the given content into a file. If the `contentsToInsert` string is already
  present in the current contents, the file will not be changed unless `force` option
  is passed.

  If `options.before` is specified, `contentsToInsert` will be inserted before
  the first instance of that string.  If `options.after` is specified, the
  contents will be inserted after the first instance of that string.
  If the string specified by options.before or options.after is not in the file,
  no change will be made.

  If neither `options.before` nor `options.after` are present, `contentsToInsert`
  will be inserted at the end of the file.

  Example:
  ```
  // app/router.js
  Router.map(function(){
  });

  insertIntoFile('app/router.js',
                 '  this.route("admin");',
                 {after:'Router.map(function() {'+EOL});

  // new app/router.js
  Router.map(function(){
    this.route("admin");
  });
  ```

  @method insertIntoFile
  @param {String} pathRelativeToProjectRoot
  @param {String} contentsToInsert
  @param {Object} options
  @return {Promise}
*/
Blueprint.prototype.insertIntoFile = function(pathRelativeToProjectRoot, contentsToInsert, providedOptions) {
  var fullPath          = path.join(this.project.root, pathRelativeToProjectRoot);
  var originalContents  = '';

  if (existsSync(fullPath)) {
    originalContents = fs.readFileSync(fullPath, { encoding: 'utf8' });
  }

  var contentsToWrite   = originalContents;

  var options           = providedOptions || {};
  var alreadyPresent    = originalContents.indexOf(contentsToInsert) > -1;
  var insert            = !alreadyPresent;
  var insertBehavior    = 'end';

  if (options.before) { insertBehavior = 'before'; }
  if (options.after)  { insertBehavior = 'after'; }

  if (options.force) { insert = true; }

  if (insert) {
    if (insertBehavior === 'end') {
      contentsToWrite += contentsToInsert;
    } else {
      var contentMarker      = options[insertBehavior];
      var contentMarkerIndex = contentsToWrite.indexOf(contentMarker);

      if (contentMarkerIndex !== -1) {
        var insertIndex = contentMarkerIndex;
        if (insertBehavior === 'after') { insertIndex += contentMarker.length; }

        contentsToWrite = contentsToWrite.slice(0, insertIndex) +
                          contentsToInsert + EOL +
                          contentsToWrite.slice(insertIndex);
      }
    }
  }

  var returnValue = {
    path: fullPath,
    originalContents: originalContents,
    contents: contentsToWrite,
    inserted: false
  };

  if (contentsToWrite !== originalContents) {
    returnValue.inserted = true;

    return writeFile(fullPath, contentsToWrite)
      .then(function() {
        return returnValue;
      });
  } else {
    return Promise.resolve(returnValue);
  }
};

Blueprint.prototype.printDetailedHelp = function() {
  var markdownColor = new MarkdownColor();
  var filePath = null;

  if (this.path) {
    filePath = path.join(this.path, './HELP.md');
  }

  if (existsSync(filePath)) {
    return markdownColor.renderFile(filePath, {indent:'        '});
  }
  return '';
};

/**
  Used to retrieve a blueprint with the given name.

  @method lookupBlueprint
  @param dasherizedName
  @public
*/
Blueprint.prototype.lookupBlueprint = function(dasherizedName) {
  var projectPaths = this.project ? this.project.blueprintLookupPaths() : [];

  return Blueprint.lookup(dasherizedName, {
    paths: projectPaths
  });
};

/**
  @static
  @method lookup
  @namespace Blueprint
  @param {String} [name]
  @param {Object} [options]
  @param {Array} [options.paths] Extra paths to search for blueprints
  @param {Object} [options.properties] Properties
  @return {Blueprint}
*/
Blueprint.lookup = function(name, options) {
  options = options || {};

  var lookupPaths = generateLookupPaths(options.paths);

  var lookupPath;
  var blueprintPath;

  for (var i = 0; lookupPath = lookupPaths[i]; i++) {
    blueprintPath = path.resolve(lookupPath, name);

    if (existsSync(blueprintPath)) {
      return Blueprint.load(blueprintPath);
    }
  }

  if (!options.ignoreMissing) {
    throw new SilentError('Unknown blueprint: ' + name);
  }
};

/**
  Loads a blueprint from given path.
  @static
  @method load
  @namespace Blueprint
  @param {String} blueprintPath
  @return {Blueprint} blueprint instance
*/
Blueprint.load = function(blueprintPath) {
  var constructorPath = path.resolve(blueprintPath, 'index.js');
  var blueprintModule;
  var Constructor = Blueprint;

  if (fs.lstatSync(blueprintPath).isDirectory()) {

    if (existsSync(constructorPath)) {
      blueprintModule = require(constructorPath);

      if (typeof blueprintModule === 'function') {
        Constructor = blueprintModule;
      } else {
        Constructor = Blueprint.extend(blueprintModule);
      }
    }

    return new Constructor(blueprintPath);
  }

  return;
};

/**
  @static
  @method list
  @namespace Blueprint
  @param {Object} [options]
  @param {Array} [options.paths] Extra paths to search for blueprints
  @return {Blueprint}
*/
Blueprint.list = function(options) {
  options = options || {};

  var lookupPaths = generateLookupPaths(options.paths);
  var seen = [];

  return lookupPaths.map(function(lookupPath) {
    var blueprints = dir(lookupPath);
    var packagePath = path.join(lookupPath, '../package.json');
    var source;

    if (existsSync(packagePath)) {
      source = require(packagePath).name;
    } else {
      source = path.basename(path.join(lookupPath, '..'));
    }

    blueprints = blueprints.map(function(blueprintPath) {
      var blueprint   = Blueprint.load(blueprintPath);
      var name;

      if (blueprint) {
        name = blueprint.name;
        blueprint.overridden = contains(seen, name);
        seen.push(name);

        return blueprint;
      }

      return;
    });

    return {
      source: source,
      blueprints: compact(blueprints)
    };
  });
};

/**
  @static
  @property renameFiles
*/
Blueprint.renamedFiles = {
  'gitignore': '.gitignore'
};

/**
  @static
  @property ignoredFiles
*/
Blueprint.ignoredFiles = [
  '.DS_Store'
];

/**
  @static
  @property ignoredUpdateFiles
*/
Blueprint.ignoredUpdateFiles = [
  '.gitkeep',
  'app.css'
];

/**
  @static
  @property defaultLookupPaths
*/
Blueprint.defaultLookupPaths = function() {
  return [
    path.resolve(__dirname, '..', '..', 'blueprints')
  ];
};

/**
  @private
  @method prepareConfirm
  @param {FileInfo} info
  @return {Promise}
*/
function prepareConfirm(info) {
  return info.checkForConflict().then(function(resolution) {
    info.resolution = resolution;
    return info;
  });
}

/**
  @private
  @method markIdenticalToBeSkipped
  @param {FileInfo} info
*/
function markIdenticalToBeSkipped(info) {
  if (info.resolution === 'identical') {
    info.action = 'skip';
  }
}

/**
  @private
  @method markToBeRemoved
  @param {FileInfo} info
*/
function markToBeRemoved(info) {
  info.action = 'remove';
}

/**
  @private
  @method gatherConfirmationMessages
  @param {Array} collection
  @param {FileInfo} info
  @return {Array}
*/
function gatherConfirmationMessages(collection, info) {
  if (info.resolution === 'confirm') {
    collection.push(info.confirmOverwriteTask());
  }
  return collection;
}

/**
  @private
  @method isFile
  @param {FileInfo} info
  @return {Boolean}
*/
function isFile(info) {
  return stat(info.inputPath).invoke('isFile');
}

/**
  @private
  @method isIgnored
  @param {FileInfo} info
  @return {Boolean}
*/
function isIgnored(info) {
  var fn = info.inputPath;

  return any(Blueprint.ignoredFiles, function(ignoredFile) {
    return minimatch(fn, ignoredFile, { matchBase: true });
  });
}

/**
  Combines provided lookup paths with defaults and removes
  duplicates.

  @private
  @method generateLookupPaths
  @param {Array} lookupPaths
  @return {Array}
*/
function generateLookupPaths(lookupPaths) {
  lookupPaths = lookupPaths || [];
  lookupPaths = lookupPaths.concat(Blueprint.defaultLookupPaths());
  return uniq(lookupPaths);
}

/**
  Looks for a __path__ token in the files folder. Must be present for
  the blueprint to support pod tokens.

  @private
  @method hasPathToken
  @param {files} files
  @return {Boolean}
*/
function hasPathToken(files) {
  return files.join().match(/__path__/);
}

function inRepoAddonExists(name, root) {
  var addonPath = path.join(root, 'lib', name);
  return existsSync(addonPath);
}

function podDeprecations(config, ui){
  /*
  var podModulePrefix = config.podModulePrefix || '';
  var podPath = podModulePrefix.substr(podModulePrefix.lastIndexOf('/') + 1);
  // Disabled until we are ready to deprecate podModulePrefix
  deprecateUI(ui)('`podModulePrefix` is deprecated and will be removed from future versions of ember-cli.'+
    ' Please move existing pods from \'app/' + podPath + '/\' to \'app/\'.', config.podModulePrefix);
  */
  deprecateUI(ui)('`usePodsByDefault` is no longer supported in \'config/environment.js\','+
    ' use `usePods` in \'.ember-cli\' instead.', config.usePodsByDefault);
}

/**
  @private
  @method destPath
  @param {String} intoDir
  @param {String} file
  @return {String} new path
*/
function destPath(intoDir, file) {
  return path.join(intoDir, file);
}

/**
  @private
  @method isValidFile
  @param {Object} fileInfo
  @return {Promise}
*/
function isValidFile(fileInfo) {
  if (isIgnored(fileInfo)) {
    return Promise.resolve(false);
  } else {
    return isFile(fileInfo);
  }
}

/**
  @private
  @method isFilePath
  @param {Object} fileInfo
  @return {Promise}
*/
function isFilePath(fileInfo) {
  return fs.statSync(fileInfo.inputPath).isFile();
}

/**
 @private

 @method dir
 @returns {Array} list of files in the given directory or and empty array if no directory exists
*/
function dir(fullPath) {
  if (existsSync(fullPath)) {
    return fs.readdirSync(fullPath).map(function(fileName) {
      return path.join(fullPath, fileName);
    });
  } else {
    return [];
  }
}


text:
package org.openspaces.admin.internal.application;

import org.openspaces.admin.application.Application;

public interface InternalApplicationAware {

    void setApplication(Application application);

}


text:
describe RuboCop::Cop::Lint::UselessAccessModifier do
  let(:config) { RuboCop::Config.new }
  subject(:cop) { described_class.new(config) }

  context 'when an access modifier has no effect' do
    let(:source) do
      <<-END.strip_indent
        class SomeClass
          def some_method
            puts 10
          end
          private
          def self.some_method
            puts 10
          end
        end
      END
    end

    it 'registers an offense' do
      inspect_source(cop, source)
      expect(cop.offenses.size).to eq(1)
      expect(cop.offenses.first.message)
        .to eq('Useless `private` access modifier.')
      expect(cop.offenses.first.line).to eq(5)
      expect(cop.highlights).to eq(['private'])
    end
  end

  context 'when an access modifier has no methods' do
    let(:source) do
      <<-END.strip_indent
        class SomeClass
          def some_method
            puts 10
          end
          protected
        end
      END
    end

    it 'registers an offense' do
      inspect_source(cop, source)
      expect(cop.offenses.size).to eq(1)
      expect(cop.offenses.first.message)
        .to eq('Useless `protected` access modifier.')
      expect(cop.offenses.first.line).to eq(5)
      expect(cop.highlights).to eq(['protected'])
    end
  end

  context 'when an access modifier is followed by attr_*' do
    let(:source) do
      <<-END.strip_indent
        class SomeClass
          protected
          attr_accessor :some_property
          public
          attr_reader :another_one
          private
          attr :yet_again, true
          protected
          attr_writer :just_for_good_measure
        end
      END
    end

    it 'does not register an offense' do
      inspect_source(cop, source)
      expect(cop.offenses).to be_empty
    end
  end

  context 'when an access modifier is followed by a ' \
    'class method defined on constant' do
    let(:source) do
      <<-END.strip_indent
        class SomeClass
          protected
          def SomeClass.some_method
          end
        end
      END
    end

    it 'registers an offense' do
      inspect_source(cop, source)
      expect(cop.offenses.size).to eq(1)
      expect(cop.offenses.first.message)
        .to eq('Useless `protected` access modifier.')
      expect(cop.offenses.first.line).to eq(2)
      expect(cop.highlights).to eq(['protected'])
    end
  end

  context 'when there are consecutive access modifiers' do
    let(:source) do
      <<-END.strip_indent
        class SomeClass
         private
         private
          def some_method
            puts 10
          end
          def some_other_method
            puts 10
          end
        end
      END
    end

    it 'registers an offense' do
      inspect_source(cop, source)
      expect(cop.offenses.size).to eq(1)
      expect(cop.offenses.first.message)
        .to eq('Useless `private` access modifier.')
      expect(cop.offenses.first.line).to eq(3)
      expect(cop.highlights).to eq(['private'])
    end
  end

  context 'when passing method as symbol' do
    let(:source) do
      <<-END.strip_indent
        class SomeClass
          def some_method
            puts 10
          end
          private :some_method
        end
      END
    end

    it 'does not register an offense' do
      inspect_source(cop, source)
      expect(cop.offenses).to be_empty
    end
  end

  context 'when class is empty save modifier' do
    let(:source) do
      <<-END.strip_indent
        class SomeClass
          private
        end
      END
    end

    it 'registers an offense' do
      inspect_source(cop, source)
      expect(cop.offenses.size).to eq(1)
      expect(cop.offenses.first.message)
        .to eq('Useless `private` access modifier.')
      expect(cop.offenses.first.line).to eq(2)
      expect(cop.highlights).to eq(['private'])
    end
  end

  context 'when multiple class definitions in file but only one has offense' do
    let(:source) do
      <<-END.strip_indent
        class SomeClass
          private
        end
        class SomeOtherClass
        end
      END
    end

    it 'registers an offense' do
      inspect_source(cop, source)
      expect(cop.offenses.size).to eq(1)
      expect(cop.offenses.first.message)
        .to eq('Useless `private` access modifier.')
      expect(cop.offenses.first.line).to eq(2)
      expect(cop.highlights).to eq(['private'])
    end
  end

  if RUBY_ENGINE == 'ruby' && RUBY_VERSION.start_with?('2.1')
    context 'ruby 2.1 style modifiers' do
      let(:source) do
        <<-END.strip_indent
          class SomeClass
            private def some_method
              puts 10
            end
          end
        END
      end

      it 'does not register an offense' do
        inspect_source(cop, source)
        expect(cop.offenses).to be_empty
      end
    end
  end

  context 'when only a constant or local variable is defined after the ' \
    'modifier' do
    %w[CONSTANT some_var].each do |binding_name|
      let(:source) do
        <<-END.strip_indent
          class SomeClass
            private
            #{binding_name} = 1
          end
        END
      end

      it 'registers an offense' do
        inspect_source(cop, source)
        expect(cop.offenses.size).to eq(1)
      end
    end
  end

  context 'when a def is an argument to a method call' do
    let(:source) do
      <<-END.strip_indent
        class SomeClass
          private
          helper_method def some_method
            puts 10
          end
        end
      END
    end

    it 'does not register an offense' do
      inspect_source(cop, source)
      expect(cop.offenses).to be_empty
    end
  end

  context "when using ActiveSupport's `concerning` method" do
    let(:config) do
      RuboCop::Config.new(
        'Lint/UselessAccessModifier' => {
          'ContextCreatingMethods' => ['concerning']
        }
      )
    end
    it 'is aware that this creates a new scope' do
      src = <<-END.strip_indent
        class SomeClass
          concerning :FirstThing do
            def foo
            end
            private

            def method
            end
          end

          concerning :SecondThing do
            def omg
            end
            private
            def method
            end
          end
         end
      END
      inspect_source(cop, src)
      expect(cop.offenses).to be_empty
    end

    it 'still points out redundant uses within the block' do
      src = <<-END.strip_indent
        class SomeClass
          concerning :FirstThing do
            def foo
            end
            private

            def method
            end
          end

          concerning :SecondThing do
            def omg
            end
            private
            def method
            end
            private
            def another_method
            end
          end
         end
      END
      inspect_source(cop, src)
      expect(cop.offenses.size).to eq(1)
      expect(cop.offenses.first.line).to eq(17)
    end
  end

  context 'when using ActiveSupport behavior when Rails is not eabled' do
    it 'reports offenses' do
      src = <<-END.strip_indent
        module SomeModule
          extend ActiveSupport::Concern
          class_methods do
            def some_public_class_method
            end
            private
            def some_private_class_method
            end
          end
          def some_public_instance_method
          end
          private
          def some_private_instance_method
          end
        end
      END
      inspect_source(cop, src)
      expect(cop.offenses.size).to eq(1)
    end
  end

  context 'when using the class_methods method from ActiveSupport::Concern' do
    let(:config) do
      RuboCop::Config.new(
        'Lint/UselessAccessModifier' => {
          'ContextCreatingMethods' => ['class_methods']
        }
      )
    end
    it 'is aware that this creates a new scope' do
      src = <<-END.strip_indent
        module SomeModule
          extend ActiveSupport::Concern
          class_methods do
            def some_public_class_method
            end
            private
            def some_private_class_method
            end
          end
          def some_public_instance_method
          end
          private
          def some_private_instance_method
          end
        end
      END
      inspect_source(cop, src)
      expect(cop.offenses).to be_empty
    end
  end

  context 'when using a known method-creating method' do
    let(:config) do
      RuboCop::Config.new(
        'Lint/UselessAccessModifier' => {
          'MethodCreatingMethods' => ['delegate']
        }
      )
    end
    it 'is aware that this creates a new method' do
      src = <<-END.strip_indent
        class SomeClass
          private

          delegate :foo, to: :bar
        end
      END
      inspect_source(cop, src)
      expect(cop.offenses).to be_empty
    end

    it 'still points out redundant uses within the module' do
      src = <<-END.strip_indent
        class SomeClass
          delegate :foo, to: :bar

          private
        end
      END
      inspect_source(cop, src)
      expect(cop.offenses.size).to eq(1)
      expect(cop.offenses.first.line).to eq(4)
    end
  end

  shared_examples 'at the top of the body' do |keyword|
    it 'registers an offense for `public`' do
      src = <<-END.strip_indent
        #{keyword} A
          public
          def method
          end
        end
      END
      inspect_source(cop, src)
      expect(cop.offenses.size).to eq(1)
    end

    it "doesn't register an offense for `protected`" do
      src = <<-END.strip_indent
        #{keyword} A
          protected
          def method
          end
        end
      END
      inspect_source(cop, src)
      expect(cop.offenses).to be_empty
    end

    it "doesn't register an offense for `private`" do
      src = <<-END.strip_indent
        #{keyword} A
          private
          def method
          end
        end
      END
      inspect_source(cop, src)
      expect(cop.offenses).to be_empty
    end
  end

  shared_examples 'repeated visibility modifiers' do |keyword, modifier|
    it "registers an offense when `#{modifier}` is repeated" do
      src = <<-END.strip_indent
        #{keyword} A
          #{modifier == 'private' ? 'protected' : 'private'}
          def method1
          end
          #{modifier}
          #{modifier}
          def method2
          end
        end
      END
      inspect_source(cop, src)
      expect(cop.offenses.size).to eq(1)
    end
  end

  shared_examples 'non-repeated visibility modifiers' do |keyword|
    it 'registers an offense even when `public` is not repeated' do
      src = <<-END.strip_indent
        #{keyword} A
          def method1
          end
          public
          def method2
          end
        end
      END
      inspect_source(cop, src)
      expect(cop.offenses.size).to eq(1)
    end

    it "doesn't register an offense when `protected` is not repeated" do
      src = <<-END.strip_indent
        #{keyword} A
          def method1
          end
          protected
          def method2
          end
        end
      END
      inspect_source(cop, src)
      expect(cop.offenses).to be_empty
    end

    it "doesn't register an offense when `private` is not repeated" do
      src = <<-END.strip_indent
        #{keyword} A
          def method1
          end
          private
          def method2
          end
        end
      END
      inspect_source(cop, src)
      expect(cop.offenses).to be_empty
    end
  end

  shared_examples 'at the end of the body' do |keyword, modifier|
    it "registers an offense for trailing `#{modifier}`" do
      src = <<-END.strip_indent
        #{keyword} A
          def method1
          end
          def method2
          end
          #{modifier}
        end
      END
      inspect_source(cop, src)
      expect(cop.offenses.size).to eq(1)
    end
  end

  shared_examples 'nested in a begin..end block' do |keyword, modifier|
    it "still flags repeated `#{modifier}`" do
      src = <<-END.strip_indent
        #{keyword} A
          #{modifier == 'private' ? 'protected' : 'private'}
          def blah
          end
          begin
            def method1
            end
            #{modifier}
            #{modifier}
            def method2
            end
          end
        end
      END
      inspect_source(cop, src)
      expect(cop.offenses.size).to eq(1)
    end

    unless modifier == 'public'
      it "doesn't flag an access modifier from surrounding scope" do
        src = <<-END.strip_indent
          #{keyword} A
            #{modifier}
            begin
              def method1
              end
            end
          end
        END
        inspect_source(cop, src)
        expect(cop.offenses).to be_empty
      end
    end
  end

  shared_examples 'unused visibility modifiers' do |keyword|
    it 'registers an error when visibility is immediately changed ' \
       'without any intervening defs' do
      src = <<-END.strip_indent
        #{keyword} A
          private
          def method1
          end
          public # bad
          private
          def method2
          end
        end
      END
      inspect_source(cop, src)
      expect(cop.offenses.size).to eq(1)
    end
  end

  shared_examples 'access modifiers with argument' do |keyword|
    it "doesn't register an offense" do
      src = <<-END.strip_indent
        #{keyword} A
          def method1
          end
          private :method1
          def method2
          end
          public :method2
        end
      END
      inspect_source(cop, src)
      expect(cop.offenses).to be_empty
    end
  end

  shared_examples 'conditionally defined method' do |keyword, modifier|
    %w[if unless].each do |conditional_type|
      it "doesn't register an offense for #{conditional_type}" do
        src = <<-END.strip_indent
          #{keyword} A
            #{modifier}
            #{conditional_type} x
              def method1
              end
            end
          end
        END
        inspect_source(cop, src)
        expect(cop.offenses).to be_empty
      end
    end
  end

  shared_examples 'methods defined in an iteration' do |keyword, modifier|
    %w[each map].each do |iteration_method|
      it "doesn't register an offense for #{iteration_method}" do
        src = ["#{keyword} A",
               "  #{modifier}",
               "  [1, 2].#{iteration_method} do |i|",
               '    define_method("method#{i}") do',
               '      i',
               '    end',
               '  end',
               'end']
        inspect_source(cop, src)
        expect(cop.offenses).to be_empty
      end
    end
  end

  shared_examples 'method defined with define_method' do |keyword, modifier|
    it "doesn't register an offense if a block is passed" do
      src = <<-END.strip_indent
        #{keyword} A
          #{modifier}
          define_method(:method1) do
          end
        end
      END
      inspect_source(cop, src)
      expect(cop.offenses).to be_empty
    end

    %w[lambda proc ->].each do |proc_type|
      it "doesn't register an offense if a #{proc_type} is passed" do
        src = <<-END.strip_indent
          #{keyword} A
            #{modifier}
            define_method(:method1, #{proc_type} { })
          end
        END
        inspect_source(cop, src)
        expect(cop.offenses).to be_empty
      end
    end
  end

  shared_examples 'method defined on a singleton class' do |keyword, modifier|
    context 'inside a class' do
      it "doesn't register an offense if a method is defined" do
        src = <<-END.strip_indent
          #{keyword} A
            class << self
              #{modifier}
              define_method(:method1) do
              end
            end
          end
        END
        inspect_source(cop, src)
        expect(cop.offenses).to be_empty
      end

      it "doesn't register an offense if the modifier is the same as " \
        'outside the meta-class' do
        src = <<-END.strip_indent
          #{keyword} A
            #{modifier}
            def method1
            end
            class << self
              #{modifier}
              def method2
              end
            end
          end
        END
        inspect_source(cop, src)
        expect(cop.offenses).to be_empty
      end

      it 'registers an offense if no method is defined' do
        src = <<-END.strip_indent
          #{keyword} A
            class << self
              #{modifier}
            end
          end
        END
        inspect_source(cop, src)
        expect(cop.offenses.size).to eq(1)
      end

      it 'registers an offense if no method is defined after the modifier' do
        src = <<-END.strip_indent
          #{keyword} A
            class << self
              def method1
              end
              #{modifier}
            end
          end
        END
        inspect_source(cop, src)
        expect(cop.offenses.size).to eq(1)
      end

      it 'registers an offense even if a non-singleton-class method is ' \
        'defined' do
        src = <<-END.strip_indent
          #{keyword} A
            def method1
            end
            class << self
              #{modifier}
            end
          end
        END
        inspect_source(cop, src)
        expect(cop.offenses.size).to eq(1)
      end
    end

    context 'outside a class' do
      it "doesn't register an offense if a method is defined" do
        src = <<-END.strip_indent
          class << A
            #{modifier}
            define_method(:method1) do
            end
          end
        END
        inspect_source(cop, src)
        expect(cop.offenses).to be_empty
      end

      it 'registers an offense if no method is defined' do
        src = <<-END.strip_indent
          class << A
            #{modifier}
          end
        END
        inspect_source(cop, src)
        expect(cop.offenses.size).to eq(1)
      end

      it 'registers an offense if no method is defined after the modifier' do
        src = <<-END.strip_indent
          class << A
            def method1
            end
            #{modifier}
          end
        END
        inspect_source(cop, src)
        expect(cop.offenses.size).to eq(1)
      end
    end
  end

  shared_examples 'method defined using class_eval' do |modifier|
    it "doesn't register an offense if a method is defined" do
      src = <<-END.strip_indent
        A.class_eval do
          #{modifier}
          define_method(:method1) do
          end
        end
      END
      inspect_source(cop, src)
      expect(cop.offenses).to be_empty
    end

    it 'registers an offense if no method is defined' do
      src = <<-END.strip_indent
        A.class_eval do
          #{modifier}
        end
      END
      inspect_source(cop, src)
      expect(cop.offenses.size).to eq(1)
    end

    context 'inside a class' do
      it 'registers an offense when a modifier is ouside the block and a ' \
        'method is defined only inside the block' do
        src = <<-END.strip_indent
          class A
            #{modifier}
            A.class_eval do
              def method1
              end
            end
          end
        END
        inspect_source(cop, src)
        expect(cop.offenses.size).to eq(1)
      end

      it 'registers two offenses when a modifier is inside and outside the ' \
        ' and no method is defined' do
        src = <<-END.strip_indent
          class A
            #{modifier}
            A.class_eval do
              #{modifier}
            end
          end
        END
        inspect_source(cop, src)
        expect(cop.offenses.size).to eq(2)
      end
    end
  end

  shared_examples 'def in new block' do |klass, modifier|
    it "doesn't register an offense if a method is defined in #{klass}.new" do
      src = <<-END.strip_indent
        #{klass}.new do
          #{modifier}
          def foo
          end
        end
      END
      inspect_source(cop, src)
      expect(cop.offenses).to be_empty
    end

    it "registers an offense if no method is defined in #{klass}.new" do
      src = <<-END.strip_indent
        #{klass}.new do
          #{modifier}
        end
      END
      inspect_source(cop, src)
      expect(cop.offenses.size).to eq(1)
    end
  end

  shared_examples 'method defined using instance_eval' do |modifier|
    it "doesn't register an offense if a method is defined" do
      src = <<-END.strip_indent
        A.instance_eval do
          #{modifier}
          define_method(:method1) do
          end
        end
      END
      inspect_source(cop, src)
      expect(cop.offenses).to be_empty
    end

    it 'registers an offense if no method is defined' do
      src = <<-END.strip_indent
        A.instance_eval do
          #{modifier}
        end
      END
      inspect_source(cop, src)
      expect(cop.offenses.size).to eq(1)
    end

    context 'inside a class' do
      it 'registers an offense when a modifier is ouside the block and a ' \
        'method is defined only inside the block' do
        src = <<-END.strip_indent
          class A
            #{modifier}
            self.instance_eval do
              def method1
              end
            end
          end
        END
        inspect_source(cop, src)
        expect(cop.offenses.size).to eq(1)
      end

      it 'registers two offenses when a modifier is inside and outside the ' \
        ' and no method is defined' do
        src = <<-END.strip_indent
          class A
            #{modifier}
            self.instance_eval do
              #{modifier}
            end
          end
        END
        inspect_source(cop, src)
        expect(cop.offenses.size).to eq(2)
      end
    end
  end

  shared_examples 'nested modules' do |keyword, modifier|
    it "doesn't register an offense for nested #{keyword}s" do
      src = <<-END.strip_indent
        #{keyword} A
          #{modifier}
          def method1
          end
          #{keyword} B
            def method2
            end
            #{modifier}
            def method3
            end
          end
        end
      END
      inspect_source(cop, src)
      expect(cop.offenses).to be_empty
    end

    context 'unused modifiers' do
      it "registers an offense with a nested #{keyword}" do
        src = <<-END.strip_indent
          #{keyword} A
            #{modifier}
            #{keyword} B
              #{modifier}
            end
          end
        END
        inspect_source(cop, src)
        expect(cop.offenses.size).to eq(2)
      end

      it "registers an offense when outside a nested #{keyword}" do
        src = <<-END.strip_indent
          #{keyword} A
            #{modifier}
            #{keyword} B
              def method1
              end
            end
          end
        END
        inspect_source(cop, src)
        expect(cop.offenses.size).to eq(1)
      end

      it "registers an offense when inside a nested #{keyword}" do
        src = <<-END.strip_indent
          #{keyword} A
            #{keyword} B
              #{modifier}
            end
          end
        END
        inspect_source(cop, src)
        expect(cop.offenses.size).to eq(1)
      end
    end
  end

  %w[protected private].each do |modifier|
    it_behaves_like('method defined using class_eval', modifier)
    it_behaves_like('method defined using instance_eval', modifier)
  end

  %w[Class Module Struct].each do |klass|
    %w[protected private].each do |modifier|
      it_behaves_like('def in new block', klass, modifier)
    end
  end

  %w[module class].each do |keyword|
    it_behaves_like('at the top of the body', keyword)
    it_behaves_like('non-repeated visibility modifiers', keyword)
    it_behaves_like('unused visibility modifiers', keyword)

    %w[public protected private].each do |modifier|
      it_behaves_like('repeated visibility modifiers', keyword, modifier)
      it_behaves_like('at the end of the body', keyword, modifier)
      it_behaves_like('nested in a begin..end block', keyword, modifier)

      next if modifier == 'public'

      it_behaves_like('conditionally defined method', keyword, modifier)
      it_behaves_like('methods defined in an iteration', keyword, modifier)
      it_behaves_like('method defined with define_method', keyword, modifier)
      it_behaves_like('method defined on a singleton class', keyword, modifier)
      it_behaves_like('nested modules', keyword, modifier)
    end
  end
end


text:
package main

import "github.com/getcarina/carina/cmd"

func main() {
	cmd.Execute()
}


text:
One Term
========

Distraction free terminal window

configuration
=============

  ::

    cat ~/.onetermrc

    [style]
    font = Monospace
    fontsize = 13
    backgroundcolor=#AAA


text:
namespace Tampleworks.WindowsApplicationBlock.Demo.ApplicationLogic.ReportGeneration
{
    public sealed class ReportGenerationRunningInfo
    {
        public ReportGenerationRunningInfo(
            double? progressValue,
            bool runningInExtendedExecution
        )
        {
            ProgressValue = progressValue;
            RunningInExtendedExecution = runningInExtendedExecution;
        }
        public double? ProgressValue { get; }
        public bool RunningInExtendedExecution { get; }
    }
}


text:
@interface NSObject_JavaObjectTest : XCTestCase
@end

@implementation NSObject_JavaObjectTest

- (void)testResponds {
  XCTAssertTrue([@"tester" respondsToSelector: @selector(compareToWithId:)],
               @"NSObject+Clone category not loaded", nil);
}

- (void)testGetClass {
  // Test with class.
  JavaUtilArrayList *one = [[[JavaUtilArrayList alloc] init] autorelease];
  IOSClass *clazz = [one java_getClass];
  XCTAssertEqualObjects([clazz getName], @"java.util.ArrayList",
                 @"incorrect class name", nil);

  // Now with a protocol.
  id<JavaUtilList> two = [[[JavaUtilArrayList alloc] init] autorelease];
  clazz = [(id<JavaObject>) two java_getClass];
  XCTAssertEqualObjects([clazz getName], @"java.util.ArrayList",
                 @"incorrect class name", nil);
}

@end


text:
package com.galix.lafoska.service;

import java.util.HashMap;
import java.util.Map;

import retrofit.RequestInterceptor;
import retrofit.RestAdapter;
import android.content.Context;
import android.util.Log;
import com.galix.lafoska.LaFoskaApplication;

/**
 * Service REST class
 * @author Jaume
 *
 */
public class ServiceClient {
	private static final String TAG="LaFoska: SerivceClient";
	private static ServiceClient instance;
	public static final String LAFOSKA_BASE_URL="http://lafosca-beach.herokuapp.com/api/v1";
	private RestAdapter mRestAdapter;
	private Map<String, Object> mClients = new HashMap<String, Object>();
	private RestAdapter mRestAuthAdapter;
	private Map<String, Object> mAuthClients = new HashMap<String, Object>();
	private String mBaseUrl = LAFOSKA_BASE_URL;

	private ServiceClient() {
	}

	public static ServiceClient getInstance() {
		if (null == instance) {
			instance = new ServiceClient();
		}
		return instance;
	}

	/**
	 * Client without intercept auth header
	 * @param context
	 * @param clazz
	 * @return
	 */
	@SuppressWarnings("unchecked")
	public <T> T getClient(Context context, Class<T> clazz) {
		Log.v(TAG, "getClient without auth");
		if (mRestAdapter == null) {
			mRestAdapter = new RestAdapter.Builder().setEndpoint(LAFOSKA_BASE_URL).setLogLevel(RestAdapter.LogLevel.FULL).setRequestInterceptor(new RequestInterceptor() {
		        @Override
		        public void intercept(RequestFacade request) {
		            request.addHeader("Accept", "application/json; charset=UTF-8");
		        }
		    }).build();
		}

		T client = null;

		if ((client = (T) mClients.get(clazz.getCanonicalName())) != null) {
			return client;
		}

		client = mRestAdapter.create(clazz);
		mClients.put(clazz.getCanonicalName(), client);
		return client;
	}

	/**
	 * Client with intercept auth header
	 * @param context
	 * @param clazz
	 * @return
	 */
	@SuppressWarnings("unchecked")
	public <T> T getAuthClient(Context context, Class<T> clazz) {
		Log.v(TAG, "getClient with auth");
		if (mRestAuthAdapter == null) {
			mRestAuthAdapter = new RestAdapter.Builder().setEndpoint(LAFOSKA_BASE_URL).setLogLevel(RestAdapter.LogLevel.FULL).setRequestInterceptor(new RequestInterceptor() {
		        @Override
		        public void intercept(RequestFacade request) {
		            request.addHeader("Accept", "application/json; charset=UTF-8");
			            if(LaFoskaApplication.getToken() != null){
			                 request.addHeader("Authorization","Token token=" + LaFoskaApplication.getToken());
			            }

		        }
		    }).build();
		}

		T client = null;

		if ((client = (T) mAuthClients.get(clazz.getCanonicalName())) != null) {
			return client;
		}

		client = mRestAuthAdapter.create(clazz);
		mAuthClients.put(clazz.getCanonicalName(), client);
		return client;
	}

	public void setRestAdapter(RestAdapter restAdapter) {
		mRestAdapter = restAdapter;
	}

	public String getBaseUrl(Context context) {
		return mBaseUrl;
	}
}