text:
package es.gob.jmulticard.ui.passwordcallback.gui;

import java.awt.Component;
import java.awt.Container;
import java.awt.Dimension;
import java.awt.GridBagConstraints;
import java.awt.GridBagLayout;
import java.awt.Image;
import java.awt.Insets;
import java.awt.Toolkit;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.FocusEvent;
import java.awt.event.FocusListener;
import java.awt.event.KeyEvent;
import java.awt.event.KeyListener;

import javax.swing.AbstractAction;
import javax.swing.ImageIcon;
import javax.swing.JButton;
import javax.swing.JComponent;
import javax.swing.JDialog;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
import javax.swing.JWindow;
import javax.swing.KeyStroke;
import javax.swing.SwingConstants;
import javax.swing.WindowConstants;

import es.gob.jmulticard.ui.passwordcallback.CancelledOperationException;
import es.gob.jmulticard.ui.passwordcallback.Messages;

/** Componente dialogo que define los alerts de la aplicación.
 * @author inteco */
public final class CustomDialog extends JAccessibilityCustomDialog implements ActionListener {

    /** UID. */
    private static final long serialVersionUID = 1L;

    /** Etiqueta con la informacion de la alerta. */
    private InfoLabel infoLabel = null;

    /** Panel de botones. */
    private JPanel buttonsPanel = null;

    /** Panel de botones relacionados con la accesibilidad. */
    private JPanel accessibilityButtonsPanel = null;

    /** Panel principal. */
    private JPanel mainPanel = null;

    /** Campo de texto o campo de contrasena */
    private JSecurePasswordLabel component = null;

    JSecurePasswordLabel getComponent() {
        return this.component;
    }

    /** Etiqueta que contiene el icono de la alerta. */
    private final IconLabel iconLabel = new IconLabel();

    /** Boton de OK. */
    private static JButton okButton = null;

    static JButton getOkButton() {
        return okButton;
    }

    /** Boton de NO. */
    private JButton noButton = null;

    JButton getNoButton() {
    	return this.noButton;
    }

    /** Boton de Cancel. */
    private static JButton cancelButton = null;

    static JButton getCancelButton() {
        return cancelButton;
    }

    /** Boton de restaurar. */
    private JButton restoreButton = null;

    JButton getRestoreButton() {
        return this.restoreButton;
    }

    /** Boton de maximizar. */
    private JButton maximizeButton = null;

    JButton getMaximizeButton() {
        return this.maximizeButton;
    }

    /** Respuesta al mensaje */
    private int answer;

    /** Texto para el botón */
    private static String cancellText = Messages.getString("PrincipalGUI.cancelar"); //$NON-NLS-1$

    /** Constructor.
     * @param componentParent componente padre.
     * @param modal true si se desea que el diálogo sea modal,
     *              false en caso contrario.
     * @param message mensaje
     * @param title Título
     * @param typeMessage Tipo de mensaje
     * @param isInputDialog indica sies una alerta de tipo input */
    private CustomDialog(final JDialog componentParent,
                         final boolean modal,
                         final String message,
                         final String title,
                         final int typeMessage,
                         final boolean isInputDialog) {
        super(componentParent, modal, isInputDialog);
        initComponents(message, title, typeMessage, isInputDialog);
        setLocationRelativeTo(componentParent);
        pack();
    }

    /** Constructor.
     * @param componentParent componente padre.
     * @param modal modal
     * @param message mensaje
     * @param title titulo
     * @param typeMessage tipo de mensaje
     * @param isInputDialog indica sies una alerta de tipo input */
    private CustomDialog(final Component componentParent,
                         final boolean modal,
                         final String message,
                         final String title,
                         final int typeMessage,
                         final boolean isInputDialog) {
        super(isInputDialog);
        this.setModal(modal);
        initComponents(message, title, typeMessage, isInputDialog);
        setLocationRelativeTo(componentParent);
        pack();
    }

    /** Constructor.
     * @param componentParent Componente padre para la modalidad.
     * @param modal modal
     * @param message Mensaje del diálogo.
     * @param title Título del diálogo.
     * @param typeMessage Tipo de mensaje
     * @param isInputDialog Indica si es un diálogo de entrada de datos. */
    private CustomDialog(final JFrame componentParent,
                         final boolean modal,
                         final String message,
                         final String title,
                         final int typeMessage,
                         final boolean isInputDialog) {
        super(componentParent, modal, isInputDialog);
        initComponents(message, title, typeMessage, isInputDialog);
        setLocationRelativeTo(componentParent);
        pack();
    }

    /** Posición X inicial de la ventana dependiendo de la resolución de pantalla.
     * @param width Ancho de la ventana.
     * @return int Posición X */
    private static int getInitialX(final int width) {
        final Dimension screenSize = Toolkit.getDefaultToolkit().getScreenSize();
        return screenSize.width / 2 - width / 2;
    }

    /** Posición Y inicial de la ventana dependiendo del sistema operativo y de la
     * resolución de pantalla.
     * @param height Alto de la ventana.
     * @return int Posición Y */
    private static int getInitialY(final int height) {
        final Dimension screenSize = java.awt.Toolkit.getDefaultToolkit().getScreenSize();
        return screenSize.height / 2 - height / 2;
    }

    /** Metodo que inicializa los componentes de la alerta.
     * @param message mensaje que se mostrara en la alerta
     * @param title Título de la alerta
     * @param typeMessage tipo de mensaje
     * @param isInputDialog indica sies una alerta de tipo input */
    private void initComponents(
    		final String message,
    		final String title,
    		final int typeMessage,
    		final boolean isInputDialog) {
        // Se obtienen las dimensiones de maximizado
        final int maxWidth = this.getMaxWidth();
        final int maxHeight = this.getMaxHeight();

        // Se establece el tamano minimo
        setMinimumSize(new Dimension(this.getInitialWidth(), this.getInitialHeight()));
        setPreferredSize(new Dimension(this.getInitialWidth(), this.getInitialHeight()));
        // Se establece el tamano maximo
        setMaximumSize(new Dimension(maxWidth, maxHeight));

        // Dimensiones de la ventana en Windows y Linux
        if (GeneralConfig.isMaximized()) {
            // Se maximiza
            this.setBounds(0, 0, maxWidth, maxHeight);
        }
        else {
            // Se establece el tamano minimo en base a las opciones activas
            if (GeneralConfig.isBigFontSize() || GeneralConfig.isFontBold()) {
                setMinimumSize(new Dimension(Constants.CUSTOMDIALOG_FONT_INITIAL_WIDTH, Constants.CUSTOMDIALOG_FONT_INITIAL_HEIGHT));
            }
        }

        this.setTitle(title);
        setDefaultCloseOperation(WindowConstants.DISPOSE_ON_CLOSE);

        this.answer = JOptionPane.NO_OPTION;
        // Contenedor del dialogo
        final Container container = getContentPane();
        // Layout del contenedor
        container.setLayout(new GridBagLayout());

        // Panel con los datos del dialogo
        this.mainPanel = new JPanel(new GridBagLayout());

        // Restricciones para el panel de datos
        final GridBagConstraints c = new GridBagConstraints();
        c.fill = GridBagConstraints.BOTH;
        c.gridx = 0;
        c.gridy = 0;
        c.insets = new Insets(5, 10, 0, 10);

        // Icono del dialogo
        setIconLabel();
        final JPanel iconPanel = new JPanel(new GridBagLayout());
        final GridBagConstraints consIconPanel = new GridBagConstraints();
        consIconPanel.fill = GridBagConstraints.BOTH;

        iconPanel.add(this.iconLabel, consIconPanel);

        c.insets = new Insets(10, 5, 0, 10); // right padding
        c.gridx = 1;
        c.weightx = 1.0;
        c.weighty = 1.0;

        // Etiqueta del dialogo
        if (isInputDialog) {
            // Se crea una etiqueta sencilla
            this.infoLabel = new InfoLabel(message);
            this.infoLabel.setHorizontalAlignment(SwingConstants.LEFT); // Se alinea a la izqda
            this.infoLabel.setVerticalAlignment(SwingConstants.CENTER); // Se alinea al centro el texto
        }
        else {
            // Se crea una etiqueta focusable
            this.infoLabel = new InfoLabel(message, false);
            this.infoLabel.setHorizontalAlignment(SwingConstants.CENTER); // Se centra el texto
            // Foco a la etiqueta
            this.infoLabel.addAncestorListener(new RequestFocusListener());
            this.infoLabel.setVerticalAlignment(SwingConstants.CENTER); // Se alinea al centro el texto
        }

        // Se anade la etiqueta al panel de informacion general
        this.mainPanel.add(this.infoLabel, c);

        // Panel de botones
        createMainButtonsPanel();
        createAccessibilityButtonsPanel();

        // Restricciones del contenedor general

        final GridBagConstraints cons = new GridBagConstraints();
        cons.fill = GridBagConstraints.BOTH;

        //Se anade el panel de botones relacionados con la accesibilidad
        cons.gridx = 0;
        cons.gridy = 0;
        cons.gridwidth = 2;
        cons.gridheight = 1;
        cons.weighty = 0.0;
        cons.weightx = 0.10;
        container.add(this.accessibilityButtonsPanel, cons);

        //se anade el panel de informacion
        cons.gridx = 2;
        cons.gridy = 0;
        cons.gridwidth = 6;
        cons.gridheight = isInputDialog ? 2 : 3;
        cons.weighty = isInputDialog ? 0.35 : 0.65;
        cons.weightx = 0.90;
        container.add(this.mainPanel, cons);

        //Se anade el icono
        cons.gridx = 0;
        cons.gridy = 1;
        cons.gridwidth = 2;
        cons.gridheight = 3;
        cons.weighty = 0.90;
        cons.weightx = 0.0;
        container.add(iconPanel, cons);

        //Se anade el panel de botones
        cons.gridx = 2;
        cons.gridy = 3;
        cons.gridwidth = 6;
        cons.gridheight = 1;
        cons.weighty = isInputDialog ? 0.65 : 0.35;
        cons.weightx = 0.0;
        container.add(this.buttonsPanel, cons);

        pack();
    }

    /**
     * Se asigna el icono a la etiqueta.
     */
    private void setIconLabel() {
        // Segun el tipo de mensaje se selecciona el icono
        ImageIcon icon = new ImageIcon(CustomDialog.class.getResource("/images/dnie.png")); //$NON-NLS-1$
        final Dimension dimensionInicial = new Dimension((int) 100f, (int)(100f / icon.getIconWidth() * icon.getIconHeight()));
        this.iconLabel.setOriginalIcon(icon);
        this.iconLabel.setOriginalDimension(dimensionInicial);
        icon = new ImageIcon(icon.getImage().getScaledInstance(dimensionInicial.width, dimensionInicial.height, Image.SCALE_SMOOTH));
        this.iconLabel.setIcon(icon);
    }

