text:
package edu.pitt.library.drl.bodybuilder;

import java.awt.BorderLayout;
import java.awt.Font;
import java.awt.GraphicsEnvironment;
import java.awt.GridLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.KeyAdapter;
import java.awt.event.KeyEvent;
import java.awt.event.WindowAdapter;
import java.awt.event.WindowEvent;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;
import java.util.prefs.Preferences;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import javax.swing.JButton;
import javax.swing.JCheckBox;
import javax.swing.JFileChooser;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JMenu;
import javax.swing.JMenuBar;
import javax.swing.JMenuItem;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.JSplitPane;
import javax.swing.JTabbedPane;
import javax.swing.JTextArea;
import javax.swing.UIManager;
import javax.swing.event.DocumentEvent;
import javax.swing.event.DocumentListener;
import javax.swing.event.TreeSelectionEvent;
import javax.swing.event.TreeSelectionListener;
import javax.swing.tree.TreePath;
import org.w3c.dom.Document;
import org.w3c.dom.Element;

/**
 *
 * @author abrenner
 */

public class EditWindow extends JFrame
{

    /**
	 *
	 */
	private static final long serialVersionUID = 1L;
	// Global GUI Elements
    private JFrame frame;
    private JButton addDivButton, editDivButton, deleteDivButton, autoNumberPagesButton;
    private JCheckBox pageNumberOverwrite;
    private JLabel idLabel, textId, pageImage;
    private JTextArea OCRText, XmlView;
    private DomTree domTree;
    private JScrollPane pageImageScroll, treeScrollPane;

    // Other Global Objects
    private boolean textChanged = false;
    private DomTreeModel model;
    private String itemPath; // from JFileChooser
    private Document document;
    private TextInstance text; // an object representing current text selected
    private String pageID; // represents current page selection
    private Preferences prefs; // user preferences node object
    final String PREF_FILE_ROOT_PATH = "file_root_path";
    final String PREF_FILE_SELECT_METHOD = "file_selection_method";
    final String PREF_OPEN_FILE_LOCATION = "open_file_location";

    final Font labelFont = new Font("Sans-serif", Font.PLAIN, 11);
    final Font treeFont = new Font("Monospaced", Font.PLAIN, 13);

    /**
     * Creates main GUI window.
     */
    public EditWindow() {

        try {
            UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
        }
        catch (Exception e) {
            // OK to do nothing here; setLookAndFeel is just cosmetic.
        }

        ActionListener aListener = new MyActionListener();

        // The main frame
        frame = new JFrame("BodyBuilder");

        idLabel = new JLabel("Working with:");
        textId = new JLabel("");

        // "Add DIV" button
        addDivButton = new JButton("+ DIV");
        addDivButton.addActionListener(aListener);

        // "Edit DIV" button
        editDivButton = new JButton("Edit DIV");
        editDivButton.addActionListener(aListener);

        // "Delete DIV" button
        deleteDivButton = new JButton("- DIV");
        deleteDivButton.addActionListener(aListener);

        // "Auto Number Pages" button
        autoNumberPagesButton = new JButton("AUTO #");
        autoNumberPagesButton.addActionListener(aListener);

        // "Overwrite Page Numbers" check box
        pageNumberOverwrite = new JCheckBox("Overwrite Page Numbers");
        pageNumberOverwrite.addActionListener(aListener);

        // OCR text pane, put inside a JScrollPane
        OCRText = new JTextArea();
        OCRText.setLineWrap(true);
        OCRText.setEditable(false);
        JScrollPane OCRtextPanel = new JScrollPane(OCRText);

        // XML view text pane, put inside a JScrollPane
        XmlView = new JTextArea();
        XmlView.setLineWrap(true);
        XmlView.setEditable(false);
        @SuppressWarnings("unused")
		JScrollPane XmlViewPanel = new JScrollPane(XmlView);
        pageImage = new JLabel();
        pageImageScroll = new JScrollPane(pageImage, JScrollPane.VERTICAL_SCROLLBAR_AS_NEEDED, JScrollPane.HORIZONTAL_SCROLLBAR_AS_NEEDED);

        // TabbedPane to hold Page Image and OCR Text
        JTabbedPane tabby = new JTabbedPane();
        tabby.addTab("Page Image", pageImageScroll);
        tabby.addTab("OCR Text", OCRtextPanel);
        // tabby.addTab("XML View", XmlViewPanel);  -- not yet...

        // "File" Menu
        JMenu textMenu = new JMenu("File");
        textMenu.add(makeMenuItem("Open Text"));
        textMenu.add(makeMenuItem("Save Text"));
        textMenu.add(makeMenuItem("Quit"));

        // Add Menus to MenuBar
        JMenuBar menuBar = new JMenuBar();
        menuBar.add(textMenu);
        frame.setJMenuBar(menuBar);

        // Panel for the Item-level (i.e. Text-level) Metadata

        JPanel itemMetadata = new JPanel();
        itemMetadata.add(idLabel);
        itemMetadata.add(textId);
        JPanel namePanel = new JPanel(new GridLayout(1,1)); // used to be more here :-)
        namePanel.add(itemMetadata);

        treeScrollPane = new JScrollPane(JScrollPane.VERTICAL_SCROLLBAR_AS_NEEDED, JScrollPane.HORIZONTAL_SCROLLBAR_AS_NEEDED);

        // Left Panel of the SplitPane holds Item-level Metadata
        // and the JTree
        JPanel leftPanel = new JPanel();
        leftPanel.setLayout(new BorderLayout());
        leftPanel.add(namePanel, BorderLayout.NORTH);
        leftPanel.add(treeScrollPane);

        JPanel bottomLeftPanel = new JPanel();
        bottomLeftPanel.setLayout(new BorderLayout());

        JPanel divButtonPanel = new JPanel();
        JPanel pageNumberPanel = new JPanel();
        pageNumberPanel.add(autoNumberPagesButton);
        pageNumberPanel.add(pageNumberOverwrite);
        divButtonPanel.add(addDivButton);
        divButtonPanel.add(editDivButton);
        divButtonPanel.add(deleteDivButton);
        bottomLeftPanel.add(pageNumberPanel, BorderLayout.NORTH);
        bottomLeftPanel.add(divButtonPanel, BorderLayout.SOUTH);

        leftPanel.add(bottomLeftPanel, BorderLayout.SOUTH);

        // Right Panel of the SplitPane holds the Panel of Page-level metadata
        // and the TabbedPane holding the Page Image, OCR Text, and XML view
        JPanel rightPanel = new JPanel();
        rightPanel.setLayout(new BorderLayout());
        rightPanel.add(tabby);

        // The SplitPane
        JSplitPane split = new JSplitPane(JSplitPane.HORIZONTAL_SPLIT, leftPanel, rightPanel);
        split.setOneTouchExpandable(true);
        split.setDividerLocation(375);
        frame.add(split);

        // Final overall Frame set-up
        frame.setSize(1000, 750);
        GraphicsEnvironment env = GraphicsEnvironment.getLocalGraphicsEnvironment();
        frame.setMaximizedBounds(env.getMaximumWindowBounds());
        frame.setExtendedState(frame.getExtendedState() | JFrame.MAXIMIZED_BOTH);

        // Close the frame manually after checking if document has changed
        frame.setDefaultCloseOperation(JFrame.DO_NOTHING_ON_CLOSE);

        frame.addWindowListener(new MyWindowListener());
        frame.setVisible(true);

        prefs = Preferences.userNodeForPackage(edu.pitt.library.drl.bodybuilder.EditWindow.class);

    }

    /**
     * Uses a JFileChooser to let user pick a text's directory from the filesystem.
     * After selection of directory, calls loadText
     * @see #loadText(TextInstance text)
     */
    private void pickTextFileSystem() {

        JFileChooser jfc;

        // Retrieve the user preference node for last working directory
        String storedPath = prefs.get(PREF_OPEN_FILE_LOCATION, null);

        if (storedPath != null) {
            jfc = new JFileChooser(storedPath);
        }
        else {
            jfc = new JFileChooser();
        }
        jfc.setFileSelectionMode(JFileChooser.DIRECTORIES_ONLY);
        int returnVal = jfc.showOpenDialog(frame);
        if (returnVal == JFileChooser.APPROVE_OPTION) {

            File file = jfc.getSelectedFile();

            // store the parent location as the working directory
            prefs.put(PREF_OPEN_FILE_LOCATION, file.getParent());

            try {

              text = new TextInstance(file);
              itemPath = file.toString();
              loadText(text);

            } catch (Exception e) {

               JOptionPane.showMessageDialog(frame, "Problem loading text: " + e.getMessage());

            }

        }

    }

    private JMenuItem makeMenuItem(String name) {
        JMenuItem m = new JMenuItem(name);
        m.addActionListener(new MyActionListener());
        return m;
    }

    /**
     * Loads a text by reading/creating a DOM tree, assigning it to the TreeModel,
     * and rendering the model in the GUI.
     * @param text
     */
    private void loadText(TextInstance text) {

        // check to see if the text already has an XML file.  If so, load it and use it
        // to create the DOM/JTree.  If not, call the method to create a Skeleton XML file.

        File xmlFile = text.getXmlFile();

        if (xmlFile.exists()) {
            document = MyDomBuilder.makeDOMFromXML(xmlFile);
        }
        else {
            document = MyDomBuilder.makeSkeletonDOM(text.getPages());
        }

        model = new DomTreeModel(document);
        model.addTreeModelListener(new MyTreeModelListener());
        domTree = new DomTree(model);
        domTree.addKeyListener(new MyKeyListener());
        domTree.addTreeSelectionListener(new MyTreeSelectionListener());
        treeScrollPane.setViewportView(domTree);
        domTree.expandAll();
        domTree.selectFirstPage();
        domTree.requestFocus();
        textId.setText(text.getID());
        XmlView.setText(getXmlText());
    }

    /**
     * Loads the page image and OCR text when a page is selected.
     * @param pageID The id of the current selected page.
     */
    private void loadPageItems(String pageID) {

        // The page image
        File f = new File(itemPath + "/" + pageID + ".jpg");
        try {
            Page p = new Page(f);
            pageImage.setIcon(p.getImage());
            OCRText.setText(p.getOcrText());
        }
        catch (FileNotFoundException fnfe) {
            JOptionPane.showMessageDialog(frame, "Image for " + pageID + " not found.");
        }

    }

    private void saveText()  {

        // Check to make sure we have a document open
        if (document == null) {
            JOptionPane.showMessageDialog(frame, "You must be working with a text to Save");
            return;
        }

        // Write out the DOM to XML
        try  {
            String xmlFilePath = text.getXmlFile().toString();
            WriteXML.writeToFile(document, xmlFilePath);
        }
        catch (Exception e) {
            JOptionPane.showMessageDialog(frame, "Problem writing XML! This text has not been saved!\nError: " + e);
            return;
        }

        // re-set flag
        textChanged = false;
    }

    /**
     * Handles adding a structural division from the GUI.
     * @see ModifyDOM#addDivAsParent(Division division, AdapterNode[] nodeList, Document document)
     */
    private void addDiv() {

        // Check to make sure we have a document open
        if (document == null) {
            JOptionPane.showMessageDialog(frame, "You must be working with a text!");
            return;
        }

        // Get the selection paths as array to accomodate multi-page selections
        TreePath  [] selectedPaths = domTree.getSelectionPaths();

        // get the Row number of the first selected item
        // for re-setting the selection path after the transformation
        int [] rowList = new int [selectedPaths.length];

        // get each selected Node as an AdapterNode to give to
        // the DOM modifying method
        AdapterNode [] nodeList = new AdapterNode[selectedPaths.length];

        int lastRowIndex = 0;

        for (int i = 0; i < selectedPaths.length; i++) {
            rowList[i] = domTree.getRowForPath(selectedPaths[i]);

            if (i > 0 && (rowList[i] != lastRowIndex + 1)) {
                JOptionPane.showMessageDialog(frame, "Your page selection has a gap, or was selected out of order.  Please try again.\n\nHint: use \"SHIFT\" rather than \"CTRL\" to select multiple pages.\n");
                return;
            }

            nodeList[i] = (AdapterNode) selectedPaths[i].getLastPathComponent();
            lastRowIndex = rowList[i];
        }

        // Set image display to first in list (to view potential div title)
        loadPageItems(nodeList[0].getPageFileId());

        // Create the division editor dialog
        String divLabel = JOptionPane.showInputDialog(frame, "Division Label:");

        if (divLabel == null) {
        	return;
        }

        Division newDiv = new Division();
        newDiv.setTitle(divLabel);

        ModifyDOM.addDivAsParent(newDiv, nodeList, document);

        // Notifying the treemodel that the underlying structure
        // has changed.
        model.nodeStructureChanged(nodeList[0]);

        // After changing from the root above, the whole JTree will
        // be collapsed, so this is necessary
        domTree.expandAll();

        // After expanding, reset selected node to first in list
        domTree.setSelectionRow(rowList[0]);

        textChanged = true;

  }

