text:
package thedemitrius.androidif.glk;

import java.io.ByteArrayOutputStream;
import java.io.DataOutputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.ObjectOutputStream;
import java.util.ArrayList;

import thedemitrius.androidif.Init;
import thedemitrius.androidif.util.DataTransforms;

import android.app.Activity;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Canvas;
import android.graphics.Paint;
import android.graphics.Rect;
import android.graphics.RectF;
import android.view.MotionEvent;

class TextBufferWindow extends TextWindow
{
	private InputArea inputArea;

	private ArrayList<Paragraph> paragraphs;
	private ArrayList<Paragraph> storedParagraphs;
	private Paragraph curParagraph;

	private PrintPage printPage;
	private PrintPage storedPrintPage;

	private boolean lineInputPending;

	private Bitmap image;

	private boolean bitbucket;

	private Activity context;
	private String homeDir;
	private String lastSaveFile;

	private ByteArrayOutputStream byteStream;
	private DataOutputStream textStream;

	private int textBoundary;

	private int saveCount;

	private TextBufferWindowGestureListener gestureDispatcher;
	private boolean listen;

	private boolean restoreKeyboard;

	@SuppressWarnings("unused")
	private PageFlipper pageFlipper;

	private Bitmap background;

	private int realStartParagraph;

	private boolean serializeActive;

	private boolean customRedraw;

	private static char arrows[]={0x21e6,0x21e8};

	TextBufferWindow(Activity context,int id,int method, int size, int rock, boolean key, WindowStream stream,String homeDir,
			GLK glk,InputArea inputArea)
	{
		super(context,id, method, size, rock, key, stream);

		this.context=context;
		this.homeDir=homeDir;
		this.inputArea=inputArea;

		paragraphs=new ArrayList<Paragraph>();
		curParagraph=new Paragraph(curStyle);

		printPage=new PrintPage();

		storedParagraphs=null;

		lineInputPending=false;

		image=null;

		background=null;

		bitbucket=false;
		listen=false;

		lastSaveFile="";

		realStartParagraph=-1;

		serializeActive=true;

		customRedraw = false;

		resetTextStream();

		gestureDispatcher=new TextBufferWindowGestureListener(glk,this);
	}

	void putString(String s)
	{
		int pos=0;
		int nextLF;

		while ((nextLF=s.indexOf('\n',pos))!=-1){
			if (!bitbucket){
				curParagraph.text+=s.substring(pos,nextLF);
				paragraphs.add(curParagraph);
				curParagraph=new Paragraph(curStyle);}
			pos=nextLF+1;}

		if (pos<(s.length())){
			if (bitbucket)
				curParagraph.text=s.substring(pos);
			else
				curParagraph.text+=s.substring(pos);}
	}

	void putImage(int img)
	{
		if (curParagraph.text.length()>0)
			paragraphs.add(curParagraph);
		curParagraph=new Paragraph(img+100);
		paragraphs.add(curParagraph);
		curParagraph=new Paragraph(curStyle);
	}

	private boolean textFollows(int num)
	{
		for (int i=num;i<paragraphs.size()-1;i++){
			Paragraph next=paragraphs.get(i);
			if (next.startStyle<100)
				for (int j=0;j<next.text.length();j++)
					if (next.text.charAt(j)=='\t')
						j++;
					else
						return (true);
			else if (next.startStyle<1000)
				return (true);
		}

		return (false);
	}

	void pageForward()
	{
		customRedraw = false;

		if (printPage.lastParaLine&&(printPage.endParaNum>=paragraphs.size()-1||!textFollows(printPage.endParaNum+1))){
			if (!helpUp())
				inputArea.display(true);
			return;}

		if (printPage.lastParaLine){
			printPage.startParaNum=printPage.endParaNum+1;
			printPage.startPos=0;}
		else{
			printPage.startParaNum=printPage.endParaNum;
			printPage.startPos=printPage.endPos;}

		Bitmap newPage=Bitmap.createBitmap(getMeasuredWidth(), getMeasuredHeight(), Bitmap.Config.ARGB_8888);
		makePageFromTop(newPage,false,false,false);
		pageFlipper=new PageFlipper(context,newPage,backStore,this,true);
	}

	void makePageFromTop(Bitmap bitmap,boolean paint,boolean toBottom, boolean forceKeyboard)
	{
		try{

			if (bitmap==null)
				bitmap=backStore;

			if (paragraphs.size()==0  || getHeight() <= 0 || getWidth() <= 0)
				return;

			int startStyle=getLastStyle(paragraphs.get(printPage.startParaNum),printPage.startPos);

			int currentHyperlink=0;

			printPage.clear();

			int maxHeight;
			if (toBottom)
				maxHeight=1000000;
			else
				maxHeight=getHeight()-avgCharHeight*2;
			if (forceKeyboard && inputArea.isVisible())
				maxHeight += inputArea.getHeight();

			int endParaLoc=0;
			Paragraph printParagraph;

			for (int next=printPage.startParaNum;printPage.height<maxHeight&&next<paragraphs.size();next++){
				printParagraph= paragraphs.get(next);
				if (printParagraph.startStyle==1000)
					if (!pageHasText()&&!pageHasPicture())
						continue;
					else{
						break;}
				if (next==printPage.startParaNum){
					if (printParagraph.startStyle>=100)
						startStyle=printParagraph.startStyle;
					currentHyperlink=lineBreak(printParagraph.text.substring(printPage.startPos),startStyle,0,next,0);}
				else
					currentHyperlink=lineBreak(printParagraph.text,printParagraph.startStyle,printPage.size(),next,currentHyperlink);
				if (printParagraph.startStyle<100)
					endParaLoc=printParagraph.text.length();
				else
					endParaLoc=0;}

			maxHeight=getHeight()-avgCharHeight*2;

			if (forceKeyboard && inputArea.isVisible() && printPage.height > maxHeight) {
				inputArea.display(false);
				customRedraw = true;
				return;
			}

			printPage.lastParaLine=true;
			while (printPage.height>maxHeight){
				if (toBottom){
					printPage.removeFirst();
					continue;}
				PrintLine line=printPage.getLast();
				if (line.height>maxHeight&&!pageHasText())
					break;
				if (line.paraStart>0){
					printPage.lastParaLine=false;
					endParaLoc=line.paraStart;}
				else{
					printPage.lastParaLine=true;
					if (line.type>=100&&line.type<1000){
						if (printPage.getFirst().type>=1000){
							printPage.removeFirst();
							printPage.startParaNum=printPage.getFirst().paraNum;
							printPage.startPos=printPage.getFirst().paraStart;
							continue;}}}
				printPage.removeLast();}

			if (toBottom){
				printPage.startParaNum=printPage.getFirst().paraNum;
				printPage.startPos=printPage.getFirst().paraStart;}

			printPage.endParaNum=printPage.getLast().paraNum;
			printPage.endPos=endParaLoc;

			paintBackStore(bitmap);

			if (paint)
				postInvalidate();

		} catch (IndexOutOfBoundsException e){
			catchPageError(bitmap,paint);}
	}

	private int getLastStyle(Paragraph paragraph,int end)
	{
		if (paragraph.startStyle>=100)
			return (STYLE_NORMAL);

		if (paragraph.text==null)
			return paragraph.startStyle;

		String text=paragraph.text.substring(0,Math.min(end,paragraph.text.length()));

		if (text.length()<2)
			return (paragraph.startStyle);

		int lastIndex=text.lastIndexOf('\t');
		if (lastIndex==-1||lastIndex==text.length()-1)
			return (paragraph.startStyle);

		return (text.charAt(lastIndex+1)-16);
	}

	void pageBack()
	{
		customRedraw = false;

		boolean keyboardDown = false;

		if (!gestureDispatcher.getKeyboardLocked()) {
			if (inputArea.isVisible())
				keyboardDown = true;
			inputArea.display(false);}

		if (printPage.startParaNum<=getRealStartParagraph()&&printPage.startPos==0){
			return;}

		if (printPage.startPos==0){
			printPage.endParaNum=printPage.startParaNum-1;
			printPage.endPos=paragraphs.get(Math.min(printPage.endParaNum,paragraphs.size()-1)).text.length();}
		else{
			printPage.endParaNum=printPage.startParaNum;
			printPage.endPos=printPage.startPos;}

		if (keyboardDown) {
			makePageFromBottom(null,true);}
		else {
			Bitmap newPage=Bitmap.createBitmap(getMeasuredWidth(), getMeasuredHeight(), Bitmap.Config.ARGB_8888);
			makePageFromBottom(newPage,true);
			pageFlipper=new PageFlipper(context,newPage,backStore,this,false);}
	}

	private int getRealStartParagraph()
	{
		if (realStartParagraph==-1){
			for (int i=0;i<paragraphs.size();i++){
				Paragraph paragraph=paragraphs.get(i);
				if (paragraph.text.length()>0||(i > 0 && paragraph.startStyle>=100)){
					realStartParagraph=i;
					return (i);}
			}
		}

		return (realStartParagraph);
	}

	void makePageFromBottom(Bitmap bitmap,boolean paint)
	{
		try{

			if (bitmap==null)
				bitmap=backStore;

			if (paragraphs.size()==0 || getHeight() <= 0 || getWidth() <= 0)
				return;

			int currentHyperlink=0;

			printPage.clear();

			int maxHeight=getHeight()-avgCharHeight*2;

			for (int prev=Math.min(printPage.endParaNum,paragraphs.size()-1);prev>=0&&printPage.height<maxHeight;prev--){
				if (prev == 0) {
					printPage.startParaNum = 0;
					printPage.startPos = 0;
					makePageFromTop(bitmap, paint, false,false);
					return;
				}
				Paragraph printParagraph= paragraphs.get(prev);
				if (printParagraph.startStyle==1000){
					if (!pageHasText()&&!pageHasPicture()){
						printPage.lastParaLine=true;
						continue;}
					else
						break;}
				if (prev==printPage.endParaNum){
					currentHyperlink=lineBreak(printParagraph.text.substring(0,Math.min(printPage.endPos,printParagraph.text.length())),printParagraph.startStyle,0,prev,currentHyperlink);
					if (printParagraph.startStyle>=100)
						printPage.lastParaLine=true;
					else
						printPage.lastParaLine=(printPage.endPos>=printParagraph.text.length());}
				else
					currentHyperlink=lineBreak(printParagraph.text,printParagraph.startStyle,0,prev,currentHyperlink);
				}

			while (printPage.height>maxHeight){
				PrintLine line=printPage.getFirst();
				if (line.height>maxHeight&&!pageHasText())
					break;
				printPage.removeFirst();
			}

			printPage.startParaNum=printPage.getFirst().paraNum;
			printPage.startPos=printPage.getFirst().paraStart;

			paintBackStore(bitmap);
			if (paint)
				postInvalidate();

		} catch (IndexOutOfBoundsException e){
			catchPageError(bitmap,paint);}
	}

	private void catchPageError(Bitmap bitmap,boolean paint)
	{
		printPage.endParaNum=paragraphs.size()-1;
		printPage.endPos=0;
		makePageFromBottom(bitmap,paint);
	}

