text:
using System;
using System.Collections.Generic;
using System.Configuration;
using System.Data;
using System.IO;
using System.Linq;
using System.Threading;
using System.Threading.Tasks;
using System.Windows;

using SharpRaven;
using System.Reflection;

namespace Articulate
{
    /// <summary>
    /// Interaction logic for App.xaml
    /// </summary>
    public partial class App : Application
    {
		public const string AppMutex = "Articulate";

		internal static App Instance
		{
			get;
			private set;
		}

		static RavenClient _Sentry = null;
		internal static RavenClient Sentry
		{
			get {
                return _Sentry = _Sentry ?? new RavenClient(Constants.SentryDSN)
                {
#if DEBUG
                    Environment = "debug",
#else
                    Environment = "release",
#endif
                    Release = Assembly.GetExecutingAssembly().GetVersion()?.ToString(3),
                    Logger = "Desktop"
                };
            }
		}

		[STAThread]
		public static void Main()
		{
			AppDomain.CurrentDomain.UnhandledException += (o, e) =>
			{
				HandleError(e.ExceptionObject as Exception);
			};

			bool newInstance = false;
			using (Mutex appMutex = new Mutex(true, AppMutex, out newInstance))
			{
				if (!newInstance)
					return;

				Instance = new App();
				Instance.InitializeComponent();
				Instance.Run();
			}
		}

		static bool IsErrorHandling = false;

		[System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Maintainability", "CA1506:AvoidExcessiveClassCoupling"), System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes")]
		public static void HandleError(Exception ex)
		{
			Sentry.CaptureException(ex);

			if (IsErrorHandling) return;
			IsErrorHandling = true;

			var crashLogFolder = Environment.ExpandEnvironmentVariables(@"%AppData%\Articulate\Crashes");

			if (!Directory.Exists(crashLogFolder))
				Directory.CreateDirectory(crashLogFolder);
			using (StreamWriter sw = new StreamWriter(Path.Combine(crashLogFolder, "Crash - " + DateTime.Now.ToString("yyyy-MM-dd HH-mm-ss") + ".txt")))
			{
				sw.WriteLine("Articulate Application Crash");
				sw.WriteLine("OS: " + Environment.OSVersion.VersionString);
				sw.WriteLine("64-Bit: " + (IntPtr.Size == 8 ? "Yes" : "No"));
				sw.WriteLine(".NET Version: " + Environment.Version.ToString());
				sw.WriteLine("Command Line: " + Environment.CommandLine);
				sw.WriteLine();
				sw.Flush();
				sw.AutoFlush = true;

				WriteError(sw, ex);
			}
		}

		[System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes")]
		static void WriteError(StreamWriter sw, Exception ex)
		{

			if (ex == null)
				return;
			try
			{
				sw.WriteLine("Exception Message");
				sw.WriteLine(ex.Message);
				sw.WriteLine();

				if (ex.TargetSite != null)
				{
					sw.WriteLine("Exception Target Site");
					sw.WriteLine(ex.TargetSite.DeclaringType.FullName + " - " + ex.TargetSite.Name);
				}

				sw.WriteLine();
				sw.WriteLine("Stack Trace");
				sw.WriteLine(ex.StackTrace);
			}
			catch
			{ }

			if (ex.InnerException != null)
			{
				sw.WriteLine();
				sw.WriteLine();
				sw.WriteLine("INNER EXCEPTION:");
				WriteError(sw, ex.InnerException);
			}
		}

    }
}


text:
<?xml version="1.0" encoding="UTF-8"?>
<phpunit colors="true" bootstrap="vendor/autoload.php">
    <testsuites>
        <testsuite name="all">
            <directory suffix="Test.php">tests/</directory>
        </testsuite>
    </testsuites>
    <filter>
        <whitelist>
            <directory suffix=".php">src/</directory>
        </whitelist>
    </filter>
</phpunit>

redpajama_set_name: RedPajamaGithub


text:
package gov.nasa.ensemble.core.model.plan.provider;

import gov.nasa.ensemble.common.extension.ClassRegistry;
import gov.nasa.ensemble.common.logging.LogUtil;
import gov.nasa.ensemble.common.mission.MissionExtender;
import gov.nasa.ensemble.common.mission.MissionExtender.ConstructionException;
import gov.nasa.ensemble.common.ui.WidgetUtils;
import gov.nasa.ensemble.common.ui.color.ColorMap;
import gov.nasa.ensemble.core.model.plan.EMember;
import gov.nasa.ensemble.core.model.plan.EPlanElement;
import gov.nasa.ensemble.core.model.plan.PlanPackage;
import gov.nasa.ensemble.core.model.plan.util.EPlanUtils;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.eclipse.core.resources.IMarker;
import org.eclipse.core.resources.IMarkerDelta;
import org.eclipse.core.resources.IResourceChangeEvent;
import org.eclipse.core.resources.IResourceChangeListener;
import org.eclipse.core.resources.ResourcesPlugin;
import org.eclipse.emf.common.notify.Adapter;
import org.eclipse.emf.common.notify.AdapterFactory;
import org.eclipse.emf.common.notify.Notification;
import org.eclipse.emf.common.notify.Notifier;
import org.eclipse.emf.edit.provider.ComposedAdapterFactory;
import org.eclipse.emf.edit.provider.IItemColorProvider;
import org.eclipse.emf.edit.provider.IItemLabelProvider;
import org.eclipse.emf.edit.ui.provider.AdapterFactoryLabelProvider;
import org.eclipse.jface.viewers.ILabelDecorator;
import org.eclipse.jface.viewers.ILabelProviderListener;
import org.eclipse.jface.viewers.LabelProviderChangedEvent;
import org.eclipse.swt.SWT;
import org.eclipse.swt.graphics.Color;
import org.eclipse.swt.graphics.GC;
import org.eclipse.swt.graphics.Image;
import org.eclipse.swt.graphics.ImageData;
import org.eclipse.swt.graphics.PaletteData;
import org.eclipse.swt.graphics.RGB;
import org.eclipse.swt.graphics.Rectangle;
import org.eclipse.swt.widgets.Display;

public class EPlanElementLabelProvider extends AdapterFactoryLabelProvider implements Adapter {

	private static Map<EPlanElementImageDescriptor, Image> ePlanElementImageDescriptorToImageMap = new HashMap<EPlanElementImageDescriptor, Image>();
	private static List<ILabelDecorator> labelDecorators = null;
	private static Listener WORKSPACE_LISTENER = new Listener();
//	private static Set<String> traces = new HashSet<String>();

	public EPlanElementLabelProvider(AdapterFactory factory) {
		this(factory, true);
	}

	public EPlanElementLabelProvider() {
		this(new ComposedAdapterFactory(ComposedAdapterFactory.Descriptor.Registry.INSTANCE), false);
	}

	public EPlanElementLabelProvider(AdapterFactory factory, boolean markerUpdates) {
		super(factory);
		if(labelDecorators == null) {
			labelDecorators = ClassRegistry.createInstances(ILabelDecorator.class);
		}
		if (markerUpdates) {
			WORKSPACE_LISTENER.register(this);
		}

//		int i=0;
//		StringBuffer buffer = new StringBuffer();
//		buffer.append(Thread.currentThread().getName()+"\n");
//		for (StackTraceElement element : Thread.currentThread().getStackTrace()) {
//			buffer.append("\tat "+element.getClassName()+"."+element.getMethodName()+"("+element.getFileName()+":"+element.getLineNumber()+")\n");
//			if (++i > 20) {
//				break;
//			}
//		}
//		String trace = buffer.toString();
//		if (!traces.contains(trace)) {
//			System.out.println(trace);
//			traces.add(trace);
//		}
	}

	@Override
	public void dispose() {
		super.dispose();
		WORKSPACE_LISTENER.unregister(this);
	}

	/**
	 * Return the background RGB value for the given object.
	 * @param object
	 * @return an RGB color descriptor
	 */
	private RGB getBackgroundRGB(Object object) {
		try {
			if (MissionExtender.hasMissionSpecificClass(ItemColorProvider.class)) {
				ItemColorProvider provider = MissionExtender.construct(ItemColorProvider.class);
				RGB background = (RGB) provider.getBackground(object);
				if (background != null) {
					return background;
				}
			}
		} catch (ConstructionException e) {
			LogUtil.error(e);
		}
		IItemColorProvider itemColorProvider = getAdapter(object, IItemColorProvider.class);
		RGB backgroundColor = (itemColorProvider != null)
			? (RGB)itemColorProvider.getBackground(object) : null;
		return backgroundColor;
	}

	/**
	 * Return an unmodified image for the given object
	 * @param object
	 * @return an unmodified image for the given object.
	 */
	private Image getOriginalImage(Object object) {
		IItemLabelProvider itemLabelProvider = getAdapter(object, IItemLabelProvider.class);
		Image image = itemLabelProvider != null ? getImageFromObject(itemLabelProvider
				.getImage(object))
				: getDefaultImage(object);

		return image;
	}

	private <T> T getAdapter(Object object, Class<T> adapter) {
		return (T) adapterFactory.adapt(object, adapter);
	}

	/**
	 * Given an object, get the associated image from the cache (if there is one).
	 * If no image exists in the cache, generate one using the base image, and
	 * store the new image in the cache or later use.
	 *
	 * @param object the object whose decorated image is desired
	 * @return an image for the given object (a fully decorated one, ready for use)
	 */
	@Override
	public Image getImage(Object object) {
		RGB backgroundColor = getBackgroundRGB(object);
		Image originalImage = getOriginalImage(object);
		int severity = EPlanUtils.getSeverity(object);

		EPlanElementImageDescriptor ePlanElementImageDescriptor
			= new EPlanElementImageDescriptor(backgroundColor, originalImage, severity);

		Image image = ePlanElementImageDescriptorToImageMap.get(ePlanElementImageDescriptor);

		if(image == null) {
			image = createImage(ePlanElementImageDescriptor, object);
			ePlanElementImageDescriptorToImageMap.put(ePlanElementImageDescriptor
					, image);
		}

		return image;
	}

	/**
	 * Using a descriptor, create the appropriate image.
	 * @param ePlanElementImageDescriptor a descriptor that describes an image
	 * that should be used for the given object.
	 * @param object the object for which an image should be created
	 * @param ePlanElementImageDescriptor a descriptor that describes the type of image
	 * that should be created.
	 * @return a newly generated image (with badges, ready to use)
	 */
	private Image createImage(EPlanElementImageDescriptor ePlanElementImageDescriptor
			, Object object) {
		RGB rgb = ePlanElementImageDescriptor.getBackgroundColor();
		Image image = ePlanElementImageDescriptor.getImage();

		if (rgb != null) {
			image = getImageOverlay(image, rgb);
			Image previousImage = image;
			image = getImageWithBadges(image, object);
			if(!previousImage.equals(image)) {
				previousImage.dispose();
			}
		}

		return image;
	}

