text:
#include "libtorrent/session.hpp"
#include "libtorrent/session_settings.hpp"
#include "libtorrent/hasher.hpp"
#include "libtorrent/alert_types.hpp"
#include "libtorrent/bencode.hpp"
#include "libtorrent/thread.hpp"
#include "libtorrent/time.hpp"
#include "libtorrent/file.hpp"
#include <boost/tuple/tuple.hpp>
#include <boost/bind.hpp>

#include "test.hpp"
#include "setup_transfer.hpp"
#include "udp_tracker.hpp"
#include <fstream>
#include <iostream>

using namespace libtorrent;
using boost::tuples::ignore;

int const alert_mask = alert::all_categories
& ~alert::progress_notification
& ~alert::stats_notification;

int peer_disconnects = 0;

int tracker_responses = 0;

bool on_alert(alert* a)
{
	if (alert_cast<tracker_reply_alert>(a))
		++tracker_responses;
	else if (alert_cast<peer_disconnected_alert>(a))
		++peer_disconnects;
	else if (alert_cast<peer_error_alert>(a))
		++peer_disconnects;

	return false;
}

void test_transfer()
{
	// in case the previous run was terminated
	error_code ec;
	remove_all("tmp1_priority", ec);
	remove_all("tmp2_priority", ec);
	remove_all("tmp1_priority_moved", ec);
	remove_all("tmp2_priority_moved", ec);

	// these are declared before the session objects
	// so that they are destructed last. This enables
	// the sessions to destruct in parallel
	session_proxy p1;
	session_proxy p2;

	session ses1(fingerprint("LT", 0, 1, 0, 0), std::make_pair(48075, 49000), "0.0.0.0", 0, alert_mask);
	session ses2(fingerprint("LT", 0, 1, 0, 0), std::make_pair(49075, 50000), "0.0.0.0", 0, alert_mask);

	session_settings sett;
	sett.allow_multiple_connections_per_ip = false;
	sett.ignore_limits_on_local_network = false;

	sett.unchoke_slots_limit = 0;
	ses1.set_settings(sett);
	TEST_CHECK(ses1.settings().unchoke_slots_limit == 0);
	sett.unchoke_slots_limit = -1;
	ses1.set_settings(sett);
	TEST_CHECK(ses1.settings().unchoke_slots_limit == -1);
	sett.unchoke_slots_limit = 8;
	ses1.set_settings(sett);
	TEST_CHECK(ses1.settings().unchoke_slots_limit == 8);

	// we need a short reconnect time since we
	// finish the torrent and then restart it
	// immediately to complete the second half.
	// using a reconnect time > 0 will just add
	// to the time it will take to complete the test
	sett.min_reconnect_time = 0;
	sett.stop_tracker_timeout = 1;
	sett.announce_to_all_trackers = true;
	sett.announce_to_all_tiers = true;
	// make sure we announce to both http and udp trackers
	sett.prefer_udp_trackers = false;
	sett.enable_outgoing_utp = false;
	sett.enable_incoming_utp = false;

	ses1.set_settings(sett);
	ses2.set_settings(sett);

#ifndef TORRENT_DISABLE_ENCRYPTION
	pe_settings pes;
	pes.out_enc_policy = pe_settings::disabled;
	pes.in_enc_policy = pe_settings::disabled;
	ses1.set_pe_settings(pes);
	ses2.set_pe_settings(pes);
#endif

	torrent_handle tor1;
	torrent_handle tor2;

	create_directory("tmp1_priority", ec);
	std::ofstream file("tmp1_priority/temporary");
	boost::intrusive_ptr<torrent_info> t = ::create_torrent(&file, 16 * 1024, 13, false);
	file.close();

	int udp_tracker_port = start_udp_tracker();
	int tracker_port = start_web_server();

	char tracker_url[200];
	snprintf(tracker_url, sizeof(tracker_url), "http://127.0.0.1:%d/announce", tracker_port);
	t->add_tracker(tracker_url);

	snprintf(tracker_url, sizeof(tracker_url), "udp://127.0.0.1:%d/announce", udp_tracker_port);
	t->add_tracker(tracker_url);

	add_torrent_params addp;
	addp.flags &= ~add_torrent_params::flag_paused;
	addp.flags &= ~add_torrent_params::flag_auto_managed;

	wait_for_listen(ses1, "ses1");
	wait_for_listen(ses2, "ses1");

	peer_disconnects = 0;

	// test using piece sizes smaller than 16kB
	boost::tie(tor1, tor2, ignore) = setup_transfer(&ses1, &ses2, 0
		, true, false, true, "_priority", 8 * 1024, &t, false, 0);

	int num_pieces = tor2.torrent_file()->num_pieces();
	std::vector<int> priorities(num_pieces, 1);
	// set half of the pieces to priority 0
	std::fill(priorities.begin(), priorities.begin() + (num_pieces / 2), 0);
	tor2.prioritize_pieces(priorities);
	std::cerr << "setting priorities: ";
	std::copy(priorities.begin(), priorities.end(), std::ostream_iterator<int>(std::cerr, ", "));
	std::cerr << std::endl;

	tracker_responses = 0;

	for (int i = 0; i < 200; ++i)
	{
		print_alerts(ses1, "ses1", true, true, true, &on_alert);
		print_alerts(ses2, "ses2", true, true, true, &on_alert);

		torrent_status st1 = tor1.status();
		torrent_status st2 = tor2.status();

		if (i % 10 == 0)
		{
			print_ses_rate(i / 10.f, &st1, &st2);
		}

		// st2 is finished when we have downloaded half of the pieces
		if (st2.is_finished) break;

		if (st2.state != torrent_status::downloading)
		{
			static char const* state_str[] =
				{"checking (q)", "checking", "dl metadata"
				, "downloading", "finished", "seeding", "allocating", "checking (r)"};
			std::cerr << "st2 state: " << state_str[st2.state] << std::endl;
		}

		TEST_CHECK(st1.state == torrent_status::seeding
			|| st1.state == torrent_status::checking_files);
		TEST_CHECK(st2.state == torrent_status::downloading
			|| st2.state == torrent_status::checking_resume_data);

		if (peer_disconnects >= 2) break;

		// if nothing is being transferred after 2 seconds, we're failing the test
		if (st1.upload_payload_rate == 0 && i > 20) break;

		test_sleep(100);
	}

	// 1 announce per tracker to start
	TEST_CHECK(tracker_responses >= 2);

	TEST_CHECK(!tor2.status().is_seeding);
	TEST_CHECK(tor2.status().is_finished);

	if (tor2.status().is_finished)
		std::cerr << "torrent is finished (50% complete)" << std::endl;
	else return;

	std::vector<int> priorities2 = tor2.piece_priorities();
	std::copy(priorities2.begin(), priorities2.end(), std::ostream_iterator<int>(std::cerr, ", "));
	std::cerr << std::endl;
	TEST_CHECK(std::equal(priorities.begin(), priorities.end(), priorities2.begin()));

	std::cerr << "force recheck" << std::endl;
	tor2.force_recheck();

	priorities2 = tor2.piece_priorities();
	std::copy(priorities2.begin(), priorities2.end(), std::ostream_iterator<int>(std::cerr, ", "));
	std::cerr << std::endl;
	TEST_CHECK(std::equal(priorities.begin(), priorities.end(), priorities2.begin()));

	peer_disconnects = 0;

	// wait until force-recheck is complete
	// when we're done checking, we're likely to be put in downloading state
	// for a split second before transitioning to finished. This loop waits
	// for the finished state
	torrent_status st2;
	for (int i = 0; i < 50; ++i)
	{
		print_alerts(ses1, "ses1", true, true, true, &on_alert);
		print_alerts(ses2, "ses2", true, true, true, &on_alert);

		st2 = tor2.status();
		if (i % 10 == 0)
		{
			std::cerr << int(st2.progress * 100) << "% " << std::endl;
		}
		if (st2.state == torrent_status::finished) break;
		test_sleep(100);
	}

	TEST_CHECK(st2.state != torrent_status::checking_files);
	if (st2.state != torrent_status::checking_files) std::cerr << "recheck complete" << std::endl;

	priorities2 = tor2.piece_priorities();
	std::copy(priorities2.begin(), priorities2.end(), std::ostream_iterator<int>(std::cerr, ", "));
	std::cerr << std::endl;
	TEST_CHECK(std::equal(priorities.begin(), priorities.end(), priorities2.begin()));

	tor2.pause();
	alert const* a = ses2.wait_for_alert(seconds(10));
	bool got_paused_alert = false;
	while (a)
	{
		std::auto_ptr<alert> holder = ses2.pop_alert();
		std::cerr << "ses2: " << a->message() << std::endl;
		if (alert_cast<torrent_paused_alert>(a))
		{
			got_paused_alert = true;
			break;
		}
		a = ses2.wait_for_alert(seconds(10));
	}
	TEST_CHECK(got_paused_alert);

	std::vector<announce_entry> tr = tor2.trackers();
	tr.push_back(announce_entry("http://test.com/announce"));
	tor2.replace_trackers(tr);
	tr.clear();

	tor2.save_resume_data();

	std::vector<char> resume_data;
	a = ses2.wait_for_alert(seconds(10));
	while (a)
	{
		std::auto_ptr<alert> holder = ses2.pop_alert();
		std::cerr << "ses2: " << a->message() << std::endl;
		if (alert_cast<save_resume_data_alert>(a))
		{
			bencode(std::back_inserter(resume_data)
					, *alert_cast<save_resume_data_alert>(a)->resume_data);
			break;
		}
		a = ses2.wait_for_alert(seconds(10));
	}
	TEST_CHECK(resume_data.size());

	std::cerr << "saved resume data" << std::endl;

	ses2.remove_torrent(tor2);

	std::cerr << "removed" << std::endl;

	test_sleep(100);

	std::cout << "re-adding" << std::endl;
	add_torrent_params p;
	p.flags &= ~add_torrent_params::flag_paused;
	p.flags &= ~add_torrent_params::flag_auto_managed;
	p.ti = t;
	p.save_path = "tmp2_priority";
	p.resume_data = resume_data;
	tor2 = ses2.add_torrent(p, ec);
	ses2.set_alert_mask(alert::all_categories
		& ~alert::progress_notification
		& ~alert::stats_notification);
	tor2.prioritize_pieces(priorities);
	std::cout << "resetting priorities" << std::endl;
	tor2.resume();

	tr = tor2.trackers();
	TEST_CHECK(std::find_if(tr.begin(), tr.end()
		, boost::bind(&announce_entry::url, _1) == "http://test.com/announce") != tr.end());

	// wait for the files in ses2 to be checked, i.e. the torrent
	// to turn into finished state
	for (int i = 0; i < 5; ++i)
	{
		print_alerts(ses1, "ses1", true, true, true, &on_alert);
		print_alerts(ses2, "ses2", true, true, true, &on_alert);

		torrent_status st1 = tor1.status();
		torrent_status st2 = tor2.status();

		TEST_EQUAL(st1.state, torrent_status::seeding);

		if (st2.is_finished) break;

		test_sleep(100);
	}

	TEST_CHECK(!tor2.status().is_seeding);

	std::fill(priorities.begin(), priorities.end(), 1);
	tor2.prioritize_pieces(priorities);
	std::cout << "setting priorities to 1" << std::endl;
	TEST_EQUAL(tor2.status().is_finished, false);

	std::copy(priorities.begin(), priorities.end(), std::ostream_iterator<int>(std::cerr, ", "));
	std::cerr << std::endl;

	// drain alerts
	print_alerts(ses1, "ses1", true, true, true, &on_alert);
	print_alerts(ses2, "ses2", true, true, true, &on_alert);

	peer_disconnects = 0;

	// this loop makes sure ses2 reconnects to the peer now that it's
	// in download mode again. If this fails, the reconnect logic may
	// not work or be inefficient
	torrent_status st1 = tor1.status();
	st2 = tor2.status();
	for (int i = 0; i < 130; ++i)
	{
		print_alerts(ses1, "ses1", true, true, true, &on_alert);
		print_alerts(ses2, "ses2", true, true, true, &on_alert);

		st1 = tor1.status();
		st2 = tor2.status();

		if (i % 10 == 0)
			print_ses_rate(i / 10.f, &st1, &st2);

		if (st2.is_seeding) break;

		TEST_EQUAL(st1.state, torrent_status::seeding);
		TEST_EQUAL(st2.state, torrent_status::downloading);

		if (peer_disconnects >= 2)
		{
			fprintf(stderr, "too many disconnects (%d), exiting\n", peer_disconnects);
			break;
		}

		test_sleep(100);
	}

	st2 = tor2.status();
	if (!st2.is_seeding)
		fprintf(stderr, "ses2 failed to reconnect to ses1!\n");
	TEST_CHECK(st2.is_seeding);

	// this allows shutting down the sessions in parallel
	p1 = ses1.abort();
	p2 = ses2.abort();

	stop_udp_tracker();
	stop_web_server();
}