	void reprintPage()
	{
		makePageFromTop(backStore,true,false,false);
	}
	private int lineBreak(String paragraph,int style,int index,int paraNum,int hyperlink)
	{
		if (style>=100){
			PrintLine imageLine=prepareImage(style-100,paraNum);
			printPage.add(index,imageLine);
			return (hyperlink);}

		int lineHeight=stream.getHeight(style);
		int indent=avgCharWidth+(stream.getIndentation(style)*avgCharWidth);
		int totalHeight=0;
		String text="";

		boolean hyperlinkOff=false;

		if (paragraph.trim().length()>0){

			int[] charWidths=stream.getWidths(style);
			int lineWidth=getWidth()-avgCharWidth-indent;
			int pos=indent;
			int start=indent;
			int startChar=0;
			int lineStart=0;
			int lineCount=0;

			int[] styleMap=new int[60];
			int mapIndex=0;

			for (int i=0;i<paragraph.length();i++){

				if (paragraph.charAt(i)=='\t'){
					if (pos>indent){
						styleMap[mapIndex]=style;
						styleMap[mapIndex+1]=text.length();
						text+=paragraph.substring(startChar,i);
						styleMap[mapIndex+2]=text.length();
						mapIndex+=3;
						if ((i+2)==paragraph.length()){
							printPage.add(index,new PrintLine(text,lineHeight,indent,lineStart,paraNum,lineCount,hyperlink,
									styleMap,mapIndex,stream));
							if (hyperlinkOff){
								hyperlink=0;
								hyperlinkOff=false;}
							totalHeight+=lineHeight;}
					}
					else{
						lineHeight=0;}
					i++;
					if (paragraph.charAt(i)<100){
						style=paragraph.charAt(i)-16;
						charWidths=stream.getWidths(style);}
					else{
						if ((paragraph.charAt(i)>100)){
							hyperlinkOff=false;
							hyperlink=paragraph.charAt(i)-100;}
						else{
							hyperlinkOff=true;}
					}
					lineHeight=Math.max(lineHeight, stream.getHeight(style));
					startChar=i+1;
					continue;}

				if (paragraph.charAt(i)>255)
					pos+=stream.getWidth(paragraph.charAt(i), style);
				else
					pos+=charWidths[paragraph.charAt(i)];

				if (pos>lineWidth){
					if (paragraph.substring(lineStart, i).indexOf(' ')!=-1){
						do{
							i--;}
						while (paragraph.charAt(i)!=' ');}
					if (i<startChar){
//						i=startChar-2;
						startChar = i;
						mapIndex = Math.max(0, mapIndex - 3);}
					else{
						styleMap[mapIndex]=style;
						styleMap[mapIndex+1]=text.length();
						text+=paragraph.substring(startChar,i);
						styleMap[mapIndex+2]=text.length();
						mapIndex+=3;
						i++;
						startChar=i;}
					if (stream.getJustification(style)==STYLEHINT_JUST_CENTERED)
						start=(int) (((getWidth()-stream.getFont(style).measureText(text)))/2);
					printPage.add(index,new PrintLine(text,lineHeight,start,lineStart,paraNum,lineCount,hyperlink,
						styleMap,mapIndex,stream));
					lineStart=i;
					if (hyperlinkOff){
						hyperlink=0;
						hyperlinkOff=false;}
					text="";
					mapIndex=0;
					index++;
					lineCount++;
					totalHeight+=lineHeight;
					pos=indent;
					start=indent;}
			}

			if (startChar<paragraph.length()){
				styleMap[mapIndex]=style;
				styleMap[mapIndex+1]=text.length();
				text+=paragraph.substring(startChar);
				styleMap[mapIndex+2]=text.length();
				mapIndex+=3;
				if (stream.getJustification(style)==STYLEHINT_JUST_CENTERED)
					start=(int) (((getWidth()-stream.getFont(style).measureText(text)))/2);
				printPage.add(index,new PrintLine(text,lineHeight,start,lineStart,paraNum,lineCount,hyperlink,
						styleMap,mapIndex,stream));
				if (hyperlinkOff){
					hyperlink=0;
					hyperlinkOff=false;}
				index++;
				lineCount++;
				totalHeight+=lineHeight;}
		}

		if (totalHeight==0){
			printPage.add(index,new PrintLine(lineHeight,indent,1000,paraNum,0,hyperlink));
			if (hyperlinkOff){
				hyperlink=0;
				hyperlinkOff=false;}
			index++;
			totalHeight=lineHeight;}

		return (hyperlink);
	}

	boolean pageHasText()
	{
		for (int i=0;i<printPage.size();i++)
			if (printPage.get(i).type==0)
				return (true);

		return (false);
	}

	boolean pageHasPicture()
	{
		for (int i=0;i<printPage.size();i++){
			PrintLine next=printPage.get(i);
			if (next.type>=100&&next.type<1000)
				return (true);}

		return (false);
	}

	PrintLine prepareImage(int num,int paraNum)
	{
		image=BitmapFactory.decodeStream(getClass().getResourceAsStream(Init.storyURL+num+".pic"));
		if (image==null)
			return (null);

		int width=image.getWidth();
		int height=image.getHeight();
		if (width>getWidth()){
			float scale=(float)getWidth()/(float)width;
			width*=scale;
			height*=scale;}
		if (height>getHeight()){
			float scale=(float)getHeight()/(float)height;
			width*=scale;
			height*=scale;}
		image=Bitmap.createScaledBitmap(image, width, height, false);

		int indent=(getWidth()-image.getWidth())/2;
		if (indent<0)
			indent=0;

		if (paraNum>=0)
			return (new PrintLine(height,indent,num,paraNum,0,0));
		else
			return (null);
	}

	public void paintBackStore(Bitmap bitmap)
	{
		if (bitmap==null){
			checkBackStore();
			bitmap=backStore;}
		Canvas g=new Canvas(bitmap);

		if (background!=null)
			g.drawBitmap(background, null, new Rect(0,0,bitmap.getWidth(),bitmap.getHeight()),new Paint());
		else
			g.drawColor(stream.getBackColor(STYLE_NORMAL));

		gestureDispatcher.clearHyperlinks();

		if (printPage.size()>0){

			int curLine=0;
			PrintLine nextLine=null;
			boolean fullScreen=false;

			for (int i=0;i<printPage.size();i++){

				nextLine=printPage.get(i);

				if (nextLine.type>=100){
					if (nextLine.type<1000){
						if (image==null)
							prepareImage(nextLine.type-100,-1);
						if (nextLine.height>(getHeight()-avgCharHeight*2)){
							float scale=(float)getHeight()/(float)nextLine.height;
							float x=(getWidth()/2)-((image.getWidth()*scale)/2);
							g.drawBitmap(image,null,new RectF(x,0,x+(image.getWidth()*scale),(float)nextLine.height*scale),new Paint());
							fullScreen=true;}
						else
							g.drawBitmap(image,nextLine.startPos,curLine,new Paint());}
					curLine+=nextLine.height;}
				else{
					curLine+=nextLine.height;
					int pos=nextLine.startPos;
					for (int j=0;j<nextLine.styleLimit;j+=3){
						Paint font=stream.getFont(nextLine.styleMap[j]);
						g.drawText(nextLine.text, nextLine.styleMap[j+1], nextLine.styleMap[j+2], pos, curLine, font);
						pos+=font.measureText(nextLine.text,nextLine.styleMap[j+1],nextLine.styleMap[j+2]);}
				}
				if (gestureDispatcher.getHyperlinksActive()&&nextLine.hyperlink>0)
					gestureDispatcher.addHyperlink(nextLine.hyperlink, new Rect(0,curLine-nextLine.height,getWidth(),curLine));}

			textBoundary=curLine;

			if (!fullScreen){

				Paint font=stream.getFont(STYLE_HEADER);

				if (printPage.startParaNum>getRealStartParagraph()||printPage.startPos>0)
					g.drawText(arrows, 0, 1, avgCharWidth*4, getHeight()-5, font);

				if ((!inputArea.isVisible()&&!helpUp())||!(printPage.lastParaLine&&(printPage.endParaNum>=paragraphs.size()-1||!textFollows(printPage.endParaNum+1))))
					g.drawText(arrows, 1, 1, getWidth()-(avgCharWidth*6), getHeight()-5, font);}
		}

		paintNeeded=true;

			if (serializeActive)
				try {
					serialize();
				} catch (IOException e) {
				}
	}

	class Paragraph
	{
		int startStyle;
		String text;

		Paragraph(int startStyle)
		{
			this.startStyle=startStyle;
			text="";
		}
	}

	void clear(boolean helpActive)
	{
		resetTextStream();
		paragraphs.clear();

		printPage.fullClear();
	}

	void setStyle(int style)
	{
		curStyle=style;
		curParagraph.text+='\t';
		curParagraph.text+=(char)(style+16);
	}

	String getCommandPrompt()
	{
		return (curParagraph.text);
	}

	void updateStartParaNum()
	{
		gestureDispatcher.setKeyboardLocked(false);

		printPage.turnParaNum=printPage.startParaNum;
		printPage.turnPos=printPage.startPos;

		printPage.startPos=0;

		if (paragraphs.size()>0){
			printPage.startParaNum=paragraphs.size()-1;}
		else{
			printPage.startParaNum=0;}
	}

	void getSize(byte[] array,int widthPtr,int heightPtr)
	{
		if (widthPtr>=0)
			DataTransforms.putInt(array, widthPtr, ((getWidth()/avgCharWidth)-2));

		if (heightPtr>=0)
			DataTransforms.putInt(array, heightPtr, ((getHeight()/avgCharHeight)-2));
	}

	void setLineInputPending(boolean lineInputPending)
	{
		this.lineInputPending=lineInputPending;
	}

	void storeTextBuffer() throws IOException, InterruptedException
	{
		if (!helpUp()){
			storedParagraphs=paragraphs;
			paragraphs=new ArrayList<Paragraph>();
			storedPrintPage=printPage;
			printPage=new PrintPage();

			realStartParagraph=-1;

			restoreKeyboard=inputArea.isVisible();
			if (restoreKeyboard)
				post(new Runnable(){
					public void run(){
						inputArea.display(false);}});

			clear(true);}
	}

	void restoreTextBuffer() throws InterruptedException
	{
		if (helpUp()){

			paragraphs=storedParagraphs;
			storedParagraphs=null;
			printPage=storedPrintPage;
			storedPrintPage=null;
			printPage.startParaNum=printPage.turnParaNum;
			printPage.startPos=printPage.turnPos;

			realStartParagraph=-1;
        }
	}

	void saveTextBuffer(FileStream file) throws IOException
	{
		file.writeInt(printPage.startParaNum);
		file.writeInt(printPage.startPos);
		file.writeInt(printPage.endParaNum);
		file.writeInt(printPage.endPos);
		file.writeInt(printPage.height);
		file.writeBoolean(printPage.lastParaLine);

		int limit=paragraphs.size();
		file.writeInt(limit);

		for (;saveCount<limit;saveCount++){
			Paragraph next= paragraphs.get(saveCount);
			textStream.writeInt(next.startStyle);
			textStream.writeUTF(next.text);}

		file.putBuffer(byteStream.toByteArray(), 0, byteStream.size());
	}

	void loadTextBuffer(FileStream file) throws IOException
	{
		printPage.clear();
		paragraphs.clear();
		resetTextStream();

		printPage.startParaNum=file.readInt();
		printPage.startPos=file.readInt();
		printPage.endParaNum=file.readInt();
		printPage.endPos=file.readInt();
		printPage.height=file.readInt();
		printPage.lastParaLine=file.readBoolean();

		int limit=file.readInt();
		for (int i=0;i<limit;i++){
			Paragraph next=new Paragraph(file.readInt());
			next.text=file.readString();
			paragraphs.add(next);}
	}

	void formFeed()
	{
		if (curParagraph.text.length()>0){
			paragraphs.add(curParagraph);}
		else{
			while (paragraphs.size()>0){
				curParagraph= paragraphs.get(paragraphs.size()-1);
				if (curParagraph.text.length()>0){
					break;}
				else{
					resetTextStream();
					paragraphs.remove(paragraphs.size()-1);}
			}
		}

		curParagraph=new Paragraph(1000);
		paragraphs.add(curParagraph);
		curParagraph=new Paragraph(curStyle);
	}

	void setBitbucket(boolean bitbucket)
	{
		if (lineInputPending)
			this.bitbucket=bitbucket;
	}

