text:
import * as moment from 'moment';
import * as request from "request";
import * as R from "ramda";

import { simpleMessageEmbed, selfDestroyMessage, simpleEmbed } from '../utility';

const boorufy = (str: string) => str ?
    R.pipe(
        R.split(","), // Split string by comma
        R.map( // For each string
            R.pipe( // Do these three functions
                R.trim, // First trim
                R.split(' '), // Split by space
                R.join('_'), // Join with underscore
            ),
        ),
        R.join(" "), // Finally join the string by spaces again (instead of commas)
    )(str) : '';

const websites = {
    konachan: (query) => new Promise((resolve, reject) => {
        const url = `https://konachan.com/post.json?limit=1&tags=order:random rating:explicit ${query}`;

        request(url, (err, res, data) => {
            const result = JSON.parse(data);

            if (result.length > 0) {
                resolve(simpleEmbed(`Konachan`).setImage(`http:${result[0].file_url}`));
            } else {
                resolve(simpleMessageEmbed(`Whoops! We couldn't find ${query}`));
            }

        });
    }),
    danbooru: (query) => new Promise((resolve, reject) => {
        const url = `https://danbooru.donmai.us/posts.json?limit=1&tags=order:random ${query}`;

        request(url, (err, res, data) => {
            const result = JSON.parse(data);

            if (result.length > 0) {
                resolve(simpleEmbed(`Danbooru`).setImage(`https://danbooru.donmai.us${result[0].file_url}`));
            } else {
                resolve(simpleMessageEmbed(`Whoops! We couldn't find ${query}`));
            }

        });
    }),
    e621: (query) => new Promise((resolve, reject) => {
        const url = `http://e621.net/post/index.json?limit=1&tags=order:random ${query}`;

        request({ headers: { 'User-Agent': 'request.js' }, url }, (err, res, data) => {
            const result = JSON.parse(data);

            if (result.length > 0) {
                resolve(simpleEmbed(`e621`).setImage(`${result[0].file_url}`));
            } else {
                resolve(simpleMessageEmbed(`Whoops! We couldn't find ${query}`));
            }

        });
    }),
    atfbooru: (query) => new Promise((resolve, reject) => {
        const url = `https://atfbooru.ninja/posts.json?limit=1&tags=order:random ${query}`;

        request({ headers: { 'User-Agent': 'request.js' }, url }, (err, res, data) => {
            const result = JSON.parse(data);

            if (result.length > 0) {
                resolve(simpleEmbed(`atfbooru`).setImage(`https://atfbooru.ninja${result[0].file_url}`));
            } else {
                resolve(simpleMessageEmbed(`Whoops! We couldn't find ${query}`));
            }

        });
    }),
    reddit: (query) => new Promise((resolve, reject) => {
        const url = `https://www.reddit.com/r/${query}/random.json`;

        request(url, { method: 'HEAD', followAllRedirects: true }, (err, response, data) => {
            const actualURL = response.request.href;

            request({ headers: { 'User-Agent': 'request.js' }, url: actualURL }, (err, res, data) => {
                const result = JSON.parse(data);

                if (result[0].data.children[0].data.post_hint !== 'image') return resolve(websites.reddit(query));

                if (result.length > 0) {
                    return resolve(simpleEmbed(`reddit`).setImage(`${result[0].data.children[0].data.url}`));
                } else {
                    return resolve(simpleMessageEmbed(`Whoops! We couldn't find ${query}`));
                }

            });
        });
    }),
    // https://www.reddit.com/r/nsfw/random.json
    list: () => Promise.resolve(simpleMessageEmbed(`The available lewds sources are: \`${R.join(", ")(R.keys(R.dissoc('list', websites)))}\``)),
};

module.exports = {
    name: 'nsfw',
    match: /^(nsfw) ([A-z0-9]+) *(.+)*/gi,
    nearmatch: /^nsfw/gi,
    usage: 'nsfw <website> [tags]',
    run: async ({ message, matches }) => {
        // if ( !message.channel.nsfw ) return selfDestroyMessage(message, {embed: simpleMessageEmbed(`You can only use this command in nsfw channels.`)});
        const [, , website, query] = matches;

        // Check if website even exists
        if (R.contains(R.toLower(website))(R.keys(websites))) {
            const websiteFn = websites[R.toLower(website)];

            await message.channel.startTyping();

            const embed = await websiteFn(boorufy(query));

            await message.channel.send({ embed });

            return await message.channel.stopTyping();
        } else {
            return selfDestroyMessage(message, { embed: simpleMessageEmbed(`That website does not exist, please choose from \`${R.join(", ")(R.keys(websites))}\``) });
        }
    },
};


text:
class IReplayDemoPlayer : public IBaseInterface
{
public:
	virtual void			PlayReplay( ReplayHandle_t hReplay, int iPerformance ) = 0;
	virtual void			PlayNextReplay() = 0;
	virtual void			ClearReplayList() = 0;
	virtual void			AddReplayToList( ReplayHandle_t hReplay, int iPerformance ) = 0;
	virtual CReplay			*GetCurrentReplay() = 0;
	virtual CReplayPerformance *GetCurrentPerformance() = 0;	// The playing replay, or NULL if playing the original replay
	virtual void			PauseReplay() = 0;
	virtual bool			IsReplayPaused() = 0;
	virtual void			ResumeReplay() = 0;
	virtual void			OnSignonStateFull() = 0;
};

//----------------------------------------------------------------------------------------

#endif // IREPLAYDEMOPLAYER_H

redpajama_set_name: RedPajamaGithub


text:
import bluetooth
import sys

LIGHTS_NAME = "00651 36L RGB"

class LightStrand:

    address = None
    port = None
    socket = None
    connected = False

    def __init__(self, address, port):
        self.address = address
        self.port = port

    def __del__(self):
        if self.socket:
            self.socket.close()

    def __connect(self):
        try:
            self.socket=bluetooth.BluetoothSocket( bluetooth.RFCOMM )
            self.socket.connect((self.address, self.port))
            self.connected = True
            print "Connected to:", self.address
            sys.stdout.flush()
        except:
            self.connected = False
            print "Could not connect to:", self.address
            sys.stdout.flush()

    def send(self,command):
        try:
            if self.connected:
                self.socket.send(command)
        except:
            print "Error sending command to ", self.address
            sys.stdout.flush()
            self.connected = False

    @staticmethod
    def connect_all_strands():
        nearby_devices = bluetooth.discover_devices()

        strands = []
        for bdaddr in nearby_devices:
            if LIGHTS_NAME == bluetooth.lookup_name( bdaddr ):
                strand = LightStrand(bdaddr,6)
                strand.__connect()
                strands.append(strand)

        return strands


text:
{% load wagtailcore_tags compress static wagtailuserbar core_tags i18n %}
{% load wagtailsettings_tags wagtailimages_tags %}
{% get_settings %}

            Lorem

            Lorem

            Lorem


text:
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

    <title>FullYearCalendar - Days selection example</title>

    <link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" rel="stylesheet" integrity="sha384-BVYiiSIFeK1dGmJRAkycuHAHRg32OmUcww7on3RYdg4Va+PmSTsz/K68vbdEjh4u" crossorigin="anonymous" />

    <link href="../src/css/FullYearCalendar.css" rel="stylesheet" media="screen" />


text:
@interface KHAppearTableViewCell : UITableViewCell
@property (weak, nonatomic) IBOutlet UIImageView *winPic;
@property (weak, nonatomic) IBOutlet UILabel *winName;
@property (weak, nonatomic) IBOutlet UILabel *winTitle;
@property (weak, nonatomic) IBOutlet UILabel *proudceName;
@property (weak, nonatomic) IBOutlet UILabel *qishu;
@property (weak, nonatomic) IBOutlet UILabel *winContent;
@property (weak, nonatomic) IBOutlet UIImageView *sharePic;
@property (weak, nonatomic) IBOutlet UIImageView *pic1;
@property (weak, nonatomic) IBOutlet UIImageView *pic2;
@property (weak, nonatomic) IBOutlet UIImageView *pic3;
@property (weak, nonatomic) IBOutlet UILabel *time;
@property (weak, nonatomic) IBOutlet UILabel *number;
@property (weak, nonatomic) IBOutlet UIImageView *zanPic;

- (void)setModel:(KHAppearModel *)model;
+ (CGFloat)height;
@end


text:
namespace lldb_private {

// A general purpose class for representing timeouts for various APIs. It's
// basically an llvm::Optional<std::chrono::duration<int64_t, Ratio>>, but we
// customize it a bit to enable the standard chrono implicit conversions (e.g.
// from Timeout<std::milli> to Timeout<std::micro>.
//
// The intended meaning of the values is:
// - llvm::None - no timeout, the call should wait forever - 0 - poll, only
// complete the call if it will not block - >0 - wait for a given number of
// units for the result
template <typename Ratio>
class Timeout : public llvm::Optional<std::chrono::duration<int64_t, Ratio>> {
private:
  template <typename Ratio2> using Dur = std::chrono::duration<int64_t, Ratio2>;
  template <typename Rep2, typename Ratio2>
  using EnableIf = std::enable_if<
      std::is_convertible<std::chrono::duration<Rep2, Ratio2>,
                          std::chrono::duration<int64_t, Ratio>>::value>;

  using Base = llvm::Optional<Dur<Ratio>>;

public:
  Timeout(llvm::NoneType none) : Base(none) {}
  Timeout(const Timeout &other) = default;

  template <typename Ratio2,
            typename = typename EnableIf<int64_t, Ratio2>::type>
  Timeout(const Timeout<Ratio2> &other)
      : Base(other ? Base(Dur<Ratio>(*other)) : llvm::None) {}

  template <typename Rep2, typename Ratio2,
            typename = typename EnableIf<Rep2, Ratio2>::type>
  Timeout(const std::chrono::duration<Rep2, Ratio2> &other)
      : Base(Dur<Ratio>(other)) {}
};

} // namespace lldb_private

namespace llvm {
template<typename Ratio>
struct format_provider<lldb_private::Timeout<Ratio>, void> {
  static void format(const lldb_private::Timeout<Ratio> &timeout,
                     raw_ostream &OS, StringRef Options) {
    typedef typename lldb_private::Timeout<Ratio>::value_type Dur;

    if (!timeout)
      OS << "<infinite>";
    else
      format_provider<Dur>::format(*timeout, OS, Options);
  }
};
}

#endif // liblldb_Timeout_h_


text:
package org.reasm;

import static org.hamcrest.Matchers.contains;
import static org.hamcrest.Matchers.empty;
import static org.hamcrest.Matchers.is;
import static org.hamcrest.Matchers.sameInstance;
import static org.junit.Assert.assertThat;
import static org.junit.Assert.fail;

import java.util.Arrays;
import java.util.Collections;

import org.hamcrest.Matcher;
import org.junit.Test;

import com.google.common.collect.ImmutableList;

/**
 * Test class for {@link PredefinedSymbolTable}.
 *
 * @author Francis Gagné
 */
public class PredefinedSymbolTableTest {

    /**
     * Asserts that {@link PredefinedSymbolTable#PredefinedSymbolTable()} initializes an empty {@link PredefinedSymbolTable}.
     */
    @Test
    public void predefinedSymbolTable() {
        final PredefinedSymbolTable table = new PredefinedSymbolTable();
        assertThat(table.symbols(), is(empty()));
    }

