text:
package xeadModeler;

import java.io.*;
import java.util.*;
import java.awt.*;
import java.awt.event.*;

import javax.swing.*;
import javax.swing.event.*;

import org.w3c.dom.*;

public class DialogImportSQL extends JDialog {
	private static final long serialVersionUID = 1L;
	private static ResourceBundle res = ResourceBundle.getBundle("xeadModeler.Res");

	private JPanel panelMain = new JPanel();
	private JLabel jLabel1 = new JLabel();
	private JLabel jLabel2 = new JLabel();
	private JProgressBar jProgressBar = new JProgressBar();
	private JButton jButtonStart = new JButton();
	private JButton jButtonClose = new JButton();
	private SortableXeadNodeComboBoxModel comboBoxModelSubsystem = new SortableXeadNodeComboBoxModel();
	private JComboBox<String> jComboBoxSubsystem = new JComboBox<String>(comboBoxModelSubsystem);
	private JTextArea jTextArea1 = new JTextArea();
	private JTextField jTextFieldImportFileName = new JTextField();
	private FontMetrics metrics = null;
	private JCheckBox jCheckBoxDataTypeControl = new JCheckBox();
	private JCheckBox jCheckBoxShowControl = new JCheckBox();
	//private JCheckBox jCheckBoxTableNameControl = new JCheckBox();
	//private JCheckBox jCheckBoxFieldNameControl = new JCheckBox();
	//private JCheckBox jCheckBoxCommentControl = new JCheckBox();
	private JLabel jLabel3 = new JLabel();
	private JComboBox<String> jComboBoxCommentControl = new JComboBox<String>();

	//private int tableIDCounter = 0;
	private String textFileName = "";
	private String importResult = "";
	private Modeler frame_;
	private org.w3c.dom.Element systemElement;
	private org.w3c.dom.Element subsystemElement;
	private String subsystemID;
	private int numberOfTablesCreated = 0;
	private int numberOfTableRelationshipsCreated = 0;
	private String defaultDataTypeID = "";
	private String defaultTableTypeID = "";
	private String primaryKeyFieldID = "";

	private String[] sqlDataTypeArray = new String[84];
	private String[] sqlDataTypeArray2 = new String[40];
	private String[] nameArray = new String[1000];
	private String[] attrArray = new String[1000];
	private org.w3c.dom.Element[] tableElementArray = new org.w3c.dom.Element[1000];
	private int itemsOfArray = -1;
	private String[] hideFieldArray = new String[50];
	private int itemsOfHideFieldArray = -1;

	public DialogImportSQL(Modeler frame, String title, boolean modal) {
		super(frame, title, modal);
		try {
			frame_ = frame;
			jbInit();
			pack();
		}
		catch(Exception ex) {
			ex.printStackTrace();
		}
	}

	public DialogImportSQL(Modeler frame) {
		this(frame, "", true);
	}

	private void jbInit() throws Exception {
		this.setResizable(false);
		this.setTitle(res.getString("DialogImportSQL01"));

		sqlDataTypeArray[0] = " INTEGER ";
		sqlDataTypeArray[1] = " INT ";
		sqlDataTypeArray[2] = " TINYINT ";
		sqlDataTypeArray[3] = " SMALLINT ";
		sqlDataTypeArray[4] = " MEDIUMINT ";
		sqlDataTypeArray[5] = " BIGINT ";
		sqlDataTypeArray[6] = " REAL ";
		sqlDataTypeArray[7] = " DOUBLE ";
		sqlDataTypeArray[8] = " FLOAT ";
		sqlDataTypeArray[9] = " FLOAT(";
		sqlDataTypeArray[10] = " DECIMAL ";
		sqlDataTypeArray[11] = " DECIMAL(";
		sqlDataTypeArray[12] = " NUMERIC ";
		sqlDataTypeArray[13] = " NUMERIC(";
		sqlDataTypeArray[14] = " NUMBER ";
		sqlDataTypeArray[15] = " NUMBER(";
		sqlDataTypeArray[16] = " ENUM ";
		sqlDataTypeArray[17] = " ENUM(";
		sqlDataTypeArray[18] = " CHAR ";
		sqlDataTypeArray[19] = " CHAR(";
		sqlDataTypeArray[20] = " NCHAR ";
		sqlDataTypeArray[21] = " NCHAR(";
		sqlDataTypeArray[22] = " DATE ";
		sqlDataTypeArray[23] = " TIME ";
		sqlDataTypeArray[24] = " DATETIME ";
		sqlDataTypeArray[25] = " TIMESTAMP ";
		sqlDataTypeArray[26] = " BLOB ";
		sqlDataTypeArray[27] = " TEXT ";
		sqlDataTypeArray[28] = " TEXT(";
		sqlDataTypeArray[29] = " SET ";
		sqlDataTypeArray[30] = " BOOLEAN ";
		sqlDataTypeArray[31] = " BIT ";
		sqlDataTypeArray[32] = " integer ";
		sqlDataTypeArray[33] = " int ";
		sqlDataTypeArray[34] = " tinyint ";
		sqlDataTypeArray[35] = " smallint ";
		sqlDataTypeArray[36] = " mediumint ";
		sqlDataTypeArray[37] = " bigint ";
		sqlDataTypeArray[38] = " real ";
		sqlDataTypeArray[39] = " double ";
		sqlDataTypeArray[40] = " float ";
		sqlDataTypeArray[41] = " float(";
		sqlDataTypeArray[42] = " decimal ";
		sqlDataTypeArray[43] = " decimal(";
		sqlDataTypeArray[44] = " numeric ";
		sqlDataTypeArray[45] = " numeric(";
		sqlDataTypeArray[46] = " number ";
		sqlDataTypeArray[47] = " number(";
		sqlDataTypeArray[48] = " enum ";
		sqlDataTypeArray[49] = " enum(";
		sqlDataTypeArray[50] = " char ";
		sqlDataTypeArray[51] = " char(";
		sqlDataTypeArray[52] = " nchar ";
		sqlDataTypeArray[53] = " nchar(";
		sqlDataTypeArray[54] = " date ";
		sqlDataTypeArray[55] = " time ";
		sqlDataTypeArray[56] = " datetime ";
		sqlDataTypeArray[57] = " timestamp ";
		sqlDataTypeArray[58] = " blob ";
		sqlDataTypeArray[59] = " text ";
		sqlDataTypeArray[60] = " text(";
		sqlDataTypeArray[61] = " set ";
		sqlDataTypeArray[62] = " boolean ";
		sqlDataTypeArray[63] = " bit ";
		sqlDataTypeArray[64] = " VARCHAR ";
		sqlDataTypeArray[65] = " VARCHAR(";
		sqlDataTypeArray[66] = " varchar ";
		sqlDataTypeArray[67] = " varchar(";
		sqlDataTypeArray[68] = " LONGBLOB ";
		sqlDataTypeArray[69] = " longblob ";
		sqlDataTypeArray[70] = " INT(";
		sqlDataTypeArray[71] = " int(";
		sqlDataTypeArray[72] = " TINYINT(";
		sqlDataTypeArray[73] = " tinyint(";
		sqlDataTypeArray[74] = " LONGTEXT ";
		sqlDataTypeArray[75] = " longtext ";
		sqlDataTypeArray[76] = " TIMESTAMP(";
		sqlDataTypeArray[77] = " timestamp(";
		sqlDataTypeArray[78] = " VARCHAR2 ";
		sqlDataTypeArray[79] = " VARCHAR2(";
		sqlDataTypeArray[80] = " varchar2 ";
		sqlDataTypeArray[81] = " varchar2(";
		sqlDataTypeArray[82] = " RAW(";
		sqlDataTypeArray[83] = " raw(";

		sqlDataTypeArray2[0] = "INT";
		sqlDataTypeArray2[1] = "REAL";
		sqlDataTypeArray2[2] = "DOUBLE";
		sqlDataTypeArray2[3] = "FLOAT";
		sqlDataTypeArray2[4] = "DECIMAL";
		sqlDataTypeArray2[5] = "NUMERIC";
		sqlDataTypeArray2[6] = "NUMBER";
		sqlDataTypeArray2[7] = "ENUM";
		sqlDataTypeArray2[8] = "int";
		sqlDataTypeArray2[9] = "real";
		sqlDataTypeArray2[10] = "double";
		sqlDataTypeArray2[11] = "float";
		sqlDataTypeArray2[12] = "decimal";
		sqlDataTypeArray2[13] = "numeric";
		sqlDataTypeArray2[14] = "number";
		sqlDataTypeArray2[15] = "enum";
		sqlDataTypeArray2[16] = "CHAR";
		sqlDataTypeArray2[17] = "NCHAR";
		sqlDataTypeArray2[18] = "char";
		sqlDataTypeArray2[19] = "nchar";
		sqlDataTypeArray2[20] = "DATE";
		sqlDataTypeArray2[21] = "TIME";
		sqlDataTypeArray2[22] = "date";
		sqlDataTypeArray2[23] = "time";
		sqlDataTypeArray2[24] = "BLOB";
		sqlDataTypeArray2[25] = "blob";
		sqlDataTypeArray2[26] = "TEXT";
		sqlDataTypeArray2[27] = "text";
		sqlDataTypeArray2[28] = "SET";
		sqlDataTypeArray2[29] = "set";
		sqlDataTypeArray2[30] = "BOOLEAN";
		sqlDataTypeArray2[31] = "BIT";
		sqlDataTypeArray2[32] = "boolean";
		sqlDataTypeArray2[33] = "bit";
		sqlDataTypeArray2[34] = "VARCHAR";
		sqlDataTypeArray2[35] = "varchar";
		sqlDataTypeArray2[36] = "LONGBLOB";
		sqlDataTypeArray2[37] = "longblob";
		sqlDataTypeArray2[38] = "LONGTEXT";
		sqlDataTypeArray2[39] = "longtext";

		jLabel1.setFont(new java.awt.Font(frame_.mainFontName, 0, Modeler.MAIN_FONT_SIZE));
		jLabel1.setHorizontalAlignment(SwingConstants.RIGHT);
		jLabel1.setText(res.getString("DialogImportSQL02"));
		jLabel1.setBounds(new Rectangle(5, 12, 180, 20));
		jTextFieldImportFileName.setFont(new java.awt.Font(frame_.mainFontName, 0, Modeler.MAIN_FONT_SIZE));
		jTextFieldImportFileName.setBounds(new Rectangle(190, 9, 280, 25));
		jTextFieldImportFileName.setEditable(false);
		metrics = jTextFieldImportFileName.getFontMetrics(jTextFieldImportFileName.getFont());

		jLabel2.setFont(new java.awt.Font(frame_.mainFontName, 0, Modeler.MAIN_FONT_SIZE));
		jLabel2.setHorizontalAlignment(SwingConstants.RIGHT);
		jLabel2.setText(res.getString("DialogImportSQL03"));
		jLabel2.setBounds(new Rectangle(5, 43, 180, 20));
		jComboBoxSubsystem.setBounds(new Rectangle(190, 40, 280, 25));
		jComboBoxSubsystem.setFont(new java.awt.Font(frame_.mainFontName, 0, Modeler.MAIN_FONT_SIZE));
		jComboBoxSubsystem.addActionListener(new DialogImportSQL_jComboBoxSubsystem_actionAdapter(this));

		jLabel3.setFont(new java.awt.Font(frame_.mainFontName, 0, Modeler.MAIN_FONT_SIZE));
		jLabel3.setHorizontalAlignment(SwingConstants.RIGHT);
		jLabel3.setText(res.getString("DialogImportSQL12"));
		jLabel3.setBounds(new Rectangle(5, 74, 180, 20));
		jComboBoxCommentControl.setBounds(new Rectangle(190, 71, 280, 25));
		jComboBoxCommentControl.setFont(new java.awt.Font(frame_.mainFontName, 0, Modeler.MAIN_FONT_SIZE));
		jComboBoxCommentControl.addItem(res.getString("DialogImportSQL13"));
		jComboBoxCommentControl.addItem(res.getString("DialogImportSQL14"));
		jComboBoxCommentControl.addItem(res.getString("DialogImportSQL15"));

//		jCheckBoxTableNameControl.setBounds(new Rectangle(9, 71, 460, 25));
//		jCheckBoxTableNameControl.setFont(new java.awt.Font(frame_.mainFontName, 0, Modeler.MAIN_FONT_SIZE));
//		jCheckBoxTableNameControl.setText(res.getString("DialogImportSQL12"));
//		jCheckBoxTableNameControl.setSelected(true);
//
//		jCheckBoxCommentControl.setBounds(new Rectangle(9, 102, 460, 25));
//		jCheckBoxCommentControl.setFont(new java.awt.Font(frame_.mainFontName, 0, Modeler.MAIN_FONT_SIZE));
//		jCheckBoxCommentControl.setText(res.getString("DialogImportSQL14"));
//		jCheckBoxCommentControl.setSelected(true);
//
//		jCheckBoxFieldNameControl.setBounds(new Rectangle(9, 133, 460, 25));
//		jCheckBoxFieldNameControl.setFont(new java.awt.Font(frame_.mainFontName, 0, Modeler.MAIN_FONT_SIZE));
//		jCheckBoxFieldNameControl.setText(res.getString("DialogImportSQL13"));
//		jCheckBoxFieldNameControl.setSelected(true);

		jCheckBoxDataTypeControl.setBounds(new Rectangle(9, 102, 460, 25));
		jCheckBoxDataTypeControl.setFont(new java.awt.Font(frame_.mainFontName, 0, Modeler.MAIN_FONT_SIZE));
		jCheckBoxDataTypeControl.setText(res.getString("DialogImportSQL10"));
		jCheckBoxDataTypeControl.setSelected(true);

		jCheckBoxShowControl.setBounds(new Rectangle(9, 133, 460, 25));
		jCheckBoxShowControl.setFont(new java.awt.Font(frame_.mainFontName, 0, Modeler.MAIN_FONT_SIZE));
		jCheckBoxShowControl.setText(res.getString("DialogImportSQL11"));
		jCheckBoxShowControl.setSelected(true);
		jCheckBoxShowControl.addChangeListener(new DialogImportSQL_jCheckBoxShowControl_changeAdapter(this));

		jTextArea1.setFont(new java.awt.Font(frame_.mainFontName, 0, Modeler.MAIN_FONT_SIZE));
		jTextArea1.setEditable(true);
		jTextArea1.setBounds(new Rectangle(9, 164, 465, 162));
		jTextArea1.setText(res.getString("DialogImportSQL04"));
		jTextArea1.setLineWrap(true);
		jTextArea1.setBorder(BorderFactory.createLoweredBevelBorder());

		jProgressBar.setBounds(new Rectangle(25, 335, 290, 27));
		jButtonStart.setBounds(new Rectangle(25, 335, 290, 27));
		jButtonStart.setFont(new java.awt.Font(frame_.mainFontName, 0, Modeler.MAIN_FONT_SIZE));
		jButtonStart.setText(res.getString("DialogImportSQL05"));
		jButtonStart.addActionListener(new DialogImportSQL_jButtonStart_actionAdapter(this));
		jButtonStart.setEnabled(false);
		jButtonClose.setBounds(new Rectangle(345, 335, 110, 27));
		jButtonClose.setFont(new java.awt.Font(frame_.mainFontName, 0, Modeler.MAIN_FONT_SIZE));
		jButtonClose.setText(res.getString("DialogImportSQL06"));
		jButtonClose.addActionListener(new DialogImportSQL_jButtonClose_actionAdapter(this));

		panelMain.setLayout(null);
		panelMain.setPreferredSize(new Dimension(483, 373));
		panelMain.setBorder(BorderFactory.createEtchedBorder());
		panelMain.add(jLabel1, null);
		panelMain.add(jLabel2, null);
		panelMain.add(jTextFieldImportFileName, null);
		panelMain.add(jComboBoxSubsystem, null);
		panelMain.add(jLabel3, null);
		panelMain.add(jComboBoxCommentControl, null);
//		panelMain.add(jCheckBoxTableNameControl, null);
//		panelMain.add(jCheckBoxCommentControl, null);
//		panelMain.add(jCheckBoxFieldNameControl, null);
		panelMain.add(jCheckBoxDataTypeControl, null);
		panelMain.add(jCheckBoxShowControl, null);
		panelMain.add(jTextArea1, null);
		panelMain.add(jProgressBar, null);
		panelMain.add(jButtonStart, null);
		panelMain.add(jButtonClose, null);

		this.getContentPane().add(panelMain, BorderLayout.SOUTH);
		Dimension scrSize = Toolkit.getDefaultToolkit().getScreenSize();
		Dimension dlgSize = this.getPreferredSize();
		this.setLocation((scrSize.width - dlgSize.width)/2 , (scrSize.height - dlgSize.height)/2);
		this.pack();
	}

