text:
//
//  NavigationController.m
//  VKApp
//
//  Created by Semyon Vyatkin on 22/05/16.
//  Copyright © 2016 Semyon-Vyatkin. All rights reserved.
//

#import "NavigationController.h"
#import "AppDelegate.h"
#import "AuthService.h"
#import "UIViewController+ExtensionContoller.h"

@interface NavigationController ()

@end

@implementation NavigationController

- (void)viewDidLoad {
    [super viewDidLoad];
    [self setupAppearance];
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

#pragma mark - AuthMethods
- (IBAction)didTouchedLogout:(UIBarButtonItem *)sender {
    [[AuthService sharedInstance] deauthorizeUser];
}

- (void)didUserLogout:(LogoutStatus)logoutStatus {
    AppDelegate *app = (AppDelegate *) [UIApplication sharedApplication].delegate;
    [app setupRootController];
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end


text:
require 'csv'
require 'active_support/all'

require 'baseball_stats/version'
require 'baseball_stats/data_source'
require 'baseball_stats/calculators'
require 'baseball_stats/reporters'
require 'baseball_stats/ui'

module BaseballStats
  class << self
    def start
      set_data_source('./src/Batting-07-12.csv')
      set_player_key('./src/Master-small.csv')
      menu = UI::PlainTextMenu.new(Reporters.reporters,
                                   UI::Printers::PlainTextPrinter.new,
                                   UI::Input::PlainTextDevice.new)
      menu.prompt
    end

    private
    def set_data_source(filepath)
      BaseballStats::DataSource.set_raw_data(filepath)
    end

    def set_player_key(filepath)
      BaseballStats::DataSource.set_name_key(filepath)
    end
  end
end

redpajama_set_name: RedPajamaGithub


text:
package com.amazonaws.services.ec2.model;

import java.io.Serializable;
import javax.annotation.Generated;

/**
 *

 * Describes a block device mapping.
 *

 *
 * @see AWS API Documentation
 */
@Generated("com.amazonaws:aws-java-sdk-code-generator")
public class LaunchTemplateBlockDeviceMapping implements Serializable, Cloneable {

    /**
     *

     * The device name.
     *

     */
    private String deviceName;
    /**
     *

     * The virtual device name (ephemeralN).
     *

     */
    private String virtualName;
    /**
     *

     * Information about the block device for an EBS volume.
     *

     */
    private LaunchTemplateEbsBlockDevice ebs;
    /**
     *

     * To omit the device from the block device mapping, specify an empty string.
     *

     */
    private String noDevice;

    /**
     *

     * The device name.
     *

     *
     * @param deviceName
     *        The device name.
     */

    public void setDeviceName(String deviceName) {
        this.deviceName = deviceName;
    }

    /**
     *

     * The device name.
     *

     *
     * @return The device name.
     */

    public String getDeviceName() {
        return this.deviceName;
    }

    /**
     *

     * The device name.
     *

     *
     * @param deviceName
     *        The device name.
     * @return Returns a reference to this object so that method calls can be chained together.
     */

    public LaunchTemplateBlockDeviceMapping withDeviceName(String deviceName) {
        setDeviceName(deviceName);
        return this;
    }

    /**
     *

     * The virtual device name (ephemeralN).
     *

     *
     * @param virtualName
     *        The virtual device name (ephemeralN).
     */

    public void setVirtualName(String virtualName) {
        this.virtualName = virtualName;
    }

    /**
     *

     * The virtual device name (ephemeralN).
     *

     *
     * @return The virtual device name (ephemeralN).
     */

    public String getVirtualName() {
        return this.virtualName;
    }

    /**
     *

     * The virtual device name (ephemeralN).
     *

     *
     * @param virtualName
     *        The virtual device name (ephemeralN).
     * @return Returns a reference to this object so that method calls can be chained together.
     */

    public LaunchTemplateBlockDeviceMapping withVirtualName(String virtualName) {
        setVirtualName(virtualName);
        return this;
    }

    /**
     *

     * Information about the block device for an EBS volume.
     *

     *
     * @param ebs
     *        Information about the block device for an EBS volume.
     */

    public void setEbs(LaunchTemplateEbsBlockDevice ebs) {
        this.ebs = ebs;
    }

    /**
     *

     * Information about the block device for an EBS volume.
     *

     *
     * @return Information about the block device for an EBS volume.
     */

    public LaunchTemplateEbsBlockDevice getEbs() {
        return this.ebs;
    }

    /**
     *

     * Information about the block device for an EBS volume.
     *

     *
     * @param ebs
     *        Information about the block device for an EBS volume.
     * @return Returns a reference to this object so that method calls can be chained together.
     */

    public LaunchTemplateBlockDeviceMapping withEbs(LaunchTemplateEbsBlockDevice ebs) {
        setEbs(ebs);
        return this;
    }

    /**
     *

     * To omit the device from the block device mapping, specify an empty string.
     *

     *
     * @param noDevice
     *        To omit the device from the block device mapping, specify an empty string.
     */

    public void setNoDevice(String noDevice) {
        this.noDevice = noDevice;
    }

    /**
     *

     * To omit the device from the block device mapping, specify an empty string.
     *

     *
     * @return To omit the device from the block device mapping, specify an empty string.
     */

    public String getNoDevice() {
        return this.noDevice;
    }

    /**
     *

     * To omit the device from the block device mapping, specify an empty string.
     *

     *
     * @param noDevice
     *        To omit the device from the block device mapping, specify an empty string.
     * @return Returns a reference to this object so that method calls can be chained together.
     */

    public LaunchTemplateBlockDeviceMapping withNoDevice(String noDevice) {
        setNoDevice(noDevice);
        return this;
    }

    /**
     * Returns a string representation of this object. This is useful for testing and debugging. Sensitive data will be
     * redacted from this string using a placeholder value.
     *
     * @return A string representation of this object.
     *
     * @see java.lang.Object#toString()
     */
    @Override
    public String toString() {
        StringBuilder sb = new StringBuilder();
        sb.append("{");
        if (getDeviceName() != null)
            sb.append("DeviceName: ").append(getDeviceName()).append(",");
        if (getVirtualName() != null)
            sb.append("VirtualName: ").append(getVirtualName()).append(",");
        if (getEbs() != null)
            sb.append("Ebs: ").append(getEbs()).append(",");
        if (getNoDevice() != null)
            sb.append("NoDevice: ").append(getNoDevice());
        sb.append("}");
        return sb.toString();
    }

    @Override
    public boolean equals(Object obj) {
        if (this == obj)
            return true;
        if (obj == null)
            return false;

        if (obj instanceof LaunchTemplateBlockDeviceMapping == false)
            return false;
        LaunchTemplateBlockDeviceMapping other = (LaunchTemplateBlockDeviceMapping) obj;
        if (other.getDeviceName() == null ^ this.getDeviceName() == null)
            return false;
        if (other.getDeviceName() != null && other.getDeviceName().equals(this.getDeviceName()) == false)
            return false;
        if (other.getVirtualName() == null ^ this.getVirtualName() == null)
            return false;
        if (other.getVirtualName() != null && other.getVirtualName().equals(this.getVirtualName()) == false)
            return false;
        if (other.getEbs() == null ^ this.getEbs() == null)
            return false;
        if (other.getEbs() != null && other.getEbs().equals(this.getEbs()) == false)
            return false;
        if (other.getNoDevice() == null ^ this.getNoDevice() == null)
            return false;
        if (other.getNoDevice() != null && other.getNoDevice().equals(this.getNoDevice()) == false)
            return false;
        return true;
    }

    @Override
    public int hashCode() {
        final int prime = 31;
        int hashCode = 1;

        hashCode = prime * hashCode + ((getDeviceName() == null) ? 0 : getDeviceName().hashCode());
        hashCode = prime * hashCode + ((getVirtualName() == null) ? 0 : getVirtualName().hashCode());
        hashCode = prime * hashCode + ((getEbs() == null) ? 0 : getEbs().hashCode());
        hashCode = prime * hashCode + ((getNoDevice() == null) ? 0 : getNoDevice().hashCode());
        return hashCode;
    }

    @Override
    public LaunchTemplateBlockDeviceMapping clone() {
        try {
            return (LaunchTemplateBlockDeviceMapping) super.clone();
        } catch (CloneNotSupportedException e) {
            throw new IllegalStateException("Got a CloneNotSupportedException from Object.clone() " + "even though we're Cloneable!", e);
        }
    }

}


text:
package org.apereo.cas.rest.factory;

import org.apereo.cas.authentication.AuthenticationResult;
import org.apereo.cas.authentication.principal.Service;

import lombok.RequiredArgsConstructor;
import lombok.val;
import org.apereo.inspektr.audit.annotation.Audit;
import org.springframework.http.ResponseEntity;

import java.util.Collection;

/**
 * This is {@link CompositeServiceTicketResourceEntityResponseFactory}.
 *
 * @author Misagh Moayyed
 * @since 5.3.0
 */
@RequiredArgsConstructor
public class CompositeServiceTicketResourceEntityResponseFactory implements ServiceTicketResourceEntityResponseFactory {
    private final Collection<ServiceTicketResourceEntityResponseFactory> chain;

    @Audit(
        action = "REST_API_SERVICE_TICKET",
        actionResolverName = "REST_API_SERVICE_TICKET_ACTION_RESOLVER",
        resourceResolverName = "REST_API_SERVICE_TICKET_RESOURCE_RESOLVER")
    @Override
    public ResponseEntity<String> build(final String ticketGrantingTicket, final Service service, final AuthenticationResult authenticationResult) {
        val factory = chain.stream()
            .filter(f -> f.supports(service, authenticationResult))
            .findFirst()
            .orElseThrow(() -> new IllegalArgumentException("Unable to locate a response entity factory to build a service ticket. "
                + "This generally is due to a configuration issue where CAS is unable to recognize the incoming request"));
        return factory.build(ticketGrantingTicket, service, authenticationResult);
    }

    @Override
    public boolean supports(final Service service, final AuthenticationResult authenticationResult) {
        return service != null && authenticationResult != null;
    }

    @Override
    public int getOrder() {
        return Integer.MAX_VALUE;
    }
}


text:
import sys, os, re, codecs, random, string, uuid, io, urllib
import sigil_bs4
import sigil_gumbo_bs4_adapter as gumbo_bs4
from PIL import Image
from io import BytesIO

plugin_name = 'Baka-Img'
plugin_path = ''
text_type = str

def run(bk):
	# get python plugin path
	global plugin_path
	plugin_path = os.path.join(bk._w.plugin_dir, plugin_name)

	for (textID, textHref) in bk.text_iter():
		print('\nProcessing text file: %s' % textHref)

		textContents = bk.readfile(textID) # Read the section into textContents
		if not isinstance(textContents, text_type):	# If the section is not str then sets its type to 'utf-8'
			textContents = text_type(textContents, 'utf-8')

		soup = sigil_bs4.BeautifulSoup(textContents, "xml")

		# TODO: near square image?
		# done in getSvgForImage. not yet backport to baka-epub

		useImgForLandscape = False
		svgSizePercent = 98

		removeMe = []
		for divNode in soup.find_all("div"):
			if divNode.has_attr('class') and "svg_outer" in divNode['class']:
				for imgNode in divNode.find_all(["img", "svg"]):
					if imgNode.name == 'img':
						imgSrc = imgNode['src']
					else:
						imgSrc = imgNode.image['xlink:href']
					if imgSrc.startswith('../'): imgSrc = imgSrc[3:]
					imgID = bk.href_to_id(imgSrc)
					if imgID: # image file exists
						print('Found image: ' + imgSrc)
						if (len(bk.readfile(imgID)) == 0):
							print('Zero-length file. Removing...')
							removeMe.append(divNode)
						else:
							_useImg = useImgForLandscape
							if "svg_yes" in divNode['class']:
								_useImg = False
							_svgSizePercent = svgSizePercent
							if "svg_100" in divNode['class']:
								_svgSizePercent = 100
							svgNode = sigil_bs4.BeautifulSoup(getSvgForImage(bk, imgID, svgSizePercent=_svgSizePercent, useImgForLandscape=_useImg, dontWrapInDiv=True), "xml")
							imgNode.replace_with(svgNode)
					else:
						print('404 error: ' + imgSrc + '. Removing...')
						removeMe.append(divNode)

		for element in removeMe:
			element.decompose()

		textContents = str(soup)
		textContents = '<?xml version="1.0" encoding="utf-8"?>' + re.sub('<\?xml\s.*?\?>', '', textContents)
		bk.writefile(textID, textContents)

	print('Done.')
	return 0

def getSvgForImage(bk, manifestID, svgSizePercent=98, dispWidth=None, dispHeight=None, useImgForLandscape=True, dontWrapInDiv=False):
	from PIL import Image
	from io import BytesIO

	if not manifestID:
		return ''
	href = bk.id_to_href(manifestID)

	if manifestID and href: # id is specified and confirmed to exist
		imgName = urllib.parse.quote(os.path.split(href)[1])

		imgfile = bk.readfile(manifestID)
		imgfile_obj = BytesIO(imgfile)

		try:
			im =  Image.open(imgfile_obj)
			width, height = im.size

			template = '
<svg xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" version="1.1" width="%d%%" height="%d%%" viewBox="0 0 __width__ __height__" preserveAspectRatio="xMidYMid meet"><image width="__width__" height="__height__" xlink:href="__addr__"/></svg>
' % (svgSizePercent, svgSizePercent)
			if (1.0*width > 1.2*height) and useImgForLandscape: # do not wrap landscape images. They actually look better this way
				template = '

'
			if width < 400 and height < 400: # don't stretch small images
				template = '

'
				# use the original display resolution if it's available and is even smaller
				# note that dispWidth and dispHeight might not be pixel
				# don't bother with something like 70%
				if isfloat(dispWidth) and isfloat(dispHeight):
					dispWidth = int(float(dispWidth))
					dispHeight = int(float(dispHeight))
					if dispWidth < width and dispHeight < height:
						template = '

' % (dispWidth, dispHeight)
			imageCode = template.replace('__addr__', '../Images/' + imgName).replace('__width__', str(width)).replace('__height__', str(height))
		except Exception as e:
			print('Error occured when reading image file: ' + str(e))
			template = '

'
			imageCode = template.replace('__addr__', '../Images/' + imgName)

		if dontWrapInDiv:
			return imageCode.replace('
', '').replace('
','')
		else:
			return imageCode
	else:
		return ''

def isfloat(value):
	try:
		float(value)
		return True
	except (ValueError, TypeError):
		return False

def main():
	print ("I reached main when I should not have.\n")
	return -1

if __name__ == "__main__":
	sys.exit(main())


text:
///////////////////////////////////////////////////////////////////////////////
//                   SOFTWARE COPYRIGHT NOTICE AGREEMENT                     //
//       This software and its documentation are copyright (2010) by the     //
//   Broad Institute.  All rights are reserved.  This software is supplied   //
//   without any warranty or guaranteed support whatsoever. The Broad        //
//   Institute is not responsible for its use, misuse, or functionality.     //
///////////////////////////////////////////////////////////////////////////////

#ifndef BLOCK_H
#define BLOCK_H

#include "Alignment.h"
#include "math/Functions.h"
#include "system/System.h"

/*
 * Class block
 *
 * It captures the information of an aligning block from one align: this
 * is a gapless aligning span, identified uniquely by start on read1,
 * start on read2, and length.
 */
class block {

public:

  block( ) :
    len_ ( 0 ), mut_ ( 0 ), begin1_ ( 0 ), begin2_ ( 0 ) { }

  block( int len, int mut, int begin1, int begin2 ) :
    len_ ( len ), mut_ ( mut ), begin1_ ( begin1 ), begin2_ ( begin2 ) { }

  void Set( int len, int mut, int begin1, int begin2 )
    { len_ = len; mut_ = mut; begin1_ = begin1; begin2_ = begin2; }

  void SetLen( int len ) { len_ = len; }

  void SetMut( int mut ) { mut_ = mut; }

  void SetBegin1( int begin1 ) { begin1_ = begin1; }

  void SetBegin2( int begin2 ) { begin2_ = begin2; }

  int Len( ) const { return len_; }

  int Mut( ) const { return mut_; }

  int Begin1( ) const { return begin1_; }

  int Begin2( ) const { return begin2_; }

  int End1( ) const { return begin1_ + len_; }

  int End2( ) const { return begin2_ + len_; }

  friend std::ostream &operator<< ( std::ostream &out, const block &the_block ) {
    out << the_block.len_ << "\t"
	<< the_block.mut_ << "\t"
	<< the_block.begin1_ << "\t"
	<< the_block.begin2_ << "\n";
    return out; }

  friend std::istream &operator>> ( std::istream &in, block &the_block ) {
    int len;
    int mut;
    int begin1;
    int begin2;
    in >> len >> mut >> begin1 >> begin2;
    the_block.Set( len, mut, begin1, begin2 );
    return in; }

private:

  int len_;            // length of block
  int mut_;            // number of mutations in block
  int begin1_;         // begin of block on read1
  int begin2_;         // begin of block on read2

};

/*
 * BlocksOverlap
 *
 * Returns the amount of overlap between blocks. An example: say that
 * read1 and read2 are chimp reads, and that they align the same human
 * chromosme as per blocks left and right. This means that the two
 * intervals on human are I1= [left.begin2_, left.begin2_ + len_], and
 * I2 = [right.begin2_, right.begin2_ + len_]. BlocksOverlap returns
 * the overlap between I1 and I2 with a twist: if either block's
 * mutation rate is too high, then pretend the two do not overlap.
 */
inline int BlocksOverlap( const block &left, const block &right )
{
  const float max_mut_rate = 0.4;
  float left_mut_rate = SafeQuotient( left.Mut( ), left.Len( ) );
  float right_mut_rate = SafeQuotient( right.Mut( ), right.Len( ) );

  if (  left_mut_rate > max_mut_rate || right_mut_rate > max_mut_rate )
    return 0;

  int begin = Max( left.Begin2( ), right.Begin2( ) );
  int end = Min( left.End2( ), right.End2( ) );

  return Max( 0, end - begin );
}

#endif


text:
typedef void (^DXServiceIntentProxyCallBack)(id data);

@interface DXServiceIntentProxy : NSObject

+ (DXServiceIntentProxy *)proxyWithIntent:(DXServiceIntent *)intent;

- (id)initWithIntent:(DXServiceIntent *)intent;

- (void)perform;
- (void)cancel;

- (void)absorbEventWithName:(NSString *)eventName value:(id)eventValue;

- (void)on:(NSString *)eventName notify:(DXServiceIntentProxyCallBack)listener;
- (void)on:(NSString *)eventName notify:(void (^)(id))listener onQueue:(dispatch_queue_t)anQueue;

- (void)onSuccess:(DXServiceIntentProxyCallBack)callback;

- (void)onError:(DXServiceIntentProxyCallBack)callback;

- (void)onCommitResult:(DXServiceIntentProxyCallBack)callback;

@end


text:
/*jslint indent: 2, unparam: true*/
/*global $: false, document: false, togglbutton: false*/
'use strict';

togglbutton.render('#treeitem_panel .details.page:not(.toggl)', {observe: true}, function (elem) {
  var link, description = $('#treeitem_panel_name').innerText,
    projectFunc = function () {
      var text = $("#treeitem_panel_parent").innerText.split(">");
      return text[text.length - 1].trim();
    };

  link = togglbutton.createTimerLink({
    className: 'liquidplanner',
    description: description,
    projectName: projectFunc
  });

  elem.insertBefore(link, elem.firstChild);
});


text:
package us.nineworlds.serenity;

import android.content.Context;
import androidx.localbroadcastmanager.content.LocalBroadcastManager;

import com.birbit.android.jobqueue.JobManager;
import org.mockito.Mock;
import org.mockito.MockitoAnnotations;
import toothpick.config.Module;
import us.nineworlds.serenity.common.rest.SerenityClient;
import us.nineworlds.serenity.core.logger.Logger;
import us.nineworlds.serenity.core.util.AndroidHelper;

public class TestingModule extends Module {

  @Mock JobManager mockJobManager;
  @Mock SerenityClient mockPlexAppFactory;
  @Mock LocalBroadcastManager mockLocalBroadcastManager;
  @Mock Logger mockLogger;
  @Mock Context mockContext;
  @Mock AndroidHelper mockAndroidHelper;

  public TestingModule() {
    MockitoAnnotations.initMocks(this);
    bind(JobManager.class).toInstance(mockJobManager);
    bind(SerenityClient.class).toInstance(mockPlexAppFactory);
    bind(LocalBroadcastManager.class).toInstance(mockLocalBroadcastManager);
    bind(Logger.class).toInstance(mockLogger);
    bind(AndroidHelper.class).toInstance(mockAndroidHelper);
    //bind(Context.class).withName(ApplicationContext.class).toInstance(mockContext);
  }
}


text:
using namespace std;

int main(int argc, const char* argv[]) {

    ios::sync_with_stdio(false);
    string buf;
    while (getline(cin, buf)) {
        vector<int> nums;
        stringstream ss(buf);
        int size, input;

        // seqence size
        ss >> size;

        // get numbers
        while (ss >> input)
            nums.push_back(input);

        // create bitmap
        vector<bool> bitmap;
        bitmap.resize(size, false);
        bitmap[0] = true;

        // fill bitmap
        for (int i = 0; i < size - 1; i++) {
            int diff = abs(nums[i] - nums[i + 1]);

            if(diff <= size - 1)
                bitmap[diff] = true;
        }

        // check bitmap
        string result = find(bitmap.begin(), bitmap.end(), false)
            == bitmap.end() ? "Jolly" : "Not jolly";

        cout << result << endl;
    }
    return 0;
}


text:
package org.encuestame.mvc.view;

import java.util.Map;

import javax.servlet.http.HttpServletRequest;

import org.encuestame.core.rss.AbstractBaseAtomFeedView;
import org.springframework.stereotype.Component;

import com.sun.syndication.feed.atom.Feed;

/**
 * Survey Published Atom Feed View.
 * @author Morales, Diana Paola paolaATencuestame.org
 * @since July 21, 2011
 */
@Component(value="surveyAtomFeedView")
public final class SurveyAtomFeedView extends AbstractBaseAtomFeedView {

    /**
     * Build Feed Meta Data.
     */
    @Override
    protected void buildFeedMetadata(Map<String, Object> model, Feed feed,
            HttpServletRequest request) {
        setAtomTitle(model.get("feedTitle") == null ? "Survey Published " : model.get("feedTitle").toString());
        feed.setId(getAtomTitle());
        feed.setTitle(getAtomTitle());
    }
}


text:
package org.beamforge.extensions.thingiverse.gui;

import org.beamforge.TakePhotoThread;
import org.beamforge.ui.icons.IconLoader;
import org.beamforge.extensions.thingiverse.model.Thing;
import org.beamforge.lang.Language;
import org.beamforge.lang.LanguageConstants;
import org.beamforge.ui.MainView;
import org.beamforge.ui.VisiCutApp;

import javax.swing.*;
import java.awt.*;
import java.awt.event.ItemEvent;
import java.awt.event.ItemListener;
import java.awt.event.WindowEvent;
import java.awt.event.WindowListener;

import static org.beamforge.lang.LanguageKeys.*;

/*
 * This class is an abomination. What the actual fuck, it doesn't actually upload to thingiverse?! So why the fuck is it still here...
 */
public class ThingiverseUploadDialog extends javax.swing.JDialog {

    private static final LanguageConstants CONSTANTS = Language.load();

    private Thread livecamThread; // thread for live preview of the cam
    private Thing thing; // thing to tag as I made one
    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JButton btnPhoto;
    private javax.swing.JButton btnPhotoRedo;
    private javax.swing.JButton btnPublish;
    private javax.swing.JLabel lblLoading;
    private javax.swing.JLabel lblPhoto;
    private javax.swing.JLabel lblPublishSuccessStatus;
    private javax.swing.JLabel lblThingImage;
    private javax.swing.JLabel lblThingName;
    private javax.swing.JRadioButton rdbtnVisicam;
    private javax.swing.JRadioButton rdbtnWebcam;
    private javax.swing.JTextArea txtaPublish;
    /**
     * Creates new form ThingiverseUploadDialog
     */
    public ThingiverseUploadDialog(java.awt.Frame parent, boolean modal, Thing thing) {
        super(parent, modal);

        // auto generated code
        initComponents();

        this.thing = thing;

        // no need to keep state
        this.setDefaultCloseOperation(JDialog.DISPOSE_ON_CLOSE);

        // close camera on exit
        initWindowListener();

        // display thing
        // scale image to label size
        Image rawImage = this.thing.getImage().getImage();
        Image scaledImage = rawImage.getScaledInstance(
                lblThingImage.getWidth(),
                lblThingImage.getHeight(),
                Image.SCALE_SMOOTH);
        lblThingImage.setIcon(this.thing.getImage());
        lblThingName.setText(thing.getName());
        setTitle(String.format(CONSTANTS.get(THINGIVERSE_MADE), thing.getName()));

        // change cam source listener
        ItemListener selectChangeListener = e -> {
            boolean selected = (e.getStateChange() == ItemEvent.SELECTED);
            if (selected) { // only if selected, otherwise fired twice, for the deselected also
                closeCamera();
                setupCamera();
            }

        };
        rdbtnWebcam.addItemListener(selectChangeListener);
        rdbtnVisicam.addItemListener(selectChangeListener);

        // enable picture taking
        setupCamera();
    }

    /**
     * This method is called from within the constructor to
     * initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is
     * always regenerated by the Form Editor.
     */
    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {

        ButtonGroup grpCams = new ButtonGroup();
        JPanel pnlPhoto = new JPanel();
        btnPhoto = new javax.swing.JButton();
        btnPhotoRedo = new javax.swing.JButton();
        lblPhoto = new javax.swing.JLabel();
        btnPublish = new javax.swing.JButton();
        lblLoading = new javax.swing.JLabel();
        JLabel lblDescription = new JLabel();
        lblPublishSuccessStatus = new javax.swing.JLabel();
        JScrollPane jScrollPane1 = new JScrollPane();
        txtaPublish = new javax.swing.JTextArea();
        JPanel pnlSelectCamera = new JPanel();
        rdbtnWebcam = new javax.swing.JRadioButton();
        rdbtnVisicam = new javax.swing.JRadioButton();
        lblThingImage = new javax.swing.JLabel();
        lblThingName = new javax.swing.JLabel();

        setDefaultCloseOperation(javax.swing.WindowConstants.DISPOSE_ON_CLOSE);
        org.jdesktop.application.ResourceMap resourceMap = org.jdesktop.application.Application.getInstance(VisiCutApp.class).getContext().getResourceMap(ThingiverseUploadDialog.class);
        setTitle(resourceMap.getString("Form.title")); // NOI18N
        setLocationByPlatform(true);
        setName("Form"); // NOI18N
        setResizable(false);

        pnlPhoto.setBorder(javax.swing.BorderFactory.createLineBorder(resourceMap.getColor("pnlPhoto.border.lineColor"))); // NOI18N
        pnlPhoto.setName("pnlPhoto"); // NOI18N

        btnPhoto.setText(resourceMap.getString("btnPhoto.text")); // NOI18N
        btnPhoto.setName("btnPhoto"); // NOI18N
        btnPhoto.addActionListener(evt -> btnPhotoActionPerformed(evt));

        btnPhotoRedo.setText(resourceMap.getString("btnPhotoRedo.text")); // NOI18N
        btnPhotoRedo.setName("btnPhotoRedo"); // NOI18N
        btnPhotoRedo.addActionListener(evt -> btnPhotoRedoActionPerformed(evt));

        lblPhoto.setHorizontalAlignment(javax.swing.SwingConstants.CENTER);
        lblPhoto.setText(resourceMap.getString("lblPhoto.text")); // NOI18N
        lblPhoto.setBorder(javax.swing.BorderFactory.createLineBorder(resourceMap.getColor("lblPhoto.border.lineColor"))); // NOI18N
        lblPhoto.setName("lblPhoto"); // NOI18N

        btnPublish.setText(resourceMap.getString("btnPublish.text")); // NOI18N
        btnPublish.setName("btnPublish"); // NOI18N
        btnPublish.addActionListener(evt -> btnPublishActionPerformed(evt));

        lblLoading.setIcon(IconLoader.loadIcon(IconLoader.ICON_LOADING_CIRCLE_SMALL));
        lblLoading.setText(resourceMap.getString("lblLoading.text")); // NOI18N
        lblLoading.setName("lblLoading"); // NOI18N

        lblDescription.setText(resourceMap.getString("lblDescription.text")); // NOI18N
        lblDescription.setName("lblDescription"); // NOI18N

        lblPublishSuccessStatus.setText(resourceMap.getString("lblPublishSuccessStatus.text")); // NOI18N
        lblPublishSuccessStatus.setName("lblPublishSuccessStatus"); // NOI18N

        jScrollPane1.setBorder(javax.swing.BorderFactory.createLineBorder(resourceMap.getColor("jScrollPane1.border.lineColor"))); // NOI18N
        jScrollPane1.setName("jScrollPane1"); // NOI18N

        txtaPublish.setColumns(20);
        txtaPublish.setRows(5);
        txtaPublish.setName("txtaPublish"); // NOI18N
        jScrollPane1.setViewportView(txtaPublish);

        javax.swing.GroupLayout pnlPhotoLayout = new javax.swing.GroupLayout(pnlPhoto);
        pnlPhoto.setLayout(pnlPhotoLayout);
        pnlPhotoLayout.setHorizontalGroup(
                pnlPhotoLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                        .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, pnlPhotoLayout.createSequentialGroup()
                                .addContainerGap()
                                .addGroup(pnlPhotoLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                                        .addGroup(pnlPhotoLayout.createSequentialGroup()
                                                .addComponent(btnPhoto)
                                                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                                                .addComponent(btnPhotoRedo))
                                        .addComponent(lblPhoto, javax.swing.GroupLayout.PREFERRED_SIZE, 316, javax.swing.GroupLayout.PREFERRED_SIZE))
                                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                                .addGroup(pnlPhotoLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING)
                                        .addGroup(pnlPhotoLayout.createSequentialGroup()
                                                .addComponent(lblDescription)
                                                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                                                .addComponent(lblPublishSuccessStatus, javax.swing.GroupLayout.PREFERRED_SIZE, 93, javax.swing.GroupLayout.PREFERRED_SIZE)
                                                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, 67, Short.MAX_VALUE)
                                                .addComponent(lblLoading, javax.swing.GroupLayout.PREFERRED_SIZE, 16, javax.swing.GroupLayout.PREFERRED_SIZE)
                                                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                                                .addComponent(btnPublish))
                                        .addComponent(jScrollPane1, javax.swing.GroupLayout.DEFAULT_SIZE, 318, Short.MAX_VALUE))
                                .addContainerGap())
        );
        pnlPhotoLayout.setVerticalGroup(
                pnlPhotoLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                        .addGroup(pnlPhotoLayout.createSequentialGroup()
                                .addContainerGap()
                                .addGroup(pnlPhotoLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                                        .addComponent(btnPhoto)
                                        .addComponent(btnPhotoRedo)
                                        .addComponent(btnPublish)
                                        .addComponent(lblLoading, javax.swing.GroupLayout.PREFERRED_SIZE, 16, javax.swing.GroupLayout.PREFERRED_SIZE)
                                        .addComponent(lblDescription)
                                        .addComponent(lblPublishSuccessStatus))
                                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                                .addGroup(pnlPhotoLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                                        .addComponent(jScrollPane1, javax.swing.GroupLayout.DEFAULT_SIZE, 219, Short.MAX_VALUE)
                                        .addComponent(lblPhoto, javax.swing.GroupLayout.PREFERRED_SIZE, 219, javax.swing.GroupLayout.PREFERRED_SIZE))
                                .addContainerGap())
        );

        pnlSelectCamera.setBorder(javax.swing.BorderFactory.createTitledBorder(resourceMap.getString("pnlSelectCamera.border.title"))); // NOI18N
        pnlSelectCamera.setName("pnlSelectCamera"); // NOI18N
        pnlSelectCamera.setLayout(new java.awt.GridLayout(2, 1));

        grpCams.add(rdbtnWebcam);
        rdbtnWebcam.setSelected(true);
        rdbtnWebcam.setText(resourceMap.getString("rdbtnWebcam.text")); // NOI18N
        rdbtnWebcam.setName("rdbtnWebcam"); // NOI18N
        pnlSelectCamera.add(rdbtnWebcam);

        grpCams.add(rdbtnVisicam);
        rdbtnVisicam.setText(resourceMap.getString("rdbtnVisicam.text")); // NOI18N
        rdbtnVisicam.setName("rdbtnVisicam"); // NOI18N
        pnlSelectCamera.add(rdbtnVisicam);

        lblThingImage.setText(resourceMap.getString("lblThingImage.text")); // NOI18N
        lblThingImage.setName("lblThingImage"); // NOI18N

        lblThingName.setFont(resourceMap.getFont("lblThingName.font")); // NOI18N
        lblThingName.setText(resourceMap.getString("lblThingName.text")); // NOI18N
        lblThingName.setVerticalAlignment(javax.swing.SwingConstants.TOP);
        lblThingName.setName("lblThingName"); // NOI18N

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
        getContentPane().setLayout(layout);
        layout.setHorizontalGroup(
                layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                        .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
                                .addContainerGap()
                                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING)
                                        .addComponent(pnlPhoto, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                                        .addGroup(layout.createSequentialGroup()
                                                .addComponent(lblThingImage, javax.swing.GroupLayout.PREFERRED_SIZE, 64, javax.swing.GroupLayout.PREFERRED_SIZE)
                                                .addGap(18, 18, 18)
                                                .addComponent(lblThingName, javax.swing.GroupLayout.PREFERRED_SIZE, 442, javax.swing.GroupLayout.PREFERRED_SIZE)
                                                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, 61, Short.MAX_VALUE)
                                                .addComponent(pnlSelectCamera, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)))
                                .addContainerGap())
        );
        layout.setVerticalGroup(
                layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                        .addGroup(layout.createSequentialGroup()
                                .addGap(11, 11, 11)
                                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                                        .addComponent(pnlSelectCamera, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                                        .addComponent(lblThingImage, javax.swing.GroupLayout.PREFERRED_SIZE, 64, javax.swing.GroupLayout.PREFERRED_SIZE)
                                        .addComponent(lblThingName, javax.swing.GroupLayout.PREFERRED_SIZE, 69, javax.swing.GroupLayout.PREFERRED_SIZE))
                                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                                .addComponent(pnlPhoto, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                                .addContainerGap())
        );

        pack();
    }// </editor-fold>//GEN-END:initComponents

    private void btnPublishActionPerformed(java.awt.event.ActionEvent evt)
    {

        // disable controls for publishing, enable feedback
        SwingUtilities.invokeLater(() -> {
            lblLoading.setVisible(true);
            btnPhotoRedo.setEnabled(false);
            btnPublish.setEnabled(false);
            txtaPublish.setEditable(false);
            txtaPublish.setBackground(Color.lightGray);
        });

        // things to publish
        //ImageIcon icon = (ImageIcon)lblPhoto.getIcon();
        //final Image image = icon.getImage();
        // final String message = txtaPublish.getText();

        // do publishing
        new Thread(() -> {
            // TODO: What the actual fuck, guys. WTF.
            // fake processing !!! to be changed later
            try {
                Thread.currentThread().sleep(2000);
            } catch (InterruptedException ex) {

            }

            // create user feedback message
            boolean success = true; // WTF
            String msg;
            if (success) {
                msg = "Successful upload";
            } else {
                msg = "Error uploading photo";
            }

            // display success state
            final String message = msg;
            SwingUtilities.invokeLater(() -> {
                // enable upload dialog feedback
                lblPublishSuccessStatus.setText(message);
                lblPublishSuccessStatus.setVisible(true);
                btnPhotoRedo.setEnabled(true);
                lblLoading.setVisible(false);

                MainView.getInstance().getDialog().showSuccessMessage("Sucessfully published \"" + thing.getName() + "\" as I made one."); // main view feedback
                dispose(); // close on success
            });

        }).start();
    }

    private void btnPhotoRedoActionPerformed(java.awt.event.ActionEvent evt)
    {
        setupCamera(); // set up a clean camera to try again
    }

    private void btnPhotoActionPerformed(java.awt.event.ActionEvent evt)
    {
        closeCamera();

        // enable publishing
        btnPhoto.setEnabled(false);
        btnPhotoRedo.setEnabled(true);
        btnPublish.setEnabled(true);

    }

    // close camera on window close
    private void initWindowListener() {
        this.addWindowListener(new WindowListener() {

            public void windowOpened(WindowEvent e) {

            }

            public void windowClosing(WindowEvent e) {
                closeCamera();
            }

            public void windowClosed(WindowEvent e) {

            }

            public void windowIconified(WindowEvent e) {

            }

            public void windowDeiconified(WindowEvent e) {

            }

            public void windowActivated(WindowEvent e) {

            }

            public void windowDeactivated(WindowEvent e) {

            }
        });
    }
    // End of variables declaration//GEN-END:variables

  /*
   * Camera functions
   */

    /*
       * Function starts the live preview thread depending on the selected source or displays error message.
       * This function ensures that the correct UI elements are enabled for the corresponding state (Disable publishing functionality at startup).
       */
    private void setupCamera() {
        // disable publish functions
        lblPhoto.setIcon(null);
        lblLoading.setVisible(false);
        lblPublishSuccessStatus.setVisible(false);
        btnPhotoRedo.setEnabled(false);
        btnPublish.setEnabled(false);

        // check selected cam mode and if corresponding hardware is available
        boolean start = false;
        if (rdbtnWebcam.isSelected()) {
            if (TakePhotoThread.isWebCamDetected()) {
                start = true;
            }
        } else {// visicam
            if (TakePhotoThread.isVisiCamDetected()) {
                start = true;
            }
        }

        if (start) { // everything was correct, start preview thread
            // start picture taking thread to display live preview
            boolean webcamMode = rdbtnWebcam.isSelected(); // if false, then visicam
            livecamThread = new TakePhotoThread(lblPhoto, webcamMode, TakePhotoThread.PHOTO_RESOLUTION_HIGH);
            livecamThread.start();

            btnPhoto.setEnabled(true);
        } else { // no correct set up found, enable error message
            // disable taking photos
            btnPhoto.setEnabled(false);
            lblPhoto.setText("Please attach webcam");
        }
    }

    // just interrupt live preview, closing camera is handled by thread itself.
    private void closeCamera() {
        if (livecamThread != null) {
            livecamThread.interrupt(); // stop live stream thread
            livecamThread = null;
        }
    }

}


