text:
#pragma once

#include <tvector.h>
#include <tstring.h>
#include <vector.h>
#include <geometry.h>
#include <trs.h>

class CToy;

class CSceneArea
{
public:
	AABB					m_aabbArea;
	tvector<uint32_t>		m_aiNeighboringAreas;
	tvector<uint32_t>		m_aiVisibleAreas;
	tstring					m_sFileName;
};

// For reading and writing .toy files
class CToyUtil
{
public:
					CToyUtil();

public:
	tstring			GetGameDirectory() const { return m_sGameDirectory; }
	void			SetGameDirectory(const tstring& sGame) { m_sGameDirectory = sGame; }
	tstring			GetGameDirectoryFile(const tstring& sFile) const;

	tstring			GetScriptDirectory() const { return m_sScriptDirectory; }
	void			SetScriptDirectory(const tstring& sScript) { m_sScriptDirectory = sScript; }
	tstring			GetScriptDirectoryFile(const tstring& sFile) const;

	tstring			GetOutputDirectory() const { return m_sOutputDirectory; }
	void			SetOutputDirectory(const tstring& sOutput) { m_sOutputDirectory = sOutput; }

	tstring			GetOutputFile() const { return m_sOutputFile; }
	void			SetOutputFile(const tstring& sOutput) { m_sOutputFile = sOutput; }

	void			AddMaterial(const tstring& sMaterial, const tstring& sOriginalFile = "");
	size_t			GetNumMaterials() { return m_asMaterials.size(); }
	void            UseUV(bool bUse = true);
	void            UseNormals(bool bUse = true);
	void            AddVertex(size_t iMaterial, const Vector& vecPosition, const Vector2D& vecUV, const Matrix4x4& mNormals = Matrix4x4());
	size_t          GetNumVerts() const;
	bool            IsUsingUV() const { return m_bUseUV; }
	bool            IsUsingNormals() const { return m_bUseNormals; }

	size_t          GetVertexSizeInBytes() const;
	int             GetVertexUVOffsetInBytes() const;
	int             GetVertexNormalOffsetInBytes() const;
	int             GetVertexTangentOffsetInBytes() const;
	int             GetVertexBitangentOffsetInBytes() const;

	void			AddPhysTriangle(size_t v1, size_t v2, size_t v3);
	void			AddPhysVertex(Vector vecPosition);
	void            AllowConcave(bool bAllowed) { m_bConcaveAllowed = bAllowed; }
	bool            IsConcaveAllowed() { return m_bConcaveAllowed; }
	size_t			GetNumPhysIndices() { return m_aiPhysIndices.size(); }
	size_t			GetNumPhysVerts() { return m_avecPhysVerts.size(); }

	// Shapes
	void			AddPhysBox(const TRS& trsBox);
	size_t			GetNumPhysBoxes() { return m_atrsPhysBoxes.size(); }

	size_t			AddSceneArea(const tstring& sFileName);
	void			AddSceneAreaNeighbor(size_t iSceneArea, size_t iNeighbor);
	void			AddSceneAreaVisible(size_t iSceneArea, size_t iVisible);
	bool			IsVisibleFrom(size_t iSceneArea, size_t iVisible);
	size_t			GetNumSceneAreas() { return m_asSceneAreas.size(); }

	AABB			GetVisBounds() { return m_aabbVisBounds; };
	AABB			GetPhysBounds() { return m_aabbPhysBounds; };

	void			SetNeighborDistance(float flDistance) { m_flNeighborDistance = flDistance; };
	void			UseGlobalTransformations(bool bGlobal = true) { m_bUseLocalTransforms = !bGlobal; };
	void			UseLocalTransformations(bool bLocal = true) { m_bUseLocalTransforms = bLocal; };
	bool			IsUsingLocalTransformations() const { return m_bUseLocalTransforms; };

	void			AddVisibleNeighbors(size_t iArea, size_t iVisible);
	void			CalculateVisibleAreas();
	bool			Write(const tstring& sFileName);

	static bool		Read(const tstring& sFileName, CToy* pToy);

protected:
	tstring					m_sGameDirectory;
	tstring					m_sScriptDirectory;
	tstring					m_sOutputDirectory;
	tstring					m_sOutputFile;

	bool m_bUseUV;
	bool m_bUseNormals;

	tvector<tstring>			m_asMaterials;
	//tvector<tstring>			m_asCopyTextures;
	tvector<tvector<float> >	m_aaflData;
	AABB						m_aabbVisBounds;
	AABB						m_aabbPhysBounds;
	tvector<uint32_t>			m_aiPhysIndices;
	tvector<Vector>				m_avecPhysVerts;
	tvector<TRS>				m_atrsPhysBoxes;
	bool                        m_bConcaveAllowed;
	tvector<CSceneArea>			m_asSceneAreas;

	float					m_flNeighborDistance;	// How far can an area be considered a neighbor in the finding neighbors check?
	bool					m_bUseLocalTransforms;
};

redpajama_set_name: RedPajamaGithub


text:
/* -*- Mode:C++; c-file-style:"gnu"; indent-tabs-mode:nil; -*- */
/*
 * Copyright (c) 2006 INRIA
 *
 * This program is free software; you can redistribute it and/or modify
 * it under the terms of the GNU General Public License version 2 as
 * published by the Free Software Foundation;
 *
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with this program; if not, write to the Free Software
 * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
 *
 * Author: Mathieu Lacage <mathieu.lacage@sophia.inria.fr>
 */
#include "ns3/system-wall-clock-ms.h"
#include "ns3/packet.h"
#include "ns3/packet-metadata.h"
#include <iostream>
#include <sstream>
#include <string>
#include <stdlib.h> // for exit ()

using namespace ns3;

template <int N>
class BenchHeader : public Header
{
public:
  BenchHeader ();
  bool IsOk (void) const;

  static TypeId GetTypeId (void);
  virtual TypeId GetInstanceTypeId (void) const;
  virtual void Print (std::ostream &os) const;
  virtual uint32_t GetSerializedSize (void) const;
  virtual void Serialize (Buffer::Iterator start) const;
  virtual uint32_t Deserialize (Buffer::Iterator start);
private:
  static std::string GetTypeName (void);
  bool m_ok;
};

template <int N>
BenchHeader<N>::BenchHeader ()
  : m_ok (false)
{}

template <int N>
bool
BenchHeader<N>::IsOk (void) const
{
  return m_ok;
}

template <int N>
std::string
BenchHeader<N>::GetTypeName (void)
{
  std::ostringstream oss;
  oss << "ns3::BenchHeader<" << N << ">";
  return oss.str ();
}

template <int N>
TypeId
BenchHeader<N>::GetTypeId (void)
{
  static TypeId tid = TypeId (GetTypeName ().c_str ())
    .SetParent<Header> ()
    ;
  return tid;
}
template <int N>
TypeId
BenchHeader<N>::GetInstanceTypeId (void) const
{
  return GetTypeId ();
}

template <int N>
void
BenchHeader<N>::Print (std::ostream &os) const
{
  NS_ASSERT (false);
}
template <int N>
uint32_t
BenchHeader<N>::GetSerializedSize (void) const
{
  return N;
}
template <int N>
void
BenchHeader<N>::Serialize (Buffer::Iterator start) const
{
  start.WriteU8 (N, N);
}
template <int N>
uint32_t
BenchHeader<N>::Deserialize (Buffer::Iterator start)
{
  m_ok = true;
  for (int i = 0; i < N; i++)
    {
      if (start.ReadU8 () != N)
        {
          m_ok = false;
        }
    }
  return N;
}

template <int N>
class BenchTag : public Tag
{
public:
  static std::string GetName (void) {
    std::ostringstream oss;
    oss << "anon::BenchTag<" << N << ">";
    return oss.str ();
  }
  static TypeId GetTypeId (void) {
    static TypeId tid = TypeId (GetName ().c_str ())
      .SetParent<Tag> ()
      .AddConstructor<BenchTag > ()
      .HideFromDocumentation ()
      ;
    return tid;
  }
  virtual TypeId GetInstanceTypeId (void) const {
    return GetTypeId ();
  }
  virtual uint32_t GetSerializedSize (void) const {
    return N;
  }
  virtual void Serialize (TagBuffer buf) const {
    for (uint32_t i = 0; i < N; ++i)
      {
        buf.WriteU8 (N);
      }
  }
  virtual void Deserialize (TagBuffer buf) {
    for (uint32_t i = 0; i < N; ++i)
      {
        buf.ReadU8 ();
      }
  }
  virtual void Print (std::ostream &os) const {
    os << "N=" << N;
  }
  BenchTag ()
    : Tag () {}
};

static void
benchD (uint32_t n)
{
  BenchHeader<25> ipv4;
  BenchHeader<8> udp;
  BenchTag<16> tag1;
  BenchTag<17> tag2;

  for (uint32_t i = 0; i < n; i++) {
    Ptr<Packet> p = Create<Packet> (2000);
    p->AddPacketTag (tag1);
    p->AddHeader (udp);
    p->RemovePacketTag (tag1);
    p->AddPacketTag (tag2);
    p->AddHeader (ipv4);
    Ptr<Packet> o = p->Copy ();
    o->RemoveHeader (ipv4);
    p->RemovePacketTag (tag2);
    o->RemoveHeader (udp);
  }
}

static void
benchA (uint32_t n)
{
  BenchHeader<25> ipv4;
  BenchHeader<8> udp;

  for (uint32_t i = 0; i < n; i++) {
    Ptr<Packet> p = Create<Packet> (2000);
    p->AddHeader (udp);
    p->AddHeader (ipv4);
    Ptr<Packet> o = p->Copy ();
    o->RemoveHeader (ipv4);
    o->RemoveHeader (udp);
  }
}

static void
benchB (uint32_t n)
{
  BenchHeader<25> ipv4;
  BenchHeader<8> udp;

  for (uint32_t i = 0; i < n; i++) {
    Ptr<Packet> p = Create<Packet> (2000);
    p->AddHeader (udp);
    p->AddHeader (ipv4);
  }
}

static void
C2 (Ptr<Packet> p)
{
  BenchHeader<8> udp;

  p->RemoveHeader (udp);
}

static void
C1 (Ptr<Packet> p)
{
  BenchHeader<25> ipv4;
  p->RemoveHeader (ipv4);
  C2 (p);
}

static void
benchC (uint32_t n)
{
  BenchHeader<25> ipv4;
  BenchHeader<8> udp;

  for (uint32_t i = 0; i < n; i++) {
    Ptr<Packet> p = Create<Packet> (2000);
    p->AddHeader (udp);
    p->AddHeader (ipv4);
    C1 (p);
  }
}

static void
runBench (void (*bench) (uint32_t), uint32_t n, char const *name)
{
  SystemWallClockMs time;
  time.Start ();
  (*bench) (n);
  uint64_t deltaMs = time.End ();
  double ps = n;
  ps *= 1000;
  ps /= deltaMs;
  std::cout << name<<"=" << ps << " packets/s" << std::endl;
}

int main (int argc, char *argv[])
{
  uint32_t n = 0;
  while (argc > 0) {
      if (strncmp ("--n=", argv[0],strlen ("--n=")) == 0)
        {
          char const *nAscii = argv[0] + strlen ("--n=");
          std::istringstream iss;
          iss.str (nAscii);
          iss >> n;
        }
      if (strncmp ("--enable-printing", argv[0], strlen ("--enable-printing")) == 0)
        {
          Packet::EnablePrinting ();
        }
      argc--;
      argv++;
  }
  if (n == 0)
    {
      std::cerr << "Error-- number of packets must be specified " <<
        "by command-line argument --n=(number of packets)" << std::endl;
      exit (1);
    }
  std::cout << "Running bench-packets with n=" << n << std::endl;

  runBench (&benchA, n, "a");
  runBench (&benchB, n, "b");
  runBench (&benchC, n, "c");
  runBench (&benchD, n, "d");

  return 0;
}


text:
const definitions = require('./definitions');
const ahjDocuments = require('./ahjDocuments');

const authorityInfo = {
    serviceId: "1111111",
    latitude: 27.7806527,
    longitude: -82.6913532,
    City: "Kenny City",
    place: "incorporatedPlace"
};

module.exports = {
    authorityInfo,
    documents: [
        ...ahjDocuments,
        ...definitions
    ],
    apiVersion: 'v2'
}