    private void autoNumberNativePagination() {

        // Select the first page
        domTree.selectFirstPage();

        // Get the selection path
        TreePath selectedPath = domTree.getSelectionPath();

        // get the selected Node as an AdapterNode to give to
        // the DOM modifying method
        AdapterNode pbNode = (AdapterNode) selectedPath.getLastPathComponent();
        String lastNativePage = "0001";
        ModifyDOM.setNativePagination(lastNativePage, pbNode, document);

        // loop over all the rest of the PB nodes, setting pagination.
        int rowInt = domTree.getRowForPath(selectedPath);
        while (rowInt < domTree.getRowCount() - 1)
        {
            domTree.selectNextPage();
            selectedPath = domTree.getSelectionPath();
            rowInt = domTree.getRowForPath(selectedPath);
            pbNode = (AdapterNode) selectedPath.getLastPathComponent();
            String thisPage = derivePageFromPrevious(lastNativePage);
            ModifyDOM.setNativePagination(thisPage, pbNode, document);
            lastNativePage = thisPage;
        }

        // Re-select the first page
        domTree.selectFirstPage();
        domTree.requestFocus();
        textChanged = true;

    }

    /**
     * Called whenever tree selection changes.  Changes the DOM and then
     * notifies the model.
     */
    private void setNativePagination() {

        String natPag;

        // Get the selection path
        TreePath selectedPath = domTree.getSelectionPath();
        int rowInt = domTree.getRowForPath(selectedPath);

        // get the selected Node as an AdapterNode to give to
        // the DOM modifying method
        AdapterNode pageNode = (AdapterNode) selectedPath.getLastPathComponent();

        // get the PREVIOUS SIBLING pb node and its value by
        // iterating through previous siblings until we find a "mets:fptr"

        String prevNodeValue = ""; // initalize to empty string

        for (int r = (rowInt - 1); r > 0; r--) {

            TreePath tp = domTree.getPathForRow(r);
            AdapterNode prevNode = (AdapterNode) tp.getLastPathComponent();
            Element prevElement = (Element) prevNode.domNode;
            if (prevElement.getAttribute("TYPE").equals("page")) {
                //prevNodeValue = prevNode.domNode.getAttributes().getNamedItem("LABEL").getNodeValue();
                prevNodeValue = prevElement.getAttribute("LABEL");
                break;
            }
        }

        // derive this page's number from the previous value
        if (prevNodeValue.equals("")) {
            natPag = "unum";
        }
        else {
            natPag = derivePageFromPrevious(prevNodeValue);
        }

        // Stop here if the page is already properly numbered, or else there is
        // an infinite loop!!!

        if (pageNode.domNode.getAttributes().getNamedItem("LABEL").getNodeValue().equals(natPag))
            return;

        //model.valueForPathChanged(selectedPath, natPag);
        ModifyDOM.setNativePagination(natPag, pageNode, document);

        // Notify the treemodel that the underlying structure has changed.
        model.nodeStructureChanged(pageNode);

        domTree.expandAll();
        domTree.setSelectionRow(rowInt);

        textChanged = true;

  }

    /**
     * Handles removal of structural division from the GUI.
     */
    private void removeDiv() {

       // make sure that the current selection is a DIV
       AdapterNode thisNode = (AdapterNode) domTree.getLeadSelectionPath().getLastPathComponent();
       if ( ! Pattern.matches("mets:div", thisNode.domNode.getNodeName())){
           JOptionPane.showMessageDialog(frame, "You must have A DIV selected to edit it");
           return;
       }

       // pop-up confirmation
       int result = JOptionPane.showConfirmDialog(null, "Are you sure you want to delete this DIV?", "Please Confirm", JOptionPane.YES_NO_OPTION);
       if (result != JOptionPane.OK_OPTION)
            return;

       // get the Row number of the first selected item
       // for re-setting the selection path after the transformation
       int leadRow = domTree.getRowForPath(domTree.getLeadSelectionPath());

       // if we've made it this far, send to the ModifyDOM class
       ModifyDOM.removeDIV(thisNode, document);

       // Notifying the treemodel that the underlying structure
       // has changed.  This is kind of a hack in that we always
       // tell the model that the treeScrollPane has changed at the root level.
       // This seems necessary for. proper repainting of the JTree...
       model.nodeStructureChanged(thisNode.getRoot());

       // After changing from the root above, the whole JTree will
       // be collapsed, so this is necessary
       domTree.expandAll();

       // Re-use the index value from earlier to. re-set selection
       domTree.setSelectionRow(leadRow);

       textChanged = true;
   }

    /**
     * Handles editing of structural division metadata from the GUI.
     */
    private void editDiv() {

       // make sure that the current selection is a DIV
       AdapterNode thisNode = (AdapterNode) domTree.getLeadSelectionPath().getLastPathComponent();
       if ( !thisNode.domNode.getNodeName().equals("mets:div")) {
           JOptionPane.showMessageDialog(frame, "You must have A DIV selected to edit it");
           return;
       }

       int leadRow = domTree.getRowForPath(domTree.getLeadSelectionPath());

       Division div = thisNode.getDivision();

       // Create the division editor dialog
       String divLabel = JOptionPane.showInputDialog(frame, "Division Label:", div.getTitle());

       if (divLabel == null) {
    	   return;
       }

       Division newDiv = new Division();
       newDiv.setTitle(divLabel);
       ModifyDOM.replaceDivMetadata(div, newDiv, thisNode, document);

       model.nodeStructureChanged(thisNode.getRoot());
       domTree.expandAll();
       domTree.setSelectionRow(leadRow);
       textChanged = true;

   }

    /**
     * Encapsulates the logic of determining a new page number from the previous page.
     * If the previous page is "unum", the page will also be "unum".  If the previous
     * page ends with a letter (e.g. "001a"), the page will increment the letter (e.g.
     * "001b").  If the previous page starts with an "r" (e.g. "r001"), the page will
     * increment the last digit.  Finally, the page is assumed to be numeric, and is
     * incremented by one.  If there is any trouble parsing the integer of the previous
     * page, the page will become "unum".
     *
     * @param prevPg The previous page number.
     * @return Returns the derived page value as a String.
     */
    public String derivePageFromPrevious(String prevPg) {

       // if previous page is "unum", this one should be too
       if (prevPg.equals("unum")) {
           return "unum";
       }

       // if previous page ends with a letter, increment last letter
       else if (Pattern.matches("\\d\\d\\d([a-z])", prevPg)) {

           Matcher matcher = Pattern.compile("[a-z]$").matcher(prevPg);
           char c = prevPg.charAt(3);
           c++;
           return matcher.replaceFirst(String.valueOf(c));

       }

       // if previous page starts with an 'r', increment last number
       else if (Pattern.matches("r\\d\\d\\d", prevPg)) {

           String c = prevPg.substring(1,4);

           try {

               int i = Integer.parseInt(c);
                // add one to the int
                i++;
                // convert int back into zero-padded string
                return "r" + String.format("%03d", i);
            }
            catch (NumberFormatException nfe) {
                return "unum";
            }

       }

       // otherwise, assume its a numeric page and try to increment it
       else {
            // convert the zero-padded String into an int,
           // but catch number format exceptions

            try {
                int i = Integer.parseInt(prevPg);

                // add one to the int
                i++;

                // convert int back into zero-padded string
                return String.format("%04d", i);
            }
            catch (NumberFormatException nfe) {
                return "unum";
            }

       }
   }

   private String getXmlText () {

       try {

            String rtn = " ";
            BufferedReader inputStream = new BufferedReader(new FileReader(text.getXmlFile()));
            String l;
            while ((l = inputStream.readLine()) != null) {
                rtn += l;
            }
            inputStream.close();
            return rtn;
       }
       catch (FileNotFoundException e) {

           return "XML File not found!  Something's pretty wrong!";

       }
       catch (IOException ioe) {

           return "I/O Exception: " + ioe.getMessage();

       }

   }

    private void promptForSave () {

           if ( textChanged ) {

               int result = JOptionPane.showConfirmDialog(frame, "Document has changed since it was last saved.  Save now?");

               // stop here if they've hit anything other than the OK button
               if (result == JOptionPane.YES_OPTION)
               {
                   saveText();
               }
               else if ( result == JOptionPane.CANCEL_OPTION )
               {
                   return;
               }
           }

    }

   private class MyActionListener implements ActionListener, DocumentListener {

        // adapter to receive menu actions and route accordingly

        public void changedUpdate(DocumentEvent de) {
           System.out.println("changedUpdate event registered.");
        }
        public void insertUpdate(DocumentEvent de)  {
           //setNativePagination(pagination.getText());
        }
        public void removeUpdate(DocumentEvent de) {
           //setNativePagination(pagination.getText());
        }

        public void actionPerformed(ActionEvent e) {

            String command = e.getActionCommand();
            if (command.equals("Quit"))
                frame.dispatchEvent(new WindowEvent(frame, WindowEvent.WINDOW_CLOSING));

            else if (command.equals("Open Text"))
            {
                promptForSave();
                pickTextFileSystem();
            }
            else if (command.equals("Save Text"))
                saveText();

            else if (e.getSource() == addDivButton)
                addDiv();

            else if ( e.getSource() == deleteDivButton ){
                removeDiv();
            }

            else if ( e.getSource() == editDivButton ){
                editDiv();
            }
            else if ( e.getSource() == autoNumberPagesButton ) {
               int result = JOptionPane.showConfirmDialog(frame, "Are you sure you want to auto-number all the pages?");
               // stop here if they've hit anyting other than the OK button
               if (result == JOptionPane.YES_OPTION)
               {
                    autoNumberNativePagination();
               }
               else if ( result == JOptionPane.CANCEL_OPTION )
               {
                   return;
               }
            }
            else if ( e.getSource() == pageNumberOverwrite ){
                domTree.requestFocus();
            }
        }

    }

   private class MyWindowListener extends WindowAdapter {

        @Override
       public void windowClosing(WindowEvent e )
       {

           promptForSave();

           // now close
           System.exit(0);
       }

   }

   private class MyKeyListener extends KeyAdapter {

        @Override
        public void keyPressed (KeyEvent ke) {

            if ( ke.getKeyCode() == KeyEvent.VK_INSERT ) {
                if (ke.getModifiersEx() == KeyEvent.CTRL_DOWN_MASK ) {
                    editDiv();
                }
                else {
                addDiv();
                }
            }
            else if ( ke.getKeyCode() == KeyEvent.VK_DELETE ) {
                removeDiv();
            }
        }
    }

     private class MyTreeSelectionListener implements TreeSelectionListener {

         public void valueChanged(TreeSelectionEvent e) {

            try {
                TreePath p = e.getNewLeadSelectionPath();
                if (p != null) {
                    AdapterNode adpNode = (AdapterNode) p.getLastPathComponent();
                    Element element = (Element) adpNode.domNode;
                    if (element.getAttribute("TYPE").equals("page")) {
                        pageID = adpNode.getPageFileId();
                        loadPageItems(pageID);
                        if (element.getAttribute("LABEL").equals("") || pageNumberOverwrite.isSelected()) {
                            setNativePagination();
                        }
                    }
                 }
            } catch (Exception ex) {
                System.out.print(ex.toString());
            }

        }
    }

}


text:
require File.join(File.dirname(__FILE__), "..", "..", "..", "spec_helper")

