text:
/* eslint no-console:0, import/prefer-default-export:0 */
import winston from 'winston';
import moment from 'moment';
import colors from 'colors';

export const logger = new (winston.Logger)({
  transports: [
    new (winston.transports.Console)(),
    new (winston.transports.File)({
      name: 'info-file',
      filename: 'events.log',
      timestamp: false,
      maxsize: 100000000,
      level: 'info'
    }),
    new (winston.transports.File)({
      name: 'error-file',
      filename: 'errors.log',
      timestamp: false,
      maxsize: 100000000,
      level: 'error'
    })
  ]
});

const getTime = () => moment().format('M/D/YY hh:mm:ss A');
const withTime = (message) => `${colors.grey(getTime())} | ${message}`;

export const logActionType = (type) => {
  logger.log('info', withTime(colors.yellow(type)));
};

export const logUndefinedHandler = (e) => {
  logger.log('error', withTime(colors.red(e.message)));
};

export const errorNoHandler = (data) => {
  const message = `${colors.red('Unhandled or unauthorized event')}: ${data}`;

  logger.log('error', withTime(message));
};

export const errorLightStatus = (e) => {
  const alert = colors.red('Could not alter light state');
  const message = `${alert}; did you use the correct IP address or trigger a valid function?`;

  logger.log('error', withTime(message));
  if (e) logger.log('error', withTime(e));
};

export const errorNoUserIDFound = (ipaddress) => {
  logger.log('error', `userID not found for Hue bridge on ${ipaddress}`);
};


text:
Title: Hadoop Streaming
Date: 2015-09-15 00:00
Tags: hadoop, streaming