text:
<?php
// Generated by ZF2's ./bin/classmap_generator.php
return array(
    'Livraria\Module'                        => __DIR__ . '/Module.php',
    'Livraria\Controller\IndexController' => __DIR__ . '/src/Livraria/Controller/IndexController.php',
    'LivrariaTest\Framework\TestCase'        => __DIR__ . '/tests/Livraria/Framework/TestCase.php',
    'LivrariaTest\SampleTest'                => __DIR__ . '/tests/Livraria/SampleTest.php',
);


text:
/*
    This file is part of ZWaveLib Project source code.

    ZWaveLib is free software: you can redistribute it and/or modify
    it under the terms of the GNU General Public License as published by
    the Free Software Foundation, either version 3 of the License, or
    (at your option) any later version.

    ZWaveLib is distributed in the hope that it will be useful,
    but WITHOUT ANY WARRANTY; without even the implied warranty of
    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
    GNU General Public License for more details.

    You should have received a copy of the GNU General Public License
    along with ZWaveLib.  If not, see <http://www.gnu.org/licenses/>.
*/

/*
 *     Author: https://github.com/snagytx
 *     Project Homepage: https://github.com/genielabs/zwave-lib-dotnet
 */

using ZWaveLib2.Enums;

namespace ZWaveLib2.CommandClasses
{
    public class DoorLock : ICommandClass
    {
        public enum Value
        {
            Unsecured = 0x00,
            UnsecuredTimeout = 0x01,
            InsideUnsecured = 0x10,
            InsideUnsecuredTimeout = 0x11,
            OutsideUnsecured = 0x20,
            OutsideUnsecuredTimeout = 0x21,
            Secured = 0xFF}

        ;

        public enum Alarm
        {
            Locked = 0x01,
            Unlocked = 0x02,
            LockedFromOutside = 0x05,
            UnlockedByUser = 0x06,
            // with id message[16] <--- TODO: find a way to route this info
            UnatuthorizedUnlock = 0x0F}

        ;

        public CommandClass GetClassId()
        {
            return CommandClass.DoorLock;
        }

        public NodeEvent GetEvent(ZWaveNode node, byte[] message)
        {
            NodeEvent nodeEvent = null;
            byte cmdType = message[1];
            if (cmdType == (byte)Command.DoorLockReport)
            {
                nodeEvent = new NodeEvent(node, EventParameter.DoorLockStatus, message[2], 0);
            }
            return nodeEvent;
        }

        public static ZWaveMessage Get(ZWaveNode node)
        {
            return node.SendDataRequest(new byte[] {
                (byte)CommandClass.DoorLock,
                (byte)Command.DoorLockGet
            });
        }

        public static ZWaveMessage Set(ZWaveNode node, Value value)
        {
            byte lockValue;
            if (value == DoorLock.Value.Secured)
                lockValue = 255;
            else
                lockValue = 0;

            return node.SendDataRequest(new byte[] {
                (byte)CommandClass.DoorLock,
                (byte)Command.DoorLockSet,
                (byte)lockValue
            });
        }
    }
}


text:
typedef struct regmatch_t {
    int rm_so;
    int rm_eo;
} regmatch_t;
typedef const char regex_t;
#endif
#ifndef NO_LUA
#include "lua-str.h"
#endif
#include <string>

namespace std {
    string to_string(const string& s);
}

namespace textutil {

typedef const std::string& S;
template <class T> inline T from_string(S s) { return s; }
template<> inline int from_string(S s) { return std::stoi(s); }
template<> inline long from_string(S s) { return std::stoi(s); }
template<> inline unsigned long from_string(S s) { return std::stoul(s); }
template<> inline double from_string(S s) { return std::stod(s); }

class Rx {
protected:
    regex_t *rx;

public:

    enum {
        icase = 1, lua = 2, newline = 4
    };

    struct match_state {
        Rx* pr;
        regmatch_t *r_matches;
        size_t ref_count;
        bool own_rx;

        match_state(Rx* pr, bool own_rx);
        ~match_state();

        bool range(int idx, int &i1, int &i2);
        bool matches(const char *s, size_t len);
    };

    struct match {
        match_state *state;
        const char *s;
        size_t len;

        match(Rx& r, const char *s, bool own_rx=false);
        match(Rx& r, const std::string& s, bool own_rx=false);
        match(const Rx::match& other);
        match& operator= (const match& other);
         ~match();

        bool matches() { return state->matches(s,len); }
        bool subst(std::string& res);
        void next();
        std::string group(int idx = -1) const;
        bool range(int idx, int &i1,int &i2) const { return state->range(idx,i1,i2); }
        std::string operator[] (int idx) const {  return group(idx);  }

        template <class C>
        void append_to(C& c) {
            typedef typename C::value_type value_type;
            while(matches()) {
                c.push_back(from_string<value_type>(group()));
                next();
            }
        }

        template <class M>
        void fill_map(M& m) {
            while(matches()) {
                m[group(1)] = from_string<typename M::mapped_type>(group(2));
                next();
             }
        }

        struct iterator {
            match *pm;

            iterator(match *pm) : pm(pm) {
                if (pm != NULL) {
                    if (! pm->matches())
                        pm = NULL;
                }
            }

            bool operator != (const iterator& other) {
                return pm != other.pm;
            }

            bool operator == (const iterator& other) {
                return pm == other.pm;
            }

            const match& operator* () const { return *pm; }

            iterator& operator ++() {
                pm->next();
                if (! pm->matches()) {
                    pm = NULL;
                }
                return *this;
            }
        };

        iterator begin() { return iterator(this);}
        iterator end() { return iterator(NULL); }
    };

    Rx() : rx(nullptr) { }
    Rx (Rx&& other);
    Rx (regex_t *R);
    Rx& operator= (Rx&& other);

    regex_t *regexp() { return rx; }

    // the above ctor may fail to compile the regex.
    // The suggested idiom is 'if (! R) do_something_with(R.error());'
    virtual bool operator! () { return true; }

    virtual ~Rx() {}
    virtual std::string error() { return ""; }
    virtual int n_matches() { return 0; }
    virtual bool matches (const char *ps, regmatch_t *r_matches = NULL, size_t len = 0) { return false; }

    virtual bool matches (const std::string& s, regmatch_t *r_matches = NULL) {
        return matches(s.c_str(),r_matches, s.size());
    }

    // like Lua's std::string.find; also returns the range matched
    bool find (const char *str, int& i1, int& i2, int idx = 0);
    bool find (const std::string& s, int& i1, int& i2, int idx = 0) {
        return find(s.c_str(),i1,i2,idx);
    }

    bool range(int idx, int& i1, int& i2, regmatch_t *r_matches);

    std::string gsub(const char *text, const char *repl);
    std::string gsub(const std::string& text, const std::string& repl) {
        return gsub(text.c_str(),repl.c_str());
    }

    match gmatch(const char *s) &;
    match gmatch(const char *s) &&;
    match gmatch(const std::string& s) &;
    match gmatch(const std::string& s) &&;

    template <class M>
    std::string gsub(const char *text, M& map_object) {
        Rx::match ms (*this,text);
        std::string res;
        while (ms.subst(res)) {
            res.append(std::to_string(map_object[ms.group()]));
            ms.next();
        }
        return res;
    }

    template <class F>
    std::string gsub_fun(const char *text, F fun_object) {
        Rx::match ms (*this,text);
        std::string res;
        while (ms.subst(res)) {
            res.append(std::to_string(fun_object(ms)));
            ms.next();
        }
        return res;
    }

};

#ifndef NO_POSIX
class Rxp: public Rx {
    int rc;
public:
    Rxp (std::string pat, int cflags = 0);
    Rxp (Rxp&& other) {
        rx = other.rx;
        other.rx = NULL;
    }

    virtual bool operator! () { return rc != 0; }
    virtual ~Rxp();
    virtual std::string error();
    virtual int n_matches();
    virtual bool matches (const char *ps, regmatch_t *r_matches = NULL,size_t len=0);
};

inline Rx operator"" _R (const char *pat, size_t) {  return Rxp(pat); }

#endif

#ifndef NO_LUA
class Rxl: public Rx {
    const char *err;
    std::string pat;
    int n_match;

public:
    Rxl (std::string pat);
    Rxl (Rxl&& other) {
        rx = other.rx;
        other.rx = NULL;
    }

    virtual bool operator! () { return err != nullptr; }
    virtual ~Rxl();
    virtual std::string error();
    virtual int n_matches();
    virtual bool matches (const char *ps, regmatch_t *r_matches = NULL,size_t len=0);
};

inline Rx operator"" _L (const char *pat, size_t) {  return Rxl(pat); }

#endif

}
#endif


text:
namespace EMU7800.Core
{
    /// <summary>
    ///  Atari standard 2KB carts (no bankswitching)
    /// </summary>
    public sealed class CartA2K : Cart
    {
        //
        //  Cart Format                Mapping to ROM Address Space
        //  0x0000:0x0800              0x1000:0x0800
        //                             0x1800:0x0800  (1st 2k bank repeated)
        //

        #region IDevice Members

        public override byte this[ushort addr]
        {
            get { return ROM[addr & 0x07ff]; }
            set { }
        }

        #endregion

        private CartA2K()
        {
        }

        public CartA2K(byte[] romBytes)
        {
            LoadRom(romBytes, 0x0800);
        }

        public CartA2K(byte[] romBytes, int multicartBankSelector)
        {
            LoadRom(romBytes, 0x800, multicartBankSelector & 0x1f);
        }

        #region Serialization Members

        public CartA2K(DeserializationContext input, MachineBase m) : base(input)
        {
            input.CheckVersion(1);
            LoadRom(input.ReadExpectedBytes(0x0800), 0x0800);
        }

        public override void GetObjectData(SerializationContext output)
        {
            base.GetObjectData(output);

            output.WriteVersion(1);
            output.Write(ROM);
        }

        #endregion
    }
}


text:
using System.Collections.Generic;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Mvc;
using Relisten.Api;
using Relisten.Api.Models;
using Relisten.Api.Models.Api;
using Relisten.Data;

namespace Relisten.Controllers
{
    [Route("api/v2/artists")]
    [Produces("application/json")]
    public class SongsController : RelistenBaseController
    {
        public SongsController(
            RedisService redis,
            DbService db,
            ArtistService artistService,
            SetlistSongService setlistSongService,
            SetlistShowService setlistShowService
        ) : base(redis, db, artistService)
        {
            _setlistSongService = setlistSongService;
            _setlistShowService = setlistShowService;
        }

        private SetlistSongService _setlistSongService { get; }
        private SetlistShowService _setlistShowService { get; }

        [HttpGet("{artistIdOrSlug}/songs")]
        [ProducesResponseType(typeof(IEnumerable<SetlistSongWithPlayCount>), 200)]
        [ProducesResponseType(typeof(ResponseEnvelope<bool>), 404)]
        public async Task<IActionResult> Songs(string artistIdOrSlug)
        {
            return await ApiRequest(artistIdOrSlug, art =>
            {
                return _setlistSongService.AllForArtistWithPlayCount(art);
            });
        }

        [HttpGet("{artistIdOrSlug}/songs/{idAndSlug}")]
        [ProducesResponseType(typeof(SetlistSongWithShows), 200)]
        [ProducesResponseType(typeof(ResponseEnvelope<bool>), 404)]
        public async Task<IActionResult> years(string artistIdOrSlug, string idAndSlug)
        {
            return await ApiRequestWithIdentifier(artistIdOrSlug, idAndSlug, (artist, id) =>
            {
                return _setlistSongService.ForIdWithShows(artist, id.Id.Value);
            });
        }
    }
}


text:
namespace Charlotte.Chocomint.Dialogs
{
	partial class BusyDlg
	{
		/// <summary>
		/// 必要なデザイナー変数です。
		/// </summary>
		private System.ComponentModel.IContainer components = null;

		/// <summary>
		/// 使用中のリソースをすべてクリーンアップします。
		/// </summary>
		/// <param name="disposing">マネージ リソースが破棄される場合 true、破棄されない場合は false です。</param>
		protected override void Dispose(bool disposing)
		{
			if (disposing && (components != null))
			{
				components.Dispose();
			}
			base.Dispose(disposing);
		}

		#region Windows フォーム デザイナーで生成されたコード