describe "new.html.erb" do

  it "should render new pkg def page" do
    metadata = PackageConfigurations.new
    metadata.addConfiguration(PackageConfiguration.new("key1").with(PackageConfiguration::SECURE, false).with(PackageConfiguration::DISPLAY_NAME, "Key 1"))
    metadata.addConfiguration(PackageConfiguration.new("key2").with(PackageConfiguration::SECURE, true).with(PackageConfiguration::REQUIRED, false).with(PackageConfiguration::DISPLAY_NAME, "Key 2"))

    package_definition = PackageDefinition.new
    p1 = ConfigurationProperty.new(ConfigurationKey.new("key1"), ConfigurationValue.new("value1"))
    p2 = ConfigurationProperty.new(ConfigurationKey.new("key2"), EncryptedConfigurationValue.new("value2"))

    configuration = Configuration.new([p1, p2].to_java(com.thoughtworks.go.domain.config.ConfigurationProperty))
    package_definition.setConfiguration(configuration)
    assigns[:package_configuration] = PackageViewModel.new metadata, package_definition

    render "admin/package_definitions/new.html"

    response.body.should have_tag(".information", "The new package will be available to be used as material in all pipelines. Other admins might be able to edit this package.")

    response.body.should have_tag(".new_form_item_block label", "Package Name*")
    response.body.should have_tag(".new_form_item_block input[type='text'][name='material[package_definition[name]]']")

    response.body.should have_tag(".new_form_item input[type='hidden'][name='material[package_definition[configuration][0][configurationKey][name]]'][value='key1']")
    response.body.should have_tag(".new_form_item label", "Key 1*")
    response.body.should have_tag(".new_form_item input[type='text'][name='material[package_definition[configuration][0][configurationValue][value]]'][value='value1']")

    response.body.should have_tag(".new_form_item input[type='hidden'][name='material[package_definition[configuration][1][configurationKey][name]]'][value='key2']")
    response.body.should have_tag(".new_form_item label", "Key 2")
    response.body.should have_tag(".new_form_item input[type='password'][name='material[package_definition[configuration][1][configurationValue][value]]'][value='value2']")
  end
end

redpajama_set_name: RedPajamaGithub


text:
generate-flask-skeletons
========================

A simple tool to generate flask web applications skeletons

### Installing

run install.sh

`cd generate-flask-skeletons`

`sudo sh install.sh`

### Usage

just run generate.py on top of your project folder.

`sudo generate.py`

The program will create the skeleton for your flask application.

`sudo generate.py bootstrap`

The program  will download the twitter bootstrap framework and create the skeleton using it.


text:
<?xml version="1.0" encoding="utf-8"?>
<selector xmlns:android="http://schemas.android.com/apk/res/android">
    <item android:drawable="@drawable/ic_done_accent" android:state_checked="true" />
</selector>


text:
namespace Chimera {

namespace Virtual {

enum class AttributeType {
    String,
    Style,
    EventCallback
};

class Attribute {
using EventCallback = std::function<void(Chimera::Event*)>;

public:
    Attribute() { }

    Attribute(std::string key, std::string value)
        : mKey{key}
        , mStringValue{value}
        , mType{AttributeType::String}
        { }

    Attribute(std::string key, Chimera::Style value)
        : mKey{key}
        , mType{AttributeType::Style}
    {
        mStyleValue = value;
    }

    Attribute(std::string key, EventCallback value)
        : mKey{key}
        , mCallbackValue{value}
        , mType{AttributeType::EventCallback}
        { }

    std::string getKey() {
        return mKey;
    }

    std::string asString() {
        if (mType == AttributeType::String) {
            return mStringValue;
        } else {
            return "";
        }
    }

    Chimera::Style asStyle() {
        if (mType == AttributeType::Style) {
            return mStyleValue;
        } else {
            return {};
        }
    }

    EventCallback asCallback() {
        if (mType == AttributeType::EventCallback) {
            return mCallbackValue;
        } else {
            return nullptr;
        }
    }

private:
    std::string mKey;

    std::string mStringValue;
    Chimera::Style mStyleValue;
    EventCallback mCallbackValue;

    AttributeType mType;
};

class VirtualElement {
public:
    VirtualElement(std::string _name, std::vector<Attribute> _attributes);

    Element* create(Document& document);

    std::string name{"div"};
    std::string textContent;
    std::vector<VirtualElement> children{};
    std::unordered_map<std::string, Attribute> attributes{};
};

static inline VirtualElement VElement(
    std::string name,
    std::vector<Attribute> attributes)
{
    return {name, attributes};
}

static inline VirtualElement VElement(
    std::string name,
    std::vector<Attribute> attributes,
    std::string textContent)
{
    VirtualElement element{name, attributes};
    element.textContent = textContent;
    return element;
}

static inline VirtualElement VElement(
    std::string name,
    std::vector<Attribute> attributes,
    std::vector<VirtualElement> children)
{
    VirtualElement element{name, attributes};
    element.children = children;
    return element;
}

static inline VirtualElement V(
    std::string name,
    std::vector<Attribute> attributes)
{
    return {name, attributes};
}

static inline VirtualElement V(
    std::string name,
    std::vector<Attribute> attributes,
    std::string textContent)
{
    VirtualElement element{name, attributes};
    element.textContent = textContent;
    return element;
}

static inline VirtualElement V(
    std::string name,
    std::vector<Attribute> attributes,
    std::vector<VirtualElement> children)
{
    VirtualElement element{name, attributes};
    element.children = children;
    return element;
}

static inline Element* CreateTree(Document& document, VirtualElement element)
{
    return element.create(document);
}

template<class InputIt, class Func>
std::vector<VirtualElement> VList(InputIt first, InputIt last, Func f)
{
    std::vector<VirtualElement> result{};

    for (; first != last; ++first)
    {
        result.push_back(f(*first));
    }

    return result;
}

}  // namespace Virtual

}  // namespace Chimera

#endif  // CHIMERA_VTREE_H_


text:
%Installs SynNetGen software
%- Check requirements
%  - MATLAB >= 2014a
%  - GraphViz >= 2.36.0
%- Adds source and test code to MATLAB path
%- Verifies tests
%
%@author  Jonathan Karr, karr@mssm.edu
%@date    2015-04-15
function install()

%% Check requirements
%MATLAB >= 2014a
if verLessThan('matlab', '8.3.0')
    warning('SynNetGen:warning', 'tested on MATLAB 2014a. MATLAB >= 2014a may be required');
end

%GraphViz >= 2.36
[status, result] = system('dot -V');
if status
    throw(MException('SynNetGen:InvalidRequirements', 'GraphViz not installed'))
end

info = regexp(result, 'dot - graphviz version (?<version>\d+)\.(?<subversion>\d+)\.(?<subsubversion>\d+) \((?<year>\d{4,4})(?<month>\d{2,2})(?<day>\d{2,2}).(?<revision>\d+)\)\n', 'names');
if str2double([info.version '.' info.subversion]) < 2.36
    warning('SynNetGen:InvalidRequirements', 'Tested on GraphViz 2.36. GraphViz >= 2.36 may be required.')
end

%libSBML-matlab
if isempty(which('TranslateSBML'))
    throw(MException('SynNetGen:InvalidRequirements', 'libSBML-MATLAB not installed'))
end

%% check not installed
baseDir = fileparts(mfilename('fullpath'));
currPath = strsplit(path(), pathsep);
if ismember(baseDir, currPath)
    throw(MException('SynNetGen:AlreadyInstalled', 'SynNetGen already installed'));
end

%% add source, test code to path
addpath(fullfile(baseDir, 'src_test'));
addpath(fullfile(baseDir, 'doc'))
addpath(fullfile(baseDir, 'lib/m2html'));
addpath(fullfile(baseDir, 'lib/graphviz4matlab'));
addpath(fullfile(baseDir, 'lib/graphviz4matlab/layouts'));
addpath(fullfile(baseDir, 'lib/graphviz4matlab/util'));
addpath(fullfile(baseDir, 'lib/RBN'));
addpath(fullfile(baseDir, 'tmp'))
addpath(fullfile(baseDir, 'src'))
addpath(baseDir)

%% build and run tests
status = true;
try
    build();
    fprintf('Build succeed!\n');
catch
    status = status && false;
    fprintf('Unable to build software.\n');
end

try
    test();
    fprintf('Tests passed!\n');
catch
    status = status && false;
    fprintf('Tests failed.\n');
end

%undo path if not successful
if ~status
    rmpath(fullfile(baseDir, 'src_test'));
    rmpath(fullfile(baseDir, 'doc'))
    rmpath(fullfile(baseDir, 'lib/m2html'));
    rmpath(fullfile(baseDir, 'lib/graphviz4matlab'));
    rmpath(fullfile(baseDir, 'lib/graphviz4matlab/layouts'));
    rmpath(fullfile(baseDir, 'lib/graphviz4matlab/util'));
    rmpath(fullfile(baseDir, 'lib/RBN'));
    rmpath(fullfile(baseDir, 'tmp'));
    rmpath(fullfile(baseDir, 'src'));
    rmpath(baseDir);
    return
end

%% report success
fprintf('SynNetGen succesfully installed!\n');


text:
namespace sfui
{

  class Slider : public Draggable
  {
  public:
    WIDGET_DERIVED(Slider, Draggable);
    Slider(optional<Theme*> theme = optional<Theme*>(), optional<Widget*> parent = optional<Widget*>());
    virtual ~Slider() override;

    static shared_ptr Create(optional<Theme*> theme = optional<Theme*>(), optional<Widget*> parent = optional<Widget*>());

    void SetIsVertical(bool isVertical);
    virtual void OnDragged(boost::function<void(const Vec2i &)> func);
    void SetDragBounds(IntRect bds);

  protected:
    Signal<void(const Vec2i &)> m_DraggedSignal;
    bool m_IsVertical = true;
    IntRect m_DraggableBounds = { 0, 0, 0, 0 };
    virtual void Dragged(const Vec2i &delta) override;
    virtual void DragStarted() override;
    virtual void Dropped() override;
  };

}

#endif // SFUI_SLIDER_H


text:
'use strict';

var React = require('react-native');
var {
  AppRegistry,
  StyleSheet,
  Text,
  View,
} = React;

// require('./test/simple/test-dgram-address')
// require('./test/simple/test-dgram-bind-default-address')
// require('./test/simple/test-dgram-bind-shared-ports')

function randomPort() {
  return Math.random() * 60536 | 0 + 5000 // 60536-65536
}

var base64 = require('base64-js')
var dgram = require('dgram')
var a = dgram.createSocket('udp4')
var aPort = randomPort()
a.bind(aPort, function(err) {
  if (err) throw err

  console.log('address', a.address())
})

var b = dgram.createSocket('udp4')
var bPort = randomPort()
b.bind(bPort, function(err) {
  if (err) throw err

  console.log('address', b.address())
})

a.on('message', function(data, rinfo) {
  var str = String.fromCharCode.apply(null, new Uint8Array(data));
  console.log('a received', str, rinfo)
  a.close()
  b.close()
})

b.on('message', function(data, rinfo) {
  var str = String.fromCharCode.apply(null, new Uint8Array(data));
  console.log('b received', str, rinfo)

  // echo back
  b.send(data, 0, data.length, aPort, '127.0.0.1', function(err) {
    if (err) throw err

    console.log('sent')
  })
})

b.once('listening', function() {
  var msg = toByteArray('hello')
  a.send(msg, 0, msg.length, bPort, '127.0.0.1', function(err) {
    if (err) throw err

    console.log('sent')
  })
})

var rctsockets = React.createClass({
  render: function() {
    return (
      <View style={styles.container}>
        <Text style={styles.welcome}>
          Open Dev Tools to see socket chatter
        </Text>
      </View>
    );
  }
});

var styles = StyleSheet.create({
  container: {
    flex: 1,
    justifyContent: 'center',
    alignItems: 'center',
    backgroundColor: '#F5FCFF',
  },
  welcome: {
    fontSize: 20,
    textAlign: 'center',
    margin: 10,
  },
  instructions: {
    textAlign: 'center',
    color: '#333333',
    marginBottom: 5,
  },
});

// only works for 8-bit chars
function toByteArray(obj) {
  var uint = new Uint8Array(obj.length);
  for (var i = 0, l = obj.length; i < l; i++){
    uint[i] = obj.charCodeAt(i);
  }

  return new Uint8Array(uint);
}

AppRegistry.registerComponent('react-native-udp', () => rctsockets);


text:
package com.zippy.ig.common.block;

