text:
//
//  CVStockInTheNewsPortletViewController.m
//  CapitalVueHD
//
//  Created by jishen on 9/6/10.
//  Copyright 2010 SmilingMobile. All rights reserved.
//

#import "CVStockInTheNewsPortletViewController.h"

#import "CVDataProvider.h"

#import "CVStockSnapShotViewController.h"
#import "CVSetting.h"
#import "CVMenuItem.h"

@interface CVStockInTheNewsPortletViewController ()

@property (nonatomic, retain) NSArray *stockList;
@property (nonatomic, retain) NSMutableArray *controllersCache;
@property (nonatomic, retain) CVScrollPageViewController *scrollPageViewController;
@property (nonatomic, retain) UIActivityIndicatorView *activityIndicator;

- (void)loadData:(NSNumber *)numNeedRefresh;
- (CGRect)viewRectOfOrientation:(UIInterfaceOrientation)orientation;
- (CGRect)pageIndicatorFrame:(UIInterfaceOrientation)orientation;

- (void)createCache:(NSUInteger)size;
- (void)cacheInsertController:(CVStockSnapShotViewController *)controller atIndex:(NSUInteger)index;
- (CVStockSnapShotViewController *)cacheControllerAtIndex:(NSUInteger)index;
- (void)destroyCache;

@end

@implementation CVStockInTheNewsPortletViewController

@synthesize stockList;
@synthesize controllersCache;
@synthesize scrollPageViewController;
@synthesize activityIndicator;
@synthesize isNeedRefresh;

/*
 // The designated initializer.  Override if you create the controller programmatically and want to perform customization that is not appropriate for viewDidLoad.
 - (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil {
 if ((self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil])) {
 // Custom initialization
 }
 return self;
 }
 */

/*
 // Implement loadView to create a view hierarchy programmatically, without using a nib.
 - (void)loadView {
 }
 */

#define CVPORTLET_STOCK_IN_THE_NEW_PORTRAIT_ELEMENT 3
#define CVPORTLET_STOCK_IN_THE_NEW_LANDSCAPE_ELEMENT 2

// Implement viewDidLoad to do additional setup after loading the view, typically from a nib.
- (void)viewDidLoad {
	_ifLoaded = YES;
	self.style = CVPortletViewStyleRefresh | CVPortletViewStyleBarVisible;
	CVLocalizationSetting *langSetting = [CVLocalizationSetting sharedInstance];
	//self.style = CVPortletViewStyleRefresh | CVPortletViewStyleSetting| CVPortletViewStyleBarVisible;

	// fill the menu of setting
	CVSetting *setting;
	NSArray *settingArray;
	NSMutableArray *array;
	NSDictionary *element;
	CVMenuItem *item;
	setting = [CVSetting sharedInstance];
	settingArray = [setting settingStockInTheNewsCategory];
	array = [[NSMutableArray alloc] initWithCapacity:1];
	for (element in settingArray) {
		NSNumber *number;
		item = [[CVMenuItem alloc] init];
		item.title = [element objectForKey:@"title"];
		item.name = [element objectForKey:@"categoryname"];
		number = [element valueForKey:@"select"];
		item.select = [number boolValue];
		[array addObject:item];
		[item release];
	}
	self.menuItems = array;
	[array release];

	[super viewDidLoad];

	self.portletTitle =  [langSetting localizedString:@"StockIntheNews"];

	// protrait page
	CVScrollPageViewController *controller;
	controller = [[CVScrollPageViewController alloc] init];
	controller.indicatorStyle = CVScrollPageIndicatorStyleHigh;
	controller.frame = [self viewRectOfOrientation:[[UIApplication sharedApplication] statusBarOrientation]];
	controller.pageControlFrame = [self pageIndicatorFrame:[[UIApplication sharedApplication] statusBarOrientation]];
	[controller setDelegate:self];
	controller.view.backgroundColor = [UIColor clearColor];
	self.scrollPageViewController = controller;
	[controller release];

	[self.view addSubview:scrollPageViewController.view];

	activityIndicator = [[UIActivityIndicatorView alloc] initWithActivityIndicatorStyle:UIActivityIndicatorViewStyleWhiteLarge];
	activityIndicator.frame = CGRectMake(self.view.frame.size.width / 2 - 15,
										 self.view.frame.size.height / 2 - 5,
										 activityIndicator.frame.size.width,
										 activityIndicator.frame.size.height);

	[self.view addSubview:activityIndicator];

	lbl = [[UILabel alloc] initWithFrame:CGRectMake(0, 0, 300, 40)];
	lbl.numberOfLines = 2;
	lbl.font = [UIFont systemFontOfSize:13];
	lbl.center = activityIndicator.center;
	lbl.textColor = [UIColor darkGrayColor];
	lbl.backgroundColor = [UIColor clearColor];
	lbl.textAlignment = UITextAlignmentCenter;
	lbl.text = [langSetting localizedString:@"NetworkFailedMessage"];
	[self.view addSubview:lbl];
	lbl.hidden = YES;

    CVSetting *s;
	s = [CVSetting sharedInstance];
	CVDataProvider *dp = [CVDataProvider sharedInstance];
	[dp setDataIdentifier:@"StockInNewsRefreshTime" lifecycle:[s cvCachedDataLifecycle:CVSettingHomeStockInTheNews]];
}