	public String request(String name) {
		XeadNode node;
		NodeList elementList;
		importResult = "";

		textFileName = name;
		jTextFieldImportFileName.setText(textFileName);
		if (metrics.stringWidth(jTextFieldImportFileName.getText()) > jTextFieldImportFileName.getBounds().width) {
			jTextFieldImportFileName.setHorizontalAlignment(SwingConstants.RIGHT);
		} else {
			jTextFieldImportFileName.setHorizontalAlignment(SwingConstants.LEFT);
		}

		comboBoxModelSubsystem.removeAllElements();
		elementList = frame_.domDocument.getElementsByTagName("Subsystem");
		for (int i = 0; i < elementList.getLength(); i++) {
			node = new XeadNode("Subsystem",(org.w3c.dom.Element)elementList.item(i));
			comboBoxModelSubsystem.addElement((Object)node);
		}
		comboBoxModelSubsystem.sortElements();
		comboBoxModelSubsystem.insertElementAt(res.getString("DialogImportSQL07"), 0);
		comboBoxModelSubsystem.setSelectedItem(comboBoxModelSubsystem.getElementAt(0));

		jProgressBar.setValue(0);
		jProgressBar.setVisible(false);
		super.setVisible(true);

		return importResult;
	}

	void jComboBoxSubsystem_actionPerformed(ActionEvent e) {
		if (jComboBoxSubsystem.getSelectedIndex() != 0) {
			jButtonStart.setEnabled(true);
		} else {
			jButtonStart.setEnabled(false);
		}
	}

	void jButtonStart_actionPerformed(ActionEvent e) {
		XeadNode workNode;
		org.w3c.dom.Element workElement;
		NodeList elementList;
		StringBuffer buffer = new StringBuffer();
		String wrkStr = "";

		numberOfTablesCreated = 0;
		numberOfTableRelationshipsCreated = 0;
		itemsOfArray = -1;
		//tableIDCounter = 0;
		itemsOfHideFieldArray = -1;

		try {
			setCursor(new Cursor(Cursor.WAIT_CURSOR));
			jButtonStart.setVisible(false);
			jProgressBar.setVisible(true);

			elementList = frame_.domDocument.getElementsByTagName("System");
			systemElement = (org.w3c.dom.Element)elementList.item(0);

			///////////////////////////////////////////
			// get ID of the subsystem imported into //
			///////////////////////////////////////////
			workNode = (XeadNode)comboBoxModelSubsystem.getSelectedItem();
			subsystemElement = workNode.getElement();
			subsystemID = subsystemElement.getAttribute("ID");

			////////////////////////////////////////////////////////////////
			// get ID of the TableType with the smallest value of SortKey //
			////////////////////////////////////////////////////////////////
			wrkStr = "";
			elementList = frame_.domDocument.getElementsByTagName("TableType");
			for (int i = 0; i < elementList.getLength(); i++) {
				workElement = (org.w3c.dom.Element)elementList.item(i);
				if (wrkStr.equals("")) {
					wrkStr = workElement.getAttribute("SortKey");
					defaultTableTypeID = workElement.getAttribute("ID");
				} else {
					if (workElement.getAttribute("SortKey").compareTo(wrkStr) < 0) {
						wrkStr = workElement.getAttribute("SortKey");
						defaultTableTypeID = workElement.getAttribute("ID");
					}
				}
			}

			///////////////////////////////////////////////////////////////
			// get ID of the DataType with the smallest value of SortKey //
			///////////////////////////////////////////////////////////////
			wrkStr = "";
			elementList = frame_.domDocument.getElementsByTagName("DataType");
			for (int i = 0; i < elementList.getLength(); i++) {
				workElement = (org.w3c.dom.Element)elementList.item(i);
				if (wrkStr.equals("")) {
					wrkStr = workElement.getAttribute("SortKey");
					defaultDataTypeID = workElement.getAttribute("ID");
				} else {
					if (workElement.getAttribute("SortKey").compareTo(wrkStr) < 0) {
						wrkStr = workElement.getAttribute("SortKey");
						defaultDataTypeID = workElement.getAttribute("ID");
					}
				}
			}

			try {
				BufferedReader br = new BufferedReader(new FileReader(textFileName));
				String line;
				while ((line = br.readLine()) != null) {
					buffer.append(line);
				}
				br.close();
			} catch (IOException ex) {}
			//String statements = buffer.toString().toUpperCase();
			String statements = buffer.toString();

			if (jCheckBoxShowControl.isSelected()) {
				setupHideFieldNameArray();
			}

			//////////////////////////////////////////////////////
			//Substring table name and its attributes into array//
			//////////////////////////////////////////////////////
			int bracketOpen = 0;
			int bracketClose = 0;
			int scanStartFrom = 0;
			int posOfCREATE_TABLE = 0;
			int posOfFirstBracket = 0;
			int posWork = 0;
			while (scanStartFrom < statements.length()) {
				posOfCREATE_TABLE = statements.toUpperCase().indexOf("CREATE TABLE ", scanStartFrom);
				if (posOfCREATE_TABLE >= 0) {
					posOfFirstBracket = statements.indexOf("(", posOfCREATE_TABLE);
					if (posOfFirstBracket > 0) {
						posWork = posOfFirstBracket;
						bracketOpen = 0;
						bracketClose = 0;
						while (posWork < statements.length()) {
							wrkStr = statements.substring(posWork,posWork+1);
							if (wrkStr.equals("(")) {
								bracketOpen++;
							}
							if (wrkStr.equals(")")) {
								bracketClose++;
							}
							if (bracketOpen == bracketClose && bracketOpen > 0) {
								itemsOfArray++;
								nameArray[itemsOfArray] = trimBlankFromValue(statements.substring(posOfCREATE_TABLE+13, posOfFirstBracket));
								attrArray[itemsOfArray] = statements.substring(posOfFirstBracket+1, posWork);
								posOfCREATE_TABLE = posWork;
								break;
							}
							posWork++;
						}
					}
					scanStartFrom = posOfCREATE_TABLE+1;
				} else {
					scanStartFrom = statements.length();
				}
			}

			jProgressBar.setValue(0);
			jProgressBar.setMaximum(itemsOfArray + itemsOfArray);

			for (int p = 0; p <= itemsOfArray; p++) {
				jProgressBar.setValue(jProgressBar.getValue() + 1);
				jProgressBar.paintImmediately(0,0,jProgressBar.getWidth(),jProgressBar.getHeight());
				tableElementArray[p] = createTableDefinition(nameArray[p], attrArray[p]);
			}

			for (int p = 0; p <= itemsOfArray; p++) {
				jProgressBar.setValue(jProgressBar.getValue() + 1);
				jProgressBar.paintImmediately(0,0,jProgressBar.getWidth(),jProgressBar.getHeight());
				createTableRelationship(tableElementArray[p], attrArray[p]);
			}

			importResult = numberOfTablesCreated + res.getString("DialogImportSQL08") +  numberOfTableRelationshipsCreated + res.getString("DialogImportSQL09") +"\n" + "\n";

		} finally {
			jProgressBar.setValue(0);
			jButtonStart.setVisible(true);
			jProgressBar.setVisible(false);
			setCursor(new Cursor(Cursor.DEFAULT_CURSOR));
			this.setVisible(false);
		}
	}

	void jButtonClose_actionPerformed(ActionEvent e) {
		this.setVisible(false);
	}

	void jCheckBoxShowControl_stateChanged() {
		if (jCheckBoxShowControl.isSelected()) {
			jTextArea1.setForeground(Color.BLACK);
			jTextArea1.setEditable(true);
			jTextArea1.setBackground(SystemColor.window);
		} else {
			jTextArea1.setForeground(Color.GRAY);
			jTextArea1.setEditable(false);
			jTextArea1.setBackground(SystemColor.control);
		}
	}