import net.minecraft.block.Block;
import net.minecraft.block.material.Material;

public class oreColanite extends Block {

	public oreColanite(Material p_i45394_1_) {
		super(p_i45394_1_);
	}

}


text:
package com.github.onsdigital.babbage.search.helpers;

import com.github.onsdigital.babbage.error.BadRequestException;
import com.github.onsdigital.babbage.error.ResourceNotFoundException;
import com.github.onsdigital.babbage.search.helpers.dates.PublishDates;
import com.github.onsdigital.babbage.search.helpers.dates.PublishDatesException;
import com.github.onsdigital.babbage.search.input.SortBy;
import com.github.onsdigital.babbage.search.input.TypeFilter;
import org.apache.commons.lang3.StringUtils;

import javax.servlet.http.HttpServletRequest;
import java.text.SimpleDateFormat;
import java.util.HashSet;
import java.util.Set;
import java.util.function.BiFunction;

import static com.github.onsdigital.babbage.configuration.ApplicationConfiguration.appConfig;
import static com.github.onsdigital.babbage.search.helpers.dates.PublishDates.publishedDates;
import static com.github.onsdigital.babbage.search.helpers.dates.PublishDates.updatedWithinPeriod;
import static com.github.onsdigital.babbage.util.RequestUtil.getParam;
import static com.github.onsdigital.logging.v2.event.SimpleEvent.error;
import static org.apache.commons.lang3.EnumUtils.getEnum;
import static org.apache.commons.lang3.StringUtils.isEmpty;
import static org.apache.commons.lang3.StringUtils.upperCase;

/**
 * Common utilities to manipulate search request query and extracting common search parameters
 */

public class SearchRequestHelper {

    static final String FROM_DAY_PARAM = "fromDateDay";
    static final String FROM_MONTH_PARAM = "fromDateMonth";
    static final String FROM_YEAR_PARAM = "fromDateYear";
    static final String TO_DAY_PARAM = "toDateDay";
    static final String TO_MONTH_PARAM = "toDateMonth";
    static final String TO_YEAR_PARAM = "toDateYear";
    static final String UPDATED_PARAM = "updated";
    static final String UPCOMING_PARAM = "upcoming";
    static final String VIEW_PARAM = "view";

    static BiFunction<HttpServletRequest, String, String> extractDayOrMonthDateValue = (request, parameterName) ->
            StringUtils.isEmpty(request.getParameter(parameterName)) ? "" : request.getParameter(parameterName) + "/";

    static BiFunction<HttpServletRequest, String, String> extractYearDateValue = (request, parameterName) ->
            StringUtils.isEmpty(request.getParameter(parameterName)) ? "" : request.getParameter(parameterName);

    static SimpleDateFormat SDF = new SimpleDateFormat("dd/MM/yy");

    private SearchRequestHelper() {
        // contains only static methods - hide constructor.
    }

    public static PublishDates extractPublishDates(HttpServletRequest request) throws PublishDatesException {
        String updatedPeriod = request.getParameter(UPDATED_PARAM);
        PublishDates publishDates;

        if (StringUtils.isEmpty(updatedPeriod)) {
            publishDates = parseDates(request);
        } else {
            publishDates = updatedWithinPeriod(updatedPeriod);
        }
        return publishDates;
    }

    public static PublishDates parseDates(HttpServletRequest req) throws PublishDatesException {
        String fromDateStr = extractDateStr(req, FROM_DAY_PARAM, FROM_MONTH_PARAM, FROM_YEAR_PARAM);
        String toDateStr = extractDateStr(req, TO_DAY_PARAM, TO_MONTH_PARAM, TO_YEAR_PARAM);
        return publishedDates(fromDateStr, toDateStr, allowFutureAfterDate(req));
    }

    private static String extractDateStr(HttpServletRequest req, String dayKey, String monthKey, String yearKey) {
        StringBuilder stringDate = new StringBuilder();
        stringDate.append(extractDayOrMonthDateValue.apply(req, dayKey));
        stringDate.append(extractDayOrMonthDateValue.apply(req, monthKey));
        stringDate.append(extractYearDateValue.apply(req, yearKey));
        return stringDate.toString();
    }

    /**
     * Extracts filter parameters requested, including only filter if given default filters, otherwise ignores.
     * <p>
     * If there are no valid filters will return default filters
     *
     * @param request
     * @param defaultFilters
     * @return
     */
    public static Set<TypeFilter> extractSelectedFilters(HttpServletRequest request, Set<TypeFilter> defaultFilters, Boolean ignoreFilters) {
        String[] filters = request.getParameterValues("filter");
        if (ignoreFilters || filters == null) {
            return defaultFilters;
        }

        HashSet<TypeFilter> selectedFilters = new HashSet<>();
        for (int i = 0; i < filters.length; i++) {
            TypeFilter typeFilter = getEnum(TypeFilter.class, upperCase(filters[i]));
            if (defaultFilters.contains(typeFilter)) {
                selectedFilters.add(typeFilter);
            }
        }
        return selectedFilters.isEmpty() ? defaultFilters : selectedFilters;
    }

    public static SortBy extractSortBy(HttpServletRequest request, SortBy defaultSort) {
        String sortBy = getParam(request, "sortBy");
        if (isEmpty(sortBy)) {
            return defaultSort;
        }
        try {
            return SortBy.valueOf(sortBy.toLowerCase());
        } catch (IllegalArgumentException e) {
            return defaultSort;
        }
    }

    /**
     * Extract the page number from a request - for paged results.
     *
     * @return
     */
    public static int extractPage(HttpServletRequest request) {
        String page = request.getParameter("page");

        if (isEmpty(page)) {
            return 1;
        }
        try {
            int pageNumber = Integer.parseInt(page);
            if (pageNumber < 1) {
                throw new ResourceNotFoundException();
            }
            return pageNumber;
        } catch (NumberFormatException e) {
            return 1;
        }
    }

    /**
     * If a size parameter exists use that otherwise use default.
     */
    public static int extractSize(HttpServletRequest request) {
        int result = appConfig().babbage().getResultsPerPage();
        if (StringUtils.isNotEmpty(request.getParameter("size"))) {
            try {
                result = Integer.parseInt(request.getParameter("size"));
                return Math.max(appConfig().babbage().getResultsPerPage(), Math.min(result,
                        appConfig().babbage().getMaxResultsPerPage()));
            } catch (NumberFormatException ex) {
                error().exception(ex).data("value", result)
                        .log("failed to parse size parameter to integer default value will be used");
            }
        }
        return result;
    }

    /**
     * Extracts search term, checks for parameter "q" if it does not exist looks for parameter "query"
     *
     * @param request
     * @return
     */
    public static String extractSearchTerm(HttpServletRequest request) {
        String query = getParam(request, "q", getParam(request, "query"));//get query if q not given, list pages use query
        if (StringUtils.isEmpty(query)) {
            return null;
        }
        if (query.length() > 200) {
            throw new BadRequestException("Search query contains too many characters");
        }
        return query;
    }

    private static boolean allowFutureAfterDate(HttpServletRequest request) {
        return UPCOMING_PARAM.equalsIgnoreCase(request.getParameter(VIEW_PARAM));
    }

}


text:
'use strict';

var Frame = require('../../../v2/frame.js');

var bufrw = require('bufrw');

module.exports = TestBody;

function TestBody(payload) {
    if (!(this instanceof TestBody)) {
        return new TestBody(payload);
    }
    var self = this;
    self.type = TestBody.TypeCode;
    self.payload = payload;
}

TestBody.TypeCode = 0x00;

TestBody.RW = bufrw.Struct(TestBody, {
    payload: bufrw.buf1
});

TestBody.testWith = function testWidTestBody(desc, t) {
    var test = require('tape');
    test(desc, function s(assert) {
        Frame.Types[TestBody.TypeCode] = TestBody;
        assert.once('end', function removeTestBody() {
            delete Frame.Types[TestBody.TypeCode];
        });
        return t(assert);
    });
};


text:
// HTMLParser Library $Name: v1_5 $ - A java-based parser for HTML
// http://sourceforge.org/projects/htmlparser
// Copyright (C) 2004 Somik Raha
//
// Revision Control Information
//
// $Source: /cvsroot/htmlparser/htmlparser/src/org/htmlparser/tags/SelectTag.java,v $
// $Author: derrickoswald $
// $Date: 2005/04/10 23:20:45 $
// $Revision: 1.39 $
//
// This library is free software; you can redistribute it and/or
// modify it under the terms of the GNU Lesser General Public
// License as published by the Free Software Foundation; either
// version 2.1 of the License, or (at your option) any later version.
//
// This library is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
// Lesser General Public License for more details.
//
// You should have received a copy of the GNU Lesser General Public
// License along with this library; if not, write to the Free Software
// Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
//

package org.htmlparser.tags;

import org.htmlparser.util.NodeList;

/**
 * A select tag within a form.
 */
public class SelectTag extends CompositeTag
{
    /**
     * The set of names handled by this tag.
     */
    private static final String[] mIds = new String[] {"SELECT"};

    /**
     * The set of tag names that indicate the end of this tag.
     */
    private static final String[] mEnders = new String[] {"INPUT", "TEXTAREA", "SELECT"};

    /**
     * The set of end tag names that indicate the end of this tag.
     */
    private static final String[] mEndTagEnders = new String[] {"FORM", "BODY", "HTML"};

    /**
     * Create a new select tag.
     */
    public SelectTag ()
    {
    }

    /**
     * Return the set of names handled by this tag.
     * @return The names to be matched that create tags of this type.
     */
    public String[] getIds ()
    {
        return (mIds);
    }

    /**
     * Return the set of tag names that cause this tag to finish.
     * @return The names of following tags that stop further scanning.
     */
    public String[] getEnders ()
    {
        return (mEnders);
    }

    /**
     * Return the set of end tag names that cause this tag to finish.
     * @return The names of following end tags that stop further scanning.
     */
    public String[] getEndTagEnders ()
    {
        return (mEndTagEnders);
    }

    /**
     * Get the list of options in this SELECT tag.
     * @return The {@.html <OPTION>} tags contained by this tag.
     */
    public OptionTag [] getOptionTags ()
    {
        NodeList list;
        OptionTag[] ret;

        list = searchFor (OptionTag.class, true);
        ret = new OptionTag[list.size()];
        list.copyToNodeArray (ret);

        return (ret);
    }
}


text:
var osquery = require('osquery');

var os = osquery.createClient({ path: '/var/osquery/osquery.em' });
os.query('select timestamp from time', function(err, res) {
  console.log(res);
});


text:
import RPi.GPIO as GPIO
import time
import atexit

def left():
    print "Left turn"
    GPIO.output(15, True)
    GPIO.output(16, False)

def center():
    print "Straight"
    GPIO.output(15, False)
    GPIO.output(16, False)

def right():
    print "Right turn"
    GPIO.output(16, True)
    GPIO.output(15, False)

def forward():
    print "Forward"
    GPIO.output(13, False)
    GPIO.output(11, True)

def reverse():
    print "Reverse"
    GPIO.output(13, True)
    GPIO.output(11, False)

def stop():
    print "Stop"
    GPIO.output(13, False)
    GPIO.output(11, False)

def cleanup():
    print "Cleaning up"
    GPIO.output(12, False)
    GPIO.output(11, False)
    GPIO.output(13, False)
    GPIO.output(15, False)
    GPIO.output(16, False)
    GPIO.cleanup()

# Moves the wheels from one side to the next,
# pausing for interval seconds, for a total of reps cycles
def wheelswing(interval, reps):
    for i in range(reps):
        left()
        time.sleep(interval)

        right()
        time.sleep(interval)
    center()

GPIO.setmode(GPIO.BOARD)
GPIO.setup(12, GPIO.OUT) #Enable
GPIO.setup(11, GPIO.OUT) # This
GPIO.setup(13, GPIO.OUT) # And this must complement
GPIO.setup(15, GPIO.OUT) # this
GPIO.setup(16, GPIO.OUT) # And this must complement

atexit.register(cleanup)
GPIO.output(12, True)

for i in range(3):

    forward()
    time.sleep(1)

    stop()
    time.sleep(0.25)

    wheelswing(0.25, 1)
    time.sleep(0.55)

    reverse()
    time.sleep(1)
    stop()
    time.sleep(0.25)


