text:
import java.awt.Dimension;
import java.awt.Point;
import java.awt.event.MouseEvent;
import java.util.LinkedList;
import javax.swing.JTextField;

/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */
/**
 *
 * @author franzqat
 */
public class TexoScreen extends javax.swing.JFrame {

    /**
     * Creates new form TexoScreen
     */
    private Point mouseDownCompCoords = null;
    private final LinkedList<Tasto> list;
    private int counter;
    private int istanziato=0;

    public TexoScreen() {
        this.counter = 0;
        this.list = new LinkedList<>();
        initComponents();
    }

    /**
     * This method is called from within the constructor to initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is always
     * regenerated by the Form Editor.
     */
    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {

        jCheckBox1 = new javax.swing.JCheckBox();
        jButton1 = new javax.swing.JButton();
        jTextField1 = new javax.swing.JTextField();
        jLabel1 = new javax.swing.JLabel();
        jButton2 = new javax.swing.JButton();
        jButton3 = new javax.swing.JButton();
        jLabel4 = new javax.swing.JLabel();
        distanzaTasti = new javax.swing.JTextField();
        jLabel5 = new javax.swing.JLabel();
        jLabel2 = new javax.swing.JLabel();
        jLabel3 = new javax.swing.JLabel();
        jTextField2 = new javax.swing.JTextField();
        jButton4 = new javax.swing.JButton();
        ClearButton = new javax.swing.JButton();
        sizejButton = new javax.swing.JButton();
        width = new javax.swing.JTextField();
        height = new javax.swing.JTextField();
        jLabel6 = new javax.swing.JLabel();
        jLabel7 = new javax.swing.JLabel();

        setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);
        setTitle("TexoScreen");
        setForeground(java.awt.Color.gray);