    /**
     * Asserts that {@link PredefinedSymbolTable#PredefinedSymbolTable(Iterable)} throws an {@link IllegalArgumentException} when
     * the collection contains {@link PredefinedSymbol PredefinedSymbols} with the same name.
     */
    @Test
    public void predefinedSymbolTableIterableDuplicateName() {
        final PredefinedSymbol predefinedSymbol1 = new PredefinedSymbol(SymbolContext.VALUE, "foo", SymbolType.CONSTANT,
                new UnsignedIntValue(42L));
        final PredefinedSymbol predefinedSymbol2 = new PredefinedSymbol(SymbolContext.VALUE, "bar", SymbolType.CONSTANT,
                new SignedIntValue(-78L));
        final PredefinedSymbol predefinedSymbol3 = new PredefinedSymbol(SymbolContext.VALUE, "foo", SymbolType.VARIABLE,
                new FloatValue(3.25));

        try {
            new PredefinedSymbolTable(Arrays.asList(predefinedSymbol1, predefinedSymbol2, predefinedSymbol3));
        } catch (IllegalArgumentException e) {
            return;
        }

        fail("new PredefinedSymbolTable(Iterable) should have thrown IllegalArgumentException");
    }

    /**
     * Asserts that {@link PredefinedSymbolTable#PredefinedSymbolTable(Iterable)} throws an {@link IllegalArgumentException} when
     * the collection contains {@link PredefinedSymbol PredefinedSymbols} with the same name, ignoring the case.
     */
    @Test
    public void predefinedSymbolTableIterableDuplicateNameDifferentCase() {
        final PredefinedSymbol predefinedSymbol1 = new PredefinedSymbol(SymbolContext.VALUE, "foo", SymbolType.CONSTANT,
                new UnsignedIntValue(42L));
        final PredefinedSymbol predefinedSymbol2 = new PredefinedSymbol(SymbolContext.VALUE, "bar", SymbolType.CONSTANT,
                new SignedIntValue(-78L));
        final PredefinedSymbol predefinedSymbol3 = new PredefinedSymbol(SymbolContext.VALUE, "FOO", SymbolType.VARIABLE,
                new FloatValue(3.25));

        try {
            new PredefinedSymbolTable(Arrays.asList(predefinedSymbol1, predefinedSymbol2, predefinedSymbol3));
        } catch (IllegalArgumentException e) {
            return;
        }

        fail("new PredefinedSymbolTable(Iterable) should have thrown IllegalArgumentException");
    }

    /**
     * Asserts that {@link PredefinedSymbolTable#PredefinedSymbolTable(Iterable)} initializes an empty {@link PredefinedSymbolTable}
     * when the symbols argument is an empty collection.
     */
    @Test
    public void predefinedSymbolTableIterableEmpty() {
        final PredefinedSymbolTable table = new PredefinedSymbolTable(Collections.<PredefinedSymbol> emptySet());
        assertThat(table.symbols(), is(empty()));
    }

    /**
     * Asserts that {@link PredefinedSymbolTable#PredefinedSymbolTable(Iterable)} throws a {@link NullPointerException} when the
     * symbols argument is null.
     */
    @Test(expected = NullPointerException.class)
    public void predefinedSymbolTableIterableNull() {
        new PredefinedSymbolTable(null);
    }

    /**
     * Asserts that {@link PredefinedSymbolTable#PredefinedSymbolTable(Iterable)} initializes a {@link PredefinedSymbolTable} with
     * the specified symbol.
     */
    @Test
    public void predefinedSymbolTableIterableOneSymbol() {
        final PredefinedSymbol predefinedSymbol = new PredefinedSymbol(SymbolContext.VALUE, "foo", SymbolType.CONSTANT,
                new UnsignedIntValue(42L));
        final PredefinedSymbolTable table = new PredefinedSymbolTable(Collections.singleton(predefinedSymbol));
        assertThat(table.symbols(), contains(sameInstance(predefinedSymbol)));
    }

    /**
     * Asserts that {@link PredefinedSymbolTable#PredefinedSymbolTable(Iterable)} initializes a {@link PredefinedSymbolTable} with
     * the specified symbols.
     */
    @Test
    public void predefinedSymbolTableIterableThreeSymbols() {
        final PredefinedSymbol predefinedSymbol1 = new PredefinedSymbol(SymbolContext.VALUE, "foo", SymbolType.CONSTANT,
                new UnsignedIntValue(42L));
        final PredefinedSymbol predefinedSymbol2 = new PredefinedSymbol(SymbolContext.VALUE, "bar", SymbolType.CONSTANT,
                new SignedIntValue(-78L));
        final PredefinedSymbol predefinedSymbol3 = new PredefinedSymbol(SymbolContext.VALUE, "baz", SymbolType.VARIABLE,
                new FloatValue(3.25));
        final PredefinedSymbolTable table = new PredefinedSymbolTable(Arrays.asList(predefinedSymbol1, predefinedSymbol2,
                predefinedSymbol3));
        assertThat(table.symbols(), contains(ImmutableList.<Matcher<? super PredefinedSymbol>> of(sameInstance(predefinedSymbol1),
                sameInstance(predefinedSymbol2), sameInstance(predefinedSymbol3))));
    }

}


text:
using System;
using System.Runtime.InteropServices;

namespace BootstrapUI.Windows.Win32
{
    internal class NativeMethods
    {
        public const int S_OK = 0;
        public const int WM_DPICHANGED = 0x02E0;
        public const int MONITOR_DEFAULTTONEAREST = 0x00000002;

        [DllImport("Shcore.dll")]
        public static extern int GetProcessDpiAwareness(IntPtr hprocess, out ProcessDpiAwareness value);
        [DllImport("Shcore.dll")]
        public static extern int SetProcessDpiAwareness(ProcessDpiAwareness value);
        [DllImport("user32.dll")]
        public static extern bool IsProcessDPIAware();
        [DllImport("user32.dll")]
        public static extern int SetProcessDPIAware();
        [DllImport("shcore.dll")]
        public static extern int GetDpiForMonitor(IntPtr hMonitor, int dpiType, ref uint xDpi, ref uint yDpi);
        [DllImport("user32.dll")]
        public static extern IntPtr MonitorFromWindow(IntPtr hwnd, int flag);
    }
}


text:
import searchDatacite from './searchDatacite';

export default function searchZenodo(searchFor, pageNum, rows, onComplete) {
  return searchDatacite(searchFor, 'zenodo', pageNum, rows, onComplete);
}


text:
/**
 * NowUtil: an assorted collection of general-purpose functions used
 * in NowJS.
 */

var util = {
  parseCookie: function (cookie) {
    if (typeof cookie !== 'string') {
      return {};
    }
    var regex = /(.+?)(;|$)\s*/g;
    var match = cookie.match(regex);
    if (!match) {
      return {};
    }
    var jsonCookie = {};
    var m, end, index;
    for (var i = 0; i < match.length; i++) {
      m = match[i];
      index = m.indexOf('=');
      end = m.lastIndexOf(';');
      if (index === -1) {
        jsonCookie[m.substr(index + 1,
                            end + 1 ?
                            end - index - 1:
                            undefined)] = true;
      } else {
        jsonCookie[m.substr(0, index)] = m.substr(index + 1,
                                                  (end + 1 ?
                                                   end - index - 1 :
                                                   undefined));
      }
    }
    return jsonCookie;
  },

  hasProperty: function (obj, prop) {
    return Object.prototype.hasOwnProperty.call(Object(obj), prop);
  },

  noop: function () {
  },

  clone: function (proto, obj) {
    // note regarding speed and C++ bindings: evidently it's slightly
    // faster to provide a wrapper function than adding an additional
    // level of lookup.
    if (!(obj && typeof obj === 'object')) {
      obj = {};
    }
    obj.__proto__ = proto;
    return obj;
  },

  generateRandomString: function () {
    return ("" + Math.random()).substring(2);
  },

  error: function (err) {
    console.log(err);
    if (util.hasProperty(err, 'stack')) {
      console.log(err.stack);
    }
  },

  getAllChildFqns: function (parentObj, parentFqn) {
    var fqns = [];
    var prop;
    function getAllChildFqnsHelper(parentObj, parentFqn) {
      for (var i = 0, keys = Object.keys(parentObj), ll = keys.length; i < ll; i++ ) {
        prop = keys[i];
        if (parentObj[prop] && typeof parentObj[prop] === 'object') {
          getAllChildFqnsHelper(parentObj[prop], parentFqn + '.' + prop);
        } else {
          fqns.push(parentFqn + '.' + prop);
        }
      }
      if (ll == 0) {
        fqns.push(parentFqn);
      }
    }
    getAllChildFqnsHelper(parentObj, parentFqn);
    return fqns;
  },

  extend: function (target, obj) {
    for (var i = 0, keys = Object.keys(obj), ii = keys.length; i < ii; i++) {
      var key = keys[i];
      if (util.hasProperty(target, key) && obj[key] && typeof obj[key] === 'object') {
        if(Array.isArray(obj[key])) {
          target[key] = target[key] || [];
        } else {
          target[key] = target[key] || {};
        }
        util.extend(target[key], obj[key]);
      } else {
        target[key] = obj[key];
      }
    }
  },

  getVarFromFqn: function (fqn, scope) {
    var path = fqn.split('.');
    path.shift();
    var currVar = scope;
    var prop;
    while (path.length > 0) {
      prop = path.shift();
      if (util.hasProperty(currVar, prop)) {
        currVar = currVar[prop];
      } else {
        return false;
      }
    }
    return currVar;
  },

  stringify: JSON.stringify,

  parse: JSON.parse,

  flatten: function (val, fqn) {
    var vals = {};
    var fqns = util.getAllChildFqns(val, '');
    var m;
    for (var i = 0, ii = fqns.length; i < ii; i++) {
      m = util.getVarFromFqn(fqns[i], val);
      vals[fqn + fqns[i]] = m;
    }
    return vals;
  },

  getValOrFqn: function (val, fqn) {
    if (typeof val === 'function') {
      return {fqn: fqn};
    } else {
      return val;
    }
  },

  isEmptyObj: function (obj) {
    for (var i in obj) {
      return false;
    }
    return true;
  }
};

if (!util.hasProperty(Array.prototype, 'toJSON')) {
  var obj = { enumerable: false,
              value: function () {
                if (Array.isArray(this)) {
                  return this;
                }
                var toReturn = [];
                for (var i = 0, ll = this.length; i < ll; i++) {
                  toReturn[i] = this[i];
                }
                return toReturn;
              }
            };
  Object.defineProperty(Array.prototype, 'toJSON', obj);
}

exports.nowUtil = util;