	void setupHideFieldNameArray() {
		String wrkStr = jTextArea1.getText().replaceAll("\n", "");
		StringTokenizer workTokenizer = new StringTokenizer(wrkStr, "," );
		int numberOfItem = workTokenizer.countTokens();
		for (int j = 0; j < numberOfItem; j++) {
			if (j < 50) {
				hideFieldArray[j] = trimBlankFromValue(workTokenizer.nextToken());
				itemsOfHideFieldArray = j+1;
			}
		}
	}

	org.w3c.dom.Element createTableDefinition(String tableName, String tableAttributes) {
		org.w3c.dom.Element lastElement;
		int lastID = 0;
		String[] fieldArray = new String[1000];

		///////////////////////////
		//Create Table Definition//
		///////////////////////////
		org.w3c.dom.Element tableElement = frame_.domDocument.createElement("Table");
		lastElement = getLastDomElementOfTheType("Table");
		if (lastElement == null) {
			lastID = 0;
		} else {
			lastID = Integer.parseInt(lastElement.getAttribute("ID"));
		}
		tableElement.setAttribute("ID", Integer.toString(lastID + 1));
		tableElement.setAttribute("Name", tableName);

//		if (jCheckBoxTableNameControl.isSelected()) {
//			tableIDCounter++;
//			tableElement.setAttribute("SortKey", "T" + getFormatted3ByteString(tableIDCounter) + "0");
//		} else {
			tableElement.setAttribute("SortKey", tableName);
//		}
		tableElement.setAttribute("SubsystemID", subsystemID);
		tableElement.setAttribute("Descriptions", "");
		tableElement.setAttribute("TableTypeID", defaultTableTypeID);
		systemElement.appendChild(tableElement);

		//////////////////////
		//Create Primary Key//
		//////////////////////
		org.w3c.dom.Element primaryKeyElement = frame_.domDocument.createElement("TableKey");
		primaryKeyElement.setAttribute("ID", "1");
		primaryKeyElement.setAttribute("SortKey", "000");
		primaryKeyElement.setAttribute("Type", "PK");
		tableElement.appendChild(primaryKeyElement);
		primaryKeyFieldID = "";

		/////////////////////////////////////
		//Create Subsystem Table attributes//
		/////////////////////////////////////
		org.w3c.dom.Element subsystemTableElement = frame_.domDocument.createElement("SubsystemTable");
		subsystemTableElement.setAttribute("TableID", tableElement.getAttribute("ID"));
		int work = lastID % 10;
		work = 50 + work * 10;
		subsystemTableElement.setAttribute("BoxPosition", work + "," + work);
		subsystemTableElement.setAttribute("ExtDivLoc", "600");
		subsystemTableElement.setAttribute("IntDivLoc", "300");
		subsystemTableElement.setAttribute("ShowOnModel", "true");
		subsystemTableElement.setAttribute("ShowInstance", "false");
		subsystemTableElement.setAttribute("Instance", "");
		subsystemElement.appendChild(subsystemTableElement);

		///////////////////////////////////
		//Substring attributes into array//
		///////////////////////////////////
		int itemsOfArray = -1;
		int i = 0;
		int j = 0;
		int bracketOpen = 0;
		int bracketClose = 0;
		tableAttributes = tableAttributes.replaceAll("\n", "");
		tableAttributes = tableAttributes.replaceAll("\t", " ");
		tableAttributes = tableAttributes.replaceAll(",", " ,");
		int posStartFrom = 0;
		for (int pos = 0; pos < tableAttributes.length(); pos++) {
			if (tableAttributes.substring(pos, pos+1).equals(",") || pos+1 == tableAttributes.length()) {
				if (bracketOpen == bracketClose || pos+1 == tableAttributes.length()) {
					itemsOfArray++;
					fieldArray[itemsOfArray] = tableAttributes.substring(posStartFrom, pos);
					posStartFrom = pos + 1;
					bracketOpen = 0;
					bracketClose = 0;
				}
			}
			if (tableAttributes.substring(pos, pos+1).equals("(")) {
				bracketOpen++;
			}
			if (tableAttributes.substring(pos, pos+1).equals(")")) {
				bracketClose++;
			}
		}

		/////////////////////
		//Create TableField//
		/////////////////////
		int sortKey = 0;
		for (i = 0; i <= itemsOfArray; i++) {
			for (j = 0; j < sqlDataTypeArray.length; j++) {
				if (fieldArray[i].indexOf(sqlDataTypeArray[j], 0) > 0) {
					sortKey++;
					createFieldDefinition(tableElement, sortKey, fieldArray[i]);
					break;
				}
			}
		}

		////////////////////////////
		//Set Fields of PrimaryKey//
		////////////////////////////
		if (primaryKeyFieldID.equals("")) {
			for (i = 0; i <= itemsOfArray; i++) {
				if (fieldArray[i].toUpperCase().indexOf("PRIMARY KEY", 0) >= 0) {
					setKeyFieldOfTheKey(primaryKeyElement, tableElement, fieldArray[i]);
					break;
				}
			}
		} else {
			org.w3c.dom.Element keyFieldElement = frame_.domDocument.createElement("TableKeyField");
			keyFieldElement.setAttribute("FieldID", primaryKeyFieldID);
			keyFieldElement.setAttribute("SortKey", "0010");
			primaryKeyElement.appendChild(keyFieldElement);
		}

		/////////////////////
		//Create SK and FK //
		/////////////////////
		for (i = 0; i <= itemsOfArray; i++) {
			if (fieldArray[i].toUpperCase().indexOf("UNIQUE", 0) >= 0 && fieldArray[i].indexOf("PRIMARY KEY", 0) == -1) {
				createSecondaryKeyDefinition(tableElement, fieldArray[i]);
			}
		}

		numberOfTablesCreated++;

		return tableElement;
	}

	void createFieldDefinition(org.w3c.dom.Element tableElement, int sortKey, String fieldAttrString) {
		String fieldNameValue = "";
		String notNullValue = "false";
		String defaultValue = "";
		String commentValue = "";
		org.w3c.dom.Element lastElement;
		int lastID = 0;

		fieldNameValue = trimBlankFromValue(fieldAttrString);
		if (fieldNameValue.equals("")) {
			return;
		}

		////////////////
		//Get NOT NULL//
		////////////////
		if (fieldAttrString.toUpperCase().indexOf("NOT NULL", 0) > 0) {
			notNullValue = "true";
		}

		////////////////
		//Get Default //
		////////////////
		defaultValue = "";
		int posStart = 0;
		int posEnd = 0;
		int i = fieldAttrString.toUpperCase().indexOf(" DEFAULT ", 0);
		if (i > 0) {
			for (int j=i+8; j < fieldAttrString.length(); j++) {
				if (posStart == 0 && !fieldAttrString.substring(j,j+1).equals(" ")) {
					posStart = j;
				}
				posEnd = j;
				if (posStart > 0 && (fieldAttrString.substring(j,j+1).equals(" ") || fieldAttrString.substring(j,j+1).equals(","))) {
					break;
				}
			}
			if (posEnd > posStart) {
				defaultValue = fieldAttrString.substring(posStart, posEnd).replaceAll("'", "");
			}
		}

		////////////////
		//Get COMMENT //
		////////////////
		commentValue = "";
		posStart = 0;
		posEnd = 0;
		i = fieldAttrString.toUpperCase().indexOf(" COMMENT ", 0);
		if (i > 0) {
			for (int j=i+9; j < fieldAttrString.length(); j++) {
				if (posStart == 0 && !fieldAttrString.substring(j,j+1).equals("'")) {
					posStart = j;
				}
				posEnd = j;
				if (posStart > 0 && fieldAttrString.substring(j,j+1).equals("'")) {
					break;
				}
			}
			if (posEnd > posStart) {
				commentValue = fieldAttrString.substring(posStart, posEnd);
			}
		}

		////////////////////////
		//Set field attributes//
		////////////////////////
		org.w3c.dom.Element fieldElement = frame_.domDocument.createElement("TableField");
		lastElement = getLastDomElementOfTheType("TableField");
		if (lastElement == null) {
			lastID = 0;
		} else {
			lastID = Integer.parseInt(lastElement.getAttribute("ID"));
		}
		fieldElement.setAttribute("ID", Integer.toString(lastID + 1));
//		if (jCheckBoxCommentControl.isSelected()) {
//			fieldElement.setAttribute("Name", commentValue);
//			fieldElement.setAttribute("Descriptions", "");
//		} else {
//			fieldElement.setAttribute("Name", fieldNameValue);
//			fieldElement.setAttribute("Descriptions", commentValue);
//		}
		if (jComboBoxCommentControl.getSelectedIndex() == 0) {
			fieldElement.setAttribute("Name", commentValue);
			fieldElement.setAttribute("Descriptions", "");
		}
		if (jComboBoxCommentControl.getSelectedIndex() == 1) {
			fieldElement.setAttribute("Name", fieldNameValue);
			fieldElement.setAttribute("Descriptions", commentValue);
		}
		fieldElement.setAttribute("SortKey", getFormatted3ByteString(sortKey) + "0");
		//if (jCheckBoxFieldNameControl.isSelected()) {
			fieldElement.setAttribute("Alias", fieldNameValue);
		//} else {
		//	fieldElement.setAttribute("Alias", "");
		//}
		fieldElement.setAttribute("AttributeType", "NATIVE");
		fieldElement.setAttribute("DataTypeID", getDataTypeID(fieldAttrString));
		fieldElement.setAttribute("ShowOnModel", "true");
		if (jCheckBoxShowControl.isSelected()) {
			for (i = 0; i < itemsOfHideFieldArray; i++) {
				if (hideFieldArray[i].equals(fieldNameValue)) {
					fieldElement.setAttribute("ShowOnModel", "false");
					break;
				}
			}
		}
		fieldElement.setAttribute("NotNull", notNullValue);
		fieldElement.setAttribute("Default", defaultValue);
		tableElement.appendChild(fieldElement);

		if (fieldAttrString.toUpperCase().indexOf("PRIMARY KEY", 0) > 0) {
			primaryKeyFieldID = fieldElement.getAttribute("ID");
		}
	}