    /** Se crea el panel de botones de accesibilidad. */
    private void createAccessibilityButtonsPanel() {
        this.accessibilityButtonsPanel = new JPanel(new GridBagLayout());

        // Para el tooltip
        final JWindow tip = new JWindow();
        final JLabel tipText = new JLabel();

        // Panel que va a contener los botones de accesibilidad
        final JPanel panel = new JPanel(new GridBagLayout());

        // Restricciones para los botones
        final GridBagConstraints consButtons = new GridBagConstraints();
        consButtons.fill = GridBagConstraints.BOTH;
        consButtons.gridx = 0;
        consButtons.gridy = 0;
        consButtons.weightx = 1.0;
        consButtons.weighty = 1.0;
        consButtons.insets = new Insets(0, 0, 0, 0); // right padding

        // Restore button
        final JPanel restorePanel = new JPanel();
        final ImageIcon imageIconRestore = new ImageIcon(CustomDialog.class.getResource("/images/restore.png")); //$NON-NLS-1$
        this.restoreButton = new JButton(imageIconRestore);
        this.restoreButton.setMnemonic(KeyEvent.VK_R);
        this.restoreButton.setToolTipText(Messages.getString("Wizard.restaurar.description")); //$NON-NLS-1$
        this.restoreButton.getAccessibleContext().setAccessibleName(this.restoreButton.getToolTipText());

        this.restoreButton.addFocusListener(new FocusListener() {

            /** Evento que se produce cuando el componente pierde el foco. */
            @Override
            public void focusLost(final FocusEvent e) {
                Utils.showToolTip(false, tip, CustomDialog.this.getRestoreButton(), tipText);
            }

            /** Evento que se produce cuando el componente tiene el foco. */
            @Override
            public void focusGained(final FocusEvent e) {
                Utils.showToolTip(true, tip, CustomDialog.this.getRestoreButton(), tipText);
            }
        });
        final Dimension dimension = new Dimension(20, 20);
        this.restoreButton.setPreferredSize(dimension);
        this.restoreButton.addKeyListener(new KeyListener() {

			@Override public void keyTyped(final KeyEvent arg0) { /* No necesario */ }
			@Override public void keyReleased(final KeyEvent arg0) { /* No necesario */ }

			@Override
			public void keyPressed(final KeyEvent ke) {
				if (10 == ke.getKeyCode()) {
					getRestoreButton().doClick();
				}
			}
		});
        this.restoreButton.setName("restaurar"); //$NON-NLS-1$
        restorePanel.add(this.restoreButton);
        this.restoreButton.addActionListener(new ActionListener() {
            /** Accion del boton. */
            @Override
            public void actionPerformed(final ActionEvent e) {
                restaurarActionPerformed();
            }
        });
        Utils.remarcar(this.restoreButton);

        panel.add(restorePanel, consButtons);

        consButtons.gridx = 1;
        consButtons.insets = new Insets(0, 0, 0, 0); // right padding

        // Maximize button
        final JPanel maximizePanel = new JPanel();

        final ImageIcon imageIconMaximize = new ImageIcon(CustomDialog.class.getResource("/images/maximize.png")); //$NON-NLS-1$
        this.maximizeButton = new JButton(imageIconMaximize);
        this.maximizeButton.setMnemonic(KeyEvent.VK_M);
        this.maximizeButton.setToolTipText(Messages.getString("Wizard.maximizar.description")); //$NON-NLS-1$
        this.maximizeButton.getAccessibleContext().setAccessibleName(this.maximizeButton.getToolTipText());
        this.maximizeButton.addKeyListener(new KeyListener() {

			@Override public void keyTyped(final KeyEvent arg0) { /* No necesario */ }
			@Override public void keyReleased(final KeyEvent arg0) { /* No necesario */ }

			@Override
			public void keyPressed(final KeyEvent ke) {
				if (10 == ke.getKeyCode()) {
					getMaximizeButton().doClick();
				}
			}
		});

        this.maximizeButton.setName("maximizar"); //$NON-NLS-1$
        // Se asigna una dimension por defecto
        this.maximizeButton.setPreferredSize(dimension);

        Utils.remarcar(this.maximizeButton);
        maximizePanel.add(this.maximizeButton);

        this.maximizeButton.addFocusListener(new FocusListener() {
            /** Evento que se produce cuando el componente pierde el foco. */
            @Override
            public void focusLost(final FocusEvent e) {
                Utils.showToolTip(false, tip, CustomDialog.this.getMaximizeButton(), tipText);
            }

            /** Evento que se produce cuando el componente tiene el foco. */
            @Override
            public void focusGained(final FocusEvent e) {
                Utils.showToolTip(true, tip, CustomDialog.this.getMaximizeButton(), tipText);
            }
        });

        this.maximizeButton.addActionListener(new ActionListener() {
            /** Accion del boton. */
            @Override
            public void actionPerformed(final ActionEvent e) {
                maximizarActionPerformed();
            }
        });

        panel.add(maximizePanel, consButtons);

        // Se anade al panel general
        // Restricciones para el panel de botones
        final GridBagConstraints c = new GridBagConstraints();
        c.fill = GridBagConstraints.NONE;
        c.gridx = 0;
        c.gridy = 0;
        c.weightx = 1.0;
        c.weighty = 1.0;
        c.insets = new Insets(0, 0, 0, 0);
        c.anchor = GridBagConstraints.SOUTH;

        this.accessibilityButtonsPanel.add(panel, c);

        // Habilitado/Deshabilitado de botones restaurar/maximizar
        if (GeneralConfig.isMaximized()) {
            // Se deshabilita el boton de maximizado
            this.maximizeButton.setEnabled(false);
            // Se habilita el boton de restaurar
            this.restoreButton.setEnabled(true);
        }
        else {
            // Se habilita el boton de maximizado
            this.maximizeButton.setEnabled(true);
            // Se deshabilita el boton de restaurar
            this.restoreButton.setEnabled(false);
        }
    }

    /** Panel que contiene los botones principales de las alerta. */
    void createMainButtonsPanel() {
        this.buttonsPanel = new JPanel(new GridBagLayout());

        // Restricciones para el panel de botones
        final GridBagConstraints consButtons = new GridBagConstraints();
        consButtons.fill = GridBagConstraints.NONE;
        consButtons.gridx = 0;
        consButtons.gridy = 0;
        consButtons.insets = new Insets(0, 10, 0, 10); // right padding
        consButtons.anchor = GridBagConstraints.CENTER;

        // OK button
        final JPanel okPanel = new JPanel();
        CustomDialog.okButton = getButton(Messages.getString("PrincipalGUI.aceptar"), KeyEvent.VK_A); //$NON-NLS-1$
        okButton.addKeyListener(new KeyListener() {

			@Override public void keyTyped(final KeyEvent arg0) { /* No necesario */ }
			@Override public void keyReleased(final KeyEvent arg0) { /* No necesario */ }

			@Override
			public void keyPressed(final KeyEvent ke) {
				if (10 == ke.getKeyCode()) {
					getOkButton().doClick();
				}
			}
		});

        okPanel.add(CustomDialog.okButton);
        this.buttonsPanel.add(okPanel, consButtons);

        CustomDialog.okButton.addActionListener(this);

    }

    /** Muestra un dialogo con un mensaje que pide la interacion del usuario.
     * @param componentParent componente padre
     * @param modal modal
     * @param message mensaje a mostrar
     * @param title titulo del dialogo
     * @param typeOption opciones de interacion
     * @param typeMessage tipo de mensaje
     * @return respuesta del usuario. */
    public static int showConfirmDialog(final Component componentParent,
                                        final boolean modal,
                                        final String message,
                                        final String title,
                                        final int typeOption,
                                        final int typeMessage) {

        final CustomDialog customDialog = CustomDialog.getInstanceCustomDialog(componentParent, modal, message, title, typeMessage, false);
        CustomDialog.okButton.setEnabled(true);
        customDialog.getRootPane().setDefaultButton(null);

        // Restricciones
        final GridBagConstraints cons = new GridBagConstraints();
        cons.fill = GridBagConstraints.HORIZONTAL;
        cons.gridy = 0;
        cons.insets = new Insets(0, 0, 0, 10); // right padding

        // Se comprueba el tipo de dialogo
        if (typeOption == JOptionPane.YES_NO_OPTION) {
            // Boton Si
            CustomDialog.okButton.setText(Messages.getString("CustomDialog.confirmDialog.yes")); //$NON-NLS-1$
            CustomDialog.okButton.setMnemonic(KeyEvent.VK_S);
            // Boton no
            customDialog.noButton = customDialog.getButton(Messages.getString("CustomDialog.confirmDialog.no"), KeyEvent.VK_N); //$NON-NLS-1$
            customDialog.noButton.addKeyListener(new KeyListener() {

    			@Override public void keyTyped(final KeyEvent arg0) { /* No necesario */ }
    			@Override public void keyReleased(final KeyEvent arg0) { /* No necesario */ }

    			@Override
    			public void keyPressed(final KeyEvent ke) {
    				if (10 == ke.getKeyCode()) {
    					customDialog.getNoButton().doClick();
    				}
    			}
    		});
            final JPanel noPanel = new JPanel();
            noPanel.add(customDialog.noButton);
            customDialog.buttonsPanel.add(noPanel, cons);
            customDialog.noButton.addActionListener(customDialog);
        }
        else {
            throw new UnsupportedOperationException("Solo se soportan dialogos de tipo Si/No"); //$NON-NLS-1$
        }

        customDialog.infoLabel.setHorizontalAlignment(SwingConstants.CENTER); // Se centra el texto
        customDialog.pack();
        customDialog.setSize(customDialog.getInitialWidth() + 1, customDialog.getInitialHeight() + 1); // Hacemos un resize para forzar un repintado
        customDialog.setVisible(true);

        return customDialog.getAnswer();
    }

    /** Muestra un diálogo de solicitud de contraseña.
     * @param componentParent Componente padre para la modalidad
     * @param modal true si se desea que el diálogo sea modal,
     *              false en caso contrario.
     * @param beep true si se desean usar sonidos como ayuda al usuario,
     *             false en caso contrario.
     * @param message Mensaje a mostrar.
     * @param mnemonic Atajo de teclado.
     * @param title Título del diálogo.
     * @param typeMessage Tipo de mensaje
     * @return Contraseña introducida por el usuario */
    public static char[] showInputPasswordDialog(final Component componentParent,
                                                 final boolean modal,
                                                 final boolean beep,
                                                 final String message,
                                                 final int mnemonic,
                                                 final String title,
                                                 final int typeMessage) {
    	final CustomDialog customDialog = CustomDialog.getInstanceCustomDialog(
    			componentParent,
    			modal,
    			message,
    			title,
    			typeMessage,
    			true
    	);
        CustomDialog.okButton.setEnabled(false);
        customDialog.getRootPane().setDefaultButton(null);

        // Restricciones para el panel de datos
        final GridBagConstraints c = new GridBagConstraints();
        c.fill = GridBagConstraints.BOTH;
        c.gridx = 1;
        c.gridy = 1;
        c.weightx = 0.0;
        c.weighty = 0.5;
        c.gridwidth = 2;
        c.insets = new Insets(2, 5, 2, 10); // right padding

        // campo de password del dialogo
        customDialog.component = new JSecurePasswordLabel(16);
        customDialog.component.addKeyListener(new KeyListener() {

            @Override
            public void keyTyped(final KeyEvent arg0) { /* Vacio */}

            @Override
            public void keyReleased(final KeyEvent ke) {
            	//final char[] pwd = customDialog.getComponent().getPassword();
            	//final int length = pwd.length;
            	// Machacamos la copia por seguridad
            	//for (int i=0;i<length;i++) {
            	//	pwd[i] = '\0';
            	//}
            	final int length = customDialog.getComponent().getPasswordLength();
                //Control de los botones aceptar/cancelar
                if (length > 7 && length < 17) {
                    getOkButton().setEnabled(true);
                	if (10 == ke.getKeyCode()) {
    					getOkButton().doClick();
    				}
                }
                else {
                    getOkButton().setEnabled(false);
                }
            }

            @Override
            public void keyPressed(final KeyEvent arg0) { /* Vacio */}
        });
        customDialog.component.addAncestorListener(new RequestFocusListener());
        Utils.remarcar(customDialog.component);
        Utils.setContrastColor(customDialog.component);
        Utils.setFontBold(customDialog.component);
        customDialog.component.getAccessibleContext()
                              .setAccessibleName(message.replaceAll(Constants.HTML_SALTO_LINEA, "") + "  ALT + " + mnemonic + ". "); //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$
        // Se anade el campo de texto al panel de informacion general
        customDialog.mainPanel.add(customDialog.component, c);

        // Etiqueta principal
        // Se relaciona la etiqueta con el componente
        customDialog.infoLabel.setLabelFor(customDialog.component);
        // Se asigna un atajo
        customDialog.infoLabel.setDisplayedMnemonic(mnemonic);
        // Se muestra el atajo
        final String text = Utils.remarkMnemonic(customDialog.infoLabel.getText(), mnemonic);
        customDialog.infoLabel.setText(text);

        // Restricciones para el check
        c.insets = new Insets(0, 0, 0, 10); // right padding
        c.gridy = 2;

        // Se anade el check al panel de informacion general
        //customDialog.mainPanel.add(panelCheckShowPass, c);

        // Restricciones del panel de botones
        final GridBagConstraints cons = new GridBagConstraints();
        cons.insets = new Insets(0, 0, 0, 10); // right padding

        // Cancel button
        cancelButton = customDialog.getButton(cancellText, KeyEvent.VK_C);
        final JPanel cancelPanel = new JPanel();
        cancelPanel.add(cancelButton);
        customDialog.buttonsPanel.add(cancelPanel, cons);
        cancelButton.addActionListener(customDialog);
        cancelButton.addKeyListener(new KeyListener() {

			@Override public void keyTyped(final KeyEvent arg0) { /* No necesario */ }
			@Override public void keyReleased(final KeyEvent arg0) { /* No necesario */ }

			@Override
			public void keyPressed(final KeyEvent ke) {
				if (10 == ke.getKeyCode()) {
					getCancelButton().doClick();
				}
			}
		});

        customDialog.infoLabel.setHorizontalAlignment(SwingConstants.LEFT); // Se centra el texto
        customDialog.component.setVisible(true); // Se hace visible el campo de texto

        cancelButton.addActionListener(customDialog);

        customDialog.pack();
        customDialog.setSize(customDialog.getInitialWidth() + 1, customDialog.getInitialHeight() + 1); // Hacemos un resize para forzar un repintado
        customDialog.setVisible(true);

        // Control para saber si se ha pulsado el boton cancelar
        if (customDialog.getAnswer() == JOptionPane.YES_OPTION) {
        	final char[] finalPin = customDialog.getComponent().getPassword();

        	// Por precaucion borramos el PIN y dejamos sus componentes relacionados
        	// listos para ser descartados
        	customDialog.getComponent().setText(""); //$NON-NLS-1$
        	customDialog.getComponent().setText(null);
        	//customDialog.getComponent().setDocument(new PlainDocument());
        	customDialog.component = null;
        	customDialog.dispose();
        	System.runFinalization();
        	System.gc();

            return finalPin;
        }
        throw new CancelledOperationException("La insercion de contrasena ha sido cancelada por el usuario"); //$NON-NLS-1$
    }