text:
Describe "UntrustedDataMode tests for variable assignments" -Tags 'CI' {

    BeforeAll {

        $testModule = Join-Path $TestDrive "UntrustedDataModeTest.psm1"
        Set-Content -Path $testModule -Value @'
        $scriptVar = 15
        $Global:globalVar = "Hello"

        ## A script cmdlet, it goes through CmdletParameterBinderController
        function Test-Untrusted
        {
            [CmdletBinding()]
            param(
                [Parameter()]
                [ValidateTrustedData()]
                $Argument
            )

            Write-Output $Argument
        }

        ## A simple function, it goes through ScriptParameterBinderController
        function Test-SimpleUntrusted
        {
            param(
                [ValidateTrustedData()]
                $Argument
            )

            Write-Output $Argument
        }

        ## A script cmdlet that tests other parameter types
        function Test-OtherParameterType
        {
            [CmdletBinding()]
            param(
                [Parameter()]
                [ValidateTrustedData()]
                [string[]] $Name,

                [Parameter()]
                [ValidateTrustedData()]
                [DateTime] $Date,

                [Parameter()]
                [ValidateTrustedData()]
                [System.IO.FileInfo] $File,

                [Parameter()]
                [ValidateTrustedData()]
                [System.Diagnostics.ProcessStartInfo] $StartInfo
            )

            throw "No Validation Exception!"
        }

        function Test-WithScriptVar { Test-Untrusted -Argument $scriptVar }
        function Test-WithGlobalVar { Test-Untrusted -Argument $Global:globalVar }

        function Test-SplatScriptVar { Test-Untrusted @scriptVar }
        function Test-SplatGlobalVar { Test-Untrusted @Global:globalVar }

        function Get-ScriptVar { $scriptVar }
        function Get-GlobalVar { $Global:globalVar }

        function Set-ScriptVar { $Script:scriptVar = "Trusted-Script" }
        function Set-GlobalVar { $Global:globalVar = "Trusted-Global" }

        ##
        ## ValidateTrustedData attribute is applied to some powershell cmdlets
        ## and the functions below are for testing them in FullLanguage
        ##
        function Test-AddType { Add-Type -TypeDefinition $args[0] }
        function Test-InvokeExpression { Invoke-Expression -Command $args[0] }
        function Test-NewObject { New-Object -TypeName $args[0] }
        function Test-ForeachObject { Get-Date | Foreach-Object -MemberName $args[0] }
        function Test-ImportModule { Import-Module -Name $args[0] }
        function Test-StartJob { Start-Job -ScriptBlock $args[0] }

'@

        ## Use a different runspace
        $ps = [powershell]::Create()

        ## Helper function to execute script
        function Execute-Script
        {
            param([string]$Script)

            $ps.Commands.Clear()
            $ps.Streams.ClearStreams()
            $ps.AddScript($Script).Invoke()
        }

        ## Import the module and verify the original behavior of functions
        ## exposed from UntrustedDataModeTest in FullLanguage
        Execute-Script -Script "Import-Module $testModule"

        ## Set the LanguageMode to be 'ConstrainedLanguage'
        Execute-Script -Script '$ExecutionContext.SessionState.LanguageMode = "ConstrainedLanguage"'

        ## Assign the ModuleInfo object to $mo
        Execute-Script -Script '$mo = Get-Module UntrustedDataModeTest'
    }

    AfterAll {
        ## Clean up the powershell object
        $ps.Dispose()

        ## Set the LanguageMode to force rebuilding the type conversion cache.
        ## This is needed because type conversions that happen in the new powershell runspace with 'ConstrainedLanguage' mode
        ## will be put in the type conversion cache, and that may affect the default session.
        $ExecutionContext.SessionState.LanguageMode = "FullLanguage"
    }

    It "verify the initial state of the test module 'UntrustedDataModeTest'" {
        $result = Execute-Script -Script "Test-WithScriptVar"
        $result | Should -Be 15

        $result = Execute-Script -Script "Test-WithGlobalVar"
        $result | Should -Be "Hello"

        $result = Execute-Script -Script "Get-ScriptVar"
        $result | Should -Be 15

        $result = Execute-Script -Script "Get-GlobalVar"
        $result | Should -Be "Hello"

        $result = Execute-Script -Script '$ExecutionContext.SessionState.LanguageMode'
        $result | Should -Be "ConstrainedLanguage"
    }

    Context "Set global variable value in top-level session state" {

        BeforeAll {

            $testScript = @'
            Get-GlobalVar
            try { Test-WithGlobalVar } catch { $_.FullyQualifiedErrorId }
'@

            $testCases = @(
                ## Assignment in language
                @{
                    Name = 'language in global scope'
                    SetupScript = '$globalVar = "language in global scope"'
                    ExpectedOutput = "language in global scope;ParameterArgumentValidationError,Test-Untrusted"
                },
                @{
                    Name = 'language in sub scope'
                    SetupScript = '& { $Global:globalVar = "language in sub scope" }'
                    ExpectedOutput = "language in sub scope;ParameterArgumentValidationError,Test-Untrusted"
                },

                ## New-Variable
                @{
                    Name = 'New-Variable in global scope'
                    SetupScript = 'New-Variable globalVar -Value "New-Variable in global scope" -Force'
                    ExpectedOutput = "New-Variable in global scope;ParameterArgumentValidationError,Test-Untrusted"
                },
                @{
                    Name = "New-Variable in sub scope with [-Scope Global]"
                    SetupScript = '& { New-Variable globalVar -Value "New-Variable in sub scope with [-Scope Global]" -Force -Scope Global }'
                    ExpectedOutput = "New-Variable in sub scope with [-Scope Global];ParameterArgumentValidationError,Test-Untrusted"
                },
                @{
                    Name = "New-Variable in sub scope with [-Scope 1]"
                    SetupScript = '& { New-Variable globalVar -Value "New-Variable in sub scope with [-Scope 1]" -Force -Scope 1 }'
                    ExpectedOutput = "New-Variable in sub scope with [-Scope 1];ParameterArgumentValidationError,Test-Untrusted"
                },

                ## Set-Variable
                @{
                    Name = 'Set-Variable in global scope'
                    SetupScript = 'Set-Variable globalVar -Value "Set-Variable in global scope" -Force'
                    ExpectedOutput = "Set-Variable in global scope;ParameterArgumentValidationError,Test-Untrusted"
                },
                @{
                    Name = 'Set-Variable in sub scope with [-Scope Global]'
                    SetupScript = '& { Set-Variable globalVar -Value "Set-Variable in sub scope with [-Scope Global]" -Scope Global  }'
                    ExpectedOutput = "Set-Variable in sub scope with [-Scope Global];ParameterArgumentValidationError,Test-Untrusted"
                },
                @{
                    Name = 'Set-Variable in sub scope with [-Scope 1]'
                    SetupScript = '& { Set-Variable globalVar -Value "Set-Variable in sub scope with [-Scope 1]" -Scope 1  }'
                    ExpectedOutput = "Set-Variable in sub scope with [-Scope 1];ParameterArgumentValidationError,Test-Untrusted"
                },

                ## New-Item
                @{
                    Name = 'New-Item in global scope'
                    SetupScript = 'New-Item variable:\globalVar -Value "New-Item in global scope" -Force'
                    ExpectedOutput = "New-Item in global scope;ParameterArgumentValidationError,Test-Untrusted"
                },
                @{
                    Name = 'New-Item in sub scope'
                    ## New-Item in sub scope won't affect global variable
                    SetupScript = 'Set-GlobalVar; & { New-Item variable:\globalVar -Value "New-Item in sub scope" -Force }'
                    ExpectedOutput = "Trusted-Global;Trusted-Global"
                },

                ## Set-Item
                @{
                    Name = 'Set-Item in global scope'
                    SetupScript = 'Set-Item variable:\globalVar -Value "Set-Item in global scope" -Force'
                    ExpectedOutput = "Set-Item in global scope;ParameterArgumentValidationError,Test-Untrusted"
                },
                @{
                    Name = 'Set-Item in sub scope'
                    ## Set-Item in sub scope won't affect global variable
                    SetupScript = 'Set-GlobalVar; & { Set-Item variable:\globalVar -Value "Set-Item in sub scope" -Force }'
                    ExpectedOutput = "Trusted-Global;Trusted-Global"
                },

                ## Error Variable
                @{
                    Name = 'ErrorVariable in global scope'
                    SetupScript = 'Write-Error "Error" -ErrorAction SilentlyContinue -ErrorVariable globalVar'
                    ExpectedOutput = "Error;ParameterArgumentValidationError,Test-Untrusted"
                },
                @{
                    Name = 'ErrorVariable in sub scope'
                    SetupScript = '& { Write-Error "Error-in-Sub" -ErrorAction SilentlyContinue -ErrorVariable global:globalVar }'
                    ExpectedOutput = "Error-in-Sub;ParameterArgumentValidationError,Test-Untrusted"
                },

                ## Out Variable
                @{
                    Name = 'OutVariable in global scope'
                    SetupScript = 'Write-Output "Out" -OutVariable globalVar'
                    ExpectedOutput = "Out;ParameterArgumentValidationError,Test-Untrusted"
                },
                @{
                    Name = 'OutVariable in sub scope'
                    SetupScript = '& { Write-Output "Out-in-Sub" -OutVariable global:globalVar }'
                    ExpectedOutput = "Out-in-Sub;ParameterArgumentValidationError,Test-Untrusted"
                },

                ## Warning Variable
                @{
                    Name = 'WarningVariable in global scope'
                    SetupScript = 'Write-Warning "Warning" -WarningAction SilentlyContinue -WarningVariable globalVar'
                    ExpectedOutput = "Warning;ParameterArgumentValidationError,Test-Untrusted"
                },
                @{
                    Name = 'WarningVariable in sub scope'
                    SetupScript = '& { Write-Warning "Warning-in-Sub" -WarningAction SilentlyContinue -WarningVariable global:globalVar }'
                    ExpectedOutput = "Warning-in-Sub;ParameterArgumentValidationError,Test-Untrusted"
                },

                ## Information Variable
                @{
                    Name = 'InformationVariable in global scope'
                    SetupScript = 'Write-Information "Information" -InformationAction SilentlyContinue -InformationVariable globalVar'
                    ExpectedOutput = "Information;ParameterArgumentValidationError,Test-Untrusted"
                },
                @{
                    Name = 'InformationVariable in sub scope'
                    SetupScript = '& { Write-Information "Information-in-Sub" -InformationAction SilentlyContinue -InformationVariable global:globalVar }'
                    ExpectedOutput = "Information-in-Sub;ParameterArgumentValidationError,Test-Untrusted"
                },

                ## Data Section
                <# @{
                    Name = 'Data Section - "data global:var"'
                    ## 'data global:var { }' syntax is not supported today. If it's added someday, this test should be enabled
                    SetupScript = '& { data global:globalVar { "data section - [global:]" } }'
                    ExpectedOutput = "data section - [global:];ParameterArgumentValidationError,Test-Untrusted"
                }, #>
                @{
                    Name = 'Data Section'
                    SetupScript = 'data globalVar { "data section" }'
                    ExpectedOutput = "data section;ParameterArgumentValidationError,Test-Untrusted"
                }
            )
        }

        It "<Name>" -TestCases $testCases {
            param ($SetupScript, $ExpectedOutput)

            Execute-Script -Script $SetupScript > $null
            $result = Execute-Script -Script $testScript

            $result -join ";" | Should -Be $ExpectedOutput
        }

        It "Enable 'data global:var' test if the syntax is supported" {
            try {
                [scriptblock]::Create('data global:var { "data section" }')
                throw "No Exception!"
            } catch {

                ## Syntax 'data global:var { }' is not supported at the time writting the tests here
                ## If this test fail, then maybe this syntax is supported now, and in that case, please
                ## enable the test 'Data Section - "data global:var"' in $testCases above
                $_.FullyQualifiedErrorId | Should -Be "ParseException"
            }
        }
    }

    Context "Set variable in Import-LocalizedData" {

        BeforeAll {
            $localData = Join-Path $TestDrive "local.psd1"
            Set-Content $localData -Value '"Localized-Data"'
        }

        It "test global variable set by Import-LocalizedData" {
            $testScript = @'
            Get-GlobalVar
            try { Test-WithGlobalVar } catch { $_.FullyQualifiedErrorId }
'@
            Execute-Script -Script "Import-LocalizedData -BindingVariable globalVar -BaseDirectory $TestDrive -FileName local.psd1"
            $result = Execute-Script -Script $testScript

            $result -join ";" | Should -Be "Localized-Data;ParameterArgumentValidationError,Test-Untrusted"
        }
    }

    Context "Exported variables by module loading" {

        BeforeAll {
            ## Create a module that exposes two variables
            $VarModule = Join-Path $TestDrive "Var.psm1"
            Set-Content $VarModule -Value @'
            $globalVar = "global-from-module"
            $scriptVar = "script-from-module"
            Export-ModuleMember -Variable globalVar, scriptVar
'@

            $testScript = @'
            Get-GlobalVar
            try { Test-WithGlobalVar } catch { $_.FullyQualifiedErrorId }

            Get-ScriptVar
            try { Test-WithScriptVar } catch { $_.FullyQualifiedErrorId }
'@
        }

        BeforeEach {
            ## Set both the global and script vars to default value
            Execute-Script -Script "Set-ScriptVar; Set-GlobalVar"
        }

        It "test global variable set by exported variable" {
            try {
                ## Import the module in the global scope of the runspace, so only the
                ## global variable is affected, the module script variable is not.
                Execute-Script -Script "Import-Module $VarModule"
                $result = Execute-Script -Script $testScript

                $result -join ";" | Should -Be "global-from-module;ParameterArgumentValidationError,Test-Untrusted;Trusted-Script;Trusted-Script"
            } finally {
                Execute-Script -Script "Remove-Module Var -Force"
            }
        }
    }

    Context "Splatting of untrusted value" {
        It "test splatting global variable" {
            $testScript = @'
            Get-GlobalVar
            try { Test-SplatGlobalVar } catch { $_.FullyQualifiedErrorId }
'@
            Execute-Script -Script '$globalVar = @{ Argument = "global-splatting" }'
            $result = Execute-Script -Script $testScript

            $result -join ";" | Should -Be "System.Collections.Hashtable;ParameterArgumentValidationError,Test-Untrusted"
        }
    }

    Context "ValidateTrustedDataAttribute takes NO effect in non-FullLanguage" {

        It "test 'ValidateTrustedDataAttribute' NOT take effect in non-FullLanguage [Add-Type]" {
            ## Run this in the global scope, so value of $globalVar will be marked as untrusted
            $result = Execute-Script -Script @'
            try {
                $globalVar = "C# Code"
                Add-Type -TypeDefinition $globalVar
                throw "Expected 'CannotDefineNewType' error was not thrown"
            } catch {
                $_.FullyQualifiedErrorId
            }
'@
            $result | Should -Be "CannotDefineNewType,Microsoft.PowerShell.Commands.AddTypeCommand"
        }

        It "test 'ValidateTrustedDataAttribute' NOT take effect in non-FullLanguage [Invoke-Expression]" {
            ## Run this in the global scope, so value of $globalVar will be marked as untrusted
            $result = Execute-Script -Script @'
            $globalVar = "Get-Process -id $PID"
            Invoke-Expression -Command $globalVar | ForEach-Object Id
'@
            $result | Should -Be $PID
        }

        It "test 'ValidateTrustedDataAttribute' NOT take effect in non-FullLanguage [New-Object]" {
            ## Run this in the global scope, so value of $globalVar will be marked as untrusted
            $result = Execute-Script -Script @'
            $globalVar = "uri"
            New-Object -TypeName $globalVar -ArgumentList 'https://www.bing.com'
'@
            $result | Should -Not -BeNullOrEmpty
        }

        It "test 'ValidateTrustedDataAttribute' NOT take effect in non-FullLanguage [Foreach-Object]" {
            ## Run this in the global scope, so value of $globalVar will be marked as untrusted
            $result = Execute-Script -Script @'
            $globalVar = "Year"
            Get-Date | Foreach-Object -MemberName $globalVar
'@
            $result | Should -Not -BeNullOrEmpty
        }

        It "test 'ValidateTrustedDataAttribute' NOT take effect in non-FullLanguage [Import-Module]" {
            ## Run this in the global scope, so value of $globalVar will be marked as untrusted
            $result = Execute-Script -Script @'
            $globalVar = "NonExistModule"
            Import-Module -Name $globalVar -ErrorAction SilentlyContinue -ErrorVariable ev; $ev
'@
            $result | Should -Not -BeNullOrEmpty
            $result.FullyQualifiedErrorId | Should -Be "Modules_ModuleNotFound,Microsoft.PowerShell.Commands.ImportModuleCommand"
        }

        It "test 'ValidateTrustedDataAttribute' NOT take effect in non-FullLanguage [Start-Job]" {
            ## Run this in the global scope, so value of $globalVar will be marked as untrusted
            $result = Execute-Script -Script @'
            try {
                $globalVar = {1+1}
                Start-Job -ScriptBlock $globalVar
                throw "Expected 'CannotStartJob' error was not thrown"
            } catch {
                $_.FullyQualifiedErrorId
            }
'@
            $result | Should -Be "CannotStartJobInconsistentLanguageMode,Microsoft.PowerShell.Commands.StartJobCommand"
        }
    }

    Context "ValidateTrustedDataAttribute takes effect in FullLanguage" {

        It "test 'ValidateTrustedDataAttribute' take effect when calling from 'Constrained' to 'Full' [Script Cmdlet]" {
            ## Run this in the global scope, so value of $globalVar will be marked as untrusted
            $result = Execute-Script -Script @'
            try {
                $globalVar = "C# Code"
                Test-Untrusted -Argument $globalVar
                throw "Expected 'ParameterArgumentValidationError' was not thrown"
            } catch {
                $_.FullyQualifiedErrorId
            }
'@
            $result | Should -Be "ParameterArgumentValidationError,Test-Untrusted"
        }

        It "test 'ValidateTrustedDataAttribute' take effect when calling from 'Constrained' to 'Full' [Simple function]" {
            ## Run this in the global scope, so value of $globalVar will be marked as untrusted
            $result = Execute-Script -Script @'
            try {
                $globalVar = "C# Code"
                Test-SimpleUntrusted -Argument $globalVar
                throw "Expected 'ParameterArgumentValidationError' was not thrown"
            } catch {
                $_.FullyQualifiedErrorId
            }
'@
            $result | Should -Be "ParameterArgumentValidationError,Test-SimpleUntrusted"
        }

        It "test 'ValidateTrustedDataAttribute' with param type conversion [string -> string[]]" {
            ## Run this in the global scope, so value of $globalVar will be marked as untrusted
            $result = Execute-Script -Script @'
            try {
                $globalVar = "John"
                Test-OtherParameterType -Name $globalVar
                throw "Expected 'ParameterArgumentValidationError' was not thrown"
            } catch {
                $_.FullyQualifiedErrorId
            }
'@
            $result | Should -Be "ParameterArgumentValidationError,Test-OtherParameterType"
        }

        It "test 'ValidateTrustedDataAttribute' with value type param [DateTime]" {
            ## Run this in the global scope, so value of $globalVar will be marked as untrusted
            $result = Execute-Script -Script @'
            try {
                $globalVar = Get-Date
                Test-OtherParameterType -Date $globalVar
                throw "Expected 'ParameterArgumentValidationError' was not thrown"
            } catch {
                $_.FullyQualifiedErrorId
            }
'@
            $result | Should -Be "ParameterArgumentValidationError,Test-OtherParameterType"
        }

        It "test 'ValidateTrustedDataAttribute' with param type conversion [string -> FileInfo]" {
            ## Run this in the global scope, so value of $globalVar will be marked as untrusted
            $result = Execute-Script -Script @'
            try {
                $globalVar = "FakeFile"
                Test-OtherParameterType -File $globalVar
                throw "Expected 'ParameterArgumentValidationError' was not thrown"
            } catch {
                $_.FullyQualifiedErrorId
            }
'@
            $result | Should -Be "ParameterArgumentValidationError,Test-OtherParameterType"
        }

        It "test type property conversion to [ProcessStartInfo] should fail during Lang-Mode transition" {
            ## Run this in the global scope, so value of $globalVar will be marked as untrusted
            $result = Execute-Script -Script @'
            try {
                Test-OtherParameterType -StartInfo @{ FileName = "File" }
                throw "Expected conversion error was not thrown"
            } catch {
                $_.FullyQualifiedErrorId
            }
'@
            $result | Should -Be "ParameterArgumentTransformationError,Test-OtherParameterType"
        }
    }

    Context "Validate trusted data for parameters of some built-in powershell cmdlets" {

        BeforeAll {
            $ScriptTemplate = @'
            try {{
                {0}
                throw "Expected 'ParameterArgumentValidationError' was not thrown"
            }} catch {{
                $_.FullyQualifiedErrorId
            }}
'@
            $testCases = @(
                @{ Name = "test 'ValidateTrustedDataAttribute' on [Add-Type]";          Argument = '$globalVar = "Global-Value"; Test-AddType $globalVar';          ExpectedErrorId = "ParameterArgumentValidationError,Microsoft.PowerShell.Commands.AddTypeCommand" }
                @{ Name = "test 'ValidateTrustedDataAttribute' on [Invoke-Expression]"; Argument = '$globalVar = "Global-Value"; Test-InvokeExpression $globalVar'; ExpectedErrorId = "ParameterArgumentValidationError,Microsoft.PowerShell.Commands.InvokeExpressionCommand" }
                @{ Name = "test 'ValidateTrustedDataAttribute' on [New-Object]";        Argument = '$globalVar = "Global-Value"; Test-NewObject $globalVar';        ExpectedErrorId = "ParameterArgumentValidationError,Microsoft.PowerShell.Commands.NewObjectCommand" }
                @{ Name = "test 'ValidateTrustedDataAttribute' on [Foreach-Object]";    Argument = '$globalVar = "Global-Value"; Test-ForeachObject $globalVar';    ExpectedErrorId = "ParameterArgumentValidationError,Microsoft.PowerShell.Commands.ForeachObjectCommand" }
                @{ Name = "test 'ValidateTrustedDataAttribute' on [Import-Module]";     Argument = '$globalVar = "Global-Value"; Test-ImportModule $globalVar';     ExpectedErrorId = "ParameterArgumentValidationError,Microsoft.PowerShell.Commands.ImportModuleCommand" }
                @{ Name = "test 'ValidateTrustedDataAttribute' on [Start-Job]";         Argument = '$globalVar = {1+1}; Test-StartJob $globalVar';                  ExpectedErrorId = "ParameterArgumentValidationError,Microsoft.PowerShell.Commands.StartJobCommand" }
            )
        }

        It "<Name>" -TestCases $testCases {
            param ($Argument, $ExpectedErrorId)
            ## Run this in the global scope, so value of $globalVar will be marked as untrusted
            $testScript = $ScriptTemplate -f $Argument
            $result = Execute-Script -Script $testScript
            $result | Should -Be $ExpectedErrorId
        }
    }
}