	@Override
	public void notifyChanged(Notification n) {
		Object feature = n.getFeature();
		if (PlanPackage.Literals.COMMON_MEMBER__COLOR == feature) {
			EMember member = (EMember) n.getNotifier();
			EPlanElement planElement = member.getPlanElement();
//			if (images.containsKey(planElement)) {
//				images.remove(planElement);
//			}
			for (ILabelProviderListener l : labelProviderListeners) {
				l.labelProviderChanged(new LabelProviderChangedEvent(this, planElement));
			}
		} else if (PlanPackage.Literals.EPLAN_ELEMENT__NAME == feature) {
			for (ILabelProviderListener l : labelProviderListeners) {
				l.labelProviderChanged(new LabelProviderChangedEvent(this, n.getNotifier()));
			}
		}
		super.notifyChanged(n);
	}

	private Image getImageOverlay(Image image, RGB rgb) {
		Rectangle rect = image.getBounds();
		Display display = WidgetUtils.getDisplay();

		// 1. create image

		PaletteData palette = new PaletteData(0xFF0000, 0xFF00, 0xFF);
		ImageData imageData = new ImageData(rect.width, rect.height, 24, palette);
		Image imageOverlay = new Image(display, imageData);
		GC gc = new GC(imageOverlay);
		Color backgroudColor = ColorMap.RGB_INSTANCE.getColor(rgb);
		gc.setBackground(backgroudColor);
		gc.fillOval(rect.x, rect.y, rect.width, rect.height);
		gc.drawImage(image, rect.x, rect.y);
		gc.dispose();
		//backgroudColor.dispose();
 		imageData = imageOverlay.getImageData();
 		imageOverlay.dispose();

 		// 2. create alpha channel

		PaletteData grayPalette = new PaletteData(0xFF, 0xFF, 0xFF);
		ImageData alphaImageData = new ImageData(rect.width, rect.height, 8, grayPalette);
		Image imageAlpha = new Image(display, alphaImageData);
		gc = new GC(imageAlpha);
		gc.setAntialias(SWT.ON);
		gc.setBackground(display.getSystemColor(SWT.COLOR_WHITE));
		gc.fillOval(rect.x, rect.y, rect.width, rect.height);
		gc.dispose();
 		alphaImageData = imageAlpha.getImageData();
 		imageAlpha.dispose();

 		// 3. Apply alpha channel

 		for (int x = 0; x < imageData.width; ++x)
 			for (int y = 0; y < imageData.height; ++y)
 				imageData.setAlpha(x, y, (int) (alphaImageData.palette.getRGB(alphaImageData.getPixel(x, y)).getHSB()[2] * 255));

		return new Image(display, imageData);
	}

	/**
	 * Add badges to an existing image given an object. Label decorators that are
	 * loaded through the ClassRegistry extension point are programmed to decorate
	 * and existing image given an element.
	 *
	 * @param image the image to decorate
	 * @param element the element which shall determine the decoration
	 * @return a new decorated image if a decoration was performed, the original
	 * image otherwise.
	 */
	private Image getImageWithBadges(Image image, Object element) {
		Image decoratedImage = image;
		Image previousImage = null;
		for(ILabelDecorator labelDecorator : labelDecorators) {
			if(!decoratedImage.equals(image)) {
				previousImage = decoratedImage;
			}

			decoratedImage = labelDecorator.decorateImage(image, element);

			if(previousImage != null && !previousImage.isDisposed()) {
				previousImage.dispose();
			}
		}
		return decoratedImage;
	}

	@Override
	public Notifier getTarget() {
		return null;
	}

	@Override
	public boolean isAdapterForType(Object type) {
		return false;
	}

	@Override
	public void setTarget(Notifier newTarget) {
		// no implementation
	}

	/**
	 * This class does not extend ImageDescriptor. The sole purpose of this class
	 * is to provide a means to caching the images needed by this label provider.
	 * By creating a new descriptor for each image request, we can see if such an
	 * image has been created before, and return the request image.
	 */
	static class EPlanElementImageDescriptor {
		private RGB backgroundColor;
		private Image image;
		private int severity;

		public EPlanElementImageDescriptor(RGB backgroundColor, Image image
				, int severity) {
			this.backgroundColor = backgroundColor;
			this.image = image;
			this.severity = severity;
		}

		/**
		 * Custom hash code, since using the default hash code will return a different
		 * code for two EPlanElementImageDescriptor instances which would be deemed
		 * "equal"
		 * @return the calculated hashCode
		 */
		@Override
		public int hashCode() {
			return backgroundColor.hashCode() + image.hashCode() + severity;
		}

		@Override
		public boolean equals(Object object) {
			if(object instanceof EPlanElementImageDescriptor) {
				EPlanElementImageDescriptor ePlanElementImageDescriptor
					= (EPlanElementImageDescriptor)object;
				if(this.backgroundColor.equals(ePlanElementImageDescriptor.getBackgroundColor())
						&& this.image.equals(ePlanElementImageDescriptor.getImage())
						&& this.severity == ePlanElementImageDescriptor.getSeverity()) {
					return true;
				}
			}
			return false;
		}

		public RGB getBackgroundColor() {
			return this.backgroundColor;
		}

		public Image getImage() {
			return this.image;
		}

		public int getSeverity() {
			return this.severity;
		}
	}

	private static class Listener implements IResourceChangeListener {

		private final List<EPlanElementLabelProvider> providers = new ArrayList<EPlanElementLabelProvider>();

		public void register(EPlanElementLabelProvider lp) {
			synchronized (providers) {
				if (providers.isEmpty()) {
					ResourcesPlugin.getWorkspace().addResourceChangeListener(this);
				}
				providers.add(lp);
			}
		}

		public void unregister(EPlanElementLabelProvider lp) {
			synchronized (providers) {
				providers.remove(lp);
				if (providers.isEmpty()) {
					ResourcesPlugin.getWorkspace().removeResourceChangeListener(this);
				}
			}
		}

		@Override
		public void resourceChanged(IResourceChangeEvent event) {
			final List<EPlanElementLabelProvider> markedProviders = new ArrayList<EPlanElementLabelProvider>();
			synchronized (providers) {
				for (EPlanElementLabelProvider provider : providers) {
					if (event.getType() == IResourceChangeEvent.POST_CHANGE) {
						boolean includeSubTypes = true;
						IMarkerDelta[] markerDeltas = event.findMarkerDeltas(IMarker.MARKER, includeSubTypes);
						if (markerDeltas.length > 0) {
							markedProviders.add(provider);
						}
					}
				}
			}
			WidgetUtils.getDisplay().asyncExec(new Runnable() {
				@Override
				public void run() {
					for (EPlanElementLabelProvider provider : markedProviders) {
						provider.fireLabelProviderChanged();
					}
				}
			});
		}
	}

}


text:
package structures.data.actions.logic;

import structures.data.DataAction;

public class Else extends DataAction {

	public Else(){
		init();
	}

	@Override
	public String getTitle() {
		return "Else";
	}

	@Override
	public String getDescription() {
		return "Else";
	}

	@Override
	protected String getSyntax() {
		return "\n } else {\n";
	}

}


text:
define(function(require, exports, module) {
    "use strict";

    var ProjectFiles = require('ProjectFiles');
    var ConfigurationManager = {},
        configuration = {};

    function projectOpenDone( config ) {
        configuration = JSON.parse(config);
        $(ConfigurationManager).trigger("load", [configuration]);
    }

    function projectOpenFailed() {
        configuration = {};
        $(ConfigurationManager).trigger("load", [configuration]);
    }

    // Project settings for tomcat
    $(ProjectFiles).on("projectOpen", function() {
        $(ConfigurationManager).trigger("unload", [configuration]);

        ProjectFiles.openFile( ".tomcat-manager" )
            .done(function( file ) {
                file.read()
                    .done(projectOpenDone)
                    .fail(projectOpenFailed);
            })
            .fail(projectOpenFailed);
    });

    ConfigurationManager.getConfiguration = function( ) {
        return configuration;
    };

    ConfigurationManager.saveConfiguration = function() {
        ProjectFiles.openFile( ".tomcat-manager", "write", true )
            .done(function( fileWriter ) {
                fileWriter.write( JSON.stringify( configuration ) );
            })
            .fail(projectOpenFailed);
    };

    ConfigurationManager.getServersAsArray = function() {
        var result = [];
        var servers = (configuration.Servers || {});
        for ( var iServer in servers ) {
            if ( !servers.hasOwnProperty(iServer) ) {
                continue;
            }

            result.push(ConfigurationManager.getServer(iServer));
        }

        return result;
    };

    ConfigurationManager.getServers = function() {
        return (configuration.Servers || {});
    };

    ConfigurationManager.getAppServer = function( server ) {
        if ( typeof server === "string" ) {
            server = ConfigurationManager.getServer(server);
        }

        var appServers = configuration.AppServers || {};
        return appServers[server.AppServer];
    };

    ConfigurationManager.getServer = function( serverName ) {
        var server = (configuration.Servers || {})[serverName] || false;
        if (server) {
            server.name = serverName;
        }
        return server;
    };

    ConfigurationManager.getServerDetails = function( serverName ) {
        var server = ConfigurationManager.getServer(serverName);
        var appServer = ConfigurationManager.getAppServer(server);
        return $.extend({}, server, {"AppServer": appServer});
    };

    return ConfigurationManager;
});


text:
package dm.kafka.consumer;

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

import javax.jms.JMSException;
import javax.jms.MessageProducer;
import javax.jms.Session;
import javax.jms.TextMessage;

import com.amazon.sqs.javamessaging.AmazonSQSMessagingClientWrapper;
import com.amazon.sqs.javamessaging.ProviderConfiguration;
import com.amazon.sqs.javamessaging.SQSConnection;
import com.amazon.sqs.javamessaging.SQSConnectionFactory;
import com.amazonaws.services.sqs.AmazonSQSClientBuilder;
import com.amazonaws.services.sqs.model.CreateQueueRequest;

public class SQSProducer implements DataSink{

	Session session;
	MessageProducer producer;
	SQSConnection connection;
	AWSKafkaConfig config;
	int seqNum = 1;
	String deDuplicationId = "NA";