    /** Metodo que crea un boton.
     * Si el boton corresponde al de cancelar, se le asigna la tecla esc.
     * @param text texto del boton
     * @param mnemonic atajo
     * @return boton */
    private JButton getButton(final String text, final int mnemonic) {
        final JButton button = new JButton(text);
        button.setMnemonic(mnemonic);
        Utils.remarcar(button);
        Utils.setContrastColor(button);
        Utils.setFontBold(button);
        // Se comprueba si el boton es el de cancelar
        if (text.equalsIgnoreCase(cancellText)) {
            // Se asigna la tecla escape a dicho boton
            final String cancelKey = "cancel"; //$NON-NLS-1$
            this.getRootPane().getInputMap(JComponent.WHEN_IN_FOCUSED_WINDOW).put(KeyStroke.getKeyStroke(KeyEvent.VK_ESCAPE, 0), cancelKey);
            this.getRootPane().getActionMap().put(cancelKey, new ButtonAbstractAction());
        }

        return button;
    }

    @Override
    public int getMinimumRelation() {
        return 7;
    }

    /** @return the answer */
    private int getAnswer() {
        return this.answer;
    }

    /** Cambia el tamaño de la ventana al tamaño máximo de pantalla menos el tamaño de la barra de tareas de windows */
    void maximizarActionPerformed() {
        setActualPositionX(this.getX());
        setActualPositionY(this.getY());
        setActualWidth(this.getWidth());
        setActualHeight(this.getHeight());

        // Se obtienen las dimensiones de maximizado
        final int maxWidth = this.getMaxWidth();
        final int maxHeight = this.getMaxHeight();

        // Se hace el resize
        this.setBounds(getInitialX(maxWidth), getInitialY(maxHeight), maxWidth, maxHeight);

        // Habilitado/Deshabilitado de botones restaurar/maximizar
        this.maximizeButton.setEnabled(false);
        this.restoreButton.setEnabled(true);
    }

    /** Restaura el tamaño de la ventana a la posicion anterior al maximizado */
    void restaurarActionPerformed() {
        // Dimensiones de restaurado
        int minWidth = this.getInitialWidth();
        int minHeight = this.getInitialHeight();
        // Se comprueba las opciones de accesibilidad activas
        if (GeneralConfig.isBigFontSize() || GeneralConfig.isFontBold() || isBigSizeDefault()) {
            minWidth = Constants.CUSTOMDIALOG_FONT_INITIAL_WIDTH;
            minHeight = Constants.CUSTOMDIALOG_FONT_INITIAL_HEIGHT;
        }
        // Se establece el tamano minimo
        setMinimumSize(new Dimension(minWidth, minHeight));

        // Se situa el dialogo
        if (getActualPositionX() != -1 && getActualPositionY() != -1 && getActualWidth() != -1 && getActualHeight() != -1) {
            this.setBounds(getActualPositionX(), getActualPositionY(), getActualWidth(), getActualHeight());
        }
        else {
            setBounds(getInitialX(minWidth), getInitialY(minHeight), minWidth, minHeight);
        }

        // Habilitado/Deshabilitado de botones restaurar/maximizar
        this.maximizeButton.setEnabled(true);
        this.restoreButton.setEnabled(false);
    }

    /** Metodo que devuelve una instancia de CustomDialog.
     * @param componentParent Componente padre
     * @param modal modal
     * @param message mensaje
     * @param title titulo del dialogo
     * @param typeMessage tipo de alerta.
     * @param isInputDialog indica sies una alerta de tipo input
     * @return instancia de CustomDialog. */
    static CustomDialog getInstanceCustomDialog(final Component componentParent,
                                                final boolean modal,
                                                final String message,
                                                final String title,
                                                final int typeMessage,
                                                final boolean isInputDialog) {
        CustomDialog customDialog = null;
        // Se chequea cual sera el componente padre.
        if (componentParent instanceof JDialog) {
            customDialog = new CustomDialog((JDialog) componentParent, modal, message, title, typeMessage, isInputDialog);
        }
        else if (componentParent instanceof JFrame) {
            customDialog = new CustomDialog((JFrame) componentParent, modal, message, title, typeMessage, isInputDialog);
        }
        else {
            customDialog = new CustomDialog(componentParent, modal, message, title, typeMessage, isInputDialog);
        }
        return customDialog;
    }

    /** Accion correspondiente a los botones de las alertas. */
    @Override
    public void actionPerformed(final ActionEvent e) {

        if (e.getSource().equals(CustomDialog.okButton)) {
            this.answer = JOptionPane.YES_OPTION;
        }
        else if (e.getSource().equals(this.noButton)) {
            this.answer = JOptionPane.NO_OPTION;
        }
        else {
            this.answer = JOptionPane.CANCEL_OPTION;
        }
        setVisible(false);
    }

    private static final class ButtonAbstractAction extends AbstractAction {
        /** UID. */
        private static final long serialVersionUID = 1L;

        ButtonAbstractAction() {
            super();
        }

        /** Indica que la accion es la de pulsar el boton cancelar. */
        @Override
        public void actionPerformed(final ActionEvent event) {
            CustomDialog.getCancelButton().doClick();
        }
    }

}


text:
package org.jetbrains.plugins.groovy.intentions.conversions.strings;

import javax.annotation.Nonnull;

import com.intellij.openapi.editor.Editor;
import com.intellij.openapi.project.Project;
import com.intellij.psi.PsiElement;
import com.intellij.util.IncorrectOperationException;
import org.jetbrains.plugins.groovy.intentions.base.Intention;
import org.jetbrains.plugins.groovy.intentions.base.PsiElementPredicate;
import org.jetbrains.plugins.groovy.lang.psi.GroovyPsiElementFactory;
import org.jetbrains.plugins.groovy.lang.psi.api.statements.expressions.GrExpression;
import org.jetbrains.plugins.groovy.lang.psi.api.statements.expressions.GrSafeCastExpression;
import org.jetbrains.plugins.groovy.lang.psi.api.statements.expressions.literals.GrLiteral;

/**
 * @author Max Medvedev
 */
public class GrConvertStringToCharIntention extends Intention {
  @Override
  protected void processIntention(@Nonnull PsiElement element, Project project, Editor editor) throws IncorrectOperationException {
    final GrExpression cast = GroovyPsiElementFactory.getInstance(project).createExpressionFromText("a as char");
    ((GrSafeCastExpression)cast).getOperand().replaceWithExpression((GrExpression)element, true);

    ((GrExpression)element).replaceWithExpression(cast, true);
  }

  @Nonnull
  @Override
  protected PsiElementPredicate getElementPredicate() {
    return new PsiElementPredicate() {
      @Override
      public boolean satisfiedBy(PsiElement element) {
        if (!(element instanceof GrLiteral)) return false;

        final Object value = ((GrLiteral)element).getValue();
        return value instanceof String && ((String)value).length() == 1;
      }
    };
  }
}

redpajama_set_name: RedPajamaGithub