	int getParagraphCount()
	{
		return (paragraphs.size());
	}

	void trimParagraphs(int size)
	{
		if (size<=0)
			return;

		if (paragraphs.size()>size)
			resetTextStream();

		while (paragraphs.size()>size)
			paragraphs.remove(paragraphs.size()-1);

		printPage.startParaNum=paragraphs.size()-1;
	}

	void jumpTo(int paraNum)
	{
		printPage.startParaNum=paraNum;
		printPage.startPos=0;
		makePageFromTop(backStore,true,false,false);
	}

	void setStartParaNum(int startParaNum)
	{
		printPage.startParaNum=startParaNum;
	}

	private void serialize() throws IOException
	{
		if (storedPrintPage==null&&lastSaveFile.length()>0){
			FileRef file=FileRef.createFileRef(context,homeDir,"state",0);
			if (file.exists())
				file.delete();
			ObjectOutputStream out=new ObjectOutputStream(new FileOutputStream(file));
			out.writeUTF(lastSaveFile);
			out.writeObject(printPage);
			out.close();}
	}

	void setLastSaveFile(String lastSaveFile)
	{
		this.lastSaveFile=lastSaveFile;
	}

	private void resetTextStream()
	{
		byteStream=new ByteArrayOutputStream();
		textStream=new DataOutputStream(byteStream);
		saveCount=0;
	}

	void setPage(PrintPage page,boolean revertToTurnParaNum)
	{
		printPage=page;

		if (revertToTurnParaNum){
			printPage.startParaNum=printPage.turnParaNum;
			printPage.startPos=printPage.turnPos;}

		post(new Runnable(){
			public void run(){
				makePageFromTop(null,true,false,false);
				invalidate();}});
	}

	int getTextBoundary()
	{
		return (textBoundary);
	}

	public Object getValue(String key) {
		return null;
	}

	public void putValue(String key, Object value) {}

	boolean helpUp()
	{
		return (storedParagraphs!=null);
	}

	void toggleHyperlinks(boolean active)
	{
		gestureDispatcher.toggleHyperlinks(active);
	}

	void setHyperlink(int linkVal)
	{
		if (gestureDispatcher.getHyperlinksActive()&&linkVal>=0){
			curParagraph.text+='\t';
			curParagraph.text+=(char)(linkVal+100);}
	}

	void setBackground(int num)
	{
		if (num==0)
			background=null;
		else
			background=BitmapFactory.decodeStream(getClass().getResourceAsStream(Init.storyURL+num+".pic"));
	}

	public boolean onTouchEvent(MotionEvent e)
	{
		if (!listen)
			return (true);

		return (gestureDispatcher.handleTouchEvent(e));
	}

	void gestureListen(boolean listen)
	{
		this.listen=listen;
	}

	public void onSizeChanged(int w,int h, int oldw, int oldh)
	{
		checkBackStore();

		if (customRedraw) {
			makePageFromTop(null, false, false, false);
			return;
		}

		if (helpUp())
			paintBackStore(backStore);
		else
			makePageFromBottom(backStore,false);
	}

	public void finalize()
	{
		gestureDispatcher.finalize();
	}

	void setSerializeActive(boolean serializeActive)
	{
		this.serializeActive=serializeActive;
	}

	void setCustomRedraw(boolean newRedraw) {
		customRedraw = newRedraw;
	}
}


text:
import re
import tempfile
from collections import OrderedDict

from django.db.models import Q

from memoized import memoized

from couchexport.models import Format
from couchexport.writers import Excel2007ExportWriter
from dimagi.utils.couch.loosechange import map_reduce
from soil import DownloadBase
from soil.util import expose_blob_download

from corehq.apps.consumption.shortcuts import (
    build_consumption_dict,
    get_loaded_default_monthly_consumption,
)
from corehq.apps.domain.models import Domain
from corehq.apps.locations.const import (
    LOCATION_SHEET_HEADERS_BASE,
    LOCATION_SHEET_HEADERS_OPTIONAL,
    LOCATION_TYPE_SHEET_HEADERS,
)
from corehq.apps.locations.models import LocationType, SQLLocation
from corehq.apps.products.models import Product
from corehq.blobs import CODES, get_blob_db
from corehq.form_processor.interfaces.supply import SupplyInterface
from corehq.util.files import safe_filename_header

def load_locs_json(domain, selected_loc_id=None, include_archived=False,
        user=None, only_administrative=False):
    """initialize a json location tree for drill-down controls on
    the client. tree is only partially initialized and branches
    will be filled in on the client via ajax.

    what is initialized:
    * all top level locs
    * if a 'selected' loc is provided, that loc and its complete
      ancestry

    only_administrative - if False get all locations
                          if True get only administrative locations
    """
    def loc_to_json(loc):
        return {
            'name': loc.name,
            'location_type': loc.location_type.name,  # todo: remove when types aren't optional
            'uuid': loc.location_id,
            'is_archived': loc.is_archived,
            'can_edit': True
        }

    locations = SQLLocation.root_locations(
        domain, include_archive_ancestors=include_archived
    )

    if only_administrative:
        locations = locations.filter(location_type__administrative=True)

    loc_json = [loc_to_json(loc) for loc in locations]

    # if a location is selected, we need to pre-populate its location hierarchy
    # so that the data is available client-side to pre-populate the drop-downs
    if selected_loc_id:
        selected = SQLLocation.objects.get(
            domain=domain,
            location_id=selected_loc_id
        )

        lineage = selected.get_ancestors()

        parent = {'children': loc_json}
        for loc in lineage:
            children = loc.child_locations(include_archive_ancestors=include_archived)
            if only_administrative:
                children = children.filter(location_type__administrative=True)

            # find existing entry in the json tree that corresponds to this loc
            try:
                this_loc = [k for k in parent['children'] if k['uuid'] == loc.location_id][0]
            except IndexError:
                # if we couldn't find this location the view just break out of the loop.
                # there are some instances in viewing archived locations where we don't actually
                # support drilling all the way down.
                break
            this_loc['children'] = [loc_to_json(loc) for loc in children]
            parent = this_loc

    return loc_json

def location_hierarchy_config(domain):
    return [(loc_type.name, [loc_type.parent_type.name
                             if loc_type.parent_type else None])
            for loc_type in Domain.get_by_name(domain).location_types]

def parent_child(domain):
    """
    Returns a dict mapping from a location type to its possible
    child types
    """
    return map_reduce(lambda k_v: [(p, k_v[0]) for p in k_v[1]],
                      data=dict(location_hierarchy_config(domain)).items())

def get_location_data_model(domain):
    from .views import LocationFieldsView
    from corehq.apps.custom_data_fields.models import CustomDataFieldsDefinition
    return CustomDataFieldsDefinition.get_or_create(
        domain,
        LocationFieldsView.field_type,
    )