        jCheckBox1.setFont(new java.awt.Font("Dialog", 1, 8)); // NOI18N
        jCheckBox1.setText("Always on Top");
        jCheckBox1.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jCheckBox1ActionPerformed(evt);
            }
        });

        jButton1.setFont(jButton1.getFont().deriveFont(jButton1.getFont().getSize()-4f));
        jButton1.setText("X");
        jButton1.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jButton1ActionPerformed(evt);
            }
        });

        jLabel1.setText("Input:");

        jButton2.setText("Generate!");
        jButton2.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jButton2ActionPerformed(evt);
            }
        });

        jButton3.setText("Distanzia");
        jButton3.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jButton3ActionPerformed(evt);
            }
        });

        distanzaTasti.setText("45");

        jLabel5.setText("Distance");

        jLabel2.setForeground(new java.awt.Color(255, 51, 102));

        jLabel3.setText("Active boxes:");

        jTextField2.setText("Q,W,E,R");

        jButton4.setText("QuickButton");
        jButton4.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jButton4ActionPerformed(evt);
            }
        });

        ClearButton.setText("Clear all!");
        ClearButton.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                ClearButtonActionPerformed(evt);
            }
        });

        sizejButton.setText("Box Size");
        sizejButton.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                sizejButtonActionPerformed(evt);
            }
        });

        width.setText("40");
        width.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                widthActionPerformed(evt);
            }
        });

        height.setText("40");
        height.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                heightActionPerformed(evt);
            }
        });

        jLabel6.setText("H");

        jLabel7.setText("W");

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
        getContentPane().setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addContainerGap()
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addGroup(layout.createSequentialGroup()
                        .addComponent(jCheckBox1, javax.swing.GroupLayout.PREFERRED_SIZE, 98, javax.swing.GroupLayout.PREFERRED_SIZE)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                        .addComponent(jButton1))
                    .addGroup(layout.createSequentialGroup()
                        .addGap(12, 12, 12)
                        .addComponent(jLabel1, javax.swing.GroupLayout.PREFERRED_SIZE, 31, javax.swing.GroupLayout.PREFERRED_SIZE)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                            .addGroup(layout.createSequentialGroup()
                                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                                    .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
                                        .addComponent(jButton2, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                                        .addGap(32, 32, 32)
                                        .addComponent(ClearButton))
                                    .addGroup(layout.createSequentialGroup()
                                        .addGap(1, 1, 1)
                                        .addComponent(jButton3, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                                        .addGap(36, 36, 36)
                                        .addComponent(jLabel5, javax.swing.GroupLayout.PREFERRED_SIZE, 60, javax.swing.GroupLayout.PREFERRED_SIZE)
                                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                                        .addComponent(distanzaTasti, javax.swing.GroupLayout.PREFERRED_SIZE, 45, javax.swing.GroupLayout.PREFERRED_SIZE)
                                        .addGap(29, 29, 29)))
                                .addGap(82, 82, 82))
                            .addGroup(layout.createSequentialGroup()
                                .addComponent(jTextField1, javax.swing.GroupLayout.PREFERRED_SIZE, 169, javax.swing.GroupLayout.PREFERRED_SIZE)
                                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                                .addComponent(jLabel3)
                                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                                .addComponent(jLabel4, javax.swing.GroupLayout.PREFERRED_SIZE, 48, javax.swing.GroupLayout.PREFERRED_SIZE)
                                .addGap(0, 0, Short.MAX_VALUE))
                            .addGroup(layout.createSequentialGroup()
                                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                                    .addGroup(layout.createSequentialGroup()
                                        .addComponent(sizejButton)
                                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                                        .addComponent(jLabel7, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
                                    .addGroup(layout.createSequentialGroup()
                                        .addComponent(jButton4)
                                        .addGap(18, 18, 18)
                                        .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false)
                                            .addGroup(layout.createSequentialGroup()
                                                .addComponent(width, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                                                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                                                .addComponent(jLabel6, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                                                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                                                .addComponent(height, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                                            .addComponent(jTextField2, javax.swing.GroupLayout.PREFERRED_SIZE, 82, javax.swing.GroupLayout.PREFERRED_SIZE))))
                                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                                .addComponent(jLabel2, javax.swing.GroupLayout.PREFERRED_SIZE, 131, javax.swing.GroupLayout.PREFERRED_SIZE)
                                .addGap(25, 25, 25)))))
                .addGap(0, 0, 0))
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addContainerGap()
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(jButton1)
                    .addComponent(jCheckBox1, javax.swing.GroupLayout.PREFERRED_SIZE, 26, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addGap(11, 11, 11)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addComponent(jLabel4, javax.swing.GroupLayout.Alignment.TRAILING, javax.swing.GroupLayout.PREFERRED_SIZE, 24, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                        .addComponent(jTextField1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                        .addComponent(jLabel1)
                        .addComponent(jLabel3)))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(jButton2)
                    .addComponent(ClearButton))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(jButton3)
                    .addComponent(distanzaTasti, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(jLabel5))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(jButton4)
                    .addComponent(jTextField2, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addComponent(jLabel2, javax.swing.GroupLayout.PREFERRED_SIZE, 32, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                        .addComponent(sizejButton)
                        .addComponent(width, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                        .addComponent(height, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                        .addComponent(jLabel6)
                        .addComponent(jLabel7)))
                .addGap(14, 14, 14))
        );

        pack();
    }// </editor-fold>//GEN-END:initComponents

    private void jCheckBox1ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jCheckBox1ActionPerformed
        try {
            setAlwaysOnTop(true);
        } catch (java.lang.SecurityException e1) {
            e1.printStackTrace();
        }
    }//GEN-LAST:event_jCheckBox1ActionPerformed

    private void getMouseCoords(MouseEvent evt) {
        // TODO add your handling code here:
        mouseDownCompCoords = evt.getPoint();
    }

    private void setLocation(MouseEvent evt) {
        // TODO add your handling code here:

        Point currCoords = evt.getLocationOnScreen();
        setLocation(currCoords.x - mouseDownCompCoords.x, currCoords.y - mouseDownCompCoords.y);
    }

    private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton1ActionPerformed
        // TODO add your handling code here:
        System.exit(0);
    }//GEN-LAST:event_jButton1ActionPerformed

    private void releaseMouse() {
        // TODO add your handling code here:
        mouseDownCompCoords = null;
    }

    private void jButton2ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton2ActionPerformed
        // TODO add your handling code here:

        Tasto t = new Tasto();
        setTastoLocation(t);
        t.SetJLabel(jTextField1.getText());
        addList(t);
        clearField();

    }//GEN-LAST:event_jButton2ActionPerformed

    private void addList(Tasto t) {
        list.add(t);
        updateList();
    }

    private void updateList() {
        jLabel4.setText("" + list.size());
    }

    private void setTastoLocation(Tasto t) {

        t.setLocation(t.getLocation().x + 40 * count(), t.getLocation().y);
        t.setVisible(true);
    }

    private int count() {
        return ++counter;
    }

    private void jButton3ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton3ActionPerformed
        // TODO add your handling code her
        try {
            if (Integer.parseInt(distanzaTasti.getText()) > 0)
            groupMove(Integer.parseInt(distanzaTasti.getText()));
            else jLabel2.setText("Value must be >0");

        } catch (java.lang.NumberFormatException e) {
            jLabel2.setText("Inserisci un numero");
        }

    }//GEN-LAST:event_jButton3ActionPerformed

    private void jButton4ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton4ActionPerformed
        String s[] = splitGetTextField(jTextField2);
        for (String str : s) {
            Tasto t = new Tasto();
            setTastoLocation(t);
            t.SetJLabel(str);
            addList(t);
        }
    }//GEN-LAST:event_jButton4ActionPerformed

    private String[] splitGetTextField(JTextField jtf) {
        // TODO add your handling code here:
        String[] s = jtf.getText().split(",");
        return s;
    }

    private void ClearButtonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_ClearButtonActionPerformed
        // TODO add your handling code here:
        list.forEach((t) -> {
            t.dispose();
        });
        list.clear();
        updateList();

    }//GEN-LAST:event_ClearButtonActionPerformed

    private void sizejButtonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_sizejButtonActionPerformed
        // TODO add your handling code here:
        //Distanzia di width
        //setsize
        try {
            list.forEach((t) -> {
                changeSize(t);
            });
            groupMove(Integer.parseInt(width.getText()));

        } catch (java.lang.NumberFormatException e) {
            jLabel2.setText("Inserisci un numero");
        }
    }//GEN-LAST:event_sizejButtonActionPerformed

    private void widthActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_widthActionPerformed
        // TODO add your handling code here:
    }//GEN-LAST:event_widthActionPerformed

    private void heightActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_heightActionPerformed
        // TODO add your handling code here:
    }//GEN-LAST:event_heightActionPerformed
    private void changeSize(Tasto t) {

        Dimension dimensioni = new Dimension(Integer.parseInt(width.getText()), Integer.parseInt(height.getText()));
        t.setSize(dimensioni);
    }

    private boolean checkListaVuota() {
        //true if is empty
        return list.isEmpty();
    }

    public void groupMove(int distanza) {

        if (!checkListaVuota()) {
            Point p = list.get(0).getLocation();
            int i = 0;
            for (Tasto t : list) {
                t.setLocation(p.getLocation().x + distanza * i, p.y);
                i++;
            }
        }

    }

    private void clearField() {
        jTextField1.setText("");
    }

    public TexoScreen getInstance(){
        if (istanziato == 0){
           istanziato = 1;
                 java.awt.EventQueue.invokeLater(new Runnable() {
            @Override
            public void run() {
                new TexoScreen().setVisible(true);
            }
        });
        }
        return this;

    }

    public void start() {
        /* Set the Nimbus look and feel */
        //<editor-fold defaultstate="collapsed" desc=" Look and feel setting code (optional) ">
        /* If Nimbus (introduced in Java SE 6) is not available, stay with the default look and feel.
         * For details see http://download.oracle.com/javase/tutorial/uiswing/lookandfeel/plaf.html
         */
        try {
            for (javax.swing.UIManager.LookAndFeelInfo info : javax.swing.UIManager.getInstalledLookAndFeels()) {
                if ("Nimbus".equals(info.getName())) {
                    javax.swing.UIManager.setLookAndFeel(info.getClassName());
                    break;
                }
            }
        } catch (ClassNotFoundException ex) {
            java.util.logging.Logger.getLogger(TexoScreen.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (InstantiationException ex) {
            java.util.logging.Logger.getLogger(TexoScreen.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (IllegalAccessException ex) {
            java.util.logging.Logger.getLogger(TexoScreen.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (javax.swing.UnsupportedLookAndFeelException ex) {
            java.util.logging.Logger.getLogger(TexoScreen.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        }
        //</editor-fold>
        //</editor-fold>

        /* Create and display the form */

    }

    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JButton ClearButton;
    private javax.swing.JTextField distanzaTasti;
    private javax.swing.JTextField height;
    private javax.swing.JButton jButton1;
    private javax.swing.JButton jButton2;
    private javax.swing.JButton jButton3;
    private javax.swing.JButton jButton4;
    private javax.swing.JCheckBox jCheckBox1;
    private javax.swing.JLabel jLabel1;
    private javax.swing.JLabel jLabel2;
    private javax.swing.JLabel jLabel3;
    private javax.swing.JLabel jLabel4;
    private javax.swing.JLabel jLabel5;
    private javax.swing.JLabel jLabel6;
    private javax.swing.JLabel jLabel7;
    private javax.swing.JTextField jTextField1;
    private javax.swing.JTextField jTextField2;
    private javax.swing.JButton sizejButton;
    private javax.swing.JTextField width;
    // End of variables declaration//GEN-END:variables

}


text:
<?xml version="1.0" encoding="UTF-8" ?>
<testsuite tests="1" failures="0" name="ru.job4j.CalculateTest" time="0" errors="0" skipped="0">
  <properties>
    <property name="java.runtime.name" value="Java(TM) SE Runtime Environment"/>
    <property name="sun.boot.library.path" value="c:\Program Files\Java\jdk1.8.0_121\jre\bin"/>
    <property name="java.vm.version" value="25.121-b13"/>
    <property name="java.vm.vendor" value="Oracle Corporation"/>
    <property name="maven.multiModuleProjectDirectory" value="C:\projects\kachalad"/>
    <property name="java.vendor.url" value="http://java.oracle.com/"/>
    <property name="path.separator" value=";"/>
    <property name="guice.disable.misplaced.annotation.check" value="true"/>
    <property name="java.vm.name" value="Java HotSpot(TM) 64-Bit Server VM"/>
    <property name="file.encoding.pkg" value="sun.io"/>
    <property name="user.script" value=""/>
    <property name="user.country" value="RU"/>
    <property name="sun.java.launcher" value="SUN_STANDARD"/>
    <property name="sun.os.patch.level" value="Service Pack 1"/>
    <property name="java.vm.specification.name" value="Java Virtual Machine Specification"/>
    <property name="user.dir" value="C:\projects\kachalad"/>
    <property name="java.runtime.version" value="1.8.0_121-b13"/>
    <property name="java.awt.graphicsenv" value="sun.awt.Win32GraphicsEnvironment"/>
    <property name="java.endorsed.dirs" value="c:\Program Files\Java\jdk1.8.0_121\jre\lib\endorsed"/>
    <property name="os.arch" value="amd64"/>
    <property name="java.io.tmpdir" value="C:\Users\Dmi3\AppData\Local\Temp\"/>
    <property name="line.separator" value="
"/>
    <property name="java.vm.specification.vendor" value="Oracle Corporation"/>
    <property name="user.variant" value=""/>
    <property name="os.name" value="Windows 7"/>
    <property name="classworlds.conf" value="c:\Tools\apache-maven-3.5.0\bin\..\bin\m2.conf"/>
    <property name="sun.jnu.encoding" value="Cp1251"/>
    <property name="java.library.path" value="c:\Program Files\Java\jdk1.8.0_121\bin;C:\Windows\Sun\Java\bin;C:\Windows\system32;C:\Windows;C:\ProgramData\Oracle\Java\javapath;C:\Program Files (x86)\AMD APP\bin\x86_64;C:\Program Files (x86)\AMD APP\bin\x86;C:\Windows\system32;C:\Windows;C:\Windows\System32\Wbem;C:\Windows\System32\WindowsPowerShell\v1.0\;C:\Program Files (x86)\ATI Technologies\ATI.ACE\Core-Static;C:\Program Files (x86)\Skype\Phone\;c:\Program Files\Java\jdk1.8.0_121\bin;c:\Tools\apache-maven-3.5.0\bin;C:\Program Files\Git\cmd;."/>
    <property name="maven.conf" value="c:\Tools\apache-maven-3.5.0\bin\../conf"/>
    <property name="java.specification.name" value="Java Platform API Specification"/>
    <property name="java.class.version" value="52.0"/>
    <property name="sun.management.compiler" value="HotSpot 64-Bit Tiered Compilers"/>
    <property name="os.version" value="6.1"/>
    <property name="library.jansi.path" value="c:\Tools\apache-maven-3.5.0\bin\..\lib\jansi-native\windows64"/>
    <property name="user.home" value="C:\Users\Dmi3"/>
    <property name="user.timezone" value="Europe/Moscow"/>
    <property name="java.awt.printerjob" value="sun.awt.windows.WPrinterJob"/>
    <property name="java.specification.version" value="1.8"/>
    <property name="file.encoding" value="Cp1251"/>
    <property name="user.name" value="Dmi3"/>
    <property name="java.class.path" value="c:\Tools\apache-maven-3.5.0\bin\..\boot\plexus-classworlds-2.5.2.jar"/>
    <property name="java.vm.specification.version" value="1.8"/>
    <property name="sun.arch.data.model" value="64"/>
    <property name="java.home" value="c:\Program Files\Java\jdk1.8.0_121\jre"/>
    <property name="sun.java.command" value="org.codehaus.plexus.classworlds.launcher.Launcher clean install"/>
    <property name="java.specification.vendor" value="Oracle Corporation"/>
    <property name="user.language" value="ru"/>
    <property name="awt.toolkit" value="sun.awt.windows.WToolkit"/>
    <property name="java.vm.info" value="mixed mode"/>
    <property name="java.version" value="1.8.0_121"/>
    <property name="java.ext.dirs" value="c:\Program Files\Java\jdk1.8.0_121\jre\lib\ext;C:\Windows\Sun\Java\lib\ext"/>
    <property name="sun.boot.class.path" value="c:\Program Files\Java\jdk1.8.0_121\jre\lib\resources.jar;c:\Program Files\Java\jdk1.8.0_121\jre\lib\rt.jar;c:\Program Files\Java\jdk1.8.0_121\jre\lib\sunrsasign.jar;c:\Program Files\Java\jdk1.8.0_121\jre\lib\jsse.jar;c:\Program Files\Java\jdk1.8.0_121\jre\lib\jce.jar;c:\Program Files\Java\jdk1.8.0_121\jre\lib\charsets.jar;c:\Program Files\Java\jdk1.8.0_121\jre\lib\jfr.jar;c:\Program Files\Java\jdk1.8.0_121\jre\classes"/>
    <property name="sun.stderr.encoding" value="cp866"/>
    <property name="java.vendor" value="Oracle Corporation"/>
    <property name="maven.home" value="c:\Tools\apache-maven-3.5.0\bin\.."/>
    <property name="file.separator" value="\"/>
    <property name="java.vendor.url.bug" value="http://bugreport.sun.com/bugreport/"/>
    <property name="sun.cpu.endian" value="little"/>
    <property name="sun.io.unicode.encoding" value="UnicodeLittle"/>
    <property name="sun.stdout.encoding" value="cp866"/>
    <property name="sun.desktop" value="windows"/>
    <property name="sun.cpu.isalist" value="amd64"/>
  </properties>
  <testcase classname="ru.job4j.CalculateTest" name="whenAddOneToOneThenTwo" time="0"/>
</testsuite>

redpajama_set_name: RedPajamaGithub


text:
package org.deftserver.io;

import static com.google.common.collect.Collections2.transform;

import java.io.EOFException;
import java.io.IOException;
import java.nio.channels.CancelledKeyException;
import java.nio.channels.SelectableChannel;
import java.nio.channels.SelectionKey;
import java.nio.channels.Selector;
import java.util.Collection;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;
import java.util.concurrent.atomic.AtomicInteger;

import org.deftserver.io.callback.CallbackManager;
import org.deftserver.io.callback.JMXDebuggableCallbackManager;
import org.deftserver.io.timeout.JMXDebuggableTimeoutManager;
import org.deftserver.io.timeout.Timeout;
import org.deftserver.io.timeout.TimeoutManager;
import org.deftserver.util.Closeables;
import org.deftserver.util.MXBeanUtil;
import org.deftserver.web.AsyncCallback;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.google.common.base.Function;
import com.google.common.collect.Lists;

public class IOLoop implements IOLoopMXBean {

	/* IOLoop singleton to use for convenience (otherwise you would have to pass around the
	 * IOLoop instance explicitly, now you can simply use IOLoop.INSTANCE) */
	public static final IOLoop INSTANCE;
	static {
		try {
			INSTANCE = new IOLoop();
		} catch (IOException e) {
			throw new IllegalStateException("Couldn't create IOLoop", e);
		}
	}

	private volatile boolean running = false;

	private final Logger logger = LoggerFactory.getLogger(IOLoop.class);

	private Selector selector;

	private final Map<SelectableChannel, IOHandler> handlers = new HashMap<>();

	private final TimeoutManager tm = new JMXDebuggableTimeoutManager();
	private final CallbackManager cm = new JMXDebuggableCallbackManager();

	private static final AtomicInteger sequence = new AtomicInteger(0);

	public IOLoop() throws IOException {
		selector = Selector.open();
		MXBeanUtil.registerMXBean(this, "IOLoop");
	}
	/**
	 * Start the io loop. The thread that invokes this method will be blocked (until {@link IOLoop#stop} is invoked)
	 * and will be the io loop thread.
	 */
	public void start() {
		if (running) throw new IllegalStateException("IOLoop already running.");

		Thread.currentThread().setName("I/O-LOOP" + sequence.getAndIncrement());
		running = true;

		long selectorTimeout = 250; // 250 ms
		while (running) {
			try {
				if (selector.select(selectorTimeout) == 0) {
					long ms = tm.execute();
					selectorTimeout = Math.min(ms, /*selectorTimeout*/ 250);
					if (cm.execute()) {
						selectorTimeout = 1;
					}
					continue;
				}
				Iterator<SelectionKey> keys = selector.selectedKeys().iterator();
				while (keys.hasNext()) {
					SelectionKey key = keys.next();
					keys.remove();
					IOHandler handler = handlers.get(key.channel());
					if (handler == null) {
						logger.debug("No handler found in IOLoop for channel: {}", key.channel());
						Closeables.closeQuietly(this, key.channel());
						continue;
					}
					try {
						if (key.isReadable()) {
							try {
								handler.handleRead(key);
							} catch (EOFException e) {
								logger.debug("EOFException in read", e);
								Closeables.closeQuietly(this, key.channel());
								continue;
							} catch (IOException e) {
								logger.debug("IOException in read", e);
								Closeables.closeQuietly(this, key.channel());
								continue;
							}
						}
						if (key.isWritable()) {
							try {
								handler.handleWrite(key);
							} catch (IOException e) {
								logger.debug("IOException in write", e);
								Closeables.closeQuietly(this, key.channel());
								continue;
							}
						}
						if (key.isConnectable()) {
							try {
								handler.handleConnect(key);
							} catch (IOException e) {
								logger.debug("Unable to connect", e);
								Closeables.closeQuietly(this, key.channel());
								continue;
							}
						}
						if (key.isAcceptable()) {
							try {
								handler.handleAccept(key);
							} catch (IOException e) {
								logger.debug("Unable to accept connection", e);
							}
						}
					} catch (CancelledKeyException e) {
						logger.debug("CancelledKeyException in IOLoop", e);
						Closeables.closeQuietly(this, key.channel());
					}
				}
				long ms = tm.execute();
				selectorTimeout = Math.min(ms, /*selectorTimeout*/ 250);
				if (cm.execute()) {
					selectorTimeout = 1;
				}
			} catch (IOException e) {
				logger.error("IOException received in IOLoop", e);
			}
		}
	}

	/**
	 * Stop the io loop and release the thread (io loop thread) that invoked the {@link IOLoop#start} method.
	 */
	public void stop() {
		logger.debug("Stopping IOLoop...");
		running = false;
	}

	/**
	 * Registers a new {@code IOHandler} with this {@code IOLoop}.
	 *
	 * @param channel The {@code SelectableChannel}
	 * @param handler {@code IOHandler that will receive the io callbacks.}
	 * @param interestOps See {@link SelectionKey} for valid values. (Xor for multiple interests).
	 * @param attachment The {@code attachment} that will be accessible from the returning {@code SelectionKey}s
	 * attachment.
	 *
	 */
	public SelectionKey addHandler(SelectableChannel channel, IOHandler handler, int interestOps, Object attachment) throws IOException {
		SelectionKey key = registerChannel(channel, interestOps, attachment);
		handlers.put(channel, handler);
		return key;
	}

	/**
	 * Unregisters the previously registered {@code IOHandler}.

	 * @param channel The {@code SelectableChannel} that was registered with a user defined {@code IOHandler}
	 */
	public void removeHandler(SelectableChannel channel) {
		handlers.remove(channel);
	}

	/**
	 * Update an earlier registered {@code SelectableChannel}
	 *
	 * @param channel The {@code SelectableChannel}
	 * @param newInterestOps The complete new set of interest operations.
	 */
	public void updateHandler(SelectableChannel channel, int newInterestOps) {
		if (handlers.containsKey(channel)) {
			channel.keyFor(selector).interestOps(newInterestOps);
		} else {
			logger.warn("Tried to update interestOps for an unknown SelectableChannel.");
		}
	}

	/**
	 *
	 * @param channel
	 * @param interestOps
	 * @param attachment
	 * @return
	 */
	private SelectionKey registerChannel(SelectableChannel channel, int interestOps, Object attachment) throws IOException {
		return channel.register(selector, interestOps, attachment);
	}

	public void addKeepAliveTimeout(SelectableChannel channel, Timeout keepAliveTimeout) {
		tm.addKeepAliveTimeout(channel, keepAliveTimeout);
	}

	public boolean hasKeepAliveTimeout(SelectableChannel channel) {
		return tm.hasKeepAliveTimeout(channel);
	}

	public void addTimeout(Timeout timeout) {
		tm.addTimeout(timeout);
	}

	/**
	 * The callback will be invoked in the next iteration in the io loop. This is the only thread safe method that is
	 * exposed by Deft.
	 * This is a convenient way to return control to the io loop.
	 */
	public void addCallback(AsyncCallback callback) {
		cm.addCallback(callback);
	}

// implements IOLoopMXBean
	@Override
	public int getNumberOfRegisteredIOHandlers() {
		return handlers.size();
	}

	@Override
	public List<String> getRegisteredIOHandlers() {
		Map<SelectableChannel, IOHandler> defensive = new HashMap<SelectableChannel, IOHandler>(handlers);
		Collection<String> readables = transform(defensive.values(), new Function<IOHandler, String>() {
			@Override public String apply(IOHandler handler) { return handler.toString(); }
		});
		return Lists.newLinkedList(readables);
	}

	public void dispose() {
		for (Entry<SelectableChannel, IOHandler> he : handlers.entrySet()) {
			Closeables.closeQuietly(this, he.getKey());
		}
		stop();
	}
}


text:
package org.apache.ignite.internal.processors.cache.distributed.dht;

import java.lang.reflect.Field;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Collections;
import java.util.HashSet;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;
import java.util.UUID;
import org.apache.ignite.Ignite;
import org.apache.ignite.IgniteCheckedException;
import org.apache.ignite.IgniteLogger;
import org.apache.ignite.cache.affinity.Affinity;
import org.apache.ignite.cache.affinity.AffinityFunction;
import org.apache.ignite.cluster.ClusterNode;
import org.apache.ignite.internal.processors.affinity.AffinityTopologyVersion;
import org.apache.ignite.internal.processors.cache.GridCacheAdapter;
import org.apache.ignite.internal.processors.cache.GridCacheConcurrentMap;
import org.apache.ignite.internal.processors.cache.GridCacheContext;
import org.apache.ignite.internal.processors.cache.GridCacheEntryEx;
import org.apache.ignite.internal.processors.cache.KeyCacheObject;
import org.apache.ignite.internal.processors.cache.distributed.dht.preloader.GridDhtPartitionMap2;
import org.apache.ignite.internal.util.typedef.F;
import org.apache.ignite.internal.util.typedef.P1;
import org.apache.ignite.internal.util.typedef.internal.CU;

import static org.apache.ignite.internal.processors.cache.distributed.dht.GridDhtPartitionState.OWNING;

/**
 * Utility methods for dht preloader testing.
 */
public class GridCacheDhtTestUtils {
    /**
     * Ensure singleton.
     */
    private GridCacheDhtTestUtils() {
        // No-op.
    }

    /**
     * @param dht Cache.
     * @param keyCnt Number of test keys to put into cache.
     * @throws IgniteCheckedException If failed to prepare.
     */
    @SuppressWarnings({"UnusedAssignment", "unchecked"})
    static void prepareKeys(GridDhtCache<Integer, String> dht, int keyCnt) throws IgniteCheckedException {
        AffinityFunction aff = dht.context().config().getAffinity();

        GridCacheConcurrentMap cacheMap;

        try {
            Field field = GridCacheAdapter.class.getDeclaredField("map");

            field.setAccessible(true);

            cacheMap = (GridCacheConcurrentMap)field.get(dht);
        }
        catch (Exception e) {
            throw new IgniteCheckedException("Failed to get cache map.", e);
        }

        GridDhtPartitionTopology top = dht.topology();

        GridCacheContext ctx = dht.context();

        for (int i = 0; i < keyCnt; i++) {
            KeyCacheObject cacheKey = ctx.toCacheKeyObject(i);

            cacheMap.putEntryIfObsoleteOrAbsent(
                AffinityTopologyVersion.NONE,
                cacheKey,
                ctx.toCacheKeyObject("value" + i),
                false,
                false);

            dht.preloader().request(Collections.singleton(cacheKey), AffinityTopologyVersion.NONE);

            GridDhtLocalPartition part = top.localPartition(aff.partition(i), false);

            assert part != null;

            part.own();
        }
    }

    /**
     * @param dht Dht cache.
     * @param idx Cache index
     */
    static void printDhtTopology(GridDhtCache<Integer, String> dht, int idx) {
        final Affinity<Integer> aff = dht.affinity();

        Ignite ignite = dht.context().grid();
        ClusterNode locNode = ignite.cluster().localNode();

        GridDhtPartitionTopology top = dht.topology();

        System.out.println("\nTopology of cache #" + idx + " (" + locNode.id() + ")" + ":");
        System.out.println("----------------------------------");

        List<Integer> affParts = new LinkedList<>();

        GridDhtPartitionMap2 map = dht.topology().partitions(locNode.id());

        if (map != null)
            for (int p : map.keySet())
                affParts.add(p);

        Collections.sort(affParts);

        System.out.println("Affinity partitions: " + affParts + "\n");

        List<GridDhtLocalPartition> locals = new ArrayList<GridDhtLocalPartition>(top.localPartitions());

        Collections.sort(locals);

        for (final GridDhtLocalPartition part : locals) {
            Collection<ClusterNode> partNodes = aff.mapKeyToPrimaryAndBackups(part.id());

            String ownStr = !partNodes.contains(dht.context().localNode()) ? "NOT AN OWNER" :
                F.eqNodes(CU.primary(partNodes), locNode) ? "PRIMARY" : "BACKUP";

            Collection<Integer> keys = F.viewReadOnly(dht.keySet(), F.<Integer>identity(), new P1<Integer>() {
                @Override public boolean apply(Integer k) {
                    return aff.partition(k) == part.id();
                }
            });

            System.out.println("Local partition: [" + part + "], [owning=" + ownStr + ", keyCnt=" + keys.size() +
                ", keys=" + keys + "]");
        }

        System.out.println("\nNode map:");

        for (Map.Entry<UUID, GridDhtPartitionMap2> e : top.partitionMap(false).entrySet()) {
            List<Integer> list = new ArrayList<>(e.getValue().keySet());

            Collections.sort(list);

            System.out.println("[node=" + e.getKey() + ", parts=" + list + "]");
        }

        System.out.println("");
    }

    /**
     * Checks consistency of partitioned cache.
     * Any preload processes must be finished before this method call().
     *
     * @param dht Dht cache.
     * @param idx Cache index.
     * @param log Logger.
     */
    @SuppressWarnings("unchecked")
    static void checkDhtTopology(GridDhtCache<Integer, String> dht, int idx, IgniteLogger log) {
        assert dht != null;
        assert idx >= 0;
        assert log != null;

        log.info("Checking balanced state of cache #" + idx);

        Affinity<Object> aff = (Affinity)dht.affinity();

        Ignite ignite = dht.context().grid();
        ClusterNode locNode = ignite.cluster().localNode();

        GridDhtPartitionTopology top = dht.topology();

        // Expected partitions calculated with affinity function.
        // They should be in topology in OWNING state.
        Collection<Integer> affParts = new HashSet<>();

        GridDhtPartitionMap2 map = dht.topology().partitions(locNode.id());

        if (map != null)
            for (int p : map.keySet())
                affParts.add(p);

        if (F.isEmpty(affParts))
            return;

        for (int p : affParts)
            assert top.localPartition(p, false) != null :
                "Partition does not exist in topology: [cache=" + idx + ", part=" + p + "]";

        for (GridDhtLocalPartition p : top.localPartitions()) {
            assert affParts.contains(p.id()) :
                "Invalid local partition: [cache=" + idx + ", part=" + p + ", node partitions=" + affParts + "]";

            assert p.state() == OWNING : "Invalid partition state [cache=" + idx + ", part=" + p + "]";

            Collection<ClusterNode> partNodes = aff.mapPartitionToPrimaryAndBackups(p.id());

            assert partNodes.contains(locNode) :
                "Partition affinity nodes does not contain local node: [cache=" + idx + "]";
        }

        // Check keys.
        for (GridCacheEntryEx e : dht.entries()) {
            GridDhtCacheEntry entry = (GridDhtCacheEntry)e;

            if (!affParts.contains(entry.partition()))
                log.warning("Partition of stored entry is obsolete for node: [cache=" + idx + ", entry=" + entry +
                    ", node partitions=" + affParts + "]");

            int p = aff.partition(entry.key());

            if (!affParts.contains(p))
                log.warning("Calculated entry partition is not in node partitions: [cache=" + idx + ", part=" + p +
                    ", entry=" + entry + ", node partitions=" + affParts + "]");
        }
    }
}


text:
package org.messaginghub.pooled.jms;

import java.util.List;
import java.util.concurrent.CopyOnWriteArrayList;
import java.util.concurrent.atomic.AtomicBoolean;

import jakarta.jms.Connection;
import jakarta.jms.ConnectionConsumer;
import jakarta.jms.ConnectionMetaData;
import jakarta.jms.Destination;
import jakarta.jms.ExceptionListener;
import jakarta.jms.IllegalStateException;
import jakarta.jms.JMSException;
import jakarta.jms.Queue;
import jakarta.jms.QueueConnection;
import jakarta.jms.QueueSession;
import jakarta.jms.ServerSessionPool;
import jakarta.jms.Session;
import jakarta.jms.TemporaryQueue;
import jakarta.jms.TemporaryTopic;
import jakarta.jms.Topic;
import jakarta.jms.TopicConnection;
import jakarta.jms.TopicSession;

import org.messaginghub.pooled.jms.pool.PooledConnection;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

/**
 * Represents a proxy {@link Connection} which is-a {@link TopicConnection} and
 * {@link QueueConnection} which is pooled and on {@link #close()} will return
 * its reference to the ConnectionPool backing it.
 *
 * <b>NOTE</b> this implementation is only intended for use when sending
 * messages. It does not deal with pooling of consumers.
 */
public class JmsPoolConnection implements TopicConnection, QueueConnection, JmsPoolSessionEventListener, AutoCloseable {

    private static final Logger LOG = LoggerFactory.getLogger(JmsPoolConnection.class);

    protected PooledConnection connection;

    private final AtomicBoolean closed = new AtomicBoolean();

    private final List<TemporaryQueue> connTempQueues = new CopyOnWriteArrayList<TemporaryQueue>();
    private final List<TemporaryTopic> connTempTopics = new CopyOnWriteArrayList<TemporaryTopic>();
    private final List<JmsPoolSession> loanedSessions = new CopyOnWriteArrayList<JmsPoolSession>();

    /**
     * Creates a new PooledConnection instance that uses the given ConnectionPool to create
     * and manage its resources.  The ConnectionPool instance can be shared amongst many
     * PooledConnection instances.
     *
     * @param pool
     *      The connection and pool manager backing this proxy connection object.
     */
    public JmsPoolConnection(PooledConnection pool) {
        this.connection = pool;
    }

    @Override
    public void close() throws JMSException {
        if (closed.compareAndSet(false, true)) {
            this.cleanupAllLoanedSessions();
            this.cleanupConnectionTemporaryDestinations();
            if (this.connection != null) {
                this.connection.decrementReferenceCount();
                this.connection = null;
            }
        }
    }

    @Override
    public void start() throws JMSException {
        checkClosed();
        connection.start();
    }

    @Override
    public void stop() throws JMSException {
        checkClosed();
    }

    @Override
    public ConnectionMetaData getMetaData() throws JMSException {
        return getConnection().getMetaData();
    }

    @Override
    public ExceptionListener getExceptionListener() throws JMSException {
        checkClosed();
        return connection.getParentExceptionListener();
    }

    @Override
    public void setExceptionListener(ExceptionListener exceptionListener) throws JMSException {
        checkClosed();
        connection.setParentExceptionListener(exceptionListener);
    }

    @Override
    public String getClientID() throws JMSException {
        return getConnection().getClientID();
    }

    @Override
    public void setClientID(String clientID) throws JMSException {
        // ignore repeated calls to setClientID() with the same client id
        // this could happen when a JMS component such as Spring that uses a
        // Pooled JMS ConnectionFactory when it shuts down and reinitializes.
        if (this.getConnection().getClientID() == null || !this.getClientID().equals(clientID)) {
            getConnection().setClientID(clientID);
        }
    }

    //----- ConnectionConsumer factory methods -------------------------------//

    @Override
    public ConnectionConsumer createConnectionConsumer(Destination destination, String selector, ServerSessionPool serverSessionPool, int maxMessages) throws JMSException {
        return getConnection().createConnectionConsumer(destination, selector, serverSessionPool, maxMessages);
    }

    @Override
    public ConnectionConsumer createConnectionConsumer(Topic topic, String s, ServerSessionPool serverSessionPool, int maxMessages) throws JMSException {
        return getConnection().createConnectionConsumer(topic, s, serverSessionPool, maxMessages);
    }

    @Override
    public ConnectionConsumer createDurableConnectionConsumer(Topic topic, String selector, String s1, ServerSessionPool serverSessionPool, int i) throws JMSException {
        return getConnection().createDurableConnectionConsumer(topic, selector, s1, serverSessionPool, i);
    }

    @Override
    public ConnectionConsumer createSharedDurableConnectionConsumer(Topic topic, String subscriptionName, String selector, ServerSessionPool sessionPool, int maxMessages) throws JMSException {
        checkClosed();
        connection.checkClientJMSVersionSupport(2, 0);
        return getConnection().createSharedDurableConnectionConsumer(topic, subscriptionName, selector, sessionPool, maxMessages);
    }

    @Override
    public ConnectionConsumer createSharedConnectionConsumer(Topic topic, String subscriptionName, String selector, ServerSessionPool sessionPool, int maxMessages) throws JMSException {
        checkClosed();
        connection.checkClientJMSVersionSupport(2, 0);
        return getConnection().createSharedConnectionConsumer(topic, subscriptionName, selector, sessionPool, maxMessages);
    }

    @Override
    public ConnectionConsumer createConnectionConsumer(Queue queue, String selector, ServerSessionPool serverSessionPool, int maxMessages) throws JMSException {
        return getConnection().createConnectionConsumer(queue, selector, serverSessionPool, maxMessages);
    }

    //----- Session factory methods ------------------------------------------//

    @Override
    public QueueSession createQueueSession(boolean transacted, int ackMode) throws JMSException {
        return (QueueSession) createSession(transacted, ackMode);
    }

    @Override
    public TopicSession createTopicSession(boolean transacted, int ackMode) throws JMSException {
        return (TopicSession) createSession(transacted, ackMode);
    }

    @Override
    public Session createSession() throws JMSException {
        return createSession(false, Session.AUTO_ACKNOWLEDGE);
    }

    @Override
    public Session createSession(int sessionMode) throws JMSException {
        return createSession(sessionMode == Session.SESSION_TRANSACTED, sessionMode);
    }

    @Override
    public Session createSession(boolean transacted, int ackMode) throws JMSException {
        checkClosed();

        JmsPoolSession result = (JmsPoolSession) connection.createSession(transacted, ackMode);

        // Store the session so we can close the sessions that this Pooled JMS Connection
        // created in order to ensure that consumers etc are closed per the JMS contract.
        loanedSessions.add(result);

        // Add a event listener to the session that notifies us when the session
        // creates / destroys temporary destinations and closes etc.
        result.addSessionEventListener(this);
        return result;
    }

    //----- Pooled JMS Session specific methods ------------------------------//

    @Override
    public void onTemporaryQueueCreate(TemporaryQueue tempQueue) {
        connTempQueues.add(tempQueue);
    }

    @Override
    public void onTemporaryTopicCreate(TemporaryTopic tempTopic) {
        connTempTopics.add(tempTopic);
    }

    @Override
    public void onSessionClosed(JmsPoolSession session) {
        this.loanedSessions.remove(session);
    }

    public Connection getConnection() throws JMSException {
        checkClosed();
        return connection.getConnection();
    }

    @Override
    public String toString() {
        return getClass().getSimpleName() + " { " + connection + " }";
    }

    /**
     * Remove all of the temporary destinations created for this connection.
     * This is important since the underlying connection may be reused over a
     * long period of time, accumulating all of the temporary destinations from
     * each use. However, from the perspective of the lifecycle from the
     * client's view, close() closes the connection and, therefore, deletes all
     * of the temporary destinations created.
     */
    protected void cleanupConnectionTemporaryDestinations() {
        for (TemporaryQueue tempQueue : connTempQueues) {
            try {
                tempQueue.delete();
            } catch (JMSException ex) {
                LOG.info("failed to delete Temporary Queue \"" + tempQueue.toString() + "\" on closing pooled connection: " + ex.getMessage());
            }
        }
        connTempQueues.clear();

        for (TemporaryTopic tempTopic : connTempTopics) {
            try {
                tempTopic.delete();
            } catch (JMSException ex) {
                LOG.info("failed to delete Temporary Topic \"" + tempTopic.toString() + "\" on closing pooled connection: " + ex.getMessage());
            }
        }
        connTempTopics.clear();
    }

    /**
     * The PooledSession tracks all Sessions that it created and now we close them.  Closing the
     * PooledSession will return the internal Session to the Pool of Session after cleaning up
     * all the resources that the Session had allocated for this PooledConnection.
     */
    protected void cleanupAllLoanedSessions() {
        for (JmsPoolSession session : loanedSessions) {
            try {
                session.close();
            } catch (JMSException ex) {
                LOG.info("failed to close loaned Session \"" + session + "\" on closing pooled connection: " + ex.getMessage());
            }
        }

        loanedSessions.clear();
    }

    /**
     * @return the total number of Pooled session including idle sessions that are not
     *          currently loaned out to any client.
     *
     * @throws JMSException if the connection has been closed.
     */
    public int getNumSessions() throws JMSException {
        checkClosed();
        return this.connection.getNumSessions();
    }

    /**
     * @return the number of Sessions that are currently checked out of this Connection's session pool.
     *
     * @throws JMSException if the connection has been closed.
     */
    public int getNumActiveSessions() throws JMSException {
        checkClosed();
        return this.connection.getNumActiveSessions();
    }

    /**
     * @return the number of Sessions that are idle in this Connection's sessions pool.
     *
     * @throws JMSException if the connection has been closed.
     */
    public int getNumtIdleSessions() throws JMSException {
        checkClosed();
        return this.connection.getNumIdleSessions();
    }

    //----- Internal support methods -----------------------------------------//

    protected void checkClosed() throws IllegalStateException {
        if (closed.get()) {
            throw new IllegalStateException("Connection closed");
        }
    }
}


text:
package org.globus.ftp;

import java.io.IOException;
import java.io.InputStream;
import java.io.EOFException;
import java.io.InterruptedIOException;

import org.globus.util.CircularBuffer;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;

// if write() blocked, it will not be unblocked by close
public class InputStreamDataSink implements DataSink {

    protected CircularBuffer buffers = null;
    private DataInputStream in;
    private boolean closed = false;

    public InputStreamDataSink() {
	this.buffers = new CircularBuffer(5);
	this.in = new DataInputStream();
    }

    public void write(Buffer buffer)
	throws IOException {
	if (isClosed()) {
	    throw new EOFException();
	}
	try {
	    if (!buffers.put(buffer)) {
		throw new EOFException();
	    }
	} catch (InterruptedException e) {
	    throw new InterruptedIOException();
	}
    }

    public void close()
	throws IOException {
	// will let get run until it returns null
	// and will throe EOFException on next put call
	// but existing put calls will not be interrupted
	setClosed();
	this.buffers.closePut();
    }

    private synchronized void setClosed() {
	this.closed = true;
    }

    private synchronized boolean isClosed() {
	return this.closed;
    }

    public InputStream getInputStream() {
	return this.in;
    }

    class DataInputStream extends InputStream {

	protected byte[] buff;
	protected int index;
	protected int length;

	public synchronized int read(byte [] data)
	    throws IOException {
	    return read(data, 0, data.length);
	}

	public synchronized int read(byte[] data, int off, int len)
	    throws IOException {
	    if (!ensureData()) {
		return -1;
	    }
	    int max = (index + len > length) ? length - index : len;
	    System.arraycopy(buff, index, data, off, max);
	    index += max;
	    return max;
	}

	public synchronized int read()
	    throws IOException {
	    if (!ensureData()) {
		return -1;
	    }
	    return buff[index++] & 0xff;
	}

	public void close()
	    throws IOException {
	    buffers.interruptBoth();
	}

	protected synchronized boolean ensureData()
	    throws IOException {
	    if (buffers.isGetInterrupted()) {
		return false;
	    }
	    if (this.length == this.index) {
		try {
		    Buffer buf = (Buffer)buffers.get();
		    if (buf == null) {
			return false;
		    }
		    this.index = 0;
		    this.length = buf.getLength();
		    this.buff = buf.getBuffer();
		} catch (InterruptedException e) {
		    // that should never happen
		    throw new InterruptedIOException();
		}
	    }
	    return true;
	}

    }
}


text:
import { NgModule } from '@angular/core';
import { BrowserModule } from '@angular/platform-browser';
import { IonicApp, IonicModule } from '../../../../..';

import { AppComponent } from './app.component';
import { PageOneModule } from '../pages/page-one/page-one.module';
import { SidePageModule } from '../pages/side-page/side-page.module';

@NgModule({
  declarations: [
    AppComponent
  ],
  imports: [
    BrowserModule,
    IonicModule.forRoot(AppComponent, {
      swipeBackEnabled: true
    }),
    PageOneModule,
    SidePageModule
  ],
  bootstrap: [IonicApp]
})
export class AppModule {}


text:
=head1 NAME

Bio::Tools::ProteinToGenomeBlat

=head1 SYNOPSIS

  use Bio::Tools::ProteinToGenomeBlat;
  my $blat_parser = new Bio::Tools::ProteinToGenomeBlat(-fh =>$filehandle );
  while( my $blat_feat = $blat_parser->next_result ) {
        push @bllat_feat, $blat_feat;
  }

=head1 DESCRIPTION

 Parser for Blat  program

=head1 FEEDBACK

=head2 Mailing Lists

 User feedback is an integral part of the evolution of this and other
 Bioperl modules. Send your comments and suggestions preferably to
 the Bioperl mailing list.  Your participation is much appreciated.

 bioperl-l@bioperl.org              - General discussion
 http://bioperl.org/MailList.shtml  - About the mailing lists

=head2 Reporting Bugs

 Report bugs to the Bioperl bug tracking system to help us keep track
 of the bugs and their resolution. Bug reports can be submitted via
 email or the web:

 bioperl-bugs@bioperl.org
 http://bugzilla.bioperl.org/

=head1 AUTHOR - Balamurugan Kumarasamy

 Email: bala@tll.org.sg

=head1 APPENDIX

 The rest of the documentation details each of the object methods.
 Internal methods are usually preceded with a _

=cut

package Bio::Tools::ProteinToGenomeBlat;
use vars qw(@ISA);
use strict;
use Bio::SeqFeature::Generic;
use Bio::Root::Root;
use Bio::SeqFeature::FeaturePair;
use Bio::Root::IO;
use Bio::SeqFeature::Generic;
@ISA = qw(Bio::Root::Root Bio::Root::IO );

=head2 new

 Title   : new
 Usage   : my $obj = new Bio::Tools::ProteinToGenomeBlat(-fh=>$filehandle);
 Function: Builds a new Bio::Tools::ProteinToGenomeBlat object
 Returns : Bio::Tools::ProteinToGenomeBlat
 Args    : -filename
           -fh (filehandle)

=cut

sub new {
    my ( $class, @args ) = @_;

    my $self = $class->SUPER::new(@args);
    $self->_initialize_io(@args);

    return $self;
}

=head2 next_result

 Title   : next_result
 Usage   : my $feat = $blat_parser->next_result
 Function: Get the next result set from parser data
 Returns : L<Bio::SeqFeature::Generic>
 Args    : none

=cut

sub next_result {
    my ($self) = @_;
    my $filehandle;

    my $line;

    my $id;
    while ( $_ = $self->_readline() ) {

        # first split on spaces:
        $line = $_;
        chomp $line;

        # chomp;

        my (
            $matches,      $mismatches,    $rep_matches,  $n_count,
            $q_num_insert, $q_base_insert, $t_num_insert, $t_base_insert,
            $strand,       $q_name,        $q_length,     $q_start,
            $q_end,        $t_name,        $t_length,     $t_start,
            $t_end,        $block_count,   $block_sizes,  $q_starts,
            $t_starts
        ) = split;

        my $superfeature = Bio::SeqFeature::Generic->new();

        # ignore any preceeding text
        unless ( $matches =~ /^\d+$/ ) {
            next;
        }

        # create as many features as blocks there are in each output line
        my ( %gfeat, %pfeat );
        $gfeat{name} = $t_name;
        $pfeat{name} = $q_name;

        $pfeat{strand} = substr $strand, 0, 1;
        $gfeat{strand} = substr $strand, 1, 1;

        my $percent_id = sprintf "%.2f",
          ( 100 *
              ( $matches + $rep_matches ) /
              ( $matches + $mismatches + $rep_matches ) );

        unless ($q_length) {
            $self->warn("length of query is zero, something is wrong!");
            next;
        }
        my $score = sprintf "%.2f",
          ( 100 * ( $matches + $mismatches + $rep_matches ) / $q_length );

        # size of each block of alignment (inclusive)
        my @block_sizes = split ",", $block_sizes;

# start position of each block (you must add 1 as psl output is off by one in the start coordinate)
        my @q_start_positions = split ",", $q_starts;
        my @t_start_positions = split ",", $t_starts;

        $superfeature->seq_id($q_name);
        $superfeature->score($score);

        #$superfeature->percent_id( $percent_id );
        $superfeature->add_tag_value( 'percent_id', $percent_id );
        $superfeature->add_tag_value( 'ident',      $matches );
        $superfeature->add_tag_value( 'qgap_cnt',   $q_num_insert );
        $superfeature->add_tag_value( 'qgap_bases', $q_base_insert );
        $superfeature->add_tag_value( 'tgap_cnt',   $t_num_insert );
        $superfeature->add_tag_value( 'tgap_bases', $t_base_insert );

# each line of output represents one possible entire aligment of the query (gfeat) and the target(pfeat)
        for ( my $i = 0 ; $i < $block_count ; $i++ ) {

            my ( $query_start, $query_end );

            if ( $pfeat{strand} eq '+' ) {
                $query_start = $q_start_positions[$i] + 1;
                $query_end   = $query_start + $block_sizes[$i] - 1;
            }
            else {
                $query_end   = $q_length - $q_start_positions[$i];
                $query_start = $query_end - $block_sizes[$i] + 1;
            }

            #$pfeat {start} = $q_start_positions[$i] + 1;
            #$pfeat {end}   = $pfeat{start} + $block_sizes[$i] - 1;
            $pfeat{start} = $query_start;
            $pfeat{end}   = $query_end;
            if ( $query_end < $query_start ) {
                $self->warn(
"dodgy feature coordinates: end = $query_end, start = $query_start. Reversing..."
                );
                $pfeat{end}   = $query_start;
                $pfeat{start} = $query_end;
            }

            # set the start and end for the genomic coordinates.  must account
            # for codon size.
            if ( $gfeat{strand} eq '+' ) {
                $gfeat{start} = $t_start_positions[$i] + 1;
                $gfeat{end}   = $gfeat{start} + 3 * $block_sizes[$i] - 1;
            }
            else {
                $gfeat{end}   = $t_length - $t_start_positions[$i];
                $gfeat{start} = $gfeat{end} - 3 * $block_sizes[$i] + 1;
            }

            # we put all the features with the same score and percent_id
            $pfeat{score}   = $score;
            $gfeat{score}   = $pfeat{score};
            $pfeat{percent} = $percent_id;
            $gfeat{percent} = $pfeat{percent};

            # other stuff:
            $gfeat{db}         = undef;
            $gfeat{db_version} = undef;
            $gfeat{program}    = 'blat';
            $gfeat{p_version}  = '1';
            $gfeat{source}     = 'blat';
            $gfeat{primary}    = 'similarity';
            $pfeat{source}     = 'blat';
            $pfeat{primary}    = 'similarity';

            my $feature_pair = $self->create_feature( \%gfeat, \%pfeat );
            $superfeature->add_sub_SeqFeature( $feature_pair, 'EXPAND' );
        }

        #push(@features_within_features, $superfeature);
        return $superfeature;
    }

}

=head2 create_feature

 Title   : create_feature
 Usage   : my $feat=$blat_parser->create_feature($feature,$seqname)
 Function: creates a SeqFeature Generic object
 Returns : L<Bio::SeqFeature::Generic>
 Args    :

=cut

sub create_feature {
    my ( $self, $gfeat, $pfeat ) = @_;

    my $feature1 = Bio::SeqFeature::Generic->new(
        -seq_id  => $gfeat->{name},
        -start   => $gfeat->{start},
        -end     => $gfeat->{end},
        -strand  => $gfeat->{strand},
        -score   => $gfeat->{score},
        -source  => $gfeat->{source},
        -primary => $gfeat->{primary},
    );

    my $feature2 = Bio::SeqFeature::Generic->new(
        -seq_id  => $pfeat->{name},
        -start   => $pfeat->{start},
        -end     => $pfeat->{end},
        -strand  => $pfeat->{strand},
        -score   => $pfeat->{score},
        -source  => $pfeat->{source},
        -primary => $pfeat->{primary},
    );

    my $featurepair = Bio::SeqFeature::FeaturePair->new;
    $featurepair->feature1($feature1);
    $featurepair->feature2($feature2);

    $featurepair->add_tag_value( 'evalue',     $pfeat->{p} );
    $featurepair->add_tag_value( 'percent_id', $pfeat->{percent} );
    $featurepair->add_tag_value( "hid",        $pfeat->{primary} );
    return $featurepair;

}

1;


text:
[Alvin Jin](https://alvincjin.github.io/) is a Senior Big Data & Machine Learning Tech Lead in Toronto, Canada.
He mainly focuses on Big Data Platform development and Machine Learning Algorithms research.

Email: alvincjin@gmail.com


text:
title: LitePub
repo: mirovarga/litepub
homepage: https://github.com/mirovarga/litepub
language:
  - Go
license:
  - MIT
templates:
  - Go
description: A Lightweight Static Blog Generator
---

LitePub is a static blog generator that tries to be as easy to use as possible.

It requires no software dependencies, needs no configuration files, uses no
databases. All it needs is one binary, posts written in Markdown and a set
of templates to render the posts to static HTML files.

Posts don't have to include any special metadata (aka front matter) like title
or date in them - the title, date and optional tags are parsed from
the natural flow of the posts.


text:
/** @file Vector3d.cpp
 *
 *  @author Kristofer Björnson
 */

#include "TBTK/TBTKMacros.h"
#include "TBTK/Vector3d.h"

using namespace std;

namespace TBTK{

Vector3d::Vector3d(){
}

Vector3d::Vector3d(initializer_list<double> components){
	TBTKAssert(
		components.size() == 3,
		"Vector3d::Vector3d()",
		"Incompatible dimensions. Vector3d takes 3 components, but "
		<< components.size() << " was given.",
		""
	);

	x = *(components.begin() + 0);
	y = *(components.begin() + 1);
	z = *(components.begin() + 2);
}

Vector3d::Vector3d(const vector<double> &components){
	TBTKAssert(
		components.size() == 3,
		"Vector3d::Vector3d()",
		"Incompatible dimensions. Vector3d takes 3 components, but "
		<< components.size() << " was given.",
		""
	);

	x = *(components.begin() + 0);
	y = *(components.begin() + 1);
	z = *(components.begin() + 2);
}

};	//End of namespace TBTK


text:
package org.openqa.grid.common.exception;

import java.util.Map;

public class CapabilityNotPresentOnTheGridException extends GridException {

  private static final long serialVersionUID = -5382151149204616537L;

  public CapabilityNotPresentOnTheGridException(String msg) {
    super(msg);
  }

  public CapabilityNotPresentOnTheGridException(Map<String, Object> capabilities) {
    super("cannot find : " + capabilities);
  }
}


text:
namespace Problem03AnimalHierarchy
{
    using System;

    public class Kitten : Cat
    {
        public Kitten(string name, byte age)
            : base(name, age, false) { }

        #region Overrides of Cat

        public override void SaySomething()
        {
            Console.WriteLine("Kitty miao, miao, miao...");
        }

        #endregion
    }
}


text:
#pragma once

#include <alsa/asoundlib.h>
#include <pulse/pulseaudio.h>

int
pa_format_to_alsa(pa_sample_format_t format);

pa_sample_format_t
pa_sample_format_from_string(const char *str);

/// finds largest number that is less or equal than |number| and multiple of
/// |multiple_of|.
size_t
pa_find_multiple_of(size_t number, size_t multiple_of,
                    int towards_larger_numbers);

void
pa_apply_volume_multiplier(void *buf, size_t sz,
                           const pa_volume_t volume[PA_CHANNELS_MAX],
                           const pa_sample_spec *ss);


text:
package org.apache.cloudstack.api.command.user.iso;

import java.util.List;

import org.apache.cloudstack.api.APICommand;
import org.apache.cloudstack.api.ApiConstants;
import org.apache.cloudstack.api.ApiErrorCode;
import org.apache.cloudstack.api.BaseCmd;
import org.apache.cloudstack.api.Parameter;
import org.apache.cloudstack.api.ResponseObject.ResponseView;
import org.apache.cloudstack.api.ServerApiException;
import org.apache.cloudstack.api.command.user.UserCmd;
import org.apache.cloudstack.api.response.DomainResponse;
import org.apache.cloudstack.api.response.GuestOSResponse;
import org.apache.cloudstack.api.response.ListResponse;
import org.apache.cloudstack.api.response.ProjectResponse;
import org.apache.cloudstack.api.response.TemplateResponse;
import org.apache.cloudstack.api.response.ZoneResponse;
import org.apache.cloudstack.context.CallContext;
import org.apache.log4j.Logger;

import com.cloud.exception.ResourceAllocationException;
import com.cloud.template.VirtualMachineTemplate;

@APICommand(name = "registerIso", responseObject = TemplateResponse.class, description = "Registers an existing ISO into the CloudStack Cloud.", responseView = ResponseView.Restricted,
        requestHasSensitiveInfo = false, responseHasSensitiveInfo = false)
public class RegisterIsoCmd extends BaseCmd implements UserCmd {
    public static final Logger s_logger = Logger.getLogger(RegisterIsoCmd.class.getName());

    private static final String s_name = "registerisoresponse";

    /////////////////////////////////////////////////////
    //////////////// API parameters /////////////////////
    /////////////////////////////////////////////////////

    @Parameter(name = ApiConstants.BOOTABLE, type = CommandType.BOOLEAN, description = "true if this ISO is bootable. If not passed explicitly its assumed to be true")
    private Boolean bootable;

    @Parameter(name = ApiConstants.DISPLAY_TEXT,
               type = CommandType.STRING,
               required = true,
               description = "the display text of the ISO. This is usually used for display purposes.",
               length = 4096)
    private String displayText;

    @Parameter(name = ApiConstants.IS_FEATURED, type = CommandType.BOOLEAN, description = "true if you want this ISO to be featured")
    private Boolean featured;

    @Parameter(name = ApiConstants.IS_PUBLIC,
               type = CommandType.BOOLEAN,
               description = "true if you want to register the ISO to be publicly available to all users, false otherwise.")
    private Boolean publicIso;

    @Parameter(name = ApiConstants.IS_EXTRACTABLE, type = CommandType.BOOLEAN, description = "true if the ISO or its derivatives are extractable; default is false")
    private Boolean extractable;

    @Parameter(name = ApiConstants.NAME, type = CommandType.STRING, required = true, description = "the name of the ISO")
    private String isoName;

    @Parameter(name = ApiConstants.OS_TYPE_ID,
               type = CommandType.UUID,
               entityType = GuestOSResponse.class,
               description = "the ID of the OS type that best represents the OS of this ISO. If the ISO is bootable this parameter needs to be passed")
    private Long osTypeId;

    @Parameter(name = ApiConstants.URL, type = CommandType.STRING, required = true, length = 2048, description = "the URL to where the ISO is currently being hosted")
    private String url;

    @Parameter(name=ApiConstants.ZONE_ID, type=CommandType.UUID, entityType = ZoneResponse.class,
            required=true, description="the ID of the zone you wish to register the ISO to.")
    protected Long zoneId;

    @Parameter(name = ApiConstants.DOMAIN_ID,
               type = CommandType.UUID,
               entityType = DomainResponse.class,
               description = "an optional domainId. If the account parameter is used, domainId must also be used.")
    private Long domainId;

    @Parameter(name = ApiConstants.ACCOUNT, type = CommandType.STRING, description = "an optional account name. Must be used with domainId.")
    private String accountName;

    @Parameter(name = ApiConstants.CHECKSUM, type = CommandType.STRING, description = "the checksum value of this ISO. " + ApiConstants.CHECKSUM_PARAMETER_PREFIX_DESCRIPTION)
    private String checksum;

    @Parameter(name = ApiConstants.PROJECT_ID, type = CommandType.UUID, entityType = ProjectResponse.class, description = "Register ISO for the project")
    private Long projectId;

    @Parameter(name = ApiConstants.IMAGE_STORE_UUID, type = CommandType.STRING, description = "Image store UUID")
    private String imageStoreUuid;

    @Parameter(name = ApiConstants.IS_DYNAMICALLY_SCALABLE,
               type = CommandType.BOOLEAN,
               description = "true if ISO contains XS/VMWare tools inorder to support dynamic scaling of VM CPU/memory")
    protected Boolean isDynamicallyScalable;

    @Parameter(name=ApiConstants.DIRECT_DOWNLOAD,
            type = CommandType.BOOLEAN,
            description = "true if ISO should bypass Secondary Storage and be downloaded to Primary Storage on deployment")
    private Boolean directDownload;

    @Parameter(name = ApiConstants.PASSWORD_ENABLED,
            type = CommandType.BOOLEAN,
            description = "true if password reset feature is supported; default is false")
    private Boolean passwordEnabled;

    /////////////////////////////////////////////////////
    /////////////////// Accessors ///////////////////////
    /////////////////////////////////////////////////////

    public Boolean isBootable() {
        return bootable;
    }

    public void setBootable(Boolean bootable) {
        this.bootable = bootable;
    }

    public String getDisplayText() {
        return displayText;
    }

    public void setDisplayText(String displayText) {
        this.displayText = displayText;
    }

    public Boolean isFeatured() {
        return featured;
    }

    public Boolean isPublic() {
        return publicIso;
    }

    public void setPublic(Boolean publicIso) {
        this.publicIso = publicIso;
    }

    public Boolean isExtractable() {
        return extractable;
    }

    public String getIsoName() {
        return isoName;
    }

    public void setIsoName(String isoName) {
        this.isoName = isoName;
    }

    public Long getOsTypeId() {
        return osTypeId;
    }

    public String getUrl() {
        return url;
    }

    public void setUrl(String url) {
        this.url = url;
    }

    public Long getZoneId() {
        return zoneId;
    }

    public void setZoneId(Long zoneId) {
        this.zoneId = zoneId;
    }

    public Long getDomainId() {
        return domainId;
    }

    public void setDomainId(Long domainId) {
        this.domainId = domainId;
    }

    public String getAccountName() {
        return accountName;
    }

    public void setAccountName(String accountName) {
        this.accountName = accountName;
    }

    public String getChecksum() {
        return checksum;
    }

    public void setChecksum(String checksum) {
        this.checksum = checksum;
    }

    public String getImageStoreUuid() {
        return imageStoreUuid;
    }

    public Boolean isDynamicallyScalable() {
        return isDynamicallyScalable ==  null ? Boolean.FALSE : isDynamicallyScalable;
    }

    public boolean isDirectDownload() {
        return directDownload == null ? false : directDownload;
    }

    public boolean isPasswordEnabled() {
        return passwordEnabled == null ? false : passwordEnabled;
    }

    /////////////////////////////////////////////////////
    /////////////// API Implementation///////////////////
    /////////////////////////////////////////////////////

    @Override
    public String getCommandName() {
        return s_name;
    }

    @Override
    public long getEntityOwnerId() {
        Long accountId = _accountService.finalyzeAccountId(accountName, domainId, projectId, true);
        if (accountId == null) {
            return CallContext.current().getCallingAccount().getId();
        }

        return accountId;
    }

    @Override
    public void execute() throws ResourceAllocationException {
        VirtualMachineTemplate template = _templateService.registerIso(this);
        if (template != null) {
            ListResponse<TemplateResponse> response = new ListResponse<TemplateResponse>();
            List<TemplateResponse> templateResponses = _responseGenerator.createIsoResponses(getResponseView(), template, zoneId, false);
            response.setResponses(templateResponses);
            response.setResponseName(getCommandName());
            setResponseObject(response);
        } else {
            throw new ServerApiException(ApiErrorCode.INTERNAL_ERROR, "Failed to register ISO");
        }

    }
}


text:
package io.github.mattthomson.depijp.cascading;

import cascading.flow.FlowProcess;
import cascading.operation.BaseOperation;
import cascading.operation.Function;
import cascading.operation.FunctionCall;
import cascading.tuple.Fields;
import cascading.tuple.Tuple;
import cascading.tuple.TupleEntry;
import io.github.mattthomson.depijp.KeyValue;

public class ToKeyValueFunction<K, V> extends BaseOperation<Void> implements Function<Void> {
    private final Fields keyField;
    private final Fields valueField;
    private final Fields outputField;

    public ToKeyValueFunction(Fields keyField, Fields valueField, Fields outputField) {
        super(2, outputField);

        this.keyField = keyField;
        this.valueField = valueField;
        this.outputField = outputField;
    }

    @Override
    public void operate(FlowProcess flowProcess, FunctionCall<Void> functionCall) {
        K key = (K) functionCall.getArguments().getObject(keyField);
        V value = (V) functionCall.getArguments().getObject(valueField);

        functionCall.getOutputCollector().add(new TupleEntry(outputField, new Tuple(new KeyValue<>(key, value))));
    }
}


text:
package com.fastame.formichella.lupusintabula;

import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.Button;

import static android.content.ContentValues.TAG;

public class chooseGame extends Activity {

    private Button signUpButton;
    private Button joinButton;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.choose_game_activity);
        View view = LayoutInflater.from(this).inflate(R.layout.choose_game_activity,null, false);
        setContentView(view);

        signUpButton = view.findViewById(R.id.createButton);
        signUpButton.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                Intent intent = new Intent(chooseGame.this, gameScreen.class);
                startActivity(intent);
            }
        });

        joinButton = view.findViewById(R.id.joinButton);
        joinButton.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                Intent intent = new Intent(chooseGame.this, gameScreen.class);
                startActivity(intent);
            }
        });
    }
}