text:
import itertools
import random

from flask import Flask
from flask.ext.script import Manager
from flask.ext.restful import Api, Resource

#
# Free Coding session for 2015-01-10
# Written by Matt Warren
#

class Card:
    SUITS = ['Diamonds', 'Clubs', 'Hearts', 'Spades']
    FACES = [2, 3, 4, 5, 6, 7, 8, 9, 10, 'Jack', 'Queen', 'King', 'Ace']

    def __init__(self, face, suit):
        self.face = face
        self.suit = suit

    def serialize(self):
        return {
            'suit': self.SUITS[self.suit],
            'face': self.FACES[self.face]
        }

    def __repr__(self):
        return "%s of %s" % (self.FACES[self.face], self.SUITS[self.suit])

class Deck:
    def __init__(self):
        self.deck = []
        self.build_deck()

    def build_deck(self):
        for i, j in itertools.product(range(13), range(4)):
            self.deck.append(Card(i, j))

    def shuffle(self):
        random.shuffle(self.deck)

    def get_card(self):
        return self.deck.pop()

app = Flask(__name__)
api = Api(app)
manager = Manager(app)

class CardAPI(Resource):
    def __init__(self):
        self.deck = Deck()
        self.deck.shuffle()

    def get(self):
        return self.deck.get_card().serialize()

api.add_resource(CardAPI, '/')

if __name__ == '__main__':
    manager.run()


text:
UI.Component = (function() {
	"use strict"

	var EL_EVENTS = [
		'click', 'dblclick', 'contextmenu', 'blur', 'focus',
		'tap', 'dbltap', 'shorttap', 'longtap',
		'keyup', 'keydown', 'mousewheel',
		'touchstart', 'touchmove', 'touchend', 'touchstop',
		'mouseup', 'mousedown', 'mouseover', 'mousemove', 'mouseout', 'mouseout',
		'orientationchange',
		'drag', 'dragstart', 'drop', 'dragover',
		'swipeleft', 'swiperight',
		'staged', 'unstaged',
		'attach', 'attached', 'detach', 'detached',
		'add', 'remove', 'added', 'removed',
		'cleared', 'changed', 'changed.dom', 'changed.attr', 'changed.html', 'changed.class', 'changed.style', 'changed.value'
	];
	var EL_BRIDGE = [
		'click', 'dblclick', 'contextmenu', 'blur', 'focus',
		'tap', 'dbltap', 'shorttap', 'longtap',
		'touchstart', 'touchmove', 'touchend', 'touchstop',
		'mouseup', 'mousedown', 'mouseover', 'mousemove', 'mouseout', 'mouseout',
		'keyup', 'keydown', 'mousewheel','orientationchange',
		'drag', 'dragstart', 'drop', 'dragover',
		'swipeleft', 'swiperight',
		'staged', 'unstaged',
		'attach', 'attached', 'detach', 'detached'
	];

	var seq = 100;

	// class Component
	function Component(options) {
		var o = this.options = new Options(options);
		var cls = this.constructor;

		if( o.debug ) this.debug = true;

		// create el
		if( !this.el ) this.el = $.create((o.tag || cls.tag || 'div'), o.attrs);
		else this.el.clear();

		// setup el
		var el = this.el.data('component', this);

		// setup context & name
		if( o.name ) this.name(o.name);
		if( o.context ) this.context(o.context);
		this.classes(o.classes);
		if( o.origin ) this.origin(o.origin);

		// setup status
		if( o.hidden ) el.style('display', 'none');
		if( o.movable ) el.movable(o.movable);
		if( o.enable ) this.enable(o.enable);

		// setup style & dom
		if( o.style ) this.style(o.style);
		if( o.css ) this.css(o.css);
		if( o.theme ) this.theme(o.theme);
		if( o.abs ) this.abs(o.abs);
		if( o.html ) this.html(o.html);

		// href
		if( o.href ) this.href(o.href);

		// bg 와 width height font 에 대해서는 편의적 메소드를 제공하기로...
		if( o.bg || o.background ) el.bg(o.bg || o.background);
		if( o.color ) el.color(o.color);
		if( o.flex ) el.flex(o.flex);
		if( o['float'] ) this['float'](o['float']);
		if( o.font ) el.font(o.font);
		if( o.margin ) el.margin(o.margin);
		if( o.padding ) el.padding(o.padding);
		if( o.border ) el.border(o.border);
		if( o.width || o.width === 0 ) el.width(o.width);
		if( o.minWidth || o.minWidth === 0 ) el.minWidth(o.minWidth);
		if( o.maxWidth || o.maxWidth === 0 ) el.maxWidth(o.maxWidth);
		if( o.height || o.height === 0 ) el.height(o.height);
		if( o.minHeight || o.minHeight === 0 ) el.minHeight(o.minHeight);
		if( o.maxHeight || o.maxHeight === 0 ) el.maxHeight(o.maxHeight);

		if( o.fit ) el.ac('fit');

		// confirm event scope
		var scope = o.e && o.e.scope;
		if( scope == 'el' ) scope = el;
		else if( scope == 'element' ) scope = el[0];

		// bind event in options
		var dispatcher = this._dispatcher = new EventDispatcher().source((o.e && o.e.source) || this).scope(scope || this);

		if( o.e ) {
			for(var k in o.e) {
				var fn = o.e[k];
				if( typeof(fn) === 'function' ) this.on(k, fn);
			}
		}

		// invoke class's build & options build
		if( typeof(o.before) === 'function' ) o.before.apply(this);
		if( this.build ) this.build();
		if( typeof(o.build) === 'function' ) o.build.apply(this);
		if( typeof(o.after) === 'function' ) o.after.apply(this);

		// block build method
		this.build = function() { throw new Error('illegal access'); };
	}

	Component.prototype = {
		id: function(id) {
			if( !arguments.length ) return this.el.attr('id');
			this.el.attr('id', id);
			return this;
		},
		title: function(title) {
			if( !arguments.length ) return this.el.attr('title');
			this.el.attr('title', title);
			return this;
		},
		origin: function(origin) {
			if( !arguments.length ) return this._origin;

			if( origin instanceof Path ) this._origin = origin;
			else if( origin && typeof(origin) === 'string' ) this._origin = new Path(origin);
			else console.error('[WARN] invalid origin path', origin);

			if( UI.debug && origin ) this.el.attr('origin', origin);

			return this;
		},
		base: function() {
			var origin = this.origin();
			if( origin ) return origin.dir();
			else return Path.dir(location.href);
		},
		context: function(context) {
			if( !arguments.length ) return this._context || UI.context();

			if( context === true ) context = new UI.Context();

			if( context === false ) {
				if( this._context ) this._context.disconnect(this);
				this._context = null;
			} else if( context instanceof UI.Context ) {
				context.connect(this);
				this._context = context;
			} else {
				console.error('[ERROR] invalid context', context);
				throw new Error('invalid context:' + context);
			}

			this.classes(true);

			return this;
		},
		name: function(name) {
			if( !arguments.length ) return this._name;
			if( typeof(name) !== 'string' ) {
				console.error('WARN:illegal component.name(string)', name);
				return this;
			}

			var previous = this._name;
			this._name = name;
			this.el.attr('name', name);
			this.fireSync('named', {previous: previous, name: name});

			return this;
		},
		rebuild: function() {
			_makeup.call(this);
			this.fire('rebuilt');
			return this;
		},
		parent: function() {
			return this._parent;
		},
		detach: function() {
			var parent = this.parent();
			if( parent ) {
				if( parent.disconnect(this) ) {
					this.el.detach();
				} else {
					console.log('detach refused by ', target);
					throw new Error('cannot detach from target');
				}
			} else {
				this.el.detach();
			}

			return this;
		},
		attachTo: function(target, index) {
			if( !target ) return this;

			var origin = target;

			if( EL.isElement(target) || typeof(target) === 'string' ) target = $(target) || target;

			if( typeof(target) === 'string' ) {
				var context = this.context();

				if( context ) {
					target = context.find(target) || target;
				}
			}

			if( target instanceof UI.Attachable ) {
				if( target.attachTarget() && target.connect(this) ) {
					target.attachTarget().attach(this.el, index);
				} else {
					console.log('attach refused by ', target);
					throw new Error('cannot attach to target');
				}
			} else if( target instanceof EL ) {
				target.attach(this.el, index);
			} else {
				console.error('invalid target', origin);
				throw new Error('invalid target(available only Element or EL or UI.Attachable)');
			}

			return this;
		},

		// dom control
		classes: function(classes) {
			var el = this.el;
			var cls = this.constructor;

			if( !arguments.length ) return el.classes();

			var accessor;
			if( cls.accessor ) {
				accessor = cls.accessor;
			} else {
				for(var c = cls;c = c.inherits;) {
					accessor = (c && c.accessor);
					if( accessor ) break;
				}
			}

			el.classes('');
			el.ac(this.context().theme(this.theme()).accessor().split('.'));
			el.ac(accessor);
			if( typeof(classes) === 'string' ) el.ac(classes);
			return this;
		},
		theme: function(theme) {
			if( !arguments.length ) return this._theme;

			if( typeof(theme) === 'string' ) this._theme = theme;
			else return console.error('invalid theme name', theme);

			this.classes(true);

			return this;
		},
		style: function(key, value) {
			if( !arguments.length ) return this.el.style();
			if( arguments.length === 1 && typeof(key) === 'string' ) return this.el.style(key);

			this.el.style.apply(this.el, arguments);
			return this;
		},
		css: function(css) {
			var el = this.el;
			var id = el.id();
			var stylesheet = this.context().stylesheet();

			if( !arguments.length ) return id ? stylesheet.get('#' + id) : null;

			if( typeof(css) === 'object' ) {
				id = id || ('gen-' + (this.constructor.cmpname || 'nemo') + '-' + (seq++));
				el.id(id);
				stylesheet.update('#' + id, css);
				if( css.debug ) console.log('#' + id, stylesheet.build());
			} else if( css === false ) {
				if( id ) {
					el.id(false);
					stylesheet.remove(id);
				}
			} else {
				console.warn('invalid css', css);
			}

			return this;
		},
		abs: function(abs) {
			var el = this.el;
			if( !arguments.length ) return el.hc('abs');

			el.rc('abs').rc('top').rc('right').rc('left').rc('bottom');

			if( abs !== false ) {
				this.el.ac('abs');
			}

			if( typeof(abs) === 'string' ) {
				if( ~abs.indexOf('top') ) el.ac('top');
				if( ~abs.indexOf('left') ) el.ac('left');
				if( ~abs.indexOf('right') ) el.ac('right');
				if( ~abs.indexOf('bottom') ) el.ac('bottom');
			}

			return this;
		},
		html: function(html) {
			if( !arguments.length ) return this.el.html();
			if( typeof(html) === 'string' ) this.el.html(html);
			return this;
		},
		anim: function(from, to, fn) {
			this.el.anim(from, to, fn);
			return this;
		},
		show: function(anim, fn) {
			this.el.show();
			this.fire('show');
			return this;
		},
		hide: function(anim, fn) {
			this.el.hide();
			this.fire('hide');
			return this;
		},
		disable: function(b) {
			this.enable(b === false ? true : false);
		},
		enable: function(b) {
			var el = this.el;
			if( b === false ) {
				if( !el.hc('disabled') ) {
					el.ac('disabled');
					this.fire('disabled');
				}
			} else {
				if( el.hc('disabled') ) {
					el.rc('disabled');
					this.fire('enabled');
				}
			}

			return this;
		},
		boundary: function() {
			return this.el.boundary();
		},
		data: function(key, value) {
			if( !arguments.length ) return this.el.data();
			if( arguments.length == 1 ) return this.el.data(key);

			this.el.data(key, value);

			return this;
		},

		// href
		action: function(href) {
			if( !href ) return false;

			var href = href.trim();
			if( href.toLowerCase().startsWith('javascript:') ) {
				var script = href.substring(11);
				var self = this;
				(function() {
					var context = self.context();
					var module = (context) ? context.origin() : null;
					var o = eval(script);
					if( o ) console.log('href script call has result', o);
				})();
			} else if( href.startsWith('this:') ) {
				var path = href.substring(5);
				var context = self.context();
				if( context ) url = context.path(path);
				location.href = path;
			} else {
				location.href = href;
			}

			return true;
		},
		href: function(href) {
			if( !arguments.length ) return this._href;

			this._href = href;
			if( this._hrefhandler ) this.un('click', this._hrefhandler);

			if( href && typeof(href) === 'string' ) {
				var self = this;
				this._hrefhandler = function(e) {
					self.action.call(self, self._href);
				};
				this.on('click', this._hrefhandler);
				this.el.ac('clickable');
			} else {
				this.el.rc('clickable');
				this._href = null;
				try { delete this._href; } catch(e) {}
			}

			return this;
		},

		// event handle
		on: function(action, fn, bubble) {
			if( !action ) return null;

			var dispatcher = this._dispatcher;
			if( !dispatcher ) return;

			// if action is dom element event type, binding events to dom element
			if( ~EL_BRIDGE.indexOf(action) || action.startsWith('el.') || action == '*' || action == 'el.*' || action === 'resize' ) {
				var type = action.startsWith('el.') ? action.substring(3) : action;

				var self = this;
				var el = this.el;
				var listener = (function(fn) {
					return function(e) {
						e.src = self;
						fn.call(dispatcher.scope(), e);
					}
				})(fn);

				fn.proxies = listener;

				if( type === '*' ) for(var i=0; i < EL_EVENTS.length; i++) el.on(EL_EVENTS[i], listener, bubble);
				else if( ~EL_EVENTS.indexOf(type) ) el.on(type, listener, bubble);

				if( type === 'resize' || type === '*' ) {
					var oel = el[0];
					var w = oel.scrollWidth, h = oel.scrollHeight;

					listener = (function(handler) {
						return function(e) {
							if( w !== oel.scrollWidth || h !== oel.scrollHeight ) {
								e.src = self;
								handler.call(dispatcher.scope(), e);
								w = oel.scrollWidth;
								h = oel.scrollHeight;
							}
						}
					})(fn);

					fn.resize_proxy = listener;
					UI.on('resize', listener, bubble);
				}
			}

			// adjust event type name for nomalize usage
			if( ~EL_BRIDGE.indexOf(action) || action.startsWith('el.') ) {
				action = (action.startsWith('el.')) ? action.substring(3) : action;
				arguments[0] = action;
			}

			dispatcher.on.apply(dispatcher, arguments);
			return this;
		},
		un: function(action, fn, bubble) {
			if( !action ) return null;

			var dispatcher = this._dispatcher;
			if( !dispatcher ) return;

			if( ~EL_BRIDGE.indexOf(action) || action.startsWith('el.') || action == '*' || action == 'el.*' || action === 'resize' ) {
				var type = action.startsWith('el.') ? action.substring(3) : action;
				var listener = fn.proxies;
				var resize_proxy = fn.resize_proxy;

				if( listener ) {
					if( type === '*' ) for(var i=0; i < EL_EVENTS.length; i++) el.un(EL_EVENTS[i], listener, bubble);
					else if( ~EL_EVENTS.indexOf(type) ) el.un(type, listener, bubble);
				}

				if( resize_proxy && type === 'resize' || type === '*' ) UI.un('resize', resize_proxy, bubble);
			}

			// adjust event type name for nomalize usage
			if( ~EL_BRIDGE.indexOf(action) || action.startsWith('el.') ) {
				action = (action.startsWith('el.')) ? action.substring(3) : action;
				arguments[0] = action;
			}

			dispatcher.un.apply(dispatcher, arguments);
			return this;
		},
		fireSync: function() {
			var d = this._dispatcher;
			if( !d ) return;
			return d.fireSync.apply(d, arguments);
		},
		fire: function() {
			var d = this._dispatcher;
			if( !d ) return;
			return d.fire.apply(d, arguments);
		},
		toJSON: function() {
			var o = this.options.toJSON();

			var json = {
				component: this.constructor.namespace
			};

			for(var k in o) {
				if( o.hasOwnProperty(k) ) json[k] = o[k];
			}

			return json;
		},
		destroy: function() {
			this.detach();
			var ns = this.constructor.namespace;
			var name = this.name() || '(unknown)';
			var context = this.context();
			if( context ) context.disconnect(this);
			this.el.clear();
			for(var k in this) {
				if( this.hasOwnProperty(k) ) continue;
				var v = this[k];
				this[k] = null;
				try { delete this[k]; } catch(e) {}
				if( typeof(v) === 'function' ) this[k] = function() {throw new Error(ns + ' component [' + name + '] was destroyed.');};
			}
		}
	};

	Component.style = {
		'user-select': 'none',
		'box-sizing': 'border-box',
		'margin': 0,
		'padding': 0,

		'*': {
			'box-sizing': 'border-box',
			'margin': 0,
			'padding': 0
		},
		'::selection': {
			'background-color': '#cc3c09',
			'color': '#fff',
			'text-shadow': 'none'
		},

		// classes
		'..fit': {
			'position': 'absolute !important',
			'top': 0,
			'left': 0,
			'right': 0,
			'bottom': 0,
			'overflow': 'hidden'
		},
		'..abs': {
			'position': 'absolute !important'
		},
		'..abs.h': {
			'width': '100%'
		},
		'..abs.v': {
			'height': '100%'
		},
		'..abs.top': {
			'left': '0',
			'top': '0'
		},
		'..abs.left': {
			'top': '0',
			'left': '0'
		},
		'..abs.right': {
			'top': '0',
			'right': '0'
		},
		'..abs.bottom': {
			'left': '0',
			'bottom': '0'
		},
		'..fixed': {
			'position': 'absolute !important'
		},
		'..fixed.h': {
			'width': '100%'
		},
		'..fixed.v': {
			'height': '100%'
		},
		'..fixed.top': {
			'left': '0',
			'top': '0'
		},
		'..fixed.left': {
			'top': '0',
			'left': '0'
		},
		'..fixed.right': {
			'top': '0',
			'right': '0'
		},
		'..fixed.bottom': {
			'left': '0',
			'bottom': '0'
		},
		'..border': {
			'border': '1px solid rgba(255,255,255, 0.1)'
		},
		'..boxshadow': {
			'box-shadow': '0 0 5px rgba(25,25,25,0.3)'
		},
		'..round': {
			'border-radius': 5
		},
		'..glass': {
			'background-image': 'linear-gradient(top, rgba(255, 255, 255, 0.3) 0%, rgba(255, 255, 255, 0.1) 50%, rgba(255, 255, 255, 0) 50%)',
			'border-top': '1px solid rgba(255, 255, 255, 0.4)',
			'border-bottom': '1px solid rgba(0, 0, 0, 0.3)'
		},
		'..pad': {
			'margin': 5,
			'padding': 5
		},
		'..innerpad': {
			'padding': 5
		},
		'..outerpad': {
			'margin': 5
		},
		'..clickable': {
			'cursor': ['hand', 'pointer']
		},
		'..bg-stripe': {
			'background-image': 'url(data:image/gif;base64,R0lGODlhBwABAKIAAAAAAP///8G2pMzDtP///wAAAAAAAAAAACH5BAEAAAQALAAAAAAHAAEAAAMEKKozCQA7)'
		},
		'..bg-transparent': {
			'background-color': 'white',
			'background-image': 'url(data:image/gif;base64,R0lGODlhAgACAJEAAAAAAP///8DAwP///yH5BAEAAAMALAAAAAACAAIAAAID1CYFADs=)',
			'background-size': '16px'
		}
	};

	return Component = UI.inherit(Component, UI.UIObject, false);
})();