text:
package pieces;

import java.util.ArrayList;
import java.util.List;

import game.Board;
import game.Direction;
import game.Move;
import game.Position;

/**
 * A knight. can move in an L shape.
 * @author Mitchell
 *
 */
public class Knight extends Piece {

	/**
	 * The directions that the knight can move.
	 */
	private Direction[] directions = {
			Direction.NORTH_WEST,
			Direction.NORTH,
			Direction.NORTH_EAST,
			Direction.EAST,
			Direction.SOUTH_EAST,
			Direction.SOUTH,
			Direction.SOUTH_WEST,
			Direction.WEST,
			Direction.NORTH_WEST };

	/**
	 * The max distance that the knight can move.
	 */
	private int maxDistance = 5;

	/**
	 * Creates a knight in the position and with the alliance colour.
	 * @param position The position for the knight.
	 * @param colour The alliance colour of the knight.
	 */
	public Knight(Position position, String colour) {
		super(position, colour, 3);
	}

	/**
	 * Creates a copy of another knight.
	 * @param other The knight to copy.
	 */
	public Knight(Knight other) {
		super(other);
	}

	// Get all possible (valid) moves
	public List<Move> getMoves(Board board) {
		List<Move> moves = new ArrayList<Move>();
		Position startPos = this.getPosition();

		for (int i = 1; i < directions.length; i += 2) {
			for (int j = -1; j < 2; j += 2) {
				// Perform first half of knight movement
				Position halfPos = startPos.positionAt(directions[i], 1);
				if (halfPos.positionAt(directions[i + j], 1).isValid()) {
					// Perform second half of knight movement
					Position endPos = halfPos.positionAt(directions[i + j], 1);
					Piece pieceTaken = board.getPieceAt(endPos);
					if (pieceTaken != null
							&& pieceTaken.getColour() != this.getColour()) {
						moves.add(new Move(board, startPos, endPos));
					} else if (pieceTaken == null) {
						moves.add(new Move(board, startPos, endPos));
					}
				}
			}
		}
		return moves;
	}