text:
<?php
/**
 * Timelines controller integration tests.
 */
class TimelinesControllerTest extends NeatlineTime_Test_AppTestCase
{

    public function setUp()
    {

        parent::setUp();
        $timeline = $this->_createTimeline();

    }

    /**
     * Data provider for testRouting.
     */
    public static function routes()
    {
        return array(
            array('/neatline-time/timelines/browse', 'browse'),
            array('/neatline-time/timelines/add', 'add'),
            array('/neatline-time/timelines/show/1', 'show'),
            array('/neatline-time/timelines/edit/1', 'edit'),
            array('/neatline-time/timelines/query/1', 'query')
        );
    }

    /**
     * @dataProvider routes
     */
    public function testRouting($url, $action)
    {
        $this->dispatch($url);
        $this->assertController('timelines');
        $this->assertAction($action);
    }

}


text:
angular.module('angular-login.home', ['angular-login.grandfather'])
.config(function ($stateProvider) {
  $stateProvider
    .state('app.home', {
      url: '/',
      templateUrl: 'home/home.tpl.html',
      controller: 'HomeController'
    });
})
.controller('HomeController', function ($scope) {
  $scope.users = angular.fromJson(localStorage.getItem('userStorage'));
});


text:
/*
        map.heatLayers = {};

        map.createHeatLayer = function(data) {
            var pts = [];
            for (_i=0; _i < data.length; _i++) {
                var pt = [parseFloat(data[_i][0]),parseFloat(data[_i][1])];
                pts.push(pt);
            }
            var featureLayer = L.heatLayer(pts);
            //featureLayer.setOptions({radius: 15, blur: 20, maxZoom: 25});
            //featureLayer.setOptions({maxZoom: 12});
            return featureLayer;
        }

        map.getHeatLayer = function() {
            $.get(
                "http://" + baseURL + "/api/v1/layer/heat",
                {'uuid':$('#layers').val()},
                function(data,status){
                    if (status == 'success') {
                        var layer = map.updateHeatLayers(data);
                    }
                    else {
                        console.log(status);
                    }
                },
                "json"
            );
        }
        map.updateHeatLayers = function(data) {
            for (var _i in this.heatLayers){    // Remove old featurelayers
                if (this.hasLayer(this.heatLayers[_i])) {
                    this.removeLayer(this.heatLayers[_i]);
                }
            }
            this.heatLayers = {};    // Clear old featurelayers
            try {
                this.heatLayers[data.uuid] = this.createHeatLayer(data.geodata);    // Create new featurelayers
                this.heatLayers[data.uuid].addTo(this);    // Apply new featurelayers to map
            }
            catch(err) { console.log(err); }
        }

                    "baselayers": {
                        "Topographic": "http://services.arcgisonline.com/ArcGIS/rest/services/World_Topo_Map/MapServer/tile/{z}/{y}/{x}.png",
                        "Streets": "http://services.arcgisonline.com/ArcGIS/rest/services/World_Street_Map/MapServer/tile/{z}/{y}/{x}.png",
                        "Oceans": "http://services.arcgisonline.com/arcgis/rest/services/Ocean/World_Ocean_Base/MapServer/tile/{z}/{y}/{x}.png",
                        "NationalGeographic": "http://services.arcgisonline.com/ArcGIS/rest/services/NatGeo_World_Map/MapServer/tile/{z}/{y}/{x}.png",
                        "Gray": "http://services.arcgisonline.com/ArcGIS/rest/services/Canvas/World_Light_Gray_Base/MapServer/tile/{z}/{y}/{x}.png",
                        "DarkGray": "http://services.arcgisonline.com/ArcGIS/rest/services/Canvas/World_Dark_Gray_Base/MapServer/tile/{z}/{y}/{x}.png",
                        "Imagery": "http://services.arcgisonline.com/ArcGIS/rest/services/World_Imagery/MapServer/tile/{z}/{y}/{x}.png",
                        "ShadedRelief": "http://services.arcgisonline.com/ArcGIS/rest/services/World_Shaded_Relief/MapServer/tile/{z}/{y}/{x}.png",
                        "Terrain": "http://services.arcgisonline.com/ArcGIS/rest/services/World_Terrain_Base/MapServer/tile/{z}/{y}/{x}.png",
                        "World at Night": "https://tiles2.arcgis.com/tiles/P3ePLMYs2RVChkJx/arcgis/rest/services/Earth_at_Night_WM/MapServer/tile/{z}/{y}/{x}"
                    },
                    "overlays": {
                        "None": null,
                        "World Transportation":"https://services.arcgisonline.com/ArcGIS/rest/services/Reference/World_Transportation/MapServer/tile/{z}/{y}/{x}",
                        "LandScan World 2010 Population":"https://utility.arcgis.com/usrsvcs/rest/services/5864fa4352d34c859bd5fa4c0344f500/MapServer/tile/{z}/{y}/{x}"
                    //    ,
                    //    "tilestache": config.tilestache
                    },
                    "labels": {
                        "None": null,
                        "OceansLabels": "http://services.arcgisonline.com/arcgis/rest/services/Ocean/World_Ocean_Reference/MapServer/tile/{z}/{y}/{x}.png",
                        "GrayLabels": "http://services.arcgisonline.com/ArcGIS/rest/services/Canvas/World_Light_Gray_Reference/MapServer/tile/{z}/{y}/{x}.png",
                        "DarkGrayLabels": "http://services.arcgisonline.com/ArcGIS/rest/services/Canvas/World_Dark_Gray_Reference/MapServer/tile/{z}/{y}/{x}.png",
                        "ImageryLabels": "http://services.arcgisonline.com/ArcGIS/rest/services/Reference/World_Boundaries_and_Places/MapServer/tile/{z}/{y}/{x}.png",
                        "ShadedReliefLabels": "http://services.arcgisonline.com/ArcGIS/rest/services/Reference/World_Boundaries_and_Places_Alternate/MapServer/tile/{z}/{y}/{x}.png",
                        "TerrainLabels": "http://services.arcgisonline.com/ArcGIS/rest/services/Reference/World_Reference_Overlay/MapServer/tile/{z}/{y}/{x}.png"
                    }

*/