text:
<?php

namespace SibSet\Cache\Adapter;

use SibSet\Cache\Exception\EnvironmentException;

class XcacheAdapter implements AdapterInterface
{
    public function __construct()
    {
        if (!extension_loaded('xcache')) {
            throw new EnvironmentException('XCache extension not loaded');
        }
    }

    /**
     * @inheritdoc
     */
    public function get($key)
    {
        return xcache_get($key);
    }

    /**
     * @inheritdoc
     */
    public function set($key, $value)
    {
        xcache_set($key, $value);
    }

    /**
     * @inheritdoc
     */
    public function setExpired($key, $value, $ttl)
    {
        xcache_set($key, $value, $ttl);
    }

    /**
     * @inheritdoc
     */
    public function remove($key)
    {
        xcache_unset($key);
    }

    /**
     * @inheritdoc
     */
    public function exists($key)
    {
        return xcache_isset($key);
    }
}


text:
import {RouteSegment, Tree, RouteTree} from './segments';

/**
 * Defines route lifecycle method `routerOnActivate`, which is called by the router at the end of a
 * successful route navigation.
 *
 * The `routerOnActivate` hook is called with the current and previous {@link RouteSegment}s of the
 * component and with the corresponding route trees.
 */
export interface OnActivate {
  routerOnActivate(curr: RouteSegment, prev?: RouteSegment, currTree?: RouteTree,
                   prevTree?: RouteTree): void;
}