	public Direction[] getDirections() {
		return this.directions;
	}

	public int getMaxDistance() {
		return this.maxDistance;
	}

	public String toString() {
		if (this.getColour().equals("White")) {
			return "♘";
		} else {
			return "♞";
		}
	}

	@Override
	public Piece copy() {
		return new Knight(this);
	}
}


text:
Given /^the order is finalized$/ do
  order = Order.last
  order.finalize!
end

Then /^I should see order history tabular attributes$/ do
  output = tableish('table.index tr', 'td,th')
  data = output[0]
  data[0].should == 'Event'
  data[1].should == 'From State'
  data[2].should == 'To State'
  data[3].should == 'User'
  data[4].should == 'Date/Time'

  data = output[1]
  data[0].should == 'Order'
  data[1].should == 'cart'
  data[2].should == 'complete'
end


text:
package javax.servlet.http;

import java.util.EventListener;

/**
 * Implementations of this interface are notified of changes to the list of
 * active sessions in a web application. To receive notification events, the
 * implementation class must be configured in the deployment descriptor for the
 * web application.
 *
 * @see HttpSessionEvent
 * @since v 2.3
 */
public interface HttpSessionListener extends EventListener {

	/**
	 * Notification that a session was created. The default implementation is a
	 * NO-OP.
	 *
	 * @param se
	 *            the notification event
	 */
	public default void sessionCreated(HttpSessionEvent se)
	{
	}

	/**
	 * Notification that a session is about to be invalidated. The default
	 * implementation is a NO-OP.
	 *
	 * @param se
	 *            the notification event
	 */
	public default void sessionDestroyed(HttpSessionEvent se)
	{
	}
}


text:
/* jshint node: true */
'use strict';
var crypto = require('crypto');
var database = require('../config/database.js');

exports.getDetails = function  (secret_id,callback) {
	database.query('select id from apps where secret_id = "'+secret_id+'" and is_active = 1',function  (err,rows) {
		if (err) throw err;
		callback(rows);
	});
};

exports.getByName = function (name, callback) {
	database.query('select id from apps where name="'+name+'"',function(err, rows) {
		if (err) throw err;
		callback(rows);
	})
}

exports.create = function  (name, callback) {
	//console.log(database);
	var time = new Date();
	time = time.getTime();
	var secret_id = name+time;
	secret_id = crypto.createHash('md5').update(secret_id).digest('hex');
	database.query('insert into apps (id, name, secret_id, is_active, created_at) values (default, "'+name+'", "'+secret_id+'", 1, NOW())',function(err) {
		if (err) throw err;
		callback(secret_id);
	});
};

exports.deactivate = function (secret_id, callback) {
	database.query('update apps set is_active = 0 where secret_id = "'+secret_id+'"', function (err, result) {
		if (err) throw err;
		callback(result.affectedRows);
	});
};


text:
import { DIALOG_VISIBLE_CHANGE, DIALOG_CONTENT_CHANGE, DIALOG_LOADING_CHANGE, DIALOG_ERROR_CHANGE } from '../constants/actionTypes';

export function setDialogVisible (dialog, visible = true) {
  return {
    type: DIALOG_VISIBLE_CHANGE,
    dialog: dialog,
    visible: visible
  }
}

export function setDialogContent (dialog, content) {
  return {
    type: DIALOG_CONTENT_CHANGE,
    dialog: dialog,
    content: content
  }
}

export function setDialogLoading (dialog, loading = true) {
  return {
    type: DIALOG_LOADING_CHANGE,
    dialog: dialog,
    loading: loading
  }
}

export function setDialogError (dialog, error = '') {
  return {
    type: DIALOG_ERROR_CHANGE,
    error: error
  }
}


text:
describe Hastings::FS::Net::Paths do
  subject do
    Struct.new(:path) { include Hastings::FS::Net::Paths }.new path
  end
  let(:path) { "//share_name/long/path/goes/here" }

  describe "#base_dirs" do
    it "returns the share domain and share directory" do
      expect(subject.base_dirs).to eq %w(share_name long)
    end
  end

  describe "#base_path" do
    it "returns the hare domain and share directory in path form" do
      expect(subject.base_path).to eq("//share_name/long")
    end
  end

  describe "#local_dirs" do
    it "returns the rest of the directories (to be fetched locally)" do
      expect(subject.local_dirs).to eq %w(path goes here)
    end
  end

  describe "#local_base_path" do
    it "returns the path where things will be mounted" do
      expect(subject.local_base_path).to eq(
        File.join Hastings.root, "share_name", "long")
    end
  end

  describe "#local_full_path" do
    it "returns the path where things will be mounted" do
      expect(subject.local_full_path)
        .to eq(File.join Hastings.root, "share_name",
                         "long", "path", "goes", "here")
    end
  end
end


text:
namespace Osm
{

template <class E>
class Component : public IDable<Component<E>>
{
public:
	explicit Component(E& entity) : _owner(entity), _enabled(true) {}

	Component(Component& other) = delete;

	virtual ~Component()			{}

	E& GetOwner() const				{ return _owner; }

	bool GetEnbled() const			{ return _enabled; }

	void SetEnabled(bool enabled)		{ _enabled = enabled; }

#ifdef INSPECTOR
	virtual void Inspect() {}
#endif

protected:
	E& _owner;

protected:
	bool _enabled;
};

template <class E>
class ComponentContainer
{
public:
	/// Create a component of a certain kind
	template<class T>
	T* CreateComponent();

	/// Get a component of a certain kind
	template<class T>
	T* GetComponent();

	/// Get all components of a certain kind
	template<class T>
	std::vector<T*> GetComponents();

	/// Remove a component of a certain kind
	template<class T>
	void RemoveComponent();

	/// Set enabled for all components
	void SetComponentsEnabled(bool enbled);

protected:
	std::vector<std::unique_ptr<Component<E>>> _components;
};

template <class E>
template <class T>
T* ComponentContainer<E>::CreateComponent()
{
	E* _this = static_cast<E*>(this);
	T* component = new T(*_this);
	_components.push_back(std::unique_ptr<Component<E>>(component));
	return component;
}

template<class E>
template<class T>
T* ComponentContainer<E>::GetComponent()
{
	for (auto& c : _components)
	{
		T* found = dynamic_cast<T*>(c.get());
		if (found)
			return  found;
	}
	return nullptr;
}

template <class E>
template <class T>
std::vector<T*> ComponentContainer<E>::GetComponents()
{
	std::vector<T*> components;
	for (auto& c : _components)
	{
		T* found = dynamic_cast<T*>(c.get());
		if (found)
			components.push_back(found);
	}
	return components;
}

template <class E>
template <class T>
void ComponentContainer<E>::RemoveComponent()
{
	auto itr = _components.begin();
	T* found = nullptr;
	for (; itr != _components.end(); ++itr)
	{
		found = dynamic_cast<T*>((*itr).get());
		if (found)
			break;
	}

	if (found)
		_components.erase(itr);
}

template <class E>
void ComponentContainer<E>::SetComponentsEnabled(bool enabled)
{
	for (auto& c : _components)
	{
		c->SetEnabled(enabled);
	}
}

}


text:
extern crate bitflags;
extern crate log;
extern crate proc_macro;
extern crate unicode_width;


text:
"""This is a class that implements an interface to mySQL databases, conforming
to the API published by the Python db-sig at
http://www.python.org/sigs/db-sig/DatabaseAPI.html

It is really just a wrapper for an older python interface to mySQL databases
called mySQL, which I modified to facilitate use of a cursor.  That module was
Joseph Skinner's port of the mSQL module by David Gibson, which was a modified
version of Anthony Baxter's msql module.

As an example, to add some extra (unprivelledged) users to your database system,
and delete them again:

>>> import Mysqldb
>>> conn = Mysqldb.mysqldb('mysql@localhost root rootpasswd')
>>> curs = conn.cursor()
>>> curs.execute("insert into user (host, user) values ('%s', '%s')",
... [('localhost', 'linus'), ('somewhere.com.au', 'james')])
2
>>> curs.execute("select * from user")
>>> curs.fetchall()
 -- record listing --
>>> curs.execute("delete from user where host = 'somewhere.com.au' or user = 'linus'")
2
>>> curs.close()
>>> conn.close()

The argument to mysqldb.mysqldb is of the form 'db@host user pass',
'db@host user', 'db@host', 'db', 'db user pass' or 'db user'.

As always, the source is a good manual :-)

James Henstridge <james@daa.com.au>
"""

import _mysql
MySQL = _mysql
from string import upper, split, join

error = 'mysqldb.error'

from _mysql import FIELD_TYPE
_type_conv = { FIELD_TYPE.TINY: int,
               FIELD_TYPE.SHORT: int,
               FIELD_TYPE.LONG: long,
               FIELD_TYPE.FLOAT: float,
               FIELD_TYPE.DOUBLE: float,
               FIELD_TYPE.LONGLONG: long,
               FIELD_TYPE.INT24: int,
               FIELD_TYPE.YEAR: int }