text:
describe('javascript', function () {
    it('should have global objects that match the protractor namespace', function () {
        expect(protractor.browser === browser).toBeTruthy();
        expect(protractor.by === by).toBeTruthy();
        expect(protractor.By === By).toBeTruthy();
        expect(protractor.$ === $).toBeTruthy();
        expect(protractor.$$ === $$).toBeTruthy();
        expect(protractor.ExpectedConditions === ExpectedConditions).toBeTruthy();
    });
    it('should have selenium-webdriver components for the protractor namespace', function () {
        // expect(typeof protractor.promise.all).toEqual('function');
        // expect(typeof protractor.promise.defer).toEqual('function');
        // expect(typeof protractor.promise.Promise).toEqual('function');
        // expect(typeof protractor.ActionSequence).toEqual('function');
        expect(typeof protractor.Browser).toEqual('object');
        expect(typeof protractor.Builder).toEqual('function');
        expect(typeof protractor.Capabilities).toEqual('function');
        expect(typeof protractor.Capability).toEqual('object');
        // expect(typeof protractor.EventEmitter).toEqual('function');
        expect(typeof protractor.FileDetector).toEqual('function');
        expect(typeof protractor.Key).toEqual('object');
        expect(typeof protractor.Session).toEqual('function');
        expect(typeof protractor.WebDriver).toEqual('function');
        expect(typeof protractor.WebElement).toEqual('function');
        expect(typeof protractor.WebElementPromise).toEqual('function');
        expect(typeof protractor.error).toEqual('object');
        expect(typeof protractor.logging).toEqual('object');
        expect(typeof protractor.promise).toEqual('object');
        expect(typeof protractor.until).toEqual('object');
        expect(typeof protractor.Command).toEqual('function');
        expect(typeof protractor.CommandName).toEqual('object');
        expect(typeof protractor.utils.firefox).toEqual('object');
        expect(typeof protractor.utils.http).toEqual('object');
        expect(typeof protractor.utils.remote).toEqual('object');
    });
    it('should have protractor class definitions', function () {
        expect(typeof protractor.ProtractorBrowser).toBe('function');
        expect(typeof protractor.ElementFinder).toBe('function');
        expect(typeof protractor.ElementArrayFinder).toBe('function');
        expect(typeof protractor.ProtractorBy).toBe('function');
        expect(typeof protractor.ProtractorExpectedConditions).toBe('function');
    });
});