	String getDataTypeID(String fieldAttrString) {
		org.w3c.dom.Element workElement, lastElement;
		org.w3c.dom.Node nextSiblingNode;
		NodeList elementList;
		int lastID = 0;
		String wrkStr;
		String sqlExpression = "";
		String typeName = "";
		String lengthAndDecimal = "";
		String length = "";
		String decimal = "";
		int validPosFrom = 0;
		int validPosThru = 0;
		int j =0;
		int m =0;
		int n =0;
		int checkCounter = 0;
		String dataTypeID = defaultDataTypeID;

		if (jCheckBoxDataTypeControl.isSelected()) {
			for (int i = 0; i < sqlDataTypeArray.length; i++) {
				j = fieldAttrString.indexOf(sqlDataTypeArray[i], 0);
				if (j >= 0) {
					//Get start position of value//
					validPosFrom = j+1;
					//Get end position of value//
					validPosThru = j+1;
					for (int k = j+1; k < fieldAttrString.length(); k++) {
						wrkStr = fieldAttrString.substring(k, k+1);
						if (wrkStr.equals(" ")) {
							wrkStr = fieldAttrString.substring(k-1, k);
							if (!wrkStr.equals(",")) {
								validPosThru = k;
								break;
							}
						}
						if (wrkStr.equals(")")) {
							validPosThru = k+1;
							break;
						}
						validPosThru = k;
					}
					//
					if (validPosFrom < validPosThru) {
						sqlExpression = fieldAttrString.substring(validPosFrom, validPosThru).replaceAll(" ", "");
						elementList = frame_.domDocument.getElementsByTagName("DataType");
						checkCounter = 0;
						for (int k = 0; k < elementList.getLength(); k++) {
							workElement = (org.w3c.dom.Element)elementList.item(k);
							if (workElement.getAttribute("SortKey").equals(sqlExpression)) {
								dataTypeID = workElement.getAttribute("ID");
								checkCounter++;
								break;
							}
						}
						if (checkCounter == 0) {
							//Setup length and decimal//
							length = "5";
							decimal = "0";
							typeName = sqlExpression;
							m = sqlExpression.indexOf("(", 0);
							if (m >= 0) {
								n = sqlExpression.indexOf(")", 0);
								if (n >= 0) {
									typeName = sqlExpression.substring(0, m);
									lengthAndDecimal = sqlExpression.substring(m+1, n);
									StringTokenizer workTokenizer = new StringTokenizer(lengthAndDecimal, "," );
									length = workTokenizer.nextToken();
									if (workTokenizer.countTokens() > 0) {
										decimal = workTokenizer.nextToken();
									}
								}
							}

							org.w3c.dom.Element newElement = frame_.domDocument.createElement("DataType");
							lastElement = getLastDomElementOfTheType("DataType");
							if (lastElement == null) {
								lastID = 0;
							} else {
								lastID = Integer.parseInt(lastElement.getAttribute("ID"));
							}
							newElement.setAttribute("ID", Integer.toString(lastID + 1));
							newElement.setAttribute("Name", typeName);
							newElement.setAttribute("BasicType", getBasicTypeFromTypeName(typeName));
							newElement.setAttribute("SortKey", sqlExpression);
							newElement.setAttribute("Length", length);
							newElement.setAttribute("Decimal", decimal);
							if (newElement.getAttribute("BasicType").equals("Date")) {
								newElement.setAttribute("Length", "8");
								if (newElement.getAttribute("Name").equals("TIME") || newElement.getAttribute("Name").equals("time")) {
									newElement.setAttribute("Length", "6");
								}
								if (newElement.getAttribute("Name").equals("DATETIME") || newElement.getAttribute("Name").equals("datetime")) {
									newElement.setAttribute("Length", "12");
								}
								if (newElement.getAttribute("Name").equals("TIMESTAMP") || newElement.getAttribute("Name").equals("timestamp")) {
									newElement.setAttribute("Length", "14");
								}
							}
							if (newElement.getAttribute("BasicType").equals("Boolean")) {
								newElement.setAttribute("Length", "1");
							}
							if (newElement.getAttribute("BasicType").equals("Object")) {
								newElement.setAttribute("Length", "256");
							}
							newElement.setAttribute("SQLExpression", sqlExpression);
							nextSiblingNode = lastElement.getNextSibling();
							systemElement.insertBefore(newElement, nextSiblingNode);
							dataTypeID = newElement.getAttribute("ID");
						}
					}

					break;
				}
			}
		}

		return dataTypeID;
	}

	String getBasicTypeFromTypeName(String typeName) {
		String basicType = "String";
		for (int j = 0; j < sqlDataTypeArray2.length; j++) {
			if (typeName.indexOf(sqlDataTypeArray2[j], 0) >= 0) {
				if (j >= 0 &&  j <= 15) {basicType = "SignedNumber";}
				if (j >= 20 &&  j <= 23) {basicType = "Date";}
				if (j >= 24 &&  j <= 25) {basicType = "Object";}
				if (j >= 30 &&  j <= 33) {basicType = "Boolean";}
				break;
			}
		}
		return basicType;
	}

	void createSecondaryKeyDefinition(org.w3c.dom.Element tableElement, String fieldAttrString) {
		org.w3c.dom.Element secondaryKeyElement = frame_.domDocument.createElement("TableKey");
		secondaryKeyElement.setAttribute("ID", getNextKeyIDOfTheTable(tableElement));
		secondaryKeyElement.setAttribute("Type", "SK");
		secondaryKeyElement.setAttribute("SortKey", "010");
		setKeyFieldOfTheKey(secondaryKeyElement, tableElement, fieldAttrString);
		tableElement.appendChild(secondaryKeyElement);
	}

	void setKeyFieldOfTheKey(org.w3c.dom.Element keyElement, org.w3c.dom.Element tableElement, String fieldNames) {
		org.w3c.dom.Element element;

		int i = fieldNames.indexOf("(", 0);
		if (i >= 0) {
			int j = fieldNames.indexOf(")", i);
			if (j < 0) {
				fieldNames = fieldNames.substring(i+1, fieldNames.length());
			} else {
				fieldNames = fieldNames.substring(i+1, j);
			}
		}

		NodeList fieldList = tableElement.getElementsByTagName("TableField");
		StringTokenizer workTokenizer = new StringTokenizer(fieldNames, "," );
		String fieldName = "";
		int sortKey = 0;
		int countOfField = workTokenizer.countTokens();
		for (int k = 1; k <= countOfField; k++) {
			fieldName = trimBlankFromValue(workTokenizer.nextToken());
			for (int j = 0; j < fieldList.getLength(); j++) {
				element = (org.w3c.dom.Element)fieldList.item(j);
				if (element.getAttribute("Alias").equals(fieldName)) {
					org.w3c.dom.Element keyFieldElement = frame_.domDocument.createElement("TableKeyField");
					keyFieldElement.setAttribute("FieldID", element.getAttribute("ID"));
					sortKey++;
					keyFieldElement.setAttribute("SortKey", getFormatted3ByteString(sortKey) + "0");
					keyElement.appendChild(keyFieldElement);
					break;
				}
			}
		}
	}

	void createTableRelationship(org.w3c.dom.Element tableElement, String tableAttributes) {
		org.w3c.dom.Element workElement;
		String[] fieldArray = new String[1000];
		int lastID = 0;
		String wrkStr1 = "";
		String wrkStr2 = "";

		///////////////////////////////////
		//Substring attributes into array//
		///////////////////////////////////
		int itemsOfArray = -1;
		int i = 0;
		int j = 0;
		int bracketOpen = 0;
		int bracketClose = 0;
		while (j >= 0) {
			j = tableAttributes.indexOf(",", i);
			if (j >= 0) {
				wrkStr2 = wrkStr2 + tableAttributes.substring(i, j+1);
				//
				bracketOpen = 0;
				bracketClose = 0;
				for (int p = 0; p < wrkStr2.length(); p++) {
					wrkStr1 = wrkStr2.substring(p,p+1);
					if (wrkStr1.equals("(")) {
						bracketOpen++;
					}
					if (wrkStr1.equals(")")) {
						bracketClose++;
					}
				}
				if (bracketOpen == bracketClose) {
					itemsOfArray++;
					fieldArray[itemsOfArray] = wrkStr2;
					wrkStr2 = "";
				}
				i = j+1;
			} else {
				itemsOfArray++;
				fieldArray[itemsOfArray] = wrkStr2 + tableAttributes.substring(i, tableAttributes.length());
			}
		}

		//////////////////////
		//Create Foreign Key//
		//////////////////////
		int pos1 = 0;
		int pos2 = 0;
		int pos3 = 0;
		int pos4 = 0;
		int pos5 = 0;
		int pos6 = 0;
		String table1ID = "";
		String tableKey1ID = "";
		String tableKey1Type = "";
		int numberOfFieldsOfKey1 = 0;
		String table2ID = "";
		String tableKey2ID = "";
		String tableKey2Type = "";
		int numberOfFieldsOfKey2 = 0;
		String relationshipType = "";

		for (i = 0; i <= itemsOfArray; i++) {
			try {
				pos1 = fieldArray[i].indexOf("FOREIGN KEY", 0);
				pos2 = fieldArray[i].indexOf("(", pos1 + 10);
				pos3 = fieldArray[i].indexOf(")", pos2 + 1);
				pos4 = fieldArray[i].indexOf("REFERENCES", pos3 + 1);
				pos5 = fieldArray[i].indexOf("(", pos4 + 10);
				pos6 = fieldArray[i].indexOf(")", pos5 + 1);

				if (pos1 >= 0 && pos2 >= 0 && pos3 >= 0 && pos4 >= 0 && pos5 >= 0 && pos6 >= 0) {

					table2ID = tableElement.getAttribute("ID");

					workElement = createForeignKeyDefinition(tableElement, fieldArray[i].substring(pos2+1, pos3));
					if (workElement != null) {
						tableKey2ID = workElement.getAttribute("ID");
						tableKey2Type = workElement.getAttribute("Type");
						numberOfFieldsOfKey2 = workElement.getElementsByTagName("TableKeyField").getLength();

						workElement = getTableElementWithTableName(fieldArray[i].substring(pos4+10, pos5));
						if (workElement != null) {
							table1ID = workElement.getAttribute("ID");

							workElement = getUniqueKeyElementWithFieldNames(workElement, fieldArray[i].substring(pos5+1, pos6));
							if (workElement != null) {
								tableKey1ID = workElement.getAttribute("ID");
								tableKey1Type = workElement.getAttribute("Type");
								numberOfFieldsOfKey1 = workElement.getElementsByTagName("TableKeyField").getLength();

								if (tableKey1Type.equals("PK") || tableKey1Type.equals("SK")) {

									///////////////////////////////
									//Create Relationship Element//
									///////////////////////////////
									relationshipType = "";
									if (tableKey2Type.equals("PK") || tableKey2Type.equals("SK")) {
										if (numberOfFieldsOfKey1 == numberOfFieldsOfKey2) {
											relationshipType = "SUBTYPE";
										}
										if (numberOfFieldsOfKey1 < numberOfFieldsOfKey2) {
											relationshipType = "FAMILY";
										}
									}
									if (tableKey2Type.equals("FK")) {
										if (numberOfFieldsOfKey1 == numberOfFieldsOfKey2) {
											relationshipType = "REFFER";
										}
									}

									if (!relationshipType.equals("")) {
										org.w3c.dom.Element newElement1 = frame_.domDocument.createElement("Relationship");
										org.w3c.dom.Element lastElement = getLastDomElementOfTheType("Relationship");
										if (lastElement == null) {
											lastID = 0;
										} else {
											lastID = Integer.parseInt(lastElement.getAttribute("ID"));
										}
										newElement1.setAttribute("ID", Integer.toString(lastID + 1));
										newElement1.setAttribute("Table1ID", table1ID);
										newElement1.setAttribute("Table2ID", table2ID);
										newElement1.setAttribute("TableKey1ID", tableKey1ID);
										newElement1.setAttribute("TableKey2ID", tableKey2ID);
										newElement1.setAttribute("Type", relationshipType);
										newElement1.setAttribute("ExistWhen1", "");
										newElement1.setAttribute("ExistWhen2", "");
										systemElement.appendChild(newElement1);

										////////////////////////////////////////
										//Create SubsystemRelationship Element//
										////////////////////////////////////////
										org.w3c.dom.Element newElement2 = frame_.domDocument.createElement("SubsystemRelationship");
										newElement2.setAttribute("RelationshipID", newElement1.getAttribute("ID"));
										newElement2.setAttribute("TerminalIndex1", "17");
										newElement2.setAttribute("TerminalIndex2", "20");
										newElement2.setAttribute("ShowOnModel", "true");
										subsystemElement.appendChild(newElement2);

										numberOfTableRelationshipsCreated++;
									}
								}
							}
						}
					}
				}
			}
			catch (Exception ex) {
			}
		}
	}

	org.w3c.dom.Element createForeignKeyDefinition(org.w3c.dom.Element tableElement, String fieldNames) {
		org.w3c.dom.Element foreignKeyElement = null;
		org.w3c.dom.Element element1, element2;
		int index = 0;
		String[] fieldIDArray = new String[50];
		String wrkStr;

		//////////////////////////
		//trim brackets of string//
		//////////////////////////
		int i = fieldNames.indexOf("(", 0);
		if (i >= 0) {
			int j = fieldNames.indexOf(")", i);
			fieldNames = fieldNames.substring(i+1, j);
		}

		///////////////////////////////////////////
		//Setup fieldID array of this foreign key//
		///////////////////////////////////////////
		NodeList fieldList = tableElement.getElementsByTagName("TableField");
		StringTokenizer workTokenizer = new StringTokenizer(fieldNames, "," );
		String fieldName = "";
		int countOfField = workTokenizer.countTokens();
		for (int k = 1; k <= countOfField; k++) {
			fieldName = trimBlankFromValue(workTokenizer.nextToken());
			for (int j = 0; j < fieldList.getLength(); j++) {
				element1 = (org.w3c.dom.Element)fieldList.item(j);
				if (element1.getAttribute("Name").equals(fieldName)) {
					fieldIDArray[index] = element1.getAttribute("ID");
					index++;
					break;
				}
			}
		}

		////////////////////////////////////////////////
		//search corresponding PK(or SK) in this table//
		////////////////////////////////////////////////
		int countWork = 0;
		NodeList keyFieldList = null;
		NodeList keyList = tableElement.getElementsByTagName("TableKey");
		for (int k = 0; k < keyList.getLength(); k++) {
			element1 = (org.w3c.dom.Element)keyList.item(k);
			if (element1.getAttribute("Type").equals("PK") || element1.getAttribute("Type").equals("SK")) {
				countWork = 0;
				keyFieldList = element1.getElementsByTagName("TableKeyField");
				for (int j = 0; j < keyFieldList.getLength(); j++) {
					element2 = (org.w3c.dom.Element)keyFieldList.item(j);
					wrkStr = element2.getAttribute("FieldID");
					for (int m = 0; m < index; m++) {
						if (fieldIDArray[m].equals(wrkStr)) {
							countWork++;
						}
					}
				}
				if (keyFieldList.getLength() >= countWork && countWork > 0) {
					foreignKeyElement = element1;
					break;
				}
			}
		}

		if (foreignKeyElement == null) {
			foreignKeyElement = frame_.domDocument.createElement("TableKey");
			foreignKeyElement.setAttribute("ID", getNextKeyIDOfTheTable(tableElement));
			foreignKeyElement.setAttribute("Type", "FK");
			foreignKeyElement.setAttribute("SortKey", "010");
			setKeyFieldOfTheKey(foreignKeyElement, tableElement, fieldNames);
			tableElement.appendChild(foreignKeyElement);
		}

		return foreignKeyElement;
	}