/**
 * Defines route lifecycle method `routerOnDeactivate`, which is called by the router before
 * destroying a component as part of a route change.
 *
 * The `routerOnDeactivate` hook is called with two {@link RouteTree}s, representing the current
 * and the future state of the application.
 *
 * `routerOnDeactivate` must return a promise. The route change will wait until the promise settles.
 */
export interface CanDeactivate {
  routerCanDeactivate(currTree?: RouteTree, futureTree?: RouteTree): Promise<boolean>;
}


text:
/**
 * @fileoverview Config initialization wizard.
 * @author Ilya Volodin
 */

"use strict";

//------------------------------------------------------------------------------
// Requirements
//------------------------------------------------------------------------------

const util = require("util"),
    inquirer = require("inquirer"),
    ProgressBar = require("progress"),
    autoconfig = require("./autoconfig.js"),
    ConfigFile = require("./config-file"),
    ConfigOps = require("./config-ops"),
    getSourceCodeOfFiles = require("../util/source-code-util").getSourceCodeOfFiles,
    npmUtil = require("../util/npm-util"),
    recConfig = require("../../conf/eslint.json"),
    log = require("../logging");

const debug = require("debug")("eslint:config-initializer");

//------------------------------------------------------------------------------
// Private
//------------------------------------------------------------------------------