UI.Component = UI.component('x', UI.Component);


text:
package com.md.vertx.deserializer;

import org.junit.Test;

import static org.hamcrest.core.Is.is;
import static org.hamcrest.core.IsEqual.equalTo;
import static org.junit.Assert.assertThat;

public class StringSerializerTest {

    private StringSerializer serializer = new StringSerializer();

    @Test
    public void serialize_shouldSerializeAndDeserialize() {
        // given
        String toSerialize = "hello";

        // when
        byte[] serialized = serializer.serialize(toSerialize);

        // then
        assertThat(serialized.length, is(5));
        String deserialized = serializer.deserialize(serialized);
        assertThat(deserialized, is(equalTo(toSerialize)));
    }

    @Test(expected = SerializerException.class)
    public void serialize_shouldThrowSerializerException() {
        // when... then exception
        serializer.serialize(null);
    }

    @Test(expected = SerializerException.class)
    public void deserialize_shouldThrowSerializerException() {
        // when... then exception
        serializer.deserialize(null);
    }
}


text:
/*	$NetBSD: verified_exec.c,v 1.4 2003/07/14 15:47:04 lukem Exp $	*/

/*-
 * Copyright (c) 1998-1999 Brett Lymn
 *                         (blymn@baea.com.au, brett_lymn@yahoo.com.au)
 * All rights reserved.
 *
 * This code has been donated to The NetBSD Foundation by the Author.
 *
 * Redistribution and use in source and binary forms, with or without
 * modification, are permitted provided that the following conditions
 * are met:
 * 1. Redistributions of source code must retain the above copyright
 *    notice, this list of conditions and the following disclaimer.
 * 2. The name of the author may not be used to endorse or promote products
 *    derived from this software withough specific prior written permission
 *
 * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR
 * IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
 * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
 * IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT,
 * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
 * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
 * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
 * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
 * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
 * THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
 *
 *
 */

#include <sys/cdefs.h>
__KERNEL_RCSID(0, "$NetBSD: verified_exec.c,v 1.4 2003/07/14 15:47:04 lukem Exp $");

#include <sys/param.h>
#include <sys/systm.h>
#include <sys/proc.h>
#include <sys/errno.h>
#include <sys/verified_exec.h>
#include <sys/buf.h>
#include <sys/malloc.h>
#include <sys/ioctl.h>
#include <sys/device.h>
#include <sys/conf.h>
#include <sys/lock.h>
#include <sys/queue.h>
#include <sys/vnode.h>
#include <sys/fcntl.h>
#include <sys/namei.h>

struct verified_exec_softc {
	struct device	veriexec_dev;
};

const struct cdevsw verifiedexec_cdevsw = {
        verifiedexecopen, verifiedexecclose, noread, nowrite,
	verifiedexecioctl, nostop, notty, nopoll, nommap, nokqfilter,
};

/* internal structures */
LIST_HEAD(veriexec_devhead, veriexec_dev_list) veriexec_dev_head;
/*LIST_HEAD(veriexec_file_devhead, veriexec_dev_list) veriexec_file_dev_head;*/
struct veriexec_devhead veriexec_file_dev_head;

/* Autoconfiguration glue */
void	verifiedexecattach(struct device *parent, struct device *self,
			 void *aux);
int     verifiedexecopen(dev_t dev, int flags, int fmt, struct proc *p);
int     verifiedexecclose(dev_t dev, int flags, int fmt, struct proc *p);
int     verifiedexecioctl(dev_t dev, u_long cmd, caddr_t data, int flags,
			struct proc *p);
void    add_veriexec_inode(struct veriexec_dev_list *list, unsigned long inode,
			unsigned char fingerprint[MAXFINGERPRINTLEN],
			unsigned char type, unsigned char fp_type);
struct veriexec_dev_list *find_veriexec_dev(unsigned long dev,
				      struct veriexec_devhead *head);

/*
 * Attach for autoconfig to find.  Initialise the lists and return...
 */
void
verifiedexecattach(struct device *parent, struct device *self, void *aux)
{
	LIST_INIT(&veriexec_dev_head);
	LIST_INIT(&veriexec_file_dev_head);
}

int
verifiedexecopen(dev_t dev, int flags, int fmt, struct proc *p)
{
	return 0;
}

int
verifiedexecclose(dev_t dev, int flags, int fmt, struct proc *p)
{
#ifdef VERIFIED_EXEC_DEBUG_VERBOSE
	struct veriexec_dev_list *lp;
	struct veriexec_inode_list *ip;

	printf("Loaded exec fingerprint list is:\n");
	for (lp = LIST_FIRST(&veriexec_dev_head); lp != NULL;
	     lp = LIST_NEXT(lp, entries)) {
		for (ip = LIST_FIRST(&(lp->inode_head)); ip != NULL;
		     ip = LIST_NEXT(ip, entries)) {
			printf("Got loaded fingerprint for dev %lu, inode %lu\n",
			       lp->id, ip->inode);
		}
	}

	printf("\n\nLoaded file fingerprint list is:\n");
	for (lp = LIST_FIRST(&veriexec_file_dev_head); lp != NULL;
	     lp = LIST_NEXT(lp, entries)) {
		for (ip = LIST_FIRST(&(lp->inode_head)); ip != NULL;
		     ip = LIST_NEXT(ip, entries)) {
			printf("Got loaded fingerprint for dev %lu, inode %lu\n",
			       lp->id, ip->inode);
		}
	}
#endif
	return 0;
}