def isDDL(q):
	return upper(split(q)[0]) in ('CREATE', 'ALTER', 'GRANT', 'REVOKE',
		'DROP', 'SET')
def isDML(q):
	return upper(split(q)[0]) in ('DELETE', 'INSERT', 'UPDATE', 'LOAD')
def isDQL(q):
	return upper(split(q)[0]) in ('SELECT', 'SHOW', 'DESC', 'DESCRIBE')

class DBAPITypeObject:

    def __init__(self,*values):
        self.values = values

    def __cmp__(self,other):
        if other in self.values:
            return 0
        if other < self.values:
            return 1
        else:
            return -1

_Set = DBAPITypeObject

STRING    = _Set(FIELD_TYPE.CHAR, FIELD_TYPE.ENUM, FIELD_TYPE.INTERVAL,
                 FIELD_TYPE.SET, FIELD_TYPE.STRING, FIELD_TYPE.VAR_STRING)
BINARY    = _Set(FIELD_TYPE.BLOB, FIELD_TYPE.LONG_BLOB, FIELD_TYPE.MEDIUM_BLOB,
                 FIELD_TYPE.TINY_BLOB)
NUMBER    = _Set(FIELD_TYPE.DECIMAL, FIELD_TYPE.DOUBLE, FIELD_TYPE.FLOAT,
	         FIELD_TYPE.INT24, FIELD_TYPE.LONG, FIELD_TYPE.LONGLONG,
	         FIELD_TYPE.TINY, FIELD_TYPE.YEAR)
DATE      = _Set(FIELD_TYPE.DATE, FIELD_TYPE.NEWDATE)
TIME      = _Set(FIELD_TYPE.TIME)
TIMESTAMP = _Set(FIELD_TYPE.TIMESTAMP, FIELD_TYPE.DATETIME)
ROWID     = _Set()

class Connection:
	"""This is the connection object for the mySQL database interface."""
	def __init__(self, host, user, passwd, db):
		from _mysql import CLIENT
		kwargs = {}
		kwargs['conv'] = _type_conv
		if host: kwargs['host'] = host
		if user: kwargs['user'] = user
		if passwd: kwargs['passwd'] = passwd
		if db: kwargs['db'] = db
		try:
			self.__conn = apply(MySQL.connect, (), kwargs)
		except MySQL.Error, msg:
			raise error, msg
		self.__curs = Cursor(self.__conn)
		self.__transactional = self.__conn.server_capabilities & CLIENT.TRANSACTIONS

	def __del__(self):
		self.close()

	def __getattr__(self, key):
		return getattr(self.__curs, key)

	def __setattr__(self, key, val):
		if key in ('arraysize', 'description', 'insert_id'):
			setattr(self.__curs, key, val)
		else:
			self.__dict__[key] = val

	def close(self):
		self.__conn = None

	def cursor(self):
		if self.__conn == None: raise error, "Connection is closed."
		return Cursor(self.__conn)

	def commit(self):
		"""Commit the current transaction."""
		if self.__transactional:
			 self.__conn.query("COMMIT")

	def rollback(self):
		"""Rollback the current transaction."""
		if self.__transactional:
			 self.__conn.query("ROLLBACK")
		else: raise error, "Not supported by server"

	def callproc(self, params=None): pass

	# These functions are just here so that every action that is
	# covered by mySQL is covered by mysqldb.  They are not standard
	# DB API.  The list* methods are not included, since they can be
	# done with the SQL SHOW command.
	def create(self, dbname):
		"""This is not a standard part of Python DB API."""
		self.__conn.query("CREATE DATABASE %s" % dbname)
		self.__conn.store_result()
		return None
	def drop(self, dbname):
		"""This is not a standard part of Python DB API."""
		self.__conn.query("DROP DATABASE %s" % dbname)
		self.__conn.store_result()
		return None
	def reload(self):
		"""This is not a standard part of Python DB API."""
		self.__conn.query("RELOAD TABLES")
		self.__conn.store_result()
		return None
	def shutdown(self):
                """This is not a standard part of Python DB API."""
		return self.__conn.shutdown()

class Cursor:
	"""A cursor object for use with connecting to mySQL databases."""
	def __init__(self, conn):
		self.__conn = conn
		self.__res = None
		self.arraysize = 1
		self.__dict__['description'] = None
		self.__open = 1
		self.insert_id = 0

	def __del__(self):
		self.close()

	def __setattr__(self, key, val):
		if key == 'description':
			raise error, "description is a read-only attribute."
		else:
			self.__dict__[key] = val

	def __delattr__(self, key):
		if key in ('description', 'arraysize', 'insert_id'):
			raise error, "%s can't be deleted." % (key,)
		else:
			del self.__dict__[key]

	def close(self):
		self.__conn = None
		self.__res = None
		self.__open = 0

	def execute(self, op, params=None):
		if not self.__open: raise error, "Cursor has been closed."
		if params:
			if type(params[0]) not in (type(()), type([])):
				params = [params]
			if isDDL(op):
				self.__dict__['description'] = None
				try:
					for x in params:
						self.__res = \
						self.__conn.query(op % x)
					self.insert_id = self.__res.insert_id()
				except MySQL.Error, msg:
					raise error, msg
				return 1
			if isDML(op):
				self.__dict__['description'] = None
				af = 0
				try:
					for x in params:
						self.__res = \
						self.__conn.query(op % x)
						af =af+self.__res.affectedrows()
					self.insert_id = self.__res.insert_id()
				except MySQL.Error, msg:
					raise error, msg
				return af
			if isDQL(op):
				try:
					self.__res = self.__conn.query(
						op % params[-1])
					self.insert_id = self.__res.insert_id()
				except MySQL.Error, msg:
					raise error, msg
				self.__dict__['description'] = self.__res.describe()
				return None
		else:
			try:
				self.__conn.query(op)
				self.__res = self.__conn.store_result()
				self.insert_id = self.__conn.insert_id()
			except MySQL.Error, msg:
				raise error, msg
			self.__dict__['description'] = None
			if isDDL(op):
				return 1
			elif self.__conn.affected_rows() != -1:
				return self.__conn.affected_rows()
			else:
				self.__dict__['description'] = self.__res.describe()
				return None
	def fetchone(self):
		if not self.__res: raise error, "no query made yet."
		try:
			return self.__res.fetch_row(1)[0]
		except MySQL.Error, msg:
			raise error, msg

	def fetchmany(self, size=None):
		if not self.__res: raise error, "no query made yet."
		try:
			return self.__res.fetch_row(size or self.arraysize)
		except MySQL.Error, msg:
			raise error, msg

	def fetchall(self):
		if not self.__res: raise error, "no query made yet."
		try:
			return self.__res.fetch_row(0)
		except MySQL.Error, msg:
			raise error, msg

	def fetchoneDict(self):
		"""This is not a standard part of Python DB API."""
		if not self.__res: raise error, "no query made yet."
		try:
			return  self.__res.fetch_row(1, 2)[0]
		except MySQL.Error, msg:
			raise error, msg

	def fetchmanyDict(self, size=None):
		"""This is not a standard part of Python DB API."""
		if not self.__res: raise error, "no query made yet."
		try:
			return  self.__res.fetch_row(size or self.arraysize, 2)
		except MySQL.Error, msg:
			raise error, msg

	def fetchallDict(self):
		"""This is not a standard part of Python DB API."""
		if not self.__res: raise error, "no query made yet."
		try:
			return self.__res.fetch_row(0,2)
		except MySQL.Error, msg:
			raise error, msg

	def setinputsizes(self, sizes): pass
	def setoutputsize(self, size, col=None): pass

def mysqldb(connect_string):
	"""Makes a connection to the MySQL server.  The Argument should be of
	the form 'db@host user pass' or 'db@host user' or 'db@host' or 'db'
	or 'db user pass' or 'db user', where db is the database name, host
	is the server's host name, user is your user name, and pass is your
	password."""
	val = split(connect_string)
	if len(val) == 0: raise error, "no database specified"
	while len(val) < 3: val.append('')
	dh = split(val[0], '@')
	if len(dh) == 0: raise error, "no database specified"
	while len(dh) < 2: dh.append('')
	return Connection(dh[1], val[1], val[2], dh[0])