class LocationExporter(object):

    def __init__(self, domain, include_consumption=False, root_location_ids=None,
                 headers_only=False, async_task=None, **kwargs):
        self.domain = domain
        self.domain_obj = Domain.get_by_name(domain)
        self.include_consumption_flag = include_consumption
        self.data_model = get_location_data_model(domain)
        self.administrative_types = {}
        self.location_types = LocationType.objects.by_domain(domain)
        self.async_task = async_task
        self._location_count = None
        self._locations_exported = 0

        additional_filters = self._extract_additional_filters(**kwargs)
        selected_location_only = kwargs.get('selected_location_only', False)

        if headers_only:
            self.base_query = SQLLocation.objects.none()
        elif root_location_ids:
            if selected_location_only:
                # Use filter so base_query is a LocationQuerySet
                self.base_query = SQLLocation.objects.filter(location_id__in=root_location_ids)
            else:
                root_location_ids = SQLLocation.objects.filter(location_id__in=root_location_ids).values('id')
                self.base_query = SQLLocation.objects.get_descendants(
                    Q(domain=self.domain, id__in=[root_location_ids])
                ).filter(**additional_filters)
        else:
            self.base_query = SQLLocation.objects.filter(
                domain=self.domain,
                **additional_filters,
            )

    def _extract_additional_filters(self, **kwargs):
        additional_filters = {}
        if 'is_archived' in kwargs:
            additional_filters['is_archived'] = kwargs.get('is_archived')
        return additional_filters

    @property
    @memoized
    def consumption_dict(self):
        return build_consumption_dict(self.domain)

    def _increment_progress(self):
        if self._location_count is None:
            self._location_count = self.base_query.count()
            self._progress_update_chunksize = max(10, self._location_count // 100)
        self._locations_exported += 1
        if self._locations_exported % self._progress_update_chunksize == 0:
            DownloadBase.set_progress(self.async_task, self._locations_exported, self._location_count)

    @property
    @memoized
    def include_consumption(self):
        if bool(
            self.include_consumption_flag and
            self.domain_obj.commtrack_settings.individual_consumption_defaults
        ):
            # we'll be needing these, so init 'em:
            self.products = Product.by_domain(self.domain)
            self.product_codes = [p.code for p in self.products]
            self.supply_point_map = SupplyInterface(self.domain).get_supply_point_ids_by_location()
            self.administrative_types = {
                lt.name for lt in self.location_types
                if lt.administrative

            }
            return True
        return False

    def get_consumption(self, loc):
        if (
            not self.include_consumption or
            loc.location_type_name in self.administrative_types or
            not self.consumption_dict
        ):
            return {}
        if loc.location_id in self.supply_point_map:
            sp_id = self.supply_point_map[loc.location_id]
        else:
            # this only happens if the supply point case did
            # not already exist
            sp_id = SupplyInterface(self.domain).get_or_create_by_location(loc).location_id
        return {
            p.code: get_loaded_default_monthly_consumption(
                self.consumption_dict,
                self.domain,
                p._id,
                loc.location_type_name,
                sp_id
            ) or ''
            for p in self.products
        }

    def get_headers(self):
        headers = OrderedDict([
            ('types', [list(LOCATION_TYPE_SHEET_HEADERS.values())])
        ])
        for loc_type in self.location_types:
            additional_headers = []
            additional_headers.extend('data: {}'.format(f.slug) for f in self.data_model.get_fields())
            if self.include_consumption_flag and loc_type.name not in self.administrative_types:
                additional_headers.extend('consumption: {}'.format(code) for code in self.product_codes)
            additional_headers.append(LOCATION_SHEET_HEADERS_OPTIONAL['uncategorized_data'])
            additional_headers.append(LOCATION_SHEET_HEADERS_OPTIONAL['delete_uncategorized_data'])

            headers[loc_type.code] = [list(LOCATION_SHEET_HEADERS_BASE.values()) + additional_headers]

        return list(headers.items())

    def write_data(self, writer):
        self._write_type_sheet(writer)
        for location_type in self.location_types:
            self._write_locations(writer, location_type)

    def _write_locations(self, writer, location_type):
        include_consumption = self.include_consumption_flag and location_type.name not in self.administrative_types

        def _row_generator(include_consumption=include_consumption):
            query = self.base_query.filter(location_type=location_type)
            for loc in query:
                model_data, uncategorized_data = self.data_model.get_model_and_uncategorized(loc.metadata)
                row_data = {
                    'location_id': loc.location_id,
                    'site_code': loc.site_code,
                    'name': loc.name,
                    'parent_code': loc.parent.site_code if loc.parent else '',
                    'external_id': loc.external_id,
                    'latitude': loc.latitude or '',
                    'longitude': loc.longitude or '',
                    'do_delete': '',
                }
                row = [row_data[attr] for attr in LOCATION_SHEET_HEADERS_BASE.keys()]
                for field in self.data_model.get_fields():
                    row.append(model_data.get(field.slug, ''))

                if include_consumption:
                    consumption_data = self.get_consumption(loc)
                    row.extend([consumption_data[code] for code in self.product_codes])

                row.append(', '.join('{}: {}'.format(*d) for d in uncategorized_data.items()))

                yield row
                self._increment_progress()

        writer.write([(location_type.code, _row_generator())])

    def _write_type_sheet(self, writer):
        def foreign_code(lt, attr):
            val = getattr(lt, attr, None)
            if val:
                return val.code
            else:
                return None

        def coax_boolean(value):
            if isinstance(value, bool):
                value = 'yes' if value else 'no'
            return value

        rows = []
        for lt in self.location_types:
            rows.append([
                lt.code,
                lt.name,
                foreign_code(lt, 'parent_type'),
                '',  # do_delete
                coax_boolean(lt.shares_cases),
                coax_boolean(lt.view_descendants),
            ])

        writer.write([('types', rows)])

def dump_locations(domain, download_id, include_consumption, headers_only,
                   owner_id, root_location_ids=None, task=None, **kwargs):
    exporter = LocationExporter(domain, include_consumption=include_consumption, root_location_ids=root_location_ids,
                                headers_only=headers_only, async_task=task, **kwargs)

    fd, path = tempfile.mkstemp()
    writer = Excel2007ExportWriter()
    writer.open(header_table=exporter.get_headers(), file=path)
    with writer:
        exporter.write_data(writer)

    with open(path, 'rb') as file_:
        db = get_blob_db()
        expiry_mins = 60
        db.put(
            file_,
            domain=domain,
            parent_id=domain,
            type_code=CODES.tempfile,
            key=download_id,
            timeout=expiry_mins,
        )

        file_format = Format.from_format(Excel2007ExportWriter.format)
        filename = '{}_locations'.format(domain)
        if len(root_location_ids) == 1:
            root_location = SQLLocation.objects.get(location_id=root_location_ids[0])
            filename += '_{}'.format(root_location.name)
        expose_blob_download(
            download_id,
            expiry=expiry_mins * 60,
            mimetype=file_format.mimetype,
            content_disposition=safe_filename_header(filename, file_format.extension),
            download_id=download_id,
            owner_ids=[owner_id],
        )

def get_locations_from_ids(location_ids, domain, base_queryset=None):
    """
    Returns the SQLLocations with the given location_ids, ensuring
    that they belong to the given domain. Raises SQLLocation.DoesNotExist
    if any of the locations do not match the given domain or are not
    found.
    """
    if not base_queryset:
        base_queryset = SQLLocation.objects

    location_ids = list(set(location_ids))
    expected_count = len(location_ids)

    locations = base_queryset.filter(
        domain=domain,
        is_archived=False,
        location_id__in=location_ids,
    )
    if len(locations) != expected_count:
        raise SQLLocation.DoesNotExist('One or more of the locations was not found.')
    return locations

def valid_location_site_code(site_code):
    slug_regex = re.compile(r'^[-_\w\d]+$')
    return slug_regex.match(site_code)

redpajama_set_name: RedPajamaGithub


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

-->
<pageDefinition xmlns="http://xmlns.oracle.com/adfm/uimodel" version="12.1.3.2.1" id="IncidentAttViewPageDef"
                Package="Incident">
  <parameters/>
  <executables>
    <invokeAction Binds="getAttachmentData" id="invoke_getAttachmentData" Refresh="always"/>
    <variableIterator id="variables">
      <variable Type="java.lang.String" Name="getAttachmentData_Return" IsQueriable="false" IsUpdateable="0"
                DefaultValue="${bindings.getAttachmentData.result}" />
    </variableIterator>
  </executables>
  <bindings>
    <methodAction id="getAttachmentData" Action="invokeMethod" MethodName="getAttachmentData"
                  IsViewObjectMethod="false" DataControl="IncidentAttachmentsController"
                  InstanceName="data.IncidentAttachmentsController.dataProvider"
                  ReturnName="data.IncidentAttachmentsController.methodResults.getAttachmentData_IncidentAttachmentsController_dataProvider_getAttachmentData_result"
                  CacheReturnDefinition="false">
      <NamedData NDName="incidentId" NDValue="#{pageFlowScope.incidentId}" NDType="java.lang.String"/>
      <NamedData NDName="attachmentId" NDValue="#{pageFlowScope.attachmentId}" NDType="java.lang.String"/>
    </methodAction>
    <attributeValues IterBinding="variables" id="Return">
      <AttrNames>
        <Item Value="getAttachmentData_Return"/>
      </AttrNames>
    </attributeValues>
  </bindings>
</pageDefinition>


text:
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE hibernate-configuration PUBLIC
        "-//Hibernate/Hibernate Configuration DTD 3.0//EN"
        "http://hibernate.sourceforge.net/hibernate-configuration-3.0.dtd">

<hibernate-configuration>

    <session-factory>

        <!-- Database connection settings -->
        <property name="connection.driver_class">com.mysql.jdbc.Driver</property>
        <property name="connection.url">jdbc:mysql://localhost:3306/navdb</property>
        <property name="connection.username">root</property>
        <property name="connection.password">mysql</property>

        <!-- JDBC connection pool (use the built-in) -->
        <property name="connection.pool_size">2</property>

        <!-- SQL dialect -->
        <property name="dialect">org.hibernate.dialect.MySQLDialect</property>

        <!-- Enable Hibernate's current session context -->
        <property name="current_session_context_class">thread</property>

        <!-- Echo all executed SQL to stdout -->
        <property name="show_sql">true</property>

        <!-- Drop and re-create the database schema on startup -->
        <property name="hbm2ddl.auto">create</property>

	<mapping resource="Emp.hbm.xml"/>
     <!-- for inheritance   -->
     <mapping resource="InheStrategy3.xml"/>
    </session-factory>

</hibernate-configuration>


text:
package knezzz.hr.ultrarapidspectate.map;

import android.graphics.Bitmap;
import android.graphics.BitmapFactory;

import knezzz.hr.ultrarapidspectate.R;

/**
 * Created by knezzz on 15/04/15 in knezzz.hr.ultrarapidspectate.map.
 */
public class Dragon {
    private final static int DRAGON_SIZE = 80;
    private final static int x = 9866;
    private final static int y = 4414;
    private final static int spawnTime = 150000; // 2:30
    private final static int respawnTime = 360000; // 6:00
    private long killTimestamp;
    private Bitmap dragonBitmap;
    private boolean dead;

    public Dragon(MapView c){
        dead = false;
        dragonBitmap = BitmapFactory.decodeResource(c.getResources(), R.drawable.dragon);
        dragonBitmap = Bitmap.createScaledBitmap(dragonBitmap, DRAGON_SIZE, DRAGON_SIZE, false);
    }

    public void kill(long timeStamp){
        dead = true;
        killTimestamp = timeStamp;
    }

    public boolean isDead(){
        return dead;
    }

    public void respawn(){
        dead = false;
    }

    public int getX(){
        return x;
    }

    public int getY(){
        return y;
    }

    public long getRespawnTime(){
        return (killTimestamp+respawnTime)/10;
    }

    public long getSpawnTime(){
        return spawnTime/10;
    }

    public Bitmap getIcon(){
        return dragonBitmap;
    }

    public int getDragonSize(){
        return DRAGON_SIZE;
    }
}


text:
Twitter Bootstrap <small>(SASS only)</small>
=================

This is a Bower's component with [Bootstrap](http://getbootstrap.com/) containing SASS and font libraries only.
Thought to fit well with [Angular-UI Bootstrap](https://github.com/angular-ui/bootstrap-bower).

Current version is v3.3.7

# Installation

`bower install bootstrap-only-sass`


text:
void readStr(string, int);

#endif


text:
sf::Texture playerTex;

Player::Player() :
	mHealth(100), mMaxHealth(100), mCurWeapon(nullptr)
{
	playerTex.loadFromFile("Resources/Player.png");

	mPosition = sf::Vector2f(100, 250);

	mWeapons.push_back(new Weapons::Machinegun);
	mWeapons.push_back(new Weapons::HeavyMachinegun);

	for (auto& w : mWeapons)
	{
		w->setOwner(this);
		w->init();
	}

	mCurWeapon = mWeapons.front();
}

Player::~Player()
{
	for (auto& w : mWeapons)
		delete w;
}

void Player::handleEvent(sf::Event& ev)
{
	if (ev.type == sf::Event::KeyPressed)
	{
		if (ev.key.code == sf::Keyboard::Tab)
		{
			bool found = false;
			auto lastWeap = mCurWeapon;
			mCurWeapon = nullptr;
			for (auto& w : mWeapons)
			{
				if (w == lastWeap)
					found = true;
				else if (found)
				{
					mCurWeapon = w;
					break;
				}
			}

			if (!mCurWeapon)
				mCurWeapon = mWeapons.front();

			std::cout << "[WP] " << mCurWeapon->getName() << std::endl;

			lastWeap->setFiring(false);
			mCurWeapon->setFiring(true);
		}
		else if (ev.key.code >= sf::Keyboard::Num1 && ev.key.code <= sf::Keyboard::Num9)
		{
			int level = ev.key.code - sf::Keyboard::Num0;
			mCurWeapon->setLevel(level);
		}
	}
}
void Player::fixed_update(float dt)
{
	mCurWeapon->setFirePos(mPosition - sf::Vector2f(0, 100));

	for(auto& w : mWeapons)
		w->fixed_update(dt);
}
void Player::variadic_update(float dt)
{

}
void Player::draw(sf::RenderTarget& target)
{
	sf::Sprite player(playerTex);
	player.setOrigin((sf::Vector2f)playerTex.getSize() / 2.f);
	player.setPosition(mPosition);

	target.draw(player);
}
void Player::drawUI(sf::RenderTarget& target)
{

}

const sf::Vector2f& Player::getPosition() const
{
	return mPosition;
}


text:
上传证件 - 建议在Wi-Fi环境下上传

                <input type="hidden" id="passportA-input" name="inputPassportA" value="">

                <input type="hidden" id="passportB-input" name="inputPassportB" value="">

                <input type="hidden" id="passportC-input" name="inputPassportC" value="">


text:
module Fog
  module Compute
    class Google
      class Mock
        def update_url_map(url_map, host_rules)
          Fog::Mock.not_implemented
        end
      end

      class Real
        def update_url_map(url_map, host_rules, path_matchers = nil)
          api_method = @compute.url_maps.update
          parameters = {
            'project' => @project,
            'urlMap' => url_map.name
          }

          # add new properties to the url_map resource
          if  url_map.hostRules then
            url_map.hostRules.concat(host_rules)
          else
            url_map.hostRules = host_rules
          end

          # a path matcher can only be created with a host rule that uses it
          if path_matchers then
            if url_map.pathMatchers then
              url_map.pathMatchers.concat(path_matchers)
            else
              url_map.pathMatchers = path_matchers
            end
          end

          request(api_method, parameters, body_object=url_map)
        end
      end
    end
  end
end


text:
class Plc::EnrollmentUnitAssignmentsController < ApplicationController
  load_and_authorize_resource

  # GET /plc/enrollment_unit_assignments
  # GET /plc/enrollment_unit_assignments.json
  def index
  end

  # GET /plc/enrollment_unit_assignments/1
  # GET /plc/enrollment_unit_assignments/1.json
  def show
  end

  # GET /plc/enrollment_unit_assignments/new
  def new
  end

  # POST /plc/enrollment_unit_assignments
  # POST /plc/enrollment_unit_assignments.json
  def create
    @enrollment_unit_assignment = Plc::EnrollmentUnitAssignment.new(plc_enrollment_unit_assignment_params)

    if @enrollment_unit_assignment.save
      redirect_to @enrollment_unit_assignment, notice: 'Course unit was successfully created'
    else
      redirect_to action: :new
    end
  end

  # DELETE /plc/enrollment_unit_assignments/1
  # DELETE /plc/enrollment_unit_assignments/1.json
  def destroy
    @plc_enrollment_unit_assignment.destroy

    redirect_to plc_enrollment_unit_assignments_url
  end

  private
  # Never trust parameters from the scary internet, only allow the white list through.
  def plc_enrollment_unit_assignment_params
    params.require(:plc_enrollment_unit_assignment).permit(:plc_user_course_enrollment_id, :plc_course_unit_id, :status)
  end
end


text:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:gravity="center_horizontal"
    android:orientation="vertical">

    <Button
        android:id="@+id/open"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:onClick="onClick"
        android:text="开启悬浮球" />

    <Button
        android:id="@+id/close"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:onClick="onClick"
        android:text="关闭悬浮球" />

    <Button
        android:id="@+id/startAnim"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:onClick="onClick"
        android:text="startAnim" />

    <Button
        android:id="@+id/stopAnim"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:onClick="onClick"
        android:text="stopAnim" />

    <ImageView
        android:id="@+id/wifi"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_marginTop="20dp"
        android:background="@mipmap/ic_launcher"
        android:contentDescription="@string/app_name"
        android:minHeight="100dp"
        android:minWidth="100dp"
        android:scaleType="centerInside" />
</LinearLayout>


text:
using Chloe.Core.Visitors;
using Chloe.DbExpressions;
using Chloe.Utility;
using System.Linq.Expressions;

namespace Chloe.Query.Visitors
{
    class GroupKeySelectorParser : ExpressionVisitor<DbExpression[]>
    {
        ScopeParameterDictionary _scopeParameters;
        StringSet _scopeTables;
        public GroupKeySelectorParser(ScopeParameterDictionary scopeParameters, StringSet scopeTables)
        {
            this._scopeParameters = scopeParameters;
            this._scopeTables = scopeTables;
        }

        public static DbExpression[] Parse(Expression keySelector, ScopeParameterDictionary scopeParameters, StringSet scopeTables)
        {
            return new GroupKeySelectorParser(scopeParameters, scopeTables).Visit(keySelector);
        }

        public override DbExpression[] Visit(Expression exp)
        {
            switch (exp.NodeType)
            {
                case ExpressionType.Lambda:
                    return this.VisitLambda((LambdaExpression)exp);
                case ExpressionType.New:
                    return this.VisitNew((NewExpression)exp);
                default:
                    {
                        var dbExp = GeneralExpressionParser.Parse(exp, this._scopeParameters, this._scopeTables);
                        return new DbExpression[1] { dbExp };
                    }
            }
        }

        protected override DbExpression[] VisitLambda(LambdaExpression exp)
        {
            return this.Visit(exp.Body);
        }
        protected override DbExpression[] VisitNew(NewExpression exp)
        {
            DbExpression[] ret = new DbExpression[exp.Arguments.Count];
            for (int i = 0; i < exp.Arguments.Count; i++)
            {
                var dbExp = GeneralExpressionParser.Parse(exp.Arguments[i], this._scopeParameters, this._scopeTables);
                ret[i] = dbExp;
            }

            return ret;
        }
    }
}


text:
export class ProseMirrorError extends Error {
  // :: (string)
  // Create an instance of this error type, capturing the current
  // stack.
  constructor(message) {
    super(message)
    if (this.message != message) {
      this.message = message
      if (Error.captureStackTrace) Error.captureStackTrace(this, this.name)
      else this.stack = (new Error(message)).stack
    }
  }

  get name() {
    return this.constructor.name || functionName(this.constructor) || "ProseMirrorError"
  }
}

// ;; Error type used to signal miscellaneous invariant violations.
export class AssertionError extends ProseMirrorError {}

// ;; Error type used to report name clashes or other violations in
// namespacing.
export class NamespaceError extends ProseMirrorError {}

function functionName(f) {
  let match = /^function (\w+)/.exec(f.toString())
  return match && match[1]
}


text:
#pragma warning disable 0649
//------------------------------------------------------------------------------
// <auto-generated>This code was generated by LLBLGen Pro v4.1.</auto-generated>
//------------------------------------------------------------------------------
using System;
using System.Data.Linq;
using System.Data.Linq.Mapping;
using System.ComponentModel;

namespace L2S.Bencher.EntityClasses
{
	/// Class which represents the entity 'Product', mapped on table 'AdventureWorks.Production.Product'.
	[Table(Name="[Production].[Product]")]
	public partial class Product : INotifyPropertyChanging, INotifyPropertyChanged
	{
		#region Events
		/// Event which is raised when a property value is changing.
		public event PropertyChangingEventHandler PropertyChanging;
		/// Event which is raised when a property value changes.
		public event PropertyChangedEventHandler PropertyChanged;
		#endregion

		#region Class Member Declarations
		private System.String	_class;
		private System.String	_color;
		private System.Int32	_daysToManufacture;
		private Nullable<System.DateTime>	_discontinuedDate;
		private System.Boolean	_finishedGoodsFlag;
		private System.Decimal	_listPrice;
		private System.Boolean	_makeFlag;
		private System.DateTime	_modifiedDate;
		private System.String	_name;
		private System.Int32	_productId;
		private System.String	_productLine;
		private Nullable<System.Int32>	_productModelId;
		private System.String	_productNumber;
		private Nullable<System.Int32>	_productSubcategoryId;
		private System.Int16	_reorderPoint;
		private System.Guid	_rowguid;
		private System.Int16	_safetyStockLevel;
		private Nullable<System.DateTime>	_sellEndDate;
		private System.DateTime	_sellStartDate;
		private System.String	_size;
		private System.String	_sizeUnitMeasureCode;
		private System.Decimal	_standardCost;
		private System.String	_style;
		private Nullable<System.Decimal>	_weight;
		private System.String	_weightUnitMeasureCode;
		private EntitySet <BillOfMaterial> _billOfMaterials;
		private EntitySet <BillOfMaterial> _billOfMaterials1;
		private EntitySet <ProductCostHistory> _productCostHistories;
		private EntitySet <ProductDocument> _productDocuments;
		private EntitySet <ProductInventory> _productInventories;
		private EntitySet <ProductListPriceHistory> _productListPriceHistories;
		private EntityRef <ProductModel> _productModel;
		private EntitySet <ProductProductPhoto> _productProductPhotos;
		private EntitySet <ProductReview> _productReviews;
		private EntityRef <ProductSubcategory> _productSubcategory;
		private EntitySet <ProductVendor> _productVendors;
		private EntitySet <PurchaseOrderDetail> _purchaseOrderDetails;
		private EntitySet <ShoppingCartItem> _shoppingCartItems;
		private EntitySet <SpecialOfferProduct> _specialOfferProducts;
		private EntitySet <TransactionHistory> _transactionHistories;
		private EntityRef <UnitMeasure> _unitMeasure;
		private EntityRef <UnitMeasure> _unitMeasure1;
		private EntitySet <WorkOrder> _workOrders;
		#endregion

		#region Extensibility Method Definitions
		partial void OnLoaded();
		partial void OnValidate(System.Data.Linq.ChangeAction action);
		partial void OnCreated();
		partial void OnClassChanging(System.String value);
		partial void OnClassChanged();
		partial void OnColorChanging(System.String value);
		partial void OnColorChanged();
		partial void OnDaysToManufactureChanging(System.Int32 value);
		partial void OnDaysToManufactureChanged();
		partial void OnDiscontinuedDateChanging(Nullable<System.DateTime> value);
		partial void OnDiscontinuedDateChanged();
		partial void OnFinishedGoodsFlagChanging(System.Boolean value);
		partial void OnFinishedGoodsFlagChanged();
		partial void OnListPriceChanging(System.Decimal value);
		partial void OnListPriceChanged();
		partial void OnMakeFlagChanging(System.Boolean value);
		partial void OnMakeFlagChanged();
		partial void OnModifiedDateChanging(System.DateTime value);
		partial void OnModifiedDateChanged();
		partial void OnNameChanging(System.String value);
		partial void OnNameChanged();
		partial void OnProductIdChanging(System.Int32 value);
		partial void OnProductIdChanged();
		partial void OnProductLineChanging(System.String value);
		partial void OnProductLineChanged();
		partial void OnProductModelIdChanging(Nullable<System.Int32> value);
		partial void OnProductModelIdChanged();
		partial void OnProductNumberChanging(System.String value);
		partial void OnProductNumberChanged();
		partial void OnProductSubcategoryIdChanging(Nullable<System.Int32> value);
		partial void OnProductSubcategoryIdChanged();
		partial void OnReorderPointChanging(System.Int16 value);
		partial void OnReorderPointChanged();
		partial void OnRowguidChanging(System.Guid value);
		partial void OnRowguidChanged();
		partial void OnSafetyStockLevelChanging(System.Int16 value);
		partial void OnSafetyStockLevelChanged();
		partial void OnSellEndDateChanging(Nullable<System.DateTime> value);
		partial void OnSellEndDateChanged();
		partial void OnSellStartDateChanging(System.DateTime value);
		partial void OnSellStartDateChanged();
		partial void OnSizeChanging(System.String value);
		partial void OnSizeChanged();
		partial void OnSizeUnitMeasureCodeChanging(System.String value);
		partial void OnSizeUnitMeasureCodeChanged();
		partial void OnStandardCostChanging(System.Decimal value);
		partial void OnStandardCostChanged();
		partial void OnStyleChanging(System.String value);
		partial void OnStyleChanged();
		partial void OnWeightChanging(Nullable<System.Decimal> value);
		partial void OnWeightChanged();
		partial void OnWeightUnitMeasureCodeChanging(System.String value);
		partial void OnWeightUnitMeasureCodeChanged();
		#endregion

		/// Initializes a new instance of the <see cref="Product"/> class.
		public Product()
		{
			_billOfMaterials = new EntitySet<BillOfMaterial>(new Action<BillOfMaterial>(this.Attach_BillOfMaterials), new Action<BillOfMaterial>(this.Detach_BillOfMaterials) );
			_billOfMaterials1 = new EntitySet<BillOfMaterial>(new Action<BillOfMaterial>(this.Attach_BillOfMaterials1), new Action<BillOfMaterial>(this.Detach_BillOfMaterials1) );
			_productCostHistories = new EntitySet<ProductCostHistory>(new Action<ProductCostHistory>(this.Attach_ProductCostHistories), new Action<ProductCostHistory>(this.Detach_ProductCostHistories) );
			_productDocuments = new EntitySet<ProductDocument>(new Action<ProductDocument>(this.Attach_ProductDocuments), new Action<ProductDocument>(this.Detach_ProductDocuments) );
			_productInventories = new EntitySet<ProductInventory>(new Action<ProductInventory>(this.Attach_ProductInventories), new Action<ProductInventory>(this.Detach_ProductInventories) );
			_productListPriceHistories = new EntitySet<ProductListPriceHistory>(new Action<ProductListPriceHistory>(this.Attach_ProductListPriceHistories), new Action<ProductListPriceHistory>(this.Detach_ProductListPriceHistories) );
			_productModel = default(EntityRef<ProductModel>);
			_productProductPhotos = new EntitySet<ProductProductPhoto>(new Action<ProductProductPhoto>(this.Attach_ProductProductPhotos), new Action<ProductProductPhoto>(this.Detach_ProductProductPhotos) );
			_productReviews = new EntitySet<ProductReview>(new Action<ProductReview>(this.Attach_ProductReviews), new Action<ProductReview>(this.Detach_ProductReviews) );
			_productSubcategory = default(EntityRef<ProductSubcategory>);
			_productVendors = new EntitySet<ProductVendor>(new Action<ProductVendor>(this.Attach_ProductVendors), new Action<ProductVendor>(this.Detach_ProductVendors) );
			_purchaseOrderDetails = new EntitySet<PurchaseOrderDetail>(new Action<PurchaseOrderDetail>(this.Attach_PurchaseOrderDetails), new Action<PurchaseOrderDetail>(this.Detach_PurchaseOrderDetails) );
			_shoppingCartItems = new EntitySet<ShoppingCartItem>(new Action<ShoppingCartItem>(this.Attach_ShoppingCartItems), new Action<ShoppingCartItem>(this.Detach_ShoppingCartItems) );
			_specialOfferProducts = new EntitySet<SpecialOfferProduct>(new Action<SpecialOfferProduct>(this.Attach_SpecialOfferProducts), new Action<SpecialOfferProduct>(this.Detach_SpecialOfferProducts) );
			_transactionHistories = new EntitySet<TransactionHistory>(new Action<TransactionHistory>(this.Attach_TransactionHistories), new Action<TransactionHistory>(this.Detach_TransactionHistories) );
			_unitMeasure = default(EntityRef<UnitMeasure>);
			_unitMeasure1 = default(EntityRef<UnitMeasure>);
			_workOrders = new EntitySet<WorkOrder>(new Action<WorkOrder>(this.Attach_WorkOrders), new Action<WorkOrder>(this.Detach_WorkOrders) );
			OnCreated();
		}

		/// Raises the PropertyChanging event
		/// <param name="propertyName">name of the property which is changing</param>
		protected virtual void SendPropertyChanging(string propertyName)
		{
			if((this.PropertyChanging != null))
			{
				this.PropertyChanging(this, new PropertyChangingEventArgs(propertyName));
			}
		}

		/// Raises the PropertyChanged event for the property specified
		/// <param name="propertyName">name of the property which was changed</param>
		protected virtual void SendPropertyChanged(string propertyName)
		{
			if((this.PropertyChanged != null))
			{
				this.PropertyChanged(this, new PropertyChangedEventArgs(propertyName));
			}
		}

		/// Attaches this instance to the entity specified as an associated entity
		/// <param name="entity">The related entity to attach to</param>
		private void Attach_BillOfMaterials(BillOfMaterial entity)
		{
			this.SendPropertyChanging("BillOfMaterials");
			entity.Product = this;
		}

		/// Detaches this instance from the entity specified so it's no longer an associated entity
		/// <param name="entity">The related entity to detach from</param>
		private void Detach_BillOfMaterials(BillOfMaterial entity)
		{
			this.SendPropertyChanging("BillOfMaterials");
			entity.Product = null;
		}

		/// Attaches this instance to the entity specified as an associated entity
		/// <param name="entity">The related entity to attach to</param>
		private void Attach_BillOfMaterials1(BillOfMaterial entity)
		{
			this.SendPropertyChanging("BillOfMaterials1");
			entity.Product1 = this;
		}

		/// Detaches this instance from the entity specified so it's no longer an associated entity
		/// <param name="entity">The related entity to detach from</param>
		private void Detach_BillOfMaterials1(BillOfMaterial entity)
		{
			this.SendPropertyChanging("BillOfMaterials1");
			entity.Product1 = null;
		}

		/// Attaches this instance to the entity specified as an associated entity
		/// <param name="entity">The related entity to attach to</param>
		private void Attach_ProductCostHistories(ProductCostHistory entity)
		{
			this.SendPropertyChanging("ProductCostHistories");
			entity.Product = this;
		}

		/// Detaches this instance from the entity specified so it's no longer an associated entity
		/// <param name="entity">The related entity to detach from</param>
		private void Detach_ProductCostHistories(ProductCostHistory entity)
		{
			this.SendPropertyChanging("ProductCostHistories");
			entity.Product = null;
		}

		/// Attaches this instance to the entity specified as an associated entity
		/// <param name="entity">The related entity to attach to</param>
		private void Attach_ProductDocuments(ProductDocument entity)
		{
			this.SendPropertyChanging("ProductDocuments");
			entity.Product = this;
		}

		/// Detaches this instance from the entity specified so it's no longer an associated entity
		/// <param name="entity">The related entity to detach from</param>
		private void Detach_ProductDocuments(ProductDocument entity)
		{
			this.SendPropertyChanging("ProductDocuments");
			entity.Product = null;
		}

		/// Attaches this instance to the entity specified as an associated entity
		/// <param name="entity">The related entity to attach to</param>
		private void Attach_ProductInventories(ProductInventory entity)
		{
			this.SendPropertyChanging("ProductInventories");
			entity.Product = this;
		}

		/// Detaches this instance from the entity specified so it's no longer an associated entity
		/// <param name="entity">The related entity to detach from</param>
		private void Detach_ProductInventories(ProductInventory entity)
		{
			this.SendPropertyChanging("ProductInventories");
			entity.Product = null;
		}

		/// Attaches this instance to the entity specified as an associated entity
		/// <param name="entity">The related entity to attach to</param>
		private void Attach_ProductListPriceHistories(ProductListPriceHistory entity)
		{
			this.SendPropertyChanging("ProductListPriceHistories");
			entity.Product = this;
		}

		/// Detaches this instance from the entity specified so it's no longer an associated entity
		/// <param name="entity">The related entity to detach from</param>
		private void Detach_ProductListPriceHistories(ProductListPriceHistory entity)
		{
			this.SendPropertyChanging("ProductListPriceHistories");
			entity.Product = null;
		}

		/// Attaches this instance to the entity specified as an associated entity
		/// <param name="entity">The related entity to attach to</param>
		private void Attach_ProductProductPhotos(ProductProductPhoto entity)
		{
			this.SendPropertyChanging("ProductProductPhotos");
			entity.Product = this;
		}

		/// Detaches this instance from the entity specified so it's no longer an associated entity
		/// <param name="entity">The related entity to detach from</param>
		private void Detach_ProductProductPhotos(ProductProductPhoto entity)
		{
			this.SendPropertyChanging("ProductProductPhotos");
			entity.Product = null;
		}

		/// Attaches this instance to the entity specified as an associated entity
		/// <param name="entity">The related entity to attach to</param>
		private void Attach_ProductReviews(ProductReview entity)
		{
			this.SendPropertyChanging("ProductReviews");
			entity.Product = this;
		}

		/// Detaches this instance from the entity specified so it's no longer an associated entity
		/// <param name="entity">The related entity to detach from</param>
		private void Detach_ProductReviews(ProductReview entity)
		{
			this.SendPropertyChanging("ProductReviews");
			entity.Product = null;
		}

		/// Attaches this instance to the entity specified as an associated entity
		/// <param name="entity">The related entity to attach to</param>
		private void Attach_ProductVendors(ProductVendor entity)
		{
			this.SendPropertyChanging("ProductVendors");
			entity.Product = this;
		}

		/// Detaches this instance from the entity specified so it's no longer an associated entity
		/// <param name="entity">The related entity to detach from</param>
		private void Detach_ProductVendors(ProductVendor entity)
		{
			this.SendPropertyChanging("ProductVendors");
			entity.Product = null;
		}

		/// Attaches this instance to the entity specified as an associated entity
		/// <param name="entity">The related entity to attach to</param>
		private void Attach_PurchaseOrderDetails(PurchaseOrderDetail entity)
		{
			this.SendPropertyChanging("PurchaseOrderDetails");
			entity.Product = this;
		}

		/// Detaches this instance from the entity specified so it's no longer an associated entity
		/// <param name="entity">The related entity to detach from</param>
		private void Detach_PurchaseOrderDetails(PurchaseOrderDetail entity)
		{
			this.SendPropertyChanging("PurchaseOrderDetails");
			entity.Product = null;
		}

		/// Attaches this instance to the entity specified as an associated entity
		/// <param name="entity">The related entity to attach to</param>
		private void Attach_ShoppingCartItems(ShoppingCartItem entity)
		{
			this.SendPropertyChanging("ShoppingCartItems");
			entity.Product = this;
		}

		/// Detaches this instance from the entity specified so it's no longer an associated entity
		/// <param name="entity">The related entity to detach from</param>
		private void Detach_ShoppingCartItems(ShoppingCartItem entity)
		{
			this.SendPropertyChanging("ShoppingCartItems");
			entity.Product = null;
		}

		/// Attaches this instance to the entity specified as an associated entity
		/// <param name="entity">The related entity to attach to</param>
		private void Attach_SpecialOfferProducts(SpecialOfferProduct entity)
		{
			this.SendPropertyChanging("SpecialOfferProducts");
			entity.Product = this;
		}

		/// Detaches this instance from the entity specified so it's no longer an associated entity
		/// <param name="entity">The related entity to detach from</param>
		private void Detach_SpecialOfferProducts(SpecialOfferProduct entity)
		{
			this.SendPropertyChanging("SpecialOfferProducts");
			entity.Product = null;
		}

		/// Attaches this instance to the entity specified as an associated entity
		/// <param name="entity">The related entity to attach to</param>
		private void Attach_TransactionHistories(TransactionHistory entity)
		{
			this.SendPropertyChanging("TransactionHistories");
			entity.Product = this;
		}

		/// Detaches this instance from the entity specified so it's no longer an associated entity
		/// <param name="entity">The related entity to detach from</param>
		private void Detach_TransactionHistories(TransactionHistory entity)
		{
			this.SendPropertyChanging("TransactionHistories");
			entity.Product = null;
		}

		/// Attaches this instance to the entity specified as an associated entity
		/// <param name="entity">The related entity to attach to</param>
		private void Attach_WorkOrders(WorkOrder entity)
		{
			this.SendPropertyChanging("WorkOrders");
			entity.Product = this;
		}

		/// Detaches this instance from the entity specified so it's no longer an associated entity
		/// <param name="entity">The related entity to detach from</param>
		private void Detach_WorkOrders(WorkOrder entity)
		{
			this.SendPropertyChanging("WorkOrders");
			entity.Product = null;
		}

		#region Class Property Declarations
		/// Gets or sets the Class field. Mapped on target field 'Class'.
		[Column(Name="Class", Storage="_class", DbType="nchar(2) NULL")]
		public System.String Class
		{
			get	{ return _class; }
			set
			{
				if((_class != value))
				{
					OnClassChanging(value);
					SendPropertyChanging("Class");
					_class = value;
					SendPropertyChanged("Class");
					OnClassChanged();
				}
			}
		}

		/// Gets or sets the Color field. Mapped on target field 'Color'.
		[Column(Name="Color", Storage="_color", DbType="nvarchar(15) NULL")]
		public System.String Color
		{
			get	{ return _color; }
			set
			{
				if((_color != value))
				{
					OnColorChanging(value);
					SendPropertyChanging("Color");
					_color = value;
					SendPropertyChanged("Color");
					OnColorChanged();
				}
			}
		}

		/// Gets or sets the DaysToManufacture field. Mapped on target field 'DaysToManufacture'.
		[Column(Name="DaysToManufacture", Storage="_daysToManufacture", CanBeNull=false, DbType="int NOT NULL")]
		public System.Int32 DaysToManufacture
		{
			get	{ return _daysToManufacture; }
			set
			{
				if((_daysToManufacture != value))
				{
					OnDaysToManufactureChanging(value);
					SendPropertyChanging("DaysToManufacture");
					_daysToManufacture = value;
					SendPropertyChanged("DaysToManufacture");
					OnDaysToManufactureChanged();
				}
			}
		}

		/// Gets or sets the DiscontinuedDate field. Mapped on target field 'DiscontinuedDate'.
		[Column(Name="DiscontinuedDate", Storage="_discontinuedDate", DbType="datetime NULL")]
		public Nullable<System.DateTime> DiscontinuedDate
		{
			get	{ return _discontinuedDate; }
			set
			{
				if((_discontinuedDate != value))
				{
					OnDiscontinuedDateChanging(value);
					SendPropertyChanging("DiscontinuedDate");
					_discontinuedDate = value;
					SendPropertyChanged("DiscontinuedDate");
					OnDiscontinuedDateChanged();
				}
			}
		}

		/// Gets or sets the FinishedGoodsFlag field. Mapped on target field 'FinishedGoodsFlag'.
		[Column(Name="FinishedGoodsFlag", Storage="_finishedGoodsFlag", CanBeNull=false, DbType="bit NOT NULL")]
		public System.Boolean FinishedGoodsFlag
		{
			get	{ return _finishedGoodsFlag; }
			set
			{
				if((_finishedGoodsFlag != value))
				{
					OnFinishedGoodsFlagChanging(value);
					SendPropertyChanging("FinishedGoodsFlag");
					_finishedGoodsFlag = value;
					SendPropertyChanged("FinishedGoodsFlag");
					OnFinishedGoodsFlagChanged();
				}
			}
		}

		/// Gets or sets the ListPrice field. Mapped on target field 'ListPrice'.
		[Column(Name="ListPrice", Storage="_listPrice", CanBeNull=false, DbType="money NOT NULL")]
		public System.Decimal ListPrice
		{
			get	{ return _listPrice; }
			set
			{
				if((_listPrice != value))
				{
					OnListPriceChanging(value);
					SendPropertyChanging("ListPrice");
					_listPrice = value;
					SendPropertyChanged("ListPrice");
					OnListPriceChanged();
				}
			}
		}

		/// Gets or sets the MakeFlag field. Mapped on target field 'MakeFlag'.
		[Column(Name="MakeFlag", Storage="_makeFlag", CanBeNull=false, DbType="bit NOT NULL")]
		public System.Boolean MakeFlag
		{
			get	{ return _makeFlag; }
			set
			{
				if((_makeFlag != value))
				{
					OnMakeFlagChanging(value);
					SendPropertyChanging("MakeFlag");
					_makeFlag = value;
					SendPropertyChanged("MakeFlag");
					OnMakeFlagChanged();
				}
			}
		}

		/// Gets or sets the ModifiedDate field. Mapped on target field 'ModifiedDate'.
		[Column(Name="ModifiedDate", Storage="_modifiedDate", CanBeNull=false, DbType="datetime NOT NULL")]
		public System.DateTime ModifiedDate
		{
			get	{ return _modifiedDate; }
			set
			{
				if((_modifiedDate != value))
				{
					OnModifiedDateChanging(value);
					SendPropertyChanging("ModifiedDate");
					_modifiedDate = value;
					SendPropertyChanged("ModifiedDate");
					OnModifiedDateChanged();
				}
			}
		}

		/// Gets or sets the Name field. Mapped on target field 'Name'.
		[Column(Name="Name", Storage="_name", CanBeNull=false, DbType="nvarchar(50) NOT NULL")]
		public System.String Name
		{
			get	{ return _name; }
			set
			{
				if((_name != value))
				{
					OnNameChanging(value);
					SendPropertyChanging("Name");
					_name = value;
					SendPropertyChanged("Name");
					OnNameChanged();
				}
			}
		}

		/// Gets or sets the ProductId field. Mapped on target field 'ProductID'.
		[Column(Name="ProductID", Storage="_productId", AutoSync=AutoSync.OnInsert, CanBeNull=false, DbType="int NOT NULL IDENTITY", IsPrimaryKey=true, IsDbGenerated=true, UpdateCheck=UpdateCheck.Never)]
		public System.Int32 ProductId
		{
			get	{ return _productId; }
			set
			{
				if((_productId != value))
				{
					OnProductIdChanging(value);
					SendPropertyChanging("ProductId");
					_productId = value;
					SendPropertyChanged("ProductId");
					OnProductIdChanged();
				}
			}
		}

		/// Gets or sets the ProductLine field. Mapped on target field 'ProductLine'.
		[Column(Name="ProductLine", Storage="_productLine", DbType="nchar(2) NULL")]
		public System.String ProductLine
		{
			get	{ return _productLine; }
			set
			{
				if((_productLine != value))
				{
					OnProductLineChanging(value);
					SendPropertyChanging("ProductLine");
					_productLine = value;
					SendPropertyChanged("ProductLine");
					OnProductLineChanged();
				}
			}
		}

		/// Gets or sets the ProductModelId field. Mapped on target field 'ProductModelID'.
		[Column(Name="ProductModelID", Storage="_productModelId", DbType="int NULL")]
		public Nullable<System.Int32> ProductModelId
		{
			get	{ return _productModelId; }
			set
			{
				if((_productModelId != value))
				{
					if(_productModel.HasLoadedOrAssignedValue)
					{
						throw new System.Data.Linq.ForeignKeyReferenceAlreadyHasValueException();
					}
					OnProductModelIdChanging(value);
					SendPropertyChanging("ProductModelId");
					_productModelId = value;
					SendPropertyChanged("ProductModelId");
					OnProductModelIdChanged();
				}
			}
		}

		/// Gets or sets the ProductNumber field. Mapped on target field 'ProductNumber'.
		[Column(Name="ProductNumber", Storage="_productNumber", CanBeNull=false, DbType="nvarchar(25) NOT NULL")]
		public System.String ProductNumber
		{
			get	{ return _productNumber; }
			set
			{
				if((_productNumber != value))
				{
					OnProductNumberChanging(value);
					SendPropertyChanging("ProductNumber");
					_productNumber = value;
					SendPropertyChanged("ProductNumber");
					OnProductNumberChanged();
				}
			}
		}

		/// Gets or sets the ProductSubcategoryId field. Mapped on target field 'ProductSubcategoryID'.
		[Column(Name="ProductSubcategoryID", Storage="_productSubcategoryId", DbType="int NULL")]
		public Nullable<System.Int32> ProductSubcategoryId
		{
			get	{ return _productSubcategoryId; }
			set
			{
				if((_productSubcategoryId != value))
				{
					if(_productSubcategory.HasLoadedOrAssignedValue)
					{
						throw new System.Data.Linq.ForeignKeyReferenceAlreadyHasValueException();
					}
					OnProductSubcategoryIdChanging(value);
					SendPropertyChanging("ProductSubcategoryId");
					_productSubcategoryId = value;
					SendPropertyChanged("ProductSubcategoryId");
					OnProductSubcategoryIdChanged();
				}
			}
		}

		/// Gets or sets the ReorderPoint field. Mapped on target field 'ReorderPoint'.
		[Column(Name="ReorderPoint", Storage="_reorderPoint", CanBeNull=false, DbType="smallint NOT NULL")]
		public System.Int16 ReorderPoint
		{
			get	{ return _reorderPoint; }
			set
			{
				if((_reorderPoint != value))
				{
					OnReorderPointChanging(value);
					SendPropertyChanging("ReorderPoint");
					_reorderPoint = value;
					SendPropertyChanged("ReorderPoint");
					OnReorderPointChanged();
				}
			}
		}

		/// Gets or sets the Rowguid field. Mapped on target field 'rowguid'.
		[Column(Name="rowguid", Storage="_rowguid", AutoSync=AutoSync.OnInsert, CanBeNull=false, DbType="uniqueidentifier NOT NULL", IsDbGenerated=true, UpdateCheck=UpdateCheck.Never)]
		public System.Guid Rowguid
		{
			get	{ return _rowguid; }
			set
			{
				if((_rowguid != value))
				{
					OnRowguidChanging(value);
					SendPropertyChanging("Rowguid");
					_rowguid = value;
					SendPropertyChanged("Rowguid");
					OnRowguidChanged();
				}
			}
		}

		/// Gets or sets the SafetyStockLevel field. Mapped on target field 'SafetyStockLevel'.
		[Column(Name="SafetyStockLevel", Storage="_safetyStockLevel", CanBeNull=false, DbType="smallint NOT NULL")]
		public System.Int16 SafetyStockLevel
		{
			get	{ return _safetyStockLevel; }
			set
			{
				if((_safetyStockLevel != value))
				{
					OnSafetyStockLevelChanging(value);
					SendPropertyChanging("SafetyStockLevel");
					_safetyStockLevel = value;
					SendPropertyChanged("SafetyStockLevel");
					OnSafetyStockLevelChanged();
				}
			}
		}

		/// Gets or sets the SellEndDate field. Mapped on target field 'SellEndDate'.
		[Column(Name="SellEndDate", Storage="_sellEndDate", DbType="datetime NULL")]
		public Nullable<System.DateTime> SellEndDate
		{
			get	{ return _sellEndDate; }
			set
			{
				if((_sellEndDate != value))
				{
					OnSellEndDateChanging(value);
					SendPropertyChanging("SellEndDate");
					_sellEndDate = value;
					SendPropertyChanged("SellEndDate");
					OnSellEndDateChanged();
				}
			}
		}

		/// Gets or sets the SellStartDate field. Mapped on target field 'SellStartDate'.
		[Column(Name="SellStartDate", Storage="_sellStartDate", CanBeNull=false, DbType="datetime NOT NULL")]
		public System.DateTime SellStartDate
		{
			get	{ return _sellStartDate; }
			set
			{
				if((_sellStartDate != value))
				{
					OnSellStartDateChanging(value);
					SendPropertyChanging("SellStartDate");
					_sellStartDate = value;
					SendPropertyChanged("SellStartDate");
					OnSellStartDateChanged();
				}
			}
		}

		/// Gets or sets the Size field. Mapped on target field 'Size'.
		[Column(Name="Size", Storage="_size", DbType="nvarchar(5) NULL")]
		public System.String Size
		{
			get	{ return _size; }
			set
			{
				if((_size != value))
				{
					OnSizeChanging(value);
					SendPropertyChanging("Size");
					_size = value;
					SendPropertyChanged("Size");
					OnSizeChanged();
				}
			}
		}

		/// Gets or sets the SizeUnitMeasureCode field. Mapped on target field 'SizeUnitMeasureCode'.
		[Column(Name="SizeUnitMeasureCode", Storage="_sizeUnitMeasureCode", DbType="nchar(3) NULL")]
		public System.String SizeUnitMeasureCode
		{
			get	{ return _sizeUnitMeasureCode; }
			set
			{
				if((_sizeUnitMeasureCode != value))
				{
					if(_unitMeasure.HasLoadedOrAssignedValue)
					{
						throw new System.Data.Linq.ForeignKeyReferenceAlreadyHasValueException();
					}
					OnSizeUnitMeasureCodeChanging(value);
					SendPropertyChanging("SizeUnitMeasureCode");
					_sizeUnitMeasureCode = value;
					SendPropertyChanged("SizeUnitMeasureCode");
					OnSizeUnitMeasureCodeChanged();
				}
			}
		}

		/// Gets or sets the StandardCost field. Mapped on target field 'StandardCost'.
		[Column(Name="StandardCost", Storage="_standardCost", CanBeNull=false, DbType="money NOT NULL")]
		public System.Decimal StandardCost
		{
			get	{ return _standardCost; }
			set
			{
				if((_standardCost != value))
				{
					OnStandardCostChanging(value);
					SendPropertyChanging("StandardCost");
					_standardCost = value;
					SendPropertyChanged("StandardCost");
					OnStandardCostChanged();
				}
			}
		}

		/// Gets or sets the Style field. Mapped on target field 'Style'.
		[Column(Name="Style", Storage="_style", DbType="nchar(2) NULL")]
		public System.String Style
		{
			get	{ return _style; }
			set
			{
				if((_style != value))
				{
					OnStyleChanging(value);
					SendPropertyChanging("Style");
					_style = value;
					SendPropertyChanged("Style");
					OnStyleChanged();
				}
			}
		}

		/// Gets or sets the Weight field. Mapped on target field 'Weight'.
		[Column(Name="Weight", Storage="_weight", DbType="decimal(8,2) NULL")]
		public Nullable<System.Decimal> Weight
		{
			get	{ return _weight; }
			set
			{
				if((_weight != value))
				{
					OnWeightChanging(value);
					SendPropertyChanging("Weight");
					_weight = value;
					SendPropertyChanged("Weight");
					OnWeightChanged();
				}
			}
		}

		/// Gets or sets the WeightUnitMeasureCode field. Mapped on target field 'WeightUnitMeasureCode'.
		[Column(Name="WeightUnitMeasureCode", Storage="_weightUnitMeasureCode", DbType="nchar(3) NULL")]
		public System.String WeightUnitMeasureCode
		{
			get	{ return _weightUnitMeasureCode; }
			set
			{
				if((_weightUnitMeasureCode != value))
				{
					if(_unitMeasure1.HasLoadedOrAssignedValue)
					{
						throw new System.Data.Linq.ForeignKeyReferenceAlreadyHasValueException();
					}
					OnWeightUnitMeasureCodeChanging(value);
					SendPropertyChanging("WeightUnitMeasureCode");
					_weightUnitMeasureCode = value;
					SendPropertyChanged("WeightUnitMeasureCode");
					OnWeightUnitMeasureCodeChanged();
				}
			}
		}

		/// Represents the navigator which is mapped onto the association 'BillOfMaterial.Product - Product.BillOfMaterials (m:1)'
		[Association(Name="BillOfMaterial_Product30e78042efd74e5b9884d562b26e3fc9", Storage="_billOfMaterials", OtherKey="ComponentId")]
		public EntitySet<BillOfMaterial> BillOfMaterials
		{
			get { return this._billOfMaterials; }
			set { this._billOfMaterials.Assign(value); }
		}

		/// Represents the navigator which is mapped onto the association 'BillOfMaterial.Product1 - Product.BillOfMaterials1 (m:1)'
		[Association(Name="BillOfMaterial_Product08ed1c5580994d11bd24a9914ee85c6d", Storage="_billOfMaterials1", OtherKey="ProductAssemblyId")]
		public EntitySet<BillOfMaterial> BillOfMaterials1
		{
			get { return this._billOfMaterials1; }
			set { this._billOfMaterials1.Assign(value); }
		}

		/// Represents the navigator which is mapped onto the association 'ProductCostHistory.Product - Product.ProductCostHistories (m:1)'
		[Association(Name="ProductCostHistory_Product2e35c02f9cd54013a729212d2a97f538", Storage="_productCostHistories", OtherKey="ProductId")]
		public EntitySet<ProductCostHistory> ProductCostHistories
		{
			get { return this._productCostHistories; }
			set { this._productCostHistories.Assign(value); }
		}

		/// Represents the navigator which is mapped onto the association 'ProductDocument.Product - Product.ProductDocuments (m:1)'
		[Association(Name="ProductDocument_Productfc4642fc06fb4679b3d9771eb56ab7d9", Storage="_productDocuments", OtherKey="ProductId")]
		public EntitySet<ProductDocument> ProductDocuments
		{
			get { return this._productDocuments; }
			set { this._productDocuments.Assign(value); }
		}

		/// Represents the navigator which is mapped onto the association 'ProductInventory.Product - Product.ProductInventories (m:1)'
		[Association(Name="ProductInventory_Product3acb3bf8eef544d19542622090083b01", Storage="_productInventories", OtherKey="ProductId")]
		public EntitySet<ProductInventory> ProductInventories
		{
			get { return this._productInventories; }
			set { this._productInventories.Assign(value); }
		}

		/// Represents the navigator which is mapped onto the association 'ProductListPriceHistory.Product - Product.ProductListPriceHistories (m:1)'
		[Association(Name="ProductListPriceHistory_Product648c48d1c99548868500bfed9a20d003", Storage="_productListPriceHistories", OtherKey="ProductId")]
		public EntitySet<ProductListPriceHistory> ProductListPriceHistories
		{
			get { return this._productListPriceHistories; }
			set { this._productListPriceHistories.Assign(value); }
		}

		/// Represents the navigator which is mapped onto the association 'Product.ProductModel - ProductModel.Products (m:1)'
		[Association(Name="Product_ProductModel739aed265eb8478fac72a5d913abb48e", Storage="_productModel", ThisKey="ProductModelId", IsForeignKey=true)]
		public ProductModel ProductModel
		{
			get { return _productModel.Entity; }
			set
			{
				ProductModel previousValue = _productModel.Entity;
				if((previousValue != value) || (_productModel.HasLoadedOrAssignedValue == false))
				{
					this.SendPropertyChanging("ProductModel");
					if(previousValue != null)
					{
						_productModel.Entity = null;
						previousValue.Products.Remove(this);
					}
					_productModel.Entity = value;
					if(value == null)
					{
						_productModelId = default(Nullable<System.Int32>);
					}
					else
					{
						value.Products.Add(this);
						_productModelId = value.ProductModelId;
					}
					this.SendPropertyChanged("ProductModel");
				}
			}
		}

		/// Represents the navigator which is mapped onto the association 'ProductProductPhoto.Product - Product.ProductProductPhotos (m:1)'
		[Association(Name="ProductProductPhoto_Productf09090fc15c6433e90c3424f422e1af5", Storage="_productProductPhotos", OtherKey="ProductId")]
		public EntitySet<ProductProductPhoto> ProductProductPhotos
		{
			get { return this._productProductPhotos; }
			set { this._productProductPhotos.Assign(value); }
		}

		/// Represents the navigator which is mapped onto the association 'ProductReview.Product - Product.ProductReviews (m:1)'
		[Association(Name="ProductReview_Product179037abdb49461bbd96ab67c4e9e6cf", Storage="_productReviews", OtherKey="ProductId")]
		public EntitySet<ProductReview> ProductReviews
		{
			get { return this._productReviews; }
			set { this._productReviews.Assign(value); }
		}

		/// Represents the navigator which is mapped onto the association 'Product.ProductSubcategory - ProductSubcategory.Products (m:1)'
		[Association(Name="Product_ProductSubcategoryafa3a96e7a354f4e89e7574f115cd350", Storage="_productSubcategory", ThisKey="ProductSubcategoryId", IsForeignKey=true)]
		public ProductSubcategory ProductSubcategory
		{
			get { return _productSubcategory.Entity; }
			set
			{
				ProductSubcategory previousValue = _productSubcategory.Entity;
				if((previousValue != value) || (_productSubcategory.HasLoadedOrAssignedValue == false))
				{
					this.SendPropertyChanging("ProductSubcategory");
					if(previousValue != null)
					{
						_productSubcategory.Entity = null;
						previousValue.Products.Remove(this);
					}
					_productSubcategory.Entity = value;
					if(value == null)
					{
						_productSubcategoryId = default(Nullable<System.Int32>);
					}
					else
					{
						value.Products.Add(this);
						_productSubcategoryId = value.ProductSubcategoryId;
					}
					this.SendPropertyChanged("ProductSubcategory");
				}
			}
		}

		/// Represents the navigator which is mapped onto the association 'ProductVendor.Product - Product.ProductVendors (m:1)'
		[Association(Name="ProductVendor_Product870d999dfa5647ce8879f7499a26181d", Storage="_productVendors", OtherKey="ProductId")]
		public EntitySet<ProductVendor> ProductVendors
		{
			get { return this._productVendors; }
			set { this._productVendors.Assign(value); }
		}

		/// Represents the navigator which is mapped onto the association 'PurchaseOrderDetail.Product - Product.PurchaseOrderDetails (m:1)'
		[Association(Name="PurchaseOrderDetail_Producta9b7302820a54752ba8de2670b42257d", Storage="_purchaseOrderDetails", OtherKey="ProductId")]
		public EntitySet<PurchaseOrderDetail> PurchaseOrderDetails
		{
			get { return this._purchaseOrderDetails; }
			set { this._purchaseOrderDetails.Assign(value); }
		}

		/// Represents the navigator which is mapped onto the association 'ShoppingCartItem.Product - Product.ShoppingCartItems (m:1)'
		[Association(Name="ShoppingCartItem_Producta5751febdf9c4b43b64d7c423831400f", Storage="_shoppingCartItems", OtherKey="ProductId")]
		public EntitySet<ShoppingCartItem> ShoppingCartItems
		{
			get { return this._shoppingCartItems; }
			set { this._shoppingCartItems.Assign(value); }
		}

		/// Represents the navigator which is mapped onto the association 'SpecialOfferProduct.Product - Product.SpecialOfferProducts (m:1)'
		[Association(Name="SpecialOfferProduct_Productaca41663409d44bab7ca96c0b6d2b89c", Storage="_specialOfferProducts", OtherKey="ProductId")]
		public EntitySet<SpecialOfferProduct> SpecialOfferProducts
		{
			get { return this._specialOfferProducts; }
			set { this._specialOfferProducts.Assign(value); }
		}

		/// Represents the navigator which is mapped onto the association 'TransactionHistory.Product - Product.TransactionHistories (m:1)'
		[Association(Name="TransactionHistory_Productc9d33ae9dea447e3b82d40f37a4b1214", Storage="_transactionHistories", OtherKey="ProductId")]
		public EntitySet<TransactionHistory> TransactionHistories
		{
			get { return this._transactionHistories; }
			set { this._transactionHistories.Assign(value); }
		}

		/// Represents the navigator which is mapped onto the association 'Product.UnitMeasure - UnitMeasure.Products (m:1)'
		[Association(Name="Product_UnitMeasure4e4a7f30c95440cd94bfa734af4037a5", Storage="_unitMeasure", ThisKey="SizeUnitMeasureCode", IsForeignKey=true)]
		public UnitMeasure UnitMeasure
		{
			get { return _unitMeasure.Entity; }
			set
			{
				UnitMeasure previousValue = _unitMeasure.Entity;
				if((previousValue != value) || (_unitMeasure.HasLoadedOrAssignedValue == false))
				{
					this.SendPropertyChanging("UnitMeasure");
					if(previousValue != null)
					{
						_unitMeasure.Entity = null;
						previousValue.Products.Remove(this);
					}
					_unitMeasure.Entity = value;
					if(value == null)
					{
						_sizeUnitMeasureCode = default(System.String);
					}
					else
					{
						value.Products.Add(this);
						_sizeUnitMeasureCode = value.UnitMeasureCode;
					}
					this.SendPropertyChanged("UnitMeasure");
				}
			}
		}

		/// Represents the navigator which is mapped onto the association 'Product.UnitMeasure1 - UnitMeasure.Products1 (m:1)'
		[Association(Name="Product_UnitMeasure425caec4610f4e93aeb62d99daca56af", Storage="_unitMeasure1", ThisKey="WeightUnitMeasureCode", IsForeignKey=true)]
		public UnitMeasure UnitMeasure1
		{
			get { return _unitMeasure1.Entity; }
			set
			{
				UnitMeasure previousValue = _unitMeasure1.Entity;
				if((previousValue != value) || (_unitMeasure1.HasLoadedOrAssignedValue == false))
				{
					this.SendPropertyChanging("UnitMeasure1");
					if(previousValue != null)
					{
						_unitMeasure1.Entity = null;
						previousValue.Products1.Remove(this);
					}
					_unitMeasure1.Entity = value;
					if(value == null)
					{
						_weightUnitMeasureCode = default(System.String);
					}
					else
					{
						value.Products1.Add(this);
						_weightUnitMeasureCode = value.UnitMeasureCode;
					}
					this.SendPropertyChanged("UnitMeasure1");
				}
			}
		}

		/// Represents the navigator which is mapped onto the association 'WorkOrder.Product - Product.WorkOrders (m:1)'
		[Association(Name="WorkOrder_Producte10d028a5e8f49689152b78216000512", Storage="_workOrders", OtherKey="ProductId")]
		public EntitySet<WorkOrder> WorkOrders
		{
			get { return this._workOrders; }
			set { this._workOrders.Assign(value); }
		}

		#endregion
	}
}
#pragma warning restore 0649