text:
export interface AgTreeGridOptions {

  autoGroupColumnDef?: any;

  columnDefs?: any[];

  rowData?: any[];

  nodesRequest?: Promise<any>;

}


text:
/* eslint no-console:0 */
/**
 * browser
 *
 * Authors:
 *   大果 <liuxiong.lx@alibaba-inc.com>
 */

'use strict';

/**
 * Module dependencies.
 */
var path = require('path');
var exec = require('child_process').exec;
var Promise = require('bluebird');
var request = require('request');
var _ = require('lodash');
var debug = require('debug')('browser:browser');
var chalk = require('chalk');
var getPort = require('get-port');

var codes = require('./codes');

/**
 * Module exports
 */
module.exports = Browser;

function Browser(cfg) {

  this.cfg = cfg;
  this.name = cfg.name;
  this.port = cfg.port || Math.floor(Math.random() * (10000 - 1000) + 1000);
  // 执行 js 默认的等待时间
  this.timeout = cfg.timeout || 1 * 60 * 1000;
}

/**
 * 打开浏览器之前,获取端口号等
 */
Browser.prototype._prepare = function() {

  var self = this;
  var cfg = this.cfg;
  var getFreePort = cfg.port ? Promise.resolve(cfg.port) : getPort();

  return getFreePort.then(function(port) {
    self.port = port;
    self.hostname = '127.0.0.1';
    self.href = 'http://' + self.hostname + ':' + self.port;

    if (self.name === 'chrome') {
      self.options = ' --port=' + self.port;
      var cmds = {
        darwin: path.resolve(__dirname, '../driver/chromedriver-darwin'),
        win32: path.resolve(__dirname, '../driver/chromedriver.exe')
      };
    } else if (self.name === 'phantomjs') {
      self.options = ' --webdriver=' + self.port;
      var cmds = {
        darwin: path.resolve(__dirname, '../driver/phantomjs-darwin'),
        win32: path.resolve(__dirname, '../driver/phantomjs.exe'),
        linux: path.resolve(__dirname, '../driver/phantomjs-linux')
      };
    } else if (self.name === 'ie') {
      self.options = ' --port' + self.port;
      var cmds = {
        win32: path.resolve(__dirname, '../driver/IEDriverServer.exe')
      };
    } else if (self.name === 'firefox') {
      // 暂不支持
      self.options = ' --port=' + self.port;
      var cmds = {
        darwin: '/Applications/Firefox.app/Contents/MacOS/firefox-bin',
        win32: '%PROGRAMFILES%\Mozilla Firefox\firefox.exe',
        linux: 'fiefox'
      };

    } else {
      console.log(chalk.yellow('不支持 %s 浏览器', self.name));
    }

    self.cmd = cmds[process.platform];

    if (cfg.options) {
      self.options = self.options + ' ' + cfg.options;
    }
    return;
  });

};

