text:
/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package com.eas.client.form;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.logging.Level;
import java.util.logging.Logger;

import com.bearsoft.gwt.ui.HasImageParagraph;
import com.bearsoft.gwt.ui.HasImageResource;
import com.bearsoft.gwt.ui.Orientation;
import com.bearsoft.gwt.ui.widgets.DropDownButton;
import com.bearsoft.gwt.ui.widgets.ImageButton;
import com.bearsoft.gwt.ui.widgets.ObjectFormat;
import com.bearsoft.gwt.ui.widgets.grid.header.HeaderNode;
import com.eas.client.CallbackAdapter;
import com.eas.client.Utils;
import com.eas.client.Utils.JsObject;
import com.eas.client.application.PlatypusImageResource;
import com.eas.client.form.grid.columns.ModelColumn;
import com.eas.client.form.grid.columns.header.CheckHeaderNode;
import com.eas.client.form.grid.columns.header.ModelHeaderNode;
import com.eas.client.form.grid.columns.header.RadioHeaderNode;
import com.eas.client.form.grid.columns.header.ServiceHeaderNode;
import com.eas.client.form.published.containers.AnchorsPane;
import com.eas.client.form.published.containers.BorderPane;
import com.eas.client.form.published.containers.BoxPane;
import com.eas.client.form.published.containers.ButtonGroup;
import com.eas.client.form.published.containers.CardPane;
import com.eas.client.form.published.containers.FlowPane;
import com.eas.client.form.published.containers.GridPane;
import com.eas.client.form.published.containers.ScrollPane;
import com.eas.client.form.published.containers.SplitPane;
import com.eas.client.form.published.containers.TabbedPane;
import com.eas.client.form.published.containers.ToolBar;
import com.eas.client.form.published.menu.PlatypusMenu;
import com.eas.client.form.published.menu.PlatypusMenuBar;
import com.eas.client.form.published.menu.PlatypusMenuItemCheckBox;
import com.eas.client.form.published.menu.PlatypusMenuItemImageText;
import com.eas.client.form.published.menu.PlatypusMenuItemRadioButton;
import com.eas.client.form.published.menu.PlatypusMenuItemSeparator;
import com.eas.client.form.published.menu.PlatypusPopupMenu;
import com.eas.client.form.published.widgets.DesktopPane;
import com.eas.client.form.published.widgets.PlatypusButton;
import com.eas.client.form.published.widgets.PlatypusCheckBox;
import com.eas.client.form.published.widgets.PlatypusFormattedTextField;
import com.eas.client.form.published.widgets.PlatypusHtmlEditor;
import com.eas.client.form.published.widgets.PlatypusLabel;
import com.eas.client.form.published.widgets.PlatypusPasswordField;
import com.eas.client.form.published.widgets.PlatypusProgressBar;
import com.eas.client.form.published.widgets.PlatypusRadioButton;
import com.eas.client.form.published.widgets.PlatypusSlider;
import com.eas.client.form.published.widgets.PlatypusSplitButton;
import com.eas.client.form.published.widgets.PlatypusTextArea;
import com.eas.client.form.published.widgets.PlatypusTextField;
import com.eas.client.form.published.widgets.PlatypusToggleButton;
import com.eas.client.form.published.widgets.model.ModelCheck;
import com.eas.client.form.published.widgets.model.ModelCombo;
import com.eas.client.form.published.widgets.model.ModelDate;
import com.eas.client.form.published.widgets.model.ModelDecoratorBox;
import com.eas.client.form.published.widgets.model.ModelFormattedField;
import com.eas.client.form.published.widgets.model.ModelGrid;
import com.eas.client.form.published.widgets.model.ModelSpin;
import com.eas.client.form.published.widgets.model.ModelTextArea;
import com.eas.client.form.published.HasBinding;
import com.eas.client.form.published.HasComponentPopupMenu;
import com.eas.client.form.published.HasEmptyText;
import com.eas.client.form.published.HasJsName;
import com.eas.client.form.published.HasPlatypusButtonGroup;
import com.eas.client.form.published.HasPublished;
import com.eas.client.form.published.PublishedColor;
import com.eas.client.form.published.PublishedComponent;
import com.eas.client.form.published.PublishedFont;
import com.google.gwt.core.client.JavaScriptObject;
import com.google.gwt.resources.client.ImageResource;
import com.google.gwt.user.client.ui.HasEnabled;
import com.google.gwt.user.client.ui.HasText;
import com.google.gwt.user.client.ui.HasValue;
import com.google.gwt.user.client.ui.UIObject;
import com.google.gwt.user.client.ui.Widget;
import com.google.gwt.xml.client.Element;
import com.google.gwt.xml.client.Node;

/**
 *
 * @author mg
 */
public class FormFactory {

	protected static class Dimension {
		public int width;
		public int height;
	}

	protected Element element;
	protected JsObject model;
	protected PlatypusWindow form;
	protected Map<String, UIObject> widgets = new HashMap<>();
	protected List<UIObject> widgetsList = new ArrayList<>();
	protected String rootContainerName;
	//
	protected List<Runnable> resolvers = new ArrayList<>();

	public FormFactory(Element anElement, JavaScriptObject aModel) {
		super();
		element = anElement;
		model = aModel != null ? aModel.<JsObject> cast() : null;
	}

	public Map<String, UIObject> getWidgets() {
		return widgets;
	}

	public List<UIObject> getWidgetsList() {
		return widgetsList;
	}

	public PlatypusWindow getForm() {
		return form;
	}

	public void parse() throws Exception {
		if (!element.hasAttribute("view")) {
			throw new IllegalStateException("Old form format detected. Please open the form with a new form designer and re-save it.");
		} else {
			rootContainerName = element.getAttribute("view");
			Node childNode = element.getFirstChild();
			while (childNode != null) {
				if (childNode instanceof Element) {
					UIObject widget = readWidget((Element) childNode);
					String wName = ((HasJsName) widget).getJsName();
					assert wName != null && !wName.isEmpty() : "A widget is expected to be a named item.";
					widgets.put(wName, widget);
					widgetsList.add(widget);
				}
				childNode = childNode.getNextSibling();
			}
		}
		UIObject viewWidget = widgets.get(rootContainerName);
		if (viewWidget == null) {
			viewWidget = new AnchorsPane();
			viewWidget.setSize(400 + "px", 300 + "px");
			Logger.getLogger(FormFactory.class.getName()).log(Level.WARNING, "view widget missing. Falling back to AnchrosPane.");
		}
		form = new PlatypusWindow((Widget) viewWidget);
		form.setDefaultCloseOperation(Utils.getIntegerAttribute(element, "defaultCloseOperation", 2));
		String iconImage = element.getAttribute("icon");
		if (iconImage != null && !iconImage.isEmpty()) {
			PlatypusImageResource.load(iconImage, new CallbackAdapter<ImageResource, String>() {
				@Override
				protected void doWork(ImageResource aResult) throws Exception {
					form.setIcon(aResult);
				}

				@Override
				public void onFailure(String reason) {
					Logger.getLogger(PlatypusWindow.class.getName()).log(Level.SEVERE, "Factory failed to load window title icon. " + reason);
				}
			});
		}
		form.setTitle(element.getAttribute("title"));
		form.setMaximizable(Utils.getBooleanAttribute(element, "maximizable", Boolean.TRUE));
		form.setMinimizable(Utils.getBooleanAttribute(element, "minimizable", Boolean.TRUE));
		form.setResizable(Utils.getBooleanAttribute(element, "resizable", Boolean.TRUE));
		form.setUndecorated(Utils.getBooleanAttribute(element, "undecorated", Boolean.FALSE));
		form.setOpacity(Utils.getFloatAttribute(element, "opacity", 1.0f));
		form.setAlwaysOnTop(Utils.getBooleanAttribute(element, "alwaysOnTop", Boolean.FALSE));
		form.setLocationByPlatform(Utils.getBooleanAttribute(element, "locationByPlatform", Boolean.TRUE));
		// form.setDesignedViewSize(viewWidget.getPreferredSize());
		for (int i = 0; i < resolvers.size(); i++) {
			Runnable r = resolvers.get(i);
			r.run();
		}
	}

	protected Dimension readPrefSize(Element anElement) throws NumberFormatException {
		if (anElement.hasAttribute("prefWidth") && anElement.hasAttribute("prefHeight")) {
			Dimension prefSize = new Dimension();
			String prefWidth = anElement.getAttribute("prefWidth");
			String prefHeight = anElement.getAttribute("prefHeight");
			if (prefWidth.length() > 2 && prefWidth.endsWith("px")) {
				prefSize.width = Integer.parseInt(prefWidth.substring(0, prefWidth.length() - 2));
			}
			if (prefHeight.length() > 2 && prefHeight.endsWith("px")) {
				prefSize.height = Integer.parseInt(prefHeight.substring(0, prefHeight.length() - 2));
			}
			return prefSize;
		} else
			return null;
	}

	protected JsObject resolveEntity(String aEntityName) throws Exception {
		if (model.has(aEntityName)) {
			JavaScriptObject oEntity = model.getJs(aEntityName);
			if (oEntity != null) {
				return oEntity.cast();
			}
		}
		return null;
	}

	protected JsObject resolveEntity(long aEntityId) throws Exception {
		return null;
	}