/* istanbul ignore next: hard to test fs function */
/**
 * Create .eslintrc file in the current working directory
 * @param {Object} config object that contains user's answers
 * @param {string} format The file format to write to.
 * @returns {void}
 */
function writeFile(config, format) {

    // default is .js
    let extname = ".js";

    if (format === "YAML") {
        extname = ".yml";
    } else if (format === "JSON") {
        extname = ".json";
    }

    ConfigFile.write(config, "./.eslintrc" + extname);
    log.info("Successfully created .eslintrc" + extname + " file in " + process.cwd());

    if (config.installedESLint) {
        log.info("ESLint was installed locally. We recommend using this local copy instead of your globally-installed copy.");
    }
}

/**
 * Synchronously install necessary plugins, configs, parsers, etc. based on the config
 * @param   {Object} config  config object
 * @returns {void}
 */
function installModules(config) {
    let modules = [];

    // Create a list of modules which should be installed based on config
    if (config.plugins) {
        modules = modules.concat(config.plugins.map(function(name) {
            return "eslint-plugin-" + name;
        }));
    }
    if (config.extends && config.extends.indexOf("eslint:") === -1) {
        modules.push("eslint-config-" + config.extends);
    }

    // Determine which modules are already installed
    if (modules.length === 0) {
        return;
    }

    // Add eslint to list in case user does not have it installed locally
    modules.unshift("eslint");

    const installStatus = npmUtil.checkDevDeps(modules);

    // Install packages which aren't already installed
    const modulesToInstall = Object.keys(installStatus).filter(function(module) {
        const notInstalled = installStatus[module] === false;

        if (module === "eslint" && notInstalled) {
            log.info("Local ESLint installation not found.");
            config.installedESLint = true;
        }

        return notInstalled;
    });

    if (modulesToInstall.length > 0) {
        log.info("Installing " + modulesToInstall.join(", "));
        npmUtil.installSyncSaveDev(modulesToInstall);
    }
}

/**
 * Set the `rules` of a config by examining a user's source code
 *
 * Note: This clones the config object and returns a new config to avoid mutating
 * the original config parameter.
 *
 * @param   {Object} answers  answers received from inquirer
 * @param   {Object} config   config object
 * @returns {Object}          config object with configured rules
 */
function configureRules(answers, config) {
    const BAR_TOTAL = 20,
        BAR_SOURCE_CODE_TOTAL = 4,
        newConfig = Object.assign({}, config),
        disabledConfigs = {};
    let sourceCodes,
        registry;

    // Set up a progress bar, as this process can take a long time
    const bar = new ProgressBar("Determining Config: :percent [:bar] :elapseds elapsed, eta :etas ", {
        width: 30,
        total: BAR_TOTAL
    });

    bar.tick(0); // Shows the progress bar

    // Get the SourceCode of all chosen files
    const patterns = answers.patterns.split(/[\s]+/);

    try {
        sourceCodes = getSourceCodeOfFiles(patterns, { baseConfig: newConfig, useEslintrc: false }, function(total) {
            bar.tick((BAR_SOURCE_CODE_TOTAL / total));
        });
    } catch (e) {
        log.info("\n");
        throw e;
    }
    const fileQty = Object.keys(sourceCodes).length;

    if (fileQty === 0) {
        log.info("\n");
        throw new Error("Automatic Configuration failed.  No files were able to be parsed.");
    }

    // Create a registry of rule configs
    registry = new autoconfig.Registry();
    registry.populateFromCoreRules();

    // Lint all files with each rule config in the registry
    registry = registry.lintSourceCode(sourceCodes, newConfig, function(total) {
        bar.tick((BAR_TOTAL - BAR_SOURCE_CODE_TOTAL) / total); // Subtract out ticks used at beginning
    });
    debug("\nRegistry: " + util.inspect(registry.rules, {depth: null}));

    // Create a list of recommended rules, because we don't want to disable them
    const recRules = Object.keys(recConfig.rules).filter(function(ruleId) {
        return ConfigOps.isErrorSeverity(recConfig.rules[ruleId]);
    });

    // Find and disable rules which had no error-free configuration
    const failingRegistry = registry.getFailingRulesRegistry();

    Object.keys(failingRegistry.rules).forEach(function(ruleId) {

        // If the rule is recommended, set it to error, otherwise disable it
        disabledConfigs[ruleId] = (recRules.indexOf(ruleId) !== -1) ? 2 : 0;
    });

    // Now that we know which rules to disable, strip out configs with errors
    registry = registry.stripFailingConfigs();

    // If there is only one config that results in no errors for a rule, we should use it.
    // createConfig will only add rules that have one configuration in the registry.
    const singleConfigs = registry.createConfig().rules;

    // The "sweet spot" for number of options in a config seems to be two (severity plus one option).
    // Very often, a third option (usually an object) is available to address
    // edge cases, exceptions, or unique situations. We will prefer to use a config with
    // specificity of two.
    const specTwoConfigs = registry.filterBySpecificity(2).createConfig().rules;

    // Maybe a specific combination using all three options works
    const specThreeConfigs = registry.filterBySpecificity(3).createConfig().rules;

    // If all else fails, try to use the default (severity only)
    const defaultConfigs = registry.filterBySpecificity(1).createConfig().rules;

    // Combine configs in reverse priority order (later take precedence)
    newConfig.rules = Object.assign({}, disabledConfigs, defaultConfigs, specThreeConfigs, specTwoConfigs, singleConfigs);

    // Make sure progress bar has finished (floating point rounding)
    bar.update(BAR_TOTAL);

    // Log out some stats to let the user know what happened
    const finalRuleIds = Object.keys(newConfig.rules);
    const totalRules = finalRuleIds.length;
    const enabledRules = finalRuleIds.filter(function(ruleId) {
        return (newConfig.rules[ruleId] !== 0);
    }).length;
    const resultMessage = [
        "\nEnabled " + enabledRules + " out of " + totalRules,
        "rules based on " + fileQty,
        "file" + ((fileQty === 1) ? "." : "s.")
    ].join(" ");

    log.info(resultMessage);

    ConfigOps.normalizeToStrings(newConfig);
    return newConfig;
}