		/// <summary>
		/// デザイナー サポートに必要なメソッドです。このメソッドの内容を
		/// コード エディターで変更しないでください。
		/// </summary>
		private void InitializeComponent()
		{
			this.components = new System.ComponentModel.Container();
			System.ComponentModel.ComponentResourceManager resources = new System.ComponentModel.ComponentResourceManager(typeof(BusyDlg));
			this.ProgressBar = new System.Windows.Forms.ProgressBar();
			this.Message = new System.Windows.Forms.Label();
			this.MainTimer = new System.Windows.Forms.Timer(this.components);
			this.SuspendLayout();
			//
			// ProgressBar
			//
			this.ProgressBar.Anchor = ((System.Windows.Forms.AnchorStyles)(((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Left)
            | System.Windows.Forms.AnchorStyles.Right)));
			this.ProgressBar.Location = new System.Drawing.Point(12, 95);
			this.ProgressBar.Maximum = 1000;
			this.ProgressBar.Name = "ProgressBar";
			this.ProgressBar.Size = new System.Drawing.Size(560, 30);
			this.ProgressBar.TabIndex = 0;
			//
			// Message
			//
			this.Message.AutoSize = true;
			this.Message.Location = new System.Drawing.Point(40, 40);
			this.Message.Name = "Message";
			this.Message.Size = new System.Drawing.Size(113, 20);
			this.Message.TabIndex = 1;
			this.Message.Text = "処理しています。";
			//
			// MainTimer
			//
			this.MainTimer.Enabled = true;
			this.MainTimer.Tick += new System.EventHandler(this.MainTimer_Tick);
			//
			// BusyDlg
			//
			this.AutoScaleDimensions = new System.Drawing.SizeF(8F, 20F);
			this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font;
			this.ClientSize = new System.Drawing.Size(584, 161);
			this.Controls.Add(this.Message);
			this.Controls.Add(this.ProgressBar);
			this.Font = new System.Drawing.Font("メイリオ", 9.75F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((byte)(128)));
			this.Icon = ((System.Drawing.Icon)(resources.GetObject("$this.Icon")));
			this.Margin = new System.Windows.Forms.Padding(4, 5, 4, 5);
			this.MaximizeBox = false;
			this.MinimizeBox = false;
			this.Name = "BusyDlg";
			this.SizeGripStyle = System.Windows.Forms.SizeGripStyle.Show;
			this.StartPosition = System.Windows.Forms.FormStartPosition.CenterScreen;
			this.Text = "処理中";
			this.FormClosing += new System.Windows.Forms.FormClosingEventHandler(this.BusyDlg_FormClosing);
			this.FormClosed += new System.Windows.Forms.FormClosedEventHandler(this.BusyDlg_FormClosed);
			this.Load += new System.EventHandler(this.BusyDlg_Load);
			this.Shown += new System.EventHandler(this.BusyDlg_Shown);
			this.ResumeLayout(false);
			this.PerformLayout();

		}

		#endregion

		private System.Windows.Forms.ProgressBar ProgressBar;
		private System.Windows.Forms.Timer MainTimer;
		public System.Windows.Forms.Label Message;
	}
}


text:
package org.spongepowered.common.mixin.core.world;

import com.google.common.collect.ImmutableList;
import com.google.common.collect.Maps;
import net.minecraft.block.Block;
import net.minecraft.block.BlockEventData;
import net.minecraft.block.state.IBlockState;
import net.minecraft.entity.player.EntityPlayer;
import net.minecraft.util.BlockPos;
import net.minecraft.world.IBlockAccess;
import net.minecraft.world.NextTickListEntry;
import net.minecraft.world.World;
import net.minecraft.world.WorldServer;
import net.minecraft.world.WorldSettings;
import org.spongepowered.api.block.ScheduledBlockUpdate;
import org.spongepowered.api.entity.living.player.Player;
import org.spongepowered.api.entity.living.player.User;
import org.spongepowered.api.event.cause.Cause;
import org.spongepowered.api.event.cause.NamedCause;
import org.spongepowered.api.util.annotation.NonnullByDefault;
import org.spongepowered.api.world.GeneratorType;
import org.spongepowered.api.world.GeneratorTypes;
import org.spongepowered.asm.mixin.Implements;
import org.spongepowered.asm.mixin.Interface;
import org.spongepowered.asm.mixin.Mixin;
import org.spongepowered.asm.mixin.Shadow;
import org.spongepowered.asm.mixin.injection.At;
import org.spongepowered.asm.mixin.injection.Inject;
import org.spongepowered.asm.mixin.injection.Redirect;
import org.spongepowered.asm.mixin.injection.callback.CallbackInfo;
import org.spongepowered.asm.mixin.injection.callback.CallbackInfoReturnable;
import org.spongepowered.common.entity.PlayerTracker;
import org.spongepowered.common.interfaces.IMixinBlockUpdate;
import org.spongepowered.common.interfaces.IMixinChunk;
import org.spongepowered.common.util.SpongeHooks;
import org.spongepowered.common.util.StaticMixinHelper;
import org.spongepowered.common.util.VecHelper;

import java.util.Collection;
import java.util.Map;
import java.util.Optional;
import java.util.Random;
import java.util.Set;
import java.util.TreeSet;

@NonnullByDefault
@Mixin(WorldServer.class)
public abstract class MixinWorldServer extends MixinWorld {

    private Map<BlockPos, User> trackedBlockEvents = Maps.newHashMap();

    @Shadow public abstract void updateBlockTick(BlockPos p_175654_1_, Block p_175654_2_, int p_175654_3_, int p_175654_4_);
    @Shadow public abstract boolean fireBlockEvent(BlockEventData event);
    @Shadow private Set<NextTickListEntry> pendingTickListEntriesHashSet;
    @Shadow private TreeSet<NextTickListEntry> pendingTickListEntriesTreeSet;

    @Inject(method = "createSpawnPosition(Lnet/minecraft/world/WorldSettings;)V", at = @At("HEAD"), cancellable = true)
    public void onCreateSpawnPosition(WorldSettings settings, CallbackInfo ci) {
        GeneratorType generatorType = (GeneratorType) settings.getTerrainType();
        if (generatorType != null && generatorType.equals(GeneratorTypes.THE_END)) {
            this.worldInfo.setSpawn(new BlockPos(55, 60, 0));
            ci.cancel();
        }
    }

    @Inject(method = "init", at = @At("HEAD"))
    public void beforeInit(CallbackInfoReturnable<World> cir) {
        updateWorldGenerator();
    }

    @Redirect(method = "updateBlocks", at = @At(value = "INVOKE", target = "Lnet/minecraft/block/Block;randomTick(Lnet/minecraft/world/World;Lnet/minecraft/util/BlockPos;Lnet/minecraft/block/state/IBlockState;Ljava/util/Random;)V"))
    public void onUpdateBlocks(Block block, net.minecraft.world.World worldIn, BlockPos pos, IBlockState state, Random rand) {
        if (this.isRemote || this.currentTickBlock != null) {
            block.randomTick(worldIn, pos, state, rand);
            return;
        }

        this.processingCaptureCause = true;
        this.currentTickBlock = createSpongeBlockSnapshot(state, state.getBlock().getActualState(state, (IBlockAccess) this, pos), pos, 0);
        block.randomTick(worldIn, pos, state, rand);
        handlePostTickCaptures(Cause.of(NamedCause.source(this.currentTickBlock)));
        this.currentTickBlock = null;
        this.processingCaptureCause = false;
    }

    @Redirect(method = "updateBlockTick", at = @At(value = "INVOKE", target="Lnet/minecraft/block/Block;updateTick(Lnet/minecraft/world/World;Lnet/minecraft/util/BlockPos;Lnet/minecraft/block/state/IBlockState;Ljava/util/Random;)V"))
    public void onUpdateBlockTick(Block block, net.minecraft.world.World worldIn, BlockPos pos, IBlockState state, Random rand) {
        if (this.isRemote || this.currentTickBlock != null) {
            block.updateTick(worldIn, pos, state, rand);
            return;
        }

        this.processingCaptureCause = true;
        this.currentTickBlock = createSpongeBlockSnapshot(state, state.getBlock().getActualState(state, (IBlockAccess) this, pos), pos, 0);
        block.updateTick(worldIn, pos, state, rand);
        handlePostTickCaptures(Cause.of(NamedCause.source(this.currentTickBlock)));
        this.currentTickBlock = null;
        this.processingCaptureCause = false;
    }

    @Redirect(method = "tickUpdates", at = @At(value = "INVOKE", target = "Lnet/minecraft/block/Block;updateTick(Lnet/minecraft/world/World;Lnet/minecraft/util/BlockPos;"
            + "Lnet/minecraft/block/state/IBlockState;Ljava/util/Random;)V"))
    public void onUpdateTick(Block block, net.minecraft.world.World worldIn, BlockPos pos, IBlockState state, Random rand) {
        if (this.isRemote || this.currentTickBlock != null) {
            block.updateTick(worldIn, pos, state, rand);
            return;
        }

        this.processingCaptureCause = true;
        this.currentTickBlock = createSpongeBlockSnapshot(state, state.getBlock().getActualState(state, (IBlockAccess) this, pos), pos, 0);
        block.updateTick(worldIn, pos, state, rand);
        handlePostTickCaptures(Cause.of(NamedCause.source(this.currentTickBlock)));
        this.currentTickBlock = null;
        this.processingCaptureCause = false;
    }

    @Inject(method = "addBlockEvent", at = @At(value = "HEAD"))
    public void onAddBlockEvent(BlockPos pos, Block blockIn, int eventID, int eventParam, CallbackInfo ci) {
        if (StaticMixinHelper.packetPlayer != null) {
            // Add player to block event position
            if (isBlockLoaded(pos)) {
                IMixinChunk spongeChunk = (IMixinChunk) getChunkFromBlockCoords(pos);
                Optional<User> owner = spongeChunk.getBlockOwner(pos);
                Optional<User> notifier = spongeChunk.getBlockNotifier(pos);
                if (notifier.isPresent()) {
                    spongeChunk.addTrackedBlockPosition(blockIn, pos, notifier.get(), PlayerTracker.Type.NOTIFIER);
                    this.trackedBlockEvents.put(pos, notifier.get());
                } else if (owner.isPresent()) {
                    spongeChunk.addTrackedBlockPosition(blockIn, pos, owner.get(), PlayerTracker.Type.NOTIFIER);
                    this.trackedBlockEvents.put(pos, owner.get());
                }
            }
        } else {
            BlockPos sourcePos = null;
            if (this.currentTickBlock != null) {
                sourcePos = VecHelper.toBlockPos(this.currentTickBlock.getPosition());
            } else if (this.currentTickOnBlockAdded != null) {
                sourcePos = VecHelper.toBlockPos(this.currentTickOnBlockAdded.getPosition());
            } else if (this.currentTickTileEntity != null) {
                sourcePos = ((net.minecraft.tileentity.TileEntity) this.currentTickTileEntity).getPos();
            }
            if (sourcePos != null && isBlockLoaded(sourcePos)) {
                IMixinChunk spongeChunk = (IMixinChunk) getChunkFromBlockCoords(sourcePos);
                Optional<User> owner = spongeChunk.getBlockOwner(sourcePos);
                Optional<User> notifier = spongeChunk.getBlockNotifier(sourcePos);
                if (notifier.isPresent()) {
                    spongeChunk.addTrackedBlockPosition(blockIn, pos, notifier.get(), PlayerTracker.Type.NOTIFIER);
                    this.trackedBlockEvents.put(pos, notifier.get());
                } else if (owner.isPresent()) {
                    spongeChunk.addTrackedBlockPosition(blockIn, pos, owner.get(), PlayerTracker.Type.NOTIFIER);
                    this.trackedBlockEvents.put(pos, owner.get());
                }
            }
        }
    }

    // special handling for Pistons since they use their own event system
    @Redirect(method = "sendQueuedBlockEvents", at = @At(value = "INVOKE", target = "Lnet/minecraft/world/WorldServer;fireBlockEvent(Lnet/minecraft/block/BlockEventData;)Z"))
    public boolean onFireBlockEvent(net.minecraft.world.WorldServer worldIn, BlockEventData event) {
        IBlockState currentState = worldIn.getBlockState(event.getPosition());
        this.processingCaptureCause = true;
        this.currentTickBlock = createSpongeBlockSnapshot(currentState, currentState.getBlock().getActualState(currentState, (IBlockAccess) this, event.getPosition()), event.getPosition(), 3);
        Cause cause = Cause.of(NamedCause.source(this.currentTickBlock));
        if (this.trackedBlockEvents.get(event.getPosition()) != null) {
            User user = this.trackedBlockEvents.get(event.getPosition());
            cause = cause.with(NamedCause.notifier(user));
            StaticMixinHelper.blockEventUser = user;
        }
        boolean result = fireBlockEvent(event);
        this.handlePostTickCaptures(cause);
        StaticMixinHelper.blockEventUser = null;
        this.currentTickBlock = null;
        this.processingCaptureCause = false;
        this.trackedBlockEvents.remove(event.getPosition());
        return result;
    }