text:
<LinearLayout
        xmlns:android="http://schemas.android.com/apk/res/android"
        android:orientation="vertical"
        android:background="@color/white"
        android:layout_width="fill_parent"
        android:layout_height="fill_parent" >

    <ScrollView
        android:layout_width="fill_parent"
        android:layout_height="fill_parent" android:fillViewport="true" android:layout_weight="1">

        <LinearLayout
            android:id="@+id/LinearLayout2"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:orientation="vertical" >
            <LinearLayout
                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                android:background="@color/lightgrey"
                android:orientation="vertical"
                android:padding="5dp" >

                <EditText
                    android:id="@+id/detail_item_edit"
                    android:layout_width="match_parent"
                    android:layout_height="48dip"
                    android:ems="10"
                    android:hint="@string/hint_detail_title"
                    android:imeOptions="actionNext"
                    android:singleLine="true">

                    <requestFocus />
                </EditText>
            </LinearLayout>

            <View
                android:layout_width="fill_parent"
                android:layout_height="1dip"
                android:background="@color/grey" />

            <LinearLayout
                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                android:orientation="vertical" >

                <LinearLayout
                    android:layout_width="match_parent"
                    android:layout_height="wrap_content"
                    android:background="@color/lightergrey"
                    android:padding="5dp" >

                    <TextView
                        android:id="@+id/textView1"
                        android:layout_width="0dip"
                        android:layout_height="fill_parent"
                        android:layout_weight="1"
                        android:gravity="center_vertical"
                        android:text="@string/label_detail_contacts" />

                    <Button
                        android:id="@+id/button_add_contact"
                        android:layout_width="wrap_content"
                        android:layout_height="wrap_content"
                        android:text="@string/label_add" />
                </LinearLayout>

                <View
                    android:layout_width="fill_parent"
                    android:layout_height="1dip"
                    android:background="@color/grey" />

                <de.rndm.todo.custom.ExpandableHeightGridView
                    android:id="@+id/list_contacts"
                    android:layout_width="wrap_content"
                    android:layout_height="wrap_content"
                    android:gravity="center"
                    android:horizontalSpacing="0dp"
                    android:isScrollContainer="false"
                    android:numColumns="2"
                    android:stretchMode="columnWidth"
                    android:verticalSpacing="0dp" >
                </de.rndm.todo.custom.ExpandableHeightGridView>

            </LinearLayout>

            <View
                android:layout_width="fill_parent"
                android:layout_height="1dip"
                android:background="@color/grey" />

            <LinearLayout
                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                android:background="@color/lightergrey"
                android:padding="5dp" >

                <TextView
                    android:id="@+id/label_planned"
                    android:layout_width="wrap_content"
                    android:layout_height="wrap_content"
                    android:layout_weight="0.48"
                    android:text="@string/label_detail_planned"
                    android:textSize="14sp" />

                <Button
                    android:id="@+id/detail_time_button"
                    android:layout_width="wrap_content"
                    android:layout_height="wrap_content"
                    android:layout_weight="0.48"
                    android:text="@string/button_detail_time" />

                <Button
                    android:id="@+id/detail_date_button"
                    android:layout_width="wrap_content"
                    android:layout_height="wrap_content"
                    android:layout_weight="0.48"
                    android:text="@string/button_detail_date" />
            </LinearLayout>

            <View
                android:layout_width="fill_parent"
                android:layout_height="1dip"
                android:background="@color/grey" />

            <EditText
                android:id="@+id/detail_description"
                android:layout_width="match_parent"
                android:layout_height="fill_parent"
                android:minHeight="150dp"
                android:layout_marginLeft="5dp"
                android:layout_marginRight="5dp"
                android:layout_marginTop="5dp"
                android:layout_weight="1"
                android:gravity="top"
                android:hint="@string/hint_detail_description"
                android:inputType="textMultiLine"
                android:padding="5dp" />

            <View
                android:layout_width="fill_parent"
                android:layout_height="1dip"
                android:background="@color/grey" />

            <CheckBox
                android:id="@+id/detail_active"
                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                android:background="@color/lightergrey"
                android:gravity="center"
                android:text="@string/checkbox_detail_done" />

            <View
                android:layout_width="fill_parent"
                android:layout_height="1dip"
                android:background="@color/grey" />
        </LinearLayout>

    </ScrollView>
    <LinearLayout
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:background="@color/lightgrey"
            android:layout_weight="0">

        <Button
                android:id="@+id/detail_submit"
                android:layout_width="match_parent"
                android:layout_height="fill_parent"
                android:layout_weight="0.6"
                android:text="@string/button_detail_save" />

        <ImageButton
                android:id="@+id/detail_revert"
                android:layout_width="wrap_content"
                android:layout_height="fill_parent"
                android:src="@android:drawable/ic_menu_revert" />

        <ImageButton
                android:id="@+id/detail_delete"
                android:layout_width="wrap_content"
                android:layout_height="fill_parent"
                android:src="@android:drawable/ic_menu_delete" />
    </LinearLayout>
</LinearLayout>


text:
const DrawCard = require('../../drawcard.js');
const AbilityDsl = require('../../abilitydsl');

class LicensedQuarter extends DrawCard {
    setupCardAbilities() {
        this.reaction({
            title: 'Discard the top card of your opponents conflict deck',
            when: {
                afterConflict: (event, context) => event.conflict.winner === context.player
            },
            effect: 'discard the top card of {1}\'s conflict deck',
            effectArgs: context => context.player.opponent,
            gameAction: AbilityDsl.actions.discardCard(context => ({
                target: context.player.opponent && context.player.opponent.conflictDeck.first()
            })),
            limit: AbilityDsl.limit.unlimitedPerConflict()
        });
    }
}

LicensedQuarter.id = 'licensed-quarter';

module.exports = LicensedQuarter;


text:
package uk.co.senab.photup.tasks;

import com.facebook.android.FacebookError;

import org.json.JSONException;

import android.content.Context;
import android.os.AsyncTask;

import java.lang.ref.WeakReference;
import java.util.List;

import uk.co.senab.photup.facebook.FacebookRequester;
import uk.co.senab.photup.listeners.FacebookErrorListener;
import uk.co.senab.photup.model.Account;

public class AccountsAsyncTask extends AsyncTask<Void, Void, List<Account>> {

    public static interface AccountsResultListener extends FacebookErrorListener {

        public void onAccountsLoaded(List<Account> friends);
    }

    private final WeakReference<Context> mContext;
    private final WeakReference<AccountsResultListener> mListener;

    public AccountsAsyncTask(Context context, AccountsResultListener listener) {
        mContext = new WeakReference<Context>(context);
        mListener = new WeakReference<AccountsResultListener>(listener);
    }

    @Override
    protected List<Account> doInBackground(Void... params) {
        Context context = mContext.get();
        if (null != context) {
            Account account = Account.getAccountFromSession(context);
            if (null != account) {
                try {
                    FacebookRequester requester = new FacebookRequester(account);
                    return requester.getAccounts();
                } catch (FacebookError e) {
                    AccountsResultListener listener = mListener.get();
                    if (null != listener) {
                        listener.onFacebookError(e);
                    } else {
                        e.printStackTrace();
                    }
                } catch (JSONException e) {
                    e.printStackTrace();
                }
            }
        }
        return null;
    }

    @Override
    protected void onPostExecute(List<Account> result) {
        super.onPostExecute(result);

        Context context = mContext.get();
        if (null != context) {
            if (null != result) {
                Account.saveToDatabase(context, result);
            } else {
                result = Account.getFromDatabase(context);
            }
        }

        AccountsResultListener listener = mListener.get();
        if (null != result && null != listener) {
            listener.onAccountsLoaded(result);
        }
    }

}


text:
package org.javarosa.services.transport;

import org.javarosa.core.services.Logger;
import org.javarosa.services.transport.impl.TransportException;
import org.javarosa.services.transport.impl.TransportMessageStatus;
import org.javarosa.services.transport.impl.TransportMessageStore;
import org.javarosa.services.transport.senders.SenderThread;
import org.javarosa.services.transport.senders.SimpleSenderThread;
import org.javarosa.services.transport.senders.TransporterSharingSender;

import java.io.IOException;
import java.util.Date;
import java.util.Vector;

/**
 * The TransportService is generic. Its capabilities are extended by defining
 * new kinds of Transport.
 *
 * To define a new kind of transport, it is necessary to implement two
 * interfaces:
 *

 *
TransportMessage - a new kind of message
 *
Transporter - an object with the ability to send one of the new messages
 *

 *
 * A TransportMessage must be able to create an appropriate Transporter (via the
 * createTransporter() method) whose constructor takes the message
 * itself.
 *
 * The result is an intuitive programmer interface which involves the following
 * steps alone:
 *

 *
create a Message
 *
ask the TransportService to send the Message
 *

 *
 * For example:
 *
 *
 * TransportMessage m = new SomeTransportMessage()
 * TransportService.send(m);
 *
 *
 */
public class TransportService {

    /**
     *
     * The TransportService has a cache, in which all messages to be sent are
     * persisted immediately
     *
     */
    private static TransportMessageStore T_CACHE;

    private static TransporterSharingSender SENDER;

    private static final String CACHE_LOCK="CACHE_LOCK";

    /**
     * The maximum number of forms which can fail to send in a row before the submission
     * process is cancelled
     */
    private static final int MAX_FAILURES = 5;

    public static final int PAYLOAD_SIZE_REPORTING_THRESHOLD = 15000;

    private static TransportMessageStore CACHE() {
        synchronized(CACHE_LOCK) {
            if(T_CACHE == null) {
                T_CACHE = new TransportMessageStore();
            }
            return T_CACHE;
        }
    }

    public static synchronized void init() {
        CACHE();
        SENDER  = new TransporterSharingSender();
    }

    public static void reinit() {
        synchronized(CACHE_LOCK) {
            T_CACHE = new TransportMessageStore();
        }
    }

    /**
     *
     * Send a message in a thread, using the default number of tries and the
     * default pause between tries
     *
     * Sending a message happens like this:
     *
     *

     *
The message creates an appropriate Transporter (which contains the
     * message)
     *
The message is given a SenderDeadline, equal to the maximum time it
     * can spend in a SenderThread
     *
The message is persisted in the cache
     *
A SenderThread is started, which tries and retries the Transporter's
     * send method until either the specified number of tries are exhausted, or
     * the message is successfully sent
     *
The SenderThread is returned
     *

     *
     * @param message
     * @return Thread used to try to send message
     * @throws IOException
     */
    public static SenderThread send(TransportMessage message)
            throws TransportException {
        return send(message, SenderThread.DEFAULT_TRIES,
                SenderThread.DEFAULT_DELAY);
    }

    /**
     *
     * Send a message, specifying a number of tries and the pause between the
     * tries (in seconds)
     *
     *
     * @param message
     * @param tries
     * @param delay
     * @return
     * @throws IOException
     */
    public static SenderThread send(TransportMessage message, int tries, int delay) throws TransportException {
        boolean sendLater = (tries == 0);

        // if the message should be stored and never lost
        if (message.isCacheable()) {

            // record the deadline for the sending thread phase in the message
            message.setSendingThreadDeadline(getSendingThreadDeadline(tries, delay));

            synchronized (CACHE()) {
                // persist the message
                CACHE().cache(message);

                if (sendLater) {
                    Logger.log("send", "msg cached " + message.getTag() + "; " + CACHE().getCachedMessagesCount() + " in queue");
                }
            }
        } else {
            message.setStatus(TransportMessageStatus.QUEUED);
        }

        if (sendLater) {
            return null;
        } else {
            // create a sender thread
            SenderThread thread = new SimpleSenderThread(message, CACHE(), tries, delay);

            // start the sender thread
            Logger.log("send", "start " + message.getTag());
            thread.start();

            // return the sender thread in case
            // an application wants to permit the user to cancel it
            return thread;
        }
    }

    /**
     * @param message
     * @return
     * @throws TransportException
     */
    public static TransportMessage sendBlocking(TransportMessage message)
            throws TransportException {

        // if the message should be saved in case of sending failure
        if (message.isCacheable()) {
            // persist the message
            CACHE().cache(message);
        }

        message.send();

        // if the message had been cached..
        if (message.isCacheable()) {

            if (message.getStatus() == TransportMessageStatus.SENT) {
                // if it was sent successfully, then remove it from cache
                CACHE().decache(message);
            } else {
                // otherwise, set the status to cached
                message.setStatus(TransportMessageStatus.CACHED);
                CACHE().updateMessage(message);
            }
        }
        return message;
    }

    /**
     *
     * Any messages which aren't successfully sent in SendingThreads are then
     * "Cached".
     *
     * Applications can activate new attempts to send the CachedMessages via
     * this sendCached method
     *
     *
     */
    public static void sendCached(TransportListener listener) throws TransportException {
        if(SENDER == null) {
            //This is very bad, and the service should have been initialized
            SENDER  = new TransporterSharingSender();
        }

        //We get into a lot of trouble with synchronicity if we just let all kinds of
        //senders start going at once, so we'll just use the one and queue up
        //sendCached attempts.
        synchronized(SENDER) {
            // get all the cached messages
            Vector messages = getCachedMessages();

            Logger.log("send-all", "start; " + messages.size() + " msgs");

            if (messages.size() > 0) {
                try {
                    SENDER.init(messages, CACHE(), listener, MAX_FAILURES);
                    SENDER.send();
                } finally {
                    //Make _damn_ sure we remove the listener hook. Otherwise memory can't be cleared up
                    SENDER.uninit();
                }
            }
        }
    }

    /**
     *
     * Compute the lifetime of a sending thread with the given parameters and
     * returns the time in the future at which this duration would have elapsed
     *
     * @param tries
     * @param delay
     * @return
     */
    private static long getSendingThreadDeadline(int tries, int delay) {
        long duration = (new Long(tries).longValue()
                * new Long(delay).longValue() * 1000);
        long now = new Date().getTime();
        return (now + duration);
    }

    /**
     * @return
     */
    public static Vector getCachedMessages() {
        return CACHE().getCachedMessages();
    }