- (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation {
    // Overriden to allow any orientation.
    return YES;
}

- (void)willRotateToInterfaceOrientation:(UIInterfaceOrientation)toInterfaceOrientation duration:(NSTimeInterval)duration {
}

- (void)didReceiveMemoryWarning {
    // Releases the view if it doesn't have a superview.
    [super didReceiveMemoryWarning];

    // Release any cached data, images, etc that aren't in use.
}

- (void)viewDidUnload {
    [super viewDidUnload];
    // Release any retained subviews of the main view.
    // e.g. self.myOutlet = nil;
}

- (void)dealloc {
	[stockList release];
	[controllersCache release];
	[scrollPageViewController release];
	[activityIndicator release];
	[lbl release];
    [super dealloc];
}

#pragma mark private methods
- (void)loadData:(NSNumber *)numNeedRefresh {
	_ifLoaded = NO;
	self.isNeedRefresh = [numNeedRefresh boolValue];
	CVLocalizationSetting *langSetting = [CVLocalizationSetting sharedInstance];
	NSAutoreleasePool *pool = [[NSAutoreleasePool alloc] init];

	CVDataProvider *dp;
	CVParamInfo *paramInfo;
	NSDictionary *dict;
	NSMutableArray *stockListArray, *tempArray;

	stockListArray = [[NSMutableArray alloc] initWithCapacity:1];

	dp = [CVDataProvider sharedInstance];

	// load today's news of major industry that are selected
	CVMenuItem *item;
	NSArray *arrayParam = nil;

	// to get the stock list for a special categories, the dataprovider
	// requires the parameter having the format like below
	// ($industry='5',$token='')
	// FIXME, it is better to mamage the id of sectors in the config file,
	// and token for the purpose of update function shall be implemented
	for (item in self.menuItems) {
		// check every item , if its select is YES, load its stock list
		if (YES == item.select) {
			NSUInteger sectorNumber;
			if ([item.title isEqualToString:@"Heath Care"]) {
				sectorNumber = 35;
			} else if ([item.title isEqualToString:@"Consumer Staples"]) {
				sectorNumber = 30;
			} else if ([item.title isEqualToString:@"Consumer Discretionary"]) {
				sectorNumber = 25;
			} else if ([item.title isEqualToString:@"Industrials"]) {
				sectorNumber = 20;
			} else if ([item.title isEqualToString:@"Telecommunication Services"]) {
				sectorNumber = 50;
			} else if ([item.title isEqualToString:@"Utilities"]) {
				sectorNumber = 55;
			} else if ([item.title isEqualToString:@"Information Technology"]) {
				sectorNumber = 45;
			} else if ([item.title isEqualToString:@"Energy"]) {
				sectorNumber = 10;
			} else if ([item.title isEqualToString:@"Financials"]) {
				sectorNumber = 40;
			} else if ([item.title isEqualToString:@"Materials"]) {
				sectorNumber = 15;
			} else {
				sectorNumber = 0;
			}

			if (0 != sectorNumber) {
				arrayParam = [[[NSArray alloc] initWithObjects:
                               [NSString stringWithFormat:@"$industry='%d'", sectorNumber],
                               nil] autorelease];
			}

			break;
		}
	}
	paramInfo = [[[CVParamInfo alloc] init] autorelease];
	paramInfo.minutes = 15;
	NSString *oldToken;
	if (nil != arrayParam) {
		// a sector is selected
		paramInfo.parameters = arrayParam;

		oldToken = [[[dp getStockInNewsToken:CVDataProviderStockListTypeNewsRelated withParams:paramInfo] copy] autorelease];

		if (self.isNeedRefresh) {
			dict = [dp ReGetStockList:CVDataProviderStockListTypeNewsRelated withParams:paramInfo];
		}else {
			dict = [dp GetStockList:CVDataProviderStockListTypeNewsRelated withParams:paramInfo];
		}

		tempArray = [dict objectForKey:@"data"];
		if (nil != tempArray) {
			[stockListArray addObjectsFromArray:tempArray];
		}
	} else {
		// no sector is selected, merely load today's news

		oldToken = [[[dp getStockInNewsToken:CVDataProviderStockListTypeNewsRelated withParams:paramInfo] copy] autorelease];

		if (self.isNeedRefresh) {
			dict = [dp ReGetStockList:CVDataProviderStockListTypeNewsRelated withParams:paramInfo];
		} else {
			dict = [dp GetStockList:CVDataProviderStockListTypeNewsRelated withParams:paramInfo];
		}

		tempArray = [dict objectForKey:@"data"];
		[stockListArray addObjectsFromArray:tempArray];
	}
	if (nil != stockListArray && [stockListArray count] > 0) {
		NSDictionary *dict;
		NSString *date;
		NSString *t;

		dict = [stockListArray objectAtIndex:0];
		date = [dict objectForKey:@"t_stamp"];

		t = [[NSMutableString alloc] initWithFormat:@"%@ %@", [langSetting localizedString:@"StockIntheNews"],date];
		self.portletTitle = t;
		[t release];
	}

	NSString *newToken = [[[dp getStockInNewsToken:CVDataProviderStockListTypeNewsRelated withParams:paramInfo] copy] autorelease];
	if ([newToken isEqualToString:oldToken] && self.isNeedRefresh == NO && stockList) {
		_isNewToken = NO;
	} else {
		_isNewToken = YES;
	}

	self.stockList = stockListArray;
	[stockListArray release];

	// TIP: the usage of temporary orientationLog
	// as the current 3.2 iOS doesn't provide correct orientation of device at the very first time,
	// e.g. between the lauching period of application and subsequent 5-seconds period. Consequently,
	// the construction of landscape view always reads the wrong orientation and does the wrong job.
	// The temporary variant guarantee the righteous construction of landscape view and revert after
	// completion.

	if (UIInterfaceOrientationPortrait == portalInterfaceOrientation ||
		UIInterfaceOrientationPortraitUpsideDown == portalInterfaceOrientation) {
		scrollPageViewController.pageCount = [stockList count] / CVPORTLET_STOCK_IN_THE_NEW_PORTRAIT_ELEMENT;
		scrollPageViewController.pageCount += ([stockList count] % CVPORTLET_STOCK_IN_THE_NEW_PORTRAIT_ELEMENT == 0)?0:1;
	} else {
		scrollPageViewController.pageCount = [stockList count] / CVPORTLET_STOCK_IN_THE_NEW_LANDSCAPE_ELEMENT;
		scrollPageViewController.pageCount += ([stockList count] % CVPORTLET_STOCK_IN_THE_NEW_LANDSCAPE_ELEMENT == 0)?0:1;
	}

	[self performSelectorOnMainThread:@selector(afterLoadData) withObject:nil waitUntilDone:NO];

	[pool release];
}

-(void)afterLoadData{
	if (_isNewToken) {
		[self createCache:[stockList count]];
		[scrollPageViewController reloadData];
	}

	[activityIndicator stopAnimating];
	activityIndicator.hidden = YES;
	_ifLoaded = YES;
	self.isNeedRefresh = NO;

	if ([self.stockList count] > 0) {
		lbl.hidden = YES;
		scrollPageViewController.view.hidden = NO;
	}else {
		lbl.hidden = NO;
	}

}

- (CGRect)viewRectOfOrientation:(UIInterfaceOrientation)orientation {
	CGRect rect;
	if (UIInterfaceOrientationPortrait == orientation ||
		UIInterfaceOrientationPortraitUpsideDown == orientation) {
		rect = CGRectMake(7,
						  CVPORTLET_BAR_HEIGHT + 10,
						  CVPORTLET_STOCK_IN_THE_NEW_WIDTH * CVPORTLET_STOCK_IN_THE_NEW_PORTRAIT_ELEMENT,
						  211);
	} else {
		rect = CGRectMake(7,
						  CVPORTLET_BAR_HEIGHT + 10,
						  CVPORTLET_STOCK_IN_THE_NEW_WIDTH * CVPORTLET_STOCK_IN_THE_NEW_LANDSCAPE_ELEMENT,
						  211);
	}

	return rect;
}

- (CGRect)pageIndicatorFrame:(UIInterfaceOrientation)orientation {
	CGRect rect;

	rect = CGRectMake((scrollPageViewController.frame.size.width - CVSCROLLPAGE_INDICTOR_WIDTH) / 2,
                      scrollPageViewController.frame.size.height - 10,
                      CVSCROLLPAGE_INDICTOR_WIDTH,
                      CVSCROLLPAGE_INDICTOR_HEIGHT);

	return rect;
}

- (void)createCache:(NSUInteger)size {
	NSMutableArray *array;
	NSUInteger i;

	array = [[NSMutableArray alloc] init];
	for (i = 0; i < size; i++) {
		[array addObject:[NSNull null]];
	}
	self.controllersCache = array;
	[array release];
}

- (void)cacheInsertController:(CVStockSnapShotViewController *)controller atIndex:(NSUInteger)index {
	if (nil != controller && index < [controllersCache count]) {
		[controllersCache replaceObjectAtIndex:index withObject:controller];
	}
}

- (CVStockSnapShotViewController *)cacheControllerAtIndex:(NSUInteger)index {
	CVStockSnapShotViewController *controller;

	controller = nil;
	if (index < [controllersCache count]) {
		controller = [controllersCache objectAtIndex:index];
		if ([NSNull null] == (NSNull *)controller)
			controller = nil;
	}

	return controller;
}

- (void)destroyCache {
	[controllersCache release];
	controllersCache = nil;
}

#pragma mark CVScrollPageViewDeleage
- (NSUInteger)numberOfPagesInScrollPageView {
	NSUInteger count;
	if (UIInterfaceOrientationPortrait == portalInterfaceOrientation ||
		UIInterfaceOrientationPortraitUpsideDown == portalInterfaceOrientation) {
		count = [stockList count] / 3 + 1;
	} else {
		count = [stockList count] / 2 + 1;
	}
	return count;
}

- (UIView *)scrollPageView:(id)scrollPageView viewForPageAtIndex:(NSUInteger)index {
	CVLocalizationSetting *langSetting = [CVLocalizationSetting sharedInstance];
	UIView *pageView;

	if (UIInterfaceOrientationPortrait == self.portalInterfaceOrientation ||
		UIInterfaceOrientationPortraitUpsideDown == self.portalInterfaceOrientation) {
		pageView = [scrollPageView dequeueReusablePage:index];
		if (nil == pageView) {
			pageView = [[[UIView alloc] initWithFrame:CGRectMake(0, 5, CVPORTLET_STOCK_IN_THE_NEW_WIDTH * 3, CVPORTLET_STOCK_IN_THE_NEW_HEIGHT)] autorelease];
			pageView.backgroundColor = [UIColor clearColor];
		}

		NSUInteger newsCount = [self.stockList count];
		for (NSUInteger i = index * CVPORTLET_STOCK_IN_THE_NEW_PORTRAIT_ELEMENT; (i < (index * CVPORTLET_STOCK_IN_THE_NEW_PORTRAIT_ELEMENT + CVPORTLET_STOCK_IN_THE_NEW_PORTRAIT_ELEMENT)) && i < newsCount; i++) {
			CVStockSnapShotViewController *snapViewController;
			NSDictionary *dict;
			// temperarily used for log strings
			NSString *tempString;

			snapViewController = [self cacheControllerAtIndex:i];
			if (nil == snapViewController) {
				dict = [stockList objectAtIndex:i];
				snapViewController = [[CVStockSnapShotViewController alloc] init];
				snapViewController.isNeedRefresh = self.isNeedRefresh;
				snapViewController.stockCode = [dict objectForKey:@"GPDM"];

				snapViewController.view.backgroundColor = [UIColor clearColor];

				snapViewController.view.frame = CGRectMake((i - index * CVPORTLET_STOCK_IN_THE_NEW_PORTRAIT_ELEMENT)*CVPORTLET_STOCK_IN_THE_NEW_WIDTH,
                                                           0,
                                                           snapViewController.view.frame.size.width,
                                                           snapViewController.view.frame.size.height);
				snapViewController.code.text = [dict objectForKey:@"GPDM"];
				snapViewController.code.font = [UIFont boldSystemFontOfSize:13];
				snapViewController.code.textColor = [UIColor colorWithRed:77.0/255 green:77.0/255 blue:77.0/255 alpha:1];
				dict = [stockList objectAtIndex:i];
				snapViewController.symbol.text = [dict objectForKey:@"GPJC"];
				snapViewController.symbol.font = [UIFont boldSystemFontOfSize:16];
				snapViewController.symbol.textColor = [UIColor colorWithRed:77.0/255 green:77.0/255 blue:77.0/255 alpha:1];

				snapViewController.desc.font = [UIFont systemFontOfSize:12];
				snapViewController.desc.text = [dict objectForKey:@"title"];
				[snapViewController adjustDescLabel];
				snapViewController.desc.textColor = [UIColor colorWithRed:77.0/255 green:77.0/255 blue:77.0/255 alpha:1];
				snapViewController.strPostID = [dict objectForKey:@"post_id"];
				tempString = [dict objectForKey:@"KPJ"];
				snapViewController.previousPrice = [tempString floatValue];
				tempString = [dict objectForKey:@"SPJ"];
				snapViewController.currentPrice = [tempString floatValue];

				snapViewController.price.text = [NSString stringWithFormat:@"%.2f", [tempString floatValue] / 1000];

				UIColor *posColor = [langSetting getColor:@"GainersRate"];
				UIColor *negColor = [langSetting getColor:@"LosersRate"];

				if (snapViewController.previousPrice < snapViewController.currentPrice) {
					snapViewController.price.textColor = posColor;
					NSString *pathx = [[NSBundle mainBundle] pathForResource:[NSString stringWithFormat:@"portlet_stock_arrow_pos_%@.png",[langSetting localizedString:@"LangCode"]] ofType:nil];
					UIImage *imgx = [[UIImage alloc] initWithContentsOfFile:pathx];
					snapViewController.priceIndicator.image = imgx;
					[imgx release];
				}
				else if (snapViewController.previousPrice > snapViewController.currentPrice){
					snapViewController.price.textColor = negColor;
					NSString *pathx = [[NSBundle mainBundle] pathForResource:[NSString stringWithFormat:@"portlet_stock_arrow_neg_%@.png",[langSetting localizedString:@"LangCode"]] ofType:nil];
					UIImage *imgx = [[UIImage alloc] initWithContentsOfFile:pathx];
					snapViewController.priceIndicator.image = imgx;
					[imgx release];
				}
				else {
					snapViewController.price.textColor = [UIColor colorWithRed:77.0/255 green:77.0/255 blue:77.0/255 alpha:1];
				}

				[self cacheInsertController:snapViewController atIndex:i];
				[snapViewController release];
			} else {
				snapViewController.view.frame = CGRectMake((i - index * CVPORTLET_STOCK_IN_THE_NEW_PORTRAIT_ELEMENT)*CVPORTLET_STOCK_IN_THE_NEW_WIDTH,
														   0,
														   snapViewController.view.frame.size.width,
														   snapViewController.view.frame.size.height);
			}

			[pageView addSubview:snapViewController.view];
		}
	} else {
		pageView = [scrollPageView dequeueReusablePage:index];

		if (nil == pageView) {
			pageView = [[[UIView alloc] initWithFrame:CGRectMake(0, 10, CVPORTLET_STOCK_IN_THE_NEW_WIDTH * CVPORTLET_STOCK_IN_THE_NEW_LANDSCAPE_ELEMENT, 211)] autorelease];
			[pageView setBackgroundColor:[UIColor clearColor]];
		}

		NSUInteger newsCount = [self.stockList count];
		for (NSUInteger i = index * CVPORTLET_STOCK_IN_THE_NEW_LANDSCAPE_ELEMENT; (i < (index * CVPORTLET_STOCK_IN_THE_NEW_LANDSCAPE_ELEMENT + CVPORTLET_STOCK_IN_THE_NEW_LANDSCAPE_ELEMENT)) && i < newsCount; i++) {
			CVStockSnapShotViewController *snapViewController;
			NSDictionary *dict;
			// temperarily used for log strings
			NSString *tempString;

			snapViewController = [self cacheControllerAtIndex:i];
			if (nil == snapViewController) {
				dict = [stockList objectAtIndex:i];
				snapViewController = [[CVStockSnapShotViewController alloc] init];
				snapViewController.isNeedRefresh = self.isNeedRefresh;
				snapViewController.stockCode = [dict objectForKey:@"GPDM"];

				snapViewController.view.backgroundColor = [UIColor clearColor];

				snapViewController.view.frame = CGRectMake((i - index * CVPORTLET_STOCK_IN_THE_NEW_LANDSCAPE_ELEMENT)*CVPORTLET_STOCK_IN_THE_NEW_WIDTH,
                                                           0,
                                                           snapViewController.view.frame.size.width,
                                                           snapViewController.view.frame.size.height);
				snapViewController.code.text = [dict objectForKey:@"GPDM"];
				snapViewController.code.font = [UIFont boldSystemFontOfSize:13];
				snapViewController.code.textColor = [UIColor colorWithRed:77.0/255 green:77.0/255 blue:77.0/255 alpha:1];
				dict = [stockList objectAtIndex:i];
				snapViewController.symbol.text = [dict objectForKey:@"GPJC"];
				snapViewController.symbol.font = [UIFont boldSystemFontOfSize:16];
				snapViewController.symbol.textColor = [UIColor colorWithRed:77.0/255 green:77.0/255 blue:77.0/255 alpha:1];
				snapViewController.desc.font = [UIFont systemFontOfSize:12];
				snapViewController.desc.text = [dict objectForKey:@"title"];
				[snapViewController adjustDescLabel];
				snapViewController.desc.textColor = [UIColor colorWithRed:77.0/255 green:77.0/255 blue:77.0/255 alpha:1];
				snapViewController.strPostID = [dict objectForKey:@"post_id"];
				tempString = [dict objectForKey:@"ZSP"];
				snapViewController.previousPrice = [tempString floatValue];

				tempString = [dict objectForKey:@"SPJ"];
				snapViewController.currentPrice = [tempString floatValue];
				tempString = [NSString stringWithFormat:@"%0.2f", [tempString floatValue] / 1000];
				snapViewController.price.text  = tempString;

				UIColor *posColor = [langSetting getColor:@"GainersRate"];
				UIColor *negColor = [langSetting getColor:@"LosersRate"];

				if (snapViewController.previousPrice < snapViewController.currentPrice) {
					snapViewController.price.textColor = posColor;
					NSString *pathx = [[NSBundle mainBundle] pathForResource:[NSString stringWithFormat:@"portlet_stock_arrow_pos_%@.png",[langSetting localizedString:@"LangCode"]] ofType:nil];
					UIImage *imgx = [[UIImage alloc] initWithContentsOfFile:pathx];
					snapViewController.priceIndicator.image = imgx;
					[imgx release];
				}
				else if (snapViewController.previousPrice > snapViewController.currentPrice){
					snapViewController.price.textColor = negColor;
					NSString *pathx = [[NSBundle mainBundle] pathForResource:[NSString stringWithFormat:@"portlet_stock_arrow_neg_%@.png",[langSetting localizedString:@"LangCode"]] ofType:nil];
					UIImage *imgx = [[UIImage alloc] initWithContentsOfFile:pathx];
					snapViewController.priceIndicator.image = imgx;
					[imgx release];
				}
				else {
					snapViewController.price.textColor = [UIColor colorWithRed:77.0/255 green:77.0/255 blue:77.0/255 alpha:1];
				}

				[self cacheInsertController:snapViewController atIndex:i];
				[snapViewController release];
			} else {
				snapViewController.view.frame = CGRectMake((i - index * CVPORTLET_STOCK_IN_THE_NEW_LANDSCAPE_ELEMENT)*CVPORTLET_STOCK_IN_THE_NEW_WIDTH,
														   0,
														   snapViewController.view.frame.size.width,
														   snapViewController.view.frame.size.height);
			}

			[pageView addSubview:snapViewController.view];
		}
	}

	return pageView;
}

- (void)didScrollToPageAtIndex:(NSUInteger)index {
}

#pragma mark public methods

- (void)adjustSubviews:(UIInterfaceOrientation)orientation {
	[super adjustSubviews:orientation];

	scrollPageViewController.frame = [self viewRectOfOrientation:orientation];
	scrollPageViewController.pageControlFrame = [self pageIndicatorFrame:orientation];
	if (UIInterfaceOrientationPortrait == portalInterfaceOrientation ||
		UIInterfaceOrientationPortraitUpsideDown == portalInterfaceOrientation) {
		scrollPageViewController.pageCount = [stockList count] / CVPORTLET_STOCK_IN_THE_NEW_PORTRAIT_ELEMENT;
		scrollPageViewController.pageCount += ([stockList count] % CVPORTLET_STOCK_IN_THE_NEW_PORTRAIT_ELEMENT == 0)?0:1;
	} else {
		scrollPageViewController.pageCount = [stockList count] / CVPORTLET_STOCK_IN_THE_NEW_LANDSCAPE_ELEMENT;
		scrollPageViewController.pageCount += ([stockList count] % CVPORTLET_STOCK_IN_THE_NEW_LANDSCAPE_ELEMENT == 0)?0:1;
	}
	[scrollPageViewController reloadData];

	activityIndicator.frame = CGRectMake(self.view.frame.size.width / 2 - 15,
										 self.view.frame.size.height / 2 - 5,
										 activityIndicator.frame.size.width,
										 activityIndicator.frame.size.height);
	lbl.center = CGPointMake(self.view.frame.size.width/2, self.view.frame.size.height / 2);

	[self.view bringSubviewToFront:activityIndicator];
}

#pragma mark -
#pragma mark Override
- (void)actionMenuDidDismiss {
	[self reloadData];
}

- (void)clickFresh:(id)sender {
	if (!_ifLoaded) {
		return;
	}
	CVSetting *setting = [CVSetting sharedInstance];
	if (![setting isReachable]) {
		if ([self.stockList count] > 0) {
			lbl.hidden = YES;
		}else {
			lbl.hidden = NO;
		}
		return;
	}
	[activityIndicator startAnimating];
	activityIndicator.hidden = NO;

	scrollPageViewController.view.hidden = YES;

	[self destroyCache];
	self.isNeedRefresh = YES;
	[NSThread detachNewThreadSelector:@selector(loadData:) toTarget:self withObject:[NSNumber numberWithBool:YES]];
}

-(void)reloadData{
	if (!_ifLoaded) {
		return;
	}
    CVDataProvider *dp = [CVDataProvider sharedInstance];
	CVSetting *setting = [CVSetting sharedInstance];
	if (![setting isReachable]) {
		if ([self.stockList count] > 0) {
			lbl.hidden = YES;
		}else {
			lbl.hidden = NO;
		}
		return;
	} else {
        if ([self.stockList count] > 0 && ![dp isDataExpired:@"StockInNewsRefreshTime"]) {
			//do not need refresh
            return;
		}
    }
	lbl.hidden = YES;
	[activityIndicator startAnimating];
	activityIndicator.hidden = NO;

	scrollPageViewController.view.hidden = YES;

	[NSThread detachNewThreadSelector:@selector(loadData:) toTarget:self withObject:[NSNumber numberWithBool:NO]];
}

@end


text:
package uk.co.epii.stephenson.cif;

import java.io.Serializable;

/**
 * User: James Robinson
 * Date: 17/08/2014
 * Time: 16:39
 */
public interface Train extends Serializable {

  public String getUniqueIdentifier();
  public BasicSchedule getBasicSchedule();
  public BasicScheduleExtraDetails getBasicScheduleExtraDetails();
  public OriginLocation getOriginLocation();
  public Iterable<IntermediateLocation> getIntermediateLocations();
  public Iterable<IntermediateLocation> getIntermediateStops();
  public TerminatingLocation getTerminatingLocation();
  public boolean stops(String... stations);

}

redpajama_set_name: RedPajamaGithub


text:
from datetime import datetime
from ..common.exceptions import ErrorInResponseException
from ..common.exceptions import InvalidSwitchToTargetException
from webelement import WebElement
from firefoxlauncher import FirefoxLauncher
from firefox_profile import FirefoxProfile
from extensionconnection import ExtensionConnection
import utils

class WebDriver(object):
    name = "Firefox"

    """The main interface to use for testing,
    which represents an idealised web browser."""
    def __init__(self, profile=None, timeout=30):
        """Creates a webdriver instance.

        Args:
          profile: a FirefoxProfile object (it can also be a profile name,
                   but the support for that may be removed in future, it is
                   recommended to pass in a FirefoxProfile object)
          timeout: the amount of time to wait for extension socket
        """
        self.browser = FirefoxLauncher()
        if type(profile) == str:
            # This is to be Backward compatible because we used to take a
            # profile name
            profile = FirefoxProfile(name=profile)
        if not profile:
            profile = FirefoxProfile()
        self.browser.launch_browser(profile)
        self._conn = ExtensionConnection(timeout)
        self._conn.connect()

    def execute_script(self, script, *args):
        """Executes arbitrary javascript.
        For WebElement argument, the format is:
        execute_script("argument[0].value='cheese'", elem)
        """
        converted_args = []
        for arg in args:
            if type(arg) == WebElement:
                converted_args.append({"type": "ELEMENT", "value": arg.id})
            else:
                converted_args.append({"type": "STRING", "value": arg})
        resp = self._command("executeScript", script, converted_args)
        if "ELEMENT" == resp["type"]:
            return WebElement(self, resp["value"])
        else:
            return resp["value"]

    def get(self, url):
        """Loads a web page in the current browser."""
        self._command("get", url)

    def get_current_url(self):
        """Gets the current url."""
        return self._command("getCurrentUrl")

    def get_title(self):
        """Gets the title of the current page."""
        return self._command("title")

    def find_element_by_xpath(self, xpath):
        """Finds an element by xpath."""
        return self._find_element_by("xpath", xpath)

    def find_element_by_link_text(self, link):
        """Finds an element by its link text.

        throws NoSuchElementException when no element is found
        with the link text.
        """
        return self._find_element_by("link text", link)

    def find_elements_by_link_text(self, link):
        """Finds all elements with the same link text.

        throws NoSuchElementException when no element is found
        with the link text.
        """
        return self._find_elements_by("link text", link)

    def find_element_by_partial_link_text(self, text):
        """Finds an element by a segment of its link text

        throws NoSuchElementException when no element is found
        with the link text.
        """
        return self._find_element_by("partial link text", text)

    def find_elements_by_partial_link_text(self, text):
        """Finds all elements by a segment of the link text.

        throws NoSuchElementException when no element is found
        with the link text.
        """
        return self._find_elements_by("partial link text", text)

    def find_element_by_id(self, id_):
        """Finds an element by its id."""
        return self._find_element_by("id", id_)

    def find_element_by_name(self, name):
        """Finds and element by its name."""
        return self._find_element_by("name", name)

    def find_elements_by_xpath(self, xpath):
        """Finds all the elements for the given xpath query."""
        return self._find_elements_by("xpath", xpath)

    def find_element_by_tag_name(self, tag_name):
        """Finds and element by its tag name."""
        return self._find_element_by("tag name", tag_name)

    def find_elements_by_tag_name(self, tag_name):
        """Finds all the elements with the given tag"""
        return self._find_elements_by("tag name", tag_name)

    def get_page_source(self):
        """Gets the page source."""
        return self._command("getPageSource")

    def close(self):
        """Closes the current window.
        Quit the browser if it's the last window open.
        """
        if self._conn.is_connectable():
            self._conn.driver_command("close")
        self.browser.kill()

    def quit(self):
        """Quits the driver and close every associated window."""
        self._conn.quit()
        self.browser.kill()

    def switch_to_active_element(self):
        """Returns the element with focus, or BODY if nothing has focus"""
        return WebElement(self, self._command("switchToActiveElement"))

    def switch_to_window(self, window_name):
        """Switches focus to a window."""
        resp = self._command("switchToWindow", window_name)
        if not resp or "No window found" in resp:
            raise InvalidSwitchToTargetException(
                "Window %s not found" % window_name)
        self._conn.context = resp

    def get_current_window_handle(self):
        handle = self._command("getCurrentWindowHandle")
        assert "," not in handle, "there should be only one current handle"
        return handle

    def get_window_handles(self):
        return self._command("getWindowHandles")

    def switch_to_frame(self, index_or_name):
        """Switches focus to a frame by index or name."""
        self._command("switchToFrame", str(index_or_name))

    def back(self):
        """Goes back in browser history."""
        self._command("goBack")

    def forward(self):
        """Goes forward in browser history."""
        self._command("goForward")

    def get_cookies(self):
        """Gets all the cookies."""
        try:
            cookie_response = self._command("getCookie")
        except ErrorInResponseException:
            return []

        #cookie_response is a list of cookies of type unicode
        cookies = []
        for cookie_unicode in cookie_response:
            cookie = self.get_cookie_in_dict(cookie_unicode)
            if cookie:
                cookies.append(cookie)
        return cookies

    def delete_all_cookies(self):
        """Gets the current url."""
        cookies = self.get_cookies()
        for cookie in cookies:
            self.delete_cookie(cookie['name'])

    def delete_cookie(self, cookie_name):
        """Delete a cookie."""
        cookie_arg = "{\"name\" : \"%s\"}" % cookie_name
        self._command("deleteCookie", cookie_arg)

    def get_cookie_in_dict(self, cookie_str):
        """Convert a cookie in unicode (returned by self._command('getCookie'))
        to a dictionary representation.
        """
        tokens = cookie_str.split(";")
        if len(tokens) > 1:
            name, value = tuple(tokens[0].split("=", 1))
            cookie_dict = dict([tuple(token.split("=", 1))
                                for token in tokens[1:] if token])
            cookie_dict["name"] = name
            cookie_dict["value"] = value
            return cookie_dict

    def add_cookie(self, cookie_dict):
        self._command("addCookie", cookie_dict)

    def save_screenshot(self, png_file):
        """Saves a screenshot of the current page into the given
        file."""
        self._command("saveScreenshot", png_file)

    def _command(self, cmd, *args):
        """Forward command on to the extension connection."""
        return self._conn.driver_command(cmd, *args)["response"]

    @property
    def conn(self):
        return self._conn

    def _find_element_by(self, selector, key):
        try:
          elem_id = self._command("findElement", selector, key)
          return WebElement(self, elem_id)
        except ErrorInResponseException, ex:
            utils.handle_find_element_exception(ex)

    def _find_elements_by(self, selector, key):
        try:
            elem_ids = self._command("findElements", selector, key)
            elems = []
            if elem_ids:
                for elem_id in elem_ids:
                    elem = WebElement(self, elem_id)
                    elems.append(elem)
            return elems
        except ErrorInResponseException, ex:
            utils.handle_find_element_exception(ex)


text:
@implementation SQLColumn{
    NSString *_name;
    NSString *_alias;
    SQLColumnType _type;
    SQLAggregate _aggregate;
    bool _primaryKey;
    bool _notNull;
    bool _unique;
    id _value;
}
#pragma mark -
#pragma mark Init Methods
- (id) init{
    return [self initWithColumn:nil];
}
- (id) initWithColumn:(NSString *)columnName{
    return [self initWithColumn:columnName ofColumnType:SQLColumnTypeNone usingAlias:nil aggregate:SQLAggregateNone];
}
- (id) initWithColumn:(NSString *)columnName usingAlias:(NSString *)alias{
    return [self initWithColumn:columnName ofColumnType:SQLColumnTypeNone usingAlias:alias aggregate:SQLAggregateNone];
}
- (id) initWithColumn:(NSString *)columnName ofColumnType:(SQLColumnType)newColumnType usingAlias:(NSString *)newAlias aggregate:(SQLAggregate)aggregate{
    if((self = [super init])){
        _name = columnName;
        _type = newColumnType;
        _alias = newAlias;
        _aggregate = aggregate;
        _primaryKey = NO;
        _notNull = NO;
        _unique = NO;
        _value = nil;
    }
    return self;
}
#pragma mark - Private Methods
#pragma mark - Protocol Methods
- (id) copyWithZone:(NSZone *)zone{
    SQLColumn *copy = [[SQLColumn alloc] initWithColumn:_name usingAlias:_alias];
    copy.type = _type;
    copy.aggregate = _aggregate;
    copy.primaryKey = _primaryKey;
    copy.notNull = _notNull;
    copy.unique = _unique;
    return copy;
}
#pragma mark - Properties
- (NSString *) nameString{
    if (_alias){
        return _alias;
    } else {
        if (_aggregate != SQLAggregateNone){
            return $(@"%@(%@)", self.columnAggregateString, _name);
        } else {
            return _name;
        }
    }
}
- (NSString *) columnTypeString{
    switch (_type) {
        case SQLColumnTypeText:
            return @"TEXT";
        case SQLColumnTypeInt:
            return @"INTEGER";
        case SQLColumnTypeReal:
            return @"REAL";
        case SQLColumnTypeBlob:
            return @"BLOB";
        case SQLColumnTypeNone:
            return @"";
        default:
            return @"";
    }
}
- (NSString *) columnAggregateString{
    switch (_aggregate) {
        case SQLAggregateNone:
            return @"";
        case SQLAggregateTotal:
            return @"total";
        case SQLAggregateMax:
            return @"max";
        case SQLAggregateMin:
            return @"min";
        case SQLAggregateAvg:
            return @"avg";
        case SQLAggregateCount:
            return @"COUNT";
        default:
            return @"";
    }
}
- (void) setValue:(id)value{
    if ([self validateValue:value]) _value = value;
    else {
      //FlxLog(@"Column type: %@, couldn't validate Value: %@", [self columnTypeString], value);
        _value = nil;
    }
}
- (id) value{
    return  _value;
}
#pragma mark - Standard Methods
- (BOOL) validateValue:(id)value{
    if (!value) return YES;
    switch (_type) {
        case SQLColumnTypeNone:
            return YES;
        case SQLColumnTypeReal:
        case SQLColumnTypeInt:
            return [value isKindOfClass:[NSNumber class]] || [value isKindOfClass:[NSDate class]];
        case SQLColumnTypeBlob:
            return [value isKindOfClass:[NSString class]] || [value isKindOfClass:[NSData class]];
        case SQLColumnTypeText:
            return [value isKindOfClass:[NSString class]];
    }
    return NO;
}
#pragma mark - Overridden Methods
- (NSUInteger) hash{
    return [self nameString].hash;
}
- (BOOL) isEqual:(id)object{
    if (![object isKindOfClass:[SQLColumn class]]) return NO;
    return [self.nameString isEqualToString:[object nameString]];
}
@end


text:
# hello-world
Not much to say about me...


text:
package io.github.easyframe.demo.stand;

import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.cloud.netflix.eureka.EnableEurekaClient;
import org.springframework.core.env.Environment;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.Date;

/**
 * Demo Server: default url is http://localhost:28080
 *
 * @author linzhaoming
 */
@SpringBootApplication
@RestController
@Slf4j
@EnableEurekaClient
public class DemoApplication {

    @Autowired
    private Environment environment;

    public static void main(String[] args) {
        SpringApplication.run(DemoApplication.class, args);
    }

    @GetMapping("/test")
    public String test() {
        log.info("From /test request: " + new Date());
        return "EasyFrame-22 \n";
    }

    @GetMapping("/test1")
    public String test1() {
        return "test12: " + new Date();
    }

    @GetMapping("/test2")
    public String test2() {
        return "test2: " + new Date();
    }

    @GetMapping("/test3")
    public String test3() {
        return "test3: linzm=" + environment.getProperty("linzm");
    }

}


text:
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>es2015 Web Component Tutorial</title>
    <script src="Scripts/src/webcomponents.min.js"></script>
    <script src="date-widget.js"></script>
</head>
<body>
<date-widget theme="green"></date-widget>
</body>
</html>


text:
- Nervion won't raise an exception if you try to stop it and it wasn't running
- Added `running?` method to check whether Nervion is running or not

# version 0.0.3

- Allow Nervion to run without being responsible for EventMachine's event loop

# version 0.0.2

- Support for firehose endpoint
- Validate client setup before start streaming

# version 0.0.1

- Support for sample and filter endpoints
- OAuth authentication


text:
package multiverse.server.objects;

import multiverse.server.util.*;
import multiverse.server.math.*;
import java.io.*;
import java.util.*;
import java.util.concurrent.locks.*;

/**
 * although we use a 3d point, this boundary is a 2d boundary which only looks
 * at the X,Z values of the point
 */
public class Boundary implements Cloneable, Serializable {
    public Boundary() {
        setupTransient();
    }

    public Boundary(String name) {
        setupTransient();
        this.name = name;
    }

    public Boundary(List<Point> points) {
        setupTransient();
        setPoints(points);
    }

    void setupTransient() {
        lock = LockFactory.makeLock("BoundaryLock");
    }

    private void readObject(java.io.ObjectInputStream in)
            throws java.io.IOException, ClassNotFoundException {
        in.defaultReadObject();
        setupTransient();
    }

    public void setName(String name) {
        this.name = name;
    }

    public String getName() {
        return name;
    }

    public String toString() {
        String s = "[Boundary: name=" + name;
        lock.lock();
        try {
            for (Point p : pointList) {
                s += " p=" + p;
            }
            return s + "]";
        } finally {
            lock.unlock();
        }
    }

    public Object clone() {
        lock.lock();
        try {
            Boundary b = new Boundary(this.pointList);
            b.setName(this.getName());
            return b;
        } finally {
            lock.unlock();
        }
    }

    public void setPoints(List<Point> points) {
        lock.lock();
        try {
            this.pointList = new LinkedList<Point>(points);
            boundingBox = null;
        } finally {
            lock.unlock();
        }
    }

    public List<Point> getPoints() {
        lock.lock();
        try {
            return new LinkedList<Point>(pointList);
        } finally {
            lock.unlock();
        }
    }

    public void addPoint(Point p) {
        lock.lock();
        try {
            pointList.add(p);
            boundingBox = null;
        } finally {
            lock.unlock();
        }
    }

    public Geometry getBoundingBox() {
        lock.lock();
        try {
            if (boundingBox != null)
                return boundingBox;

            int minX = Integer.MAX_VALUE, maxX = Integer.MIN_VALUE, minZ = Integer.MAX_VALUE, maxZ = Integer.MIN_VALUE;
            for (Point p : pointList) {
                if (p.getX() < minX)
                    minX = p.getX();
                if (p.getX() > maxX)
                    maxX = p.getX();
                if (p.getZ() < minZ)
                    minZ = p.getZ();
                if (p.getZ() > maxZ)
                    maxZ = p.getZ();
            }
            boundingBox = new Geometry(minX, maxX, minZ, maxZ);
            return boundingBox;
        } finally {
            lock.unlock();
        }
    }

    protected Geometry boundingBox = null;

    /**
     * returns if the point is contained within this 2d boundary
     *
     * pick a point outside of the boundary, create a line segment from the
     * point in question, to the point outside the line. count how many times it
     * crosses line segments of the boundary. if even, its not inside the
     * boundary
     */
    public boolean contains(Point p) {
        // if (Log.loggingDebug)
        //     Log.debug("Boundary.contains: checking p=" + p + ", boundary=" + this);
        int count = 0;

        lock.lock();
        try {
            // pick a point outside the boundary
            // find the largest Z value and pick something bigger
            Integer maxZ = null;
            Integer maxX = null;
            for (Point tmpP : pointList) {
                if (maxZ == null) {
                    maxZ = tmpP.getZ();
                    maxX = tmpP.getX();
                    continue;
                }
                if (tmpP.getZ() > maxZ) {
                    maxZ = tmpP.getZ();
                }
                if (tmpP.getX() > maxX) {
                    maxX = tmpP.getX();
                }
            }
            if ((maxZ == null) || (maxX == null)) {
                return false;
            }

            Point prevPoint = null;
            Point curPoint = null;
            Point firstPoint = null;
            Iterator<Point> iter = pointList.iterator();
            while (iter.hasNext()) {
                // set up the first time around
                if (curPoint == null) {
                    curPoint = iter.next();
                    firstPoint = curPoint;
                    continue;
                }

                // make the line segment from the prevPoint and curPoint
                // the boundary
                prevPoint = curPoint;
                curPoint = iter.next();
                Vector2 p1 = new Vector2(prevPoint.getX(), prevPoint.getZ());
                Vector2 p2 = new Vector2(curPoint.getX(), curPoint.getZ());

                // make the line segment from the point passed in and
                // the point outside the boundary
                Vector2 p3 = new Vector2(p.getX(), p.getZ());
                Vector2 p4 = new Vector2(maxX, maxZ + 1000);

//                Log.debug("Boundary.contains: line segment p1=" + p1 + ", p2="
//                        + p2 + " -- intersect segment p3=" + p3 + ", p4=" + p4);
                if (IntersectSegments(p1, p2, p3, p4)) {
                    count++;
                    // Log.debug("Boundary.contains: intersected");
                } else {
                    // Log.debug("Boundary.contains: did not intersect");
                }
            }
            // check the segment that closes the last to the first points
            if (IntersectSegments(new Vector2(firstPoint.getX(), firstPoint.getZ()),
                    new Vector2(curPoint.getX(), curPoint.getZ()),
                    new Vector2(p.getX(), p.getZ()),
                    new Vector2(maxX, maxZ + 1000))) {
                count++;
                // Log.debug("Boundary.contains: last side intersected");
            }
            else {
                // Log.debug("Boundary.contains: last side did not intersect");
            }
            boolean rv = ((count % 2) != 0);
            // Log.debug("Boundary.contains: final count=" + count + ", contains="
            //        + rv);
            return rv;
        } finally {
            lock.unlock();
        }
    }

    // check if 2 segments intersect
    private static boolean IntersectSegments(Vector2 p1, Vector2 p2,
            Vector2 p3, Vector2 p4) {
        long den = ((p4.y - p3.y) * (p2.x - p1.x))
                - ((p4.x - p3.x) * (p2.y - p1.y));

        long t1num = ((p4.x - p3.x) * (p1.y - p3.y))
                - ((p4.y - p3.y) * (p1.x - p3.x));

        long t2num = ((p2.x - p1.x) * (p1.y - p3.y))
                - ((p2.y - p1.y) * (p1.x - p3.x));

        if (den == 0) {
            return false;
        }

        double t1 = (double) t1num / (double) den;
        double t2 = (double) t2num / (double) den;

        // if (Log.loggingDebug)
        //     Log.debug("IntersectSegments: t1=" + t1 + ", t2=" + t2);
        // note that we include the endpoint of the second line in the
        // intersection test, but not the endpoint of the first line.
        if ((t1 >= 0) && (t1 < 1) && (t2 >= 0) && (t2 <= 1)) {
            return true;
        }
        return false;
    }

    public static Boundary getMaxBoundary() {
        int min = 0x80000000;
        int max = 0x7fffffff;
        Boundary b = new Boundary();
        b.addPoint(new Point(min,0,max));
        b.addPoint(new Point(max,0,max));
        b.addPoint(new Point(max,0,min));
        b.addPoint(new Point(min,0,min));
        return b;
    }
    List<Point> pointList = new LinkedList<Point>();

    transient Lock lock = null;

    String name = null;
    private static final long serialVersionUID = 1L;
}


text: Project aspnet Mvc


text:
package net.sourceforge.dynamicgmf.diagram.part;

import java.util.Iterator;
import java.util.List;

import org.eclipse.gef.EditPart;
import org.eclipse.gef.Request;
import org.eclipse.gef.commands.Command;
import org.eclipse.gef.commands.UnexecutableCommand;
import org.eclipse.gmf.runtime.diagram.ui.actions.AbstractDeleteFromAction;
import org.eclipse.gmf.runtime.diagram.ui.actions.ActionIds;
import org.eclipse.gmf.runtime.diagram.ui.commands.CommandProxy;
import org.eclipse.gmf.runtime.diagram.ui.commands.ICommandProxy;
import org.eclipse.gmf.runtime.diagram.ui.l10n.DiagramUIMessages;
import org.eclipse.gmf.runtime.emf.commands.core.command.CompositeTransactionalCommand;
import org.eclipse.ui.ISharedImages;
import org.eclipse.ui.IWorkbenchPage;
import org.eclipse.ui.IWorkbenchPart;
import org.eclipse.ui.PlatformUI;

/**
 * @generated
 */
public class DeleteElementAction extends AbstractDeleteFromAction {

	/**
	 * @generated
	 */
	public DeleteElementAction(IWorkbenchPart part) {
		super(part);
	}

	/**
	 * @generated
	 */
	public DeleteElementAction(IWorkbenchPage workbenchPage) {
		super(workbenchPage);
	}

	/**
	 * @generated
	 */
	public void init() {
		super.init();
		setId(ActionIds.ACTION_DELETE_FROM_MODEL);
		setText(DiagramUIMessages.DiagramEditor_Delete_from_Model);
		setToolTipText(DiagramUIMessages.DiagramEditor_Delete_from_ModelToolTip);
		ISharedImages workbenchImages = PlatformUI.getWorkbench()
				.getSharedImages();
		setHoverImageDescriptor(workbenchImages
				.getImageDescriptor(ISharedImages.IMG_TOOL_DELETE));
		setImageDescriptor(workbenchImages
				.getImageDescriptor(ISharedImages.IMG_TOOL_DELETE));
		setDisabledImageDescriptor(workbenchImages
				.getImageDescriptor(ISharedImages.IMG_TOOL_DELETE_DISABLED));
	}

	/**
	 * @generated
	 */
	protected String getCommandLabel() {
		return DiagramUIMessages.DiagramEditor_Delete_from_Model;
	}

	/**
	 * @generated
	 */
	protected Command getCommand(Request request) {
		List operationSet = getOperationSet();
		if (operationSet.isEmpty()) {
			return UnexecutableCommand.INSTANCE;
		}
		Iterator editParts = operationSet.iterator();
		CompositeTransactionalCommand command = new CompositeTransactionalCommand(
				getEditingDomain(), getCommandLabel());
		while (editParts.hasNext()) {
			EditPart editPart = (EditPart) editParts.next();
			Command curCommand = editPart.getCommand(request);
			if (curCommand != null) {
				command.compose(new CommandProxy(curCommand));
			}
		}
		if (command.isEmpty() || command.size() != operationSet.size()) {
			return UnexecutableCommand.INSTANCE;
		}
		return new ICommandProxy(command);
	}
}


text:
require 'spec_helper'

RSpec.feature 'Member managing jobs', type: :feature do
  let(:member) { Fabricate(:member) }

  before do
    login(member)
  end

  context 'viewing their jobs' do
    scenario 'can view all jobs they posted' do
      jobs = Fabricate.times(3, :published_job, created_by: member)
      pending_jobs = Fabricate.times(2, :pending_job, created_by: member)
      drafts = Fabricate.times(3, :job, created_by: member)
      visit member_jobs_path

      expect(page.all(:xpath, "//td/span[text()='Published']").count).to eq(3)
      expect(page.all(:xpath, "//td/span[text()='Pending approval']").count).to eq(2)
      expect(page.all(:xpath, "//td/span[text()='Draft']").count).to eq(3)
    end

    it 'an approved job renders the member job page' do
      job = Fabricate(:job, approved: true, created_by: member)

      visit member_jobs_path
      click_on job.title

      expect(page.current_path).to eq(member_job_path(job.id))
    end

    it 'drafts job post take a user to the member job page' do
      job = Fabricate(:job, submitted: true, approved: false, created_by: member)

      visit member_jobs_path
      click_on job.title

      expect(page.current_path).to eq(member_job_path(job.id))
    end

    it 'pending job post take a user to the member job post' do
      job = Fabricate(:job, submitted: false, approved: false, created_by: member)

      visit member_jobs_path
      click_on job.title

      expect(page.current_path).to eq(member_job_path(job.id))
    end
  end

  context 'creating a new job' do
    scenario 'is unsuccessful unless all mandatory fields are submitted' do
      visit new_member_job_path

      fill_in 'Name', with: 'codebar'
      click_on 'Submit job'

      expect(page).to have_content('Title can\'t be blank')
    end

    scenario 'is succesful when all madantory fields are submitted' do
      visit new_member_job_path

      fill_in 'Title', with: 'Internship'
      fill_in 'Description', with: Faker::Lorem.paragraph
      fill_in 'Name', with: 'codebar'
      fill_in 'Website', with: 'https://codebar.io'
      fill_in 'Location', with: 'London'
      fill_in 'Link to job post', with: Faker::Internet.url
      fill_in 'Application closing date', with: (Time.zone.now + 3.months).strftime('%d/%m/%y')

      click_on 'Submit job'

      expect(page).to have_content('This is a preview of your job.Edit to amend or Submit for approval')
    end

    scenario 'can view text that address and postcode fields are optional' do
      visit new_member_job_path

      expect(page).to have_content('The information below is only required if you want this job post to be shared with Google Search UK.')
    end
  end

  context 'viewing a job' do
    it 'renders a preview of the job' do
      job = Fabricate(:job, submitted: false, approved: false, created_by: member)

      visit member_job_path(job.id)

      expect(page).to have_content('This is a preview of your job.Edit to amend or Submit for approval')
      expect(page).to have_content(job.title)
    end

    it 'informs the user if a job has already been submitted' do
      job = Fabricate(:pending_job, created_by: member)
      visit member_job_path(job.id)

      expect(page).to have_content("This job is pending approval. Edit to amend your post.")
    end

    it 'allows the user to submit draft jobs' do
      job = Fabricate(:job, created_by: member)
      visit member_job_path(job.id)

      expect(page).to have_content('This is a preview of your job.Edit to amend or Submit for approval.')

      click_on 'Submit'
      expect(page).to have_content("Job submitted for approval. You will receive an email when it's been approved.")
    end
  end

  context '#edit' do
    scenario 'can edit their job' do
      job =  Fabricate(:job, approved: false, created_by: member)
      visit edit_member_job_path(job.id)

      fill_in 'Title', with: 'JavaScript Internship'
      click_on 'Submit'

      expect(page).to have_content('Your job has been updated')
    end

    scenario 'can not reset  mandatory fields' do
      job =  Fabricate(:job, approved: false, created_by: member)
      visit edit_member_job_path(job.id)

      fill_in 'Title', with: ''
      click_on 'Submit'

      expect(page).to have_content('Title can\'t be blank')
    end

    scenario 'can not edit an approved job' do
      approved_job =  Fabricate(:published_job, created_by: member)
      visit edit_member_job_path(approved_job.id)

      expect(page).to have_content('You cannot edit a job that has already been approved.')
    end
  end
end


text:
var test = require("ava");
var webpack = require("webpack");

var conf = require("./utils/conf");

test.cb("eslint-loader can return warning", function(t) {
  t.plan(2);
  webpack(
    conf({
      entry: "./test/fixtures/warn.js"
    }),
    function(err, stats) {
      if (err) {
        throw err;
      }

      // console.log(stats.compilation.warnings)
      t.true(
        stats.hasWarnings(),
        "a file that contains eslint warning should return warning"
      );

      // console.log(stats.compilation.errors)
      t.false(
        stats.hasErrors(),
        "a bad file should return no error if it contains only warning by default"
      );
      t.end();
    }
  );
});


text:
package mappers.io;

import java.io.IOException;

import org.apache.hadoop.mapreduce.Mapper;

import data.Triple;
import data.TripleSource;

public class CleanTriplesDuplicatesMapper extends
		Mapper<TripleSource, Triple, Triple, TripleSource> {

	protected void map(TripleSource key, Triple value, Context context)
			throws IOException, InterruptedException {
		context.write(value, key);
	}

}


text:
from __future__ import unicode_literals

from django.contrib.auth.models import Permission
from django.db import migrations

def delete_old_logo_permission(apps, schema_editor):
    """
    Deletes the old 'can_manage_logo' permission which is replaced with
    'can_manage_logos_and_fonts'. If this is a fresh database, no permission
    will be deleted, in fact the old permission does not exist. Django creates
    the permission after all migration and the old one is not generated.
    If this is an old database, the new permission will be created and the old
    one deleted. Also it will be assigned to the groups, which had the old permission.
    """
    perm = Permission.objects.filter(codename="can_manage_logos")

    if len(perm):
        perm = perm.get()
        # Save content_type for manual creation of new permissions.
        content_type = perm.content_type

        # Save groups. list() is necessary to evaluate the database query right now.
        groups = list(perm.group_set.all())

        # Delete permission
        perm.delete()

        # Create new permission
        perm = Permission.objects.create(
            codename="can_manage_logos_and_fonts",
            name="Can manage logos and fonts",
            content_type=content_type,
        )

        for group in groups:
            group.permissions.add(perm)
            group.save()

class Migration(migrations.Migration):

    dependencies = [("core", "0006_auto_20180123_0903")]

    operations = [
        migrations.AlterModelOptions(
            name="configstore",
            options={
                "default_permissions": (),
                "permissions": (
                    ("can_manage_config", "Can manage configuration"),
                    ("can_manage_logos_and_fonts", "Can manage logos and fonts"),
                ),
            },
        ),
        migrations.RunPython(delete_old_logo_permission),
    ]


text:
(function ($) {
  $.fn.extend({
    postlink: function (options) {
      return this.each(function () {
        $(this).click(function (e) {
          var frm = $("<form>");
          frm.attr({'action': $(this).attr('href'), 'method': 'post'});
          frm.appendTo("body");
          frm.submit();
          e.preventDefault();
        });
      });
    }
  });

  $(function () {
    $('.postlink').postlink();

    $('table.flow span.step-label').click(function (e) {
      var stepData = $(this).siblings('div.action');
      stepData.slideToggle();
    });

    $('.plan-step .step-label').click(function (e) {
      var stepData = $(this).siblings('div.action');
      stepData.slideToggle();
    });
  });

})(jQuery);


text:
package com.vaadin.tests.components.combobox;

import static org.junit.Assert.assertEquals;

import org.junit.Test;
import org.openqa.selenium.Keys;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.interactions.Actions;

import com.vaadin.testbench.By;
import com.vaadin.testbench.commands.TestBenchElementCommands;
import com.vaadin.testbench.elements.ComboBoxElement;
import com.vaadin.testbench.parallel.BrowserUtil;
import com.vaadin.tests.tb3.MultiBrowserTest;

/**
 * ComboBox should clear its value when setting to null with new items.
 */
public class ComboBoxSetNullWhenNewItemsAllowedTest extends MultiBrowserTest {

    @Test
    public void testNewValueIsClearedAppropriately()
            throws InterruptedException {
        setDebug(true);
        openTestURL();

        WebElement element = $(ComboBoxElement.class).first()
                .findElement(By.vaadin("#textbox"));
        ((TestBenchElementCommands) element).click(8, 7);
        element.clear();
        element.sendKeys("New value");
        assertEquals("New value", element.getAttribute("value"));
        if (BrowserUtil.isPhantomJS(getDesiredCapabilities())) {
            new Actions(getDriver()).sendKeys(Keys.ENTER).perform();
            Thread.sleep(500);
        } else {
            element.sendKeys(Keys.RETURN);
        }

        assertEquals("", element.getAttribute("value"));
    }
}


text:
#include "zbarmodule.h"

static char symbolset_doc[] = PyDoc_STR(
    "symbol result container.\n"
    "\n"
    "collection of symbols.");

static int
symbolset_clear (zbarSymbolSet *self)
{
    if(self->zsyms) {
        zbar_symbol_set_t *zsyms = (zbar_symbol_set_t*)self->zsyms;
        self->zsyms = NULL;
        zbar_symbol_set_ref(zsyms, -1);
    }
    return(0);
}

static void
symbolset_dealloc (zbarSymbolSet *self)
{
    symbolset_clear(self);
    ((PyObject*)self)->ob_type->tp_free((PyObject*)self);
}

static zbarSymbolIter*
symbolset_iter (zbarSymbolSet *self)
{
    return(zbarSymbolIter_FromSymbolSet(self));
}

Py_ssize_t
symbolset_length (zbarSymbolSet *self)
{
    if(self->zsyms)
        return(zbar_symbol_set_get_size(self->zsyms));
    return(0);
}

static PySequenceMethods symbolset_as_sequence = {
    .sq_length      = (lenfunc)symbolset_length,
};

PyTypeObject zbarSymbolSet_Type = {
    PyObject_HEAD_INIT(NULL)
    .tp_name        = "zbar.SymbolSet",
    .tp_doc         = symbolset_doc,
    .tp_basicsize   = sizeof(zbarSymbolSet),
    .tp_flags       = Py_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE,
    .tp_dealloc     = (destructor)symbolset_dealloc,
    .tp_iter        = (getiterfunc)symbolset_iter,
    .tp_as_sequence = &symbolset_as_sequence,
};

zbarSymbolSet*
zbarSymbolSet_FromSymbolSet(const zbar_symbol_set_t *zsyms)
{
    zbarSymbolSet *self = PyObject_New(zbarSymbolSet, &zbarSymbolSet_Type);
    if(!self)
        return(NULL);
    if(zsyms) {
        zbar_symbol_set_t *ncsyms = (zbar_symbol_set_t*)zsyms;
        zbar_symbol_set_ref(ncsyms, 1);
    }
    self->zsyms = zsyms;
    return(self);
}


text:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace RemoveNegativesAndReverse_Framework
{
    class Program
    {
        static void Main(string[] args)
        {

            List<int> numbers = Console.ReadLine().Split(' ').Select(int.Parse).ToList();
            List<int> positiveNumbers = new List<int>();
            for (int i = 0; i < numbers.Count; i++)
            {
                if (numbers[i] > 0)
                {
                    positiveNumbers.Add(numbers[i]);
                }
            }
            positiveNumbers.Reverse();
            if (positiveNumbers.Count == 0)
            {
                Console.WriteLine($"empty");
            }

            else
            {
                Console.WriteLine(string.Join(" ",positiveNumbers));
            }

        }
    }
}


text:
<!doctype html>

<script src="./js/upvHandler.js"></script>


text:
<?php
namespace Bolt\Events;

use Symfony\Component\EventDispatcher\GenericEvent;

/**
 * Event instance for Storage events.
 *
 * PRE_SAVE (preSave)
 * - Available:
 *   - Content obejct
 * - Notes:
 *   - Do not call saveContent()
 *
 * POST_SAVE (postSave)
 * - Available:
 *   - Content obejct
 *   - ID
 * - Notes:
 *   - Safe to call saveContent()
 *
 * PRE_DELETE (preDelete)
 * - Available:
 *   - Content obejct
 *   - ID
 * - Notes:
 *   - Do not call saveContent()
 *
 * POST_DELETE (postDelete)
 * - Available:
 *   - Content obejct
 *   - ID
 * - Notes:
 *   - Do not call saveContent()
 *   - Database record will no longer exist
 */
class StorageEvent extends GenericEvent
{
    /**
     * @var \Bolt\Legacy\Content|array
     */
    protected $subject;

    /**
     * @var array
     */
    protected $arguments;

    /**
     * Instantiate generic Storage Event.
     *
     * @param \Bolt\Legacy\Content|array $subject   A Content object that is being saved or deleted
     * @param array                      $arguments Arguments to store in the event.
     */
    public function __construct($subject = null, array $arguments = [])
    {
        $this->subject = $subject;
        $this->arguments = $arguments;
    }

    /**
     * Return the record id.
     *
     * @return integer
     */
    public function getId()
    {
        return $this->getSubject()->id;
    }

    /**
     * Return the record contenttype.
     *
     * @return string
     */
    public function getContentType()
    {
        $contentType = $this->getSubject()->contenttype;
        if ($contentType !== null && isset($contentType['slug'])) {
            return $contentType['slug'];
        }
    }

    /**
     * Return the content object.
     *
     * @return \Bolt\Legacy\Content
     */
    public function getContent()
    {
        return $this->getSubject();
    }

    /**
     * Is the record being created, updated or deleted.
     *
     * @return bool|null True  - Create
     *                   False - Update
     *                   Null  - Delete
     */
    public function isCreate()
    {
        if ($this->hasArgument('create')) {
            return $this->getArgument('create');
        }

        return null;
    }
}


text:
var promisify = require('../../../src/util').promisify;

module.exports = promisify(function returnPromise(firstParam, secondParam, callback) {
  setTimeout(function() {
    callback(null, 'Cool');
  }, 300);
});


text:
/**
  @module ember-flexberry-gis
*/

import Ember from 'ember';

/**
  Mixin containing handlers for
  {{#crossLink "FlexberryMapComponent"}}flexberry-map component's{{/crossLink}} actions.

  @class FlexberryMapActionsHandlerMixin
  @extends Ember.Mixin
*/
export default Ember.Mixin.create({
  actions: {
    /**
      Handles {{#crossLink "FlexberryMapComponent/sendingActions.leafletInit:method"}}flexberry-map component's 'leafletInit' action{{/crossLink}}.
      It stores value of action's event object 'map' property in property with given path.

      @method actions.onMapInit
      @param {String} mutablePropertyPath Path to a property, which value must be mutated on action.
      @param {Object} e Action's event object.
      @param {Object} e.map Initialized [Leaflet map](http://leafletjs.com/reference-1.0.0.html#map).

      @example
      templates/my-form.hbs
      ```handlebars
        {{flexberry-map
          lat=model.lat
          lng=model.lng
          zoom=model.zoom
          leafletInit=(action "onMapLeafletInit" "leafletMap")
        }}
      ```

      controllers/my-form.js
      ```javascript
        import Ember from 'ember';
        import FlexberryMapActionsHandlerMixin from 'ember-flexberry-gis/mixins/flexberry-map-actions-handler';

        export default Ember.Controller.extend(FlexberryMapActionsHandlerMixin, {
          // Property where leaflet map will be stored after init.
          leafletMap: null
        });
      ```
    */
    onMapLeafletInit(...args) {
      // User can pass any additional arguments to action handler,
      // so original action's event object will be the last one in arguments array.
      let leafletMapPropertyPath = args[0];
      let e = args[args.length - 1];

      Ember.assert(
        `Wrong type of \`leafletMapPropertyPath\` argument: actual type is \`${leafletMapPropertyPath}\`, ` +
        `but \`string\` is expected`,
        Ember.typeOf(leafletMapPropertyPath) === 'string');

      Ember.set(this, leafletMapPropertyPath, e.map);
      Ember.set(window, leafletMapPropertyPath, e.map);
    },

    onServiceLayerInit(property, serviceLayer) {
      this.set(property, serviceLayer);
    },

    /**
      Handles {{#crossLink "FlexberryMapComponent/sendingActions.leafletDestroy:method"}}flexberry-map component's 'leafletDestroy' action{{/crossLink}}.
      It cleans up previously stored leaflet map.

      @method actions.onMapLeafletDestroy
      @param {String} leafletMapPropertyPath Path to a previously stored leaflet map, which must be cleaned up on action.

      @example
      templates/my-form.hbs
      ```handlebars
        {{flexberry-map
          lat=model.lat
          lng=model.lng
          zoom=model.zoom
          leafletInit=(action "onMapLeafletInit" "leafletMap")
          leafletDestroy=(action "onMapLeafletDestroy" "leafletMap")
        }}
      ```

      controllers/my-form.js
      ```javascript
        import Ember from 'ember';
        import FlexberryMapActionsHandlerMixin from 'ember-flexberry-gis/mixins/flexberry-map-actions-handler';

        export default Ember.Controller.extend(FlexberryMapActionsHandlerMixin, {
          // Property where leaflet map will be stored after init.
          leafletMap: null
        });
      ```
    */
    onMapLeafletDestroy(...args) {
      let leafletMapPropertyPath = args[0];
      Ember.assert(
        `Wrong type of \`leafletMapPropertyPath\` argument: actual type is \`${Ember.typeOf(leafletMapPropertyPath)}\`, ` +
        `but \`string\` is expected`,
        Ember.typeOf(leafletMapPropertyPath) === 'string');

      Ember.set(this, leafletMapPropertyPath, null);
      Ember.set(window, leafletMapPropertyPath, null);
    },

    /**
      Handles {{#crossLink "FlexberryMapComponent/sendingActions.moveend:method"}}flexberry-map component's 'moveend' action{{/crossLink}}.
      It mutates values of lat, lng properties with given names to values of new map center.

      @method actions.onMapMoveend
      @param {String} latPropertyPath Path to a property, containing map center lat.
      @param {String} lngPropertyPath Path to a property, containing map center lng.
      @param {Object} e Action's event object.
      @param {Object} e.taget [Leaflet map](http://leafletjs.com/reference-1.0.0.html#map).

      @example
      templates/my-form.hbs
      ```handlebars
        {{flexberry-map
          lat=model.lat
          lng=model.lng
          zoom=model.zoom
          leafletInit=(action "onMapLeafletInit" "leafletMap")
          moveend=(action "onMapMoveend" "model.lat" "model.lng")
        }}
      ```

      controllers/my-form.js
      ```javascript
        import Ember from 'ember';
        import FlexberryMapActionsHandlerMixin from 'ember-flexberry-gis/mixins/flexberry-map-actions-handler';

        export default Ember.Controller.extend(FlexberryMapActionsHandlerMixin, {
          // Property where leaflet map will be stored after init.
          leafletMap: null
        });
      ```
    */
    onMapMoveend(...args) {
      // User can pass any additional arguments to action handler,
      // so original action's event object will be the last one in arguments array.
      let latPropertyPath = args[0];
      let lngPropertyPath = args[1];
      let e = args[args.length - 1];

      Ember.assert(
        `Wrong type of \`latPropertyPath\` argument: actual type is \`${Ember.typeOf(latPropertyPath)}\`, ` +
        `but \`string\` is expected`,
        Ember.typeOf(latPropertyPath) === 'string');
      Ember.assert(
        `Wrong type of \`lngPropertyPath\` argument: actual type is \`${Ember.typeOf(lngPropertyPath)}\`, ` +
        `but \`string\` is expected`,
        Ember.typeOf(lngPropertyPath) === 'string');

      let newCenterLatLng = e.target.getCenter();
      this.transitionToRoute({ queryParams: { lat: newCenterLatLng.lat, lng: newCenterLatLng.lng, zoom: e.target.getZoom() } });
    },

    /**
      Handles {{#crossLink "FlexberryMapComponent/sendingActions.zoomend:method"}}flexberry-map component's 'zoomend' action{{/crossLink}}.
      It mutates value of zoom property with given name to value of new map zoom.

      @method actions.onMapZoomend
      @param {String} zoomPropertyPath Path to a property, containing map zoom.
      @param {Object} e Action's event object.
      @param {Object} e.taget [Leaflet map](http://leafletjs.com/reference-1.0.0.html#map).

      @example
      templates/my-form.hbs
      ```handlebars
        {{flexberry-map
          lat=model.lat
          lng=model.lng
          zoom=model.zoom
          leafletInit=(action "onMapLeafletInit" "leafletMap")
          mzoomend=(action "onMapZoomend" "model.zoom")
        }}
      ```

      controllers/my-form.js
      ```javascript
        import Ember from 'ember';
        import FlexberryMapActionsHandlerMixin from 'ember-flexberry-gis/mixins/flexberry-map-actions-handler';

        export default Ember.Controller.extend(FlexberryMapActionsHandlerMixin, {
          // Property where leaflet map will be stored after init.
          leafletMap: null
        });
      ```
    */
    onMapZoomend(...args) {
      // User can pass any additional arguments to action handler,
      // so original action's event object will be the last one in arguments array.
      let zoomPropertyPath = args[0];
      let e = args[args.length - 1];

      Ember.assert(
        `Wrong type of \`zoomPropertyPath\` argument: actual type is \`${Ember.typeOf(zoomPropertyPath)}\`, ` +
        `but \`string\` is expected`,
        Ember.typeOf(zoomPropertyPath) === 'string');

      let newZoom = e.target.getZoom();
      this.transitionToRoute({ queryParams: { zoom: newZoom } });
    }
  }
});


text:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Data.SqlClient;
using System.Data;
using System.Web.Configuration;
using static System.Web.UI.MasterPage;

namespace person2
{
    public partial class registration : System.Web.UI.Page
    {
        protected void Page_Load(object sender, EventArgs e)
        {

            if (this.IsPostBack == false)
            {

            }
            else
            {

            }
        }

        protected void btnRegistration_Click(object sender, EventArgs e)
        {
            string name = txtName.Text;
            string code = txtCode.Text;
            string strRoletype = ddlroletype.SelectedValue;
            int roletype = 1;     // 預設角色為學生
            int.TryParse(strRoletype, out roletype);

            DateTime createdtime = DateTime.Now;
            string email = txtEmail.Text;
            string username = txtUsername.Text;
            string password = txtPassword.Text;
            int sex = int.Parse(rblSex.SelectedValue);

            string strcountry = ddlCountry.SelectedValue;
            int country = 1; //預設國家為臺灣
            int.TryParse(strcountry, out country);

            string education = ddlEducation.Text;
            string region = ddlRegion.Text;

            string strtitle = ddlPtitle.SelectedValue;
            int title = 1; //預設職稱為學生
            int.TryParse(strtitle, out title);

            string strdepartment = ddlPDepartment.SelectedValue;
            int department = 1;//預設系為資管系
            int.TryParse(strdepartment, out department);

            string strcollege = ddlPCollege.SelectedValue;
            int college = 1;//預設院為資訊學院
            int.TryParse(strcollege,out college);

            string year = ddlYear.SelectedValue;
            string month = ddlMonth.SelectedValue;
            string day = ddlDay.SelectedValue;
            DateTime birthday = DateTime.Parse(year + "/" + month + "/" + day);

            using (SqlConnection conn = new SqlConnection(WebConfigurationManager.ConnectionStrings["OTTConnectionString"].ConnectionString))
            {
                SqlCommand cmd = new SqlCommand();
                cmd.CommandText = "Insert Into Person (PName, PCode, PRoleType, PCreatedOn,PEmail,PUserName,PPassword,PSex,PCountry,PBirthDate,PEducation,PRegion,PSuper,PTitle,PDepartment,PCollege) VALUES (@PName, @PCode,@PRoleType,@PCreatedOn,@PEmail,@PUserName,@PPassword,@PSex,@PCountry,@PBirthDate,@PEducation,@PRegion,1,@PTitle,@PDepartment,@PCollege)";
                cmd.Connection = conn;
                cmd.Parameters.AddWithValue("@PName", name);
                cmd.Parameters.AddWithValue("@PCode", code);
                cmd.Parameters.AddWithValue("@PRoleType", roletype);
                cmd.Parameters.AddWithValue("@PCreatedOn",createdtime);
                cmd.Parameters.AddWithValue("@PEmail", email);
                cmd.Parameters.AddWithValue("@PUserName", username);
                cmd.Parameters.AddWithValue("@PPassword", password);
                cmd.Parameters.AddWithValue("@PSex", sex);
                cmd.Parameters.AddWithValue("@PCountry", country);
                cmd.Parameters.AddWithValue("@PBirthDate", birthday);
                cmd.Parameters.AddWithValue("@PEducation", education);
                cmd.Parameters.AddWithValue("@PRegion", region);
                cmd.Parameters.AddWithValue("@PTitle", title);
                cmd.Parameters.AddWithValue("@PDepartment", department);
                cmd.Parameters.AddWithValue("@PCollege",college );

                conn.Open();
                int result = cmd.ExecuteNonQuery();
                if (result == 1)
                {
                    Response.Write("<script>alert('註冊成功,前往登入頁面進行會員登入!'); location.href='Login.aspx'; </script>");
                    //Response.Redirect("Default.aspx");
                }

            }

        }

    }
}


text:
package com.google.security.zynamics.binnavi.Gui.Debug.BreakpointTable.Actions;

import java.awt.event.ActionEvent;

import javax.swing.AbstractAction;
import javax.swing.Action;

import com.google.common.base.Preconditions;
import com.google.security.zynamics.binnavi.Gui.Debug.BreakpointTable.Implementations.CBreakpointSetFunctions;
import com.google.security.zynamics.binnavi.debug.debugger.BackEndDebuggerProvider;

/**
 * Action class that enables all breakpoints.
 */
public final class CEnableAllAction extends AbstractAction {
  /**
   * Used for serialization.
   */
  private static final long serialVersionUID = -2248603396543802677L;

  /**
   * Provides the debuggers where breakpoints can be set.
   */
  private final BackEndDebuggerProvider m_debuggerProvider;

  /**
   * Creates a new action object.
   *
   * @param debuggerProvider Provides the debuggers where breakpoints can be set.
   */
  public CEnableAllAction(final BackEndDebuggerProvider debuggerProvider) {
    Preconditions.checkNotNull(
        debuggerProvider, "IE01349: Debugger provider argument can not be null");

    m_debuggerProvider = debuggerProvider;

    putValue(Action.SHORT_DESCRIPTION, "Enable all breakpoints");
  }

  @Override
  public void actionPerformed(final ActionEvent event) {
    CBreakpointSetFunctions.enableAll(m_debuggerProvider);
  }
}


text:
namespace SchoolClasses
{
    using System;
    using System.Collections.Generic;

    public class SchoolMain
    {
        public static void Main()
        {
            School school = new School("Test school");
            Console.WriteLine("School name: \"{0}\"\n", school.Name);

            var students = new List<Student>
            {
                new Student("Pesho", 1, "Class leader"),
                new Student("Gosho", 2),
                new Student("Ivo", 3),
                new Student("Doncho", 4)
            };

            Console.WriteLine("\nList of students: \n");

            foreach (var student in students)
            {
                Console.WriteLine(student);
            }

            var disciplines = new List<Discipline>
            {
                new Discipline("Math", 15, 15)
            };

            Discipline physics = new Discipline("Physics", 10, 10);
            disciplines.Add(physics);

            Console.WriteLine("\n\nList of disciplines:\n");

            foreach (var discipline in disciplines)
            {
                Console.WriteLine(discipline);
                Console.WriteLine();
            }

            Teacher peshov = new Teacher("Pesho Peshov", new List<Discipline>() { new Discipline("Physics", 10, 10) });
            Teacher goshev = new Teacher("Gosho Goshev", new List<Discipline>() { new Discipline("Math", 10, 10) });

            List<Teacher> teachers = new List<Teacher>() { peshov, goshev };

            Console.WriteLine("\nList of teachers:\n");

            foreach (Teacher teacher in teachers)
            {
                Console.WriteLine("{0} {1}", teacher.FullName, string.Join("\n", teacher.DisciplinesList));
                Console.WriteLine();
            }

            Class tenA = new Class("10 A",
                new List<Teacher>() { peshov },
                new List<Student>() { new Student("Toshko", 1), new Student("Peshka", 2) });

            Console.WriteLine("\nClass: ");
            Console.WriteLine(tenA);

            tenA.Comment = "Very good results last year!";
            Console.WriteLine("\n\nClass \"{0}\" comment: {1}\n", tenA.ClassID,tenA.Comment);
        }
    }
}


text:
This directory contains the code generator plugin, which is run when you
do `capnp compile -o haskell`. This document provides a high-level
overview of its internals.

Like all capnproto code generator plugins, it accepts a
capnproto-serialized `CodeGenratorRequest` (defined in `schema.capnp`)
on standard input, and emits code accordingly. For an overview on *what*
exactly is emitted, see `Capnp.Tutorial`.

The data read from standard input transitions through several
intermediate forms before finally being written out to disk as Haskell
source code. The `IR/` subdirectory defines the intermediate forms
themselves, while each transition is defined in a module under `Trans/`.
`Main` ties ties the whole thing together.

# The Pipeline

```
CGR ---> Stage1 ---> Flat ---> NEW ---> Haskell (IR) --> Haskell (source code)
```

The flow is as follows:

* First, we read in the data from standard in, and parse it as a
  `CodeGeneratorRequest` (henceforth `CGR`). We use the high-level API
  for this.
* Next, we translate to the IR defined in `IR.Stage1`. This represents
  essentially the same information as the CGR, but:
  * Information we won't use has been discarded.
  * It is more type safe, in that the structure of the IR cannot
    represent certain illegal structures that are representable in the
    CGR.
  * Whereas the CGR contains a list of nodes by id, and entries in the
    CGR reference each other by ID, in the Stage1 IR we have tied the
    knot, and the referenced nodes are available directly as fields of
    their referers.
* Then, we translate to the `Flat` IR. This is still a declarative
  representation of the information in the schema, but it is in a form
  that maps more nicely to Haskell. The goal of this stage is to massage
  the information into a form such that later stages don't have to do any
  work to find out basic facts about the schema.
  For example:
  * We have flattened the namespace, all definitions are at top level;
    Haskell doesn't support nested namespaces, so this solves an
    impedence mismatch. The hierarchical structure is recoverable, as
    the names themselves encode the structure; see `IR.Name`.
  * Unions are now represented more cleanly as sums, rather than being
    mixed in with other fields.
  * Interfaces now contain a full list of their ancestors, not just
    immediate superclasses. This is useful when genrating instance
    declarations later on.
* Next, we translate to the `AbstractOp` IR. This form encodes the
  Haskell structures to be generated, rather than what is declared in
  the schema -- but the it is still abstract in the sense that it
  only specifies what constructs should be generated. Thus, Abstract
  and Operational. Examples:
  * Type declaration for this capnp type
  * An instance for 'Parse' for this type
  * etc
* Then, we translate this form into a Haskell AST, defined in
  `IR.Haskell`. We use our own AST instead of an off-the-shelf
  library for a couple reasons:
  * We want to eventually insert comments from the schema into the
    code as Haddock comments, and the libraries I(zenhack) was able
    to find do not support comments.
  * The full Haskell syntax is quite complicated, and we don't need
    most of it; our AST has just the parts we need, and so is simpler
    to work with.
  * It is useful when generating code to be able treat certain
    constructs as primitive syntax which really aren't. For example:
    * Our AST does not reflect the fact that function application is
      curried;
    * Our expression type treats "functorial" application, e.g.
      `f <$> x <*> y <*> z`, as primitive, which is convienent for
      our purposes.
* Finally, we translate the Haskell AST into text, and write it out
  to disk.

# Misc notes

* There are a couple modules that are shared between more than one phase
  and/or IR:

* `IR.Name` and `IR.Common` are used by multiple of the IRs.
* `Trans.ToHaskellCommon` used to be used by multiple modules. It should
   be folded into `Trans.AbstractOpToHaskell`.

* The names of some of the IRs are not very good.
  * `IR.Stage1` latter is not terribly descriptive.
  * `IR.Flat` reflects an out of date notion of what the flat IR's
    purpose is (it does more than just flatten the namespace).