/**
 * process user's answers and create config object
 * @param {Object} answers answers received from inquirer
 * @returns {Object} config object
 */
function processAnswers(answers) {
    let config = {rules: {}, env: {}};

    if (answers.es6) {
        config.env.es6 = true;
        if (answers.modules) {
            config.parserOptions = config.parserOptions || {};
            config.parserOptions.sourceType = "module";
        }
    }
    if (answers.commonjs) {
        config.env.commonjs = true;
    }
    answers.env.forEach(function(env) {
        config.env[env] = true;
    });
    if (answers.jsx) {
        config.parserOptions = config.parserOptions || {};
        config.parserOptions.ecmaFeatures = config.parserOptions.ecmaFeatures || {};
        config.parserOptions.ecmaFeatures.jsx = true;
        if (answers.react) {
            config.plugins = ["react"];
            config.parserOptions.ecmaFeatures.experimentalObjectRestSpread = true;
        }
    }

    if (answers.source === "prompt") {
        config.extends = "eslint:recommended";
        config.rules.indent = ["error", answers.indent];
        config.rules.quotes = ["error", answers.quotes];
        config.rules["linebreak-style"] = ["error", answers.linebreak];
        config.rules.semi = ["error", answers.semi ? "always" : "never"];
    }

    installModules(config);

    if (answers.source === "auto") {
        config = configureRules(answers, config);
        config = autoconfig.extendFromRecommended(config);
    }

    ConfigOps.normalizeToStrings(config);
    return config;
}

/**
 * process user's style guide of choice and return an appropriate config object.
 * @param {string} guide name of the chosen style guide
 * @returns {Object} config object
 */
function getConfigForStyleGuide(guide) {
    const guides = {
        google: {extends: "google"},
        airbnb: {extends: "airbnb", plugins: ["react", "jsx-a11y", "import"]},
        standard: {extends: "standard", plugins: ["standard", "promise"]}
    };

    if (!guides[guide]) {
        throw new Error("You referenced an unsupported guide.");
    }

    installModules(guides[guide]);

    return guides[guide];
}

/* istanbul ignore next: no need to test inquirer*/
/**
 * Ask use a few questions on command prompt
 * @param {Function} callback callback function when file has been written
 * @returns {void}
 */
function promptUser(callback) {
    let config;

    inquirer.prompt([
        {
            type: "list",
            name: "source",
            message: "How would you like to configure ESLint?",
            default: "prompt",
            choices: [
                {name: "Answer questions about your style", value: "prompt"},
                {name: "Use a popular style guide", value: "guide"},
                {name: "Inspect your JavaScript file(s)", value: "auto"}
            ]
        },
        {
            type: "list",
            name: "styleguide",
            message: "Which style guide do you want to follow?",
            choices: [{name: "Google", value: "google"}, {name: "AirBnB", value: "airbnb"}, {name: "Standard", value: "standard"}],
            when: function(answers) {
                answers.packageJsonExists = npmUtil.checkPackageJson();
                return answers.source === "guide" && answers.packageJsonExists;
            }
        },
        {
            type: "input",
            name: "patterns",
            message: "Which file(s), path(s), or glob(s) should be examined?",
            when: function(answers) {
                return (answers.source === "auto");
            },
            validate: function(input) {
                if (input.trim().length === 0 && input.trim() !== ",") {
                    return "You must tell us what code to examine. Try again.";
                }
                return true;
            }
        },
        {
            type: "list",
            name: "format",
            message: "What format do you want your config file to be in?",
            default: "JavaScript",
            choices: ["JavaScript", "YAML", "JSON"],
            when: function(answers) {
                return ((answers.source === "guide" && answers.packageJsonExists) || answers.source === "auto");
            }
        }
    ], function(earlyAnswers) {

        // early exit if you are using a style guide
        if (earlyAnswers.source === "guide") {
            if (!earlyAnswers.packageJsonExists) {
                log.info("A package.json is necessary to install plugins such as style guides. Run `npm init` to create a package.json file and try again.");
                return;
            }

            try {
                config = getConfigForStyleGuide(earlyAnswers.styleguide);
                writeFile(config, earlyAnswers.format);
            } catch (err) {
                callback(err);
                return;
            }
            return;
        }

        // continue with the questions otherwise...
        inquirer.prompt([
            {
                type: "confirm",
                name: "es6",
                message: "Are you using ECMAScript 6 features?",
                default: false
            },
            {
                type: "confirm",
                name: "modules",
                message: "Are you using ES6 modules?",
                default: false,
                when: function(answers) {
                    return answers.es6 === true;
                }
            },
            {
                type: "checkbox",
                name: "env",
                message: "Where will your code run?",
                default: ["browser"],
                choices: [{name: "Browser", value: "browser"}, {name: "Node", value: "node"}]
            },
            {
                type: "confirm",
                name: "commonjs",
                message: "Do you use CommonJS?",
                default: false,
                when: function(answers) {
                    return answers.env.some(function(env) {
                        return env === "browser";
                    });
                }
            },
            {
                type: "confirm",
                name: "jsx",
                message: "Do you use JSX?",
                default: false
            },
            {
                type: "confirm",
                name: "react",
                message: "Do you use React",
                default: false,
                when: function(answers) {
                    return answers.jsx;
                }
            }
        ], function(secondAnswers) {

            // early exit if you are using automatic style generation
            if (earlyAnswers.source === "auto") {
                try {
                    const combinedAnswers = Object.assign({}, earlyAnswers, secondAnswers);

                    config = processAnswers(combinedAnswers);
                    installModules(config);
                    writeFile(config, earlyAnswers.format);
                } catch (err) {
                    callback(err);
                    return;
                }
                return;
            }

            // continue with the style questions otherwise...
            inquirer.prompt([
                {
                    type: "list",
                    name: "indent",
                    message: "What style of indentation do you use?",
                    default: "tab",
                    choices: [{name: "Tabs", value: "tab"}, {name: "Spaces", value: 4}]
                },
                {
                    type: "list",
                    name: "quotes",
                    message: "What quotes do you use for strings?",
                    default: "double",
                    choices: [{name: "Double", value: "double"}, {name: "Single", value: "single"}]
                },
                {
                    type: "list",
                    name: "linebreak",
                    message: "What line endings do you use?",
                    default: "unix",
                    choices: [{name: "Unix", value: "unix"}, {name: "Windows", value: "windows"}]
                },
                {
                    type: "confirm",
                    name: "semi",
                    message: "Do you require semicolons?",
                    default: true
                },
                {
                    type: "list",
                    name: "format",
                    message: "What format do you want your config file to be in?",
                    default: "JavaScript",
                    choices: ["JavaScript", "YAML", "JSON"]
                }
            ], function(answers) {
                try {
                    const totalAnswers = Object.assign({}, earlyAnswers, secondAnswers, answers);

                    config = processAnswers(totalAnswers);
                    installModules(config);
                    writeFile(config, answers.format);
                } catch (err) {
                    callback(err);
                    return;
                }
                return;
            });
        });
    });
}

//------------------------------------------------------------------------------
// Public Interface
//------------------------------------------------------------------------------

const init = {
    getConfigForStyleGuide: getConfigForStyleGuide,
    processAnswers: processAnswers,
    initializeConfig: /* istanbul ignore next */ function(callback) {
        promptUser(callback);
    }
};

module.exports = init;


text:
package io.github.furti.spring.web.extended.io;

import java.io.IOException;
import java.util.Collections;
import java.util.Map;

import org.springframework.core.io.Resource;
import org.springframework.util.Assert;

import io.github.furti.spring.web.extended.util.SpringWebExtendedUtils;

public class ResourceScanners
{

    private final Map<String, ResourceScanner> scanners;

    public ResourceScanners(Map<String, ResourceScanner> scanners)
    {
        super();
        this.scanners = scanners;
    }

    /**
     * @param resourcePath
     * @param basePath
     * @return the found resources or an empty map when no resources where found.
     * @throws IOException
     */
    public Map<String, Resource> scanResources(String resourcePath, String basePath) throws IOException
    {
        String[] split = SpringWebExtendedUtils.parseExpression(resourcePath);

        Assert.isTrue(split.length == 2, "Invalid expression " + resourcePath);
        Assert.isTrue(scanners.containsKey(split[0]), "Unknown expression prefix " + split[0]);

        Map<String, Resource> foundResources = scanners.get(split[0]).scanResources(split[1], basePath);

        if (foundResources == null)
        {
            foundResources = Collections.emptyMap();
        }

        return foundResources;
    }

    /**
     * @param location
     * @param file
     * @param scanSubDirectories
     * @return the found resources or an empty map when no resources where found.
     * @throws IOException
     */
    public Map<String, Resource> scanResources(String location, String file, boolean scanSubDirectories)
        throws IOException
    {
        String[] split = SpringWebExtendedUtils.parseExpression(location);

        Assert.isTrue(split.length == 2, "Invalid expression " + location);
        Assert.isTrue(scanners.containsKey(split[0]), "Unknown expression prefix " + split[0]);

        Map<String, Resource> foundResources = scanners.get(split[0]).scanResources(split[1], file, scanSubDirectories);

        if (foundResources == null)
        {
            foundResources = Collections.emptyMap();
        }

        return foundResources;
    }
}


text:
package io.cattle.platform.lb.instance.service.impl;

import io.cattle.platform.core.dao.LoadBalancerDao;
import io.cattle.platform.core.model.Instance;
import io.cattle.platform.core.model.LoadBalancer;
import io.cattle.platform.core.model.LoadBalancerTarget;
import io.cattle.platform.object.ObjectManager;

import java.util.HashSet;
import java.util.List;
import java.util.Set;

import javax.inject.Inject;

public class UpdateInstanceLoadBalancerLookup implements LoadBalancerLookup {

    @Inject
    ObjectManager objectManager;

    @Inject
    LoadBalancerDao lbDao;

    @Override
    public Set<Long> getLoadBalancerIds(Object obj) {
        Set<Long> lbIds = new HashSet<>();
        if (!(obj instanceof Instance)) {
            return lbIds;
        }

        Instance instance = (Instance) obj;
        List<? extends LoadBalancerTarget> targets = objectManager.mappedChildren(objectManager.loadResource(Instance.class, instance.getId()),
                LoadBalancerTarget.class);

        for (LoadBalancerTarget target : targets) {
            LoadBalancer lb = lbDao.getActiveLoadBalancerById(target.getLoadBalancerId());
            if (lb != null) {
                lbIds.add(lb.getId());
            }
        }

        return lbIds;
    }

}