    /**
     * @return
     */
    public static int getCachedMessagesSize() {
        return CACHE().getCachedMessagesCount();
    }

    /**
     *
     * A TransportMessage is assigned a uniqueId when persisted. Applications
     * can access the message again via this method
     *
     * @param id
     *            The unique id assigned to the TransportMessage when it was
     *            queued for sending
     * @return The TransportMessage identified by the id (or null if no such
     *         message was found)
     */
    public static TransportMessage retrieve(String id) {
        return CACHE().findMessage(id);
    }

    public static void halt() {
        if(SENDER != null) {
            SENDER.halt();
        }
    }
}


text:
using System.Reflection;

namespace Swisstalk.Foundation.Metadata.Reflection.Blueprints.Builder.Extraction
{
    public interface IMemberExtractionPredicate
    {
        bool IsEligible(MemberInfo memberInfo);
    }
}


text:
package foam.core;

import java.util.Comparator;

public interface FObject
  extends FCloneable, Comparable
{

  public Model model();

  public StringBuilder append(StringBuilder sb);

  public StringBuilder appendToJSON(StringBuilder b);

  public String toJSON();

  public AbstractFObject set(Property p, Object value);

}


text:
package org.zaproxy.zap.extension.pscanrules;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileReader;
import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import net.htmlparser.jericho.Element;
import net.htmlparser.jericho.HTMLElementName;
import net.htmlparser.jericho.Source;
import net.htmlparser.jericho.StartTagType;
import net.htmlparser.jericho.Tag;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.parosproxy.paros.Constant;
import org.parosproxy.paros.core.scanner.Alert;
import org.parosproxy.paros.network.HttpMessage;
import org.zaproxy.zap.extension.pscan.PassiveScanThread;
import org.zaproxy.zap.extension.pscan.PluginPassiveScanner;

public class InformationDisclosureSuspiciousCommentsScanRule extends PluginPassiveScanner {

    private static final String MESSAGE_PREFIX =
            "pscanrules.informationdisclosuresuspiciouscomments.";
    private static final int PLUGIN_ID = 10027;

    private static final int MAX_ELEMENT_CHRS_TO_REPORT = 128;

    public static final String suspiciousCommentsListDir = "xml";
    public static final String suspiciousCommentsListFile = "suspicious-comments.txt";
    private static final Logger logger =
            LogManager.getLogger(InformationDisclosureSuspiciousCommentsScanRule.class);

    private static List<Pattern> patterns = null;

    @Override
    public void scanHttpResponseReceive(HttpMessage msg, int id, Source source) {

        List<Pattern> patterns = getPatterns();
        Map<String, List<AlertSummary>> alertMap = new HashMap<>();

        if (msg.getResponseBody().length() > 0 && msg.getResponseHeader().isText()) {

            if (msg.getResponseHeader().isJavaScript()) {
                // Just treat as text
                String[] lines = msg.getResponseBody().toString().split("\n");
                for (String line : lines) {
                    for (Pattern pattern : patterns) {
                        Matcher m = pattern.matcher(line);
                        if (m.find()) {
                            recordAlertSummary(
                                    alertMap,
                                    new AlertSummary(
                                            pattern.toString(),
                                            line,
                                            Alert.CONFIDENCE_LOW,
                                            m.group()));
                            break; // Only need to record this line once
                        }
                    }
                }
            } else {
                // Can use the parser

                // Check the comments
                List<Tag> tags = source.getAllTags(StartTagType.COMMENT);
                for (Tag tag : tags) {
                    String tagStr = tag.toString();
                    for (Pattern pattern : patterns) {
                        Matcher m = pattern.matcher(tagStr);
                        if (m.find()) {
                            recordAlertSummary(
                                    alertMap,
                                    new AlertSummary(
                                            pattern.toString(),
                                            tagStr,
                                            Alert.CONFIDENCE_MEDIUM,
                                            m.group()));
                            break; // Only need to record this comment once
                        }
                    }
                }
                // Check the scripts
                Element el;
                int offset = 0;
                while ((el = source.getNextElement(offset, HTMLElementName.SCRIPT)) != null) {
                    for (Pattern pattern : patterns) {
                        String elStr = el.toString();
                        Matcher m = pattern.matcher(elStr);
                        if (m.find()) {
                            recordAlertSummary(
                                    alertMap,
                                    new AlertSummary(
                                            pattern.toString(),
                                            elStr,
                                            Alert.CONFIDENCE_LOW,
                                            m.group()));
                            break; // Only need to record this script once
                        }
                    }
                    offset = el.getEnd();
                }
            }
        }

        // Only raise one alert for each pattern detected, giving a total count if > 1 instance
        for (Entry<String, List<AlertSummary>> entry : alertMap.entrySet()) {
            String other;
            AlertSummary firstSummary = entry.getValue().get(0);
            if (entry.getValue().size() == 1) {
                other =
                        Constant.messages.getString(
                                MESSAGE_PREFIX + "otherinfo",
                                firstSummary.getPattern(),
                                truncateString(firstSummary.getDetail()));
            } else {
                other =
                        Constant.messages.getString(
                                MESSAGE_PREFIX + "otherinfo2",
                                firstSummary.getPattern(),
                                truncateString(firstSummary.getDetail()),
                                entry.getValue().size());
            }
            this.raiseAlert(
                    msg, id, other, firstSummary.getConfidence(), firstSummary.getEvidence());
        }
    }

    private static void recordAlertSummary(
            Map<String, List<AlertSummary>> alertMap, AlertSummary summary) {
        alertMap.computeIfAbsent(summary.getPattern(), k -> new ArrayList<>()).add(summary);
    }

    private String truncateString(String str) {
        if (str.length() > MAX_ELEMENT_CHRS_TO_REPORT) {
            return str.substring(0, MAX_ELEMENT_CHRS_TO_REPORT);
        }
        return str;
    }

    private void raiseAlert(
            HttpMessage msg, int id, String detail, int confidence, String evidence) {
        newAlert()
                .setRisk(Alert.RISK_INFO)
                .setConfidence(confidence)
                .setDescription(getDescription())
                .setOtherInfo(detail)
                .setSolution(getSolution())
                .setCweId(200) // CWE Id 200 - Information Exposure
                .setWascId(13) // WASC Id 13 - Info leakage
                .setEvidence(evidence)
                .raise();
    }

    private static List<Pattern> getPatterns() {
        if (patterns == null) {
            patterns = new ArrayList<>();

            try {
                File f =
                        new File(
                                Constant.getZapHome()
                                        + File.separator
                                        + suspiciousCommentsListDir
                                        + File.separator
                                        + suspiciousCommentsListFile);
                if (!f.exists()) {
                    throw new IOException("Couldn't find resource: " + f.getAbsolutePath());
                }
                try (BufferedReader reader = new BufferedReader(new FileReader(f))) {
                    String line = null;
                    while ((line = reader.readLine()) != null) {
                        line = line.trim();
                        if (!line.startsWith("#") && line.length() > 0) {
                            patterns.add(
                                    Pattern.compile(
                                            "\\b" + line + "\\b", Pattern.CASE_INSENSITIVE));
                        }
                    }
                }
            } catch (IOException e) {
                logger.error(
                        "Error on opening/reading suspicious comments file: {}{}{}{} Error: {}",
                        File.separator,
                        suspiciousCommentsListDir,
                        File.separator,
                        suspiciousCommentsListFile,
                        e.getMessage());
            }
        }
        return patterns;
    }

    @Override
    public void setParent(PassiveScanThread parent) {
        // Nothing to do.
    }

    @Override
    public String getName() {
        return Constant.messages.getString(MESSAGE_PREFIX + "name");
    }

    private String getSolution() {
        return Constant.messages.getString(MESSAGE_PREFIX + "soln");
    }

    private String getDescription() {
        return Constant.messages.getString(MESSAGE_PREFIX + "desc");
    }

    @Override
    public int getPluginId() {
        return PLUGIN_ID;
    }

    private static class AlertSummary {
        private final String pattern;
        private final String detail;
        private final int confidence;
        private final String evidence;

        public AlertSummary(String pattern, String detail, int confidence, String evidence) {
            super();
            this.pattern = pattern;
            this.detail = detail;
            this.confidence = confidence;
            this.evidence = evidence;
        }

        public String getPattern() {
            return pattern;
        }

        public String getDetail() {
            return detail;
        }

        public int getConfidence() {
            return confidence;
        }

        public String getEvidence() {
            return evidence;
        }
    }
}


text:
@class PXBackground, PXCanvas, PXCrosshair, PXGrid;

@interface PXCanvasView : NSView
{
  @private
	PXCrosshair *crosshair;
	NSAffineTransform *transform;

	NSBezierPath *cachedMarqueePath;
	NSColor *antsPattern;
	NSTimer *marqueeAnimationTimer;
	NSPoint marqueePatternOffset;
	BOOL drawsSelectionMarquee;

	NSPoint centeredPoint;
	BOOL shouldDrawMainBackground;
	BOOL shouldDrawGrid;

	BOOL drawsToolBeziers;
	BOOL acceptsFirstMouse;

	NSTrackingRectTag trackingRect;

	NSPoint lastMousePosition;
	BOOL _usesToolCursors, _updatesInfoBar;

	BOOL erasing;
}

@property (nonatomic, weak) PXCanvas *canvas;
@property (nonatomic, assign) int zoomPercentage;

@property (nonatomic, assign) BOOL usesToolCursors;
@property (nonatomic, assign) BOOL updatesInfoBar;

@property (nonatomic, weak) id delegate;

- (void)setCrosshair:aCrosshair;
- (PXCrosshair *)crosshair;
- (id) initWithFrame:(NSRect)rect;

- (NSPoint)convertFromCanvasToViewPoint:(NSPoint)point;
- (NSRect)convertFromCanvasToViewRect:(NSRect)rect;
- (NSPoint)convertFromViewToCanvasPoint:(NSPoint)point;
- (NSPoint)convertFromViewToPartialCanvasPoint:(NSPoint)point;
- (NSPoint)convertFromWindowToCanvasPoint:(NSPoint)location;

- (void)updateMousePosition:(NSPoint)locationInWindow dragging:(BOOL)dragging;

- (void)setShouldDrawSelectionMarquee:(BOOL)drawsSelectionMarquee;
- (void)setNeedsDisplayInCanvasRect:(NSRect)rect;
- (void)sizeToCanvas;
- (void)centerOn:(NSPoint)aPoint;
- (NSAffineTransform *)setupTransform;
- (NSAffineTransform *)setupScaleTransform;
- (NSAffineTransform *)transform;

- (void)panByX:(float)x y:(float)y;

- (void)drawSelectionMarqueeWithRect:(NSRect)rect offset:(NSPoint)off;
- (void)scrollUpBy:(int)amount;
- (void)scrollRightBy:(int)amount;
- (void)scrollDownBy:(int)amount;
- (void)scrollLeftBy:(int)amount;

- (void)setShouldDrawMainBackground:(BOOL)newShouldDraw;
- (void)setShouldDrawGrid:(BOOL)newShouldDraw;
- (PXGrid *)grid;
- (NSRect)convertFromViewToCanvasRect:(NSRect)viewRect;

- (void)setAcceptsFirstMouse:(BOOL)accepts;
- (void)setShouldDrawToolBeziers:(BOOL)newShouldDraw;

- (void)updateCrosshairs:(NSPoint)newLocation;
- (void)updateInfoBarWithMousePosition:(NSPoint)point dragging:(BOOL)dragging;

- (PXBackground *)mainBackground;
- (PXBackground *)alternateBackground;

@end

void PXDebugRect(NSRect r, float alpha);

@interface NSObject (PXCanvasViewDelegate)