    @Override
    public Collection<ScheduledBlockUpdate> getScheduledUpdates(int x, int y, int z) {
        BlockPos position = new BlockPos(x, y, z);
        ImmutableList.Builder<ScheduledBlockUpdate> builder = ImmutableList.builder();
        for (NextTickListEntry sbu : this.pendingTickListEntriesTreeSet) {
            if (sbu.position.equals(position)) {
                builder.add((ScheduledBlockUpdate) sbu);
            }
        }
        return builder.build();
    }

    private NextTickListEntry tmpScheduledObj;

    @Redirect(method = "updateBlockTick(Lnet/minecraft/util/BlockPos;Lnet/minecraft/block/Block;II)V",
            at = @At(value = "INVOKE", target = "Lnet/minecraft/world/NextTickListEntry;setPriority(I)V"))
    private void onUpdateScheduledBlock(NextTickListEntry sbu, int priority) {
        this.onCreateScheduledBlockUpdate(sbu, priority);
    }

    @Redirect(method = "scheduleBlockUpdate(Lnet/minecraft/util/BlockPos;Lnet/minecraft/block/Block;II)V",
            at = @At(value = "INVOKE", target = "Lnet/minecraft/world/NextTickListEntry;setPriority(I)V"))
    private void onCreateScheduledBlockUpdate(NextTickListEntry sbu, int priority) {
        sbu.setPriority(priority);
        ((IMixinBlockUpdate) sbu).setWorld((WorldServer) (Object) this);
        // Pistons, Beacons, Notes, Comparators etc. schedule block updates so we must track these positions
        if (this.currentTickBlock != null) {
            BlockPos pos = VecHelper.toBlockPos(this.currentTickBlock.getPosition());
            SpongeHooks.tryToTrackBlock((net.minecraft.world.World)(Object) this, this.currentTickBlock, pos, sbu.getBlock(), sbu.position, PlayerTracker.Type.NOTIFIER);
        }

        this.tmpScheduledObj = sbu;
    }

    @Override
    public ScheduledBlockUpdate addScheduledUpdate(int x, int y, int z, int priority, int ticks) {
        BlockPos pos = new BlockPos(x, y, z);
        ((WorldServer) (Object) this).scheduleBlockUpdate(pos, getBlockState(pos).getBlock(), ticks, priority);
        ScheduledBlockUpdate sbu = (ScheduledBlockUpdate) this.tmpScheduledObj;
        this.tmpScheduledObj = null;
        return sbu;
    }

    @Override
    public void removeScheduledUpdate(int x, int y, int z, ScheduledBlockUpdate update) {
        // Note: Ignores position argument
        this.pendingTickListEntriesHashSet.remove(update);
        this.pendingTickListEntriesTreeSet.remove(update);
    }

    @Redirect(method = "updateAllPlayersSleepingFlag()V", at = @At(value = "INVOKE",
            target = "Lnet/minecraft/entity/player/EntityPlayer;isSpectator()Z"))
    public boolean isSpectatorOrIgnored(EntityPlayer entityPlayer) {
        // spectators are excluded from the sleep tally in vanilla
        // this redirect expands that check to include sleep-ignored players as well
        boolean ignore = entityPlayer instanceof Player && ((Player)entityPlayer).isSleepingIgnored();
        return ignore || entityPlayer.isSpectator();
    }

    @Redirect(method = "areAllPlayersAsleep()Z", at = @At(value = "INVOKE",
            target = "Lnet/minecraft/entity/player/EntityPlayer;isPlayerFullyAsleep()Z"))
    public boolean isPlayerFullyAsleep(EntityPlayer entityPlayer) {
        // if isPlayerFullyAsleep() returns false areAllPlayerAsleep() breaks its loop and returns false
        // this redirect forces it to return true if the player is sleep-ignored even if they're not sleeping
        boolean ignore = entityPlayer instanceof Player && ((Player)entityPlayer).isSleepingIgnored();
        return ignore || entityPlayer.isPlayerFullyAsleep();
    }

    @Redirect(method = "areAllPlayersAsleep()Z", at = @At(value = "INVOKE",
            target = "Lnet/minecraft/entity/player/EntityPlayer;isSpectator()Z"))
    public boolean isSpectatorAndNotIgnored(EntityPlayer entityPlayer) {
        // if a player is marked as a spectator areAllPlayersAsleep() breaks its loop and returns false
        // this redirect forces it to return false if a player is sleep-ignored even if they're a spectator
        boolean ignore = entityPlayer instanceof Player && ((Player)entityPlayer).isSleepingIgnored();
        return !ignore && entityPlayer.isSpectator();
    }
}


text:
T1A05-if-else-Michael

Enter a number:
<input id="myText01"  type=number  value=7> try 3, 8, 200

....