	org.w3c.dom.Element getUniqueKeyElementWithFieldNames(org.w3c.dom.Element tableElement, String fieldNames) {
		org.w3c.dom.Element keyElement = null;
		org.w3c.dom.Element element1, element2;
		int index = 0;
		String[] fieldIDArray = new String[50];
		String wrkStr;

		///////////////////////////////////
		//trim brackets of fieldAttrString//
		///////////////////////////////////
		int i = fieldNames.indexOf("(", 0);
		if (i >= 0) {
			int j = fieldNames.indexOf(")", i);
			fieldNames = fieldNames.substring(i+1, j);
		}

		///////////////////////////////////
		//Setup fieldID array of this key//
		///////////////////////////////////
		NodeList fieldList = tableElement.getElementsByTagName("TableField");
		StringTokenizer workTokenizer = new StringTokenizer(fieldNames, "," );
		String fieldName = "";
		int countOfField = workTokenizer.countTokens();
		for (int k = 1; k <= countOfField; k++) {
			fieldName = trimBlankFromValue(workTokenizer.nextToken());
			for (int j = 0; j < fieldList.getLength(); j++) {
				element1 = (org.w3c.dom.Element)fieldList.item(j);
				if (element1.getAttribute("Name").equals(fieldName)) {
					fieldIDArray[index] = element1.getAttribute("ID");
					index++;
					break;
				}
			}
		}

		////////////////////////////////////////////////
		//search corresponding PK(or SK) in this table//
		////////////////////////////////////////////////
		int countWork = 0;
		NodeList keyFieldList = null;
		NodeList keyList = tableElement.getElementsByTagName("TableKey");
		for (int k = 0; k < keyList.getLength(); k++) {
			element1 = (org.w3c.dom.Element)keyList.item(k);
			if (element1.getAttribute("Type").equals("PK") || element1.getAttribute("Type").equals("SK")) {
				countWork = 0;
				keyFieldList = element1.getElementsByTagName("TableKeyField");
				for (int j = 0; j < keyFieldList.getLength(); j++) {
					element2 = (org.w3c.dom.Element)keyFieldList.item(j);
					wrkStr = element2.getAttribute("FieldID");
					for (int m = 0; m < index; m++) {
						if (fieldIDArray[m].equals(wrkStr)) {
							countWork++;
						}
					}
				}
				if (keyFieldList.getLength() == countWork) {
					keyElement = element1;
					break;
				}
			}
		}

		return keyElement;
	}

	org.w3c.dom.Element getTableElementWithTableName(String name) {
		org.w3c.dom.Element keyElement = null;
		String trimmedName = trimBlankFromValue(name);
		for (int i = 0; i <= itemsOfArray; i++) {
			if (nameArray[i].equals(trimmedName)) {
				keyElement = tableElementArray[i];
			}
		}
		return keyElement;
	}

	String trimBlankFromValue(String value) {
		int namePosFrom = -1;
		int namePosThru = -1;
		String wrkStr;
		String trimmedValue = "";

		for (int i = 0; i < value.length(); i++) {
			wrkStr = value.substring(i, i+1);
			if (!wrkStr.equals(" ") && namePosFrom == -1) {
				namePosFrom = i;
			}
			if (wrkStr.equals(" ") && namePosFrom != -1 && namePosThru == -1) {
				namePosThru = i;
				break;
			}
		}
		if (namePosThru == -1) {
			namePosThru = value.length();
		}

		if (namePosFrom < namePosThru) {
			trimmedValue = value.substring(namePosFrom, namePosThru);
		}

		return trimmedValue;
	}

	String getFormatted3ByteString(int number) {
		String formattedNumberString = "999";
		String numberString = Integer.toString(number);
		if (0 <= number && number < 10) {formattedNumberString = "00" + numberString;}
		if (10 <= number && number < 100) {formattedNumberString = "0" + numberString;}
		if (100 <= number && number < 1000) {formattedNumberString = numberString;}
		return formattedNumberString;
	}

	org.w3c.dom.Element getLastDomElementOfTheType(String tagName) {
		org.w3c.dom.Element element = null;
		org.w3c.dom.Element lastDomElement = null;
		int lastDomElementID = 0;
		int elementID = 0;
		NodeList nodeList = frame_.domDocument.getElementsByTagName(tagName);
		for (int i = 0; i < nodeList.getLength(); i++) {
			element = (org.w3c.dom.Element)nodeList.item(i);
			if (lastDomElement == null) {
				lastDomElement = element;
			} else {
				elementID = Integer.parseInt(element.getAttribute("ID"));
				lastDomElementID = Integer.parseInt(lastDomElement.getAttribute("ID"));
				if (elementID > lastDomElementID) {
					lastDomElement = element;
				}
			}
		}
		return lastDomElement;
	}

	String getNextKeyIDOfTheTable(org.w3c.dom.Element tableElement) {
		org.w3c.dom.Element element = null;
		int workElementID = 0;
		int elementID = 0;
		NodeList nodeList = tableElement.getElementsByTagName("TableKey");
		for (int i = 0; i < nodeList.getLength(); i++) {
			element = (org.w3c.dom.Element)nodeList.item(i);
			if (elementID == 0) {
				elementID = Integer.parseInt(element.getAttribute("ID"));
			} else {
				workElementID = Integer.parseInt(element.getAttribute("ID"));
				if (workElementID > elementID) {
					elementID = workElementID;
				}
			}
		}
		return Integer.toString(elementID + 1);
	}

	/**
	 * Class of Xead Tree Node
	 */
	class XeadNode implements Comparable {
		private String nodeType_;
		private org.w3c.dom.Element domNode_;
		public XeadNode(String type, org.w3c.dom.Element node) {
			super();
			nodeType_ = type;
			domNode_ = node;
		}
		public String toString() {
			String str = "";
			str = this.getName();
			return str;
		}
		public String getName() {
			String str = "";
			if (nodeType_.equals("Subsystem")) {
				str = domNode_.getAttribute("SortKey") + " " + domNode_.getAttribute("Name");
			}
			return str;
		}
		public org.w3c.dom.Element getElement() {
			return domNode_;
		}
        public int compareTo(Object other) {
            XeadNode otherNode = (XeadNode)other;
            return domNode_.getAttribute("SortKey").compareTo(otherNode.getElement().getAttribute("SortKey"));
        }
	}

	/**
	 * Class of ComboBox-model to sort elements by its "SortKey"
	 */
	class SortableXeadNodeComboBoxModel extends DefaultComboBoxModel {
		private static final long serialVersionUID = 1L;
		public void sortElements() {
//			TreeSet<XeadNode> treeSet = new TreeSet<XeadNode>(new NodeComparator());
//			int elementCount = this.getSize();
//			XeadNode node;
//			for (int i = 0; i < elementCount; i++) {
//				node = (XeadNode)this.getElementAt(i);
//				treeSet.add(node);
//			}
//			this.removeAllElements();
//			Iterator<XeadNode> it = treeSet.iterator();
//			while( it.hasNext() ){
//				node = (XeadNode)it.next();
//				this.addElement(node);
//			}
			ArrayList<XeadNode> list = new ArrayList<XeadNode>();
			for (int i = 0; i < this.getSize(); i++) {
				list.add((XeadNode)this.getElementAt(i));
			}
			this.removeAllElements();
			Collections.sort(list);
			Iterator<XeadNode> it = list.iterator();
			while(it.hasNext()){
				this.addElement(it.next());
			}
		}
	}

//	/**
//	 * Class of Node Comparator
//	 */
//	class NodeComparator implements java.util.Comparator<XeadNode> {
//		public int compare(XeadNode node1, XeadNode node2) {
//			String value1, value2;
//			value1 = node1.getElement().getAttribute("SortKey");
//			value2 = node2.getElement().getAttribute("SortKey");
//			int compareResult = value1.compareTo(value2);
//			if (compareResult == 0) {
//				value1 = node1.getElement().getAttribute("ID");
//				value2 = node2.getElement().getAttribute("ID");
//				compareResult = value1.compareTo(value2);
//				if (compareResult == 0) {
//					compareResult = 1;
//				}
//			}
//			return(compareResult);
//		}
//	}
}

class DialogImportSQL_jCheckBoxShowControl_changeAdapter implements ChangeListener {
	DialogImportSQL adaptee;

	DialogImportSQL_jCheckBoxShowControl_changeAdapter(DialogImportSQL adaptee) {
		this.adaptee = adaptee;
	}
	public void stateChanged(ChangeEvent e) {
		adaptee.jCheckBoxShowControl_stateChanged();
	}
}

class DialogImportSQL_jComboBoxSubsystem_actionAdapter implements java.awt.event.ActionListener {
	DialogImportSQL adaptee;

	DialogImportSQL_jComboBoxSubsystem_actionAdapter(DialogImportSQL adaptee) {
		this.adaptee = adaptee;
	}
	public void actionPerformed(ActionEvent e) {
		adaptee.jComboBoxSubsystem_actionPerformed(e);
	}
}
class DialogImportSQL_jButtonStart_actionAdapter implements java.awt.event.ActionListener {
	DialogImportSQL adaptee;

	DialogImportSQL_jButtonStart_actionAdapter(DialogImportSQL adaptee) {
		this.adaptee = adaptee;
	}
	public void actionPerformed(ActionEvent e) {
		adaptee.jButtonStart_actionPerformed(e);
	}
}

class DialogImportSQL_jButtonClose_actionAdapter implements java.awt.event.ActionListener {
	DialogImportSQL adaptee;

	DialogImportSQL_jButtonClose_actionAdapter(DialogImportSQL adaptee) {
		this.adaptee = adaptee;
	}
	public void actionPerformed(ActionEvent e) {
		adaptee.jButtonClose_actionPerformed(e);
	}
}


text:
from random import randint, choice

class Walk(object):
    def __init__(self, name):
        self.name = name
        self.steps = randint(0,9)

    def __str__(self):
        return "<Walk: %s (%s)>" % (self.name, self.steps)

    def __repr__(self):
        return "<Walk: %s (%s)>" % (self.name, self.steps)

    def move(self):
        actions = ['shamble', 'stagger', 'roll', 'crawl', 'stumble']
        print " ".join([choice(actions) for x in range(self.steps)])

redpajama_set_name: RedPajamaGithub


text:
Affix

The subnavigation on the right is a live demo of the affix plugin.

		To move your affix block inside some parent, just add position: relative to that parent.

document.querySelector("#affix-el").affix({ offset: -25 })

Properties

			Name
			Default
			Description

			spy
			@el.getAttribute('data-spy') or 'affix'

				Set type of spying

			offset
			@el.getAttribute( 'data-offset' ) or 5

				In px. Affix's block offset from top.

Methods

			Method
			Description

			start

Activate affix

			stop

Deativate affix

Events

	Inside each event function of affix element use @ or this in js. Class instance always stores in data attribute of the affix element @data['kitAffix'] or this.data['kitAffix'] in js.

			Event
			Description

			beforeactive