	private UIObject readWidget(Element anElement) throws Exception {
		String type = anElement.getTagName();
		switch (type) {
		// widgets
		case "Label":
			final PlatypusLabel label = new PlatypusLabel();
			Publisher.publish(label);
			readGeneralProps(anElement, label);
			readImageParagraph(anElement, label);
			return label;
		case "Button":
			PlatypusButton button = new PlatypusButton();
			Publisher.publish(button);
			readGeneralProps(anElement, button);
			readImageParagraph(anElement, button);
			return button;
		case "DropDownButton":
			final PlatypusSplitButton dropDownButton = new PlatypusSplitButton();
			Publisher.publish(dropDownButton);
			readGeneralProps(anElement, dropDownButton);
			readImageParagraph(anElement, dropDownButton);
			if (anElement.hasAttribute("dropDownMenu")) {
				final String dropDownMenuName = anElement.getAttribute("dropDownMenu");
				resolvers.add(new Runnable() {
					public void run() {
						if (widgets.containsKey(dropDownMenuName)) {
							UIObject compMenu = widgets.get(dropDownMenuName);
							if (compMenu instanceof PlatypusPopupMenu) {
								dropDownButton.setMenu((PlatypusPopupMenu) compMenu);
							}
						}
					}
				});
			}
			return dropDownButton;
		case "ButtonGroup":
			ButtonGroup buttonGroup = new ButtonGroup();
			Publisher.publish(buttonGroup);
			if (anElement.hasAttribute("name")) {
				buttonGroup.setJsName(anElement.getAttribute("name"));
			}
			return buttonGroup;
		case "CheckBox":
			PlatypusCheckBox checkBox = new PlatypusCheckBox();
			Publisher.publish(checkBox);
			readGeneralProps(anElement, checkBox);
			readImageParagraph(anElement, checkBox);
			if (anElement.hasAttribute("selected")) {
				boolean selected = Utils.getBooleanAttribute(anElement, "selected", Boolean.FALSE);
				checkBox.setValue(selected);
			}
			if (anElement.hasAttribute("text")) {
				checkBox.setText(anElement.getAttribute("text"));
			}
			return checkBox;
		case "TextArea":
			PlatypusTextArea textArea = new PlatypusTextArea();
			Publisher.publish(textArea);
			readGeneralProps(anElement, textArea);
			if (anElement.hasAttribute("text")) {
				textArea.setText(anElement.getAttribute("text"));
			}
			return textArea;
		case "HtmlArea":
			PlatypusHtmlEditor htmlArea = new PlatypusHtmlEditor();
			Publisher.publish(htmlArea);
			readGeneralProps(anElement, htmlArea);
			if (anElement.hasAttribute("text")) {
				String text = anElement.getAttribute("text");
				htmlArea.setValue(text);
			}
			return htmlArea;
		case "FormattedField": {
			PlatypusFormattedTextField formattedField = new PlatypusFormattedTextField();
			Publisher.publish(formattedField);
			readGeneralProps(anElement, formattedField);
			String format = anElement.getAttribute("format");
			int valueType = Utils.getIntegerAttribute(anElement, "valueType", ObjectFormat.REGEXP);
			formattedField.setValueType(valueType);
			formattedField.setFormat(format);
			if (anElement.hasAttribute("text")) {
				formattedField.setText(anElement.getAttribute("text"));
			}
			return formattedField;
		}
		case "PasswordField":
			PlatypusPasswordField passwordField = new PlatypusPasswordField();
			Publisher.publish(passwordField);
			readGeneralProps(anElement, passwordField);
			if (anElement.hasAttribute("text")) {
				passwordField.setText(anElement.getAttribute("text"));
			}
			return passwordField;
		case "ProgressBar": {
			PlatypusProgressBar progressBar = new PlatypusProgressBar();
			Publisher.publish(progressBar);
			readGeneralProps(anElement, progressBar);
			int minimum = Utils.getIntegerAttribute(anElement, "minimum", 0);
			int value = Utils.getIntegerAttribute(anElement, "value", 0);
			int maximum = Utils.getIntegerAttribute(anElement, "maximum", 100);
			progressBar.setMinProgress(minimum);
			progressBar.setMaxProgress(maximum);
			progressBar.setValue((double) value);
			if (anElement.hasAttribute("string")) {
				progressBar.setText(anElement.getAttribute("string"));
			}
			return progressBar;
		}
		case "RadioButton":
			PlatypusRadioButton radio = new PlatypusRadioButton();
			Publisher.publish(radio);
			readGeneralProps(anElement, radio);
			readImageParagraph(anElement, radio);
			if (anElement.hasAttribute("selected")) {
				boolean selected = Utils.getBooleanAttribute(anElement, "selected", Boolean.FALSE);
				radio.setValue(selected);
			}
			if (anElement.hasAttribute("text")) {
				radio.setText(anElement.getAttribute("text"));
			}
			return radio;
		case "Slider":
			PlatypusSlider slider = new PlatypusSlider();
			Publisher.publish(slider);
			readGeneralProps(anElement, slider);
			int minimum = Utils.getIntegerAttribute(anElement, "minimum", 0);
			int value = Utils.getIntegerAttribute(anElement, "value", 0);
			int maximum = Utils.getIntegerAttribute(anElement, "maximum", 100);
			slider.setMinValue(minimum);
			slider.setMaxValue(maximum);
			slider.setValue((double) value);
			return slider;
		case "TextField":
			PlatypusTextField textField = new PlatypusTextField();
			Publisher.publish(textField);
			readGeneralProps(anElement, textField);
			if (anElement.hasAttribute("text")) {
				textField.setText(anElement.getAttribute("text"));
			}
			return textField;
		case "ToggleButton":
			PlatypusToggleButton toggle = new PlatypusToggleButton();
			Publisher.publish(toggle);
			readGeneralProps(anElement, toggle);
			readImageParagraph(anElement, toggle);
			if (anElement.hasAttribute("selected")) {
				boolean selected = Utils.getBooleanAttribute(anElement, "selected", Boolean.FALSE);
				toggle.setValue(selected);
			}
			return toggle;
		case "DesktopPane":
			DesktopPane desktop = new DesktopPane();
			Publisher.publish(desktop);
			readGeneralProps(anElement, desktop);
			return desktop;
			// model widgets
		case "ModelCheckBox":
			ModelCheck modelCheckBox = new ModelCheck();
			Publisher.publish(modelCheckBox);
			readGeneralProps(anElement, modelCheckBox);
			if (anElement.hasAttribute("text")) {
				modelCheckBox.setText(anElement.getAttribute("text"));
			}
			return modelCheckBox;
		case "ModelCombo":
			ModelCombo modelCombo = new ModelCombo();
			Publisher.publish(modelCombo);
			readGeneralProps(anElement, modelCombo);
			boolean list = Utils.getBooleanAttribute(anElement, "list", Boolean.TRUE);
			modelCombo.setList(list);
			if (anElement.hasAttribute("displayList")) {
				String displayList = anElement.getAttribute("displayList");
				modelCombo.setDisplayList(resolveEntity(displayList));
			}
			if (anElement.hasAttribute("displayField")) {
				String displayField = anElement.getAttribute("displayField");
				modelCombo.setDisplayField(displayField);
			}
			return modelCombo;
		case "ModelDate":
			ModelDate modelDate = new ModelDate();
			Publisher.publish(modelDate);
			readGeneralProps(anElement, modelDate);
			if (anElement.hasAttribute("dateFormat")) {
				String dateFormat = anElement.getAttribute("dateFormat");
				try {
					modelDate.setFormat(dateFormat);
				} catch (Exception ex) {
					Logger.getLogger(FormFactory.class.getName()).log(Level.SEVERE, null, ex);
				}
			}
			if (anElement.hasAttribute("datePicker")) {
				boolean selected = Utils.getBooleanAttribute(anElement, "datePicker", Boolean.FALSE);
				modelDate.setDateShown(selected);
			}
			if (anElement.hasAttribute("timePicker")) {
				boolean selected = Utils.getBooleanAttribute(anElement, "timePicker", Boolean.FALSE);
				modelDate.setTimeShown(selected);
			}
			return modelDate;
		case "ModelFormattedField":
			ModelFormattedField modelFormattedField = new ModelFormattedField();
			Publisher.publish(modelFormattedField);
			readGeneralProps(anElement, modelFormattedField);
			try {
				String format = anElement.getAttribute("format");
				int valueType = Utils.getIntegerAttribute(anElement, "valueType", ObjectFormat.REGEXP);
				modelFormattedField.setValueType(valueType);
				modelFormattedField.setFormat(format);
				if (anElement.hasAttribute("text")) {
					modelFormattedField.setText(anElement.getAttribute("text"));
				}
			} catch (Exception ex) {
				Logger.getLogger(FormFactory.class.getName()).log(Level.SEVERE, null, ex);
			}
			return modelFormattedField;
		case "ModelSpin":
			ModelSpin modelSpin = new ModelSpin();
			Publisher.publish(modelSpin);
			readGeneralProps(anElement, modelSpin);
			Double min = null;
			if (anElement.hasAttribute("min"))
				min = Utils.getDoubleAttribute(anElement, "min", -Double.MAX_VALUE);
			double step = Utils.getDoubleAttribute(anElement, "step", 1.0d);
			Double max = null;
			if (anElement.hasAttribute("max"))
				max = Utils.getDoubleAttribute(anElement, "max", Double.MAX_VALUE);
			try {
				modelSpin.setMin(min);
				modelSpin.setMax(max);
				modelSpin.setStep(step);
			} catch (Exception ex) {
				Logger.getLogger(FormFactory.class.getName()).log(Level.SEVERE, null, ex);
			}
			return modelSpin;
		case "ModelTextArea":
			ModelTextArea modelTextArea = new ModelTextArea();
			Publisher.publish(modelTextArea);
			readGeneralProps(anElement, modelTextArea);
			if (anElement.hasAttribute("text")) {
				modelTextArea.setValue(anElement.getAttribute("text"));
			}
			return modelTextArea;
		case "ModelGrid": {
			ModelGrid grid = new ModelGrid();
			Publisher.publish(grid);
			readGeneralProps(anElement, grid);
			int frozenColumns = Utils.getIntegerAttribute(anElement, "frozenColumns", 0);
			int frozenRows = Utils.getIntegerAttribute(anElement, "frozenRows", 0);
			boolean insertable = Utils.getBooleanAttribute(anElement, "insertable", Boolean.TRUE);
			boolean deletable = Utils.getBooleanAttribute(anElement, "deletable", Boolean.TRUE);
			boolean editable = Utils.getBooleanAttribute(anElement, "editable", Boolean.TRUE);
			boolean headerVisible = Utils.getBooleanAttribute(anElement, "headerVisible", Boolean.TRUE);
			boolean draggableRows = Utils.getBooleanAttribute(anElement, "draggableRows", Boolean.FALSE);
			boolean showHorizontalLines = Utils.getBooleanAttribute(anElement, "showHorizontalLines", Boolean.TRUE);
			boolean showVerticalLines = Utils.getBooleanAttribute(anElement, "showVerticalLines", Boolean.TRUE);
			boolean showOddRowsInOtherColor = Utils.getBooleanAttribute(anElement, "showOddRowsInOtherColor", Boolean.TRUE);
			int rowsHeight = Utils.getIntegerAttribute(anElement, "rowsHeight", 20);
			grid.setHeaderVisible(headerVisible);
			grid.setDraggableRows(draggableRows);
			grid.setRowsHeight(rowsHeight);
			grid.setShowOddRowsInOtherColor(showOddRowsInOtherColor);
			grid.setShowVerticalLines(showVerticalLines);
			grid.setShowHorizontalLines(showHorizontalLines);
			grid.setEditable(editable);
			grid.setDeletable(deletable);
			grid.setInsertable(insertable);
			grid.setFrozenColumns(frozenColumns);
			grid.setFrozenRows(frozenRows);
			if (anElement.hasAttribute("oddRowsColor")) {
				String oddRowsColorDesc = anElement.getAttribute("oddRowsColor");
				grid.setOddRowsColor(ControlsUtils.parseColor(oddRowsColorDesc));
			}
			if (anElement.hasAttribute("gridColor")) {
				String gridColorDesc = anElement.getAttribute("gridColor");
				grid.setGridColor(ControlsUtils.parseColor(gridColorDesc));
			}
			if (anElement.hasAttribute("parentField")) {
				String parentFieldPath = anElement.getAttribute("parentField");
				grid.setParentField(parentFieldPath);
			}
			if (anElement.hasAttribute("childrenField")) {
				String childrenFieldPath = anElement.getAttribute("childrenField");
				grid.setChildrenField(childrenFieldPath);
			}
			List<HeaderNode<JavaScriptObject>> roots = readColumns(anElement);
			grid.setHeader(roots);
			if (anElement.hasAttribute("data")) {
				String entityName = anElement.getAttribute("data");
				try {
					grid.setData(resolveEntity(entityName));
				} catch (Exception ex) {
					Logger.getLogger(FormFactory.class.getName()).log(Level.SEVERE,
					        "While setting data to named model's property " + entityName + " to widget " + grid.getJsName() + " exception occured: " + ex.getMessage());
				}
			}
			if (anElement.hasAttribute("field")) {
				String dataPropertyPath = anElement.getAttribute("field");
				grid.setField(dataPropertyPath);
			}
			return grid;
		}
		// containers
		case "AnchorsPane":
			AnchorsPane anchorsPane = new AnchorsPane();
			Publisher.publish(anchorsPane);
			readGeneralProps(anElement, anchorsPane);
			return anchorsPane;
		case "BorderPane": {
			int hgap = Utils.getIntegerAttribute(anElement, "hgap", 0);
			int vgap = Utils.getIntegerAttribute(anElement, "vgap", 0);
			BorderPane borderPane = new BorderPane(hgap, vgap);
			Publisher.publish(borderPane);
			readGeneralProps(anElement, borderPane);
			return borderPane;
		}
		case "BoxPane": {
			int hgap = Utils.getIntegerAttribute(anElement, "hgap", 0);
			int vgap = Utils.getIntegerAttribute(anElement, "vgap", 0);
			int orientation = Utils.getIntegerAttribute(anElement, "orientation", Orientation.HORIZONTAL);
			BoxPane boxPane = new BoxPane(orientation, hgap, vgap);
			Publisher.publish(boxPane);
			readGeneralProps(anElement, boxPane);
			return boxPane;
		}
		case "CardPane": {
			int hgap = Utils.getIntegerAttribute(anElement, "hgap", 0);
			int vgap = Utils.getIntegerAttribute(anElement, "vgap", 0);
			CardPane cardPane = new CardPane(hgap, vgap);
			Publisher.publish(cardPane);
			readGeneralProps(anElement, cardPane);
			return cardPane;
		}
		case "FlowPane": {
			int hgap = Utils.getIntegerAttribute(anElement, "hgap", 0);
			int vgap = Utils.getIntegerAttribute(anElement, "vgap", 0);
			FlowPane flowPane = new FlowPane(hgap, vgap);
			Publisher.publish(flowPane);
			readGeneralProps(anElement, flowPane);
			return flowPane;
		}
		case "GridPane": {
			int hgap = Utils.getIntegerAttribute(anElement, "hgap", 0);
			int vgap = Utils.getIntegerAttribute(anElement, "vgap", 0);
			int rows = Utils.getIntegerAttribute(anElement, "rows", 0);
			int columns = Utils.getIntegerAttribute(anElement, "columns", 0);
			GridPane gridPane = new GridPane(rows, columns, hgap, vgap);
			Publisher.publish(gridPane);
			readGeneralProps(anElement, gridPane);
			return gridPane;
		}
		// predefined layout containers
		case "ScrollPane":
			ScrollPane scroll = new ScrollPane();
			Publisher.publish(scroll);
			readGeneralProps(anElement, scroll);
			boolean wheelScrollingEnabled = Utils.getBooleanAttribute(anElement, "wheelScrollingEnabled", Boolean.TRUE);
			int horizontalScrollBarPolicy = Utils.getIntegerAttribute(anElement, "horizontalScrollBarPolicy", ScrollPane.SCROLLBAR_AS_NEEDED);
			int verticalScrollBarPolicy = Utils.getIntegerAttribute(anElement, "verticalScrollBarPolicy", ScrollPane.SCROLLBAR_AS_NEEDED);
			scroll.setHorizontalScrollBarPolicy(horizontalScrollBarPolicy);
			scroll.setVerticalScrollBarPolicy(verticalScrollBarPolicy);
			return scroll;
		case "SplitPane":
			final SplitPane split = new SplitPane();
			Publisher.publish(split);
			readGeneralProps(anElement, split);
			boolean oneTouchExpandable = Utils.getBooleanAttribute(anElement, "oneTouchExpandable", true);
			int dividerLocation = Utils.getIntegerAttribute(anElement, "dividerLocation", 0);
			int orientation = Utils.getIntegerAttribute(anElement, "orientation", Orientation.VERTICAL);
			split.setDividerLocation(dividerLocation);
			split.setOrientation(orientation);
			split.setOneTouchExpandable(oneTouchExpandable);
			if (anElement.hasAttribute("leftComponent")) {
				final String leftComponentName = anElement.getAttribute("leftComponent");
				resolvers.add(new Runnable() {
					@Override
					public void run() {
						UIObject leftComponent = widgets.get(leftComponentName);
						split.setFirstWidget((Widget) leftComponent);
					}
				});
			}
			if (anElement.hasAttribute("rightComponent")) {
				final String rightComponentName = anElement.getAttribute("rightComponent");
				resolvers.add(new Runnable() {
					@Override
					public void run() {
						UIObject rightComponent = widgets.get(rightComponentName);
						split.setSecondWidget((Widget) rightComponent);
					}
				});
			}
			return split;
		case "TabbedPane":
			TabbedPane tabs = new TabbedPane();
			Publisher.publish(tabs);
			readGeneralProps(anElement, tabs);
			/*
			 * int tabPlacement = Utils.getIntegerAttribute(anElement,
			 * "tabPlacement", TabbedPane.TOP);
			 * tabs.setTabPlacement(tabPlacement);
			 */
			return tabs;
		case "ToolBar":
			ToolBar toolbar = new ToolBar();
			Publisher.publish(toolbar);
			readGeneralProps(anElement, toolbar);
			return toolbar;
			// menus
		case "Menu":
			PlatypusMenu menu = new PlatypusMenu();
			Publisher.publish(menu);
			readGeneralProps(anElement, menu);
			if (anElement.hasAttribute("text")) {
				menu.setText(anElement.getAttribute("text"));
			}
			return menu;
		case "MenuItem":
			PlatypusMenuItemImageText menuitem = new PlatypusMenuItemImageText();
			Publisher.publish(menuitem);
			readGeneralProps(anElement, menuitem);
			readImageParagraph(anElement, menuitem);
			if (anElement.hasAttribute("text")) {
				menuitem.setText(anElement.getAttribute("text"));
			}
			return menuitem;
		case "CheckMenuItem":
			PlatypusMenuItemCheckBox checkMenuItem = new PlatypusMenuItemCheckBox();
			Publisher.publish(checkMenuItem);
			readGeneralProps(anElement, checkMenuItem);
			readImageParagraph(anElement, checkMenuItem);
			if (anElement.hasAttribute("selected")) {
				boolean selected = Utils.getBooleanAttribute(anElement, "selected", Boolean.FALSE);
				checkMenuItem.setValue(selected);
			}
			if (anElement.hasAttribute("text")) {
				checkMenuItem.setText(anElement.getAttribute("text"));
			}
			return checkMenuItem;
		case "RadioMenuItem":
			PlatypusMenuItemRadioButton radioMenuItem = new PlatypusMenuItemRadioButton();
			Publisher.publish(radioMenuItem);
			readGeneralProps(anElement, radioMenuItem);
			readImageParagraph(anElement, radioMenuItem);
			if (anElement.hasAttribute("selected")) {
				boolean selected = Utils.getBooleanAttribute(anElement, "selected", Boolean.FALSE);
				radioMenuItem.setValue(selected);
			}
			if (anElement.hasAttribute("text")) {
				radioMenuItem.setText(anElement.getAttribute("text"));
			}
			return radioMenuItem;
		case "MenuSeparator":
			PlatypusMenuItemSeparator menuSeparator = new PlatypusMenuItemSeparator();
			Publisher.publish(menuSeparator);
			readGeneralProps(anElement, menuSeparator);
			return menuSeparator;
		case "MenuBar":
			PlatypusMenuBar menuBar = new PlatypusMenuBar();
			Publisher.publish(menuBar);
			readGeneralProps(anElement, menuBar);
			return menuBar;
		case "PopupMenu":
			PlatypusPopupMenu popupMenu = new PlatypusPopupMenu();
			Publisher.publish(popupMenu);
			readGeneralProps(anElement, popupMenu);
			return popupMenu;
		default:
			return null;
		}
	}