<input type=button value="First" onClick="{
  myNumber = document.getElementById('myText01').value
  document.getElementById('myDiv01').innerHTML = ''

  if (myNumber == 7)  {document.getElementById('myDiv01').innerHTML += 'You entered a number
'}

  if (myNumber < 9)  {document.getElementById('myDiv01').innerHTML += 'Less than 9
'}

  if (myNumber > 0)  {document.getElementById('myDiv01').innerHTML += 'This is a natural number
'}

  if (myNumber < 0)  {document.getElementById('myDiv01').innerHTML += 'This is not a natural number
'}

  if (myNumber == 0)  {document.getElementById('myDiv01').innerHTML += 'This is neither negative nor positive
'}

  if ( (myNumber < 3) || (myNumber > 20) ) {document.getElementById('myDiv01').innerHTML += 'Less than 3 or greater than 20
'}

}" >


text:
require 'set'

#
# Gems
#

require 'active_record'
require 'active_support/dependencies/autoload'

#
# Project
#

require "metasploit/erd/version"

# Shared namespace for metasploit gems; used in {https://github.com/rapid7/metasploit-concern metasploit-concern},
# {https://github.com/rapid7/metasploit-erd metasploit-erd},
# {https://github.com/rapid7/metasploit-framework metasploit-framework}, and
# {https://github.com/rapid7/metasploit-model metasploit-model}
module Metasploit
  # The namespace for this gem.
  module ERD
    extend ActiveSupport::Autoload

    autoload :Cluster
    autoload :Clusterable
    autoload :Diagram
    autoload :Entity
    autoload :Relationship
  end
end


text:
/**
 * Helper class used to generate a canvas to manipulate images
 */
export class CanvasGenerator {
    /**
     * Create a new canvas (or offscreen canvas depending on the context)
     * @param width defines the expected width
     * @param height defines the expected height
     * @return a new canvas or offscreen canvas
     */
    public static CreateCanvas(width: number, height: number): HTMLCanvasElement | OffscreenCanvas {
        if (typeof document === "undefined") {
            return new OffscreenCanvas(width, height);
        }

        let canvas = document.createElement("canvas");
        canvas.width = width;
        canvas.height = height;

        return canvas;
    }
}


text:
require 'spec_helper'

describe OfflineSort::Sorter do

  shared_examples "a correct offline sort" do
    let(:count) { 10000 }
    let(:entries_per_chunk) { 900 }
    let(:enumerable) {}
    let(:sort) {}

    before do
      @unsorted = enumerable.dup
      r = Benchmark.measure do
        result = OfflineSort.sort(enumerable, chunk_size: entries_per_chunk, &sort)

        @sorted = result.map do |entry|
          entry
        end
      end
      puts r
    end

    it "produces the same sorted result as an in-memory sort" do
      expect(@unsorted).to match_array(enumerable)
      expect do
        last = nil
        entry_count = 0
        @sorted.each do |entry|
          if last.nil?
            last = entry
            entry_count += 1
            next
          end

          raise "Out of order at line #{entry_count}" unless (sort.call(last) <=> sort.call(entry)) == -1

          last = entry
          entry_count += 1
        end
      end.not_to raise_error
      expect(@sorted).to match_array(enumerable.sort_by(&sort))
    end
  end

  let(:arrays) do
    Array.new(count) do |index|
      [SecureRandom.hex, index, SecureRandom.hex]
    end
  end

  let(:array_sort_index) { 2 }
  let(:array_sort) { Proc.new { |arr| arr[array_sort_index] } }

  let(:hashes) do
    Array.new(count) do |index|
      { 'a' => SecureRandom.hex, 'b' => index, 'c' => SecureRandom.hex }
    end
  end

  let(:hash_sort_key) { 'c' }
  let(:hash_sort) { Proc.new { |hash| hash[hash_sort_key] } }

  context "with arrays" do
    it_behaves_like "a correct offline sort" do
      let(:enumerable) { arrays }
      let(:sort) { array_sort }
    end

    context "with multiple sort keys" do
      it_behaves_like "a correct offline sort" do
        let(:enumerable) do
          Array.new(count) do |index|
            [index.round(-1), index, SecureRandom.hex]
          end.shuffle
        end
        let(:sort) { Proc.new { |arr| [arr[0], arr[1]] } }
      end
    end
  end

  context "hashes" do
    it_behaves_like "a correct offline sort" do
      let(:enumerable) { hashes }
      let(:sort) { hash_sort }
    end

    context "with multiple sort keys" do
      it_behaves_like "a correct offline sort" do
        let(:enumerable) do
          Array.new(count) do |index|
            { 'a' => index.round(-1), 'b' => index, 'c' => SecureRandom.hex }
          end.shuffle
        end
        let(:sort) { Proc.new { |hash| [hash['a'], hash['c']] } }
      end
    end
  end
end


text:
module Fictive
  class Bundle
    def self.import(path, options={})
      bundle_path = Pathname.new(path)

      if bundle_path.directory?
        files = bundle_path.children.select { |file| file.extname == '.txt' }
      elsif bundle_path.exist?
        files = [bundle_path] if bundle_path.extname == '.txt'
      else
        # File not found
      end

      self.new(files)
    end

    attr_reader :documents

    def initialize(files)
      @documents = files.map { |file| Document.new(file.read) }.freeze
    end

    def passages
      # Bad code fix it
      fragments = []

      @documents.each do |document|
        fragments.concat(document.passages)
      end

      fragments
    end
  end
end


text:
namespace rocksdb {

FilterPolicy::~FilterPolicy() { }

}  // namespace rocksdb


text:
<?xml version="1.0" encoding="UTF-8"?>
<testPlan xmlns="urn:io.apiman.test:2014:02:testPlan">

  <testGroup name="Create Entities">
    <test name="Create Gateway">test-plan-data/export/creates-1/000_create-gateway.resttest</test>
    <test name="Create Organization">test-plan-data/export/creates-1/001_create_org.resttest</test>
    <test name="Create Plan">test-plan-data/export/creates-1/002_create-plan1.resttest</test>
    <test name="Create Plan Version">test-plan-data/export/creates-1/003_create-plan1-version-1.0.resttest</test>
    <test name="Lock Plan">test-plan-data/export/creates-1/003.5_lock-plan-1.resttest</test>
    <test name="Create Client">test-plan-data/export/creates-1/004_create-client1.resttest</test>
    <test name="Create Client Version">test-plan-data/export/creates-1/005_create-client1-version-1.0.resttest</test>
    <test name="Create API">test-plan-data/export/creates-1/006_create-api1.resttest</test>
    <test name="Create API Version">test-plan-data/export/creates-1/007_create-api1-version-1.0.resttest</test>
    <test name="Update API Version">test-plan-data/export/creates-1/008_update-api1-version-1.0.resttest</test>
    <test name="Publish API">test-plan-data/export/creates-1/009_publish-api-1.resttest</test>
    <test name="Create Contract">test-plan-data/export/creates-1/010_create-contract1.resttest</test>
    <test name="Register Client">test-plan-data/export/creates-1/011_register-client-1.resttest</test>
    <test name="Wait" delay="2000" />
  </testGroup>

  <testGroup name="Exporting">
    <test name="Export ">test-plan-data/export/export/001_export-1.resttest</test>
    <test name="Export (2) Prep">test-plan-data/export/export/002_export-2-prepare.resttest</test>
    <test name="Export (2) Download">test-plan-data/export/export/003_export-2-download.resttest</test>
  </testGroup>

  <testGroup name="Create Entities (2)">
    <test name="Create Organization (2)">test-plan-data/export/creates-2/001_create_org.resttest</test>
    <test name="Create Plan (2)">test-plan-data/export/creates-2/002_create-plan1.resttest</test>
    <test name="Create Plan Version (2)">test-plan-data/export/creates-2/003_create-plan1-version-1.0.resttest</test>
    <test name="Lock Plan (2)">test-plan-data/export/creates-2/003.5_lock-plan-1.resttest</test>
    <test name="Create Client (2)">test-plan-data/export/creates-2/004_create-client1.resttest</test>
    <test name="Create Client Version (2)">test-plan-data/export/creates-2/005_create-client1-version-1.0.resttest</test>
    <test name="Create API (2)">test-plan-data/export/creates-2/006_create-api1.resttest</test>
    <test name="Create API Version (2)">test-plan-data/export/creates-2/007_create-api1-version-1.0.resttest</test>
    <test name="Update API Version (2)">test-plan-data/export/creates-2/008_update-api1-version-1.0.resttest</test>
    <test name="Publish API (2)">test-plan-data/export/creates-2/009_publish-api-1.resttest</test>
    <test name="Create Contract (2)">test-plan-data/export/creates-2/010_create-contract1.resttest</test>
    <test name="Register Client (2)">test-plan-data/export/creates-2/011_register-client-1.resttest</test>
    <test name="Create Plan Version 1.1 (2)">test-plan-data/export/creates-2/012_create-plan1-version-1.1.resttest</test>
    <test name="Create Plan Version 1.2 (2)">test-plan-data/export/creates-2/013_create-plan1-version-1.2.resttest</test>
    <test name="Wait (2)" delay="2000" />
  </testGroup>

  <testGroup name="Exporting Again">
    <test name="Export (3)">test-plan-data/export/export/004_export-3.resttest</test>
  </testGroup>

</testPlan>


text:
package net.authorize.data.cim;

import java.util.ArrayList;

import net.authorize.data.xml.Address;

public class CustomerProfile {

    protected String merchantCustomerId;
    protected String description;
    protected String email;
    protected String customerProfileId;
    protected ArrayList<Address> shipToAddressList = new ArrayList<Address>();

    private CustomerProfile() { }

    /**
     * Create a new CustomerProfile object
     *
     * @return CustomerProfile
     */
    public static CustomerProfile createCustomerProfile() {
    	return new CustomerProfile();
    }

    /**
     * Get the customer profile id.
     *
	 * @return the id
	 */
	public String getCustomerProfileId() {
		return customerProfileId;
	}

	/**
	 * Set the customer profile id.
	 *
	 * @param id the id to set
	 */
	public void setCustomerProfileId(String id) {
		this.customerProfileId = id;
	}

	/**
     * Gets the value of the merchantCustomerId property.
     *
     * @return
     *     possible object is
     *     {@link String }
     *
     */
    public String getMerchantCustomerId() {
        return merchantCustomerId;
    }

    /**
     * Sets the value of the merchantCustomerId property.
     *
     * @param value
     *     allowed object is
     *     {@link String }
     *
     */
    public void setMerchantCustomerId(String value) {
        this.merchantCustomerId = value;
    }

    /**
     * Gets the value of the description property.
     *
     * @return
     *     possible object is
     *     {@link String }
     *
     */
    public String getDescription() {
        return description;
    }

    /**
     * Sets the value of the description property.
     *
     * @param value
     *     allowed object is
     *     {@link String }
     *
     */
    public void setDescription(String value) {
        this.description = value;
    }

    /**
     * Gets the value of the email property.
     *
     * @return
     *     possible object is
     *     {@link String }
     *
     */
    public String getEmail() {
        return email;
    }

    /**
     * Sets the value of the email property.
     *
     * @param value
     *     allowed object is
     *     {@link String }
     *
     */
    public void setEmail(String value) {
        this.email = value;
    }

	/**
	 * @return the shipToAddressList
	 */
	public ArrayList<Address> getShipToAddressList() {
		return shipToAddressList;
	}

	/**
	 * @param shipToAddressList the shipToAddressList to set
	 */
	public void setShipToAddressList(ArrayList<Address> shipToAddressList) {
		this.shipToAddressList = shipToAddressList;
	}

	/**
	 * Add an address to the ship to list.
	 *
	 * @param shipTo
	 */
	public void addShipToAddress(Address shipTo) {
		if(this.shipToAddressList == null) {
			this.shipToAddressList = new ArrayList<Address>();
		}

		this.shipToAddressList.add(shipTo);
	}

	/**
	 * Return the first (perhaps only) address in the list.
	 *
	 * @return Address
	 */
	public Address getShipToAddress() {

		Address retval = null;
		if(this.shipToAddressList != null &&
				this.shipToAddressList.size() > 0) {

			retval = this.shipToAddressList.get(0);
		}

		return retval;
	}
}


text:
"use strict";

const {
  GraphQLObjectType,
  GraphQLSchema,
  GraphQLInt,
  GraphQLString,
  GraphQLList,
  GraphQLNonNull,
  GraphQLBoolean,
  GraphQLInputObjectType,
  GraphQLID,
  GraphQLEnumType,
} = require('graphql');
const _ = require('lodash');
const pluralize = require('pluralize');
const camelcase = require('camelcase');
const Sequelize = require('sequelize');

const {
  fromGlobalId,
  mutationWithClientMutationId
} = require('graphql-relay');

const {
  defaultArgs,
  defaultListArgs,
  attributeFields,
  typeMapper,
  resolver,
  relay: {
    sequelizeNodeInterface,
    sequelizeConnection
  }
} = require('graphql-sequelize');

const jsonType = require('graphql-sequelize/lib/types/jsonType.js');

typeMapper.mapType((type) => {
   //map bools as strings
   if (type instanceof Sequelize.JSON) {
     return jsonType.default;
   }
   //use default for everything else
   return false;
});

function connectionNameForAssociation(Model, associationName) {
  return camelcase(`${Model.name}_${associationName}`);
}
function queryName(Model, type) {
  switch (type) {
    case 'findAll': {
      return camelcase(pluralize.plural(Model.name));
    }
    case 'findById': {
      return camelcase(Model.name);
    }
    default: {
      console.warn('Unknown query type: ',type);
      return camelcase(`${type}_${Model.name}`);
    }
  }
}
function mutationName(Model, type) {
  switch (type) {
    case 'create': {
      return camelcase(`${type}_${Model.name}`);
    }
    case 'update': {
      return camelcase(`${type}_${pluralize.plural(Model.name)}`);
    }
    case 'updateOne': {
      return camelcase(`update_${Model.name}`);
    }
    case 'delete': {
      return camelcase(`${type}_${pluralize.plural(Model.name)}`);
    }
    case 'deleteOne': {
      return camelcase(`delete_${Model.name}`);
    }
    default: {
      console.warn('Unknown mutation type: ',type);
      return camelcase(`${type}_${Model.name}`);
    }
  }
}

function convertFieldsToGlobalId(Model, fields) {
  // Fix Relay Global ID
  _.each(Object.keys(Model.rawAttributes), (k) => {
    if (k === 'clientMutationId') {
      return;
    }
    // Check if reference attribute
    let attr = Model.rawAttributes[k];
    if (attr.references) {
      // console.log(`Replacing ${Model.name}'s field ${k} with globalIdInputField.`);
      let modelName = attr.references.model;
      // let modelType = types[modelName];
      fields[k] = globalIdInputField(modelName);
      if (attr.allowNull == null || attr.allowNull == true) {
        fields[k].type = GraphQLID;
      }
    } else if (attr.primaryKey) {
      fields[k] = globalIdInputField(Model.name);
      // Make primaryKey optional (allowNull=True)
      fields[k].type = GraphQLID;
    }
  });
}

function convertFieldsFromGlobalId(Model, data) {
  // Fix Relay Global ID
  _.each(Object.keys(data), (k) => {
    if (k === 'clientMutationId') {
      return;
    }
    // Check if reference attribute
    let attr = Model.rawAttributes[k];
    if (attr.references || attr.primaryKey) {
      let {id} = fromGlobalId(data[k]);

      // Check if id is numeric.
      if(!_.isNaN(_.toNumber(id))) {
          data[k] = parseInt(id);
      } else {
          data[k] = id;
      }
    }
  });
}

function isSingleAssociation(atype){
  return (atype === 'BelongsTo' || atype === 'HasOne');
}

function addAttributeFieldOptions(Model){
  return Model.attributeFieldOptions || {};
}

function addDefaultListArgs(Model){
  return Model.defaultListArgs || {};
}

function globalIdInputField(modelName) {
  return {
    name: 'id',
    description: `The ID for ${modelName}`,
    type: new GraphQLNonNull(GraphQLID),
  };
}

function _createRecord({
  mutations,
  Model,
  modelType,
  ModelTypes,
  associationsToModel,
  associationsFromModel,
  cache
}) {

  let createMutationName = mutationName(Model, 'create');
  mutations[createMutationName] = mutationWithClientMutationId({
    name: createMutationName,
    description: `Create ${Model.name} record.`,
    inputFields: () => {
      let fields = attributeFields(Model, _.assign({
        commentToDescription: true,
        // exclude: [Model.primaryKeyAttribute],
        cache
      }, addAttributeFieldOptions(Model)));

      convertFieldsToGlobalId(Model, fields);

      // FIXME: Handle timestamps
      // console.log('_timestampAttributes', Model._timestampAttributes);
      delete fields.createdAt;
      delete fields.updatedAt;

      return fields;
    },
    outputFields: () => {
      let output = {};
      // New Record
      output[camelcase(`new_${Model.name}`)] = {
        type: modelType,
        description: `The new ${Model.name}, if successfully created.`,
        resolve: (args,e,context,info) => {
          return resolver(Model, {
          })({}, {
            [Model.primaryKeyAttribute]: args[Model.primaryKeyAttribute]
          }, context, info);
        }
      };

      // New Edges
      _.each(associationsToModel[Model.name], (a) => {
        let {
          from,
          type: atype,
          key: field
        } = a;
        // console.log("Edge To", Model.name, "From", from, field, atype);
        if (!isSingleAssociation(atype)) {
          // HasMany Association
          let {connection} = associationsFromModel[from][`${Model.name}_${field}`];
          let fromType = ModelTypes[from];
          // let nodeType = conn.nodeType;
          // let association = Model.associations[field];
          // let targetType = association
          // console.log("Connection", Model.name, field, nodeType, conn, association);
          output[camelcase(`new_${fromType.name}_${field}_Edge`)] = {
            type: connection.edgeType,
            resolve: (payload) => connection.resolveEdge(payload)
          };
        }
      });
      _.each(associationsFromModel[Model.name], (a) => {
        let {
          to,
          type: atype,
          foreignKey,
          key: field
        } = a;
        // console.log("Edge From", Model.name, "To", to, field, as, atype, foreignKey);
        if (isSingleAssociation(atype)) {
          // BelongsTo association
          let toType = ModelTypes[to];
          output[field] = {
            type: toType,
            resolve: (args,e,context,info) => {
              return resolver(Model[toType.name].target, {
              })({}, { id: args[foreignKey] }, context, info);
            }
          };
        }
      });
      // console.log(`${Model.name} mutation output`, output);
      return output;
    },
    mutateAndGetPayload: (data, context) => {
      convertFieldsFromGlobalId(Model, data);
      return Model.create(data, {requestUser: context.user});
    }
  });

}

function _findRecord({
  queries,
  Model,
  modelType,
  options
}) {
  let findByIdQueryName = queryName(Model, 'findById'); //`find${Model.name}ById`;
  queries[findByIdQueryName] = {
    type: modelType,
    args: defaultArgs(Model, options),
    resolve: resolver(Model, {
      globalId: options.globalId
    })
  };
}

function _findAll({
  queries,
  Model,
  modelType,
  options
}) {
  let findAllQueryName = queryName(Model, 'findAll');
  queries[findAllQueryName] = {
    type: new GraphQLList(modelType),
    args: _.assign(defaultListArgs(Model), addDefaultListArgs(Model)),
    resolve: resolver(Model, {
      globalId: options.globalId
    })
  };
}

function _updateRecords({
  mutations,
  Model,
  modelType,
  ModelTypes,
  associationsToModel,
  associationsFromModel,
  cache
}) {

  let updateMutationName = mutationName(Model, 'update');
  mutations[updateMutationName] = mutationWithClientMutationId({
    name: updateMutationName,
    description: `Update multiple ${Model.name} records.`,
    inputFields: () => {
      let fields = attributeFields(Model, _.assign({
        commentToDescription: true,
        allowNull: true,
        cache
      }, addAttributeFieldOptions(Model)));

      convertFieldsToGlobalId(Model, fields);

      let updateModelTypeName = `Update${Model.name}ValuesInput`;
      let UpdateModelValuesType = cache[updateModelTypeName] || new GraphQLInputObjectType({
        name: updateModelTypeName,
        description: 'Values to update',
        fields
      });
      cache[updateModelTypeName] = UpdateModelValuesType;

      var UpdateModelWhereType = new GraphQLInputObjectType({
        name: `Update${Model.name}WhereInput`,
        description: 'Options to describe the scope of the search.',
        fields
      });

      return {
        values: {
          type: UpdateModelValuesType
        },
        where: {
          type: UpdateModelWhereType,
        }
      };

    },
    outputFields: () => {
      let output = {};
      // New Record
      output[camelcase(`new_${Model.name}`)] = {
        type: modelType,
        description: `The new ${Model.name}, if successfully created.`,
        resolve: (args,e,context,info) => {
          return resolver(Model, {
          })({}, {
            [Model.primaryKeyAttribute]: args[Model.primaryKeyAttribute]
          }, context, info);
        }
      };

      // New Edges
      _.each(associationsToModel[Model.name], (a) => {
        let {
          from,
          type: atype,
          key: field
        } = a;
        // console.log("Edge To", Model.name, "From", from, field, atype);
        if (!isSingleAssociation(atype)) {
          // HasMany Association
          let {connection} = associationsFromModel[from][`${Model.name}_${field}`];
          let fromType = ModelTypes[from];
          // console.log("Connection", Model.name, field, nodeType, conn, association);
          output[camelcase(`new_${fromType.name}_${field}_Edge`)] = {
            type: connection.edgeType,
            resolve: (payload) => connection.resolveEdge(payload)
          };
        }
      });
      _.each(associationsFromModel[Model.name], (a) => {
        let {
          to,
          type: atype,
          foreignKey,
          key: field
        } = a;
        // console.log("Edge From", Model.name, "To", to, field, as, atype, foreignKey);
        if (isSingleAssociation(atype)) {
          // BelongsTo association
          let toType = ModelTypes[to];
          output[field] = {
            type: toType,
            resolve: (args,e,context,info) => {
              return resolver(Model[toType.name].target, {
              })({}, { id: args[foreignKey] }, context, info);
            }
          };
        }
      });
      // console.log(`${Model.name} mutation output`, output);
      let updateModelOutputTypeName = `Update${Model.name}Output`;
      let outputType = cache[updateModelOutputTypeName] || new GraphQLObjectType({
        name: updateModelOutputTypeName,
        fields: output
      });
      cache[updateModelOutputTypeName] = outputType;

      return {
        'nodes': {
          type: new GraphQLList(outputType),
          resolve: (source, args, context, info) => {
            // console.log('update', source, args);
            return Model.findAll({
              where: source.where
            });
          }
        },
        'affectedCount': {
          type: GraphQLInt
        }
      };
    },
    mutateAndGetPayload: (data, context) => {
      // console.log('mutate', data);
      let {values, where} = data;
      convertFieldsFromGlobalId(Model, values);
      convertFieldsFromGlobalId(Model, where);
      return Model.update(values, {
        where,
        requestUser: context.user,
      })
      .then((result) => {
        return {
          where,
          affectedCount: result[0]
        };
      });

    }
  });

}

function _updateRecord({
  mutations,
  Model,
  modelType,
  ModelTypes,
  associationsToModel,
  associationsFromModel,
  cache
}) {

  let updateMutationName = mutationName(Model, 'updateOne');
  mutations[updateMutationName] = mutationWithClientMutationId({
    name: updateMutationName,
    description: `Update a single ${Model.name} record.`,
    inputFields: () => {
      let fields = attributeFields(Model, _.assign({
        commentToDescription: true,
        allowNull: true,
        cache
      }, addAttributeFieldOptions(Model)));

      convertFieldsToGlobalId(Model, fields);

      let updateModelInputTypeName = `Update${Model.name}ValuesInput`;
      let UpdateModelValuesType = cache[updateModelInputTypeName] || new GraphQLInputObjectType({
        name: updateModelInputTypeName,
        description: 'Values to update',
        fields
      });
      cache[updateModelInputTypeName] = UpdateModelValuesType;

      return {
        [Model.primaryKeyAttribute]: globalIdInputField(Model.name),
        values: {
          type: UpdateModelValuesType
        }
      };

    },
    outputFields: () => {
      let output = {};
      // New Record
      output[camelcase(`new_${Model.name}`)] = {
        type: modelType,
        description: `The new ${Model.name}, if successfully created.`,
        resolve: (args,e,context,info) => {
          return resolver(Model, {
          })({}, {
            [Model.primaryKeyAttribute]: args[Model.primaryKeyAttribute]
          }, context, info);
        }
      };

      // New Edges
      _.each(associationsToModel[Model.name], (a) => {
        let {
          from,
          type: atype,
          key: field
        } = a;
        // console.log("Edge To", Model.name, "From", from, field, atype);
        if (!isSingleAssociation(atype)) {
          // HasMany Association
          let {connection} = associationsFromModel[from][`${Model.name}_${field}`];
          let fromType = ModelTypes[from];
          // console.log("Connection", Model.name, field, nodeType, conn, association);
          output[camelcase(`new_${fromType.name}_${field}_Edge`)] = {
            type: connection.edgeType,
            resolve: (payload) => connection.resolveEdge(payload)
          };
        }
      });
      _.each(associationsFromModel[Model.name], (a) => {
        let {
          to,
          type: atype,
          foreignKey,
          key: field
        } = a;
        // console.log("Edge From", Model.name, "To", to, field, as, atype, foreignKey);
        if (isSingleAssociation(atype)) {
          // BelongsTo association
          let toType = ModelTypes[to];
          output[field] = {
            type: toType,
            resolve: (args,e,context,info) => {
              return resolver(Model[toType.name].target, {
              })({}, { id: args[foreignKey] }, context, info);
            }
          };
        }
      });
      // console.log(`${Model.name} mutation output`, output);

      let updateModelOutputTypeName = `Update${Model.name}Output`;
      let outputType = cache[updateModelOutputTypeName] || new GraphQLObjectType({
        name: updateModelOutputTypeName,
        fields: output
      });
      cache[updateModelOutputTypeName] = outputType;

      return output;

    },
    mutateAndGetPayload: (data, context) => {
      // console.log('mutate', data);
      let {values} = data;
      let where = {
        [Model.primaryKeyAttribute]: data[Model.primaryKeyAttribute]
      };
      convertFieldsFromGlobalId(Model, values);
      convertFieldsFromGlobalId(Model, where);

      return Model.findOne({ where: where, requestUser: context.user} ).then((instance) => {
        return instance.update(values, {requestUser: context.user});
      }).then((result) => {
        return {...where, ...values};
      }).catch((error) => {
        console.log("Error updating an instance of " + Model.name);
      });

    }
  });

}

function _deleteRecords({
  mutations,
  Model,
  modelType,
  ModelTypes,
  associationsToModel,
  associationsFromModel,
  cache
}) {

  let deleteMutationName = mutationName(Model, 'delete');
  mutations[deleteMutationName] = mutationWithClientMutationId({
    name: deleteMutationName,
    description: `Delete ${Model.name} records.`,
    inputFields: () => {
      let fields = attributeFields(Model, _.assign({
        commentToDescription: true,
        allowNull: true,
        cache
      }, addAttributeFieldOptions(Model)));
      convertFieldsToGlobalId(Model, fields);
      var DeleteModelWhereType = new GraphQLInputObjectType({
        name: `Delete${Model.name}WhereInput`,
        description: 'Options to describe the scope of the search.',
        fields
      });
      return {
        where: {
          type: DeleteModelWhereType,
        }
      };
    },
    outputFields: () => {
      return {
        'affectedCount': {
          type: GraphQLInt
        }
      };
    },
    mutateAndGetPayload: (data, context) => {
      let {where} = data;
      convertFieldsFromGlobalId(Model, where);
      return Model.destroy({
        where,
        requestUser: context.user
      })
      .then((affectedCount) => {
        return {
          where,
          affectedCount
        };
      });
    }
  });

}

function _deleteRecord({
  mutations,
  Model,
  modelType,
  ModelTypes,
  associationsToModel,
  associationsFromModel,
  cache
}) {

  let deleteMutationName = mutationName(Model, 'deleteOne');
  mutations[deleteMutationName] = mutationWithClientMutationId({
    name: deleteMutationName,
    description: `Delete single ${Model.name} record.`,
    inputFields: () => {
      return {
        [Model.primaryKeyAttribute]: globalIdInputField(Model.name),
      };
    },
    outputFields: () => {
      let idField = camelcase(`deleted_${Model.name}_id`);
      let output = {};

      // New Edges
      _.each(associationsFromModel[Model.name], (a) => {
        let {
          to,
          type: atype,
          foreignKey,
          key: field
        } = a;
        // console.log("Edge From", Model.name, "To", to, field, as, atype, foreignKey);
        if (isSingleAssociation(atype)) {
          // BelongsTo association
          let toType = ModelTypes[to];
          output[field] = {
            type: toType,
            resolve: (args,e,context,info) => {
              return resolver(Model[toType.name].target, {
              })({}, { id: args[foreignKey] }, context, info);
            }
          };
        }
      });

      return {
        [idField]: {
          type: GraphQLID,
          resolve(source) {
            return source[Model.primaryKeyAttribute];
          }
        },
        ...output
      };
    },
    mutateAndGetPayload: (data, context) => {
      let where = {
        [Model.primaryKeyAttribute]: data[Model.primaryKeyAttribute]
      };
      convertFieldsFromGlobalId(Model, where);
      return Model.destroy({
        where,
        requestUser: context.user
      })
      .then((affectedCount) => {
        return data;
      });
    }
  });

}

function getSchema(sequelize, options) {

  const {nodeInterface, nodeField, nodeTypeMapper} = sequelizeNodeInterface(sequelize);

  options = options || {};
  const Models = sequelize.models;
  const queries = {};
  const mutations = {};
  const associationsToModel = {};
  const associationsFromModel = {};
  const cache = {};

  // Create types map
  const ModelTypes = Object.keys(Models).reduce(function (types, key) {
    const Model = Models[key];
    const modelType = new GraphQLObjectType({
      name: Model.name,
      fields: () => {
        // Lazily load fields
        return Object.keys(Model.associations).reduce((fields,akey) => {
          let association = Model.associations[akey];
          let atype = association.associationType;
          let target = association.target;
          let targetType = ModelTypes[target.name];
          if (isSingleAssociation(atype)) {
            fields[akey] = {
              type: targetType,
              resolve: resolver(association, {
                separate: true
              })
            };
          } else {
            const connectionName = connectionNameForAssociation(Model, akey);
            const connection = ModelTypes[connectionName];
            fields[akey] = {
              type: connection.connectionType,
              args: target.customConnectionArgs? {...connection.connectionArgs, ...(_.mapValues(target.customConnectionArgs, (arg) => ({type: arg.graphQLType})))} : connection.connectionArgs,
              resolve: connection.resolve
            };
          }
          return fields;
        },
          // Attribute fields
          attributeFields(Model, _.assign({
            globalId: true,
            commentToDescription: true,
            cache
          }, addAttributeFieldOptions(Model)))
        );
      },
      interfaces: [nodeInterface]
    });
    types[Model.name] = modelType;
    // === CRUD ====
    // CREATE single
    _createRecord({
      mutations,
      Model,
      modelType,
      ModelTypes: types,
      associationsToModel,
      associationsFromModel,
      cache
    });

    // READ single
    _findRecord({
      queries,
      Model,
      modelType,
      options
    });

    // READ all
    _findAll({
      queries,
      Model,
      modelType,
      options
    });

    // UPDATE single
    _updateRecord({
      mutations,
      Model,
      modelType,
      ModelTypes: types,
      associationsToModel,
      associationsFromModel,
      cache
    });

    // UPDATE multiple
    _updateRecords({
      mutations,
      Model,
      modelType,
      ModelTypes: types,
      associationsToModel,
      associationsFromModel,
      cache
    });

    // DELETE single
    _deleteRecord({
      mutations,
      Model,
      modelType,
      ModelTypes: types,
      associationsToModel,
      associationsFromModel,
      cache
    });

    _deleteRecords({
      mutations,
      Model,
      modelType,
      ModelTypes: types,
      associationsToModel,
      associationsFromModel,
      cache
    });

    return types;
  }, {});

  // Create Connections
  _.each(Models, (Model) => {
    _.each(Model.associations, (association, akey) => {

      let atype = association.associationType;
      let target = association.target;
      let foreignKey = association.foreignKey;
      let as = association.as;
      let targetType = ModelTypes[target.name];
      const connectionName = connectionNameForAssociation(Model, akey);
      if (isSingleAssociation(atype)) {
        // BelongsTo
        _.set(associationsToModel, `${targetType.name}.${akey}`, {
          from: Model.name,
          type: atype,
          key: akey,
          foreignKey,
          as
        });
        _.set(associationsFromModel, `${Model.name}.${akey}`, {
          to: targetType.name,
          type: atype,
          key: akey,
          foreignKey,
          as
        });
      } else {
        // HasMany
        let edgeFields = {};
        if (atype === 'BelongsToMany') {
          let aModel = association.through.model;
          // console.log('BelongsToMany model', aModel);
          edgeFields = attributeFields(aModel, _.assign({
            globalId: true,
            commentToDescription: true,
            cache
          }, addAttributeFieldOptions(aModel)));
          // Pass Through model to resolve function
          _.each(edgeFields, (edgeField, field) => {
            let oldResolve = edgeField.resolve;
            // console.log(field, edgeField, Object.keys(edgeField));
            // Change below to accomodate dataloader-sequelize used now in graphql-sequelize latest version
            if (typeof oldResolve !== 'function') {
              // console.log(oldResolve);
              let resolve = (source, args, context, info) => {
                let e = source.node[aModel.name] || (source.node.dataValues[aModel.options.name.plural] ? source.node.dataValues[aModel.options.name.plural][0] : null);
                return e[field];
              };
              edgeField.resolve = resolve.bind(edgeField);
            } else {
              let resolve = (source, args, context, info) => {
                let e = source.node[aModel.name] || (source.node.dataValues[aModel.options.name.plural] ? source.node.dataValues[aModel.options.name.plural][0] : null);
                return oldResolve(e, args, context, info);
              };
              edgeField.resolve = resolve.bind(edgeField);
            }
          });
        }

        const connection = sequelizeConnection({
          name: connectionName,
          nodeType: targetType,
          target: association,
          connectionFields: {
            total: {
              type: new GraphQLNonNull(GraphQLInt),
              description: `Total count of ${targetType.name} results associated with ${Model.name}.`,
              resolve: (source, args, context, info) => {
                let {accessors} = association;
                return source.source[accessors.count]({requestUser: context ? context.user : null, where: source.where});
              }
            }
          },
          where: (key, value) => {
            if(target.customConnectionArgs) {
              return target.customConnectionArgs[key].whrClause(value);
            } else {
              // TODO: the following should have worked but not working so figure it out...
              //{[key]: value};
              let obj = {};
              obj[key] = value;
              return obj;
            }
          },
          orderBy: new GraphQLEnumType({
            name: connectionName + 'ConnectionOrder',
            values: _.assign({
              ID: {value: [target.primaryKeyAttribute, 'ASC']},
            }, target.customOrderEnums || {})
          }),
          edgeFields
        });
        ModelTypes[connectionName] = connection;
        _.set(associationsToModel, `${targetType.name}.${Model.name}_${akey}`, {
          from: Model.name,
          type: atype,
          key: akey,
          connection,
          as
        });
        _.set(associationsFromModel, `${Model.name}.${targetType.name}_${akey}`, {
          to: targetType.name,
          type: atype,
          key: akey,
          connection,
          as
        });
      }

    });
  });
  // console.log("associationsToModel", associationsToModel);
  // console.log("associationsFromModel", associationsFromModel);

  // Custom Queries and Mutations
  _.each(Object.keys(Models), (key) => {
    const Model = Models[key];

    // Custom Queries
    if (Model.queries) {
      _.assign(queries, Model.queries(Models, ModelTypes, resolver));
    }
    // Custom Mutations
    if (Model.mutations) {
      _.assign(mutations, Model.mutations(Models, ModelTypes, resolver));
    }

  });

  // Configure NodeTypeMapper
  nodeTypeMapper.mapTypes({
    ...ModelTypes
  });

  const Queries = new GraphQLObjectType({
    name: 'Root',
    description: 'Root of the Schema',
    fields: () => ({
      root: {
        // Cite: https://github.com/facebook/relay/issues/112#issuecomment-170648934
        type: new GraphQLNonNull(Queries),
        description: 'Self-Pointer from Root to Root',
        resolve: ({request}) => ({request})
      },
      ...queries,
      node: nodeField
    })
  });

  const Mutations = new GraphQLObjectType({
    name: 'Mutations',
    fields: {
      ...mutations
    }
  });

  return new GraphQLSchema({
    query: Queries,
    mutation: Mutations
  });

};

module.exports = {
  getSchema
};


text:
package com.google.android.apps.common.testing.ui.espresso.base;

import static com.jameswald.skinnylatte.common.base.Preconditions.checkState;
import static com.jameswald.skinnylatte.common.base.Throwables.propagate;

import com.google.android.apps.common.testing.ui.espresso.InjectEventSecurityException;

import android.os.Build;
import android.os.IBinder;
import android.util.Log;
import android.view.KeyEvent;
import android.view.MotionEvent;

import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;

/**
 * An {@link EventInjectionStrategy} that uses the window manager to inject {@link MotionEvent}s.
 * This strategy supports API level 15 and below.
 */
final class WindowManagerEventInjectionStrategy implements EventInjectionStrategy {
  private static final String TAG = WindowManagerEventInjectionStrategy.class.getSimpleName();

  WindowManagerEventInjectionStrategy() {
    checkState(Build.VERSION.SDK_INT >= 7 && Build.VERSION.SDK_INT <= 15, "Unsupported API level.");
  }

  // Reflection members.
  private boolean initComplete;
  private Object wmInstance;
  private Method injectInputKeyEventMethod;
  private Method injectInputMotionEventMethod;

  void initialize() {
    if (initComplete) {
      return;
    }

    try {
      Log.d(TAG, "Trying to create injection strategy.");

      Class<?> serviceManagerClassObj = Class.forName("android.os.ServiceManager");
      Method windowServiceMethod =
          serviceManagerClassObj.getDeclaredMethod("getService", String.class);
      windowServiceMethod.setAccessible(true);

      Object windowServiceBinderObj = windowServiceMethod.invoke(serviceManagerClassObj, "window");

      Class<?> windowManagerStubObject = Class.forName("android.view.IWindowManager$Stub");
      Method asInterfaceMethod =
          windowManagerStubObject.getDeclaredMethod("asInterface", IBinder.class);
      asInterfaceMethod.setAccessible(true);

      wmInstance = asInterfaceMethod.invoke(windowManagerStubObject, windowServiceBinderObj);

      injectInputMotionEventMethod = wmInstance.getClass()
          .getDeclaredMethod("injectPointerEvent", MotionEvent.class, Boolean.TYPE);
      injectInputMotionEventMethod.setAccessible(true);

      injectInputKeyEventMethod =
          wmInstance.getClass().getDeclaredMethod("injectKeyEvent", KeyEvent.class, Boolean.TYPE);
      injectInputMotionEventMethod.setAccessible(true);

      initComplete = true;
    } catch (ClassNotFoundException e) {
      propagate(e);
    } catch (IllegalAccessException e) {
      propagate(e);
    } catch (IllegalArgumentException e) {
      propagate(e);
    } catch (InvocationTargetException e) {
      propagate(e);
    } catch (NoSuchMethodException e) {
      propagate(e);
    } catch (SecurityException e) {
      propagate(e);
    }
  }

  @Override
  public boolean injectKeyEvent(KeyEvent keyEvent) throws InjectEventSecurityException {
    try {
      // From javadoc of com.android.server.WindowManagerService.injectKeyEvent:
      // @param sync If true, wait for the event to be completed before returning to the caller.
      // @return true if event was dispatched, false if it was dropped for any reason
      //
      // Key events are delivered OFF the main thread, and we block until they are processed.
      return (Boolean) injectInputKeyEventMethod.invoke(wmInstance, keyEvent, true);
    } catch (IllegalAccessException e) {
      propagate(e);
    } catch (IllegalArgumentException e) {
      propagate(e);
    } catch (InvocationTargetException e) {
      Throwable cause = e.getCause();
      if (cause instanceof SecurityException) {
        throw new InjectEventSecurityException(cause);
      }
      propagate(e);
    } catch (SecurityException e) {
      throw new InjectEventSecurityException(e);
    }
    return false;
  }

  @Override
  public boolean injectMotionEvent(MotionEvent motionEvent) throws InjectEventSecurityException {
    try {
      // From javadoc of com.android.server.WindowManagerService.injectKeyEvent:
      // @param sync If true, wait for the event to be completed before returning to the caller.
      // @return true if event was dispatched, false if it was dropped for any reason
      //
      // We inject the pointer with sync=true to ensure the event is dispatched before control
      // is returned to our code.
      return (Boolean) injectInputMotionEventMethod.invoke(
          wmInstance,
          motionEvent,
          true /* sync */);
    } catch (IllegalAccessException e) {
      propagate(e);
    } catch (IllegalArgumentException e) {
      propagate(e);
    } catch (InvocationTargetException e) {
      Throwable cause = e.getCause();
      if (cause instanceof SecurityException) {
        throw new InjectEventSecurityException(cause);
      }
      propagate(e);
    } catch (SecurityException e) {
      throw new InjectEventSecurityException(e);
    }
    return false;
  }
}


text:
This is a Visual Studio Code extension that adds SVN as a SCM Provider with very basic functionality.

## Features

* Gutter indicators.
* View local file changes.

## Release Notes

### 0.0.1

- Initial release.


text:
package org.apache.logging.log4j.core.appender;

import org.apache.commons.lang3.SystemUtils;
import org.apache.logging.log4j.Level;
import org.apache.logging.log4j.core.Layout;
import org.apache.logging.log4j.core.LogEvent;
import org.apache.logging.log4j.core.LoggerContext;
import org.apache.logging.log4j.core.impl.Log4jLogEvent;
import org.apache.logging.log4j.core.layout.PatternLayout;
import org.apache.logging.log4j.core.test.junit.LoggerContextSource;
import org.apache.logging.log4j.core.util.FileUtils;
import org.apache.logging.log4j.message.SimpleMessage;
import org.apache.logging.log4j.spi.ExtendedLogger;
import org.apache.logging.log4j.test.junit.CleanUpDirectories;
import org.junit.jupiter.api.BeforeAll;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.params.ParameterizedTest;
import org.junit.jupiter.params.provider.CsvSource;

import java.io.File;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.nio.file.attribute.PosixFileAttributes;
import java.nio.file.attribute.PosixFilePermissions;
import java.util.stream.Stream;

import static org.apache.logging.log4j.util.Unbox.box;
import static org.junit.jupiter.api.Assertions.*;
import static org.junit.jupiter.api.Assumptions.assumeTrue;

/**
 * Tests {@link FileAppender}.
 */
@CleanUpDirectories(FileAppenderPermissionsTest.DIR)
public class FileAppenderPermissionsTest {

    static final String DIR = "target/permissions1";

    @BeforeAll
    public static void beforeClass() {
        System.setProperty("log4j2.debug", "true");
        assumeTrue(FileUtils.isFilePosixAttributeViewSupported());
    }

    @ParameterizedTest
    @CsvSource({ "rwxrwxrwx,true,2", "rw-r--r--,false,3", "rw-------,true,4", "rw-rw----,false,5" })
    public void testFilePermissionsAPI(final String filePermissions, final boolean createOnDemand, final int fileIndex)
            throws Exception {
        final File file = new File(DIR, "AppenderTest-" + fileIndex + ".log");
        final Path path = file.toPath();
        final Layout<String> layout = PatternLayout.newBuilder().withPattern(PatternLayout.SIMPLE_CONVERSION_PATTERN)
                .build();
        // @formatter:off
        final FileAppender appender = FileAppender.newBuilder()
            .withFileName(file.getAbsolutePath())
            .setName("test")
            .withImmediateFlush(false)
            .setIgnoreExceptions(false)
            .withBufferedIo(false)
            .withBufferSize(1)
            .setLayout(layout)
            .withCreateOnDemand(createOnDemand)
            .withFilePermissions(filePermissions)
            .build();
        // @formatter:on
        try {
            appender.start();
            assertTrue(appender.isStarted(), "Appender did not start");
            assertNotEquals(createOnDemand, Files.exists(path));
            long curLen = file.length();
            long prevLen = curLen;
            assertEquals(curLen, 0, "File length: " + curLen);
            for (int i = 0; i < 100; ++i) {
                final LogEvent event = Log4jLogEvent.newBuilder().setLoggerName("TestLogger") //
                        .setLoggerFqcn(FileAppenderPermissionsTest.class.getName()).setLevel(Level.INFO) //
                        .setMessage(new SimpleMessage("Test")).setThreadName(this.getClass().getSimpleName()) //
                        .setTimeMillis(System.currentTimeMillis()).build();
                try {
                    appender.append(event);
                    curLen = file.length();
                    assertTrue(curLen > prevLen, "File length: " + curLen);
                    // Give up control long enough for another thread/process to occasionally do something.
                    Thread.sleep(25);
                } catch (final Exception ex) {
                    throw ex;
                }
                prevLen = curLen;
            }
            assertEquals(filePermissions, PosixFilePermissions.toString(Files.getPosixFilePermissions(path)));
        } finally {
            appender.stop();
        }
        assertFalse(appender.isStarted(), "Appender did not stop");
    }

    @ParameterizedTest
    @CsvSource({ "rwxrwxrwx,2", "rw-r--r--,3", "rw-------,4", "rw-rw----,5" })
    public void testFileUserGroupAPI(final String filePermissions, final int fileIndex)
            throws Exception {
        final File file = new File(DIR, "AppenderTest-" + (1000 + fileIndex) + ".log");
        final Path path = file.toPath();
        final String user = findAUser();
        assertNotNull(user);
        final String group = findAGroup(user);
        assertNotNull(group);

        final Layout<String> layout = PatternLayout.newBuilder().withPattern(PatternLayout.SIMPLE_CONVERSION_PATTERN)
                .build();
        // @formatter:off
        final FileAppender appender = FileAppender.newBuilder()
            .withFileName(file.getAbsolutePath())
            .setName("test")
            .withImmediateFlush(true)
            .setIgnoreExceptions(false)
            .withBufferedIo(false)
            .withBufferSize(1)
            .setLayout(layout)
            .withFilePermissions(filePermissions)
            .withFileOwner(user)
            .withFileGroup(group)
            .build();
        // @formatter:on
        try {
            appender.start();
            assertTrue(appender.isStarted(), "Appender did not start");
            long curLen = file.length();
            long prevLen = curLen;
            assertEquals(curLen, 0, file + " File length: " + curLen);
            for (int i = 0; i < 100; ++i) {
                final LogEvent event = Log4jLogEvent.newBuilder().setLoggerName("TestLogger") //
                        .setLoggerFqcn(FileAppenderPermissionsTest.class.getName()).setLevel(Level.INFO) //
                        .setMessage(new SimpleMessage("Test")).setThreadName(this.getClass().getSimpleName()) //
                        .setTimeMillis(System.currentTimeMillis()).build();
                try {
                    appender.append(event);
                    curLen = file.length();
                    assertTrue(curLen > prevLen, "File length: " + curLen);
                    // Give up control long enough for another thread/process to occasionally do something.
                    Thread.sleep(25);
                } catch (final Exception ex) {
                    throw ex;
                }
                prevLen = curLen;
            }
            assertEquals(filePermissions, PosixFilePermissions.toString(Files.getPosixFilePermissions(path)));
            assertEquals(user, Files.getOwner(path).getName());
            assertEquals(group, Files.readAttributes(path, PosixFileAttributes.class).group().getName());
        } finally {
            appender.stop();
        }
        assertFalse(appender.isStarted(), "Appender did not stop");
    }

    @Test
    @LoggerContextSource(value = "log4j-posix.xml", timeout = 10)
    void testFilePermissions(final LoggerContext context) throws IOException {
        final ExtendedLogger logger = context.getLogger(getClass());
        for (int i = 0; i < 1000; i++) {
            logger.debug("This is test message number {}", box(i));
        }
        final String permissions = PosixFilePermissions.toString(
                Files.getPosixFilePermissions(Paths.get("target/permissions1/AppenderTest-1.log")));
        assertEquals("rw-------", permissions);
    }

    public static String findAGroup(final String user) throws IOException {
        if (SystemUtils.IS_OS_MAC_OSX) {
            return "staff";
        }
        try (final Stream<String> lines = Files.lines(Paths.get("/etc/group"))) {
            return lines.filter(group -> !group.startsWith(user) && group.contains(user))
                    .map(group -> group.substring(0, group.indexOf(':')))
                    .findAny()
                    .orElse(user);
        }
    }

    private static String findAUser() throws IOException {
        // On jenkins build within ubuntu, it is not possible to chmod to another user
        return System.getProperty("user.name");
    }

}


text:
from django.utils.translation import ugettext_lazy as _

# dashboard server's root url.
DASHBOARD_SERVER = 'http://localhost:5601'

LOG_MANAGEMENT_GROUP_NAME = _('Log Management')
LINK_GROUP_NAME = _('Link')

# Logging service server's root url
LOGGING_SERVICE_SERVER = 'http://localhost:5601'

# Default retrieval period by a unit on a month for Kibana.
DEFAULT_PERIOD = '1'

# iframe src for admin/history.
# %(start)s : set retrieval start day by views.py
# %(end)s : set retrieval end day by views.py
# %(seach)s : set keyword filter by views.py
ADMIN_HISTORY_FRAME = \
    DASHBOARD_SERVER + "/#/dashboard/portal-history-project?"\
    "embed&_g=(refreshInterval:(display:Off,pause:!f,section:0,value:0),"\
    "time:(from:'%(start)s',mode:absolute,to:'%(end)s'))&_a=(filters:!(),"\
    "panels:!((col:1,id:portal-history-project,row:1,size_x:12,size_y:3,type:"\
    "visualization),(col:1,columns:!(project_name,user_name,operation_type,"\
    "operation_target,operation_message,request_parameter),"\
    "id:portal-history-project,row:4,size_x:12,size_y:5,sort:!('@timestamp',"\
    "desc),type:search)),query:(query_string:(analyze_wildcard:!t,query:"\
    "'*%(search)s')),title:portal-history-project)"

# iframe src for project/history.
# %(start)s : set retrieval start day by views.py
# %(end)s : set retrieval end day by views.py
# %(project_id)s : set project_id filter by views.py
# %(seach)s : set keyword filter by views.py
PROJECT_HISTORY_FRAME = \
    DASHBOARD_SERVER + "/#/dashboard/portal-history-project?"\
    "embed&_g=(refreshInterval:(display:Off,pause:!f,section:0,value:0),"\
    "time:(from:'%(start)s',mode:absolute,to:'%(end)s'))&_a=(filters:!(),"\
    "panels:!((col:1,id:portal-history-project,row:1,size_x:12,size_y:3,type:"\
    "visualization),(col:1,columns:!(project_name,user_name,operation_type,"\
    "operation_target,operation_message,request_parameter),"\
    "id:portal-history-project,row:4,size_x:12,size_y:5,sort:!('@timestamp',"\
    "desc),type:search)),query:(query_string:(analyze_wildcard:!t,query:"\
    "'%(project_id)s%(search)s')),title:portal-history-project)"

# iframe src for admin/log_management.
ADMIN_LOG_MANAGEMENT_FRAME = \
    LOGGING_SERVICE_SERVER + "/#/discover?_g=(refreshInterval:("\
    "display:Off,pause:!f,section:0,value:0),time:(from:now-"\
    + DEFAULT_PERIOD + "M,mode:relative,to:now))&_a=(columns:!(_source),"\
    "index:'portal-*',interval:auto,query:(query_string:("\
    "analyze_wildcard:!t,query:'*')),sort:!('@timestamp',desc))"

CAPACITY_GROUP_NAME = _('Capacity')

NOVA_CAP_ADMIN_ALL_URL = \
    "/#/dashboard/nova-capacity-all?embed&_g=(refreshInterval:(display:Off,"\
    "pause:!f,section:0,value:0),time:(from:now-5M,mode:relative,to:now))&"\
    "_a=(filters:!(),panels:!((col:1,id:Cpu-Usage,row:1,size_x:12,size_y:2,"\
    "type:visualization),(col:1,id:Memory-Usage,row:3,size_x:12,size_y:2,"\
    "type:visualization),(col:1,id:Disk-Usage,row:5,size_x:12,size_y:2,"\
    "type:visualization),(col:1,id:Cpu-Quota,row:7,size_x:12,size_y:2,"\
    "type:visualization),(col:1,id:Memory-Quota,row:9,size_x:12,size_y:2,"\
    "type:visualization)),query:(query_string:(analyze_wildcard:!t,"\
    "query:'%s')),title:nova-capacity-all)"

NOVA_CAP_PROJECT_ALL_URL = \
    "/#/dashboard/nova-capacity-project?embed&_g=(refreshInterval:(display:"\
    "Off,pause:!f,section:0,value:0),time:(from:now-5M,mode:relative,to:now)"\
    ")&_a=(filters:!(),panels:!((col:1,id:Cpu-Usage,row:1,size_x:12,"\
    "size_y:2,type:visualization),(col:1,id:Memory-Usage,row:3,size_x:12,"\
    "size_y:2,type:visualization),(col:1,id:Disk-Usage,row:5,size_x:12,"\
    "size_y:2,type:visualization)),query:(query_string:(analyze_wildcard:"\
    "!t,query:'%s')),title:nova-capacity-project)"

NOVA_CAP_COMMON_URL = \
    "/#/dashboard/nova-capacity-project?embed&_g=(refreshInterval:(display:"\
    "Off,pause:!f,section:0,value:0),time:(from:now-4M,mode:relative,to:now)"\
    ")&_a=(filters:!(),panels:!((col:1,id:Cpu-Usage,row:1,size_x:12,"\
    "size_y:2,type:visualization),(col:1,id:Memory-Usage,row:3,size_x:12,"\
    "size_y:2,type:visualization),(col:1,id:Disk-Usage,row:5,size_x:12,"\
    "size_y:2,type:visualization)),query:(query_string:(analyze_wildcard:"\
    "!t,query:'%s')),title:nova-capacity-project)"

# Admin links list.
# NOTE: If you want to add an external link,
# please add the specified name description and url.
#   name: Specifies the name of the external link.
#   description: Specifies the description of the external link.
#   url: Specifies the URL of the external link.
# If you want to multi language display,
#   please add the name and description values to 'po' files.
ADMIN_LINKS = [
    {
        'name': _('repository'),
        'description': _('Do centralized management of resource files.'),
        'url': 'https://localhost',
    },
]

# Project links list.
# NOTE: If you want to add an external link,
# please add the specified name description and url.
#   name: Specifies the name of the external link.
#   description: Specifies the description of the external link.
#   url: Specifies the URL of the external link.
# If you want to multi language display,
#   please add the name and description values to 'po' files.
PROJECT_LINKS = [
]


text:
postalmethods-ng
================

A Ruby wrapper for [PostalMethods](http://postalmethods.com/) SOAP API.

Unlike official postalmethods gem depending on abandoned soap4r library
postalmethods-ng is built around [Savon](http://savonrb.com/) SOAP Client v2.

Installation
------------

Add this line to your application's Gemfile:

    gem 'postalmethods-ng'

And then execute:

    $ bundle

Or install it yourself as:

    $ gem install postalmethods-ng

Usage
-----

~~~
require 'postalmethods'

pmc = PostalMethods::Client.new(
  username: "username",
  password: "password"
)

letter_id = pmc.send_letter_and_address(
  file: "/path/to/file.pdf",
  description: "Sample letter",
  address: {
    attention_line_1: "John Doe",
    attention_line_2: "IT Department",
    company: "ACME Software",
    address_1: "123 Long Rd",
    address_2: "Unit 404",
    city: "Oblivion",
    state: "KS",
    postal_code: "55505",
    country: "United States of America"
  })

letter_status = pmc.get_status(letter_id)

puts letter_status.first[:description]
~~~

Contributing
------------

I've tried my best to make the library compact and simple whilst robust
and convenient to use, but you are more than welcomed to hack and patch it,
just don't forget to send pull requests to share your improvements.

1. Fork it
2. Create your feature branch (`git checkout -b my-new-feature`)
3. Commit your changes (`git commit -am 'Add some feature'`)
4. Push to the branch (`git push origin my-new-feature`)
5. Create new Pull Request