	//StringBuilder messageBuffer = new StringBuilder();
	DataTransformer mPreProcessor = null;
	DataReplaceXmit mXmitReplacement = null;
	//BinData binObj = null;
	boolean mXmitDisable = false;
	public void init(AWSKafkaConfig config){

		this.config = config;
		deDuplicationId  = config.getDeDeupPrefix();

		mXmitDisable = config.getAwsXmitDisable();

		SQSConnectionFactory connectionFactory = new SQSConnectionFactory(
		        new ProviderConfiguration(),
		        AmazonSQSClientBuilder.standard()
		                .withRegion(config.getRegions())
		                .withCredentials(config.getCredentialsProvider())
		        );
		try{

			mPreProcessor = config.getPre();
			mXmitReplacement = config.getReplaceXmit(this);
			// Create the connection.
			connection = connectionFactory.createConnection();

			// Create the queue if needed
	        //ExampleCommon.ensureQueueExists(connection, config.getQueueName());

	        // Create the session
	        session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE);
	        producer = session.createProducer( session.createQueue( config.getQueueName() ) );

	     // Get the wrapped client
	        AmazonSQSMessagingClientWrapper client = connection.getWrappedAmazonSQSClient();

	        // Create an Amazon SQS queue if it does not already exist
	        if (!client.queueExists(config.getQueueName())) {
	            Map<String, String> attributes = new HashMap<String, String>();
	            attributes.put(config.getQueueName(), "true");
	            attributes.put("ContentBasedDeduplication", "true");
	            client.createQueue(new CreateQueueRequest().withQueueName(config.getQueueName()).withAttributes(attributes));
	        }
		}catch(JMSException e){
		}

	}
	public void close(){
		//ceanup, transmit any remaining data
		try{
			if(mPreProcessor!= null){
				mPreProcessor.close();
			}
			if(mXmitReplacement != null){
				mXmitReplacement.close();
			}
			connection.close();
		}catch(JMSException e){
		}

		System.out.println("Exit called on SQSProducer");
	}

	public void sendMessages( String orgMsg) {
		String msg = orgMsg;
		if(mPreProcessor!= null){
			msg = mPreProcessor.alter(orgMsg);
		}

    	if(mXmitReplacement == null){
    		xmitData(msg);
    	}else{
    		mXmitReplacement.send(msg);
    	}
    }

	@Override
	public void xmitData(String data) {
		try {
			if(mXmitDisable == false){
				TextMessage message = session.createTextMessage(data);
		        message.setStringProperty("JMSXGroupID", "Default");
		        message.setStringProperty("JMS_SQS_DeduplicationId", deDuplicationId+(seqNum++));
		        producer.send(message);
			}
		} catch (JMSException e) {
	        System.err.println( "Failed sending message: " + e.getMessage() );
	        e.printStackTrace();
	    }

	}

}


text: module.exports = require("npm:mustache@0.7.3/mustache");


text:
Define_Module(Ns2MotionMobility);

Ns2MotionMobility::Ns2MotionMobility()
{
    vecpos = 0;
    ns2File = NULL;
    nodeId = 0;
    scrollX = 0;
    scrollY = 0;
}

Ns2MotionMobility::~Ns2MotionMobility()
{
    if (ns2File)
        delete ns2File;
}

void Ns2MotionMobility::parseFile(const char *filename)
{

    std::ifstream in(filename, std::ios::in);

    if (in.fail())
        throw cRuntimeError("Cannot open file '%s'", filename);
    ns2File->initial[0] = ns2File->initial[1] = ns2File->initial[2] = -1;
    std::string line;
    std::string subline;

    while (std::getline(in, line))
    {
        // '#' line
        int num_node;
        std::string::size_type found = line.find('#');
        if (found == 0)
            continue;
        if (found != std::string::npos)
            subline = line;
        else
            subline = line.substr(0, found);
        found = subline.find("$node_");
        if (found == std::string::npos)
            continue;
        // Node Id
        std::string::size_type pos1 = subline.find('(');
        std::string::size_type pos2 = subline.find(')');
        if (pos2-pos1>1)
            num_node = std::atoi(subline.substr(pos1+1, pos2-1).c_str());
        if (num_node!=nodeId)
            continue;
        // Initial position
        found = subline.find("set ");
        if (found!=std::string::npos)
        {
            // Initial position
            found = subline.find("X_");
            if (found!=std::string::npos)
            {
                ns2File->initial[0] = std::atof(subline.substr(found+3, std::string::npos).c_str());
            }
            found = subline.find("Y_");
            if (found!=std::string::npos)
            {
                ns2File->initial[1] = std::atof(subline.substr(found+3, std::string::npos).c_str());
            }

            found = subline.find("Z_");
            if (found!=std::string::npos)
            {
                ns2File->initial[2] = std::atof(subline.substr(found+3, std::string::npos).c_str());
            }
        }
        found = subline.find("setdest");
        if (found!=std::string::npos)
        {
            ns2File->lines.push_back(Ns2MotionFile::Line());
            Ns2MotionFile::Line& vec = ns2File->lines.back();
            // initial time
            found = subline.find("at");
            vec.push_back(std::atof(subline.substr(found+3).c_str()));

            std::string parameters = subline.substr(subline.find("setdest ")+8, std::string::npos);

            std::stringstream linestream(parameters);
            double d;
            while (linestream >> d)
                vec.push_back(d);
        }
    }
    in.close();
    // exist data?
    if (ns2File->initial[0]==-1 || ns2File->initial[1]==-1 || ns2File->initial[2]==-1)
        throw cRuntimeError("node '%d' Error ns2 motion file '%s'", nodeId, filename);

}

void Ns2MotionMobility::initialize(int stage)
{
    LineSegmentsMobilityBase::initialize(stage);
    EV << "initializing Ns2MotionMobility stage " << stage << endl;
    if (stage == 0)
    {
        scrollX = par("scrollX");
        scrollY = par("scrollY");
        nodeId = par("nodeId");
        if (nodeId == -1)
            nodeId = getParentModule()->getIndex();
        const char *fname = par("traceFile");
        ns2File = new Ns2MotionFile;
        parseFile(fname);
        vecpos = 0;
        WATCH(nodeId);
    }
}

void Ns2MotionMobility::initializePosition()
{
    lastPosition.x = ns2File->initial[0]+scrollX;
    lastPosition.y = ns2File->initial[1]+scrollY;
}

void Ns2MotionMobility::setTargetPosition()
{

    if (ns2File->lines.size()==0)
    {
        stationary = true;
        return;
    }

    if (vecpos >= ns2File->lines.size())
    {
        stationary = true;
        return;
    }

    if (ns2File->lines.begin()+vecpos == ns2File->lines.end())
    {
        stationary = true;
        return;
    }

    const Ns2MotionFile::Line& vec = ns2File->lines[vecpos];
    double time = vec[0];
    simtime_t now = simTime();
    // TODO: this code is dubious at best
    if (now < time)
    {
        nextChange = time;
        targetPosition = lastPosition;
    }
    else if (vec[3] == 0) // the node is stopped
    {
        const Ns2MotionFile::Line& vec = ns2File->lines[vecpos+1];
        double time = vec[0];
        nextChange = time;
        targetPosition = lastPosition;
        vecpos++;
    }
    else
    {
        targetPosition.x = vec[1]+scrollX;
        targetPosition.y = vec[2]+scrollY;
        double speed = vec[3];
        double distance = lastPosition.distance(targetPosition);
        double travelTime = distance / speed;
        nextChange = now + travelTime;
        vecpos++;
    }
    EV << "TARGET: t=" << nextChange << " (" << targetPosition.x << "," << targetPosition.y << ")\n";
}

void Ns2MotionMobility::move()
{
    LineSegmentsMobilityBase::move();
    raiseErrorIfOutside();
}