	protected void readImageParagraph(Element anElement, final UIObject aImageParagraph) throws Exception {
		if (anElement.hasAttribute("icon") && aImageParagraph instanceof HasImageResource) {
			String iconImage = anElement.getAttribute("icon");
			PlatypusImageResource.load(iconImage, new CallbackAdapter<ImageResource, String>() {
				@Override
				protected void doWork(ImageResource aResult) throws Exception {
					((HasImageResource) aImageParagraph).setImageResource(aResult);
				}

				@Override
				public void onFailure(String reason) {
					Logger.getLogger(PlatypusWindow.class.getName()).log(Level.SEVERE, "Factory failed to load button icon. " + reason);
				}
			});
		}
		if (anElement.hasAttribute("text") && aImageParagraph instanceof HasText) {
			((HasText) aImageParagraph).setText(anElement.getAttribute("text"));
		}
		if (aImageParagraph instanceof HasImageParagraph) {
			HasImageParagraph hip = (HasImageParagraph) aImageParagraph;
			hip.setHorizontalAlignment(Utils.getIntegerAttribute(anElement, "horizontalAlignment", aImageParagraph instanceof ImageButton || aImageParagraph instanceof DropDownButton ? HasImageParagraph.CENTER
			        : HasImageParagraph.LEFT));
			hip.setVerticalAlignment(Utils.getIntegerAttribute(anElement, "verticalAlignment", HasImageParagraph.CENTER));
			hip.setIconTextGap(Utils.getIntegerAttribute(anElement, "iconTextGap", 4));
			hip.setHorizontalTextPosition(Utils.getIntegerAttribute(anElement, "horizontalTextPosition", HasImageParagraph.RIGHT));
			hip.setVerticalTextPosition(Utils.getIntegerAttribute(anElement, "verticalTextPosition", HasImageParagraph.CENTER));
		}
	}