int test_main()
{
	using namespace libtorrent;

	// test with all kinds of proxies
	test_transfer();

	error_code ec;
	remove_all("tmp1_priorities", ec);
	remove_all("tmp2_priorities", ec);
	remove_all("tmp1_priorities_moved", ec);
	remove_all("tmp2_priorities_moved", ec);

	return 0;
}


text:
layout: default
---

# System-specific resources

Below are some useful resources for various popular systems. If you're unsure what you want to work on I recommend starting with a CHIP-8 tutorial, of which there are many (just Google it). After that, move to whatever system you want to. You don't need to "work your way up" to it or whatever as many seem to think. ([relevant thread](https://reddit.com/r/EmuDev/comments/8ve8lu/i_give_up_some_ramblings_of_someone_who_took_over/e1muyme/?context=3)). Just make sure you have the basics down first, remember to study the source code of existing emulators (super important) and if you get stuck, ask questions on our [discord](https://discordapp.gg/dkmJAes) or in the [emudev subreddit](https://reddit.com/r/EmuDev).

# Systems

## Multiple systems
- <https://www.zophar.net/documents.html>
- <http://emulator101.com>
- <http://hitmen.c02.at/index.html>
- <http://www.codeslinger.co.uk> (doesn't respond to https://, disable extensions such as HTTPS Everywhere if it doesn't load)
- <https://emudev.de>
- [Shonumi's blog](https://shonumi.github.io)
- [Shell-storm multi-architecture assembler and disassembler](http://shell-storm.org/online/Online-Assembler-and-Disassembler)
- [8bitworkshop IDE](https://8bitworkshop.com/redir.html)
- [240p test suite, supporting multiple systems](https://sourceforge.net/projects/testsuite240p/files/Sega_Genesis-MegaDrive-SegaCD_MegaCD)

## CHIP-8
- There are a lot of full tutorials on the Internet, so just searching "chip8 emulator tutorial" and looking for one in your language of choice should be enough if you're looking for a step-by-step guide
- If not, see the References below. There are usually no "full" tutorials for other systems, so it's challenging but more realistic and perhaps more helpful in the long run, assuming you'll want to move on to other systems after CHIP-8
- [High-level guide to making a CHIP-8 emulator](https://tobiasvl.github.io/blog/write-a-chip-8-emulator)
- References:
    - [CHIP-8 technical reference](https://github.com/mattmikolay/chip-8/wiki/CHIP%E2%80%908-Technical-Reference)
    - [CHIP-8 instruction set](https://github.com/mattmikolay/chip-8/wiki/CHIP%E2%80%908-Instruction-Set)
    - [Cowgod's Technical Reference](http://devernay.free.fr/hacks/chip8/C8TECH10.HTM) (doesn't respond to https://)
- Test ROMs:
    - BestCoder test:
        - [Description](https://cdn.discordapp.com/attachments/465586212804100106/482263582793531423/BC_test.txt)
        - [ROM](https://cdn.discordapp.com/attachments/465586212804100106/482263586547302426/BC_test.ch8)
    - <https://github.com/corax89/chip8-test-rom>
    - <https://github.com/metteo/chip8-test-rom>
    - <https://github.com/Skosulor/c8int/tree/master/test>
- Other resources:
    - [ROM compatibility issues](https://github.com/tomdaley92/Kiwi8/issues/9)
    - [Writing a CHIP-8 interpreter for the COSMAC ELF](https://cdn.discordapp.com/attachments/465586212804100106/482263592696152074/ELF_CHIP-8_Interpreter.pdf)
    - [COSMAC VIP manual](https://cdn.discordapp.com/attachments/465586212804100106/482263593753247744/VIP_Manual_Game_Manual_I.pdf)

## Bytepusher
- <https://esolangs.org/wiki/BytePusher>

## Pac-Man
- See [Z80 resources](#z80) below
- [Pac-Man emulation guide](https://www.lomont.org/software/games/pacman/PacmanEmulation.pdf)
- [Disassembly](http://cubeman.org/arcade-source/pacman.asm)

## Space Invaders
- See [8080 resources](#8080) below
- [SN76477N technical data](https://web.archive.org/web/20150425030455/http://www.emutalk.net/attachment.php?attachmentid=34143&d=1160668005)
- [General info on Space Invaders](http://www.brentradio.com/SpaceInvaders.htm)
- [Space Invaders disassembly and info](https://computerarcheology.com/Arcade/SpaceInvaders)
- [CPU tests](https://altairclone.com/downloads/cpu_tests) (need a CP/M implementation or to fake it to some extent, see CP/M section and [this Discord message](https://discord.com/channels/465585922579103744/466417993912680459/735434453228191794))

## CP/M
- See [8080 resources](#8080) below
- [General CP/M info](https://en.m.wikipedia.org/wiki/CP/M)
- [Zero page breakdown](https://en.m.wikipedia.org/wiki/Zero_page_(CP/M))
- [CP/M BDOS system calls](https://www.seasip.info/Cpm/bdos.html)
- [CP/M Programmer's Guide](https://cdn.discordapp.com/attachments/466417993912680459/735454519701536788/cpm3-pgr.pdf)
- [CP/M-86 System Guide](https://cdn.discordapp.com/attachments/466417993912680459/735455014100926544/CPM-86_System_Guide.pdf)

## Game Boy/Game Boy Color
- [Pandocs](https://gbdev.io/pandocs)
- [The Cycle-Accurate GB Docs](https://github.com/AntonioND/giibiiadvance/blob/master/docs/TCAGBD.pdf)
- [Opcode table](https://izik1.github.io/gbops/table/table.html)
- [List of GB opcodes and their behavior](https://rednex.github.io/rgbds/gbz80.7.html)
- [GB instruction decoding table](https://cdn.discordapp.com/attachments/465586075830845475/742438340078469150/SM83_decoding.pdf)
- [Decoding GB opcodes algorithmically](https://gb-archive.github.io/salvage/decoding_gbz80_opcodes/Decoding%20Gamboy%20Z80%20Opcodes.html)
- [A journey into GB emulation](https://robertovaccari.com/blog/2020_09_26_gameboy)
- [WIP tutorial on writing a GB emulator in Rust](https://rylev.github.io/DMG-01/public/book/)
- [GameBoy Emulator Development Guide](https://hacktix.github.io/GBEDG)
- Test ROMs:
    - [Blargg's test ROMs](https://github.com/retrio/gb-test-roms)
    - [Mooneye-gb test ROMs](https://github.com/Gekkio/mooneye-gb/tree/master/tests)
    - [dmg-acid (rendering test)](https://github.com/mattcurrie/dmg-acid2)
    - [cgb-acid (rendering test)](https://github.com/mattcurrie/cgb-acid2)
    - [PeterLemon's GB demos](https://github.com/PeterLemon/GB)
    - [Test ROM execution logs](https://github.com/wheremyfoodat/Gameboy-logs)
- [Bootrom disassembly](https://gist.github.com/6063288)
- [The Ultimate Game Boy Talk](https://youtu.be/HyzD8pNlpwI)
- [Other valuable resources](https://github.com/avivace/awesome-gbdev)
- [Notes by GhostSonic on GB sound emulation](https://www.reddit.com/r/EmuDev/comments/5gkwi5/gb_apu_sound_emulation/dat3zni)
- [Explanation of binary-coded decimals and the DAA instruction](https://ehaskins.com/2018-01-30%20Z80%20DAA)
- [Guide to the half-carry flag](https://robdor.com/2016/08/10/gameboy-emulator-half-carry-flag)

## Game Boy Advance
- See relevant [ARM resources](#arm) below (the ARM7TDMI used in the GBA implements ARMv4T)
- [GBATEK](https://problemkaputt.de/gbatek.htm)
- [no$gba](https://problemkaputt.de/gba.htm) (get the debug version)
- [TONC (GBA tutorial and demos)](https://www.coranac.com/projects/tonc)
- [Cycle counting on the GBA](https://mgba.io/2015/06/27/cycle-counting-prefetch)
- Test ROMs:
    - [Various test ROMs, including an archive of TONC binaries](https://github.com/shonumi/Emu-Docs/tree/master/GameBoy%20Advance/test_roms)
    - <https://github.com/destoer/armwrestler-gba-fixed>
    - <https://github.com/DenSinH/FuzzARM>
    - <https://github.com/jsmolka/gba-suite>
    - <https://github.com/destoer/gba_tests>
    - <https://github.com/PeterLemon/GBA>
    - <https://github.com/ladystarbreeze/gba-tests/tree/master/dma-test>
- [mGBA blog](https://mgba.io) (particularly the "development" and "emulation" tags)
- Homebrew development:
    - <https://rust-console.github.io/gba>
    - <https://patater.com/gbaguy/gbaasm.htm>

## Nintendo DS
- See relevant [ARM resources](#arm) below (the DS uses an ARM7TDMI and an ARM946E-S, implementing respectively ARMv4T and ARMv5TE)
- [GBATEK](https://problemkaputt.de/gbatek.htm)
- [Other docs](https://github.com/shonumi/Emu-Docs/tree/master/Nintendo%20DS)
- Test ROMs:
    - <https://github.com/mic-/armwrestler>
        - [Built ROM](https://cdn.discordapp.com/attachments/667132407262216272/732206968252661800/armwrestler.nds)
    - <https://github.com/Arisotura/arm7wrestler>
        - [Built ROM](https://cdn.discordapp.com/attachments/667132407262216272/732206999890165780/arm7wrestler.nds)
    - <https://tcrf.net/Aging_Card_NTR>
- [Sample homebrew programs](https://github.com/devkitPro/nds-examples)
- [Arisotura's blog](https://melonds.kuribo64.net) (uses self-signed certificate but works with https://)

## Nintendo 3DS
- See relevant [ARM resources](#arm) (the 3DS's ARM11 MPCore implements ARMv6K, not plain ARMv6, so you'll have to look at the ARMv7-AR manual too for the few additions; the ARM9 is the same as on the [Nintendo DS](#nintendo-ds))
- [GBATEK](https://problemkaputt.de/gbatek.htm)
- [The 3DBrew wiki](https://www.3dbrew.org/wiki/Main_Page)

## Nintendo Entertainment System
- See [65xx family resources](#65xx-family)
- [6502 instruction set reference](https://www.masswerk.at/6502/6502_instruction_set.html)
- [The NesDev wiki](https://wiki.nesdev.com)
- [NES emulator development guide](https://nesdev.com/NES%20emulator%20development%20guide.txt)
- [Overview of writing a NES emulator](https://yizhang82.dev/nes-emu-overview)
- [Articles on writing a NES emulator (among other things)](https://emudev.de/nes-emulator/overview)
- [Sample ROMs](https://github.com/PeterLemon/NES)

## Super Nintendo Entertainment System
- See [65xx family resources](#65xx-family)
- [fullsnes](https://problemkaputt.de/fullsnes.htm)
- [65c816 primer](https://softpixel.com/~cwright/sianse/docs/65816NFO.HTM)
- [YouTube playlist](https://www.youtube.com/playlist?list=PLHQ0utQyFw5KCcj1ljIhExH_lvGwfn6GV)
- [Adventures in Retro Development: SNES Edition](https://mynameismjp.wordpress.com/2019/01/14/adventures-in-retro-development-snes-edition) (focuses on homebrew development environment)
- [Anomie's SNES docs](https://www.romhacking.net/?page=documents&platform=9&author=548)
- [WIP Super Mario World disassembly](https://raw.githubusercontent.com/gnaghi/SMWDisC/master/SMWDisC.txt)
- [SNES development wiki](https://wiki.superfamicom.org):
    - [65c816 CPU reference](https://wiki.superfamicom.org/65816-reference)
    - [SPC-700 APU reference](https://wiki.superfamicom.org/spc700-reference)
    - [Capcom Cx4 coprocessor docs](https://wiki.superfamicom.org/capcom-cx4-hitachi-hg51b169)
- Test ROMs:
    - <https://github.com/PeterLemon/SNES>
    - [Blargg's SPC SNES test ROMs](https://forums.nesdev.com/viewtopic.php?f=12&t=18005)
    - [More of Blargg's SNES test ROMs](https://web.archive.org/web/20150601173734/http://blargg.8bitalley.com/parodius/snes-tests)
- [SNES sprite engine design guidelines](https://megacatstudios.com/blogs/retro-development/snes-sprite-engine-design-guidelines)
- [SNES programming book](https://en.wikibooks.org/wiki/Super_NES_Programming)
    - [Super FX tutorial](https://en.wikibooks.org/wiki/Super_NES_Programming/Super_FX_tutorial)

## Nintendo Virtual Boy
- <https://files.virtual-boy.com/download/978651/stsvb.html>

## Nintendo 64
- See [MIPS resources](#mips)
- [Notes and resources](https://github.com/Dillonb/n64-resources)
- [Development resources](https://ultra64.ca/resources/documentation)
- [Info on the N64's boot code](https://www.retroreversing.com/n64bootcode)
- [Test ROMs](https://github.com/PeterLemon/N64)
- [Fork of the above test ROMs, with a few more ones](https://github.com/fraser125/N64) (significantly outdated)
- [RSP docs](https://github.com/rasky/r64emu/blob/master/doc/rsp.md)
- [Other resources](https://n64.dev)

## Nintendo GameCube
- See [PowerPC resources](#powerpc)
- <https://www.gc-forever.com/yagcd>
- [GameCube resources GitHub repository](https://github.com/DenSinH/GameCubeResources)

## PlayStation 1
- See [MIPS resources](#mips)
- [Guide to writing a PSX emulator](https://github.com/simias/psx-guide)
    - [Rendered](https://cdn.discordapp.com/attachments/492036343376117778/492037613721616406/guide.PDF)
- [psx-spx](https://problemkaputt.de/psx-spx.htm)
- [PSX reverse engineering project](https://github.com/ogamespec/psxdev/tree/master/reverse)
- [BIOS info](http://wiki.psxdev.ru/index.php/BIOS)
    - [Translated](https://translate.google.com/translate?sl=auto&tl=en&u=http://wiki.psxdev.ru/index.php/BIOS)
- [The PSX GPU texture pipeline and how to emulate it](https://www.reddit.com/r/EmuDev/comments/fmhtcn)
- [PSX EXE header](http://www.emulatronia.com/doctec/consolas/psx/exeheader.txt) (also see "CDROM File Formats" section in psx-spx)
- [PSX system software reverse engineering project](https://github.com/ogamespec/psxdev/tree/master/reverse)
- [Other PSX documentation (including a CPU reference manual)](http://hitmen.c02.at/html/psx_docs.html)
- [PSX GTE docs/reverse engineering](https://github.com/ogamespec/pops-gte)
- [PSX MDEC & CD-ROM info](https://github.com/m35/jpsxdec/blob/readme/jpsxdec/PlayStation1_STR_format.txt)
- [Dithering on the PSX](https://www.youtube.com/watch?v=3XDyQnY5GHI)
- [PlayStation emulator development info](https://drhell.web.fc2.com/ps1/index.html)
    - [Translated](https://translate.google.com/translate?sl=auto&tl=en&u=http%3A%2F%2Fdrhell.web.fc2.com%2Fps1%2Findex.html)
- Test ROMs:
    - [Amidog's tests](https://emulation.gametechwiki.com/index.php/PS1_Tests)
    - <https://github.com/PeterLemon/PSX>
    - <https://github.com/JaCzekanski/ps1-tests>
    - <https://github.com/simias/psx-hardware-tests/tree/master/tests>
    - [PSX demos](https://www.pouet.net/prodlist.php?order=thumbup&platform%5B0%5D=Playstation&page=1)

## PlayStation 2
- See [MIPS resources](#mips)
- [PS2TEK](https://psi-rockin.github.io/ps2tek)
- [PS2 docs](https://web.archive.org/web/20191102085229/https://hwdocs.webs.com/ps2)
- [PS2 unofficial clang erratum](https://github.com/ZirconiumX/ps2-clang-patches/blob/master/erratum/unofficial-erratum.md)
- [GS Mode Selector](https://web.archive.org/web/20191111013442/https://psx-scene.com/forums/f291/gs-mode-selector-development-feedback-61808)
- [PS2 busses](https://web.archive.org/web/20191112223653/https://assemblergames.com/threads/the-playstation-2-busses-dev9.67961)

## Sega Game Gear
- [VDP test ROM](https://www.retrorgb.com/game-gear-vdp-test-software.html)
- [Button test ROM](https://github.com/GameGearSamples/ButtonTest)
- [Krom's demos](https://github.com/PeterLemon/GG)

## Sega Master System
- See [Z80 resources](#z80) below
- [SMS info](https://www.smspower.org/Development)
    - [BIOS documentation](https://www.smspower.org/Development/BIOSes)
    - [Memory map](https://www.smspower.org/Development/MemoryMap)
    - [Z80 info](https://www.smspower.org/Development/Z80-Index)
    - [Video Hardware](https://www.smspower.org/Development/VDPRegisters)
    - [Sound Hardware](https://www.smspower.org/Development/SN76489)
- Test ROMs:
    - [Homebrew test cases](https://www.smspower.org/Homebrew/NotOnlyWords-SMS)
    - [ZEXALL test ROM](https://www.smspower.org/Homebrew/ZEXALL-SMS) (doesn't require any hardware, it can log to an IO port)
    - [PeterLemon's SMS demos](https://github.com/PeterLemon/SMS)
    - [VDP test ROM](https://www.smspower.org/Homebrew/SMSVDPTest-SMS)
    - [WIP test suite](https://github.com/sverx/SMSTestSuite)

## Sega Genesis/Mega Drive
- See [Z80](#z80) and [m68k](#m68k) resources below
- [Collection of docs](https://segaretro.org/Mega_Drive_official_documentation)
- [CPU test ROM](https://github.com/flamewing/68k-bcd-verifier)
- [VDP test ROM](http://gendev.spritesmind.net/forum/viewtopic.php?f=8&t=1585)
- [Development tools list](http://techdocs.exodusemulator.com/Console/SegaMegaDrive/Software.html)

## Sega Saturn
- [SH-2 programming manual](https://antime.kapsi.fi/sega/files/h12p0.pdf)
- [GAM1 test ROM, harnessing most hardware](https://segaxtreme.net/threads/sega-saturn-sample-by-sega.24264)
- Misc homebrew:
    - <http://www.rockin-b.de/saturn.html>
    - <https://reddit.com/r/SegaSaturn/comments/223cdp/best_saturn_homebrews_available_atm>

## Commodore 64
- See 6502 resources in the [65xx family section](#65xx-family) (the C64 uses a 6510)
- [MCS6500 family programming manual](http://archive.6502.org/books/mcs6500_family_programming_manual.pdf) (doesn't respond to https://)
- [C64 wiki](https://www.c64-wiki.com)
- [VICE test ROMs](https://vice-emu.pokefinder.org/index.php/Testbench)
- [SID manual](http://archive.6502.org/datasheets/mos_6581_sid.pdf) (doesn't respond to https://)
- [C64 assembly language programming](https://www.retro-programming.de)
    - [Translated](https://translate.google.com/translate?sl=auto&tl=en&u=https%3A%2F%2Fwww.retro-programming.de)
- [Scanline missing cycles](http://www.antimon.org/dl/c64/code/missing.txt)
- [Opening the borders](http://www.antimon.org/dl/c64/code/opening.txt)
- [Info on the VIC-II](http://www.zimmers.net/cbmpics/cbm/c64/vic-ii.txt)
- [SID info](http://www.oxyron.de/html/registers_sid.html) (doesn't respond to https://)
- Programming the C64's SID:
    - [Part 1](https://www.atarimagazines.com/compute/issue49/424_1_Programming_64_Sound.php)
    - [Part 2](https://www.atarimagazines.com/compute/issue50/277_1_Programming_64_Sound.php)
- [6502 decimal mode](https://www.atarimagazines.com/compute/issue50/268_1_MACHINE_LANGUAGE.php)
- [The Commodore 64 Music Book](https://archive.org/details/The_Commodore_64_Music_Book)
- [C64 user's guide (start of sound chapter)](https://archive.org/details/Commodore_64_Users_Guide_1984_Commodore/page/n87)

## Mac
- See [m68k](#m68k)/[PowerPC](#powerpc) resources below
- [Apple's guide to the macintosh family hardware](https://archive.org/details/apple-guide-macintosh-family-hardware) (400 MB pdf)

## MSX
- See [Z80 resources](#z80) below
- [Test ROMs](https://github.com/PeterLemon/MSX)

## ZX Spectrum
- <https://spectrumforeveryone.com/technical>
- <https://worldofspectrum.org/faq/resources/documents.htm>
- [Krom's demos](https://github.com/PeterLemon/ZXSpectrum)

## Amiga
- [Info on the Amiga and "Another World"](https://fabiensanglard.net/another_world_polygons_amiga500/index.html)

## Xbox
- [Xbox architecture](https://www.copetti.org/projects/consoles/xbox)

## Neo Geo
- [Development wiki](https://wiki.neogeodev.org/index.php?title=Main_Page) (has overviews of every piece of hardware)
- [Sample ROMs](https://github.com/PeterLemon/NEO-GEO)

## Pokémon Mini
- <https://www.pokemon-mini.net/documentation>

## Tamagotchi
- [Tech specs and resources](https://tama.loociano.com)
- [ROM dump and reverse engineering](https://hackaday.com/2013/05/24/tamagotchi-rom-dump-and-reverse-engineering)
        - [Archive of linked article](https://web.archive.org/web/20180831183942/https://www.kwartzlab.ca/2013/05/first-glimpse-soul-tamagotchi)
        - [ROM dump GitHub repository](https://github.com/natashenka/Tamagotchi-Hack/tree/master/codedump)

# Processors and architectures

## 65xx family
- [Programming manual](https://wiki.nesdev.com/w/images/7/76/Programmanual.pdf)
- [6502 decimal mode](https://www.atarimagazines.com/compute/issue50/268_1_MACHINE_LANGUAGE.php)

## 8080
- [8080 tutorial (among other things)](http://emulator101.com)
- [Assembly programming manual](https://altairclone.com/downloads/manuals/8080%20Programmers%20Manual.pdf)
- [Datasheet](https://altairclone.com/downloads/manuals/8080%20Data%20Sheet.pdf)
- [Instruction table](https://tobiasvl.github.io/optable/intel-8080/classic)
- [Loading test ROMs that require a CP/M implementation/stub](https://discord.com/channels/465585922579103744/466417993912680459/735434453228191794)

## Z80
- [Z80 CPU User Manual](https://www.zilog.com/force_download.php?filepath=YUhSMGNEb3ZMM2QzZHk1NmFXeHZaeTVqYjIwdlpHOWpjeTk2T0RBdlZVMHdNRGd3TG5Ca1pnPT0=)
- [Z80 heaven](http://z80-heaven.wikidot.com)
- [Z80 instruction table](http://clrhome.org/table)
- [The undocumented Z80 documented](http://www.z80.info/zip/z80-documented.pdf)
- [Z80 undocumented behavior](https://baltazarstudios.com/zilog-z80-undocumented-behavior)
- [Z80 undocumented instructions](http://www.z80.info/z80undoc.htm)
- [Z80 test ROMs](https://github.com/superzazu/z80/tree/master/roms)
- [Loading test ROMs that require a CP/M implementation/stub](https://discord.com/channels/465585922579103744/466417993912680459/735434453228191794)

## m68k
- [Instruction set reference](http://wpage.unina.it/rcanonic/didattica/ce1/docs/68000.pdf) (just a summary for each instruction, doesn't respond to https://)
- [Programmer's reference manual](https://www.nxp.com/files-static/archives/doc/ref_manual/M68000PRM.pdf)

## PowerPC
- [IBM's PowerPC Architecture Book](https://www.ibm.com/developerworks/systems/library/es-archguide-v2.html)

## ARM
- [ARM instruction set info for the ARM7TDMI-S](https://vision.gel.ulaval.ca/~jflalonde/cours/1001/h17/docs/arm-instructionset.pdf) (not the full document, which apparently can't be found anymore)
- [ARM7TDMI datasheet](https://www.dwedit.org/files/ARM7TDMI.pdf) (contains info about ARM and thumb instruction sets)
- [ARM7TDMI Technical Reference Manual](https://documentation-service.arm.com/static/5f4786a179ff4c392c0ff819)
- [ARM7TDMI-S Technical Reference Manual](https://documentation-service.arm.com/static/5e8e13a9fd977155116a3368) (doesn't contain instruction descriptions, but has info on timing)
- [ARMv5TE Reference Manual](https://cdn.discordapp.com/attachments/667132407262216272/733255145495986246/ARMv5TE_reference_manual.pdf) (contains a few corrections to the original documents)
- [ARM9E-S Technical Reference Manual](https://documentation-service.arm.com/static/5e8e2f18fd977155116a77fb) (contains info on timing that applies to all ARM9\*E-S processors)
- [ARM946E-S Technical Reference Manual](https://documentation-service.arm.com/static/5f032835cafe527e86f5b8ad)
- [ARMv6 Reference Manual](https://documentation-service.arm.com/static/5f1060400daa596235e7a60a)
- [ARMv7-A/R Reference Manual](https://documentation-service.arm.com/static/5f1074ce0daa596235e834b5)
- [ARM11 MPCore Technical Reference Manual](https://documentation-service.arm.com/static/5e8e1e0388295d1e18d368b2)

## x86
- [8086 family user's manual](https://edge.edx.org/c4x/BITSPilani/EEE231/asset/8086_family_Users_Manual_1_.pdf)
- [Intel® 64 and IA-32 manuals](https://software.intel.com/content/www/us/en/develop/articles/intel-sdm.html)
- [8086/80186 test ROM](https://cdn.discordapp.com/attachments/466418871210082325/708247243072733255/test186.zip)
- [Felix Cloutier's x86 and AMD64 instruction reference](https://www.felixcloutier.com/x86)
- [Agner Fog's software optimization resources](https://www.agner.org/optimize)

## MIPS
- [MIPS64 Instruction Set Reference Manual](https://s3-eu-west-1.amazonaws.com/downloads-mips/documents/MD00087-2B-MIPS64BIS-AFP-6.06.pdf)
- [IDT R30xx Family Software Reference Manual](https://cgi.cse.unsw.edu.au/~cs3231/doc/R3000.pdf) (PS1 CPU, PS2 IOP)
- [VR43xx CPU manual](http://datasheets.chipdb.org/NEC/Vr-Series/Vr43xx/U10504EJ7V0UMJ1.pdf) (Nintendo 64, doesn't respond with the correct file using https://)

## Itanium
- [Itanium Architecture Software Developer's Manual](https://cdn.discordapp.com/attachments/698838582181363752/805813408309837904/itanium-architecture-vol-1-2-3-4-reference-set-manual.pdf) ([original](https://www.intel.com/content/dam/doc/manual/itanium-architecture-vol-1-2-3-4-reference-set-manual.pdf))
- [Itanium System Abstraction Layer Specification](https://cdn.discordapp.com/attachments/698838582181363752/805813867694653500/itanium-system-abstraction-layer-specification.pdf) ([original](https://www.intel.com/content/dam/www/public/us/en/documents/specification-updates/itanium-system-abstraction-layer-specification.pdf))
- [460GX Chipset Developer's Manual](https://cdn.discordapp.com/attachments/698838582181363752/805814367097716766/460gx.pdf) ([original](https://www.manualslib.com/manual/77665/Intel-460gx.html))
- [Intel® E8870IO Server I/O Hub Datasheet](https://cdn.discordapp.com/attachments/698838582181363752/805814970977747015/e8870io-server-io-hub-datasheet.pdf) ([original](https://www.intel.com/content/dam/doc/datasheet/e8870io-server-io-hub-datasheet.pdf))
- [Intel® E8870 SNC Datasheet](https://cdn.discordapp.com/attachments/698838582181363752/805815757861945344/e8870-snc-datasheet.pdf) ([original](https://pccomponents.com/datasheets/INTEL-251112.PDF))

redpajama_set_name: RedPajamaGithub


text:
// Skip tslint any type check cause this method is aiming to check type of
// input.
// tslint:disable-next-line:no-any
export function isLocalPath(source: any): boolean {
  return (typeof source === 'string') && source.slice(0, 7) === 'file://';
}


text:
<?php

namespace Mistress\Http\Controllers\Sub;

use Auth;
use Flash;
use Input;
use Mistress\Http\Controllers\Controller;
use Mistress\Rule;
use Redirect;
use Response;

class RuleController extends Controller
{

    public function __construct()
    {
        $this->middleware('auth');
        $this->middleware('sub_only');
    }

    /**
     * Display a listing of the resource.
     *
     * @return Response
     */
    public function index()
    {
        $rules = Auth::user()->rules;
        return view('sub.rule.index', compact('rules'));
    }

    /**
     * Display the specified resource.
     *
     * @param  Rule $rule
     * @return Response
     */
    public function show(Rule $rule)
    {
        return view('sub.rule.show', compact('rule'));
    }
}


text:
<?php

namespace Sonata\CacheAltBundle\Tests\Cache;

use Sonata\CacheAltBundle\Adapter\ApcCache;
use Symfony\Component\Routing\RouterInterface;
use Sonata\CacheAltBundle\Cache\CacheElement;

class ApcCacheTest extends \PHPUnit_Framework_TestCase
{
    public function setUp()
    {
        if (!function_exists('apc_store')) {
            $this->markTestSkipped('APC is not installed');
        }

        if (ini_get('apc.enable_cli') == 0) {
            $this->markTestSkipped('APC is not enabled in cli, please add apc.enable_cli=On into the apc.ini file');
        }
    }

    public function testInitCache()
    {
        $router = $this->getMock('Symfony\Component\Routing\RouterInterface');

        $cache = new ApcCache($router, 'token', 'prefix_', array());

        $this->assertTrue($cache->flush(array()));
        $this->assertTrue($cache->flushAll());

        $cacheElement = $cache->set(array('id' => 7), 'data');

        $this->assertInstanceOf('Sonata\CacheAltBundle\Cache\CacheElement', $cacheElement);

        $this->assertTrue($cache->has(array('id' => 7)));

        $this->assertFalse($cache->has(array('id' => 8)));

        $cacheElement = $cache->get(array('id' => 7));

        $this->assertInstanceOf('Sonata\CacheAltBundle\Cache\CacheElement', $cacheElement);
    }
}


text:
<?php

namespace Github\Api\Repository;

use Github\Api\AbstractApi;
use Github\Exception\MissingArgumentException;

/**
 * @link   http://developer.github.com/v3/issues/labels/
 * @author Joseph Bielawski <stloyd@gmail.com>
 */
class Labels extends AbstractApi
{
    public function all($username, $repository)
    {
        return $this->get('repos/'.urlencode($username).'/'.urlencode($repository).'/labels');
    }

    public function show($username, $repository, $label)
    {
        return $this->get('repos/'.urlencode($username).'/'.urlencode($repository).'/labels/'.urlencode($label));
    }

    public function create($username, $repository, array $params)
    {
        if (!isset($params['name'], $params['color'])) {
            throw new MissingArgumentException(array('name', 'color'));
        }

        return $this->post('repos/'.urlencode($username).'/'.urlencode($repository).'/labels', $params);
    }

    public function update($username, $repository, $label, array $params)
    {
        if (!isset($params['name'], $params['color'])) {
            throw new MissingArgumentException(array('name', 'color'));
        }

        return $this->patch('repos/'.urlencode($username).'/'.urlencode($repository).'/labels/'.urlencode($label), $params);
    }

    public function remove($username, $repository, $label)
    {
        return $this->delete('repos/'.urlencode($username).'/'.urlencode($repository).'/labels/'.urlencode($label));
    }
}


text:
package com.orientechnologies.orient.core.metadata.schema;

import static org.testng.AssertJUnit.assertEquals;

import java.io.Externalizable;
import java.io.IOException;
import java.io.ObjectInput;
import java.io.ObjectOutput;
import java.io.Serializable;
import java.math.BigDecimal;
import java.math.BigInteger;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;

import org.testng.annotations.Test;

import com.orientechnologies.orient.core.db.record.OIdentifiable;
import com.orientechnologies.orient.core.db.record.ORecordLazyList;
import com.orientechnologies.orient.core.db.record.ORecordLazyMap;
import com.orientechnologies.orient.core.db.record.ORecordLazySet;
import com.orientechnologies.orient.core.db.record.OTrackedList;
import com.orientechnologies.orient.core.db.record.OTrackedMap;
import com.orientechnologies.orient.core.db.record.OTrackedSet;
import com.orientechnologies.orient.core.db.record.ridbag.ORidBag;
import com.orientechnologies.orient.core.exception.OSerializationException;
import com.orientechnologies.orient.core.id.ORecordId;
import com.orientechnologies.orient.core.record.ORecord;
import com.orientechnologies.orient.core.record.impl.ODocument;
import com.orientechnologies.orient.core.record.impl.ODocumentInternal;
import com.orientechnologies.orient.core.serialization.ODocumentSerializable;
import com.orientechnologies.orient.core.serialization.OSerializableStream;
import com.orientechnologies.orient.core.type.tree.OMVRBTreeRIDSet;

public class TestOTypeDetection {

  public class CustomClass implements OSerializableStream {

    @Override
    public byte[] toStream() throws OSerializationException {
      return null;
    }

    @Override
    public OSerializableStream fromStream(byte[] iStream) throws OSerializationException {
      return null;
    }

  }

  public class DocumentSer implements ODocumentSerializable {

    @Override
    public ODocument toDocument() {
      // TODO Auto-generated method stub
      return null;
    }

    @Override
    public void fromDocument(ODocument document) {
      // TODO Auto-generated method stub

    }

  }

  public class ClassSerializable implements Serializable {
    private String aaa;

  }

  @Test
  public void testOTypeFromClass() {

    assertEquals(OType.BOOLEAN, OType.getTypeByClass(Boolean.class));

    assertEquals(OType.BOOLEAN, OType.getTypeByClass(Boolean.TYPE));

    assertEquals(OType.LONG, OType.getTypeByClass(Long.class));

    assertEquals(OType.LONG, OType.getTypeByClass(Long.TYPE));

    assertEquals(OType.INTEGER, OType.getTypeByClass(Integer.class));

    assertEquals(OType.INTEGER, OType.getTypeByClass(Integer.TYPE));

    assertEquals(OType.SHORT, OType.getTypeByClass(Short.class));

    assertEquals(OType.SHORT, OType.getTypeByClass(Short.TYPE));

    assertEquals(OType.FLOAT, OType.getTypeByClass(Float.class));

    assertEquals(OType.FLOAT, OType.getTypeByClass(Float.TYPE));

    assertEquals(OType.DOUBLE, OType.getTypeByClass(Double.class));

    assertEquals(OType.DOUBLE, OType.getTypeByClass(Double.TYPE));

    assertEquals(OType.BYTE, OType.getTypeByClass(Byte.class));

    assertEquals(OType.BYTE, OType.getTypeByClass(Byte.TYPE));

    assertEquals(OType.STRING, OType.getTypeByClass(Character.class));

    assertEquals(OType.STRING, OType.getTypeByClass(Character.TYPE));

    assertEquals(OType.STRING, OType.getTypeByClass(String.class));

    // assertEquals(OType.BINARY, OType.getTypeByClass(Byte[].class));

    assertEquals(OType.BINARY, OType.getTypeByClass(byte[].class));

    assertEquals(OType.DATETIME, OType.getTypeByClass(Date.class));

    assertEquals(OType.DECIMAL, OType.getTypeByClass(BigDecimal.class));

    assertEquals(OType.INTEGER, OType.getTypeByClass(BigInteger.class));

    assertEquals(OType.LINK, OType.getTypeByClass(OIdentifiable.class));

    assertEquals(OType.LINK, OType.getTypeByClass(ORecordId.class));

    assertEquals(OType.LINK, OType.getTypeByClass(ORecord.class));

    assertEquals(OType.LINK, OType.getTypeByClass(ODocument.class));

    assertEquals(OType.EMBEDDEDLIST, OType.getTypeByClass(ArrayList.class));

    assertEquals(OType.EMBEDDEDLIST, OType.getTypeByClass(List.class));

    assertEquals(OType.EMBEDDEDLIST, OType.getTypeByClass(OTrackedList.class));

    assertEquals(OType.EMBEDDEDSET, OType.getTypeByClass(Set.class));

    assertEquals(OType.EMBEDDEDSET, OType.getTypeByClass(HashSet.class));

    assertEquals(OType.EMBEDDEDSET, OType.getTypeByClass(OTrackedSet.class));

    assertEquals(OType.EMBEDDEDMAP, OType.getTypeByClass(Map.class));

    assertEquals(OType.EMBEDDEDMAP, OType.getTypeByClass(HashMap.class));

    assertEquals(OType.EMBEDDEDMAP, OType.getTypeByClass(OTrackedMap.class));

    assertEquals(OType.LINKSET, OType.getTypeByClass(OMVRBTreeRIDSet.class));

    assertEquals(OType.LINKSET, OType.getTypeByClass(ORecordLazySet.class));

    assertEquals(OType.LINKLIST, OType.getTypeByClass(ORecordLazyList.class));

    assertEquals(OType.LINKMAP, OType.getTypeByClass(ORecordLazyMap.class));

    assertEquals(OType.LINKBAG, OType.getTypeByClass(ORidBag.class));

    assertEquals(OType.CUSTOM, OType.getTypeByClass(OSerializableStream.class));

    assertEquals(OType.CUSTOM, OType.getTypeByClass(CustomClass.class));

    assertEquals(OType.EMBEDDEDLIST, OType.getTypeByClass(Object[].class));

    assertEquals(OType.EMBEDDEDLIST, OType.getTypeByClass(String[].class));

    assertEquals(OType.EMBEDDED, OType.getTypeByClass(ODocumentSerializable.class));

    assertEquals(OType.EMBEDDED, OType.getTypeByClass(DocumentSer.class));

    assertEquals(OType.CUSTOM, OType.getTypeByClass(ClassSerializable.class));

  }

  @Test
  public void testOTypeFromValue() {

    assertEquals(OType.BOOLEAN, OType.getTypeByValue(true));

    assertEquals(OType.LONG, OType.getTypeByValue(2L));

    assertEquals(OType.INTEGER, OType.getTypeByValue(2));

    assertEquals(OType.SHORT, OType.getTypeByValue((short) 4));

    assertEquals(OType.FLOAT, OType.getTypeByValue(0.5f));

    assertEquals(OType.DOUBLE, OType.getTypeByValue(0.7d));

    assertEquals(OType.BYTE, OType.getTypeByValue((byte) 10));

    assertEquals(OType.STRING, OType.getTypeByValue('a'));

    assertEquals(OType.STRING, OType.getTypeByValue("yaaahooooo"));

    assertEquals(OType.BINARY, OType.getTypeByValue(new byte[] { 0, 1, 2 }));

    assertEquals(OType.DATETIME, OType.getTypeByValue(new Date()));

    assertEquals(OType.DECIMAL, OType.getTypeByValue(new BigDecimal(10)));

    assertEquals(OType.INTEGER, OType.getTypeByValue(new BigInteger("20")));

    assertEquals(OType.LINK, OType.getTypeByValue(new ODocument()));

    assertEquals(OType.LINK, OType.getTypeByValue(new ORecordId()));

    assertEquals(OType.EMBEDDEDLIST, OType.getTypeByValue(new ArrayList<Object>()));

    assertEquals(OType.EMBEDDEDLIST, OType.getTypeByValue(new OTrackedList<Object>(new ODocument())));

    assertEquals(OType.EMBEDDEDSET, OType.getTypeByValue(new HashSet<Object>()));

    assertEquals(OType.EMBEDDEDMAP, OType.getTypeByValue(new HashMap<Object, Object>()));

    assertEquals(OType.LINKSET, OType.getTypeByValue(new ORecordLazySet(new ODocument())));

    assertEquals(OType.LINKLIST, OType.getTypeByValue(new ORecordLazyList(new ODocument())));

    assertEquals(OType.LINKMAP, OType.getTypeByValue(new ORecordLazyMap(new ODocument())));

    assertEquals(OType.LINKBAG, OType.getTypeByValue(new ORidBag()));

    assertEquals(OType.CUSTOM, OType.getTypeByValue(new CustomClass()));

    assertEquals(OType.EMBEDDEDLIST, OType.getTypeByValue(new Object[] {}));

    assertEquals(OType.EMBEDDEDLIST, OType.getTypeByValue(new String[] {}));

    assertEquals(OType.EMBEDDED, OType.getTypeByValue(new DocumentSer()));

    assertEquals(OType.CUSTOM, OType.getTypeByValue(new ClassSerializable()));
  }

  @Test
  public void testOTypeFromValueInternal() {
    Map<String, ORecordId> linkmap = new HashMap<String, ORecordId>();
    linkmap.put("some", new ORecordId());
    assertEquals(OType.LINKMAP, OType.getTypeByValue(linkmap));

    Map<String, ORecord> linkmap2 = new HashMap<String, ORecord>();
    linkmap2.put("some", new ODocument());
    assertEquals(OType.LINKMAP, OType.getTypeByValue(linkmap2));

    List<ORecordId> linkList = new ArrayList<ORecordId>();
    linkList.add(new ORecordId());
    assertEquals(OType.LINKLIST, OType.getTypeByValue(linkList));

    List<ORecord> linkList2 = new ArrayList<ORecord>();
    linkList2.add(new ODocument());
    assertEquals(OType.LINKLIST, OType.getTypeByValue(linkList2));

    Set<ORecordId> linkSet = new HashSet<ORecordId>();
    linkSet.add(new ORecordId());
    assertEquals(OType.LINKSET, OType.getTypeByValue(linkSet));

    Set<ORecord> linkSet2 = new HashSet<ORecord>();
    linkSet2.add(new ODocument());
    assertEquals(OType.LINKSET, OType.getTypeByValue(linkSet2));

    ODocument document = new ODocument();
    ODocumentInternal.addOwner(document, new ODocument());
    assertEquals(OType.EMBEDDED, OType.getTypeByValue(document));
  }

}


text:
import { getJSONFixture } from 'helpers/fixtures';
import * as getters from '~/pipelines/stores/test_reports/getters';
import { iconForTestStatus, formattedTime } from '~/pipelines/stores/test_reports/utils';

describe('Getters TestReports Store', () => {
  let state;

  const testReports = getJSONFixture('pipelines/test_report.json');

  const defaultState = {
    testReports,
    selectedSuiteIndex: 0,
  };

  const emptyState = {
    testReports: {},
    selectedSuite: null,
  };

  beforeEach(() => {
    state = {
      testReports,
    };
  });

  const setupState = (testState = defaultState) => {
    state = testState;
  };

  describe('getTestSuites', () => {
    it('should return the test suites', () => {
      setupState();

      const suites = getters.getTestSuites(state);
      const expected = testReports.test_suites.map(x => ({
        ...x,
        formattedTime: formattedTime(x.total_time),
      }));

      expect(suites).toEqual(expected);
    });

    it('should return an empty array when testReports is empty', () => {
      setupState(emptyState);

      expect(getters.getTestSuites(state)).toEqual([]);
    });
  });

  describe('getSelectedSuite', () => {
    it('should return the selected suite', () => {
      setupState();

      const selectedSuite = getters.getSelectedSuite(state);
      const expected = testReports.test_suites[state.selectedSuiteIndex];

      expect(selectedSuite).toEqual(expected);
    });
  });

  describe('getSuiteTests', () => {
    it('should return the test cases inside the suite', () => {
      setupState();

      const cases = getters.getSuiteTests(state);
      const expected = testReports.test_suites[0].test_cases.map(x => ({
        ...x,
        formattedTime: formattedTime(x.execution_time),
        icon: iconForTestStatus(x.status),
      }));

      expect(cases).toEqual(expected);
    });

    it('should return an empty array when testReports is empty', () => {
      setupState(emptyState);

      expect(getters.getSuiteTests(state)).toEqual([]);
    });
  });
});


text:
package org.apereo.cas.authentication.policy;

import org.apereo.cas.authentication.Authentication;
import org.apereo.cas.authentication.AuthenticationHandler;
import org.apereo.cas.authentication.AuthenticationPolicyExecutionResult;

import com.fasterxml.jackson.annotation.JsonTypeInfo;
import lombok.AllArgsConstructor;
import lombok.EqualsAndHashCode;
import lombok.Getter;
import lombok.NoArgsConstructor;
import lombok.Setter;
import lombok.extern.slf4j.Slf4j;
import lombok.val;
import org.springframework.context.ConfigurableApplicationContext;

import java.io.Serial;
import java.io.Serializable;
import java.util.Optional;
import java.util.Set;

/**
 * Authentication policy that is satisfied by at least one successfully authenticated credential.
 *
 * @author Marvin S. Addison
 * @since 4.0.0
 */
@Slf4j
@JsonTypeInfo(use = JsonTypeInfo.Id.CLASS)
@NoArgsConstructor(force = true)
@EqualsAndHashCode(callSuper = true)
@Setter
@Getter
@AllArgsConstructor
public class AtLeastOneCredentialValidatedAuthenticationPolicy extends BaseAuthenticationPolicy {

    @Serial
    private static final long serialVersionUID = -7484490540437793931L;

    /**
     * Flag to try all credentials before policy is satisfied. Defaults to {@code false}.
     */
    private final boolean tryAll;

    @Override
    public AuthenticationPolicyExecutionResult isSatisfiedBy(final Authentication authn,
                                                             final Set<AuthenticationHandler> authenticationHandlers,
                                                             final ConfigurableApplicationContext applicationContext,
                                                             final Optional<Serializable> assertion) throws Exception {
        if (this.tryAll) {
            val match = authenticationHandlers.stream()
                .allMatch(handler -> authn.getSuccesses().containsKey(handler.getName()));
            if (!match) {
                LOGGER.warn("Authentication handlers qualified to handle this transaction, [{}], "
                            + "have not all completed a successful authentication event. Successful "
                            + "authentication events recorded currently are [{}]",
                    authenticationHandlers, authn.getSuccesses().keySet());
                return AuthenticationPolicyExecutionResult.failure();
            }
            LOGGER.debug("Authentication policy is satisfied with all authentication transactions");
            return AuthenticationPolicyExecutionResult.success(!authn.getSuccesses().isEmpty());
        }
        if (!authn.getSuccesses().isEmpty()) {
            LOGGER.debug("Authentication policy is satisfied having found at least one authentication transactions");
            return AuthenticationPolicyExecutionResult.success();
        }
        LOGGER.warn("Authentication policy has failed to find a successful authentication transaction");
        return AuthenticationPolicyExecutionResult.failure();
    }
}


text:
import Ember from 'ember';

export default Ember.Controller.extend({
	init: function () {
		var self = this;
		window.setInterval(function () {
			if (self.get('model')) {
				self.set('model.currentDate', new Date());
			}
		}, 1000);
		return this._super();
	}
});


text:
const {difference, prettyPrint} = require('../../flowResult');

const {default: simpleDiffAssertion} = require('./simpleDiffAssertion');

import type {AssertionLocation, ErrorAssertion} from './assertionTypes';

function newErrors(
  expected: string,
  assertLoc: ?AssertionLocation,
): ErrorAssertion {
  return (reason: ?string, env) => {
    const diff = difference(env.getNewErrors(), env.getOldErrors());
    const actual = prettyPrint(diff);

    let suggestion = {method: 'noNewErrors', args: []};
    if (!diff.passed) {
      suggestion = {
        method: 'newErrors',
        args: [prettyPrint(diff)],
      };
    }
    return simpleDiffAssertion(
      expected,
      actual,
      assertLoc,
      reason,
      'new errors',
      suggestion,
    );
  };
}

module.exports = {
  default: newErrors,
};


text:
package eu.monnetproject.coal;

import java.io.File;
import java.io.InputStream;

import eu.monnetproject.align.Alignment;
import eu.monnetproject.align.AlignmentSerializer;
import eu.monnetproject.ontology.OntologySerializer;
import java.io.Reader;

public interface CoalReader {

	public Alignment readAlignment(File file, AlignmentSerializer alignmentSerializer, OntologySerializer ontoSerializer);

	public Alignment readAlignment(InputStream stream, AlignmentSerializer alignmentSerializer, OntologySerializer ontoSerializer);

        public Alignment readAlignment(Reader reader, AlignmentSerializer alignmentSerializer, OntologySerializer ontoSerializer);

}


text:
<resources>

    <!--
        Base application theme for API 11+. This theme completely replaces
        AppBaseTheme from res/values/styles.xml on API 11+ devices.
    -->
    <style name="AppBaseTheme" parent="Theme.AppCompat.Light.NoActionBar">
        <item name="windowActionBar">false</item>
        <!-- API 11 theme customizations can go here. -->
    </style>

</resources>


text:
require 'formula'

class Sntop < Formula
  desc "Curses-based utility that polls hosts to determine connectivity"
  homepage 'http://sntop.sourceforge.net/'
  url 'http://distcache.freebsd.org/ports-distfiles/sntop-1.4.3.tar.gz'
  sha1 '8a96bb453a83262e30215a31be508c16dbd71e27'

  depends_on 'fping'

  def install
    system "./configure", "--disable-debug", "--disable-dependency-tracking",
                          "--prefix=#{prefix}",
                          "--mandir=#{man}",
                          "--sysconfdir=#{etc}"
    etc.mkpath
    bin.mkpath
    man1.mkpath
    system "make install"
  end

  def caveats; <<-EOS.undent
    sntop uses fping by default and fping can only be run by root by default.
    You can run `sudo sntop` (or `sntop -p` which uses standard ping).
    You should be certain that you trust any software you grant root privileges.
    EOS
  end
end


text:
package org.hawkular.agent.monitor.api;

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

import org.hawkular.agent.monitor.inventory.Resource;
import org.hawkular.agent.monitor.inventory.ResourceManager;
import org.hawkular.agent.monitor.inventory.ResourceTypeManager;
import org.hawkular.agent.monitor.protocol.EndpointService;
import org.hawkular.agent.monitor.protocol.Session;

/**
 * A event for discovery scans.
 *
 * @see InventoryListener
 */
public class InventoryEvent<L, S extends Session<L>> {

    private final EndpointService<L, S> service;
    private final ResourceManager<L> resourceManager;
    private final Optional<ResourceTypeManager<L>> resourceTypeManager;
    private final List<Resource<L>> addedOrModified;
    private final List<Resource<L>> removed;

    /**
     * Creates an inventory event.
     *
     * @param service a service that provides details such as feed ID and endpoint information that helps
     *                identify the resources in the event, plus has methods that can be used to monitor
     *                the resources in the event.
     * @param resourceManager the resources associated with the event
     * @param resourceTypeManager the resource types associated with the event. Omit if resource type sync is not
     *                            needed
     * @param addedOrModified list of added or modified resources
     * @param removed list of removed resources
     */
    private InventoryEvent(
            EndpointService<L, S> service,
            ResourceManager<L> resourceManager,
            Optional<ResourceTypeManager<L>> resourceTypeManager,
            List<Resource<L>> addedOrModified,
            List<Resource<L>> removed) {

        if (service == null) {
            throw new IllegalArgumentException("service cannot be null");
        }

        if (resourceManager == null) {
            throw new IllegalArgumentException("Resource manager cannot be null");
        }

        if (resourceTypeManager == null) {
            throw new IllegalArgumentException("Resource type manager cannot be null");
        }

        this.service = service;
        this.resourceManager = resourceManager;
        this.resourceTypeManager = resourceTypeManager;
        this.addedOrModified = addedOrModified;
        this.removed = removed;
    }

    /**
     * Build an {@link InventoryEvent} for removed resources.
     *
     * @param service a service that provides details such as feed ID and endpoint information that helps
     *                identify the resources in the event, plus has methods that can be used to monitor
     *                the resources in the event.
     * @param resourceManager the resources associated with the event
     * @param removed list of removed resources
     */
    public static <L, S extends Session<L>> InventoryEvent<L, S> removed(
            EndpointService<L, S> service,
            ResourceManager<L> resourceManager,
            List<Resource<L>> removed) {
        return new InventoryEvent<>(service, resourceManager, Optional.empty(), new ArrayList<>(), removed);
    }

    /**
     * Build an {@link InventoryEvent} for added or modified resources.
     *
     * @param service a service that provides details such as feed ID and endpoint information that helps
     *                identify the resources in the event, plus has methods that can be used to monitor
     *                the resources in the event.
     * @param resourceManager the resources associated with the event
     * @param addedOrModified list of added or modified resources
     */
    public static <L, S extends Session<L>> InventoryEvent<L, S> addedOrModified(
            EndpointService<L, S> service,
            ResourceManager<L> resourceManager,
            List<Resource<L>> addedOrModified) {
        return new InventoryEvent<>(service, resourceManager, Optional.empty(), addedOrModified, new ArrayList<>());
    }

    /**
     * Build an {@link InventoryEvent} for added or modified resources.
     *
     * @param service a service that provides details such as feed ID and endpoint information that helps
     *                identify the resources in the event, plus has methods that can be used to monitor
     *                the resources in the event.
     * @param resourceManager the resources associated with the event
     * @param resourceTypeManager the resource types associated with the event
     * @param addedOrModified list of added or modified resources
     * @param removed list of removed resources
     */
    public static <L, S extends Session<L>> InventoryEvent<L, S> discovery(
            EndpointService<L, S> service,
            ResourceManager<L> resourceManager,
            ResourceTypeManager<L> resourceTypeManager,
            List<Resource<L>> addedOrModified,
            List<Resource<L>> removed) {
        return new InventoryEvent<>(
                service,
                resourceManager,
                Optional.of(resourceTypeManager),
                addedOrModified,
                removed);
    }

    /**
     * @return the contextual sampling service associated with the event
     */
    public EndpointService<L, S> getEndpointService() {
        return service;
    }

    /**
     * @return the resource manager that was populated for this event
     */
    public ResourceManager<L> getResourceManager() {
        return resourceManager;
    }

    /**
     * @return when relevant, the resource type manager containing all the types of resources that discovery scans
     * might find
     */
    public Optional<ResourceTypeManager<L>> getResourceTypeManager() {
        return resourceTypeManager;
    }

    /**
     * @return the list of added or modified resources, including non-root resources
     */
    public List<Resource<L>> getAddedOrModified() {
        return addedOrModified;
    }

    /**
     * @return the list of removed resources, including non-root resources
     */
    public List<Resource<L>> getRemoved() {
        return removed;
    }
}


text:
package kr.co.shineware.nlp.komoran.admin.service;

import kr.co.shineware.nlp.komoran.admin.domain.FwdUser;
import kr.co.shineware.nlp.komoran.admin.domain.PosType;
import kr.co.shineware.nlp.komoran.admin.exception.ParameterInvalidException;
import kr.co.shineware.nlp.komoran.admin.exception.ResourceDuplicatedException;
import kr.co.shineware.nlp.komoran.admin.exception.ResourceNotFoundException;
import kr.co.shineware.nlp.komoran.admin.repository.FwdUserRepository;
import kr.co.shineware.nlp.komoran.admin.util.parser.query.FilterQueryParser;
import kr.co.shineware.nlp.komoran.admin.util.parser.query.SorterQueryParser;
import kr.co.shineware.nlp.komoran.admin.util.parser.stream.FwdUserStreamParser;
import org.json.simple.JSONObject;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Sort;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;
import java.util.stream.Stream;

@Service
@Transactional
public class FwdUserService {
    private static final Logger logger = LoggerFactory.getLogger(FwdUserService.class);

    @Autowired
    private FwdUserRepository fwdUserRepository;

    private FwdUser getFwdUserItem(int id) {
        FwdUser fwdUser = fwdUserRepository.findById(id);

        if (fwdUser == null) {
            throw new ResourceNotFoundException("ID: " + id);
        }

        return fwdUser;
    }

    private boolean isValidFwdAnalyzedResult(String analyzed) {
        if (analyzed == null || "".equals(analyzed)) {
            return false;
        }

        String[] analyzedResults = analyzed.split(" ");

        for (String anAnalyzedResult : analyzedResults) {
            String[] tmpAnalyzedResults = anAnalyzedResult.split("/");

            // INVALID FORM
            if (tmpAnalyzedResults.length < 2) {
                return false;
            }

            // FOR VALIDATING ANALYZED RESULT, PARSE IT
            String tmpAnalyzedTerm;
            String tmpAnalyzedPosInRaw;

            // Term includes delimiter '/'
            if (tmpAnalyzedResults.length > 2) {
                int delimiterIdx = anAnalyzedResult.lastIndexOf("/");
                tmpAnalyzedTerm = anAnalyzedResult.substring(0, delimiterIdx);
                tmpAnalyzedPosInRaw = anAnalyzedResult.substring(delimiterIdx + 1);
            } else {
                tmpAnalyzedTerm = tmpAnalyzedResults[0];
                tmpAnalyzedPosInRaw = tmpAnalyzedResults[1];
            }

            // VALIDATE ANALYZED TERM
            if ("".equals(tmpAnalyzedTerm)) {
                return false;
            }

            // VALIDATE ANALYZED POS
            try {
                PosType.valueOf(tmpAnalyzedPosInRaw);
            } catch (IllegalArgumentException e) {
                return false;
            }
        }

        return true;
    }

    @Transactional
    public FwdUser checkGivenFullAndAnalyzedExist(String full, String analyzed) {
        if (full == null || "".equals(full)) {
            throw new ParameterInvalidException("기분석 어절: " + full);
        } else if (!isValidFwdAnalyzedResult(analyzed)) {
            throw new ParameterInvalidException("기분석 결과: " + analyzed);
        }

        FwdUser fwdUserToFind = fwdUserRepository.findByFullAndAnalyzed(full, analyzed);

        if (fwdUserToFind == null) {
            throw new ResourceNotFoundException(full + "=>" + analyzed);
        }

        return fwdUserToFind;
    }

    @Transactional
    public FwdUser updateFullById(int id, String full) {
        if (id <= 0) {
            throw new ParameterInvalidException("ID: " + id);
        } else if (full == null || "".equals(full)) {
            throw new ParameterInvalidException("기분석 어절: " + full);
        }

        FwdUser fwdUserToUpdate = getFwdUserItem(id);

        fwdUserToUpdate.setFull(full);
        fwdUserRepository.save(fwdUserToUpdate);

        return fwdUserToUpdate;
    }

    @Transactional
    public FwdUser updateAnalyzedById(int id, String analyzed) {
        if (id <= 0) {
            throw new ParameterInvalidException("ID: " + id);
        } else if (!isValidFwdAnalyzedResult(analyzed)) {
            throw new ParameterInvalidException("기분석 결과: " + analyzed);
        }

        FwdUser fwdUserToUpdate = getFwdUserItem(id);

        fwdUserToUpdate.setAnalyzed(analyzed);
        fwdUserRepository.save(fwdUserToUpdate);

        return fwdUserToUpdate;
    }

    @Transactional
    public FwdUser deleteItemById(int id) {
        if (id <= 0) {
            throw new ParameterInvalidException("ID: " + id);
        }

        FwdUser fwdUserToDelete = getFwdUserItem(id);

        fwdUserRepository.delete(fwdUserToDelete);

        return fwdUserToDelete;
    }

    @Transactional
    public FwdUser addItem(String full, String analyzed) {
        if (full == null || "".equals(full)) {
            throw new ParameterInvalidException("기분석 어절: " + full);
        } else if (!isValidFwdAnalyzedResult(analyzed)) {
            throw new ParameterInvalidException("기분석 결과: " + analyzed);
        }

        FwdUser duplicateItem = fwdUserRepository.findByFull(full);

        if (duplicateItem != null) {
            throw new ResourceDuplicatedException(duplicateItem.getFull());
        }

        FwdUser fwdUserToAdd = new FwdUser(full, analyzed);
        fwdUserRepository.save(fwdUserToAdd);

        return fwdUserToAdd;
    }

    //    @Async("threadPoolTaskExecutor")
    @Transactional
    public void purgeAllData() {
        logger.debug("Purging all data...");
        fwdUserRepository.deleteAll();
        logger.debug("Purged");
    }

    //    @Async("threadPoolTaskExecutor")
    @Transactional
    public void importFromFile(Path savedFilePath) throws IOException {
        Stream<String> lines = Files.lines(savedFilePath);

        // @formatter:off
        List<FwdUser> fwdUsersToInsert = lines.filter(line -> !line.isEmpty())
                .flatMap(FwdUserStreamParser::parse)
                .distinct()
                .collect(Collectors.toList());
        // @formatter:on

        fwdUserRepository.deleteAll();
        fwdUserRepository.flush();

        fwdUserRepository.saveAll(fwdUsersToInsert);

        lines.close();
        fwdUserRepository.flush();
        logger.debug("Imported");
    }

    public String exportToString() {
        Stream<String> fwdUserExportStream = fwdUserRepository.getAllItemsWithExportForm();

        return fwdUserExportStream.collect(Collectors.joining("\n"));
    }

    @SuppressWarnings("unchecked")
    public JSONObject getFwdUserList(int page, int size, Map<String, String> allParameters) {
        JSONObject result = new JSONObject();
        Page<FwdUser> pageResult;

        if (allParameters.isEmpty()) {
            pageResult = fwdUserRepository.findAll(PageRequest.of(page - 1, size));
        } else {
            SorterQueryParser sorterQueryParser = new SorterQueryParser();
            FilterQueryParser filterQueryParser = new FilterQueryParser();

            Sort sortBy = sorterQueryParser.getSorter(allParameters);
            HashMap<String, String> filters = filterQueryParser.getFilter(allParameters);

            logger.debug("Sorters: " + sortBy.toString());
            logger.debug("Filters: " + filters.toString());

            if (filters.containsKey("full") && filters.containsKey("analyzed")) {
                // full && analyzed
                pageResult = fwdUserRepository.findByFullContainingAndAnalyzedContaining(
                        filters.get("full"), filters.get("analyzed"), PageRequest.of(page - 1, size, sortBy));
            } else if (filters.containsKey("full")) {
                // full
                pageResult = fwdUserRepository.findByFullContaining(
                        filters.get("full"), PageRequest.of(page - 1, size, sortBy));
            } else if (filters.containsKey("analyzed")) {
                // analyzed
                pageResult = fwdUserRepository.findByAnalyzedContaining(
                        filters.get("analyzed"), PageRequest.of(page - 1, size, sortBy));
            } else {
                // NOTHING
                pageResult = fwdUserRepository.findAll(PageRequest.of(page - 1, size, sortBy));
            }
        }

        result.put("data", pageResult.getContent());
        result.put("last_page", pageResult.getTotalPages());

        return result;
    }

}


text:
class Subscription: public resip::AppDialogSet{
public:
	Subscription(resip::DialogUsageManager &dum);
	~Subscription();

    resip::DialogUsageManager& getDUM();
    std::string getDevice();
    resip::NameAddr getContact();
    std::string getID();
    std::string getDeviceState();
    void toJSON(Dumais::JSON::JSON& json);

private:
    // TODO: will need to unfriend this
    friend class PhoneModule;
    friend class SIPEngine;

    resip::InviteSessionHandle mInviteSessionHandle;
    std::string mDevice;
    resip::NameAddr mOwner;
    resip::NameAddr mTo;
    resip::NameAddr mContact;
    std::string mDeviceStatus;
};

#endif


text:
<?xml version="1.0"?>
<!--

-->
<config xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="../../../../../../vendor/magento/mtf/etc/variations.xsd">
    <testCase name="Mage\Admin\Test\TestCase\CreateAdminUserEntityTest">
        <variation name="CreateAdminUserEntityTestVariation1" firstConstraint="Mage\Admin\Test\Constraint\AssertUserSuccessSaveMessage" method="test">
            <data name="user/data/username" xsi:type="string">AdminUser%isolation%</data>
            <data name="user/data/firstname" xsi:type="string">FirstName%isolation%</data>
            <data name="user/data/lastname" xsi:type="string">LastName%isolation%</data>
            <data name="user/data/email" xsi:type="string">email%isolation%@example.com</data>
            <data name="user/data/password" xsi:type="string">123123q</data>
            <data name="user/data/password_confirmation" xsi:type="string">123123q</data>
            <data name="user/data/is_active" xsi:type="string">Active</data>
            <data name="user/data/role_id/dataSet" xsi:type="string">administrators</data>
            <data name="user/data/current_password" xsi:type="string">123123q</data>
            <constraint name="Mage\Admin\Test\Constraint\AssertUserSuccessSaveMessage" next="Mage\Admin\Test\Constraint\AssertUserInGrid" />
            <constraint name="Mage\Admin\Test\Constraint\AssertUserInGrid" next="Mage\Admin\Test\Constraint\AssertUserSuccessLogOut" prev="Mage\Admin\Test\Constraint\AssertUserSuccessSaveMessage" />
            <constraint name="Mage\Admin\Test\Constraint\AssertUserSuccessLogOut" next="Mage\Admin\Test\Constraint\AssertUserSuccessLogin" prev="Mage\Admin\Test\Constraint\AssertUserInGrid" />
            <constraint name="Mage\Admin\Test\Constraint\AssertUserSuccessLogin" prev="Mage\Admin\Test\Constraint\AssertUserSuccessLogOut" />
        </variation>
        <variation name="CreateAdminUserEntityTestVariation2" firstConstraint="Mage\Admin\Test\Constraint\AssertUserSuccessSaveMessage" method="test">
            <data name="user/data/username" xsi:type="string">AdminUser%isolation%</data>
            <data name="user/data/firstname" xsi:type="string">FirstName%isolation%</data>
            <data name="user/data/lastname" xsi:type="string">LastName%isolation%</data>
            <data name="user/data/email" xsi:type="string">email%isolation%@example.com</data>
            <data name="user/data/password" xsi:type="string">123123q</data>
            <data name="user/data/password_confirmation" xsi:type="string">123123q</data>
            <data name="user/data/is_active" xsi:type="string">Inactive</data>
            <data name="user/data/role_id/dataSet" xsi:type="string">administrators</data>
            <data name="user/data/current_password" xsi:type="string">123123q</data>
            <constraint name="Mage\Admin\Test\Constraint\AssertUserSuccessSaveMessage" next="Mage\Admin\Test\Constraint\AssertUserInGrid" />
            <constraint name="Mage\Admin\Test\Constraint\AssertUserInGrid" next="Mage\Admin\Test\Constraint\AssertUserSuccessLogOut" prev="Mage\Admin\Test\Constraint\AssertUserSuccessSaveMessage" />
            <constraint name="Mage\Admin\Test\Constraint\AssertUserSuccessLogOut" next="Mage\Admin\Test\Constraint\AssertUserWrongCredentialsMessage" prev="Mage\Admin\Test\Constraint\AssertUserInGrid" />
            <constraint name="Mage\Admin\Test\Constraint\AssertUserWrongCredentialsMessage" prev="Mage\Admin\Test\Constraint\AssertUserSuccessLogOut" />
        </variation>
        <variation name="CreateAdminUserEntityTestVariation3" firstConstraint="Mage\Admin\Test\Constraint\AssertUserDuplicateMessage" method="test">
            <data name="user/data/username" xsi:type="string">-</data>
            <data name="user/data/firstname" xsi:type="string">FirstName%isolation%</data>
            <data name="user/data/lastname" xsi:type="string">LastName%isolation%</data>
            <data name="user/data/email" xsi:type="string">email%isolation%@example.com</data>
            <data name="user/data/password" xsi:type="string">123123q</data>
            <data name="user/data/password_confirmation" xsi:type="string">123123q</data>
            <data name="user/data/is_active" xsi:type="string">Active</data>
            <data name="user/data/role_id/dataSet" xsi:type="string">administrators</data>
            <data name="duplicatedParam" xsi:type="string">username</data>
            <data name="user/data/current_password" xsi:type="string">123123q</data>
            <data name="issue" xsi:type="string">Bug: MPERF-6585: Typo mistake in User already exists error message.</data>
            <constraint name="Mage\Admin\Test\Constraint\AssertUserDuplicateMessage" />
        </variation>
        <variation name="CreateAdminUserEntityTestVariation4" firstConstraint="Mage\Admin\Test\Constraint\AssertUserDuplicateMessage" method="test">
            <data name="user/data/username" xsi:type="string">AdminUser%isolation%</data>
            <data name="user/data/firstname" xsi:type="string">FirstName%isolation%</data>
            <data name="user/data/lastname" xsi:type="string">LastName%isolation%</data>
            <data name="user/data/email" xsi:type="string">-</data>
            <data name="user/data/password" xsi:type="string">123123q</data>
            <data name="user/data/password_confirmation" xsi:type="string">123123q</data>
            <data name="user/data/is_active" xsi:type="string">Active</data>
            <data name="user/data/role_id/dataSet" xsi:type="string">administrators</data>
            <data name="duplicatedParam" xsi:type="string">email</data>
            <data name="user/data/current_password" xsi:type="string">123123q</data>
            <data name="issue" xsi:type="string">Bug: MPERF-6585: Typo mistake in User already exists error message.</data>
            <constraint name="Mage\Admin\Test\Constraint\AssertUserDuplicateMessage" />
        </variation>
        <variation name="CreateAdminUserEntityTestVariation5" firstConstraint="Mage\Admin\Test\Constraint\AssertUserSuccessSaveMessage" method="test">
            <data name="user/data/username" xsi:type="string">AdminUser%isolation%</data>
            <data name="user/data/firstname" xsi:type="string">FirstName%isolation%</data>
            <data name="user/data/lastname" xsi:type="string">LastName%isolation%</data>
            <data name="user/data/email" xsi:type="string">email%isolation%@example.com</data>
            <data name="user/data/password" xsi:type="string">123123q</data>
            <data name="user/data/password_confirmation" xsi:type="string">123123q</data>
            <data name="user/data/is_active" xsi:type="string">Active</data>
            <data name="user/data/role_id/dataSet" xsi:type="string">-</data>
            <data name="user/data/current_password" xsi:type="string">123123q</data>
            <constraint name="Mage\Admin\Test\Constraint\AssertUserSuccessSaveMessage" next="Mage\Admin\Test\Constraint\AssertUserInGrid" />
            <constraint name="Mage\Admin\Test\Constraint\AssertUserInGrid" next="Mage\Admin\Test\Constraint\AssertUserSuccessLogOut" prev="Mage\Admin\Test\Constraint\AssertUserSuccessSaveMessage" />
            <constraint name="Mage\Admin\Test\Constraint\AssertUserSuccessLogOut" next="Mage\Admin\Test\Constraint\AssertUserWrongCredentialsMessage" prev="Mage\Admin\Test\Constraint\AssertUserInGrid" />
            <constraint name="Mage\Admin\Test\Constraint\AssertUserWrongCredentialsMessage" prev="Mage\Admin\Test\Constraint\AssertUserSuccessLogOut" />
        </variation>
        <variation name="CreateAdminUserEntityTestVariation6" firstConstraint="Mage\Admin\Test\Constraint\AssertUserInvalidEmailMessage" method="test">
            <data name="user/data/username" xsi:type="string">AdminUser%isolation%</data>
            <data name="user/data/firstname" xsi:type="string">FirstName%isolation%</data>
            <data name="user/data/lastname" xsi:type="string">LastName%isolation%</data>
            <data name="user/data/email" xsi:type="string">email%isolation%@example.cim</data>
            <data name="user/data/password" xsi:type="string">123123q</data>
            <data name="user/data/password_confirmation" xsi:type="string">123123q</data>
            <data name="user/data/is_active" xsi:type="string">Active</data>
            <data name="user/data/role_id/dataSet" xsi:type="string">-</data>
            <data name="user/data/current_password" xsi:type="string">123123q</data>
            <constraint name="Mage\Admin\Test\Constraint\AssertUserInvalidEmailMessage" />
        </variation>
        <variation name="CreateAdminUserEntityTestVariation7" firstConstraint="Mage\Admin\Test\Constraint\AssertUserWithCustomRole" method="test">
            <data name="user/data/username" xsi:type="string">CustomUser%isolation%</data>
            <data name="user/data/firstname" xsi:type="string">FirstName%isolation%</data>
            <data name="user/data/lastname" xsi:type="string">LastName%isolation%</data>
            <data name="user/data/email" xsi:type="string">email%isolation%@example.com</data>
            <data name="user/data/password" xsi:type="string">123123q</data>
            <data name="user/data/password_confirmation" xsi:type="string">123123q</data>
            <data name="user/data/is_active" xsi:type="string">Active</data>
            <data name="user/data/role_id/dataSet" xsi:type="string">custom</data>
            <data name="isCustomRole" xsi:type="boolean">true</data>
            <data name="user/data/current_password" xsi:type="string">123123q</data>
            <constraint name="Mage\Admin\Test\Constraint\AssertUserWithCustomRole"/>
        </variation>
    </testCase>
</config>


text:
namespace pecopeco.progs.MainForm {
	partial class DiaryBrowserForm {
		/// <summary>
		/// Required designer variable.
		/// </summary>
		private System.ComponentModel.IContainer components = null;

		/// <summary>
		/// Clean up any resources being used.
		/// </summary>
		/// <param name="disposing">true if managed resources should be disposed; otherwise, false.</param>
		protected override void Dispose(bool disposing) {
			if(disposing && (components != null)) {
				components.Dispose();
			}
			base.Dispose(disposing);
		}

		#region Windows Form Designer generated code

		/// <summary>
		/// Required method for Designer support - do not modify
		/// the contents of this method with the code editor.
		/// </summary>
		private void InitializeComponent() {
			this.webBrowser1 = new System.Windows.Forms.WebBrowser();
			this.SuspendLayout();
			//
			// webBrowser1
			//
			this.webBrowser1.Anchor = ((System.Windows.Forms.AnchorStyles)((((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Bottom)
            | System.Windows.Forms.AnchorStyles.Left)
            | System.Windows.Forms.AnchorStyles.Right)));
			this.webBrowser1.Location = new System.Drawing.Point(0, 0);
			this.webBrowser1.MinimumSize = new System.Drawing.Size(20, 20);
			this.webBrowser1.Name = "webBrowser1";
			this.webBrowser1.Size = new System.Drawing.Size(773, 492);
			this.webBrowser1.TabIndex = 0;
			//
			// DiaryBrowserForm
			//
			this.AutoScaleDimensions = new System.Drawing.SizeF(6F, 12F);
			this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font;
			this.ClientSize = new System.Drawing.Size(773, 492);
			this.Controls.Add(this.webBrowser1);
			this.Name = "DiaryBrowserForm";
			this.Text = "DiaryBrowserForm";
			this.ResumeLayout(false);

		}

		#endregion

		private System.Windows.Forms.WebBrowser webBrowser1;
	}
}


text:
module Azure::DataFactory::Mgmt::V2018_06_01
  module Models
    #
    # Defines values for VariableType
    #
    module VariableType
      String = "String"
      Bool = "Bool"
      Array = "Array"
    end
  end
end


text:
<?php

namespace GingerWorkflowEngineTest\Model\QueryResult;

use GingerWorkflowEngine\Model\Action\ActionId;
use GingerWorkflowEngine\Model\Action\Arguments;
use GingerWorkflowEngine\Model\Action\Name;
use GingerWorkflowEngine\Model\QueryResult\ItemsLoaderManager;
use GingerWorkflowEngine\Model\QueryResult\LazyItemsLoader;
use GingerWorkflowEngine\Model\QueryResult\MetaInformation;
use GingerWorkflowEngine\Model\WorkflowRun\WorkflowRunId;
use GingerWorkflowEngineTest\Mock\ItemsLoaderMock;
use GingerWorkflowEngineTest\TestCase;
use Rhumsaa\Uuid\Uuid;

/**
 * Class LazyItemsLoaderTest
 *
 * @package GingerWorkflowEngineTest\Model\QueryResult
 * @author Alexander Miertsch <kontakt@codeliner.ws>
 */
class LazyItemsLoaderTest extends TestCase
{
    /**
     * @var LazyItemsLoader
     */
    private $lazyItemsLoader;

    protected function setUp()
    {
        $anItemsLoaderManager = new ItemsLoaderManager();

        $anItemsLoader = new ItemsLoaderMock();

        $anItemsLoaderManager->setInvokableClass($anItemsLoader->name(), get_class($anItemsLoader));

        LazyItemsLoader::setItemsLoaderManager($anItemsLoaderManager);

        $this->lazyItemsLoader = new LazyItemsLoader($anItemsLoader);
    }

    public function testToAndFromJsonAndSameValueAs()
    {
        $jsonString = $this->lazyItemsLoader->toJSON();

        $this->assertJson($jsonString);

        $aLazyItemsLoader = LazyItemsLoader::fromJSON($jsonString);

        $this->assertTrue($this->lazyItemsLoader->sameValueAs($aLazyItemsLoader));
    }

    public function testItems()
    {
        $aMetaInformation = new MetaInformation(
            new WorkflowRunId(Uuid::uuid4()),
            new ActionId(Uuid::uuid4()),
            new Name('TestQuery'),
            new Arguments(array()),
            4
        );

        $anItemsList = $this->lazyItemsLoader->items(1, 2, $aMetaInformation);

        $anItemsStringList = array();

        foreach($anItemsList as $anItem) {
            $anItemsStringList[] = $anItem->data();
        }

        $this->assertEquals(array('second item', 'third item'), $anItemsStringList);
    }

    public function testIsSingleItemResult()
    {
        $this->assertFalse($this->lazyItemsLoader->isSingleItemResult());
    }

    public function testIsFullItemCollection()
    {
        $this->assertFalse($this->lazyItemsLoader->isFullItemCollection());
    }

    public function testIsPagedItemCollection()
    {
        $this->assertTrue($this->lazyItemsLoader->isPagedItemCollection());
    }
}


text:
namespace MakarovDev.ExpandCollapsePanel
{
    partial class ExpandCollapsePanel
    {
        /// <summary>
        /// Required designer variable.
        /// </summary>
        private System.ComponentModel.IContainer components = null;

        /// <summary>
        /// Clean up any resources being used.
        /// </summary>
        /// <param name="disposing">true if managed resources should be disposed; otherwise, false.</param>
        protected override void Dispose(bool disposing)
        {
            if (disposing && (components != null))
            {
                components.Dispose();
            }
            base.Dispose(disposing);
        }

        #region Component Designer generated code

        /// <summary>
        /// Required method for Designer support - do not modify
        /// the contents of this method with the code editor.
        /// </summary>
        private void InitializeComponent()
        {
            this.components = new System.ComponentModel.Container();
            this._btnExpandCollapse = new MakarovDev.ExpandCollapsePanel.ExpandCollapseButton();
            this.animationTimer = new System.Windows.Forms.Timer(this.components);
            this.SuspendLayout();
            //
            // _btnExpandCollapse
            //
            this._btnExpandCollapse.Anchor = ((System.Windows.Forms.AnchorStyles)(((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Left)
            | System.Windows.Forms.AnchorStyles.Right)));
            this._btnExpandCollapse.ButtonSize = MakarovDev.ExpandCollapsePanel.ExpandCollapseButton.ExpandButtonSize.Normal;
            this._btnExpandCollapse.ButtonStyle = MakarovDev.ExpandCollapsePanel.ExpandCollapseButton.ExpandButtonStyle.Circle;
            this._btnExpandCollapse.IsExpanded = false;
            this._btnExpandCollapse.Location = new System.Drawing.Point(3, 3);
            this._btnExpandCollapse.Name = "_btnExpandCollapse";
            this._btnExpandCollapse.TabIndex = 0;
            //
            // animationTimer
            //
            this.animationTimer.Interval = 50;
            this.animationTimer.Tick += new System.EventHandler(this.animationTimer_Tick);
            //
            // ExpandCollapsePanel
            //
            this.Controls.Add(this._btnExpandCollapse);
            this.Size = new System.Drawing.Size(365, 319);
            this.ResumeLayout(false);

        }

        #endregion

        private MakarovDev.ExpandCollapsePanel.ExpandCollapseButton _btnExpandCollapse;
        private System.Windows.Forms.Timer animationTimer;
    }
}