text:
#include <os.h>
#include <nspireio2.h>
#include <libndls.h>
#include "main.h"

#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <inttypes.h>

int main()
{
	nio_console csl;
	lcd_incolor();
	clrscr();
	//					  54, 30 would be the normal max values, but this way a graphic bug is fixed and i do \n manually anyway
	nio_InitConsole(&csl, 55, 31, 0, 0, NIO_COLOR_BLACK, NIO_COLOR_WHITE);
	nio_DrawConsole(&csl);
	nio_drawing_enabled(&csl,TRUE);
	nio_cursor_type(&csl, NIO_CURSOR_UNDERSCORE);

	drawLogo(&csl, 3000);

	struct TradeOption *options;
	options = (struct TradeOption *)malloc(sizeof(struct TradeOption));

	for(int c = 0; c < 6; ++c)
	{
		options->trades[0][c] = -1;
		options->trades[1][c] = -1;
	}
	options->saved = 0;

	short stop = 0;
	while(stop == 0)
	{
		int choice = displayMenu(&csl);
		switch(choice){
			case 48:	// ASCII Code for 0	-> Exit
				stop = 1;
				break;
			case 49:	// ASCII Code for 1	-> Start trading
				if(options->saved == 0)
				{
					nio_printf(&csl, "\n\n[!]Please choose the Pokemons you\nwant to trade first!");
					wait_key_pressed();
					break;
				}
				TradePokemon(&csl, options);
				break;
			case 50:	// ASCII Code for 2	-> Choose Trading Options
				ChoosePokemon(options);
				options->saved = 1;
				break;
			case 51:	// ASCII Code for 3	-> Fix Savestates
				FixSaves(&csl);
				break;
			case 52:	// ASCII Code for 4	-> Display Help & Disclaimer
				nio_clear(&csl);
				nio_printf(&csl, HELPSTRING);
				wait_key_pressed();
				break;
			default:	// exit if invalid choice
				break;
		}
	}

	drawBye(&csl, 3000);
	free(options);
	clrscr();
	lcd_incolor();
	return 0;
}

// Displays the Menu string and returns the choice
int displayMenu(nio_console *csl)
{
	clrscr();
	nio_clear(csl);
	char choice[1];

	nio_printf(csl, HEADLINE);		// Print the Headline
	nio_printf(csl, MENUSTRING);	// Print the options
	nio_printf(csl, "> ");			// wait for input
	nio_fgets(choice,3,csl);		// store input in choice[]
	return (int)choice[0];			// return choice
}

// Fill struct TradeOption options with values
int ChoosePokemon(struct TradeOption *options)
{
	clrscr();

	char * title = "";	// Displays Number of the trade #%d
	char * subtitle = "Cancel to save your choice.";
	char * msg1 = "Trade your Pokemon #";
	char * msg2 = "with Partner's Pokemon #";

	int valid	= 0;
	int value1	=	1;
	int value2	=	1;
	char popup_result[256];

	for(int c = 0; c < 6; ++c)
	{
		valid	=	0;
		while(valid == 0)
		{
			valid	=	1;
			sprintf (title, "Choose Trade %d/6", c+1);

			// return 0; if pressed cancel to save the struct
			if (show_2numeric_input(title, subtitle, msg1, &value1, 1, 6, msg2, &value2, 1, 6) != 1) return 0;

			// check for double trades
			for(int i = 0; i < 6; ++i)
			{
				if(options->trades[0][i] == value1)
				{
					show_msgbox("Notice", "You can't trade a Pokemon more than once. Pick different ones!");
					valid	=	0;
					continue;
				}
				if(options->trades[1][i] == value2)
				{
					show_msgbox("Notice", "You can't trade a Pokemon more than once. Pick different ones!");
					valid	=	0;
					continue;
				}
			}
		}

		options->trades[0][c] = value2-1;
		options->trades[1][c] = value1-1;

		sprintf(popup_result, "Your Pokemon #%d will be traded \nwith your partner's Pokemon #%d", value1, value2);
		show_msgbox("Information", popup_result);
	}
	show_msgbox("Saved", "Successfully saved your choices!");
	clrscr();
	return 0;
}

// Trade Pokemon using a TradeOption
int TradePokemon(nio_console *csl, struct TradeOption *options)
{
	nio_clear(csl);
	nio_printf(csl, "Press any key start ...\n");
	wait_key_pressed();

	unsigned char *buffer; // buffer of the first savefile
	buffer=malloc(FILESIZE*sizeof(unsigned char));
	memset( buffer, 0x0, FILESIZE);

	unsigned char *buffer2; // buffer of the second savefile
	buffer2=malloc(FILESIZE*sizeof(unsigned char));
	memset( buffer2, 0x0, FILESIZE);

    struct Pokemon *TeamData;	// import/export Pokemon for trading
	TeamData=malloc(12*sizeof(struct Pokemon)); // Create an array of 12 Pokemons for both teams
	memset( TeamData, 0x0, 12);

	// loading both savefiles into buffer & buffer2
	nio_printf(csl, ">> Loading first savefile\n");
	if(loadSaveFile(buffer, FILE1) != FILESIZE)
	{
		nio_printf(csl, "\n[!] Your savefile is corrupted or can't be opened\nBe sure to use 128kb .sav files with this program");
		wait_key_pressed();
		return -1;
	}

	nio_printf(csl, ">> Loading second savefile\n");
	if(loadSaveFile(buffer2, FILE2) != FILESIZE)
	{
		nio_printf(csl, "Your partner's savefile is corrupted or can't be opened\nBe sure to use 128kb .sav files with this program");
		wait_key_pressed();
		return -1;
	}

	// load both teams into TeamData[]
	nio_printf(csl, ">> Loading teams\n");
	for(int c = 0; c<6; c++)
	{
		TeamData[c] = exportPokemon(buffer, c);
		TeamData[c+6] = exportPokemon(buffer2, c);
		/*
		TeamData[0]	=	Pokemon 1 of team 1;
		...
		TeamData[5]	=	Pokemon 2 of team 1;
		TeamData[6]	=	Pokemon 1 of team 2;
		...
		TeamData[11]	=	Pokemon 6 of team 2;
		*/
	}

	// TRADING POKEMON
	nio_printf(csl, ">> Trading Pokemon\n");
	for(int i = 0; i < 6; i++)
	{
		if( (options->trades[0][i] >= 0) && (options->trades[1][i] >= 0) )
		{
			importPokemon(buffer2, TeamData[options->trades[1][i]], options->trades[0][i]);
			importPokemon(buffer,  TeamData[(options->trades[0][i])+6], options->trades[1][i]);
		}
	}

	// write both saves back to FILE3 and FILE4 and fix their checksums before
	// so they aren't corrupted
	fixChksum(buffer);
	fixChksum(buffer2);

	nio_printf(csl, ">> Writing back the first savefile\n");
	if(writeSaveFile(buffer, FILE3) != FILESIZE)
	{
		nio_printf(csl, "[!] Error, can't write first savefile\n");
		free(buffer);
		free(buffer2);
		free(TeamData);
		wait_key_pressed();
		return 0;
	}

	nio_printf(csl, ">> Writing back the second savefile\n");
	if(writeSaveFile(buffer2, FILE4) != FILESIZE)
	{
		nio_printf(csl, "[!] Error, can't write second savefile\n");
		free(buffer);
		free(buffer2);
		free(TeamData);
		wait_key_pressed();
		return 0;
	}

	nio_printf(csl, ">> Finished, returning to menu\n");

	free(buffer);
	free(buffer2);
	free(TeamData);
	wait_key_pressed();
	return 0;
}

// load savefile into buffer and return filesize for checking after
unsigned long loadSaveFile(unsigned char buffer[], char filename[])
{
	FILE * fptr  = fopen(filename, "rb");
	if(fptr == NULL) {
		return 0;
	}
	unsigned long filesize = fread(buffer,1,FILESIZE,fptr);
	fclose(fptr);
	return filesize;
}

// write new savefile from buffer
unsigned long writeSaveFile(unsigned char buffer[], char filename[])
{
	FILE * fptr  = fopen(filename, "wb");
	if(fptr == NULL) {
		return 0;
	}
	unsigned long filesize = fwrite (buffer , 1, FILESIZE, fptr);
	fclose(fptr);
	return filesize;
}

// write Pokemon into struct Pokemon and return it
struct Pokemon exportPokemon(unsigned char *buffer, int index)
{
	int VersionOffset	=	RSE_TEAM;		// Emerald/Ruby/Sapphire Version as default version
	if(getGameCode(buffer) == 0x01)			// FireRed/LeafGreen
	{
		VersionOffset	=	FR_TEAM;
	} else {								// Ruby/Sapphire/Emerald
		VersionOffset	=	RSE_TEAM;
	}
	int64_t StartOffset = getOffset(buffer, 0x01) + VersionOffset + (100*index);
	printf("[EXPORT #%d] VersionOffset:	->	%X", index, (unsigned int) VersionOffset);
	printf("Startoffset:	->	%X\n", (unsigned int) StartOffset);
	struct Pokemon TempPoke;
	for(int c=0; c<POKEMON_SIZE; c++)
	{
		TempPoke.Data[c]	= buffer[StartOffset+c];
	}
	return TempPoke;
}

// Write Temppoke to char buffer at index
void importPokemon(unsigned char *buffer, struct Pokemon TempPoke, int index)
{
	int VersionOffset	=	RSE_TEAM;		// Emerald/Ruby/Sapphire Version as default version
	if(getGameCode(buffer) == 0x01)			// FireRed/LeafGreen
	{
		VersionOffset	=	FR_TEAM;
	} else {								// Ruby/Sapphire/Emerald
		VersionOffset	=	RSE_TEAM;
	}

	// = Offset of Team Section + Offset of the Team Content + (100(Bytes) * index)
	int64_t StartOffset = getOffset(buffer, 0x01);
	StartOffset	+=	VersionOffset;
	StartOffset	+=	(100*index);
	printf("[IMPORT to #%d] VersionOffset:	->	%X", index, (unsigned int) VersionOffset);
	printf("Startoffset:	->	%X\n", (unsigned int) StartOffset);

	for(int c=0; c<POKEMON_SIZE; ++c)
	{
		buffer[StartOffset+c] = TempPoke.Data[c];
	}
}

// only used for calculateChksum to swap the 2 Bytes
uint64_t swapBytes(uint64_t x)
{
	uint64_t tmp = x;
	x = (x & 0xFF)<<8;
	x += tmp>>8;
	return x;
}

int64_t calculateChkSum(unsigned char *buffer, int64_t offset)
{
	uint64_t bytesum  = 0;	// Sum of all Bytes in the data part of a section
	uint64_t ChkSum = 0;	// final checksum

	for(int c=0; c<BLOCK_SIZE; c+=4)
	{
		/*
			> split it up into 4 Byte parts and change the order (little endian)
			> use bitshifting to build one final value
			> add final value to bytesum
		*/
		uint64_t tmp  = (uint64_t) buffer[(uint64_t)offset+c];
		uint64_t tmp2 = (uint64_t) buffer[(uint64_t)offset+c+1];
		uint64_t tmp3 = (uint64_t) buffer[(uint64_t)offset+c+2];
		uint64_t tmp4 = (uint64_t) buffer[(uint64_t)offset+c+3];

		tmp2 = tmp2 << 8;
		tmp3 = tmp3 << 16;
		tmp4 = tmp4 << 24;
		bytesum += (tmp+tmp2+tmp3+tmp4);
	}

	// add 16 lower to 16 upper bits
	ChkSum = bytesum & 0xFFFFFFFF;	//truncate to 32 bits
	ChkSum =  bytesum>>16;			//get 16 upper bits
	ChkSum += bytesum;				//add to bytesum
	ChkSum = ChkSum & 0xFFFF;		//truncate to 16 Bits to get the lower 16 bits

	ChkSum = swapBytes(ChkSum);		//Swap Bytes because idk, sry dude but it only works this way

	return ChkSum;
}

//fixes all checksums of a buffer, so the savefiles isn't corrupted after the trade
void fixChksum(unsigned char *buffer)
{
	int64_t ChkSum = 0;
	int64_t Offset = 0;

	for(int c = 0; c < 14; c++)
	{
		Offset	=	getOffset(buffer, c);
		ChkSum	=	calculateChkSum(buffer, Offset);
		buffer[Offset+CHKSUM_OFFSET]	=	ChkSum >> 8;
		buffer[Offset+CHKSUM_OFFSET+1]	=	ChkSum & 0xFF;
	}

}

// returns the offset of a section
uint64_t getOffset(unsigned char *buffer, int SectionId)
{
	// saveindex to determine which savestate is the latest
	// There are 2 saves per 128 kb .sav file if you haven't noticed
	int64_t SaveIndex	=	-1;

	//-1 to check if something went wrong
	int64_t	Offset	=	-1;

	for( int c = 0; c<FILESIZE; c+=0x1000)
	{
		if(buffer[c+0xFF4]	==	SectionId)
		{
			if(buffer[c+0xFFC]	>=	SaveIndex)
			{
				Offset	=	c;
			}
		}
	}

	if(Offset<0)
	{
		//~ printf("\n\n[!] Offset not found for SectionID:	%X\nSaveIndex:	%X\n\n", (unsigned int) SectionId, (unsigned int) SaveIndex);
		return -1;
	}
	return Offset;
}