text:
class Revista<ReferenciaBase
      attr_reader :m_nombre_revista, :m_volumen, :m_paginas
    def initialize(a_autores,a_titulo,a_anio,a_nombre_revista, a_volumen, a_paginas)
        super(a_autores,a_titulo,a_anio)
        @m_nombre_revista,@m_volumen, @m_paginas = a_nombre_revista, a_volumen, a_paginas
    end
end


text:
namespace Serenity.Data
{
    /// <summary>
    /// LEFT JOIN type
    /// </summary>
    /// <seealso cref="Join" />
    public class LeftJoin : Join
    {
        /// <summary>
        /// Initializes a new instance of the <see cref="LeftJoin"/> class.
        /// </summary>
        /// <param name="toTable">To table.</param>
        /// <param name="alias">The alias.</param>
        /// <param name="onCriteria">The ON criteria.</param>
        public LeftJoin(string toTable, string alias, ICriteria onCriteria)
            : base(null, toTable, alias, onCriteria)
        {
        }

        /// <summary>
        /// Initializes a new instance of the <see cref="LeftJoin"/> class.
        /// </summary>
        /// <param name="joins">The joins dictionary.</param>
        /// <param name="toTable">To table.</param>
        /// <param name="alias">The alias.</param>
        /// <param name="onCriteria">The ON criteria.</param>
        public LeftJoin(IDictionary<string, Join> joins, string toTable, string alias, ICriteria onCriteria)
            : base(joins, toTable, alias, onCriteria)
        {
        }

        /// <summary>
        /// Gets the SQL keyword.
        /// </summary>
        /// <returns></returns>
        public override string GetKeyword()
        {
            return "LEFT JOIN";
        }
    }
}


text:
set(target_libraries
  CTKDICOMWidgets
  )


text:
<?hh //strict

/**
 * This file is part of hhpack\file package.
 *
 * (c) Noritaka Horio <holy.shared.design@gmail.com>
 *
 * This source file is subject to the MIT license that is bundled
 * with this source code in the file LICENSE.
 */

namespace HHPack\File;

use \SplFileInfo;

final class File {

  private SplFileInfo $stat;

  public function __construct(string $filePath) {
    $this->stat = new SplFileInfo($filePath);
  }

  public function getName(): string {
    return $this->stat->getFilename();
  }

  public function getPath(): string {
    return $this->stat->getPathname();
  }

  public static function fromString(string $filePath): File {
    return new self($filePath);
  }

  public function size(): int {
    return $this->stat->getSize();
  }

  public function exists(): bool {
    return file_exists($this->getPath());
  }

}


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

<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>
  <artifactId>ff4j-spring-services</artifactId>
  <packaging>jar</packaging>
  <name>ff4j-spring-services</name>
  <description>A spring oriented services for ff4j</description>
  <parent>
    <groupId>org.ff4j</groupId>
    <artifactId>ff4j-spring-boot-starter-parent</artifactId>
    <version>1.8.13-SNAPSHOT</version>
  </parent>
  <dependencies>
    <dependency>
      <groupId>org.springframework</groupId>
      <artifactId>spring-context</artifactId>
    </dependency>
    <dependency>
      <groupId>org.ff4j</groupId>
      <artifactId>ff4j-core</artifactId>
    </dependency>
    <dependency>
      <artifactId>ff4j-aop</artifactId>
      <groupId>org.ff4j</groupId>
    </dependency>
    <dependency>
      <groupId>org.apache.commons</groupId>
      <artifactId>commons-lang3</artifactId>
    </dependency>
    <dependency>
      <groupId>commons-collections</groupId>
      <artifactId>commons-collections</artifactId>
    </dependency>
    <!-- Test dependency -->
    <dependency>
      <groupId>com.google.code.gson</groupId>
      <artifactId>gson</artifactId>
      <scope>test</scope>
    </dependency>
    <dependency>
      <groupId>org.assertj</groupId>
      <artifactId>assertj-core</artifactId>
    </dependency>
    <dependency>
      <groupId>org.skyscreamer</groupId>
      <artifactId>jsonassert</artifactId>
    </dependency>
    <dependency>
      <groupId>org.easymock</groupId>
      <artifactId>easymock</artifactId>
    </dependency>
    <dependency>
      <groupId>org.springframework</groupId>
      <artifactId>spring-test</artifactId>
    </dependency>
    <dependency>
      <groupId>org.meanbean</groupId>
      <artifactId>meanbean</artifactId>
    </dependency>
    <dependency>
      <groupId>info.cukes</groupId>
      <artifactId>cucumber-java8</artifactId>
      <scope>test</scope>
    </dependency>
    <dependency>
      <groupId>info.cukes</groupId>
      <artifactId>cucumber-junit</artifactId>
      <scope>test</scope>
    </dependency>
    <dependency>
      <groupId>info.cukes</groupId>
      <artifactId>cucumber-spring</artifactId>
      <scope>test</scope>
    </dependency>
    <dependency>
      <groupId>org.jetbrains.kotlin</groupId>
      <artifactId>kotlin-test-junit</artifactId>
      <scope>test</scope>
    </dependency>
  </dependencies>
  <build>
    <finalName>ff4j-spring-services</finalName>
    <directory>target</directory>
    <sourceDirectory>src/main/kotlin</sourceDirectory>
    <outputDirectory>target/classes</outputDirectory>
    <testOutputDirectory>target/test-classes</testOutputDirectory>
    <resources>
      <resource>
        <directory>src/main/resources</directory>
      </resource>
    </resources>
    <testResources>
      <testResource>
        <directory>src/test/resources</directory>
      </testResource>
    </testResources>
  </build>
</project>


text:
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="com.mmartin.ghibliapi">

    <uses-permission android:name="android.permission.INTERNET" />

    <application
        android:name=".App"
        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=".film.FilmsActivity">
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />

                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>
        <activity
            android:name=".film.detail.FilmDetailActivity"
            android:label="@string/title_activity_film_detail"
            android:parentActivityName=".film.FilmsActivity"
            android:theme="@style/AppTheme.NoActionBar">
            <meta-data
                android:name="android.support.PARENT_ACTIVITY"
                android:value="com.mmartin.ghibliapi.film.FilmsActivity" />
        </activity>
        <activity
            android:name=".person.PersonDetailActivity"
            android:label="@string/title_activity_person_detail"
            android:theme="@style/AppTheme.NoActionBar" />
    </application>

</manifest>


text:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace MealsToday.Classes
{
	class Meal
	{
		public int MealId { get; set; }

		public string Name { get; set; }

		public string Description { get; set; }

		public int Calories { get; set; }

		public List<Allergen> Allergens = new List<Allergen>(5);
	}
}


text:
<?php

declare(strict_types=1);

namespace Prooph\Psr7Middleware;

use Fig\Http\Message\StatusCodeInterface;
use Prooph\Common\Messaging\Message;
use Prooph\Common\Messaging\MessageDataAssertion;
use Prooph\Common\Messaging\MessageFactory;
use Prooph\Psr7Middleware\Exception\RuntimeException;
use Prooph\Psr7Middleware\Response\ResponseStrategy;
use Prooph\ServiceBus\CommandBus;
use Prooph\ServiceBus\EventBus;
use Prooph\ServiceBus\QueryBus;
use Psr\Http\Message\ServerRequestInterface;
use Ramsey\Uuid\Uuid;
use Webimpress\HttpMiddlewareCompatibility\HandlerInterface;
use Webimpress\HttpMiddlewareCompatibility\MiddlewareInterface;

/**
 * One middleware for all message types (event, command and query)
 *
 * This class handles event, command and query messages depending on given request body data.
 */
final class MessageMiddleware implements MiddlewareInterface
{
    /**
     * Dispatches command
     *
     * @var CommandBus
     */
    private $commandBus;

    /**
     * Dispatches query
     *
     * @var QueryBus
     */
    private $queryBus;

    /**
     * Dispatches event
     *
     * @var EventBus
     */
    private $eventBus;

    /**
     * Creates message depending on name
     *
     * @var MessageFactory
     */
    private $messageFactory;

    /**
     * Generate HTTP response with result from Promise
     *
     * @var ResponseStrategy
     */
    private $responseStrategy;

    public function __construct(
        CommandBus $commandBus,
        QueryBus $queryBus,
        EventBus $eventBus,
        MessageFactory $messageFactory,
        ResponseStrategy $responseStrategy
    ) {
        $this->commandBus = $commandBus;
        $this->queryBus = $queryBus;
        $this->eventBus = $eventBus;
        $this->messageFactory = $messageFactory;
        $this->responseStrategy = $responseStrategy;
    }

    public function process(ServerRequestInterface $request, HandlerInterface $handler)
    {
        $payload = null;
        $messageName = 'UNKNOWN';

        try {
            $payload = $request->getParsedBody();

            if (\is_array($payload) && isset($payload['message_name'])) {
                $messageName = $payload['message_name'];
            }

            $messageName = $request->getAttribute('message_name', $messageName);

            $payload['message_name'] = $messageName;

            if (! isset($payload['uuid'])) {
                $payload['uuid'] = Uuid::uuid4();
            }

            if (! isset($payload['created_at'])) {
                $payload['created_at'] = new \DateTimeImmutable('now', new \DateTimeZone('UTC'));
            }

            if (! isset($payload['metadata'])) {
                $payload['metadata'] = [];
            }

            MessageDataAssertion::assert($payload);

            $message = $this->messageFactory->createMessageFromArray($messageName, $payload);

            switch ($message->messageType()) {
                case Message::TYPE_COMMAND:
                    $this->commandBus->dispatch($message);

                    return $this->responseStrategy->withStatus(StatusCodeInterface::STATUS_ACCEPTED);
                case Message::TYPE_EVENT:
                    $this->eventBus->dispatch($message);

                    return $this->responseStrategy->withStatus(StatusCodeInterface::STATUS_ACCEPTED);
                case Message::TYPE_QUERY:
                    return $this->responseStrategy->fromPromise(
                        $this->queryBus->dispatch($message)
                    );
                default:
                    throw new RuntimeException(
                        \sprintf(
                            'Invalid message type "%s" for message "%s".',
                            $message->messageType(),
                            $messageName
                        ),
                        StatusCodeInterface::STATUS_BAD_REQUEST
                    );
            }
        } catch (\Assert\InvalidArgumentException $e) {
            throw new RuntimeException(
                $e->getMessage(),
                StatusCodeInterface::STATUS_BAD_REQUEST,
                $e
            );
        } catch (\Throwable $e) {
            throw new RuntimeException(
                \sprintf('An error occurred during dispatching of message "%s"', $messageName),
                StatusCodeInterface::STATUS_INTERNAL_SERVER_ERROR,
                $e
            );
        }
    }
}