- (void)mouseDown:(NSEvent *)event;
- (void)mouseUp:(NSEvent *)event;
- (void)mouseDragged:(NSEvent *)event;
- (void)mouseMoved:(NSEvent *)event;
- (void)eraserDown:(NSEvent *)event;
- (void)eraserUp:(NSEvent *)event;
- (void)eraserDragged:(NSEvent *)event;
- (void)eraserMoved:(NSEvent *)event;

@end


text:
using System;
using System.Text;
using Bars2Db.Mapping;

namespace Bars2Db.DataProvider.PostgreSQL
{
    public class PostgreSQLMappingSchema : MappingSchema
    {
        public PostgreSQLMappingSchema() : this(ProviderName.PostgreSQL)
        {
        }

        protected PostgreSQLMappingSchema(string configuration) : base(configuration)
        {
            ColumnComparisonOption = StringComparison.OrdinalIgnoreCase;

            SetDataType(typeof(string), DataType.Undefined);

            SetValueToSqlConverter(typeof(bool), (sb, dt, v) => sb.Append(v));

            SetValueToSqlConverter(typeof(string), (sb, dt, v) => ConvertStringToSql(sb, v.ToString()));
            SetValueToSqlConverter(typeof(char), (sb, dt, v) => ConvertCharToSql(sb, (char) v));
        }

        private static void AppendConversion(StringBuilder stringBuilder, int value)
        {
            stringBuilder
                .Append("chr(")
                .Append(value)
                .Append(")")
                ;
        }

        private static void ConvertStringToSql(StringBuilder stringBuilder, string value)
        {
            DataTools.ConvertStringToSql(stringBuilder, "||", "'", AppendConversion, value);
        }

        private static void ConvertCharToSql(StringBuilder stringBuilder, char value)
        {
            DataTools.ConvertCharToSql(stringBuilder, "'", AppendConversion, value);
        }
    }
}


text:
package alluxio.grpc;

public interface CancelPOptionsOrBuilder extends
    // @@protoc_insertion_point(interface_extends:alluxio.grpc.job.CancelPOptions)
    com.google.protobuf.MessageOrBuilder {
}


text:
package de.learnlib.nfa;

import net.automatalib.automata.fsa.NFA;
import de.learnlib.api.LearningAlgorithm;

public interface NFALearner<I> extends LearningAlgorithm<NFA<?,I>, I, Boolean> {

}


text:
package org.apache.camel.component.spring.ws.springboot;

import javax.annotation.Generated;
import org.springframework.boot.context.properties.ConfigurationProperties;

/**
 * The spring-ws component is used for SOAP WebServices using Spring
 * WebServices.
 *
 * Generated by camel-package-maven-plugin - do not edit this file!
 */
@Generated("org.apache.camel.maven.packaging.SpringBootAutoConfigurationMojo")
@ConfigurationProperties(prefix = "camel.component.spring-ws")
public class SpringWebserviceComponentConfiguration {

    /**
     * Enable usage of global SSL context parameters.
     */
    private Boolean useGlobalSslContextParameters = false;
    /**
     * Whether the component should resolve property placeholders on itself when
     * starting. Only properties which are of String type can use property
     * placeholders.
     */
    private Boolean resolvePropertyPlaceholders = true;

    public Boolean getUseGlobalSslContextParameters() {
        return useGlobalSslContextParameters;
    }

    public void setUseGlobalSslContextParameters(
            Boolean useGlobalSslContextParameters) {
        this.useGlobalSslContextParameters = useGlobalSslContextParameters;
    }

    public Boolean getResolvePropertyPlaceholders() {
        return resolvePropertyPlaceholders;
    }

    public void setResolvePropertyPlaceholders(
            Boolean resolvePropertyPlaceholders) {
        this.resolvePropertyPlaceholders = resolvePropertyPlaceholders;
    }
}


text:
const chalk = require('chalk');
const prettyFormat = require('pretty-format');
const {
  AsymmetricMatcher,
  ReactElement,
  HTMLElement,
  Immutable,
} = require('pretty-format').plugins;

const PLUGINS = [AsymmetricMatcher, ReactElement, HTMLElement].concat(
  Immutable,
);

export type ValueType =
  | 'array'
  | 'boolean'
  | 'function'
  | 'null'
  | 'number'
  | 'object'
  | 'regexp'
  | 'map'
  | 'set'
  | 'string'
  | 'symbol'
  | 'undefined';

const EXPECTED_COLOR = chalk.green;
const EXPECTED_BG = chalk.bgGreen;
const RECEIVED_COLOR = chalk.red;
const RECEIVED_BG = chalk.bgRed;

const NUMBERS = [
  'zero',
  'one',
  'two',
  'three',
  'four',
  'five',
  'six',
  'seven',
  'eight',
  'nine',
  'ten',
  'eleven',
  'twelve',
  'thirteen',
];

// get the type of a value with handling the edge cases like `typeof []`
// and `typeof null`
const getType = (value: any): ValueType => {
  if (typeof value === 'undefined') {
    return 'undefined';
  } else if (value === null) {
    return 'null';
  } else if (Array.isArray(value)) {
    return 'array';
  } else if (typeof value === 'boolean') {
    return 'boolean';
  } else if (typeof value === 'function') {
    return 'function';
  } else if (typeof value === 'number') {
    return 'number';
  } else if (typeof value === 'string') {
    return 'string';
  } else if (typeof value === 'object') {
    if (value.constructor === RegExp) {
      return 'regexp';
    } else if (value.constructor === Map) {
      return 'map';
    } else if (value.constructor === Set) {
      return 'set';
    }
    return 'object';
    // $FlowFixMe https://github.com/facebook/flow/issues/1015
  } else if (typeof value === 'symbol') {
    return 'symbol';
  }

  throw new Error(`value of unknown type: ${value}`);
};

const stringify = (object: any, maxDepth?: number = 10): string => {
  const MAX_LENGTH = 10000;
  let result;

  try {
    result = prettyFormat(object, {
      maxDepth,
      min: true,
      plugins: PLUGINS,
    });
  } catch (e) {
    result = prettyFormat(object, {
      callToJSON: false,
      maxDepth,
      min: true,
      plugins: PLUGINS,
    });
  }

  return result.length >= MAX_LENGTH && maxDepth > 1
    ? stringify(object, Math.floor(maxDepth / 2))
    : result;
};

const highlightTrailingWhitespace = (text: string, bgColor: Function): string =>
  text.replace(/\s+$/gm, bgColor('$&'));

const printReceived = (object: any) =>
  highlightTrailingWhitespace(RECEIVED_COLOR(stringify(object)), RECEIVED_BG);
const printExpected = (value: any) =>
  highlightTrailingWhitespace(EXPECTED_COLOR(stringify(value)), EXPECTED_BG);

const printWithType = (
  name: string,
  received: any,
  print: (value: any) => string,
) => {
  const type = getType(received);
  return (
    name +
    ':' +
    (type !== 'null' && type !== 'undefined' ? '\n  ' + type + ': ' : ' ') +
    print(received)
  );
};

const ensureNoExpected = (expected: any, matcherName: string) => {
  matcherName || (matcherName = 'This');
  if (typeof expected !== 'undefined') {
    throw new Error(
      matcherHint('[.not]' + matcherName, undefined, '') +
        '\n\n' +
        'Matcher does not accept any arguments.\n' +
        printWithType('Got', expected, printExpected),
    );
  }
};

const ensureActualIsNumber = (actual: any, matcherName: string) => {
  matcherName || (matcherName = 'This matcher');
  if (typeof actual !== 'number') {
    throw new Error(
      matcherHint('[.not]' + matcherName) +
        '\n\n' +
        `Received value must be a number.\n` +
        printWithType('Received', actual, printReceived),
    );
  }
};

const ensureExpectedIsNumber = (expected: any, matcherName: string) => {
  matcherName || (matcherName = 'This matcher');
  if (typeof expected !== 'number') {
    throw new Error(
      matcherHint('[.not]' + matcherName) +
        '\n\n' +
        `Expected value must be a number.\n` +
        printWithType('Got', expected, printExpected),
    );
  }
};

const ensureNumbers = (actual: any, expected: any, matcherName: string) => {
  ensureActualIsNumber(actual, matcherName);
  ensureExpectedIsNumber(expected, matcherName);
};

const pluralize = (word: string, count: number) =>
  (NUMBERS[count] || count) + ' ' + word + (count === 1 ? '' : 's');

const matcherHint = (
  matcherName: string,
  received: string = 'received',
  expected: string = 'expected',
  options: ?{
    secondArgument?: ?string,
    isDirectExpectCall?: boolean,
  },
) => {
  const secondArgument = options && options.secondArgument;
  const isDirectExpectCall = options && options.isDirectExpectCall;
  return (
    chalk.dim('expect' + (isDirectExpectCall ? '' : '(')) +
    RECEIVED_COLOR(received) +
    chalk.dim((isDirectExpectCall ? '' : ')') + matcherName + '(') +
    EXPECTED_COLOR(expected) +
    (secondArgument ? `, ${EXPECTED_COLOR(secondArgument)}` : '') +
    chalk.dim(')')
  );
};

module.exports = {
  EXPECTED_BG,
  EXPECTED_COLOR,
  RECEIVED_BG,
  RECEIVED_COLOR,
  ensureActualIsNumber,
  ensureExpectedIsNumber,
  ensureNoExpected,
  ensureNumbers,
  getType,
  highlightTrailingWhitespace,
  matcherHint,
  pluralize,
  printExpected,
  printReceived,
  printWithType,
  stringify,
};


text:
jotzer.factory('BoardsServices', ['$http', 'ApiConstants', function ($http, ApiConstants) {

    var baseUrl = ApiConstants.baseUrl;

    var BoardsServices = {

        //currently selected board's index;
        selectedBoardIndex: 0,

        //all user's boards;
        boards: [],

        //get selected board's id;
        getSelectedBoardIndex: function () {
            return BoardsServices.selectedBoardIndex;
        },

        //get selected board index by boards id;
        getBoardIndexByBoardId: function (boardId) {
            var index = '';

            angular.forEach(BoardsServices.boards, function (board, key) {
                if (board.id == boardId) {
                    index = key;
                }
            });
            return index;
        },

        //set selected board by ID;
        setSelectedBoardIndexByBoardId: function (boardId) {
            BoardsServices.selectedBoardIndex = BoardsServices.getBoardIndexByBoardId(boardId);
        },

        returnBoards: function () {
            return BoardsServices.boards;
        },

        //get all user boards;
        getBoards: function () {
            return $http.get(baseUrl + 'boards').success(function (boards) {
                BoardsServices.boards = boards;

                angular.forEach(BoardsServices.boards, function (board, key) {
                    board.editable = false;
                });

            });
        },

        //get board's cards;
        getBoardsDecks: function (boardId) {
             return $http.get(baseUrl + 'boards/' + boardId + '/decks').then(function (decks) {
                 BoardsServices.decks = decks.data;
                 BoardsServices.setSelectedBoardIndexByBoardId(boardId);
             });
        },

        //get decks;
        getDecks: function () {
            return BoardsServices.decks;
        },

        //create a new board;
        createBoard: function (boardName) {
            return $http.get(baseUrl + 'boards/' + boardName + '/new').success(function (boardId) {
                BoardsServices.setSelectedBoardIndexByBoardId(boardId);
            });
        },

        //delete a board;
        deleteBoard: function (boardId) {
            return $http.get(baseUrl + 'boards/' + boardId + '/delete');
        },

        //add notes to the board;
        addNotes: function (boardId, boardNotes) {
            return $http.post(baseUrl + 'boards/' + boardId + '/addNotes', {pay: boardNotes});
        },

        //update cards positions;
        updateCardsPositions: function (boardId, decks) {
            return $http.post(baseUrl + 'boards/' + boardId + '/updateCardsPositions', decks);
        },

        //update decks' positions;
        updateDecksPositions: function (decks) {
            return $http.post(baseUrl + 'boards/' + decks[0].board_id + '/updateDecksPositions', decks);
        },

        //update board's name;
        updateBoardsName: function (boardId, boardName) {
            return $http.post(baseUrl + 'boards/' + boardId + '/updateName', {boardName: boardName});
        }

    };

    return BoardsServices;
}]);