// Fix corrupt savefiles (only possible for wrong checksums)
int FixSaves(nio_console *csl)
{
	nio_clear(csl);
	nio_printf(csl, "Press any key start ...\n");
	wait_key_pressed();
	nio_clear(csl);

	unsigned char *buffer; // buffer of the first savefile
	buffer=malloc(FILESIZE*sizeof(unsigned char));
	memset( buffer, 0x0, FILESIZE);

	unsigned char *buffer2; // buffer of the second savefile
	buffer2=malloc(FILESIZE*sizeof(unsigned char));
	memset( buffer2, 0x0, FILESIZE);

	unsigned long result; //result of loadSaveFile to check if its a) there and b) exactly 128kb big

	nio_printf(csl, ">> Fixing first savefile\n");
	result = loadSaveFile(buffer, FILE1);
	if(result == FILESIZE)
	{
		fixChksum(buffer);
		nio_printf(csl, ">> Writing back the first savefile\n");
		writeSaveFile(buffer, FILE5);
	} else {
		if(result == 0){
			nio_printf(csl, "\n[!] '1.sav' not found, continue with second\n");
		} else {
			nio_printf(csl, "\n[!] Sorry but i can't repair '1.sav'\nBe sure to use 128kb .sav files with this program");
		}
		wait_key_pressed();
	}

	nio_printf(csl, ">> Fixing second savefile\n");
	result = loadSaveFile(buffer2, FILE2);
	if(result == FILESIZE)
	{
		fixChksum(buffer2);
		nio_printf(csl, ">> Writing back the second savefile\n");
		writeSaveFile(buffer2, FILE6);
	} else {
		if(result == 0){
			nio_printf(csl, "\n[!] '2.sav' not found, exit\n");
		} else {
			nio_printf(csl, "\n[!] Sorry but i can't repair '2.sav'\nBe sure to use 128kb .sav files with this program");
		}
		wait_key_pressed();
	}

	nio_printf(csl, ">> Finished, returning to menu\n");
	free(buffer);
	free(buffer2);
	wait_key_pressed();
	return 0;
}

int getGameCode(unsigned char *buffer)
{
	uint64_t GameCodeOffset = getOffset(buffer, 0x00);
	GameCodeOffset	+=	172;
	return buffer[GameCodeOffset];
}


text:
/*
below is the base css for the original key look but adjusted for new html
----------------------------------------------------------------------------------------------------
----------------------------------------------------------------------------------------------------*/
body, p, table, ul, ol, form {margin:0; padding:0; border:0;}

html {height:100%;}