/**
 * @private: Browser post method
 *
 * @param  {string}   path     request path
 * @param  {obj}      data     body data
 */
Browser.prototype._post = function(reqPath, data) {

  var self = this;

  debug(reqPath);

  var options = {
    url: self.href + reqPath,
    form: JSON.stringify(data),
    json: true,
    headers: {
      'Content-Type': 'application/json',
      'Content-Length': Buffer.byteLength(JSON.stringify(data), 'utf8')
    }
  };

  return new Promise(function(resolve, reject) {
    request.post(options, function(err, res, body) {
      if (err) {
        reject(err);
      } else {

        if (body.status == 0) {
          return resolve(body);
        } else {
          return reject(new Error(JSON.stringify(codes[body.status])));
        }
      }
    });
  });
};

/**
 * @private: create session
 */
Browser.prototype._getSessionId = function() {

  var self = this;
  var data = {};

  var desiredCapabilities = {
    browserName: self.name,
    version: '',
    platform: 'ANY',
    javascriptEnabled: true,
    acceptSslCerts: true,
    takesScreenshot: true
  };

  data.desiredCapabilities = _.defaults(self.cfg.desiredCapabilities || {}, desiredCapabilities);
  return self._post('/session', data);
};

/**
 * @private: open webdriver by shell
 */