Set a function to call it before start affix. If it returns deferred.promise(), then affix will not start till deferred.resolve(), and woun't start at all if deferred.reject(). You can just get data with ajax for your affix block.

el.affix
	beforeactive: ->
		d = $.Deferred()

		console.log @
		# The affix DOM element will be in the log

		console.log @data['kitAffix']
		# The instance of Affix class will in log

		# Do something here before start affix
		# in this case it will start after 2 seconds
		setTimeout ->
			d.resolve()
		, 2000
		# End of your code

		d.promise()

			onactive

Set a function to call it after affix started.

			failactive

Set a function to call it if starting failed.

			beforedeactive

Call this function before affix stopped.

			ondeactive

Call this function after affix stopped.

			faildeactive

Set a function to call it if stopping failed.


text:
local CALSSSET = {}
CALSSSET.Classes =
{
	COREOBJ = "obj/coreobj.lua",
}

function CALSSSET.LoadAllClass()
	for k, v in pairs(CALSSSET.Classes) do
		CALSSSET[k] = Import(CONST_PATH .. v)
		assert(CALSSSET[k], string.format("Error : Read (%s) File Error !!! ", v))
	end
end

CALSSSET.LoadAllClass()

return CALSSSET


text:
.select-element, .select-element:after, .select-element:before, .select-element *, .select-element *:after, .select-element *:before {
  -webkit-box-sizing: border-box;
  -moz-box-sizing: border-box;
  box-sizing: border-box; }

.select-element {
  position: absolute;
  display: none; }
  .select-element.select-open {
    display: block; }

.select-theme-chosen {
  font-family: "Helvetica Neue", sans-serif;
  font-size: 13px; }
  .select-theme-chosen, .select-theme-chosen *, .select-theme-chosen *:after, .select-theme-chosen *:before {
    -webkit-box-sizing: border-box;
    -moz-box-sizing: border-box;
    box-sizing: border-box; }

.select.select-theme-chosen .select-content {
  -webkit-border-radius: 5px;
  -moz-border-radius: 5px;
  -ms-border-radius: 5px;
  -o-border-radius: 5px;
  border-radius: 5px;
  -webkit-box-shadow: 0 0 0 1px rgba(0, 0, 0, 0.1), 0 2px 8px rgba(0, 0, 0, 0.2);
  -moz-box-shadow: 0 0 0 1px rgba(0, 0, 0, 0.1), 0 2px 8px rgba(0, 0, 0, 0.2);
  box-shadow: 0 0 0 1px rgba(0, 0, 0, 0.1), 0 2px 8px rgba(0, 0, 0, 0.2);
  background: white;
  color: #444444;
  overflow: auto;
  max-width: 248px;
  max-height: 248px; }
  @media (max-width: 372px), (max-height: 372px) {
    .select.select-theme-chosen .select-content {
      max-width: 155px;
      max-height: 155px; } }