text:
<!DOCTYPE html>

    <title>Cluster.Worker#isConnected documentation</title>
    <link rel="stylesheet" type="text/css" href="../../../../../../index.css" />
    <link rel="stylesheet" type="text/css" href="../../../../../../highlight.css" />

            member

                Function

                |

                :Cluster.Worker#isConnected

                    isConnected (
                    ) {

        This document was generated with
        doczar
        at 3:55pm on 8/14/2015


text:
package base.models.annotations;

import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;

@Retention(RetentionPolicy.RUNTIME)
@Target({ElementType.TYPE})
public @interface TrackHistory {
    Class<?> model() default void.class;
    String pkg() default "models.history";
}


text:
namespace visionaray
{
namespace gl
{

shader::shader(GLuint name)
    : name_(name)
{
}

shader::~shader()
{
    reset();
}

void shader::destroy()
{
#if VSNRAY_HAVE_GLEW || VSNRAY_HAVE_OPENGLES
    glDeleteShader(name_);
#endif
}

void shader::reset(GLuint name)
{
    if (name_ != 0)
    {
        destroy();
    }

    name_ = name;
}

GLuint shader::get() const
{
    return name_;
}

void shader::set_source(char const* source) const
{
#if VSNRAY_HAVE_GLEW || VSNRAY_HAVE_OPENGLES
    GLint len = static_cast<GLint>(std::strlen(source));

    glShaderSource(name_, 1, &source, &len);
#else
    VSNRAY_UNUSED(source);
#endif
}

void shader::compile() const
{
#if VSNRAY_HAVE_GLEW || VSNRAY_HAVE_OPENGLES
    glCompileShader(name_);
#endif
}

bool shader::check_compiled() const
{
#if VSNRAY_HAVE_GLEW || VSNRAY_HAVE_OPENGLES
    GLint success = GL_FALSE;
    glGetShaderiv(name_, GL_COMPILE_STATUS, &success);

    if (!success)
    {
        GLint length = 0;
        glGetShaderiv(name_, GL_INFO_LOG_LENGTH, &length);

        if (length > 0)
        {
            std::vector<GLchar> buf(static_cast<size_t>(length));
            glGetShaderInfoLog(name_, length, &length, buf.data());
            std::cerr << std::string(buf.data()) << '\n';
        }

        return false;
    }

    return true;
#else
    return false;
#endif
}

} // gl
} // visionaray


text:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Microsoft.VisualStudio.TestTools.UnitTesting;
using CCT.NUI.Core.Clustering;
using CCT.NUI.Core;

namespace CCT.NUI.Tests.Core.Clustering
{
    [TestClass]
    public class KMeansClusterFactoryTests
    {
        private KMeansClusterFactory factory;
        private IntSize size;

        [TestInitialize]
        public void Setup()
        {
            var settings = new ClusterDataSourceSettings();
            settings.LowerBorder = 0;
            settings.MinimalPointsForClustering = 1;
            settings.MinimalPointsForValidCluster = 1;
            settings.PointModulo = 1;
            settings.MergeMaximumClusterCenterDistances = 1;
            settings.MergeMaximumClusterCenterDistances2D = 1;
            settings.MergeMinimumDistanceToCluster = 1;

            this.size = new IntSize(20, 10);

            this.factory = new KMeansClusterFactory(settings, this.size);
        }

        [TestMethod]
        public void Creates_Two_Clusters()
        {
            var data = PrepareTwoClusterData();

            var result = this.factory.Create(data);

            Assert.AreEqual(2, result.Count);
        }

        private IList<Point> PrepareTwoClusterData()
        {
            var data = new List<Point>();
            for (int x = 0; x < this.size.Width; x++)
            {
                for (int y = 0; y < this.size.Height; y++)
                {
                    if ((x == 2 && y == 2) || (x == 15 && y == 8))
                    {
                        data.Add(new Point(x, y, 700));
                    }
                }
            }
            return data;
        }
    }
}


text:
<?php namespace Fungku\NetSuite\Classes;

class EmployeeAddressbook {
	public $defaultShipping;
	public $defaultBilling;
	public $label;
	public $addressbookAddress;
	public $internalId;
	static $paramtypesmap = array(
		"defaultShipping" => "boolean",
		"defaultBilling" => "boolean",
		"label" => "string",
		"addressbookAddress" => "Address",
		"internalId" => "string",
	);
}


text:
class ActiveAdmin::Inputs::SelectInput < Formtastic::Inputs::SelectInput
  def input_html_options
    super.merge(data: { tags: @options[:tags].present? })
  end

  def raw_collection
    field_value = begin
                    object.send(method)
                  rescue NoMethodError
                    nil
                  end

    @options[:tags].present? && field_value.present? ? (super.to_a << field_value).uniq : super
  end
end


text:
using System;
using System.Collections;
using System.Xml;
using System.Xml.Schema;
using System.IO;
using System.Threading;
using NUnit.Core;

namespace NUnit.Util
{
	/// <summary>
	/// Types of changes that may occur to a config
	/// </summary>
	public enum ProjectChangeType
	{
		ActiveConfig,
		AddConfig,
		RemoveConfig,
		UpdateConfig,
		Other
	}

	/// <summary>
	///  Arguments for a project event
	/// </summary>
	public class ProjectEventArgs : EventArgs
	{
		public ProjectChangeType type;
		public string configName;

		public ProjectEventArgs( ProjectChangeType type, string configName )
		{
			this.type = type;
			this.configName = configName;
		}
	}

	/// <summary>
	/// Delegate to be used to handle project events
	/// </summary>
	public delegate void ProjectEventHandler( object sender, ProjectEventArgs e );

	/// <summary>
	/// Class that represents an NUnit test project
	/// </summary>
	public class NUnitProject
	{
		#region Static and instance variables

		/// <summary>
		/// Used to generate default names for projects
		/// </summary>
		private static int projectSeed = 0;

		/// <summary>
		/// The extension used for test projects
		/// </summary>
		private static readonly string nunitExtension = ".nunit";

		/// <summary>
		/// Path to the file storing this project
		/// </summary>
		private string projectPath;

		/// <summary>
		/// Application Base for the project. Since this
		/// can be null, always fetch from the property
		/// rather than using the field directly.
		/// </summary>
		private string basePath;

		/// <summary>
		///  Whether the project is dirty
		/// </summary>
		private bool isDirty = false;

		/// <summary>
		/// Collection of configs for the project
		/// </summary>
		private ProjectConfigCollection configs;

		/// <summary>
		/// The currently active configuration
		/// </summary>
		private ProjectConfig activeConfig;

		/// <summary>
		/// Flag indicating that this project is a
		/// temporary wrapper for an assembly.
		/// </summary>
		private bool isAssemblyWrapper = false;

		#endregion

		#region Constructor

		public NUnitProject( string projectPath )
		{
			this.projectPath = Path.GetFullPath( projectPath );
			configs = new ProjectConfigCollection( this );
		}

		#endregion

		#region Static Methods
		// True if it's one of our project types
		public static bool IsProjectFile( string path )
		{
			return Path.GetExtension( path ) == nunitExtension;
		}

		// True if it's ours or one we can load
		public static bool CanLoadAsProject( string path )
		{
			return	IsProjectFile( path ) ||
					VSProject.IsProjectFile( path ) ||
					VSProject.IsSolutionFile( path );
		}

		public static string GenerateProjectName()
		{
			return string.Format( "Project{0}", ++projectSeed );
		}

		public static NUnitProject EmptyProject()
		{
			return new NUnitProject( GenerateProjectName() );
		}

		public static NUnitProject NewProject()
		{
			NUnitProject project = EmptyProject();

			project.Configs.Add( "Debug" );
			project.Configs.Add( "Release" );
			project.IsDirty = false;

			return project;
		}

		/// <summary>
		/// Return a test project by either loading it from
		/// the supplied path, creating one from a VS file
		/// or wrapping an assembly.
		/// </summary>
		public static NUnitProject LoadProject( string path )
		{
			if ( NUnitProject.IsProjectFile( path ) )
			{
				NUnitProject project = new NUnitProject( path );
				project.Load();
				return project;
			}
			else if ( VSProject.IsProjectFile( path ) )
				return NUnitProject.FromVSProject( path );
			else if ( VSProject.IsSolutionFile( path ) )
				return NUnitProject.FromVSSolution( path );
			else
				return NUnitProject.FromAssembly( path );

		}

		/// <summary>
		/// Creates a project to wrap a list of assemblies
		/// </summary>
		public static NUnitProject FromAssemblies( string[] assemblies )
		{
			// if only one assembly is passed in then the configuration file
			// should follow the name of the assembly. This will only happen
			// if the LoadAssembly method is called. Currently the console ui
			// does not differentiate between having one or multiple assemblies
			// passed in.
			if ( assemblies.Length == 1)
				return NUnitProject.FromAssembly(assemblies[0]);

			NUnitProject project = NUnitProject.EmptyProject();
			ProjectConfig config = new ProjectConfig( "Default" );
			foreach( string assembly in assemblies )
			{
				string fullPath = Path.GetFullPath( assembly );

				if ( !File.Exists( fullPath ) )
					throw new FileNotFoundException( string.Format( "Assembly not found: {0}", fullPath ) );

				config.Assemblies.Add( fullPath );
			}

			project.Configs.Add( config );

			// TODO: Deduce application base, and provide a
			// better value for loadpath and project path
			// analagous to how new projects are handled
			string basePath = Path.GetDirectoryName( Path.GetFullPath( assemblies[0] ) );
			project.projectPath = Path.Combine( basePath, project.Name + ".nunit" );

			project.IsDirty = true;

			return project;
		}

		/// <summary>
		/// Creates a project to wrap an assembly
		/// </summary>
		public static NUnitProject FromAssembly( string assemblyPath )
		{
			if ( !File.Exists( assemblyPath ) )
				throw new FileNotFoundException( string.Format( "Assembly not found: {0}", assemblyPath ) );

			string fullPath = Path.GetFullPath( assemblyPath );

			NUnitProject project = new NUnitProject( fullPath );

			ProjectConfig config = new ProjectConfig( "Default" );
			config.Assemblies.Add( fullPath );
			project.Configs.Add( config );

			project.isAssemblyWrapper = true;
			project.IsDirty = false;

			return project;
		}

		public static NUnitProject FromVSProject( string vsProjectPath )
		{
			NUnitProject project = new NUnitProject( Path.GetFullPath( vsProjectPath ) );

			VSProject vsProject = new VSProject( vsProjectPath );
			project.Add( vsProject );

			project.isDirty = false;

			return project;
		}

		public static NUnitProject FromVSSolution( string solutionPath )
		{
			NUnitProject project = new NUnitProject( Path.GetFullPath( solutionPath ) );

			string solutionDirectory = Path.GetDirectoryName( solutionPath );
			using(StreamReader reader = new StreamReader( solutionPath ))
			{
				char[] delims = { '=', ',' };
				char[] trimchars = { ' ', '"' };

				string line = reader.ReadLine();
				while ( line != null )
				{
					if ( line.StartsWith( "Project" ) )
					{
						string[] parts = line.Split( delims );
						string vsProjectPath = parts[2].Trim(trimchars);

						if ( VSProject.IsProjectFile( vsProjectPath ) )
							project.Add( new VSProject( Path.Combine( solutionDirectory, vsProjectPath ) ) );
					}

					line = reader.ReadLine();
				}
			}

			project.isDirty = false;

			return project;
		}

		/// <summary>
		/// Figure out the proper name to be used when saving a file.
		/// </summary>
		public static string ProjectPathFromFile( string path )
		{
			string fileName = Path.GetFileNameWithoutExtension( path ) + nunitExtension;
			return Path.Combine( Path.GetDirectoryName( path ), fileName );
		}

		#endregion

		#region Properties and Events

		public static int ProjectSeed
		{
			get { return projectSeed; }
			set { projectSeed = value; }
		}

		/// <summary>
		/// The path to which a project will be saved.
		/// </summary>
		public string ProjectPath
		{
			get { return projectPath; }
			set
			{
				projectPath = Path.GetFullPath( value );
				isDirty = true;
			}
		}

		public string DefaultBasePath
		{
			get { return Path.GetDirectoryName( projectPath ); }
		}

		/// <summary>
		/// The base path for the project. Constructor sets
		/// it to the directory part of the project path.
		/// </summary>
		public string BasePath
		{
			get
			{
				if ( basePath == null || basePath == string.Empty )
					return DefaultBasePath;
				return basePath;
			}
			set
			{
				basePath = value;

				if ( basePath != null && basePath != string.Empty
					&& !Path.IsPathRooted( basePath ) )
				{
					basePath = Path.Combine(
						DefaultBasePath,
						basePath );
				}

				basePath = PathUtils.Canonicalize( basePath );
			}
		}

		/// <summary>
		/// The name of the project.
		/// </summary>
		public string Name
		{
			get { return Path.GetFileNameWithoutExtension( projectPath ); }
		}

		public ProjectConfig ActiveConfig
		{
			get
			{
				// In case the previous active config was removed
				if ( activeConfig != null && !configs.Contains( activeConfig ) )
					activeConfig = null;

				// In case no active config is set or it was removed
				if ( activeConfig == null && configs.Count > 0 )
					activeConfig = configs[0];

				return activeConfig;
			}
		}

		// Safe access to name of the active config
		public string ActiveConfigName
		{
			get
			{
				ProjectConfig config = ActiveConfig;
				return config == null ? null : config.Name;
			}
		}

		public bool IsLoadable
		{
			get
			{
				return	ActiveConfig != null &&
					ActiveConfig.Assemblies.Count > 0;
			}
		}

		// A project made from a single assembly is treated
		// as a transparent wrapper for some purposes until
		// a change is made to it.
		public bool IsAssemblyWrapper
		{
			get { return isAssemblyWrapper; }
		}

		public string ConfigurationFile
		{
			get
			{
				// TODO: Check this
				return isAssemblyWrapper
					  ? Path.GetFileName( projectPath ) + ".config"
					  : Path.GetFileNameWithoutExtension( projectPath ) + ".config";
			}
		}

		public bool IsDirty
		{
			get { return isDirty; }
			set { isDirty = value; }
		}

		public ProjectConfigCollection Configs
		{
			get { return configs; }
		}

		public event ProjectEventHandler Changed;

		#endregion

		#region Instance Methods

		public void SetActiveConfig( int index )
		{
			activeConfig = configs[index];
			OnProjectChange( ProjectChangeType.ActiveConfig, activeConfig.Name );
		}

		public void SetActiveConfig( string name )
		{
			foreach( ProjectConfig config in configs )
			{
				if ( config.Name == name )
				{
					activeConfig = config;
					OnProjectChange( ProjectChangeType.ActiveConfig, activeConfig.Name );
					break;
				}
			}
		}

//		public int IndexOf( string name )
//		{
//			for( int index = 0; index < configs.Count; index++ )
//				if( configs[index].Name == name )
//					return index;
//
//			return -1;
//		}

		public void OnProjectChange( ProjectChangeType type, string configName )
		{
			isDirty = true;

			if ( isAssemblyWrapper )
			{
				projectPath = Path.ChangeExtension( projectPath, ".nunit" );
				isAssemblyWrapper = false;
			}

			if ( Changed != null )
				Changed( this, new ProjectEventArgs( type, configName ) );

			if ( type == ProjectChangeType.RemoveConfig )
			{
				if ( activeConfig == null || activeConfig.Name == configName )
				{
					if ( configs.Count > 0 )
						SetActiveConfig( 0 );
				}
			}
		}

		public void Add( VSProject vsProject )
		{
			foreach( VSProjectConfig vsConfig in vsProject.Configs )
			{
				string name = vsConfig.Name;

				if ( !configs.Contains( name ) )
					configs.Add( name );

				ProjectConfig config = this.Configs[name];

				foreach ( string assembly in vsConfig.Assemblies )
					config.Assemblies.Add( assembly );
			}
		}

		public void Load()
		{
			XmlTextReader reader = new XmlTextReader( projectPath );

			string activeConfigName = null;
			ProjectConfig currentConfig = null;

			try
			{
				reader.MoveToContent();
				if ( reader.NodeType != XmlNodeType.Element || reader.Name != "NUnitProject" )
					throw new ProjectFormatException(
						"Invalid project format: <NUnitProject> expected.",
						reader.LineNumber, reader.LinePosition );

				while( reader.Read() )
					if ( reader.NodeType == XmlNodeType.Element )
						switch( reader.Name )
						{
							case "Settings":
								if ( reader.NodeType == XmlNodeType.Element )
								{
									activeConfigName = reader.GetAttribute( "activeconfig" );
                                    if (activeConfigName == "NUnitAutoConfig")
                                    {
#if DEBUG
                                        if (Environment.Version.Major == 2)
                                            activeConfigName = "Debug2005";
                                        else
                                            activeConfigName = "Debug";
#else
                                        if (Environment.Version.Major == 2)
                                            activeConfigName = "Release2005";
                                        else
                                            activeConfigName = "Release";
#endif
                                    }
									string appbase = reader.GetAttribute( "appbase" );
									if ( appbase != null )
										this.BasePath = appbase;
								}
								break;

							case "Config":
								if ( reader.NodeType == XmlNodeType.Element )
								{
									string configName = reader.GetAttribute( "name" );
									currentConfig = new ProjectConfig( configName );
									currentConfig.BasePath = reader.GetAttribute( "appbase" );
									currentConfig.ConfigurationFile = reader.GetAttribute( "configfile" );

									string binpath = reader.GetAttribute( "binpath" );
									currentConfig.PrivateBinPath = binpath;
									string type = reader.GetAttribute( "binpathtype" );
									if ( type == null )
										if ( binpath == null )
											currentConfig.BinPathType = BinPathType.Auto;
										else
											currentConfig.BinPathType = BinPathType.Manual;
									else
										currentConfig.BinPathType = (BinPathType)Enum.Parse( typeof( BinPathType ), type, true );
									Configs.Add( currentConfig );
									if ( configName == activeConfigName )
										activeConfig = currentConfig;
								}
								else if ( reader.NodeType == XmlNodeType.EndElement )
									currentConfig = null;
								break;

							case "assembly":
								if ( reader.NodeType == XmlNodeType.Element && currentConfig != null )
								{
									string path = reader.GetAttribute( "path" );
									currentConfig.Assemblies.Add(
										Path.Combine( currentConfig.BasePath, path ) );
								}
								break;

							default:
								break;
						}

				this.IsDirty = false;
			}
			catch( FileNotFoundException )
			{
				throw;
			}
			catch( XmlException e )
			{
				throw new ProjectFormatException(
					string.Format( "Invalid project format: {0}", e.Message ),
					e.LineNumber, e.LinePosition );
			}
			catch( Exception e )
			{
				throw new ProjectFormatException(
					string.Format( "Invalid project format: {0} Line {1}, Position {2}",
					e.Message, reader.LineNumber, reader.LinePosition ),
					reader.LineNumber, reader.LinePosition );
			}
			finally
			{
				reader.Close();
			}
		}

		public void Save()
		{
			projectPath = ProjectPathFromFile( projectPath );

			XmlTextWriter writer = new XmlTextWriter(  projectPath, System.Text.Encoding.UTF8 );
			writer.Formatting = Formatting.Indented;

			writer.WriteStartElement( "NUnitProject" );

			if ( configs.Count > 0 || this.BasePath != this.DefaultBasePath )
			{
				writer.WriteStartElement( "Settings" );
				if ( configs.Count > 0 )
					writer.WriteAttributeString( "activeconfig", ActiveConfigName );
				if ( this.BasePath != this.DefaultBasePath )
					writer.WriteAttributeString( "appbase", this.BasePath );
				writer.WriteEndElement();
			}

			foreach( ProjectConfig config in Configs )
			{
				writer.WriteStartElement( "Config" );
				writer.WriteAttributeString( "name", config.Name );
				string appbase = config.BasePath;
				if ( !PathUtils.SamePathOrUnder( this.BasePath, appbase ) )
					writer.WriteAttributeString( "appbase", appbase );
				else if ( config.RelativeBasePath != null )
					writer.WriteAttributeString( "appbase", config.RelativeBasePath );

				string configFile = config.ConfigurationFile;
				if ( configFile != null && configFile != this.ConfigurationFile )
					writer.WriteAttributeString( "configfile", config.ConfigurationFile );

				if ( config.BinPathType == BinPathType.Manual )
					writer.WriteAttributeString( "binpath", config.PrivateBinPath );
				else
					writer.WriteAttributeString( "binpathtype", config.BinPathType.ToString() );

				foreach( string assembly in config.Assemblies )
				{
					writer.WriteStartElement( "assembly" );
					writer.WriteAttributeString( "path", PathUtils.RelativePath( config.BasePath, assembly ) );
					writer.WriteEndElement();
				}

				writer.WriteEndElement();
			}

			writer.WriteEndElement();

			writer.Close();
			this.IsDirty = false;

			// Once we save a project, it's no longer
			// loaded as an assembly wrapper on reload.
			this.isAssemblyWrapper = false;
		}

		public void Save( string projectPath )
		{
			this.ProjectPath = projectPath;
			Save();
		}

		public TestPackage MakeTestPackage()
		{
			TestPackage package = new TestPackage( this.ProjectPath );

			if ( !this.IsAssemblyWrapper )
				foreach ( string assembly in this.ActiveConfig.Assemblies )
					package.Assemblies.Add( assembly );

			package.BasePath = this.ActiveConfig.BasePath;
			package.ConfigurationFile = this.ActiveConfig.ConfigurationFile;
			package.PrivateBinPath = this.ActiveConfig.PrivateBinPath;
			package.AutoBinPath = this.ActiveConfig.BinPathType == BinPathType.Auto;

			return package;
		}
		#endregion
	}
}


text:
package io.cattle.iaas.lb.api.action;

import io.cattle.iaas.lb.service.LoadBalancerService;
import io.cattle.platform.api.action.ActionHandler;
import io.cattle.platform.core.constants.LoadBalancerConstants;
import io.cattle.platform.core.dao.GenericMapDao;
import io.cattle.platform.core.model.LoadBalancerConfig;
import io.cattle.platform.core.model.LoadBalancerConfigListenerMap;
import io.cattle.platform.json.JsonMapper;
import io.cattle.platform.object.ObjectManager;
import io.cattle.platform.object.util.DataAccessor;
import io.github.ibuildthecloud.gdapi.request.ApiRequest;

import java.util.ArrayList;
import java.util.List;

import javax.inject.Inject;

public class LoadBalancerConfigSetListenersActionHandler implements ActionHandler {
    @Inject
    JsonMapper jsonMapper;

    @Inject
    GenericMapDao mapDao;

    @Inject
    ObjectManager objectManager;

    @Inject
    LoadBalancerService lbService;

    @Override
    public String getName() {
        return LoadBalancerConstants.PROCESS_LB_CONFIG_SET_LISTENERS;
    }

    @Override
    public Object perform(String name, Object obj, ApiRequest request) {
        if (!(obj instanceof LoadBalancerConfig)) {
            return null;
        }
        LoadBalancerConfig config = (LoadBalancerConfig) obj;
        List<? extends Long> newListenerIds = DataAccessor.fromMap(request.getRequestObject())
                .withKey(LoadBalancerConstants.FIELD_LB_LISTENER_IDS).asList(jsonMapper,
                Long.class);

        if (newListenerIds != null) {
            // remove old listeners set
            removeOldListenerMaps(config, newListenerIds);

            // create a new set
            createNewListenerMaps(config, newListenerIds);
        }
        return objectManager.reload(config);
    }

    private void createNewListenerMaps(LoadBalancerConfig config, List<? extends Long> newListenerIds) {
        for (Long listenerId : newListenerIds) {
            lbService.addListenerToConfig(config, listenerId);
        }
    }

    private void removeOldListenerMaps(LoadBalancerConfig config, List<? extends Long> newListenerIds) {
        List<? extends LoadBalancerConfigListenerMap> existingMaps = mapDao.findToRemove(
                LoadBalancerConfigListenerMap.class, LoadBalancerConfig.class, config
                        .getId());

        List<LoadBalancerConfigListenerMap> mapsToRemove = new ArrayList<>();

        for (LoadBalancerConfigListenerMap existingListenerId : existingMaps) {
            if (!newListenerIds.contains(existingListenerId.getLoadBalancerListenerId())) {
                mapsToRemove.add(existingListenerId);
            }
        }

        for (LoadBalancerConfigListenerMap mapToRemove : mapsToRemove) {
            lbService.removeListenerFromConfig(config, mapToRemove.getLoadBalancerListenerId());
        }
    }
}


text:
You realize that you shouldn't automattically assume the
marshmellow man is your captor. You attempt to greet him and
to your great surprise he speaks english. He informs you
that he was simply trying to hand you the lighter. He is
also a captive but has been unable to escapte or use the
lighter due to lack of aposable thumbs.
Do you:

[Laugh out loud!](lol/laugh-out-loud.md)

[Do not tell him you're hungry!](hungry/hungry.md)

[Attempt to speak the marshmallowish language](marshmallowish/marshmallowish.md)


text:
class FetchNewMovieReleasesJob < ActiveJob::Base
  queue_as :default

  def perform(movie)
    ActiveRecord::Base.connection_pool.with_connection do
      fetch_releases(movie)
    end
  end

  private

  def fetch_releases(movie)
    Services::FetchNewMovieReleases.new(movie).perform
  end
end