Browser.prototype._create = function() {

  var self = this;

  var cmd = self.cmd;
  var options = self.options;
  var isCreated = false;

  debug('Open driver: ', cmd, options);

  return new Promise(function(resolve, reject) {

    function getSessionId() {
      self._getSessionId().then(function(data) {

        debug('get sessionId:', data);

        if (data.status != 0) {
          reject(new Error('创建 sessionId 出错:' + data.value.message));
        }

        resolve(data);
      }).catch(function(err) {
        reject(err);
      });
    }

    self.process = exec(cmd + options);
    var timer = setTimeout(function() {
      // 超时的情况,有可能是已经启动,则直接执行之
      console.error('启动 webdriver 超时,尝试请求');
      clearTimeout(timer);

      if (!isCreated) {
        getSessionId();
      }

    }, 6 * 1000);

    self.process.stderr.on('err', function(err) {
      console.error(chalk.red(err));
    });

    self.process.stdout.on('data', function(data) {
      debug('webdriver 启动日志:', data.toString());
      // 启动成功
      if (/on port/ig.test(data.toString())) {
        clearTimeout(timer);
        if (!isCreated) {
          getSessionId();
        }
      }
    });
  });
};

/**
 * open url with browser
 *
 * @param {string} url
 */
Browser.prototype.open = function(url) {

  var self = this;

  return self._prepare().then(function() {
    return self._create();
  }).then(function(data) {

    self.sessionId = data.sessionId;
    var data = {url: url};
    var reqPath = '/session/' + self.sessionId + '/url';

    return self._post(reqPath, data);
  });
};