body {min-height:100%; color:#000; font-family:'Lucida Grande', sans-serif; background-color:#fff; font-size:10pt; line-height:15pt;}

a {text-decoration:none; color:#00f;}
a:hover {text-decoration:underline;}

/* clearfix */
.minorContent:after,
.mainContent div.submit:after {display:block; content:""; clear:both; visibility:hidden; line-height:0; height:0;}

/* structure
--------------------------------------------------*/
.main {width:580px; margin:0 auto; padding:3em 0; position:relative;}

.header {margin-bottom:4em; text-align:center;}
.header p {color:#666; padding:0.5em 32px;}

/* menu & help
--------------------------------------------------*/
.menu {margin:2em 25px 0; font-size:13pt; font-weight:normal; overflow:hidden; padding:0; height:34px;}
.menu li {float:left; list-style:none; margin:0 3px; overflow:hidden; padding:7px 0; border:1px solid #333; border-bottom:0; background-color:#3c3c3c;}
.menu li:hover {background-color:#666;}
.menu li a {color:#fff; padding:12px 10px; background-color:#3c3c3c;}
.menu li a:hover {background-color:#666; text-decoration:none;}
.menu li.selected,
.menu li.selected:hover {background-color:#fff;}
.menu li.selected a,
.menu li.selected a:hover {background-color:#fff; color:#000;}

#ssoHelp {overflow:visible; position:absolute; right:25px; z-index:100; background-color:#3c3c3c; border-bottom:1px solid #333; padding-bottom:6px;}
#ssoHelp:hover {background-color:#666;}
#ssoHelp_link {background-color:transparent; color:#fff;}
#ssoHelp_popup-wrap {display:none; position:absolute; width:1px; height:1px; right:-1px; top:-1px;} /* jQuery needs the box to be 1x1, so don't change to 0x0 as it once was */
#ssoHelp_link-active {position:absolute; top:0; right:0; padding:0; height:44px; color:#fff; background-color:#999; border:1px solid #333; border-bottom:0;}
#ssoHelp_link-active span {display:block; padding:7px 10px 0;}
#ssoHelp_link-active:hover {color:#000;}
#ssoHelp_popup {position:absolute; z-index:100; right:0; top:35px; width:320px;}
.ssoHelp_content {border:1px solid #333; border-top-width:0;}
.ssoHelp_content-in {border:6px solid #999; background-color:#e5e5e5; font-size:9pt;}
.ssoHelp_content h2 {margin:0.75em 60px 0.75em 10px; font-size:13pt;}
.ssoHelp_content p {margin-left:10px; margin-right:10px; margin-bottom:1em;}
.ssoHelp_content p.ssoHelp_exit {font-weight:bold;}
.ssoHelp_content ol,
.ssoHelp_content ul {padding:0 2em 1em 3em;}
.ssoHelp_content li {overflow:visible; border-width:0; float:none; display:list-item;}
.ssoHelp_content ul li {list-style-type:disc;}
.ssoHelp_content ol li {list-style-type:decimal;}
.ssoHelp_content .ssoHelp_footer {font-weight:bold;}
.menu li .ssoHelp_content a,
.menu li .ssoHelp_content a:hover,
.menu li .ssoHelp_content li,
.menu li .ssoHelp_content li:hover {background-color:transparent !important;}
.menu li .ssoHelp_content a {padding:0; color:#00f;}

/* content
--------------------------------------------------*/
.content {border:1px solid #333; background-color:#fff;}
.content_header {text-align:center; margin:1.5em 0; color:#333; clear:none; font-size:10.5pt;}
.content_header p {padding:0.25em 3px;}

.mainContent {margin:0.25em 35px 1.5em;}
.mainContent label {font-weight:bold; padding:0 4px; text-transform:capitalize;}
.mainContent input {font-size:12pt; margin:0;}
.mainContent div.section {border-bottom:1px dashed #ccc; padding-bottom:1em; margin-bottom:0.75em;}
.mainContent div.section ul {margin:0.75em 0 0.75em 20px;}
.mainContent div.section p,
.mainContent div.errors {margin:0.75em 0 0.75em 4px;}
.mainContent div.errors {color:#f00; font-weight:bold;}
.mainContent div.group {margin:0.75em 0 1.5em;}
.mainContent div.group a {padding:0.25em 4px; display:block;}
.mainContent div.group input {padding:0.25em 3px; margin-top:0.25em;}
.mainContent div.group input.form_text,
.mainContent div.group textarea.form_textarea {border:1px solid #aaa; width:500px;}
.mainContent div.group textarea.form_textarea {height:9em; background-color:#f2f2f2;}
.mainContent div.group .form_error span {background-color:#f99; border-bottom:2px solid #f00; padding:0.25em 4px;}
.mainContent div.submit {margin:1.5em 2px 0.5em; padding-bottom:0.75em; position:relative;}
.mainContent div.submit input,
.mainContent div.submit .form_submit-wrap {float:right; clear:none; cursor:pointer; margin-left:24px;}
.mainContent div.submit .form_submit-wrap input {float:none; margin:0;}
.mainContent div.submit input:hover {color:#00f;}
.mainContent div.section.searchResults {background-color:#e5e5e5; border:1px solid; border-color:#555 #999 #ddd; padding:0 10px;}
.mainContent div.section.searchResults .group {margin-right:-16px;}
.mainContent div.section.searchResults select {border:1px solid #ccc; width:85%;}

/* facebook button */
.facebookLogin {display: none;}
.fb_button, .fb_button_text {line-height:14px !important; font-style:normal !important;}
.fb_button {padding:0 !important;}
.fb_button .fb_button_text, .fb_button_rtl .fb_button_text {margin-left:22px !important;}
.fb_button:hover {text-decoration:none !important;}

.minorContent {padding:1em 39px 0; border-top:1px solid #ccc;}
.minorContent .logo-wrap {float:right; margin-bottom:1em;}
.minorContent .logo {height:7em;}
.minorContent .menu_minorContent-wrap {float:right;}
.minorContent .menu_minorContent {margin-right:32px; padding:2em 30px; border-right:1px dashed #ccc;}
.minorContent .menu_minorContent li {margin:0; padding:0; list-style:none;}

#languagesList {margin:1em 8px; text-align:center;}
#languagesList li {display:inline; padding:2px 8px;}
#languagesList li a {color:#666; white-space:nowrap; text-decoration:underline;}
#languagesList li.selected a {color:#000; font-weight:bold; text-decoration:none;}
#languagesList li a:hover {color:#000;}

/* page-specific overrides
--------------------------------------------------*/
body.page_SelfServe_AccountDetails #ssoHelp_popup {width:450px;}

/* ie hacks
	\9 = ie9 & below, * = ie7 & below, _ = ie6 & below
--------------------------------------------------*/
#ssoHelp_popup-wrap {_right:-2px;}
.mainContent div.submit {height:1em;}
.mainContent div.submit input,
.mainContent div.submit .form_submit-wrap {position:relative; top:-1px;}
.mainContent div.submit .form_submit-wrap input {top:0;}
.mainContent div.group .form_error {padding-top:0.1em;}
.minorContent {height:8em;}

/*
client css overrides
----------------------------------------------------------------------------------------------------
----------------------------------------------------------------------------------------------------*/
body {background:transparent url(/Portals/_default/skins/AgapeBlue/images/BackgroundRepeat.gif) repeat top left;}

.menu li,
.menu li a,
#ssoHelp {background-color:#0d3163;}

.menu li:hover,
.menu li a:hover,
#ssoHelp:hover,
#ssoHelp_link-active {background-color:#4a6ea3;}
.ssoHelp_content-in {border-color:#4a6ea3;}

#ssoHelp_link-active:hover {color:#fff;}
.minorContent {background:transparent url(GetLogo.aspx) no-repeat right top; height:100px;}
.minorContent .logo-wrap {display:none;}
.minorContent .menu_minorContent-wrap {margin-right:240px;}
.facebookLogin {visibility:hidden;}

redpajama_set_name: RedPajamaGithub


text:
static UIStatusBarStyle style_ = UIStatusBarStyleDefault;
static BOOL statusBarHidden_ = NO;

@interface SUGoodsController1 ()
/// 模型视图
@property (nonatomic, readonly, strong) SUGoodsViewModel1 *viewModel;
/// 滚动到顶部的按钮
@property (nonatomic, readwrite, weak) UIButton *scrollToTopButton;
/// 自定义的导航条
@property (nonatomic, readwrite, weak) UIView *navBar;
/// searchBar
@property (nonatomic, readwrite, weak) SUSearchBarView *titleView;
/// headerView
@property (nonatomic, readwrite, weak) SDCycleScrollView *headerView;
@end

@implementation SUGoodsController1
{
    /// KVOController 监听数据
    FBKVOController *_KVOController;
}
@dynamic viewModel;

- (void)dealloc
{
    MHDealloc;
}

- (void)viewWillAppear:(BOOL)animated
{
    [super viewWillAppear:animated];

    // 如果你发现你的CycleScrollview会在viewWillAppear时图片卡在中间位置,你可以调用此方法调整图片位置
    [self.headerView adjustWhenControllerViewWillAppera];
}

- (void)viewDidLoad {
    [super viewDidLoad];

    // hide sys navBar
    self.fd_prefersNavigationBarHidden = YES;
    // 去掉侧滑pop手势
    self.fd_interactivePopDisabled = YES;
    // create subViews
    [self _setupSubViews];
    // deal action
    [self _dealAction];
    /// tableView rigister  cell
    [self.tableView mh_registerNibCell:[SUGoodsCell class]];
    [self.tableView registerNib:[UINib nibWithNibName:NSStringFromClass([SUGoodsHeaderView class]) bundle:nil] forHeaderFooterViewReuseIdentifier:NSStringFromClass([SUGoodsHeaderView class])];

    /// estimatedRowHeight
    /// Fixed:如果添加下面👇代码 会导致当表格滚动到大于一页的时候 ,点击右下角的向上按钮 无法滚动到顶部的bug。原因还在排查中...
//    self.tableView.estimatedRowHeight = 280.0f;
//    self.tableView.rowHeight = UITableViewAutomaticDimension;
//
    /// bind viewModel
    [self _bindViewModel];
}

#pragma mark - BindModel
- (void)_bindViewModel{
    /// kvo
    _KVOController = [FBKVOController controllerWithObserver:self];
}

#pragma mark - 事件处理
/// 事件处理
- (void)_dealAction
{
    /// 点击搜索框的事件:这里我就不跳转到搜索界面了  直接退出该界面
    @weakify(self);
    self.titleView.searchBarViewClicked = ^ {
        @strongify(self);
        @weakify(self);
        UIAlertAction *confirmlAction = [UIAlertAction actionWithTitle:@"确定" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
            @strongify(self);
            [self.navigationController popToRootViewControllerAnimated:YES];
        }];
        UIAlertAction *cancelAction = [UIAlertAction actionWithTitle:@"取消" style:UIAlertActionStyleDefault handler:nil];
        UIAlertController *alertController = [UIAlertController alertControllerWithTitle:nil message:@"确定要注销当前用户吗?" preferredStyle:UIAlertControllerStyleAlert];
        [alertController addAction:confirmlAction];
        [alertController addAction:cancelAction];
        [self presentViewController:alertController animated:YES completion:nil];
    };
    /// banner 视图被点击
    self.headerView.clickItemOperationBlock = ^(NSInteger currentIndex) {
        @strongify(self);
        SUPublicWebViewModel1 *viewModel = [[SUPublicWebViewModel1 alloc] initWithParams:@{SUViewModelRequestKey:[self.viewModel bannerUrlWithIndex:currentIndex]}];
        SUPublicWebController1 *webViewVc = [[SUPublicWebController1 alloc] initWithViewModel:viewModel];
        [self.navigationController pushViewController:webViewVc animated:YES];
    };
}
/// 滚动到顶部
- (void)_scrollToTop {
    [self.tableView setContentOffset:CGPointMake(0, 0) animated:YES];
}
#pragma mark - Override
//// 下拉刷新
- (void)tableViewDidTriggerHeaderRefresh{
    /// 先调用父类的加载数据
    [super tableViewDidTriggerHeaderRefresh];
    /// 加载banners data
    [self.viewModel loadBannerData:^(id responseObject) {
        /// 配置数据
        self.headerView.imageURLStringsGroup = self.viewModel.banners;
        self.headerView.hidden = !(self.viewModel.banners.count>0);
    } failure:nil];
}
/// config  cell
- (UITableViewCell *)tableView:(UITableView *)tableView dequeueReusableCellWithIdentifier:(NSString *)identifier forIndexPath:(NSIndexPath *)indexPath
{
    SUGoodsCell *cell = [tableView dequeueReusableCellWithIdentifier:NSStringFromClass([SUGoodsCell class])];
    /// 处理事件
    @weakify(self);
    /// 头像
    cell.avatarClickedHandler = ^(SUGoodsCell *goodsCell) {
        @strongify(self);
        SUGoodsItemViewModel *viewModel = self.viewModel.dataSource[indexPath.row];
        [self _pushToPublicViewControllerWithTitle:viewModel.goods.nickName];
    };
    /// 位置
    cell.locationClickedHandler = ^(SUGoodsCell *goodsCell) {
        @strongify(self);
        SUGoodsItemViewModel *viewModel = self.viewModel.dataSource[indexPath.row];
        [self _pushToPublicViewControllerWithTitle:viewModel.goods.locationAreaName];
    };

    /// 回复
    cell.replyClickedHandler = ^(SUGoodsCell *goodsCell) {
        @strongify(self);
        SUGoodsItemViewModel *viewModel = self.viewModel.dataSource[indexPath.row];
        [self _pushToPublicViewControllerWithTitle:[NSString stringWithFormat:@"商品%@的评论列表",viewModel.goods.goodsId]];
    };

    /// 点赞
    cell.thumbClickedHandler = ^(SUGoodsCell *goodsCell) {
        @strongify(self);
        /// show loading
        [MBProgressHUD mh_showProgressHUD:@"Loading..." addedToView:self.view];
        SUGoodsItemViewModel *viewModel = self.viewModel.dataSource[indexPath.row];
        /// 点赞
        [self.viewModel thumbGoodsWithGoodsItemViewModel:viewModel success:^(NSNumber * responseObject) {
            [MBProgressHUD mh_hideHUDForView:self.view];
            NSString *tips = (responseObject.boolValue)?@"收藏商品成功":@"取消收藏商品";
            [MBProgressHUD mh_showTips:tips];
            /// reload data
            [self.tableView reloadData];
        } failure:nil];
    };
    return cell;
}

/// config  data
- (void)configureCell:(SUGoodsCell *)cell atIndexPath:(NSIndexPath *)indexPath withObject:(SUGoodsItemViewModel *)object
{
    /// config data (PS:由于MVVM主要是View与数据之间的绑定,但是跟 setViewModel: 差不多啦)
    [cell bindViewModel:object];
}

/// 文本内容区域
- (UIEdgeInsets)contentInset
{
    return UIEdgeInsetsZero;
}

#pragma mark - UITableViewDelegate
- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    /// 由于使用系统的autoLayout来计算cell的高度,每次滚动时都要重新计算cell的布局以此来获得cell的高度 这样一来性能不好
    /// 所以笔者采用实现计算好的cell的高度
    return [self.viewModel.dataSource[indexPath.row] cellHeight];
}
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    [tableView deselectRowAtIndexPath:indexPath animated:YES];
    // 跳转到商品详请
    [self _pushToPublicViewControllerWithTitle:@"商品详情"];
}

#pragma mark - UIScrollViewDelegate
- (void)scrollViewDidScroll:(UIScrollView *)scrollView {
    CGFloat offsetY = scrollView.contentOffset.y;
    self.scrollToTopButton.hidden = (offsetY < scrollView.mh_height);

    CGFloat duration = 0.65;
    CGFloat titleViewAlpha = (offsetY >= 0)?1.0:0.;
    CGFloat navBarAlhpa = (offsetY >= self.headerView.mh_height)?1.0:0.0;

    navBarAlhpa = (offsetY - self.headerView.mh_height) / self.headerView.mh_height + 1;

    [UIView animateWithDuration:duration animations:^{
        self.navBar.backgroundColor = MHAlphaColor(254.0f, 132.0f, 154.0f, navBarAlhpa);
        self.titleView.alpha = titleViewAlpha;
    }];

    UIStatusBarStyle tempStyle = (offsetY >= self.headerView.mh_height)?UIStatusBarStyleLightContent:UIStatusBarStyleDefault;
    BOOL tempStatusBarHidden = (offsetY >= 0)?NO:YES;
    if ((tempStyle == style_) && (tempStatusBarHidden == statusBarHidden_)) {
    } else {
        style_ = tempStyle;
        statusBarHidden_ = tempStatusBarHidden;
        /// 更新状态栏
        [self setNeedsStatusBarAppearanceUpdate];
    }
}

#pragma mark - 辅助方法
/// 跳转界面 这里只是一个跳转,实际情况,自行定夺
- (void)_pushToPublicViewControllerWithTitle:(NSString *)title
{
    SUPublicViewModel1 *viewModel = [[SUPublicViewModel1 alloc] initWithParams:@{SUViewModelTitleKey:title}];
    SUPublicController1 *publicVC = [[SUPublicController1 alloc] initWithViewModel:viewModel];
    [self.navigationController pushViewController:publicVC animated:YES];
}

////////////////// 以下为UI代码,不必过多关注 ///////////////////
#pragma mark - UITableViewDelegate
- (CGFloat)tableView:(UITableView *)tableView heightForFooterInSection:(NSInteger)section {
    return .0001f;
}

- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section {
    /// FIXED : when data is empty ,the backgroundColor is exist
    return (self.viewModel.dataSource.count==0)?.0001f:53;
}
- (UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section {
    /// FIXED : when data is empty ,show nothing
    if (self.viewModel.dataSource.count==0) return nil;

    SUGoodsHeaderView *sectionHeader = [tableView dequeueReusableHeaderFooterViewWithIdentifier:NSStringFromClass([SUGoodsHeaderView class])];
    sectionHeader.backgroundColor = self.view.backgroundColor;
    return sectionHeader;
}

#pragma mark - Override
- (UIStatusBarStyle)preferredStatusBarStyle {
    return style_;
}
- (BOOL)prefersStatusBarHidden {
    return statusBarHidden_;
}

#pragma mark - 初始化子控件
- (void)_setupSubViews
{
    /// Create NavBar;
    UIView *navBar = [[UIView alloc] initWithFrame:CGRectMake(0, 0, MHMainScreenWidth, self.navigationController.navigationBar.mh_height+20)];
    navBar.backgroundColor = MHAlphaColor(254.0f, 88.0f, 62.0f, .0f) ;
    self.navBar = navBar;
    [self.view addSubview:navBar];

    /// 搜索框View
    CGFloat titleViewX = 26;
    CGFloat titleViewH = 28;
    CGFloat titleViewY = 20 + floor((navBar.mh_height - 20 - titleViewH)/2);
    CGFloat titleViewW = MHMainScreenWidth - 2 * titleViewX;
    SUSearchBarView *titleView = [[SUSearchBarView alloc] initWithFrame:CGRectMake(titleViewX, titleViewY, titleViewW, titleViewH)];
    titleView.backgroundColor = [UIColor whiteColor];
    self.titleView = titleView;
    [navBar addSubview:titleView];

    /// 滚动到顶部的按钮
    CGFloat scrollToTopButtonW = 52;
    CGFloat scrollToTopButtonH = 90;
    CGFloat scrollToTopButtonX = (MHMainScreenWidth - scrollToTopButtonW) - 12;
    CGFloat scrollToTopButtonY = (MHMainScreenHeight - scrollToTopButtonH) - 60;
    UIButton *scrollToTopButton = [[UIButton alloc] initWithFrame:CGRectMake(scrollToTopButtonX, scrollToTopButtonY, scrollToTopButtonW, scrollToTopButtonH)];
    [scrollToTopButton setImage:[UIImage imageNamed:@"home_page_scroll_to_top"] forState:UIControlStateNormal];
    scrollToTopButton.hidden = YES;
    self.scrollToTopButton = scrollToTopButton;
    [self.view addSubview:scrollToTopButton];
    //// 添加事件处理
    [scrollToTopButton addTarget:self action:@selector(_scrollToTop) forControlEvents:UIControlEventTouchUpInside];

    /// 头视图 banner
    SDCycleScrollView *headerView = [[SDCycleScrollView alloc] initWithFrame:CGRectMake(0, 0, self.tableView.mh_width, SUGoodsBannerViewHeight)];
    headerView.autoScrollTimeInterval = 5.0f;
    headerView.pageControlStyle = SDCycleScrollViewPageContolStyleAnimated;
    headerView.placeholderImage = MHWebPlaceholderImage();
    self.headerView = headerView;
    /// default is Hidden until have data to show
    headerView.hidden = YES;
    headerView.backgroundColor = [UIColor whiteColor];
    self.tableView.tableHeaderView = headerView;
}
@end


text:
import errorMap from './error-map';

function VASTError(code = 'default') {
  var error = errorMap[code];
  this.name = 'VASTError';
  this.message = `${error.node}: ${error.message}`;
  this.stack = (new Error()).stack;
}

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

export default VASTError;


text:
/* eslint-disable no-console */
const { createDefaultEnvironment } = require('@cardstack/test-support/env');
const JSONAPIFactory = require('@cardstack/test-support/jsonapi-factory');

const openAPIPatch = [
  // Workaround for https://www.drupal.org/node/2902117
  {
    op: "add",
    path: "/definitions/node:recipe/properties/attributes/properties/difficulty/enum",
    value: ["easy", "medium", "hard"]
  },

  // Workaround for https://www.drupal.org/node/2902127
  {
    op: "add",
    path: "/definitions/node:recipe/properties/type/enum",
    value: ["recipes"]
  },
  {
    op: "add",
    path: "/definitions/node:article/properties/type/enum",
    value: ["articles"]
  },
  {
    op: "add",
    path: "/definitions/node:page/properties/type/enum",
    value: ["pages"]
  },
  {
    op: "add",
    path: "/definitions/node:tutorial/properties/type/enum",
    value: ["node--tutorial"]
  },
  {
    op: "add",
    path: "/definitions/media:image/properties/type/enum",
    value: ["images"]
  },

  // Workaround for https://www.drupal.org/node/2902112
  {
    op: "replace",
    path: "/basePath",
    value: "/"
  }
];

async function go() {
  let factory = new JSONAPIFactory();
  factory.addResource('data-sources').withAttributes({
    'source-type': '@cardstack/drupal',
    params: {
      url: 'http://localhost',
      authToken: process.env.DRUPAL_TOKEN,
      openAPIPatch
    }
  });
  factory.addResource('plugin-configs').withAttributes({
    module: '@cardstack/drupal'
  });
  await createDefaultEnvironment(__dirname + '/../', factory.getModels());
}

async function login() {
  let request = require('superagent');
  let response = await request.post('http://localhost/oauth/token')
      .type('form')
      .send({
        client_id: '3e1a2872-e329-47f4-8447-3b4589744de6',
        client_secret: 'contenta',
        grant_type: 'password',
        username: 'edward',
        password: 'contenta'
      });
  process.stdout.write(`\n export DRUPAL_TOKEN=${response.body.access_token}\n\n`);
}

let main = go;
if (process.argv.includes("login")) {
  main = login;
}
main().then(() => process.exit(0), err => { console.log(err); process.exit(-1); });


text:
[![Build Status](https://travis-ci.org/Nirespire/lolcaptions.svg?branch=master)](https://travis-ci.org/Nirespire/lolcaptions)

## Overview
This personal project was undertaken to remake the flash game of a similar name.
The last place I could find the game was [here](http://www.kongregate.com/games/gyre_o_guile/lolcaptions), but it has
since stopped functioning. The purpose of this project is to remake that same game using Node and adding fun features
that I would have liked to see when playing it with my friends.

The basic idea is you have a room of at least 2 players, and they each get to submit a caption to a random picture. Everyone anonymously votes for the caption they like the best, and the winner gets some points. Repeat each round.

## How to run
- ```npm install```
- ```node index.js```
- Client can connect to port 8080 by default

## Current Feaures
- Multiplayer lobby and chat run by [SocketIO](http://socket.io/)
- Multiplayer chat
- Support for Twitch emotes thanks to [code](https://github.com/popcorncolonel/Chrome-Extensions/tree/master/Kappa%20Everywhere) form [popcorncolonel](https://github.com/popcorncolonel)
- Game is playable but still looking rough on general looks

## TODO
- ~~Get chat working again~~
- ~~Build username register screen~~
- ~~Configure Imgur API to retreive random, captionable images~~
- ~~Fix display of random images (size and position)~~
- ~~Build image voting system~~
- ~~Build caption submitting system~~
- ~~Build caption voting system~~
- Build scoring system
- Build players, scores and images display
- ~~Build winner screen~~ sort of
- Reorganize UI into 3 columns (caption submitting/voting, image display, chat)


text:
namespace _winml {

class OnnxruntimeEngineBuilder;
class OnnxruntimeEngineFactory;
class OnnxruntimeEnvironment;
class OnnxruntimeModel;
class OnnxruntimeEngine;
class OnnxruntimeThreading;

struct IOrtSessionBuilder;

class OnnxruntimeValue : public Microsoft::WRL::RuntimeClass<
                             Microsoft::WRL::RuntimeClassFlags<Microsoft::WRL::ClassicCom>,
                             IValue> {
 public:
  OnnxruntimeValue();
  ~OnnxruntimeValue();

  HRESULT RuntimeClassInitialize(OnnxruntimeEngine* engine, UniqueOrtValue&& value, UniqueOrtAllocator&& allocator);

  STDMETHOD(IsEmpty)
  (bool* out) override;
  STDMETHOD(IsCpu)
  (bool* out) override;
  STDMETHOD(GetResource)
  (_winml::Resource& resource) override;
  STDMETHOD(IsTensor)
  (bool* out) override;
  STDMETHOD(IsOfTensorType)
  (winml::TensorKind kind, bool* out) override;
  STDMETHOD(GetTensorShape)
  (std::vector<int64_t>& shape_vector) override;
  STDMETHOD(IsOfMapType)
  (winml::TensorKind key_kind, winml::TensorKind value_kind, bool* out) override;
  STDMETHOD(IsOfVectorMapType)
  (winml::TensorKind key_kind, winml::TensorKind value_kind, bool* out) override;
  STDMETHOD(IsOfVectorTensorType)
  (winml::TensorKind kind, bool* out) override;

  HRESULT(SetParameter)
  (IUnknown* param);
  OrtValue* UseOrtValue();
  HRESULT AssignOrtValue(OrtValue* ptr);

 private:
  Microsoft::WRL::ComPtr<OnnxruntimeEngine> engine_;
  Microsoft::WRL::ComPtr<IUnknown> param_;
  UniqueOrtValue value_;
  UniqueOrtAllocator allocator_;
};

class OnnxruntimeEngine : public Microsoft::WRL::RuntimeClass<
                              Microsoft::WRL::RuntimeClassFlags<Microsoft::WRL::ClassicCom>,
                              IEngine> {
 public:
  OnnxruntimeEngine();
  HRESULT RuntimeClassInitialize(OnnxruntimeEngineFactory* engine_factory, UniqueOrtSession&& session, IOrtSessionBuilder* session_builder);

  STDMETHOD(LoadModel)
  (_In_ IModel* model) override;
  STDMETHOD(Initialize)
  () override;
  STDMETHOD(RegisterGraphTransformers)
  () override;
  STDMETHOD(RegisterCustomRegistry)
  (IMLOperatorRegistry* registry) override;
  STDMETHOD(EndProfiling)
  () override;
  STDMETHOD(StartProfiling)
  () override;
  STDMETHOD(FlushContext)
  () override;
  STDMETHOD(ReleaseCompletedReferences)
  () override;
  STDMETHOD(Sync)
  () override;
  STDMETHOD(CreateTensorValue)
  (const int64_t* shape, size_t count, winml::TensorKind kind, _Out_ IValue** out) override;
  STDMETHOD(CreateTensorValueFromExternalD3DResource)
  (ID3D12Resource* resource, const int64_t* shape, size_t count, winml::TensorKind kind, _Out_ IValue** out) override;
  STDMETHOD(CreateTensorValueFromExternalBuffer)
  (void* data, size_t size_in_bytes, const int64_t* shape, size_t count, winml::TensorKind kind, _Out_ IValue** out) override;
  STDMETHOD(CreateStringTensorValueFromDataWithCopy)
  (const char* const* data, size_t num_elements, const int64_t* shape, size_t count, _Out_ IValue** out) override;
  STDMETHOD(CreateNullValue)
  (_Out_ IValue** out) override;
  STDMETHOD(CreateMapValue)
  (IInspectable* map, winml::TensorKind key_kind, winml::TensorKind value_kind, _Out_ IValue** out) override;
  STDMETHOD(CreateSequenceOfMapsValue)
  (IInspectable* map, winml::TensorKind key_kind, winml::TensorKind value_kind, _Out_ IValue** out) override;
  STDMETHOD(CreateSequenceOfValuesValue)
  (IValue ** values, size_t size, IValue * *out) override;

  STDMETHOD(CreateOneInputAcrossDevices)
  (const char* name, IValue* src, IValue** dest) override;
  STDMETHOD(CopyValueAcrossDevices)
  (IValue* src, IValue* dest) override;
  STDMETHOD(Run)
  (const char** input_names, IValue** inputs, size_t num_inputs, const char** output_names, IValue** outputs, size_t num_outputs) override;
  STDMETHOD(FillFromMapValue)
  (IInspectable* map, winml::TensorKind key_kind, winml::TensorKind value_kind, IValue* value) override;
  STDMETHOD(FillSequenceOfMapsValue)
  (IInspectable* sequence, winml::TensorKind key_kind, winml::TensorKind value_kind, IValue* value) override;

  STDMETHOD(GetSequenceOfTensorValues)
  (_In_  _winml::IValue* sequence_value, _Out_ std::vector<winrt::com_ptr<_winml::IValue>>& out_values) override;

  STDMETHOD(GetNumberOfIntraOpThreads)
  (uint32_t* num_threads) override;

  STDMETHOD(GetIntraOpThreadSpinning)
  (bool* allow_spinning) override;

  STDMETHOD(GetNamedDimensionOverrides)
  (wfc::IMapView<winrt::hstring, uint32_t>& overrides) override;

  OrtSession* UseOrtSession();
  const OrtApi* UseOrtApi();
  OnnxruntimeEngineFactory* GetEngineFactory();
  HRESULT CreateTensorValueFromDefaultAllocator(const int64_t* shape, size_t count, winml::TensorKind kind, _Out_ IValue** out);

 private:
  Microsoft::WRL::ComPtr<OnnxruntimeEngineFactory> engine_factory_;
  Microsoft::WRL::ComPtr<IOrtSessionBuilder> session_builder_;
  UniqueOrtSession session_;
};

class OnnxruntimeEngineFactory : public Microsoft::WRL::RuntimeClass<
                                     Microsoft::WRL::RuntimeClassFlags<Microsoft::WRL::ClassicCom>,
                                     IEngineFactory> {
 public:
  HRESULT RuntimeClassInitialize();
  STDMETHOD(CreateModel)
  (_In_ const char* model_path, _In_ size_t len, _Outptr_ IModel** out) override;
  STDMETHOD(CreateModel)
  (_In_opt_ void* data, _In_ size_t size, _Outptr_ IModel** out) override;
  STDMETHOD(CreateEmptyModel)
  (_In_ int64_t opset, _Outptr_ IModel** out) override;
  STDMETHOD(CreateEngineBuilder)
  (_Outptr_ IEngineBuilder** engine_builder) override;
  STDMETHOD(EnableDebugOutput)
  (bool is_enabled) override;
  STDMETHOD(CreateCustomRegistry)
  (_Out_ IMLOperatorRegistry** registry) override;

  const OrtApi* UseOrtApi();
  const WinmlAdapterApi* UseWinmlAdapterApi();
  HRESULT EnsureEnvironment();
  HRESULT GetOrtEnvironment(_Out_ OrtEnv** ort_env);

  STDMETHOD(CreateTensorDescriptorInfo)
  (_In_ winml::TensorKind kind, _In_ int64_t* dims, _In_ size_t num_dims, _Out_ IDescriptorInfo** info) override;

  STDMETHOD(CreateSequenceDescriptorInfo)
  (_Out_ IDescriptorInfo** info) override;

  STDMETHOD(CreateMapDescriptorInfo)
  (_Out_ IDescriptorInfo** info) override;

  STDMETHOD(CreateThreadPool)
  (_In_ bool allow_spinning, _In_ uint32_t num_intra_op_threads, _Out_ IThreading** thread_pool) override;

 private:
  const OrtApi* ort_api_ = nullptr;
  const WinmlAdapterApi* winml_adapter_api_ = nullptr;
  std::shared_ptr<OnnxruntimeEnvironment> environment_;
  std::mutex mutex_;
};

class OnnxruntimeThreading : public Microsoft::WRL::RuntimeClass<
                                  Microsoft::WRL::RuntimeClassFlags<Microsoft::WRL::ClassicCom>,
                                  IThreading> {
public:
  OnnxruntimeThreading();
  ~OnnxruntimeThreading();

  HRESULT RuntimeClassInitialize(OnnxruntimeEngineFactory* engine_factory);

  HRESULT SetIntraOpThreadPool(UniqueOrtThreadPool&& intra_op_ort_pool);
  HRESULT SetInterOpThreadPool(UniqueOrtThreadPool&& inter_op_ort_pool);
  OrtThreadPool* UseIntraOpThreadPool();
  OrtThreadPool* UseInterOpThreadPool();

private:
  Microsoft::WRL::ComPtr<OnnxruntimeEngineFactory> engine_factory_ = nullptr;
  UniqueOrtThreadPool inter_op_ort_pool_;
  UniqueOrtThreadPool intra_op_ort_pool_;

};

}  // namespace _winml


text:
layout: contributor-profile
credit-name: Max Cole-Takanikos
first-name: Max
last-name: Cole-Takanikos
file-as: c
role: Author
role-2:
role-3:
title: Max Cole-Takanikos — Work in Fireside
description:
twitter-handle:
profile-pic:
website-url: maxcoletakanikos.com
short-name: max-cole-takanikos
permalink: max-cole-takanikos
---
Max Cole-Takanikos is an illustrator, graphic designer, storyteller, tattoo artist, and real human being from Seattle, Washington. Enjoys watching science fiction, sifting through vintage clothing racks, and swimming in the sea.


text:
<action-sheet
  action-sheet-show="showMenu">

Website

          {{data}}

Open website

      Cancel

Bitcoin Address

          {{data}}

Add as a contact

Send payment to this address

Copy to clipboard

      Cancel

Text

          {{data}}

Copy to clipboard

      Cancel

Private Key

          {{data}}

Sweep paper wallet

Copy to clipboard

      Cancel

</action-sheet>


text:
#pragma once

namespace hadesmem
{
class Process;
}

void DumpMemory(hadesmem::Process const& process);


text:
                <etb-info-menu class="pull-right"></etb-info-menu>

Release Notes

2.0.17 - 28.03.17

Sticky Routes only for long lists (sets and tunes)

2.0.15 - 20.03.17

Restoring scroll position when navigating back

Sticky Routes (pages don't reload every time when navigating back)

Ahead of Time Compilation (faster loading)

2.0.11 - 18.09.16

Two new buttons: Show Tune in Tune List and Show Set in Set List

State of Sorting of Tune List and Set List memorized

2.0.4 - 17.08.16

Tune Randomizer, Filter and Info moved from SideNavigation to TopNavigation

Navigation items turn yellow and get disabled when active

Sort Buttons turn yellow when active

Active Sort Buttons show sort direction

Scroll to top of page after pressing Sort Button

Buttons for Scrolling to Top and Bottom of Page

2.0.3 - 09.08.16

Give playdate more room in playlist view.

Refresh playdate every minute (angular2-moment)

2.0.2 - 08.08.16

Fix for Duplication of Midi Download Button

Refreshing Page didn't work. Fixed

2.0.1 - 07.08.16

Download Tune in Midi Format

Offline didn't work. Fixed

2.0.0 - 25.07.16

Major visual redesign. Enhanced usability on small devices.

Major internal redesign: Migration to Typescript, Angular 2 and Bootstrap 4.

Tunes can now be combined to sets by drag and drop

Tunes, Sets, Playlists, Videos, Links are now displayed as cards

Notes, Sets, Videos, Links are shown all together for a tune.

Playlists where a set is involved are now shown beneath the set.

Stateful Filter: Filtersettings apply to Tunes, Sets, Playlists and the Tune Randomizer

Enhanced Gig List Navigation. No more scrolling. Isolated view of Playlist Position.

New Option for displaying notes for tunes in a playlist position: 4 or 8 bars, or the whole tune.

Deprecated: Tune: Skill

Deprecated: Tune: Repeat and Annotation. These informations are now entered only in the context of a
                        playlist

Deprecated: Note Editor

Deprecated: Import/Export from and to Google Drive via Web API

1.2.4 - 11.08.14

Print Playlists.

Bug-Fix (Workaround for Bootstrap issue): Dropdown in Navbar is now visible on small devices.

Show previous Play Position when navigating back from tune or set.

1.2.3 - 03.08.14

Collapse and Expand Playlist Positions.

Navigation within Playlists using Play, Fordŵard and Backward Buttons.

Show color of tune in Playlist View.

Navigate from Tune to Playlist (Playlist filtered by Tune).

Button for new Tune, new Playlist and new Playlist Position moved to bottom of viewport.

Temporarily removed loading bar (due to version conflicts).

Removed Skill in Tune and Set List.

Removed Tunes Dropdown in Tune View.

Bug-Fix: Determination of next Playlist Id.

Bug-Fix: Importing Tunebook without eTb Directives.

Bug-Fix: Importing and Exporting Tunebook with special characters (spanish).

1.2.2 - 16.04.14

Display current Filter.

Copy a Playlist Position to another Playlist.

Delete Button for Tunes.

1.2.1 - 02.03.14

Copy Playlists.

Override Repeat and Annotations of a Tune in a Playlist.

Specify Part Play Infos for a Tune in a Playlist.

Numbering Tunes per Set in a Playlist.

Delete Confirm when deleting Playlists, Playlist Positions, Part Play Infos and TuneSet Positions.

Fixed broken Type Filter.

1.2.0 - 09.01.14

eTuneBook runs offline in case there is no internet connection.

Playlists: Group your sets into collections or gig lists.

Deprecated: TuneSet Target (replaced by Playlist Event)

Deprecated: TuneSet Environment (replaced by Playlist Band)

Deprecated: TuneSet Name (replaced by Playlist-Position Name)

1.1.8 - 27.11.13

Note Editor: Edit Note elements by choosing from options instead of typing text: Chord, Fingering, Accidental,
                        Note, Octave and Length.

1.1.7 - 12.11.13

Export TuneBook to Google Drive.

Import TuneBook from Google Drive.

Loading Bar during HTML Requests.

Fixed broken Video.

1.1.6 - 18.10.13

Optimization for small screens: ngTouch for faster clicks.

Same Filter for Tunes and Sets.

Filter for a given range of playing frequency.

Filter for a given range of modification dates.

Filter for a given range of play dates.

Picking date ranges by bootstrap-daterangepicker.

'Just played the Set' can now be pressed directly on the Set List.

1.1.5 - 10.10.13

Search-Box on Tune-Set-List (although not refreshing yet upon removing the search text again. work in
                        progress...).

Search-Box on Tune-List (skipped ng-grid column menu).

Navigating back from a Set: Set should now be first set on list (buz id not in most cases. work in progress...).

Navigating back from a Tune: Tune is now first tune on list.

Buttons: YouTube, FaceBook, Twitter.

Optimization for small screens: Less Tune-Set-List-Columns on mobile Devices.

Optimization for small screens: Less Tune-List-Columns on mobile Devices.

TuneBook was cached by Browser which prevented loading of new Versions. Cache removed from Ajax-Request.

Creating a new Set by copying/moving a Tune (by not choosing a Target).

Moving Tunes within same Set was broken. Fixed now.

1.1.4 - 29.09.13

Random Selection of Tunes and Sets: Filter by Playdates.

Tune-View: Sets-Selection navigates away to Set-View, if only one Set exists.

Tune- and Set-List: Links to Record-Views by Standard Anchors.

Set-List: Link to Tune-View.

Moving/Copying Tunes was broken. Fixed now.

1.1.3 - 16.09.13

Random Tune in Tune-View, Random Set in Set-View.

Tune-Selection in Tune-View, Set-Selection in Set-View.

Optimization for small screens: Tune Dropdown Button instead of Tabs.

Optimization for small screens: NavBar Buttons, non-collapsing.

Optimization for small screens: BookTitle removed from Navbar.

1.1.2 - 12.09.13

Optimization for small screens: Tune-Set-Filter moved from bottom-fixed NavBar to a Modal Dialog.

Optimization for small screens: BookTitle moved to Navbar.

Fixed broken Modals in Set-View (Bootstrap Migration Part 2).

1.1.1 - 09.09.13

Fixed broken Navigation from the Set-View to the Tune-View in Firefox and IE.

Angular-UI-Router Version 0.2.0

Angular Version 1.0.8. Removed Animation Stuff.

Bootstrap Version 3.0.0. Fix for broken Navigation on Smartphones.

1.1.0 - 31.07.13

Major Rework of Navigation (migrated to ui-router): Tune List, Set List, Tune Editor and Set Editor.

Top Navigation simplified to: Book, Sets, Tunes, Info.

Edit Book Title, Version and Description (Book Editor).

Introduction of fast scrolling List Grids (migrated to ng-grid).

New Tune List (ng-grid) supporting fast sorting, filtering and grouping.

Set-Editor: Sorting TuneSet Position as Number (sets having more than 10 Tunes are now sorted as they
                        should)

Dropped support for offline modus (appcache skipped).

Temporarily dropped Midi Support due to problems with the Quicktime-Plugin.

Midi-Support will be re-introduced as soon as abcjs will support javascript Midi.

Major Rework of how videos and external sites ar managed (ng-grid). You can now add more than 3 records.

'Just played the set' puts the current date and time on all tunes in a set.

'Just played the tune' can be clicked in the Set Editor and the Tune Editor.

Filter sets for Target, Environment and Name of TuneSet.

Delete a set position.

Add a new Set for an existing tune.

Add a comment specific for a set position.

Development/Deployment: Migrated to WebStorm and Yeoman.

1.0.7 - 23.05.13

Fixed New TuneBook/New Tune, which was broken when no TuneBook was imported before.

Export TuneBook to a File on your hard disk.

Edit TuneSet Infos: Target, Environment and Name of TuneSet.

Fixed broken dropdown when navigation bar was collapsed

Copy a tune to another set

1.0.6 - 28.04.2013

New Tune was broken. Fixed now.

Dots scale increased

Settings: Removed Show/Hide Info,Edit,Rehearse Buttons

abcjs: 1.6 -> 1.7

Change in Topnavigation: Color and Shading

abcjs: 1.3 -> 1.6

Bootstrap: 2.0.4 -> 2.3.1

Angular: 1.0.4 -> 1.0.6

Playing tunes on a MIDI Instrument (IE not supported)

Sets are now printable

Sorting by last modification date

Single Tunes are now printable

1.0.5 - 13.02.2013

Tunebook Name, Version and Description is now extracted from the abc-header.

Fixed broken Random-Sorting.

First Version of Deep-Linking. Browser Back- and Forward-Button now supported.

1.0.3 - 22.12.2012

FaceBook LikeBox

First version of tune transposer

1.0.2 - 09.12.2012

Twice the same tune title in one set: dots are now rendered.

Introduced more compact session modus for smaller screens.

1.0.1 - 15.10.2012

Total tune set count fixed in key-selector.

The following settings are now remembered (stored in local storage): Which buttons to show, filter and
                        sort algorithm, selected page.

Reduced page size from 10 sets to 5.

Reduced sample dots to 4 bars.

1.0.0 - 05.10.2012

Launch of eTuneBook

Added AppCache for offline work.

Fixed broken fingering-switch and extended it to sample dots.

Fixed disappearing of sample dots after editing.


text:
//
//  QZKitDelegate.h
//  SDk
//
//  Created by tang.johannes on 15/1/23.
//  Copyright (c) 2015年 tang.johannes. All rights reserved.
//

#import <Foundation/Foundation.h>
#import <UIKit/UIKit.h>

@class QUserInfo;
@class QAgentInfo;
@class QMessageRecvInfo;

typedef enum {
    ParamTypePhoneNumber, /**< 电话号码  */
    ParamTypeQZId         /**< 青芝Id  */
} ParamType;

extern NSString * const AbilityIM;
extern NSString * const AbilityPhone;
extern NSString * const AbilityAgent;

extern NSString * const QAgentEventServiceStart;//客户分配给坐席,坐席开始振铃
extern NSString * const QAgentEventServicePickup;//客户分配给坐席,坐席摘机
extern NSString * const QAgentEventServiceEnd;//坐席服务结束
extern NSString * const QAgentEventServiceComplete;//坐席服务完成

extern NSString * const MessageInChatRecvRangeAll; //普通聊天消息范围涉及所有sender-id,不涉及群聊范围

@protocol QZUCCDelegate <NSObject>

@required

/**
 * 获取AppDelegate下root view ctrl
 * @return self.window.rootViewController;
 */
- (UIViewController *)getAppRootViewController;

/**
 * 查询用户
 * @param paramString 参数字符串
 * @param type 参数类型,详见ParamType
 * @return 查询成功返回QUserInfo对象,否则返回nil
 */
- (QUserInfo *)getQUserInfo:(NSString *)paramString type:(ParamType)type;

/**
 * 各能力状态变化事件
 * @param ability 能力类型,参见Ability常量定义
 * @param state 状态值,取值0、1,其中1--初始化完成且连接成功,0则是断开连接
 * @return
 */
- (void)onAbilityStateChange:(NSString *)ability state:(int)state;

/**
 * 座席状态变化事件
 * @param agentInfo 座席信息,详见各属性描述
 *
 */
- (void)onAgentStatusEventChange:(QAgentInfo *)agentInfo;

/**
 * 坐席服务事件
 * @param eventDic  - 事件详情内容
 * @param type - 事件类型,参见QAgentEventService常量定义
 * @return
 */
- (void)onAgentServiceEventChange:(NSDictionary *)eventDic eventType:(NSString *)type;

/**
 * 指定sender_id订阅来自其所发送的消息,当有指定Id后,sdk接收该sender_id的消息后执行<onRecvMessageFromSubscribeSenderIds:>回调方法
 * 其中sender_id的取值范围:
 * --   1.普通用户,则直接填写qz_id;
 * --   2.后台服务中消息中转代理模块的特定用户,则由后台开发人员指定;
 * 若返回 @[MessageInChatRecvRangeAll], 则订阅所有普通聊天, 但不涉及群聊天;其中MessageInChatRecvRangeAll为常量;
 */
- (NSArray *)subscribeMessageFromSenderIds;

/*
 * 接收subscribeMessageFromSenderIds中指定sender_id发来的消息
 * @param msgInfo 消息对象
 */
- (void)onRecvMessageFromSubscribeSenderIds:(QMessageRecvInfo *)msgInfo;

@end


text:
#include <iostream>

#include <llamaos/api/sleep.h>
#include <llamaos/api/pci/PCI.h>

using namespace std;
using namespace llamaos::api;
using namespace llamaos::api::pci;

int main (int /* argc */, char ** /* argv [] */)
{
   cout << "running 82574 llamaNET domain...\n" << endl;
   PCI pci;
   sleep (1);
   cout << "PCI config:" << endl;
   cout << pci << endl << endl;

   cout << "waiting 1 sec, then exit..." << endl;
   cout.flush ();
   sleep (1);

   return 0;
}


text:
import os
import unittest

from py4j.protocol import Py4JJavaError

from pyspark import keyword_only
from pyspark.testing.utils import PySparkTestCase
from pyspark.find_spark_home import _find_spark_home

class KeywordOnlyTests(unittest.TestCase):
    class Wrapped:
        @keyword_only
        def set(self, x=None, y=None):
            if "x" in self._input_kwargs:
                self._x = self._input_kwargs["x"]
            if "y" in self._input_kwargs:
                self._y = self._input_kwargs["y"]
            return x, y

    def test_keywords(self):
        w = self.Wrapped()
        x, y = w.set(y=1)
        self.assertEqual(y, 1)
        self.assertEqual(y, w._y)
        self.assertIsNone(x)
        self.assertFalse(hasattr(w, "_x"))

    def test_non_keywords(self):
        w = self.Wrapped()
        self.assertRaises(TypeError, lambda: w.set(0, y=1))

    def test_kwarg_ownership(self):
        # test _input_kwargs is owned by each class instance and not a shared static variable
        class Setter:
            @keyword_only
            def set(self, x=None, other=None, other_x=None):
                if "other" in self._input_kwargs:
                    self._input_kwargs["other"].set(x=self._input_kwargs["other_x"])
                self._x = self._input_kwargs["x"]

        a = Setter()
        b = Setter()
        a.set(x=1, other=b, other_x=2)
        self.assertEqual(a._x, 1)
        self.assertEqual(b._x, 2)

class UtilTests(PySparkTestCase):
    def test_py4j_str(self):
        with self.assertRaises(Py4JJavaError) as context:
            # This attempts java.lang.String(null) which throws an NPE.
            self.sc._jvm.java.lang.String(None)

        self.assertTrue("NullPointerException" in str(context.exception))

    def test_parsing_version_string(self):
        from pyspark.util import VersionUtils

        self.assertRaises(ValueError, lambda: VersionUtils.majorMinorVersion("abced"))

    def test_find_spark_home(self):
        # SPARK-38827: Test find_spark_home without `SPARK_HOME` environment variable set.
        origin = os.environ["SPARK_HOME"]
        try:
            del os.environ["SPARK_HOME"]
            self.assertEquals(origin, _find_spark_home())
        finally:
            os.environ["SPARK_HOME"] = origin

if __name__ == "__main__":
    from pyspark.tests.test_util import *  # noqa: F401

    try:
        import xmlrunner  # type: ignore[import]

        testRunner = xmlrunner.XMLTestRunner(output="target/test-reports", verbosity=2)
    except ImportError:
        testRunner = None
    unittest.main(testRunner=testRunner, verbosity=2)


text:
/**
 * @file led.cpp
 *
 * LED driver.
 */

#include <px4_config.h>
#include <px4_posix.h>
#include <drivers/device/device.h>
#include <drivers/drv_led.h>
#include <stdio.h>

/*
 * Ideally we'd be able to get these from up_internal.h,
 * but since we want to be able to disable the NuttX use
 * of leds for system indication at will and there is no
 * separate switch, we need to build independent of the
 * CONFIG_ARCH_LEDS configuration switch.
 */
__BEGIN_DECLS
extern void led_init();
extern void led_on(int led);
extern void led_off(int led);
extern void led_toggle(int led);
__END_DECLS

#ifdef __PX4_NUTTX
class LED : device::CDev
#else
class LED : device::VDev
#endif
{
public:
	LED();
	virtual ~LED();

	virtual int		init();
	virtual int		ioctl(device::file_t *filp, int cmd, unsigned long arg);
};

LED::LED() :
#ifdef __PX4_NUTTX
	CDev("led", LED0_DEVICE_PATH)
#else
	VDev("led", LED0_DEVICE_PATH)
#endif
{
	// force immediate init/device registration
	init();
}

LED::~LED()
{
}

int
LED::init()
{
	debug("LED::init");
#ifdef __PX4_NUTTX
	CDev::init();
#else
	VDev::init();
#endif
	led_init();

	return 0;
}

int
LED::ioctl(device::file_t *filp, int cmd, unsigned long arg)
{
	int result = OK;

	switch (cmd) {
	case LED_ON:
		led_on(arg);
		break;

	case LED_OFF:
		led_off(arg);
		break;

	case LED_TOGGLE:
		led_toggle(arg);
		break;

	default:
#ifdef __PX4_NUTTX
		result = CDev::ioctl(filp, cmd, arg);
#else
		result = VDev::ioctl(filp, cmd, arg);
#endif
	}
	return result;
}

namespace
{
LED	*gLED;
}

void
drv_led_start(void)
{
	if (gLED == nullptr) {
		gLED = new LED;
		if (gLED != nullptr)
			gLED->init();
	}
}


text:
* Not a group of servers
* A sum of resources of all the servers
* Do not deploy to a server
* Instruct a scheduler what the requirements are
* Scheduler decides where to deploy

# Docker Machine

* Lightweight VM
* Very simple
* Prepared for Docker
* Good for local simulation
* Bad for production usage

## Creating DM Servers

```bash
docker-machine create -d virtualbox swarm-1

docker-machine ls

docker-machine env swarm-1

eval $(docker-machine env swarm-1)

docker version

docker-machine create -d virtualbox swarm-2

docker-machine create -d virtualbox swarm-3

docker-machine ls
```

## Initializing A Swarm Cluster

```bash
docker swarm init --advertise-addr $(docker-machine ip swarm-1)

docker node ls
```

## Adding Managers

```bash
docker swarm join-token -q manager

TOKEN=$(docker swarm join-token -q manager)

eval $(docker-machine env swarm-2)

docker swarm join --advertise-addr $(docker-machine ip swarm-2) \
  --token $TOKEN $(docker-machine ip swarm-1):2377

eval $(docker-machine env swarm-3)

docker swarm join --advertise-addr $(docker-machine ip swarm-3) \
  --token $TOKEN $(docker-machine ip swarm-1):2377

docker node ls
```

## Adding Workers

```bash
docker-machine create -d virtualbox swarm-4

docker swarm join-token -q worker

TOKEN=$(docker swarm join-token -q worker)

eval $(docker-machine env swarm-4)

docker swarm join --token $TOKEN --advertise-addr $(docker-machine ip swarm-4) $(docker-machine ip swarm-1):2377

docker node ls

eval $(docker-machine env swarm-1)

docker node ls
```


text:
package org.apache.flink.runtime.scheduler;

import org.apache.flink.runtime.instance.SlotSharingGroupId;
import org.apache.flink.runtime.jobgraph.IntermediateResultPartitionID;
import org.apache.flink.runtime.jobgraph.JobVertexID;
import org.apache.flink.runtime.jobmanager.scheduler.CoLocationConstraint;
import org.apache.flink.runtime.jobmanager.scheduler.CoLocationGroup;
import org.apache.flink.runtime.jobmanager.scheduler.SlotSharingGroup;
import org.apache.flink.runtime.scheduler.adapter.DefaultExecutionTopology;
import org.apache.flink.runtime.scheduler.strategy.ConsumedPartitionGroup;
import org.apache.flink.runtime.scheduler.strategy.ExecutionVertexID;
import org.apache.flink.runtime.scheduler.strategy.SchedulingExecutionVertex;
import org.apache.flink.runtime.scheduler.strategy.SchedulingTopology;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.HashSet;
import java.util.IdentityHashMap;
import java.util.Iterator;
import java.util.LinkedHashMap;
import java.util.LinkedHashSet;
import java.util.List;
import java.util.Map;
import java.util.Objects;
import java.util.Set;

import static org.apache.flink.util.Preconditions.checkNotNull;
import static org.apache.flink.util.Preconditions.checkState;

/**
 * This strategy tries to reduce remote data exchanges. Execution vertices, which are connected and
 * belong to the same SlotSharingGroup, tend to be put in the same ExecutionSlotSharingGroup.
 * Co-location constraints will be respected.
 */
class LocalInputPreferredSlotSharingStrategy
        implements SlotSharingStrategy, SchedulingTopologyListener {

    private final Map<ExecutionVertexID, ExecutionSlotSharingGroup> executionSlotSharingGroupMap;

    private final Set<SlotSharingGroup> logicalSlotSharingGroups;

    private final Set<CoLocationGroup> coLocationGroups;

    LocalInputPreferredSlotSharingStrategy(
            final SchedulingTopology topology,
            final Set<SlotSharingGroup> logicalSlotSharingGroups,
            final Set<CoLocationGroup> coLocationGroups) {

        this.logicalSlotSharingGroups = checkNotNull(logicalSlotSharingGroups);
        this.coLocationGroups = checkNotNull(coLocationGroups);

        this.executionSlotSharingGroupMap =
                new ExecutionSlotSharingGroupBuilder(
                                topology, logicalSlotSharingGroups, coLocationGroups)
                        .build();
        topology.registerSchedulingTopologyListener(this);
    }

    @Override
    public ExecutionSlotSharingGroup getExecutionSlotSharingGroup(
            final ExecutionVertexID executionVertexId) {
        return executionSlotSharingGroupMap.get(executionVertexId);
    }

    @Override
    public Set<ExecutionSlotSharingGroup> getExecutionSlotSharingGroups() {
        return new HashSet<>(executionSlotSharingGroupMap.values());
    }

    @Override
    public void notifySchedulingTopologyUpdated(
            SchedulingTopology schedulingTopology, List<ExecutionVertexID> newExecutionVertices) {

        final Map<ExecutionVertexID, ExecutionSlotSharingGroup> newMap =
                new LocalInputPreferredSlotSharingStrategy.ExecutionSlotSharingGroupBuilder(
                                schedulingTopology, logicalSlotSharingGroups, coLocationGroups)
                        .build();

        for (ExecutionVertexID vertexId : newMap.keySet()) {
            final ExecutionSlotSharingGroup newEssg = newMap.get(vertexId);
            final ExecutionSlotSharingGroup oldEssg = executionSlotSharingGroupMap.get(vertexId);
            if (oldEssg == null) {
                executionSlotSharingGroupMap.put(vertexId, newEssg);
            } else {
                // ensures that existing slot sharing groups are not changed
                checkState(
                        oldEssg.getExecutionVertexIds().equals(newEssg.getExecutionVertexIds()),
                        "Existing ExecutionSlotSharingGroups are changed after topology update");
            }
        }
    }

    static class Factory implements SlotSharingStrategy.Factory {

        public LocalInputPreferredSlotSharingStrategy create(
                final SchedulingTopology topology,
                final Set<SlotSharingGroup> logicalSlotSharingGroups,
                final Set<CoLocationGroup> coLocationGroups) {

            return new LocalInputPreferredSlotSharingStrategy(
                    topology, logicalSlotSharingGroups, coLocationGroups);
        }
    }

    private static class ExecutionSlotSharingGroupBuilder {
        private final SchedulingTopology topology;

        private final Map<JobVertexID, SlotSharingGroup> slotSharingGroupMap;

        private final Map<JobVertexID, CoLocationGroup> coLocationGroupMap;

        private final Map<ExecutionVertexID, ExecutionSlotSharingGroup>
                executionSlotSharingGroupMap;

        private final Map<CoLocationConstraint, ExecutionSlotSharingGroup>
                constraintToExecutionSlotSharingGroupMap;

        private final Map<SlotSharingGroupId, List<ExecutionSlotSharingGroup>>
                executionSlotSharingGroups;

        /**
         * A JobVertex only belongs to one {@link SlotSharingGroup}. A SlotSharingGroup is
         * corresponding to a set of {@link ExecutionSlotSharingGroup}s. We can maintain available
         * ExecutionSlotSharingGroups for each JobVertex.
         *
         *
Once an ExecutionSlotSharingGroup is created, it becomes available for all JobVertices
         * in the corresponding SlotSharingGroup in the beginning.
         *
         *
Once a SchedulingExecutionVertex is added to the ExecutionSlotSharingGroup, the group
         * is no longer available for other SchedulingExecutionVertices with the same JobVertexID.
         *
         *
Here we use {@link LinkedHashSet} to reserve the order the same as the
         * SchedulingVertices are traversed.
         */
        private final Map<JobVertexID, LinkedHashSet<ExecutionSlotSharingGroup>>
                availableGroupsForJobVertex;

        /**
         * Maintains the candidate {@link ExecutionSlotSharingGroup}s for every {@link
         * ConsumedPartitionGroup}. The ConsumedPartitionGroup represents a group of partitions that
         * is consumed by the same ExecutionVertices. These ExecutionVertices belong to one consumer
         * JobVertex. Thus, we can say, a ConsumedPartitionGroup is corresponding to one consumer
         * JobVertex.
         *
         *
This mapping is used to find an available producer ExecutionSlotSharingGroup for the
         * consumer vertex. If a candidate group is available for this consumer vertex, it will be
         * assigned to this vertex.
         *
         *
The candidate groups are computed in {@link
         * #computeAllCandidateGroupsForConsumedPartitionGroup} when the ConsumedPartitionGroup is
         * traversed for the first time.
         *
         *
Here we use {@link LinkedHashSet} to reserve the order the same as the
         * SchedulingVertices are traversed.
         */
        private final Map<ConsumedPartitionGroup, LinkedHashSet<ExecutionSlotSharingGroup>>
                candidateGroupsForConsumedPartitionGroup;

        private ExecutionSlotSharingGroupBuilder(
                final SchedulingTopology topology,
                final Set<SlotSharingGroup> logicalSlotSharingGroups,
                final Set<CoLocationGroup> coLocationGroups) {

            this.topology = checkNotNull(topology);

            this.slotSharingGroupMap = new HashMap<>();
            for (SlotSharingGroup slotSharingGroup : logicalSlotSharingGroups) {
                for (JobVertexID jobVertexId : slotSharingGroup.getJobVertexIds()) {
                    slotSharingGroupMap.put(jobVertexId, slotSharingGroup);
                }
            }

            this.coLocationGroupMap = new HashMap<>();
            for (CoLocationGroup coLocationGroup : coLocationGroups) {
                for (JobVertexID jobVertexId : coLocationGroup.getVertexIds()) {
                    coLocationGroupMap.put(jobVertexId, coLocationGroup);
                }
            }

            executionSlotSharingGroupMap = new HashMap<>();
            constraintToExecutionSlotSharingGroupMap = new HashMap<>();
            executionSlotSharingGroups = new HashMap<>();
            availableGroupsForJobVertex = new HashMap<>();
            candidateGroupsForConsumedPartitionGroup = new IdentityHashMap<>();
        }

        /**
         * Build ExecutionSlotSharingGroups for all vertices in the topology. The
         * ExecutionSlotSharingGroup of a vertex is determined in order below:
         *
         *
1. try finding an existing group of the corresponding co-location constraint.
         *
         *
2. try finding an available group of its producer vertex if the producer is in the
         * same slot sharing group.
         *
         *
3. try finding any available group.
         *
         *
4. create a new group.
         */
        private Map<ExecutionVertexID, ExecutionSlotSharingGroup> build() {
            final LinkedHashMap<JobVertexID, List<SchedulingExecutionVertex>> allVertices =
                    getExecutionVertices();

            // loop on job vertices so that an execution vertex will not be added into a group
            // if that group better fits another execution vertex
            for (List<SchedulingExecutionVertex> executionVertices : allVertices.values()) {
                final List<SchedulingExecutionVertex> remaining =
                        tryFindOptimalAvailableExecutionSlotSharingGroupFor(executionVertices);

                findAvailableOrCreateNewExecutionSlotSharingGroupFor(remaining);

                updateConstraintToExecutionSlotSharingGroupMap(executionVertices);
            }

            return executionSlotSharingGroupMap;
        }

        /**
         * The vertices are topologically sorted since {@link DefaultExecutionTopology#getVertices}
         * are topologically sorted.
         */
        private LinkedHashMap<JobVertexID, List<SchedulingExecutionVertex>> getExecutionVertices() {
            final LinkedHashMap<JobVertexID, List<SchedulingExecutionVertex>> vertices =
                    new LinkedHashMap<>();
            for (SchedulingExecutionVertex executionVertex : topology.getVertices()) {
                final List<SchedulingExecutionVertex> executionVertexGroup =
                        vertices.computeIfAbsent(
                                executionVertex.getId().getJobVertexId(), k -> new ArrayList<>());
                executionVertexGroup.add(executionVertex);
            }
            return vertices;
        }

        private List<SchedulingExecutionVertex> tryFindOptimalAvailableExecutionSlotSharingGroupFor(
                final List<SchedulingExecutionVertex> executionVertices) {

            final List<SchedulingExecutionVertex> remaining = new ArrayList<>();
            for (SchedulingExecutionVertex executionVertex : executionVertices) {
                ExecutionSlotSharingGroup group =
                        tryFindAvailableCoLocatedExecutionSlotSharingGroupFor(executionVertex);

                if (group == null) {
                    group = tryFindAvailableProducerExecutionSlotSharingGroupFor(executionVertex);
                }

                if (group == null) {
                    remaining.add(executionVertex);
                } else {
                    addVertexToExecutionSlotSharingGroup(executionVertex, group);
                }
            }

            return remaining;
        }

        private ExecutionSlotSharingGroup tryFindAvailableCoLocatedExecutionSlotSharingGroupFor(
                final SchedulingExecutionVertex executionVertex) {

            final ExecutionVertexID executionVertexId = executionVertex.getId();
            final CoLocationGroup coLocationGroup =
                    coLocationGroupMap.get(executionVertexId.getJobVertexId());
            if (coLocationGroup != null) {
                final CoLocationConstraint constraint =
                        coLocationGroup.getLocationConstraint(executionVertexId.getSubtaskIndex());

                return constraintToExecutionSlotSharingGroupMap.get(constraint);
            } else {
                return null;
            }
        }

        private ExecutionSlotSharingGroup tryFindAvailableProducerExecutionSlotSharingGroupFor(
                final SchedulingExecutionVertex executionVertex) {

            final ExecutionVertexID executionVertexId = executionVertex.getId();

            for (ConsumedPartitionGroup consumedPartitionGroup :
                    executionVertex.getConsumedPartitionGroups()) {

                Set<ExecutionSlotSharingGroup> candidateGroups =
                        candidateGroupsForConsumedPartitionGroup.computeIfAbsent(
                                consumedPartitionGroup,
                                group ->
                                        computeAllCandidateGroupsForConsumedPartitionGroup(
                                                executionVertexId.getJobVertexId(), group));

                Iterator<ExecutionSlotSharingGroup> candidateIterator = candidateGroups.iterator();

                while (candidateIterator.hasNext()) {
                    ExecutionSlotSharingGroup candidateGroup = candidateIterator.next();
                    // There are two cases for this candidate group:
                    //
                    // 1. The group is available for this vertex, and it will be assigned to this
                    // vertex;
                    // 2. The group is not available for this vertex, because it's already assigned
                    // to another vertex with the same JobVertexID.
                    //
                    // No matter what case it is, the candidate group is no longer a candidate and
                    // should be removed.
                    candidateIterator.remove();
                    if (isExecutionSlotSharingGroupAvailableForVertex(
                            candidateGroup, executionVertexId)) {
                        return candidateGroup;
                    }
                }
            }

            return null;
        }

        private boolean isExecutionSlotSharingGroupAvailableForVertex(
                ExecutionSlotSharingGroup executionSlotSharingGroup, ExecutionVertexID vertexId) {

            Set<ExecutionSlotSharingGroup> availableGroupsForCurrentVertex =
                    availableGroupsForJobVertex.get(vertexId.getJobVertexId());

            return availableGroupsForCurrentVertex != null
                    && availableGroupsForCurrentVertex.contains(executionSlotSharingGroup);
        }

        private boolean inSameLogicalSlotSharingGroup(
                final JobVertexID jobVertexId1, final JobVertexID jobVertexId2) {

            return Objects.equals(
                    getSlotSharingGroup(jobVertexId1).getSlotSharingGroupId(),
                    getSlotSharingGroup(jobVertexId2).getSlotSharingGroupId());
        }

        private SlotSharingGroup getSlotSharingGroup(final JobVertexID jobVertexId) {
            // slot sharing group of a vertex would never be null in production
            return checkNotNull(slotSharingGroupMap.get(jobVertexId));
        }

        private void addVertexToExecutionSlotSharingGroup(
                final SchedulingExecutionVertex vertex, final ExecutionSlotSharingGroup group) {

            ExecutionVertexID executionVertexId = vertex.getId();
            group.addVertex(executionVertexId);
            executionSlotSharingGroupMap.put(executionVertexId, group);

            // The ExecutionSlotSharingGroup is no longer available for the JobVertex
            Set<ExecutionSlotSharingGroup> availableExecutionSlotSharingGroups =
                    availableGroupsForJobVertex.get(executionVertexId.getJobVertexId());
            if (availableExecutionSlotSharingGroups != null) {
                availableExecutionSlotSharingGroups.remove(group);
            }
        }

        private void findAvailableOrCreateNewExecutionSlotSharingGroupFor(
                final List<SchedulingExecutionVertex> executionVertices) {

            for (SchedulingExecutionVertex executionVertex : executionVertices) {

                ExecutionSlotSharingGroup group =
                        tryFindAvailableExecutionSlotSharingGroupFor(executionVertex);

                if (group == null) {
                    group = createNewExecutionSlotSharingGroup(executionVertex.getId());
                }

                addVertexToExecutionSlotSharingGroup(executionVertex, group);
            }
        }

        private ExecutionSlotSharingGroup tryFindAvailableExecutionSlotSharingGroupFor(
                SchedulingExecutionVertex executionVertex) {

            Set<ExecutionSlotSharingGroup> availableGroupsForCurrentVertex =
                    availableGroupsForJobVertex.get(executionVertex.getId().getJobVertexId());

            if (availableGroupsForCurrentVertex != null
                    && !availableGroupsForCurrentVertex.isEmpty()) {
                return availableGroupsForCurrentVertex.iterator().next();
            }

            return null;
        }

        private ExecutionSlotSharingGroup createNewExecutionSlotSharingGroup(
                ExecutionVertexID executionVertexId) {
            final SlotSharingGroup slotSharingGroup =
                    getSlotSharingGroup(executionVertexId.getJobVertexId());
            final List<ExecutionSlotSharingGroup> correspondingExecutionSlotSharingGroups =
                    executionSlotSharingGroups.computeIfAbsent(
                            slotSharingGroup.getSlotSharingGroupId(), k -> new ArrayList<>());

            final ExecutionSlotSharingGroup newGroup = new ExecutionSlotSharingGroup();
            newGroup.setResourceProfile(slotSharingGroup.getResourceProfile());

            correspondingExecutionSlotSharingGroups.add(newGroup);

            // Once a new ExecutionSlotSharingGroup is created, it's available for all JobVertices
            // in this SlotSharingGroup
            for (JobVertexID jobVertexId : slotSharingGroup.getJobVertexIds()) {
                Set<ExecutionSlotSharingGroup> availableExecutionSlotSharingGroups =
                        availableGroupsForJobVertex.computeIfAbsent(
                                jobVertexId, ignore -> new LinkedHashSet<>());
                availableExecutionSlotSharingGroups.add(newGroup);
            }

            return newGroup;
        }

        private void updateConstraintToExecutionSlotSharingGroupMap(
                final List<SchedulingExecutionVertex> executionVertices) {

            for (SchedulingExecutionVertex executionVertex : executionVertices) {
                final ExecutionVertexID executionVertexId = executionVertex.getId();
                final CoLocationGroup coLocationGroup =
                        coLocationGroupMap.get(executionVertexId.getJobVertexId());
                if (coLocationGroup != null) {
                    final CoLocationConstraint constraint =
                            coLocationGroup.getLocationConstraint(
                                    executionVertexId.getSubtaskIndex());

                    constraintToExecutionSlotSharingGroupMap.put(
                            constraint, executionSlotSharingGroupMap.get(executionVertexId));
                }
            }
        }

        private LinkedHashSet<ExecutionSlotSharingGroup>
                computeAllCandidateGroupsForConsumedPartitionGroup(
                        JobVertexID consumerJobVertexId,
                        ConsumedPartitionGroup consumedPartitionGroup) {

            // We tend to reserve the order of ExecutionSlotSharingGroups as they are traversed
            // topologically
            final LinkedHashSet<ExecutionSlotSharingGroup> candidateExecutionSlotSharingGroups =
                    new LinkedHashSet<>();

            JobVertexID producerJobVertexId =
                    topology.getResultPartition(consumedPartitionGroup.getFirst())
                            .getProducer()
                            .getId()
                            .getJobVertexId();

            // Check if the producer JobVertex and the consumer JobVertex are in the same
            // SlotSharingGroup
            if (inSameLogicalSlotSharingGroup(producerJobVertexId, consumerJobVertexId)) {

                // Iterate over the producer ExecutionVertices of all the partitions in the
                // ConsumedPartitionGroup
                for (IntermediateResultPartitionID consumedPartition : consumedPartitionGroup) {

                    ExecutionVertexID producerExecutionVertexId =
                            topology.getResultPartition(consumedPartition).getProducer().getId();

                    ExecutionSlotSharingGroup assignedGroupForProducerExecutionVertex =
                            executionSlotSharingGroupMap.get(producerExecutionVertexId);
                    checkNotNull(assignedGroupForProducerExecutionVertex);

                    candidateExecutionSlotSharingGroups.add(
                            assignedGroupForProducerExecutionVertex);
                }
            }

            return candidateExecutionSlotSharingGroups;
        }
    }
}


text:
module TokyoMetro::Modules::ToFactory::Api::Convert::Customize::RailwayLine::ChiyodaBranchLine::Generate
end


text:
@class GoogleChartAxis;
@class GoogleChartLegend;

@interface GoogleChart : NSObject {
  NSString *apiUrl;
  int width;
  int height;
  NSString *type;
  NSMutableArray *data;
  NSString *dataEncoding;
  float scaleFactor;
  NSMutableArray *labels;
  GoogleChartAxis *xAxis;
  GoogleChartAxis *yAxis;
  GoogleChartAxis *topAxis;
  GoogleChartAxis *rightAxis;
  GoogleChartLegend *legend;
  NSMutableArray *colors;
  NSMutableArray *lineStyles;
}

@property (nonatomic, readonly, assign) NSString *apiUrl;
@property (nonatomic, assign) int width;
@property (nonatomic, assign) int height;
@property (nonatomic, assign) NSString *type;
@property (nonatomic, assign) NSMutableArray *data;
@property (nonatomic, assign) NSString *dataEncoding;
@property (nonatomic, assign) float scaleFactor;
@property (nonatomic, assign) NSMutableArray *labels;
@property (nonatomic, assign) GoogleChartAxis *xAxis;
@property (nonatomic, assign) GoogleChartAxis *yAxis;
@property (nonatomic, assign) GoogleChartAxis *topAxis;
@property (nonatomic, assign) GoogleChartAxis *rightAxis;
@property (nonatomic, assign) GoogleChartLegend *legend;
@property (nonatomic, assign) NSMutableArray *colors;
@property (nonatomic, assign) NSMutableArray *lineStyles;

+ (NSString *)extendedEncodingFor:(int)value;
+ (NSString *)textEncodingFor:(int)value;
- (NSString *)size;
- (NSString *)url;
- (NSString *)scaling;
- (int)maxDataValue;
@end

@interface GoogleChart (hidden)
- (NSString *)axisData;
- (NSString *)chartType;
- (NSString *)dataLabels;
- (NSString *)formattedData;
- (NSString *)formattedColors;
- (NSString *)formattedLineStyles;
- (NSString *)valueForUrlParameter:(NSString *)parameter;
@end


text:
package defaultbackend

import (
	"context"
	"fmt"
	"net/http"
	"strings"

	"github.com/onsi/ginkgo/v2"
	"github.com/stretchr/testify/assert"
	appsv1 "k8s.io/api/apps/v1"
	metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"

	"k8s.io/ingress-nginx/test/e2e/framework"
)

var _ = framework.IngressNginxDescribe("[Default Backend] custom service", func() {
	f := framework.NewDefaultFramework("custom-default-backend")

	ginkgo.It("uses custom default backend that returns 200 as status code", func() {
		f.NewEchoDeployment()

		err := f.UpdateIngressControllerDeployment(func(deployment *appsv1.Deployment) error {
			args := deployment.Spec.Template.Spec.Containers[0].Args
			args = append(args, fmt.Sprintf("--default-backend-service=%v/%v", f.Namespace, framework.EchoService))
			deployment.Spec.Template.Spec.Containers[0].Args = args
			_, err := f.KubeClientSet.AppsV1().Deployments(f.Namespace).Update(context.TODO(), deployment, metav1.UpdateOptions{})
			return err
		})
		assert.Nil(ginkgo.GinkgoT(), err, "updating deployment")

		f.WaitForNginxServer("_",
			func(server string) bool {
				return strings.Contains(server, `set $proxy_upstream_name "upstream-default-backend"`)
			})

		f.HTTPTestClient().
			GET("/").
			Expect().
			Status(http.StatusOK)
	})
})


text:
package com.rasterfoundry.database

import com.rasterfoundry.database.Implicits._

import cats.Monoid
import doobie._
import doobie.implicits._
import doobie.postgres.implicits._
import geotrellis.vector.MultiPolygon
import geotrellis.vector.Polygon
import geotrellis.vector.{Geometry, Projected, ProjectedExtent}
import geotrellis.vectortile._

import java.util.UUID

/** Container for methods required to get byte arrays of MVT layers from the db
  *
  * Claims to be a Dao, but doesn't extend Dao[Option[Array[Byte]]] because we can't provide
  * sensible values for some of the required Dao fields, e.g., what should the `selectF` be?
  * Or fieldnames? Or table name?
  */
object MVTLayerDao {

  final case class LabelTileGeometry(
      geom: Projected[Geometry],
      envelope: ProjectedExtent,
      taskId: UUID,
      score: Option[Float],
      labelClassId: UUID,
      className: String,
      colorHexCode: String
  ) {
    def vtValues: Map[String, Value] =
      Map(
        "annotation_task_id" -> VString(taskId.toString),
        "label_class_id" -> VString(labelClassId.toString),
        "name" -> VString(className),
        "color_hex_code" -> VString(colorHexCode)
      ) ++ score.fold(Map.empty[String, Value])(v => Map("score" -> VDouble(v)))
  }

  private[database] def getAnnotationProjectTasksQ(
      annotationProjectId: UUID,
      z: Int,
      x: Int,
      y: Int
  ): Query0[Array[Byte]] =
    fr"""WITH mvtgeom AS
      (
        SELECT
          ST_AsMVTGeom(
            geometry,
            ST_TileEnvelope(${z},${x},${y})
          ) AS geom,
          *
        FROM tasks
        WHERE
          ST_Intersects(
            geometry,
            ST_TileEnvelope(${z},${x},${y})
          ) AND
          annotation_project_id = ${annotationProjectId} AND
          task_type = 'LABEL'::task_type AND
          status <> 'SPLIT'
      )
    SELECT ST_AsMVT(mvtgeom.*) FROM mvtgeom;""".query[Array[Byte]]

  def getAnnotationProjectTasks(
      annotationProjectId: UUID,
      z: Int,
      x: Int,
      y: Int
  ): ConnectionIO[Array[Byte]] =
    getAnnotationProjectTasksQ(annotationProjectId, z, x, y).unique

  // By default, create MVT for human-generated labels
  // If hitl version ID provided, only render versioned machine labels
  private[database] def getAnnotationProjectLabelsQ(
      annotationProjectId: UUID,
      z: Int,
      x: Int,
      y: Int,
      hitlVersionIdO: Option[UUID] = None
  ): Query0[LabelTileGeometry] = {
    val hitlFilterF = hitlVersionIdO match {
      case Some(hitlVersionId) =>
        fr"AND annotation_labels.hitl_version_id = ${hitlVersionId}"
      case _ => fr"AND annotation_labels.hitl_version_id IS NULL"
    }
    (fr"""
        SELECT
          annotation_labels.geometry,
          ST_TileEnvelope(${z}, ${x}, ${y}) as envelope,
          annotation_labels.annotation_task_id,
          annotation_labels.score,
          annotation_label_classes.id as label_class_id,
          annotation_label_classes.name,
          annotation_label_classes.color_hex_code
        FROM
          annotation_labels join tasks on annotation_labels.annotation_task_id = tasks.id
           JOIN annotation_labels_annotation_label_classes on
           annotation_labels.id = annotation_labels_annotation_label_classes.annotation_label_id
          JOIN annotation_label_classes on annotation_labels_annotation_label_classes.annotation_class_id = annotation_label_classes.id
        WHERE
          ST_Intersects(
            annotation_labels.geometry,
            ST_TileEnvelope(${z}, ${x}, ${y})
          )
          AND annotation_labels.annotation_project_id = ${annotationProjectId}
          AND annotation_labels.is_active = true
          AND tasks.status <> 'SPLIT'
      """ ++ hitlFilterF).query[LabelTileGeometry]
  }

  /** We know the `foldMap` will produce an inhabited stream, since
    * that's what the Monoid instance is for, so it's safe to compile it
    * to a list and take the head.
    */
  @SuppressWarnings(Array("TraversableHead"))
  def getAnnotationProjectLabels(
      annotationProjectId: UUID,
      z: Int,
      x: Int,
      y: Int
  ): ConnectionIO[Array[Byte]] = {
    getAnnotationProjectLabelsQ(annotationProjectId, z, x, y).stream
      .foldMap({ labelTileGeom =>
        labelTileGeom.geom.geom match {
          case g: MultiPolygon =>
            Monoid[MVTFeatures].empty.copy(
              multiPolygons = List(
                MVTFeature(
                  None,
                  g,
                  labelTileGeom.vtValues
                )
              )
            )
          case g: Polygon =>
            Monoid[MVTFeatures].empty.copy(
              polygons = List(
                MVTFeature(
                  None,
                  g,
                  labelTileGeom.vtValues
                )
              )
            )
          case _ => Monoid[MVTFeatures].empty
        }
      })
      .compile
      .toList map { featuresList =>
      val features = featuresList.head
      val layer = StrictLayer(
        "default",
        4096,
        2,
        tiling.tmsLevels(z).mapTransform.keyToExtent(x, y),
        features
      )
      VectorTile(Map("default" -> layer), layer.tileExtent).toBytes
    }
  }

  @SuppressWarnings(Array("TraversableHead"))
  def getAnnotationProjectHITLLabels(
      annotationProjectId: UUID,
      z: Int,
      x: Int,
      y: Int,
      hitlVersionId: UUID
  ): ConnectionIO[Array[Byte]] = {
    getAnnotationProjectLabelsQ(
      annotationProjectId,
      z,
      x,
      y,
      Some(hitlVersionId)
    ).stream
      .foldMap({ labelTileGeom =>
        labelTileGeom.geom.geom match {
          case g: MultiPolygon =>
            Monoid[MVTFeatures].empty.copy(
              multiPolygons = List(
                MVTFeature(
                  None,
                  g,
                  labelTileGeom.vtValues
                )
              )
            )
          case g: Polygon =>
            Monoid[MVTFeatures].empty.copy(
              polygons = List(
                MVTFeature(
                  None,
                  g,
                  labelTileGeom.vtValues
                )
              )
            )
          case _ => Monoid[MVTFeatures].empty
        }
      })
      .compile
      .toList map { featuresList =>
      val features = featuresList.head
      val layer = StrictLayer(
        "default",
        4096,
        2,
        tiling.tmsLevels(z).mapTransform.keyToExtent(x, y),
        features
      )
      VectorTile(Map("default" -> layer), layer.tileExtent).toBytes
    }
  }
}


text:
package com.stratio.sparta.serving.core.models.policy.cube

import com.stratio.sparta.sdk.pipeline.aggregation.cube.DimensionType

case class DimensionModel(name: String,
                          field: String,
                          precision: String = DimensionType.IdentityName,
                          `type`: String = DimensionType.DefaultDimensionClass,
                          computeLast: Option[String] = None,
                          configuration: Option[Map[String, String]] = None) {

}


text:
package geometry;

/**
 * An integer interval
 */
public final class IntegerInterval {

    private final int start;
    private final int length;

    /**
     * Create an integer interval with the given starting value and length
     * @param start starting value
     * @param length length of the interval in the positive direction
     * @throws IllegalArgumentException if given length is negative or zero
     */
    public IntegerInterval(int start, int length) throws IllegalArgumentException {
        if (length <= 0) {
            throw new IllegalArgumentException("length must be positive");
        }

        this.start = start;
        this.length = length;
    }

    /**
     * Produces true if this interval intersects other interval
     */
    public boolean intersects(IntegerInterval otherInterval) {
        int newMin = Math.max(this.start, otherInterval.start);
        int newMax = Math.min(this.start + this.length, otherInterval.start + otherInterval.length);

        return newMax > newMin;
    }
}


text:
package exception;

/**
 * Created by cosmin on 02/11/16.
 */
public class FileNotOpenedException extends Exception {
    public FileNotOpenedException() {
        super("FileNotOpenedException");
    }
    public FileNotOpenedException(String s) {
        super(s);
    }
}


text:
/**
 * @autor Rikard Lindstrom <rlindstrom@google.com>
 */

import { readable } from "svelte/store";

export const currentRoute = readable(null, () => {
  console.log("start listening!");
  const handlePopState = (event) => {
    console.log(event);
  };
  window.addEventListener("popstate", handlePopState);
  return () => {
    window.removeEventListener("popstate", handlePopState);
  };
});


text:
import { GaEnhancedEcomAction, GaEnhancedEcomActionFieldObject, GaEnhancedEcomImpressionFieldObject, GaEnhancedEcomProductFieldObject } from './ga-enhanced-ecom-options';
import * as i0 from "@angular/core";
export declare class Angulartics2GoogleAnalyticsEnhancedEcommerce {
    /**
     * Add impression in GA enhanced ecommerce tracking
     * @link https://developers.google.com/analytics/devguides/collection/analyticsjs/enhanced-ecommerce#measuring-activities
     */
    ecAddImpression(properties: Partial<GaEnhancedEcomImpressionFieldObject>): void;
    /**
     * Add product in GA enhanced ecommerce tracking
     * @link https://developers.google.com/analytics/devguides/collection/analyticsjs/ecommerce
     */
    ecAddProduct(product: Partial<GaEnhancedEcomProductFieldObject>): void;
    /**
     * Set action in GA enhanced ecommerce tracking
     * @link https://developers.google.com/analytics/devguides/collection/analyticsjs/ecommerce
     */
    ecSetAction(action: GaEnhancedEcomAction, properties: Partial<GaEnhancedEcomActionFieldObject>): void;
    static ɵfac: i0.ɵɵFactoryDeclaration<Angulartics2GoogleAnalyticsEnhancedEcommerce, never>;
    static ɵprov: i0.ɵɵInjectableDeclaration<Angulartics2GoogleAnalyticsEnhancedEcommerce>;
}


text:
var Router = require('./node_modules/express/lib/router');
// console.log(router);

var r = new Router();

var route = r.route('/foo');
route.get(function(){});