text:
  error_at_line(-(__LINE__), errno, __FILE__, __LINE__, fmt, ## __VA_ARGS__)

namespace {

enum InputFormat {
  HTML_ARCHIVE,
  SINGLE_HTML_DOCUMENT,
  DEFAULT_INPUT_FORMAT = HTML_ARCHIVE
};

enum {
  MIN_NUM_CHARS_THRESHOLD = nwc_toolkit::CetrDocument::MIN_NUM_CHARS_THRESHOLD,
  MAX_NUM_CHARS_THRESHOLD = 1 << 12,
  DEFAULT_NUM_CHARS_THRESHOLD =
      nwc_toolkit::CetrDocument::DEFAULT_NUM_CHARS_THRESHOLD
};

enum {
  MIN_WINDOW_SIZE = nwc_toolkit::CetrDocument::MIN_WINDOW_SIZE,
  MAX_WINDOW_SIZE = 16,
  DEFAULT_WINDOW_SIZE = nwc_toolkit::CetrDocument::DEFAULT_WINDOW_SIZE
};

enum {
  MIN_NUM_CLUSTERS = nwc_toolkit::CetrCluster::MIN_NUM_CLUSTERS,
  MAX_NUM_CLUSTERS = 16,
  DEFAULT_NUM_CLUSTERS = nwc_toolkit::CetrCluster::DEFAULT_NUM_CLUSTERS
};

enum OutputFormat {
  TEXT_DOCUMENT,
  XML_DOCUMENT,
  DEFAULT_OUTPUT_FORMAT = TEXT_DOCUMENT
};

InputFormat input_format = DEFAULT_INPUT_FORMAT;
int num_chars_threshold = DEFAULT_NUM_CHARS_THRESHOLD;
int window_size = DEFAULT_WINDOW_SIZE;
int num_clusters = DEFAULT_NUM_CLUSTERS;
OutputFormat output_format = DEFAULT_OUTPUT_FORMAT;
nwc_toolkit::String output_file_name;
bool is_help_mode = false;

int ParseIntegerValue(const char *arg, long min_value, long max_value) {
  char *end_of_value;
  long value = std::strtol(optarg, &end_of_value, 10);
  if (*end_of_value != '\0' || (value < min_value) || (value > max_value)) {
    return -1;
  }
  return static_cast<int>(value);
}

void ParseOptions(int argc, char *argv[]) {
  static const struct option long_options[] = {
    { "archive", 0, NULL, 'a' },
    { "single", 0, NULL, 's' },
    { "chars", 1, NULL, 'n' },
    { "window", 1, NULL, 'w' },
    { "clusters", 1, NULL, 'c' },
    { "text", 0, NULL, 't' },
    { "xml", 0, NULL, 'x' },
    { "output", 1, NULL, 'o' },
    { "help", 0, NULL, 'h' },
    { NULL, 0, NULL, '\0' }
  };

  int value;
  while ((value = ::getopt_long(argc, argv,
      "asn:w:c:txo:h", long_options, NULL)) != -1) {
    switch (value) {
      case 'a': {
        input_format = HTML_ARCHIVE;
        break;
      }
      case 's': {
        input_format = SINGLE_HTML_DOCUMENT;
        break;
      }
      case 'n': {
        num_chars_threshold = ParseIntegerValue(optarg,
            MIN_NUM_CHARS_THRESHOLD, MAX_NUM_CHARS_THRESHOLD);
        if (num_chars_threshold < 0) {
          NWC_TOOLKIT_ERROR("invalid argument: `%c', %s", value, optarg);
        }
        break;
      }
      case 'w': {
        window_size = ParseIntegerValue(optarg,
            MIN_WINDOW_SIZE, MAX_WINDOW_SIZE);
        if (window_size < 0) {
          NWC_TOOLKIT_ERROR("invalid argument: `%c', %s", value, optarg);
        }
        break;
      }
      case 'c': {
        num_clusters = ParseIntegerValue(optarg,
            MIN_NUM_CLUSTERS, MAX_NUM_CLUSTERS);
        if (num_clusters < 0) {
          NWC_TOOLKIT_ERROR("invalid argument: `%c', %s", value, optarg);
        }
        break;
      }
      case 't': {
        output_format = TEXT_DOCUMENT;
        break;
      }
      case 'x': {
        output_format = XML_DOCUMENT;
        break;
      }
      case 'o': {
        output_file_name = optarg;
        break;
      }
      case 'h': {
        is_help_mode = true;
        break;
      }
      default: {
        NWC_TOOLKIT_ERROR("invalid option");
      }
    }
  }
}

void PrintHelp(const char *command) {
  std::cerr << "Usage: " << command << " [OPTION]... [FILE]...\n\n"
      "Options:\n"
      "  -a, --archive  extract text from HTML archives (default)\n"
      "  -s, --single   extract text from HTML documents\n"
      "  -n, --chars=[N]      "
      "limit the number of chars in line to N (default: "
      << DEFAULT_NUM_CHARS_THRESHOLD << ")\n"
      "  -w, --window=[N]     "
      "limit the window size to N (default: "
      << DEFAULT_WINDOW_SIZE << ")\n"
      "  -c, --clusters=[N]   "
      "limit the number of clusters to N (default: "
      << DEFAULT_NUM_CLUSTERS << ")\n"
      "  -t, --text     output result in text-format (default)\n"
      "  -x, --xml      output result in xml-format\n"
      "  -o, --output=[FILE]  write result to FILE (default: stdout)\n"
      "  -h, --help     print this help\n"
      << std::flush;
}

void WriteXmlHeader(nwc_toolkit::OutputFile *output_file) {
  if (!output_file->Write(
      "<?xml version=\"1.0\" encoding=\"UTF-8\" standalone=\"yes\"?>\n"
      "<ResultSet>\n")) {
    NWC_TOOLKIT_ERROR("failed to write xml header");
  }
}

void WriteXmlFooter(nwc_toolkit::OutputFile *output_file) {
  if (!output_file->Write("</ResultSet>\n")) {
    NWC_TOOLKIT_ERROR("failed to write xml header");
  }
}

void GetLineTag(const nwc_toolkit::CetrDocument &doc,
    std::size_t line_id, nwc_toolkit::StringBuilder *result) {
  enum { MAX_LENGTH = 256 };
  result->Reserve(result->length() + MAX_LENGTH);
  int length = std::snprintf(result->buf() + result->length(), MAX_LENGTH,
      "<Line is_content=\"%s\" num_tags=\"%zd\" num_chars=\"%zd\""
      " tag_ratio=\"%f\" smoothed_tag_ratio=\"%f\""
      " derivate=\"%f\" smoothed_derivate=\"%f\">\n",
      (doc.is_content(line_id) ? "yes" : " no"),
      doc.line(line_id).num_tags(), doc.line(line_id).num_text_chars(),
      doc.tag_ratio(line_id), doc.smoothed_tag_ratio(line_id),
      doc.derivate(line_id), doc.smoothed_derivate(line_id));
  if ((length < 0) || (length >= MAX_LENGTH)) {
    NWC_TOOLKIT_ERROR("too long line tag");
  }
  result->Resize(result->length() + length);
}

void GetXmlResult(const nwc_toolkit::CetrDocument &doc,
    nwc_toolkit::StringBuilder *result) {
  result->Append("<Result>\n");
  for (std::size_t i = 0; i < doc.num_lines(); ++i) {
    GetLineTag(doc, i, result);
    const nwc_toolkit::CetrLine &line = doc.line(i);
    for (std::size_t j = 0; j < line.num_units(); ++j) {
      const nwc_toolkit::CetrUnit &unit = line.unit(j);
      result->Append("<Unit type=\"");
      switch (unit.type()) {
        case nwc_toolkit::CetrUnit::TAG_UNIT: {
          result->Append("tag");
          break;
        }
        case nwc_toolkit::CetrUnit::TEXT_UNIT: {
          result->Append("text");
          break;
        }
        case nwc_toolkit::CetrUnit::INVISIBLE_UNIT: {
          result->Append("invisible");
          break;
        }
        default: {
          NWC_TOOLKIT_ERROR("invalid unit type: %d", unit.type());
        }
      }
      result->Append("\">");
      nwc_toolkit::CharacterReference::Encode(unit.content(), result);
      result->Append("</Unit>\n");
    }
    result->Append("</Line>\n");
  }
  result->Append("</Result>\n");
}

void AppendByteToTextResult(char byte, nwc_toolkit::StringBuilder *result) {
  if (nwc_toolkit::IsSpace()(byte)) {
    // Successive white-spaces are replaced with a single white-space or
    // end-of-line mark.
    char last_byte = !result->is_empty()
        ? ((*result)[result->length() - 1]) : '\n';
    if ((byte == '\r') || (byte == '\n')) {
      if (!nwc_toolkit::IsSpace()(last_byte)) {
        result->Append('\n');
      } else if (last_byte != '\n') {
        (*result)[result->length() - 1] = '\n';
      }
    } else if (!nwc_toolkit::IsSpace()(last_byte)) {
      result->Append(' ');
    }
  } else {
    result->Append(byte);
  }
}

void GetTextResult(const nwc_toolkit::CetrDocument &doc,
    nwc_toolkit::StringBuilder *result) {
  for (std::size_t i = 0; i < doc.num_lines(); ++i) {
    if (!doc.is_content(i)) {
      continue;
    }
    const nwc_toolkit::CetrLine &line = doc.line(i);
    for (std::size_t j = 0; j < line.num_units(); ++j) {
      const nwc_toolkit::CetrUnit &unit = line.unit(j);
      if (unit.type() == nwc_toolkit::CetrUnit::TEXT_UNIT) {
        const nwc_toolkit::String &text = unit.content();
        for (std::size_t i = 0; i < text.length(); ++i) {
          AppendByteToTextResult(text[i], result);
        }
      }
    }
  }
  AppendByteToTextResult('\n', result);
  result->Append('\n');
}

void GetResult(const nwc_toolkit::CetrDocument &doc,
    nwc_toolkit::StringBuilder *result) {
  switch (output_format) {
    case TEXT_DOCUMENT: {
      GetTextResult(doc, result);
      break;
    }
    case XML_DOCUMENT: {
      GetXmlResult(doc, result);
      break;
    }
    default: {
      NWC_TOOLKIT_ERROR("invalid output format");
    }
  }
}

void ExtractContentsFromHtmlArchvie(nwc_toolkit::InputFile *input_file,
    nwc_toolkit::OutputFile *output_file) {
  std::time_t start_time = std::time(NULL);

  nwc_toolkit::HtmlDocument html_doc;
  nwc_toolkit::CetrDocument cetr_doc;
  nwc_toolkit::StringBuilder result;

  long long num_entries = 0;
  long long status_error_count = 0;
  long long parse_error_count = 0;
  nwc_toolkit::HtmlArchiveEntry entry;
  while (entry.Read(input_file)) {
    html_doc.Clear();
    cetr_doc.Clear();
    result.Clear();

    if (entry.status_code() != 200) {
      ++status_error_count;
    } else if (!html_doc.Parse(entry)) {
      ++parse_error_count;
    } else {
      cetr_doc.Parse(html_doc);
    }

    GetResult(cetr_doc, &result);
    if (!output_file->Write(result.str())) {
      NWC_TOOLKIT_ERROR("failed to write result");
    }

    if ((++num_entries % 100) == 0) {
      std::cerr << '\r' << status_error_count << " ("
          << std::fixed << std::setw(5) << std::setprecision(2)
          << (100.0 * status_error_count / num_entries)
          << "%) / " << parse_error_count << " ("
          << std::fixed << std::setw(5) << std::setprecision(2)
          << (100.0 * parse_error_count / num_entries)
          << "%) / " << num_entries
          << " (" << (std::time(NULL) - start_time) << "sec)";
    }
  }
  std::cerr << '\r' << status_error_count << " ("
      << std::fixed << std::setw(5) << std::setprecision(2)
      << ((num_entries != 0) ? (100.0 * status_error_count / num_entries) : 0.0)
      << "%) / " << parse_error_count << " ("
      << std::fixed << std::setw(5) << std::setprecision(2)
      << ((num_entries != 0) ? (100.0 * parse_error_count / num_entries) : 0.0)
      << "%) / " << num_entries
      << " (" << (std::time(NULL) - start_time) << "sec)" << std::endl;
}

void ExtractContentsFromSingleHtmlDocument(nwc_toolkit::InputFile *input_file,
    nwc_toolkit::OutputFile *output_file) {
  nwc_toolkit::String line;
  nwc_toolkit::StringBuilder body;
  while (input_file->ReadLine(&line)) {
    body.Append(line);
  }

  nwc_toolkit::HtmlDocument html_doc;
  if (!html_doc.Parse(body.str())) {
    NWC_TOOLKIT_ERROR("failed to parse html document");
  }

  nwc_toolkit::CetrDocument cetr_doc;
  cetr_doc.Parse(html_doc);

  nwc_toolkit::StringBuilder result;
  GetResult(cetr_doc, &result);
  if (!output_file->Write(result.str())) {
    NWC_TOOLKIT_ERROR("failed to write result");
  }
}

void ExtractContents(nwc_toolkit::InputFile *input_file,
    nwc_toolkit::OutputFile *output_file) {
  switch (output_format) {
    case TEXT_DOCUMENT: {
      break;
    }
    case XML_DOCUMENT: {
      WriteXmlHeader(output_file);
      break;
    }
    default: {
      NWC_TOOLKIT_ERROR("invalid output format");
    }
  }

  switch (input_format) {
    case HTML_ARCHIVE: {
      ExtractContentsFromHtmlArchvie(input_file, output_file);
      break;
    }
    case SINGLE_HTML_DOCUMENT: {
      ExtractContentsFromSingleHtmlDocument(input_file, output_file);
      break;
    }
    default: {
      NWC_TOOLKIT_ERROR("invalid input format");
    }
  }

  if (output_format == XML_DOCUMENT) {
    WriteXmlFooter(output_file);
  }
}

}  // namespace

int main(int argc, char *argv[]) {
  ParseOptions(argc, argv);
  if (is_help_mode) {
    PrintHelp(argv[0]);
    return 0;
  }

  nwc_toolkit::OutputFile output_file;
  std::cerr << "output: " << (output_file_name.is_empty()
      ? "(standard output)" : output_file_name) << std::endl;
  if (!output_file.Open(output_file_name)) {
    NWC_TOOLKIT_ERROR("failed to open output file: %s",
        output_file_name.ptr());
  }

  if (optind == argc) {
    nwc_toolkit::InputFile input_file;
    std::cerr << "input: (standard input)" << std::endl;
    if (!input_file.Open(NULL)) {
      NWC_TOOLKIT_ERROR("failed to open standard input");
    }
    ExtractContents(&input_file, &output_file);
  }

  for (int i = optind; i < argc; ++i) {
    nwc_toolkit::String input_file_name = argv[i];
    std::cerr << "input: " << (input_file_name.is_empty()
        ? "(standard input)" : input_file_name) << std::endl;
    nwc_toolkit::InputFile input_file;
    if (!input_file.Open(input_file_name)) {
      NWC_TOOLKIT_ERROR("failed to open input file: %s",
          input_file_name.ptr());
    }
    ExtractContents(&input_file, &output_file);
  }

  return 0;
}


text:
var List = require('mongoose').model('List'),
	Card = require('mongoose').model('Card');

module.exports = function() {
	List
		.find({})
		.exec(function(err, collection) {
			if (collection.length == 0) {
				List.create({ title: 'To Do', cardLimit: 0, position: 1 }, function(err, todo) {
					Card.create({ title: 'Task 1', listId: todo._id, position:1 });
					Card.create({ title: 'Task 2', listId: todo._id, position:2 });
				});
				List.create({ title: 'Doing', cardLimit: 3, position: 2 }, function(err, doing) {
					Card.create({ title: 'Task 3', description: 'This task has a description', listId: doing._id, position:1 });
					Card.create({ title: 'Task 4', listId: doing._id, priority: 'high', position:2 });
					Card.create({ title: 'Task 5', listId: doing._id, position:3 });
				});
				List.create({ title: 'Done', cardLimit: 0, position: 3 });
			}
		});
};


text:
"""
This file is part of the PSL software.
Copyright 2011-2015 University of Maryland
Copyright 2013-2022 The Regents of the University of California

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.
"""

import shutil
import sys

from pslpython import model
from pslpython import util

def main(argv):
    command = [
        shutil.which('java'),
        '-jar',
        model.Model.CLI_JAR_PATH,
    ]
    command += argv

    exit_status = util.execute(command)
    if (exit_status != 0):
        sys.exit(1)

    sys.exit(0)

if (__name__ == '__main__'):
    main(sys.argv[1:])


text:
var storageTenantJobApi = require('../../monitor/tenant-storage/jobs/storage.tenant.jobs.js');
var storageInfraJobApi = require('../../monitor/storage-infra/jobs/storage.infra.jobs.js');
var jobsProcess = module.exports;

jobsProcess.processStorageClusterStatusRequestByJob =
    function(pubChannel, saveChannelKey, jobData, done) {
    storageTenantJobApi.processStorageClusterStatus(pubChannel, saveChannelKey, jobData, done);
}

jobsProcess.processStorageOSDsSummaryRequestByJob =
    function(pubChannel, saveChannelKey, jobData, done) {
    storageTenantJobApi.processStorageOSDsSummaryRequestByJob(pubChannel, saveChannelKey, jobData, done);
}

jobsProcess.processStorageOSDsTreeRequestByJob =
    function(pubChannel, saveChannelKey, jobData, done) {
        storageTenantJobApi.processStorageOSDsTreeRequestByJob(pubChannel, saveChannelKey, jobData, done);
    }

jobsProcess.processStorageSummaryRequestByJob =
    function(pubChannel, saveChannelKey, jobData, done) {
        storageInfraJobApi.processStorageSummaryRequestByJob(pubChannel, saveChannelKey, jobData, done);
    }


text:
using MongoDB.Driver;

namespace ASaed.Poc.MongoDb.Data.ioc
{
    public class MongoConnectionFactory
    {
        public static MongoDatabase GetMongoDatabase()
        {
            var mongoClientSettings = new MongoClientSettings();
            mongoClientSettings.Credentials = new[] { MongoCredential.CreateCredential(AppSettings.MongoDbCredentialDb, AppSettings.MongoDbCredentialUserName, AppSettings.MongoDbCredentialPassword) };
            mongoClientSettings.Server = new MongoServerAddress(AppSettings.MongoDbHostName, AppSettings.MongoDbHostPort);

            var mongoClient = new MongoClient(mongoClientSettings);

            return mongoClient.GetServer().GetDatabase(AppSettings.MongoDbDatabaseName);
        }
    }
}


text:
export LC_ALL=C.UTF-8

export HOST=arm-linux-gnueabihf
# The host arch is unknown, so we run the tests through qemu.
# If the host is arm and wants to run the tests natively, it can set QEMU_USER_CMD to the empty string.
if [ -z ${QEMU_USER_CMD+x} ]; then export QEMU_USER_CMD="${QEMU_USER_CMD:-"qemu-arm -L /usr/arm-linux-gnueabihf/"}"; fi
export DPKG_ADD_ARCH="armhf"
export PACKAGES="python3-zmq g++-arm-linux-gnueabihf busybox libc6:armhf libstdc++6:armhf libfontconfig1:armhf libxcb1:armhf"
if [ -n "$QEMU_USER_CMD" ]; then
  # Likely cross-compiling, so install the needed gcc and qemu-user
  export PACKAGES="$PACKAGES qemu-user"
fi
export CONTAINER_NAME=ci_arm_linux
# Use debian to avoid 404 apt errors when cross compiling
export DOCKER_NAME_TAG="debian:bullseye"
export USE_BUSY_BOX=true
export RUN_UNIT_TESTS=true
export RUN_FUNCTIONAL_TESTS=false
export GOAL="install"
# -Wno-psabi is to disable ABI warnings: "note: parameter passing for argument of type ... changed in GCC 7.1"
# This could be removed once the ABI change warning does not show up by default
export BITCOIN_CONFIG="--enable-reduce-exports CXXFLAGS=-Wno-psabi"


text:
'use strict';

function AuthError(message, status) {
  this.name = 'AuthError';
  this.message = message;
  this.status = status;
}

function DrinkError(message, status) {
  this.name = 'DrinkError';
  this.message = message;
  this.status = status;
}

function DrinksError(message, status) {
  this.name = 'DrinksError';
  this.message = message;
  this.status = status;
}

function UserError(message, status) {
  this.name = 'UserError';
  this.message = message;
  this.status = status;
}

AuthError.prototype = Object.create(Error.prototype);
AuthError.prototype.constructor = AuthError;

DrinkError.prototype = Object.create(Error.prototype);
DrinkError.prototype.constructor = DrinkError;

DrinksError.prototype = Object.create(Error.prototype);
DrinksError.prototype.constructor = DrinksError;

UserError.prototype = Object.create(Error.prototype);
UserError.prototype.constructor = UserError;

module.exports = {
  AuthError: AuthError,
  DrinkError: DrinkError,
  DrinksError: DrinksError,
  UserError: UserError
};


text:
using System.Text.Json;
using Azure.Core;

namespace Azure.ResourceManager.Workloads.Models
{
    public partial class SapDiskConfiguration
    {
        internal static SapDiskConfiguration DeserializeSapDiskConfiguration(JsonElement element)
        {
            Optional<string> volume = default;
            Optional<string> diskType = default;
            Optional<long> diskCount = default;
            Optional<long> diskSizeGB = default;
            Optional<long> diskIopsReadWrite = default;
            Optional<long> diskMBpsReadWrite = default;
            Optional<string> diskStorageType = default;
            foreach (var property in element.EnumerateObject())
            {
                if (property.NameEquals("volume"))
                {
                    volume = property.Value.GetString();
                    continue;
                }
                if (property.NameEquals("diskType"))
                {
                    diskType = property.Value.GetString();
                    continue;
                }
                if (property.NameEquals("diskCount"))
                {
                    if (property.Value.ValueKind == JsonValueKind.Null)
                    {
                        property.ThrowNonNullablePropertyIsNull();
                        continue;
                    }
                    diskCount = property.Value.GetInt64();
                    continue;
                }
                if (property.NameEquals("diskSizeGB"))
                {
                    if (property.Value.ValueKind == JsonValueKind.Null)
                    {
                        property.ThrowNonNullablePropertyIsNull();
                        continue;
                    }
                    diskSizeGB = property.Value.GetInt64();
                    continue;
                }
                if (property.NameEquals("diskIopsReadWrite"))
                {
                    if (property.Value.ValueKind == JsonValueKind.Null)
                    {
                        property.ThrowNonNullablePropertyIsNull();
                        continue;
                    }
                    diskIopsReadWrite = property.Value.GetInt64();
                    continue;
                }
                if (property.NameEquals("diskMBpsReadWrite"))
                {
                    if (property.Value.ValueKind == JsonValueKind.Null)
                    {
                        property.ThrowNonNullablePropertyIsNull();
                        continue;
                    }
                    diskMBpsReadWrite = property.Value.GetInt64();
                    continue;
                }
                if (property.NameEquals("diskStorageType"))
                {
                    diskStorageType = property.Value.GetString();
                    continue;
                }
            }
            return new SapDiskConfiguration(volume.Value, diskType.Value, Optional.ToNullable(diskCount), Optional.ToNullable(diskSizeGB), Optional.ToNullable(diskIopsReadWrite), Optional.ToNullable(diskMBpsReadWrite), diskStorageType.Value);
        }
    }
}


text:
<?php $this->load->view('inc/html-head'); ?>
	<?php $this->load->view('inc/header'); ?>

			<?php $this->load->view('inc/sidebar'); ?>

<?php echo lang('create_group_heading');?>

<?php echo lang('create_group_subheading');?>

					<?php if (isset($message) && $message): ?>

<?php echo $message;?>

                    <?php endif ?>
                    <?php echo form_open("users/create_group");?>

                            <?php echo lang('create_group_name_label', 'group_name');?>
                            <?php echo form_input($group_name, FALSE, 'class="form-control"');?>

                            <?php echo lang('create_group_desc_label', 'description');?>
                            <?php echo form_input($description, FALSE, 'class="form-control"');?>

                            <?php echo form_submit('submit', lang('create_group_submit_btn'), 'class="btn btn-primary"');?>

                    <?php echo form_close();?>

    <?php $this->load->view('inc/footer'); ?>
<?php $this->load->view('inc/html-footer'); ?>


text:
/**
 * Created by Ascarbek on 01.12.2015.
 */
var connect = require('connect');
var serveStatic = require('serve-static');
var path = require('path');
var envConfig = require('./env.config.json');

connect().use(serveStatic(path.resolve(__dirname, '..', envConfig.envDir) )).listen(8085);
console.log('server listening at port 8085');
console.log('demo page available at http://localhost:8085/demo.html');


text:
class ApplicationHelper::Button::Pdf < ApplicationHelper::Button::Basic
  def skip?
    !PdfGenerator.available?
  end
end


text:
<android.support.v7.widget.CardView
    xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    app:cardCornerRadius="8dip"
    app:contentPadding="10dip"
    android:layout_margin="5dp">
    <TextView
        android:id="@+id/textview"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"/>
</android.support.v7.widget.CardView>


text:
<!DOCTYPE html>

        <meta charset="utf-8">
        <meta name="viewport" content="width=device-width, initial-scale=1.0">
        <meta name="description" content="A fully featured admin theme which can be used to build CRM, CMS, etc.">
        <meta name="author" content="Coderthemes">

        <link rel="shortcut icon" href="assets/images/favicon.ico">

        <title>Adminto - Responsive Admin Dashboard Template</title>

        <link href="assets/css/bootstrap.min.css" rel="stylesheet" type="text/css" />
        <link href="assets/css/core.css" rel="stylesheet" type="text/css" />
        <link href="assets/css/components.css" rel="stylesheet" type="text/css" />
        <link href="assets/css/icons.css" rel="stylesheet" type="text/css" />
        <link href="assets/css/pages.css" rel="stylesheet" type="text/css" />
        <link href="assets/css/menu.css" rel="stylesheet" type="text/css" />
        <link href="assets/css/responsive.css" rel="stylesheet" type="text/css" />

Coming Soon

Days

Hours

Minutes

Seconds


text:
'use strict';

var blogApp = angular.module('blogApp');

blogApp.controller('EditCtrl', function ($scope, $http, $state, $sce, $stateParams, $timeout, Story, PreviousState) {
    var id = $stateParams.id;
    $scope.story = {};
    Story.getStory(id).then(function(story) {
        $scope.story = story;
    }, function(err) {
        console.error(err);
    });
    $scope.story.date = $scope.story.date || new Date();
    $scope.media = {};
    var initialized = false;

    $timeout(function() {
        initialized = true;
    }, 500);

    $scope.$watch(function() {
        if (!$scope.story.content) {
            return 0;
        }
        var matches = $scope.story.content.match(/{image\d+}/g) || [];
        return matches.length;
    }, function(newValue, oldValue) {
        if (newValue < oldValue) {
            $scope.story.media.images.pop();
        } else if (newValue > 0 && initialized) {
            $scope.story.media.images.push('image' + newValue);
        }
    });

    $scope.$watch(function() {
        if (!$scope.story.content) {
            return 0;
        }
        var matches = $scope.story.content.match(/{video\d+}/g) || [];
        return matches.length;
    }, function(newValue, oldValue) {
        if (newValue < oldValue) {
            $scope.story.media.videos.pop();
        } else if (newValue > 0 && initialized) {
            $scope.story.media.videos.push('video' + newValue);
        }
    });

    $http.get('/api/media').success(function(response) {
        $scope.media = response;
    });

    $scope.today = function() {
        $scope.date = new Date();
    };

    $scope.open = function($event) {
        $event.preventDefault();
        $event.stopPropagation();

        $scope.opened = true;
    };

    $scope.dateOptions = {
        showWeeks: 'false',
        startingDay: 1
    };

    $scope.send = function() {
        $http.put('/api/stories/' + id, $scope.story).success(function() {
            Story.setStory($scope.story);
            var previousState = PreviousState.get();
            if (previousState.name === 'detail') {
                $state.go('detail', PreviousState.params());
            } else {
                $state.go('main');
            }
        }).error(function(response) {
            console.log(response);
        });
    };

    $scope.uploadFiles = function() {
        Story.setStory($scope.story);
        $state.go('upload');
    };

    $scope.trustAsHtml = function(value) {
        if (value) {
            return $sce.trustAsHtml(value.toString());
        } else {
            return '';
        }
    };

    $('#send').text('Edytuj wpis');
});

blogApp.config(function(uiSelectConfig) {
    uiSelectConfig.theme = 'bootstrap';
});


text:
using System;
using Nest.Resolvers.Converters;
using Newtonsoft.Json;

namespace Nest
{
	[JsonConverter(typeof(CustomJsonConverter))]
	public class FilterAggregationDescriptor<T>
		: BucketAggregationBaseDescriptor<FilterAggregationDescriptor<T>, T>
		, ICustomJson
		where T : class
	{
		internal BaseFilter _Filter { get; set; }

		public FilterAggregationDescriptor<T> Filter(Func<FilterDescriptor<T>, BaseFilter> selector)
		{
			this._Filter = selector(new FilterDescriptor<T>());
			return this;
		}

		object ICustomJson.GetCustomJson()
		{
			return _Filter;
		}
	}
}


text:
'use strict';

var SolveBio = require('../src/solvebio');

describe('Tests filters', function() {
  beforeEach(function() {
    SolveBio.init({
      debug: true,
      accessToken: 'fakeToken'
    });
  });

  it('should create a single filter', function() {
    var filter = SolveBio.Filter({
      rcv_accession: 'RCV000058095'
    });
    expect(filter.filters).toEqual(['rcv_accession', 'RCV000058095']);
  });

  it('should create an and filter', function() {
    var filter = SolveBio.Filter({
      rcv_accession: 'RCV000058095',
      clinical_significance: 'Pathogenic'
    });
    expect(filter.filters).toEqual({
      and: [
        ['rcv_accession', 'RCV000058095'],
        ['clinical_significance', 'Pathogenic']
      ]
    });
  });

  it('should combine filters with all()', function() {
    var filter1 = SolveBio.Filter({
      gene_symbol: 'BRCA1'
    });
    var filter2 = SolveBio.Filter({
      clinical_significance: 'Pathogenic'
    });
    expect(filter1.and(filter2).filters).toEqual({
      and: [
        ['gene_symbol', 'BRCA1'],
        ['clinical_significance', 'Pathogenic']
      ]
    });
  });

  it('should combine filters with or()', function() {
    var filter1 = SolveBio.Filter({
      gene_symbol: 'BRCA1'
    });
    var filter2 = SolveBio.Filter({
      gene_symbol: 'BRCA2'
    });
    expect(filter1.or(filter2).filters).toEqual({
      or: [
        ['gene_symbol', 'BRCA1'],
        ['gene_symbol', 'BRCA2']
      ]
    });
  });

  it('should support nested filters', function() {
    var filter1 = SolveBio.Filter({
      gene_symbol: 'BRCA1'
    });
    var filter2 = SolveBio.Filter({
      gene_symbol: 'BRCA2'
    });
    var filter3 = SolveBio.Filter({
      clinical_significance: 'Pathogenic'
    });
    expect(filter1.or(filter2.and(filter3)).filters).toEqual({
      or: [
        ['gene_symbol', 'BRCA1'],
        {
          and: [
            ['gene_symbol', 'BRCA2'],
            ['clinical_significance', 'Pathogenic']
          ]
        }
      ]
    });
  });

  it('should inverse a filter', function() {
    var filter = SolveBio.Filter({
      gene_symbol: 'BRCA1'
    });
    expect(filter.not().filters).toEqual({
      not: ['gene_symbol', 'BRCA1']
    });
  });
});


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

import javax.annotation.Generated;

/**
 *
 */
@Generated("com.amazonaws:aws-java-sdk-code-generator")
public enum AccessDirection {

    Inbound("inbound"),
    Outbound("outbound");

    private String value;

    private AccessDirection(String value) {
        this.value = value;
    }

    @Override
    public String toString() {
        return this.value;
    }

    /**
     * Use this in place of valueOf.
     *
     * @param value
     *        real value
     * @return AccessDirection corresponding to the value
     *
     * @throws IllegalArgumentException
     *         If the specified value does not map to one of the known values in this enum.
     */
    public static AccessDirection fromValue(String value) {
        if (value == null || "".equals(value)) {
            throw new IllegalArgumentException("Value cannot be null or empty!");
        }

        for (AccessDirection enumEntry : AccessDirection.values()) {
            if (enumEntry.toString().equals(value)) {
                return enumEntry;
            }
        }

        throw new IllegalArgumentException("Cannot create enum from " + value + " value!");
    }
}


text:
"""
Created on 2015/02/04
@author: Jimmy Liu
@group : waditu
@contact: jimmysoa@sina.cn
"""
import pandas as pd
import tushare as ts
from pandas import compat
import os

class Store(object):

    def __init__(self, data=None, name=None, path=None):
        if isinstance(data, pd.DataFrame):
            self.data = data
        else:
            raise RuntimeError('data type is incorrect')
        self.name = name
        self.path = path

    def save_as(self, name, path, to='csv'):
        if name is None:
            name = self.name
        if path is None:
            path = self.path
        file_path = '%s%s%s.%s'
        if isinstance(name, compat.string_types) and name is not '':
            if (path is None) or (path == ''):
                file_path = '.'.join([name, to])
            else:
                try:
                    if os.path.exists(path) is False:
                        os.mkdir(path)
                    file_path = file_path%(path, '/', name, to)
                except:
                    pass

        else:
            print('input error')


text:
import React from 'react';
import { Route, IndexRoute } from 'react-router';

import About from './about/About';
import Adventures from './adventures/Adventures';
import Main from './main/Main';
import Signup from './signup/Signup';

const routes = (
  <Route path="/" component={Main}>
    <IndexRoute component={Signup} />
    <Route path="about" component={About} />
    <Route path="adventures" component={Adventures} />
    <Route path="signup" component={Signup} />
  </Route>
);

export default routes;


text:
package main

import (
	"runtime"
	"testing"

	"testlib"
	glfw "github.com/go-gl/glfw3"
	"github.com/remogatto/mandala"
	"github.com/remogatto/prettytest"
)

const (
	Width      = 320
	Height     = 240
	outputPath = "output"
)

func main() {
	runtime.LockOSThread()
	defer runtime.UnlockOSThread()
	defer glfw.Terminate()

	mandala.Verbose = true

	if !glfw.Init() {
		panic("Can't init glfw!")
	}

	// Enable OpenGL ES 2.0.
	glfw.WindowHint(glfw.ClientApi, glfw.OpenglEsApi)
	glfw.WindowHint(glfw.ContextVersionMajor, 2)
	window, err := glfw.CreateWindow(Width, Height, "Shapes black-box testing", nil, nil)
	if err != nil {
		panic(err)
	}

	glfw.SwapInterval(0)

	mandala.Init(window)

	go prettytest.Run(new(testing.T), testlib.NewTestSuite(outputPath))

	for !window.ShouldClose() {
		glfw.WaitEvents()
	}
}


text:
extern const NSUInteger RACReplaySubjectUnlimitedCapacity;

// A replay subject saves the values it is sent (up to its defined capacity)
// and resends those to new subscribers. It will also replay an error or
// completion.
@interface RACReplaySubject : RACSubject

// Creates a new replay subject with the given capacity. A capacity of
// RACReplaySubjectUnlimitedCapacity means values are never trimmed.
+ (instancetype)replaySubjectWithCapacity:(NSUInteger)capacity;

@end


text:
//*****************************************************************************/
// Copyright (c) 1998-2006 Autodesk, Inc.
// All rights reserved.
//
// These coded instructions, statements, and computer programs contain
// unpublished proprietary information written by Autodesk, Inc., and are
// protected by Federal copyright law. They may not be disclosed to third
// parties or copied or duplicated in any form, in whole or in part, without
// the prior written consent of Autodesk, Inc.
//*****************************************************************************/
/*==============================================================================

  file:     imrTranslation.h

  author:   Daniel Levesque

  created:  16 Feb 2006

  description:

    Defition of the central mental ray translation interface

  modified:

==============================================================================*/
#pragma once

#include "..\baseinterface.h"
#include "..\maxtypes.h"

// Forward declarations
class INode;
class Box3;
class Interval;

//==============================================================================
// class imrTranslation
//
//! \brief Access interface for the mental ray translator.
/*!	This interface is the access point for the mental ray translator. Any
	functionality that needs to be exposed to various mental ray API classes
	is exposed through this.
*/
class imrTranslation : public InterfaceServer {

public:

	//! \brief Calculates and returns the bounding box of every object to be rendered,
	//! in the object space of a given node.
	/*!	Implements a caching mechanism to avoid re-calculating the same bounding box
		multiple times during the same render operation. The calculated bounding box
		only includes objects to be rendered.
		\param[in] t - The time at which the bounding box is to be calculated.
		\param[in] nodeForSpace - The bounding box is calculated in the object space
		of this node. Pass NULL in order to calculate the bounding box in world space.
		\param[out] sceneBox - Return value for the calculated bounding box.
		\param[inout] valid - Modified validity interval; intersected with the validity
		interval of the scene.
	*/
	virtual void CalculateSceneBoundingBox(TimeValue t, INode* nodeForSpace, Box3& sceneBox, Interval& valid) = 0;
};


text:
package app.frames;

public class TelaConsole extends javax.swing.JFrame {

    /**
     * Creates new form TelaConsole
     */
    public TelaConsole() {
        initComponents();
    }

    /**
     * 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() {

        jScrollPane1 = new javax.swing.JScrollPane();
        jTextArea1 = new javax.swing.JTextArea();

        setDefaultCloseOperation(javax.swing.WindowConstants.DISPOSE_ON_CLOSE);
        setTitle("ConsoleChat");
        setResizable(false);

        jTextArea1.setEditable(false);
        jTextArea1.setColumns(20);
        jTextArea1.setLineWrap(true);
        jTextArea1.setRows(5);
        jTextArea1.setWrapStyleWord(true);
        jScrollPane1.setViewportView(jTextArea1);

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
        getContentPane().setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addComponent(jScrollPane1, javax.swing.GroupLayout.DEFAULT_SIZE, 527, Short.MAX_VALUE)
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addComponent(jScrollPane1, javax.swing.GroupLayout.DEFAULT_SIZE, 300, Short.MAX_VALUE)
        );

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

    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JScrollPane jScrollPane1;
    public javax.swing.JTextArea jTextArea1;
    // End of variables declaration//GEN-END:variables
}


text:
class BadgesController < ApplicationController
  before_action :require_admin
  before_action :set_badge, only: [:show, :edit, :update, :destroy]

  layout 'admin'

  def index
    @badges = Badge.all
  end

  def show
  end

  def new
    @badge = Badge.new
  end

  def edit
  end

  def create
    @badge = Badge.new(badge_params)

    respond_to do |format|
      if @badge.save
        format.html { redirect_to badges_path, notice: 'Badge creado exitosamente.' }
        format.json { render :show, status: :created, location: @badge }
      else
        format.html { render :new }
        format.json { render json: @badge.errors, status: :unprocessable_entity }
      end
    end
  end

  def update
    respond_to do |format|
      if @badge.update(badge_params)
        format.html { redirect_to badges_path, notice: 'Badge actualizado exitosamente.' }
        format.json { render :show, status: :ok, location: @badge }
      else
        format.html { render :edit }
        format.json { render json: @badge.errors, status: :unprocessable_entity }
      end
    end
  end

  def destroy
    @badge.destroy
    respond_to do |format|
      format.html { redirect_to badges_url, notice: 'Badge was successfully destroyed.' }
      format.json { head :no_content }
    end
  end

  private
    def set_badge
      @badge = Badge.find(params[:id])
    end

    def badge_params
      params.require(:badge).permit(:name,:image,:points)
    end
end


text:
package com.jakduk.api.auth;

import com.jakduk.api.TestMvcConfig;
import com.jakduk.api.common.Constants;
import com.jakduk.api.common.util.AuthUtils;
import com.jakduk.api.common.util.ObjectMapperUtils;
import com.jakduk.api.configuration.security.JakdukAuthority;
import com.jakduk.api.mock.WithMockJakdukUser;
import com.jakduk.api.model.db.FootballClub;
import com.jakduk.api.model.db.FootballClubOrigin;
import com.jakduk.api.model.db.User;
import com.jakduk.api.model.embedded.LocalName;
import com.jakduk.api.repository.user.UserRepository;
import com.jakduk.api.restcontroller.AuthRestController;
import com.jakduk.api.restcontroller.vo.EmptyJsonResponse;
import com.jakduk.api.restcontroller.vo.user.AttemptSocialUser;
import com.jakduk.api.restcontroller.vo.user.LoginSocialUserForm;
import com.jakduk.api.restcontroller.vo.user.SessionUser;
import com.jakduk.api.restcontroller.vo.user.SocialProfile;
import com.jakduk.api.service.UserService;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.autoconfigure.restdocs.AutoConfigureRestDocs;
import org.springframework.boot.test.autoconfigure.web.servlet.WebMvcTest;
import org.springframework.boot.test.mock.mockito.MockBean;
import org.springframework.context.annotation.Import;
import org.springframework.http.MediaType;
import org.springframework.restdocs.constraints.ConstraintDescriptions;
import org.springframework.restdocs.payload.JsonFieldType;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.test.context.support.WithAnonymousUser;
import org.springframework.security.test.context.support.WithMockUser;
import org.springframework.test.context.junit4.SpringRunner;
import org.springframework.test.web.servlet.MockMvc;

import javax.servlet.http.Cookie;
import java.time.LocalDateTime;
import java.util.*;
import java.util.stream.Collectors;
import java.util.stream.Stream;

import static org.mockito.ArgumentMatchers.any;
import static org.mockito.ArgumentMatchers.anyString;
import static org.mockito.Mockito.when;
import static org.springframework.restdocs.headers.HeaderDocumentation.*;
import static org.springframework.restdocs.mockmvc.MockMvcRestDocumentation.document;
import static org.springframework.restdocs.mockmvc.RestDocumentationRequestBuilders.get;
import static org.springframework.restdocs.mockmvc.RestDocumentationRequestBuilders.post;
import static org.springframework.restdocs.payload.PayloadDocumentation.*;
import static org.springframework.restdocs.request.RequestDocumentation.*;
import static org.springframework.security.test.web.servlet.request.SecurityMockMvcRequestPostProcessors.csrf;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.content;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status;

@RunWith(SpringRunner.class)
@WebMvcTest({AuthRestController.class})
@Import({TestMvcConfig.class})
@AutoConfigureRestDocs(outputDir = "build/snippets")
public class AuthMvcTests {

    @Autowired
    private MockMvc mvc;

    @MockBean private UserService userService;
    @MockBean private AuthUtils authUtils;
    @MockBean private UserRepository userRepository;

    @MockBean private AuthenticationManager authenticationManager;

    private SocialProfile socialProfile;
    private Constants.ACCOUNT_TYPE providerId;
    private FootballClub footballClub;
    private User jakdukUser;

    @Before
    public void setup() {

        providerId = Constants.ACCOUNT_TYPE.FACEBOOK;

        socialProfile = new SocialProfile();
        socialProfile.setId("abc123");
        socialProfile.setNickname("daumUser01");
        socialProfile.setEmail("test17@test.com");
        socialProfile.setPictureUrl("https://img1.daumcdn.net/thumb/R158x158/?fname=http%3A%2F%2Ftwg.tset.daumcdn.net%2Fprofile%2F6enovyMT1pI0&t=1507478752861");

        FootballClubOrigin footballClubOrigin = new FootballClubOrigin();
        footballClubOrigin.setId("54e1d2a58bf86df3fe819871");
        footballClubOrigin.setName("SEONGNAM");
        footballClubOrigin.setClubType(Constants.CLUB_TYPE.FOOTBALL_CLUB);
        footballClubOrigin.setAge(Constants.CLUB_AGE.SENIOR);
        footballClubOrigin.setSex(Constants.CLUB_SEX.MEN);

        footballClub = new FootballClub();
        footballClub.setId("54e1d2c68bf86df3fe819874");
        footballClub.setOrigin(footballClubOrigin);
        footballClub.setActive("active");
        footballClub.setNames(
                Arrays.asList(
                        new LocalName(Locale.KOREAN.getLanguage(), "성남FC", "성남"),
                        new LocalName(Locale.ENGLISH.getLanguage(), "SEONGNAM FC", "SEONGNAM"))
        );

        jakdukUser = new User();
        jakdukUser.setId("597df86caaf4fc0545d4f3e9");
        jakdukUser.setEmail("example@jakduk.com");
        jakdukUser.setUsername("JakdukUser");
        jakdukUser.setPassword("841db2bc28e4730906bd82d79e69c80633747570d96ffade7dd77f58270f31a222e129e005cb70d2");
        jakdukUser.setProviderId(Constants.ACCOUNT_TYPE.JAKDUK);
        jakdukUser.setAbout("안녕하세요.");
        jakdukUser.setRoles(Arrays.asList(JakdukAuthority.ROLE_USER_01.getCode()));
        jakdukUser.setSupportFC(footballClub);
        jakdukUser.setLastLogged(LocalDateTime.now());
    }

    @Test
    @WithMockUser
    public void formLoginTest() throws Exception {

        when(userRepository.findOneByEmail(anyString()))
                .thenReturn(Optional.of(jakdukUser));

        mvc.perform(
                post("/api/auth/login")
                        .contentType(MediaType.APPLICATION_FORM_URLENCODED)
                        .accept(MediaType.APPLICATION_JSON)
                        .param("username", "example@jakduk.com")
                        .param("password", "1111")
                        .param("remember-me", "1")
                        .with(csrf()))
                .andExpect(status().isOk())
//                .andExpect(cookie().exists("JSESSIONID")) // FIXME Mock 객체라서 그런지 응답으로 안옴
                .andExpect(content().contentTypeCompatibleWith(MediaType.APPLICATION_JSON))
                .andExpect(content().json(ObjectMapperUtils.writeValueAsString(EmptyJsonResponse.newInstance())))
                .andDo(
                        document("login-jakduk-user",
                                requestParameters(
                                        parameterWithName("username").description("이메일 주소"),
                                        parameterWithName("password").description("비밀번호"),
                                        parameterWithName("remember-me").description("(optional) 로그인 유지 여부. 1 or 0"),
                                        parameterWithName("_csrf").description("CSRF 토큰")
                                ),
                                responseHeaders(
                                        headerWithName("Set-Cookie").description("인증 쿠키. value는 JSESSIONID=키값").optional()
                                )
                        ));
    }

    @Test
    @WithMockUser
    public void snsLoginTest() throws Exception {

        Map<String, Object> requestForm = new HashMap<String, Object>() {{
            put("accessToken", "baada13b7df9af000fa20355bf07b25f808940ab69dd7f32b6c009efdd0f6d29");
        }};

        when(authUtils.getSnsProfile(any(Constants.ACCOUNT_TYPE.class), anyString()))
                .thenReturn(socialProfile);

        Optional<User> optUser = Optional.of(
                new User() {{
                    setId("58b2dbf1d6d83b04bf365277");
                    setEmail("test07@test.com");
                    setUsername("생글이");
                    setProviderId(providerId);
                    setProviderUserId(socialProfile.getId());
                    setRoles(Arrays.asList(JakdukAuthority.ROLE_USER_01.getCode()));
                    setAbout("안녕하세요.");
                }}
        );

        when(userService.findOneByProviderIdAndProviderUserId(any(Constants.ACCOUNT_TYPE.class), anyString()))
                .thenReturn(optUser);

        ConstraintDescriptions loginSocialUserConstraints = new ConstraintDescriptions(LoginSocialUserForm.class);

        mvc.perform(
                post("/api/auth/login/{providerId}", providerId)
                        .contentType(MediaType.APPLICATION_JSON)
                        .accept(MediaType.APPLICATION_JSON)
                        .content(ObjectMapperUtils.writeValueAsString(requestForm))
                        .with(csrf()))
                .andExpect(status().isOk())
                .andExpect(content().contentTypeCompatibleWith(MediaType.APPLICATION_JSON))
                .andExpect(content().json(ObjectMapperUtils.writeValueAsString(EmptyJsonResponse.newInstance())))
                .andDo(
                        document("login-sns-user",
                                pathParameters(
                                        parameterWithName("providerId").description("SNS 분류 " +
                                                Stream.of(Constants.ACCOUNT_TYPE.values())
                                                        .filter(accountType -> ! accountType.equals(Constants.ACCOUNT_TYPE.JAKDUK))
                                                        .map(Enum::name)
                                                        .map(String::toLowerCase)
                                                        .collect(Collectors.toList())
                                        )
                                ),
                                requestFields(
                                        fieldWithPath("accessToken").type(JsonFieldType.STRING).description("OAuth의 Access Token " +
                                                loginSocialUserConstraints.descriptionsForProperty("accessToken"))
                                ),
                                responseHeaders(
                                        headerWithName("Set-Cookie").description("인증 쿠키. value는 JSESSIONID=키값").optional()
                                )
                        ));
    }

    @Test
    @WithAnonymousUser
    public void getAttemptSocialUserTest() throws Exception {

        AttemptSocialUser expectAttemptSocialUser = new AttemptSocialUser();
        expectAttemptSocialUser.setEmail(socialProfile.getEmail());
        expectAttemptSocialUser.setUsername(socialProfile.getNickname());
        expectAttemptSocialUser.setProviderId(providerId);
        expectAttemptSocialUser.setProviderUserId(socialProfile.getId());
        expectAttemptSocialUser.setExternalLargePictureUrl(socialProfile.getPictureUrl());

        Map<String, Object> sessionAttributes = new HashMap<>();
        sessionAttributes.put(Constants.PROVIDER_SIGNIN_ATTEMPT_SESSION_ATTRIBUTE, expectAttemptSocialUser);

        mvc.perform(
                get("/api/auth/user/attempt")
                        .header("Cookie", "JSESSIONID=3F0E029648484BEAEF6B5C3578164E99")
                        .sessionAttrs(sessionAttributes)
                        .accept(MediaType.APPLICATION_JSON))
                .andExpect(status().isOk())
                .andExpect(content().contentTypeCompatibleWith(MediaType.APPLICATION_JSON))
                .andExpect(content().json(ObjectMapperUtils.writeValueAsString(expectAttemptSocialUser)))
                .andDo(
                        document("get-attempt-social-session-user",
                                requestHeaders(
                                        headerWithName("Cookie").description("인증 쿠키. value는 JSESSIONID=키값")
                                ),
                                responseFields(
                                        fieldWithPath("email").type(JsonFieldType.STRING).description("Provider에서 제공한 이메일 주소"),
                                        fieldWithPath("username").type(JsonFieldType.STRING).description("Provider에서 제공한 별명"),
                                        fieldWithPath("providerId").type(JsonFieldType.STRING).description("SNS 분류 " +
                                                        Stream.of(Constants.ACCOUNT_TYPE.values())
                                                                .filter(accountType -> ! accountType.equals(Constants.ACCOUNT_TYPE.JAKDUK))
                                                                .map(Enum::name)
                                                                .collect(Collectors.toList())
                                                ),
                                        fieldWithPath("providerUserId").type(JsonFieldType.STRING).description("Provider에서 제공한 사용자 ID"),
                                        fieldWithPath("externalLargePictureUrl").type(JsonFieldType.STRING).description("Provider에서 제공한 큰 사진 URL")
                                )
                        ));
    }

    @Test
    @WithMockUser
    public void logoutTest() throws Exception {
        mvc.perform(
                post("/api/auth/logout")
                        .cookie(new Cookie("JSESSIONID", "3F0E029648484BEAEF6B5C3578164E99"))
                        .accept(MediaType.APPLICATION_JSON)
                        .with(csrf()))
                .andExpect(status().isOk())
                .andExpect(content().contentTypeCompatibleWith(MediaType.APPLICATION_JSON))
                .andExpect(content().json(ObjectMapperUtils.writeValueAsString(EmptyJsonResponse.newInstance())))
                .andDo(
                        document("logout",
                                requestHeaders(
                                        headerWithName("Cookie").optional().description("인증 쿠키. value는 JSESSIONID=키값")
                                )
                        ));
    }

    @Test
    @WithMockJakdukUser
    public void getMySessionProfileTest() throws Exception {

        SessionUser expectResponse = AuthUtils.getSessionProfile();

        mvc.perform(
                get("/api/auth/user")
                        .header("Cookie", "JSESSIONID=3F0E029648484BEAEF6B5C3578164E99")
                        .accept(MediaType.APPLICATION_JSON))
                .andExpect(status().isOk())
                .andExpect(content().contentTypeCompatibleWith(MediaType.APPLICATION_JSON))
                .andExpect(content().json(ObjectMapperUtils.writeValueAsString(expectResponse)))
                .andDo(
                        document("get-my-session-user",
                                requestHeaders(
                                        headerWithName("Cookie").description("인증 쿠키. value는 JSESSIONID=키값")
                                ),
                                responseFields(
                                        fieldWithPath("id").type(JsonFieldType.STRING).description("회원 ID"),
                                        fieldWithPath("email").type(JsonFieldType.STRING).description("이메일 주소"),
                                        fieldWithPath("username").type(JsonFieldType.STRING).description("별명"),
                                        fieldWithPath("providerId").type(JsonFieldType.STRING).description("계정 분류 " +
                                                Stream.of(Constants.ACCOUNT_TYPE.values()).map(Enum::name).collect(Collectors.toList())),
                                        fieldWithPath("roles").type(JsonFieldType.ARRAY).description("권한 목록 " +
                                                Stream.of(JakdukAuthority.values()).map(Enum::name).collect(Collectors.toList())),
                                        fieldWithPath("picture").type(JsonFieldType.OBJECT).description("회원 사진"),
                                        fieldWithPath("picture.id").type(JsonFieldType.STRING).description("회원 사진 ID"),
                                        fieldWithPath("picture.smallPictureUrl").type(JsonFieldType.STRING).description("회원 작은 사진 URL"),
                                        fieldWithPath("picture.largePictureUrl").type(JsonFieldType.STRING).description("회원 큰 사진 URL")
                                )
                        ));
    }

}