text:
#include "libtorrent/pch.hpp"

#include <boost/version.hpp>
#include <boost/bind.hpp>

#include "libtorrent/natpmp.hpp"
#include "libtorrent/io.hpp"
#include "libtorrent/assert.hpp"
#include "libtorrent/enum_net.hpp"
#include "libtorrent/socket_io.hpp"
#include "libtorrent/io_service.hpp"
//#include "libtorrent/random.hpp"

#if BOOST_VERSION < 103500
#include <asio/ip/host_name.hpp>
#else
#include <boost/asio/ip/host_name.hpp>
#endif

//#define NATPMP_LOG

#ifdef NATPMP_LOG
#include <iostream>
#endif

#if defined TORRENT_ASIO_DEBUGGING
#include "libtorrent/debug.hpp"
#endif

using namespace libtorrent;

natpmp::natpmp(io_service& ios, address const& listen_interface
	, portmap_callback_t const& cb, log_callback_t const& lcb)
	: m_callback(cb)
	, m_log_callback(lcb)
	, m_currently_mapping(-1)
	, m_retry_count(0)
	, m_socket(ios)
	, m_send_timer(ios)
	, m_refresh_timer(ios)
	, m_next_refresh(-1)
	, m_disabled(false)
	, m_abort(false)
{
	// unfortunately async operations rely on the storage
	// for this array not to be reallocated, by passing
	// around pointers to its elements. so reserve size for now
	m_mappings.reserve(10);
	rebind(listen_interface);
}

void natpmp::rebind(address const& listen_interface)
{
	mutex::scoped_lock l(m_mutex);

	error_code ec;
	address gateway = get_default_gateway(m_socket.get_io_service(), ec);
	if (ec)
	{
		char msg[200];
		snprintf(msg, sizeof(msg), "failed to find default route: %s", ec.message().c_str());
		log(msg, l);
		disable(ec, l);
		return;
	}

	m_disabled = false;

	udp::endpoint nat_endpoint(gateway, 5351);
	if (nat_endpoint == m_nat_endpoint) return;
	m_nat_endpoint = nat_endpoint;

	char msg[200];
	snprintf(msg, sizeof(msg), "found router at: %s"
		, print_address(m_nat_endpoint.address()).c_str());
	log(msg, l);

	m_socket.open(udp::v4(), ec);
	if (ec)
	{
		disable(ec, l);
		return;
	}
	m_socket.bind(udp::endpoint(address_v4::any(), 0), ec);
	if (ec)
	{
		disable(ec, l);
		return;
	}

#if defined TORRENT_ASIO_DEBUGGING
	add_outstanding_async("natpmp::on_reply");
#endif
	m_socket.async_receive_from(asio::buffer(&m_response_buffer, 16)
		, m_remote, boost::bind(&natpmp::on_reply, self(), _1, _2));
	send_get_ip_address_request(l);

	for (std::vector<mapping_t>::iterator i = m_mappings.begin()
		, end(m_mappings.end()); i != end; ++i)
	{
		if (i->protocol != none
			|| i->action != mapping_t::action_none)
			continue;
		i->action = mapping_t::action_add;
		update_mapping(i - m_mappings.begin(), l);
	}
}

void natpmp::send_get_ip_address_request(mutex::scoped_lock& l)
{
	using namespace libtorrent::detail;

	char buf[2];
	char* out = buf;
	write_uint8(0, out); // NAT-PMP version
	write_uint8(0, out); // public IP address request opcode
	log("==> get public IP address", l);

	error_code ec;
	m_socket.send_to(asio::buffer(buf, sizeof(buf)), m_nat_endpoint, 0, ec);
}

bool natpmp::get_mapping(int index, int& local_port, int& external_port, int& protocol) const
{
	mutex::scoped_lock l(m_mutex);

	TORRENT_ASSERT(index < int(m_mappings.size()) && index >= 0);
	if (index >= int(m_mappings.size()) || index < 0) return false;
	mapping_t const& m = m_mappings[index];
	if (m.protocol == none) return false;
	local_port = m.local_port;
	external_port = m.external_port;
	protocol = m.protocol;
	return true;
}

void natpmp::log(char const* msg, mutex::scoped_lock& l)
{
	l.unlock();
	m_log_callback(msg);
	l.lock();
}

void natpmp::disable(error_code const& ec, mutex::scoped_lock& l)
{
	m_disabled = true;

	for (std::vector<mapping_t>::iterator i = m_mappings.begin()
		, end(m_mappings.end()); i != end; ++i)
	{
		if (i->protocol == none) continue;
		i->protocol = none;
		int index = i - m_mappings.begin();
		l.unlock();
		m_callback(index, address(), 0, ec);
		l.lock();
	}
	close_impl(l);
}

void natpmp::delete_mapping(int index)
{
	mutex::scoped_lock l(m_mutex);

	TORRENT_ASSERT(index < int(m_mappings.size()) && index >= 0);
	if (index >= int(m_mappings.size()) || index < 0) return;
	mapping_t& m = m_mappings[index];

	if (m.protocol == none) return;
	if (!m.map_sent)
	{
		m.action = mapping_t::action_none;
		m.protocol = none;
		return;
	}

	m.action = mapping_t::action_delete;
	update_mapping(index, l);
}

int natpmp::add_mapping(protocol_type p, int external_port, int local_port)
{
	mutex::scoped_lock l(m_mutex);

	if (m_disabled) return -1;

	std::vector<mapping_t>::iterator i = std::find_if(m_mappings.begin()
		, m_mappings.end(), boost::bind(&mapping_t::protocol, _1) == int(none));
	if (i == m_mappings.end())
	{
		m_mappings.push_back(mapping_t());
		i = m_mappings.end() - 1;
	}
	i->protocol = p;
	i->external_port = external_port;
	i->local_port = local_port;
	i->action = mapping_t::action_add;

	int mapping_index = i - m_mappings.begin();

#ifdef NATPMP_LOG
	ptime now = time_now();
	for (std::vector<mapping_t>::iterator m = m_mappings.begin()
		, end(m_mappings.end()); m != end; ++m)
	{
	std::cout << " ADD MAPPING: " << mapping_index << " [ "
			"proto: " << (i->protocol == none ? "none" : i->protocol == tcp ? "tcp" : "udp")
			<< " port: " << i->external_port
			<< " local-port: " << i->local_port
			<< " action: " << (i->action == mapping_t::action_none ? "none" : i->action == mapping_t::action_add ? "add" : "delete")
			<< " ttl: " << total_seconds(i->expires - now)
			<< " ]" << std::endl;
	}
#endif

	update_mapping(mapping_index, l);
	return mapping_index;
}

void natpmp::try_next_mapping(int i, mutex::scoped_lock& l)
{
#ifdef NATPMP_LOG
	ptime now = time_now();
	for (std::vector<mapping_t>::iterator m = m_mappings.begin()
		, end(m_mappings.end()); m != end; ++m)
	{
	std::cout << "     " << (m - m_mappings.begin()) << " [ "
			"proto: " << (m->protocol == none ? "none" : m->protocol == tcp ? "tcp" : "udp")
			<< " port: " << m->external_port
			<< " local-port: " << m->local_port
			<< " action: " << (m->action == mapping_t::action_none ? "none" : m->action == mapping_t::action_add ? "add" : "delete")
			<< " ttl: " << total_seconds(m->expires - now)
			<< " ]" << std::endl;
	}
#endif
	if (i < int(m_mappings.size()) - 1)
	{
		update_mapping(i + 1, l);
		return;
	}

	std::vector<mapping_t>::iterator m = std::find_if(
		m_mappings.begin(), m_mappings.end()
		, boost::bind(&mapping_t::action, _1) != int(mapping_t::action_none));

	if (m == m_mappings.end())
	{
		if (m_abort)
		{
			error_code ec;
			m_send_timer.cancel(ec);
			m_socket.close(ec);
		}
#ifdef NATPMP_LOG
		std::cout << "     done" << (m_abort?" shutting down":"") << std::endl;
#endif
		return;
	}

#ifdef NATPMP_LOG
	std::cout << "     updating " << (m - m_mappings.begin()) << std::endl;
#endif

	update_mapping(m - m_mappings.begin(), l);
}

void natpmp::update_mapping(int i, mutex::scoped_lock& l)
{
	if (i == int(m_mappings.size()))
	{
		if (m_abort)
		{
			error_code ec;
			m_send_timer.cancel(ec);
			m_socket.close(ec);
		}
#ifdef NATPMP_LOG
		std::cout << "     done" << (m_abort?" shutting down":"") << std::endl;
#endif
		return;
	}

	natpmp::mapping_t& m = m_mappings[i];
	if (m.action == mapping_t::action_none
		|| m.protocol == none)
	{
		try_next_mapping(i, l);
		return;
	}

	if (m_currently_mapping == -1)
	{
		// the socket is not currently in use
		// send out a mapping request
		m_retry_count = 0;
		send_map_request(i, l);
	}
}

void natpmp::send_map_request(int i, mutex::scoped_lock& l)
{
	using namespace libtorrent::detail;

	TORRENT_ASSERT(m_currently_mapping == -1
		|| m_currently_mapping == i);
	m_currently_mapping = i;
	mapping_t& m = m_mappings[i];
	TORRENT_ASSERT(m.action != mapping_t::action_none);
	char buf[12];
	char* out = buf;
	write_uint8(0, out); // NAT-PMP version
	write_uint8(m.protocol, out); // map "protocol"
	write_uint16(0, out); // reserved
	write_uint16(m.local_port, out); // private port
	write_uint16(m.external_port, out); // requested public port
	int ttl = m.action == mapping_t::action_add ? 3600 : 0;
	write_uint32(ttl, out); // port mapping lifetime

	char msg[200];
	snprintf(msg, sizeof(msg), "==> port map [ mapping: %d action: %s"
		" proto: %s local: %u external: %u ttl: %u ]"
		, i, m.action == mapping_t::action_add ? "add" : "delete"
		, m.protocol == udp ? "udp" : "tcp"
		, m.local_port, m.external_port, ttl);
	log(msg, l);

	error_code ec;
	m_socket.send_to(asio::buffer(buf, sizeof(buf)), m_nat_endpoint, 0, ec);
	m.map_sent = true;
	m.outstanding_request = true;
	if (m_abort)
	{
		// when we're shutting down, ignore the
		// responses and just remove all mappings
		// immediately
		m_currently_mapping = -1;
		m.action = mapping_t::action_none;
		try_next_mapping(i, l);
	}
	else
	{
#if defined TORRENT_ASIO_DEBUGGING
		add_outstanding_async("natpmp::resend_request");
#endif
		// linear back-off instead of exponential
		++m_retry_count;
		m_send_timer.expires_from_now(milliseconds(250 * m_retry_count), ec);
		m_send_timer.async_wait(boost::bind(&natpmp::resend_request, self(), i, _1));
	}
}

void natpmp::resend_request(int i, error_code const& e)
{
#if defined TORRENT_ASIO_DEBUGGING
	complete_async("natpmp::resend_request");
#endif
	if (e) return;
	mutex::scoped_lock l(m_mutex);
	if (m_currently_mapping != i) return;

	// if we're shutting down, don't retry, just move on
	// to the next mapping
	if (m_retry_count >= 9 || m_abort)
	{
		m_currently_mapping = -1;
		m_mappings[i].action = mapping_t::action_none;
		// try again in two hours
		m_mappings[i].expires = time_now() + hours(2);
		try_next_mapping(i, l);
		return;
	}
	send_map_request(i, l);
}