text:
  clear: both;
  color: #333;
  background: #f5f1e2 url(/images/admin/vertical_tan_gradient.png) repeat-x top;
  margin: 10px 0;
  border-radius: 8px;
  -moz-border-radius: 8px;
  -webkit-border-radius: 8px;
  overflow: hidden;
}
#attachments .toolbar {
  float: right;
  padding: 6px 6px 0;
  text-align: right;
  width: 150px;
}
#attachments a.add-link img {
  padding: 1px 2px;
  vertical-align: top;
}
#attachments a.add-link {
  display: block;
  text-decoration: none;
  padding: 15px 19px;
}
#attachments h3 {
  font-size: 16px;
  padding: 7px 0;
}
#attachments h3, #attachments p.notice {
  background: #eae3c5;
  margin: 0;
  padding: 0.5em;
}
#attachments .attachment_upload {
  padding: 0 0.8em 0.8em 0.8em;
}
#attachments p.notice {
  padding: .5em .8em;
  font-style: italic;
  font-size: 90%;
  color: red;
}
#attachments .attachment_upload img,
#attachments .attachment img.delete {
  cursor: pointer;
  padding: 2px;
  margin-left:7px;
}
#attachments .attachment img.drag_order {
  cursor: move;
  float: right;
  padding: 2px;
  margin-right:6px;
}
#attachments ol {
  list-style: none;
  padding: 0 10px 0 10px;
  margin: 0;
}
#attachments ol li {
  margin-left: 0;
}
#attachments ol li div {
  float: left;
  width: 25px;
}
#attachments ol li a.thumbnail {
  float: left;
  margin: 0 10px 0 10px;
}
#attachments ol li p {
  margin: 0 0 5px 0;
}
#attachments ol li {
  border-bottom: 1px dashed #cccccc;
  width: 100%;
  padding: 8px 0;
}
#attachments ol li:last-child {
}
#attachments .attachment .thumbnail img {
  background: white;
  border: 1px solid #d4cba4;
  padding: 3px;
  border-radius: 3px;
  -moz-border-radius: 3px;
  -webkit-border-radius: 3px;
}
#attachments p.title {
  border-bottom: 1px #eae3c5 solid;
  width: 66%;
  font-size: 17px;
  font-weight: bold;
  margin: 1em 0 ;
}
#attachments table {
  margin-top: 1em;
}
#attachments table th {
  font-weight: bold;
  text-align: right;
  padding-right: 10px;
  width: 120px;
  padding-bottom: 5px;
}
#attachments table td {
 padding-bottom: 5px;
}
#attachments li.attachment.deleted em {
  color: #ff0000;
  margin: 0 0 10px 20px;
}
#attachments li.attachment.deleted a {
  opacity: 0.5;
  text-decoration: line-through;
}
#attachments li.attachment.deleted img.delete {
  visibility: hidden;
}

.clearfix:after {
  content: ".";
  display: block;
  height: 0;
  clear: both;
  visibility: hidden;
}
.clearfix {
  display:inline-block;
}
.clearfix {
  display:block;
}
li.clearfix {
  display: list-item;
}

#attachment_list { clear: both; }

body#browser {
  background-color: #9E9E9E;
  font-family: 'Lucida Grande', 'Bitstream Vera Sans', Helvetica, Verdana, Arial, sans-serif;
  font-size: 12px;
}
body#browser a {
  color: #06C;
}


text:
var expect = require('chai').expect;
var server = require('./fixture/server');
var request = require('request');
var cheerio = require('cheerio');
var xmldom = require('xmldom');
var xmlhelper = require('./xmlhelper');