	private void readGeneralProps(final Element anElement, final UIObject aTarget) throws Exception {
		String widgetName = "";
		if (anElement.hasAttribute("name") && aTarget instanceof HasJsName) {
			widgetName = anElement.getAttribute("name");
			((HasJsName) aTarget).setJsName(widgetName);
		}
		if (anElement.hasAttribute("nullable") && aTarget instanceof ModelDecoratorBox<?>) {
			((ModelDecoratorBox<?>) aTarget).setNullable(Utils.getBooleanAttribute(anElement, "nullable", true));
		}
		/*
		 * if (anElement.hasAttribute("editable") && aTarget instanceof
		 * HasEditable) { ((HasEditable)
		 * aTarget).setEditable(Utils.getBooleanAttribute(anElement, "editable",
		 * Boolean.TRUE)); }
		 */
		if (anElement.hasAttribute("emptyText") && aTarget instanceof HasEmptyText) {
			((HasEmptyText) aTarget).setEmptyText(anElement.getAttribute("emptyText"));
		}
		if (aTarget instanceof HasBinding) {
			if (anElement.hasAttribute("field")) {
				String fieldPath = anElement.getAttribute("field");
				try {
					((HasBinding) aTarget).setField(fieldPath);
				} catch (Exception ex) {
					Logger.getLogger(FormFactory.class.getName()).log(Level.SEVERE, "While setting field (" + fieldPath + ") to widget " + widgetName + " exception occured: " + ex.getMessage());
				}
			}
			if (anElement.hasAttribute("data")) {
				String entityName = anElement.getAttribute("data");
				try {
					((HasBinding) aTarget).setData(resolveEntity(entityName));
				} catch (Exception ex) {
					Logger.getLogger(FormFactory.class.getName()).log(Level.SEVERE,
					        "While setting data to named model's property (" + entityName + ") to widget " + widgetName + " exception occured: " + ex.getMessage());
				}
			}
		}
		if (aTarget instanceof HasEnabled)
			((HasEnabled) aTarget).setEnabled(Utils.getBooleanAttribute(anElement, "enabled", Boolean.TRUE));
		// aTarget.setFocusable(Utils.getBooleanAttribute(anElement,
		// "focusable", Boolean.TRUE));
		if (aTarget instanceof Widget && aTarget instanceof HasPublished) {
			PublishedComponent pComp = ((HasPublished) aTarget).getPublished().cast();
			PublishedFont font = readFont(anElement);
			if (font != null) {
				pComp.setFont(font);
			}
			if (anElement.hasAttribute("opaque")) {
				pComp.setOpaque(Utils.getBooleanAttribute(anElement, "opaque", Boolean.TRUE));
			}
			if (anElement.hasAttribute("background")) {
				PublishedColor background = ControlsUtils.parseColor(anElement.getAttribute("background"));
				pComp.setBackground(background);
			}
			if (anElement.hasAttribute("foreground")) {
				PublishedColor foreground = ControlsUtils.parseColor(anElement.getAttribute("foreground"));
				pComp.setForeground(foreground);
			}
			if (anElement.hasAttribute("toolTipText")) {
				pComp.setToolTipText(anElement.getAttribute("toolTipText"));
			}
		}
		if (anElement.hasAttribute("visible")) {
			aTarget.setVisible(Utils.getBooleanAttribute(anElement, "visible", Boolean.TRUE));
		}
		if (anElement.hasAttribute("componentPopupMenu") && aTarget instanceof HasComponentPopupMenu) {
			final String popupName = anElement.getAttribute("componentPopupMenu");
			if (!popupName.isEmpty()) {
				resolvers.add(new Runnable() {
					public void run() {
						UIObject popup = widgets.get(popupName);
						if (popup instanceof PlatypusPopupMenu) {
							((HasComponentPopupMenu) aTarget).setPlatypusPopupMenu((PlatypusPopupMenu) popup);
						}
					}
				});
			}
		}
		if (anElement.hasAttribute("buttonGroup") && aTarget instanceof HasPlatypusButtonGroup) {
			final String buttonGroupName = anElement.getAttribute("buttonGroup");
			if (!buttonGroupName.isEmpty()) {
				resolvers.add(new Runnable() {
					public void run() {
						UIObject buttonGroup = widgets.get(buttonGroupName);
						if (buttonGroup instanceof ButtonGroup) {
							ButtonGroup bg = (ButtonGroup) buttonGroup;
							bg.add((HasValue<Boolean>) aTarget);
						}
					}
				});
			}
		}
		if (anElement.hasAttribute("parent")) {
			final String parentName = anElement.getAttribute("parent");
			if (!parentName.isEmpty()) {
				resolvers.add(new Runnable() {
					public void run() {
						UIObject parent = widgets.get(parentName);
						try {
							addToParent(anElement, aTarget, parent);
						} catch (Exception ex) {
							ex.printStackTrace();
						}
					}
				});
			}
		}
		if (aTarget instanceof Widget && aTarget instanceof HasPublished && !(aTarget instanceof PlatypusMenu)) {
			Dimension prefSize = readPrefSize(anElement);
			if (prefSize != null) {
				PublishedComponent pComp = ((HasPublished) aTarget).getPublished().<PublishedComponent> cast();
				pComp.setWidth(prefSize.width);
				pComp.setHeight(prefSize.height);
			}
		}
	}

	protected PublishedFont readFont(Element anElement) throws Exception {
		PublishedFont font = readFontTag(anElement, "font");
		if (font != null) {
			return font;
		} else {
			return null;
		}
	}

	private PublishedFont readFontTag(Element anElement, String aSubTagName) throws Exception {
		Element easFontElement = Utils.getElementByTagName(anElement, aSubTagName);
		if (easFontElement != null) {
			String name = easFontElement.getAttribute("name");
			if (name == null || name.isEmpty()) {
				name = "Arial";
			}
			int style = Utils.getIntegerAttribute(easFontElement, "style", 0);
			int size = Utils.getIntegerAttribute(easFontElement, "size", 12);
			return PublishedFont.create(name, style, size);
		} else {
			return null;
		}
	}

	private void addToParent(Element anElement, UIObject aTarget, UIObject parent) throws Exception {
		if (parent instanceof PlatypusMenu) {
			((PlatypusMenu) parent).add(aTarget);
		} else if (parent instanceof PlatypusMenuBar) {
			((PlatypusMenuBar) parent).add(aTarget);
		} else if (parent instanceof PlatypusPopupMenu) {
			((PlatypusPopupMenu) parent).add(aTarget);
		} else if (parent instanceof ToolBar) {
			((ToolBar) parent).add((Widget) aTarget);
		} else if (parent instanceof TabbedPane) {
			Element constraintsElement = Utils.getElementByTagName(anElement, TabbedPane.class.getSimpleName() + "Constraints");
			String tabTitle = constraintsElement.getAttribute("tabTitle");
			String tabIconName = constraintsElement.getAttribute("tabIcon");
			String tabTooltipText = constraintsElement.getAttribute("tabTooltipText");
			((TabbedPane) parent).add((Widget) aTarget, tabTitle, false, null);
			// ((TabbedPane) parent).add(aTarget, tabTitle,
			// resolveIcon(tabIconName));
		} else if (parent instanceof SplitPane) {
			// Split pane children are:
			// - left component
			// - right component
			// Theese children are setted while resolving component references
			// of a split pane.
		} else if (parent instanceof ScrollPane) {
			ScrollPane scroll = (ScrollPane) parent;
			// Dimension prefSize = readPrefSize(anElement);
			// aTarget.setSize(prefSize.width + "px", prefSize.height + "px");
			scroll.setWidget((Widget) aTarget);
		} else if (parent instanceof BorderPane) {
			Element constraintsElement = Utils.getElementByTagName(anElement, "BorderPaneConstraints");
			Dimension prefSize = readPrefSize(anElement);
			Integer place = Utils.getIntegerAttribute(constraintsElement, "place", HorizontalPosition.CENTER);
			Integer size = 0;
			switch (place) {
			case HorizontalPosition.LEFT:
				size = prefSize.width;
				break;
			case HorizontalPosition.RIGHT:
				size = prefSize.width;
				break;
			case VerticalPosition.TOP:
				size = prefSize.height;
				break;
			case VerticalPosition.BOTTOM:
				size = prefSize.height;
				break;
			}
			BorderPane borderPane = (BorderPane) parent;
			borderPane.add((Widget) aTarget, place, size);
		} else if (parent instanceof BoxPane) {
			Dimension prefSize = readPrefSize(anElement);
			BoxPane box = (BoxPane) parent;
			if (box.getOrientation() == Orientation.HORIZONTAL) {
				box.add((Widget) aTarget, prefSize.width);
			} else {
				box.add((Widget) aTarget, prefSize.height);
			}
		} else if (parent instanceof CardPane) {
			Element constraintsElement = Utils.getElementByTagName(anElement, "CardPaneConstraints");
			String cardName = constraintsElement.getAttribute("cardName");
			((CardPane) parent).add((Widget) aTarget, cardName);
		} else if (parent instanceof FlowPane) {
			// Dimension prefSize = readPrefSize(anElement);
			// aTarget.setSize(prefSize.width + "px", prefSize.height + "px");
			((FlowPane) parent).add((Widget) aTarget);
		} else if (parent instanceof GridPane) {
			GridPane gridPane = (GridPane) parent;
			gridPane.addToFreeCell((Widget) aTarget);
		} else if (parent instanceof AnchorsPane) {
			Element constraintsElement = Utils.getElementByTagName(anElement, "AnchorsPaneConstraints");
			MarginConstraints constraints = readMarginConstraints(constraintsElement);
			((AnchorsPane) parent).add((Widget) aTarget, constraints);
		}
	}

	private static MarginConstraints readMarginConstraints(Element anElement) {
		MarginConstraints result = new MarginConstraints();
		if (anElement.hasAttribute("left")) {
			result.setLeft(MarginConstraints.Margin.parse(anElement.getAttribute("left")));
		}
		if (anElement.hasAttribute("right")) {
			result.setRight(MarginConstraints.Margin.parse(anElement.getAttribute("right")));
		}
		if (anElement.hasAttribute("top")) {
			result.setTop(MarginConstraints.Margin.parse(anElement.getAttribute("top")));
		}
		if (anElement.hasAttribute("bottom")) {
			result.setBottom(MarginConstraints.Margin.parse(anElement.getAttribute("bottom")));
		}
		if (anElement.hasAttribute("width")) {
			result.setWidth(MarginConstraints.Margin.parse(anElement.getAttribute("width")));
		}
		if (anElement.hasAttribute("height")) {
			result.setHeight(MarginConstraints.Margin.parse(anElement.getAttribute("height")));
		}
		return result;
	}