/*
 * Search the list of devices looking for the one given.  If it is not
 * in the list then add it.
 */
struct veriexec_dev_list *
find_veriexec_dev(unsigned long dev, struct veriexec_devhead *head)
{
	struct veriexec_dev_list *lp;

	for (lp = LIST_FIRST(head); lp != NULL;
	     lp = LIST_NEXT(lp, entries))
		if (lp->id == dev) break;

	if (lp == NULL) {
		  /* if pointer is null then entry not there, add a new one */
		MALLOC(lp, struct veriexec_dev_list *,
                       sizeof(struct veriexec_dev_list), M_TEMP, M_WAITOK);
		LIST_INIT(&(lp->inode_head));
		lp->id = dev;
		LIST_INSERT_HEAD(head, lp, entries);
	}

	return lp;
}

/*
 * Add a file's inode and fingerprint to the list of inodes attached
 * to the device id.  Only add the entry if it is not already on the
 * list.
 */
void
add_veriexec_inode(struct veriexec_dev_list *list, unsigned long inode,
		unsigned char fingerprint[MAXFINGERPRINTLEN],
		unsigned char type, unsigned char fp_type)
{
	struct veriexec_inode_list *ip;

	for (ip = LIST_FIRST(&(list->inode_head)); ip != NULL;
	     ip = LIST_NEXT(ip, entries))
		  /* check for a dupe inode in the list, skip if an entry
		   * exists for this inode except for when the type is
		   * VERIEXEC_INDIRECT, always set the type when it is so
		   * we don't get a hole caused by conflicting types on
		   * hardlinked files.  XXX maybe we should validate
		   * fingerprint is same and complain if it is not...
		   */
		if (ip->inode == inode) {
			if (type == VERIEXEC_INDIRECT)
				ip->type = type;
			return;
		}

	MALLOC(ip, struct veriexec_inode_list *, sizeof(struct veriexec_inode_list),
	       M_TEMP, M_WAITOK);
	ip->type = type;
	ip->fp_type = fp_type;
	ip->inode = inode;
	memcpy(ip->fingerprint, fingerprint, sizeof(ip->fingerprint));
	LIST_INSERT_HEAD(&(list->inode_head), ip, entries);
}

/*
 * Handle the ioctl for the device
 */
int
verifiedexecioctl(dev_t dev, u_long cmd, caddr_t data, int flags,
		struct proc *p)
{
	int error = 0;
	struct verified_exec_params *params = (struct verified_exec_params *)data;
	struct nameidata nid;
	struct vattr vattr;
	struct veriexec_dev_list *dlp;

#ifdef VERIFIED_EXEC_DEBUG
	printf("veriexec_ioctl: got cmd 0x%lx for file %s\n", cmd, params->file);
#endif

	switch (cmd) {
	  case VERIEXECLOAD:
		if (securelevel > 0) {
			  /* don't allow updates when secure */
			error = EPERM;
		} else {
			  /*
			   * Get the attributes for the file name passed
			   * stash the file's device id and inode number
			   * along with it's fingerprint in a list for
			   * exec to use later.
			   */
                        NDINIT(&nid, LOOKUP, FOLLOW, UIO_USERSPACE,
                               params->file, p);
			if ((error = vn_open(&nid, FREAD, 0)) != 0) {
				return(error);
			}
			error = VOP_GETATTR(nid.ni_vp, &vattr, p->p_ucred, p);
			if (error) {
				nid.ni_vp->fp_status = FINGERPRINT_INVALID;
				VOP_UNLOCK(nid.ni_vp, 0);
				(void) vn_close(nid.ni_vp, FREAD,
						p->p_ucred, p);
				return(error);
			}
			/* invalidate the node fingerprint status
			 * which will have been set in the vn_open
			 * and would always be FINGERPRINT_NOTFOUND
			 */
			nid.ni_vp->fp_status = FINGERPRINT_INVALID;
			VOP_UNLOCK(nid.ni_vp, 0);
			(void) vn_close(nid.ni_vp, FREAD, p->p_ucred, p);
			  /* vattr.va_fsid = dev, vattr.va_fileid = inode */
			if (params->type == VERIEXEC_FILE) {
				dlp = find_veriexec_dev(vattr.va_fsid,
						     &veriexec_file_dev_head);
			} else {
				dlp = find_veriexec_dev(vattr.va_fsid,
						     &veriexec_dev_head);
			}

			add_veriexec_inode(dlp, vattr.va_fileid,
					params->fingerprint, params->type,
					params->fp_type);
		}
		break;

	default:
		error = ENODEV;
	}

	return (error);
}


text:
<?xml version="1.0" encoding="UTF-8"?>
<definitions xmlns="http://ws.apache.org/ns/synapse">
    <api xmlns="http://ws.apache.org/ns/synapse"
         name="status_code_200_API"
         context="/response200" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://ws.apache.org/ns/synapse ">
        <resource methods="GET POST" url-mapping="/*">
            <inSequence>
                <property name="HTTP_SC" value="200" scope="axis2"/>
                <header name="To" action="remove"/>
                <property name="RESPONSE" value="true" scope="default" type="STRING"/>
                <payloadFactory media-type="json">
                    <format>
                        {"employees":[
                        {"firstName":"John", "lastName":"Doe"},
                        {"firstName":"Anna", "lastName":"Smith"},
                        {"firstName":"Peter", "lastName":"Jones"}
                        ]}
                    </format>
                </payloadFactory>
                <send/>
            </inSequence>
        </resource>
    </api>
</definitions>


text:
import type {
  AggregatedResult,
  AssertionResult,
  CodeCoverageFormatter,
  CodeCoverageReporter,
  FormattedAssertionResult,
  FormattedTestResult,
  FormattedTestResults,
  TestResult,
} from 'types/TestResult';

const formatResult = (
  testResult: TestResult,
  codeCoverageFormatter: CodeCoverageFormatter,
  reporter: CodeCoverageReporter,
): FormattedTestResult => {
  const now = Date.now();
  const output: FormattedTestResult = {
    assertionResults: [],
    coverage: {},
    endTime: now,
    message: '',
    name: testResult.testFilePath,
    startTime: now,
    status: 'failed',
    summary: '',
  };

  if (testResult.testExecError) {
    output.message = testResult.testExecError.message;
    output.coverage = {};
  } else {
    const allTestsPassed = testResult.numFailingTests === 0;
    output.status = allTestsPassed ? 'passed' : 'failed';
    output.startTime = testResult.perfStats.start;
    output.endTime = testResult.perfStats.end;
    output.coverage = codeCoverageFormatter(testResult.coverage, reporter);
  }

  output.assertionResults = testResult.testResults.map(formatTestAssertion);

  if (testResult.failureMessage) {
    output.message = testResult.failureMessage;
  }

  return output;
};

function formatTestAssertion(
  assertion: AssertionResult,
): FormattedAssertionResult {
  const result: FormattedAssertionResult = {
    failureMessages: null,
    fullName: assertion.fullName,
    status: assertion.status,
    title: assertion.title,
  };
  if (assertion.failureMessages) {
    result.failureMessages = assertion.failureMessages;
  }
  return result;
}

function formatTestResults(
  results: AggregatedResult,
  codeCoverageFormatter?: CodeCoverageFormatter,
  reporter?: CodeCoverageReporter,
): FormattedTestResults {
  const formatter = codeCoverageFormatter || (coverage => coverage);

  const testResults = results.testResults.map(testResult =>
    formatResult(testResult, formatter, reporter),
  );

  return Object.assign((Object.create(null): any), results, {
    testResults,
  });
}

module.exports = formatTestResults;


text:
from django.contrib.auth import get_user_model
from django.contrib.sites.models import Site
from django.core.exceptions import ObjectDoesNotExist

from userena.backends import UserenaAuthenticationBackend

class SiteBackend(UserenaAuthenticationBackend):
    def authenticate(self, request, **credentials):
        if 'username' in credentials and 'password' in credentials:
            # auth request from admin login form
            user_or_none = super().authenticate(
                    request,
                    identification=credentials['username'],
                    password=credentials['password'])
        else:
            user_or_none = super().authenticate(request, **credentials)
        if (user_or_none and
                Site.objects.get_current()
                not in user_or_none.userprofile.sites.all()):
            return
        return user_or_none

    def get_user(self, user_id):
        try:
            return get_user_model().objects.get(
                pk=user_id, userprofile__sites=Site.objects.get_current())
        except ObjectDoesNotExist:
            return None


text:
import React from 'react'
import Header from '../components/common/Header'
import { Tabs } from 'antd-mobile'
const TabPane = Tabs.TabPane;
function callback() {
    console.log(1);
}
const Audits = ({
    location: { pathname }
}) => {
    return (

            <Tabs defaultActiveKey="1" onchange={callback}>
                <TabPane tab="已审批" key="1">

                        选项卡一内容

                </TabPane>
                <TabPane tab="待审批" key="2">

                        选项卡一内容

                </TabPane>
                <TabPane tab="近30天" key="3">

                        选项卡一内容

                </TabPane>
            </Tabs>

    )
}

export default Audits


text:
require File.dirname(__FILE__) + '/../../spec_helper'
require File.dirname(__FILE__) + '/fixtures/classes'

ruby_version_is "1.9" do
  describe "Kernel#respond_to_missing?" do
    before :each do
      @a = KernelSpecs::A.new
    end

    it "returns false by default" do
      Object.new.respond_to_missing?.should be_false
    end

    it "is not called when #respond_to? would return true" do
      obj = mock('object')
      obj.stub!(:glark)
      obj.should_not_receive(:respond_to_missing?)
      obj.respond_to?(:glark).should be_true
    end

    it "is called when #respond_to? would return false" do
      obj = mock('object')
      obj.should_receive(:respond_to_missing?).with(:undefined_method)
      obj.respond_to?(:undefined_method)
    end

    it "is called with true as the second argument when #respond_to? is" do
      obj = mock('object')
      obj.should_receive(:respond_to_missing?).with(:undefined_method, true)
      obj.respond_to?(:undefined_method, true)
    end

    it "causes #respond_to? to return true if called and not returning false" do
      obj = mock('object')
      obj.should_receive(:respond_to_missing?).with(:undefined_method).and_return(:glark)
      obj.respond_to?(:undefined_method).should be_true
    end

    it "causes #respond_to? to return false if called and returning false" do
      obj = mock('object')
      obj.should_receive(:respond_to_missing?).with(:undefined_method).and_return(false)
      obj.respond_to?(:undefined_method).should be_false
    end

    it "is not called with false as a second argument when #respond_to? is" do
      obj = mock('object')
      obj.should_receive(:respond_to_missing?).with(:undefined_method)
      obj.respond_to?(:undefined_method, false)
    end

    it "isn't called when obj responds to the given public method" do
      @a.should_not_receive(:respond_to_missing?)
      @a.respond_to?(:pub_method).should be_true
    end

    it "isn't called when obj responds to the given public method, include_private = true" do
      @a.should_not_receive(:respond_to_missing?)
      @a.respond_to?(:pub_method, true).should be_true
    end

    it "isn't called when obj responds to the given protected method" do
      @a.should_not_receive(:respond_to_missing?)
      @a.respond_to?(:protected_method, false).should be_true
    end

    it "isn't called when obj responds to the given protected method, include_private = true" do
      @a.should_not_receive(:respond_to_missing?)
      @a.respond_to?(:protected_method, true).should be_true
    end

    it "is called when obj responds to the given private method, include_private = false" do
      @a.should_receive(:respond_to_missing?).with(:private_method)
      @a.respond_to?(:private_method)
    end

    it "isn't called when obj responds to the given private method, include_private = true" do
      @a.should_not_receive(:respond_to_missing?)
      @a.respond_to?(:private_method, true).should be_true
    end

    it "is called for missing class methods" do
      @a.class.should_receive(:respond_to_missing?).with(:oOoOoO)
      @a.class.respond_to?(:oOoOoO)
    end
  end