- [Hadoop Streaming Made Simple using Joins and Keys with Python](http://allthingshadoop.com/2011/12/16/simple-hadoop-streaming-tutorial-using-joins-and-keys-with-python/)

redpajama_set_name: RedPajamaGithub


text:
package edu.bupt.mms;

import java.io.IOException;

import org.xmlpull.v1.XmlPullParser;
import org.xmlpull.v1.XmlPullParserException;

import com.android.internal.telephony.TelephonyProperties;

import android.content.Context;
import android.content.res.XmlResourceParser;
import android.util.Log;

public class MmsConfig {
    private static final String TAG = "MmsConfig";
    private static final boolean DEBUG = true;
    private static final boolean LOCAL_LOGV = false;

    private static final String DEFAULT_HTTP_KEY_X_WAP_PROFILE = "x-wap-profile";
    private static final String DEFAULT_USER_AGENT = "Android-Mms/2.0";

    private static final int MAX_IMAGE_HEIGHT = 480;
    private static final int MAX_IMAGE_WIDTH = 640;
    private static final int MAX_TEXT_LENGTH = 2000;

    /**
     * Whether to hide MMS functionality from the user (i.e. SMS only).
     */
    private static boolean mTransIdEnabled = false;
    private static int mMmsEnabled = 1;                         // default to true
    private static int mMaxMessageSize = 300 * 1024;            // default to 300k max size
    private static String mUserAgent = DEFAULT_USER_AGENT;
    private static String mUaProfTagName = DEFAULT_HTTP_KEY_X_WAP_PROFILE;
    private static String mUaProfUrl = null;
    private static String mHttpParams = null;
    private static String mHttpParamsLine1Key = null;
    private static String mEmailGateway = null;
    private static int mMaxImageHeight = MAX_IMAGE_HEIGHT;      // default value
    private static int mMaxImageWidth = MAX_IMAGE_WIDTH;        // default value
    private static int mRecipientLimit = Integer.MAX_VALUE;     // default value
    private static int mDefaultSMSMessagesPerThread = 500;      // default value
    private static int mDefaultMMSMessagesPerThread = 50;       // default value
    private static int mMinMessageCountPerThread = 2;           // default value
    private static int mMaxMessageCountPerThread = 5000;        // default value
    private static int mHttpSocketTimeout = 60*1000;            // default to 1 min
    private static int mMinimumSlideElementDuration = 7;        // default to 7 sec
    private static boolean mNotifyWapMMSC = false;
    private static boolean mAllowAttachAudio = true;

    // If mEnableMultipartSMS is true, long sms messages are always sent as multi-part sms
    // messages, with no checked limit on the number of segments.
    // If mEnableMultipartSMS is false, then as soon as the user types a message longer
    // than a single segment (i.e. 140 chars), then the message will turn into and be sent
    // as an mms message. This feature exists for carriers that don't support multi-part sms's.
    private static boolean mEnableMultipartSMS = true;

    // If mEnableMultipartSMS is true and mSmsToMmsTextThreshold > 1, then multi-part SMS messages
    // will be converted into a single mms message. For example, if the mms_config.xml file
    // specifies <int name="smsToMmsTextThreshold">4</int>, then on the 5th sms segment, the
    // message will be converted to an mms.
    private static int mSmsToMmsTextThreshold = -1;

    private static boolean mEnableSlideDuration = true;
    private static boolean mEnableMMSReadReports = true;        // key: "enableMMSReadReports"
    private static boolean mEnableSMSDeliveryReports = true;    // key: "enableSMSDeliveryReports"
    private static boolean mEnableMMSDeliveryReports = true;    // key: "enableMMSDeliveryReports"
    private static int mMaxTextLength = -1;

    // This is the max amount of storage multiplied by mMaxMessageSize that we
    // allow of unsent messages before blocking the user from sending any more
    // MMS's.
    private static int mMaxSizeScaleForPendingMmsAllowed = 4;       // default value

    // Email gateway alias support, including the master switch and different rules
    private static boolean mAliasEnabled = false;
    private static int mAliasRuleMinChars = 2;
    private static int mAliasRuleMaxChars = 48;

    private static int mMaxSubjectLength = 40;  // maximum number of characters allowed for mms
                                                // subject

    public static void init(Context context) {
        if (LOCAL_LOGV) {
            Log.v(TAG, "MmsConfig.init()");
        }
        // Always put the mnc/mcc in the log so we can tell which mms_config.xml was loaded.
        Log.v(TAG, "mnc/mcc: " +
                android.os.SystemProperties.get(TelephonyProperties.PROPERTY_ICC_OPERATOR_NUMERIC));

        loadMmsSettings(context);
    }

    public static int getSmsToMmsTextThreshold() {
        return mSmsToMmsTextThreshold;
    }

    public static boolean getMmsEnabled() {
        return mMmsEnabled == 1 ? true : false;
    }

    public static int getMaxMessageSize() {
        if (LOCAL_LOGV) {
            Log.v(TAG, "MmsConfig.getMaxMessageSize(): " + mMaxMessageSize);
        }
       return mMaxMessageSize;
    }

    /**
     * This function returns the value of "enabledTransID" present in mms_config file.
     * In case of single segment wap push message, this "enabledTransID" indicates whether
     * TransactionID should be appended to URI or not.
     */
    public static boolean getTransIdEnabled() {
        return mTransIdEnabled;
    }

    public static String getUserAgent() {
        return mUserAgent;
    }

    public static String getUaProfTagName() {
        return mUaProfTagName;
    }

    public static String getUaProfUrl() {
        return mUaProfUrl;
    }

    public static String getHttpParams() {
        return mHttpParams;
    }

    public static String getHttpParamsLine1Key() {
        return mHttpParamsLine1Key;
    }

    public static String getEmailGateway() {
        return mEmailGateway;
    }

    public static int getMaxImageHeight() {
        return mMaxImageHeight;
    }

    public static int getMaxImageWidth() {
        return mMaxImageWidth;
    }

    public static int getRecipientLimit() {
        return mRecipientLimit;
    }

    public static int getMaxTextLimit() {
        return mMaxTextLength > -1 ? mMaxTextLength : MAX_TEXT_LENGTH;
    }

    public static int getDefaultSMSMessagesPerThread() {
        return mDefaultSMSMessagesPerThread;
    }

    public static int getDefaultMMSMessagesPerThread() {
        return mDefaultMMSMessagesPerThread;
    }

    public static int getMinMessageCountPerThread() {
        return mMinMessageCountPerThread;
    }

    public static int getMaxMessageCountPerThread() {
        return mMaxMessageCountPerThread;
    }

    public static int getHttpSocketTimeout() {
        return mHttpSocketTimeout;
    }

    public static int getMinimumSlideElementDuration() {
        return mMinimumSlideElementDuration;
    }

    public static boolean getMultipartSmsEnabled() {
        return mEnableMultipartSMS;
    }

    public static boolean getSlideDurationEnabled() {
        return mEnableSlideDuration;
    }

    public static boolean getMMSReadReportsEnabled() {
        return mEnableMMSReadReports;
    }

    public static boolean getSMSDeliveryReportsEnabled() {
        return mEnableSMSDeliveryReports;
    }

    public static boolean getMMSDeliveryReportsEnabled() {
        return mEnableMMSDeliveryReports;
    }

    public static boolean getNotifyWapMMSC() {
        return mNotifyWapMMSC;
    }

    public static int getMaxSizeScaleForPendingMmsAllowed() {
        return mMaxSizeScaleForPendingMmsAllowed;
    }

    public static boolean isAliasEnabled() {
        return mAliasEnabled;
    }

    public static int getAliasMinChars() {
        return mAliasRuleMinChars;
    }

    public static int getAliasMaxChars() {
        return mAliasRuleMaxChars;
    }

    public static boolean getAllowAttachAudio() {
        return mAllowAttachAudio;
    }

    public static int getMaxSubjectLength() {
        return mMaxSubjectLength;
    }

    public static final void beginDocument(XmlPullParser parser, String firstElementName) throws XmlPullParserException, IOException
    {
        int type;
        while ((type=parser.next()) != parser.START_TAG
                   && type != parser.END_DOCUMENT) {
            ;
        }

        if (type != parser.START_TAG) {
            throw new XmlPullParserException("No start tag found");
        }

        if (!parser.getName().equals(firstElementName)) {
            throw new XmlPullParserException("Unexpected start tag: found " + parser.getName() +
                    ", expected " + firstElementName);
        }
    }

    public static final void nextElement(XmlPullParser parser) throws XmlPullParserException, IOException
    {
        int type;
        while ((type=parser.next()) != parser.START_TAG
                   && type != parser.END_DOCUMENT) {
            ;
        }
    }

    private static void loadMmsSettings(Context context) {
        XmlResourceParser parser = context.getResources().getXml(R.xml.mms_config);

        try {
            beginDocument(parser, "mms_config");

            while (true) {
                nextElement(parser);
                String tag = parser.getName();
                if (tag == null) {
                    break;
                }
                String name = parser.getAttributeName(0);
                String value = parser.getAttributeValue(0);
                String text = null;
                if (parser.next() == XmlPullParser.TEXT) {
                    text = parser.getText();
                }

                if (DEBUG) {
                    Log.v(TAG, "tag: " + tag + " value: " + value + " - " +
                            text);
                }
                if ("name".equalsIgnoreCase(name)) {
                    if ("bool".equals(tag)) {
                        // bool config tags go here
                        if ("enabledMMS".equalsIgnoreCase(value)) {
                            mMmsEnabled = "true".equalsIgnoreCase(text) ? 1 : 0;
                        } else if ("enabledTransID".equalsIgnoreCase(value)) {
                            mTransIdEnabled = "true".equalsIgnoreCase(text);
                        } else if ("enabledNotifyWapMMSC".equalsIgnoreCase(value)) {
                            mNotifyWapMMSC = "true".equalsIgnoreCase(text);
                        } else if ("aliasEnabled".equalsIgnoreCase(value)) {
                            mAliasEnabled = "true".equalsIgnoreCase(text);
                        } else if ("allowAttachAudio".equalsIgnoreCase(value)) {
                            mAllowAttachAudio = "true".equalsIgnoreCase(text);
                        } else if ("enableMultipartSMS".equalsIgnoreCase(value)) {
                            mEnableMultipartSMS = "true".equalsIgnoreCase(text);
                        } else if ("enableSlideDuration".equalsIgnoreCase(value)) {
                            mEnableSlideDuration = "true".equalsIgnoreCase(text);
                        } else if ("enableMMSReadReports".equalsIgnoreCase(value)) {
                            mEnableMMSReadReports = "true".equalsIgnoreCase(text);
                        } else if ("enableSMSDeliveryReports".equalsIgnoreCase(value)) {
                            mEnableSMSDeliveryReports = "true".equalsIgnoreCase(text);
                        } else if ("enableMMSDeliveryReports".equalsIgnoreCase(value)) {
                            mEnableMMSDeliveryReports = "true".equalsIgnoreCase(text);
                        }
                    } else if ("int".equals(tag)) {
                        // int config tags go here
                        if ("maxMessageSize".equalsIgnoreCase(value)) {
                            mMaxMessageSize = Integer.parseInt(text);
                        } else if ("maxImageHeight".equalsIgnoreCase(value)) {
                            mMaxImageHeight = Integer.parseInt(text);
                        } else if ("maxImageWidth".equalsIgnoreCase(value)) {
                            mMaxImageWidth = Integer.parseInt(text);
                        } else if ("defaultSMSMessagesPerThread".equalsIgnoreCase(value)) {
                            mDefaultSMSMessagesPerThread = Integer.parseInt(text);
                        } else if ("defaultMMSMessagesPerThread".equalsIgnoreCase(value)) {
                            mDefaultMMSMessagesPerThread = Integer.parseInt(text);
                        } else if ("minMessageCountPerThread".equalsIgnoreCase(value)) {
                            mMinMessageCountPerThread = Integer.parseInt(text);
                        } else if ("maxMessageCountPerThread".equalsIgnoreCase(value)) {
                            mMaxMessageCountPerThread = Integer.parseInt(text);
                        } else if ("recipientLimit".equalsIgnoreCase(value)) {
                            mRecipientLimit = Integer.parseInt(text);
                            if (mRecipientLimit < 0) {
                                mRecipientLimit = Integer.MAX_VALUE;
                            }
                        } else if ("httpSocketTimeout".equalsIgnoreCase(value)) {
                            mHttpSocketTimeout = Integer.parseInt(text);
                        } else if ("minimumSlideElementDuration".equalsIgnoreCase(value)) {
                            mMinimumSlideElementDuration = Integer.parseInt(text);
                        } else if ("maxSizeScaleForPendingMmsAllowed".equalsIgnoreCase(value)) {
                            mMaxSizeScaleForPendingMmsAllowed = Integer.parseInt(text);
                        } else if ("aliasMinChars".equalsIgnoreCase(value)) {
                            mAliasRuleMinChars = Integer.parseInt(text);
                        } else if ("aliasMaxChars".equalsIgnoreCase(value)) {
                            mAliasRuleMaxChars = Integer.parseInt(text);
                        } else if ("smsToMmsTextThreshold".equalsIgnoreCase(value)) {
                            mSmsToMmsTextThreshold = Integer.parseInt(text);
                        } else if ("maxMessageTextSize".equalsIgnoreCase(value)) {
                            mMaxTextLength = Integer.parseInt(text);
                        } else if ("maxSubjectLength".equalsIgnoreCase(value)) {
                            mMaxSubjectLength = Integer.parseInt(text);
                        }
                    } else if ("string".equals(tag)) {
                        // string config tags go here
                        if ("userAgent".equalsIgnoreCase(value)) {
                            mUserAgent = text;
                        } else if ("uaProfTagName".equalsIgnoreCase(value)) {
                            mUaProfTagName = text;
                        } else if ("uaProfUrl".equalsIgnoreCase(value)) {
                            mUaProfUrl = text;
                        } else if ("httpParams".equalsIgnoreCase(value)) {
                            mHttpParams = text;
                        } else if ("httpParamsLine1Key".equalsIgnoreCase(value)) {
                            mHttpParamsLine1Key = text;
                        } else if ("emailGatewayNumber".equalsIgnoreCase(value)) {
                            mEmailGateway = text;
                        }
                    }
                }
            }
        } catch (XmlPullParserException e) {
            Log.e(TAG, "loadMmsSettings caught ", e);
        } catch (NumberFormatException e) {
            Log.e(TAG, "loadMmsSettings caught ", e);
        } catch (IOException e) {
            Log.e(TAG, "loadMmsSettings caught ", e);
        } finally {
            parser.close();
        }

        String errorStr = null;

        if (getMmsEnabled() && mUaProfUrl == null) {
            errorStr = "uaProfUrl";
        }

        if (errorStr != null) {
            String err =
                String.format("MmsConfig.loadMmsSettings mms_config.xml missing %s setting",
                        errorStr);
            Log.e(TAG, err);
        }
    }

}


text:
using YamlDotNet.Serialization;
using YamlDotNet.Serialization.NamingConventions;
using TxtBlog.Models;
using System.IO;
using System.Collections.Generic;
using Microsoft.Framework.Runtime;
using System.Linq;
using System;

namespace TxtBlog.DAL
{
    public class PostRepository
    {
        // Where the YAML configuration ends
        // This is used to split the content so that the deserializer
        // will not choke
        private const string YAMLEND = "...\n";

        private readonly IApplicationEnvironment _appEnvironment;

        public PostRepository(IApplicationEnvironment appEnv)
        {
            _appEnvironment = appEnv;
        }

#region public
        public IEnumerable<Post> GetAllPosts()
        {
            return this.getPostsToLimit(0);
        }

        public IEnumerable<Post> GetLastTenPosts()
        {
            return this.getPostsToLimit(10);
        }

        public Post GetPostBySlug(string slug)
        {
            string fileName = string.Format("{0}.md", slug);
            return this.getPost(fileName);
        }
#endregion

#region private
        private Post getPost(string filename)
        {
            Post post = null;
            using (FileStream fs = File.OpenRead("blog/" + filename))
            {
                using (StreamReader sr = new StreamReader(fs))
                {
                    var deserializer = new Deserializer(
                        namingConvention: new CamelCaseNamingConvention()
                    );

                    string fileContents = sr.ReadToEnd();
                    string[] yamlEnd = new string[] { YAMLEND };
                    string[] parts = fileContents.Split(yamlEnd, StringSplitOptions.None);

                    string metaData = string.Format("{0}\n{1}", parts[0], YAMLEND);
                    string content = parts[1];

                    // create post object
                    post = deserializer.Deserialize<Post>(new StringReader(metaData));
                    if (post != null)
                    {
                        post.Content = content;
                    }
                }
            }

            return post;
        }

        private IEnumerable<Post> getPostsToLimit(int limit = 0)
        {
            DirectoryInfo di = new DirectoryInfo(_appEnvironment.ApplicationBasePath);
            FileInfo[] fileEntries = di.GetFiles("blog/*.md");

            var deserializer = new Deserializer(namingConvention: new CamelCaseNamingConvention());

            List<Post> posts = new List<Post>();
            foreach (FileInfo f in fileEntries)
            {
                //parse file yaml
                Post post = null;
                using (StreamReader sr = new StreamReader(f.OpenRead()))
                {
                    string fileContents = sr.ReadToEnd();
                    string[] separators = new string[] { YAMLEND };
                    string[] parts = fileContents.Split(separators, StringSplitOptions.None);

                    string metaData = string.Format("{0}\n{1}", parts[0], YAMLEND);
                    string content = parts[1];

                    post = deserializer.Deserialize<Post>(new StringReader(metaData));
                    if (post != null)
                    {
                        post.Content = content;
                        post.Slug = f.Name.Replace(".md","");
                    }
                }

                if (post != null)
                {
                    posts.Add(post);
                }
            }

            if (limit > 0)
            {
                return posts.OrderByDescending(p => p.Date).Take(limit);
            }

            return posts.OrderByDescending(p => p.Date);
        }
    }
#endregion
}


text:
layout: page
title: Chrome Trade Party
date: 2016-05-24
author: Ronald Harrison
tags: weekly links, java
status: published
summary: Cras augue tellus, aliquam nec tortor non, dictum.
banner: images/banner/meeting-01.jpg
booking:
  startDate: 06/09/2018
  endDate: 06/14/2018
  ctyhocn: GSOFSHX
  groupCode: CTP
published: true
---
Nullam facilisis arcu quis mi fringilla, at accumsan diam cursus. Nam sit amet laoreet mauris. Duis laoreet quam eu velit tempus, sit amet tristique ex laoreet. Aliquam gravida imperdiet purus et dapibus. Nunc vitae vehicula sapien, id fringilla quam. Donec vulputate elit quis quam hendrerit sagittis. Mauris aliquet eu lacus a dapibus. Aliquam commodo non sem at vestibulum. Integer ut leo ut velit maximus sodales quis in quam. Pellentesque porttitor pellentesque commodo. Sed et convallis lectus.

* Donec lobortis ipsum nec odio finibus, in dignissim arcu consectetur
* Pellentesque in augue vitae metus sollicitudin pharetra eget ac eros
* Proin viverra sapien at imperdiet rutrum.

Pellentesque sit amet nunc a lacus sollicitudin placerat. Sed et tempus justo. Proin quis metus nec risus tristique rhoncus. Donec elementum, elit sit amet maximus tincidunt, justo ex pellentesque diam, a pulvinar sem lectus eget nunc. Suspendisse suscipit mauris sed ex interdum dapibus. Aliquam non blandit velit, in pellentesque ex. Donec et est ut magna egestas blandit. Donec in odio non arcu mattis cursus in vel magna. Cum sociis natoque penatibus et magnis dis parturient montes, nascetur ridiculus mus. Pellentesque id lacus in nibh tincidunt condimentum. Aenean egestas nisi ut scelerisque facilisis.


text:
<!DOCTYPE html><html><head><meta charset="utf-8" />
<meta http-equiv="refresh" content="0;url=/place/iceland/companies/" />
</head></html>


text:
/**
 *
 *
 * @module AppsMallUI.directivesModule
 * @submodule AppsMallUI.ResizingModule
 * @requires amlApp.directives
 */
'use strict';

/**
 * HTML class directive: Resizes this element when parent resizes, so that other sibling elements do not change dimension.
 *
 * Usage: ```<[element] class="resizing"></[element]>```
 *
 * @class AppsMallUI.ResizingDirective
 * @static
 */

/**
 * @class AppsMallUI.ResizingDirective
 * @constructor
 */
var ResizingDirective = [function() {
    return {
        restrict: 'C',
        link: function(scope, element, attrs) {
            var $parentElement = $(element).parent();
            var previousWindowHeight = null;
            var resizeFunc = function() {
                var currentWindowHeight = $(window).height();
                if (previousWindowHeight !== currentWindowHeight) {
                    var currentElementHeight = $(element).height();
                    var allChildrenHeight =  _.chain($parentElement.children())
                                              .map(function(el) { return $(el).outerHeight(true); })
                                              .reduce(function(v1,v2) { return v1+v2; })
                                              .value();

                    var otherChildrenHeight = allChildrenHeight - currentElementHeight;

                    $(element).css('max-height', (currentWindowHeight - otherChildrenHeight - 30));

                    // console.log('* Element height = ' + currentElementHeight + ', other children height = ' + otherChildrenHeight);
                    // console.log('  New max height = ' + (currentWindowHeight - otherChildrenHeight - 30) + ', window height = ' + $(window).height());
                    previousWindowHeight = currentWindowHeight;
                }
            };
            resizeFunc();
            $(window).resize(resizeFunc);
        }
    };
}];

directivesModule.directive('resizing', ResizingDirective);


text:
package aspguidc.service.generation.writer.input;

import aspguidc.helper.FileHelper;
import aspguidc.model.input.InputElementDefinition;
import aspguidc.model.input.ProgramInputDefinition;
import aspguidc.model.input.entity.EntityInputDefinition;
import aspguidc.model.input.value.ValueInputDefinition;
import org.jtwig.JtwigModel;

import java.io.File;
import java.io.IOException;
import java.util.AbstractMap;
import java.util.LinkedHashMap;
import java.util.Map;
import java.util.logging.Logger;

/**
 * Writer class which provides methods for generating source code files which depend on the program input section
 * of an gui definition.
 * An instance of this class is assigned to a single target directory, which is used to store the generated source
 * code files.
 */
public class ProgramInputTemplateWriter {
    private final File sourceCodeDirectory;
    private final ValueInputTemplateWriter valueInputWriter;
    private final EntityInputTemplateWriter entityInputWriter;

    /**
     * Create a new writer instance with the given directory as output directory.
     *
     * @param sourceCodeDirectory directory which is used to write the generated source code into
     */
    public ProgramInputTemplateWriter(File sourceCodeDirectory) {
        this.sourceCodeDirectory = sourceCodeDirectory;
        this.valueInputWriter = new ValueInputTemplateWriter(sourceCodeDirectory);
        this.entityInputWriter = new EntityInputTemplateWriter(sourceCodeDirectory);
    }

    /**
     * Generate an write the source code files for the given program input definition.
     * This method first generates the source code files for all input elements in the given program input definition,
     * then generates program input fxml file which contains the paths to the generated input elements.
     *
     * @param programInput program input definition which is used for source code generation
     * @throws IOException
     */
    public void writeProgramInput(ProgramInputDefinition programInput) throws IOException {
        Logger.getGlobal().info("[generating] write program input files");

        Map<String, String> fxmlPathTypeMap = new LinkedHashMap<>(); // use linked map to keep order

        // generate source code for input elements
        for (InputElementDefinition inputElement : programInput.getInputElements().values()) {
            Map.Entry<String, String> elementPathTypeEntry = this.writeInputElement(inputElement);
            fxmlPathTypeMap.put(elementPathTypeEntry.getKey(), elementPathTypeEntry.getValue());
        }

        // generate fxml including the input element fxml paths
        JtwigModel model = JtwigModel.newModel().with("inputElementFxmlPaths", fxmlPathTypeMap);
        FileHelper.writeTemplateFile("src/main/resources/fxml/input/program_input.fxml", model, this.sourceCodeDirectory);
    }

    /**
     * Generate and write the source code files for the given input element definition by calling the respective
     * writer for the input element type.
     *
     * @param inputElement input element definition which is used for source code generation
     * @return tuple containing the relative path of the generated fxml file and the type of the input element
     * @throws IOException
     */
    private Map.Entry<String, String> writeInputElement(InputElementDefinition inputElement) throws IOException {
        if (inputElement instanceof ValueInputDefinition) {
            String path = this.valueInputWriter.writeValueInputElement((ValueInputDefinition) inputElement);
            return new AbstractMap.SimpleEntry<>(path, "value");
        } else if (inputElement instanceof EntityInputDefinition) {
            String path = this.entityInputWriter.writeEntityInputElement((EntityInputDefinition) inputElement);
            return new AbstractMap.SimpleEntry<>(path, "entity");
        }

        throw new IllegalArgumentException("invalid type of input element while generating source code");
    }

}


text:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    android:orientation="vertical"
    android:background="@color/homescreen_background" >

		<ScrollView
		    android:orientation="vertical"
		    android:layout_width="fill_parent"
		    android:layout_height="fill_parent"
            android:layout_weight="1"
            android:fillViewport="true" >

            <LinearLayout
                android:id="@+id/linearLayout"
                android:layout_width="match_parent"
                android:layout_height="match_parent"
                android:background="@color/homescreen_background"
                android:orientation="vertical"
                android:padding="12dp" >

				<TextView
					android:id="@+id/txtAlarmsEntry1"
					android:text="@string/txtAlarmsEntry1"

                    android:layout_width="match_parent"
                    android:layout_height="match_parent"
                    android:layout_weight="1"
				    android:background="@color/homescreen_background"
				    android:textColor="@color/card_textcolor_regular"
				    android:textSize="@dimen/card_textsize_regular"
				    android:focusable="true"
				    android:ellipsize="none"
				    android:scrollHorizontally="false"
				/>

				<View
				    android:layout_width="fill_parent"
				    android:layout_height="1dp"
				    android:layout_marginTop="6dp"
				    android:layout_marginBottom="6dp"
				    android:background="@android:color/darker_gray"/>

				<TextView
					android:id="@+id/txtAlarmsEntry2"
					android:text="@string/txtAlarmsEntry2"
                    android:layout_width="match_parent"
                    android:layout_height="match_parent"
                    android:layout_weight="1"
				    android:background="@color/homescreen_background"
				    android:textColor="@color/card_textcolor_regular"
				    android:textSize="@dimen/card_textsize_regular"
				    android:focusable="true"
				    android:ellipsize="none"
				    android:scrollHorizontally="false"
				/>

				<View
				    android:layout_width="fill_parent"
				    android:layout_height="1dp"
				    android:layout_marginTop="6dp"
				    android:layout_marginBottom="6dp"
				    android:background="@android:color/darker_gray"/>

				<TextView
					android:id="@+id/txtAlarmsEntry3"
					android:text="@string/txtAlarmsEntry3"
                    android:layout_width="match_parent"
                    android:layout_height="match_parent"
                    android:layout_weight="1"
				    android:background="@color/homescreen_background"
				    android:textColor="@color/card_textcolor_regular"
				    android:textSize="@dimen/card_textsize_regular"
				    android:focusable="true"
				    android:ellipsize="none"
				    android:scrollHorizontally="false"
				/>

				<View
				    android:layout_width="fill_parent"
				    android:layout_height="1dp"
				    android:layout_marginTop="6dp"
				    android:layout_marginBottom="6dp"
				    android:background="@android:color/darker_gray"/>

				<TextView
					android:id="@+id/txtAlarmsEntry4"
					android:text="@string/txtAlarmsEntry4"
                    android:layout_width="match_parent"
                    android:layout_height="match_parent"
                    android:layout_weight="1"
				    android:background="@color/homescreen_background"
				    android:textColor="@color/card_textcolor_regular"
				    android:textSize="@dimen/card_textsize_regular"
				    android:focusable="true"
				    android:ellipsize="none"
				    android:scrollHorizontally="false"
				/>

				<View
				    android:layout_width="fill_parent"
				    android:layout_height="1dp"
				    android:layout_marginTop="6dp"
				    android:layout_marginBottom="6dp"
				    android:background="@android:color/darker_gray"/>

				<TextView
					android:id="@+id/txtAlarmsEntry5"
					android:text="@string/txtAlarmsEntry5"
                    android:layout_width="match_parent"
                    android:layout_height="match_parent"
                    android:layout_weight="1"
				    android:background="@color/homescreen_background"
				    android:textColor="@color/card_textcolor_regular"
				    android:textSize="@dimen/card_textsize_regular"
				    android:focusable="true"
				    android:ellipsize="none"
				    android:scrollHorizontally="false"
				/>

			</LinearLayout>
		</ScrollView>

	<LinearLayout
	    android:orientation="vertical"
	    android:layout_width="fill_parent"
	    android:layout_height="wrap_content"
	    android:background="@color/navigation_bar_background"
	    android:layout_weight="0">

		<TableLayout
		    android:layout_width="fill_parent"
		    android:layout_height="wrap_content"
		    android:layout_centerVertical="true"
		    android:gravity="center_vertical"
		    android:stretchColumns="0,2"
		    android:weightSum="3"
		    android:paddingTop="1px"
		    android:paddingBottom="12px" >

			<TableRow
			    android:layout_weight="1"
			    android:gravity="center_vertical" >

				<Button
					android:id="@+id/btnNavigationBack"
					android:text="@string/btnNavigationBack"
					android:contentDescription="@string/btnNavigationBack"
					android:layout_weight="1"
				    android:layout_width="0dip"
				    android:layout_height="@dimen/navigation_bar_height"
					android:background="@color/navigation_bar_background"
				    android:textColor="@color/navigation_bar_textcolor"
				    android:textStyle="bold"
				    android:textSize="@dimen/card_textsize_navigation"
				    android:gravity="center"
					android:focusable="true"
				/>

				<TextView
					android:id="@+id/txtEmpty5"
					android:text="@string/txtEmpty"
				    android:layout_width="12px"
				    android:layout_height="1px"
				    android:background="@color/navigation_bar_background"
				    android:focusable="false"
				/>

				<Button
					android:id="@+id/btnNavigationHome"
					android:text="@string/btnNavigationHome"
					android:contentDescription="@string/btnNavigationHome"
					android:layout_weight="1"
				    android:layout_width="0dip"
				    android:layout_height="@dimen/navigation_bar_height"
					android:background="@color/navigation_bar_background"
				    android:textColor="@color/navigation_bar_textcolor"
				    android:textStyle="bold"
				    android:textSize="@dimen/card_textsize_navigation"
				    android:gravity="center"
					android:focusable="true"
				/>
			</TableRow>
		</TableLayout>
	</LinearLayout>

</LinearLayout>


text:
\documentclass[12pt,a4paper]{article}
\usepackage{graphicx}
\usepackage[margin=0.5in]{geometry}
\begin{document}
\thispagestyle{empty}
\begin{table}[]
\centering
\Huge
\begin{tabular}{cccc}
 Seahorse& Hat& Pillow& Towel\\  & & & \\
 Sushi& Fridge& Sun& Blender\\  & & & \\
 Door& Mirror& Zebra& Oven\\  & & & \\
 Guitar& Wheel& Fan& Spoon\\  & & & \\
 Shark& Owl& Star& Tea Pot\\  & & & \\
\end{tabular}
\end{table}
\end{document}


text:
package org.onosproject.incubator.net.virtual.provider;

import org.onosproject.incubator.net.virtual.NetworkId;
import org.onosproject.net.DeviceId;
import org.onosproject.net.provider.ProviderId;

import java.util.Set;

/**
 * Registry for tracking information providers with the core.
 */
public interface VirtualProviderRegistryService {

    /**
     * Registers the supplied virtual provider.
     *
     * @param virtualProvider a virtual provider to be registered
     * @throws java.lang.IllegalArgumentException if the provider is registered already
     */
    void registerProvider(VirtualProvider virtualProvider);

    /**
     * Unregisters the supplied virtual provider.
     * As a result the previously issued virtual provider service will be invalidated
     * and any subsequent invocations of its methods may throw
     * {@link java.lang.IllegalStateException}.
     * <p>
     * Unregistering a virtual provider that has not been previously registered results
     * in a no-op.
     * </p>
     *
     * @param virtualProvider a virtual provider to be unregistered
     */
    void unregisterProvider(VirtualProvider virtualProvider);

    /**
     * Registers the supplied virtual provider.
     *
     * @param networkId a virtual network identifier
     * @param virtualProviderService a virtual provider service to be registered
     */
    void registerProviderService(NetworkId networkId,
                                 VirtualProviderService virtualProviderService);

    /**
     * Unregisters the supplied virtual provider service.
     *
     * @param networkId a virtual network identifier
     * @param virtualProviderService a virtual provider service to be unregistered
     */
    void unregisterProviderService(NetworkId networkId,
                                   VirtualProviderService virtualProviderService);

    /**
     * Returns a set of currently registered virtual provider identities.
     *
     * @return set of virtual provider identifiers
     */
    Set<ProviderId> getProviders();

    /**
     * Returns a set of currently registered virtual provider identities
     * corresponding to the requested providerService.
     *
     * @param virtualProviderService a virtual provider service
     * @return set of virtual provider identifiers
     */
    Set<ProviderId> getProvidersByService(VirtualProviderService virtualProviderService);

    /**
     * Returns the virtual provider registered with the specified provider ID or null
     * if none is found for the given provider family and default fall-back is
     * not supported.
     *
     * @param providerId provider identifier
     * @return provider
     */
    VirtualProvider getProvider(ProviderId providerId);

    /**
     * Returns the virtual provider for the specified device ID based on URI scheme.
     *
     * @param deviceId virtual device identifier
     * @return provider bound to the URI scheme
     */
    VirtualProvider getProvider(DeviceId deviceId);

    /**
     * Returns the virtual provider registered with the specified scheme.
     *
     * @param scheme provider scheme
     * @return provider
     */
    VirtualProvider getProvider(String scheme);

    /**
     * Returns a virtual provider service corresponding to
     * the virtual network and provider class type.
     *
     * @param networkId a virtual network identifier
     * @param providerClass a type of virtual provider
     * @return a virtual provider service
     */
    VirtualProviderService getProviderService(NetworkId networkId,
                                              Class<? extends VirtualProvider> providerClass);
}


text:
<?php

/**
 * Single line text input control.
 *
 * @copyright  Copyright (c) 2004, 2010 David Grudl
 * @package    Nette\Forms
 */
class TextInput extends TextBase
{

	/**
	 * @param  string  control name
	 * @param  string  label
	 * @param  int  width of the control
	 * @param  int  maximum number of characters the user may enter
	 */
	public function __construct($label = NULL, $cols = NULL, $maxLength = NULL)
	{
		parent::__construct($label);
		$this->control->type = 'text';
		$this->control->size = $cols;
		$this->control->maxlength = $maxLength;
		$this->filters[] = callback('String', 'trim');
		$this->filters[] = callback($this, 'checkMaxLength');
		$this->value = '';
	}

	/**
	 * Filter: shortens value to control's max length.
	 * @return string
	 */
	public function checkMaxLength($value)
	{
		if ($this->control->maxlength && iconv_strlen($value, 'UTF-8') > $this->control->maxlength) {
			$value = iconv_substr($value, 0, $this->control->maxlength, 'UTF-8');
		}
		return $value;
	}

	/**
	 * Sets or unsets the password mode.
	 * @param  bool
	 * @return TextInput  provides a fluent interface
	 */
	public function setPasswordMode($mode = TRUE)
	{
		$this->control->type = $mode ? 'password' : 'text';
		return $this;
	}

	/**
	 * Generates control's HTML element.
	 * @return Html
	 */
	public function getControl()
	{
		$control = parent::getControl();
		if ($this->control->type !== 'password') {
			$control->value = $this->getValue() === '' ? $this->translate($this->emptyValue) : $this->value;
		}
		return $control;
	}

	public function notifyRule(Rule $rule)
	{
		if (is_string($rule->operation) && strcasecmp($rule->operation, ':length') === 0 && !$rule->isNegative) {
			$this->control->maxlength = is_array($rule->arg) ? $rule->arg[1] : $rule->arg;

		} elseif (is_string($rule->operation) && strcasecmp($rule->operation, ':maxLength') === 0 && !$rule->isNegative) {
			$this->control->maxlength = $rule->arg;
		}

		parent::notifyRule($rule);
	}

}


text:
angular.module('wwwApp').controller('FaqCtrl', ['$scope', function ($scope) {
  'use strict';

}]);


text:
@interface RACObservablePropertySubject : RACPropertySubject

// Returns a new RACPropertySubject wrapper for `keyPath` on `target` with a
// starting value equal to the value of `keyPath` on `target`.
+ (instancetype)propertyWithTarget:(id)target keyPath:(NSString *)keyPath;

@end

// Methods needed for the convenience macro. Do not call explicitly.
@interface RACObservablePropertySubject (RACBind)

- (id)objectForKeyedSubscript:(id)key;
- (void)setObject:(id)obj forKeyedSubscript:(id)key;

@end


text:
using NUnit.Framework;
using QuantConnect.Data.Market;
using QuantConnect.Indicators;

namespace QuantConnect.Tests.Indicators
{
    [TestFixture]
    public class AccumulationDistributionOscillatorTests : CommonIndicatorTests<TradeBar>
    {
        protected override IndicatorBase<TradeBar> CreateIndicator()
        {
            return new AccumulationDistributionOscillator(3, 10);
        }

        protected override string TestFileName
        {
            get { return "spy_ad_osc.txt"; }
        }

        protected override string TestColumnName
        {
            get { return "AdOsc_3_10"; }
        }
    }
}


text:
/**
 * Autogenerated by Thrift Compiler (0.9.1)
 *
 * DO NOT EDIT UNLESS YOU ARE SURE THAT YOU KNOW WHAT YOU ARE DOING
 *  @generated
 */
package com.sina.recomm.engine.idl;

import org.apache.thrift.scheme.IScheme;
import org.apache.thrift.scheme.SchemeFactory;
import org.apache.thrift.scheme.StandardScheme;

import org.apache.thrift.scheme.TupleScheme;
import org.apache.thrift.protocol.TTupleProtocol;
import org.apache.thrift.protocol.TProtocolException;
import org.apache.thrift.EncodingUtils;
import org.apache.thrift.TException;
import org.apache.thrift.async.AsyncMethodCallback;
import org.apache.thrift.server.AbstractNonblockingServer.*;
import java.util.List;
import java.util.ArrayList;
import java.util.Map;
import java.util.HashMap;
import java.util.EnumMap;
import java.util.Set;
import java.util.HashSet;
import java.util.EnumSet;
import java.util.Collections;
import java.util.BitSet;
import java.nio.ByteBuffer;
import java.util.Arrays;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

public class RetrievalRequest implements org.apache.thrift.TBase<RetrievalRequest, RetrievalRequest._Fields>, java.io.Serializable, Cloneable, Comparable<RetrievalRequest> {
  private static final org.apache.thrift.protocol.TStruct STRUCT_DESC = new org.apache.thrift.protocol.TStruct("RetrievalRequest");

  private static final org.apache.thrift.protocol.TField KEYWORDS_FIELD_DESC = new org.apache.thrift.protocol.TField("keywords", org.apache.thrift.protocol.TType.LIST, (short)1);
  private static final org.apache.thrift.protocol.TField DEBUG_LEVEL_FIELD_DESC = new org.apache.thrift.protocol.TField("debug_level", org.apache.thrift.protocol.TType.I16, (short)2);
  private static final org.apache.thrift.protocol.TField LOG_LEVEL_FIELD_DESC = new org.apache.thrift.protocol.TField("log_level", org.apache.thrift.protocol.TType.I16, (short)3);

  private static final Map<Class<? extends IScheme>, SchemeFactory> schemes = new HashMap<Class<? extends IScheme>, SchemeFactory>();
  static {
    schemes.put(StandardScheme.class, new RetrievalRequestStandardSchemeFactory());
    schemes.put(TupleScheme.class, new RetrievalRequestTupleSchemeFactory());
  }

  public List<RetrievalRequestInfo> keywords; // required
  public short debug_level; // optional
  public short log_level; // optional

  /** The set of fields this struct contains, along with convenience methods for finding and manipulating them. */
  public enum _Fields implements org.apache.thrift.TFieldIdEnum {
    KEYWORDS((short)1, "keywords"),
    DEBUG_LEVEL((short)2, "debug_level"),
    LOG_LEVEL((short)3, "log_level");

    private static final Map<String, _Fields> byName = new HashMap<String, _Fields>();

    static {
      for (_Fields field : EnumSet.allOf(_Fields.class)) {
        byName.put(field.getFieldName(), field);
      }
    }

    /**
     * Find the _Fields constant that matches fieldId, or null if its not found.
     */
    public static _Fields findByThriftId(int fieldId) {
      switch(fieldId) {
        case 1: // KEYWORDS
          return KEYWORDS;
        case 2: // DEBUG_LEVEL
          return DEBUG_LEVEL;
        case 3: // LOG_LEVEL
          return LOG_LEVEL;
        default:
          return null;
      }
    }

    /**
     * Find the _Fields constant that matches fieldId, throwing an exception
     * if it is not found.
     */
    public static _Fields findByThriftIdOrThrow(int fieldId) {
      _Fields fields = findByThriftId(fieldId);
      if (fields == null) throw new IllegalArgumentException("Field " + fieldId + " doesn't exist!");
      return fields;
    }

    /**
     * Find the _Fields constant that matches name, or null if its not found.
     */
    public static _Fields findByName(String name) {
      return byName.get(name);
    }

    private final short _thriftId;
    private final String _fieldName;

    _Fields(short thriftId, String fieldName) {
      _thriftId = thriftId;
      _fieldName = fieldName;
    }

    public short getThriftFieldId() {
      return _thriftId;
    }

    public String getFieldName() {
      return _fieldName;
    }
  }

  // isset id assignments
  private static final int __DEBUG_LEVEL_ISSET_ID = 0;
  private static final int __LOG_LEVEL_ISSET_ID = 1;
  private byte __isset_bitfield = 0;
  private _Fields optionals[] = {_Fields.DEBUG_LEVEL,_Fields.LOG_LEVEL};
  public static final Map<_Fields, org.apache.thrift.meta_data.FieldMetaData> metaDataMap;
  static {
    Map<_Fields, org.apache.thrift.meta_data.FieldMetaData> tmpMap = new EnumMap<_Fields, org.apache.thrift.meta_data.FieldMetaData>(_Fields.class);
    tmpMap.put(_Fields.KEYWORDS, new org.apache.thrift.meta_data.FieldMetaData("keywords", org.apache.thrift.TFieldRequirementType.REQUIRED,
        new org.apache.thrift.meta_data.ListMetaData(org.apache.thrift.protocol.TType.LIST,
            new org.apache.thrift.meta_data.StructMetaData(org.apache.thrift.protocol.TType.STRUCT, RetrievalRequestInfo.class))));
    tmpMap.put(_Fields.DEBUG_LEVEL, new org.apache.thrift.meta_data.FieldMetaData("debug_level", org.apache.thrift.TFieldRequirementType.OPTIONAL,
        new org.apache.thrift.meta_data.FieldValueMetaData(org.apache.thrift.protocol.TType.I16)));
    tmpMap.put(_Fields.LOG_LEVEL, new org.apache.thrift.meta_data.FieldMetaData("log_level", org.apache.thrift.TFieldRequirementType.OPTIONAL,
        new org.apache.thrift.meta_data.FieldValueMetaData(org.apache.thrift.protocol.TType.I16)));
    metaDataMap = Collections.unmodifiableMap(tmpMap);
    org.apache.thrift.meta_data.FieldMetaData.addStructMetaDataMap(RetrievalRequest.class, metaDataMap);
  }

  public RetrievalRequest() {
    this.debug_level = (short)0;

    this.log_level = (short)0;

  }

  public RetrievalRequest(
    List<RetrievalRequestInfo> keywords)
  {
    this();
    this.keywords = keywords;
  }

  /**
   * Performs a deep copy on <i>other</i>.
   */
  public RetrievalRequest(RetrievalRequest other) {
    __isset_bitfield = other.__isset_bitfield;
    if (other.isSetKeywords()) {
      List<RetrievalRequestInfo> __this__keywords = new ArrayList<RetrievalRequestInfo>(other.keywords.size());
      for (RetrievalRequestInfo other_element : other.keywords) {
        __this__keywords.add(new RetrievalRequestInfo(other_element));
      }
      this.keywords = __this__keywords;
    }
    this.debug_level = other.debug_level;
    this.log_level = other.log_level;
  }

  public RetrievalRequest deepCopy() {
    return new RetrievalRequest(this);
  }

  @Override
  public void clear() {
    this.keywords = null;
    this.debug_level = (short)0;

    this.log_level = (short)0;

  }

  public int getKeywordsSize() {
    return (this.keywords == null) ? 0 : this.keywords.size();
  }

  public java.util.Iterator<RetrievalRequestInfo> getKeywordsIterator() {
    return (this.keywords == null) ? null : this.keywords.iterator();
  }

  public void addToKeywords(RetrievalRequestInfo elem) {
    if (this.keywords == null) {
      this.keywords = new ArrayList<RetrievalRequestInfo>();
    }
    this.keywords.add(elem);
  }

  public List<RetrievalRequestInfo> getKeywords() {
    return this.keywords;
  }

  public RetrievalRequest setKeywords(List<RetrievalRequestInfo> keywords) {
    this.keywords = keywords;
    return this;
  }

  public void unsetKeywords() {
    this.keywords = null;
  }

  /** Returns true if field keywords is set (has been assigned a value) and false otherwise */
  public boolean isSetKeywords() {
    return this.keywords != null;
  }

  public void setKeywordsIsSet(boolean value) {
    if (!value) {
      this.keywords = null;
    }
  }

  public short getDebug_level() {
    return this.debug_level;
  }

  public RetrievalRequest setDebug_level(short debug_level) {
    this.debug_level = debug_level;
    setDebug_levelIsSet(true);
    return this;
  }

  public void unsetDebug_level() {
    __isset_bitfield = EncodingUtils.clearBit(__isset_bitfield, __DEBUG_LEVEL_ISSET_ID);
  }

  /** Returns true if field debug_level is set (has been assigned a value) and false otherwise */
  public boolean isSetDebug_level() {
    return EncodingUtils.testBit(__isset_bitfield, __DEBUG_LEVEL_ISSET_ID);
  }

  public void setDebug_levelIsSet(boolean value) {
    __isset_bitfield = EncodingUtils.setBit(__isset_bitfield, __DEBUG_LEVEL_ISSET_ID, value);
  }

  public short getLog_level() {
    return this.log_level;
  }

  public RetrievalRequest setLog_level(short log_level) {
    this.log_level = log_level;
    setLog_levelIsSet(true);
    return this;
  }

  public void unsetLog_level() {
    __isset_bitfield = EncodingUtils.clearBit(__isset_bitfield, __LOG_LEVEL_ISSET_ID);
  }

  /** Returns true if field log_level is set (has been assigned a value) and false otherwise */
  public boolean isSetLog_level() {
    return EncodingUtils.testBit(__isset_bitfield, __LOG_LEVEL_ISSET_ID);
  }

  public void setLog_levelIsSet(boolean value) {
    __isset_bitfield = EncodingUtils.setBit(__isset_bitfield, __LOG_LEVEL_ISSET_ID, value);
  }

  public void setFieldValue(_Fields field, Object value) {
    switch (field) {
    case KEYWORDS:
      if (value == null) {
        unsetKeywords();
      } else {
        setKeywords((List<RetrievalRequestInfo>)value);
      }
      break;

    case DEBUG_LEVEL:
      if (value == null) {
        unsetDebug_level();
      } else {
        setDebug_level((Short)value);
      }
      break;

    case LOG_LEVEL:
      if (value == null) {
        unsetLog_level();
      } else {
        setLog_level((Short)value);
      }
      break;

    }
  }

  public Object getFieldValue(_Fields field) {
    switch (field) {
    case KEYWORDS:
      return getKeywords();

    case DEBUG_LEVEL:
      return Short.valueOf(getDebug_level());

    case LOG_LEVEL:
      return Short.valueOf(getLog_level());

    }
    throw new IllegalStateException();
  }

  /** Returns true if field corresponding to fieldID is set (has been assigned a value) and false otherwise */
  public boolean isSet(_Fields field) {
    if (field == null) {
      throw new IllegalArgumentException();
    }

    switch (field) {
    case KEYWORDS:
      return isSetKeywords();
    case DEBUG_LEVEL:
      return isSetDebug_level();
    case LOG_LEVEL:
      return isSetLog_level();
    }
    throw new IllegalStateException();
  }

  @Override
  public boolean equals(Object that) {
    if (that == null)
      return false;
    if (that instanceof RetrievalRequest)
      return this.equals((RetrievalRequest)that);
    return false;
  }

  public boolean equals(RetrievalRequest that) {
    if (that == null)
      return false;

    boolean this_present_keywords = true && this.isSetKeywords();
    boolean that_present_keywords = true && that.isSetKeywords();
    if (this_present_keywords || that_present_keywords) {
      if (!(this_present_keywords && that_present_keywords))
        return false;
      if (!this.keywords.equals(that.keywords))
        return false;
    }

    boolean this_present_debug_level = true && this.isSetDebug_level();
    boolean that_present_debug_level = true && that.isSetDebug_level();
    if (this_present_debug_level || that_present_debug_level) {
      if (!(this_present_debug_level && that_present_debug_level))
        return false;
      if (this.debug_level != that.debug_level)
        return false;
    }

    boolean this_present_log_level = true && this.isSetLog_level();
    boolean that_present_log_level = true && that.isSetLog_level();
    if (this_present_log_level || that_present_log_level) {
      if (!(this_present_log_level && that_present_log_level))
        return false;
      if (this.log_level != that.log_level)
        return false;
    }

    return true;
  }

  @Override
  public int hashCode() {
    return 0;
  }

  @Override
  public int compareTo(RetrievalRequest other) {
    if (!getClass().equals(other.getClass())) {
      return getClass().getName().compareTo(other.getClass().getName());
    }

    int lastComparison = 0;

    lastComparison = Boolean.valueOf(isSetKeywords()).compareTo(other.isSetKeywords());
    if (lastComparison != 0) {
      return lastComparison;
    }
    if (isSetKeywords()) {
      lastComparison = org.apache.thrift.TBaseHelper.compareTo(this.keywords, other.keywords);
      if (lastComparison != 0) {
        return lastComparison;
      }
    }
    lastComparison = Boolean.valueOf(isSetDebug_level()).compareTo(other.isSetDebug_level());
    if (lastComparison != 0) {
      return lastComparison;
    }
    if (isSetDebug_level()) {
      lastComparison = org.apache.thrift.TBaseHelper.compareTo(this.debug_level, other.debug_level);
      if (lastComparison != 0) {
        return lastComparison;
      }
    }
    lastComparison = Boolean.valueOf(isSetLog_level()).compareTo(other.isSetLog_level());
    if (lastComparison != 0) {
      return lastComparison;
    }
    if (isSetLog_level()) {
      lastComparison = org.apache.thrift.TBaseHelper.compareTo(this.log_level, other.log_level);
      if (lastComparison != 0) {
        return lastComparison;
      }
    }
    return 0;
  }

  public _Fields fieldForId(int fieldId) {
    return _Fields.findByThriftId(fieldId);
  }

  public void read(org.apache.thrift.protocol.TProtocol iprot) throws org.apache.thrift.TException {
    schemes.get(iprot.getScheme()).getScheme().read(iprot, this);
  }

  public void write(org.apache.thrift.protocol.TProtocol oprot) throws org.apache.thrift.TException {
    schemes.get(oprot.getScheme()).getScheme().write(oprot, this);
  }

  @Override
  public String toString() {
    StringBuilder sb = new StringBuilder("RetrievalRequest(");
    boolean first = true;

    sb.append("keywords:");
    if (this.keywords == null) {
      sb.append("null");
    } else {
      sb.append(this.keywords);
    }
    first = false;
    if (isSetDebug_level()) {
      if (!first) sb.append(", ");
      sb.append("debug_level:");
      sb.append(this.debug_level);
      first = false;
    }
    if (isSetLog_level()) {
      if (!first) sb.append(", ");
      sb.append("log_level:");
      sb.append(this.log_level);
      first = false;
    }
    sb.append(")");
    return sb.toString();
  }

  public void validate() throws org.apache.thrift.TException {
    // check for required fields
    if (keywords == null) {
      throw new org.apache.thrift.protocol.TProtocolException("Required field 'keywords' was not present! Struct: " + toString());
    }
    // check for sub-struct validity
  }

  private void writeObject(java.io.ObjectOutputStream out) throws java.io.IOException {
    try {
      write(new org.apache.thrift.protocol.TCompactProtocol(new org.apache.thrift.transport.TIOStreamTransport(out)));
    } catch (org.apache.thrift.TException te) {
      throw new java.io.IOException(te);
    }
  }

  private void readObject(java.io.ObjectInputStream in) throws java.io.IOException, ClassNotFoundException {
    try {
      // it doesn't seem like you should have to do this, but java serialization is wacky, and doesn't call the default constructor.
      __isset_bitfield = 0;
      read(new org.apache.thrift.protocol.TCompactProtocol(new org.apache.thrift.transport.TIOStreamTransport(in)));
    } catch (org.apache.thrift.TException te) {
      throw new java.io.IOException(te);
    }
  }

  private static class RetrievalRequestStandardSchemeFactory implements SchemeFactory {
    public RetrievalRequestStandardScheme getScheme() {
      return new RetrievalRequestStandardScheme();
    }
  }

  private static class RetrievalRequestStandardScheme extends StandardScheme<RetrievalRequest> {

    public void read(org.apache.thrift.protocol.TProtocol iprot, RetrievalRequest struct) throws org.apache.thrift.TException {
      org.apache.thrift.protocol.TField schemeField;
      iprot.readStructBegin();
      while (true)
      {
        schemeField = iprot.readFieldBegin();
        if (schemeField.type == org.apache.thrift.protocol.TType.STOP) {
          break;
        }
        switch (schemeField.id) {
          case 1: // KEYWORDS
            if (schemeField.type == org.apache.thrift.protocol.TType.LIST) {
              {
                org.apache.thrift.protocol.TList _list60 = iprot.readListBegin();
                struct.keywords = new ArrayList<RetrievalRequestInfo>(_list60.size);
                for (int _i61 = 0; _i61 < _list60.size; ++_i61)
                {
                  RetrievalRequestInfo _elem62;
                  _elem62 = new RetrievalRequestInfo();
                  _elem62.read(iprot);
                  struct.keywords.add(_elem62);
                }
                iprot.readListEnd();
              }
              struct.setKeywordsIsSet(true);
            } else {
              org.apache.thrift.protocol.TProtocolUtil.skip(iprot, schemeField.type);
            }
            break;
          case 2: // DEBUG_LEVEL
            if (schemeField.type == org.apache.thrift.protocol.TType.I16) {
              struct.debug_level = iprot.readI16();
              struct.setDebug_levelIsSet(true);
            } else {
              org.apache.thrift.protocol.TProtocolUtil.skip(iprot, schemeField.type);
            }
            break;
          case 3: // LOG_LEVEL
            if (schemeField.type == org.apache.thrift.protocol.TType.I16) {
              struct.log_level = iprot.readI16();
              struct.setLog_levelIsSet(true);
            } else {
              org.apache.thrift.protocol.TProtocolUtil.skip(iprot, schemeField.type);
            }
            break;
          default:
            org.apache.thrift.protocol.TProtocolUtil.skip(iprot, schemeField.type);
        }
        iprot.readFieldEnd();
      }
      iprot.readStructEnd();

      // check for required fields of primitive type, which can't be checked in the validate method
      struct.validate();
    }

    public void write(org.apache.thrift.protocol.TProtocol oprot, RetrievalRequest struct) throws org.apache.thrift.TException {
      struct.validate();

      oprot.writeStructBegin(STRUCT_DESC);
      if (struct.keywords != null) {
        oprot.writeFieldBegin(KEYWORDS_FIELD_DESC);
        {
          oprot.writeListBegin(new org.apache.thrift.protocol.TList(org.apache.thrift.protocol.TType.STRUCT, struct.keywords.size()));
          for (RetrievalRequestInfo _iter63 : struct.keywords)
          {
            _iter63.write(oprot);
          }
          oprot.writeListEnd();
        }
        oprot.writeFieldEnd();
      }
      if (struct.isSetDebug_level()) {
        oprot.writeFieldBegin(DEBUG_LEVEL_FIELD_DESC);
        oprot.writeI16(struct.debug_level);
        oprot.writeFieldEnd();
      }
      if (struct.isSetLog_level()) {
        oprot.writeFieldBegin(LOG_LEVEL_FIELD_DESC);
        oprot.writeI16(struct.log_level);
        oprot.writeFieldEnd();
      }
      oprot.writeFieldStop();
      oprot.writeStructEnd();
    }

  }

  private static class RetrievalRequestTupleSchemeFactory implements SchemeFactory {
    public RetrievalRequestTupleScheme getScheme() {
      return new RetrievalRequestTupleScheme();
    }
  }

  private static class RetrievalRequestTupleScheme extends TupleScheme<RetrievalRequest> {

    @Override
    public void write(org.apache.thrift.protocol.TProtocol prot, RetrievalRequest struct) throws org.apache.thrift.TException {
      TTupleProtocol oprot = (TTupleProtocol) prot;
      {
        oprot.writeI32(struct.keywords.size());
        for (RetrievalRequestInfo _iter64 : struct.keywords)
        {
          _iter64.write(oprot);
        }
      }
      BitSet optionals = new BitSet();
      if (struct.isSetDebug_level()) {
        optionals.set(0);
      }
      if (struct.isSetLog_level()) {
        optionals.set(1);
      }
      oprot.writeBitSet(optionals, 2);
      if (struct.isSetDebug_level()) {
        oprot.writeI16(struct.debug_level);
      }
      if (struct.isSetLog_level()) {
        oprot.writeI16(struct.log_level);
      }
    }

    @Override
    public void read(org.apache.thrift.protocol.TProtocol prot, RetrievalRequest struct) throws org.apache.thrift.TException {
      TTupleProtocol iprot = (TTupleProtocol) prot;
      {
        org.apache.thrift.protocol.TList _list65 = new org.apache.thrift.protocol.TList(org.apache.thrift.protocol.TType.STRUCT, iprot.readI32());
        struct.keywords = new ArrayList<RetrievalRequestInfo>(_list65.size);
        for (int _i66 = 0; _i66 < _list65.size; ++_i66)
        {
          RetrievalRequestInfo _elem67;
          _elem67 = new RetrievalRequestInfo();
          _elem67.read(iprot);
          struct.keywords.add(_elem67);
        }
      }
      struct.setKeywordsIsSet(true);
      BitSet incoming = iprot.readBitSet(2);
      if (incoming.get(0)) {
        struct.debug_level = iprot.readI16();
        struct.setDebug_levelIsSet(true);
      }
      if (incoming.get(1)) {
        struct.log_level = iprot.readI16();
        struct.setLog_levelIsSet(true);
      }
    }
  }

}


text:
package moe.pizza.auth.adapters

import java.io.File
import java.util.UUID

import moe.pizza.auth.ldap.client.LdapClient
import moe.pizza.auth.ldap.client.LdapClient._
import moe.pizza.auth.ldap.server.EmbeddedLdapServer
import moe.pizza.auth.models.Pilot
import org.apache.directory.api.ldap.model.entry.DefaultEntry
import org.scalatest.{FlatSpec, MustMatchers}

/**
  * Created by andi on 18/02/16.
  */
class LdapUserDatabaseSpec extends FlatSpec with MustMatchers {

  def createTempFolder(suffix: String): File = {
    val base = new File(new File(System.getProperty("java.io.tmpdir")),
                        "pizza-auth-test")
    base.delete()
    val dir = new File(base, UUID.randomUUID().toString + suffix)
    dir.mkdirs()
    dir
  }

  "inserting a user into LDAP" should "create the entry in a way that can be extracted again" in {
    val tempfolder = createTempFolder("loadusertest")
    try {
      val server = new EmbeddedLdapServer(tempfolder.toString,
                                          "ou=pizza",
                                          "localhost",
                                          3390,
                                          instanceName =
                                            "pizza-auth-ldap-user-db-spec")
      server.setPassword("testpassword")
      server.start()
      // TODO find a way to make a schemamanager without the server
      val schema = server.directoryService.getSchemaManager
      // use the client
      val c = new LdapClient("localhost",
                             3390,
                             "uid=admin,ou=system",
                             "testpassword")
      // wrap it in an LUD
      val lud = new LdapUserDatabase(c, schema, "ou=pizza")
      val p = new Pilot("lucia_denniard",
                        Pilot.Status.internal,
                        "Confederation of xXPIZZAXx",
                        "Love Squad",
                        "Lucia Denniard",
                        "lucia@pizza.moe",
                        Pilot.OM.createObjectNode(),
                        List(),
                        List(),
                        List())
      lud.addUser(p, "luciapassword") must equal(true)
      c.withConnection { con =>
        val r = con.filter("ou=pizza", "(uid=lucia_denniard)")
        val user = r.toList.headOption.map(_.toMap).map(Pilot.fromMap)
        user must equal(Some(p))
      }
      server.stop()
    } finally {
      tempfolder.delete()
    }
  }

  "inserting a user into LDAP then reading it back out" should "create the entry in a way that can be extracted again" in {
    val tempfolder = createTempFolder("loadusertest2")
    try {
      val server = new EmbeddedLdapServer(tempfolder.toString,
                                          "ou=pizza",
                                          "localhost",
                                          3391,
                                          instanceName =
                                            "pizza-auth-ldap-user-db-spec-1")
      server.setPassword("testpassword")
      server.start()
      // TODO find a way to make a schemamanager without the server
      val schema = server.directoryService.getSchemaManager
      // use the client
      val c = new LdapClient("localhost",
                             3391,
                             "uid=admin,ou=system",
                             "testpassword")
      // wrap it in an LUD
      val lud = new LdapUserDatabase(c, schema, "ou=pizza")
      val p = new Pilot("lucia_denniard",
                        Pilot.Status.internal,
                        "Confederation of xXPIZZAXx",
                        "Love Squad",
                        "Lucia Denniard",
                        "lucia@pizza.moe",
                        Pilot.OM.createObjectNode(),
                        List(),
                        List(),
                        List())
      lud.addUser(p, "luciapassword") must equal(true)
      lud.getUser("lucia_denniard") must equal(Some(p))
      val p2 = new Pilot("lucia_denniard2",
                         Pilot.Status.internal,
                         "Confederation of xXPIZZAXx",
                         "Love Squad",
                         "Lucia Denniard",
                         "lucia@pizza.moe",
                         Pilot.OM.createObjectNode(),
                         List(),
                         List("cresttoken"),
                         List())
      lud.addUser(p2, "luciapassword") must equal(true)
      lud.getUser("lucia_denniard2") must equal(Some(p2))
      server.stop()
    } finally {
      tempfolder.delete()
    }
  }

  "inserting a user into LDAP then authenticating with it" should "authenticate with the right password" in {
    val tempfolder = createTempFolder("loadusertest2")
    try {
      val server = new EmbeddedLdapServer(tempfolder.toString,
                                          "ou=pizza",
                                          "localhost",
                                          3392,
                                          instanceName =
                                            "pizza-auth-ldap-user-db-spec-2")
      server.setPassword("testpassword")
      server.start()
      // TODO find a way to make a schemamanager without the server
      val schema = server.directoryService.getSchemaManager
      // use the client
      val c = new LdapClient("localhost",
                             3392,
                             "uid=admin,ou=system",
                             "testpassword")
      // wrap it in an LUD
      val lud = new LdapUserDatabase(c, schema, "ou=pizza")
      val p = new Pilot("lucia_denniard",
                        Pilot.Status.internal,
                        "Confederation of xXPIZZAXx",
                        "Love Squad",
                        "Lucia Denniard",
                        "lucia@pizza.moe",
                        Pilot.OM.createObjectNode(),
                        List(),
                        List(),
                        List())
      lud.addUser(p, "luciapassword") must equal(true)
      lud.getUser("lucia_denniard") must equal(Some(p))
      lud.authenticateUser("lucia_denniard", "notluciapassword") must equal(
        None)
      lud.authenticateUser("lucia_denniard", "luciapassword") must equal(
        Some(p))
      server.stop()
    } finally {
      tempfolder.delete()
    }
  }

  "inserting a user into LDAP and changing it's password" should "authenticate with the right passwords" in {
    val tempfolder = createTempFolder("loadusertest2")
    try {
      val server = new EmbeddedLdapServer(tempfolder.toString,
                                          "ou=pizza",
                                          "localhost",
                                          3393,
                                          instanceName =
                                            "pizza-auth-ldap-user-db-spec-3")
      server.setPassword("testpassword")
      server.start()
      // TODO find a way to make a schemamanager without the server
      val schema = server.directoryService.getSchemaManager
      // use the client
      val c = new LdapClient("localhost",
                             3393,
                             "uid=admin,ou=system",
                             "testpassword")
      // wrap it in an LUD
      val lud = new LdapUserDatabase(c, schema, "ou=pizza")
      val p = new Pilot("lucia_denniard",
                        Pilot.Status.internal,
                        "Confederation of xXPIZZAXx",
                        "Love Squad",
                        "Lucia Denniard",
                        "lucia@pizza.moe",
                        Pilot.OM.createObjectNode(),
                        List(),
                        List(),
                        List())
      lud.addUser(p, "luciapassword") must equal(true)
      lud.getUser("lucia_denniard") must equal(Some(p))
      lud.authenticateUser("lucia_denniard", "notluciapassword") must equal(
        None)
      lud.authenticateUser("lucia_denniard", "luciapassword") must equal(
        Some(p))
      lud.setPassword(p, "luciaNEWpassword") must equal(true)
      lud.authenticateUser("lucia_denniard", "luciapassword") must equal(None)
      lud.authenticateUser("lucia_denniard", "luciaNEWpassword") must equal(
        Some(p))
      server.stop()
    } finally {
      tempfolder.delete()
    }
  }

  "deleting a user" should "delete the user" in {
    val tempfolder = createTempFolder("loadusertest2")
    try {
      val server = new EmbeddedLdapServer(tempfolder.toString,
                                          "ou=pizza",
                                          "localhost",
                                          3394,
                                          instanceName =
                                            "pizza-auth-ldap-user-db-spec-4")
      server.setPassword("testpassword")
      server.start()
      // TODO find a way to make a schemamanager without the server
      val schema = server.directoryService.getSchemaManager
      // use the client
      val c = new LdapClient("localhost",
                             3394,
                             "uid=admin,ou=system",
                             "testpassword")
      // wrap it in an LUD
      val lud = new LdapUserDatabase(c, schema, "ou=pizza")
      val p = new Pilot("lucia_denniard",
                        Pilot.Status.internal,
                        "Confederation of xXPIZZAXx",
                        "Love Squad",
                        "Lucia Denniard",
                        "lucia@pizza.moe",
                        Pilot.OM.createObjectNode(),
                        List(),
                        List(),
                        List())
      lud.addUser(p, "luciapassword") must equal(true)
      lud.getUser("lucia_denniard") must equal(Some(p))
      lud.authenticateUser("lucia_denniard", "notluciapassword") must equal(
        None)
      lud.authenticateUser("lucia_denniard", "luciapassword") must equal(
        Some(p))
      lud.setPassword(p, "luciaNEWpassword") must equal(true)
      lud.authenticateUser("lucia_denniard", "luciapassword") must equal(None)
      lud.authenticateUser("lucia_denniard", "luciaNEWpassword") must equal(
        Some(p))
      lud.getUsers("uid=lucia_denniard") must equal(List(p))
      lud.getAllUsers() must equal(Seq(p))
      lud.deleteUser(p) must equal(true)
      lud.getUser("lucia_denniard") must equal(None)
      lud.getAllUsers() must equal(Seq())
      lud.getUsers("uid=lucia_denniard") must equal(List())
      server.stop()
    } finally {
      tempfolder.delete()
    }
  }
  "updating users" should "update users" in {
    val tempfolder = createTempFolder("loadusertest2")
    try {
      val server = new EmbeddedLdapServer(tempfolder.toString,
                                          "ou=pizza",
                                          "localhost",
                                          3395,
                                          instanceName =
                                            "pizza-auth-ldap-user-db-spec-5")
      server.setPassword("testpassword")
      server.start()
      // TODO find a way to make a schemamanager without the server
      val schema = server.directoryService.getSchemaManager
      // use the client
      val c = new LdapClient("localhost",
                             3395,
                             "uid=admin,ou=system",
                             "testpassword")
      // wrap it in an LUD
      val lud = new LdapUserDatabase(c, schema, "ou=pizza")
      val p = new Pilot("lucia_denniard",
                        Pilot.Status.internal,
                        "Confederation of xXPIZZAXx",
                        "Love Squad",
                        "Lucia Denniard",
                        "lucia@pizza.moe",
                        Pilot.OM.createObjectNode(),
                        List(),
                        List(),
                        List())
      lud.addUser(p, "sluciapassword") must equal(true)
      val r = lud.getUser("lucia_denniard")
      val p2 = p.copy(alliance = "No Alliance")
      lud.updateUser(p2) must equal(true)
      lud.getUser("lucia_denniard") must equal(Some(p2))
      val p3 = p2.copy(corporation = "nocorp")
      lud.updateUser(p3) must equal(true)
      lud.getUser("lucia_denniard") must equal(Some(p3))
      val p4 = p3.copy(email = "otheremail")
      lud.updateUser(p4)
      lud.getUser("lucia_denniard") must equal(Some(p4))
      val p5 = p4.copy(accountStatus = Pilot.Status.ineligible)
      lud.updateUser(p5)
      lud.getUser("lucia_denniard") must equal(Some(p5))
      val p6 = p5.copy(authGroups = List("onegroup"))
      lud.updateUser(p6) must equal(true)
      lud.getUser("lucia_denniard") must equal(Some(p6))
      val p7 = p6.copy(authGroups = List("othergroup"))
      lud.updateUser(p7)
      lud.getUser("lucia_denniard") must equal(Some(p7))
      val p8 = p7.copy(crestTokens = List("mycresttoken"))
      lud.updateUser(p8)
      lud.getUser("lucia_denniard") must equal(Some(p8))
      val p9 = p8.copy(crestTokens = List("newcresttoken"))
      lud.updateUser(p9)
      lud.getUser("lucia_denniard") must equal(Some(p9))
      val p10 = p9.copy(apiKeys = List("apikey"))
      lud.updateUser(p10)
      lud.getUser("lucia_denniard") must equal(Some(p10))
      val p11 = p10.copy(apiKeys = List("newerapikey"))
      lud.updateUser(p11)
      lud.getUser("lucia_denniard") must equal(Some(p11))
      val p12 =
        p11.copy(metadata = Pilot.OM.readTree("{\"value\":\"imcool\"}"))
      lud.updateUser(p12)
      lud.getUser("lucia_denniard") must equal(Some(p12))
      server.stop()
    } finally {
      tempfolder.delete()
    }
  }
  "inserting a user into LDAP then searching for it with broadcast tools" should "return it when it matches the filters" in {
    val tempfolder = createTempFolder("loadusertest2")
    try {
      val server = new EmbeddedLdapServer(tempfolder.toString,
                                          "ou=pizza",
                                          "localhost",
                                          3391,
                                          instanceName =
                                            "pizza-auth-ldap-user-db-spec-6")
      server.setPassword("testpassword")
      server.start()
      // TODO find a way to make a schemamanager without the server
      val schema = server.directoryService.getSchemaManager
      // use the client
      val c = new LdapClient("localhost",
                             3391,
                             "uid=admin,ou=system",
                             "testpassword")
      // wrap it in an LUD
      val lud = new LdapUserDatabase(c, schema, "ou=pizza")
      val p = new Pilot("lucia_denniard",
                        Pilot.Status.internal,
                        "Confederation of xXPIZZAXx",
                        "Love Squad",
                        "Lucia Denniard",
                        "lucia@pizza.moe",
                        Pilot.OM.createObjectNode(),
                        List(),
                        List(),
                        List())
      lud.addUser(p, "luciapassword") must equal(true)
      lud.getUser("lucia_denniard") must equal(Some(p))

      // add to group
      lud.updateUser(p.copy(authGroups = List("titans")))
      val p2 = lud.getUser("lucia_denniard").get
      p2 must equal(p.copy(authGroups = List("titans")))

      import moe.pizza.auth.interfaces.BroadcastService.BroadcastableUserDatabase
      // search by group
      lud.getGroupUsers("titans") must equal(List(p2))
      // search by corp
      lud.getGroupUsers("Love Squad") must equal(List(p2))
      // search by alliance
      lud.getGroupUsers("Confederation of xXPIZZAXx") must equal(List(p2))

      server.stop()
    } finally {
      tempfolder.delete()
    }
  }

}


text:
package helloworld

import (
	"context"
	"encoding/json"
	"io/ioutil"
	"net/http"
	"net/http/httptest"
	"testing"

	compute "cloud.google.com/go/compute/apiv1"
	"github.com/cloudevents/sdk-go/v2/event"
	"google.golang.org/api/option"
	computepb "google.golang.org/genproto/googleapis/cloud/compute/v1"
	"google.golang.org/protobuf/encoding/protojson"
)

type FakeInstancesServer struct {
	http.ServeMux
	changedLabels map[string]string
	instance      *computepb.Instance
}

func NewFakeInstancesServer(i *computepb.Instance) *FakeInstancesServer {
	fake := &FakeInstancesServer{
		instance:      i,
		changedLabels: make(map[string]string),
	}
	fake.HandleFunc("/compute/v1/projects/PROJECT/zones/ZONE/instances/INSTANCE",
		func(w http.ResponseWriter, r *http.Request) {
			rbytes, err := protojson.Marshal(fake.instance)
			if err != nil {
				w.WriteHeader(http.StatusInternalServerError)
			}
			w.Write(rbytes)
		})
	fake.HandleFunc("/compute/v1/projects/PROJECT/zones/ZONE/instances/INSTANCE/setLabels",
		func(w http.ResponseWriter, r *http.Request) {
			var labelReq computepb.InstancesSetLabelsRequest
			body, err := ioutil.ReadAll(r.Body)
			if err != nil {
				w.WriteHeader(http.StatusInternalServerError)
				return
			}
			err = protojson.Unmarshal(body, &labelReq)
			if err != nil {
				w.WriteHeader(http.StatusInternalServerError)
				return
			}
			fake.changedLabels = labelReq.GetLabels()
			response, _ := protojson.Marshal(&computepb.Operation{})
			w.Write(response)
			w.WriteHeader(http.StatusOK)
		})
	fake.HandleFunc("/", func(w http.ResponseWriter, r *http.Request) {
		w.WriteHeader(http.StatusBadRequest)
	})
	return fake
}

func TestLabelGceInstance(t *testing.T) {
	tests := []struct {
		name       string
		payload    *AuditLogProtoPayload
		instance   *computepb.Instance
		newCreator string
	}{
		{
			name: "no label",
			payload: &AuditLogProtoPayload{
				MethodName:   "",
				ResourceName: "",
				AuthenticationInfo: map[string]interface{}{
					"principalEmail": "user@example.com",
				},
			},
			instance: &computepb.Instance{
				Hostname:         new(string),
				Id:               new(uint64),
				Kind:             new(string),
				LabelFingerprint: new(string),
				Labels:           map[string]string{},
				Name:             new(string),
				SelfLink:         new(string),
				Zone:             new(string),
			},
			newCreator: "user_example_com",
		},
		{
			name: "existing-creator",
			payload: &AuditLogProtoPayload{
				MethodName:   "",
				ResourceName: "",
				AuthenticationInfo: map[string]interface{}{
					"principalEmail": "user@example.com",
				},
			},
			instance: &computepb.Instance{
				Hostname:         new(string),
				Id:               new(uint64),
				Kind:             new(string),
				LabelFingerprint: new(string),
				Labels: map[string]string{
					"creator": "existing_creator",
				},
				Name:     new(string),
				SelfLink: new(string),
				Zone:     new(string),
			},
		},
	}
	for _, tt := range tests {
		t.Run(tt.name, func(t *testing.T) {

			fake := NewFakeInstancesServer(tt.instance)
			fakeserver := httptest.NewServer(fake)
			defer fakeserver.Close()

			var err error
			client, err = compute.NewInstancesRESTClient(context.Background(), option.WithEndpoint(fakeserver.URL))
			if err != nil {
				t.Fatalf("Failed to create mock client: %s", err)
			}
			e := event.New()
			e.SetSubject("compute.googleapis.com/projects/PROJECT/zones/ZONE/instances/INSTANCE")
			e.SetType("google.cloud.audit.log.v1.written")
			auditlog := &AuditLogEntry{
				ProtoPayload: tt.payload,
			}
			eventdata, err := json.Marshal(auditlog)
			if err != nil {
				t.Fatalf("failed to marshal json for test %s: %s", tt.name, err)
			}
			e.SetDataContentType("application/json")
			e.SetData("application/json", eventdata)

			if err := labelGceInstance(context.Background(), e); err != nil {
				t.Fatalf("LabelGceInstance(%s): unexpected error %s", tt.name, err)
			}
			// check that we updated creator label if expected.
			if tt.newCreator != "" {
				newvalue, ok := fake.changedLabels["creator"]
				if !ok || newvalue != tt.newCreator {
					t.Fatalf("LabelGceInstance(%s): incorrect creator label: got %s, want %s", tt.name, newvalue, tt.newCreator)
				}
			}

		})
	}
}


text:
#pragma once

#include <map>
#include <memory>
#include <string>
#include <unordered_set>
#include <vector>

#include "paddle/fluid/framework/ir/node.h"
#include "paddle/fluid/framework/program_desc.h"
#include "paddle/fluid/platform/enforce.h"
#include "paddle/fluid/platform/variant.h"

namespace paddle {
namespace framework {

namespace details {

// This attr is not recommended, because the graph should not dependence
// the program once it is built.
constexpr char kStaleProgramOpDescs[] = "stale_program_op_descs";
}  //  namespace details

namespace ir {

/*
 * The graph is a Directed Acyclic Single Static Assignment Graph.
 *
 * In more detail, the following properties must hold:
 *
 *   The graph shouldn't contain cycle. Each node is a black-box to the graph
 *   so the node itself could be a loop operator.
 *
 *   Each Variable-type node has only one input (thus single static assignment).
 *
 *   The output/input of operator is variable and the output/input of variable
 *   is operator.
 *
 * The following data harzards in Program are addressed in the Graph:
 *
 *   Write-After-Read
 *     a = op1(x)
 *     x = op2(b)
 *     A control-dependency connection is created bettwen op1 and op2 such that
 *     op1->op2, so as to ensure correct order.
 *
 *   Write-After-Write
 *     x = op1(a)
 *     x = op2(b)
 *     A control-dependency connection is created between op1 and op2 such that
 *     op1->op2, so as to ensure correct order.
 *
 * Other properties currently hold, but is not enforced yet:
 *
 *   Variable-type node (not control dep) with the same variable name share
 *   the same underlying VarDesc.
 */
class Graph {
 public:
  explicit Graph(const ProgramDesc &program);

  virtual ~Graph() {
    for (auto &attr : attrs_) {
      attr_dels_[attr.first]();
    }
    attrs_.clear();
    attr_dels_.clear();
  }

  bool Has(const std::string &attr_name) const {
    return attrs_.count(attr_name) > 0;
  }

  template <typename AttrType>
  AttrType &GetOrInit(const std::string &attr_name) {
    if (!Has(attr_name)) {
      Set(attr_name, new AttrType);
    }
    return Get<AttrType>(attr_name);
  }

  template <typename AttrType>
  AttrType &Get(const std::string &attr_name) const {
    PADDLE_ENFORCE_EQ(Has(attr_name), true, "%s attr not registered for graph.",
                      attr_name);
    try {
      return *boost::any_cast<AttrType *>(attrs_.at(attr_name));
    } catch (boost::bad_any_cast &) {
      PADDLE_THROW(
          "Invalid attribute type of %s error, expected: %s, actual: %s",
          attr_name, typeid(AttrType *).name(),
          attrs_.at(attr_name).type().name());
    }
  }

  template <typename AttrType>
  void Set(const std::string &attr_name, AttrType *attr) {
    PADDLE_ENFORCE_EQ(attrs_.count(attr_name), 0, "%s already set in the graph",
                      attr_name);
    attrs_[attr_name] = attr;
    attr_dels_[attr_name] = [attr, attr_name]() {
      VLOG(3) << "deleting " << attr_name;
      delete attr;
    };
  }

  template <typename AttrType>
  void SetNotOwned(const std::string &attr_name, AttrType *attr) {
    PADDLE_ENFORCE_EQ(attrs_.count(attr_name), 0, "%s already set in the graph",
                      attr_name);
    attrs_[attr_name] = attr;
    attr_dels_[attr_name] = []() {};
  }

  void Erase(const std::string &attr_name) {
    PADDLE_ENFORCE_NE(attrs_.count(attr_name), 0, "%s not set in the graph",
                      attr_name);
    attr_dels_[attr_name]();
    attrs_.erase(attr_name);
    attr_dels_.erase(attr_name);
  }

  const std::unordered_set<ir::Node *> &Nodes() const { return node_set_; }

  // Create a normal variable with non-null VarDesc.
  ir::Node *CreateVarNode(VarDesc *var_desc) {
    PADDLE_ENFORCE_NOT_NULL(var_desc);
    auto *x = AddNode(new ir::Node(var_desc));
    x->SetId(num_node_created_++);
    return x;
  }

  // Create a normal runnable operator with OpDesc.
  ir::Node *CreateOpNode(OpDesc *op_desc) {
    PADDLE_ENFORCE_NOT_NULL(op_desc);
    auto *x = AddNode(new ir::Node(op_desc));
    x->SetId(num_node_created_++);
    return x;
  }

  // Create a control dependency var that connects 2 operations. The
  // var doesn't hold any data. Other than that, it's no different from
  // other var, considering dependency analysis.
  ir::Node *CreateControlDepVar() {
    // TODO(panyx0718): control var name should be really unique.
    const std::string name = string::Sprintf(
        "%s@%llu", static_cast<const char *>(ir::Node::kControlDepVarName),
        num_node_created_);
    auto *x = AddNode(new ir::Node(name, ir::Node::Type::kVariable));
    x->SetId(num_node_created_++);
    return x;
  }

  // A more free style way of creating a graph node. Mostly use for test
  // or "copy" from another node. Avoid using it if possible.
  ir::Node *CreateEmptyNode(const std::string &name, ir::Node::Type type) {
    auto *x = AddNode(new ir::Node(name, type));
    x->SetId(num_node_created_++);
    return x;
  }

  // Clear all node information of the graph and return the ownership of the
  // nodes.
  std::vector<std::unique_ptr<ir::Node>> ReleaseNodes() {
    std::vector<std::unique_ptr<ir::Node>> ret;
    for (auto &n : nodes_) {
      ret.emplace_back(n.second.release());
    }
    nodes_.clear();
    node_set_.clear();
    return ret;
  }

  std::unique_ptr<ir::Node> RemoveNode(ir::Node *node) {
    PADDLE_ENFORCE_EQ(node_set_.find(node) != node_set_.end(), true);
    std::unique_ptr<ir::Node> ret;
    ret.reset(nodes_.at(node).release());
    nodes_.erase(node);
    node_set_.erase(node);
    return ret;
  }

  // NOTE low performance, but simple and secure.
  Node *RetrieveNode(int id) {
    for (auto &node : nodes_) {
      if (node.second->id() == id) {
        return node.second.get();
      }
    }
    return nullptr;
  }

  // Returns reference to the original program.
  // WARN: After a series of passes, the current graph can be quite
  // different from OriginProgram. Caller shouldn't assume much from
  // the returned OriginProgram.
  const ProgramDesc &OriginProgram() const { return program_; }

  // This method takes ownership of `node`.
  ir::Node *AddNode(ir::Node *node) {
    PADDLE_ENFORCE_EQ(node_set_.find(node) == node_set_.end(), true);
    nodes_[node].reset(node);
    node_set_.insert(node);
    return node;
  }

  void ResolveHazard(
      const std::map<std::string, std::vector<ir::Node *>> &var_nodes);

  // Create a new and duplicated graph.
  // WARN: The method only clones the graph structure, not its attributes.
  std::shared_ptr<Graph> Clone();

 private:
  std::map<std::string, std::vector<ir::Node *>> InitFromProgram(
      const ProgramDesc &program);

  // NOTE: program_ shouldn't be exposed to user.
  const ProgramDesc program_;
  std::map<std::string, boost::any> attrs_;
  std::map<std::string, std::function<void(void)>> attr_dels_;
  std::map<ir::Node *, std::unique_ptr<ir::Node>> nodes_;
  std::unordered_set<ir::Node *> node_set_;
  size_t num_node_created_{0};  // help to generate a unique node id.
};

bool IsControlDepVar(const ir::Node &var);
}  // namespace ir
}  // namespace framework
}  // namespace paddle


text:
namespace Sample.Blazor.Server.Data
{
    using System;
    using System.Linq;
    using System.Threading.Tasks;

    public class WeatherForecastService
    {
        private static readonly string[] Summaries = new[]
        {
            "Freezing", "Bracing", "Chilly", "Cool", "Mild", "Warm", "Balmy", "Hot", "Sweltering", "Scorching"
        };

        public Task<WeatherForecast[]> GetForecastAsync(DateTime startDate)
        {
            var rng = new Random();
            return Task.FromResult(Enumerable.Range(1, 5).Select(index => new WeatherForecast
            {
                Date = startDate.AddDays(index),
                TemperatureC = rng.Next(-20, 55),
                Summary = Summaries[rng.Next(Summaries.Length)]
            }).ToArray());
        }
    }
}


text:
SYNONYM

#### According to
The Catalogue of Life, 3rd January 2011

#### Published in
Phytologia 28(5): 486 (1974)

#### Original name
Lichen centrifugus L.

### Remarks
null


text:
<?php

namespace Agenda_ILM\ClienteBundle\Entity;

use Doctrine\ORM\Mapping as ORM;

/**
 * Cliente
 *
 * @ORM\Table()
 * @ORM\Entity
 */
class Cliente
{
    /**
     * @var integer
     *
     * @ORM\Column(name="id", type="integer")
     * @ORM\Id
     * @ORM\GeneratedValue(strategy="AUTO")
     */
    private $id;

    /**
     * @var boolean
     *
     * @ORM\Column(name="PosibleCliente", type="boolean")
     */
    private $PosibleCliente;

    /**
     * @var integer
     *
     * @ORM\ManyToOne(targetEntity="Agenda_ILM\CorreoBundle\Entity\Correo")
     */
    private $IdCorreo;

    /**
     * @var integer
     *
     * @ORM\ManyToOne(targetEntity="Agenda_ILM\TelefonoBundle\Entity\Telefono")
     */
    private $IdTelefono;

    /**
     * @var integer
     *
     * @ORM\ManyToOne(targetEntity="Agenda_ILM\DireccionBundle\Entity\Direccion")
     */
    private $IdDireccion;

    /**
     * @var integer
     *
     * @ORM\Column(name="Status", type="integer")
     */
    private $Status;

    /**
     * @var \DateTime
     *
     * @ORM\Column(name="FechaCreacion", type="datetime")
     */
    private $FechaCreacion;

    /**
     * @var \DateTime
     *
     * @ORM\Column(name="FechaModificacion", type="datetime")
     */
    private $FechaModificacion;

    /**
     * Get id
     *
     * @return integer
     */
    public function getId()
    {
        return $this->id;
    }

    /**
     * Set PosibleCliente
     *
     * @param boolean $posibleCliente
     * @return Cliente
     */
    public function setPosibleCliente($posibleCliente)
    {
        $this->PosibleCliente = $posibleCliente;

        return $this;
    }

    /**
     * Get PosibleCliente
     *
     * @return boolean
     */
    public function getPosibleCliente()
    {
        return $this->PosibleCliente;
    }

    /**
     * Set IdCorreo
     *
     * @param integer $idCorreo
     * @return Cliente
     */
    public function setIdCorreo(\Agenda_ILM\CorreoBundle\Entity\Correo $idCorreo)
    {
        $this->IdCorreo = $idCorreo;

        return $this;
    }

    /**
     * Get IdCorreo
     *
     * @return integer
     */
    public function getIdCorreo()
    {
        return $this->IdCorreo;
    }

    /**
     * Set IdTelefono
     *
     * @param integer $idTelefono
     * @return Cliente
     */
    public function setIdTelefono(\Agenda_ILM\TelefonoBundle\Entity\Telefono $idTelefono)
    {
        $this->IdTelefono = $idTelefono;

        return $this;
    }

    /**
     * Get IdTelefono
     *
     * @return integer
     */
    public function getIdTelefono()
    {
        return $this->IdTelefono;
    }

    /**
     * Set IdDireccion
     *
     * @param integer $idDireccion
     * @return Cliente
     */
    public function setIdDireccion(\Agenda_ILM\DireccionBundle\Entity\Direccion $idDireccion)
    {
        $this->IdDireccion = $idDireccion;

        return $this;
    }

    /**
     * Get IdDireccion
     *
     * @return integer
     */
    public function getIdDireccion()
    {
        return $this->IdDireccion;
    }

    /**
     * Set Status
     *
     * @param integer $status
     * @return Cliente
     */
    public function setStatus($status)
    {
        $this->Status = $status;

        return $this;
    }

    /**
     * Get Status
     *
     * @return integer
     */
    public function getStatus()
    {
        return $this->Status;
    }

    /**
     * Set FechaCreacion
     *
     * @param \DateTime $fechaCreacion
     * @return Cliente
     */
    public function setFechaCreacion($fechaCreacion)
    {
        $this->FechaCreacion = $fechaCreacion;

        return $this;
    }

    /**
     * Get FechaCreacion
     *
     * @return \DateTime
     */
    public function getFechaCreacion()
    {
        return $this->FechaCreacion;
    }

    /**
     * Set FechaModificacion
     *
     * @param \DateTime $fechaModificacion
     * @return Cliente
     */
    public function setFechaModificacion($fechaModificacion)
    {
        $this->FechaModificacion = $fechaModificacion;

        return $this;
    }

    /**
     * Get FechaModificacion
     *
     * @return \DateTime
     */
    public function getFechaModificacion()
    {
        return $this->FechaModificacion;
    }
}


text:
using System;
using System.Collections.Generic;
using System.Linq;
using Microsoft.Xna.Framework.Content;

namespace MonoGame.Extended.Content
{
    internal static class ContentReaderExtensions
    {
        public static string GetRelativeAssetPath(this ContentReader contentReader, string relativePath)
        {
            var assetName = contentReader.AssetName;
            var assetNodes = assetName.Split(new[] {'/', '\\'}, StringSplitOptions.RemoveEmptyEntries);
            var relativeNodes = relativePath.Split(new[] {'/', '\\'}, StringSplitOptions.RemoveEmptyEntries);
            var relativeIndex = assetNodes.Length - 1;
            var newPathNodes = new List<string>();

            foreach (var relativeNode in relativeNodes)
                if (relativeNode == "..")
                    relativeIndex--;
                else
                    newPathNodes.Add(relativeNode);

            var values = assetNodes
                .Take(relativeIndex)
                .Concat(newPathNodes)
                .ToArray();

            return string.Join("/", values);
        }
    }
}