	private List<HeaderNode<JavaScriptObject>> readColumns(Element aColumnsElement) throws Exception {
		List<HeaderNode<JavaScriptObject>> nodes = new ArrayList<>();
		Node childNode = aColumnsElement.getFirstChild();
		while (childNode != null) {
			if (childNode instanceof Element) {
				Element childTag = (Element) childNode;
				String columnType = childTag.getTagName();
				switch (columnType) {
				case "CheckGridColumn": {
					CheckHeaderNode column = new CheckHeaderNode();
					Publisher.publish(column);
					readColumnNode(column, childTag);
					nodes.add(column);
					List<HeaderNode<JavaScriptObject>> children = readColumns(childTag);
					for (int i = 0; i < children.size(); i++) {
						column.addColumnNode(children.get(i));
					}
					break;
				}
				case "RadioGridColumn": {
					RadioHeaderNode column = new RadioHeaderNode();
					Publisher.publish(column);
					readColumnNode(column, childTag);
					nodes.add(column);
					List<HeaderNode<JavaScriptObject>> children = readColumns(childTag);
					for (int i = 0; i < children.size(); i++) {
						column.addColumnNode(children.get(i));
					}
					break;
				}
				case "ServiceGridColumn": {
					ServiceHeaderNode column = new ServiceHeaderNode();
					Publisher.publish(column);
					readColumnNode(column, childTag);
					nodes.add(column);
					List<HeaderNode<JavaScriptObject>> children = readColumns(childTag);
					for (int i = 0; i < children.size(); i++) {
						column.addColumnNode(children.get(i));
					}
					break;
				}
				case "ModelGridColumn": {
					ModelHeaderNode column = new ModelHeaderNode();
					Publisher.publish(column);
					readColumnNode(column, childTag);
					if (childTag.hasAttribute("field")) {
						column.setField(childTag.getAttribute("field"));
					}
					if (childTag.hasAttribute("sortField")) {
						column.setSortField(childTag.getAttribute("sortField"));
					}
					Node _childNode = childTag.getFirstChild();
					while (_childNode != null) {
						if (_childNode instanceof Element) {
							Element _childTag = (Element) _childNode;
							UIObject editorComp = readWidget(_childTag);
							if (editorComp instanceof ModelDecoratorBox<?>) {
								ModelColumn col = (ModelColumn) column.getColumn();
								col.setEditor((ModelDecoratorBox<Object>) editorComp);
								// ModelWidget viewComp = (ModelWidget)
								// readWidget((Element) _childNode);
								// col.setView(viewComp);
								break;
							}
						}
						_childNode = _childNode.getNextSibling();
					}
					nodes.add(column);
					List<HeaderNode<JavaScriptObject>> children = readColumns(childTag);
					for (int i = 0; i < children.size(); i++) {
						column.addColumnNode(children.get(i));
					}
					break;
				}
				}
			}
			childNode = childNode.getNextSibling();
		}
		return nodes;
	}

	private void readColumnNode(ModelHeaderNode aNode, Element anElement) throws Exception {
		aNode.setJsName(anElement.getAttribute("name"));
		if (anElement.hasAttribute("title")) {
			aNode.setTitle(anElement.getAttribute("title"));
		}
		if (anElement.hasAttribute("background")) {
			PublishedColor background = ControlsUtils.parseColor(anElement.getAttribute("background"));
			aNode.setBackground(background);
		}
		if (anElement.hasAttribute("foreground")) {
			PublishedColor foreground = ControlsUtils.parseColor(anElement.getAttribute("foreground"));
			aNode.setForeground(foreground);
		}
		aNode.setReadonly(Utils.getBooleanAttribute(anElement, "readonly", Boolean.FALSE));
		// aNode.setEnabled(Utils.getBooleanAttribute(anElement, "enabled",
		// Boolean.TRUE));
		PublishedFont font = readFont(anElement);
		if (font != null) {
			aNode.setFont(font);
		}
		if (anElement.hasAttribute("minWidth")) {
			String minWidth = anElement.getAttribute("minWidth");
			if (minWidth.length() > 2 && minWidth.endsWith("px")) {
				aNode.setMinWidth(Integer.parseInt(minWidth.substring(0, minWidth.length() - 2)));
			}
		}
		if (anElement.hasAttribute("maxWidth")) {
			String maxWidth = anElement.getAttribute("maxWidth");
			if (maxWidth.length() > 2 && maxWidth.endsWith("px")) {
				aNode.setMaxWidth(Integer.parseInt(maxWidth.substring(0, maxWidth.length() - 2)));
			}
		}
		if (anElement.hasAttribute("preferredWidth")) {
			String preferredWidth = anElement.getAttribute("preferredWidth");
			if (preferredWidth.length() > 2 && preferredWidth.endsWith("px")) {
				aNode.setPreferredWidth(Integer.parseInt(preferredWidth.substring(0, preferredWidth.length() - 2)));
			}
		}
		aNode.setMoveable(Utils.getBooleanAttribute(anElement, "movable", Boolean.TRUE));
		aNode.setResizable(Utils.getBooleanAttribute(anElement, "resizable", aNode instanceof CheckHeaderNode || aNode instanceof RadioHeaderNode || aNode instanceof ServiceHeaderNode ? Boolean.FALSE
		        : Boolean.TRUE));
		// aNode.setSelectOnly(Utils.getBooleanAttribute(anElement,
		// "selectOnly", Boolean.FALSE));
		aNode.setSortable(Utils.getBooleanAttribute(anElement, "sortable", Boolean.TRUE));
		aNode.setVisible(Utils.getBooleanAttribute(anElement, "visible", Boolean.TRUE));
	}
}


text:
package java.rmi;

import java.security.*;

/**
 * A subclass of {@link SecurityManager} used by RMI applications that use
 * downloaded code.  RMI's class loader will not download any classes from
 * remote locations if no security manager has been set.
 * RMISecurityManager does not apply to applets, which run
 * under the protection of their browser's security manager.
 *
 * RMISecurityManager implements a policy that
 * is no different than the policy implemented by {@link SecurityManager}.
 * Therefore an RMI application should use the SecurityManager
 * class or another application-specific SecurityManager
 * implementation instead of this class.
 *
 *
To use a SecurityManager in your application, add
 * the following statement to your code (it needs to be executed before RMI
 * can download code from remote hosts, so it most likely needs to appear
 * in the main method of your application):
 *
 *

 * System.setSecurityManager(new SecurityManager());
 *

 *
 * @author  Roger Riggs
 * @author  Peter Jones
 * @since JDK1.1
 **/
public class RMISecurityManager extends SecurityManager {

    /**
     * Constructs a new RMISecurityManager.
     * @since JDK1.1
     */
    public RMISecurityManager() {
    }
}

redpajama_set_name: RedPajamaGithub


text:
package br.ufc.mdcc.mpos.util;

/**
 * This interface maybe be used inside <AsyncTask>, for get some intermediaries
 * results.
 *
 * @author Philipp B. Costa
 */
public interface TaskResult<T> {
	void completedTask(T obj);

	void taskOnGoing(int completed);

	void taskOnGoing(int completed, String statusText);
}


text:
#include "file_util.h"

// int
// tokenizer()
// {
//   const char str[80] = "This is - www.tutorialspoint.com - website";
//   const char s[2] = "-";
//   char *token;

//   /* get the first token */
//   token = strtok(str, s);

//   /* walk through other tokens */
//   while( token != NULL )
//   {
//     printf( " %s\n", token );

//     token = strtok(NULL, s);
//   }

//   return(0);
// }

/**
  Initializes and return a general purpose table
  @param size: the size of the char array
  @return poiter to buffer
*/
table_t*
give_me_a_table(
  size_t size )
{
  table_t *buffer = NULL;
  char *data = NULL;

  size_t reserved_size = size + 1;

  buffer = (table_t *) malloc( sizeof( table_t ) );
  memset( buffer, 0, sizeof( table_t ) );

  data = (char *) malloc (sizeof(char) * reserved_size);

  buffer->pk     = 0;
  buffer->column = data;
  buffer->column_length = strlen( buffer->column );
  buffer->column_allocated_size = reserved_size;

  return buffer;
}

void
assign_column_data_to_table(
  table_t *source,
  const char *string )
{
  size_t data_length = strlen( string );

  if ( data_length > source->column_allocated_size ) {
    die("You tried to put a bigger array that your buffer can hold");
  }

  strncpy( source->column, string, data_length ); // Avoid buffer overflows
  source->column_length = data_length;

}

size_t
find_the_size_of_a_file( FILE *file ) {
  size_t size = 0;

  fseek(file, 0L, SEEK_END);
  size = ftell(file);
  fseek(file, 0L, SEEK_SET);

  return size;
}

off_t
find_the_size_of_a_regularfile( char *filename )
{
  struct stat stbuf;
  int fd;

  fd = open( filename, O_RDONLY );
  if (fd == -1) {
    FILE *a = fopen( filename, "w");
    fclose(a);
  }

  if ( (fstat(fd, &stbuf) != 0) || ( !S_ISREG(stbuf.st_mode) ) ) { /* Handle error */ }

  return stbuf.st_size;
}

void
assign_column_pk_to_table(
  table_t *source,
  const off_t pk )
{
  source->pk = pk;
}

int
write_table_to_text_file(
  char *filename,
  table_t *table,
  int FILETYPE )
{
  FILE *file = NULL;

  off_t id = find_the_size_of_a_regularfile( filename );

  if ( (file = fopen( filename, "a" )) ) {

    assign_column_pk_to_table( table, id );

    fputs( table->column, file );

    fclose(file);
  } /* END_WHILE_FEOF_FILE*/
  else {
    perror("auheuhaeuhae");
    return 0;
  }

  return 1;
}

int
write_table_to_bin_file(
  char *filename,
  table_t *table,
  int FILETYPE )
{
  FILE *file = NULL;

  off_t id = find_the_size_of_a_regularfile( filename );

  if ( (file = fopen( filename, "a" )) ) {

    assign_column_pk_to_table( table, id );

    fwrite( table, sizeof(table_t), 1, file );

    fclose(file);
  } /* END_WHILE_FEOF_FILE*/
  else {
    perror("auheuhaeuhae");
    return 0;
  }

  return 1;
}