.select.select-theme-chosen .select-options {
  -webkit-tap-highlight-color: rgba(0, 0, 0, 0);
  -webkit-touch-callout: none;
  margin: 0;
  padding: 0; }
  .select.select-theme-chosen .select-options .select-option {
    -webkit-tap-highlight-color: rgba(0, 0, 0, 0);
    -webkit-touch-callout: none;
    position: relative;
    list-style: none;
    margin: 0;
    line-height: 19px;
    padding: 6px 11px 6px 30px;
    display: block;
    cursor: pointer;
    white-space: nowrap;
    overflow: hidden;
    text-overflow: ellipsis; }
    .select.select-theme-chosen .select-options .select-option.select-option-selected:before {
      content: url("data:image/svg+xml;utf8,<svg xmlns='http://www.w3.org/2000/svg' width='100%' height='100%' viewBox='-0.5 0 20 15'><rect fill='#444444' stroke='none' transform='rotate(45 4.0033 8.87436)' height='5' width='6.32304' y='6.37436' x='0.84178'></rect><rect fill='#444444' stroke='none' transform='rotate(45 11.1776 7.7066)' width='5' height='16.79756' y='-0.69218' x='8.67764'></rect></svg>");
      position: absolute;
      left: 13px;
      top: 0;
      top: 5px;
      height: 11px;
      width: 11px;
      margin: auto; }
    .select.select-theme-chosen .select-options .select-option:hover, .select.select-theme-chosen .select-options .select-option.select-option-highlight {
      background-image: -webkit-gradient(linear, 50% 0%, 50% 100%, color-stop(20%, #3875d7), color-stop(90%, #2a62bc));
      background-image: -webkit-linear-gradient(#3875d7 20%, #2a62bc 90%);
      background-image: -moz-linear-gradient(#3875d7 20%, #2a62bc 90%);
      background-image: -o-linear-gradient(#3875d7 20%, #2a62bc 90%);
      background-image: linear-gradient(#3875d7 20%, #2a62bc 90%);
      background-color: #3875d7;
      color: white; }
      .select.select-theme-chosen .select-options .select-option:hover.select-option-selected:before, .select.select-theme-chosen .select-options .select-option.select-option-highlight.select-option-selected:before {
        content: url("data:image/svg+xml;utf8,<svg xmlns='http://www.w3.org/2000/svg' width='100%' height='100%' viewBox='-0.5 0 20 15'><rect fill='white' stroke='none' transform='rotate(45 4.0033 8.87436)' height='5' width='6.32304' y='6.37436' x='0.84178'></rect><rect fill='white' stroke='none' transform='rotate(45 11.1776 7.7066)' width='5' height='16.79756' y='-0.69218' x='8.67764'></rect></svg>"); }
    .select.select-theme-chosen .select-options .select-option:first-child {
      -webkit-border-radius: 5px 5px 0 0;
      -moz-border-radius: 5px 5px 0 0;
      -ms-border-radius: 5px 5px 0 0;
      -o-border-radius: 5px 5px 0 0;
      border-radius: 5px 5px 0 0; }
    .select.select-theme-chosen .select-options .select-option:last-child {
      -webkit-border-radius: 0 0 5px 5px;
      -moz-border-radius: 0 0 5px 5px;
      -ms-border-radius: 0 0 5px 5px;
      -o-border-radius: 0 0 5px 5px;
      border-radius: 0 0 5px 5px; }

.select-target.select-theme-chosen {
  display: -moz-inline-stack;
  display: inline-block;
  vertical-align: middle;
  *vertical-align: auto;
  zoom: 1;
  *display: inline;
  -webkit-border-radius: 5px;
  -moz-border-radius: 5px;
  -ms-border-radius: 5px;
  -o-border-radius: 5px;
  border-radius: 5px;
  -webkit-user-select: none;
  -moz-user-select: none;
  -ms-user-select: none;
  -o-user-select: none;
  user-select: none;
  -webkit-tap-highlight-color: rgba(0, 0, 0, 0);
  -webkit-touch-callout: none;
  -webkit-box-shadow: 0 0 3px white inset, 0 1px 1px rgba(0, 0, 0, 0.1);
  -moz-box-shadow: 0 0 3px white inset, 0 1px 1px rgba(0, 0, 0, 0.1);
  box-shadow: 0 0 3px white inset, 0 1px 1px rgba(0, 0, 0, 0.1);
  background-image: -webkit-gradient(linear, 50% 0%, 50% 100%, color-stop(20%, #ffffff), color-stop(50%, #f6f6f6), color-stop(52%, #eeeeee), color-stop(100%, #f4f4f4));
  background-image: -webkit-linear-gradient(top, #ffffff 20%, #f6f6f6 50%, #eeeeee 52%, #f4f4f4 100%);
  background-image: -moz-linear-gradient(top, #ffffff 20%, #f6f6f6 50%, #eeeeee 52%, #f4f4f4 100%);
  background-image: -o-linear-gradient(top, #ffffff 20%, #f6f6f6 50%, #eeeeee 52%, #f4f4f4 100%);
  background-image: linear-gradient(top, #ffffff 20%, #f6f6f6 50%, #eeeeee 52%, #f4f4f4 100%);
  position: relative;
  padding: 3px 30px 2px 11px;
  background: #f6f6f6;
  border: 1px solid #aaaaaa;
  cursor: pointer;
  color: #444444;
  text-decoration: none;
  white-space: nowrap;
  max-width: 100%;
  overflow: hidden;
  text-overflow: ellipsis;
  line-height: 24px; }
  .select-target.select-theme-chosen.select-target-focused, .select-target.select-theme-chosen.select-target-focused:focus {
    border-color: #5897fb;
    outline: none; }
  .select-target.select-theme-chosen b {
    position: absolute;
    right: 13px;
    top: 0;
    bottom: 1px;
    margin: auto;
    height: 16px;
    width: 26px; }
    .select-target.select-theme-chosen b:before, .select-target.select-theme-chosen b:after {
      content: "";
      display: block;
      position: absolute;
      margin: auto;
      right: 0;
      height: 0;
      width: 0;
      border: 3px solid transparent; }
    .select-target.select-theme-chosen b:before {
      top: 0;
      border-bottom-color: inherit; }
    .select-target.select-theme-chosen b:after {
      bottom: 0;
      border-top-color: inherit; }


text:
FROM debian:wheezy
MAINTAINER  Adam Greene <adam.greene@gmail.com>

ENV CONFD_VERSION 0.6.3

RUN echo "deb http://cdn.debian.net/debian wheezy-backports main" >> /etc/apt/sources.list

# Install Haproxy.
# 		sed -i 's/^ENABLED=.*/ENABLED=1/' /etc/default/haproxy && \
RUN apt-get update -y && \
	apt-get install -y -q --no-install-recommends \
		haproxy -t wheezy-backports && \
	apt-get clean && \
	rm -rf /var/lib/apt/lists/*

# Install confd.  TODO: use a released confd when 0.7 is released
# ADD https://github.com/kelseyhightower/confd/releases/download/v${CONFD_VERSION}/confd-${CONFD_VERSION}-linux-amd64 /usr/local/bin/confd
# RUN echo 'e3edd9667b98ea32ae504bb7987bb0a269479267  /usr/local/bin/confd' > /tmp/confd.sha1 && \
# 	sha1sum --check /tmp/confd.sha1 && \
# 	rm /tmp/* && \
# 	chmod +x /usr/local/bin/confd

ADD confd-custom-linux-amd64 /usr/local/bin/confd
RUN chmod +x /usr/local/bin/confd
ADD haproxy_configuration.toml /etc/confd/conf.d/haproxy_configuration.toml
ADD haproxy.tmpl /etc/confd/templates/haproxy.tmpl
#RUN chown -R daemon:daemon /etc/haproxy /var/lib/haproxy

# install Python
RUN apt-get update -y && \
	apt-get install -y -q --no-install-recommends \
		python2.7-minimal \
		python-pip \
		openssl && \
	apt-get clean && \
	rm -rf /var/lib/apt/lists/*

RUN /usr/bin/pip -q install requests boto3

ADD service-toolkit /usr/local/bin/service-toolkit
RUN chmod +x /usr/local/bin/service-toolkit

#USER daemon

ENTRYPOINT ["/usr/local/bin/service-toolkit"]
CMD        ["--help"]


text:
package org.apache.orc;

import org.junit.Test;

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

import static junit.framework.Assert.assertEquals;
import static junit.framework.Assert.fail;

public class TestCorruptTypes {

  @Test
  public void testIllType() {
    testCorruptHelper(OrcProto.Type.Kind.LIST, 0,
            "LIST type should contain exactly one subtype but has 0");
    testCorruptHelper(OrcProto.Type.Kind.LIST, 2,
            "LIST type should contain exactly one subtype but has 2");
    testCorruptHelper(OrcProto.Type.Kind.MAP, 1,
            "MAP type should contain exactly two subtypes but has 1");
    testCorruptHelper(OrcProto.Type.Kind.MAP, 3,
            "MAP type should contain exactly two subtypes but has 3");
    testCorruptHelper(OrcProto.Type.Kind.UNION, 0,
            "UNION type should contain at least one subtype but has none");
  }

  private void testCorruptHelper(OrcProto.Type.Kind type,
                                 int subTypesCnt,
                                 String errMsg) {

    List<OrcProto.Type> types = new ArrayList<OrcProto.Type>();
    OrcProto.Type.Builder builder = OrcProto.Type.newBuilder().setKind(type);
    for (int i = 0; i < subTypesCnt; ++i) {
      builder.addSubtypes(i + 2);
    }
    types.add(builder.build());
    try {
      OrcUtils.convertTypeFromProtobuf(types, 0);
      fail("Should throw FileFormatException for ill types");
    } catch (FileFormatException e) {
      assertEquals(errMsg, e.getMessage());
    } catch (Throwable e) {
      fail("Should only trow FileFormatException for ill types");
    }
  }
}


text:
import ast
import logging

from .func_resolver import Library
from ..tasks import TaskManager
from .context import Context
from .provenance import BioProv

logging.basicConfig(level=logging.DEBUG)

class Interpreter:
    '''
    The interpreter for PhenoWL DSL
    '''
    def __init__(self):
        self.context = Context()
        self.line = 0

    def get_args(self, expr):
        v = []
        for e in expr:
            v.append(self.eval(e))
        return v

    def dofunc(self, expr):
        '''
        Execute func expression.
        :param expr:
        '''
        function = expr[0] if len(expr) < 3 else expr[1]
        package = expr[0][:-1] if len(expr) > 2 else None

        params = expr[1] if len(expr) < 3 else expr[2]
        v = self.get_args(params)

        # call task if exists
        if package is None and function in self.context.library.tasks:
            return self.context.library.run_task(function, v, self.dotaskstmt)

        if not self.context.library.check_function(function, package):
            raise Exception(r"'{0}' doesn't exist.".format(function))

        return self.context.library.call_func(self.context, package, function, v)

    def dorelexpr(self, expr):
        '''
        Executes relative expression.
        :param expr:
        '''
        left = self.eval(expr[0])
        right = self.eval(expr[2])
        operator = expr[1]
        if operator == '<':
            return left < right
        elif operator == '>':
            return left > right
        elif operator == '<=':
            return left <= right
        elif operator == '>=':
            return left >= right
        else:
            return left == right

    def doand(self, expr):
        '''
        Executes "and" expression.
        :param expr:
        '''
        if not expr:
            return True
        right = self.eval(expr[-1])
        if len(expr) == 1:
            return right
        left = expr[:-2]
        if len(left) > 1:
            left = ['ANDEXPR'] + left
        left = self.eval(left)
        return left and right

    def dopar(self, expr):
        taskManager = TaskManager()
        for stmt in expr:
            taskManager.submit_func(self.dopar_stmt, stmt)
        taskManager.wait();

    def dopar_stmt(self, expr):
        '''
        Execute a for expression.
        :param expr:
        '''
        self.run_multstmt(lambda: self.eval(expr))

    def run_multstmt(self, f):
        local_symtab = self.context.append_local_symtab()
        try:
            f()
        finally:
            self.context.pop_local_symtab()

    def dolog(self, expr):
        '''
        Executes a logical expression.
        :param expr:
        '''
        right = self.eval(expr[-1])
        if len(expr) == 1:
            return right
        left = expr[:-2]
        if len(left) > 1:
            left = ['LOGEXPR'] + left
        left = self.eval(left)
        return left or right

    def domult(self, expr):
        '''
        Executes a multiplication/division operation
        :param expr:
        '''
        right = self.eval(expr[-1])
        if len(expr) == 1:
            return right
        left = expr[:-2]
        if len(left) > 1:
            left = ['MULTEXPR'] + left
        left = self.eval(left)
        return left / right if expr[-2] == '/' else left * right

    def doarithmetic(self, expr):
        '''
        Executes arithmetic operation.
        :param expr:
        '''
        right = self.eval(expr[-1])
        if len(expr) == 1:
            return right
        left = expr[:-2]
        if len(left) > 1:
            left = ['NUMEXPR'] + left
        left = self.eval(left)
        return left + right if expr[-2] == '+' else left - right

    def doif(self, expr):
        '''
        Executes if statement.
        :param expr:
        '''
        cond = self.eval(expr[0])
        if cond:
            self.eval(expr[1])
        elif len(expr) > 3 and expr[3]:
            self.eval(expr[3])

    def dolock(self, expr):
        if not self.context.symtab.var_exists(expr[0]) or not isinstance(self.context.symtab.get_var(expr[0]), _thread.RLock):
            self.context.symtab.add_var(expr[0], threading.RLock())
        with self.context.symtab.get_var(expr[0]):
            self.eval(expr[1])
        pass

    def doassign(self, left, right):
        '''
        Evaluates an assignment expression.
        :param expr:
        '''
        if len(left) == 1:
            self.context.add_var(left[0], self.eval(right))
        elif left[0] == 'LISTIDX':
            left = left[1]
            idx = self.eval(left[1])
            if self.context.var_exists(left[0]):
                v = self.context.get_var(left[0])
                if isinstance(v, list):
                    while len(v) <= idx:
                        v.append(None)
                    v[int(idx)] = self.eval(right)
                elif isinstance(v, dict):
                    v[idx] = self.eval(right)
                else:
                    raise ValueError("Not a list or dictionary")
            else:
                v = []
                while len(v) <= idx:
                    v.append(None)
                v[int(idx)] = self.eval(right)
                self.context.add_var(left[0], v)

    def dofor(self, expr):
        '''
        Execute a for expression.
        :param expr:
        '''
        self.context.add_var(expr[0], None)
        for var in self.eval(expr[1]):
            self.context.update_var(expr[0], var)
            self.eval(expr[2])

    def eval_value(self, str_value):
        '''
        Evaluate a single expression for value.
        :param str_value:
        '''
        try:
            t = ast.literal_eval(str_value)
            if type(t) in [int, float, bool, complex]:
                if t in set((True, False)):
                    bool(str_value)
                if type(t) is int:
                    return int(str_value)
                if type(t) is float:
                    return float(t)
                if type(t) is complex:
                    return complex(t)
            else:
                if len(str_value) > 1:
                    if (str_value.startswith("'") and str_value.endswith("'")) or (str_value.startswith('"') and str_value.endswith('"')):
                        return str_value[1:-1]
            return str_value
        except ValueError:
            if self.context.var_exists(str_value):
                return self.context.get_var(str_value)
            return str_value

    def dolist(self, expr):
        '''
        Executes a list operation.
        :param expr:
        '''
        v = []
        for e in expr:
            v.append(self.eval(e))
        return v

    def remove_single_item_list(self, expr):
        if not isinstance(expr, list):
            return expr
        if len(expr) == 1:
            return self.remove_single_item_list(expr[0])
        return expr

    def dodict(self, expr):
        '''
        Executes a list operation.
        :param expr:
        '''
        v = {}
        for e in expr:
            #e = self.remove_single_item_list(e)
            v[self.eval(e[0])] = self.eval(e[1])
        return v

    def dolistidx(self, expr):
        val = self.context.get_var(expr[0])
        return val[self.eval(expr[1])]

    def dostmt(self, expr):
        if len(expr) > 1:
            logging.debug("Processing line: {0}".format(expr[0]))
            self.line = int(expr[0])
            return self.eval(expr[1:])

    #===========================================================================
    # dotaskdefstmt
    # if task has no name, it will be called at once.
    # if task has a name, it will be called like a function call afterwards
    #===========================================================================
    def get_params(self, expr):
        params = []
        for e in expr:
            param = self.eval(e)
#             if not isinstance(param, tuple):
#                 param = param, None
            params.append(param)
        return params

    def dotaskdefstmt(self, expr):
        if not expr[0]:
            #v = self.get_args(expr[1])
            return self.dotaskstmt(expr[1:], None) # anonymous task; run immediately
        else:
            self.context.library.add_task(expr[0], expr)

    def args_to_symtab(self, expr):
        for e in expr:
            if e[0] is not "NAMEDARG":
                continue
            param = self.donamedarg(e[1])

            if isinstance(param, tuple):
                self.context.add_var(param[0], param[1])

    def dotaskstmt(self, expr, args):

        params, kwparams = Library.split_args(self.get_params(expr[0]))

        symtab_added, dci_added = False, False
        try:
            local_symtab = self.context.append_local_symtab()
            symtab_added = True
            for k,v in kwparams.items():
                self.context.add_or_update_var(k, v)

            if args:
                arguments, kwargs = Library.split_args(args)
                for k, v in kwargs.items():
                    self.context.add_or_update_var(k, v)

                for index, param in enumerate(params, start = 0):
                    if index >= len(arguments):
                        break
                    self.context.add_or_update_var(k, v)

            if not local_symtab.var_exists('server'):
                local_symtab.add_var('server', None)
            if not local_symtab.var_exists('user'):
                local_symtab.add_var('user', None)
            if not local_symtab.var_exists('password'):
                local_symtab.add_var('password', None)

            # if no new server name given, parent dci is used
            if local_symtab.get_var('server') is not None:
                self.context.append_dci(local_symtab.get_var('server'), local_symtab.get_var('user'), local_symtab.get_var('password'))
                dci_added = True

            if local_symtab.var_exists('provenance') and local_symtab.get_var('provenance'):
                prov = BioProv(lambda: self.eval(expr[1]))
                result = prov.run()
                return result[0].ref if result else None
            else:
                return self.eval(expr[1])

        finally:
            if dci_added:
                self.context.pop_dci()
            if symtab_added:
                self.context.pop_local_symtab()

    def donamedarg(self, expr):
        name = expr[0]
        arg = expr[2]
        return str(name), self.eval(arg)

    def eval(self, expr):
        '''
        Evaluate an expression
        :param expr: The expression in AST tree form.
        '''
        if not isinstance(expr, list):
            return self.eval_value(expr)
        if not expr:
            return
        if len(expr) == 1:
            if expr[0] == "LISTEXPR":
                return list()
            elif expr[0] == "DICTEXPR":
                return dict()
            else:
                return self.eval(expr[0])
        if expr[0] == "FOR":
            return self.dofor(expr[1])
        elif expr[0] == "ASSIGN":
            return self.doassign(expr[1], expr[2])
        elif expr[0] == "CONST":
            return self.eval_value(expr[1])
        elif expr[0] == "NUMEXPR":
            return self.doarithmetic(expr[1:])
        elif expr[0] == "MULTEXPR":
            return self.domult(expr[1:])
        elif expr[0] == "CONCAT":
            return self.doarithmetic(expr[1:])
        elif expr[0] == "LOGEXPR":
            return self.dolog(expr[1:])
        elif expr[0] == "ANDEXPR":
            return self.doand(expr[1:])
        elif expr[0] == "RELEXPR":
            return self.dorelexpr(expr[1:])
        elif expr[0] == "IF":
            return self.doif(expr[1])
        elif expr[0] == "LISTEXPR":
            return self.dolist(expr[1:])
        elif expr[0] == "DICTEXPR":
            return self.dodict(expr[1:])
        elif expr[0] == "FUNCCALL":
            return self.dofunc(expr[1])
        elif expr[0] == "LISTIDX":
            return self.dolistidx(expr[1])
        elif expr[0] == "PAR":
            return self.dopar(expr[1])
        elif expr[0] == "LOCK":
            return self.dolock(expr[1:])
        elif expr[0] == "STMT":
            return self.dostmt(expr[1:])
        elif expr[0] == "MULTISTMT":
            return self.eval(expr[2:])
        elif expr[0] == "NAMEDARG":
            return self.donamedarg(expr[1])
        elif expr[0] == "TASK":
            return self.dotaskdefstmt(expr[1:])
        else:
            val = []
            for subexpr in expr:
                val.append(self.eval(subexpr))
            return val

    # Run it
    def run(self, prog):
        '''
        Run a new program.
        :param prog: Pyparsing ParseResults
        '''
        try:
            #self.context.reload()
            stmt = prog.asList()
            self.eval(stmt)
        except Exception as err:
            self.context.err.append("Error at line {0}: {1}".format(self.line, err))


text:
package calendar.token;

import org.junit.Before;
import org.junit.BeforeClass;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.mockito.InjectMocks;
import org.mockito.Mock;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.test.context.junit4.SpringRunner;

import static org.junit.Assert.*;
import static org.mockito.Mockito.*;

/**
 * Class TokenValidatorTest
 *
 * @author Axel Nilsson (axnion)
 */
@RunWith(SpringRunner.class)
@SpringBootTest
public class TokenValidatorTest {
    @Mock
    private TokenDAO dao;
    @InjectMocks
    private TokenValidator sut;

    @Test
    public void validToken() {
        String strToken = "token";
        int maxRequests = 10000;
        int requests = 999;

        Token token = mock(Token.class);

        when(dao.get(strToken)).thenReturn(token);
        when(token.getMaxRequests()).thenReturn(maxRequests);
        when(token.getRequests()).thenReturn(requests);

        boolean results = sut.validate(strToken);

        verify(token, times(1)).setRequests(requests + 1);
        verify(dao, times(1)).update(token);

        assertTrue(results);
    }

    @Test
    public void invalidTokenDoesNotExist() {
        String strToken = "token";
        int maxRequests = 10000;
        int requests = 999;

        Token token = mock(Token.class);

        when(dao.get(strToken)).thenReturn(null);
        when(token.getMaxRequests()).thenReturn(maxRequests);
        when(token.getRequests()).thenReturn(requests);

        boolean results = sut.validate(strToken);

        verify(token, never()).setRequests(requests + 1);
        verify(dao, never()).update(token);

        assertFalse(results);
    }

    @Test
    public void invalidTokenHasExceededMaxRequests() {
        String strToken = "token";
        int maxRequests = 10000;
        int requests = 10001;

        Token token = mock(Token.class);

        when(dao.get(strToken)).thenReturn(token);
        when(token.getMaxRequests()).thenReturn(maxRequests);
        when(token.getRequests()).thenReturn(requests);

        boolean results = sut.validate(strToken);

        verify(token, never()).setRequests(requests + 1);
        verify(dao, never()).update(token);

        assertFalse(results);
    }
}


text:
'use strict';

var tabject = require('./writables/tabject-writable')

var go = module.exports = function (el, opts) {
  return tabject(el, { tabject: opts }, true);
}


text:
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:orientation="vertical" >

    <LinearLayout
        android:id="@+id/calendario"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:orientation="vertical" >
    </LinearLayout>

    <RelativeLayout
        android:id="@+id/button_layout"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:gravity="center" >

        <Button
            android:id="@+id/btnLegendas"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_marginTop="10dp"
            android:drawableLeft="@drawable/ic_legendas"
            android:gravity="left|center_vertical|center_horizontal"
            android:text="@string/action_legendas"
            android:textSize="15sp"
            android:width="175dp" />

    </RelativeLayout>

</LinearLayout>


text:
<?php
namespace Tunny\Loader;

use Tunny\Tunny;

abstract class AbstractLoader implements LoaderInterface
{
    private $file;
    private $value_tree;
    private $conf;
    protected $content;

    public function __construct($file)
    {
        $this->file = $file;
        $this->conf = null;
        $this->bootstrap($file);
    }

    public function getConf()
    {
        return $this->conf;
    }

    protected function parse($content)
    {
        return $content;
    }

    protected function readFile($file)
    {
        $this->checkFile($file);
        return file_get_contents($file);
    }

    protected function checkFile($file)
    {
        if(!is_file($file)) {
            throw new \InvalidArgumentException("Invalid file path {$file}.");
        }
        return true;
    }

    private function bootstrap($file)
    {
        if (!is_array($file)) {
            $file = array($file);
        }

        $this->loadMultipleFiles($file);
    }

    private function loadMultipleFiles(array $files)
    {
        $out = array();
        foreach ($files as $k => $f) {
            $file_content = $this->readFile($f);
            $out = Tunny::array_overlay($out, $this->parse($file_content));
        }

        $this->conf = $out;
    }
}


text:
//
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License. See LICENSE in the project root for license information.
//
using UnityEngine;
using UnityEngine.UI;
using System;

namespace HUX.Dialogs.Debug
{
    /// <summary>
    /// A debug menu item that displays a button for the user to click.
    /// </summary>
    public class DebugLabelItem : DebugMenuItem
    {
        /// <summary>
        /// The text that sits on the button.
        /// </summary>
        [SerializeField]
        private Text m_LabelText;

        /// <summary>
        /// The function to call when the button is pressed.
        /// </summary>
        private Func<string> m_StringFunc;

		/// <summary>
		/// Setup method.
		/// </summary>
		/// <param name="name">The name of this debug item.</param>
		/// <param name="labelText">The text to put on the label.</param>
		/// <param name="callback">The function to call for update label text.</param>
		public void Setup(string name, string labelText, Func<string> stringFunc)
        {
            Title = name;
            m_StringFunc = stringFunc;

            if (labelText != null)
            {
                m_LabelText.text = labelText;
            }
        }

        /// <summary>
        /// Unity Update function.
        /// </summary>
        private void Update()
        {
            if (m_StringFunc != null )
            {
                string val = m_StringFunc();

                if (val != m_LabelText.text)
                    m_LabelText.text = val;
            }
        }
    }
}


text:
module ActiveMerchant #:nodoc:
  module Billing #:nodoc:
    class TwoPayGateway < Gateway
      self.test_url = 'https://twopay-api'
      self.live_url = 'https://twopay-api'

      # The countries the gateway supports merchants from as 2 digit ISO country codes
      self.supported_countries = ['BR']

      self.default_currency = 'BRL'

      # The card types supported by the payment gateway
      self.supported_cardtypes = [:visa, :master]

      # The homepage URL of the gateway
      self.homepage_url = 'http://www.2pay.us/'

      # The name of the gateway
      self.display_name = '2pay Gateway'

      def initialize(options = {})
        #requires!(options, :login, :password)
        super
      end

      def authorize(money, creditcard, options = {})
        post = {}
        add_invoice(post, options)
        add_creditcard(post, creditcard)
        add_address(post, creditcard, options)
        add_customer_data(post, options)

        commit('authonly', money, post)
      end

      def purchase(money, creditcard, options = {})
        post = {}
        post[:amount] = amount(money).to_i
        add_invoice(post, options)
        add_creditcard(post, creditcard)
        add_address(post, creditcard, options)
        add_customer_data(post, options)

        commit('sale', money, post)
      end

      def capture(money, authorization, options = {})
        post = {}
        commit('capture', money, post)
      end

      private

      def expdate(creditcard)
        year  = sprintf("%.4i", creditcard.year)
        month = sprintf("%.2i", creditcard.month)

        "#{month}#{year[-2..-1]}"
      end

      def add_customer_data(post, options)
      end

      def add_address(post, creditcard, options)
      end

      def add_invoice(post, options)
      end

      def add_creditcard(post, creditcard)
        post["card[number]"]   = creditcard.number
        post["card[cvc]"]  = creditcard.verification_value if creditcard.verification_value?
        post["card[exp_month"]   = "12"
        post["card[exp_year"]   = expdate(creditcard)
        post["card[holdername"] = creditcard.first_name
      end

       def parse(body)
        fields = JSON.parse(body)
        error = fields[0]

        results = {
          :response_code => error["errorCode"],
          :description => error["description"],
          :errorField => error["errorField"],
          :severityCodeEnum => error["severityCodeEnum"],
          :order_status => error["order_status"]
        }
        results
      end

      def commit(action, money, parameters)
         parameters[:paymentmethodcode] = 1

         data = ssl_post(self.test_url, post_data(action, parameters))

         response          = parse(data)
         response[:action] = action

        message = message_from(response)

        p success?(response)

        Response.new(success?(response), message, response)
        #   :authorization => response["authorization_code"],
        #   :avs_result => { :code => response["avs_result_code"] },
        #   :cvv_result => response["card_code"]
        # )
      end

      def success?(response)
        response[:order_status] == "Paid"
      end

      def message_from(response)
        if response[:order_status] == "Paid"
          return "This transaction has been approved"
        else
          return "This transaction has not been approved"
        end
      end

      def post_data(action, parameters = {})
        post = {}

        post[:type]           = action
        post[:solution_ID]    = application_id if application_id.present? && application_id != "ActiveMerchant"

        request = post.merge(parameters).collect { |key, value| "#{key}=#{CGI.escape(value.to_s)}" }.join("&")
        request
      end
    end
  end
end


text:
// Copyright Dirk Lemstra https://github.com/dlemstra/Magick.NET.
// Licensed under the Apache License, Version 2.0.

using ImageMagick;
using Xunit;

namespace Magick.NET.Tests
{
    public partial class ColorRGBTests
    {
        public class TheOperators
        {
            [Fact]
            public void ShouldReturnTheCorrectValueWhenInstanceIsNull()
            {
                var color = new ColorRGB(0, 0, 0);

                Assert.False(color == null);
                Assert.True(color != null);
                Assert.False(color < null);
                Assert.False(color <= null);
                Assert.True(color > null);
                Assert.True(color >= null);
                Assert.False(null == color);
                Assert.True(null != color);
                Assert.True(null < color);
                Assert.True(null <= color);
                Assert.False(null > color);
                Assert.False(null >= color);
            }

            [Fact]
            public void ShouldReturnTheCorrectValueWhenInstancesAreEqual()
            {
                var first = new ColorRGB(0, 0, Quantum.Max);
                var second = new ColorRGB(0, 0, Quantum.Max);

                Assert.True(first == second);
                Assert.False(first != second);
                Assert.False(first < second);
                Assert.True(first <= second);
                Assert.False(first > second);
                Assert.True(first >= second);
            }

            [Fact]
            public void ShouldReturnTheCorrectValueWhenInstancesAreNotEqual()
            {
                var first = new ColorRGB(Quantum.Max, 0, 0);
                var second = new ColorRGB(0, Quantum.Max, 0);

                Assert.False(first == second);
                Assert.True(first != second);
                Assert.False(first < second);
                Assert.False(first <= second);
                Assert.True(first > second);
                Assert.True(first >= second);
            }

            [Fact]
            public void ShouldReturnTheCorrectValueWhenCastedFromMagickColor()
            {
                var expected = new ColorRGB(Quantum.Max, 0, 0);
                var actual = (ColorRGB)new MagickColor(Quantum.Max, 0, 0);
                Assert.Equal(expected, actual);
            }
        }
    }
}


text:
<?php

namespace Okvpn\Bundle\RedisQueueBundle\Transport\Redis;

use Okvpn\Bundle\RedisQueueBundle\Transport\Redis\Driver\RedisConnection;
use Oro\Component\MessageQueue\Transport\DestinationInterface;
use Oro\Component\MessageQueue\Transport\Exception\Exception;
use Oro\Component\MessageQueue\Transport\Exception\InvalidMessageException;
use Oro\Component\MessageQueue\Transport\MessageInterface;
use Oro\Component\MessageQueue\Transport\MessageProducerInterface;
use Oro\Component\MessageQueue\Transport\QueueInterface;
use Oro\Component\MessageQueue\Transport\TopicInterface;
use Oro\Component\MessageQueue\Util\JSON;

class RedisMessageProducer implements MessageProducerInterface
{
    /** @var RedisConnection */
    protected $connection;

    /**
     * @param RedisConnection $connection
     */
    public function __construct(RedisConnection $connection)
    {
        $this->connection = $connection;
    }

    /**
     * {@inheritdoc}
     *
     * @param RedisMessage $message
     */
    public function send(DestinationInterface $destination, MessageInterface $message)
    {
        $body = $message->getBody();
        if (is_scalar($body) || is_null($body)) {
            $body = (string) $body;
        } else {
            throw new InvalidMessageException(sprintf(
                'The message body must be a scalar or null. Got: %s',
                is_object($body) ? get_class($body) : gettype($body)
            ));
        }

        if ($destination instanceof TopicInterface) {
            $name = $destination->getTopicName();
        } elseif ($destination instanceof QueueInterface) {
            $name = $destination->getQueueName();
        } else {
            throw new Exception('The "destination" must be instance of TopicInterface or QueueInterface');
        }

        try {
            $rMessage = [
                'body' => $body,
                'headers' => $message->getHeaders(),
                'properties' => $message->getProperties()
            ];

            $connection = $this->connection->getRedisConnection();
            if ($message->getDelay() !== null) {
                $connection->zAdd(
                    $this->connection->getSetsName($name),
                    $message->getDelay(),
                    JSON::encode($rMessage)
                );
            } else {
                $connection->lPush(
                    $this->connection->getListName($name, $message->getPriority()),
                    JSON::encode($rMessage)
                );
            }
        } catch (\Exception $e) {
            throw new Exception('The transport fails to send the message due to some internal error.', null, $e);
        }
    }
}