describe('samlp', function () {
  before(function (done) {
    server.start( {
      audience: 'https://auth0-dev-ed.my.salesforce.com'
    },done);
  });

  after(function (done) {
    server.close(done);
  });

  describe('SAMLRequest on querystring', function () {
    var body, $, signedAssertion, attributes;

    before(function (done) {
      request.get({
        jar: request.jar(),
        uri: 'http://localhost:5050/samlp?SAMLRequest=fZJbc6owFIX%2FCpN3EAEVMmIHEfDaqlCP%2BtKJELkUEkqCl%2F76Uj3O9JyHPmay9l4r%2BVb%2F6VLkwglXLKXEBG1JBgImIY1SEpvgNXBFHTwN%2BgwVeQmtmidkjT9qzLjQzBEGbxcmqCsCKWIpgwQVmEEeQt9azKEiybCsKKchzYFgMYYr3hjZlLC6wJWPq1Ma4tf13AQJ5yWDrVZO45RIDOWYHWkVYimkBRBGjWVKEL%2BlfEhDSjhlVEJNLvlb1%2FqOA4TJyARvynPH80qFFJPAdg%2Fh1fNnGVqpKO3OLkZonUfJ0Nu2Y2t6PdlVPj1RZxVlThywI8rihVH0MuksTQz3sx1Fm2xv5LO9nYSs5KXxfnm364%2FwfMDPWMqn182qHOqpjzR0dncsM6xO1Vs7h860HI97yrB7xHE9dt2loy%2FQu1prie%2FMcuNNL2i6nUdWp%2Fdnk3yekb7dXYhWjFjil%2Br2IC%2Bd%2FexlNF7wS77Zomvo7epFbCuyVx5tq3klYzWeEMYR4SZQ5LYqypqo6IGiQE2FmiKpencPhOXf%2Fx%2Bm5E71N1iHu4jBcRAsxeWLHwBh82hHIwD3LsCbefWjBL%2BvRQ%2FyYPCAd4MmRvgk4kgqrv8R77d%2B2Azup38LOPgC&RelayState=123'
      }, function (err, response, b){
        if(err) return done(err);
        expect(response.statusCode)
          .to.equal(200);

        body = b;
        $ = cheerio.load(body);
        var SAMLResponse = $('input[name="SAMLResponse"]').attr('value');
        var decoded = new Buffer(SAMLResponse, 'base64').toString();
        signedAssertion = /(<saml:Assertion.*<\/saml:Assertion>)/.exec(decoded)[1];
        attributes = xmlhelper.getAttributes(signedAssertion);
        done();
      });
    });

    it('should contain a form in the result', function(){
      expect(body).to.match(/<form/);
    });

    it('should contain the RelayState input', function () {
      expect($('input[name="RelayState"]').attr('value')).to.equal('123');
    });

    it('should contain a valid signal assertion', function(){
      var isValid = xmlhelper.verifySignature(
                signedAssertion,
                server.credentials.cert);
      expect(isValid).to.be.ok;
    });

    it('should have signature after issuer', function(){
      var doc = new xmldom.DOMParser().parseFromString(signedAssertion);

      var signature = doc.documentElement.getElementsByTagName('Signature');

      expect('saml:Issuer', signature[0].previousSibling.nodeName);
    });

    it('should use sha256 as default signature algorithm', function(){
      var algorithm = xmlhelper.getSignatureMethodAlgorithm(signedAssertion);
      expect(algorithm).to.equal('http://www.w3.org/2001/04/xmldsig-more#rsa-sha256');
    });

    it('should use sha256 as default diigest algorithm', function(){
      var algorithm = xmlhelper.getDigestMethodAlgorithm(signedAssertion);
      expect(algorithm).to.equal('http://www.w3.org/2001/04/xmlenc#sha256');
    });

    it('should map every attributes from profile', function(){
      function validateAttribute(position, name, value) {
        expect(attributes[position].getAttribute('Name'))
          .to.equal(name);
        expect(attributes[position].firstChild.textContent)
          .to.equal(value);
      }

      validateAttribute(0, 'http://schemas.xmlsoap.org/ws/2005/05/identity/claims/nameidentifier', server.fakeUser.id);
      validateAttribute(1, 'http://schemas.xmlsoap.org/ws/2005/05/identity/claims/emailaddress',   server.fakeUser.emails[0].value);
      validateAttribute(2, 'http://schemas.xmlsoap.org/ws/2005/05/identity/claims/name',           server.fakeUser.displayName);
      validateAttribute(3, 'http://schemas.xmlsoap.org/ws/2005/05/identity/claims/givenname',      server.fakeUser.name.givenName);
      validateAttribute(4, 'http://schemas.xmlsoap.org/ws/2005/05/identity/claims/surname',         server.fakeUser.name.familyName);
    });

    it('should contains the name identifier', function(){
      expect(xmlhelper.getNameIdentifier(signedAssertion).textContent)
        .to.equal(server.fakeUser.id);
    });

    it('should set nameidentifier format to urn:oasis:names:tc:SAML:1.1:nameid-format:unspecified by default', function(){
      expect(xmlhelper.getNameIdentifier(signedAssertion).getAttribute('Format'))
        .to.equal('urn:oasis:names:tc:SAML:1.1:nameid-format:unspecified');
    });

    it('should contains the issuer', function(){
      expect(xmlhelper.getIssuer(signedAssertion))
        .to.equal('urn:fixture-test');
    });

    it('should contains the audiences', function(){
      expect(xmlhelper.getAudiences(signedAssertion)[0].textContent)
        .to.equal('https://auth0-dev-ed.my.salesforce.com');
    });

    it('should contain the callback', function () {
      expect($('form').attr('action')).to.equal('http://office.google.com');
    });

    it('should use the default authnContextClassRef', function () {
      expect(xmlhelper.getAuthnContextClassRef(signedAssertion).textContent)
        .to.equal('urn:oasis:names:tc:SAML:2.0:ac:classes:unspecified');
    });
  });

  describe('SAMLRequest on querystring with a specific authnContextClassRef', function () {
    var body, $, signedAssertion, attributes;

    before(function (done) {
      server.options = { authnContextClassRef: "something" };
      request.get({
        jar: request.jar(),
        uri: 'http://localhost:5050/samlp?SAMLRequest=fZJbc6owFIX%2FCpN3EAEVMmIHEfDaqlCP%2BtKJELkUEkqCl%2F76Uj3O9JyHPmay9l4r%2BVb%2F6VLkwglXLKXEBG1JBgImIY1SEpvgNXBFHTwN%2BgwVeQmtmidkjT9qzLjQzBEGbxcmqCsCKWIpgwQVmEEeQt9azKEiybCsKKchzYFgMYYr3hjZlLC6wJWPq1Ma4tf13AQJ5yWDrVZO45RIDOWYHWkVYimkBRBGjWVKEL%2BlfEhDSjhlVEJNLvlb1%2FqOA4TJyARvynPH80qFFJPAdg%2Fh1fNnGVqpKO3OLkZonUfJ0Nu2Y2t6PdlVPj1RZxVlThywI8rihVH0MuksTQz3sx1Fm2xv5LO9nYSs5KXxfnm364%2FwfMDPWMqn182qHOqpjzR0dncsM6xO1Vs7h860HI97yrB7xHE9dt2loy%2FQu1prie%2FMcuNNL2i6nUdWp%2Fdnk3yekb7dXYhWjFjil%2Br2IC%2Bd%2FexlNF7wS77Zomvo7epFbCuyVx5tq3klYzWeEMYR4SZQ5LYqypqo6IGiQE2FmiKpencPhOXf%2Fx%2Bm5E71N1iHu4jBcRAsxeWLHwBh82hHIwD3LsCbefWjBL%2BvRQ%2FyYPCAd4MmRvgk4kgqrv8R77d%2B2Azup38LOPgC&RelayState=123'
      }, function (err, response, b){
        if(err) return done(err);
        expect(response.statusCode)
          .to.equal(200);

        body = b;
        $ = cheerio.load(body);
        var SAMLResponse = $('input[name="SAMLResponse"]').attr('value');
        var decoded = new Buffer(SAMLResponse, 'base64').toString();
        signedAssertion = /(<saml:Assertion.*<\/saml:Assertion>)/.exec(decoded)[1];
        attributes = xmlhelper.getAttributes(signedAssertion);
        done();
      });
    });

    it('should use the expected authnContextClassRef', function () {
      expect(xmlhelper.getAuthnContextClassRef(signedAssertion).textContent)
        .to.equal('something');
    });
  });

  describe('when using an invalid audience', function () {
    before(function () {
      server.options = { getPostURL: function getPostURL (audience, samlRequestDom, req, callback) {
          // return a null post url
          callback(null, null);
        }
      };
    });

    it('should return error', function(done){
      request.get({
        jar: request.jar(),
        uri: 'http://localhost:5050/samlp?SAMLRequest=fZJbc6owFIX%2FCpN3EAEVMmIHEfDaqlCP%2BtKJELkUEkqCl%2F76Uj3O9JyHPmay9l4r%2BVb%2F6VLkwglXLKXEBG1JBgImIY1SEpvgNXBFHTwN%2BgwVeQmtmidkjT9qzLjQzBEGbxcmqCsCKWIpgwQVmEEeQt9azKEiybCsKKchzYFgMYYr3hjZlLC6wJWPq1Ma4tf13AQJ5yWDrVZO45RIDOWYHWkVYimkBRBGjWVKEL%2BlfEhDSjhlVEJNLvlb1%2FqOA4TJyARvynPH80qFFJPAdg%2Fh1fNnGVqpKO3OLkZonUfJ0Nu2Y2t6PdlVPj1RZxVlThywI8rihVH0MuksTQz3sx1Fm2xv5LO9nYSs5KXxfnm364%2FwfMDPWMqn182qHOqpjzR0dncsM6xO1Vs7h860HI97yrB7xHE9dt2loy%2FQu1prie%2FMcuNNL2i6nUdWp%2Fdnk3yekb7dXYhWjFjil%2Br2IC%2Bd%2FexlNF7wS77Zomvo7epFbCuyVx5tq3klYzWeEMYR4SZQ5LYqypqo6IGiQE2FmiKpencPhOXf%2Fx%2Bm5E71N1iHu4jBcRAsxeWLHwBh82hHIwD3LsCbefWjBL%2BvRQ%2FyYPCAd4MmRvgk4kgqrv8R77d%2B2Azup38LOPgC&RelayState=123'
      }, function (err, response){
        if(err) return done(err);
        expect(response.statusCode)
          .to.equal(401);
        done();
      });
    });
  });

describe('when using a different name identifier format', function () {
    var body, $, signedAssertion, attributes;

    before(function (done) {
      server.options = { nameIdentifierFormat: 'urn:oasis:names:tc:SAML:1.1:nameid-format:emailAddress' };
      request.get({
        jar: request.jar(),
        uri: 'http://localhost:5050/samlp?SAMLRequest=fZJbc6owFIX%2FCpN3EAEVMmIHEfDaqlCP%2BtKJELkUEkqCl%2F76Uj3O9JyHPmay9l4r%2BVb%2F6VLkwglXLKXEBG1JBgImIY1SEpvgNXBFHTwN%2BgwVeQmtmidkjT9qzLjQzBEGbxcmqCsCKWIpgwQVmEEeQt9azKEiybCsKKchzYFgMYYr3hjZlLC6wJWPq1Ma4tf13AQJ5yWDrVZO45RIDOWYHWkVYimkBRBGjWVKEL%2BlfEhDSjhlVEJNLvlb1%2FqOA4TJyARvynPH80qFFJPAdg%2Fh1fNnGVqpKO3OLkZonUfJ0Nu2Y2t6PdlVPj1RZxVlThywI8rihVH0MuksTQz3sx1Fm2xv5LO9nYSs5KXxfnm364%2FwfMDPWMqn182qHOqpjzR0dncsM6xO1Vs7h860HI97yrB7xHE9dt2loy%2FQu1prie%2FMcuNNL2i6nUdWp%2Fdnk3yekb7dXYhWjFjil%2Br2IC%2Bd%2FexlNF7wS77Zomvo7epFbCuyVx5tq3klYzWeEMYR4SZQ5LYqypqo6IGiQE2FmiKpencPhOXf%2Fx%2Bm5E71N1iHu4jBcRAsxeWLHwBh82hHIwD3LsCbefWjBL%2BvRQ%2FyYPCAd4MmRvgk4kgqrv8R77d%2B2Azup38LOPgC&RelayState=123'
      }, function (err, response, b){
        if(err) return done(err);
        expect(response.statusCode)
          .to.equal(200);

        body = b;
        $ = cheerio.load(body);
        var SAMLResponse = $('input[name="SAMLResponse"]').attr('value');
        var decoded = new Buffer(SAMLResponse, 'base64').toString();
        signedAssertion = /(<saml:Assertion.*<\/saml:Assertion>)/.exec(decoded)[1];
        attributes = xmlhelper.getAttributes(signedAssertion);
        done();
      });
    });

    it('should override nameidentifier format', function(){
      expect(xmlhelper.getNameIdentifier(signedAssertion).getAttribute('Format'))
        .to.equal('urn:oasis:names:tc:SAML:1.1:nameid-format:emailAddress');
    });
  });

 describe('when sending SAMLRequest ID ', function () {
    var body, $, signedAssertion, samlResponse;

    before(function (done) {
      // SAMLRequest =
      // <?xml version="1.0" encoding="UTF-8"?>
      // <samlp:AuthnRequest xmlns:samlp="urn:oasis:names:tc:SAML:2.0:protocol" AssertionConsumerServiceURL="https://acs"
      //        Destination="https://destination"
      //        ID="12345"
      //        IssueInstant="2013-04-28T22:43:42.386Z"
      //        ProtocolBinding="urn:oasis:names:tc:SAML:2.0:bindings:HTTP-POST" Version="2.0">
      //     <saml:Issuer xmlns:saml="urn:oasis:names:tc:SAML:2.0:assertion">http://sp</saml:Issuer>
      //  </samlp:AuthnRequest>
      request.get({
        jar: request.jar(),
        uri: 'http://localhost:5050/samlp?SAMLRequest=fZBPb4MwDMW%2FSuQ7fxrYhCygYqumVeo0VOgOu2U0WpEgYXGo9vGXwdDaS2%2BO7fi990vX333HztJQq1UGKz8EJlWjj636zOBQP3kJrPOURN8NWIz2pPbya5RkmfunCKdBBqNRqAW1hEr0ktA2WBUvO%2BR%2BiIPRVje6A1YQSWOd0KNWNPbSVNKc20Ye9rsMTtYOhEEgGgK2cQqtEnYytUyO%2F01g241zy6P4zpVEo9wqskLZDHi4irww9nhSc45xhDH3o%2BT%2BHVj5Z%2BShVXO8W64%2F5iXC57ouvfK1qoG9LZjcAsxQcBI3FzRunxULAsh%2FY7lUNKTBxaV8fl3Dzn8A&RelayState=123'
      }, function (err, response, b){
        if(err) return done(err);
        expect(response.statusCode)
          .to.equal(200);

        body = b;
        $ = cheerio.load(body);
        var SAMLResponse = $('input[name="SAMLResponse"]').attr('value');
        samlResponse = new Buffer(SAMLResponse, 'base64').toString();
        signedAssertion = /(<saml:Assertion.*<\/saml:Assertion>)/.exec(samlResponse)[1];
        done();
      });
    });

    it('should send back the ID as InResponseTo', function(){
      expect(xmlhelper.getSubjectConfirmationData(signedAssertion).getAttribute('InResponseTo'))
        .to.equal('12345');
    });

    it('should send back the ID as InResponseTo', function(){
      var doc = new xmldom.DOMParser().parseFromString(samlResponse);
      expect(doc.documentElement.getAttribute('InResponseTo')).to.equal('12345');
    });
  });

 describe('when sending SAMLRequest without RelayState ', function () {
    var body, $, signedAssertion, samlResponse;

    before(function (done) {
      request.get({
        jar: request.jar(),
        uri: 'http://localhost:5050/samlp?SAMLRequest=fZBPb4MwDMW%2FSuQ7fxrYhCygYqumVeo0VOgOu2U0WpEgYXGo9vGXwdDaS2%2BO7fi990vX333HztJQq1UGKz8EJlWjj636zOBQP3kJrPOURN8NWIz2pPbya5RkmfunCKdBBqNRqAW1hEr0ktA2WBUvO%2BR%2BiIPRVje6A1YQSWOd0KNWNPbSVNKc20Ye9rsMTtYOhEEgGgK2cQqtEnYytUyO%2F01g241zy6P4zpVEo9wqskLZDHi4irww9nhSc45xhDH3o%2BT%2BHVj5Z%2BShVXO8W64%2F5iXC57ouvfK1qoG9LZjcAsxQcBI3FzRunxULAsh%2FY7lUNKTBxaV8fl3Dzn8A'
      }, function (err, response, b){
        if(err) return done(err);
        expect(response.statusCode)
          .to.equal(200);

        body = b;
        $ = cheerio.load(body);
        var SAMLResponse = $('input[name="SAMLResponse"]').attr('value');
        samlResponse = new Buffer(SAMLResponse, 'base64').toString();
        signedAssertion = /(<saml:Assertion.*<\/saml:Assertion>)/.exec(samlResponse)[1];
        done();
      });
    });

    it('should not throw an error', function(){
      expect(xmlhelper.getSubjectConfirmationData(signedAssertion).getAttribute('InResponseTo'))
        .to.equal('12345');
    });

  });
});


text:
using System;
using Microsoft.VisualStudio.TestTools.UnitTesting;
using System.Collections.Generic;
using MoG.Domain.Models;
using MoG.Domain.Service;
using MoG.App_Start;
using Ninject;
using System.Linq;
using MoG.Domain.Repository;

namespace MoG.Test.Service
{
    [TestClass]
    public class FileServiceTest
    {
        private IFileService serviceFile;

        private IUserService serviceUser;

        private IProjectService serviceProject;

        private IAuthCredentialRepository repoCredential;

        [TestInitialize]
        public void MyTestInitialize()
        {
            var kernel = NinjectWebCommon.CreatePublicKernel();
            serviceFile = kernel.Get<IFileService>();
            serviceUser = kernel.Get<IUserService>();
            serviceProject = kernel.Get<IProjectService>();
            repoCredential = kernel.Get<IAuthCredentialRepository>();
        }

        [TestMethod]
        public void FileService_GetProjectFiles()
        {
            List<ProjectFile> files = serviceFile.GetProjectFile(1);

            Assert.IsNotNull(files);
            Assert.IsTrue(files.Count > 0);

        }
        [TestMethod]
        public void FileService_GetFile()
        {
            int fileId = 1;
            var file = serviceFile.GetById(fileId);

            Assert.IsNotNull(file);
            Assert.IsTrue(file.Id == fileId);
            Assert.IsNotNull(file.Project);
        }

        [TestMethod]
        public void FileService_GetComments()
        {
            int fileId = 1;
            var messages = serviceFile.GetFileComments(fileId);

            Assert.IsNotNull(messages);

            foreach (var message in messages)
            {
                Assert.IsTrue(message.FileId == fileId);
            }

        }
        [TestMethod]
        public void FileService_Create()
        {
            var project = serviceProject.GetNew(1,10,false,false).ToList();
            var storageCredential = this.repoCredential.GetById(1);
            var user = serviceUser.GetAll().FirstOrDefault();
            ProjectFile f = new ProjectFile();
            f.Description = "Test + " + DateTime.Now.ToString();
            f.Tags = FileType.Drums.ToString();
            f.Likes = 42;
            f.DisplayName = "TEST FILE " + DateTime.Now.Ticks;
            f.InternalName = "TEST FILE INTERNAL " + DateTime.Now.Ticks;
            f.ProjectId = project[0].Id;
            f.AuthCredentialId = storageCredential.Id;

            int i = this.serviceFile.Create(f, user);
            var activities = this.serviceProject.GetProjectActivity(f.ProjectId);
            var fileActivities = activities.Where(a => (a.Type & ActivityType.File) == ActivityType.File).ToList();

            Assert.IsTrue(i > 0);
            Assert.IsTrue(f.Id > 0);
            Assert.IsTrue(fileActivities.Count > 0);

        }
    }
}