/**
  From: http://www.tutorialspoint.com/cprogramming/c_file_io.htm

  int fseek(FILE *stream, long int offset, int whence)

  SEEK_SET  Beginning of file
  SEEK_CUR  Current position of the file pointer
  SEEK_END  End of file

  FILE *fopen( const char * filename, const char * mode );

  r Opens an existing text file for reading purpose.
  w Opens a text file for writing, if it does not exist then a new file is created. Here your program will start writing content from the beginning of the file.
  a Opens a text file for writing in appending mode, if it does not exist then a new file is created. Here your program will start appending content in the existing file content.
  r+  Opens a text file for reading and writing both.
  w+  Opens a text file for reading and writing both. It first truncate the file to zero length if it exists otherwise create the file if it does not exist.
  a+  Opens a text file for reading and writing both. It creates the file if it does not exist. The reading will start from the beginning but writing can only be appended.

  "rb", "wb", "ab", "rb+", "r+b", "wb+", "w+b", "ab+", "a+b"

int fputc( int c, FILE *fp );
int fgetc( FILE * fp );
int fputs( const char *s, FILE *fp );
char *fgets( char *buf, int n, FILE *fp );

size_t fread(void *ptr, size_t size_of_elements,
             size_t number_of_elements, FILE *a_file);
size_t fwrite(const void *ptr, size_t size_of_elements,
             size_t number_of_elements, FILE *a_file);

*/

/**
  Error handler
*/
void
die( const char *message )
{
  if(errno) {
      perror(message);
  } else {
    printf("[ ERROR ] %s. {INFO: Use gdb to debbug}\n", message);
  }

  exit(1);
}

int main(int argc, char const *argv[])
{
  /* code */
  return 0;
}


text:
<?php include_once('header.php');?>

	<?php include_once('navbar.php');?>

<a href="<?php echo base_url()."index.php/students/";?>">Manage Students

<a href="<?php echo base_url()."/index.php/notices/";?>">Notices(current)

<a href="<?php echo base_url()."/index.php/batch/";?>">Batch management

<a href="<?php echo base_url()."index.php/form";?>">Programe mangement

<a href="<?php echo base_url()."index.php/AddAdmin";?>">Admin management

		<?php include_once('navbar_right.php');?>

					Admin stuff

				<?php include_once('sidebar.php');?>

		<?php include_once('footer.php');?>


text:
from riskmetrics import riskmetrics

def test_construct_cpe():
    cpe = riskmetrics.construct_cpe("vendor", "product", "0.1")
    assert cpe == 'cpe:/a:vendor:product:0.1'

def test_get_latest_version():
    version = riskmetrics.get_latest_version("35g3q", "fq34gf")
    assert version == ""