void natpmp::on_reply(error_code const& e
	, std::size_t bytes_transferred)
{
	mutex::scoped_lock l(m_mutex);

#if defined TORRENT_ASIO_DEBUGGING
	complete_async("natpmp::on_reply");
#endif

	using namespace libtorrent::detail;
	if (e)
	{
		char msg[200];
		snprintf(msg, sizeof(msg), "error on receiving reply: %s", e.message().c_str());
		log(msg, l);
		return;
	}

#if defined TORRENT_ASIO_DEBUGGING
	add_outstanding_async("natpmp::on_reply");
#endif
	// make a copy of the response packet buffer
	// to avoid overwriting it in the next receive call
	char msg_buf[16];
	memcpy(msg_buf, m_response_buffer, bytes_transferred);

	m_socket.async_receive_from(asio::buffer(&m_response_buffer, 16)
		, m_remote, boost::bind(&natpmp::on_reply, self(), _1, _2));

	// simulate packet loss
/*
	if ((random() % 2) == 0)
	{
		log(" simulating drop", l);
		return;
	}
*/
	if (m_remote != m_nat_endpoint)
	{
		char msg[200];
		snprintf(msg, sizeof(msg), "received packet from wrong IP: %s"
			, print_endpoint(m_remote).c_str());
		log(msg, l);
		return;
	}

	error_code ec;
	m_send_timer.cancel(ec);

	if (bytes_transferred < 12)
	{
		char msg[200];
		snprintf(msg, sizeof(msg), "received packet of invalid size: %d", int(bytes_transferred));
		log(msg, l);
		return;
	}

	char* in = msg_buf;
	int version = read_uint8(in);
	int cmd = read_uint8(in);
	int result = read_uint16(in);
	int time = read_uint32(in);

	if (cmd == 128)
	{
		// public IP request response
		m_external_ip = read_v4_address(in);

		char msg[200];
		snprintf(msg, sizeof(msg), "<== public IP address [ %s ]", print_address(m_external_ip).c_str());
		log(msg, l);
		return;

	}

	if (bytes_transferred < 16)
	{
		char msg[200];
		snprintf(msg, sizeof(msg), "received packet of invalid size: %d", int(bytes_transferred));
		log(msg, l);
		return;
	}

	int private_port = read_uint16(in);
	int public_port = read_uint16(in);
	int lifetime = read_uint32(in);

	(void)time; // to remove warning

	int protocol = (cmd - 128 == 1)?udp:tcp;

	char msg[200];
	int num_chars = snprintf(msg, sizeof(msg), "<== port map ["
		" protocol: %s local: %u external: %u ttl: %u ]"
		, (cmd - 128 == 1 ? "udp" : "tcp")
		, private_port, public_port, lifetime);

	if (version != 0)
	{
		snprintf(msg + num_chars, sizeof(msg) - num_chars, "unexpected version: %u"
			, version);
		log(msg, l);
	}

	mapping_t* m = 0;
	int index = -1;
	for (std::vector<mapping_t>::iterator i = m_mappings.begin()
		, end(m_mappings.end()); i != end; ++i)
	{
		if (private_port != i->local_port) continue;
		if (protocol != i->protocol) continue;
		if (!i->map_sent) continue;
		if (!i->outstanding_request) continue;
		m = &*i;
		index = i - m_mappings.begin();
		break;
	}

	if (m == 0)
	{
		snprintf(msg + num_chars, sizeof(msg) - num_chars, " not found in map table");
		log(msg, l);
		return;
	}
	m->outstanding_request = false;

	log(msg, l);

	if (public_port == 0 || lifetime == 0)
	{
		// this means the mapping was
		// successfully closed
		m->protocol = none;
	}
	else
	{
		m->expires = time_now() + seconds(int(lifetime * 0.7f));
		m->external_port = public_port;
	}

	if (result != 0)
	{
		int errors[] =
		{
			errors::unsupported_protocol_version,
			errors::natpmp_not_authorized,
			errors::network_failure,
			errors::no_resources,
			errors::unsupported_opcode,
		};
		int ev = errors::no_error;
		if (result >= 1 && result <= 5) ev = errors[result - 1];

		m->expires = time_now() + hours(2);
		l.unlock();
		m_callback(index, address(), 0, error_code(ev, get_libtorrent_category()));
		l.lock();
	}
	else if (m->action == mapping_t::action_add)
	{
		l.unlock();
		m_callback(index, m_external_ip, m->external_port,
			error_code(errors::no_error, get_libtorrent_category()));
		l.lock();
	}

	if (m_abort) return;

	m_currently_mapping = -1;
	m->action = mapping_t::action_none;
	m_send_timer.cancel(ec);
	update_expiration_timer(l);
	try_next_mapping(index, l);
}

void natpmp::update_expiration_timer(mutex::scoped_lock& l)
{
	if (m_abort) return;

	ptime now = time_now() + milliseconds(100);
#ifdef NATPMP_LOG
	std::cout << time_now_string() << " update_expiration_timer " << std::endl;
	for (std::vector<mapping_t>::iterator i = m_mappings.begin()
		, end(m_mappings.end()); i != end; ++i)
	{
	std::cout << "     " << (i - m_mappings.begin()) << " [ "
			"proto: " << (i->protocol == none ? "none" : i->protocol == tcp ? "tcp" : "udp")
			<< " port: " << i->external_port
			<< " local-port: " << i->local_port
			<< " action: " << (i->action == mapping_t::action_none ? "none" : i->action == mapping_t::action_add ? "add" : "delete")
			<< " ttl: " << total_seconds(i->expires - now)
			<< " ]" << std::endl;
	}
#endif
	ptime min_expire = now + seconds(3600);
	int min_index = -1;
	for (std::vector<mapping_t>::iterator i = m_mappings.begin()
		, end(m_mappings.end()); i != end; ++i)
	{
		if (i->protocol == none
			|| i->action != mapping_t::action_none) continue;
		int index = i - m_mappings.begin();
		if (i->expires < now)
		{
			char msg[200];
			snprintf(msg, sizeof(msg), "mapping %u expired", index);
			log(msg, l);
			i->action = mapping_t::action_add;
			if (m_next_refresh == index) m_next_refresh = -1;
			update_mapping(index, l);
		}
		else if (i->expires < min_expire)
		{
			min_expire = i->expires;
			min_index = index;
		}
	}

	// this is already the mapping we're waiting for
	if (m_next_refresh == min_index) return;

	if (min_index >= 0)
	{
#ifdef NATPMP_LOG
	std::cout << time_now_string() << " next expiration ["
			" i: " << min_index
			<< " ttl: " << total_seconds(min_expire - time_now())
			<< " ]" << std::endl;
#endif
		error_code ec;
		if (m_next_refresh >= 0) m_refresh_timer.cancel(ec);

#if defined TORRENT_ASIO_DEBUGGING
		add_outstanding_async("natpmp::mapping_expired");
#endif
		m_refresh_timer.expires_from_now(min_expire - now, ec);
		m_refresh_timer.async_wait(boost::bind(&natpmp::mapping_expired, self(), _1, min_index));
		m_next_refresh = min_index;
	}
}

void natpmp::mapping_expired(error_code const& e, int i)
{
#if defined TORRENT_ASIO_DEBUGGING
	complete_async("natpmp::mapping_expired");
#endif
	if (e) return;
	mutex::scoped_lock l(m_mutex);
	char msg[200];
	snprintf(msg, sizeof(msg), "mapping %u expired", i);
	log(msg, l);
	m_mappings[i].action = mapping_t::action_add;
	if (m_next_refresh == i) m_next_refresh = -1;
	update_mapping(i, l);
}

void natpmp::close()
{
	mutex::scoped_lock l(m_mutex);
	close_impl(l);
}

void natpmp::close_impl(mutex::scoped_lock& l)
{
	m_abort = true;
	log("closing", l);
#ifdef NATPMP_LOG
	std::cout << time_now_string() << " close" << std::endl;
	ptime now = time_now();
#endif
	if (m_disabled) return;
	for (std::vector<mapping_t>::iterator i = m_mappings.begin()
		, end(m_mappings.end()); i != end; ++i)
	{
#ifdef NATPMP_LOG
	std::cout << "     " << (i - m_mappings.begin()) << " [ "
			"proto: " << (i->protocol == none ? "none" : i->protocol == tcp ? "tcp" : "udp")
			<< " port: " << i->external_port
			<< " local-port: " << i->local_port
			<< " action: " << (i->action == mapping_t::action_none ? "none" : i->action == mapping_t::action_add ? "add" : "delete")
			<< " ttl: " << total_seconds(i->expires - now)
			<< " ]" << std::endl;
#endif
		if (i->protocol == none) continue;
		i->action = mapping_t::action_delete;
	}
	error_code ec;
	m_refresh_timer.cancel(ec);
	m_currently_mapping = -1;
	update_mapping(0, l);
}


text:
GreatBy8
===============================

Search-and-Filter Map (with 2 layers: points and polygons, with dynamic legend) that draws data from Google Fusion Tables, based on template by Derek Eder

Live demo at http://jackdougherty.github.io/greatby8

Use this template if you wish to create a Search-and-Filter map that turns on/off at least 2 layers (points and polygons), with a dynamic legend for thematic polygons, and draws data from Google Fusion Tables. The default point map displays a textual legend (A, B, C), with option to switch to numeric (0-100) values. Based on template customized by Derek Eder http://derekeder.com/searchable_map_template/

Basic steps:

1) Use Google Fusion Tables to create your point and polygon map layers, and change the feature styles (set ranges, colors, etc.) and info windows.

2) Make your own copy of this template: either Fork to your own GitHub account, or Clone in Desktop, or Download a ZIP compressed version to your desktop.

3) Modify two files, following instructions in the code comments, to match your Google Fusion Table data:

- index.html
- maps_lib.js (located inside the js folder)

3) Host everything on the web (such as a GitHub repository gh-pages branch)

Learn more in an open-access Data Visualization book-in-progress by Jack Dougherty at Trinity College CT
http://epress.trincoll.edu/dataviz


text:
FOUNDATION_EXPORT double WordKitVersionNumber;

//! Project version string for WordKit.
FOUNDATION_EXPORT const unsigned char WordKitVersionString[];

// In this header, you should import all the public headers of your framework using statements like #import <WordKit/PublicHeader.h>


text:
SYNONYM

#### According to
The Catalogue of Life, 3rd January 2011

#### Published in
Bull. Soc. bot. Fr. 23: 325 (1876)

#### Original name
Lepiota lilacina Quél., 1876

### Remarks
null


text:
package ac.uk.abdn.fits.demo.hibernate.dao.impl;

/**
 * @author Cheng Zeng, University of Aberdeen
 *
 */

import java.util.List;

import org.hibernate.Criteria;
import org.hibernate.Query;
import org.hibernate.SessionFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import ac.uk.abdn.fits.demo.hibernate.dao.FareStructureDAO;
import ac.uk.abdn.fits.demo.hibernate.model.FareStructure;

@Service
public class FareStructureDAOImpl implements FareStructureDAO{

	@Autowired
	private SessionFactory sessionFactory;

	@Override
	public void insertFareStructure(FareStructure fare) {
		sessionFactory.
	      getCurrentSession();
		sessionFactory.getCurrentSession().save(fare);
	}

	@Override
	public FareStructure getFareStructureByOpId(int id) {
		Query query = sessionFactory.
			      getCurrentSession().
	      createQuery("from Fare_structure where operator_id = :operator_id");
		  query.setParameter("operator_id", id);
		  if(query.list().size() > 0){
			  return (FareStructure)query.list().get(0);
		  }
		  return null;
	}

	@Override
	@SuppressWarnings("unchecked")
	public List<FareStructure> getFareStructures() {
		Criteria criteria = sessionFactory.
			      getCurrentSession().
			      createCriteria(FareStructure.class);
		return criteria.list();
	}

}