/**
 * close webdriver
 */
Browser.prototype.close = function() {

  var self = this;
  var options = {
    url: self.href + '/session/' + self.sessionId,
    method: 'DELETE'
  };

  return new Promise(function(resolve, reject) {
    request(options, function(err, res, body) {
      self.process && self.process.kill();
      err ? reject(err) : resolve(body);
    });

  });
};

/**
 * @private: 设置执行 js 允许的等待时间
 */
Browser.prototype._setTimeout = function() {
  var reqPath = '/session/' + this.sessionId + '/timeouts/async_script';
  var data = {ms: this.timeout};
  return this._post(reqPath, data);
};

/**
 * 注入执行 js
 * @param  {string}   script  content
 */
Browser.prototype.injectJs = function(script) {

  var self = this;

  return self._setTimeout().then(function() {
    script = 'var endCallback = arguments[arguments.length - 1];' + script;
    var data = {script: script, args: []};
    var reqPath = '/session/' + self.sessionId + '/execute_async';
    return self._post(reqPath, data);
  });
};

/**
 * 自动登录
 *
 * @param  {string}   name     用户名
 * @param  {string}   pwd      密码
 */
Browser.prototype.login = function(name, pwd) {

  var self = this;
  // 参数需要双引号引起来
  var script = '(' + login.script.toString() + ')("' + name + '","' + pwd + '");';
  return self.injectJs(script);
};

/**
 * refresh page
 *
 * @param {string} url
 */
Browser.prototype.refresh = function() {
  var reqPath = '/session/' + this.sessionId + '/refresh';
  return this._post(reqPath, {});
};

/**
 * resize page
 *
 * @param {string} url
 */
Browser.prototype.resize = function(width, height) {

  var data = {width: width, height: height};
  var reqPath = '/session/' + this.sessionId + '/window/current/size';
  return this._post(reqPath, data);
};

/**
 * Take a screenshot of the current page.
 *
 * @return {string} The screenshot as a base64 encoded PNG
 */
Browser.prototype.screenshot = function() {
  var self = this;
  var url = self.href + '/session/' + this.sessionId + '/screenshot';

  return new Promise(function(resolve, reject) {
    request({
      uri: url,
      json: true
    }, function(err, res, body) {
      err ? reject(err) : resolve(body);
    });
  });
};


text: React components based on [Rework Flex Grid](http://johnotander.com/rework-flex-grid/#css)