text:
{-# OPTIONS_GHC -fno-warn-type-defaults #-}
{-# OPTIONS_GHC -fno-warn-orphans       #-}

module Math.NumberTheory.EisensteinIntegersBench
  ( benchSuite
  ) where

import Data.Maybe
import Gauge.Main

import Math.NumberTheory.ArithmeticFunctions (tau)
import Math.NumberTheory.Primes (isPrime)
import Math.NumberTheory.Quadratic.EisensteinIntegers

benchFindPrime :: Integer -> Benchmark
benchFindPrime n = bench (show n) $ nf findPrime (fromJust (isPrime n))

benchTau :: Integer -> Benchmark
benchTau n = bench (show n) $ nf (\m -> sum [tau (x :+ y) | x <- [1..m], y <- [0..m]] :: Word) n

benchSuite :: Benchmark
benchSuite = bgroup "Eisenstein"
  [ bgroup "findPrime" $ map benchFindPrime [1000003, 10000141, 100000039, 1000000021, 10000000033, 100000000003, 1000000000039, 10000000000051]
  , bgroup "tau" $ map benchTau [10, 20, 40, 80]
  ]


text:
using System;
using System.Runtime.CompilerServices;
using EnvDTE;

#if VS10 || VS11 || VS12
using NuGetVS = NuGet.VisualStudio12;
#endif

#if VS14
using NuGetVS = NuGet.VisualStudio14;
#endif

namespace NuGet.VisualStudio
{
    public abstract class CpsProjectSystem : VsProjectSystem
    {
        protected CpsProjectSystem(Project project, IFileSystemProvider fileSystemProvider) :
            base(project, fileSystemProvider)
        {
        }

        public override bool IsBindingRedirectSupported
        {
            get
            {
                return false;
            }
        }

        protected override void AddGacReference(string name)
        {
            // Native & JS projects don't know about GAC
        }

        public override void AddImport(string targetPath, ProjectImportLocation location)
        {
            if (VsVersionHelper.IsVisualStudio2010)
            {
                base.AddImport(targetPath, location);
            }
            else
            {
                // For VS 2012 or above, the operation has to be done inside the Writer lock
                if (String.IsNullOrEmpty(targetPath))
                {
                    throw new ArgumentNullException(CommonResources.Argument_Cannot_Be_Null_Or_Empty, "targetPath");
                }

                string relativeTargetPath = PathUtility.GetRelativePath(PathUtility.EnsureTrailingSlash(Root), targetPath);
                if (VsVersionHelper.IsVisualStudio2012)
                {
                    Project.DoWorkInWriterLock(buildProject => NuGet.MSBuildProjectUtility.AddImportStatement(buildProject, relativeTargetPath, location));
                    Project.Save(this);
                }
                else
                {
                    AddImportStatementForVS2013(location, relativeTargetPath);
                }
            }
        }

        // IMPORTANT: The NoInlining is required to prevent CLR from loading VisualStudio12.dll assembly while running
        // in VS2010 and VS2012
        [MethodImpl(MethodImplOptions.NoInlining)]
        private void AddImportStatementForVS2013(ProjectImportLocation location, string relativeTargetPath)
        {
            NuGetVS.ProjectHelper.DoWorkInWriterLock(
                Project,
                Project.ToVsHierarchy(),
                buildProject => NuGet.MSBuildProjectUtility.AddImportStatement(buildProject, relativeTargetPath, location));

            // notify the project system of the change
            UpdateImportStamp(Project);
        }

        public override void RemoveImport(string targetPath)
        {
            if (VsVersionHelper.IsVisualStudio2010)
            {
                base.RemoveImport(targetPath);
            }
            else
            {
                if (String.IsNullOrEmpty(targetPath))
                {
                    throw new ArgumentNullException(CommonResources.Argument_Cannot_Be_Null_Or_Empty, "targetPath");
                }

                // For VS 2012 or above, the operation has to be done inside the Writer lock
                string relativeTargetPath = PathUtility.GetRelativePath(PathUtility.EnsureTrailingSlash(Root), targetPath);
                if (VsVersionHelper.IsVisualStudio2012)
                {
                    Project.DoWorkInWriterLock(buildProject => NuGet.MSBuildProjectUtility.RemoveImportStatement(buildProject, relativeTargetPath));
                    Project.Save(this);
                }
                else
                {
                    RemoveImportStatementForVS2013(relativeTargetPath);
                }
            }
        }

        // IMPORTANT: The NoInlining is required to prevent CLR from loading VisualStudio12.dll assembly while running
        // in VS2010 and VS2012
        [MethodImpl(MethodImplOptions.NoInlining)]
        private void RemoveImportStatementForVS2013(string relativeTargetPath)
        {
            NuGetVS.ProjectHelper.DoWorkInWriterLock(
                Project,
                Project.ToVsHierarchy(),
                buildProject => NuGet.MSBuildProjectUtility.RemoveImportStatement(buildProject, relativeTargetPath));

            // notify the project system of the change
            UpdateImportStamp(Project);
        }
    }
}


text:
#include <linux/module.h>
#include <linux/init.h>
#include <linux/slab.h>
#include <linux/page-flags.h>
#include <linux/device.h>
#include <linux/dma-mapping.h>
#include <linux/dmapool.h>
#include <linux/list.h>
#include <linux/scatterlist.h>

#include <asm/cacheflush.h>

#undef STATS

#ifdef STATS
#define DO_STATS(X) do { X ; } while (0)
#else
#define DO_STATS(X) do { } while (0)
#endif

/* ************************************************** */

struct safe_buffer {
	struct list_head node;

	/* original request */
	void		*ptr;
	size_t		size;
	int		direction;

	/* safe buffer info */
	struct dmabounce_pool *pool;
	void		*safe;
	dma_addr_t	safe_dma_addr;
};

struct dmabounce_pool {
	unsigned long	size;
	struct dma_pool	*pool;
#ifdef STATS
	unsigned long	allocs;
#endif
};

struct dmabounce_device_info {
	struct device *dev;
	struct list_head safe_buffers;
#ifdef STATS
	unsigned long total_allocs;
	unsigned long map_op_count;
	unsigned long bounce_count;
	int attr_res;
#endif
	struct dmabounce_pool	small;
	struct dmabounce_pool	large;

	rwlock_t lock;

	int (*needs_bounce)(struct device *, dma_addr_t, size_t);
};

#ifdef STATS
static ssize_t dmabounce_show(struct device *dev, struct device_attribute *attr,
			      char *buf)
{
	struct dmabounce_device_info *device_info = dev->archdata.dmabounce;
	return sprintf(buf, "%lu %lu %lu %lu %lu %lu\n",
		device_info->small.allocs,
		device_info->large.allocs,
		device_info->total_allocs - device_info->small.allocs -
			device_info->large.allocs,
		device_info->total_allocs,
		device_info->map_op_count,
		device_info->bounce_count);
}

static DEVICE_ATTR(dmabounce_stats, 0400, dmabounce_show, NULL);
#endif

/* allocate a 'safe' buffer and keep track of it */
static inline struct safe_buffer *
alloc_safe_buffer(struct dmabounce_device_info *device_info, void *ptr,
		  size_t size, enum dma_data_direction dir)
{
	struct safe_buffer *buf;
	struct dmabounce_pool *pool;
	struct device *dev = device_info->dev;
	unsigned long flags;

	dev_dbg(dev, "%s(ptr=%p, size=%d, dir=%d)\n",
		__func__, ptr, size, dir);

	if (size <= device_info->small.size) {
		pool = &device_info->small;
	} else if (size <= device_info->large.size) {
		pool = &device_info->large;
	} else {
		pool = NULL;
	}

	buf = kmalloc(sizeof(struct safe_buffer), GFP_ATOMIC);
	if (buf == NULL) {
		dev_warn(dev, "%s: kmalloc failed\n", __func__);
		return NULL;
	}

	buf->ptr = ptr;
	buf->size = size;
	buf->direction = dir;
	buf->pool = pool;

	if (pool) {
		buf->safe = dma_pool_alloc(pool->pool, GFP_ATOMIC,
					   &buf->safe_dma_addr);
	} else {
		buf->safe = dma_alloc_coherent(dev, size, &buf->safe_dma_addr,
					       GFP_ATOMIC);
	}

	if (buf->safe == NULL) {
		dev_warn(dev,
			 "%s: could not alloc dma memory (size=%d)\n",
			 __func__, size);
		kfree(buf);
		return NULL;
	}

#ifdef STATS
	if (pool)
		pool->allocs++;
	device_info->total_allocs++;
#endif

	write_lock_irqsave(&device_info->lock, flags);
	list_add(&buf->node, &device_info->safe_buffers);
	write_unlock_irqrestore(&device_info->lock, flags);

	return buf;
}

/* determine if a buffer is from our "safe" pool */
static inline struct safe_buffer *
find_safe_buffer(struct dmabounce_device_info *device_info, dma_addr_t safe_dma_addr)
{
	struct safe_buffer *b, *rb = NULL;
	unsigned long flags;

	read_lock_irqsave(&device_info->lock, flags);

	list_for_each_entry(b, &device_info->safe_buffers, node)
		if (b->safe_dma_addr <= safe_dma_addr &&
		    b->safe_dma_addr + b->size > safe_dma_addr) {
			rb = b;
			break;
		}

	read_unlock_irqrestore(&device_info->lock, flags);
	return rb;
}

static inline void
free_safe_buffer(struct dmabounce_device_info *device_info, struct safe_buffer *buf)
{
	unsigned long flags;

	dev_dbg(device_info->dev, "%s(buf=%p)\n", __func__, buf);

	write_lock_irqsave(&device_info->lock, flags);

	list_del(&buf->node);

	write_unlock_irqrestore(&device_info->lock, flags);

	if (buf->pool)
		dma_pool_free(buf->pool->pool, buf->safe, buf->safe_dma_addr);
	else
		dma_free_coherent(device_info->dev, buf->size, buf->safe,
				    buf->safe_dma_addr);

	kfree(buf);
}

/* ************************************************** */

static struct safe_buffer *find_safe_buffer_dev(struct device *dev,
		dma_addr_t dma_addr, const char *where)
{
	if (!dev || !dev->archdata.dmabounce)
		return NULL;
	if (dma_mapping_error(dev, dma_addr)) {
		dev_err(dev, "Trying to %s invalid mapping\n", where);
		return NULL;
	}
	return find_safe_buffer(dev->archdata.dmabounce, dma_addr);
}

static int needs_bounce(struct device *dev, dma_addr_t dma_addr, size_t size)
{
	if (!dev || !dev->archdata.dmabounce)
		return 0;

	if (dev->dma_mask) {
		unsigned long limit, mask = *dev->dma_mask;

		limit = (mask + 1) & ~mask;
		if (limit && size > limit) {
			dev_err(dev, "DMA mapping too big (requested %#x "
				"mask %#Lx)\n", size, *dev->dma_mask);
			return -E2BIG;
		}

		/* Figure out if we need to bounce from the DMA mask. */
		if ((dma_addr | (dma_addr + size - 1)) & ~mask)
			return 1;
	}

	return !!dev->archdata.dmabounce->needs_bounce(dev, dma_addr, size);
}

static inline dma_addr_t map_single(struct device *dev, void *ptr, size_t size,
		enum dma_data_direction dir)
{
	struct dmabounce_device_info *device_info = dev->archdata.dmabounce;
	struct safe_buffer *buf;

	if (device_info)
		DO_STATS ( device_info->map_op_count++ );

	buf = alloc_safe_buffer(device_info, ptr, size, dir);
	if (buf == NULL) {
		dev_err(dev, "%s: unable to map unsafe buffer %p!\n",
		       __func__, ptr);
		return DMA_ERROR_CODE;
	}

	dev_dbg(dev, "%s: unsafe buffer %p (dma=%#x) mapped to %p (dma=%#x)\n",
		__func__, buf->ptr, virt_to_dma(dev, buf->ptr),
		buf->safe, buf->safe_dma_addr);

	if (dir == DMA_TO_DEVICE || dir == DMA_BIDIRECTIONAL) {
		dev_dbg(dev, "%s: copy unsafe %p to safe %p, size %d\n",
			__func__, ptr, buf->safe, size);
		memcpy(buf->safe, ptr, size);
	}

	return buf->safe_dma_addr;
}

static inline void unmap_single(struct device *dev, struct safe_buffer *buf,
		size_t size, enum dma_data_direction dir)
{
	BUG_ON(buf->size != size);
	BUG_ON(buf->direction != dir);

	dev_dbg(dev, "%s: unsafe buffer %p (dma=%#x) mapped to %p (dma=%#x)\n",
		__func__, buf->ptr, virt_to_dma(dev, buf->ptr),
		buf->safe, buf->safe_dma_addr);

	DO_STATS(dev->archdata.dmabounce->bounce_count++);

	if (dir == DMA_FROM_DEVICE || dir == DMA_BIDIRECTIONAL) {
		void *ptr = buf->ptr;

		dev_dbg(dev, "%s: copy back safe %p to unsafe %p size %d\n",
			__func__, buf->safe, ptr, size);
		memcpy(ptr, buf->safe, size);

		/*
		 * Since we may have written to a page cache page,
		 * we need to ensure that the data will be coherent
		 * with user mappings.
		 */
		__cpuc_flush_dcache_area(ptr, size);
	}
	free_safe_buffer(dev->archdata.dmabounce, buf);
}

/* ************************************************** */

/*
 * see if a buffer address is in an 'unsafe' range.  if it is
 * allocate a 'safe' buffer and copy the unsafe buffer into it.
 * substitute the safe buffer for the unsafe one.
 * (basically move the buffer from an unsafe area to a safe one)
 */
static dma_addr_t dmabounce_map_page(struct device *dev, struct page *page,
		unsigned long offset, size_t size, enum dma_data_direction dir,
		struct dma_attrs *attrs)
{
	dma_addr_t dma_addr;
	int ret;

	dev_dbg(dev, "%s(page=%p,off=%#lx,size=%zx,dir=%x)\n",
		__func__, page, offset, size, dir);

	dma_addr = pfn_to_dma(dev, page_to_pfn(page)) + offset;

	ret = needs_bounce(dev, dma_addr, size);
	if (ret < 0)
		return DMA_ERROR_CODE;

	if (ret == 0) {
		arm_dma_ops.sync_single_for_device(dev, dma_addr, size, dir);
		return dma_addr;
	}

	if (PageHighMem(page)) {
		dev_err(dev, "DMA buffer bouncing of HIGHMEM pages is not supported\n");
		return DMA_ERROR_CODE;
	}

	return map_single(dev, page_address(page) + offset, size, dir);
}

/*
 * see if a mapped address was really a "safe" buffer and if so, copy
 * the data from the safe buffer back to the unsafe buffer and free up
 * the safe buffer.  (basically return things back to the way they
 * should be)
 */
static void dmabounce_unmap_page(struct device *dev, dma_addr_t dma_addr, size_t size,
		enum dma_data_direction dir, struct dma_attrs *attrs)
{
	struct safe_buffer *buf;

	dev_dbg(dev, "%s(dma=%#x,size=%d,dir=%x)\n",
		__func__, dma_addr, size, dir);

	buf = find_safe_buffer_dev(dev, dma_addr, __func__);
	if (!buf) {
		arm_dma_ops.sync_single_for_cpu(dev, dma_addr, size, dir);
		return;
	}

	unmap_single(dev, buf, size, dir);
}

static int __dmabounce_sync_for_cpu(struct device *dev, dma_addr_t addr,
		size_t sz, enum dma_data_direction dir)
{
	struct safe_buffer *buf;
	unsigned long off;

	dev_dbg(dev, "%s(dma=%#x,sz=%zx,dir=%x)\n",
		__func__, addr, sz, dir);

	buf = find_safe_buffer_dev(dev, addr, __func__);
	if (!buf)
		return 1;

	off = addr - buf->safe_dma_addr;

	BUG_ON(buf->direction != dir);

	dev_dbg(dev, "%s: unsafe buffer %p (dma=%#x off=%#lx) mapped to %p (dma=%#x)\n",
		__func__, buf->ptr, virt_to_dma(dev, buf->ptr), off,
		buf->safe, buf->safe_dma_addr);

	DO_STATS(dev->archdata.dmabounce->bounce_count++);

	if (dir == DMA_FROM_DEVICE || dir == DMA_BIDIRECTIONAL) {
		dev_dbg(dev, "%s: copy back safe %p to unsafe %p size %d\n",
			__func__, buf->safe + off, buf->ptr + off, sz);
		memcpy(buf->ptr + off, buf->safe + off, sz);
	}
	return 0;
}

static void dmabounce_sync_for_cpu(struct device *dev,
		dma_addr_t handle, size_t size, enum dma_data_direction dir)
{
	if (!__dmabounce_sync_for_cpu(dev, handle, size, dir))
		return;

	arm_dma_ops.sync_single_for_cpu(dev, handle, size, dir);
}

static int __dmabounce_sync_for_device(struct device *dev, dma_addr_t addr,
		size_t sz, enum dma_data_direction dir)
{
	struct safe_buffer *buf;
	unsigned long off;

	dev_dbg(dev, "%s(dma=%#x,sz=%zx,dir=%x)\n",
		__func__, addr, sz, dir);

	buf = find_safe_buffer_dev(dev, addr, __func__);
	if (!buf)
		return 1;

	off = addr - buf->safe_dma_addr;

	BUG_ON(buf->direction != dir);

	dev_dbg(dev, "%s: unsafe buffer %p (dma=%#x off=%#lx) mapped to %p (dma=%#x)\n",
		__func__, buf->ptr, virt_to_dma(dev, buf->ptr), off,
		buf->safe, buf->safe_dma_addr);

	DO_STATS(dev->archdata.dmabounce->bounce_count++);

	if (dir == DMA_TO_DEVICE || dir == DMA_BIDIRECTIONAL) {
		dev_dbg(dev, "%s: copy out unsafe %p to safe %p, size %d\n",
			__func__,buf->ptr + off, buf->safe + off, sz);
		memcpy(buf->safe + off, buf->ptr + off, sz);
	}
	return 0;
}

static void dmabounce_sync_for_device(struct device *dev,
		dma_addr_t handle, size_t size, enum dma_data_direction dir)
{
	if (!__dmabounce_sync_for_device(dev, handle, size, dir))
		return;

	arm_dma_ops.sync_single_for_device(dev, handle, size, dir);
}

static int dmabounce_set_mask(struct device *dev, u64 dma_mask)
{
	if (dev->archdata.dmabounce)
		return 0;

	return arm_dma_ops.set_dma_mask(dev, dma_mask);
}

static struct dma_map_ops dmabounce_ops = {
	.alloc			= arm_dma_alloc,
	.free			= arm_dma_free,
	.mmap			= arm_dma_mmap,
	.get_sgtable		= arm_dma_get_sgtable,
	.map_page		= dmabounce_map_page,
	.unmap_page		= dmabounce_unmap_page,
	.sync_single_for_cpu	= dmabounce_sync_for_cpu,
	.sync_single_for_device	= dmabounce_sync_for_device,
	.map_sg			= arm_dma_map_sg,
	.unmap_sg		= arm_dma_unmap_sg,
	.sync_sg_for_cpu	= arm_dma_sync_sg_for_cpu,
	.sync_sg_for_device	= arm_dma_sync_sg_for_device,
	.set_dma_mask		= dmabounce_set_mask,
};

static int dmabounce_init_pool(struct dmabounce_pool *pool, struct device *dev,
		const char *name, unsigned long size)
{
	pool->size = size;
	DO_STATS(pool->allocs = 0);
	pool->pool = dma_pool_create(name, dev, size,
				     0 /* byte alignment */,
				     0 /* no page-crossing issues */);

	return pool->pool ? 0 : -ENOMEM;
}

int dmabounce_register_dev(struct device *dev, unsigned long small_buffer_size,
		unsigned long large_buffer_size,
		int (*needs_bounce_fn)(struct device *, dma_addr_t, size_t))
{
	struct dmabounce_device_info *device_info;
	int ret;

	device_info = kmalloc(sizeof(struct dmabounce_device_info), GFP_ATOMIC);
	if (!device_info) {
		dev_err(dev,
			"Could not allocated dmabounce_device_info\n");
		return -ENOMEM;
	}

	ret = dmabounce_init_pool(&device_info->small, dev,
				  "small_dmabounce_pool", small_buffer_size);
	if (ret) {
		dev_err(dev,
			"dmabounce: could not allocate DMA pool for %ld byte objects\n",
			small_buffer_size);
		goto err_free;
	}

	if (large_buffer_size) {
		ret = dmabounce_init_pool(&device_info->large, dev,
					  "large_dmabounce_pool",
					  large_buffer_size);
		if (ret) {
			dev_err(dev,
				"dmabounce: could not allocate DMA pool for %ld byte objects\n",
				large_buffer_size);
			goto err_destroy;
		}
	}

	device_info->dev = dev;
	INIT_LIST_HEAD(&device_info->safe_buffers);
	rwlock_init(&device_info->lock);
	device_info->needs_bounce = needs_bounce_fn;

#ifdef STATS
	device_info->total_allocs = 0;
	device_info->map_op_count = 0;
	device_info->bounce_count = 0;
	device_info->attr_res = device_create_file(dev, &dev_attr_dmabounce_stats);
#endif

	dev->archdata.dmabounce = device_info;
	set_dma_ops(dev, &dmabounce_ops);

	dev_info(dev, "dmabounce: registered device\n");

	return 0;

 err_destroy:
	dma_pool_destroy(device_info->small.pool);
 err_free:
	kfree(device_info);
	return ret;
}
EXPORT_SYMBOL(dmabounce_register_dev);

void dmabounce_unregister_dev(struct device *dev)
{
	struct dmabounce_device_info *device_info = dev->archdata.dmabounce;

	dev->archdata.dmabounce = NULL;
	set_dma_ops(dev, NULL);

	if (!device_info) {
		dev_warn(dev,
			 "Never registered with dmabounce but attempting"
			 "to unregister!\n");
		return;
	}

	if (!list_empty(&device_info->safe_buffers)) {
		dev_err(dev,
			"Removing from dmabounce with pending buffers!\n");
		BUG();
	}

	if (device_info->small.pool)
		dma_pool_destroy(device_info->small.pool);
	if (device_info->large.pool)
		dma_pool_destroy(device_info->large.pool);

#ifdef STATS
	if (device_info->attr_res == 0)
		device_remove_file(dev, &dev_attr_dmabounce_stats);
#endif

	kfree(device_info);

	dev_info(dev, "dmabounce: device unregistered\n");
}
EXPORT_SYMBOL(dmabounce_unregister_dev);

MODULE_AUTHOR("Christopher Hoover <ch@hpl.hp.com>, Deepak Saxena <dsaxena@plexity.net>");
MODULE_DESCRIPTION("Special dma_{map/unmap/dma_sync}_* routines for systems with limited DMA windows");
MODULE_LICENSE("GPL");


text:
""" Caching facility for SymPy """
from __future__ import print_function, division

from distutils.version import LooseVersion as V

class _cache(list):
    """ List of cached functions """

    def print_cache(self):
        """print cache info"""

        for item in self:
            name = item.__name__
            myfunc = item
            while hasattr(myfunc, '__wrapped__'):
                if hasattr(myfunc, 'cache_info'):
                    info = myfunc.cache_info()
                    break
                else:
                    myfunc = myfunc.__wrapped__
            else:
                info = None

            print(name, info)

    def clear_cache(self):
        """clear cache content"""
        for item in self:
            myfunc = item
            while hasattr(myfunc, '__wrapped__'):
                if hasattr(myfunc, 'cache_clear'):
                    myfunc.cache_clear()
                    break
                else:
                    myfunc = myfunc.__wrapped__

# global cache registry:
CACHE = _cache()
# make clear and print methods available
print_cache = CACHE.print_cache
clear_cache = CACHE.clear_cache

from sympy.core.compatibility import lru_cache
from functools import update_wrapper

try:
    import fastcache
    from warnings import warn
    # the version attribute __version__ is not present for all versions
    if not hasattr(fastcache, '__version__'):
        warn("fastcache version >= 0.4.0 required", UserWarning)
        raise ImportError
        # ensure minimum required version of fastcache is present
    if V(fastcache.__version__) < '0.4.0':
        warn("fastcache version >= 0.4.0 required, detected {}"\
             .format(fastcache.__version__), UserWarning)
        raise ImportError
    # Do not use fastcache if running under pypy
    import platform
    if platform.python_implementation() == 'PyPy':
        raise ImportError

except ImportError:

    def __cacheit(maxsize):
        """caching decorator.

           important: the result of cached function must be *immutable*

           Examples
           ========

           >>> from sympy.core.cache import cacheit
           >>> @cacheit
           ... def f(a, b):
           ...    return a+b

           >>> @cacheit
           ... def f(a, b):
           ...    return [a, b] # <-- WRONG, returns mutable object

           to force cacheit to check returned results mutability and consistency,
           set environment variable SYMPY_USE_CACHE to 'debug'
        """
        def func_wrapper(func):
            cfunc = lru_cache(maxsize, typed=True)(func)

            # wraps here does not propagate all the necessary info
            # for py2.7, use update_wrapper below
            def wrapper(*args, **kwargs):
                try:
                    retval = cfunc(*args, **kwargs)
                except TypeError:
                    retval = func(*args, **kwargs)
                return retval

            wrapper.__wrapped__ = cfunc.__wrapped__
            wrapper.cache_info = cfunc.cache_info
            wrapper.cache_clear = cfunc.cache_clear
            update_wrapper(wrapper, func)
            CACHE.append(wrapper)
            return wrapper

        return func_wrapper
else:

    def __cacheit(maxsize):
        """caching decorator.

           important: the result of cached function must be *immutable*

           Examples
           ========

           >>> from sympy.core.cache import cacheit
           >>> @cacheit
           ... def f(a, b):
           ...    return a+b

           >>> @cacheit
           ... def f(a, b):
           ...    return [a, b] # <-- WRONG, returns mutable object

           to force cacheit to check returned results mutability and consistency,
           set environment variable SYMPY_USE_CACHE to 'debug'
        """
        def func_wrapper(func):

            cfunc = fastcache.clru_cache(maxsize, typed=True, unhashable='ignore')(func)
            CACHE.append(cfunc)
            return cfunc

        return func_wrapper
########################################

def __cacheit_nocache(func):
    return func

def __cacheit_debug(maxsize):
    """cacheit + code to check cache consistency"""
    def func_wrapper(func):
        from .decorators import wraps

        cfunc = __cacheit(maxsize)(func)

        @wraps(func)
        def wrapper(*args, **kw_args):
            # always call function itself and compare it with cached version
            r1 = func(*args, **kw_args)
            r2 = cfunc(*args, **kw_args)

            # try to see if the result is immutable
            #
            # this works because:
            #
            # hash([1,2,3])         -> raise TypeError
            # hash({'a':1, 'b':2})  -> raise TypeError
            # hash((1,[2,3]))       -> raise TypeError
            #
            # hash((1,2,3))         -> just computes the hash
            hash(r1), hash(r2)

            # also see if returned values are the same
            if r1 != r2:
                raise RuntimeError("Returned values are not the same")
            return r1
        return wrapper
    return func_wrapper

def _getenv(key, default=None):
    from os import getenv
    return getenv(key, default)

# SYMPY_USE_CACHE=yes/no/debug
USE_CACHE = _getenv('SYMPY_USE_CACHE', 'yes').lower()
# SYMPY_CACHE_SIZE=some_integer/None
# special cases :
#  SYMPY_CACHE_SIZE=0    -> No caching
#  SYMPY_CACHE_SIZE=None -> Unbounded caching
scs = _getenv('SYMPY_CACHE_SIZE', '1000')
if scs.lower() == 'none':
    SYMPY_CACHE_SIZE = None
else:
    try:
        SYMPY_CACHE_SIZE = int(scs)
    except ValueError:
        raise RuntimeError(
            'SYMPY_CACHE_SIZE must be a valid integer or None. ' + \
            'Got: %s' % SYMPY_CACHE_SIZE)

if USE_CACHE == 'no':
    cacheit = __cacheit_nocache
elif USE_CACHE == 'yes':
    cacheit = __cacheit(SYMPY_CACHE_SIZE)
elif USE_CACHE == 'debug':
    cacheit = __cacheit_debug(SYMPY_CACHE_SIZE)   # a lot slower
else:
    raise RuntimeError(
        'unrecognized value for SYMPY_USE_CACHE: %s' % USE_CACHE)


text:
import os

inputDirectory = "C:/parsedTranscripts/"
transcripts = []
lessons = []

for root, dirs, files in os.walk(inputDirectory):
    lessons.append(dirs)

for lesson in lessons[0]:
    for root, dirs, files in os.walk(inputDirectory + lesson):
        for f in files:
            if f.endswith(".txt"):
                transcripts.append(inputDirectory + lesson + "/" + f)

file = open("oneBigFile.txt", "w")
for transcript in transcripts:
    source = open(transcript, "r")
    file.write("\n\n" + transcript.split("/")[-1].split(".")[0] + "\n")
    for line in source:
        file.write(line)
file.close()