end


text:
function mm = DegreesToRetinalMM(degs,eyeLengthMM,fulltrig)
%  mm = DegreesToRetinalMM(degs,eyeLengthMM,[fulltrig])
%
% Convert foveal extent in degrees to mm of retina in the fovea.
%
% This is implemented by default as a simple linear scaling based on the
% appropriate conversion for small angles.  It does not take the
% non-linearity of the tangent for larger angles into account, nor the
% actual shape and optics of the eye.  Interestingly, although the trig
% calculation would be exactly correct for pinhole camera and a planar
% retina oriented orthogonal to the optical axis, it deviates more from
% what the real eye does than the linear approximation.
%
% In addition, this routine and RetinalMMToDegrees are implemented as the
% exact inverses of each other in this default mode.
%
% If optional argument fulltrig is passed as true (it is false by default),
% then it uses the inverse tangent on the actuall passed mm.  This was the
% behavior prior to July 2015. This behavior does not exactly self invert
% with RetinalMMToDegrees.  Nor does it account for the shape and optics of
% the eye.
%
% Routine EyeLength returns posterior nodal eye lengths for various species
% and sources.  Use 'Human' and 'Rodieck' to get the eye lenght implicit in
% RetinalEccentricityMMToDegrees and DegreesToRetinalEccentricityMM for
% human, and similarly 'Rhesus' and 'PerryCowey' for rhesus.
%
% See also: RetinalMMToDegrees, EyeLength, RetinalEccentricityMMToDegrees, DegreesToRetinalEccentricityMM
%
% 7/15/03  dhb  Wrote it.
% 7/01/15  dhb  Update comments, change default behavior, preserve old behavior optionally.

% Default args
if (nargin < 3 || isempty(fulltrig))
    fulltrig = false;
end

if (~fulltrig)
    factor = 2*tan((pi/180)*1/2)*eyeLengthMM;
    mm = factor*degs;
else
    mm = 2*tan((pi/180)*degs/2)*eyeLengthMM;
end


text:
title: 'Clarification & Credits for openSUSE on ARM Chromebooks'
author: Andrew Wafaa
layout: post
kind: article
created_at: 2012-10-26
permalink: /clarification-credits-for-opensuse-on-arm-chromebooks/
dsq_thread_id:
  - 901015438
categories:
  - ARM
  - openSUSE
tags:
  - ARM
  - ARMv5
  - ARMv7
  - Chromebook
  - thanks
---
#

After my [post][1] yesterday on getting openSUSE on the new ARM Chromebook, a lot of interest was generated with discussions on various forms of media – heck I even got Slashdotted (thanks :-) ). I read some but not all of them and even the comments. One thing popped out to me, and I feel I need to clarify some things.

 [1]: http://andrew.wafaa.eu/2012/10/25/geeko-goes-chrome.html "Geeko goes Chrome"

1.  Whilst I do indeed work for ARM, my device was a private purchase and not provided to me by my employer. Luckily as part of my role I am able to spend time doing fun things like getting openSUSE on the Chromebook.
2.  I have never taken credit for doing all the hard work of working out what needed to be done to get openSUSE on the Chromebook, the hard work was done by Olof Johanssen as I mentioned. He wrote up some excellent steps that were very easy to follow. I and all other people interested in getting Linux on the Chromebook regardless of distro are indebted to Olof for his work.
3.  I am not responsible or incharge of getting openSUSE on ARM. It is a collaborative effort by the community, and there are many others that have put in a whole heap of hard work doing things that I can only aspire to do. To name a few of the fine people in our community that have put in the time and effort would be a mistake as I will undoubtedly miss some people off the list, but it is  a mistake I'm willing to accept so here goes - Adrian Schröter, Alex Graf, Joop Boonen, Guillaume Gardet, Marcus Schäfer, Dirk Müller, Andreas Färber, Bernhard Wiedemann, Bamvor Jian Zhang, Peter Czanik, Michal Vyskocil, and many more. Without the blood, sweat and tears that these fine folk have shed we would not be in the position we are now; so thank you all for your hard work and long may it continue :-)

Hopefully that will clarify any confusion that some people may have had, and sorry to those that I missed off the list – if you feel hard done by me omitting your name off this list please let me know and I will make sure you get the credit you deserve!


text:
require('./_xt');

module.exports = _xt;


text:
namespace bp = boost::python;

void register_ComponentArea_class(){

    { //::CEGUI::ComponentArea
        typedef bp::class_< CEGUI::ComponentArea > ComponentArea_exposer_t;
        ComponentArea_exposer_t ComponentArea_exposer = ComponentArea_exposer_t( "ComponentArea", bp::init< >() );
        bp::scope ComponentArea_scope( ComponentArea_exposer );
        { //::CEGUI::ComponentArea::getAreaPropertySource

            typedef ::CEGUI::String const & ( ::CEGUI::ComponentArea::*getAreaPropertySource_function_type )(  ) const;

            ComponentArea_exposer.def(
                "getAreaPropertySource"
                , getAreaPropertySource_function_type( &::CEGUI::ComponentArea::getAreaPropertySource )
                , bp::return_value_policy< bp::copy_const_reference >()
                , "*!\n\
                \n\
                    Return the name of the property that will be used to determine the pixel\n\
                    area for this ComponentArea.\n\
            \n\
                @return\n\
                    String object holding the name of a Propery.\n\
                *\n" );

        }
        { //::CEGUI::ComponentArea::getPixelRect

            typedef ::CEGUI::Rectf ( ::CEGUI::ComponentArea::*getPixelRect_function_type )( ::CEGUI::Window const & ) const;

            ComponentArea_exposer.def(
                "getPixelRect"
                , getPixelRect_function_type( &::CEGUI::ComponentArea::getPixelRect )
                , ( bp::arg("wnd") )
                , "*!\n\
                \n\
                    Return a Rect describing the absolute pixel area represented by this\n\
                    ComponentArea.\n\
            \n\
                @param wnd\n\
                    Window object to be used when calculating final pixel area.\n\
            \n\
                @return\n\
                    Rectf object describing the pixels area represented by this ComponentArea\n\
                    when using  wnd as a reference for calculating the final pixel\n\
                    dimensions.\n\
                *\n" );

        }
        { //::CEGUI::ComponentArea::getPixelRect

            typedef ::CEGUI::Rectf ( ::CEGUI::ComponentArea::*getPixelRect_function_type )( ::CEGUI::Window const &,::CEGUI::Rectf const & ) const;

            ComponentArea_exposer.def(
                "getPixelRect"
                , getPixelRect_function_type( &::CEGUI::ComponentArea::getPixelRect )
                , ( bp::arg("wnd"), bp::arg("container") )
                , "*!\n\
                \n\
                    Return a Rectd describing the absolute pixel area represented by this\n\
                    ComponentArea.\n\
            \n\
                @param wnd\n\
                    Window object to be used when calculating final pixel area.\n\
            \n\
                @param container\n\
                    Rect object to be used as a base or container when converting relative\n\
                    dimensions.\n\
            \n\
                @return\n\
                    Rectf object describing the pixels area represented by this\n\
                    ComponentArea when using  wnd and  container as a reference for\n\
                    calculating the final pixel dimensions.\n\
                *\n" );

        }
        { //::CEGUI::ComponentArea::handleFontRenderSizeChange

            typedef bool ( ::CEGUI::ComponentArea::*handleFontRenderSizeChange_function_type )( ::CEGUI::Window &,::CEGUI::Font const * ) const;

            ComponentArea_exposer.def(
                "handleFontRenderSizeChange"
                , handleFontRenderSizeChange_function_type( &::CEGUI::ComponentArea::handleFontRenderSizeChange )
                , ( bp::arg("window"), bp::arg("font") )
                , "! perform any processing required due to the given font having changed.\n" );

        }
        { //::CEGUI::ComponentArea::isAreaFetchedFromNamedArea

            typedef bool ( ::CEGUI::ComponentArea::*isAreaFetchedFromNamedArea_function_type )(  ) const;

            ComponentArea_exposer.def(
                "isAreaFetchedFromNamedArea"
                , isAreaFetchedFromNamedArea_function_type( &::CEGUI::ComponentArea::isAreaFetchedFromNamedArea )
                , "*!\n\
                \n\
                    Return whether this ComponentArea fetches it's area via a named area\n\
                    defined.\n\
            \n\
                @return\n\
                    - true if the area comes via a named area defined in a WidgetLook.\n\
                    - false if the area is not sourced from a named area.\n\
                *\n" );

        }
        { //::CEGUI::ComponentArea::isAreaFetchedFromProperty

            typedef bool ( ::CEGUI::ComponentArea::*isAreaFetchedFromProperty_function_type )(  ) const;

            ComponentArea_exposer.def(
                "isAreaFetchedFromProperty"
                , isAreaFetchedFromProperty_function_type( &::CEGUI::ComponentArea::isAreaFetchedFromProperty )
                , "*!\n\
                \n\
                    Return whether this ComponentArea fetches it's area via a property on\n\
                    the target window.\n\
            \n\
                @return\n\
                    - true if the area comes via a Propery.\n\
                    - false if the area is not sourced from a Property.\n\
                *\n" );

        }
        { //::CEGUI::ComponentArea::setAreaPropertySource

            typedef void ( ::CEGUI::ComponentArea::*setAreaPropertySource_function_type )( ::CEGUI::String const & ) ;

            ComponentArea_exposer.def(
                "setAreaPropertySource"
                , setAreaPropertySource_function_type( &::CEGUI::ComponentArea::setAreaPropertySource )
                , ( bp::arg("property") )
                , "*!\n\
                \n\
                    Set the name of the property that will be used to determine the pixel\n\
                    area for this ComponentArea.\n\
            \n\
                \note\n\
                    Calling this will replace any existing souce, such as a named area.\n\
            \n\
                @param property\n\
                    String object holding the name of a Propery.  The property should access\n\
                    a URect type property.\n\
                *\n" );

        }
        { //::CEGUI::ComponentArea::setNamedAreaSouce

            typedef void ( ::CEGUI::ComponentArea::*setNamedAreaSouce_function_type )( ::CEGUI::String const &,::CEGUI::String const & ) ;

            ComponentArea_exposer.def(
                "setNamedAreaSouce"
                , setNamedAreaSouce_function_type( &::CEGUI::ComponentArea::setNamedAreaSouce )
                , ( bp::arg("widget_look"), bp::arg("area_name") )
                , "! Set the named area source of the ComponentArea.\n" );

        }
        { //::CEGUI::ComponentArea::writeXMLToStream

            typedef void ( ::CEGUI::ComponentArea::*writeXMLToStream_function_type )( ::CEGUI::XMLSerializer & ) const;

            ComponentArea_exposer.def(
                "writeXMLToStream"
                , writeXMLToStream_function_type( &::CEGUI::ComponentArea::writeXMLToStream )
                , ( bp::arg("xml_stream") )
                , "*!\n\
                \n\
                    Writes an xml representation of this ComponentArea to  out_stream.\n\
            \n\
                @param xml_stream\n\
                    XMLSerializer where xml data should be output.\n\
                *\n" );

        }
        ComponentArea_exposer.def_readwrite( "d_bottom_or_height", &CEGUI::ComponentArea::d_bottom_or_height, "! Either the right edge or the width of the area.\n\
        ! Either the bototm edge or the height of the area.\n" );
        ComponentArea_exposer.def_readwrite( "d_left", &CEGUI::ComponentArea::d_left, "! Left edge of the area.\n" );
        ComponentArea_exposer.def_readwrite( "d_right_or_width", &CEGUI::ComponentArea::d_right_or_width, "! Top edge of the area.\n\
        ! Either the right edge or the width of the area.\n" );
        ComponentArea_exposer.def_readwrite( "d_top", &CEGUI::ComponentArea::d_top, "! Left edge of the area.\n\
        ! Top edge of the area.\n" );
    }

}


text:
package de.kumpelblase2.remoteentities.entities;

import de.kumpelblase2.remoteentities.api.Fightable;
import de.kumpelblase2.remoteentities.api.RemoteEntity;

public interface RemoteOcelote extends RemoteEntity, Fightable
{
}