repo_name
stringlengths
5
108
path
stringlengths
6
333
size
stringlengths
1
6
content
stringlengths
4
977k
license
stringclasses
15 values
sait-berkeley-infosec/SecureMe
app/src/main/java/edu/berkeley/rescomp/secureme/ItemDetailFragment.java
3456
package edu.berkeley.rescomp.secureme; import android.app.ActionBar; import android.app.Activity; import android.content.Intent; import android.os.Bundle; import android.support.v4.app.Fragment; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.Button; import android.widget.FrameLayout; import android.widget.LinearLayout; import android.widget.TextView; import edu.berkeley.rescomp.secureme.checklist.SecurityChecklist; /** * A fragment representing a single Item detail screen. * This fragment is either contained in a {@link ItemListActivity} * in two-pane mode (on tablets) or a {@link ItemDetailActivity} * on handsets. */ public class ItemDetailFragment extends Fragment { /** * The fragment argument representing the item ID that this fragment * represents. */ public static final String ARG_ITEM_ID = "item_id"; /** * The content this fragment is presenting. */ private SecurityChecklist.SecurityItem mItem; /** * Mandatory empty constructor for the fragment manager to instantiate the * fragment (e.g. upon screen orientation changes). */ public ItemDetailFragment() { } @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); if (getArguments().containsKey(ARG_ITEM_ID)) { // Load the content specified by the fragment // arguments. In a real-world scenario, use a Loader // to load content from a content provider. mItem = SecurityChecklist.ITEM_MAP.get(getArguments().getString(ARG_ITEM_ID)); } } @Override public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { View rootView = inflater.inflate(R.layout.fragment_item_detail, container, false); // Show the content as text in a TextView. if (mItem != null) { Activity context = getActivity(); mItem.update(context); ((TextView) rootView.findViewById(R.id.item_detail)) .setText(context.getString(mItem.getDetailsId())); Button btnToNextScreen = (Button) rootView.findViewById(R.id.item_detail_button); if (mItem.getIntent() != null) { btnToNextScreen.setText(mItem.getButtonTextId()); btnToNextScreen.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { startActivity(new Intent(mItem.getIntent())); } }); if (btnToNextScreen.getVisibility() != View.VISIBLE) { btnToNextScreen.setVisibility(View.VISIBLE); } } else if (btnToNextScreen != null) { btnToNextScreen.setVisibility(View.GONE); } } return rootView; } @Override public void onResume() { super.onResume(); if (mItem != null) { Activity context = getActivity(); mItem.update(context); ((TextView) context.findViewById(R.id.item_detail)) .setText(context.getString(mItem.getDetailsId())); } } }
gpl-2.0
lamsfoundation/lams
3rdParty_sources/hibernate-core/org/hibernate/type/descriptor/java/NClobTypeDescriptor.java
4001
/* * Hibernate, Relational Persistence for Idiomatic Java * * License: GNU Lesser General Public License (LGPL), version 2.1 or later. * See the lgpl.txt file in the root directory or <http://www.gnu.org/licenses/lgpl-2.1.html>. */ package org.hibernate.type.descriptor.java; import java.io.Reader; import java.io.Serializable; import java.sql.NClob; import java.sql.SQLException; import java.util.Comparator; import org.hibernate.HibernateException; import org.hibernate.engine.jdbc.CharacterStream; import org.hibernate.engine.jdbc.NClobImplementer; import org.hibernate.engine.jdbc.NClobProxy; import org.hibernate.engine.jdbc.WrappedNClob; import org.hibernate.engine.jdbc.internal.CharacterStreamImpl; import org.hibernate.type.descriptor.WrapperOptions; /** * Descriptor for {@link java.sql.NClob} handling. * <p/> * Note, {@link java.sql.NClob nclobs} really are mutable (their internal state can in fact be mutated). We simply * treat them as immutable because we cannot properly check them for changes nor deep copy them. * * @author Steve Ebersole */ public class NClobTypeDescriptor extends AbstractTypeDescriptor<NClob> { public static final NClobTypeDescriptor INSTANCE = new NClobTypeDescriptor(); public static class NClobMutabilityPlan implements MutabilityPlan<NClob> { public static final NClobMutabilityPlan INSTANCE = new NClobMutabilityPlan(); public boolean isMutable() { return false; } public NClob deepCopy(NClob value) { return value; } public Serializable disassemble(NClob value) { throw new UnsupportedOperationException( "Clobs are not cacheable" ); } public NClob assemble(Serializable cached) { throw new UnsupportedOperationException( "Clobs are not cacheable" ); } } public NClobTypeDescriptor() { super( NClob.class, NClobMutabilityPlan.INSTANCE ); } @Override public String extractLoggableRepresentation(NClob value) { return value == null ? "null" : "{nclob}"; } public String toString(NClob value) { return DataHelper.extractString( value ); } public NClob fromString(String string) { return NClobProxy.generateProxy( string ); } @Override @SuppressWarnings({ "unchecked" }) public Comparator<NClob> getComparator() { return IncomparableComparator.INSTANCE; } @Override public int extractHashCode(NClob value) { return System.identityHashCode( value ); } @Override public boolean areEqual(NClob one, NClob another) { return one == another; } @SuppressWarnings({ "unchecked" }) public <X> X unwrap(final NClob value, Class<X> type, WrapperOptions options) { if ( value == null ) { return null; } try { if ( CharacterStream.class.isAssignableFrom( type ) ) { if ( NClobImplementer.class.isInstance( value ) ) { // if the incoming NClob is a wrapper, just pass along its BinaryStream return (X) ( (NClobImplementer) value ).getUnderlyingStream(); } else { // otherwise we need to build a BinaryStream... return (X) new CharacterStreamImpl( DataHelper.extractString( value.getCharacterStream() ) ); } } else if (NClob.class.isAssignableFrom( type )) { final NClob nclob = WrappedNClob.class.isInstance( value ) ? ( (WrappedNClob) value ).getWrappedNClob() : value; return (X) nclob; } } catch ( SQLException e ) { throw new HibernateException( "Unable to access nclob stream", e ); } throw unknownUnwrap( type ); } public <X> NClob wrap(X value, WrapperOptions options) { if ( value == null ) { return null; } // Support multiple return types from // org.hibernate.type.descriptor.sql.ClobTypeDescriptor if ( NClob.class.isAssignableFrom( value.getClass() ) ) { return options.getLobCreator().wrap( (NClob) value ); } else if ( Reader.class.isAssignableFrom( value.getClass() ) ) { Reader reader = (Reader) value; return options.getLobCreator().createNClob( DataHelper.extractString( reader ) ); } throw unknownWrap( value.getClass() ); } }
gpl-2.0
unscharf/Colegio
Colegio 19-08-15/src/InternalFrame/DetallesAsignaturas_profesor.java
6261
/* * 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. */ package InternalFrame; import Metodos.DAO; import java.awt.Color; import java.awt.Graphics; import java.util.ArrayList; import javax.swing.JOptionPane; import javax.swing.table.DefaultTableModel; import javax.swing.table.TableColumn; import javax.swing.table.TableRowSorter; import org.hibernate.SessionFactory; /** * * @author Blutharsch */ public final class DetallesAsignaturas_profesor extends javax.swing.JInternalFrame { DefaultTableModel dtm= new DefaultTableModel(){ @Override public boolean isCellEditable(int row, int column) { return false;} }; int Id; SessionFactory sf; String NProfesor; @Override protected void paintComponent(Graphics g){ g.setColor(new Color(255,255,255,64)); g.fillRect(0, 0, getWidth(), getHeight()); } /** * Creates new form DetallesAsignaturas_profesor * @param Id * @param sf * @param NProfesor */ public DetallesAsignaturas_profesor(int Id, SessionFactory sf, String NProfesor) { initComponents(); //Constructores this.Id=Id; this.sf=sf; this.NProfesor=NProfesor; //*****************************************************************// dtm.setColumnIdentifiers(new Object[]{"ID","Asignatura"}); jTable1.setModel(dtm); TableRowSorter rs= new TableRowSorter(dtm); jTable1.setRowSorter(rs); RenderTable(); this.setTitle("Profesor: "+NProfesor); txbNProfesor.setText(NProfesor); } public DetallesAsignaturas_profesor(){initComponents(); } public void CargarAsignaturas(int Id){ DAO d= new DAO(sf); ArrayList<Object[]> lista= DAO.CargarAsignaturas_profesor(Id); if(lista.isEmpty()){ JOptionPane.showMessageDialog(this,"Lista vacia");}else{ for (Object[] o: lista) { Object[] row= o; dtm.addRow(row); } } } public void RenderTable(){ TableColumn c= jTable1.getColumn("ID"); c.setMaxWidth(120); c.setMinWidth(70); CargarAsignaturas(Id); } public void LimpiarTabla(){ for(int i=dtm.getRowCount()-1;i>=0;i--){ dtm.removeRow(i); } } /** * 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() { jPanel1 = new javax.swing.JPanel(); jScrollPane1 = new javax.swing.JScrollPane(); jTable1 = new javax.swing.JTable(); jLabel1 = new javax.swing.JLabel(); txbNProfesor = new javax.swing.JLabel(); setClosable(true); setIconifiable(true); setMaximizable(true); jPanel1.setBackground(java.awt.SystemColor.activeCaption); jTable1.setModel(new javax.swing.table.DefaultTableModel( new Object [][] { }, new String [] { } )); jScrollPane1.setViewportView(jTable1); jLabel1.setFont(new java.awt.Font("Verdana", 0, 11)); // NOI18N jLabel1.setText("Asignaturas impartidas por:"); txbNProfesor.setFont(new java.awt.Font("Verdana", 0, 11)); // NOI18N txbNProfesor.setText("Nombre_profesor"); javax.swing.GroupLayout jPanel1Layout = new javax.swing.GroupLayout(jPanel1); jPanel1.setLayout(jPanel1Layout); jPanel1Layout.setHorizontalGroup( jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(jPanel1Layout.createSequentialGroup() .addContainerGap() .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addComponent(jScrollPane1, javax.swing.GroupLayout.PREFERRED_SIZE, 366, javax.swing.GroupLayout.PREFERRED_SIZE) .addGroup(jPanel1Layout.createSequentialGroup() .addComponent(jLabel1) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED) .addComponent(txbNProfesor))) .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)) ); jPanel1Layout.setVerticalGroup( jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, jPanel1Layout.createSequentialGroup() .addContainerGap(30, Short.MAX_VALUE) .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE) .addComponent(jLabel1) .addComponent(txbNProfesor)) .addGap(28, 28, 28) .addComponent(jScrollPane1, javax.swing.GroupLayout.PREFERRED_SIZE, 210, javax.swing.GroupLayout.PREFERRED_SIZE) .addGap(29, 29, 29)) ); javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane()); getContentPane().setLayout(layout); layout.setHorizontalGroup( layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addComponent(jPanel1, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE) ); layout.setVerticalGroup( layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addComponent(jPanel1, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE) ); pack(); }// </editor-fold>//GEN-END:initComponents // Variables declaration - do not modify//GEN-BEGIN:variables private javax.swing.JLabel jLabel1; private javax.swing.JPanel jPanel1; private javax.swing.JScrollPane jScrollPane1; private javax.swing.JTable jTable1; private javax.swing.JLabel txbNProfesor; // End of variables declaration//GEN-END:variables }
gpl-2.0
phrh/RBP
src/priority/gui/ParamPanel.java
16075
package priority.gui; import java.awt.BorderLayout; import java.awt.GridLayout; import java.awt.Dimension; import javax.swing.JRadioButton; import javax.swing.JPanel; import javax.swing.JTextField; import javax.swing.JSpinner; import javax.swing.BorderFactory; import javax.swing.ButtonGroup; import javax.swing.JLabel; import javax.swing.SpinnerNumberModel; import javax.swing.SpinnerModel; import javax.swing.DefaultListModel; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import java.io.File; import priority.Parameters; import priority.Strings; /** * ParamPanel - a panel for setting the parameters. * @author raluca */ class ParamPanel extends JPanel implements ActionListener { static final long serialVersionUID = 1; JPanel north, center, pathPanel, numberPanel; /* in north panel */ JTextField tfName; FilePanel tfFilePanel; JRadioButton fileTF, individualTF; ButtonGroup radioButtonGroup; /* in center->pathPanel */ JLabel pathData, pathBkgr, pathOutput; FilePanel dataFilePanel, bkgrFilePanel, outputFilePanel; /* in center->center */ PriorFilesPanel priorFilesPanel; SinglePriorFilePanel singlePriorFilePanel; /* in center->numberPanel */ JSpinner wsizeSpinner, iterationsSpinner, trialsSpinner, bkgrOrderSpinner; /** Creates and initilizes the components. */ public void init() { this.setLayout(new BorderLayout()); this.setBorder(BorderFactory.createEmptyBorder(5,0,0,5)); /* the north panel */ north = new JPanel(new GridLayout(4, 1, 0, 5)); north.setBorder(BorderFactory.createCompoundBorder( BorderFactory.createCompoundBorder( BorderFactory.createEmptyBorder(1,1,0,1), BorderFactory.createLoweredBevelBorder()), BorderFactory.createCompoundBorder( BorderFactory.createRaisedBevelBorder(), BorderFactory.createEmptyBorder(0,10,10,10))) ); north.setPreferredSize(new Dimension(190,125)); fileTF = new JRadioButton(Strings.getString("fileTF")); fileTF.setPreferredSize(new Dimension(60,20)); fileTF.setBorder(BorderFactory.createEmptyBorder(8,0,3,0)); fileTF.addActionListener(this); individualTF = new JRadioButton(Strings.getString("individualTF")); individualTF.setPreferredSize(new Dimension(60,20)); individualTF.setBorder(BorderFactory.createEmptyBorder(8,0,3,0)); individualTF.addActionListener(this); radioButtonGroup = new ButtonGroup(); radioButtonGroup.add(fileTF); radioButtonGroup.add(individualTF); tfFilePanel = new FilePanel(Parameters.tf_path, false); tfName = new JTextField(); tfName.setPreferredSize(new Dimension(60,20)); tfName.setBorder(BorderFactory.createCompoundBorder( BorderFactory.createLoweredBevelBorder(), BorderFactory.createEmptyBorder(0,5,0,5))); tfName.setText(Parameters.tf_name); if (Parameters.individualTF == false) { fileTF.setSelected(true); tfName.setEnabled(false); } else { individualTF.setSelected(true); tfFilePanel.setEnabled(false); } north.add(individualTF); north.add(tfName); north.add(fileTF); north.add(tfFilePanel); this.add(north, BorderLayout.NORTH); /* the center panel */ center = new JPanel(new BorderLayout()); this.add(center, BorderLayout.CENTER); /* the center->north panel (pathPanel) */ pathPanel = new JPanel(new GridLayout(6, 1, 0, 0)); pathPanel.setBorder(BorderFactory.createCompoundBorder( BorderFactory.createCompoundBorder( BorderFactory.createEmptyBorder(7,1,1,1), BorderFactory.createLoweredBevelBorder()), BorderFactory.createCompoundBorder( BorderFactory.createRaisedBevelBorder(), BorderFactory.createEmptyBorder(0,10,5,10))) ); pathPanel.setPreferredSize(new Dimension(70,170)); dataFilePanel = new FilePanel(Parameters.fname_path, true); bkgrFilePanel = new FilePanel(Parameters.back_file, false); outputFilePanel = new FilePanel(Parameters.path_output, true); pathData = new JLabel(Strings.getString("pathData")); pathData.setBorder(BorderFactory.createEmptyBorder(15,0,10,0)); pathBkgr = new JLabel(Strings.getString("pathBkgr")); pathBkgr.setBorder(BorderFactory.createEmptyBorder(15,0,10,0)); pathOutput = new JLabel(Strings.getString("pathOutput")); pathOutput.setBorder(BorderFactory.createEmptyBorder(15,0,10,0)); pathPanel.add(pathData); pathPanel.add(dataFilePanel); pathPanel.add(pathBkgr); pathPanel.add(bkgrFilePanel); pathPanel.add(pathOutput); pathPanel.add(outputFilePanel); center.add(pathPanel, BorderLayout.NORTH); /* the center->center panel */ priorFilesPanel = new PriorFilesPanel(); priorFilesPanel.setBorder(BorderFactory.createCompoundBorder( BorderFactory.createCompoundBorder( BorderFactory.createEmptyBorder(7,1,1,1), BorderFactory.createLoweredBevelBorder()), BorderFactory.createCompoundBorder( BorderFactory.createRaisedBevelBorder(), BorderFactory.createEmptyBorder(10,10,5,10))) ); singlePriorFilePanel = new SinglePriorFilePanel(); singlePriorFilePanel.setBorder(BorderFactory.createCompoundBorder( BorderFactory.createCompoundBorder( BorderFactory.createEmptyBorder(7,1,1,1), BorderFactory.createLoweredBevelBorder()), BorderFactory.createCompoundBorder( BorderFactory.createRaisedBevelBorder(), BorderFactory.createEmptyBorder(5,5,5,5))) ); if (Parameters.multiple_priors == false) { center.add(singlePriorFilePanel, BorderLayout.CENTER); } else { center.add(priorFilesPanel, BorderLayout.CENTER); } /* the center->south panel (numberPanel) */ numberPanel = new JPanel(new BorderLayout()); JPanel numberPanelCenter = new JPanel(new GridLayout(4, 1, 3, 5)); numberPanel.add(numberPanelCenter, BorderLayout.CENTER); JPanel numberPanelEast = new JPanel(new GridLayout(4, 1, 3, 5)); numberPanelEast.setBorder(BorderFactory.createEmptyBorder(0,5,0,5)); numberPanel.add(numberPanelEast, BorderLayout.EAST); numberPanel.setBorder(BorderFactory.createCompoundBorder( BorderFactory.createCompoundBorder( BorderFactory.createEmptyBorder(7,1,1,1), BorderFactory.createLoweredBevelBorder()), BorderFactory.createCompoundBorder( BorderFactory.createRaisedBevelBorder(), BorderFactory.createEmptyBorder(5,0,5,0))) ); wsizeSpinner = ParamPanel.createAndAddSpinner(numberPanelCenter, numberPanelEast, Strings.getString("wsizeSpinner"), Parameters.wsize, Parameters.wsizeMin, Parameters.wsizeMax); bkgrOrderSpinner = ParamPanel.createAndAddSpinner(numberPanelCenter, numberPanelEast, Strings.getString("bkgrOrderSpinner"), Parameters.bkgrOrder, Parameters.bkgrOrderMin, Parameters.bkgrOrderMax); trialsSpinner = ParamPanel.createAndAddSpinner(numberPanelCenter, numberPanelEast, Strings.getString("trialsSpinner"), Parameters.trials, 1, Integer.MAX_VALUE); iterationsSpinner = ParamPanel.createAndAddSpinner(numberPanelCenter, numberPanelEast, Strings.getString("iterationsSpinner"), Parameters.iter, 1, Integer.MAX_VALUE); center.add(numberPanel, BorderLayout.SOUTH); } /** Creates spinner, sets spinner properties and adds it to the panel. */ private static JSpinner createAndAddSpinner(JPanel panelLabel, JPanel panel, String label, int value, int min, int max) { SpinnerNumberModel model = new SpinnerNumberModel(value, min, max, 1); JSpinner spinner = new JSpinner(model); spinner.setPreferredSize(new Dimension(80,22)); spinner.setBorder(BorderFactory.createLoweredBevelBorder()); JLabel ll = new JLabel(label,JLabel.RIGHT); ll.setLabelFor(spinner); ((JSpinner.DefaultEditor)(spinner.getEditor())).getTextField(). setBorder(BorderFactory.createEmptyBorder(0,5,0,5)); panelLabel.add(ll); panel.add(spinner); return spinner; } /** Implements the actionPerformed function (from ActionListener) */ public void actionPerformed(ActionEvent ev) { if (ev.getSource() == fileTF) { tfName.setEnabled(false); tfFilePanel.setEnabled(true); return; } if (ev.getSource() == individualTF) { tfName.setEnabled(true); tfFilePanel.setEnabled(false); return; } } public void switchToSinglePrior() { center.remove(priorFilesPanel); center.add(singlePriorFilePanel, BorderLayout.CENTER); Parameters.multiple_priors = false; } public void switchToMultiplePriors() { center.remove(singlePriorFilePanel); center.add(priorFilesPanel, BorderLayout.CENTER); Parameters.multiple_priors = true; } /** Gets the values for all parameters from the widgets * in this panel, checks them and copies them into the * static members of the class Parameters. */ public String setParameterValues() { /* the number of iterations and number of trials are valid for sure */ /* we also set wsize and bkgrOrder (whether or not they are valid will be checked later) */ try { Parameters.trials = Integer.parseInt((String) ((JSpinner.DefaultEditor)trialsSpinner.getEditor()).getTextField().getText()); Parameters.iter = ((Number)((SpinnerModel)iterationsSpinner.getModel()).getValue()).intValue(); Parameters.wsize = Integer.parseInt((String) ((JSpinner.DefaultEditor)wsizeSpinner.getEditor()).getTextField().getText()); Parameters.bkgrOrder = Integer.parseInt((String) ((JSpinner.DefaultEditor)bkgrOrderSpinner.getEditor()).getTextField().getText()); } catch(Exception e) { System.out.println(e);/* it shouldn't get here (ever) */ } /* *********************************************************************************** */ /* the path for the output files: must be a writable directory */ String path = outputFilePanel.getText(); File dir = new File(path); if (!dir.exists()) { return "Error: the directory for the output files (\"" + path + "\") does not exist!"; } if (!dir.isDirectory()) { return "Error: the path for the output files (\"" + path + "\") is not a valid directory!"; } if (!dir.canWrite()) { return "Error: the directory for the output files (\"" + path + "\") is not writable!"; } Parameters.path_output = path; /* the bkgr model file: must be a readable file + the content will be checked later */ path = bkgrFilePanel.getText(); File file = new File(path); if (!file.exists()) { return "Error: the background model file (\"" + path + "\") does not exist!"; } if (!file.isFile()) { return "Error: the background model file (\"" + path + "\") is not a valid file!"; } if (!file.canRead()) { return "Error: the background model file (\"" + path + "\") is not readable!"; } Parameters.back_file = path; /* the path for the FASTA data files: must be a readable directory + check content later */ path = dataFilePanel.getText(); dir = new File(path); if (!dir.exists()) { return "Error: the directory for the FASTA files (\"" + path + "\") does not exist!"; } if (!dir.isDirectory()) { return "Error: the path for the FASTA files (\"" + path + "\") is not a valid directory!"; } if (!dir.canRead()) { return "Error: the directory for the FASTA files (\"" + path + "\") is not readable!"; } Parameters.fname_path = path; /* *********************************************************************************** */ /* next we check the content of the bkgr model file: it must have 4 or 4+4^2 or * 4+4^2+4^3 or ...+4^k lines, each line must be between 0 and 1 and each group of * four lines must add to 1 (or very close to 1) + the order must be <(k-1) */ /* the bkgr file name and the order are already set in the class Parameters, * so we don't need to send them !!!! */ String err = Parameters.readBackground(); if (err.compareTo("") != 0) { return err; } System.out.println("Background model... OK"); /* setting the TF names */ if (individualTF.isSelected()) { /*we apply the alg for a TF only */ Parameters.tf_name = (tfName.getText()).trim(); if (Parameters.tf_name.length() < 1) { tfName.requestFocus(); return "Error: the TF name field is empty!"; } Parameters.individualTF = true; Parameters.tf_names = null; Parameters.tf_names = new String[1]; Parameters.tf_names[0] = Parameters.tf_name; } else { /* we apply the alg to all the TFs in a file */ /* the TF names file must be a readable file */ path = tfFilePanel.getText(); file = new File(path); if (!file.exists()) { return "Error: the file with the TF names (\"" + path + "\") does not exist!"; } if (!file.isFile()) { return "Error: the file with the TF names (\"" + path + "\") is not a valid file!"; } if (!file.canRead()) { return "Error: the file with the TF names (\"" + path + "\") is not readable!"; } Parameters.tf_path = path; Parameters.individualTF = false; err = Parameters.read_TFnames(); if (err.compareTo("") != 0) { return err; } } /* next we have to check that for every TF there is a file in the data path * with the same name as the TF */ for (int i=0; i<Parameters.tf_names.length; i++) { path = Parameters.fname_path + "/" + Parameters.tf_names[i] + ".fasta"; file = new File(path); if (!file.exists()) { return "Error: the data file \"" + path + "\"\ncorresponding to the TF \"" + Parameters.tf_names[i] + "\" does not exist!"; } if (!file.isFile()) { return "Error: the data file \"" + path + "\"\ncorresponding to the TF \"" + Parameters.tf_names[i] + "\" is not a valid file!"; } if (!file.canRead()) { return "Error: the data file \"" + path + "\"\ncorresponding to the TF \"" + Parameters.tf_names[i] + "\" is not a readable file!"; } } /* *********************************************************************************** */ /* SET THE PRIOR INFORMATION */ /* first check single/multiple files */ if (Parameters.multiple_priors == false) { /* uniform or single prior */ Parameters.putative_class = -1; if (this.singlePriorFilePanel.uniformPrior.isSelected()) { Parameters.otherclass = true; Parameters.prior_dirs = new String[0]; } else { Parameters.otherclass = false; Parameters.prior_dirs = new String[1]; Parameters.prior_dirs[0] = this.singlePriorFilePanel.priorFilePanel.getText(); } } else { /* multiple priors */ /* set the putative class and the "other class"-flag */ if (priorFilesPanel.putativeClassCheckbox.isSelected()) { Parameters.putative_class = ((DefaultListModel)priorFilesPanel.classList.getModel()). indexOf(priorFilesPanel.putativeClassText.getText()); } else { Parameters.putative_class = -1; } Parameters.otherclass = priorFilesPanel.otherClassCheckbox.isSelected(); /* now the class names will be copied in Parameters.prior_dirs */ int n; if (Parameters.otherclass) { n = priorFilesPanel.classListModel.size() - 1; } else { n = priorFilesPanel.classListModel.size(); } Parameters.prior_dirs = new String[n]; for (int i=0;i<n;i++) { Parameters.prior_dirs[i] = (String)priorFilesPanel.classListModel.getElementAt(i); } } /* Each entry in Parameters.prior_dirs (if such entries exist) must be the name * of a readable directory. */ for (int i=0; i<Parameters.prior_dirs.length; i++) { dir = new File(Parameters.prior_dirs[i]); if ((!dir.exists()) || (!dir.isDirectory()) || (!dir.canRead())) { return "Error: the prior directory: \"" + Parameters.prior_dirs[i] + "\" does not exist or is not readable!"; } } if (err.compareTo("") != 0) { return err; } System.out.println("Prior files (" + Parameters.prior_dirs.length + ")... OK"); return ""; } }
gpl-2.0
boetersep/p2km.nl
p2000decoder/src/main/java/cc/boeters/p2000decoder/source/model/area/Province.java
2538
package cc.boeters.p2000decoder.source.model.area; import java.util.ArrayList; import java.util.List; import javax.xml.bind.annotation.XmlAccessType; import javax.xml.bind.annotation.XmlAccessorType; import javax.xml.bind.annotation.XmlAttribute; import javax.xml.bind.annotation.XmlElement; import javax.xml.bind.annotation.XmlID; import javax.xml.bind.annotation.XmlIDREF; import javax.xml.bind.annotation.adapters.XmlJavaTypeAdapter; import com.fasterxml.jackson.annotation.JsonIgnore; import com.fasterxml.jackson.annotation.JsonProperty; import com.google.common.base.Objects; import jersey.repackaged.com.google.common.base.MoreObjects; @XmlAccessorType(XmlAccessType.FIELD) public class Province extends Area<Municipality> { @XmlID @XmlAttribute @XmlJavaTypeAdapter(AreaIdAdapter.class) private Integer id; @XmlAttribute private String name; @XmlAttribute @XmlIDREF private Country country; @JsonIgnore @XmlElement(name = "municipality") private List<Municipality> municipalities; public Province() { municipalities = new ArrayList<Municipality>(); } @Override public Integer getId() { return id; } public void setId(Integer id) { this.id = id; } public void setName(String name) { this.name = name; } @Override public String getName() { return name; } @JsonIgnore public List<Municipality> getMunicipalities() { return municipalities; } public void setCountry(Country country) { this.country = country; } @JsonProperty public void setMunicipalities(List<Municipality> municipalities) { this.municipalities = municipalities; } @Override public Country getCoveringArea() { return null; } public Country getCountry() { return country; } @Override public String toString() { return MoreObjects.toStringHelper(this).add("id", id).add("name", name).add("municipalities", municipalities) .toString(); } @Override public int hashCode() { return Objects.hashCode(id, name); } @Override public boolean equals(Object obj) { if (obj == null) { return false; } if (getClass() != obj.getClass()) { return false; } final Province other = (Province) obj; return Objects.equal(this.id, other.id) && Objects.equal(this.name, other.name); } public Municipality getMunicipalityById(Integer id) { for (Municipality municipality : municipalities) { if (id.equals(municipality.getId())) { return municipality; } } return null; } @Override public List<Municipality> getSubAreas() { return getMunicipalities(); } }
gpl-2.0
tommythorn/yari
shared/cacao-related/phoneme_feature/midp_abb/src/classes/javax/microedition/media/Manager.java
6747
/* * Copyright 1990-2006 Sun Microsystems, Inc. All Rights Reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License version * 2 only, as published by the Free Software Foundation. * * This program is distributed in the hope that it will be useful, but * WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * General Public License version 2 for more details (a copy is * included at /legal/license.txt). * * You should have received a copy of the GNU General Public License * version 2 along with this work; if not, write to the Free Software * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA * 02110-1301 USA * * Please contact Sun Microsystems, Inc., 4150 Network Circle, Santa * Clara, CA 95054 or visit www.sun.com if you need additional * information or have any questions. */ package javax.microedition.media; import java.util.Vector; import java.io.IOException; import java.io.InputStream; import java.util.Enumeration; import java.util.Hashtable; import com.sun.mmedia.TonePlayer; import com.sun.mmedia.Configuration; import com.sun.mmedia.ABBBasicPlayer; /** * This class is defined by the JSR-135 specification * <em>Mobile Media API, * Version 1.2.</em> */ // JAVADOC COMMENT ELIDED public final class Manager { private static Configuration config = Configuration.getConfiguration(); private static TonePlayer tonePlayer; private static Object createLock = new Object(); // JAVADOC COMMENT ELIDED public final static String TONE_DEVICE_LOCATOR = "device://tone"; private final static String DS_ERR = "Cannot create a DataSource for: "; private final static String PL_ERR = "Cannot create a Player for: "; private final static String REDIRECTED_MSG = " with exception message: "; /** * This private constructor keeps anyone from actually * getting a <CODE>Manager</CODE>. */ private Manager() { } // JAVADOC COMMENT ELIDED public static String[] getSupportedContentTypes(String protocol) { return config.getSupportedContentTypes(protocol); } // JAVADOC COMMENT ELIDED public static String[] getSupportedProtocols(String content_type) { return config.getSupportedProtocols(content_type); } // JAVADOC COMMENT ELIDED public static Player createPlayer(String locator) throws IOException, MediaException { if (locator == null) { throw new IllegalArgumentException(); } String locStr = locator.toLowerCase(); String validLoc; if (locStr.equals(validLoc = TONE_DEVICE_LOCATOR)) { ABBBasicPlayer p; // separate device & encodings int encInd = locator.indexOf('?'); String encStr = null; if (encInd > 0) { encStr = locator.substring(encInd + 1); locStr = locStr.substring(0, encInd); /* * TBD: check case when '?' is the last Locator symbol: *Will encStr be == "", or it will be == null ? */ } else { /* * detect invalid locator case: * if no '?' found then locStr & validLoc shall be * equivalent strings, but since they have already passed * char-to-char comparison, we to check lengths only... */ if (locStr.length() != validLoc.length()) throw new MediaException("Malformed locator"); encStr = ""; } String className = config.getHandler(locStr); try { // Try and instance the player .... Class protoClass = Class.forName(className); p = (ABBBasicPlayer) protoClass.newInstance(); // Pass encStr to created Player as argument if (!p.initFromURL(encStr)) { throw new MediaException("Invalid locator media encodings"); }; //System.out.println("DEBUG: Manager.createPlayer(" + locator + ") returned#1 " + p); return p; } catch (Exception e) { throw new MediaException(PL_ERR + locator + REDIRECTED_MSG + e.getMessage()); } } else { // not in the list of predefined locators, // find handler by extension String theProtocol = null; int idx = locStr.indexOf(':'); if (idx != -1) { theProtocol = locStr.substring(0, idx); } else { throw new MediaException("Malformed locator"); } String[] supported = getSupportedProtocols(config.ext2Mime(locStr)); boolean found = false; for (int i = 0; i < supported.length; i++) { if (theProtocol.equals(supported[i])) { found = true; break; } } if (!found) { throw new MediaException(PL_ERR + locator); } Player pp = null; throw new MediaException("Not supported"); //System.out.println("DEBUG: Manager.createPlayer(" + locator + ") returned#2 " + pp); // return pp; } } // JAVADOC COMMENT ELIDED public static Player createPlayer(InputStream stream, String type) throws IOException, MediaException { if (stream == null) { throw new IllegalArgumentException(); } if (type == null) { throw new MediaException(PL_ERR + "NULL content-type"); } throw new MediaException("Not supported"); } // JAVADOC COMMENT ELIDED public static void playTone(int note, int duration, int volume) throws MediaException { if (note < 0 || note > 127 || duration <= 0) { throw new IllegalArgumentException("bad param"); } if (duration == 0 || volume == 0) { return; } synchronized(createLock) { if (tonePlayer == null) { tonePlayer = config.getTonePlayer(); } } if (tonePlayer != null) { tonePlayer.playTone(note, duration, volume); } else { throw new MediaException("no tone player"); } } }
gpl-2.0
tkdiooo/sfsctech
common-parent/common-data/common-data-mybatis/src/main/java/com/sfsctech/data/mybatis/dao/IBaseDao.java
2971
package com.sfsctech.data.mybatis.dao; import com.github.pagehelper.PageInfo; import com.sfsctech.core.base.domain.model.PagingInfo; import java.io.Serializable; import java.util.List; /** * Class IBaseDao * * @author 张麒 2017/6/30. * @version Description: */ public interface IBaseDao<T, PK extends Serializable, Example> { /** * This method was generated by MyBatis Generator. */ List<T> selectByExample(Example example); /** * This method was generated by MyBatis Generator. */ T selectByPrimaryKey(PK key); /** * This method was generated by MyBatis Generator for Cache. */ T selectByPrimaryKeyForCache(PK key); /** * This method was generated by MyBatis Generator. */ int deleteByPrimaryKey(PK key); /** * This method was generated by MyBatis Generator for Cache. */ int deleteByPrimaryKeyForCache(PK key); /** * This method was generated by MyBatis Generator. */ int deleteByExample(Example example); /** * This method was generated by MyBatis Generator for Cache. */ int deleteByExampleForCache(Example example); /** * This method was generated by MyBatis Generator. */ int insert(T model); /** * This method was generated by MyBatis Generator for Cache. */ int insertForCache(T model); /** * This method was generated by MyBatis Generator. */ int insertSelective(T model); /** * This method was generated by MyBatis Generator for Cache. */ int insertSelectiveForCache(T model); /** * This method was generated by MyBatis Generator. */ long countByExample(Example example); /** * This method was generated by MyBatis Generator. */ int updateByExampleSelective(T model, Example example); /** * This method was generated by MyBatis Generator for Cache. */ int updateByExampleSelectiveForCache(T model, Example example); /** * This method was generated by MyBatis Generator. */ int updateByExample(T model, Example example); /** * This method was generated by MyBatis Generator for Cache. */ int updateByExampleForCache(T model, Example example); /** * This method was generated by MyBatis Generator. */ int updateByPrimaryKeySelective(T model); /** * This method was generated by MyBatis Generator for Cache. */ int updateByPrimaryKeySelectiveForCache(T model); /** * This method was generated by MyBatis Generator. */ int updateByPrimaryKey(T model); /** * This method was generated by MyBatis Generator for Cache. */ int updateByPrimaryKeyForCache(T model); boolean checkUnique(Example example, String fieldName, Object condition); PageInfo<T> queryPagination(int pageNum, int pageSize, Example example); PageInfo<T> queryPagination(PagingInfo<T> paging); }
gpl-2.0
leonardocintra/FormacaoJavaManoelJailton
PlataformaAntiga/Estrutura de Dados/src/br/com/mjailton/AulaListaEncadeada/ListaEncadeada.java
1851
package br.com.mjailton.AulaListaEncadeada; public class ListaEncadeada <E> { private Nodo primeiro; private Nodo ultimo; private int totalDeObjetos; // Insere um objeto no começo da lista public void inserirNoComeco(E objeto){ Nodo novoNodo = new Nodo(primeiro, objeto); primeiro = novoNodo; if (totalDeObjetos == 0) { ultimo = primeiro; } totalDeObjetos++; } // Insere um objeto no final da lista public void inserir(E objeto){ if(totalDeObjetos == 0){ inserirNoComeco(objeto); } else{ Nodo novoNodo = new Nodo(objeto); ultimo.setProximo(novoNodo); ultimo = novoNodo; totalDeObjetos++; } } public void inserir(int posicao, E objeto){ if(posicao == 0) inserirNoComeco(objeto); else if (posicao == totalDeObjetos) { inserir(objeto); } else { Nodo anterior = pegaNodo(posicao - 1); Nodo novoNodo = new Nodo(anterior.getProximo(), objeto); anterior.setProximo(novoNodo); totalDeObjetos++; } } private boolean posicaoPreenchida(int posicao){ if(posicao >= 0 && posicao < totalDeObjetos) return true; else return false; } private Nodo pegaNodo(int posicao){ if(!posicaoPreenchida(posicao)) throw new IllegalArgumentException("Esta posição não é valida"); Nodo atual = primeiro; for (int i = 0; i < posicao; i++) { atual = atual.getProximo(); } return atual; } public E verObjeto(int posicao){ if(!posicaoPreenchida(posicao)) throw new IllegalArgumentException("Essa posição não esta preenchida"); return (E)pegaNodo(posicao).getObjeto(); } public int tamanhoDaLista(){ return totalDeObjetos; } public void removerDoComeco(){ if(!posicaoPreenchida(0)) throw new IllegalArgumentException("Essa posição não esta preenchida"); primeiro = primeiro.getProximo(); totalDeObjetos--; } }
gpl-2.0
MER-GROUP/JavaRushHomeWork
src/socket/HttpServer005.java
2624
package socket; import java.io.BufferedReader; import java.io.InputStream; import java.io.InputStreamReader; import java.io.OutputStream; import java.net.ServerSocket; import java.net.Socket; /** * Created by M.E.R.lin on 11.12.2015. */ public class HttpServer005 { public static void main(String[] args) throws Throwable { ServerSocket serverSocket=new ServerSocket(8080); while (true){ System.out.println("Server started"); Socket socket=serverSocket.accept(); System.out.println("Client accepted"); new Thread(new SocketProcessor(socket)).start(); } } private static class SocketProcessor implements Runnable{ private Socket socket; private InputStream inputStream; private OutputStream outputStream; public SocketProcessor(Socket socket) throws Throwable { this.socket = socket; this.inputStream=socket.getInputStream(); this.outputStream=socket.getOutputStream(); } private void ReadInputHeaders() throws Throwable{ BufferedReader bufferedReader=new BufferedReader(new InputStreamReader(inputStream)); while (true){ String stringMessage=bufferedReader.readLine(); System.out.println("stringMessage = "+stringMessage); if (stringMessage==null || stringMessage.trim().length()==0){ break; } } } private void WriteResponse(String stringMessage) throws Throwable{ String stringResponse="HTTP/1.1 200 OK\r\n"+ "Server : MaxRamanenkaServer/2015-11-15\r\n"+ "Content-Type : text/html\r\n"+ "Content-Length : "+stringMessage.length()+"\r\n"+ "Connection : close\r\n\r\n"; String stringResult=stringResponse+" "+stringMessage; outputStream.write(stringResult.getBytes()); outputStream.flush(); } @Override public void run() { try{ ReadInputHeaders(); WriteResponse("<html><body><h1>Hello from Max Ramanenka</h1></body></html>"); }catch (Throwable t){ //do nothing }finally { try{ socket.close(); }catch (Throwable t){ //do nothing } } System.err.println("Client processing finished"); } } }
gpl-2.0
profosure/porogram
TMessagesProj/src/main/java/com/porogram/profosure1/tgnet/SerializedData.java
12249
/* * This is the source code of Telegram for Android v. 3.x.x. * It is licensed under GNU GPL v. 2 or later. * You should have received a copy of the license in this archive (see LICENSE). * * Copyright Nikolai Kudashov, 2013-2017. */ package com.porogram.profosure1.tgnet; import com.porogram.profosure1.messenger.FileLog; import java.io.ByteArrayInputStream; import java.io.ByteArrayOutputStream; import java.io.DataInputStream; import java.io.DataOutputStream; import java.io.File; import java.io.FileInputStream; public class SerializedData extends AbstractSerializedData { protected boolean isOut = true; private ByteArrayOutputStream outbuf; private DataOutputStream out; private ByteArrayInputStream inbuf; private DataInputStream in; private boolean justCalc = false; private int len; public SerializedData() { outbuf = new ByteArrayOutputStream(); out = new DataOutputStream(outbuf); } public SerializedData(boolean calculate) { if (!calculate) { outbuf = new ByteArrayOutputStream(); out = new DataOutputStream(outbuf); } justCalc = calculate; len = 0; } public SerializedData(int size) { outbuf = new ByteArrayOutputStream(size); out = new DataOutputStream(outbuf); } public SerializedData(byte[] data) { isOut = false; inbuf = new ByteArrayInputStream(data); in = new DataInputStream(inbuf); len = 0; } public void cleanup() { try { if (inbuf != null) { inbuf.close(); inbuf = null; } } catch (Exception e) { FileLog.e(e); } try { if (in != null) { in.close(); in = null; } } catch (Exception e) { FileLog.e(e); } try { if (outbuf != null) { outbuf.close(); outbuf = null; } } catch (Exception e) { FileLog.e(e); } try { if (out != null) { out.close(); out = null; } } catch (Exception e) { FileLog.e(e); } } public SerializedData(File file) throws Exception { FileInputStream is = new FileInputStream(file); byte[] data = new byte[(int)file.length()]; new DataInputStream(is).readFully(data); is.close(); isOut = false; inbuf = new ByteArrayInputStream(data); in = new DataInputStream(inbuf); } public void writeInt32(int x) { if (!justCalc) { writeInt32(x, out); } else { len += 4; } } private void writeInt32(int x, DataOutputStream out) { try { for(int i = 0; i < 4; i++) { out.write(x >> (i * 8)); } } catch(Exception e) { FileLog.e("write int32 error"); } } public void writeInt64(long i) { if (!justCalc) { writeInt64(i, out); } else { len += 8; } } private void writeInt64(long x, DataOutputStream out) { try { for(int i = 0; i < 8; i++) { out.write((int)(x >> (i * 8))); } } catch(Exception e) { FileLog.e("write int64 error"); } } public void writeBool(boolean value) { if (!justCalc) { if (value) { writeInt32(0x997275b5); } else { writeInt32(0xbc799737); } } else { len += 4; } } public void writeBytes(byte[] b) { try { if (!justCalc) { out.write(b); } else { len += b.length; } } catch (Exception e) { FileLog.e("write raw error"); } } public void writeBytes(byte[] b, int offset, int count) { try { if (!justCalc) { out.write(b, offset, count); } else { len += count; } } catch (Exception e) { FileLog.e("write bytes error"); } } public void writeByte(int i) { try { if (!justCalc) { out.writeByte((byte) i); } else { len += 1; } } catch (Exception e) { FileLog.e("write byte error"); } } public void writeByte(byte b) { try { if (!justCalc) { out.writeByte(b); } else { len += 1; } } catch (Exception e) { FileLog.e("write byte error"); } } public void writeByteArray(byte[] b) { try { if (b.length <= 253) { if (!justCalc) { out.write(b.length); } else { len += 1; } } else { if (!justCalc) { out.write(254); out.write(b.length); out.write(b.length >> 8); out.write(b.length >> 16); } else { len += 4; } } if (!justCalc) { out.write(b); } else { len += b.length; } int i = b.length <= 253 ? 1 : 4; while((b.length + i) % 4 != 0) { if (!justCalc) { out.write(0); } else { len += 1; } i++; } } catch (Exception e) { FileLog.e("write byte array error"); } } public void writeString(String s) { try { writeByteArray(s.getBytes("UTF-8")); } catch(Exception e) { FileLog.e("write string error"); } } public void writeByteArray(byte[] b, int offset, int count) { try { if(count <= 253) { if (!justCalc) { out.write(count); } else { len += 1; } } else { if (!justCalc) { out.write(254); out.write(count); out.write(count >> 8); out.write(count >> 16); } else { len += 4; } } if (!justCalc) { out.write(b, offset, count); } else { len += count; } int i = count <= 253 ? 1 : 4; while ((count + i) % 4 != 0) { if (!justCalc) { out.write(0); } else { len += 1; } i++; } } catch (Exception e) { FileLog.e("write byte array error"); } } public void writeDouble(double d) { try { writeInt64(Double.doubleToRawLongBits(d)); } catch(Exception e) { FileLog.e("write double error"); } } public int length() { if (!justCalc) { return isOut ? outbuf.size() : inbuf.available(); } return len; } protected void set(byte[] newData) { isOut = false; inbuf = new ByteArrayInputStream(newData); in = new DataInputStream(inbuf); } public byte[] toByteArray() { return outbuf.toByteArray(); } public void skip(int count) { if (count == 0) { return; } if (!justCalc) { if (in != null) { try { in.skipBytes(count); } catch (Exception e) { FileLog.e(e); } } } else { len += count; } } public int getPosition() { return len; } public boolean readBool(boolean exception) { int consructor = readInt32(exception); if (consructor == 0x997275b5) { return true; } else if (consructor == 0xbc799737) { return false; } if (exception) { throw new RuntimeException("Not bool value!"); } else { FileLog.e("Not bool value!"); } return false; } public void readBytes(byte[] b, boolean exception) { try { in.read(b); len += b.length; } catch (Exception e) { if (exception) { throw new RuntimeException("read bytes error", e); } else { FileLog.e("read bytes error"); } } } public byte[] readData(int count, boolean exception) { byte[] arr = new byte[count]; readBytes(arr, exception); return arr; } public String readString(boolean exception) { try { int sl = 1; int l = in.read(); len++; if(l >= 254) { l = in.read() | (in.read() << 8) | (in.read() << 16); len += 3; sl = 4; } byte[] b = new byte[l]; in.read(b); len++; int i=sl; while((l + i) % 4 != 0) { in.read(); len++; i++; } return new String(b, "UTF-8"); } catch (Exception e) { if (exception) { throw new RuntimeException("read string error", e); } else { FileLog.e("read string error"); } } return null; } public byte[] readByteArray(boolean exception) { try { int sl = 1; int l = in.read(); len++; if (l >= 254) { l = in.read() | (in.read() << 8) | (in.read() << 16); len += 3; sl = 4; } byte[] b = new byte[l]; in.read(b); len++; int i = sl; while((l + i) % 4 != 0) { in.read(); len++; i++; } return b; } catch (Exception e) { if (exception) { throw new RuntimeException("read byte array error", e); } else { FileLog.e("read byte array error"); } } return null; } public double readDouble(boolean exception) { try { return Double.longBitsToDouble(readInt64(exception)); } catch(Exception e) { if (exception) { throw new RuntimeException("read double error", e); } else { FileLog.e("read double error"); } } return 0; } public int readInt32(boolean exception) { try { int i = 0; for(int j = 0; j < 4; j++) { i |= (in.read() << (j * 8)); len++; } return i; } catch(Exception e) { if (exception) { throw new RuntimeException("read int32 error", e); } else { FileLog.e("read int32 error"); } } return 0; } public long readInt64(boolean exception) { try { long i = 0; for(int j = 0; j < 8; j++) { i |= ((long)in.read() << (j * 8)); len++; } return i; } catch (Exception e) { if (exception) { throw new RuntimeException("read int64 error", e); } else { FileLog.e("read int64 error"); } } return 0; } @Override public void writeByteBuffer(NativeByteBuffer buffer) { } @Override public NativeByteBuffer readByteBuffer(boolean exception) { return null; } }
gpl-2.0
52North/SOS
core/api/src/main/java/org/n52/sos/exception/sos/InvalidPropertyOfferingCombinationException.java
2015
/* * Copyright (C) 2012-2022 52°North Spatial Information Research GmbH * * This program is free software; you can redistribute it and/or modify it * under the terms of the GNU General Public License version 2 as published * by the Free Software Foundation. * * If the program is linked with libraries which are licensed under one of * the following licenses, the combination of the program with the linked * library is not considered a "derivative work" of the program: * * - Apache License, version 2.0 * - Apache Software License, version 1.0 * - GNU Lesser General Public License, version 3 * - Mozilla Public License, versions 1.0, 1.1 and 2.0 * - Common Development and Distribution License (CDDL), version 1.0 * * Therefore the distribution of the program linked with libraries licensed * under the aforementioned licenses, is permitted by the copyright holders * if the distribution is compliant with both the GNU General Public * License version 2 and the aforementioned licenses. * * This program is distributed in the hope that it will be useful, but * WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General * Public License for more details. */ package org.n52.sos.exception.sos; import org.n52.janmayen.http.HTTPStatus; import org.n52.shetland.ogc.sos.exception.CodedSosException; import org.n52.shetland.ogc.sos.exception.SosExceptionCode; /** * @author <a href="mailto:c.autermann@52north.org">Christian Autermann</a> * @author <a href="mailto:e.h.juerrens@52north.org">Eike Hinderk * J&uuml;rrens</a> * * @since 4.0.0 */ public class InvalidPropertyOfferingCombinationException extends CodedSosException { private static final long serialVersionUID = 7758576540177872103L; public InvalidPropertyOfferingCombinationException() { super(SosExceptionCode.InvalidPropertyOfferingCombination); setStatus(HTTPStatus.BAD_REQUEST); } }
gpl-2.0
gardir/INF1010-V16
uke02/Square.java
674
class Square implements Shape, Comparable<Square>{ private double sidelength; public Square(double sl){ sidelength = sl; } public double area(){ return sidelength*sidelength; } public double perimeter(){ return 4*sidelength; } /* a.compareTo(b) > 0: a storre enn b a.compareTo(b) == 0: a er like stor som b a.compareTo(b) < 0: a er mindre enn b */ public int compareTo(Square s){ double compare = area() - s.area(); if(compare > 0){ return 1; }else if(compare < 0){ return -1; }else{ return 0; } } }
gpl-2.0
yuflyud/websearch
websearch-engine/src/main/java/org/yflyud/projects/websearch/engine/config/ConfigurationException.java
553
package org.yflyud.projects.websearch.engine.config; public class ConfigurationException extends Exception { private static final long serialVersionUID = 7141646545440764761L; public ConfigurationException() { } public ConfigurationException(String paramString) { super(paramString); } public ConfigurationException(Throwable paramThrowable) { super(paramThrowable); } public ConfigurationException(String paramString, Throwable paramThrowable) { super(paramString, paramThrowable); } }
gpl-2.0
lyrgard/HexScape
common/src/main/java/fr/lyrgard/hexScape/model/piece/PieceInstance.java
1721
package fr.lyrgard.hexScape.model.piece; import com.fasterxml.jackson.annotation.JsonCreator; import com.fasterxml.jackson.annotation.JsonIgnore; import com.fasterxml.jackson.annotation.JsonProperty; import fr.lyrgard.hexScape.model.card.CardInstance; import fr.lyrgard.hexScape.model.map.Direction; public class PieceInstance { private String id; @JsonIgnore private CardInstance card; private int x; private int y; private int z; private Direction direction = Direction.EAST; private String modelId; public PieceInstance(String id, String modelId, CardInstance card) { this.id = id; this.modelId= modelId; this.card = card; } @JsonCreator public PieceInstance( @JsonProperty("id") String id, @JsonProperty("modelId") String modelId, @JsonProperty("direction") Direction direction, @JsonProperty("x") int x, @JsonProperty("y") int y, @JsonProperty("z") int z) { this.id = id; this.modelId= modelId; this.direction = direction; this.x = x; this.y = y; this.z = z; } public int getX() { return x; } public void setX(int x) { this.x = x; } public int getY() { return y; } public void setY(int y) { this.y = y; } public int getZ() { return z; } public void setZ(int z) { this.z = z; } public Direction getDirection() { return direction; } public void setDirection(Direction direction) { this.direction = direction; } public String getModelId() { return modelId; } public String getId() { return id; } public void setId(String id) { this.id = id; } @JsonIgnore public CardInstance getCard() { return card; } @JsonIgnore public void setCard(CardInstance card) { this.card = card; } }
gpl-2.0
cblichmann/idajava
javasrc/src/de/blichmann/idajava/natives/generic_linput_t.java
1638
/* ---------------------------------------------------------------------------- * This file was automatically generated by SWIG (http://www.swig.org). * Version 2.0.0 * * Do not make changes to this file unless you know what you are doing--modify * the SWIG interface file instead. * ----------------------------------------------------------------------------- */ package de.blichmann.idajava.natives; public class generic_linput_t { private long swigCPtr; protected boolean swigCMemOwn; public generic_linput_t(long cPtr, boolean cMemoryOwn) { swigCMemOwn = cMemoryOwn; swigCPtr = cPtr; } public static long getCPtr(generic_linput_t obj) { return (obj == null) ? 0 : obj.swigCPtr; } protected void finalize() { delete(); } public synchronized void delete() { if (swigCPtr != 0) { if (swigCMemOwn) { swigCMemOwn = false; IdaJavaJNI.delete_generic_linput_t(swigCPtr); } swigCPtr = 0; } } public void setFilesize(long value) { IdaJavaJNI.generic_linput_t_filesize_set(swigCPtr, this, value); } public long getFilesize() { return IdaJavaJNI.generic_linput_t_filesize_get(swigCPtr, this); } public void setBlocksize(long value) { IdaJavaJNI.generic_linput_t_blocksize_set(swigCPtr, this, value); } public long getBlocksize() { return IdaJavaJNI.generic_linput_t_blocksize_get(swigCPtr, this); } public int read(SWIGTYPE_p_off_t off, SWIGTYPE_p_void buffer, long nbytes) { return IdaJavaJNI.generic_linput_t_read(swigCPtr, this, SWIGTYPE_p_off_t.getCPtr(off), SWIGTYPE_p_void.getCPtr(buffer), nbytes); } }
gpl-2.0
lamsfoundation/lams
3rdParty_sources/spring/org/springframework/orm/jpa/AbstractEntityManagerFactoryBean.java
24020
/* * Copyright 2002-2017 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.springframework.orm.jpa; import java.io.IOException; import java.io.NotSerializableException; import java.io.ObjectInputStream; import java.io.ObjectStreamException; import java.io.Serializable; import java.lang.reflect.InvocationHandler; import java.lang.reflect.InvocationTargetException; import java.lang.reflect.Method; import java.lang.reflect.Proxy; import java.util.HashMap; import java.util.LinkedHashSet; import java.util.Map; import java.util.Properties; import java.util.Set; import java.util.concurrent.Callable; import java.util.concurrent.ExecutionException; import java.util.concurrent.Future; import javax.persistence.EntityManager; import javax.persistence.EntityManagerFactory; import javax.persistence.PersistenceException; import javax.persistence.Query; import javax.persistence.spi.PersistenceProvider; import javax.persistence.spi.PersistenceUnitInfo; import javax.sql.DataSource; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; import org.springframework.beans.BeanUtils; import org.springframework.beans.factory.BeanClassLoaderAware; import org.springframework.beans.factory.BeanFactory; import org.springframework.beans.factory.BeanFactoryAware; import org.springframework.beans.factory.BeanNameAware; import org.springframework.beans.factory.DisposableBean; import org.springframework.beans.factory.FactoryBean; import org.springframework.beans.factory.InitializingBean; import org.springframework.core.task.AsyncTaskExecutor; import org.springframework.dao.DataAccessException; import org.springframework.dao.support.PersistenceExceptionTranslator; import org.springframework.util.Assert; import org.springframework.util.ClassUtils; import org.springframework.util.CollectionUtils; /** * Abstract {@link org.springframework.beans.factory.FactoryBean} that creates * a local JPA {@link javax.persistence.EntityManagerFactory} instance within * a Spring application context. * * <p>Encapsulates the common functionality between the different JPA bootstrap * contracts (standalone as well as container). * * <p>Implements support for standard JPA configuration conventions as well as * Spring's customizable {@link JpaVendorAdapter} mechanism, and controls the * EntityManagerFactory's lifecycle. * * <p>This class also implements the * {@link org.springframework.dao.support.PersistenceExceptionTranslator} * interface, as autodetected by Spring's * {@link org.springframework.dao.annotation.PersistenceExceptionTranslationPostProcessor}, * for AOP-based translation of native exceptions to Spring DataAccessExceptions. * Hence, the presence of e.g. LocalEntityManagerFactoryBean automatically enables * a PersistenceExceptionTranslationPostProcessor to translate JPA exceptions. * * @author Juergen Hoeller * @author Rod Johnson * @since 2.0 * @see LocalEntityManagerFactoryBean * @see LocalContainerEntityManagerFactoryBean */ @SuppressWarnings("serial") public abstract class AbstractEntityManagerFactoryBean implements FactoryBean<EntityManagerFactory>, BeanClassLoaderAware, BeanFactoryAware, BeanNameAware, InitializingBean, DisposableBean, EntityManagerFactoryInfo, PersistenceExceptionTranslator, Serializable { /** Logger available to subclasses */ protected final Log logger = LogFactory.getLog(getClass()); private PersistenceProvider persistenceProvider; private String persistenceUnitName; private final Map<String, Object> jpaPropertyMap = new HashMap<String, Object>(); private Class<? extends EntityManagerFactory> entityManagerFactoryInterface; private Class<? extends EntityManager> entityManagerInterface; private JpaDialect jpaDialect; private JpaVendorAdapter jpaVendorAdapter; private AsyncTaskExecutor bootstrapExecutor; private ClassLoader beanClassLoader = getClass().getClassLoader(); private BeanFactory beanFactory; private String beanName; /** Raw EntityManagerFactory as returned by the PersistenceProvider */ private EntityManagerFactory nativeEntityManagerFactory; /** Future for lazily initializing raw target EntityManagerFactory */ private Future<EntityManagerFactory> nativeEntityManagerFactoryFuture; /** Exposed client-level EntityManagerFactory proxy */ private EntityManagerFactory entityManagerFactory; /** * Set the PersistenceProvider implementation class to use for creating the * EntityManagerFactory. If not specified, the persistence provider will be * taken from the JpaVendorAdapter (if any) or retrieved through scanning * (as far as possible). * @see JpaVendorAdapter#getPersistenceProvider() * @see javax.persistence.spi.PersistenceProvider * @see javax.persistence.Persistence */ public void setPersistenceProviderClass(Class<? extends PersistenceProvider> persistenceProviderClass) { this.persistenceProvider = BeanUtils.instantiateClass(persistenceProviderClass); } /** * Set the PersistenceProvider instance to use for creating the * EntityManagerFactory. If not specified, the persistence provider * will be taken from the JpaVendorAdapter (if any) or determined * by the persistence unit deployment descriptor (as far as possible). * @see JpaVendorAdapter#getPersistenceProvider() * @see javax.persistence.spi.PersistenceProvider * @see javax.persistence.Persistence */ public void setPersistenceProvider(PersistenceProvider persistenceProvider) { this.persistenceProvider = persistenceProvider; } @Override public PersistenceProvider getPersistenceProvider() { return this.persistenceProvider; } /** * Specify the name of the EntityManagerFactory configuration. * <p>Default is none, indicating the default EntityManagerFactory * configuration. The persistence provider will throw an exception if * ambiguous EntityManager configurations are found. * @see javax.persistence.Persistence#createEntityManagerFactory(String) */ public void setPersistenceUnitName(String persistenceUnitName) { this.persistenceUnitName = persistenceUnitName; } @Override public String getPersistenceUnitName() { return this.persistenceUnitName; } /** * Specify JPA properties, to be passed into * {@code Persistence.createEntityManagerFactory} (if any). * <p>Can be populated with a String "value" (parsed via PropertiesEditor) or a * "props" element in XML bean definitions. * @see javax.persistence.Persistence#createEntityManagerFactory(String, java.util.Map) * @see javax.persistence.spi.PersistenceProvider#createContainerEntityManagerFactory(javax.persistence.spi.PersistenceUnitInfo, java.util.Map) */ public void setJpaProperties(Properties jpaProperties) { CollectionUtils.mergePropertiesIntoMap(jpaProperties, this.jpaPropertyMap); } /** * Specify JPA properties as a Map, to be passed into * {@code Persistence.createEntityManagerFactory} (if any). * <p>Can be populated with a "map" or "props" element in XML bean definitions. * @see javax.persistence.Persistence#createEntityManagerFactory(String, java.util.Map) * @see javax.persistence.spi.PersistenceProvider#createContainerEntityManagerFactory(javax.persistence.spi.PersistenceUnitInfo, java.util.Map) */ public void setJpaPropertyMap(Map<String, ?> jpaProperties) { if (jpaProperties != null) { this.jpaPropertyMap.putAll(jpaProperties); } } /** * Allow Map access to the JPA properties to be passed to the persistence * provider, with the option to add or override specific entries. * <p>Useful for specifying entries directly, for example via * "jpaPropertyMap[myKey]". */ public Map<String, Object> getJpaPropertyMap() { return this.jpaPropertyMap; } /** * Specify the (potentially vendor-specific) EntityManagerFactory interface * that this EntityManagerFactory proxy is supposed to implement. * <p>The default will be taken from the specific JpaVendorAdapter, if any, * or set to the standard {@code javax.persistence.EntityManagerFactory} * interface else. * @see JpaVendorAdapter#getEntityManagerFactoryInterface() */ public void setEntityManagerFactoryInterface(Class<? extends EntityManagerFactory> emfInterface) { this.entityManagerFactoryInterface = emfInterface; } /** * Specify the (potentially vendor-specific) EntityManager interface * that this factory's EntityManagers are supposed to implement. * <p>The default will be taken from the specific JpaVendorAdapter, if any, * or set to the standard {@code javax.persistence.EntityManager} * interface else. * @see JpaVendorAdapter#getEntityManagerInterface() * @see EntityManagerFactoryInfo#getEntityManagerInterface() */ public void setEntityManagerInterface(Class<? extends EntityManager> emInterface) { this.entityManagerInterface = emInterface; } @Override public Class<? extends EntityManager> getEntityManagerInterface() { return this.entityManagerInterface; } /** * Specify the vendor-specific JpaDialect implementation to associate with * this EntityManagerFactory. This will be exposed through the * EntityManagerFactoryInfo interface, to be picked up as default dialect by * accessors that intend to use JpaDialect functionality. * @see EntityManagerFactoryInfo#getJpaDialect() */ public void setJpaDialect(JpaDialect jpaDialect) { this.jpaDialect = jpaDialect; } @Override public JpaDialect getJpaDialect() { return this.jpaDialect; } /** * Specify the JpaVendorAdapter implementation for the desired JPA provider, * if any. This will initialize appropriate defaults for the given provider, * such as persistence provider class and JpaDialect, unless locally * overridden in this FactoryBean. */ public void setJpaVendorAdapter(JpaVendorAdapter jpaVendorAdapter) { this.jpaVendorAdapter = jpaVendorAdapter; } /** * Return the JpaVendorAdapter implementation for this * EntityManagerFactory, or {@code null} if not known. */ public JpaVendorAdapter getJpaVendorAdapter() { return this.jpaVendorAdapter; } /** * Specify an asynchronous executor for background bootstrapping, * e.g. a {@link org.springframework.core.task.SimpleAsyncTaskExecutor}. * <p>{@code EntityManagerFactory} initialization will then switch into background * bootstrap mode, with a {@code EntityManagerFactory} proxy immediately returned for * injection purposes instead of waiting for the JPA provider's bootstrapping to complete. * However, note that the first actual call to a {@code EntityManagerFactory} method will * then block until the JPA provider's bootstrapping completed, if not ready by then. * For maximum benefit, make sure to avoid early {@code EntityManagerFactory} calls * in init methods of related beans, even for metadata introspection purposes. * @since 4.3 */ public void setBootstrapExecutor(AsyncTaskExecutor bootstrapExecutor) { this.bootstrapExecutor = bootstrapExecutor; } /** * Return the asynchronous executor for background bootstrapping, if any. * @since 4.3 */ public AsyncTaskExecutor getBootstrapExecutor() { return this.bootstrapExecutor; } @Override public void setBeanClassLoader(ClassLoader classLoader) { this.beanClassLoader = classLoader; } @Override public ClassLoader getBeanClassLoader() { return this.beanClassLoader; } @Override public void setBeanFactory(BeanFactory beanFactory) { this.beanFactory = beanFactory; } @Override public void setBeanName(String name) { this.beanName = name; } @Override public final void afterPropertiesSet() throws PersistenceException { if (this.jpaVendorAdapter != null) { if (this.persistenceProvider == null) { this.persistenceProvider = this.jpaVendorAdapter.getPersistenceProvider(); } Map<String, ?> vendorPropertyMap = this.jpaVendorAdapter.getJpaPropertyMap(); if (vendorPropertyMap != null) { for (Map.Entry<String, ?> entry : vendorPropertyMap.entrySet()) { if (!this.jpaPropertyMap.containsKey(entry.getKey())) { this.jpaPropertyMap.put(entry.getKey(), entry.getValue()); } } } if (this.entityManagerFactoryInterface == null) { this.entityManagerFactoryInterface = this.jpaVendorAdapter.getEntityManagerFactoryInterface(); if (!ClassUtils.isVisible(this.entityManagerFactoryInterface, this.beanClassLoader)) { this.entityManagerFactoryInterface = EntityManagerFactory.class; } } if (this.entityManagerInterface == null) { this.entityManagerInterface = this.jpaVendorAdapter.getEntityManagerInterface(); if (!ClassUtils.isVisible(this.entityManagerInterface, this.beanClassLoader)) { this.entityManagerInterface = EntityManager.class; } } if (this.jpaDialect == null) { this.jpaDialect = this.jpaVendorAdapter.getJpaDialect(); } } if (this.bootstrapExecutor != null) { this.nativeEntityManagerFactoryFuture = this.bootstrapExecutor.submit(new Callable<EntityManagerFactory>() { @Override public EntityManagerFactory call() { return buildNativeEntityManagerFactory(); } }); } else { this.nativeEntityManagerFactory = buildNativeEntityManagerFactory(); } // Wrap the EntityManagerFactory in a factory implementing all its interfaces. // This allows interception of createEntityManager methods to return an // application-managed EntityManager proxy that automatically joins // existing transactions. this.entityManagerFactory = createEntityManagerFactoryProxy(this.nativeEntityManagerFactory); } private EntityManagerFactory buildNativeEntityManagerFactory() { EntityManagerFactory emf = createNativeEntityManagerFactory(); if (emf == null) { throw new IllegalStateException( "JPA PersistenceProvider returned null EntityManagerFactory - check your JPA provider setup!"); } if (this.jpaVendorAdapter != null) { this.jpaVendorAdapter.postProcessEntityManagerFactory(emf); } if (logger.isInfoEnabled()) { logger.info("Initialized JPA EntityManagerFactory for persistence unit '" + getPersistenceUnitName() + "'"); } return emf; } /** * Create a proxy of the given EntityManagerFactory. We do this to be able * to return transaction-aware proxies for application-managed * EntityManagers, and to introduce the NamedEntityManagerFactory interface * @param emf EntityManagerFactory as returned by the persistence provider * @return proxy entity manager */ protected EntityManagerFactory createEntityManagerFactoryProxy(EntityManagerFactory emf) { Set<Class<?>> ifcs = new LinkedHashSet<Class<?>>(); if (this.entityManagerFactoryInterface != null) { ifcs.add(this.entityManagerFactoryInterface); } else if (emf != null) { ifcs.addAll(ClassUtils.getAllInterfacesForClassAsSet(emf.getClass(), this.beanClassLoader)); } else { ifcs.add(EntityManagerFactory.class); } ifcs.add(EntityManagerFactoryInfo.class); try { return (EntityManagerFactory) Proxy.newProxyInstance( this.beanClassLoader, ifcs.toArray(new Class<?>[ifcs.size()]), new ManagedEntityManagerFactoryInvocationHandler(this)); } catch (IllegalArgumentException ex) { if (this.entityManagerFactoryInterface != null) { throw new IllegalStateException("EntityManagerFactory interface [" + this.entityManagerFactoryInterface + "] seems to conflict with Spring's EntityManagerFactoryInfo mixin - consider resetting the "+ "'entityManagerFactoryInterface' property to plain [javax.persistence.EntityManagerFactory]", ex); } else { throw new IllegalStateException("Conflicting EntityManagerFactory interfaces - " + "consider specifying the 'jpaVendorAdapter' or 'entityManagerFactoryInterface' property " + "to select a specific EntityManagerFactory interface to proceed with", ex); } } } /** * Delegate an incoming invocation from the proxy, dispatching to EntityManagerFactoryInfo * or the native EntityManagerFactory accordingly. */ Object invokeProxyMethod(Method method, Object[] args) throws Throwable { if (method.getDeclaringClass().isAssignableFrom(EntityManagerFactoryInfo.class)) { return method.invoke(this, args); } else if (method.getName().equals("createEntityManager") && args != null && args.length > 0 && args[0] != null && args[0].getClass().isEnum() && "SYNCHRONIZED".equals(args[0].toString())) { // JPA 2.1's createEntityManager(SynchronizationType, Map) // Redirect to plain createEntityManager and add synchronization semantics through Spring proxy EntityManager rawEntityManager = (args.length > 1 ? getNativeEntityManagerFactory().createEntityManager((Map<?, ?>) args[1]) : getNativeEntityManagerFactory().createEntityManager()); return ExtendedEntityManagerCreator.createApplicationManagedEntityManager(rawEntityManager, this, true); } // Look for Query arguments, primarily JPA 2.1's addNamedQuery(String, Query) if (args != null) { for (int i = 0; i < args.length; i++) { Object arg = args[i]; if (arg instanceof Query && Proxy.isProxyClass(arg.getClass())) { // Assumably a Spring-generated proxy from SharedEntityManagerCreator: // since we're passing it back to the native EntityManagerFactory, // let's unwrap it to the original Query object from the provider. try { args[i] = ((Query) arg).unwrap(null); } catch (RuntimeException ex) { // Ignore - simply proceed with given Query object then } } } } // Standard delegation to the native factory, just post-processing EntityManager return values Object retVal = method.invoke(getNativeEntityManagerFactory(), args); if (retVal instanceof EntityManager) { // Any other createEntityManager variant - expecting non-synchronized semantics EntityManager rawEntityManager = (EntityManager) retVal; retVal = ExtendedEntityManagerCreator.createApplicationManagedEntityManager(rawEntityManager, this, false); } return retVal; } /** * Subclasses must implement this method to create the EntityManagerFactory * that will be returned by the {@code getObject()} method. * @return EntityManagerFactory instance returned by this FactoryBean * @throws PersistenceException if the EntityManager cannot be created */ protected abstract EntityManagerFactory createNativeEntityManagerFactory() throws PersistenceException; /** * Implementation of the PersistenceExceptionTranslator interface, as * autodetected by Spring's PersistenceExceptionTranslationPostProcessor. * <p>Uses the dialect's conversion if possible; otherwise falls back to * standard JPA exception conversion. * @see org.springframework.dao.annotation.PersistenceExceptionTranslationPostProcessor * @see JpaDialect#translateExceptionIfPossible * @see EntityManagerFactoryUtils#convertJpaAccessExceptionIfPossible */ @Override public DataAccessException translateExceptionIfPossible(RuntimeException ex) { return (this.jpaDialect != null ? this.jpaDialect.translateExceptionIfPossible(ex) : EntityManagerFactoryUtils.convertJpaAccessExceptionIfPossible(ex)); } @Override public EntityManagerFactory getNativeEntityManagerFactory() { if (this.nativeEntityManagerFactory != null) { return this.nativeEntityManagerFactory; } else { try { return this.nativeEntityManagerFactoryFuture.get(); } catch (InterruptedException ex) { throw new IllegalStateException("Interrupted during initialization of native EntityManagerFactory: " + ex.getMessage()); } catch (ExecutionException ex) { throw new IllegalStateException("Failed to asynchronously initialize native EntityManagerFactory: " + ex.getMessage(), ex.getCause()); } } } @Override public PersistenceUnitInfo getPersistenceUnitInfo() { return null; } @Override public DataSource getDataSource() { return null; } /** * Return the singleton EntityManagerFactory. */ @Override public EntityManagerFactory getObject() { return this.entityManagerFactory; } @Override public Class<? extends EntityManagerFactory> getObjectType() { return (this.entityManagerFactory != null ? this.entityManagerFactory.getClass() : EntityManagerFactory.class); } @Override public boolean isSingleton() { return true; } /** * Close the EntityManagerFactory on bean factory shutdown. */ @Override public void destroy() { if (logger.isInfoEnabled()) { logger.info("Closing JPA EntityManagerFactory for persistence unit '" + getPersistenceUnitName() + "'"); } this.entityManagerFactory.close(); } //--------------------------------------------------------------------- // Serialization support //--------------------------------------------------------------------- private void readObject(ObjectInputStream ois) throws IOException, ClassNotFoundException { throw new NotSerializableException("An EntityManagerFactoryBean itself is not deserializable - " + "just a SerializedEntityManagerFactoryBeanReference is"); } protected Object writeReplace() throws ObjectStreamException { if (this.beanFactory != null && this.beanName != null) { return new SerializedEntityManagerFactoryBeanReference(this.beanFactory, this.beanName); } else { throw new NotSerializableException("EntityManagerFactoryBean does not run within a BeanFactory"); } } /** * Minimal bean reference to the surrounding AbstractEntityManagerFactoryBean. * Resolved to the actual AbstractEntityManagerFactoryBean instance on deserialization. */ @SuppressWarnings("serial") private static class SerializedEntityManagerFactoryBeanReference implements Serializable { private final BeanFactory beanFactory; private final String lookupName; public SerializedEntityManagerFactoryBeanReference(BeanFactory beanFactory, String beanName) { this.beanFactory = beanFactory; this.lookupName = BeanFactory.FACTORY_BEAN_PREFIX + beanName; } private Object readResolve() { return this.beanFactory.getBean(this.lookupName, AbstractEntityManagerFactoryBean.class); } } /** * Dynamic proxy invocation handler proxying an EntityManagerFactory to * return a proxy EntityManager if necessary from createEntityManager() * methods. */ @SuppressWarnings("serial") private static class ManagedEntityManagerFactoryInvocationHandler implements InvocationHandler, Serializable { private final AbstractEntityManagerFactoryBean entityManagerFactoryBean; public ManagedEntityManagerFactoryInvocationHandler(AbstractEntityManagerFactoryBean emfb) { this.entityManagerFactoryBean = emfb; } @Override public Object invoke(Object proxy, Method method, Object[] args) throws Throwable { try { if (method.getName().equals("equals")) { // Only consider equal when proxies are identical. return (proxy == args[0]); } else if (method.getName().equals("hashCode")) { // Use hashCode of EntityManagerFactory proxy. return System.identityHashCode(proxy); } else if (method.getName().equals("unwrap")) { // Handle JPA 2.1 unwrap method - could be a proxy match. Class<?> targetClass = (Class<?>) args[0]; if (targetClass == null) { return this.entityManagerFactoryBean.getNativeEntityManagerFactory(); } else if (targetClass.isInstance(proxy)) { return proxy; } } return this.entityManagerFactoryBean.invokeProxyMethod(method, args); } catch (InvocationTargetException ex) { throw ex.getTargetException(); } } } }
gpl-2.0
Atrament666/timer
src/main/java/org/atrament/timer7/preferences/actions/PreferencesAction.java
1801
/* * Copyright (C) 2017 Atrament <atrament666@gmail.com> * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License * as published by the Free Software Foundation; either version 2 * of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. */ package org.atrament.timer7.preferences.actions; import java.awt.event.ActionEvent; import javax.annotation.PostConstruct; import javax.swing.AbstractAction; import javax.swing.SwingUtilities; import org.atrament.timer7.preferences.ui.PreferencesDialog; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Component; /** * * @author Atrament <atrament666@gmail.com> */ @Component public class PreferencesAction extends AbstractAction { private PreferencesDialog preferencesDialog; public PreferencesAction() { } @PostConstruct private void initComponent() { putValue(NAME, "Options"); } @Override public void actionPerformed(ActionEvent e) { SwingUtilities.invokeLater(() -> { preferencesDialog.setVisible(true); }); } @Autowired public void setPreferencesDialog(PreferencesDialog preferencesDialog) { this.preferencesDialog = preferencesDialog; } }
gpl-2.0
Sofd/viskit
src/main/java/de/sofd/viskit/model/LookupTableImpl.java
4022
package de.sofd.viskit.model; import java.nio.FloatBuffer; import java.nio.IntBuffer; public class LookupTableImpl implements LookupTable { protected final String name; protected final FloatBuffer rgbaValues; protected FloatBuffer rgba256floatValues; protected IntBuffer rgba256intValues; protected float[][] rgbaFloatArrays; protected float[][] rgba256floatArrays; protected int[][] rgba256intArrays; public LookupTableImpl(String name, FloatBuffer rgbaValues) { this.name = name; this.rgbaValues = rgbaValues; } @Override public String getName() { return name; } @Override public FloatBuffer getRGBAValues() { return rgbaValues; } @Override public FloatBuffer getRGBA256floatValues() { if (null == rgba256floatValues) { int n = rgbaValues.limit(); rgba256floatValues = FloatBuffer.allocate(n); for (int i = 0; i < n; i++) { rgba256floatValues.put(i, 255 * rgbaValues.get(i)); } } return rgba256floatValues; } @Override public IntBuffer getRGBA256intValues() { if (null == rgba256intValues) { int n = rgbaValues.limit(); rgba256intValues = IntBuffer.allocate(n); for (int i = 0; i < n; i++) { rgba256intValues.put(i, (int)(255 * rgbaValues.get(i))); } } return rgba256intValues; } @Override public float[][] getRGBAfloatArrays() { if (null == rgbaFloatArrays) { int n = rgbaValues.limit() / 4; rgbaFloatArrays = new float[n][]; for (int i = 0; i < n; i++) { rgbaValues.position(4*i); rgbaFloatArrays[i] = new float[4]; rgbaValues.get(rgbaFloatArrays[i]); } } return rgbaFloatArrays; } @Override public float[][] getRGBA256floatArrays() { if (null == rgba256floatArrays) { int n = rgbaValues.limit() / 4; rgba256floatArrays = new float[n][]; for (int i = 0; i < n; i++) { rgbaValues.position(4*i); rgba256floatArrays[i] = new float[4]; rgba256floatArrays[i][0] = 255 * rgbaValues.get(); rgba256floatArrays[i][1] = 255 * rgbaValues.get(); rgba256floatArrays[i][2] = 255 * rgbaValues.get(); rgba256floatArrays[i][3] = 255 * rgbaValues.get(); } } return rgba256floatArrays; } @Override public int[][] getRGBA256intArrays() { if (null == rgba256intArrays) { int n = rgbaValues.limit() / 4; rgba256intArrays = new int[n][]; for (int i = 0; i < n; i++) { rgbaValues.position(4*i); rgba256intArrays[i] = new int[4]; rgba256intArrays[i][0] = (int)(255 * rgbaValues.get()); rgba256intArrays[i][1] = (int)(255 * rgbaValues.get()); rgba256intArrays[i][2] = (int)(255 * rgbaValues.get()); rgba256intArrays[i][3] = (int)(255 * rgbaValues.get()); } } return rgba256intArrays; } @Override public int hashCode() { final int prime = 31; int result = 1; result = prime * result + ((name == null) ? 0 : name.hashCode()); return result; } @Override public boolean equals(Object obj) { if (this == obj) return true; if (obj == null) return false; if (getClass() != obj.getClass()) return false; LookupTableImpl other = (LookupTableImpl) obj; if (name == null) { if (other.name != null) return false; } else if (!name.equals(other.name)) return false; return true; } @Override public String toString() { return name; } }
gpl-2.0
BarbaN3rd/CartaDaGioco
Mazzo.java
3303
import java.util.Random; public class Mazzo { private CartaDaGioco[] mazzo; public Mazzo() { mazzo = new CartaDaGioco[40]; int j = 1; for(int i = 0; i < 10; i++) { // 0 - 9 mazzo[i] = new CartaDaGioco(j, "Cuori"); j++; }//for j = 1; for(int i = 10; i < 20 ; i++) { // 10 - 19 mazzo[i] = new CartaDaGioco(j, "Quadri"); j++; }//for j = 1; for(int i = 20; i < 30; i++) { //20 - 29 mazzo[i] = new CartaDaGioco(j, "Fiori"); j++; }//for j = 1; for(int i = 30; i < 40; i++) { //30 - 39 mazzo[i] = new CartaDaGioco(j, "Picche"); j++; }//for }//I Costruttore /*Metodo toString, ritorna una rappresentazione grafica testuale *dell'elemento *@return rappresentazione grafica dell'elemento */ public String toString() { String supporto = ""; for(int i = 0; i < 40; i++) { supporto = supporto + mazzo[i].toString(); }//for return supporto; }//toString /* Metodo mescolare - non funzionante*/ public void mescolare() { CartaDaGioco[] mazzo2 = new CartaDaGioco[40]; Random random = new Random(); //Errore su questa operazione for(int i = 0; i < 40; i++) { mazzo2[i] = mazzo[i]; }//for for(int i = 0; i < 40; i++) { int j = random.nextInt(39); mazzo[i] = mazzo2[j]; }//for }//mescolare /*Metodo primaCarta, rimuove la prima carta del mazzo @return prima carta del mazzo */ public void estraiPrimaCarta() { CartaDaGioco mazzo2[] = new CartaDaGioco[mazzo.length - 1]; for(int i = 0; i < mazzo2.length; i++) { mazzo[i+1] = mazzo2[i]; } } /*Metodo rimettiCarta La carta passata va riposta in fondo al mazzo, facendo scalare le successive*/ public void rimettiCarta(CartaDaGioco c1) { CartaDaGioco[] mazzo2 = new CartaDaGioco[mazzo.length - 1]; for(int i = 0; i < mazzo2.length; i++) { mazzo2[i] = mazzo[i+1]; }//for mazzo = mazzo2; }//rimettiCarta /* Metodo gioca *@param c1 carta da gioco esplicita *@return giocatore vincente */ public String gioca(CartaDaGioco c1) { String vincitore = ""; int colore1 = 0; int colore2 = 0; int ap1 = 0; int ap2 = 0; if (mazzo[1].getSeme() == "Cuori") { colore1 = 1; ap1 = 1; }//if if (mazzo[1].getSeme() == "Quadri") { colore1 = 1; ap1 = 2; }//if if (mazzo[1].getSeme() == "Fiori") { colore1 = 2; ap1 = 3; }//if if (mazzo[1].getSeme() == "Picche") { colore1 = 2; ap1 = 4; }//if if (c1.getSeme() == "Cuori") { colore2 = 1; ap2 = 1; }//if if (c1.getSeme() == "Quadri") { colore2 = 1; ap2 = 2; }//if if (c1.getSeme() == "Fiori") { colore2 = 2; ap2 = 3; }//if if (c1.getSeme() == "Picche") { colore2 = 2; ap2 = 4; }//if if ((colore1 == colore2) && (mazzo[1].getValore() == c1.getValore())) { if(colore1 > colore2) { vincitore = "Giocatore 1"; } else { vincitore = "Giocatore 2"; }//if }//if if ((colore1 != colore2) && (mazzo[1].getValore() != c1.getValore())) { if(mazzo[1].getValore() > c1.getValore()) { vincitore = "Giocatore 1"; } else { vincitore = "Giocatore 2"; }//if }//if if (((colore1 == colore2)) && (mazzo[1].getValore() != c1.getValore())) { if(ap1 < ap2) { vincitore = "Giocatore 1"; } else { vincitore = "Giocatore 2"; }//if }//if return vincitore; }//gioca }//Mazzo
gpl-2.0
plum-umd/rubah
src/main/java/rubah/bytecode/transformers/DecreaseClassMethodsProtection.java
2460
/******************************************************************************* * Copyright 2014, * Luis Pina <luis@luispina.me>, * Michael Hicks <mwh@cs.umd.edu> * * This file is part of Rubah. * * Rubah is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * Rubah is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with Rubah. If not, see <http://www.gnu.org/licenses/>. *******************************************************************************/ package rubah.bytecode.transformers; import java.lang.reflect.Modifier; import org.objectweb.asm.ClassVisitor; import org.objectweb.asm.MethodVisitor; import rubah.tools.BootstrapJarProcessor; public class DecreaseClassMethodsProtection extends ClassVisitor { private String className; public DecreaseClassMethodsProtection(ClassVisitor cv) { super(BootstrapJarProcessor.ASM5, cv); } @Override public void visit(int version, int access, String name, String signature, String superName, String[] interfaces) { // Make access public so that fields can be set from Rubah access &= ~(BootstrapJarProcessor.ACC_PROTECTED & BootstrapJarProcessor.ACC_PRIVATE); access |= BootstrapJarProcessor.ACC_PUBLIC; if (AddTraverseMethod.isAllowed(name.replace('/', '.'))) access &= ~BootstrapJarProcessor.ACC_FINAL; className = name; super.visit(version, access, name, signature, superName, interfaces); } @Override public MethodVisitor visitMethod(int access, String name, String desc, String signature, String[] exceptions) { if (!className.startsWith("java/lang") || className.equals(Enum.class.getName().replace('.', '/'))) access &= ~BootstrapJarProcessor.ACC_FINAL; if (!Modifier.isPrivate(access) || Modifier.isStatic(access)) { access &= ~BootstrapJarProcessor.ACC_PRIVATE; access &= ~BootstrapJarProcessor.ACC_PROTECTED; access |= BootstrapJarProcessor.ACC_PUBLIC; } return super.visitMethod(access, name, desc, signature, exceptions); } }
gpl-2.0
eda-globetrotter/NetSim
population/graph/Edge.java
3112
/** * This is the underlying data structure for NetSim, abstracting a collection * of pairwise connections/relations between pairs of objects. These * connection/relations are abstracted by edges, and these objected are * represented by nodes. * * The Graph to be implemented shall be directed and weighted, such that all * edges/relations are non-symmetric and are assigned values, which maybe be * costs in monetary or in distance sense. */ package population.graph; // importing packages import utility.*; /** * This interface defines the minimum set of necessary functionality for an * edge in a Graph. An edge maintains information of the interconnection or * relations between nodes in the Graph ADT. This representation can be seen * as a vector from one node to another. * * @author Andy Hao-Wei Lo * @author Zhiyang Ong * @version 0.3.2-andy * @since 0.2 * @acknowledgement Matthew Berryman, Wei-li Khoo and Hiep Nguyen, and code * obtained from Henry Detmold for Programming Techniques, * Assignment 1, available <a href="http://www.cs.adelaide.edu.au/users/third/pt/assignments/assignment1.tgz">here</a>. */ public interface Edge extends Usable { /** * Returns the departure node of this edge * @return the node which this edge starts from */ public Node getFromNode(); /** * Returns the destination node of this edge * @return the node which this edge ends */ public Node getToNode(); /** * Sets the departure node of this edge * @param n The node which this edge starts from */ public void setFromNode(Node n); /** * Sets the destination node of this edge * @param n The node which this edge ends */ public void setToNode(Node n); /** * Returns the descriptive label of this edge. Current version implements * this as a String, but later Objects maybe used for more flexibility. * @return a String that sufficiently describes the Edge * @throws PostconditionException If Null is returned. */ public String getLabel() throws PostconditionException; /** * Sets a descriptive label for the edge. Current version implemetns as a * String, but later Objects maybe used for more flexibility. * @param l A String that sufficiently describes the Edge * @throws PreconditionException If <code>l</code> is a Null String. */ public void setLabel(String l) throws PreconditionException; /** * Returns the cost of using this edge to transfer data. * @throws PostconditionException If the returned cost is negative. * @return the cost of transfering data along this Edge */ public double getCost() throws PostconditionException; /** * Assigns (or reassigns) a cost value to this edge. * @param cost The new cost of this edge * @throws PreconditionException If <code>cost</code> is negative. */ public void setCost(double cost) throws PreconditionException; }
gpl-2.0
hmsiccbl/screensaver
core/src/main/java/edu/harvard/med/screensaver/model/cells/CellLineage.java
1239
// $HeadURL: http://seanderickson1@forge.abcd.harvard.edu/svn/screensaver/branches/serickson/3200/core/src/main/java/edu/harvard/med/screensaver/model/libraries/Gene.java $ // $Id: Gene.java 6946 2012-01-13 18:24:30Z seanderickson1 $ // // Copyright © 2006, 2010, 2011, 2012 by the President and Fellows of Harvard College. // // Screensaver is an open-source project developed by the ICCB-L and NSRB labs // at Harvard Medical School. This software is distributed under the terms of // the GNU General Public License. package edu.harvard.med.screensaver.model.cells; import javax.persistence.Entity; import javax.persistence.PrimaryKeyJoinColumn; import org.hibernate.annotations.Immutable; import edu.harvard.med.screensaver.model.annotations.IgnoreImmutabilityTest; /** * Information about an Immortal Cell Line. * */ @Entity @Immutable @IgnoreImmutabilityTest @PrimaryKeyJoinColumn(name="cellId") @org.hibernate.annotations.ForeignKey(name = "fk_cell_lineage_to_cell") @org.hibernate.annotations.Proxy public class CellLineage extends Cell { private static final long serialVersionUID = 0L; /** * @motivation for hibernate and proxy/concrete subclass constructors */ public CellLineage() { super(); } }
gpl-2.0
lamsfoundation/lams
TestHarness4LAMS2/src/org/lamsfoundation/testharness/Call.java
9661
/**************************************************************** * Copyright (C) 2006 LAMS Foundation (http://lamsfoundation.org) * ============================================================= * License Information: http://lamsfoundation.org/licensing/lams/2.0/ * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License version 2.0 * as published by the Free Software Foundation. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 * USA * * http://www.gnu.org/licenses/gpl.txt * **************************************************************** */ package org.lamsfoundation.testharness; import java.io.InputStream; import java.security.KeyManagementException; import java.security.NoSuchAlgorithmException; import java.security.SecureRandom; import java.security.cert.CertificateException; import java.security.cert.X509Certificate; import java.text.SimpleDateFormat; import java.util.Date; import javax.net.ssl.HostnameVerifier; import javax.net.ssl.HttpsURLConnection; import javax.net.ssl.KeyManager; import javax.net.ssl.SSLContext; import javax.net.ssl.SSLSession; import javax.net.ssl.TrustManager; import javax.net.ssl.X509TrustManager; import org.apache.log4j.Logger; import com.meterware.httpunit.GetMethodWebRequest; import com.meterware.httpunit.PostMethodWebRequest; import com.meterware.httpunit.SubmitButton; import com.meterware.httpunit.WebConversation; import com.meterware.httpunit.WebForm; import com.meterware.httpunit.WebRequest; import com.meterware.httpunit.WebResponse; /** * @author Fei Yang, Marcin Cieslak */ @SuppressWarnings("deprecation") public class Call { static class CallRecord { private int suiteIndex; private String testName; private String callee; private String description; private String snapShotTime; private long timeInMillis; private Integer httpStatusCode; private String message; public CallRecord() { } public CallRecord(int suiteIndex, String testName, String callee, String description, String snapShotTime, long timeInMillis, Integer httpStatusCode, String message) { this.suiteIndex = suiteIndex; this.testName = testName; this.callee = callee; this.description = description; this.snapShotTime = snapShotTime; this.timeInMillis = timeInMillis; this.httpStatusCode = httpStatusCode; this.message = message; } public String getCallee() { return callee; } public String getDescription() { return description; } public final Integer getHttpStatusCode() { return httpStatusCode; } public String getMessage() { return message; } public String getSnapShotTime() { return snapShotTime; } public int getSuiteIndex() { return suiteIndex; } public String getTestName() { return testName; } public long getTimeInMillis() { return timeInMillis; } } private static final Logger log = Logger.getLogger(Call.class); private WebConversation wc; private AbstractTest test; private String description; private String url; private WebForm form; private InputStream is; static { TrustManager defaultTrustManager = new X509TrustManager() { @Override public void checkClientTrusted(X509Certificate[] arg0, String arg1) throws CertificateException { } @Override public void checkServerTrusted(X509Certificate[] arg0, String arg1) throws CertificateException { } @Override public X509Certificate[] getAcceptedIssuers() { return null; } }; try { SSLContext ctx = SSLContext.getInstance("TLS"); ctx.init(new KeyManager[0], new TrustManager[] { defaultTrustManager }, new SecureRandom()); SSLContext.setDefault(ctx); HostnameVerifier hv = new HostnameVerifier() { @Override public boolean verify(String hostname, SSLSession session) { return true; } }; HttpsURLConnection.setDefaultHostnameVerifier(hv); } catch (NoSuchAlgorithmException e) { Call.log.error("Error while setting Trust Manager", e); } catch (KeyManagementException e) { Call.log.error("Error while setting Trust Manager", e); } } public Call(WebConversation wc, AbstractTest test, String description, String url) { this.wc = wc; this.test = test; this.description = description; this.url = url; } public Call(WebConversation wc, AbstractTest test, String description, String url, InputStream is) { this.wc = wc; this.test = test; this.description = description; this.url = url; this.is = is; } public Call(WebConversation wc, AbstractTest test, String description, WebForm form) { this.wc = wc; this.test = test; this.description = description; this.form = form; } private static boolean isCancelButton(SubmitButton button) { return button.getName().contains("CANCEL") || button.getName().contains("Cancel") || button.getName().contains("cancel") || button.getValue().contains("cancel") || button.getValue().contains("Cancel") || button.getValue().contains("CANCEL"); } public Object execute() { String message = null; String callee = null; Integer httpStatusCode = null; long start = 0; long end = 0; try { WebResponse resp = null; WebRequest req = null; if (form != null) { SubmitButton[] submitButtons = filterCancelButton(form.getSubmitButtons()); Call.log.debug(submitButtons.length + " non-cancel submit buttons in the form"); if (submitButtons.length <= 1) { req = form.getRequest(); } else { req = form.getRequest(submitButtons[TestUtil.generateRandomNumber(submitButtons.length)]); } callee = form.getMethod().toUpperCase() + " " + form.getAction(); Call.log.debug(callee); start = System.currentTimeMillis(); resp = wc.getResponse(req); end = System.currentTimeMillis(); } else { String absoluteURL = getAbsoluteURL(url); if (is == null) { callee = "GET " + url; req = new GetMethodWebRequest(absoluteURL); } else { callee = "POST " + url; req = new PostMethodWebRequest(absoluteURL, is, "application/x-www-form-urlencoded;charset=utf-8"); } Call.log.debug(callee); start = System.currentTimeMillis(); resp = wc.getResponse(req); end = System.currentTimeMillis(); } httpStatusCode = resp.getResponseCode(); if (httpStatusCode >= 400) { Call.log.debug("Got " + httpStatusCode + " HTTP code. Retrying call: " + callee); resp = wc.getResponse(req); end = System.currentTimeMillis(); httpStatusCode = resp.getResponseCode(); if (httpStatusCode >= 400) { Call.log.debug(resp.getText()); throw new TestHarnessException(test.testName + " got HTTP code " + httpStatusCode); } } message = resp.getResponseMessage(); // set session cookie manually as the built-in mechanism can't really handle paths and domains for (String headerFieldName : resp.getHeaderFieldNames()) { if (headerFieldName.equalsIgnoreCase("SET-COOKIE")) { String cookieValue = null; String path = null; for (String headerFieldValue : resp.getHeaderFields(headerFieldName)) { String[] headerFieldSplit = headerFieldValue.split("=|;"); for (int paramIndex = 0; paramIndex < headerFieldSplit.length; paramIndex++) { String param = headerFieldSplit[paramIndex].trim(); if ("JSESSIONID".equalsIgnoreCase(param)) { cookieValue = headerFieldSplit[paramIndex + 1]; paramIndex++; } else if ("path".equalsIgnoreCase(param)) { path = headerFieldSplit[paramIndex + 1]; paramIndex++; } } } if (cookieValue != null) { Call.log.debug("Manually setting JSESSIONID = " + cookieValue); // "single use cookie" is misleading; it's just a cookie with a path and domain wc.getCookieJar().putSingleUseCookie("JSESSIONID", cookieValue, test.getTestSuite().getCookieDomain(), path); } } } return resp; } catch (Exception e) { throw new RuntimeException(e); } finally { TestReporter.getCallRecords() .add(new CallRecord(test.getTestSuite().getSuiteIndex(), test.testName, callee, description, new SimpleDateFormat("HH:mm:ss SSS").format(new Date(end)), end - start, httpStatusCode, message)); } } private SubmitButton[] filterCancelButton(SubmitButton[] sbmtBtns) { boolean found = false; int i = 0; for (; i < sbmtBtns.length; i++) { if (Call.isCancelButton(sbmtBtns[i])) { found = true; break; } } if (found) { SubmitButton[] btns = new SubmitButton[sbmtBtns.length - 1]; int j = 0; for (int k = 0; k < sbmtBtns.length; k++) { if (k != i) { btns[j] = sbmtBtns[k]; j++; } } return btns; } else { return sbmtBtns; } } private String getAbsoluteURL(String url) { if (url.startsWith("http")) { return url; } String withSlash = url.startsWith("/") ? url : "/" + url; String context = url.startsWith(test.getTestSuite().getContextRoot()) ? "" : test.getTestSuite().getContextRoot(); String targetServer = test.getTestSuite().getTargetServer(); if (!targetServer.startsWith("http")) { targetServer = "http://" + targetServer; } return targetServer + context + withSlash; } }
gpl-2.0
mgrigioni/oseb
dbPort/src/org/adempierelbr/wrapper/I_W_AD_User.java
1892
/****************************************************************************** * Product: AdempiereLBR ERP & CRM Smart Business Solution * * Copyright (C) 1999-2007 ComPiere, Inc. All Rights Reserved. * * This program is free software, you can redistribute it and/or modify it * * under the terms version 2 of the GNU General Public License as published * * by the Free Software Foundation. This program is distributed in the hope * * that it will be useful, but WITHOUT ANY WARRANTY, without even the implied * * warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. * * See the GNU General Public License for more details. * * You should have received a copy of the GNU General Public License along * * with this program, if not, write to the Free Software Foundation, Inc., * * 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA. * * For the text or an alternative of this public license, you may reach us * * ComPiere, Inc., 2620 Augustine Dr. #245, Santa Clara, CA 95054, USA * * or via info@compiere.org or http://www.compiere.org/license.html * *****************************************************************************/ package org.adempierelbr.wrapper; import org.compiere.model.*; /** Generated Interface for AD_User * @author Adempiere (generated) * @version Release 3.7.0LTS */ public interface I_W_AD_User extends I_AD_User { /** Column name lbr_IsNFeContact */ public static final String COLUMNNAME_lbr_IsNFeContact = "lbr_IsNFeContact"; /** Set NFe Contact. * User is NFe Contact (receive email automatically) */ public void setlbr_IsNFeContact (boolean lbr_IsNFeContact); /** Get NFe Contact. * User is NFe Contact (receive email automatically) */ public boolean islbr_IsNFeContact(); }
gpl-2.0
zerokullneo/PCTR
PCTR-Practicas/Practica11/src/practica11/cPiMonteCarlo.java
2170
/** * Copyright (C) 2022 Jose Manuel Barba Gonzalez <zk at wordpress.com> * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ //package practica11; /**Fichero cPiMonteCarlo.java * @author Jose Manuel Barba Gonzalez * @version 1.0 * Programacion Concurrente y de Tiempo Real * Area de CC. de la Computacion e I.A. */ import java.rmi.*; import java.rmi.registry.*; import java.util.*; /**Descripcion * Cliente que lanza las peticiones sobre el servidor PiMonteCarlo. */ public class cPiMonteCarlo { public static void main(String[] args) throws Exception { /** * puntos solicitados por la entrada estandar. */ int puntos = 0; int op; Scanner r = new Scanner(System.in); iPiMonteCarlo RefObRemoto = (iPiMonteCarlo)Naming.lookup("//localhost/ServerMonteCarlo"); do { System.out.println("-------MENU------."); System.out.println("Indique que desea hacer:"); System.out.println("1. Añadir mas puntos a la aproximacion"); System.out.println("2. Resetear la aproximacion"); System.out.println("0. Salir"); System.out.println("OPCION: "); op = r.nextInt(); switch(op) { case 1: System.out.print("Indique cuantos puntos desea añadir: "); puntos = r.nextInt(); RefObRemoto.masPuntos(puntos); System.out.println("Puntos generados: " + puntos + ", la nueva aproximacion es: " + RefObRemoto.aproxActual()); break; case 2: RefObRemoto.reset(); break; case 0: break; } }while(op != 0); } }
gpl-3.0
minborg/javapot
src/main/java/com/blogspot/minborgsjavapot/components/platform/ComponentHandler.java
1736
/** * * Copyright (c) 2006-2015, Speedment, Inc. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"); You may not * use this file except in compliance with the License. You may obtain a copy of * the License at: * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the * License for the specific language governing permissions and limitations under * the License. */ package com.blogspot.minborgsjavapot.components.platform; import java.util.Map; import java.util.concurrent.ConcurrentHashMap; import static java.util.Objects.requireNonNull; import static java.util.Objects.requireNonNull; /** * * @author pemi */ public class ComponentHandler implements ClassMapper<Component> { private final Map<Class<? extends Component>, Component> map; public ComponentHandler() { this.map = new ConcurrentHashMap<>(); } @Override public <K extends Component, V extends K> K put(Class<K> keyClass, V item) { requireNonNull(keyClass); requireNonNull(item); item.added(); @SuppressWarnings("unchecked") // We know that it is a safe cast // because V extends K final K result = (K) map.put(keyClass, item); if (result != null) { result.removed(); } return result; } @Override public <K extends Component> K get(Class<K> clazz) { @SuppressWarnings("unchecked") final K result = (K) map.get(clazz); return result; } }
gpl-3.0
huang20021/gary
SchoolRoom/src/main/java/com/msad/school/room/util/SortUtil.java
100
package com.msad.school.room.util; public class SortUtil { public static void sortList(){ } }
gpl-3.0
freaxmind/miage-m1
reseau/test/pop3/MessageTest.java
1726
/* * To change this template, choose Tools | Templates * and open the template in the editor. */ package pop3; import java.util.regex.Pattern; import org.junit.Test; import static org.junit.Assert.*; /** * Test for the class Message * @author freaxmind */ public class MessageTest { @Test public void testHeaderPatterns() { System.out.println("Message header patterns"); assertTrue(Pattern.matches(Message.fromPattern.pattern(), "From: Bob Dylan <bob.dylan@gmail.com>")); assertTrue(Pattern.matches(Message.toPattern.pattern(), "To: Alice Wonder <alice.wonder@caramail.com>")); assertTrue(Pattern.matches(Message.datePattern.pattern(), "Date: 12/12/12")); assertTrue(Pattern.matches(Message.subjectPattern.pattern(), "Subject: Hi Alice")); } @Test public void testSplit() { System.out.println("Message split header/body"); String text = ""; text += "From: Alice <alice@gmail.com>\n"; text += "To: Bob <bob@hotmail.com>\n"; text += "Date: Wed, 10 Feb 2010 02:38:34 -0800\n"; text += "Subject: hi!\n"; text += "\n"; text += "Hi, how are you?\n"; text += "- Alice"; Message message = new Message(1, 200, text); assertEquals(1, message.getId()); assertEquals(200, message.getSize()); assertEquals("Alice <alice@gmail.com>", message.getFrom()); assertEquals("Bob <bob@hotmail.com>", message.getTo()); assertEquals("Wed, 10 Feb 2010 02:38:34 -0800", message.getDate()); assertEquals("hi!", message.getSubject()); assertEquals("Hi, how are you?\n- Alice", message.getBody()); } }
gpl-3.0
arnos/java-hackerrank
src/main/java/thirtyDays/prime/Solution.java
1449
package thirtyDays.prime; /** * Author: arno on 2017-03-22. * Github: github.com/arnos */ //============================:: SOLUTION ::=======================================// import java.io.PrintStream; import java.math.BigInteger; import java.util.*; public class Solution { public static void main(String[] args) { solve(new Scanner(System.in), System.out); } public static void solve(Scanner in, PrintStream anOut) { // get the number of possible primes int numberOfPrimes= in.nextInt(); // We'll be using BigInteger as it includes a handy isProbablePrime function // another approach would be to calculate using the Sieve of Eratosthenes -- // there would a price payoff as you need to store the sieve in order to retrieve the values // which will cause issues with large values (in the billions you deal with 50 million primes) BigInteger primeCandidate; // iterate through input check if the number are prime while (numberOfPrimes-- > 0) { primeCandidate = in.nextBigInteger(); anOut.println((primeCandidate.isProbablePrime(3)? "Prime" : "Not prime" )); } // Close the scanner object, because we've finished reading // all of the input from stdin needed for this challenge. in.close(); } } //============================:: SOLUTION ::=======================================//
gpl-3.0
jonashger/geduca
geduca/geduca-ejb/src/main/generated-sources/java/br/net/fireup/geduca/model/QTurno.java
1373
package br.net.fireup.geduca.model; import static com.mysema.query.types.PathMetadataFactory.*; import com.mysema.query.types.path.*; import com.mysema.query.types.PathMetadata; import javax.annotation.Generated; import com.mysema.query.types.Path; /** * QTurno is a Querydsl query type for Turno */ @Generated("com.mysema.query.codegen.EntitySerializer") public class QTurno extends EntityPathBase<Turno> { private static final long serialVersionUID = -497319398L; public static final QTurno turno = new QTurno("turno"); public final NumberPath<Long> codigoEmpresa = createNumber("codigoEmpresa", Long.class); public final StringPath descricao = createString("descricao"); public final TimePath<java.util.Date> horaFim = createTime("horaFim", java.util.Date.class); public final TimePath<java.util.Date> horaInicio = createTime("horaInicio", java.util.Date.class); public final NumberPath<Long> id = createNumber("id", Long.class); public final TimePath<java.util.Date> tempoAula = createTime("tempoAula", java.util.Date.class); public QTurno(String variable) { super(Turno.class, forVariable(variable)); } public QTurno(Path<? extends Turno> path) { super(path.getType(), path.getMetadata()); } public QTurno(PathMetadata<?> metadata) { super(Turno.class, metadata); } }
gpl-3.0
eaglgenes101/libgdx-tussle
core/src/com/tussle/stream/PipeBufferReader.java
1624
/* * Copyright (c) 2017 eaglgenes101 * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ package com.tussle.stream; import org.apache.commons.math3.util.FastMath; import java.io.Reader; //Please, use the loader method of PipeBufferWriter to get new PipeBufferReaders //This class won't work if instantiated directly public class PipeBufferReader extends Reader { StringBuilder buffer; PipeBufferWriter writer; PipeBufferReader(PipeBufferWriter out) { buffer = new StringBuilder(); out.open(this); writer = out; } public void append(char[] buf, int off, int len) { buffer.append(buf, off, len); } public void close() { writer.close(this); } public int read(char[] buf, int off, int len) { if (buffer.length() == 0) return -1; int tryLen = FastMath.min(len, buffer.length()); buffer.getChars(0, tryLen, buf, off); buffer.delete(0, tryLen); return tryLen; } public boolean ready() { return buffer.length() > 0; } public PipeBufferWriter getWriter() { return writer; } }
gpl-3.0
RoanH/KeysPerSecond
KeysPerSecond/src/dev/roanh/kps/layout/Layout.java
5766
package dev.roanh.kps.layout; import java.awt.Component; import java.awt.Container; import java.awt.Dimension; import java.awt.LayoutManager2; import dev.roanh.kps.Main; /** * Layout manager that handles the layout * of all the panels in the program * @author Roan */ public class Layout implements LayoutManager2{ /** * The maximum width of the layout in cells */ private int maxw; /** * The maximum height of the layout in cells */ private int maxh; /** * Extra width for the layout in cells. * Extra width comes from panels that are * rendered in the end position as those * do not count towards {@link #maxw} */ private int extraWidth = 0; /** * Extra height for the layout in cells. * Extra height comes from panels that are * rendered in the end position as those * do not count towards {@link #maxh} */ private int extraHeight = 0; /** * The container this is the * LayoutManager for */ private final Container parent; /** * Constructs a new Layout for * the given container * @param parent The container this * will be the layout for */ public Layout(Container parent){ this.parent = parent; parent.setLayout(this); } /** * Removes all the components that * were added to this layout */ public void removeAll(){ parent.removeAll(); extraWidth = 0; extraHeight = 0; } /** * Gets the width in pixels of this layout * @return The width in pixels of this layout */ public int getWidth(){ return Main.config.cellSize * (maxw + extraWidth); } /** * Gets the height in pixels of this layout * @return The height in pixels of this layout */ public int getHeight(){ return Main.config.cellSize * (maxh + extraHeight); } /** * Adds the given component to this layout * @param comp The component to add */ public void add(Component comp){ LayoutPosition lp = (LayoutPosition)comp; if(lp.getLayoutX() != -1){ maxw = Math.max(maxw, lp.getLayoutX() + lp.getLayoutWidth()); }else{ extraWidth += lp.getLayoutWidth(); } if(lp.getLayoutY() != -1){ maxh = Math.max(maxh, lp.getLayoutY() + lp.getLayoutHeight()); }else{ extraHeight += lp.getLayoutHeight(); } if(comp.getParent() == null){ parent.add(comp); } } /** * Recomputes the size of the layout */ private void recomputeGrid(){ LayoutPosition lp; maxw = 0; maxh = 0; for(Component component : parent.getComponents()){ lp = (LayoutPosition)component; maxw = Math.max(maxw, lp.getLayoutX() + lp.getLayoutWidth()); maxh = Math.max(maxh, lp.getLayoutY() + lp.getLayoutHeight()); } } @Override public String toString(){ return "Layout[components=" + parent.getComponentCount() + ",maxw=" + maxw + ",maxh=" + maxh + "]"; } @Override public void addLayoutComponent(Component comp, Object constraints){ add(comp); } @Override public void addLayoutComponent(String name, Component comp){ add(comp); } @Override public Dimension maximumLayoutSize(Container target){ return new Dimension(Integer.MAX_VALUE, Integer.MAX_VALUE); } @Override public float getLayoutAlignmentX(Container target){ return 0.5F; } @Override public float getLayoutAlignmentY(Container target){ return 0.5F; } @Override public void invalidateLayout(Container target){ } @Override public void removeLayoutComponent(Component comp){ recomputeGrid(); } @Override public Dimension preferredLayoutSize(Container parent){ return new Dimension(0, 0); } @Override public Dimension minimumLayoutSize(Container parent){ return new Dimension(0, 0); } @Override public void layoutContainer(Container parent){ if(!(maxw == 0 && extraWidth == 0) && !(maxh == 0 && extraHeight == 0)){ double dx = parent.getWidth() / (maxw + extraWidth); double dy = parent.getHeight() / (maxh + extraHeight); LayoutPosition lp; int width = maxw; int height = maxh; for(Component component : parent.getComponents()){ lp = (LayoutPosition)component; if(lp.getLayoutX() == -1){ if(lp.getLayoutY() == -1){ component.setBounds((int)Math.floor(dx * width), (int)Math.floor(dy * height), (int)Math.ceil(dx * lp.getLayoutWidth()), (int)Math.ceil(dy * lp.getLayoutHeight())); width += lp.getLayoutWidth(); height += lp.getLayoutHeight(); }else{ component.setBounds((int)Math.floor(dx * width), (int)Math.floor((lp.getLayoutHeight() == -1 ? 0 : dy) * (maxh - lp.getLayoutY() - lp.getLayoutHeight())), (int)Math.ceil(dx * lp.getLayoutWidth()), (int)Math.ceil(dy * (lp.getLayoutHeight() == -1 ? (maxh + extraHeight) : lp.getLayoutHeight()))); width += lp.getLayoutWidth(); } }else{ if(lp.getLayoutY() == -1){ component.setBounds((int)Math.floor((lp.getLayoutWidth() == -1 ? 0 : dx) * lp.getLayoutX()), (int)Math.floor(dy * height), (int)Math.ceil(dx * (lp.getLayoutWidth() == -1 ? (maxw + extraWidth) : lp.getLayoutWidth())), (int)Math.ceil(dy * lp.getLayoutHeight())); height += lp.getLayoutHeight(); }else{ component.setBounds((int)Math.floor((lp.getLayoutWidth() == -1 ? 0 : dx) * lp.getLayoutX()), (int)Math.floor((lp.getLayoutHeight() == -1 ? 0 : dy) * (maxh - lp.getLayoutY() - lp.getLayoutHeight())), (int)Math.ceil(dx * (lp.getLayoutWidth() == -1 ? (maxw + extraWidth) : lp.getLayoutWidth())), (int)Math.ceil(dy * (lp.getLayoutHeight() == -1 ? (maxh + extraHeight) : lp.getLayoutHeight()))); } } } } } }
gpl-3.0
januar/KulinARMedan
src/org/medankulinar/event/api/Category.java
606
package org.medankulinar.event.api; public class Category { private int id_category; private String category; private String image; public Category() { // TODO Auto-generated constructor stub } public void setIdCategory(int id_category) { this.id_category = id_category; } public int getIdCategory() { return this.id_category; } public void setCategory(String category) { this.category = category; } public String getCategory() { return this.category; } public void setImage(String image) { this.image = image; } public String getImage() { return this.image; } }
gpl-3.0
Cyntain/Fuelsmod
fuelsmod_common/com/cyntain/Fm/core/helper/LocalizationHelper.java
1103
package com.cyntain.Fm.core.helper; import cpw.mods.fml.common.registry.LanguageRegistry; public class LocalizationHelper { /*** * Simple test to determine if a specified file name represents a XML file * or not * * @param fileName * String representing the file name of the file in question * @return True if the file name represents a XML file, false otherwise */ public static boolean isXMLLanguageFile(String fileName) { return fileName.endsWith(".xml"); } /*** * Returns the locale from file name * * @param fileName * String representing the file name of the file in question * @return String representation of the locale snipped from the file name */ public static String getLocaleFromFileName(String fileName) { return fileName.substring(fileName.lastIndexOf('/') + 1, fileName.lastIndexOf('.')); } public static String getLocalizedString(String key) { return LanguageRegistry.instance().getStringLocalization(key); } }
gpl-3.0
3203317/vnc
BirdEgg/src/com/nwyun/birdegg/lib/rfb/Encodings.java
1917
/* Copyright (C) 2002-2005 RealVNC Ltd. All Rights Reserved. * * This is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 2 of the License, or * (at your option) any later version. * * This software is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this software; if not, write to the Free Software * Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, * USA. */ package com.nwyun.birdegg.lib.rfb; public class Encodings { public static final int raw = 0; public static final int copyRect = 1; public static final int RRE = 2; public static final int coRRE = 4; public static final int hextile = 5; public static final int ZRLE = 16; public static final int max = 255; public static final int pseudoEncodingCursor = 0xffffff11; public static final int pseudoEncodingDesktopSize = 0xffffff21; public static int num(String name) { if (name.equalsIgnoreCase("raw")) return raw; if (name.equalsIgnoreCase("copyRect")) return copyRect; if (name.equalsIgnoreCase("RRE")) return RRE; if (name.equalsIgnoreCase("coRRE")) return coRRE; if (name.equalsIgnoreCase("hextile")) return hextile; if (name.equalsIgnoreCase("ZRLE")) return ZRLE; return -1; } public static String name(int num) { switch (num) { case raw: return "raw"; case copyRect: return "copyRect"; case RRE: return "RRE"; case coRRE: return "CoRRE"; case hextile: return "hextile"; case ZRLE: return "ZRLE"; default: return "[unknown encoding]"; } } }
gpl-3.0
Jyotirdeb/SpeakDict
app/src/main/java/com/thearch/speakdict/main/AppBarLayoutHelper.java
2949
/* * Copyright (c) 2017 Jyotirdeb Mukherjee * * This file is part of SpeakDict. * * SpeakDict is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * SpeakDict is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with SpeakDict. If not, see <http://www.gnu.org/licenses/>. */ package com.thearch.speakdict.main; import android.app.Activity; import android.content.Context; import android.support.design.widget.AppBarLayout; import android.view.View; import com.thearch.speakdict.R; import com.thearch.speakdict.databinding.ActivityMainBinding; public final class AppBarLayoutHelper { private AppBarLayoutHelper() { // prevent instantiation } static void enableAutoHide(ActivityMainBinding binding) { Context context = binding.getRoot().getContext(); if (context.getResources().getBoolean(R.bool.toolbar_auto_hide)) { enableAutoHide(binding.toolbar); enableAutoHide(binding.tabs); } } private static void enableAutoHide(View view) { AppBarLayout.LayoutParams params = (AppBarLayout.LayoutParams) view.getLayoutParams(); params.setScrollFlags(AppBarLayout.LayoutParams.SCROLL_FLAG_SCROLL | AppBarLayout.LayoutParams.SCROLL_FLAG_ENTER_ALWAYS | AppBarLayout.LayoutParams.SCROLL_FLAG_SNAP); view.setLayoutParams(params); } public static void forceExpandAppBarLayout(Activity activity) { if (activity == null || activity.isFinishing()) return; AppBarLayout appBarLayout = (AppBarLayout) activity.findViewById(R.id.app_bar_layout); if (appBarLayout != null) { forceExpandAppBarLayout(appBarLayout); } } static void forceExpandAppBarLayout(final AppBarLayout appBarLayout) { if (!appBarLayout.getContext().getResources().getBoolean(R.bool.toolbar_auto_hide)) return; // Add a 100ms delay to prevent this issue: // * The user is in the reader tab, with the keyboard open // * The user swipes quickly right to the empty favorites tab // * While we try to display the app bar layout, the soft keyboard is hidden by the app // * We have a glitch: the app bar layout seems to appear briefly but becomes hidden again. // With a small delay we try to make sure the event to show the app bar layout is done after // the soft keyboard is hidden. // I don't like this arbitrary delay :( appBarLayout.postDelayed(()->appBarLayout.setExpanded(true, true), 100); } }
gpl-3.0
guiguilechat/EveOnline
model/sde/SDE-Types/src/generated/java/fr/guiguilechat/jcelechat/model/sde/attributes/StructureHPMultiplier.java
864
package fr.guiguilechat.jcelechat.model.sde.attributes; import fr.guiguilechat.jcelechat.model.sde.DoubleAttribute; /** * Multiplier to the ships structural HP. */ public class StructureHPMultiplier extends DoubleAttribute { public static final StructureHPMultiplier INSTANCE = new StructureHPMultiplier(); @Override public int getId() { return 150; } @Override public int getCatId() { return 7; } @Override public boolean getHighIsGood() { return true; } @Override public double getDefaultValue() { return 1.0; } @Override public boolean getPublished() { return true; } @Override public boolean getStackable() { return true; } @Override public String toString() { return "StructureHPMultiplier"; } }
gpl-3.0
paulobcosta/ClassSimilarityAnalizer
src/br/com/localhost/gui/Loading.java
2189
package br.com.localhost.gui; import java.awt.EventQueue; import javax.swing.JFrame; import javax.swing.JPanel; import javax.swing.border.EmptyBorder; import javax.swing.JButton; import javax.swing.JLabel; import javax.swing.JProgressBar; import javax.swing.ImageIcon; import javax.swing.UIManager; import java.awt.Toolkit; public class Loading extends JFrame { /** * */ private static final long serialVersionUID = 1L; private JPanel contentPane; private JProgressBar progressBar; public JButton btnNewButton; public JLabel lblNewLabel; /** * Launch the application. */ public static void main(String[] args) { EventQueue.invokeLater(new Runnable() { public void run() { try { Loading frame = new Loading(); frame.setVisible(true); } catch (Exception e) { e.printStackTrace(); } } }); } /** * Create the frame. */ public Loading() { setResizable(false); setIconImage(Toolkit.getDefaultToolkit().getImage(Loading.class.getResource("/br/com/localhost/gui/Coffee-icon.png"))); setDefaultCloseOperation(JFrame.DO_NOTHING_ON_CLOSE); setBounds(100, 100, 450, 191); contentPane = new JPanel(); contentPane.setBorder(new EmptyBorder(5, 5, 5, 5)); setContentPane(contentPane); contentPane.setLayout(null); this.btnNewButton = new JButton("OK"); this.btnNewButton.setBounds(319, 131, 111, 20); this.btnNewButton.setEnabled(false); contentPane.add(this.btnNewButton); this.lblNewLabel = new JLabel(); lblNewLabel.setIcon(new ImageIcon(Loading.class.getResource("/br/com/localhost/gui/File-CSV-icon.png"))); lblNewLabel.setBounds(12, 0, 396, 44); contentPane.add(lblNewLabel); this.progressBar = new JProgressBar(); this.progressBar.setValue(0); this.progressBar.setForeground(UIManager.getColor("OptionPane.questionDialog.titlePane.shadow")); this.progressBar.setStringPainted(true); this.progressBar.setBounds(51, 66, 357, 33); contentPane.add(this.progressBar); } public void refreshStatus(int i,Loading l, String part) { this.progressBar.setValue(i); l.setTitle(" Montando ... " + i + "% " + part); if(i == 100) { l.btnNewButton.setEnabled(true); } } }
gpl-3.0
ConnorStroomberg/addis-core
src/main/java/org/drugis/addis/interventions/model/BothDoseTypesIntervention.java
4474
package org.drugis.addis.interventions.model; import org.drugis.addis.interventions.controller.viewAdapter.AbstractInterventionViewAdapter; import org.drugis.addis.interventions.controller.viewAdapter.BothDoseTypesInterventionViewAdapter; import javax.persistence.*; import java.net.URI; /** * Created by daan on 5-4-16. */ @Entity @PrimaryKeyJoinColumn(name = "bothTypesInterventionId", referencedColumnName = "singleInterventionId") public class BothDoseTypesIntervention extends SingleIntervention { @Embedded @AttributeOverrides( { @AttributeOverride(name="lowerBound.type" , column = @Column(name="minLowerBoundType") ), @AttributeOverride(name="lowerBound.unitName" , column = @Column(name="minLowerBoundUnitName") ), @AttributeOverride(name="lowerBound.unitPeriod" , column = @Column(name="minLowerBoundUnitPeriod") ), @AttributeOverride(name="lowerBound.unitConcept" , column = @Column(name="minLowerBoundUnitConcept") ), @AttributeOverride(name="lowerBound.value", column = @Column(name="minLowerBoundValue") ), @AttributeOverride(name="upperBound.type" , column = @Column(name="minUpperBoundType") ), @AttributeOverride(name="upperBound.unitName" , column = @Column(name="minUpperBoundUnitName") ), @AttributeOverride(name="upperBound.unitPeriod" , column = @Column(name="minUpperBoundUnitPeriod") ), @AttributeOverride(name="upperBound.unitConcept" , column = @Column(name="minUpperBoundUnitConcept") ), @AttributeOverride(name="upperBound.value", column = @Column(name="minUpperBoundValue") ) } ) private DoseConstraint minConstraint; @Embedded @AttributeOverrides( { @AttributeOverride(name="lowerBound.type" , column = @Column(name="maxLowerBoundType") ), @AttributeOverride(name="lowerBound.unitName" , column = @Column(name="maxLowerBoundUnitName") ), @AttributeOverride(name="lowerBound.unitPeriod" , column = @Column(name="maxLowerBoundUnitPeriod") ), @AttributeOverride(name="lowerBound.unitConcept" , column = @Column(name="maxLowerBoundUnitConcept") ), @AttributeOverride(name="lowerBound.value", column = @Column(name="maxLowerBoundValue") ), @AttributeOverride(name="upperBound.type" , column = @Column(name="maxUpperBoundType") ), @AttributeOverride(name="upperBound.unitName" , column = @Column(name="maxUpperBoundUnitName") ), @AttributeOverride(name="upperBound.unitPeriod" , column = @Column(name="maxUpperBoundUnitPeriod") ), @AttributeOverride(name="upperBound.unitConcept" , column = @Column(name="maxUpperBoundUnitConcept") ), @AttributeOverride(name="upperBound.value", column = @Column(name="maxUpperBoundValue") ) } ) private DoseConstraint maxConstraint; public BothDoseTypesIntervention() { } @Override public AbstractInterventionViewAdapter toViewAdapter() { return new BothDoseTypesInterventionViewAdapter(this); } public BothDoseTypesIntervention(DoseConstraint minConstraint, DoseConstraint maxConstraint) { this.minConstraint = minConstraint; this.maxConstraint = maxConstraint; } public BothDoseTypesIntervention(Integer id, Integer project, String name, String motivation, URI semanticInterventionUri, String semanticInterventionLabel, DoseConstraint minConstraint, DoseConstraint maxConstraint) { super(id, project, name, motivation, semanticInterventionUri, semanticInterventionLabel); this.minConstraint = minConstraint; this.maxConstraint = maxConstraint; } public DoseConstraint getMinConstraint() { return minConstraint; } public DoseConstraint getMaxConstraint() { return maxConstraint; } @Override public boolean equals(Object o) { if (this == o) return true; if (o == null || getClass() != o.getClass()) return false; if (!super.equals(o)) return false; BothDoseTypesIntervention that = (BothDoseTypesIntervention) o; if (minConstraint != null ? !minConstraint.equals(that.minConstraint) : that.minConstraint != null) return false; return maxConstraint != null ? maxConstraint.equals(that.maxConstraint) : that.maxConstraint == null; } @Override public int hashCode() { int result = super.hashCode(); result = 31 * result + (minConstraint != null ? minConstraint.hashCode() : 0); result = 31 * result + (maxConstraint != null ? maxConstraint.hashCode() : 0); return result; } }
gpl-3.0
Ektoplasma/TheLuggage
JAVA/Libraries/SrcLibraries/src/hashPackage/Hash.java
1357
package hashPackage; import java.security.MessageDigest; import java.util.regex.Pattern; public class Hash { public String hashFunction(String stringToHash) throws Exception { String generatedString=null; MessageDigest md = MessageDigest.getInstance("SHA-256"); md.update(stringToHash.getBytes()); byte[] bytes = md.digest(); StringBuilder sb = new StringBuilder(); for(int i=0; i< bytes.length ;i++){ sb.append(Integer.toString((bytes[i] & 0xff) + 0x100, 16).substring(1)); } generatedString = sb.toString(); return generatedString; } public boolean verifPass(String password, String realPassword) throws Exception { /* TODO RECHERCHE DE STRING HACHEE EN TANT QUE 'REALPASSWORD' DANS LA BDD SUIVANT LE NOM D'UTILISATEUR + SPLIT DE CETTE STRING SUIVANT '$' */ String[] splitString = realPassword.split(Pattern.quote("$")); String generatedHash=hashFunction(password+splitString[0]); if(generatedHash.compareTo(splitString[1])==0){ return true; } else { return false; } } public String generateSalt() { String chars = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ1234567890"; StringBuilder pass = new StringBuilder (chars.length()); for (int x = 0; x < 10; x++) { int i = (int) (Math.random() * chars.length()); pass.append(chars.charAt(i)); } return pass.toString(); } }
gpl-3.0
winder/Universal-G-Code-Sender
ugs-platform/ugs-platform-ugscore/src/main/java/com/willwinder/ugs/nbp/core/actions/ConnectDisconnectAction.java
5492
/* Copyright 2015-2018 Will Winder This file is part of Universal Gcode Sender (UGS). UGS is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. UGS is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with UGS. If not, see <http://www.gnu.org/licenses/>. */ package com.willwinder.ugs.nbp.core.actions; import com.willwinder.ugs.nbp.lib.lookup.CentralLookup; import com.willwinder.ugs.nbp.lib.services.LocalizingService; import com.willwinder.universalgcodesender.listeners.ControllerState; import com.willwinder.universalgcodesender.listeners.UGSEventListener; import com.willwinder.universalgcodesender.model.BackendAPI; import com.willwinder.universalgcodesender.model.UGSEvent; import com.willwinder.universalgcodesender.model.events.ControllerStateEvent; import com.willwinder.universalgcodesender.utils.GUIHelpers; import com.willwinder.universalgcodesender.utils.Settings; import com.willwinder.universalgcodesender.utils.ThreadHelper; import org.apache.commons.lang3.StringUtils; import org.openide.awt.ActionID; import org.openide.awt.ActionReference; import org.openide.awt.ActionReferences; import org.openide.awt.ActionRegistration; import org.openide.util.ImageUtilities; import javax.swing.*; import java.awt.*; import java.awt.event.ActionEvent; import java.util.logging.Level; import java.util.logging.Logger; /** * An action for connecting or disconnecting to a controller * * @author wwinder */ @ActionID( category = LocalizingService.ConnectDisconnectCategory, id = LocalizingService.ConnectDisconnectActionId) @ActionRegistration( iconBase = ConnectDisconnectAction.ICON_BASE_DISCONNECT, displayName = "resources.MessagesBundle#" + LocalizingService.ConnectDisconnectActionTitleKey, lazy = false) @ActionReferences({ @ActionReference( path = LocalizingService.ConnectWindowPath, position = 900), @ActionReference( path = "Toolbars/Connection", position = 975) }) public class ConnectDisconnectAction extends AbstractAction implements UGSEventListener { public static final String ICON_BASE = "resources/icons/connect.svg"; public static final String ICON_BASE_DISCONNECT = "resources/icons/disconnect.svg"; private static final Logger logger = Logger.getLogger(ConnectDisconnectAction.class.getName()); private BackendAPI backend; public ConnectDisconnectAction() { this.backend = CentralLookup.getDefault().lookup(BackendAPI.class); if (this.backend != null) { this.backend.addUGSEventListener(this); } updateIconAndText(); } @Override public void UGSEvent(UGSEvent cse) { if (cse instanceof ControllerStateEvent) { EventQueue.invokeLater(this::updateIconAndText); } } private void updateIconAndText() { if (backend.getControllerState() == ControllerState.DISCONNECTED) { putValue(NAME, LocalizingService.ConnectDisconnectTitleConnect); putValue("menuText", LocalizingService.ConnectDisconnectTitleConnect); putValue("iconBase", ICON_BASE_DISCONNECT); putValue(SMALL_ICON, ImageUtilities.loadImageIcon(ICON_BASE_DISCONNECT, false)); } else { putValue(NAME, LocalizingService.ConnectDisconnectTitleDisconnect); putValue("menuText", LocalizingService.ConnectDisconnectTitleDisconnect); putValue("iconBase", ICON_BASE); putValue(SMALL_ICON, ImageUtilities.loadImageIcon(ICON_BASE, false)); } } @Override public void actionPerformed(ActionEvent e) { try { connect(); } catch (Exception ex) { ex.printStackTrace(); } } @Override public boolean isEnabled() { // The action should always be enabled return true; } private void connect() { logger.log(Level.INFO, "openclose button, connection open: {0}", backend.isConnected()); if (backend.getControllerState() == ControllerState.DISCONNECTED) { Settings s = backend.getSettings(); String firmware = s.getFirmwareVersion(); String port = s.getPort(); int baudRate = Integer.parseInt(s.getPortRate()); ThreadHelper.invokeLater(() -> { try { backend.connect(firmware, port, baudRate); } catch (Exception e) { GUIHelpers.displayErrorDialog(e.getMessage()); } }); } else { try { backend.disconnect(); } catch (Exception e) { String message = e.getMessage(); if (StringUtils.isEmpty(message)) { message = "Got an unknown error while disconnecting, see log for more details"; logger.log(Level.SEVERE, "Got an unknown error while disconnecting", e); } GUIHelpers.displayErrorDialog(message); } } } }
gpl-3.0
wmarquesr/NoSQLProject
src/com/fasterxml/jackson/databind/deser/std/PrimitiveArrayDeserializers.java
22425
package com.fasterxml.jackson.databind.deser.std; import java.io.IOException; import com.fasterxml.jackson.annotation.JsonFormat; import com.fasterxml.jackson.core.*; import com.fasterxml.jackson.databind.*; import com.fasterxml.jackson.databind.annotation.JacksonStdImpl; import com.fasterxml.jackson.databind.deser.ContextualDeserializer; import com.fasterxml.jackson.databind.jsontype.TypeDeserializer; import com.fasterxml.jackson.databind.util.ArrayBuilders; /** * Container for deserializers used for instantiating "primitive arrays", * arrays that contain non-object java primitive types. */ @SuppressWarnings("serial") public abstract class PrimitiveArrayDeserializers<T> extends StdDeserializer<T> implements ContextualDeserializer // since 2.7 { /** * Specific override for this instance (from proper, or global per-type overrides) * to indicate whether single value may be taken to mean an unwrapped one-element array * or not. If null, left to global defaults. * * @since 2.7 */ protected final Boolean _unwrapSingle; protected PrimitiveArrayDeserializers(Class<T> cls) { super(cls); _unwrapSingle = null; } /** * @since 2.7 */ protected PrimitiveArrayDeserializers(PrimitiveArrayDeserializers<?> base, Boolean unwrapSingle) { super(base._valueClass); _unwrapSingle = unwrapSingle; } public static JsonDeserializer<?> forType(Class<?> rawType) { // Start with more common types... if (rawType == Integer.TYPE) { return IntDeser.instance; } if (rawType == Long.TYPE) { return LongDeser.instance; } if (rawType == Byte.TYPE) { return new ByteDeser(); } if (rawType == Short.TYPE) { return new ShortDeser(); } if (rawType == Float.TYPE) { return new FloatDeser(); } if (rawType == Double.TYPE) { return new DoubleDeser(); } if (rawType == Boolean.TYPE) { return new BooleanDeser(); } if (rawType == Character.TYPE) { return new CharDeser(); } throw new IllegalStateException(); } /** * @since 2.7 */ protected abstract PrimitiveArrayDeserializers<?> withResolved(Boolean unwrapSingle); @Override public JsonDeserializer<?> createContextual(DeserializationContext ctxt, BeanProperty property) throws JsonMappingException { Boolean unwrapSingle = findFormatFeature(ctxt, property, _valueClass, JsonFormat.Feature.ACCEPT_SINGLE_VALUE_AS_ARRAY); if (unwrapSingle == _unwrapSingle) { return this; } return withResolved(unwrapSingle); } @Override public Object deserializeWithType(JsonParser p, DeserializationContext ctxt, TypeDeserializer typeDeserializer) throws IOException { /* Should there be separate handling for base64 stuff? * for now this should be enough: */ return typeDeserializer.deserializeTypedFromArray(p, ctxt); } protected T handleNonArray(JsonParser p, DeserializationContext ctxt) throws IOException { // [JACKSON-620] Empty String can become null... if (p.hasToken(JsonToken.VALUE_STRING) && ctxt.isEnabled(DeserializationFeature.ACCEPT_EMPTY_STRING_AS_NULL_OBJECT)) { if (p.getText().length() == 0) { return null; } } boolean canWrap = (_unwrapSingle == Boolean.TRUE) || ((_unwrapSingle == null) && ctxt.isEnabled(DeserializationFeature.ACCEPT_SINGLE_VALUE_AS_ARRAY)); if (canWrap) { return handleSingleElementUnwrapped(p, ctxt); } ctxt.reportMappingException(_valueClass); return null; } protected abstract T handleSingleElementUnwrapped(JsonParser p, DeserializationContext ctxt) throws IOException; /* /******************************************************** /* Actual deserializers: efficient String[], char[] deserializers /******************************************************** */ @JacksonStdImpl final static class CharDeser extends PrimitiveArrayDeserializers<char[]> { private static final long serialVersionUID = 1L; public CharDeser() { super(char[].class); } protected CharDeser(CharDeser base, Boolean unwrapSingle) { super(base, unwrapSingle); } @Override protected PrimitiveArrayDeserializers<?> withResolved(Boolean unwrapSingle) { // 11-Dec-2015, tatu: Not sure how re-wrapping would work; omit return this; } @Override public char[] deserialize(JsonParser p, DeserializationContext ctxt) throws IOException { /* Won't take arrays, must get a String (could also * convert other tokens to Strings... but let's not bother * yet, doesn't seem to make sense) */ JsonToken t = p.getCurrentToken(); if (t == JsonToken.VALUE_STRING) { // note: can NOT return shared internal buffer, must copy: char[] buffer = p.getTextCharacters(); int offset = p.getTextOffset(); int len = p.getTextLength(); char[] result = new char[len]; System.arraycopy(buffer, offset, result, 0, len); return result; } if (p.isExpectedStartArrayToken()) { // Let's actually build as a String, then get chars StringBuilder sb = new StringBuilder(64); while ((t = p.nextToken()) != JsonToken.END_ARRAY) { if (t != JsonToken.VALUE_STRING) { ctxt.reportMappingException(Character.TYPE); return null; } String str = p.getText(); if (str.length() != 1) { throw JsonMappingException.from(p, "Can not convert a JSON String of length "+str.length()+" into a char element of char array"); } sb.append(str.charAt(0)); } return sb.toString().toCharArray(); } // or, maybe an embedded object? if (t == JsonToken.VALUE_EMBEDDED_OBJECT) { Object ob = p.getEmbeddedObject(); if (ob == null) return null; if (ob instanceof char[]) { return (char[]) ob; } if (ob instanceof String) { return ((String) ob).toCharArray(); } // 04-Feb-2011, tatu: byte[] can be converted; assuming base64 is wanted if (ob instanceof byte[]) { return Base64Variants.getDefaultVariant().encode((byte[]) ob, false).toCharArray(); } // not recognized, just fall through } ctxt.reportMappingException(_valueClass); return null; } @Override protected char[] handleSingleElementUnwrapped(JsonParser p, DeserializationContext ctxt) throws IOException { // not sure how this should work... ctxt.reportMappingException(_valueClass); return null; } } /* /********************************************************** /* Actual deserializers: primivate array desers /********************************************************** */ @JacksonStdImpl final static class BooleanDeser extends PrimitiveArrayDeserializers<boolean[]> { private static final long serialVersionUID = 1L; public BooleanDeser() { super(boolean[].class); } protected BooleanDeser(BooleanDeser base, Boolean unwrapSingle) { super(base, unwrapSingle); } @Override protected PrimitiveArrayDeserializers<?> withResolved(Boolean unwrapSingle) { return new BooleanDeser(this, unwrapSingle); } @Override public boolean[] deserialize(JsonParser p, DeserializationContext ctxt) throws IOException, JsonProcessingException { if (!p.isExpectedStartArrayToken()) { return handleNonArray(p, ctxt); } ArrayBuilders.BooleanBuilder builder = ctxt.getArrayBuilders().getBooleanBuilder(); boolean[] chunk = builder.resetAndStart(); int ix = 0; try { while (p.nextToken() != JsonToken.END_ARRAY) { // whether we should allow truncating conversions? boolean value = _parseBooleanPrimitive(p, ctxt); if (ix >= chunk.length) { chunk = builder.appendCompletedChunk(chunk, ix); ix = 0; } chunk[ix++] = value; } } catch (Exception e) { throw JsonMappingException.wrapWithPath(e, chunk, builder.bufferedSize() + ix); } return builder.completeAndClearBuffer(chunk, ix); } @Override protected boolean[] handleSingleElementUnwrapped(JsonParser p, DeserializationContext ctxt) throws IOException { return new boolean[] { _parseBooleanPrimitive(p, ctxt) }; } } /** * When dealing with byte arrays we have one more alternative (compared * to int/long/shorts): base64 encoded data. */ @JacksonStdImpl final static class ByteDeser extends PrimitiveArrayDeserializers<byte[]> { private static final long serialVersionUID = 1L; public ByteDeser() { super(byte[].class); } protected ByteDeser(ByteDeser base, Boolean unwrapSingle) { super(base, unwrapSingle); } @Override protected PrimitiveArrayDeserializers<?> withResolved(Boolean unwrapSingle) { return new ByteDeser(this, unwrapSingle); } @Override public byte[] deserialize(JsonParser p, DeserializationContext ctxt) throws IOException { JsonToken t = p.getCurrentToken(); // Most likely case: base64 encoded String? if (t == JsonToken.VALUE_STRING) { return p.getBinaryValue(ctxt.getBase64Variant()); } // 31-Dec-2009, tatu: Also may be hidden as embedded Object if (t == JsonToken.VALUE_EMBEDDED_OBJECT) { Object ob = p.getEmbeddedObject(); if (ob == null) return null; if (ob instanceof byte[]) { return (byte[]) ob; } } if (!p.isExpectedStartArrayToken()) { return handleNonArray(p, ctxt); } ArrayBuilders.ByteBuilder builder = ctxt.getArrayBuilders().getByteBuilder(); byte[] chunk = builder.resetAndStart(); int ix = 0; try { while ((t = p.nextToken()) != JsonToken.END_ARRAY) { // whether we should allow truncating conversions? byte value; if (t == JsonToken.VALUE_NUMBER_INT || t == JsonToken.VALUE_NUMBER_FLOAT) { // should we catch overflow exceptions? value = p.getByteValue(); } else { // should probably accept nulls as 0 if (t != JsonToken.VALUE_NULL) { ctxt.reportMappingException(_valueClass.getComponentType()); return null; } value = (byte) 0; } if (ix >= chunk.length) { chunk = builder.appendCompletedChunk(chunk, ix); ix = 0; } chunk[ix++] = value; } } catch (Exception e) { throw JsonMappingException.wrapWithPath(e, chunk, builder.bufferedSize() + ix); } return builder.completeAndClearBuffer(chunk, ix); } @Override protected byte[] handleSingleElementUnwrapped(JsonParser p, DeserializationContext ctxt) throws IOException { byte value; JsonToken t = p.getCurrentToken(); if (t == JsonToken.VALUE_NUMBER_INT || t == JsonToken.VALUE_NUMBER_FLOAT) { // should we catch overflow exceptions? value = p.getByteValue(); } else { // should probably accept nulls as 'false' if (t != JsonToken.VALUE_NULL) { ctxt.reportMappingException(_valueClass.getComponentType()); return null; } value = (byte) 0; } return new byte[] { value }; } } @JacksonStdImpl final static class ShortDeser extends PrimitiveArrayDeserializers<short[]> { private static final long serialVersionUID = 1L; public ShortDeser() { super(short[].class); } protected ShortDeser(ShortDeser base, Boolean unwrapSingle) { super(base, unwrapSingle); } @Override protected PrimitiveArrayDeserializers<?> withResolved(Boolean unwrapSingle) { return new ShortDeser(this, unwrapSingle); } @Override public short[] deserialize(JsonParser p, DeserializationContext ctxt) throws IOException { if (!p.isExpectedStartArrayToken()) { return handleNonArray(p, ctxt); } ArrayBuilders.ShortBuilder builder = ctxt.getArrayBuilders().getShortBuilder(); short[] chunk = builder.resetAndStart(); int ix = 0; try { while (p.nextToken() != JsonToken.END_ARRAY) { short value = _parseShortPrimitive(p, ctxt); if (ix >= chunk.length) { chunk = builder.appendCompletedChunk(chunk, ix); ix = 0; } chunk[ix++] = value; } } catch (Exception e) { throw JsonMappingException.wrapWithPath(e, chunk, builder.bufferedSize() + ix); } return builder.completeAndClearBuffer(chunk, ix); } @Override protected short[] handleSingleElementUnwrapped(JsonParser p, DeserializationContext ctxt) throws IOException { return new short[] { _parseShortPrimitive(p, ctxt) }; } } @JacksonStdImpl final static class IntDeser extends PrimitiveArrayDeserializers<int[]> { private static final long serialVersionUID = 1L; public final static IntDeser instance = new IntDeser(); public IntDeser() { super(int[].class); } protected IntDeser(IntDeser base, Boolean unwrapSingle) { super(base, unwrapSingle); } @Override protected PrimitiveArrayDeserializers<?> withResolved(Boolean unwrapSingle) { return new IntDeser(this, unwrapSingle); } @Override public int[] deserialize(JsonParser p, DeserializationContext ctxt) throws IOException { if (!p.isExpectedStartArrayToken()) { return handleNonArray(p, ctxt); } ArrayBuilders.IntBuilder builder = ctxt.getArrayBuilders().getIntBuilder(); int[] chunk = builder.resetAndStart(); int ix = 0; try { while (p.nextToken() != JsonToken.END_ARRAY) { // whether we should allow truncating conversions? int value = _parseIntPrimitive(p, ctxt); if (ix >= chunk.length) { chunk = builder.appendCompletedChunk(chunk, ix); ix = 0; } chunk[ix++] = value; } } catch (Exception e) { throw JsonMappingException.wrapWithPath(e, chunk, builder.bufferedSize() + ix); } return builder.completeAndClearBuffer(chunk, ix); } @Override protected int[] handleSingleElementUnwrapped(JsonParser p, DeserializationContext ctxt) throws IOException { return new int[] { _parseIntPrimitive(p, ctxt) }; } } @JacksonStdImpl final static class LongDeser extends PrimitiveArrayDeserializers<long[]> { private static final long serialVersionUID = 1L; public final static LongDeser instance = new LongDeser(); public LongDeser() { super(long[].class); } protected LongDeser(LongDeser base, Boolean unwrapSingle) { super(base, unwrapSingle); } @Override protected PrimitiveArrayDeserializers<?> withResolved(Boolean unwrapSingle) { return new LongDeser(this, unwrapSingle); } @Override public long[] deserialize(JsonParser p, DeserializationContext ctxt) throws IOException { if (!p.isExpectedStartArrayToken()) { return handleNonArray(p, ctxt); } ArrayBuilders.LongBuilder builder = ctxt.getArrayBuilders().getLongBuilder(); long[] chunk = builder.resetAndStart(); int ix = 0; try { while (p.nextToken() != JsonToken.END_ARRAY) { long value = _parseLongPrimitive(p, ctxt); if (ix >= chunk.length) { chunk = builder.appendCompletedChunk(chunk, ix); ix = 0; } chunk[ix++] = value; } } catch (Exception e) { throw JsonMappingException.wrapWithPath(e, chunk, builder.bufferedSize() + ix); } return builder.completeAndClearBuffer(chunk, ix); } @Override protected long[] handleSingleElementUnwrapped(JsonParser p, DeserializationContext ctxt) throws IOException { return new long[] { _parseLongPrimitive(p, ctxt) }; } } @JacksonStdImpl final static class FloatDeser extends PrimitiveArrayDeserializers<float[]> { private static final long serialVersionUID = 1L; public FloatDeser() { super(float[].class); } protected FloatDeser(FloatDeser base, Boolean unwrapSingle) { super(base, unwrapSingle); } @Override protected PrimitiveArrayDeserializers<?> withResolved(Boolean unwrapSingle) { return new FloatDeser(this, unwrapSingle); } @Override public float[] deserialize(JsonParser p, DeserializationContext ctxt) throws IOException, JsonProcessingException { if (!p.isExpectedStartArrayToken()) { return handleNonArray(p, ctxt); } ArrayBuilders.FloatBuilder builder = ctxt.getArrayBuilders().getFloatBuilder(); float[] chunk = builder.resetAndStart(); int ix = 0; try { while (p.nextToken() != JsonToken.END_ARRAY) { // whether we should allow truncating conversions? float value = _parseFloatPrimitive(p, ctxt); if (ix >= chunk.length) { chunk = builder.appendCompletedChunk(chunk, ix); ix = 0; } chunk[ix++] = value; } } catch (Exception e) { throw JsonMappingException.wrapWithPath(e, chunk, builder.bufferedSize() + ix); } return builder.completeAndClearBuffer(chunk, ix); } @Override protected float[] handleSingleElementUnwrapped(JsonParser p, DeserializationContext ctxt) throws IOException { return new float[] { _parseFloatPrimitive(p, ctxt) }; } } @JacksonStdImpl final static class DoubleDeser extends PrimitiveArrayDeserializers<double[]> { private static final long serialVersionUID = 1L; public DoubleDeser() { super(double[].class); } protected DoubleDeser(DoubleDeser base, Boolean unwrapSingle) { super(base, unwrapSingle); } @Override protected PrimitiveArrayDeserializers<?> withResolved(Boolean unwrapSingle) { return new DoubleDeser(this, unwrapSingle); } @Override public double[] deserialize(JsonParser p, DeserializationContext ctxt) throws IOException { if (!p.isExpectedStartArrayToken()) { return handleNonArray(p, ctxt); } ArrayBuilders.DoubleBuilder builder = ctxt.getArrayBuilders().getDoubleBuilder(); double[] chunk = builder.resetAndStart(); int ix = 0; try { while (p.nextToken() != JsonToken.END_ARRAY) { double value = _parseDoublePrimitive(p, ctxt); if (ix >= chunk.length) { chunk = builder.appendCompletedChunk(chunk, ix); ix = 0; } chunk[ix++] = value; } } catch (Exception e) { throw JsonMappingException.wrapWithPath(e, chunk, builder.bufferedSize() + ix); } return builder.completeAndClearBuffer(chunk, ix); } @Override protected double[] handleSingleElementUnwrapped(JsonParser p, DeserializationContext ctxt) throws IOException { return new double[] { _parseDoublePrimitive(p, ctxt) }; } } }
gpl-3.0
mksmbrtsh/timestatistic
app/src/main/java/decoro/watchers/DescriptorFormatWatcher.java
2224
/* * Copyright © 2016 Tinkoff Bank * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package ru.tinkoff.decoro.watchers; import android.support.annotation.NonNull; import android.support.annotation.Nullable; import ru.tinkoff.decoro.Mask; import ru.tinkoff.decoro.MaskDescriptor; import ru.tinkoff.decoro.MaskFactoryImpl; import ru.tinkoff.decoro.parser.SlotsParser; /** * @author Mikhail Artemev */ public class DescriptorFormatWatcher extends FormatWatcher { private SlotsParser slotsParser; private MaskDescriptor maskDescriptor; public DescriptorFormatWatcher(@Nullable SlotsParser slotsParser) { this.slotsParser = slotsParser; } public DescriptorFormatWatcher(@Nullable SlotsParser slotsParser, @Nullable MaskDescriptor maskDescriptor) { this.slotsParser = slotsParser; this.maskDescriptor = maskDescriptor; if (maskDescriptor != null) { changeMask(maskDescriptor); } } public DescriptorFormatWatcher() { this(null, MaskDescriptor.emptyMask()); } public DescriptorFormatWatcher(@Nullable MaskDescriptor maskDescriptor) { this(null, maskDescriptor); } public void changeMask(@NonNull final MaskDescriptor maskDescriptor) { this.maskDescriptor = maskDescriptor; refreshMask(maskDescriptor.getInitialValue()); } @NonNull @Override public Mask createMask() { return new MaskFactoryImpl(slotsParser, maskDescriptor).createMask(); } public void setSlotsParser(@Nullable SlotsParser slotsParser) { this.slotsParser = slotsParser; } @Nullable public SlotsParser getSlotsParser() { return slotsParser; } }
gpl-3.0
5zig/Platformer
src/plattformer/screens/GameScreen.java
860
package plattformer.screens; import plattformer.Game; import plattformer.level.Level; public class GameScreen extends Screen { private Level level; private int xScroll, yScroll; public GameScreen(Game game, Level level) { super(game); this.level = level; yScroll = 120; } public void render() { level.render(this, xScroll, yScroll); } public void tick() { level.tick(); xScroll = game.getPlayer().getX() - game.getScaledWidth() / 2; //yScroll = game.getPlayer().getY() - game.getScaledHeight() / 2; // allow screen scroll only til max int maxwidth = level.getWidth() * 16 - game.getScaledWidth(); if (xScroll > maxwidth) xScroll = maxwidth; if (xScroll < 0) xScroll = 0; int maxheight = level.getHeight() * 16 - game.getScaledHeight(); if (yScroll > maxheight) yScroll = maxheight; if (yScroll < 0) yScroll = 0; } }
gpl-3.0
Curtis3321/Essentials
Essentials/src/net/ess3/user/UserMap.java
6918
package net.ess3.user; import java.io.File; import java.util.*; import java.util.regex.Pattern; import static net.ess3.I18n._; import net.ess3.api.IEssentials; import net.ess3.api.IUser; import net.ess3.api.IUserMap; import net.ess3.api.InvalidNameException; import net.ess3.storage.StorageObjectMap; import net.ess3.utils.FormatUtil; import org.bukkit.entity.Player; public class UserMap extends StorageObjectMap<IUser> implements IUserMap { private final Map<String, Player> prejoinedPlayers = new HashMap<String, Player>(); public UserMap(final IEssentials ess) { super(ess, "users"); } @Override public boolean userExists(final String name) { return objectExists(name); } @Override public IUser getUser(final String name) { return getObject(name); } @Override public IUser load(final String name) throws Exception { final String lowercaseName = name.toLowerCase(Locale.ENGLISH); if (!lowercaseName.equals(name)) { final IUser user = getUser(lowercaseName); if (user == null) { throw new Exception(_("userNotFound")); } else { return user; } } Player player = prejoinedPlayers.get(name); if (player == null) { player = ess.getServer().getPlayerExact(name); } if (player != null) { return new User(ess.getServer().getOfflinePlayer(player.getName()), ess); } final File userFile = getUserFile(name); if (userFile.exists()) { keys.add(name.toLowerCase(Locale.ENGLISH)); return new User(ess.getServer().getOfflinePlayer(name), ess); } throw new Exception(_("userNotFound")); } @Override public void removeUser(final String name) throws InvalidNameException { removeObject(name); } @Override public Set<String> getAllUniqueUsers() { return getAllKeys(); } @Override public int getUniqueUsers() { return getKeySize(); } @Override public File getUserFile(String name) throws InvalidNameException { return getStorageFile(name); } @Override public IUser getUser(final Player player) { return getObject(player.getName()); } @Override public IUser matchUser(final String name, final boolean includeOffline) throws TooManyMatchesException, PlayerNotFoundException { return matchUser(name, true, includeOffline, null); } @Override public IUser matchUserExcludingHidden(final String name, final Player requester) throws TooManyMatchesException, PlayerNotFoundException { return matchUser(name, false, false, requester); } public IUser matchUser(final String name, final boolean includeHidden, final boolean includeOffline, final Player requester) throws TooManyMatchesException, PlayerNotFoundException { final Set<IUser> users = matchUsers(name, includeHidden, includeOffline, requester); if (users.isEmpty()) { throw new PlayerNotFoundException(); } else { if (users.size() > 1) { throw new TooManyMatchesException(users); } else { return users.iterator().next(); } } } @Override public Set<IUser> matchUsers(final String name, final boolean includeOffline) { return matchUsers(name, true, includeOffline, null); } @Override public Set<IUser> matchUsersExcludingHidden(final String name, final Player requester) { return matchUsers(name, false, false, requester); } private final Pattern comma = Pattern.compile(","); public Set<IUser> matchUsers(final String name, final boolean includeHidden, final boolean includeOffline, final Player requester) { final String colorlessName = FormatUtil.stripColor(name); final String[] search = comma.split(colorlessName); final boolean multisearch = search.length > 1; final Set<IUser> result = new LinkedHashSet<IUser>(); final String nicknamePrefix = FormatUtil.stripColor(getNickNamePrefix()); for (String searchString : search) { if (searchString.isEmpty()) { continue; } if (searchString.startsWith(nicknamePrefix)) { searchString = searchString.substring(nicknamePrefix.length()); } searchString = searchString.toLowerCase(Locale.ENGLISH); final boolean multimatching = searchString.endsWith("*"); if (multimatching) { searchString = searchString.substring(0, searchString.length() - 1); } Player match = null; for (Player player : ess.getServer().getOnlinePlayers()) { if (player.getName().equalsIgnoreCase(searchString) && (includeHidden || includeOffline || requester == null || requester.canSee(player))) { match = player; break; } } if (match != null) { if (multimatching || multisearch) { result.add(getUser(match)); } else { return Collections.singleton(getUser(match)); } } for (Player player : ess.getServer().getOnlinePlayers()) { final String nickname = getUser(player).getData().getNickname(); if (nickname != null && !nickname.isEmpty() && nickname.equalsIgnoreCase( searchString) && (includeHidden || includeOffline || requester == null || requester.canSee(player))) { if (multimatching || multisearch) { result.add(getUser(player)); } else { return Collections.singleton(getUser(player)); } } } if (includeOffline) { IUser matchu = null; for (String playerName : getAllUniqueUsers()) { if (playerName.equals(searchString)) { matchu = getUser(playerName); break; } } if (matchu != null) { if (multimatching || multisearch) { result.add(matchu); } else { return Collections.singleton(matchu); } } } if (multimatching || match == null) { for (Player player : ess.getServer().getOnlinePlayers()) { if (player.getName().toLowerCase(Locale.ENGLISH).startsWith( searchString) && (includeHidden || includeOffline || requester == null || requester.canSee(player))) { result.add(getUser(player)); break; } final String nickname = getUser(player).getData().getNickname(); if (nickname != null && !nickname.isEmpty() && nickname.toLowerCase(Locale.ENGLISH).startsWith( searchString) && (includeHidden || includeOffline || requester == null || requester.canSee(player))) { result.add(getUser(player)); break; } } if (includeOffline) { for (String playerName : getAllUniqueUsers()) { if (playerName.startsWith(searchString)) { result.add(getUser(playerName)); break; } } } } } return result; } private String getNickNamePrefix() { return ess.getSettings().getData().getChat().getNicknamePrefix(); } @Override public void addPrejoinedPlayer(Player player) { prejoinedPlayers.put(player.getName().toLowerCase(Locale.ENGLISH), player); } @Override public void removePrejoinedPlayer(Player player) { prejoinedPlayers.remove(player.getName().toLowerCase(Locale.ENGLISH)); } }
gpl-3.0
indeedeng/charm
src/main/java/com/indeed/charm/svn/SVNCommitInfoWrapper.java
1418
/* * Copyright (C) 2010 Indeed Inc. * * This file is part of CHARM. * * CHARM is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * CHARM is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with CHARM. If not, see <http://www.gnu.org/licenses/>. */ package com.indeed.charm.svn; import org.tmatesoft.svn.core.SVNCommitInfo; import java.util.Date; import com.indeed.charm.model.CommitInfo; /** */ public class SVNCommitInfoWrapper implements CommitInfo { private SVNCommitInfo info; public SVNCommitInfoWrapper(SVNCommitInfo info) { this.info = info; } public long getNewRevision() { return info.getNewRevision(); } public String getAuthor() { return info.getAuthor(); } public Date getDate() { return info.getDate(); } public String getErrorMessage() { return info.getErrorMessage().toString(); } public String toString() { return info.toString(); } }
gpl-3.0
greencellx/simpleCommander
src/com/ghostsq/commander/utils/LsItem.java
8456
package com.ghostsq.commander.utils; import java.text.ParseException; import java.text.SimpleDateFormat; import java.util.Calendar; import java.util.Comparator; import java.util.Date; import java.util.Locale; import java.util.regex.Matcher; import java.util.regex.Pattern; import com.ghostsq.commander.adapters.CommanderAdapter; import android.util.Log; public class LsItem { private static final String TAG = "LsItem"; // Debian FTP site // -rw-r--r-- 1 1176 1176 1062 Sep 04 18:54 README //Android FTP server // -rw-rw-rw- 1 system system 93578 Sep 26 00:26 Quote Pro 1.2.4.apk //Win2K3 IIS // -rwxrwxrwx 1 owner group 314800 Feb 10 2008 classic.jar private static Pattern unix = Pattern.compile( "^([\\-bcdlprwxsStT]{9,10}\\s+\\d+\\s+[^\\s]+\\s+[^\\s]+)\\s+(\\d+)\\s+((?:Jan|Feb|Mar|Apr|May|Jun|Jul|Aug|Sep|Oct|Nov|Dec)\\s+\\d{1,2}\\s+(?:\\d{4}|\\d{1,2}:\\d{2}))\\s(.+)" ); // inetutils-ftpd: // drwx------ 3 user 80 2009-02-15 12:33 .adobe // android native: // ----rwxr-x system sdcard_rw 683 2013-05-25 19:52 1.zip private static Pattern inet = Pattern.compile( "^([\\-bcdlprwxsStT]{9,10}\\s+.+)\\s+(\\d*)\\s+(\\d{4}-\\d{2}-\\d{2}\\s\\d{1,2}:\\d{2})\\s(.+)" ); // MSDOS style // 02-10-08 02:08PM 314800 classic.jar private static Pattern msdos = Pattern.compile( "^(\\d{2,4}-\\d{2}-\\d{2,4}\\s+\\d{1,2}:\\d{2}[AP]M)\\s+(\\d+|<DIR>)\\s+(.+)" ); private static SimpleDateFormat format_date_time = new SimpleDateFormat( "MMM d HH:mm", Locale.ENGLISH ); private static SimpleDateFormat format_date_year = new SimpleDateFormat( "MMM d yyyy", Locale.ENGLISH ); private static SimpleDateFormat format_full_date = new SimpleDateFormat( "yyyy-MM-dd HH:mm", Locale.ENGLISH ); private static SimpleDateFormat format_msdos_date = new SimpleDateFormat( "MM-dd-yy HH:mmaa", Locale.ENGLISH ); private String name, link_target_name = null, attr = null; private boolean directory = false; private boolean link = false; private long size = 0; private Date date; public static final String LINK_PTR = " -> "; public LsItem( String ls_string ) { Matcher m = unix.matcher( ls_string ); if( m.matches() ) { try { name = m.group( 4 ); if( ls_string.charAt( 0 ) == 'd' ) directory = true; if( ls_string.charAt( 0 ) == 'l' ) { link = true; int arr_pos = name.indexOf( LINK_PTR ); if( arr_pos > 0 ) { link_target_name = name.substring( arr_pos + 4 ); name = name.substring( 0, arr_pos ); } } size = Long.parseLong( m.group( 2 ) ); String date_s = m.group( 3 ); boolean in_year = date_s.indexOf( ':' ) > 0; SimpleDateFormat df = in_year ? format_date_time : format_date_year; date = df.parse( date_s ); if( in_year ) { Calendar cal = Calendar.getInstance(); int cur_year = cal.get( Calendar.YEAR ) - 1900; int cur_month = cal.get( Calendar.MONTH ); int f_month = date.getMonth(); if( f_month > cur_month ) cur_year--; date.setYear( cur_year ); } attr = m.group( 1 ); //Log.v( TAG, "Item " + name + ", " + attr ); } catch( ParseException e ) { e.printStackTrace(); } return; } m = inet.matcher( ls_string ); if( m.matches() ) { try { if( ls_string.charAt( 0 ) == 'd' ) directory = true; name = m.group( 4 ); if( ls_string.charAt( 0 ) == 'l' ) { // link link = true; int arr_pos = name.indexOf( LINK_PTR ); if( arr_pos > 0 ) { link_target_name = name.substring( arr_pos + 4 ); name = name.substring( 0, arr_pos ); } } String sz_str = m.group( 2 ); size = sz_str != null && sz_str.length() > 0 ? Long.parseLong( sz_str ) : -1; String date_s = m.group( 3 ); SimpleDateFormat df = format_full_date; date = df.parse( date_s ); attr = m.group( 1 ); if( attr != null ) attr = attr.trim(); } catch( ParseException e ) { e.printStackTrace(); } return; } m = msdos.matcher( ls_string ); if( m.matches() ) { try { name = m.group( 3 ); if( m.group( 2 ).equals( "<DIR>" ) ) directory = true; else size = Long.parseLong( m.group( 2 ) ); String date_s = m.group( 1 ); SimpleDateFormat df = format_msdos_date; date = df.parse( date_s ); } catch( ParseException e ) { e.printStackTrace(); } return; } Log.e( TAG, "\nUnmatched string: " + ls_string + "\n" ); } @Override public String toString() { StringBuilder s = new StringBuilder(); s.append( name ); if( link_target_name != null ) s.append( " " + LINK_PTR + " " + link_target_name ); if( attr != null ) s.append( " (" + attr + ")" ); if( directory ) s.append( " DIR" ); if( link ) s.append( " LINK" ); s.append( " " + size ); s.append( " " + date ); return s.toString(); } public final String getName() { return name; } public final Date getDate() { return date; } public final long length() { return size; } public final boolean isValid() { return name != null; } public final boolean isDirectory() { return directory; } public final void setDirectory() { directory = true; } public final String getLinkTarget() { return link ? link_target_name : null; } public final String getAttr() { return attr; } public final int compareTo( LsItem o ) { return getName().compareTo( o.getName() ); } public class LsItemPropComparator implements Comparator<LsItem> { int type; boolean case_ignore, ascending; public LsItemPropComparator( int type_, boolean case_ignore_, boolean ascending_ ) { type = type_; case_ignore = case_ignore_ && ( type_ == CommanderAdapter.SORT_EXT || type_ == CommanderAdapter.SORT_NAME ); ascending = ascending_; } @Override public int compare( LsItem f1, LsItem f2 ) { boolean f1IsDir = f1.isDirectory(); boolean f2IsDir = f2.isDirectory(); if( f1IsDir != f2IsDir ) return f1IsDir ? -1 : 1; int ext_cmp = 0; switch( type ) { case CommanderAdapter.SORT_EXT: ext_cmp = case_ignore ? Utils.getFileExt( f1.getName() ).compareToIgnoreCase( Utils.getFileExt( f2.getName() ) ) : Utils.getFileExt( f1.getName() ).compareTo( Utils.getFileExt( f2.getName() ) ); break; case CommanderAdapter.SORT_SIZE: ext_cmp = f1.length() - f2.length() < 0 ? -1 : 1; break; case CommanderAdapter.SORT_DATE: ext_cmp = f1.getDate().compareTo( f2.getDate() ); break; } if( ext_cmp == 0 ) ext_cmp = case_ignore ? f1.getName().compareToIgnoreCase( f2.getName() ) : f1.compareTo( f2 ); return ascending ? ext_cmp : -ext_cmp; } } public static LsItem[] createArray( int n ) { return new LsItem[n]; } }
gpl-3.0
sambayless/golems
src/com/golemgame/tool/action/information/SelectionInformation.java
1303
/******************************************************************************* * Copyright 2008, 2009, 2010 Sam Bayless. * * This file is part of Golems. * * Golems is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * Golems is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with Golems. If not, see <http://www.gnu.org/licenses/>. ******************************************************************************/ package com.golemgame.tool.action.information; import com.golemgame.tool.action.Action; public abstract class SelectionInformation extends ActionInformation { @Override public Type getType() { return Action.SELECTINFO; } public boolean isSelectable() { return true; } public boolean isMultipleSelectable() { return true; } }
gpl-3.0
tetriseffect/activate
android/app/src/main/java/com/activate/MainApplication.java
1229
package com.activate; import android.app.Application; import android.util.Log; import com.facebook.react.ReactApplication; import com.oblador.vectoricons.VectorIconsPackage; import com.i18n.reactnativei18n.ReactNativeI18n; import com.learnium.RNDeviceInfo.RNDeviceInfo; import com.lugg.ReactNativeConfig.ReactNativeConfigPackage; import com.facebook.react.ReactInstanceManager; import com.facebook.react.ReactNativeHost; import com.facebook.react.ReactPackage; import com.facebook.react.shell.MainReactPackage; import java.util.Arrays; import java.util.List; public class MainApplication extends Application implements ReactApplication { private final ReactNativeHost mReactNativeHost = new ReactNativeHost(this) { @Override protected boolean getUseDeveloperSupport() { return BuildConfig.DEBUG; } @Override protected List<ReactPackage> getPackages() { return Arrays.<ReactPackage>asList( new MainReactPackage(), new VectorIconsPackage(), new ReactNativeI18n(), new RNDeviceInfo(), new ReactNativeConfigPackage() ); } }; @Override public ReactNativeHost getReactNativeHost() { return mReactNativeHost; } }
gpl-3.0
annavicente/repositorio-de-processos
src/Modelo/TipoRegra.java
341
package entidade; public class TipoRegra { private char codigo; private String descricao; public char getCodigo() { return codigo; } public void setCodigo(char codigo) { this.codigo = codigo; } public String getDescricao() { return descricao; } public void setDescricao(String descricao) { this.descricao = descricao; } }
gpl-3.0
UnratedFilmIndustries/MovieSets
src/test/java/com/quartercode/moviesets/test/logic/MovieSetGetCenterLocationTest.java
2263
package com.quartercode.moviesets.test.logic; import static org.junit.Assert.assertEquals; import java.util.ArrayList; import java.util.Collection; import java.util.List; import org.bukkit.Location; import org.junit.Test; import org.junit.runner.RunWith; import org.junit.runners.Parameterized; import org.junit.runners.Parameterized.Parameters; import de.unratedfilms.moviesets.logic.Consts; import de.unratedfilms.moviesets.logic.MovieSet; @RunWith (Parameterized.class) public class MovieSetGetCenterLocationTest { @Parameters public static Collection<Object[]> getData() { int movieSetCenterDiff = Consts.SET_DIAMETER + Consts.SET_GAP; List<Object[]> data = new ArrayList<>(); data.add(new Object[] { 0, 0, 0 }); data.add(new Object[] { 1, movieSetCenterDiff, 0 }); data.add(new Object[] { 2, movieSetCenterDiff, -movieSetCenterDiff }); data.add(new Object[] { 3, 0, -movieSetCenterDiff }); data.add(new Object[] { 4, -movieSetCenterDiff, -movieSetCenterDiff }); data.add(new Object[] { 5, -movieSetCenterDiff, 0 }); data.add(new Object[] { 6, -movieSetCenterDiff, movieSetCenterDiff }); data.add(new Object[] { 7, 0, movieSetCenterDiff }); data.add(new Object[] { 8, movieSetCenterDiff, movieSetCenterDiff }); data.add(new Object[] { 9, 2 * movieSetCenterDiff, movieSetCenterDiff }); data.add(new Object[] { 10, 2 * movieSetCenterDiff, 0 }); data.add(new Object[] { 11, 2 * movieSetCenterDiff, -movieSetCenterDiff }); return data; } private final int index; private final int expectedX; private final int expectedZ; public MovieSetGetCenterLocationTest(int index, int expectedX, int expectedZ) { this.index = index; this.expectedX = expectedX; this.expectedZ = expectedZ; } @Test public void testGetGridPosition() { Location actualLoc = new MovieSet(index, null, null).getCenterLocation(); assertEquals("Center location x coordinate", expectedX, actualLoc.getBlockX()); assertEquals("Center location y coordinate", 0, actualLoc.getBlockY()); assertEquals("Center location z coordinate", expectedZ, actualLoc.getBlockZ()); } }
gpl-3.0
AnomalyXII/bot
bot-utils-command-handler/src/main/java/net/anomalyxii/bot/api/handlers/CommandHandlerMXBean.java
681
package net.anomalyxii.bot.api.handlers; import javax.management.MXBean; /** * A {@link MXBean} for the {@link CommandHandler} interface. * <p> * Created by Anomaly on 21/05/2017. */ @MXBean public interface CommandHandlerMXBean { // ****************************** // Interface Methods // ****************************** /** * Get whether this {@link CommandHandler} is enabled. * * @return {@literal true} if enabled; {@literal false} otherwise */ boolean isEnabled(); /** * Enable this {@link CommandHandler}. */ void enable(); /** * Disable this {@link CommandHandler}. */ void disable(); }
gpl-3.0
xbao/vanilla
src/ch/blinkenlights/android/vanilla/PreferencesTheme.java
3429
/* * Copyright (C) 2016 Adrian Ulrich <adrian@blinkenlights.ch> * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ package ch.blinkenlights.android.vanilla; import android.content.Context; import android.content.SharedPreferences; import android.graphics.Bitmap; import android.graphics.Canvas; import android.graphics.Paint; import android.graphics.drawable.BitmapDrawable; import android.graphics.drawable.Drawable; import android.os.Bundle; import android.preference.Preference; import android.preference.PreferenceFragment; import android.preference.PreferenceScreen; import android.util.Log; public class PreferencesTheme extends PreferenceFragment implements Preference.OnPreferenceClickListener { private Context mContext; @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); mContext = getActivity(); // Themes are 'pre-compiled' in themes-list: get all values // and append them to our newly created PreferenceScreen PreferenceScreen screen = getPreferenceManager().createPreferenceScreen(mContext); final String[] entries = getResources().getStringArray(R.array.theme_entries); final String[] values = getResources().getStringArray(R.array.theme_values); for (int i = 0; i < entries.length; i++) { int[] attrs = decodeValue(values[i]); final Preference pref = new Preference(mContext); pref.setPersistent(false); pref.setOnPreferenceClickListener(this); pref.setTitle(entries[i]); pref.setKey(Long.toString(attrs[0])); // that's actually our value pref.setIcon(generateThemePreview(attrs)); screen.addPreference(pref); } setPreferenceScreen(screen); } @Override public boolean onPreferenceClick(Preference pref) { SharedPreferences.Editor editor = PlaybackService.getSettings(mContext).edit(); editor.putString(PrefKeys.SELECTED_THEME, pref.getKey()); editor.apply(); return true; } private int[] decodeValue(String v) { String[] parts = v.split(","); int[] values = new int[parts.length]; for (int i=0; i<parts.length; i++) { long parsedLong = (long)Long.decode(parts[i]); // the colors overflow an int, so we first must parse it as Long to make java happy. values[i] = (int)parsedLong; } return values; } private Drawable generateThemePreview(int[] colors) { final int size = (int) getResources().getDimension(R.dimen.cover_size); final int step = size / (colors.length - 1); Bitmap bitmap = Bitmap.createBitmap(size, size, Bitmap.Config.RGB_565); Canvas canvas = new Canvas(bitmap); Paint paint = new Paint(); paint.setStyle(Paint.Style.FILL); for (int i=1; i < colors.length; i++) { paint.setColor(colors[i]); canvas.drawRect(0, step*(i-1), size, size, paint); } Drawable d = new BitmapDrawable(mContext.getResources(), bitmap); return d; } }
gpl-3.0
fr3gu/letsmod-mod
letsmod_common/com/fr3gu/letsmod/client/RenderSpaceship.java
1684
package com.fr3gu.letsmod.client; import net.minecraft.client.renderer.entity.Render; import net.minecraft.entity.Entity; import net.minecraft.util.ResourceLocation; import org.lwjgl.opengl.GL11; import com.fr3gu.letsmod.entity.EntitySpaceship; import cpw.mods.fml.relauncher.Side; import cpw.mods.fml.relauncher.SideOnly; /** * Lets Mod-Mod * * RenderSpaceship * * @author fr3gu * @license Lesser GNU Public License v3 (http://www.gnu.org/licenses/lgpl.html) * */@SideOnly(Side.CLIENT) public class RenderSpaceship extends Render { private static final ResourceLocation texture = new ResourceLocation("letsmod", "textures/models/spaceship.png"); private static final ResourceLocation chargedTexture = new ResourceLocation("letsmod", "textures/models/spaceship_charged.png"); protected ModelSpaceship model; public RenderSpaceship() { shadowSize = 0.5F; model = new ModelSpaceship(); } public void renderSpaceship(EntitySpaceship spaceship, double x, double y, double z, float yaw, float partialTickTime) { GL11.glPushMatrix(); GL11.glTranslatef((float)x, (float)y, (float)z); GL11.glRotatef(180.0F - yaw, 0.0F, 1.0F, 0.0F); GL11.glScaled(-1.0F, -1.0F, 1.0F); func_110777_b(spaceship); model.render(spaceship, 0.0F, 0.0F, -0.1F, 0.0F, 0.0F, 0.0625F); GL11.glPopMatrix(); } @Override public void doRender(Entity entity, double x, double y, double z, float yaw, float partialTickTime) { this.renderSpaceship((EntitySpaceship)entity, x, y, z, yaw, partialTickTime); } @Override protected ResourceLocation func_110775_a(Entity entity) { return ((EntitySpaceship)entity).isCharged() ? chargedTexture : texture; } }
gpl-3.0
sorsergios/mascotapp
app/src/main/java/ar/com/ponele/mascotapp/myaccount/MyAccountOptionsFragment.java
295
package ar.com.ponele.mascotapp.myaccount; import android.support.v4.app.Fragment; public class MyAccountOptionsFragment extends Fragment { public static MyAccountOptionsFragment newInstance() { MyAccountOptionsFragment fragment = new MyAccountOptionsFragment(); return fragment; } }
gpl-3.0
dested/CraftbukkitMaps
src/main/java/net/minecraft/server/BlockSoil.java
3566
package net.minecraft.server; import java.util.Random; // CraftBukkit start import org.bukkit.Bukkit; import org.bukkit.craftbukkit.CraftServer; import org.bukkit.craftbukkit.event.CraftEventFactory; import org.bukkit.event.Cancellable; import org.bukkit.event.block.Action; import org.bukkit.event.entity.EntityInteractEvent; // CraftBukkit end public class BlockSoil extends Block { protected BlockSoil(int i) { super(i, Material.EARTH); this.textureId = 87; this.a(true); this.a(0.0F, 0.0F, 0.0F, 1.0F, 0.9375F, 1.0F); this.f(255); } public AxisAlignedBB d(World world, int i, int j, int k) { return AxisAlignedBB.b((double) (i + 0), (double) (j + 0), (double) (k + 0), (double) (i + 1), (double) (j + 1), (double) (k + 1)); } public boolean a() { return false; } public boolean b() { return false; } public int a(int i, int j) { return i == 1 && j > 0 ? this.textureId - 1 : (i == 1 ? this.textureId : 2); } public void a(World world, int i, int j, int k, Random random) { if (random.nextInt(5) == 0) { if (!this.h(world, i, j, k) && !world.s(i, j + 1, k)) { int l = world.getData(i, j, k); if (l > 0) { world.setData(i, j, k, l - 1); } else if (!this.g(world, i, j, k)) { world.setTypeId(i, j, k, Block.DIRT.id); } } else { world.setData(i, j, k, 7); } } } public void b(World world, int i, int j, int k, Entity entity) { if (world.random.nextInt(4) == 0) { // CraftBukkit start - Interact Soil Cancellable cancellable; if (entity instanceof EntityHuman) { cancellable = CraftEventFactory.callPlayerInteractEvent((EntityHuman) entity, Action.PHYSICAL, i, j, k, -1, null); } else { cancellable = new EntityInteractEvent(entity.getBukkitEntity(), ((WorldServer) world).getWorld().getBlockAt(i, j, k)); ((CraftServer) Bukkit.getServer()).getPluginManager().callEvent((EntityInteractEvent) cancellable); } if (cancellable.isCancelled()) { return; } // CraftBukkit end world.setTypeId(i, j, k, Block.DIRT.id); } } private boolean g(World world, int i, int j, int k) { byte b0 = 0; for (int l = i - b0; l <= i + b0; ++l) { for (int i1 = k - b0; i1 <= k + b0; ++i1) { if (world.getTypeId(l, j + 1, i1) == Block.CROPS.id) { return true; } } } return false; } private boolean h(World world, int i, int j, int k) { for (int l = i - 4; l <= i + 4; ++l) { for (int i1 = j; i1 <= j + 1; ++i1) { for (int j1 = k - 4; j1 <= k + 4; ++j1) { if (world.getMaterial(l, i1, j1) == Material.WATER) { return true; } } } } return false; } public void doPhysics(World world, int i, int j, int k, int l) { super.doPhysics(world, i, j, k, l); Material material = world.getMaterial(i, j + 1, k); if (material.isBuildable()) { world.setTypeId(i, j, k, Block.DIRT.id); } } public int a(int i, Random random) { return Block.DIRT.a(0, random); } }
gpl-3.0
Niky4000/UsefulUtils
projects/tutorials-master/tutorials-master/jee-7/src/test/java/com/baeldung/timer/ProgrammaticTimerBeanLiveTest.java
1797
package com.baeldung.timer; import org.jboss.arquillian.container.test.api.Deployment; import org.jboss.arquillian.junit.Arquillian; import org.jboss.shrinkwrap.api.ShrinkWrap; import org.jboss.shrinkwrap.api.spec.WebArchive; import org.jboss.shrinkwrap.resolver.api.maven.Maven; import org.junit.Test; import org.junit.runner.RunWith; import javax.inject.Inject; import java.io.File; import static com.jayway.awaitility.Awaitility.await; import static com.jayway.awaitility.Awaitility.to; import static org.hamcrest.MatcherAssert.assertThat; import static org.hamcrest.Matchers.equalTo; import static org.hamcrest.Matchers.is; @RunWith(Arquillian.class) public class ProgrammaticTimerBeanLiveTest { final static long TIMEOUT = 5000l; final static long TOLERANCE = 1000l; @Inject TimerEventListener timerEventListener; @Deployment public static WebArchive deploy() { File[] jars = Maven.resolver().loadPomFromFile("pom.xml") .resolve("com.jayway.awaitility:awaitility") .withTransitivity().asFile(); return ShrinkWrap.create(WebArchive.class) .addAsLibraries(jars) .addClasses(WithinWindowMatcher.class, TimerEvent.class, TimerEventListener.class, ProgrammaticTimerBean.class); } @Test public void should_receive_two_pings() { await().untilCall(to(timerEventListener.getEvents()).size(), equalTo(2)); TimerEvent firstEvent = timerEventListener.getEvents().get(0); TimerEvent secondEvent = timerEventListener.getEvents().get(1); long delay = secondEvent.getTime() - firstEvent.getTime(); System.out.println("Actual timeout = " + delay); assertThat(delay, is(WithinWindowMatcher.withinWindow(TIMEOUT, TOLERANCE))); } }
gpl-3.0
Neosperience/platform-super-pom
architecture-springcontroller/src/main/java/com/mobc3/platform/backend/commons/architecture/spring/controller/SpringBeanProvider.java
820
package com.mobc3.platform.backend.commons.architecture.spring.controller; import java.util.*; import org.springframework.beans.*; import org.springframework.context.*; import com.mobc3.platform.backend.commons.architecture.server.*; public class SpringBeanProvider implements BeanProvider, ApplicationContextAware { protected ApplicationContext applicationContext; @Override public Object getBeanByName(String name) { return applicationContext.getBean(name); } @Override public Object getBeanByClass(Class<?> beanClass) { Map<String, ?> beans = applicationContext.getBeansOfType(beanClass); return beans.values().iterator().next(); } @Override public void setApplicationContext(ApplicationContext applicationContext) throws BeansException { this.applicationContext = applicationContext; } }
gpl-3.0
TwinSnakes007/OFCC
OFCC/src/main/java/org/gradle/RangedFee.java
957
package org.gradle; public class RangedFee implements IFee { private double lowerRange = 0, upperRange = 0, rate = 0, existingCostBasis = 0; public RangedFee(double pRate, double pLowerRange, double pUpperRange, double pExistingCostBasis) { this.lowerRange = pLowerRange; this.upperRange = pUpperRange; this.existingCostBasis = pExistingCostBasis; this.rate = pRate; } public double assessFee(double invoice) { double adjustedInvoice = invoice + existingCostBasis; if (invoice == 0) return 0; else if (existingCostBasis > upperRange) return 0; if (adjustedInvoice > lowerRange) { if (adjustedInvoice > upperRange) adjustedInvoice = upperRange - existingCostBasis > 0 ? upperRange - existingCostBasis : 0; else { adjustedInvoice = invoice > lowerRange ? lowerRange - existingCostBasis : ( invoice - existingCostBasis > 0 ? invoice - existingCostBasis : 0 ); } } return rate * adjustedInvoice; } }
gpl-3.0
WWHS-8-CS/employee_task_list
Queue.java
553
import java.util.*; public class Queue{ private List<Task> tasks; public Queue() { tasks = new ArrayList<Task>(); } public void enqueue(Task t) { tasks.add(t); } public Task dequeue() { if(tasks.size() == 0) throw new IllegalStateException("Can't dequeue from an empty queue."); return tasks.remove(0); } public Task peek() { if(tasks.size() == 0) throw new IllegalStateException("Can't peek at an empty queue."); return tasks.get(0); } public boolean isEmpty() { return tasks.size() == 0; } }
gpl-3.0
abmindiarepomanager/ABMOpenMainet
Mainet1.0/MainetServiceParent/MainetServiceCommon/src/main/java/com/abm/mainet/common/domain/TbComparentMasEntity.java
9378
/* * Created on 6 Aug 2015 ( Time 16:35:19 ) * Generated by Telosys Tools Generator ( version 2.1.1 ) */ // This Bean has a basic Primary Key (not composite) package com.abm.mainet.common.domain; import java.io.Serializable; //import javax.validation.constraints.* ; //import org.hibernate.validator.constraints.* ; import java.lang.Long; import java.util.Date; import java.util.List; import javax.persistence.CascadeType; import javax.persistence.Column; import javax.persistence.Entity; import javax.persistence.GeneratedValue; import javax.persistence.Id; import javax.persistence.JoinColumn; import javax.persistence.ManyToOne; import javax.persistence.NamedQueries; import javax.persistence.NamedQuery; import javax.persistence.OneToMany; import javax.persistence.Table; import javax.persistence.Temporal; import javax.persistence.TemporalType; import org.hibernate.annotations.GenericGenerator; /** * Persistent class for entity stored in table "TB_COMPARENT_MAS" * * @author Telosys Tools Generator * */ @Entity @Table(name="TB_COMPARENT_MAS") // Define named queries here @NamedQueries ( { @NamedQuery ( name="TbComparentMasEntity.countAll", query="SELECT COUNT(x) FROM TbComparentMasEntity x" ) } ) public class TbComparentMasEntity implements Serializable { private static final long serialVersionUID = 1L; //---------------------------------------------------------------------- // ENTITY PRIMARY KEY ( BASED ON A SINGLE FIELD ) //---------------------------------------------------------------------- @Id @GenericGenerator(name = "MyCustomGenerator", strategy = "com.abm.mainet.common.utility.SequenceIdGenerator") @GeneratedValue(generator = "MyCustomGenerator") @Column(name="COM_ID", nullable=false) private Long comId ; //---------------------------------------------------------------------- // ENTITY DATA FIELDS //---------------------------------------------------------------------- @Column(name="COM_DESC", nullable=false) private String comDesc ; @Column(name="COM_VALUE", nullable=false) private String comValue ; @Column(name="COM_LEVEL", nullable=false) private Long comLevel ; @Column(name="COM_STATUS") private String comStatus ; @Column(name="ORGID", nullable=false) private Long orgid ; @Column(name="USER_ID", nullable=false) private Long userId ; @Column(name="LANG_ID", nullable=false) private Long langId ; @Temporal(TemporalType.TIMESTAMP) @Column(name="LMODDATE", nullable=false) private Date lmoddate ; @Column(name="UPDATED_BY") private Long updatedBy ; @Temporal(TemporalType.TIMESTAMP) @Column(name="UPDATED_DATE") private Date updatedDate ; @Column(name="COM_DESC_MAR") private String comDescMar ; @Column(name="COM_REPLICATE_FLAG", length=1) private String comReplicateFlag ; @Column(name="LG_IP_MAC", length=100) private String lgIpMac ; @Column(name="LG_IP_MAC_UPD", length=100) private String lgIpMacUpd ; // "cpmId" (column "CPM_ID") is not defined by itself because used as FK in a link //---------------------------------------------------------------------- // ENTITY LINKS ( RELATIONSHIP ) //---------------------------------------------------------------------- @OneToMany(mappedBy="tbComparentMas", targetEntity=TbComparentDetEntity.class, cascade=CascadeType.ALL) private List<TbComparentDetEntity> listOfTbComparentDet; @ManyToOne @JoinColumn(name="CPM_ID", referencedColumnName="CPM_ID") private TbComparamMasEntity tbComparamMas; //---------------------------------------------------------------------- // CONSTRUCTOR(S) //---------------------------------------------------------------------- public TbComparentMasEntity() { super(); } //---------------------------------------------------------------------- // GETTER & SETTER FOR THE KEY FIELD //---------------------------------------------------------------------- public void setComId( Long comId ) { this.comId = comId ; } public Long getComId() { return this.comId; } //---------------------------------------------------------------------- // GETTERS & SETTERS FOR FIELDS //---------------------------------------------------------------------- //--- DATABASE MAPPING : COM_DESC ( NVARCHAR2 ) public void setComDesc( String comDesc ) { this.comDesc = comDesc; } public String getComDesc() { return this.comDesc; } //--- DATABASE MAPPING : COM_VALUE ( NVARCHAR2 ) public void setComValue( String comValue ) { this.comValue = comValue; } public String getComValue() { return this.comValue; } //--- DATABASE MAPPING : COM_LEVEL ( NUMBER ) public void setComLevel( Long comLevel ) { this.comLevel = comLevel; } public Long getComLevel() { return this.comLevel; } //--- DATABASE MAPPING : COM_STATUS ( NVARCHAR2 ) public void setComStatus( String comStatus ) { this.comStatus = comStatus; } public String getComStatus() { return this.comStatus; } //--- DATABASE MAPPING : ORGID ( NUMBER ) public void setOrgid( Long orgid ) { this.orgid = orgid; } public Long getOrgid() { return this.orgid; } //--- DATABASE MAPPING : USER_ID ( NUMBER ) public void setUserId( Long userId ) { this.userId = userId; } public Long getUserId() { return this.userId; } //--- DATABASE MAPPING : LANG_ID ( NUMBER ) public void setLangId( Long langId ) { this.langId = langId; } public Long getLangId() { return this.langId; } //--- DATABASE MAPPING : LMODDATE ( DATE ) public void setLmoddate( Date lmoddate ) { this.lmoddate = lmoddate; } public Date getLmoddate() { return this.lmoddate; } //--- DATABASE MAPPING : UPDATED_BY ( NUMBER ) public void setUpdatedBy( Long updatedBy ) { this.updatedBy = updatedBy; } public Long getUpdatedBy() { return this.updatedBy; } //--- DATABASE MAPPING : UPDATED_DATE ( DATE ) public void setUpdatedDate( Date updatedDate ) { this.updatedDate = updatedDate; } public Date getUpdatedDate() { return this.updatedDate; } //--- DATABASE MAPPING : COM_DESC_MAR ( NVARCHAR2 ) public void setComDescMar( String comDescMar ) { this.comDescMar = comDescMar; } public String getComDescMar() { return this.comDescMar; } //--- DATABASE MAPPING : COM_REPLICATE_FLAG ( CHAR ) public void setComReplicateFlag( String comReplicateFlag ) { this.comReplicateFlag = comReplicateFlag; } public String getComReplicateFlag() { return this.comReplicateFlag; } //--- DATABASE MAPPING : LG_IP_MAC ( VARCHAR2 ) public void setLgIpMac( String lgIpMac ) { this.lgIpMac = lgIpMac; } public String getLgIpMac() { return this.lgIpMac; } //--- DATABASE MAPPING : LG_IP_MAC_UPD ( VARCHAR2 ) public void setLgIpMacUpd( String lgIpMacUpd ) { this.lgIpMacUpd = lgIpMacUpd; } public String getLgIpMacUpd() { return this.lgIpMacUpd; } //---------------------------------------------------------------------- // GETTERS & SETTERS FOR LINKS //---------------------------------------------------------------------- public void setListOfTbComparentDet( List<TbComparentDetEntity> listOfTbComparentDet ) { this.listOfTbComparentDet = listOfTbComparentDet; } public List<TbComparentDetEntity> getListOfTbComparentDet() { return this.listOfTbComparentDet; } public void setTbComparamMas( TbComparamMasEntity tbComparamMas ) { this.tbComparamMas = tbComparamMas; } public TbComparamMasEntity getTbComparamMas() { return this.tbComparamMas; } //---------------------------------------------------------------------- // toString METHOD //---------------------------------------------------------------------- public String toString() { StringBuffer sb = new StringBuffer(); sb.append("["); sb.append(comId); sb.append("]:"); sb.append(comDesc); sb.append("|"); sb.append(comValue); sb.append("|"); sb.append(comLevel); sb.append("|"); sb.append(comStatus); sb.append("|"); sb.append(orgid); sb.append("|"); sb.append(userId); sb.append("|"); sb.append(langId); sb.append("|"); sb.append(lmoddate); sb.append("|"); sb.append(updatedBy); sb.append("|"); sb.append(updatedDate); sb.append("|"); sb.append(comDescMar); sb.append("|"); sb.append(comReplicateFlag); sb.append("|"); sb.append(lgIpMac); sb.append("|"); sb.append(lgIpMacUpd); return sb.toString(); } public String[] getPkValues() { return new String[] { "COM", "TB_COMPARENT_MAS", "COM_ID" }; } }
gpl-3.0
abmindiarepomanager/ABMOpenMainet
Mainet1.1/MainetBRMS/Mainet_BRMS_BPMN/src/main/java/com/abm/mainet/brms/core/utility/ApplicationContextProvider.java
654
package com.abm.mainet.brms.core.utility; import org.springframework.beans.BeansException; import org.springframework.context.ApplicationContext; import org.springframework.context.ApplicationContextAware; import org.springframework.stereotype.Component; @Component public class ApplicationContextProvider implements ApplicationContextAware { private static ApplicationContext applicationContext; @Override public void setApplicationContext(ApplicationContext context) throws BeansException { applicationContext = context; } public static ApplicationContext getApplicationContext() { return applicationContext; } }
gpl-3.0
idega/platform2
src/se/idega/idegaweb/commune/childcare/presentation/CCConstants.java
2156
package se.idega.idegaweb.commune.childcare.presentation; /** * enclosing_type * @author <a href="mailto:roar@idega.is">roar</a> * @version $Id: CCConstants.java,v 1.7.6.1 2006/04/04 14:26:48 dainis Exp $ * @since 14.2.2003 */ interface CCConstants { //Test for gummi final static String YES = "1"; final static String NO_NEW_DATE = "2"; final static String NO = "3"; final static String[] OK = {"cc_ok", "OK"}; final static String[] CANCEL = {"cc_cancel", "Cancel"}; final static String[] TEXT_OFFER_ACCEPTED_SUBJECT = new String[]{"cc_oas", "Offer accepted"}; final static String[] TEXT_OFFER_ACCEPTED_MESSAGE = new String[]{"cc_oam", "Your offer were accepted."}; final static String[] TEXT_OFFER_REJECTED_SUBJECT = new String[]{"cc_oas", "Offer rejected"}; final static String[] TEXT_OFFER_REJECTED_MESSAGE = new String[]{"cc_oam", "Your offer were rejected."}; final static String[] TEXT_DETAILS = new String[]{"cc_det", "Details"}; final static String[] TEXT_CUSTOMER = new String[]{"cc_cust", "Customer"}; final static String[] TEXT_CHILD = new String[]{"cc_child", "Child"}; final static String[] TEXT_FROM = new String[]{"cc_from", "From"}; final static String APPID = "APPID"; final static String PROVIDER_ID = "PROVIDER_ID"; final static String USER_ID = "USER_ID"; final static String ACCEPT_OFFER = "ACCEPT_OFFER"; final static String KEEP_IN_QUEUE = "KEEP_IN_QUEUE"; final static String NEW_DATE = "NEW_DATE"; final static String SESSION_ACCEPTED_STATUS = "SESSION_ACCEPTED_STATUS"; final static String SESSION_KEEP_IN_QUEUE = "SESSION_KEEP_IN_QUEUE"; final static String ACTION = "ACTION"; final static int NO_ACTION = 0; final static int ACTION_SUBMIT_1 = 1; final static int ACTION_CANCEL_1 = 2; final static int ACTION_SUBMIT_CONFIRM = 3; final static int ACTION_SUBMIT_2 = 4; final static int ACTION_CANCEL_2 = 5; // final static int ACTION_SUBMIT_3 = 6; final static int ACTION_CANCEL_3 = 7; final static int ACTION_REQUEST_INFO = 8; final static int ACTION_DELETE = 9; final static String ATTRIBUTE_SHOW_FEE = "show_childcare_fee"; }
gpl-3.0
shadownater/Buzzer
app/src/main/java/com/learning/jlovas/buzzer/FourPlayers.java
1139
package com.learning.jlovas.buzzer; import android.support.v7.app.ActionBarActivity; import android.os.Bundle; import android.view.Menu; import android.view.MenuItem; public class FourPlayers extends ActionBarActivity { @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_four_players); } @Override public boolean onCreateOptionsMenu(Menu menu) { // Inflate the menu; this adds items to the action bar if it is present. getMenuInflater().inflate(R.menu.menu_four_players, menu); return true; } @Override public boolean onOptionsItemSelected(MenuItem item) { // Handle action bar item clicks here. The action bar will // automatically handle clicks on the Home/Up button, so long // as you specify a parent activity in AndroidManifest.xml. int id = item.getItemId(); //noinspection SimplifiableIfStatement if (id == R.id.action_settings) { return true; } return super.onOptionsItemSelected(item); } }
gpl-3.0
ckaestne/CIDE
other/CIDE/src/coloredide/validator/checks/FieldAccessValidator.java
1657
package coloredide.validator.checks; import java.util.Set; import org.eclipse.jdt.core.dom.IBinding; import org.eclipse.jdt.core.dom.IVariableBinding; import org.eclipse.jdt.core.dom.Name; import org.eclipse.jdt.core.dom.QualifiedName; import org.eclipse.jdt.core.dom.SimpleName; import coloredide.features.Feature; import coloredide.features.source.IColoredJavaSourceFile; import coloredide.validator.ValidationErrorCallback; import coloredide.validator.ValidationVisitor; /** * checks that every access to a field belongs to the same feature as it's * declaration. field colors are stored (cached) by the AST2Feature class * * * @author cKaestner * */ public class FieldAccessValidator extends ValidationVisitor { public FieldAccessValidator(ValidationErrorCallback callback, IColoredJavaSourceFile source) { super(callback, source); // TODO Auto-generated constructor stub } public boolean visit(SimpleName node) { visitName(node); return super.visit(node); } public boolean visit(QualifiedName node) { visitName(node); return super.visit(node); } public void visitName(Name node) { IBinding binding = node.resolveBinding(); if (binding instanceof IVariableBinding && ((IVariableBinding) binding).isField()) { Set<Feature> declColors = javaElementColors().getColors(project(), (IVariableBinding) binding); Set<Feature> callColors = nodeColors().getColors(node); if (!callColors.containsAll(declColors)) callback.errorVariableAccessMustHaveDeclarationColor(node, callColors, (IVariableBinding) binding, declColors); } } }
gpl-3.0
colincarr/home
src/abcl/src/org/armedbear/lisp/Fixnum.java
25737
/* * Fixnum.java * * Copyright (C) 2002-2006 Peter Graves * $Id: Fixnum.java 13440 2011-08-05 21:25:10Z ehuelsmann $ * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License * as published by the Free Software Foundation; either version 2 * of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. * * As a special exception, the copyright holders of this library give you * permission to link this library with independent modules to produce an * executable, regardless of the license terms of these independent * modules, and to copy and distribute the resulting executable under * terms of your choice, provided that you also meet, for each linked * independent module, the terms and conditions of the license of that * module. An independent module is a module which is not derived from * or based on this library. If you modify this library, you may extend * this exception to your version of the library, but you are not * obligated to do so. If you do not wish to do so, delete this * exception statement from your version. */ package org.armedbear.lisp; import static org.armedbear.lisp.Lisp.*; import java.math.BigInteger; public final class Fixnum extends LispInteger { public static final int MAX_POS_CACHE = 256;//just like before - however never set this to less than 256 public static final Fixnum[] constants = new Fixnum[MAX_POS_CACHE]; static { for (int i = 0; i < MAX_POS_CACHE; i++) constants[i] = new Fixnum(i); } public static final Fixnum ZERO = constants[0]; public static final Fixnum ONE = constants[1]; public static final Fixnum TWO = constants[2]; public static final Fixnum THREE = constants[3]; public static final Fixnum MINUS_ONE = Fixnum.getInstance(-1); public static Fixnum getInstance(int n) { return (n >= 0 && n < MAX_POS_CACHE) ? constants[n] : new Fixnum(n); } public final int value; // set to private to hunt down sneaky creators private Fixnum(int value) { this.value = value; } @Override public Object javaInstance() { return Integer.valueOf(value); } @Override public Object javaInstance(Class c) { String cn = c.getName(); if (cn.equals("java.lang.Byte") || cn.equals("byte")) return Byte.valueOf((byte)value); if (cn.equals("java.lang.Short") || cn.equals("short")) return Short.valueOf((short)value); if (cn.equals("java.lang.Long") || cn.equals("long")) return Long.valueOf((long)value); return javaInstance(); } @Override public LispObject typeOf() { if (value == 0 || value == 1) return Symbol.BIT; if (value > 1) return list(Symbol.INTEGER, ZERO, Fixnum.getInstance(Integer.MAX_VALUE)); return Symbol.FIXNUM; } @Override public LispObject classOf() { return BuiltInClass.FIXNUM; } @Override public LispObject getDescription() { StringBuffer sb = new StringBuffer("The fixnum "); sb.append(value); return new SimpleString(sb); } @Override public LispObject typep(LispObject type) { if (type instanceof Symbol) { if (type == Symbol.FIXNUM) return T; if (type == Symbol.INTEGER) return T; if (type == Symbol.RATIONAL) return T; if (type == Symbol.REAL) return T; if (type == Symbol.NUMBER) return T; if (type == Symbol.SIGNED_BYTE) return T; if (type == Symbol.UNSIGNED_BYTE) return value >= 0 ? T : NIL; if (type == Symbol.BIT) return (value == 0 || value == 1) ? T : NIL; } else if (type instanceof LispClass) { if (type == BuiltInClass.FIXNUM) return T; if (type == BuiltInClass.INTEGER) return T; if (type == BuiltInClass.RATIONAL) return T; if (type == BuiltInClass.REAL) return T; if (type == BuiltInClass.NUMBER) return T; } else if (type instanceof Cons) { if (type.equal(UNSIGNED_BYTE_8)) return (value >= 0 && value <= 255) ? T : NIL; if (type.equal(UNSIGNED_BYTE_16)) return (value >= 0 && value <= 65535) ? T : NIL; if (type.equal(UNSIGNED_BYTE_32)) return value >= 0 ? T : NIL; } return super.typep(type); } @Override public boolean numberp() { return true; } @Override public boolean integerp() { return true; } @Override public boolean rationalp() { return true; } @Override public boolean realp() { return true; } @Override public boolean eql(int n) { return value == n; } @Override public boolean eql(LispObject obj) { if (this == obj) return true; if (obj instanceof Fixnum) { if (value == ((Fixnum)obj).value) return true; } return false; } @Override public boolean equal(int n) { return value == n; } @Override public boolean equal(LispObject obj) { if (this == obj) return true; if (obj instanceof Fixnum) { if (value == ((Fixnum)obj).value) return true; } return false; } @Override public boolean equalp(int n) { return value == n; } @Override public boolean equalp(LispObject obj) { if (obj instanceof Fixnum) return value == ((Fixnum)obj).value; if (obj instanceof SingleFloat) return value == ((SingleFloat)obj).value; if (obj instanceof DoubleFloat) return value == ((DoubleFloat)obj).value; return false; } @Override public LispObject ABS() { if (value >= 0) return this; return LispInteger.getInstance(-(long)value); } @Override public LispObject NUMERATOR() { return this; } @Override public LispObject DENOMINATOR() { return ONE; } @Override public boolean evenp() { return (value & 0x01) == 0; } @Override public boolean oddp() { return (value & 0x01) != 0; } @Override public boolean plusp() { return value > 0; } @Override public boolean minusp() { return value < 0; } @Override public boolean zerop() { return value == 0; } public static int getValue(LispObject obj) { if (obj instanceof Fixnum) return ((Fixnum)obj).value; type_error(obj, Symbol.FIXNUM); // Not reached. return 0; } @Override public float floatValue() { return (float)value; } @Override public double doubleValue() { return (double)value; } public static int getInt(LispObject obj) { if (obj instanceof Fixnum) return ((Fixnum)obj).value; type_error(obj, Symbol.FIXNUM); // Not reached. return 0; } public static BigInteger getBigInteger(LispObject obj) { if (obj instanceof Fixnum) return BigInteger.valueOf(((Fixnum)obj).value); type_error(obj, Symbol.FIXNUM); // Not reached. return null; } @Override public int intValue() { return value; } @Override public long longValue() { return (long) value; } public final BigInteger getBigInteger() { return BigInteger.valueOf(value); } @Override public final LispObject incr() { return LispInteger.getInstance(1 + (long)value); } @Override public final LispObject decr() { return LispInteger.getInstance(-1 + (long)value); } @Override public LispObject negate() { return LispInteger.getInstance((-(long)value)); } @Override public LispObject add(int n) { return LispInteger.getInstance((long) value + n); } @Override public LispObject add(LispObject obj) { if (obj instanceof Fixnum) { long result = (long) value + ((Fixnum)obj).value; return LispInteger.getInstance(result); } if (obj instanceof Bignum) return number(getBigInteger().add(((Bignum)obj).value)); if (obj instanceof Ratio) { BigInteger numerator = ((Ratio)obj).numerator(); BigInteger denominator = ((Ratio)obj).denominator(); return number(getBigInteger().multiply(denominator).add(numerator), denominator); } if (obj instanceof SingleFloat) return new SingleFloat(value + ((SingleFloat)obj).value); if (obj instanceof DoubleFloat) return new DoubleFloat(value + ((DoubleFloat)obj).value); if (obj instanceof Complex) { Complex c = (Complex) obj; return Complex.getInstance(add(c.getRealPart()), c.getImaginaryPart()); } return type_error(obj, Symbol.NUMBER); } @Override public LispObject subtract(int n) { return LispInteger.getInstance((long)value - n); } @Override public LispObject subtract(LispObject obj) { if (obj instanceof Fixnum) return number((long) value - ((Fixnum)obj).value); if (obj instanceof Bignum) return number(getBigInteger().subtract(Bignum.getValue(obj))); if (obj instanceof Ratio) { BigInteger numerator = ((Ratio)obj).numerator(); BigInteger denominator = ((Ratio)obj).denominator(); return number( getBigInteger().multiply(denominator).subtract(numerator), denominator); } if (obj instanceof SingleFloat) return new SingleFloat(value - ((SingleFloat)obj).value); if (obj instanceof DoubleFloat) return new DoubleFloat(value - ((DoubleFloat)obj).value); if (obj instanceof Complex) { Complex c = (Complex) obj; return Complex.getInstance(subtract(c.getRealPart()), ZERO.subtract(c.getImaginaryPart())); } return type_error(obj, Symbol.NUMBER); } @Override public LispObject multiplyBy(int n) { long result = (long) value * n; return LispInteger.getInstance(result); } @Override public LispObject multiplyBy(LispObject obj) { if (obj instanceof Fixnum) { long result = (long) value * ((Fixnum)obj).value; return LispInteger.getInstance(result); } if (obj instanceof Bignum) return number(getBigInteger().multiply(((Bignum)obj).value)); if (obj instanceof Ratio) { BigInteger numerator = ((Ratio)obj).numerator(); BigInteger denominator = ((Ratio)obj).denominator(); return number( getBigInteger().multiply(numerator), denominator); } if (obj instanceof SingleFloat) return new SingleFloat(value * ((SingleFloat)obj).value); if (obj instanceof DoubleFloat) return new DoubleFloat(value * ((DoubleFloat)obj).value); if (obj instanceof Complex) { Complex c = (Complex) obj; return Complex.getInstance(multiplyBy(c.getRealPart()), multiplyBy(c.getImaginaryPart())); } return type_error(obj, Symbol.NUMBER); } @Override public LispObject divideBy(LispObject obj) { try { if (obj instanceof Fixnum) { final int divisor = ((Fixnum)obj).value; // (/ MOST-NEGATIVE-FIXNUM -1) is a bignum. if (value > Integer.MIN_VALUE) if (value % divisor == 0) return Fixnum.getInstance(value / divisor); return number(BigInteger.valueOf(value), BigInteger.valueOf(divisor)); } if (obj instanceof Bignum) return number(getBigInteger(), ((Bignum)obj).value); if (obj instanceof Ratio) { BigInteger numerator = ((Ratio)obj).numerator(); BigInteger denominator = ((Ratio)obj).denominator(); return number(getBigInteger().multiply(denominator), numerator); } if (obj instanceof SingleFloat) return new SingleFloat(value / ((SingleFloat)obj).value); if (obj instanceof DoubleFloat) return new DoubleFloat(value / ((DoubleFloat)obj).value); if (obj instanceof Complex) { Complex c = (Complex) obj; LispObject realPart = c.getRealPart(); LispObject imagPart = c.getImaginaryPart(); LispObject denominator = realPart.multiplyBy(realPart).add(imagPart.multiplyBy(imagPart)); return Complex.getInstance(multiplyBy(realPart).divideBy(denominator), Fixnum.ZERO.subtract(multiplyBy(imagPart).divideBy(denominator))); } return type_error(obj, Symbol.NUMBER); } catch (ArithmeticException e) { if (obj.zerop()) return error(new DivisionByZero()); return error(new ArithmeticError(e.getMessage())); } } @Override public boolean isEqualTo(int n) { return value == n; } @Override public boolean isEqualTo(LispObject obj) { if (obj instanceof Fixnum) return value == ((Fixnum)obj).value; if (obj instanceof SingleFloat) return isEqualTo(((SingleFloat)obj).rational()); if (obj instanceof DoubleFloat) return value == ((DoubleFloat)obj).value; if (obj instanceof Complex) return obj.isEqualTo(this); if (obj.numberp()) return false; type_error(obj, Symbol.NUMBER); // Not reached. return false; } @Override public boolean isNotEqualTo(int n) { return value != n; } @Override public boolean isNotEqualTo(LispObject obj) { if (obj instanceof Fixnum) return value != ((Fixnum)obj).value; // obj is not a fixnum. if (obj instanceof SingleFloat) return isNotEqualTo(((SingleFloat)obj).rational()); if (obj instanceof DoubleFloat) return value != ((DoubleFloat)obj).value; if (obj instanceof Complex) return obj.isNotEqualTo(this); if (obj.numberp()) return true; type_error(obj, Symbol.NUMBER); // Not reached. return false; } @Override public boolean isLessThan(int n) { return value < n; } @Override public boolean isLessThan(LispObject obj) { if (obj instanceof Fixnum) return value < ((Fixnum)obj).value; if (obj instanceof Bignum) return getBigInteger().compareTo(Bignum.getValue(obj)) < 0; if (obj instanceof Ratio) { BigInteger n = getBigInteger().multiply(((Ratio)obj).denominator()); return n.compareTo(((Ratio)obj).numerator()) < 0; } if (obj instanceof SingleFloat) return isLessThan(((SingleFloat)obj).rational()); if (obj instanceof DoubleFloat) return isLessThan(((DoubleFloat)obj).rational()); type_error(obj, Symbol.REAL); // Not reached. return false; } @Override public boolean isGreaterThan(int n) { return value > n; } @Override public boolean isGreaterThan(LispObject obj) { if (obj instanceof Fixnum) return value > ((Fixnum)obj).value; if (obj instanceof Bignum) return getBigInteger().compareTo(Bignum.getValue(obj)) > 0; if (obj instanceof Ratio) { BigInteger n = getBigInteger().multiply(((Ratio)obj).denominator()); return n.compareTo(((Ratio)obj).numerator()) > 0; } if (obj instanceof SingleFloat) return isGreaterThan(((SingleFloat)obj).rational()); if (obj instanceof DoubleFloat) return isGreaterThan(((DoubleFloat)obj).rational()); type_error(obj, Symbol.REAL); // Not reached. return false; } @Override public boolean isLessThanOrEqualTo(int n) { return value <= n; } @Override public boolean isLessThanOrEqualTo(LispObject obj) { if (obj instanceof Fixnum) return value <= ((Fixnum)obj).value; if (obj instanceof Bignum) return getBigInteger().compareTo(Bignum.getValue(obj)) <= 0; if (obj instanceof Ratio) { BigInteger n = getBigInteger().multiply(((Ratio)obj).denominator()); return n.compareTo(((Ratio)obj).numerator()) <= 0; } if (obj instanceof SingleFloat) return isLessThanOrEqualTo(((SingleFloat)obj).rational()); if (obj instanceof DoubleFloat) return isLessThanOrEqualTo(((DoubleFloat)obj).rational()); type_error(obj, Symbol.REAL); // Not reached. return false; } @Override public boolean isGreaterThanOrEqualTo(int n) { return value >= n; } @Override public boolean isGreaterThanOrEqualTo(LispObject obj) { if (obj instanceof Fixnum) return value >= ((Fixnum)obj).value; if (obj instanceof Bignum) return getBigInteger().compareTo(Bignum.getValue(obj)) >= 0; if (obj instanceof Ratio) { BigInteger n = getBigInteger().multiply(((Ratio)obj).denominator()); return n.compareTo(((Ratio)obj).numerator()) >= 0; } if (obj instanceof SingleFloat) return isGreaterThanOrEqualTo(((SingleFloat)obj).rational()); if (obj instanceof DoubleFloat) return isGreaterThanOrEqualTo(((DoubleFloat)obj).rational()); type_error(obj, Symbol.REAL); // Not reached. return false; } @Override public LispObject truncate(LispObject obj) { final LispThread thread = LispThread.currentThread(); final LispObject value1, value2; try { if (obj instanceof Fixnum) { int divisor = ((Fixnum)obj).value; int quotient = value / divisor; int remainder = value % divisor; value1 = Fixnum.getInstance(quotient); value2 = remainder == 0 ? Fixnum.ZERO : Fixnum.getInstance(remainder); } else if (obj instanceof Bignum) { BigInteger val = getBigInteger(); BigInteger divisor = ((Bignum)obj).value; BigInteger[] results = val.divideAndRemainder(divisor); BigInteger quotient = results[0]; BigInteger remainder = results[1]; value1 = number(quotient); value2 = (remainder.signum() == 0) ? Fixnum.ZERO : number(remainder); } else if (obj instanceof Ratio) { Ratio divisor = (Ratio) obj; LispObject quotient = multiplyBy(divisor.DENOMINATOR()).truncate(divisor.NUMERATOR()); LispObject remainder = subtract(quotient.multiplyBy(divisor)); value1 = quotient; value2 = remainder; } else if (obj instanceof SingleFloat) { // "When rationals and floats are combined by a numerical function, // the rational is first converted to a float of the same format." // 12.1.4.1 return new SingleFloat(value).truncate(obj); } else if (obj instanceof DoubleFloat) { // "When rationals and floats are combined by a numerical function, // the rational is first converted to a float of the same format." // 12.1.4.1 return new DoubleFloat(value).truncate(obj); } else return type_error(obj, Symbol.REAL); } catch (ArithmeticException e) { if (obj.zerop()) return error(new DivisionByZero()); else return error(new ArithmeticError(e.getMessage())); } return thread.setValues(value1, value2); } @Override public LispObject MOD(LispObject divisor) { if (divisor instanceof Fixnum) return MOD(((Fixnum)divisor).value); return super.MOD(divisor); } @Override public LispObject MOD(int divisor) { final int r; try { r = value % divisor; } catch (ArithmeticException e) { return error(new ArithmeticError("Division by zero.")); } if (r == 0) return Fixnum.ZERO; if (divisor < 0) { if (value > 0) return Fixnum.getInstance(r + divisor); } else { if (value < 0) return Fixnum.getInstance(r + divisor); } return Fixnum.getInstance(r); } @Override public LispObject ash(int shift) { if (value == 0) return this; if (shift == 0) return this; long n = value; if (shift <= -32) { // Right shift. return n >= 0 ? Fixnum.ZERO : Fixnum.MINUS_ONE; } if (shift < 0) return Fixnum.getInstance((int)(n >> -shift)); if (shift <= 32) { n = n << shift; return LispInteger.getInstance(n); } // BigInteger.shiftLeft() succumbs to a stack overflow if shift // is Integer.MIN_VALUE, so... if (shift == Integer.MIN_VALUE) return n >= 0 ? Fixnum.ZERO : Fixnum.MINUS_ONE; return number(BigInteger.valueOf(value).shiftLeft(shift)); } @Override public LispObject ash(LispObject obj) { if (obj instanceof Fixnum) return ash(((Fixnum)obj).value); if (obj instanceof Bignum) { if (value == 0) return this; BigInteger n = BigInteger.valueOf(value); BigInteger shift = ((Bignum)obj).value; if (shift.signum() > 0) return error(new LispError("Can't represent result of left shift.")); if (shift.signum() < 0) return n.signum() >= 0 ? Fixnum.ZERO : Fixnum.MINUS_ONE; Debug.bug(); // Shouldn't happen. } return type_error(obj, Symbol.INTEGER); } @Override public LispObject LOGNOT() { return Fixnum.getInstance(~value); } @Override public LispObject LOGAND(int n) { return Fixnum.getInstance(value & n); } @Override public LispObject LOGAND(LispObject obj) { if (obj instanceof Fixnum) return Fixnum.getInstance(value & ((Fixnum)obj).value); if (obj instanceof Bignum) { if (value >= 0) { int n2 = (((Bignum)obj).value).intValue(); return Fixnum.getInstance(value & n2); } else { BigInteger n1 = getBigInteger(); BigInteger n2 = ((Bignum)obj).value; return number(n1.and(n2)); } } return type_error(obj, Symbol.INTEGER); } @Override public LispObject LOGIOR(int n) { return Fixnum.getInstance(value | n); } @Override public LispObject LOGIOR(LispObject obj) { if (obj instanceof Fixnum) return Fixnum.getInstance(value | ((Fixnum)obj).value); if (obj instanceof Bignum) { BigInteger n1 = getBigInteger(); BigInteger n2 = ((Bignum)obj).value; return number(n1.or(n2)); } return type_error(obj, Symbol.INTEGER); } @Override public LispObject LOGXOR(int n) { return Fixnum.getInstance(value ^ n); } @Override public LispObject LOGXOR(LispObject obj) { if (obj instanceof Fixnum) return Fixnum.getInstance(value ^ ((Fixnum)obj).value); if (obj instanceof Bignum) { BigInteger n1 = getBigInteger(); BigInteger n2 = ((Bignum)obj).value; return number(n1.xor(n2)); } return type_error(obj, Symbol.INTEGER); } @Override public LispObject LDB(int size, int position) { long n = (long) value >> position; long mask = (1L << size) - 1; return number(n & mask); } final static BigInteger BIGINTEGER_TWO = new BigInteger ("2"); /** Computes fixnum^bignum, returning a fixnum or a bignum. */ public LispObject pow(LispObject obj) { BigInteger y = Bignum.getValue(obj); if (y.compareTo (BigInteger.ZERO) < 0) return (Fixnum.getInstance(1)).divideBy(this.pow(Bignum.getInstance(y.negate()))); if (y.compareTo(BigInteger.ZERO) == 0) // No need to test base here; CLHS says 0^0 == 1. return Fixnum.getInstance(1); int x = this.value; if (x == 0) return Fixnum.getInstance(0); if (x == 1) return Fixnum.getInstance(1); BigInteger xy = BigInteger.ONE; BigInteger term = BigInteger.valueOf((long) x); while (! y.equals(BigInteger.ZERO)) { if (y.testBit(0)) xy = xy.multiply(term); term = term.multiply(term); y = y.shiftLeft(1); } return Bignum.getInstance(xy); } @Override public int hashCode() { return value; } @Override public String printObject() { final LispThread thread = LispThread.currentThread(); int base = Fixnum.getValue(Symbol.PRINT_BASE.symbolValue(thread)); String s = Integer.toString(value, base).toUpperCase(); if (Symbol.PRINT_RADIX.symbolValue(thread) != NIL) { StringBuilder sb = new StringBuilder(); switch (base) { case 2: sb.append("#b"); sb.append(s); break; case 8: sb.append("#o"); sb.append(s); break; case 10: sb.append(s); sb.append('.'); break; case 16: sb.append("#x"); sb.append(s); break; default: sb.append('#'); sb.append(String.valueOf(base)); sb.append('r'); sb.append(s); break; } s = sb.toString(); } return s; } }
gpl-3.0
siddharth2571/NewPipe-master
app/src/main/java/com/pemikir/youtubeplus/youtube/YoutubeExtractor.java
20104
package com.pemikir.youtubeplus.youtube; import android.util.Log; import android.util.Xml; import com.pemikir.youtubeplus.Downloader; import com.pemikir.youtubeplus.Extractor; import com.pemikir.youtubeplus.VideoInfo; import com.pemikir.youtubeplus.VideoInfoItem; import org.json.JSONObject; import org.jsoup.Jsoup; import org.jsoup.nodes.Document; import org.jsoup.nodes.Element; import org.jsoup.parser.Parser; import org.mozilla.javascript.Context; import org.mozilla.javascript.Function; import org.mozilla.javascript.ScriptableObject; import org.xmlpull.v1.XmlPullParser; import java.io.StringReader; import java.net.URI; import java.util.HashMap; import java.util.Map; import java.util.Vector; import java.util.regex.Matcher; import java.util.regex.Pattern; /** * Created by Christian Schabesberger on 06.08.15. * <p/> * Copyright (C) Christian Schabesberger 2015 <chris.schabesberger@mailbox.org> * YoutubeExtractor.java is part of NewPipe. * <p/> * NewPipe is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * <p/> * NewPipe is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * <p/> * You should have received a copy of the GNU General Public License * along with NewPipe. If not, see <http://www.gnu.org/licenses/>. */ public class YoutubeExtractor implements Extractor { private static final String TAG = YoutubeExtractor.class.toString(); // These lists only contain itag formats that are supported by the common Android Video player. // How ever if you are heading for a list showing all itag formats lock at // https://github.com/rg3/youtube-dl/issues/1687 private static final String DECRYPTION_FUNC_NAME = "decrypt"; private String decryptoinCode = ""; public static int resolveFormat(int itag) { switch (itag) { // video case 17: return VideoInfo.I_3GPP; case 18: return VideoInfo.I_MPEG_4; case 22: return VideoInfo.I_MPEG_4; case 36: return VideoInfo.I_3GPP; case 37: return VideoInfo.I_MPEG_4; case 38: return VideoInfo.I_MPEG_4; case 43: return VideoInfo.I_WEBM; case 44: return VideoInfo.I_WEBM; case 45: return VideoInfo.I_WEBM; case 46: return VideoInfo.I_WEBM; default: //Log.i(TAG, "Itag " + Integer.toString(itag) + " not known or not supported."); return -1; } } public static String resolveResolutionString(int itag) { switch (itag) { case 17: return "144p"; case 18: return "360p"; case 22: return "720p"; case 36: return "240p"; case 37: return "1080p"; case 38: return "1080p"; case 43: return "360p"; case 44: return "480p"; case 45: return "720p"; case 46: return "1080p"; default: //Log.i(TAG, "Itag " + Integer.toString(itag) + " not known or not supported."); return null; } } @Override public String getVideoId(String videoUrl) { try { URI uri = new URI(videoUrl); if (uri.getHost().contains("youtube")) { String query = uri.getQuery(); String queryElements[] = query.split("&"); Map<String, String> queryArguments = new HashMap<>(); for (String e : queryElements) { String[] s = e.split("="); queryArguments.put(s[0], s[1]); } return queryArguments.get("v"); } else if (uri.getHost().contains("youtu.be")) { // uri.getRawPath() does somehow not return the last character. // so we do a workaround instead. //return uri.getRawPath(); String url[] = videoUrl.split("/"); return url[url.length - 1]; } else { Log.e(TAG, "Error could not parse url: " + videoUrl); } } catch (Exception e) { Log.e(TAG, "Error could not parse url: " + videoUrl); e.printStackTrace(); return ""; } return null; } @Override public String getVideoUrl(String videoId) { return "https://www.youtube.com/watch?v=" + videoId; } @Override public VideoInfo getVideoInfo(String siteUrl) { String site = Downloader.download(siteUrl); VideoInfo videoInfo = new VideoInfo(); Document doc = Jsoup.parse(site, siteUrl); try { Pattern p = Pattern.compile("v=([0-9a-zA-Z]*)"); Matcher m = p.matcher(siteUrl); m.find(); videoInfo.id = m.group(1); } catch (Exception e) { e.printStackTrace(); } videoInfo.age_limit = 0; videoInfo.webpage_url = siteUrl; //------------------------------------- // extracting form player args //------------------------------------- JSONObject playerArgs = null; JSONObject ytAssets = null; String dashManifest = ""; { Pattern p = Pattern.compile("ytplayer.config\\s*=\\s*(\\{.*?\\});"); Matcher m = p.matcher(site); m.find(); try { playerArgs = (new JSONObject(m.group(1))) .getJSONObject("args"); ytAssets = (new JSONObject(m.group(1))) .getJSONObject("assets"); } catch (Exception e) { e.printStackTrace(); // If we fail in this part the video is most likely not available. // Determining why is done later. videoInfo.videoAvailableStatus = VideoInfo.VIDEO_UNAVAILABLE; } } try { videoInfo.uploader = playerArgs.getString("author"); videoInfo.title = playerArgs.getString("title"); //first attempt gating a small image version //in the html extracting part we try to get a thumbnail with a higher resolution videoInfo.thumbnail_url = playerArgs.getString("thumbnail_url"); videoInfo.duration = playerArgs.getInt("length_seconds"); videoInfo.average_rating = playerArgs.getString("avg_rating"); // View Count will be extracted from html dashManifest = playerArgs.getString("dashmpd"); String playerUrl = ytAssets.getString("js"); if (playerUrl.startsWith("//")) { playerUrl = "https:" + playerUrl; } if (decryptoinCode.isEmpty()) { decryptoinCode = loadDecryptioinCode(playerUrl); } // extract audio videoInfo.audioStreams = parseDashManifest(dashManifest, decryptoinCode); //------------------------------------ // extract video stream url //------------------------------------ String encoded_url_map = playerArgs.getString("url_encoded_fmt_stream_map"); Vector<VideoInfo.VideoStream> videoStreams = new Vector<>(); for (String url_data_str : encoded_url_map.split(",")) { Map<String, String> tags = new HashMap<>(); for (String raw_tag : Parser.unescapeEntities(url_data_str, true).split("&")) { String[] split_tag = raw_tag.split("="); tags.put(split_tag[0], split_tag[1]); } int itag = Integer.parseInt(tags.get("itag")); String streamUrl = terrible_unescape_workaround_fuck(tags.get("url")); // if video has a signature: decrypt it and add it to the url if (tags.get("s") != null) { if (decryptoinCode.isEmpty()) { decryptoinCode = loadDecryptioinCode(playerUrl); } streamUrl = streamUrl + "&signature=" + decryptSignature(tags.get("s"), decryptoinCode); } if (resolveFormat(itag) != -1) { videoStreams.add(new VideoInfo.VideoStream( streamUrl, resolveFormat(itag), resolveResolutionString(itag))); } } videoInfo.videoStreams = new VideoInfo.VideoStream[videoStreams.size()]; for (int i = 0; i < videoStreams.size(); i++) { videoInfo.videoStreams[i] = videoStreams.get(i); } } catch (Exception e) { e.printStackTrace(); } //------------------------------- // extrating from html page //------------------------------- // Determine what went wrong when the Video is not available if (videoInfo.videoAvailableStatus == VideoInfo.VIDEO_UNAVAILABLE) { if (doc.select("h1[id=\"unavailable-message\"]").first().text().contains("GEMA")) { videoInfo.videoAvailableStatus = VideoInfo.VIDEO_UNAVAILABLE_GEMA; } } // Try to get high resolution thumbnail if it fails use low res from the player instead try { videoInfo.thumbnail_url = doc.select("link[itemprop=\"thumbnailUrl\"]").first() .attr("abs:href"); } catch (Exception e) { Log.i(TAG, "Could not find high res Thumbnail. Use low res instead"); } // upload date videoInfo.upload_date = doc.select("strong[class=\"watch-time-text\"").first() .text(); // Try to only use date not the text around it try { Pattern p = Pattern.compile("([0-9.]*$)"); Matcher m = p.matcher(videoInfo.upload_date); m.find(); videoInfo.upload_date = m.group(1); } catch (Exception e) { e.printStackTrace(); } // description videoInfo.description = doc.select("p[id=\"eow-description\"]").first() .html(); try { // likes videoInfo.like_count = doc.select("span[class=\"like-button-renderer \"]").first() .getAllElements().select("button") .select("span").get(0).text(); // dislikes videoInfo.dislike_count = doc.select("span[class=\"like-button-renderer \"]").first() .getAllElements().select("button") .select("span").get(2).text(); } catch (Exception e) { // if it fails we know that the video does not offer dislikes. videoInfo.like_count = "0"; videoInfo.dislike_count = "0"; } // uploader thumbnail videoInfo.uploader_thumbnail_url = doc.select("a[class*=\"yt-user-photo\"]").first() .select("img").first() .attr("abs:data-thumb"); // view count videoInfo.view_count = doc.select("div[class=\"watch-view-count\"]").first().text(); /* todo finish this code // next video videoInfo.nextVideo = extractVideoInfoItem(doc.select("div[class=\"watch-sidebar-section\"]").first() .select("li").first()); int i = 0; // related videos for(Element li : doc.select("ul[id=\"watch-related\"]").first().children()) { // first check if we have a playlist. If so leave them out if(li.select("a[class*=\"content-link\"]").first() != null) { //videoInfo.relatedVideos.add(extractVideoInfoItem(li)); //i++; //Log.d(TAG, Integer.toString(i)); } } */ return videoInfo; } private VideoInfo.AudioStream[] parseDashManifest(String dashManifest, String decryptoinCode) { if (!dashManifest.contains("/signature/")) { String encryptedSig = ""; String decryptedSig = ""; try { Pattern p = Pattern.compile("/s/([a-fA-F0-9\\.]+)"); Matcher m = p.matcher(dashManifest); m.find(); encryptedSig = m.group(1); } catch (Exception e) { e.printStackTrace(); } decryptedSig = decryptSignature(encryptedSig, decryptoinCode); dashManifest = dashManifest.replace("/s/" + encryptedSig, "/signature/" + decryptedSig); } String dashDoc = Downloader.download(dashManifest); Vector<VideoInfo.AudioStream> audioStreams = new Vector<>(); try { XmlPullParser parser = Xml.newPullParser(); parser.setInput(new StringReader(dashDoc)); int eventType = parser.getEventType(); String tagName = ""; String currentMimeType = ""; int currentBandwidth = -1; int currentSamplingRate = -1; boolean currentTagIsBaseUrl = false; while (eventType != XmlPullParser.END_DOCUMENT) { switch (eventType) { case XmlPullParser.START_TAG: tagName = parser.getName(); if (tagName.equals("AdaptationSet")) { currentMimeType = parser.getAttributeValue(XmlPullParser.NO_NAMESPACE, "mimeType"); } else if (tagName.equals("Representation") && currentMimeType.contains("audio")) { currentBandwidth = Integer.parseInt( parser.getAttributeValue(XmlPullParser.NO_NAMESPACE, "bandwidth")); currentSamplingRate = Integer.parseInt( parser.getAttributeValue(XmlPullParser.NO_NAMESPACE, "audioSamplingRate")); } else if (tagName.equals("BaseURL")) { currentTagIsBaseUrl = true; } break; case XmlPullParser.TEXT: if (currentTagIsBaseUrl && (currentMimeType.contains("audio"))) { int format = -1; if (currentMimeType.equals(VideoInfo.M_WEBMA)) { format = VideoInfo.I_WEBMA; } else if (currentMimeType.equals(VideoInfo.M_M4A)) { format = VideoInfo.I_M4A; } audioStreams.add(new VideoInfo.AudioStream(parser.getText(), format, currentBandwidth, currentSamplingRate)); } case XmlPullParser.END_TAG: if (tagName.equals("AdaptationSet")) { currentMimeType = ""; } else if (tagName.equals("BaseURL")) { currentTagIsBaseUrl = false; } break; default: } eventType = parser.next(); } } catch (Exception e) { e.printStackTrace(); } VideoInfo.AudioStream[] output = new VideoInfo.AudioStream[audioStreams.size()]; for (int i = 0; i < output.length; i++) { output[i] = audioStreams.get(i); } return output; } private VideoInfoItem extractVideoInfoItem(Element li) { VideoInfoItem info = new VideoInfoItem(); info.webpage_url = li.select("a[class*=\"content-link\"]").first() .attr("abs:href"); try { Pattern p = Pattern.compile("v=([0-9a-zA-Z-]*)"); Matcher m = p.matcher(info.webpage_url); m.find(); info.id = m.group(1); } catch (Exception e) { e.printStackTrace(); } info.title = li.select("span[class=\"title\"]").first() .text(); info.uploader = li.select("span[class=\"g-hovercard\"]").first().text(); info.duration = li.select("span[class=\"video-time\"]").first().text(); Element img = li.select("img").first(); info.thumbnail_url = img.attr("abs:src"); // Sometimes youtube sends links to gif files witch somehow seam to not exist // anymore. Items with such gif also offer a secondary image source. So we are going // to use that if we caught such an item. if (info.thumbnail_url.contains(".gif")) { info.thumbnail_url = img.attr("data-thumb"); } return info; } private String terrible_unescape_workaround_fuck(String shit) { String[] splitAtEscape = shit.split("%"); String retval = ""; retval += splitAtEscape[0]; for (int i = 1; i < splitAtEscape.length; i++) { String escNum = splitAtEscape[i].substring(0, 2); char c = (char) Integer.parseInt(escNum, 16); retval += c; retval += splitAtEscape[i].substring(2); } return retval; } private String loadDecryptioinCode(String playerUrl) { String playerCode = Downloader.download(playerUrl); String decryptionFuncName = ""; String decryptionFunc = ""; String helperObjectName; String helperObject = ""; String callerFunc = "function " + DECRYPTION_FUNC_NAME + "(a){return %%(a);}"; String decryptionCode; try { Pattern p = Pattern.compile("\\.sig\\|\\|([a-zA-Z0-9$]+)\\("); Matcher m = p.matcher(playerCode); m.find(); decryptionFuncName = m.group(1); String functionPattern = "(function " + decryptionFuncName.replace("$", "\\$") + "\\([a-zA-Z0-9_]*\\)\\{.+?\\})"; p = Pattern.compile(functionPattern); m = p.matcher(playerCode); m.find(); decryptionFunc = m.group(1); p = Pattern.compile(";([A-Za-z0-9_\\$]{2})\\...\\("); m = p.matcher(decryptionFunc); m.find(); helperObjectName = m.group(1); String helperPattern = "(var " + helperObjectName.replace("$", "\\$") + "=\\{.+?\\}\\};)function"; p = Pattern.compile(helperPattern); m = p.matcher(playerCode); m.find(); helperObject = m.group(1); } catch (Exception e) { e.printStackTrace(); } callerFunc = callerFunc.replace("%%", decryptionFuncName); decryptionCode = helperObject + decryptionFunc + callerFunc; return decryptionCode; } private String decryptSignature(String encryptedSig, String decryptoinCode) { Context context = Context.enter(); context.setOptimizationLevel(-1); Object result = null; try { ScriptableObject scope = context.initStandardObjects(); context.evaluateString(scope, decryptoinCode, "decryptionCode", 1, null); Function decryptionFunc = (Function) scope.get("decrypt", scope); result = decryptionFunc.call(context, scope, scope, new Object[]{encryptedSig}); } catch (Exception e) { e.printStackTrace(); } Context.exit(); return result.toString(); } }
gpl-3.0
LoloCDF/Zinlok
libs/snmp4j-2.4.3/src/main/java/org/snmp4j/asn1/BERInputStream.java
5982
/*_############################################################################ _## _## SNMP4J 2 - BERInputStream.java _## _## Copyright (C) 2003-2016 Frank Fock and Jochen Katz (SNMP4J.org) _## _## Licensed under the Apache License, Version 2.0 (the "License"); _## you may not use this file except in compliance with the License. _## You may obtain a copy of the License at _## _## http://www.apache.org/licenses/LICENSE-2.0 _## _## Unless required by applicable law or agreed to in writing, software _## distributed under the License is distributed on an "AS IS" BASIS, _## WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. _## See the License for the specific language governing permissions and _## limitations under the License. _## _##########################################################################*/ package org.snmp4j.asn1; import java.io.*; import java.nio.ByteBuffer; import java.nio.BufferUnderflowException; /** * The <code>BERInputStream</code> class wraps a <code>ByteBuffer</code> and * implements the <code>InputStream</code> abstract class. * positions in the input stream. * * @author Frank Fock * @version 1.6.1 */ public class BERInputStream extends InputStream { private ByteBuffer buffer; public BERInputStream(ByteBuffer buffer) { this.buffer = buffer; buffer.mark(); } public ByteBuffer getBuffer() { return buffer; } public void setBuffer(ByteBuffer buf) { this.buffer = buf; } public int read() throws java.io.IOException { try { return (buffer.get() & 0xFF); } catch (BufferUnderflowException ex) { throw new IOException("Unexpected end of input stream at position "+ getPosition()); } } /** * Returns the number of bytes that can be read (or skipped over) from this * input stream without blocking by the next caller of a method for this input * stream. * * @return the number of bytes that can be read from this input stream without * blocking. * @throws IOException if an I/O error occurs. */ public int available() throws IOException { return buffer.remaining(); } /** * Closes this input stream and releases any system resources associated with * the stream. * * @throws IOException if an I/O error occurs. */ public void close() throws IOException { } /** * Marks the current position in this input stream. * * @param readlimit the maximum limit of bytes that can be read before the * mark position becomes invalid. */ public synchronized void mark(int readlimit) { buffer.mark(); } /** * Tests if this input stream supports the <code>mark</code> and * <code>reset</code> methods. * * @return <code>true</code> if this stream instance supports the mark and * reset methods; <code>false</code> otherwise. */ public boolean markSupported() { return true; } /** * Reads some number of bytes from the input stream and stores them into the * buffer array <code>b</code>. * * @param b the buffer into which the data is read. * @return the total number of bytes read into the buffer, or <code>-1</code> * is there is no more data because the end of the stream has been reached. * @throws IOException if an I/O error occurs. */ public int read(byte[] b) throws IOException { if (buffer.remaining() <= 0) { return -1; } int read = Math.min(buffer.remaining(), b.length); buffer.get(b, 0, read); return read; } /** * Reads up to <code>len</code> bytes of data from the input stream into an * array of bytes. * * @param b the buffer into which the data is read. * @param off the start offset in array <code>b</code> at which the data is * written. * @param len the maximum number of bytes to read. * @return the total number of bytes read into the buffer, or <code>-1</code> * if there is no more data because the end of the stream has been reached. * @throws IOException if an I/O error occurs. */ public int read(byte[] b, int off, int len) throws IOException { if (buffer.remaining() <= 0) { return -1; } int read = Math.min(buffer.remaining(), b.length); buffer.get(b, off, len); return read; } /** * Repositions this stream to the position at the time the <code>mark</code> * method was last called on this input stream. * * @throws IOException if this stream has not been marked or if the mark has * been invalidated. */ public synchronized void reset() throws IOException { buffer.reset(); } /** * Skips over and discards <code>n</code> bytes of data from this input stream. * * @param n the number of bytes to be skipped. * @return the actual number of bytes skipped. * @throws IOException if an I/O error occurs. */ public long skip(long n) throws IOException { long skipped = Math.min(buffer.remaining(), n); buffer.position((int)(buffer.position() + skipped)); return skipped; } /** * Gets the current position in the underlying <code>buffer</code>. * @return * <code>buffer.position()</code>. */ public long getPosition() { return buffer.position(); } /** * Checks whether a mark has been set on the input stream. This can be used * to determine whether the value returned by {@link #available()} is limited * by a readlimit set when the mark has been set. * @return * always <code>true</code>. If no mark has been set explicitly, the mark * is set to the initial position (i.e. zero). */ public boolean isMarked() { return true; } /** * Gets the total number of bytes that can be read from this input stream. * @return * the number of bytes that can be read from this stream. */ public int getAvailableBytes() { return buffer.limit(); } }
gpl-3.0
DevTechnology/DRIC
api/dric-api-webapp/src/main/java/com/devtechnology/api/domain/RecallResponse.java
818
package com.devtechnology.api.domain; import java.util.ArrayList; import java.util.List; import javax.xml.bind.annotation.XmlRootElement; /** * POJO representing DRIC response object * @author jbnimble * */ @XmlRootElement public class RecallResponse { private FdaMeta meta; private List<RecallItem> recalls; private FdaError error; public FdaMeta getMeta() { return meta; } public void setMeta(FdaMeta meta) { this.meta = meta; } public List<RecallItem> getRecalls() { recalls = (recalls == null) ? new ArrayList<RecallItem>() : recalls; return recalls; } public void setRecalls(List<RecallItem> recalls) { this.recalls = recalls; } public FdaError getError() { return error; } public void setError(FdaError error) { this.error = error; } }
gpl-3.0
RHG101997/Future-Production
FutureProduction_common/FP/Blocks/Mineral_Ore.java
584
package FP.Blocks; import FP.lib.Textures; import net.minecraft.block.Block; import net.minecraft.block.material.Material; import net.minecraft.client.renderer.texture.IconRegister; public class Mineral_Ore extends Block { public Mineral_Ore(int id, Material mat) { super(id, mat); this.setCreativeTab(FP.FutureProduction1.tabFutureProduction); this.setHardness(3.0F); this.setResistance(50F); } @Override public void registerIcons(IconRegister reg) { blockIcon = reg.registerIcon(Textures.MINERAL_ORE_LOCATION); } }
gpl-3.0
lcappuccio/simplexdb
src/test/java/org/systemexception/simplexdb/test/StorageServiceTest.java
2587
package org.systemexception.simplexdb.test; import org.junit.AfterClass; import org.junit.Before; import org.junit.BeforeClass; import org.junit.Test; import org.systemexception.simplexdb.domain.Data; import org.systemexception.simplexdb.service.StorageService; import org.systemexception.simplexdb.test.database.AbstractDbTest; import java.io.File; import java.io.IOException; import java.nio.file.Files; import java.nio.file.attribute.BasicFileAttributes; import java.text.Format; import java.text.SimpleDateFormat; import java.util.Date; import static org.junit.Assert.assertFalse; import static org.junit.Assert.assertTrue; /** * @author leo * @date 08/12/15 22:09 */ public class StorageServiceTest { private final static String STORAGE_FOLDER = AbstractDbTest.TARGET_FOLDER + File.separator + "test_output"; private final Data testData = new Data("TEST", "TEST".getBytes()); private StorageService sut; @BeforeClass public static void setSut() { File toRemove = new File(STORAGE_FOLDER); if (toRemove.exists()) { String[] files = toRemove.list(); for (String file : files) { new File(STORAGE_FOLDER + File.separator + file).delete(); } } toRemove.delete(); assertFalse(toRemove.exists()); } @AfterClass public static void tearDownSut() { File toRemove = new File(STORAGE_FOLDER); if (toRemove.exists()) { String[] files = toRemove.list(); for (String file : files) { new File(STORAGE_FOLDER + File.separator + file).delete(); } } toRemove.delete(); assertFalse(toRemove.exists()); } @Before public void setUp() throws IOException { sut = new StorageService(STORAGE_FOLDER); } @Test public void outputFolderExists() { assertTrue(new File(STORAGE_FOLDER).exists()); } @Test public void saveDataExists() throws IOException { sut.saveFile(testData); File testDataFile = new File(STORAGE_FOLDER + File.separator + testData.getName()); assertTrue(testDataFile.exists()); } @Test public void historify() throws IOException { sut.saveFile(testData); File testDataFile = new File(STORAGE_FOLDER + File.separator + testData.getName()); BasicFileAttributes attrs = Files.readAttributes(testDataFile.toPath(), BasicFileAttributes.class); sut.saveFile(testData); assertTrue(new File(STORAGE_FOLDER + File.separator + convertTime(attrs.creationTime().toMillis()) + "_" + testDataFile.getName()).exists()); } private String convertTime(long time) { Date date = new Date(time); Format format = new SimpleDateFormat(StorageService.DATE_TIME_FORMAT); return format.format(date); } }
gpl-3.0
wiki2014/Learning-Summary
alps/cts/hostsidetests/appsecurity/src/android/appsecurity/cts/AdoptableHostTest.java
14710
/* * Copyright (C) 2015 The Android Open Source Project * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package android.appsecurity.cts; import static android.appsecurity.cts.SplitTests.ABI_TO_APK; import static android.appsecurity.cts.SplitTests.APK; import static android.appsecurity.cts.SplitTests.APK_mdpi; import static android.appsecurity.cts.SplitTests.APK_xxhdpi; import static android.appsecurity.cts.SplitTests.CLASS; import static android.appsecurity.cts.SplitTests.PKG; import android.appsecurity.cts.SplitTests.BaseInstallMultiple; import com.android.cts.migration.MigrationHelper; import com.android.tradefed.build.IBuildInfo; import com.android.tradefed.device.CollectingOutputReceiver; import com.android.tradefed.device.DeviceNotAvailableException; import com.android.tradefed.testtype.DeviceTestCase; import com.android.tradefed.testtype.IAbi; import com.android.tradefed.testtype.IAbiReceiver; import com.android.tradefed.testtype.IBuildReceiver; import java.util.Arrays; import java.util.concurrent.TimeUnit; /** * Set of tests that verify behavior of adopted storage media, if supported. */ public class AdoptableHostTest extends DeviceTestCase implements IAbiReceiver, IBuildReceiver { private IAbi mAbi; private IBuildInfo mCtsBuild; @Override public void setAbi(IAbi abi) { mAbi = abi; } @Override public void setBuild(IBuildInfo buildInfo) { mCtsBuild = buildInfo; } @Override protected void setUp() throws Exception { super.setUp(); assertNotNull(mAbi); assertNotNull(mCtsBuild); getDevice().uninstallPackage(PKG); } @Override protected void tearDown() throws Exception { super.tearDown(); getDevice().uninstallPackage(PKG); } public void testApps() throws Exception { if (!hasAdoptable()) return; final String diskId = getAdoptionDisk(); try { final String abi = mAbi.getName(); final String apk = ABI_TO_APK.get(abi); assertNotNull("Failed to find APK for ABI " + abi, apk); // Install simple app on internal new InstallMultiple().useNaturalAbi().addApk(APK).addApk(apk).run(); runDeviceTests(PKG, CLASS, "testDataInternal"); runDeviceTests(PKG, CLASS, "testDataWrite"); runDeviceTests(PKG, CLASS, "testDataRead"); runDeviceTests(PKG, CLASS, "testNative"); // Adopt that disk! assertEmpty(getDevice().executeShellCommand("sm partition " + diskId + " private")); final LocalVolumeInfo vol = getAdoptionVolume(); // Move app and verify assertSuccess(getDevice().executeShellCommand( "pm move-package " + PKG + " " + vol.uuid)); runDeviceTests(PKG, CLASS, "testDataNotInternal"); runDeviceTests(PKG, CLASS, "testDataRead"); runDeviceTests(PKG, CLASS, "testNative"); // Unmount, remount and verify getDevice().executeShellCommand("sm unmount " + vol.volId); getDevice().executeShellCommand("sm mount " + vol.volId); runDeviceTests(PKG, CLASS, "testDataNotInternal"); runDeviceTests(PKG, CLASS, "testDataRead"); runDeviceTests(PKG, CLASS, "testNative"); // Move app back and verify assertSuccess(getDevice().executeShellCommand("pm move-package " + PKG + " internal")); runDeviceTests(PKG, CLASS, "testDataInternal"); runDeviceTests(PKG, CLASS, "testDataRead"); runDeviceTests(PKG, CLASS, "testNative"); // Un-adopt volume and app should still be fine getDevice().executeShellCommand("sm partition " + diskId + " public"); runDeviceTests(PKG, CLASS, "testDataInternal"); runDeviceTests(PKG, CLASS, "testDataRead"); runDeviceTests(PKG, CLASS, "testNative"); } finally { cleanUp(diskId); } } public void testPrimaryStorage() throws Exception { if (!hasAdoptable()) return; final String diskId = getAdoptionDisk(); try { final String originalVol = getDevice() .executeShellCommand("sm get-primary-storage-uuid").trim(); if ("null".equals(originalVol)) { verifyPrimaryInternal(diskId); } else if ("primary_physical".equals(originalVol)) { verifyPrimaryPhysical(diskId); } } finally { cleanUp(diskId); } } private void verifyPrimaryInternal(String diskId) throws Exception { // Write some data to shared storage new InstallMultiple().addApk(APK).run(); runDeviceTests(PKG, CLASS, "testPrimaryOnSameVolume"); runDeviceTests(PKG, CLASS, "testPrimaryInternal"); runDeviceTests(PKG, CLASS, "testPrimaryDataWrite"); runDeviceTests(PKG, CLASS, "testPrimaryDataRead"); // Adopt that disk! assertEmpty(getDevice().executeShellCommand("sm partition " + diskId + " private")); final LocalVolumeInfo vol = getAdoptionVolume(); // Move storage there and verify that data went along for ride CollectingOutputReceiver out = new CollectingOutputReceiver(); getDevice().executeShellCommand("pm move-primary-storage " + vol.uuid, out, 2, TimeUnit.HOURS, 1); assertSuccess(out.getOutput()); runDeviceTests(PKG, CLASS, "testPrimaryAdopted"); runDeviceTests(PKG, CLASS, "testPrimaryDataRead"); // Unmount and verify getDevice().executeShellCommand("sm unmount " + vol.volId); runDeviceTests(PKG, CLASS, "testPrimaryUnmounted"); getDevice().executeShellCommand("sm mount " + vol.volId); runDeviceTests(PKG, CLASS, "testPrimaryAdopted"); runDeviceTests(PKG, CLASS, "testPrimaryDataRead"); // Move app and verify backing storage volume is same assertSuccess(getDevice().executeShellCommand("pm move-package " + PKG + " " + vol.uuid)); runDeviceTests(PKG, CLASS, "testPrimaryOnSameVolume"); runDeviceTests(PKG, CLASS, "testPrimaryDataRead"); // And move back to internal out = new CollectingOutputReceiver(); getDevice().executeShellCommand("pm move-primary-storage internal", out, 2, TimeUnit.HOURS, 1); assertSuccess(out.getOutput()); runDeviceTests(PKG, CLASS, "testPrimaryInternal"); runDeviceTests(PKG, CLASS, "testPrimaryDataRead"); assertSuccess(getDevice().executeShellCommand("pm move-package " + PKG + " internal")); runDeviceTests(PKG, CLASS, "testPrimaryOnSameVolume"); runDeviceTests(PKG, CLASS, "testPrimaryDataRead"); } private void verifyPrimaryPhysical(String diskId) throws Exception { // Write some data to shared storage new InstallMultiple().addApk(APK).run(); runDeviceTests(PKG, CLASS, "testPrimaryPhysical"); runDeviceTests(PKG, CLASS, "testPrimaryDataWrite"); runDeviceTests(PKG, CLASS, "testPrimaryDataRead"); // Adopt that disk! assertEmpty(getDevice().executeShellCommand("sm partition " + diskId + " private")); final LocalVolumeInfo vol = getAdoptionVolume(); // Move primary storage there, but since we just nuked primary physical // the storage device will be empty assertSuccess(getDevice().executeShellCommand("pm move-primary-storage " + vol.uuid)); runDeviceTests(PKG, CLASS, "testPrimaryAdopted"); runDeviceTests(PKG, CLASS, "testPrimaryDataWrite"); runDeviceTests(PKG, CLASS, "testPrimaryDataRead"); // Unmount and verify getDevice().executeShellCommand("sm unmount " + vol.volId); runDeviceTests(PKG, CLASS, "testPrimaryUnmounted"); getDevice().executeShellCommand("sm mount " + vol.volId); runDeviceTests(PKG, CLASS, "testPrimaryAdopted"); runDeviceTests(PKG, CLASS, "testPrimaryDataRead"); // And move to internal assertSuccess(getDevice().executeShellCommand("pm move-primary-storage internal")); runDeviceTests(PKG, CLASS, "testPrimaryOnSameVolume"); runDeviceTests(PKG, CLASS, "testPrimaryInternal"); runDeviceTests(PKG, CLASS, "testPrimaryDataRead"); } /** * Verify that we can install both new and inherited packages directly on * adopted volumes. */ public void testPackageInstaller() throws Exception { if (!hasAdoptable()) return; final String diskId = getAdoptionDisk(); try { assertEmpty(getDevice().executeShellCommand("sm partition " + diskId + " private")); final LocalVolumeInfo vol = getAdoptionVolume(); // Install directly onto adopted volume new InstallMultiple().locationAuto().forceUuid(vol.uuid) .addApk(APK).addApk(APK_mdpi).run(); runDeviceTests(PKG, CLASS, "testDataNotInternal"); runDeviceTests(PKG, CLASS, "testDensityBest1"); // Now splice in an additional split which offers better resources new InstallMultiple().locationAuto().inheritFrom(PKG) .addApk(APK_xxhdpi).run(); runDeviceTests(PKG, CLASS, "testDataNotInternal"); runDeviceTests(PKG, CLASS, "testDensityBest2"); } finally { cleanUp(diskId); } } /** * Verify behavior when changes occur while adopted device is ejected and * returned at a later time. */ public void testEjected() throws Exception { if (!hasAdoptable()) return; final String diskId = getAdoptionDisk(); try { assertEmpty(getDevice().executeShellCommand("sm partition " + diskId + " private")); final LocalVolumeInfo vol = getAdoptionVolume(); // Install directly onto adopted volume, and write data there new InstallMultiple().locationAuto().forceUuid(vol.uuid).addApk(APK).run(); runDeviceTests(PKG, CLASS, "testDataNotInternal"); runDeviceTests(PKG, CLASS, "testDataWrite"); runDeviceTests(PKG, CLASS, "testDataRead"); // Now unmount and uninstall; leaving stale package on adopted volume getDevice().executeShellCommand("sm unmount " + vol.volId); getDevice().uninstallPackage(PKG); // Install second copy on internal, but don't write anything new InstallMultiple().locationInternalOnly().addApk(APK).run(); runDeviceTests(PKG, CLASS, "testDataInternal"); // Kick through a remount cycle, which should purge the adopted app getDevice().executeShellCommand("sm mount " + vol.volId); runDeviceTests(PKG, CLASS, "testDataInternal"); try { runDeviceTests(PKG, CLASS, "testDataRead"); fail("Unexpected data from adopted volume picked up"); } catch (AssertionError expected) { } getDevice().executeShellCommand("sm unmount " + vol.volId); // Uninstall the internal copy and remount; we should have no record of app getDevice().uninstallPackage(PKG); getDevice().executeShellCommand("sm mount " + vol.volId); assertEmpty(getDevice().executeShellCommand("pm list packages " + PKG)); } finally { cleanUp(diskId); } } private boolean hasAdoptable() throws Exception { return Boolean.parseBoolean(getDevice().executeShellCommand("sm has-adoptable").trim()); } private String getAdoptionDisk() throws Exception { final String disks = getDevice().executeShellCommand("sm list-disks adoptable"); if (disks == null || disks.length() == 0) { throw new AssertionError("Devices that claim to support adoptable storage must have " + "adoptable media inserted during CTS to verify correct behavior"); } return disks.split("\n")[0].trim(); } private LocalVolumeInfo getAdoptionVolume() throws Exception { String[] lines = null; int attempt = 0; while (attempt++ < 15) { lines = getDevice().executeShellCommand("sm list-volumes private").split("\n"); for (String line : lines) { final LocalVolumeInfo info = new LocalVolumeInfo(line.trim()); if (!"private".equals(info.volId) && "mounted".equals(info.state)) { return info; } } Thread.sleep(1000); } throw new AssertionError("Expected private volume; found " + Arrays.toString(lines)); } private void cleanUp(String diskId) throws Exception { getDevice().executeShellCommand("sm partition " + diskId + " public"); getDevice().executeShellCommand("sm forget all"); } private void runDeviceTests(String packageName, String testClassName, String testMethodName) throws DeviceNotAvailableException { Utils.runDeviceTests(getDevice(), packageName, testClassName, testMethodName); } private static void assertSuccess(String str) { if (str == null || !str.startsWith("Success")) { throw new AssertionError("Expected success string but found " + str); } } private static void assertEmpty(String str) { if (str != null && str.trim().length() > 0) { throw new AssertionError("Expected empty string but found " + str); } } private static class LocalVolumeInfo { public String volId; public String state; public String uuid; public LocalVolumeInfo(String line) { final String[] split = line.split(" "); volId = split[0]; state = split[1]; uuid = split[2]; } } private class InstallMultiple extends BaseInstallMultiple<InstallMultiple> { public InstallMultiple() { super(getDevice(), mCtsBuild, mAbi); } } }
gpl-3.0
iCarto/siga
extGeoreferencing/src/org/gvsig/georeferencing/ui/zoom/tools/SelectPointTool.java
3007
/* gvSIG. Sistema de Información Geográfica de la Generalitat Valenciana * * Copyright (C) 2007 IVER T.I. and Generalitat Valenciana. * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License * as published by the Free Software Foundation; either version 2 * of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307,USA. */ package org.gvsig.georeferencing.ui.zoom.tools; import java.awt.Graphics; import java.awt.event.MouseEvent; import java.awt.event.MouseListener; import java.awt.event.MouseMotionListener; import java.awt.geom.Point2D; import org.gvsig.georeferencing.ui.zoom.CanvasZone; /** * Herramienta de selección de puntos de control sobre la vista * * 17/01/2008 * @author Nacho Brodin (nachobrodin@gmail.com) */ public class SelectPointTool extends BaseViewTool implements MouseListener, MouseMotionListener { private Point2D[] pointSelected = null; /** * Constructor. Asigna el canvas e inicializa los listeners. * @param canvas */ public SelectPointTool(CanvasZone canvas, ToolListener listener) { super(canvas, listener); canvas.addMouseListener(this); canvas.addMouseMotionListener(this); pointSelected = new Point2D[2]; } /** * Asigna el flag que activa y desactiva la herramienta * @param active true para activarla y false para desactivarla */ public void setActive(boolean active) { this.active = active; if(active) onTool(new ToolEvent(this)); else offTool(new ToolEvent(this)); } /* * (non-Javadoc) * @see org.gvsig.rastertools.georeferencing.ui.zoom.IViewTool#draw(java.awt.image.BufferedImage, java.awt.geom.Rectangle2D) */ public void draw(Graphics g) { } /* * (non-Javadoc) * @see org.gvsig.rastertools.georeferencing.ui.zoom.IViewTool#getResult() */ public Object getResult() { return pointSelected; } /** * Selecciona el punto inicial del cuadro del que se quiere el zoom */ public void mousePressed(MouseEvent e) { if(!isActive()) return; pointSelected[0] = e.getPoint(); pointSelected[1] = canvas.viewCoordsToWorld(pointSelected[0]); for (int i = 0; i < listeners.size(); i++) ((ToolListener)listeners.get(i)).endAction(new ToolEvent(this)); } public void mouseDragged(MouseEvent e) { } public void mouseReleased(MouseEvent e) { } public void mouseClicked(MouseEvent e) { } public void mouseEntered(MouseEvent e) { } public void mouseExited(MouseEvent e) { } public void mouseMoved(MouseEvent e) { } }
gpl-3.0
repoxIST/repoxLight
repox-gui/src/main/java/harvesterUI/client/panels/overviewGrid/MyPagingToolBar.java
31329
/* * Ext GWT 2.2.0 - Ext for GWT * Copyright(c) 2007-2010, Ext JS, LLC. * licensing@extjs.com * * http://extjs.com/license */ package harvesterUI.client.panels.overviewGrid; import com.extjs.gxt.ui.client.GXT; import com.extjs.gxt.ui.client.Registry; import com.extjs.gxt.ui.client.data.*; import com.extjs.gxt.ui.client.event.*; import com.extjs.gxt.ui.client.util.Format; import com.extjs.gxt.ui.client.util.IconHelper; import com.extjs.gxt.ui.client.util.Util; import com.extjs.gxt.ui.client.widget.Component; import com.extjs.gxt.ui.client.widget.WidgetComponent; import com.extjs.gxt.ui.client.widget.button.Button; import com.extjs.gxt.ui.client.widget.form.ComboBox; import com.extjs.gxt.ui.client.widget.form.SimpleComboBox; import com.extjs.gxt.ui.client.widget.form.SimpleComboValue; import com.extjs.gxt.ui.client.widget.toolbar.FillToolItem; import com.extjs.gxt.ui.client.widget.toolbar.LabelToolItem; import com.extjs.gxt.ui.client.widget.toolbar.SeparatorToolItem; import com.extjs.gxt.ui.client.widget.toolbar.ToolBar; import com.google.gwt.event.dom.client.KeyCodes; import com.google.gwt.event.dom.client.KeyDownEvent; import com.google.gwt.event.dom.client.KeyDownHandler; import com.google.gwt.user.client.Cookies; import com.google.gwt.user.client.Element; import com.google.gwt.user.client.ui.AbstractImagePrototype; import com.google.gwt.user.client.ui.TextBox; import harvesterUI.client.HarvesterUI; import harvesterUI.client.panels.grid.DataGridContainer; import harvesterUI.client.util.CookieManager; import harvesterUI.client.util.UtilManager; /** * A specialized toolbar that is bound to a {@link ListLoader} and provides * automatic paging controls. * <p/> * <dl> * <dt>Inherited Events:</dt> * <dd>Component Enable</dd> * <dd>Component Disable</dd> * <dd>Component BeforeHide</dd> * <dd>Component Hide</dd> * <dd>Component BeforeShow</dd> * <dd>Component Show</dd> * <dd>Component Attach</dd> * <dd>Component Detach</dd> * <dd>Component BeforeRender</dd> * <dd>Component Render</dd> * <dd>Component BrowserEvent</dd> * <dd>Component BeforeStateRestore</dd> * <dd>Component StateRestore</dd> * <dd>Component BeforeStateSave</dd> * <dd>Component SaveState</dd> * </dl> */ public class MyPagingToolBar extends ToolBar { private SimpleComboBox<String> perPageCombo; /** * PagingToolBar images. */ public static class PagingToolBarImages { private AbstractImagePrototype first = GXT.isHighContrastMode ? IconHelper.create("gxt/themes/access/images/grid/page-first.gif") : GXT.IMAGES.paging_toolbar_first(); private AbstractImagePrototype prev = GXT.isHighContrastMode ? IconHelper.create("gxt/themes/access/images/grid/page-prev.gif") : GXT.IMAGES.paging_toolbar_prev(); private AbstractImagePrototype next = GXT.isHighContrastMode ? IconHelper.create("gxt/themes/access/images/grid/page-next.gif") : GXT.IMAGES.paging_toolbar_next(); private AbstractImagePrototype last = GXT.isHighContrastMode ? IconHelper.create("gxt/themes/access/images/grid/page-last.gif") : GXT.IMAGES.paging_toolbar_last(); private AbstractImagePrototype refresh = GXT.isHighContrastMode ? IconHelper.create("gxt/themes/access/images/grid/refresh.gif") : GXT.IMAGES.paging_toolbar_refresh(); private AbstractImagePrototype firstDisabled = GXT.IMAGES.paging_toolbar_first_disabled(); private AbstractImagePrototype prevDisabled = GXT.IMAGES.paging_toolbar_prev_disabled(); private AbstractImagePrototype nextDisabled = GXT.IMAGES.paging_toolbar_next_disabled(); private AbstractImagePrototype lastDisabled = GXT.IMAGES.paging_toolbar_last_disabled(); public AbstractImagePrototype getFirst() { return first; } public AbstractImagePrototype getFirstDisabled() { return firstDisabled; } public AbstractImagePrototype getLast() { return last; } public AbstractImagePrototype getLastDisabled() { return lastDisabled; } public AbstractImagePrototype getNext() { return next; } public AbstractImagePrototype getNextDisabled() { return nextDisabled; } public AbstractImagePrototype getPrev() { return prev; } public AbstractImagePrototype getPrevDisabled() { return prevDisabled; } public AbstractImagePrototype getRefresh() { return refresh; } public void setFirst(AbstractImagePrototype first) { this.first = first; } public void setFirstDisabled(AbstractImagePrototype firstDisabled) { this.firstDisabled = firstDisabled; } public void setLast(AbstractImagePrototype last) { this.last = last; } public void setLastDisabled(AbstractImagePrototype lastDisabled) { this.lastDisabled = lastDisabled; } public void setNext(AbstractImagePrototype next) { this.next = next; } public void setNextDisabled(AbstractImagePrototype nextDisabled) { this.nextDisabled = nextDisabled; } public void setPrev(AbstractImagePrototype prev) { this.prev = prev; } public void setPrevDisabled(AbstractImagePrototype prevDisabled) { this.prevDisabled = prevDisabled; } public void setRefresh(AbstractImagePrototype refresh) { this.refresh = refresh; } } /** * PagingToolBar messages. */ public static class PagingToolBarMessages { private String afterPageText; private String beforePageText = GXT.MESSAGES.pagingToolBar_beforePageText(); private String displayMsg; private String emptyMsg = GXT.MESSAGES.pagingToolBar_emptyMsg(); private String firstText = GXT.MESSAGES.pagingToolBar_firstText(); private String lastText = GXT.MESSAGES.pagingToolBar_lastText(); private String nextText = GXT.MESSAGES.pagingToolBar_nextText(); private String prevText = GXT.MESSAGES.pagingToolBar_prevText(); private String refreshText = GXT.MESSAGES.pagingToolBar_refreshText(); /** * Returns the after page text. * * @return the after page text */ public String getAfterPageText() { return afterPageText; } /** * Returns the before page text. * * @return the before page text */ public String getBeforePageText() { return beforePageText; } /** * Returns the display message. * * @return the display message. */ public String getDisplayMsg() { return displayMsg; } /** * Returns the empty message. * * @return the empty message */ public String getEmptyMsg() { return emptyMsg; } public String getFirstText() { return firstText; } /** * Returns the last text. * * @return the last text */ public String getLastText() { return lastText; } /** * Returns the next text. * * @return the next ext */ public String getNextText() { return nextText; } /** * Returns the previous text. * * @return the previous text */ public String getPrevText() { return prevText; } /** * Returns the refresh text. * * @return the refresh text */ public String getRefreshText() { return refreshText; } /** * Customizable piece of the default paging text (defaults to "of {0}"). * * @param afterPageText the after page text */ public void setAfterPageText(String afterPageText) { this.afterPageText = afterPageText; } /** * Customizable piece of the default paging text (defaults to "Page"). * * @param beforePageText the before page text */ public void setBeforePageText(String beforePageText) { this.beforePageText = beforePageText; } /** * The paging status message to display (defaults to "Displaying {0} - {1} * of {2}"). Note that this string is formatted using the braced numbers 0-2 * as tokens that are replaced by the values for start, end and total * respectively. These tokens should be preserved when overriding this * string if showing those values is desired. * * @param displayMsg the display message */ public void setDisplayMsg(String displayMsg) { this.displayMsg = displayMsg; } /** * The message to display when no records are found (defaults to "No data to * display"). * * @param emptyMsg the empty message */ public void setEmptyMsg(String emptyMsg) { this.emptyMsg = emptyMsg; } /** * Customizable piece of the default paging text (defaults to "First Page"). * * @param firstText the first text */ public void setFirstText(String firstText) { this.firstText = firstText; } /** * Customizable piece of the default paging text (defaults to "Last Page"). * * @param lastText the last text */ public void setLastText(String lastText) { this.lastText = lastText; } /** * Customizable piece of the default paging text (defaults to "Next Page"). * * @param nextText the next text */ public void setNextText(String nextText) { this.nextText = nextText; } /** * Customizable piece of the default paging text (defaults to "Previous * Page"). * * @param prevText the prev text */ public void setPrevText(String prevText) { this.prevText = prevText; } /** * Customizable piece of the default paging text (defaults to "Refresh"). * * @param refreshText the refresh text */ public void setRefreshText(String refreshText) { this.refreshText = refreshText; } } protected PagingLoader<?> loader; protected PagingLoadConfig config; protected int start, pageSize, totalLength; protected int activePage = -1, pages; protected Button first, prev, next, last, refresh; protected LabelToolItem afterText; protected LabelToolItem displayText; protected TextBox pageText; protected PagingToolBarMessages msgs; protected boolean showToolTips = true; protected LoadListener loadListener; protected PagingToolBarImages images; private boolean reuseConfig = true; private LoadEvent renderEvent; private boolean savedEnableState = true; private Listener<ComponentEvent> listener = new Listener<ComponentEvent>() { public void handleEvent(ComponentEvent be) { Component c = be.getComponent(); if (be.getType() == Events.Disable) { if (c == first) { first.setIcon(getImages().getFirstDisabled()); } else if (c == prev) { prev.setIcon(getImages().getPrevDisabled()); } else if (c == next) { next.setIcon(getImages().getNextDisabled()); } else if (c == last) { last.setIcon(getImages().getLastDisabled()); } } else { if (c == first) { first.setIcon(getImages().getFirst()); } else if (c == prev) { prev.setIcon(getImages().getPrev()); } else if (c == next) { next.setIcon(getImages().getNext()); } else if (c == last) { last.setIcon(getImages().getLast()); } } } }; protected LabelToolItem beforePage; private DataGridContainer mainGridContainer; /** * Creates a new paging tool bar with the given page size. * * @param pageSize the page size */ public MyPagingToolBar(final int pageSize, DataGridContainer mainGridContainer) { this.pageSize = pageSize; this.mainGridContainer = mainGridContainer; first = new Button(); first.addListener(Events.Disable, listener); first.addListener(Events.Enable, listener); first.addSelectionListener(new SelectionListener<ButtonEvent>() { public void componentSelected(ButtonEvent ce) { first(); } }); prev = new Button(); prev.addListener(Events.Disable, listener); prev.addListener(Events.Enable, listener); prev.addSelectionListener(new SelectionListener<ButtonEvent>() { public void componentSelected(ButtonEvent ce) { previous(); } }); next = new Button(); next.addListener(Events.Disable, listener); next.addListener(Events.Enable, listener); next.addSelectionListener(new SelectionListener<ButtonEvent>() { public void componentSelected(ButtonEvent ce) { next(); } }); last = new Button(); last.addListener(Events.Disable, listener); last.addListener(Events.Enable, listener); last.addSelectionListener(new SelectionListener<ButtonEvent>() { public void componentSelected(ButtonEvent ce) { last(); } }); refresh = new Button(); refresh.addSelectionListener(new SelectionListener<ButtonEvent>() { public void componentSelected(ButtonEvent ce) { refresh(); } }); beforePage = new LabelToolItem(); beforePage.setStyleName("my-paging-text"); afterText = new LabelToolItem(); afterText.setStyleName("my-paging-text"); pageText = new TextBox(); if (GXT.isAriaEnabled()) pageText.setTitle("Page"); pageText.addKeyDownHandler(new KeyDownHandler() { public void onKeyDown(KeyDownEvent event) { if (event.getNativeKeyCode() == KeyCodes.KEY_ENTER) { onPageChange(); } } }); pageText.setWidth("30px"); displayText = new LabelToolItem(); displayText.setId(getId() + "-display"); displayText.setStyleName("my-paging-display"); add(first); add(prev); add(new SeparatorToolItem()); add(beforePage); add(new WidgetComponent(pageText)); add(afterText); add(new SeparatorToolItem()); add(next); add(last); add(new SeparatorToolItem()); add(refresh); add(new FillToolItem()); add(displayText); // Add data providers per page Combo add(new SeparatorToolItem()); add(new LabelToolItem("&nbsp;&nbsp;" + HarvesterUI.CONSTANTS.rowsPerPage() + " &nbsp;")); perPageCombo = new SimpleComboBox<String>(); perPageCombo.setWidth(55); perPageCombo.setEditable(false); perPageCombo.setTriggerAction(ComboBox.TriggerAction.ALL); perPageCombo.add("15"); perPageCombo.add("30"); perPageCombo.add("45"); perPageCombo.add("60"); perPageCombo.add("100"); perPageCombo.add("200"); perPageCombo.setId("dataPerPageComboBox"); perPageCombo.addSelectionChangedListener(new SelectionChangedListener<SimpleComboValue<String>>() { @Override public void selectionChanged(SelectionChangedEvent<SimpleComboValue<String>> se) { setPageSize(Integer.valueOf(se.getSelectedItem().getValue())); if (perPageCombo.isVisible()) { refresh(); CookieManager cookieManager = (CookieManager) Registry.get(HarvesterUI.COOKIE_MANAGER); cookieManager.saveRowsPerPageData(perPageCombo.getSimpleValue()); } } }); String perPageData = Cookies.getCookie(CookieManager.ROWS_PER_PAGE); if (perPageData != null && !perPageData.isEmpty()) perPageCombo.setSimpleValue(perPageData); else perPageCombo.setSimpleValue("15"); add(perPageCombo); setMessages(new PagingToolBarMessages()); setImages(new PagingToolBarImages()); } public SimpleComboBox<String> getPerPageCombo() { return perPageCombo; } public int getStart() { return start; } /** * Binds the toolbar to the loader. * * @param loader the loader */ public void bind(PagingLoader<?> loader) { if (this.loader != null) { this.loader.removeLoadListener(loadListener); } this.loader = loader; if (loader != null) { loader.setLimit(pageSize); if (loadListener == null) { loadListener = new LoadListener() { public void loaderBeforeLoad(LoadEvent le) { savedEnableState = isEnabled(); setEnabled(false); refresh.setIcon(IconHelper.createStyle("x-tbar-loading")); } public void loaderLoad(LoadEvent le) { // refresh.setIcon(getImages().getRefresh()); setEnabled(savedEnableState); onLoad(le); } public void loaderLoadException(LoadEvent le) { // refresh.setIcon(getImages().getRefresh()); setEnabled(savedEnableState); } }; } loader.addLoadListener(loadListener); } } /** * Clears the current toolbar text. */ public void clear() { if (rendered) { pageText.setText(""); afterText.setLabel(""); displayText.setLabel(""); } } /** * Moves to the first page. */ public void first() { UtilManager.maskCentralPanel(HarvesterUI.CONSTANTS.loadingMainData()); // doLoadRequest(0, pageSize); config.setOffset(0); previousState = ToolbarState.FIRST; mainGridContainer.loadGridData(config); } /** * Returns the active page. * * @return the active page */ public int getActivePage() { return activePage; } public PagingToolBarImages getImages() { if (images == null) { images = new PagingToolBarImages(); } return images; } /** * Returns the tool bar's messages. * * @return the messages */ public PagingToolBarMessages getMessages() { return msgs; } /** * Returns the current page size. * * @return the page size */ public int getPageSize() { return pageSize; } /** * Returns the total number of pages. * * @return the */ public int getTotalPages() { return pages; } /** * Returns true if the previous load config is reused. * * @return the reuse config state */ public boolean isReuseConfig() { return reuseConfig; } /** * Returns true if tooltip are enabled. * * @return the show tooltip state */ public boolean isShowToolTips() { return showToolTips; } // private boolean didNext = false; /** * Moves to the last page. */ public void last() { int extra = totalLength % pageSize; int lastStart = extra > 0 ? (totalLength - extra) : totalLength - pageSize; // doLoadRequest(lastStart, pageSize); previousState = ToolbarState.LAST; UtilManager.maskCentralPanel(HarvesterUI.CONSTANTS.loadingMainData()); PagingLoadConfig config = new BasePagingLoadConfig(); config.setOffset(lastStart); config.setLimit(config.getOffset() + pageSize); mainGridContainer.loadGridData(config); } /** * Moves to the last page. */ public void next() { UtilManager.maskCentralPanel(HarvesterUI.CONSTANTS.loadingMainData()); // doLoadRequest(start + pageSize, pageSize); previousState = ToolbarState.NEXT; PagingLoadConfig config = new BasePagingLoadConfig(); config.setOffset(start + pageSize); config.setLimit(config.getOffset() + pageSize); mainGridContainer.loadGridData(config); } /** * Moves the the previous page. */ public void previous() { UtilManager.maskCentralPanel(HarvesterUI.CONSTANTS.loadingMainData()); int min = Math.max(0, start - pageSize); // doLoadRequest(min, pageSize); previousState = ToolbarState.PREVIOUS; PagingLoadConfig config = new BasePagingLoadConfig(); config.setOffset(min); config.setLimit(min + pageSize); mainGridContainer.loadGridData(config); } /** * Refreshes the data using the current configuration. */ public void refresh() { MainGrid mainGrid = (MainGrid) Registry.get("mainGrid"); if (!mainGrid.getTopToolbar().getSearchCombo().getRawValue().isEmpty() && mainGrid.getTopToolbar().getSearchCombo().getLastSavedSearch() != null) HarvesterUI.UTIL_MANAGER.getMainGridSearchResults(); else { mainGridContainer.setScrollBarY(); UtilManager.maskCentralPanel(HarvesterUI.CONSTANTS.loadingMainData()); previousState = ToolbarState.REFRESH; PagingLoadConfig config = new BasePagingLoadConfig(); if (pageText.getText().isEmpty() || Integer.valueOf(pageText.getText()) == 1) { config.setOffset(0); config.setLimit(pageSize); } else { config.setOffset(start); config.setLimit(config.getOffset() + pageSize); } mainGridContainer.loadGridData(config); } mainGrid.getBrowseFilterPanel().updateAllFilterValues(); } public void load(PagingLoadConfig config) { UtilManager.maskCentralPanel(HarvesterUI.CONSTANTS.loadingMainData()); doLoadRequest(config.getOffset(), config.getLimit()); mainGridContainer.loadGridData(config); } private ToolbarState previousState = ToolbarState.REFRESH; public void loadPagingInfo() { // ACtive page : doLoadRequest((page-1) * pageSize, pageSize); // Previous : doLoadRequest(min, pageSize); // Next : doLoadRequest(start + pageSize, pageSize); // Last : int extra = totalLength % pageSize; // int lastStart = extra > 0 ? (totalLength - extra) : totalLength - pageSize; // doLoadRequest(lastStart, pageSize); // First : doLoadRequest(0, pageSize); // Refresh: // doLoadRequest(start, pageSize); switch (previousState) { case PREVIOUS: int min = Math.max(0, start - pageSize); doLoadRequest(min, pageSize); break; case NEXT: doLoadRequest(start + pageSize, pageSize); break; case LAST: int extra = totalLength % pageSize; int lastStart = extra > 0 ? (totalLength - extra) : totalLength - pageSize; doLoadRequest(lastStart, pageSize); break; case FIRST: doLoadRequest(0, pageSize); break; case REFRESH: doLoadRequest(start, pageSize); break; } } public void showRefreshIconRunning(boolean running) { if (running) refresh.setIcon(IconHelper.createStyle("x-tbar-loading")); else refresh.setIcon(getImages().getRefresh()); } /** * Sets the active page (1 to page count inclusive). * * @param page the page */ public void setActivePage(int page) { if (page > pages) { last(); return; } if (page != activePage && page > 0 && page <= pages) { UtilManager.maskCentralPanel(HarvesterUI.CONSTANTS.loadingMainData()); // doLoadRequest((page-1) * pageSize, pageSize); previousState = ToolbarState.ACTIVE_PAGE; PagingLoadConfig config = new BasePagingLoadConfig(); config.setOffset((page - 1) * pageSize); config.setLimit(config.getOffset() + pageSize); mainGridContainer.loadGridData(config); } else { pageText.setText(String.valueOf((int) activePage)); } } public void setActivePageAlwaysReload(int page) { if (page > pages) { last(); return; } UtilManager.maskCentralPanel(HarvesterUI.CONSTANTS.loadingMainData()); // doLoadRequest((page-1) * pageSize, pageSize); previousState = ToolbarState.ACTIVE_PAGE; PagingLoadConfig config = new BasePagingLoadConfig(); config.setOffset((page - 1) * pageSize); config.setLimit(config.getOffset() + pageSize); mainGridContainer.loadGridData(config); pageText.setText(String.valueOf((int) activePage)); } public void setPageText() { pageText.setText(String.valueOf((int) activePage)); } public void setImages(PagingToolBarImages images) { this.images = images; refresh.setIcon(getImages().getRefresh()); last.setIcon(last.isEnabled() ? getImages().getLast() : getImages().getLastDisabled()); first.setIcon(first.isEnabled() ? getImages().getFirst() : getImages().getFirstDisabled()); prev.setIcon(prev.isEnabled() ? getImages().getPrev() : getImages().getPrevDisabled()); next.setIcon(next.isEnabled() ? getImages().getNext() : getImages().getNextDisabled()); } /** * Sets the tool bar's messages. * * @param messages the messages */ public void setMessages(PagingToolBarMessages messages) { msgs = messages; if (showToolTips) { first.setToolTip(msgs.getFirstText()); prev.setToolTip(msgs.getPrevText()); next.setToolTip(msgs.getNextText()); last.setToolTip(msgs.getLastText()); refresh.setToolTip(msgs.getRefreshText()); } else { first.removeToolTip(); prev.removeToolTip(); next.removeToolTip(); last.removeToolTip(); refresh.removeToolTip(); } if (GXT.isAriaEnabled()) { first.getAriaSupport().setLabel(msgs.getFirstText()); prev.getAriaSupport().setLabel(msgs.getPrevText()); next.getAriaSupport().setLabel(msgs.getNextText()); last.getAriaSupport().setLabel(msgs.getLastText()); refresh.getAriaSupport().setLabel(msgs.getRefreshText()); } beforePage.setLabel(msgs.getBeforePageText()); } /** * Sets the current page size. This method does not effect the data currently * being displayed. The new page size will not be used until the next load * request. * * @param pageSize the new page size */ public void setPageSize(int pageSize) { this.pageSize = pageSize; } /** * True to reuse the previous load config (defaults to true). * * @param reuseConfig true to reuse the load config */ public void setReuseConfig(boolean reuseConfig) { this.reuseConfig = reuseConfig; } /** * Sets if the button tool tips should be displayed (defaults to true, * pre-render). * * @param showToolTips true to show tool tips */ public void setShowToolTips(boolean showToolTips) { this.showToolTips = showToolTips; } public void doLoadRequest(int offset, int limit) { if (reuseConfig && config != null) { config.setOffset(offset); config.setLimit(pageSize); loader.load(config); } else { loader.setLimit(pageSize); loader.load(offset, limit); } } protected void onLoad(LoadEvent event) { if (!rendered) { renderEvent = event; return; } config = (PagingLoadConfig) event.getConfig(); PagingLoadResult<?> result = event.getData(); start = result.getOffset(); totalLength = result.getTotalLength(); activePage = (int) ((double) (start + pageSize) / pageSize); pageText.setText(String.valueOf((int) activePage)); pages = totalLength < pageSize ? 1 : (int) Math.ceil((double) totalLength / pageSize); if (activePage > pages) { last(); return; } String after = null, display = null; if (msgs.getAfterPageText() != null) { after = Format.substitute(msgs.getAfterPageText(), "" + pages); } else { after = GXT.MESSAGES.pagingToolBar_afterPageText(pages); } afterText.setLabel(after); first.setEnabled(activePage != 1); prev.setEnabled(activePage != 1); next.setEnabled(activePage != pages); last.setEnabled(activePage != pages); int temp = activePage == pages ? totalLength : start + pageSize; if (msgs.getDisplayMsg() != null) { String[] params = new String[]{"" + (start + 1), "" + temp, "" + totalLength}; display = Format.substitute(msgs.getDisplayMsg(), (Object[]) params); } else { display = GXT.MESSAGES.pagingToolBar_displayMsg(start + 1, (int) temp, (int) totalLength); } String msg = display; if (totalLength == 0) { msg = msgs.getEmptyMsg(); } displayText.setLabel(msg); } protected void onPageChange() { String value = pageText.getText(); if (value.equals("") || !Util.isInteger(value)) { pageText.setText(String.valueOf((int) activePage)); return; } int p = Integer.parseInt(value); setActivePage(p); } @Override protected void onRender(Element target, int index) { super.onRender(target, index); if (renderEvent != null) { onLoad(renderEvent); renderEvent = null; } if (GXT.isAriaEnabled()) { getAriaSupport().setDescribedBy(displayText.getId()); } } }
gpl-3.0
jonnius/RWETippspiel
src/Tippspiel.java
53404
/* * ©Copyright 2014 Jonatan Zeidler <jonatan_zeidler@gmx.de> * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. * * Dieses Programm ist Freie Software: Sie können es unter den Bedingungen * der GNU General Public License, wie von der Free Software Foundation, * Version 3 der Lizenz oder (nach Ihrer Wahl) jeder neueren * veröffentlichten Version, weiterverbreiten und/oder modifizieren. * * Dieses Programm wird in der Hoffnung, dass es nützlich sein wird, aber * OHNE JEDE GEWÄHRLEISTUNG, bereitgestellt; sogar ohne die implizite * Gewährleistung der MARKTFÄHIGKEIT oder EIGNUNG FÜR EINEN BESTIMMTEN ZWECK. * Siehe die GNU General Public License für weitere Details. * * Sie sollten eine Kopie der GNU General Public License zusammen mit diesem * Programm erhalten haben. Wenn nicht, siehe <http://www.gnu.org/licenses/>. * * Verwendete Bibliothek: JFreeChart (C) Copyright 2000-2013, by Object Refinery Limited and Contributors. * Quelltextdateien: * ChartColor: (C) Copyright 2003-2011, by Cameron Riley and Contributors. * ChartFactory: (C) Copyright 2001-2013, by Object Refinery Limited and Contributors. * ChartPanel: (C) Copyright 2000-2013, by Object Refinery Limited and Contributors. * JFreeChart: (C) Copyright 2000-2013, by Object Refinery Limited and Contributors. * NumberAxis: (C) Copyright 2000-2013, by Object Refinery Limited and Contributors. * CategoryPlot: (C) Copyright 2000-2013, by Object Refinery Limited and Contributors. * DefaultDrawingSupplier: (C) Copyright 2003-2008, by Object Refinery Limited. * DefaultCategoryDataset: (C) Copyright 2003-2008, by Object Refinery Limited and Contributors. * * Änderungen (Changes): Keine (None) */ import java.awt.BorderLayout; import java.awt.Color; import java.awt.Desktop; import java.awt.Font; import java.awt.GridBagConstraints; import java.awt.GridBagLayout; import java.awt.GridLayout; import java.awt.Image; import java.awt.Insets; import java.awt.Paint; import java.awt.Toolkit; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import java.awt.event.KeyAdapter; import java.awt.event.KeyEvent; import java.io.File; import java.io.FileInputStream; import java.io.FileNotFoundException; import java.io.FileOutputStream; import java.io.FileReader; import java.io.FileWriter; import java.io.IOException; import java.io.InputStream; import java.io.ObjectInputStream; import java.io.ObjectOutputStream; import java.io.Serializable; import java.io.StringWriter; import java.net.URI; import java.net.URL; import java.util.GregorianCalendar; import java.util.Iterator; import java.util.Properties; import java.util.TreeMap; import java.util.jar.JarEntry; import java.util.jar.JarInputStream; import java.util.jar.JarOutputStream; import javax.swing.ImageIcon; import javax.swing.JButton; import javax.swing.JCheckBox; import javax.swing.JComboBox; import javax.swing.JDialog; import javax.swing.JFileChooser; import javax.swing.JFrame; import javax.swing.JLabel; import javax.swing.JOptionPane; import javax.swing.JPanel; import javax.swing.JScrollPane; import javax.swing.JSlider; import javax.swing.JSpinner; import javax.swing.JSplitPane; import javax.swing.JTextField; import javax.swing.SpinnerNumberModel; import javax.swing.UIManager; import javax.swing.event.ChangeEvent; import javax.swing.event.ChangeListener; import javax.swing.filechooser.FileFilter; import org.jfree.chart.ChartColor; import org.jfree.chart.ChartFactory; import org.jfree.chart.ChartPanel; import org.jfree.chart.JFreeChart; import org.jfree.chart.axis.NumberAxis; import org.jfree.chart.plot.CategoryPlot; import org.jfree.chart.plot.DefaultDrawingSupplier; import org.jfree.data.category.DefaultCategoryDataset; public class Tippspiel extends JFrame { private static final long serialVersionUID = 1L; static boolean hintergrund = false; static File d_konfig, d_wolke, d_autostart; static String kicker, jahre[], saison, name = null; static Spiel spiele[], tipps[][]; static String namen[]; static int erinnern, spt_aktuell, spt_anzeige; static Properties konfig; static Spieler rangliste[]; static String pfad; static boolean jar, windows = false, autostart = false; static Color c_mark = new Color(93,152,233), c_mark_hg = new Color(180,202,233), c_pkt[] = {new Color(200,200,200), new Color(255,255,150), new Color(150,255,255), new Color(100,255,100)}; static Font f_rangliste = new Font("SansSerif", Font.BOLD, 18), f_ergebnisse = new Font("SansSerif", Font.BOLD, 12); static String fehler = ""; static TreeMap<GregorianCalendar,String> chat_eigen = new TreeMap<GregorianCalendar,String>(), chat_alle = new TreeMap<GregorianCalendar,String>(); //Administrator darf auch im Nachhinein seine Tipps ändern static boolean admin = false; //Admin startet als dieser Spieler, falls null, wird Spieler aus der Konfig benutzt static String admin_spieler = null; /** * Programmstart * @param args: -admin (darf auch im Nachhinein Tipps ändern)<br> * -leise (prüft, ob getippt werden muss und öffnet nur in diesem Fall das Fenster) */ public static void main(String[] args) { hintergrund = args.length >= 1 && args[0].equals("leise") || autostart; admin = admin || args.length >= 1 && args[0].equals("admin"); if(admin) System.out.println("Als Administrator gestartet"); if(hintergrund) System.out.println("Als Hintergrunddienst gestartet"); init(); aktualisiereDateien(); for(int i = 0; i<spiele.length; i++) { if(spiele[i].istAustehend() && spiele[i].tageVerbleibend() < erinnern && !tipps[0][i].mitErgebnis()) { if(hintergrund) hintergrund = JOptionPane.NO_OPTION == JOptionPane.showConfirmDialog(null, "Die Begegnung gegen "+spiele[i].gegner+" wurde noch nicht getippt. Jetzt öffnen?", "Erinnerung ans Tippen", JOptionPane.YES_NO_OPTION, JOptionPane.INFORMATION_MESSAGE); else JOptionPane.showMessageDialog(null, "Die Begegnung gegen "+spiele[i].gegner+" wurde noch nicht getippt!", "Erinnerung ans Tippen", JOptionPane.INFORMATION_MESSAGE); break; } } if(!hintergrund) new Tippspiel(); } /** * Initialisierung inkl. Auslesen bzw. Anlegen der Konfigurationsdatei */ static void init() { try { UIManager.setLookAndFeel( UIManager.getSystemLookAndFeelClassName()); } catch (Exception e) { e.printStackTrace(); } windows = System.getProperty("os.name").contains("Windows"); System.out.println(System.getProperty("os.name")); pfad = Tippspiel.class.getProtectionDomain().getCodeSource().getLocation().toString(); pfad = pfad.replace("%20"," "); pfad = pfad.substring(5); pfad = new File(pfad).getAbsolutePath(); jar = pfad.endsWith(".jar"); if(windows) { d_autostart = new File(System.getProperty("user.home")+"/AppData/Roaming/Microsoft/Windows/Start Menu/Programs/Startup/Tippspiel.jar"); autostart = pfad.equals(d_autostart.getAbsolutePath()); } else { d_autostart = new File("/home/"+System.getProperty("user.name")+"/.config/autostart/Tippspiel.desktop"); } d_konfig = new File(System.getProperty("user.home")+"/.Tippspiel.conf"); konfig = new Properties(); //Konfiguration einlesen try { FileReader fr = new FileReader(d_konfig); konfig.load(fr); fr.close(); } catch (FileNotFoundException e) { //Normal - Noch keine Datei vorhanden } catch (IOException e) { e.printStackTrace(); System.out.println("Fehler beim Lesen der Konfigurationsdatei "+d_konfig.getAbsolutePath()); } saison = konfig.getProperty("jahr", "2014-15"); kicker = konfig.getProperty("kicker", "http://www.kicker.de/news/fussball/3liga/vereine/3-liga/{jahr}/rot-weiss-erfurt-61/vereinstermine.html"); erinnern = Integer.parseInt(konfig.getProperty("erinnern", "3")); setzeAutostart(erinnern > 0, true); if(konfig.getProperty("wolke") == null) { d_wolke = erfragWolke(); if(d_wolke == null) System.exit(0); } else d_wolke = new File(konfig.getProperty("wolke")); System.out.println("Admin: "+admin); if(admin && admin_spieler != null) name = admin_spieler; else if(konfig.getProperty("name") == null) { name = JOptionPane.showInputDialog("Wie heißt du?", System.getProperty("user.name")); if(name == null) System.exit(0); } else name = konfig.getProperty("name"); // Comparator<GregorianCalendar> vergleich = new Comparator<GregorianCalendar>() { // @Override // public int compare(GregorianCalendar o1, GregorianCalendar o2) { // return o1.compareTo(o2); } // }; speicherKonfig(); } static void speicherKonfig() { //Konfiguration speichern try { konfig.setProperty("erinnern", Integer.toString(erinnern)); konfig.setProperty("wolke", d_wolke.getAbsolutePath()); konfig.setProperty("jahr", saison); konfig.setProperty("kicker", kicker); if(!admin || admin_spieler == null) konfig.setProperty("name", name); FileWriter fw = new FileWriter(d_konfig); konfig.store(fw, "Tippspielkonfiguration"); fw.close(); } catch (Exception e) { e.printStackTrace(); JOptionPane.showMessageDialog(null, "Fehler beim Schreiben der Konfigurationsdatei "+d_konfig.getAbsolutePath()); System.exit(1); } } static boolean setzeAutostart(boolean an, boolean still) { if(windows && new File(pfad).getAbsolutePath().equals(d_autostart.getAbsolutePath())) { if(!still) JOptionPane.showMessageDialog(null, "Das Programm wurde vom Autostart geladen.\n" + "Um diese Funktion umzuschalten, muss das Programm manuell gestartet worden sein.\n" + "(Diese Unanehmlichkeit wird Ihnen präsentiert von Windows)", "Umständlichkeit aufgrund von Windows", JOptionPane.ERROR_MESSAGE); return false; } if(an) { if(d_autostart.exists()) d_autostart.delete(); if(windows) { try { JarInputStream lesen = new JarInputStream(new FileInputStream(pfad)); JarOutputStream schreiben = new JarOutputStream(new FileOutputStream(d_autostart), lesen.getManifest()); JarEntry alt; while ((alt = lesen.getNextJarEntry()) != null) { JarEntry neu = new JarEntry(alt.getName()); schreiben.putNextEntry(neu); byte[] puffer = new byte[1024]; int laenge; while ((laenge = lesen.read(puffer)) > 0) { schreiben.write(puffer, 0, laenge); } } schreiben.close(); lesen.close(); return true; } catch (IOException e) { e.printStackTrace(); JOptionPane.showMessageDialog(null, "Konnte Programm nicht zum Autostart hinzufügen. Sag Onkel Windows ganz lieb Danke!.\n"+ d_autostart.getAbsolutePath(), "Fehler", JOptionPane.ERROR_MESSAGE); } } else { if(d_autostart.exists()) d_autostart.delete(); try { String str = "[Desktop Entry]\n" + "Name=Tippspiel\n" + "Exec=java -jar \""+pfad+"\" leise\n" + "Terminal=false\n" + "Type=Application\n" + "StartupNotify=false\n" + "X-GNOME-Autostart-enabled=true\n" + "Name[de_DE]=Tippspiel"; FileWriter schreiben = new FileWriter(d_autostart); schreiben.write(str); schreiben.close(); return true; } catch (Exception e) { e.printStackTrace(); JOptionPane.showMessageDialog(null, "Konnte Programm nicht zum Autostart hinzufügen. Ist dies vielleicht kein Linux?\n"+ d_autostart.getAbsolutePath(), "Fehler", JOptionPane.ERROR_MESSAGE); } } } else { d_autostart.delete(); return true; } return false; } static File erfragWolke() { JFileChooser wahl = new JFileChooser("Tippspielverzeichnis wählen (in der Wolke)"); FileFilter filter = new FileFilter() { @Override public String getDescription() { return "Wolkenordner"; } @Override public boolean accept(File f) { return f.isDirectory(); } }; wahl.setFileFilter(filter); wahl.setAcceptAllFileFilterUsed(false); wahl.setFileSelectionMode(JFileChooser.DIRECTORIES_ONLY); wahl.setApproveButtonText("Tippspielverzeichnis festlegen"); wahl.showOpenDialog(null); return wahl.getSelectedFile(); } /** * Ergebnisse aus dem Internet herunterladen und Dateien aktualisieren */ static void aktualisiereDateien() { Spiel spiele_kicker[] = new Spiel[38]; boolean heruntergeladen = false; spiele = new Spiel[38]; for(int i = 0; i<spiele.length; i++) spiele[i] = new Spiel(); String html; int ja = new GregorianCalendar().get(GregorianCalendar.YEAR); if(new GregorianCalendar().get(GregorianCalendar.MONTH) < 6) ja--; jahre = new String[2]; jahre[0] = Integer.toString(ja)+"-"+Integer.toString((ja+1)%1000); jahre[1] = Integer.toString(ja-1)+"-"+Integer.toString((ja)%1000); html = readHTML(kicker.replace("{jahr}", saison)); if(html.equals("")) { fehler = "<html>Konnte Daten nicht mit kicker.de abgleichen.<br>Möglicherweise besteht keine Internetverbindung.</html>"; System.out.println("Adresse: "+kicker.replace("{jahr}", saison)+" nicht erreichbar."); } else { if(html.contains("Es sind zur Zeit keine Daten vorhanden.")) { if(!hintergrund) JOptionPane.showMessageDialog(null, "Für die gewählte Saison "+saison+" sind keine Daten auf kicker.de vorhanden.\n" + "In der Konfigdatei kann eine andere Saison eingetragen werden:\n"+d_konfig.getAbsolutePath()); System.exit(1); } int i1 = 0, i2 = 0; for(int i = 1; i <= spiele_kicker.length; i++) { i1 = html.indexOf("<td>Spt."+i+"</td>"); i1 = html.substring(0, i1).lastIndexOf("<td class=\"first\">"); i2 = html.substring(i1).indexOf("<td class=\"aligncenter last\">")+i1; spiele_kicker[i-1] = new Spiel(html.substring(i1, i2)); } heruntergeladen = true; } boolean aenderung = false; //Ergebnisdatei laden try { ObjectInputStream lesen = new ObjectInputStream(new FileInputStream(new File(d_wolke,"Ergebnisse"))); spiele = new Spiel[38]; for(int i = 0; i<spiele.length; i++) { spiele[i] = (Spiel) lesen.readObject(); aenderung |= heruntergeladen && !spiele[i].equals(spiele_kicker[i]); } lesen.close(); } catch (FileNotFoundException e1) { aenderung = true; } catch (Exception e1) { e1.printStackTrace(); JOptionPane.showMessageDialog(null, "Fehler beim Lesen der Ergebnisdatei "+new File(d_wolke,"Ergebnisse").getAbsolutePath()); aenderung = true; } if(heruntergeladen) spiele = spiele_kicker; //Ergebnisdatei beschreiben if(aenderung) { try { ObjectOutputStream schreiben = new ObjectOutputStream(new FileOutputStream(new File(d_wolke,"Ergebnisse"))); for(Spiel sp:spiele) schreiben.writeObject(sp); schreiben.close(); } catch (Exception e) { JOptionPane.showMessageDialog(null, "Fehler beim Schreiben der Ergebnisdatei "+new File(d_wolke,"Ergebnisse").getAbsolutePath()); } } for(int i = 0; i < 38; i++) { spt_aktuell = i+1; if(!spiele[i].mitErgebnis()) break; } //Andere Tipps lesen File dat[] = d_wolke.listFiles(); int z = 0; for(int i = 0; i < dat.length; i++) { if(dat[i].isFile() && dat[i].getName().endsWith(".tipps") && !dat[i].getName().equals(name+".tipps")) z++; } tipps = new Spiel[z+1][38]; namen = new String[z+1]; rangliste = new Spieler[0]; namen[0] = name; z = 1; for(int i = 0; i < dat.length; i++) { if(dat[i].isFile() && dat[i].getName().endsWith(".tipps") && !dat[i].getName().equals(name+".tipps")) { namen[z] = dat[i].getName().substring(0, dat[i].getName().indexOf(".tipps")); tipps[z] = ladeTipps(dat[i]); new Spieler(tipps[z], spiele, namen[z]); z++; } } //Eigene Tipps lesen tipps[0] = ladeTipps(new File(d_wolke,name+".tipps")); if(!new File(d_wolke,name+".tipps").exists()) schreibeTipps(); new Spieler(tipps[0], spiele, name); } static Spiel[] ladeTipps(File f) { Spiel t[] = new Spiel[38]; for(int i = 0; i<t.length; i++) { t[i] = spiele[i].gibLeerenTipp(); } try { ObjectInputStream lesen = new ObjectInputStream(new FileInputStream(f)); for(int i = 0; i<t.length; i++) { t[i] = (Spiel) lesen.readObject(); } lesen.close(); } catch (FileNotFoundException e1) { //normal } catch (Exception e1) { e1.printStackTrace(); JOptionPane.showMessageDialog(null, "Fehler beim Lesen der Tippdatei "+f.getAbsolutePath()); } return t; } /** * Abgegebene Tipps speichern */ static void schreibeTipps() { try { ObjectOutputStream schreiben = new ObjectOutputStream(new FileOutputStream(new File(d_wolke,name+".tipps"))); for(Spiel sp:tipps[0]) schreiben.writeObject(sp); schreiben.close(); } catch (Exception e) { JOptionPane.showMessageDialog(null, "Fehler beim Schreiben der Tippdatei "+new File(d_wolke,name+".tipps").getAbsolutePath()); } } static void ladeChat() { GregorianCalendar kal; String kom; chat_eigen.clear(); chat_alle.clear(); for(String n:namen) { File d_chat = new File(d_wolke,n+".chat"); try { ObjectInputStream lesen = new ObjectInputStream(new FileInputStream(d_chat)); int groesse = lesen.readInt(); for(int i = 0; i < groesse; i++) { kal = (GregorianCalendar)lesen.readObject(); kom = (String)lesen.readObject(); chat_alle.put(kal, n+": "+kom); if(n.equals(name)) { chat_eigen.put(kal, kom); } } lesen.close(); } catch (FileNotFoundException e) { //Normal - Noch kein Kommentar abgegeben } catch (Exception e) { e.printStackTrace(); JOptionPane.showMessageDialog(null, "Fehler beim Lesen von "+name+"s Kommentardatei "+d_chat.getAbsolutePath()); } } } /** * Abgegebene Tipps speichern */ static void schreibeChat() { File d_chat = new File(d_wolke,name+".chat"); try { ObjectOutputStream schreiben = new ObjectOutputStream(new FileOutputStream(d_chat)); schreiben.writeInt(chat_eigen.size()); Iterator<GregorianCalendar> zeiten = chat_eigen.keySet().iterator(); while(zeiten.hasNext()) { GregorianCalendar kal = zeiten.next(); schreiben.writeObject(kal); schreiben.writeObject(chat_eigen.get(kal)); } schreiben.close(); } catch (Exception e) { e.printStackTrace(); JOptionPane.showMessageDialog(null, "Fehler beim Schreiben von "+name+"s Kommentardatei "+d_chat.getAbsolutePath()); } } /** * Rangliste sortieren */ static void sortiereRangliste() { for(int i = 0; i < rangliste.length-1; i++) { for(int j = 0; j < rangliste.length-1-i; j++) { if(rangliste[j+1].istBesserAls(rangliste[j], spt_anzeige)) { Spieler sp = rangliste[j]; rangliste[j] = rangliste[j+1]; rangliste[j+1] = sp; } } } } /** * Eine Webseite herunterladen * @param urltext * @return HTML-Quelltext */ public static String readHTML(String urltext) { // System.out.println("*** |Reading HTML '"+urltext+"' ...."); InputStream in = null; StringWriter schreiber = new StringWriter(); String output=""; int l = 0; try { URL url = new URL(urltext); in = url.openStream(); byte puffer[] = new byte[8192]; while ((l = in.read(puffer)) >= 0) { for(int i = 0; i < l; i++) { schreiber.write(puffer[i] & 0xff); } } output = schreiber.toString(); schreiber.close(); System.out.println("HTML fertig gelesen!");//+output); } catch (Exception e) { e.printStackTrace(); } finally { if (in != null) { try { in.close(); } catch (IOException e) { e.printStackTrace(); } } } return output; } private JPanel historie, verlauf, einstellungen; private JPanel einst_wolkenpfad, einst_intervall; private JPanel verl_spieltag, verl_tabelle, verl_graph, verl_komment, verl_unterh; private JSplitPane daten; private JSlider sl_intervall, sl_spieltag; private JLabel sl_info, sl_spt; private JCheckBox cb_erinnern; private JTextField tf_komm; private JComboBox<String> co_saison; private Aktualisierer aktualisierer; /** * Konstruktor des Hauptfensters */ public Tippspiel() { super("Das Zeidertippspiel - "+name); Image symbol; if(jar) symbol = Toolkit.getDefaultToolkit().getImage(Tippspiel.class.getResource("RWE.png")); else symbol = Toolkit.getDefaultToolkit().getImage("RWE.png"); symbol = symbol.getScaledInstance(20, 32, Image.SCALE_AREA_AVERAGING); setIconImage(symbol); setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); setSize(Toolkit.getDefaultToolkit().getScreenSize()); setExtendedState(JFrame.MAXIMIZED_BOTH); getContentPane().setLayout(new BorderLayout()); getContentPane().add(daten = new JSplitPane(JSplitPane.HORIZONTAL_SPLIT, true), BorderLayout.CENTER); getContentPane().add(einstellungen = new JPanel(), BorderLayout.SOUTH); if(jar) { getContentPane().add(new JLabel(new ImageIcon(Toolkit.getDefaultToolkit().getImage(Tippspiel.class.getResource("RWE.png")))), BorderLayout.WEST); getContentPane().add(new JLabel(new ImageIcon(Toolkit.getDefaultToolkit().getImage(Tippspiel.class.getResource("RWE2.png")))), BorderLayout.EAST); } else { getContentPane().add(new JLabel(new ImageIcon(Toolkit.getDefaultToolkit().getImage("RWE.png"))), BorderLayout.WEST); getContentPane().add(new JLabel(new ImageIcon(Toolkit.getDefaultToolkit().getImage("RWE2.png"))), BorderLayout.EAST); } initErgebnisse(); initEinstellungen(); setVisible(true); aktualisierer = new Aktualisierer(this); aktualisierer.start(); } private void initErgebnisse() { JScrollPane sc_daten, sc_verlauf; daten.setLeftComponent(sc_daten = new JScrollPane(historie = new JPanel())); sc_daten.setViewportBorder(null); daten.setRightComponent(sc_verlauf = new JScrollPane(verlauf = new JPanel())); sc_verlauf.setViewportBorder(null); spt_anzeige = spt_aktuell; verlauf.setLayout(new BorderLayout()); verlauf.add(verl_spieltag = new JPanel(), BorderLayout.NORTH); verlauf.add(verl_tabelle = new JPanel(), BorderLayout.CENTER); JPanel verl_unten; verlauf.add(verl_unten = new JPanel(), BorderLayout.SOUTH); verl_unten.setLayout(new BorderLayout()); verl_unten.add(verl_graph = new JPanel(), BorderLayout.NORTH); verl_unten.add(verl_komment = new JPanel(), BorderLayout.CENTER); verl_spieltag.setLayout(new BorderLayout()); verl_spieltag.add(sl_spt = new JLabel(" Spieltag "+spt_anzeige), BorderLayout.WEST); sl_spt.setFont(f_rangliste); verl_spieltag.add(sl_spieltag = new JSlider(1, 38), BorderLayout.CENTER); sl_spieltag.setMinorTickSpacing(1); // sl_spieltag.setMajorTickSpacing(37); // sl_spieltag.setPaintLabels(true); sl_spieltag.setPaintTicks(true); sl_spieltag.setValue(spt_anzeige-1); sl_spieltag.setForeground(c_mark); sl_spt.setForeground(c_mark); sl_spieltag.addChangeListener(new ChangeListener() { @Override public void stateChanged(ChangeEvent e) { spt_anzeige = sl_spieltag.getValue(); sl_spt.setText(" Spieltag "+spt_anzeige); if(spt_anzeige == spt_aktuell-1) { sl_spieltag.setForeground(c_mark); sl_spt.setForeground(c_mark); } else { sl_spieltag.setForeground(Color.black); sl_spt.setForeground(Color.black); } aktualisiereTabelle(); } }); aktualisiereAnzeige(); } // Alle Anzeigebereiche aktualisieren public void aktualisiereAnzeige() { aktualisiereGraph(); aktualisiereErgebnisse(); aktualisiereTabelle(); aktualisiereKommentare(); historie.revalidate(); } private void aktualisiereKommentare() { ladeChat(); if(tf_komm == null) { //Erste Ausführung verl_komment.setLayout(new BorderLayout()); // JLabel text; // verl_komment.add(text = new JLabel("Kommentare"), BorderLayout.NORTH); // text.setFont(f_ergebnisse); tf_komm = new JTextField(); tf_komm.setFont(f_ergebnisse); tf_komm.addKeyListener(new KeyAdapter() { @Override public void keyPressed(KeyEvent e) { if(e.getKeyCode() == KeyEvent.VK_ENTER) { String k = tf_komm.getText().trim(); if(!k.equals("")) { tf_komm.setText(""); chat_eigen.put(new GregorianCalendar(), k); schreibeChat(); aktualisiereKommentare(); revalidate(); tf_komm.requestFocus(); } } } }); verl_komment.add(tf_komm, BorderLayout.NORTH); } JLabel text; // verl_komment.add(text = new JLabel("Kommentare"), BorderLayout.NORTH); // JPanel unterhaltung = new JPanel(); unterhaltung.setLayout(new GridLayout(chat_alle.size(),1)); Iterator<GregorianCalendar> zeiten = chat_alle.descendingKeySet().iterator(); while(zeiten.hasNext()) { GregorianCalendar kal = zeiten.next(); String kommentar = chat_alle.get(kal); //Zeilenumbrüche bei langen Kommentaren int i = 0, leerzeichen = 0; while(kommentar.length()-i > 80) { leerzeichen = kommentar.substring(i,i+80).lastIndexOf(' '); if(leerzeichen > 0) kommentar = kommentar.substring(0,i+leerzeichen)+"<br>"+kommentar.substring(i=i+leerzeichen+1); else kommentar = kommentar.substring(0,i+80)+"<br>"+kommentar.substring(i=i+80); i+=3; } unterhaltung.add(text = new JLabel("<html>"+kommentar+"</html>")); text.setFont(f_ergebnisse); } if(verl_unterh != null) verl_komment.remove(verl_unterh); verl_komment.add(verl_unterh = unterhaltung); } private void aktualisiereErgebnisse() { JPanel hist = new JPanel(); JLabel label; GridBagConstraints gbc = new GridBagConstraints(); GridBagLayout gbl2 = new GridBagLayout(); gbc = new GridBagConstraints(); hist.setLayout(gbl2); gbc.gridx = 0; gbc.gridy = 0; gbc.weightx = 0; gbc.weighty = 0; gbc.insets = new Insets(2, 2, 2, 5); gbc.fill = GridBagConstraints.BOTH; gbc.gridx++; gbl2.setConstraints(label = new JLabel("Datum", JLabel.CENTER), gbc); label.setFont(f_ergebnisse); hist.add(label); gbc.gridx++; gbl2.setConstraints(label = new JLabel("Gegner", JLabel.CENTER), gbc); label.setFont(f_ergebnisse); hist.add(label); gbc.gridx++; gbl2.setConstraints(label = new JLabel("Ort", JLabel.CENTER), gbc); label.setFont(f_ergebnisse); hist.add(label); gbc.gridx++; gbl2.setConstraints(label = new JLabel("Ergebnis", JLabel.CENTER), gbc); label.setFont(f_ergebnisse); hist.add(label); for(int i=0; i<tipps.length; i++) { gbc.gridx++; gbl2.setConstraints(label = new JLabel(namen[i], JLabel.CENTER), gbc); label.setFont(f_ergebnisse); hist.add(label); } gbc.gridx++; gbl2.setConstraints(label = new JLabel(" ", JLabel.CENTER), gbc); label.setFont(f_ergebnisse); hist.add(label); for(int i = 0; i < spiele.length; i++) { gbc.gridy++; JPanel bereich; gbc.gridx = 0; bereich = new JPanel(); bereich.add(label = new JLabel(Integer.toString(i+1))); label.setFont(f_ergebnisse); gbl2.setConstraints(bereich, gbc); hist.add(bereich); if(i+1 == spt_aktuell) bereich.setBackground(c_mark_hg); gbc.gridx++; bereich = new JPanel(); bereich.add(label = new JLabel(spiele[i].gibDatumText())); label.setFont(f_ergebnisse); gbl2.setConstraints(bereich, gbc); hist.add(bereich); if(i+1 == spt_aktuell) bereich.setBackground(c_mark_hg); gbc.gridx++; bereich = new JPanel(); bereich.add(label = new JLabel(spiele[i].gegner)); label.setFont(f_ergebnisse); gbl2.setConstraints(bereich, gbc); hist.add(bereich); if(i+1 == spt_aktuell) bereich.setBackground(c_mark_hg); gbc.gridx++; bereich = new JPanel(); bereich.add(label = new JLabel(spiele[i].gibHeimText(), JLabel.CENTER)); label.setFont(f_ergebnisse); gbl2.setConstraints(bereich, gbc); hist.add(bereich); if(i+1 == spt_aktuell) bereich.setBackground(c_mark_hg); gbc.gridx++; bereich = new JPanel(); bereich.add(label = new JLabel(spiele[i].gibErgebnisText(), JLabel.CENTER)); gbl2.setConstraints(bereich, gbc); label.setFont(f_ergebnisse); hist.add(bereich); if(i+1 == spt_aktuell) bereich.setBackground(c_mark_hg); ActionListener tippen = new ActionListener() { @Override public void actionPerformed(ActionEvent e) { tippe(Integer.parseInt(e.getActionCommand())); } }; boolean zeigen = tipps[0][i].mitErgebnis() || !tipps[0][i].istAustehend(); for(int k = 0; k<tipps.length; k++) { gbc.gridx++; if(k == 0 && (tipps[k][i].istAustehend() && !tipps[k][i].mitErgebnis() || admin)) { JButton tipp = new JButton(tipps[k][i].gibErgebnisText()); tipp.setFont(f_ergebnisse); tipp.setActionCommand(Integer.toString(i)); tipp.addActionListener(tippen); if(i+1 == spt_aktuell && !tipps[k][i].mitErgebnis()) { tipp.setForeground(Color.red); tipp.setText("Tippen!"); tipp.setFont(new Font(tipp.getFont().getName(), Font.BOLD, tipp.getFont().getSize())); } gbl2.setConstraints(tipp, gbc); hist.add(tipp); } else { bereich = new JPanel(); if(zeigen || k == 0 || !tipps[k][i].mitErgebnis()) label = new JLabel(tipps[k][i].gibErgebnisText(), JLabel.CENTER); else label = new JLabel("?-?", JLabel.CENTER); label.setFont(f_ergebnisse); bereich.add(label); gbl2.setConstraints(bereich,gbc); hist.add(bereich); if(!tipps[k][i].istAustehend() && tipps[k][i].mitErgebnis()) { bereich.setBackground(c_pkt[spiele[i].gibPunkte(tipps[k][i])]); } } } } sl_spieltag.setValue(spt_anzeige); historie.removeAll(); historie.add(hist); } private void aktualisiereGraph() { verl_graph.removeAll(); //Daten zusammentragen DefaultCategoryDataset verlaeufe = new DefaultCategoryDataset(); for(int i = 0; i<rangliste.length; i++) { Spieler spieler = rangliste[i]; if(spieler.gibErstenTippSpieltag() > 0) for(int k = spieler.gibErstenTippSpieltag(); k < spt_aktuell; k++) { verlaeufe.addValue(spieler.gibPlatzierung(k), spieler.gibName(), Integer.toString(k)); } } //Diagramm erstellen JFreeChart chart = ChartFactory.createLineChart("Tabellenfahrt", "Spieltag", "Platzierung", verlaeufe); chart.setBackgroundPaint(new Color(0,0,0,0)); //Aussehen bearbeiten CategoryPlot plot = chart.getCategoryPlot(); plot.setDrawingSupplier( new DefaultDrawingSupplier( new Paint[] {ChartColor.BLUE, ChartColor.RED, ChartColor.DARK_GREEN, ChartColor.MAGENTA, ChartColor.CYAN, ChartColor.GRAY, ChartColor.YELLOW, ChartColor.PINK, ChartColor.ORANGE}, DefaultDrawingSupplier.DEFAULT_OUTLINE_PAINT_SEQUENCE, DefaultDrawingSupplier.DEFAULT_STROKE_SEQUENCE, DefaultDrawingSupplier.DEFAULT_OUTLINE_STROKE_SEQUENCE, DefaultDrawingSupplier.DEFAULT_SHAPE_SEQUENCE)); plot.setBackgroundAlpha(0); plot.setOutlineVisible(false); plot.setDomainGridlinesVisible(true); plot.setRangeGridlinesVisible(true); plot.setDomainGridlinePaint(Color.GRAY); plot.setRangeGridlinePaint(Color.GRAY); //Achsenbeschriftung bearbeiten NumberAxis rangeAxis = (NumberAxis) plot.getRangeAxis(); rangeAxis.setStandardTickUnits(NumberAxis.createIntegerTickUnits()); rangeAxis.setAutoRangeIncludesZero(false); rangeAxis.setInverted(true); //Bereich erstellen und einbetten ChartPanel bereich = new ChartPanel(chart); bereich.setDefaultDirectoryForSaveAs(d_wolke); verl_graph.add(bereich); } private void aktualisiereTabelle() { sortiereRangliste(); JPanel tabelle = new JPanel(); GridBagLayout gbl = new GridBagLayout(); GridBagConstraints gbc = new GridBagConstraints(); tabelle.setLayout(gbl); gbc.gridx = 0; gbc.gridy = 0; gbc.weightx = 0; gbc.weighty = 0; gbc.insets = new Insets(2, 5, 2, 5); gbc.fill = GridBagConstraints.BOTH; JLabel label; JPanel bereich = new JPanel(); gbl.setConstraints(label = new JLabel("Platz"), gbc); label.setFont(f_rangliste); tabelle.add(label); gbc.gridx++; gbl.setConstraints(label = new JLabel("Tipper"), gbc); label.setFont(f_rangliste); tabelle.add(label); gbc.gridx++; gbl.setConstraints(label = new JLabel("Spiele", JLabel.CENTER), gbc); label.setFont(f_rangliste); tabelle.add(label); gbc.gridx++; bereich = new JPanel(); label = new JLabel("Exakt", JLabel.CENTER); label.setFont(f_rangliste); bereich.setBackground(c_pkt[3]); bereich.add(label); gbl.setConstraints(bereich, gbc); tabelle.add(bereich); gbc.gridx++; bereich = new JPanel(); label = new JLabel("Differenz", JLabel.CENTER); label.setFont(f_rangliste); bereich.setBackground(c_pkt[2]); bereich.add(label); gbl.setConstraints(bereich, gbc); tabelle.add(bereich); gbc.gridx++; bereich = new JPanel(); label = new JLabel("Tendenz", JLabel.CENTER); label.setFont(f_rangliste); bereich.setBackground(c_pkt[1]); bereich.add(label); gbl.setConstraints(bereich, gbc); tabelle.add(bereich); gbc.gridx++; gbl.setConstraints(label = new JLabel("Punkte", JLabel.CENTER), gbc); label.setFont(f_rangliste); tabelle.add(label); for(int i = 0; i<rangliste.length; i++) { gbc.gridy++; gbc.gridx = 0; int platz = rangliste[i].gibPlatzierung(spt_anzeige); if(platz == i+1) { gbl.setConstraints(label = new JLabel(Integer.toString(platz), JLabel.CENTER), gbc); label.setFont(f_rangliste); tabelle.add(label); } gbc.gridx++; gbl.setConstraints(label = new JLabel(rangliste[i].gibName()), gbc); label.setFont(f_rangliste); tabelle.add(label); gbc.gridx++; gbl.setConstraints(label = new JLabel(Integer.toString(rangliste[i].gibtAnzahlTipps(Math.min(spt_anzeige,spt_aktuell-1))), JLabel.CENTER), gbc); label.setFont(f_rangliste); tabelle.add(label); gbc.gridx++; gbl.setConstraints(label = new JLabel(Integer.toString(rangliste[i].gibAnzahlExakt(spt_anzeige, 3)), JLabel.CENTER), gbc); label.setFont(f_rangliste); tabelle.add(label); gbc.gridx++; gbl.setConstraints(label = new JLabel(Integer.toString(rangliste[i].gibAnzahlExakt(spt_anzeige, 2)), JLabel.CENTER), gbc); label.setFont(f_rangliste); tabelle.add(label); gbc.gridx++; gbl.setConstraints(label = new JLabel(Integer.toString(rangliste[i].gibAnzahlExakt(spt_anzeige, 1)), JLabel.CENTER), gbc); label.setFont(f_rangliste); tabelle.add(label); gbc.gridx++; gbl.setConstraints(label = new JLabel(Integer.toString(rangliste[i].gibPunkte(spt_anzeige)), JLabel.CENTER), gbc); label.setFont(f_rangliste); tabelle.add(label); } verl_tabelle.removeAll(); verl_tabelle.add(tabelle); } private void initEinstellungen() { einstellungen.setLayout(new BorderLayout()); einstellungen.add(einst_intervall = new JPanel(),BorderLayout.WEST); einstellungen.add(einst_wolkenpfad = new JPanel(),BorderLayout.EAST); JPanel infos; JScrollPane sc_infos; einstellungen.add(sc_infos = new JScrollPane(infos = new JPanel(), JScrollPane.VERTICAL_SCROLLBAR_NEVER, JScrollPane.HORIZONTAL_SCROLLBAR_AS_NEEDED),BorderLayout.CENTER); sc_infos.setViewportBorder(null); JLabel l_fehler = new JLabel(fehler); l_fehler.setFont(f_ergebnisse); l_fehler.setForeground(Color.RED); infos.add(l_fehler); Image symbol; JButton bu_lizenz; if(jar) symbol = Toolkit.getDefaultToolkit().getImage(Tippspiel.class.getResource("gpl.png")); else symbol = Toolkit.getDefaultToolkit().getImage("gpl.png"); bu_lizenz = new JButton(new ImageIcon(symbol)); infos.add(bu_lizenz); bu_lizenz.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent e) { try { Desktop.getDesktop().browse(new URI("http://www.gnu.de/documents/gpl.de.html")); } catch (Exception e1) { e1.printStackTrace(); JOptionPane.showMessageDialog(Tippspiel.this, "Browser konnte nicht aufgerufen werden."); } } }); JButton bu_copyright; bu_copyright = new JButton("<html>© Copyright 2014 Jonatan Zeidler<br>jonatan_zeidler@gmx.de</html>"); bu_copyright.setFont(f_ergebnisse); infos.add(bu_copyright); bu_copyright.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent e) { try { Desktop.getDesktop().browse(new URI("mailto:jonatan_zeidler@gmx.de")); } catch (Exception e1) { e1.printStackTrace(); JOptionPane.showMessageDialog(Tippspiel.this, "Mailprogramm konnte nicht aufgerufen werden."); } } }); JLabel l_quelle = new JLabel("Datenquelle:"); l_quelle.setFont(f_ergebnisse); infos.add(l_quelle); JButton bu_quelle; if(jar) symbol = Toolkit.getDefaultToolkit().getImage(Tippspiel.class.getResource("kicker.png")); else symbol = Toolkit.getDefaultToolkit().getImage("kicker.png"); bu_quelle = new JButton(new ImageIcon(symbol)); bu_quelle.setFont(f_ergebnisse); infos.add(bu_quelle); bu_quelle.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent e) { try { Desktop.getDesktop().browse(new URI(kicker.replace("{jahr}", saison))); } catch (Exception e1) { e1.printStackTrace(); JOptionPane.showMessageDialog(Tippspiel.this, "Browser konnte nicht aufgerufen werden."); } } }); //Wolkenpfad einst_wolkenpfad.setLayout(new GridLayout(2,1)); JButton bu_wolke; einst_wolkenpfad.add(bu_wolke = new JButton("Tippspielverzeichnis ändern")); bu_wolke.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent e) { int a = JOptionPane.showConfirmDialog(null, "Sollen die Daten aus dem bisherigen Verzeichnis übernommen werden?\n" + "Alternativ können die Daten auch manuell kopiert werden.", "Neues Tippspielverzeichnis", JOptionPane.YES_NO_CANCEL_OPTION, JOptionPane.QUESTION_MESSAGE); if(a == JOptionPane.CANCEL_OPTION) return; File f = erfragWolke(); if(f != null) { File alt = d_wolke; d_wolke = f; speicherKonfig(); File k; if(a == JOptionPane.YES_OPTION) { if((k = new File(alt,"Ergebnisse")).exists()) k.renameTo(new File(d_wolke,"Ergebnisse")); if((k = new File(alt,name+".tipps")).exists()) k.renameTo(new File(d_wolke,name+".tipps")); } aktualisiereDateien(); aktualisiereAnzeige(); } } }); einst_wolkenpfad.add(co_saison = new JComboBox<String>(jahre)); co_saison.setSelectedItem(saison); co_saison.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent e) { String neu_saison = (String) Tippspiel.this.co_saison.getSelectedItem(); if(!neu_saison.equals(saison)) { // Alte Daten sichern File sichern = new File(d_wolke,saison); sichern.mkdirs(); new File(d_wolke,"Ergebnisse").renameTo(new File(sichern,"Ergebnisse")); for(String s:namen) { new File(d_wolke,s+".tipps").renameTo(new File(sichern,s+".tipps")); new File(d_wolke,s+".chat").renameTo(new File(sichern,s+".chat")); } // Ggf. gesicherte Daten wiederherstellen File wiederherstellen = new File(d_wolke,neu_saison); if(wiederherstellen.isDirectory()) { for(File f:wiederherstellen.listFiles()) { if(f.isFile()) f.renameTo(new File(d_wolke,f.getName())); } } saison = neu_saison; speicherKonfig(); aktualisiereDateien(); spt_anzeige = spt_aktuell; aktualisiereAnzeige(); } } }); //Intervall einst_intervall.add(cb_erinnern = new JCheckBox("Erinnern", erinnern > 0)); cb_erinnern.setFont(f_ergebnisse); cb_erinnern.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent e) { if(setzeAutostart(cb_erinnern.isSelected(), false)) { if(cb_erinnern.isSelected()) erinnern = Math.abs(erinnern); else erinnern = -Math.abs(erinnern); sl_intervall.setEnabled(cb_erinnern.isSelected()); sl_info.setEnabled(cb_erinnern.isSelected()); speicherKonfig(); } else cb_erinnern.setSelected(erinnern > 0); } }); einst_intervall.add(sl_intervall = new JSlider(1,7)); sl_intervall.setMajorTickSpacing(1); // sl_intervall.setPaintLabels(true); sl_intervall.setPaintTicks(true); sl_intervall.setValue(Math.abs(erinnern)); sl_intervall.setEnabled(cb_erinnern.isSelected()); sl_intervall.addChangeListener(new ChangeListener() { @Override public void stateChanged(ChangeEvent e) { erinnern = sl_intervall.getValue(); speicherKonfig(); if(sl_intervall.getValue() > 1) sl_info.setText(erinnern+" Tage vor dem Spiel"); else sl_info.setText("Ein Tag vor dem Spiel"); } }); if(Math.abs(erinnern) == 1) einst_intervall.add(sl_info = new JLabel("Ein Tag vor dem Spiel")); else einst_intervall.add(sl_info = new JLabel(Math.abs(erinnern)+" Tage vor dem Spiel")); sl_info.setEnabled(cb_erinnern.isSelected()); sl_intervall.setFont(f_ergebnisse); sl_info.setFont(f_ergebnisse); } /** * * @param spieltag von 0 an gezählt */ private void tippe(int spieltag) { if(tipps[0][spieltag].istAustehend() || admin) { new Tippen(this, tipps[0][spieltag]); aktualisiereErgebnisse(); } else { aktualisiereErgebnisse(); JOptionPane.showMessageDialog(this, "Spiele können nur vor der Anstoßzeit getippt werden", "Tipp nicht möglich", JOptionPane.INFORMATION_MESSAGE); } } } /** * Repräsentiert eine Ansetzung bzw. den Tipp dazu * @author jonius */ class Spiel implements Serializable { private static final long serialVersionUID = 1L; String gegner, zeit_string; boolean heim; int tore_rwe, tore_gegner; GregorianCalendar zeit; static String verein_a = "class=\"link verinsLinkBild\" style=\"\">", verein_e = "</a>", spt = "<td>Spt.", anfang = "<td>", ende = "</td>", ergebnis_a ="\">", ergebnis_e = "&nbsp;"; static int z = 1; static enum Ausgang{SIEG, UNENTSCHIEDEN, NIEDERLAGE, AUSSTEHEND}; public Spiel() { gegner = "<leer>"; zeit_string = "<leer>"; tore_gegner = -1; tore_rwe = -1; zeit = new GregorianCalendar(); heim = false; } /** * Konstruktor, der aus HTML-Quelltext von kicker.de das Objekt erzeugt * @param html */ public Spiel(String html) { String zeit_html, ausw_html, ergebnis_html; html = html.substring(html.indexOf(verein_a)+verein_a.length()); gegner = html.substring(0, html.indexOf(verein_e)); html = html.substring(html.indexOf(spt)+spt.length()); html = html.substring(html.indexOf(anfang)+anfang.length()); zeit_html = html.substring(0, html.indexOf(ende)); zeit_string = zeit_html; if(zeit_html.contains(":")) { zeit = new GregorianCalendar( 2000+Integer.parseInt(zeit_html.substring(10,12)), Integer.parseInt(zeit_html.substring(7,9))-1, Integer.parseInt(zeit_html.substring(4,6)), Integer.parseInt(zeit_html.substring(13,15)), Integer.parseInt(zeit_html.substring(16))); } else { zeit = new GregorianCalendar( 2000+Integer.parseInt(zeit_html.substring(10,12)), Integer.parseInt(zeit_html.substring(7,9))-1, Integer.parseInt(zeit_html.substring(4,6)), 14,00); } html = html.substring(html.indexOf(anfang)+anfang.length()); ausw_html = html.substring(0, html.indexOf(ende)); heim = ausw_html.equals("H"); html = html.substring(html.indexOf(anfang)+anfang.length()); html = html.substring(html.indexOf(ergebnis_a)+ergebnis_a.length()); ergebnis_html = html.substring(0, html.indexOf(ergebnis_e)); if(ergebnis_html.equals("-:-")) { tore_rwe = -1; tore_gegner = -1; } else { tore_rwe = Integer.parseInt(ergebnis_html.substring(0,ergebnis_html.indexOf(":"))); tore_gegner = Integer.parseInt(ergebnis_html.substring(ergebnis_html.indexOf(":")+1)); } // System.out.println("\nGegner: "+gegner); // System.out.println("Zeit: "+zeit.get(GregorianCalendar.DATE)+"."+(zeit.get(GregorianCalendar.MONTH)+1)+"."+zeit.get(GregorianCalendar.YEAR)+ // " "+zeit.get(GregorianCalendar.HOUR_OF_DAY)+":"+zeit.get(GregorianCalendar.MINUTE)+" am "+zeit.get(GregorianCalendar.DAY_OF_WEEK)); // System.out.println("Heim: "+heim); // System.out.println("Ergebnis: "+tore_rwe+":"+tore_gegner); // System.out.println("In "+tageVerbleibend()+" Tagen."); } /** * Erstellt ein Spiel mit den angegebenen Werten * @param gegner * @param zeit * @param heim */ public Spiel(String gegner, GregorianCalendar zeit, boolean heim, String zeit_string) { this.gegner = gegner; this.zeit = zeit; this.heim = heim; this.tore_gegner = -1; this.tore_rwe = -1; this.zeit_string = zeit_string; } /** * Prüft, ob die Objekte identisch sind */ @Override public boolean equals(Object obj) { Spiel spiel = (Spiel) obj; return this.gleiches(spiel) && tore_gegner == spiel.tore_gegner && tore_rwe == spiel.tore_rwe; } /** * Prüft, ob es sich um die selbe Ansetzung handelt. Das Ergebnis muss nicht übereinstimmen. * @param spiel * @return */ public boolean gleiches(Spiel spiel) { return zeit.equals(spiel.zeit) && gegner.equals(spiel.gegner) && heim == spiel.heim; } /** * @return true, wenn ein Ergebnis gespeichert ist */ public boolean mitErgebnis() { return tore_rwe >= 0 && tore_gegner >= 0; } /** * gibt Ausgang zurück (S,U,N) oder Ausstehend * @return */ public Ausgang gibAusgang() { if(!mitErgebnis()) return Ausgang.AUSSTEHEND; if(tore_gegner > tore_rwe) return Ausgang.NIEDERLAGE; if(tore_rwe > tore_gegner) return Ausgang.SIEG; return Ausgang.UNENTSCHIEDEN; } /** * Berechnet die gewonnenen Punkte anhand des Tipps * @param tipp * @return */ public int gibPunkte(Spiel tipp) { if(gibAusgang() == Ausgang.AUSSTEHEND || tipp.gibAusgang() == Ausgang.AUSSTEHEND) return 0; if(tore_rwe == tipp.tore_rwe && tore_gegner == tipp.tore_gegner) return 3; if(tore_rwe - tore_gegner == tipp.tore_rwe - tipp.tore_gegner) return 2; if(gibAusgang() == tipp.gibAusgang()) return 1; return 0; } /** * @return true, wenn der Spielbeginn in der Zukunft liegt */ public boolean istAustehend() { return zeit.after(new GregorianCalendar()); } /** * @return Zahl der verbleibenden Tage */ public long tageVerbleibend() { return (zeit.getTimeInMillis() - new GregorianCalendar().getTimeInMillis()) / 86400000; } /** * Gibt eine Kopie des Spiels ohne eingetragenem Ergebnis zurück * @return leerer Tipp (Spiel) */ public Spiel gibLeerenTipp() { return new Spiel(gegner, zeit, heim, zeit_string); } public String gibErgebnisText() { if(mitErgebnis()) return tore_rwe+":"+tore_gegner; return "-:-"; } public String gibHeimText() { if(heim) return "H"; return "A"; } public String gibDatumText() { return zeit_string; } } class Spieler { private Spiel tipps[], ergebnisse[]; private String name; /** * @param tipps - Tipps * @param ergebnisse - Ergebnisse * @param name - Name des Spielers */ public Spieler(Spiel tipps[], Spiel ergebnisse[], String name) { this.tipps = tipps; this.ergebnisse = ergebnisse; this.name = name; Spieler rl[] = new Spieler[Tippspiel.rangliste.length+1]; for(int i = 0; i<Tippspiel.rangliste.length; i++) { rl[i] = Tippspiel.rangliste[i]; } rl[rl.length-1] = this; Tippspiel.rangliste = rl; } /** * Vergleicht die Punktzahlen zweier Spieler. Gibt false zurück, falls gleich gut. * @param sp Spieler, mit dem verglichen wird * @return wahr, falls dieser Spieler besser ist */ public boolean istBesserAls(Spieler sp) { return istBesserAls(sp, Tippspiel.spt_aktuell); } /** * Vergleicht die Punktzahlen zweier Spieler bis zum angegebenen Spieltag. * Gibt false zurück, falls gleich gut. * @param sp Spieler, mit dem verglichen wird * @param spieltag Spieltag, bis zu dem verglichen wird * @return wahr, falls dieser Spieler besser ist */ public boolean istBesserAls(Spieler sp, int spieltag) { if(sp.gibPunkte(spieltag) < this.gibPunkte(spieltag)) return true; if(sp.gibPunkte(spieltag) > this.gibPunkte(spieltag)) return false; if(sp.gibAnzahlMin(spieltag,3) < this.gibAnzahlMin(spieltag,3)) return true; if(sp.gibAnzahlMin(spieltag,3) > this.gibAnzahlMin(spieltag,3)) return false; if(sp.gibAnzahlMin(spieltag,2) < this.gibAnzahlMin(spieltag,2)) return true; if(sp.gibAnzahlMin(spieltag,2) > this.gibAnzahlMin(spieltag,2)) return false; return false; //gleich gut } public boolean istGleichGut(Spieler sp) { return sp.gibAnzahlMin(Tippspiel.spt_aktuell,1) == gibAnzahlMin(Tippspiel.spt_aktuell,1) && sp.gibAnzahlMin(Tippspiel.spt_aktuell,2) == gibAnzahlMin(Tippspiel.spt_aktuell,2) && sp.gibAnzahlMin(Tippspiel.spt_aktuell,3) == gibAnzahlMin(Tippspiel.spt_aktuell,3); } public int gibPlatzierung(int spieltag) { int p = 1; for(Spieler s:Tippspiel.rangliste) if(s.istBesserAls(this, spieltag)) p++; return p; } /** * Gibt die Anzahl der Punkte, die der Spieler bis zum angegebenen Spieltag erreicht hat. * @param spieltag * @return Punktezahl */ public int gibPunkte(int spieltag) { return gibAnzahlMin(spieltag, 1) + gibAnzahlMin(spieltag, 2) + gibAnzahlMin(spieltag, 3); } /** * Gibt die Anzahl der Spiele bis zum angegebenen Spieltag, * bei denen die Tipps mindestens die angegebene Punktzahl eingebracht haben. * @param spieltag * @param punkte - 1 liefert die Anzahl der korrekten Tendenzen, 2 die korrekten Tordifferenzen * und 3 die exakten Ergebnisse * @return Anzahl */ public int gibAnzahlMin(int spieltag, int punkte) { int p = 0; for(int i = 0; i<spieltag; i++) { if(ergebnisse[i].gibPunkte(tipps[i]) >= punkte) p++; } return p; } /** * Gibt die Anzahl der Spiele bis zum angegebenen Spieltag, * bei denen die Tipps genau die angegebene Punktzahl eingebracht haben. * @param spieltag * @param punkte - 1 liefert die Anzahl der korrekten Tendenzen, 2 die korrekten Tordifferenzen * und 3 die exakten Ergebnisse * @return Anzahl */ public int gibAnzahlExakt(int spieltag, int punkte) { int p = 0; for(int i = 0; i<spieltag; i++) { if(ergebnisse[i].gibPunkte(tipps[i]) == punkte) p++; } return p; } /** * Gibt die Anzahl der getippten Spiele bis zum angegebenen Spieltag. * @param spieltag * @return Anzahl */ public int gibtAnzahlTipps(int spieltag) { int p = 0; for(int i = 0; i<spieltag; i++) { if(tipps[i].mitErgebnis()) p++; } return p; } /** * @return Gibt ersten Spieltag, für den ein Tipp vorliegt. */ public int gibErstenTippSpieltag() { for(int i = 0; i<tipps.length; i++) if(tipps[i].mitErgebnis()) return i+1; return -1; } /** * @return Name des Spielers */ public String gibName() { return name; } } class Tippen extends JDialog { private static final long serialVersionUID = 1L; private Spiel spieltipp; private JSpinner tore_rwe, tore_gegner; public Tippen(JFrame fenster, Spiel tipp) { super(fenster, true); setDefaultCloseOperation(JDialog.DISPOSE_ON_CLOSE); getContentPane().setLayout(new GridLayout(2,1)); this.spieltipp = tipp; JPanel tipp_panel = new JPanel(), knopf_panel = new JPanel(); JButton ok = new JButton("Tippen"), abbruch = new JButton("Abbrechen"); ok.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent e) { spieltipp.tore_gegner = (int) tore_gegner.getValue(); spieltipp.tore_rwe = (int) tore_rwe.getValue(); Tippspiel.schreibeTipps(); dispose(); } }); abbruch.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent e) { dispose(); } }); getContentPane().add(tipp_panel); getContentPane().add(knopf_panel); tipp_panel.add(new JLabel("Rot Weiß Erfurt ")); tipp_panel.add(tore_rwe = new JSpinner(new SpinnerNumberModel(Math.max(0,tipp.tore_rwe), 0, 20, 1))); tipp_panel.add(new JLabel(":")); tipp_panel.add(tore_gegner = new JSpinner(new SpinnerNumberModel(Math.max(0,tipp.tore_gegner), 0, 20, 1))); tipp_panel.add(new JLabel(" "+tipp.gegner)); knopf_panel.add(ok); knopf_panel.add(abbruch); pack(); setLocation((int)(Toolkit.getDefaultToolkit().getScreenSize().getWidth()-this.getWidth())/2, (int)(Toolkit.getDefaultToolkit().getScreenSize().getHeight()-this.getHeight())/2); setVisible(true); } } class Aktualisierer extends Thread { private Tippspiel tippspiel; public Aktualisierer(Tippspiel tippspiel) { this.tippspiel = tippspiel; this.setDaemon(true); this.setPriority(1); } @Override public void run() { int i = 0; while(true) { try { Thread.sleep(1000); } catch (InterruptedException e) { e.printStackTrace(); } tippspiel.aktualisiereAnzeige(); if(i++ >= 60) { Tippspiel.aktualisiereDateien(); i = 0; } } } }
gpl-3.0
wizzn/openpatternrepository
30_sources/PatternRepository/pattern-management/src/main/java/nl/rug/search/opr/search/parser/Parser.java
195
package nl.rug.search.opr.search.parser; import nl.rug.search.opr.search.api.SearchQuery; /** * * @author cm */ public interface Parser { int yyparse(); SearchQuery getQuery(); }
gpl-3.0
hinantin/LibreOfficePlugin
qhichwa_extended/src/client/Client.java
15105
package qhichwa.client; import com.sun.star.lang.Locale; import com.sun.star.linguistic2.ProofreadingResult; import com.sun.star.linguistic2.SingleProofreadingError; import java.io.BufferedReader; import java.io.BufferedWriter; import java.io.File; import java.io.IOException; import java.io.InputStream; import java.io.InputStreamReader; import java.io.OutputStream; import java.io.OutputStreamWriter; import java.io.PrintStream; import java.net.URL; import java.nio.charset.Charset; import java.security.MessageDigest; import java.util.ArrayList; import java.util.Formatter; import java.util.Map; import java.util.regex.Matcher; import java.util.regex.Pattern; import qhichwa.openoffice.Main; public class Client { protected Process flookup = null; protected OutputStream fl_wr = null; protected InputStream fl_rd = null; protected Process p_tcpServer = null; public File analyzeUnificado_bin = null; public File chain_bin = null; public File spellcheckUnificado_bin = null; protected File flookup_bin = null; protected File tcpServer = null; protected File tcpClient = null; protected String[] command = null; protected File foma_file = null; protected Pattern rx = Pattern.compile("(\\S+)"); protected Matcher rx_m = this.rx.matcher(""); protected Pattern rx_pb = Pattern.compile("^\\p{Punct}+(\\S+?)$"); protected Matcher rx_pb_m = this.rx_pb.matcher(""); protected Pattern rx_pe = Pattern.compile("^(\\S+?)\\p{Punct}+$"); protected Matcher rx_pe_m = this.rx_pe.matcher(""); protected Pattern rx_pbe = Pattern.compile("^\\p{Punct}+(\\S+?)\\p{Punct}+$"); protected Matcher rx_pbe_m = this.rx_pbe.matcher(""); protected int position = 0; protected boolean debug = false; public static void main(String[] args) throws Exception { System.out.println("Initializing client"); Client temp = new Client(); temp.debug = true; Locale lt = new Locale(); lt.Language = "quh"; lt.Country = "BO"; lt.Variant = "UTF-8"; System.out.println("Checking validity of ñuuqa: " + temp.isValidWord("ñuuqa")); String[] alt = temp.getAlternatives("ñuuqa"); for (int i = 0; i < alt.length; i++) { System.out.println("Checking alternatives of ñuuqa: " + alt[i]); } ProofreadingResult error = temp.proofreadText("PACHANTIN LLAQTAKUNAPA RUNAP ALLIN KANANPAQ HATUN KAMACHIY.", lt, new ProofreadingResult()); for (int x = 0; x < error.aErrors.length; x++) { System.out.println(error.aErrors[x].nErrorStart + ", " + error.aErrors[x].nErrorLength + ", " + error.aErrors[x].nErrorType + ", " + error.aErrors[x].aRuleIdentifier + ", " + error.aErrors[x].aShortComment + ", " + error.aErrors[x].aFullComment); for (int j = 0; j < error.aErrors[x].aSuggestions.length; j++) { System.out.println("\t" + error.aErrors[x].aSuggestions[j]); } } } public Client() { System.err.println("os.name\t" + System.getProperty("os.name")); System.err.println("os.arch\t" + System.getProperty("os.arch")); try { URL tcps_url = null; URL tcpc_url = null; URL url = null; this.command = new String[]{"/bin/bash", "-c", ""}; if (System.getProperty("os.name").startsWith("Windows")) { tcps_url = getClass().getResource("../../lib/foma/win32/tcpServer.exe"); tcpc_url = getClass().getResource("../../lib/foma/win32/tcpClient.exe"); url = getClass().getResource("../../lib/foma/win32/flookup.exe"); this.command = new String[]{"CMD", "/C", ""}; } else if (System.getProperty("os.name").startsWith("Mac")) { tcps_url = getClass().getResource("../../lib/foma/mac/tcpServer"); tcpc_url = getClass().getResource("../../lib/foma/mac/tcpClient"); url = getClass().getResource("../../lib/foma/mac/flookup"); } else if (System.getProperty("os.name").startsWith("Linux")) { if ((System.getProperty("os.arch").startsWith("x86_64")) || (System.getProperty("os.arch").startsWith("amd64"))) { tcps_url = getClass().getResource("../../lib/foma/linux64/tcpServer"); tcpc_url = getClass().getResource("../../lib/foma/linux64/tcpClient"); url = getClass().getResource("../../lib/foma/linux64/flookup"); } else { tcps_url = getClass().getResource("../../lib/foma/linux32/tcpServer"); tcpc_url = getClass().getResource("../../lib/foma/linux32/tcpClient"); url = getClass().getResource("../../lib/foma/linux32/flookup"); } } this.flookup_bin = new File(url.toURI()); this.tcpServer = new File(tcps_url.toURI()); this.tcpClient = new File(tcpc_url.toURI()); if ((!this.flookup_bin.canExecute()) && (!this.flookup_bin.setExecutable(true))) { throw new Exception("Foma's flookup is not executable and could not be made executable!\nTried to execute " + this.flookup_bin.getCanonicalPath()); } if ((!this.tcpServer.canExecute()) && (!this.tcpServer.setExecutable(true))) { throw new Exception("Foma's tcpServer is not executable and could not be made executable!\nTried to execute " + this.tcpServer.getCanonicalPath()); } if ((!this.tcpClient.canExecute()) && (!this.tcpClient.setExecutable(true))) { throw new Exception("Foma's tcpClient is not executable and could not be made executable!\nTried to execute " + this.tcpClient.getCanonicalPath()); } this.foma_file = new File(getClass().getResource("../../lib/foma/analyzeUnificado.bin").toURI()); this.analyzeUnificado_bin = new File(getClass().getResource("../../lib/foma/analyzeUnificado.bin").toURI()); this.chain_bin = new File(getClass().getResource("../../lib/foma/chain.bin").toURI()); this.spellcheckUnificado_bin = new File(getClass().getResource("../../lib/foma/spellcheckUnificado.bin").toURI()); if (!this.foma_file.canRead()) { throw new Exception("qhichwa.fst is not readable!"); } /* ====================================================== INICIATE / INSTATIATE THE flookup ====================================================== */ ProcessBuilder pb = new ProcessBuilder(new String[]{flookup_bin.getAbsolutePath(), "-b", "-x", foma_file.getAbsolutePath()}); Map<String, String> env = pb.environment(); env.put("CYGWIN", "nodosfilewarning"); this.flookup = pb.start(); this.fl_wr = this.flookup.getOutputStream(); this.fl_rd = this.flookup.getInputStream(); /* ====================================================== INICIATE / INSTANTIATE THE TCP SERVER PROGRAM ====================================================== */ ProcessBuilder pb_tcps = new ProcessBuilder(new String[]{this.tcpServer.getAbsolutePath(), "-P", "8888", this.analyzeUnificado_bin.getAbsolutePath(), this.chain_bin.getAbsolutePath(), this.spellcheckUnificado_bin.getAbsolutePath()}); Map<String, String> env_tcps = pb_tcps.environment(); env_tcps.put("CYGWIN", "nodosfilewarning"); this.p_tcpServer = pb_tcps.start(); } catch (Exception ex) { showError(ex); } } public synchronized ProofreadingResult proofreadText(String paraText, Locale locale, ProofreadingResult paRes) { try { paRes.nStartOfSentencePosition = this.position; paRes.nStartOfNextSentencePosition = (this.position + paraText.length()); paRes.nBehindEndOfSentencePosition = paRes.nStartOfNextSentencePosition; ArrayList<SingleProofreadingError> errors = new ArrayList(); this.rx_m.reset(paraText); while (this.rx_m.find()) { SingleProofreadingError err = processWord(this.rx_m.group(), this.rx_m.start()); if (err != null) { errors.add(err); } } paRes.aErrors = ((SingleProofreadingError[]) errors.toArray(paRes.aErrors)); } catch (Throwable t) { showError(t); paRes.nBehindEndOfSentencePosition = paraText.length(); } return paRes; } public synchronized boolean isValid(String word) { if ((this.p_tcpServer == null) || (this.flookup == null) || (this.fl_wr == null) || (this.fl_rd == null)) { return false; } if (isValidWord(word)) { return true; } String lword = word.toLowerCase(); if ((!word.equals(lword)) && (isValidWord(lword))) { return true; } this.rx_pe_m.reset(word); if (this.rx_pe_m.matches()) { if (isValidWord(this.rx_pe_m.group(1))) { return true; } if (isValidWord(this.rx_pe_m.group(1).toLowerCase())) { return true; } } this.rx_pb_m.reset(word); if (this.rx_pb_m.matches()) { if (isValidWord(this.rx_pb_m.group(1))) { return true; } if (isValidWord(this.rx_pb_m.group(1).toLowerCase())) { return true; } } this.rx_pbe_m.reset(word); if (this.rx_pbe_m.matches()) { if (isValidWord(this.rx_pbe_m.group(1))) { return true; } if (isValidWord(this.rx_pbe_m.group(1).toLowerCase())) { return true; } } return false; } public synchronized String[] getAlternatives(String word) { String[] rv = new String[0]; try { if ((this.p_tcpServer == null) || (this.tcpClient == null) || (this.tcpServer == null) || (this.foma_file == null)) { return rv; } rv = alternatives(word); } catch (Exception ex) { showError(ex); return rv; } return rv; } // Getting the alternatives from the JSON like format output stream public String[] alternatives(String word) { String[] rv = new String[0]; word = word.trim().toLowerCase(); try { String ret = ""; ProcessBuilder pb = new ProcessBuilder(new String[]{this.tcpClient.getAbsolutePath(), "-P", "8888"}); pb.redirectErrorStream(true); Map<String, String> env = pb.environment(); env.put("CYGWIN", "nodosfilewarning"); Process process = null; try { process = pb.start(); } catch (IOException e) { System.out.println("Couldn't start the process."); e.printStackTrace(); } try { if (process != null) { BufferedWriter bw = new BufferedWriter(new OutputStreamWriter(process.getOutputStream(), "UTF-8")); bw.write(word); bw.newLine(); bw.close(); } } catch (IOException e) { System.out.println("Either couldn't read from the template file or couldn't write to the OutputStream."); e.printStackTrace(); } BufferedReader br = new BufferedReader(new InputStreamReader(process.getInputStream(), "UTF-8")); String currLine = null; try { while ((currLine = br.readLine()) != null) { System.out.println("Result:\t" + currLine); String[] line = currLine.split("[:|]"); ret = line[1]; System.out.println(ret); } } catch (IOException e) { System.out.println("Couldn't read the output."); e.printStackTrace(); } String delimiter = ","; if (ret.contains(delimiter)) { rv = ret.split(delimiter); } else { rv = new String[1]; rv[0] = ret; } } catch (Exception ex) { showError(ex); return rv; } return rv; } protected SingleProofreadingError processWord(String word, int start) { if (this.debug) { System.err.println(word + "\t" + start); } if (isValid(word)) { return null; } SingleProofreadingError err = new SingleProofreadingError(); err.nErrorStart = start; err.nErrorLength = word.length(); err.nErrorType = 1; return err; } public boolean isValidWord(String word) { word = word + "\n"; byte[] res = new byte[4]; try { this.fl_wr.write(word.getBytes(Charset.forName("UTF-8"))); this.fl_wr.flush(); if (this.fl_rd.read(res, 0, 4) != 4) { throw new Exception("Failed to read first 4 bytes from flookup!"); } int avail = this.fl_rd.available(); byte[] res2 = new byte[4 + avail]; System.arraycopy(res, 0, res2, 0, 4); res = res2; if (this.fl_rd.read(res2, 4, avail) != avail) { throw new Exception("Failed to read first 4 bytes from flookup!"); } else { //String s = new String(res); //System.out.println("RES: " + s + "\n"); } } catch (Exception ex) { showError(ex); return false; } return (res[0] != 43) || (res[1] != 63) || (res[2] != 10); } static void showError(Throwable e) { Main.showError(e); } public static String makeHash(byte[] convertme) { MessageDigest md = null; try { md = MessageDigest.getInstance("SHA-1"); } catch (Throwable t) { } try { md = MessageDigest.getInstance("MD5"); } catch (Throwable t) { } return byteArray2Hex(md.digest(convertme)); } private static String byteArray2Hex(byte[] hash) { Formatter formatter = new Formatter(); for (byte b : hash) { formatter.format("%02x", new Object[]{Byte.valueOf(b)}); } return formatter.toString(); } }
gpl-3.0
alesharik/AlesharikWebServer
utils/src/com/alesharik/webserver/api/ticking/Tickable.java
1732
/* * This file is part of AlesharikWebServer. * * AlesharikWebServer is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * AlesharikWebServer is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with AlesharikWebServer. If not, see <http://www.gnu.org/licenses/>. * */ package com.alesharik.webserver.api.ticking; /** * This class may tick! If class is mutable, you may need override {@link CacheComparator}.{@link #objectEquals(Object)} and {@link CacheComparator}.{@link #objectHashCode()} methods. * All ticking classes are cached. If your class must be non cached, return <code>object == this</code> in {@link CacheComparator}.{@link #objectEquals(Object)} */ @FunctionalInterface public interface Tickable extends CacheComparator { /** * This function called in ANOTHER THREAD. * Do not recommended to do long work(get response form internet server, database or etc) if you are not using thread pool. * Main logger log all exceptions with <code>[TickingPool]</code> prefix */ void tick() throws Exception; @Override default boolean objectEquals(Object other) { return this.equals(other); } @Override default int objectHashCode() { return this.hashCode(); } }
gpl-3.0
ZevenFang/zevencourse
src/main/java/com/zeven/course/model/Teacher.java
3339
package com.zeven.course.model; import javax.persistence.Basic; import javax.persistence.Column; import javax.persistence.Entity; import javax.persistence.Id; /** * Created by fangf on 2016/5/21. */ @Entity public class Teacher { private int id; private String tno; private String password; private String name; private byte gender; private String notes; private byte isAdmin; private int deptId; @Id @Column(name = "id", nullable = false) public int getId() { return id; } public void setId(int id) { this.id = id; } @Basic @Column(name = "tno", nullable = false, length = 45) public String getTno() { return tno; } public void setTno(String tno) { this.tno = tno; } @Basic @Column(name = "password", nullable = false, length = 32) public String getPassword() { return password; } public void setPassword(String password) { this.password = password; } @Basic @Column(name = "name", nullable = false, length = 45) public String getName() { return name; } public void setName(String name) { this.name = name; } @Basic @Column(name = "gender", nullable = false) public byte getGender() { return gender; } public void setGender(byte gender) { this.gender = gender; } @Basic @Column(name = "notes", nullable = true, length = 255) public String getNotes() { return notes; } public void setNotes(String notes) { this.notes = notes; } @Basic @Column(name = "is_admin", nullable = false) public byte getIsAdmin() { return isAdmin; } public void setIsAdmin(byte isAdmin) { this.isAdmin = isAdmin; } @Basic @Column(name = "dept_id", nullable = false) public int getDeptId() { return deptId; } public void setDeptId(int deptId) { this.deptId = deptId; } @Override public boolean equals(Object o) { if (this == o) return true; if (o == null || getClass() != o.getClass()) return false; Teacher teacher = (Teacher) o; if (id != teacher.id) return false; if (gender != teacher.gender) return false; if (isAdmin != teacher.isAdmin) return false; if (deptId != teacher.deptId) return false; if (tno != null ? !tno.equals(teacher.tno) : teacher.tno != null) return false; if (password != null ? !password.equals(teacher.password) : teacher.password != null) return false; if (name != null ? !name.equals(teacher.name) : teacher.name != null) return false; if (notes != null ? !notes.equals(teacher.notes) : teacher.notes != null) return false; return true; } @Override public int hashCode() { int result = id; result = 31 * result + (tno != null ? tno.hashCode() : 0); result = 31 * result + (password != null ? password.hashCode() : 0); result = 31 * result + (name != null ? name.hashCode() : 0); result = 31 * result + (int) gender; result = 31 * result + (notes != null ? notes.hashCode() : 0); result = 31 * result + (int) isAdmin; result = 31 * result + deptId; return result; } }
gpl-3.0
LeoTremblay/activityinfo
server/src/main/java/org/activityinfo/server/database/hibernate/dao/Transactional.java
1603
package org.activityinfo.server.database.hibernate.dao; /* * #%L * ActivityInfo Server * %% * Copyright (C) 2009 - 2013 UNICEF * %% * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as * published by the Free Software Foundation, either version 3 of the * License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public * License along with this program. If not, see * <http://www.gnu.org/licenses/gpl-3.0.html>. * #L% */ import java.lang.annotation.ElementType; import java.lang.annotation.Retention; import java.lang.annotation.RetentionPolicy; import java.lang.annotation.Target; /** * Indicates that a method should be run within a single Transaction. See * {@link org.activityinfo.server.database.hibernate.dao.TransactionalInterceptor} * for implementation. * <p/> * <strong>Important note:</strong> AOP can <strong>only</strong> applied to * methods with <code>protected</code> visiblity. If you apply this annotation * to a <code>private</code> method, Guice will fail silently to override the * method and your method will not be executed within a transaction. * * @author Alex Bertram */ @Retention(RetentionPolicy.RUNTIME) @Target(ElementType.METHOD) public @interface Transactional { }
gpl-3.0
isnuryusuf/ingress-indonesia-dev
apk/classes-ekstartk/com/badlogic/gdx/utils/compression/lz/InWindow.java
3456
package com.badlogic.gdx.utils.compression.lz; import java.io.InputStream; public class InWindow { public int _blockSize; public byte[] _bufferBase; public int _bufferOffset; int _keepSizeAfter; int _keepSizeBefore; int _pointerToLastSafePosition; public int _pos; int _posLimit; InputStream _stream; boolean _streamEndWasReached; public int _streamPos; public void Create(int paramInt1, int paramInt2, int paramInt3) { this._keepSizeBefore = paramInt1; this._keepSizeAfter = paramInt2; int i = paramInt3 + (paramInt1 + paramInt2); if ((this._bufferBase == null) || (this._blockSize != i)) { Free(); this._blockSize = i; this._bufferBase = new byte[this._blockSize]; } this._pointerToLastSafePosition = (this._blockSize - paramInt2); } void Free() { this._bufferBase = null; } public byte GetIndexByte(int paramInt) { return this._bufferBase[(paramInt + (this._bufferOffset + this._pos))]; } public int GetMatchLen(int paramInt1, int paramInt2, int paramInt3) { if ((this._streamEndWasReached) && (paramInt3 + (paramInt1 + this._pos) > this._streamPos)) paramInt3 = this._streamPos - (paramInt1 + this._pos); int i = paramInt2 + 1; int j = paramInt1 + (this._bufferOffset + this._pos); for (int k = 0; (k < paramInt3) && (this._bufferBase[(j + k)] == this._bufferBase[(j + k - i)]); k++); return k; } public int GetNumAvailableBytes() { return this._streamPos - this._pos; } public void Init() { this._bufferOffset = 0; this._pos = 0; this._streamPos = 0; this._streamEndWasReached = false; ReadBlock(); } public void MoveBlock() { int i = this._bufferOffset + this._pos - this._keepSizeBefore; if (i > 0) i--; int j = this._bufferOffset + this._streamPos - i; for (int k = 0; k < j; k++) this._bufferBase[k] = this._bufferBase[(i + k)]; this._bufferOffset -= i; } public void MovePos() { this._pos = (1 + this._pos); if (this._pos > this._posLimit) { if (this._bufferOffset + this._pos > this._pointerToLastSafePosition) MoveBlock(); ReadBlock(); } } public void ReadBlock() { if (this._streamEndWasReached) return; int j; do { this._streamPos = (j + this._streamPos); if (this._streamPos >= this._pos + this._keepSizeAfter) this._posLimit = (this._streamPos - this._keepSizeAfter); int i = 0 - this._bufferOffset + this._blockSize - this._streamPos; if (i == 0) break; j = this._stream.read(this._bufferBase, this._bufferOffset + this._streamPos, i); } while (j != -1); this._posLimit = this._streamPos; if (this._bufferOffset + this._posLimit > this._pointerToLastSafePosition) this._posLimit = (this._pointerToLastSafePosition - this._bufferOffset); this._streamEndWasReached = true; } public void ReduceOffsets(int paramInt) { this._bufferOffset = (paramInt + this._bufferOffset); this._posLimit -= paramInt; this._pos -= paramInt; this._streamPos -= paramInt; } public void ReleaseStream() { this._stream = null; } public void SetStream(InputStream paramInputStream) { this._stream = paramInputStream; } } /* Location: classes_dex2jar.jar * Qualified Name: com.badlogic.gdx.utils.compression.lz.InWindow * JD-Core Version: 0.6.2 */
gpl-3.0
WangGuoTing/my-uaf
src/main/java/com/myuaf/app/DisplayPNGCharacteristicsDescriptor.java
518
package com.example.defclass; public class DisplayPNGCharacteristicsDescriptor { public long width; //required public long height; //required public /*octet*/int bitDepth; //required public /*octet*/int colorType; //required public /*octet*/int compression; //required public /*octet*/int filter; //required public /*octet*/int interlace; //required public rgbPalletteEntry[] plte; }; class rgbPalletteEntry { public short r; public short g; public short b; };
gpl-3.0
srirang/numbrcrunchr
src/main/java/com/numbrcrunchr/domain/DataException.java
405
package com.numbrcrunchr.domain; public class DataException extends RuntimeException { private static final long serialVersionUID = 1L; public DataException(String message, Throwable cause) { super(message, cause); } public DataException(String message) { super(message); } public DataException(Throwable cause) { super(cause); } }
gpl-3.0
nettee/pancake
pancake-java/pancake-core/src/main/java/me/nettee/pancake/core/page/PagedFile.java
14827
package me.nettee.pancake.core.page; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import java.io.IOException; import java.nio.ByteBuffer; import java.nio.channels.FileChannel; import java.nio.file.Files; import java.nio.file.Path; import java.util.Deque; import java.util.HashSet; import java.util.LinkedList; import java.util.Set; import java.util.function.Predicate; import java.util.function.UnaryOperator; import static com.google.common.base.Preconditions.*; import static java.nio.file.StandardOpenOption.*; /** * <b>Paged file</b> is the bottom component of pancake-core. This component * provides facilities for higher-level client components to perform file I/O in * terms of pages. * <p> * <b>Page number</b> identifies a page in a paged file. Page numbers correspond * to their location within the file on disk. When you initially create a file * and allocate pages using {@linkplain PagedFile#allocatePage() * allocatePage()}, page numbering will be sequential. However, once pages have * been deleted, the numbers of newly allocated pages are not sequential. The * paged file reallocates previously allocated pages using a LIFO (stack) * algorithm -- that is it reallocates the most recently deleted (and not * reallocated) page. A brand new page is never allocated if a previously * allocated page is available. * <p> * * @author nettee * */ public class PagedFile { private static Logger logger = LoggerFactory.getLogger(PagedFile.class); private FileChannel file; private int N; // Number of pages // private Map<Integer, Integer> disposedPageIndexes = new HashMap<>(); private Deque<Integer> disposedPageNumsStack = new LinkedList<>(); private PageBuffer buffer; private PagedFile(Path path) { buffer = new PageBuffer(this); try { this.file = FileChannel.open(path, CREATE, READ, WRITE); } catch (IOException e) { throw new PagedFileException(e); } } /** * Create a paged file. The file should not already exist. * * @param path * the path of database file * @return created paged file */ public static PagedFile create(Path path) { checkNotNull(path); checkArgument(Files.notExists(path), "file already exists: %s", path.toString()); logger.info("Creating PagedFile {}", path.toString()); PagedFile pagedFile = new PagedFile(path); pagedFile.initPages(); return pagedFile; } /** * Open a paged file. The file must already exist and have been created * using the <tt>create</tt> method. * * @param path * the path of database file * @return opened paged file * @throws PagedFileException */ public static PagedFile open(Path path) { checkNotNull(path); checkArgument(Files.exists(path), "file does not exist: %s", path.toString()); logger.info("Opening PagedFile {}", path.toString()); PagedFile pagedFile = new PagedFile(path); try { pagedFile.loadPages(); } catch (IOException e) { throw new PagedFileException(e); } return pagedFile; } private void initPages() { N = 0; } private void loadPages() throws IOException { if (file.size() % Page.PAGE_SIZE != 0) { logger.warn("file length is not dividable by {}", Page.PAGE_SIZE); } N = (int) (file.size() / Page.PAGE_SIZE); // Restore the order of disposed pages. Their pageNums are pushed // orderly into the stack. int[] disposedPageNums = new int[N+1]; for (int i = 0; i <= N; i++) { disposedPageNums[i] = -1; } for (int pageNum = 0; pageNum < N; pageNum++) { file.position(pageNum * Page.PAGE_SIZE); ByteBuffer pageNumCopy = ByteBuffer.allocate(4); file.read(pageNumCopy); pageNumCopy.flip(); int actualNum = pageNumCopy.asIntBuffer().get(0); if (actualNum < 0) { // A disposed page has its page number less than zero. int disposedOrder = -actualNum; disposedPageNums[disposedOrder] = pageNum; } } for (int pageNum : disposedPageNums) { if (pageNum >= 0) { disposedPageNumsStack.push(pageNum); } } } /** * Close the paged file. All of the pages are flushed from the buffer pool * to the disk before the file is closed. */ public void close() { logger.info("Closing PagedFile"); if (buffer.hasPinnedPages()) { logger.error("Still has pinned pages[{}]", Pages.pageRangeRepr(buffer.getPinnedPages())); throw new PagedFileException("Fail to close paged file: there are pinned pages in the buffer pool"); } Set<Integer> unpinnedPages = buffer.getUnpinnedPages(); for (int pageNum : unpinnedPages) { writeBack(buffer.get(pageNum)); } if (!unpinnedPages.isEmpty()) { logger.info("Written back unpinned pages[{}]", Pages.pageRangeRepr(unpinnedPages)); } try { file.close(); } catch (IOException e) { throw new PagedFileException(e); } } public int getNumOfPages() { return N; } private void checkPageNumRange(int pageNum) { if (pageNum < 0 || pageNum >= N) { throw new PagedFileException("page index out of bound: " + pageNum); } } private boolean isDisposed(int pageNum) { return disposedPageNumsStack.contains(pageNum); } private Page readPageFromFile(int pageNum) throws IOException { Page page = new Page(pageNum); file.position(pageNum * Page.PAGE_SIZE); ByteBuffer pageCopy = ByteBuffer.allocate(Page.PAGE_SIZE); file.read(pageCopy); pageCopy.position(4); pageCopy.get(page.data); return page; } void writePageToFile(Page page) throws IOException { file.position(page.num * Page.PAGE_SIZE); ByteBuffer out = ByteBuffer.allocate(Page.PAGE_SIZE); out.putInt(page.num); out.put(page.data); out.flip(); while (out.hasRemaining()) { file.write(out); } } /** * Allocate a new page in the file. * * @return a <tt>Page</tt> object * @throws PagedFileException When it fails to write the file. */ public Page allocatePage() { int pageNum; if (disposedPageNumsStack.isEmpty()) { pageNum = N++; } else { pageNum = disposedPageNumsStack.pop(); } logger.info("Allocating page[{}]", pageNum); Page page = new Page(pageNum); try { writePageToFile(page); } catch (IOException e) { String msg = String.format("fail to allocate page[%d]", pageNum); throw new PagedFileException(msg, e); } try { buffer.putAndPin(page); } catch (FullBufferException e) { logger.error(String.format("Fail to allocate page[%d]", page.num), e); throw e; } return page; } /** * Remove the page specified by <tt>pageNum</tt>. * A page must be unpinned before disposed. * * @param pageNum the number of the page to dispose * @throws PagedFileException When the page number is not exist, * when the page is not unpinned, * or when it fails to write the file. */ public void disposePage(int pageNum) { checkPageNumRange(pageNum); if (disposedPageNumsStack.contains(pageNum)) { // This page is already disposed. String msg = String.format("page[%d] already disposed", pageNum); throw new PagedFileException(msg); } if (buffer.contains(pageNum)) { if (buffer.isPinned(pageNum)) { String msg = String.format("cannot dispose a pinned page[%d]", pageNum); throw new PagedFileException(msg); } buffer.removeWithoutWriteBack(pageNum); // can throw exception } try { file.position(pageNum * Page.PAGE_SIZE); // Write at the pageNum position with the opposite number of the // disposed order, so that (1) we can identify disposed pages with // a negative pageNum; (2) we can restore the disposed order when // re-open the file. ByteBuffer out = ByteBuffer.allocate(Page.PAGE_SIZE); out.putInt(-1 - disposedPageNumsStack.size()); // Fill the file with default bytes for ease of debugging. out.put(Pages.makeDefaultBytes(Page.DATA_SIZE)); out.flip(); while (out.hasRemaining()) { file.write(out); } } catch (IOException e) { String msg = String.format("fail to dispose page[%d]", pageNum); throw new PagedFileException(msg, e); } disposedPageNumsStack.push(pageNum); logger.debug(String.format("dispose page[%d]", pageNum)); } /** * Read page from buffer or from file. * * NOTE: This method does not check page number range or disposed page. * * If the page is in buffer, return it simply. Otherwise, read the page from * file and put it into buffer. */ private Page readPage(int pageNum) { try { if (buffer.contains(pageNum)) { Page page = buffer.get(pageNum); // If the page is unpinned before, pin it again. buffer.pinAgainIfNot(page); return page; } else { Page page = readPageFromFile(pageNum); buffer.putAndPin(page); return page; } } catch (IOException e) { String msg = String.format("fail to read page[%d]", pageNum); throw new PagedFileException(msg); } } public Page getPage(int pageNum) { checkPageNumRange(pageNum); if (isDisposed(pageNum)) { String msg = String.format("cannot get a disposed page[%d]", pageNum); throw new PagedFileException(msg); } Page page = readPage(pageNum); logger.info("Got page[{}]", pageNum); return page; } private Page searchPage(int startPageNum, Predicate<Integer> endPredicate, UnaryOperator<Integer> next, String messageOnFail) { int pageNum = startPageNum; while (!endPredicate.test(pageNum)) { if (!isDisposed(pageNum)) { return readPage(pageNum); } pageNum = next.apply(pageNum); } // no page matches throw new PagedFileException(messageOnFail); } private Page searchPageIncreasing(int startPageNum, int endPageNum, String messageOnFail) { return searchPage(startPageNum, x -> x > endPageNum, x -> x + 1, messageOnFail); } private Page searchPageDecreasing(int startPageNum, int endPageNum, String messageOnFail) { return searchPage(startPageNum, x -> x < endPageNum, x -> x - 1, messageOnFail); } public Page getFirstPage() { Page page = searchPageIncreasing(0, N - 1, "no first page"); logger.info("Got page[{}] (first page)", page.num); return page; } public Page getLastPage() { Page page = searchPageDecreasing(N - 1, 0, "no last page"); logger.info("Got page[{}] (last page)", page.num); return page; } public Page getPreviousPage(int currentPageNum) { Page page = searchPageDecreasing(currentPageNum - 1, 0, "no previous page"); logger.info("Got page[{}] (previous page of page[{}]", page.num, currentPageNum); return page; } public Page getNextPage(int currentPageNum) { Page page = searchPageIncreasing(currentPageNum + 1, N - 1, "no next page"); logger.info("Got page[{}] (next page of page[{}]", page.num, currentPageNum); return page; } /** * Mark that the page specified by <tt>pageNum</tt> have been or will be * modified. The page must be pinned in the buffer pool. The <i>dirty</i> * pages will be written back to disk when removed from the buffer pool. * @param pageNum page number of the page to mark as dirty */ public void markDirty(int pageNum) { checkPageNumRange(pageNum); if (!buffer.contains(pageNum)) { String msg = String.format("Try to mark page[%d] as dirty which is not in buffer pool", pageNum); logger.error(msg); throw new PagedFileException(msg); } Page page = buffer.get(pageNum); if (!page.pinned) { String msg = String.format("Try to mark an unpinned page[%d] as dirty", pageNum); logger.error(msg); throw new PagedFileException(msg); } page.dirty = true; logger.info("Marked page[{}] as dirty in buffer", page.num); } /** * Mark that the <tt>page</tt> have been or will be modified. A * <i>dirty</i> page is written back to disk when it is removed from the * buffer pool. * @param page the page to mark as dirty */ public void markDirty(Page page) { markDirty(page.num); } /** * Mark that the page specified by <tt>pageNum</tt> is no longer needed in * memory. * @param pageNum page number of the page to unpin */ public void unpinPage(int pageNum) { checkPageNumRange(pageNum); if (buffer.contains(pageNum)) { buffer.unpin(pageNum); logger.info("Unpinned page[{}] in buffer", pageNum); } } /** * Mark that the <tt>page</tt> is no longer need in memory. * @param page the page to unpin */ public void unpinPage(Page page) { unpinPage(page.num); } void writeBack(Page page) { checkState(buffer.contains(page.num)); if (page.dirty) { try { writePageToFile(page); } catch (IOException e) { throw new PagedFileException(e); } } } /** * Mark that the pages specified by <tt>pageNums</tt> is no longer needed * in memory. * @param pageNums page numbers of the pages to unpin */ public void unpinPages(Set<Integer> pageNums) { Set<Integer> unpinnedPageNums = new HashSet<>(); for (int pageNum : pageNums) { checkPageNumRange(pageNum); if (buffer.contains(pageNum)) { buffer.unpin(pageNum); unpinnedPageNums.add(pageNum); } } logger.info("Unpinned pages[{}] in buffer", Pages.pageRangeRepr(unpinnedPageNums)); } void writeBack(int pageNum) { checkState(buffer.contains(pageNum)); writeBack(buffer.get(pageNum)); } private void forcePage0(int pageNum) { if (!buffer.contains(pageNum)) { String msg = String.format( "Fail to force page[%d]: page not in buffer pool", pageNum); logger.error(msg); throw new PagedFileException(msg); } writeBack(pageNum); Page page = buffer.get(pageNum); page.dirty = false; } /** * This method copies the contents of the page specified by <tt>pageNum</tt> * from the buffer pool to disk if the page is in the buffer pool and is * marked as dirty. The page remains in the buffer pool but is no longer * marked as dirty. * * @param pageNum page number * @throws PagedFileException */ public void forcePage(int pageNum) { forcePage0(pageNum); logger.info("Forced page[{}]", pageNum); } /** * This method copies the contents of the <tt>page</tt> from the buffer * pool to disk if the page is in the buffer pool and is marked as dirty. * The page remains in the buffer pool but is no longer marked as dirty. * * @param page the <tt>Page</tt> object * @throws PagedFileException */ public void forcePage(Page page) { forcePage0(page.num); logger.info("Forced page[{}]", page.num); } /** * This method copies the contents of all the pages in the buffer pool to * disk. The pages remains in the buffer pool but is no longer marked as * dirty. Calling this method has the same effect as calling * <tt>forcePage</tt> on each page. * * @throws PagedFileException */ public void forceAllPages() { // Force all the pages in the buffer pool. Set<Integer> allPages = buffer.getAllPages(); for (int pageNum : allPages) { forcePage0(pageNum); } logger.info("Forced all pages[{}]", Pages.pageRangeRepr(allPages)); } }
gpl-3.0
Niky4000/UsefulUtils
projects/tutorials-master/tutorials-master/core-java-modules/core-java-io/src/test/java/com/baeldung/java/nio2/async/AsyncEchoClient.java
2625
package com.baeldung.java.nio2.async; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import java.net.InetSocketAddress; import java.nio.ByteBuffer; import java.nio.channels.AsynchronousSocketChannel; import java.util.concurrent.ExecutionException; import java.util.concurrent.Future; public class AsyncEchoClient { private static final Logger LOG = LoggerFactory.getLogger(AsyncEchoClient.class); private AsynchronousSocketChannel client; private Future<Void> future; private static AsyncEchoClient instance; private AsyncEchoClient() { try { client = AsynchronousSocketChannel.open(); InetSocketAddress hostAddress = new InetSocketAddress("localhost", 4999); future = client.connect(hostAddress); start(); } catch (IOException e) { e.printStackTrace(); } } public static AsyncEchoClient getInstance() { if (instance == null) instance = new AsyncEchoClient(); return instance; } private void start() { try { future.get(); } catch (InterruptedException | ExecutionException e) { e.printStackTrace(); } } public String sendMessage(String message) { byte[] byteMsg = message.getBytes(); ByteBuffer buffer = ByteBuffer.wrap(byteMsg); Future<Integer> writeResult = client.write(buffer); try { writeResult.get(); } catch (Exception e) { e.printStackTrace(); } buffer.flip(); Future<Integer> readResult = client.read(buffer); try { readResult.get(); } catch (Exception e) { e.printStackTrace(); } String echo = new String(buffer.array()).trim(); buffer.clear(); return echo; } public void stop() { try { client.close(); } catch (IOException e) { e.printStackTrace(); } } public static void main(String[] args) throws Exception { AsyncEchoClient client = AsyncEchoClient.getInstance(); client.start(); BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); String line; LOG.debug("Message to server:"); while ((line = br.readLine()) != null) { String response = client.sendMessage(line); LOG.debug("response from server: " + response); LOG.debug("Message to server:"); } } }
gpl-3.0
triguero/Keel3.0
src/keel/Algorithms/UnsupervisedLearning/AssociationRules/IntervalRuleLearning/Alatasetal/Alatasetal.java
10402
/*********************************************************************** This file is part of KEEL-software, the Data Mining tool for regression, classification, clustering, pattern mining and so on. Copyright (C) 2004-2010 F. Herrera (herrera@decsai.ugr.es) L. Sánchez (luciano@uniovi.es) J. Alcalá-Fdez (jalcala@decsai.ugr.es) S. García (sglopez@ujaen.es) A. Fernández (alberto.fernandez@ujaen.es) J. Luengo (julianlm@decsai.ugr.es) This program is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program. If not, see http://www.gnu.org/licenses/ **********************************************************************/ package keel.Algorithms.UnsupervisedLearning.AssociationRules.IntervalRuleLearning.Alatasetal; /** * <p> * @author Written by Alberto Fernández (University of Granada) * @author Modified by Nicolò Flugy Papè (Politecnico di Milano) 24/03/2009 * @author Modified by Diana Martín (dmartin@ceis.cujae.edu.cu) * @version 1.1 * @since JDK1.6 * </p> */ import java.io.FileNotFoundException; import java.io.IOException; import java.io.PrintWriter; import java.util.ArrayList; import org.core.*; import keel.Dataset.*; public class Alatasetal { /** * <p> * It gathers all the parameters, launches the algorithm, and prints out the results * </p> */ private myDataset trans; private String rulesFilename; private String valuesFilename; String valuesOrderFilename; private AlatasetalProcess proc; private ArrayList<AssociationRule> associationRules; private String fileTime, fileHora, namedataset; private int nTrials; private int randomChromosomes; private int r; private int tournamentSize; private double pc; private double pmMin; private double pmMax; private double a1; private double a2; private double a3; private double a4; private double a5; private double af; private double minSupport; long startTime, totalTime; private boolean somethingWrong = false; //to check if everything is correct. /** * Default constructor */ public Alatasetal() { } /** * It reads the data from the input files and parse all the parameters from the parameters array * @param parameters It contains the input files, output files and parameters */ public Alatasetal(parseParameters parameters) { this.startTime = System.currentTimeMillis(); this.trans = new myDataset(); try { this.namedataset = parameters.getTransactionsInputFile(); System.out.println("\nReading the transaction set: " + parameters.getTransactionsInputFile()); trans.readDataSet( parameters.getTransactionsInputFile() ); } catch (IOException e) { System.err.println("There was a problem while reading the input transaction set: " + e); somethingWrong = true; } //We may check if there are some numerical attributes, because our algorithm may not handle them: //somethingWrong = somethingWrong || train.hasNumericalAttributes(); this.somethingWrong = this.somethingWrong || this.trans.hasMissingAttributes(); this.rulesFilename = parameters.getAssociationRulesFile(); this.valuesFilename = parameters.getOutputFile(0); this.valuesOrderFilename = parameters.getOutputFile(1); this.fileTime = (parameters.getOutputFile(0)).substring(0,(parameters.getOutputFile(0)).lastIndexOf('/')) + "/time.txt"; this.fileHora = (parameters.getOutputFile(0)).substring(0,(parameters.getOutputFile(0)).lastIndexOf('/')) + "/hora.txt"; long seed = Long.parseLong(parameters.getParameter(0)); this.nTrials = Integer.parseInt( parameters.getParameter(1) ); this.randomChromosomes = Integer.parseInt( parameters.getParameter(2) ); int r = Integer.parseInt( parameters.getParameter(3) ); this.tournamentSize = Integer.parseInt( parameters.getParameter(4) ); this.pc = Double.parseDouble( parameters.getParameter(5) ); this.pmMin = Double.parseDouble( parameters.getParameter(6) ); this.pmMax = Double.parseDouble( parameters.getParameter(7) ); this.a1 = Double.parseDouble( parameters.getParameter(8) ); this.a2 = Double.parseDouble( parameters.getParameter(9) ); this.a3 = Double.parseDouble( parameters.getParameter(10) ); this.a4 = Double.parseDouble( parameters.getParameter(11) ); this.a5 = Double.parseDouble( parameters.getParameter(12) ); this.af = Double.parseDouble( parameters.getParameter(13) ); this.minSupport = 0.001; this.r = (this.trans.getnVars() >= r) ? r : this.trans.getnVars(); Randomize.setSeed(seed); } /** * It launches the algorithm */ public void execute() { if (somethingWrong) { //We do not execute the program System.err.println("An error was found"); System.err.println("Aborting the program"); //We should not use the statement: System.exit(-1); } else { this.proc = new AlatasetalProcess(this.trans, this.nTrials, this.randomChromosomes, this.r, this.tournamentSize, this.pc, this.pmMin, this.pmMax, this.a1, this.a2, this.a3, this.a4, this.a5, this.af); this.proc.run(); this.associationRules = this.proc.generateRulesSet(this.minSupport);// we do not use minConfidence try { int r, i; AssociationRule a_r; Gene[] terms; ArrayList<Integer> id_attrs; PrintWriter rules_writer = new PrintWriter(this.rulesFilename); PrintWriter values_writer = new PrintWriter(this.valuesFilename); PrintWriter valueOrder_writer = new PrintWriter(this.valuesOrderFilename); rules_writer.println("<?xml version=\"1.0\" encoding=\"UTF-8\"?>"); rules_writer.println("<association_rules>"); values_writer.println("<?xml version=\"1.0\" encoding=\"UTF-8\"?>"); values_writer.println("<values>"); valueOrder_writer.print("<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n"); valueOrder_writer.println("<values>"); for (r=0; r < this.associationRules.size(); r++) { a_r = this.associationRules.get(r); rules_writer.println("<rule id=\"" + r + "\">"); values_writer.println("<rule id=\"" + r + "\" rule_support=\"" + AlatasetalProcess.roundDouble(a_r.getSupport(),2) + "\" antecedent_support=\"" + AlatasetalProcess.roundDouble(a_r.getAntecedentSupport(),2) + "\" consequent_support=\"" + AlatasetalProcess.roundDouble(a_r.getConsequentSupport(),2) + "\" confidence=\"" + AlatasetalProcess.roundDouble(a_r.getConfidence(),2) +"\" lift=\"" + AlatasetalProcess.roundDouble(a_r.getLift(),2) + "\" conviction=\"" + AlatasetalProcess.roundDouble(a_r.getConv(),2) + "\" certainFactor=\"" + AlatasetalProcess.roundDouble(a_r.getCF(),2) + "\" netConf=\"" + AlatasetalProcess.roundDouble(a_r.getnetConf(),2) + "\" yulesQ=\"" + AlatasetalProcess.roundDouble(a_r.getyulesQ(),2) + "\" nAttributes=\"" + (a_r.getAntecedents().length + a_r.getConsequents().length) + "\"/>"); rules_writer.println("<antecedents>"); terms = a_r.getAntecedents(); id_attrs = a_r.getIdOfAntecedents(); for (i=0; i < terms.length; i++) createRule(terms[i], id_attrs.get(i), rules_writer); rules_writer.println("</antecedents>"); rules_writer.println("<consequents>"); terms = a_r.getConsequents(); id_attrs = a_r.getIdOfConsequents(); for (i=0; i < terms.length; i++) createRule(terms[i], id_attrs.get(i), rules_writer); rules_writer.println("</consequents>"); rules_writer.println("</rule>"); } rules_writer.println("</association_rules>"); values_writer.println("</values>"); this.proc.saveReport(this.associationRules, values_writer); rules_writer.close(); values_writer.close(); valueOrder_writer.print(this.proc.printRules(this.associationRules)); valueOrder_writer.println("</values>"); valueOrder_writer.close(); totalTime = System.currentTimeMillis() - startTime; this.writeTime(); System.out.println("Algorithm Finished"); } catch (FileNotFoundException e) { e.printStackTrace(); } } } public void writeTime() { long seg, min, hor; String stringOut = new String(""); stringOut = "" + totalTime / 1000 + " " + this.namedataset + rulesFilename + "\n"; Files.addToFile(this.fileTime, stringOut); totalTime /= 1000; seg = totalTime % 60; totalTime /= 60; min = totalTime % 60; hor = totalTime / 60; stringOut = ""; if (hor < 10) stringOut = stringOut + "0"+ hor + ":"; else stringOut = stringOut + hor + ":"; if (min < 10) stringOut = stringOut + "0"+ min + ":"; else stringOut = stringOut + min + ":"; if (seg < 10) stringOut = stringOut + "0"+ seg; else stringOut = stringOut + seg; stringOut = stringOut + " " + rulesFilename + "\n"; Files.addToFile(this.fileHora, stringOut); } private void createRule(Gene g, int id_attr, PrintWriter w) { w.println("<attribute name=\"" + Attributes.getAttribute(id_attr).getName() + "\" value=\""); if (! g.getIsPositiveInterval()) w.print("NOT "); if ( trans.getAttributeType(id_attr) == myDataset.NOMINAL ) w.print(Attributes.getAttribute(id_attr).getNominalValue( (int)g.getLowerBound() )); else w.print("[" + g.getLowerBound() + ", " + g.getUpperBound() + "]"); w.print("\" />"); } }
gpl-3.0
Luc1412/EasyMaintenance
src/main/java/de/luc1412/em/versions/v1_12_r1/JsonChatManager.java
762
package de.luc1412.em.versions.v1_12_r1; import com.google.gson.JsonSyntaxException; import net.minecraft.server.v1_12_R1.ChatMessageType; import net.minecraft.server.v1_12_R1.IChatBaseComponent; import net.minecraft.server.v1_12_R1.PacketPlayOutChat; import org.bukkit.craftbukkit.v1_12_R1.entity.CraftPlayer; import org.bukkit.entity.Player; /** * Created by Luc1412 on 02.08.2017 at 18:54 */ public class JsonChatManager { public void sendEventMessage(Player p, String json) { try { IChatBaseComponent icbc = IChatBaseComponent.ChatSerializer.a(json); PacketPlayOutChat packet = new PacketPlayOutChat(icbc, ChatMessageType.CHAT); ((CraftPlayer) p).getHandle().playerConnection.sendPacket(packet); } catch (JsonSyntaxException e) { } } }
gpl-3.0
afatcat/LeetCodePractice
src/main/java/net/shutingg/leetCode/PartitionList.java
1286
package net.shutingg.leetCode; /** * https://leetcode.com/problems/partition-list/description/ * http://www.lintcode.com/en/problem/partition-list/ */ public class PartitionList { /** * LinkedList * (To improve: you don't need that many parameters) * @param head: The first node of linked list * @param x: An integer * @return: A ListNode */ public ListNode partition(ListNode head, int x) { if(head == null) { return head; } ListNode dummy = new ListNode(0); dummy.next = head; ListNode p1 = dummy; ListNode p2 = dummy; ListNode firstP1 = null; ListNode firstP2 = null; while (head != null) { if(head.val < x) { if(firstP1 == null){ firstP1 = head; } p1.next = head; p1 = p1.next; } else { if (firstP2 == null) { firstP2 = head; } p2.next = head; p2 = p2.next; } head = head.next; } p1.next = firstP2; p2.next = null; if(firstP1 == null) { return firstP2; } return firstP1; } }
gpl-3.0
cwmaguire/flexmud
src/flexmud/engine/context/Context.java
9082
/************************************************************************************************** * Copyright 2009 Chris Maguire (cwmaguire@gmail.com) * * * * Flexmud is free software: you can redistribute it and/or modify * * it under the terms of the GNU General Public License as published by * * the Free Software Foundation, either version 3 of the License, or * * (at your option) any later version. * * * * Flexmud is distributed in the hope that it will be useful, * * but WITHOUT ANY WARRANTY; without even the implied warranty of * * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * * GNU General Public License for more details. * * * * You should have received a copy of the GNU General Public License * * along with flexmud. If not, see <http://www.gnu.org/licenses/>. * **************************************************************************************************/ package flexmud.engine.context; import org.apache.log4j.Logger; import org.hibernate.annotations.Cascade; import javax.persistence.*; import java.util.*; @Entity @Table(name = "context") public class Context { private static final Logger LOGGER = Logger.getLogger(Context.class); public static final String ID_PROPERTY = "id"; public static final String NAME_PROPERTY = "name"; public static final String CHILD_GROUP_PROPERTY = "childGroup"; public static final String PARENT_GROUP_PROPERTY = "parentGroup"; public static final String COMMAND_CLASS_NAME_ALIASES_PROPERTY = "contextCommands"; public static final String ENTRY_MESSAGE_PROPERTY = "entryMessage"; public static final String DOES_USE_CHARACTER_PROMPT_PROPERTY = "isCharacterPromptable"; public static final String MAX_ENTRIES_PROPERTY = "maxEntries"; public static final String MAX_ENTRIES_EXCEEDED_MESSAGE_PROPERTY = "maxEntriesExceededMessage"; public static final String ENTRY_COMMAND_CLASS_NAME_PROPERTY = "entryCommandClassName"; public static final String PROMPT_COMMAND_CLASS_NAME_PROPERTY = "promptCommandClassName"; public static final String DEFAULT_COMMAND_CLASS_NAME_PROPERTY = "defaultCommandClassname"; public static final String PROMPT_PROPERTY = "prompt"; private long id; private String name; private ContextGroup childGroup; private ContextGroup parentGroup; private Set<ContextCommand> contextCommands = new HashSet<ContextCommand>(); private String entryMessage; private int maxEntries = -1; private String maxEntriesExceededMessage = ""; private String prompt; private boolean isSecure; private Map<String, ContextCommand> aliasCommandClasses = new HashMap<String, ContextCommand>(); private Map<ContextCommandFlag, List<ContextCommand>> flaggedCntxtCmds = new HashMap<ContextCommandFlag, List<ContextCommand>>(); public Context() { } public Context(String name) { this(); this.name = name; } public void init() { mapFlaggedCommandClasses(); mapAliasedCommandClasses(); } private void mapFlaggedCommandClasses() { List<ContextCommand> contextCommandsList = new ArrayList<ContextCommand>(contextCommands); if (contextCommands != null && !contextCommands.isEmpty()) { Collections.sort(contextCommandsList, new Comparator<ContextCommand>() { @Override public int compare(ContextCommand cntxtCmd1, ContextCommand cntxtCmd2) { int sequence1 = cntxtCmd1.getSequence(); int sequence2 = cntxtCmd2.getSequence(); // sort in reverse order except zero is always last if (sequence1 == 0) { return sequence2; } else if (sequence2 == 0) { return 0; } else { return sequence1 - sequence2; } } }); for (ContextCommand contextCommand : contextCommandsList) { mapFlaggedContxtCommands(contextCommand); } } } private void mapFlaggedContxtCommands(ContextCommand contextCommand) { List<ContextCommand> flaggedCntxtCmdsList; ContextCommandFlag flag = contextCommand.getContextCommandFlag(); if (flag != null) { flaggedCntxtCmdsList = this.flaggedCntxtCmds.get(flag); if (flaggedCntxtCmdsList == null) { flaggedCntxtCmdsList = new ArrayList<ContextCommand>(); } flaggedCntxtCmdsList.add(contextCommand); this.flaggedCntxtCmds.put(flag, flaggedCntxtCmdsList); } } private void mapAliasedCommandClasses() { if (contextCommands != null) { for (ContextCommand contextCommand : contextCommands) { for (ContextCommandAlias alias : contextCommand.getAliases()) { aliasCommandClasses.put(alias.getAlias(), contextCommand); } } } } @Id @GeneratedValue @Column(name = "id") public long getId() { return id; } protected void setId(long id) { this.id = id; } @Column(name = "name") public String getName() { return name; } public void setName(String name) { this.name = name; } @Column(name = "entry_message") public String getEntryMessage() { return entryMessage; } public void setEntryMessage(String entryMessage) { this.entryMessage = entryMessage; } @Column(name = "max_entries") public int getMaxEntries() { return maxEntries; } public void setMaxEntries(int maxEntries) { this.maxEntries = maxEntries; } @Column(name = "max_entries_exceeded_message") public String getMaxEntriesExceededMessage() { return maxEntriesExceededMessage; } public void setMaxEntriesExceededMessage(String maxEntriesExceededMessage) { this.maxEntriesExceededMessage = maxEntriesExceededMessage; } // allows the user to have a generic prompt instead of a specific prompt command @Column(name = "prompt") public String getPrompt() { return prompt; } public void setPrompt(String prompt) { this.prompt = prompt; } @Column(name = "is_secure") public boolean isSecure() { return isSecure; } public void setSecure(boolean isSecure) { this.isSecure = isSecure; } // maps to the context_group that holds this context's children @OneToOne(targetEntity = ContextGroup.class, cascade = CascadeType.ALL, optional = true) @JoinColumn(name = "child_group_id") public ContextGroup getChildGroup() { return childGroup; } public void setChildGroup(ContextGroup childGroup) { this.childGroup = childGroup; } // maps to the group that holds the contexts for this context's parent and siblings @ManyToOne @JoinColumn(name = "parent_group_id", nullable = true) public ContextGroup getParentGroup() { return parentGroup; } public void setParentGroup(ContextGroup parentGroup) { this.parentGroup = parentGroup; } @OneToMany(mappedBy = ContextCommand.CONTEXT_PROPERTY, cascade = CascadeType.ALL, fetch = FetchType.EAGER) public Set<ContextCommand> getContextCommands() { return contextCommands; } public void setContextCommands(Set<ContextCommand> contextCommands) { this.contextCommands = contextCommands; } @Transient public List<ContextCommand> getFlaggedContextCommands(ContextCommandFlag flag) { return flaggedCntxtCmds.get(flag); } @Transient public Map<String, ContextCommand> getAliasContextCommands() { return aliasCommandClasses; } @Transient public ContextCommand getContextCommandForAlias(String alias) { return aliasCommandClasses.get(alias); } @Override public boolean equals(Object obj) { return Context.class.isAssignableFrom(obj.getClass()) && ((Context) obj).getId() == id; } }
gpl-3.0
RtcNbClient/RtcNbClient
RtcNbClientWorkItems/RtcNbClientWorkItemsBridge/src/main/java/pl/edu/amu/wmi/kino/rtc/client/queries/model/internal/attributes/providers/lookup/IterationQueryAttributeLookupProvider.java
10671
/* * Copyright (C) 2009-2011 RtcNbClient Team (http://rtcnbclient.wmi.amu.edu.pl/) * * This file is part of RtcNbClient. * * RtcNbClient is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * RtcNbClient is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with RtcNbClient. If not, see <http://www.gnu.org/licenses/>. */ package pl.edu.amu.wmi.kino.rtc.client.queries.model.internal.attributes.providers.lookup; import java.awt.EventQueue; import java.awt.Image; import java.util.ArrayList; import org.openide.util.ImageUtilities; import org.openide.util.Lookup; import org.openide.util.lookup.AbstractLookup; import org.openide.util.lookup.InstanceContent; import pl.edu.amu.wmi.kino.rtc.client.facade.api.common.ActiveProjectArea; import pl.edu.amu.wmi.kino.rtc.client.facade.api.common.process.DevelopmentLine; import pl.edu.amu.wmi.kino.rtc.client.facade.api.common.process.Iteration; import pl.edu.amu.wmi.kino.rtc.client.facade.api.common.process.ProcessManager; import pl.edu.amu.wmi.kino.rtc.client.facade.impl.common.process.IterationImpl; import pl.edu.amu.wmi.kino.rtc.client.facade.impl.connections.ActiveProjectAreaImpl; import pl.edu.amu.wmi.kino.rtc.client.queries.model.attributes.RtcQueryAttributeValue; import pl.edu.amu.wmi.kino.rtc.client.queries.model.attributes.values.RtcQueryAttributePossibleValues; import pl.edu.amu.wmi.kino.rtc.client.queries.model.attributes.values.RtcQueryAttributePrefferedValues; import pl.edu.amu.wmi.kino.rtc.client.queries.model.internal.attributes.providers.RtcQueryAttributeLookupProvider; import pl.edu.amu.wmi.kino.rtc.client.queries.model.internal.attributes.providers.ValueCreator; import pl.edu.amu.wmi.kino.rtc.client.queries.model.internal.attributes.values.RtcQueryAttributeValueImpl; import pl.edu.amu.wmi.kino.rtc.client.workitems.attributes.values.impl.RtcIterationPossibleValues; import com.ibm.team.process.common.IIterationHandle; import com.ibm.team.workitem.common.expression.IQueryableAttribute; public class IterationQueryAttributeLookupProvider implements RtcQueryAttributeLookupProvider { private IQueryableAttribute attribute; private ActiveProjectAreaImpl area; public IterationQueryAttributeLookupProvider(IQueryableAttribute attribute, ActiveProjectArea area) { this.attribute = attribute; this.area = (ActiveProjectAreaImpl) area; } @Override public Lookup createLookup() { InstanceContent ic = new InstanceContent(); ic.add(new IterationPossibleValues(area)); ic.add(new IterationPrefferedValues(area)); return new AbstractLookup(ic); } } class IterationPrefferedValues implements RtcQueryAttributePrefferedValues { private ActiveProjectAreaImpl area; public IterationPrefferedValues(ActiveProjectAreaImpl area) { this.area = area; } @Override public RtcQueryAttributeValue[] getValues() { assert (!EventQueue.isDispatchThread()); RtcIterationPossibleValues pv = new RtcIterationPossibleValues(area); ArrayList<RtcQueryAttributeValueImpl> impls2 = new ArrayList<RtcQueryAttributeValueImpl>(); for (DevelopmentLine dl : pv.getPossibleValues()) { impls2.add(new DevelopmentLineValueImpl(dl)); } return impls2.toArray(new RtcQueryAttributeValue[] {}); } @Override public Image getIconFor(RtcQueryAttributeValue value) throws IllegalArgumentException { if (value instanceof IterationValueImpl) { IterationImpl iter = ((IterationValueImpl) value).getRtcIteration(); if (iter.isArchived()) { return ImageUtilities .loadImage("pl/edu/amu/wmi/kino/rtc/client/queries/model/internal/iteration_archived_obj.gif"); } else { return ImageUtilities .loadImage("pl/edu/amu/wmi/kino/rtc/client/queries/model/internal/iteration_obj.gif"); } } else { if (value instanceof DevelopmentLineValueImpl) { return ImageUtilities .loadImage("pl/edu/amu/wmi/kino/rtc/client/queries/model/internal/project_devline_obj.gif"); } } throw new IllegalArgumentException(); } @Override public String getDisplayName(RtcQueryAttributeValue value) throws IllegalArgumentException { if (value instanceof IterationValueImpl) { return ((IterationValueImpl) value).getRtcIteration().getName(); } else { if (value instanceof DevelopmentLineValueImpl) { return ((DevelopmentLineValueImpl) value).getLine().getName(); } } throw new IllegalArgumentException(); } @Override public RtcQueryAttributeValue[] getChildValues(RtcQueryAttributeValue value) throws IllegalArgumentException { assert (!EventQueue.isDispatchThread()); ProcessManager pm = area.getLookup().lookup(ProcessManager.class); if (value instanceof DevelopmentLineValueImpl) { ArrayList<RtcQueryAttributeValue> chs = new ArrayList<RtcQueryAttributeValue>(); DevelopmentLine line = ((DevelopmentLineValueImpl) value).getLine(); for (Iteration impl : pm.getIterations(line)) { if (impl instanceof IterationImpl) { if (!impl.isArchived()) { chs.add(new IterationValueImpl((IterationImpl) impl)); } } } return chs.toArray(new RtcQueryAttributeValue[] {}); } else { ArrayList<RtcQueryAttributeValue> chs = new ArrayList<RtcQueryAttributeValue>(); if (value instanceof IterationValueImpl) { IterationValueImpl impl = (IterationValueImpl) value; for (Iteration it : pm.getIterations(impl.getRtcIteration())) { if (it instanceof IterationImpl) { if (!it.isArchived()) { chs.add(new IterationValueImpl((IterationImpl) it)); } } } return chs.toArray(new RtcQueryAttributeValue[] {}); } } throw new IllegalArgumentException(); } @Override public boolean isValueSelectable(RtcQueryAttributeValue value) throws IllegalArgumentException { if (value instanceof DevelopmentLineValueImpl) { return false; } else { if (value instanceof IterationValueImpl) { return true; } } throw new IllegalArgumentException(); } } class IterationPossibleValues implements RtcQueryAttributePossibleValues, ValueCreator { private ActiveProjectAreaImpl area; public IterationPossibleValues(ActiveProjectAreaImpl area) { this.area = area; } @Override public DevelopmentLineValueImpl[] getValues() { assert (!EventQueue.isDispatchThread()); RtcIterationPossibleValues pv = new RtcIterationPossibleValues(area); ArrayList<DevelopmentLineValueImpl> impls2 = new ArrayList<DevelopmentLineValueImpl>(); for (DevelopmentLine dl : pv.getPossibleValues()) { impls2.add(new DevelopmentLineValueImpl(dl)); } return impls2.toArray(new DevelopmentLineValueImpl[] {}); } @Override public Image getIconFor(RtcQueryAttributeValue value) throws IllegalArgumentException { if (value instanceof IterationValueImpl) { IterationImpl iter = ((IterationValueImpl) value).getRtcIteration(); if (iter.isArchived()) { return ImageUtilities .loadImage("pl/edu/amu/wmi/kino/rtc/client/queries/model/internal/iteration_archived_obj.gif"); } else { return ImageUtilities .loadImage("pl/edu/amu/wmi/kino/rtc/client/queries/model/internal/iteration_obj.gif"); } } else { if (value instanceof DevelopmentLineValueImpl) { return ImageUtilities .loadImage("pl/edu/amu/wmi/kino/rtc/client/queries/model/internal/project_devline_obj.gif"); } } throw new IllegalArgumentException(); } @Override public String getDisplayName(RtcQueryAttributeValue value) throws IllegalArgumentException { if (value instanceof IterationValueImpl) { return ((IterationValueImpl) value).getRtcIteration().getName(); } else { if (value instanceof DevelopmentLineValueImpl) { return ((DevelopmentLineValueImpl) value).getLine().getName(); } } throw new IllegalArgumentException(); } @Override public IterationValueImpl[] getChildValues(RtcQueryAttributeValue value) throws IllegalArgumentException { assert (!EventQueue.isDispatchThread()); ProcessManager pm = area.getLookup().lookup(ProcessManager.class); if (value instanceof DevelopmentLineValueImpl) { ArrayList<IterationValueImpl> chs = new ArrayList<IterationValueImpl>(); DevelopmentLine line = ((DevelopmentLineValueImpl) value).getLine(); for (Iteration impl : pm.getIterations(line)) { if (impl instanceof IterationImpl) { chs.add(new IterationValueImpl((IterationImpl) impl)); } } return chs.toArray(new IterationValueImpl[] {}); } else { if (value instanceof IterationValueImpl) { ArrayList<IterationValueImpl> chs = new ArrayList<IterationValueImpl>(); IterationImpl impl = ((IterationValueImpl) value) .getRtcIteration(); for (Iteration it : pm.getIterations(impl)) { if (it instanceof IterationImpl) { if (!it.isArchived()) { chs.add(new IterationValueImpl((IterationImpl) it)); } } } return chs.toArray(new IterationValueImpl[] {}); } } throw new IllegalArgumentException(); } @Override public RtcQueryAttributeValue getValueForObject(Object obj) throws IllegalArgumentException { if (obj instanceof IIterationHandle) { IIterationHandle handle = (IIterationHandle) obj; for (DevelopmentLineValueImpl val : getValues()) { for (IterationValueImpl iter : getChildValues(val)) { if (iter.getRtcIteration().getIIteration().getItemId() .getUuidValue() .equals(handle.getItemId().getUuidValue())) { return iter; } } } } throw new IllegalArgumentException(); } @Override public boolean isValueSelectable(RtcQueryAttributeValue value) throws IllegalArgumentException { if (value instanceof DevelopmentLineValueImpl) { return false; } else { if (value instanceof IterationValueImpl) { return true; } } throw new IllegalArgumentException(); } } class IterationValueImpl extends RtcQueryAttributeValueImpl { private IterationImpl wi; public IterationValueImpl(IterationImpl wi) { super(wi.getIIteration()); this.wi = wi; } public IterationImpl getRtcIteration() { return wi; } } class DevelopmentLineValueImpl extends RtcQueryAttributeValueImpl { private DevelopmentLine val; public DevelopmentLineValueImpl(DevelopmentLine rtcValue) { super(null); this.val = rtcValue; } public DevelopmentLine getLine() { return val; } }
gpl-3.0
wattdepot/wattdepot
src/test/java/org/wattdepot/server/measurement/pruning/TestMeasurementGarbageCollector.java
12095
/** * TestMeasurementGarbageCollector.java This file is part of WattDepot. * * Copyright (C) 2014 Cam Moore * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ package org.wattdepot.server.measurement.pruning; import static org.junit.Assert.assertNotNull; import static org.junit.Assert.assertTrue; import java.util.HashSet; import java.util.List; import javax.measure.unit.Unit; import javax.xml.datatype.XMLGregorianCalendar; import org.junit.After; import org.junit.Before; import org.junit.BeforeClass; import org.junit.Test; import org.wattdepot.common.domainmodel.Depository; import org.wattdepot.common.domainmodel.InstanceFactory; import org.wattdepot.common.domainmodel.Measurement; import org.wattdepot.common.domainmodel.MeasurementPruningDefinition; import org.wattdepot.common.domainmodel.MeasurementType; import org.wattdepot.common.domainmodel.Organization; import org.wattdepot.common.domainmodel.Sensor; import org.wattdepot.common.domainmodel.SensorModel; import org.wattdepot.common.domainmodel.UserInfo; import org.wattdepot.common.domainmodel.UserPassword; import org.wattdepot.common.exception.BadSlugException; import org.wattdepot.common.exception.IdNotFoundException; import org.wattdepot.common.exception.MeasurementTypeException; import org.wattdepot.common.exception.MisMatchedOwnerException; import org.wattdepot.common.exception.UniqueIdException; import org.wattdepot.common.util.DateConvert; import org.wattdepot.common.util.UnitsHelper; import org.wattdepot.common.util.tstamp.Tstamp; import org.wattdepot.server.ServerProperties; import org.wattdepot.server.WattDepotPersistence; import org.wattdepot.server.depository.impl.hibernate.WattDepotPersistenceImpl; /** * TestMeasurementGarbageCollector test cases for the * MeasurementGarbageCollector class. * * @author Cam Moore * */ public class TestMeasurementGarbageCollector { private static WattDepotPersistenceImpl impl; private static UserInfo testUser; private static UserPassword testPassword; private static Organization testOrg; private static ServerProperties properties; private static Depository depository; private static Sensor sensor; private static MeasurementPruningDefinition gcd; private XMLGregorianCalendar now; private XMLGregorianCalendar start; private XMLGregorianCalendar end; private int totalMeasurements; /** * Sets up the WattDepotPersistenceImpl using test properties. */ @BeforeClass public static void setupImpl() throws Exception { properties = new ServerProperties(); properties.setTestProperties(); impl = new WattDepotPersistenceImpl(properties); testUser = InstanceFactory.getUserInfo(); testPassword = InstanceFactory.getUserPassword(); testOrg = InstanceFactory.getOrganization(); // shouldn't have to do this. testUser.setOrganizationId(testOrg.getId()); // prime the MeasurementTypes UnitsHelper.quantities.containsKey("W"); } /** * @throws java.lang.Exception if there is a problem. */ @Before public void setUp() throws Exception { // 1. define the organization w/o any users. try { impl.getOrganization(testOrg.getId(), true); } catch (IdNotFoundException e) { try { impl.defineOrganization(testOrg.getId(), testOrg.getName(), new HashSet<String>()); } catch (BadSlugException e1) { e1.printStackTrace(); } catch (IdNotFoundException e1) { e1.printStackTrace(); } } // 2. define the user try { impl.getUser(testUser.getUid(), testUser.getOrganizationId(), true); } catch (IdNotFoundException e) { try { impl.defineUserInfo(testUser.getUid(), testUser.getFirstName(), testUser.getLastName(), testUser.getEmail(), testUser.getOrganizationId(), testUser.getProperties(), testUser.getPassword()); } catch (IdNotFoundException e1) { // Shouldn't happen! e1.printStackTrace(); } } // 3. update the organization try { impl.updateOrganization(testOrg); } catch (IdNotFoundException e1) { // this shouldn't happen e1.printStackTrace(); } addSensor(); addMeasurementType(); addDepository(); addMeasurementPruningDefinition(); } /** * @throws java.lang.Exception if there is a problem. */ @After public void tearDown() throws Exception { Organization testO; try { testO = impl.getOrganization(testOrg.getId(), true); if (testO != null) { impl.deleteOrganization(testO.getId()); } } catch (IdNotFoundException e) { e.printStackTrace(); } try { impl.deleteOrganization(InstanceFactory.getUserInfo2().getOrganizationId()); } catch (IdNotFoundException e1) { // NOPMD // not a problem } UserPassword testP; try { testP = impl.getUserPassword(testPassword.getUid(), testPassword.getOrganizationId(), true); if (testP != null) { impl.deleteUserPassword(testP.getUid(), testPassword.getOrganizationId()); } } catch (IdNotFoundException e) { // NOPMD // e.printStackTrace(); } UserInfo testU; try { testU = impl.getUser(testUser.getUid(), testUser.getOrganizationId(), true); if (testU != null) { impl.deleteUser(testU.getUid(), testU.getOrganizationId()); } } catch (IdNotFoundException e) { // NOPMD // e.printStackTrace(); } } /** * Test method for * {@link org.wattdepot.server.measurement.pruning.MeasurementPruner#getMeasurementsToDelete()} * . * * @throws Exception if there is a problem. */ @Test public void testGetMeasurementsToDelete() throws Exception { populateMeasurements(2); MeasurementPruner mgc = new MeasurementPruner(properties, gcd.getId(), gcd.getOrganizationId(), false); List<Measurement> toDel = mgc.getMeasurementsToDelete(); assertTrue(toDel.size() > 0); assertTrue(toDel.size() < totalMeasurements); } /** * @throws Exception if there is a problem. */ @Test public void testMeasurementPruning() throws Exception { populateMeasurements(2); MeasurementPruner mgc = new MeasurementPruner(properties, gcd.getId(), gcd.getOrganizationId(), false); int numToDel = mgc.getMeasurementsToDelete().size(); mgc.run(); List<Measurement> toDel = mgc.getMeasurementsToDelete(); assertTrue(toDel.size() == 0); WattDepotPersistence p = mgc.getPersistance(); List<Measurement> data = p.getMeasurements(gcd.getDepositoryId(), gcd.getOrganizationId(), gcd.getSensorId(), false); assertNotNull(data); assertTrue(data.size() < totalMeasurements); assertTrue(data.size() == totalMeasurements - numToDel); } /** * @throws UniqueIdException if the Model is already defined. */ private void addSensorModel() throws UniqueIdException { SensorModel model = InstanceFactory.getSensorModel(); try { impl.getSensorModel(model.getId(), true); } catch (IdNotFoundException e1) { try { impl.defineSensorModel(model.getId(), model.getName(), model.getProtocol(), model.getType(), model.getVersion()); } catch (BadSlugException e) { e.printStackTrace(); } } } /** * @throws MisMatchedOwnerException if there is a mismatch in the ownership. * @throws UniqueIdException if the Sensor is already defined. * @throws IdNotFoundException if the SensorLocation or SensorModel aren't * defined. */ private void addSensor() throws MisMatchedOwnerException, UniqueIdException, IdNotFoundException { addSensorModel(); TestMeasurementGarbageCollector.sensor = InstanceFactory.getSensor(); try { impl.getSensor(sensor.getId(), sensor.getOrganizationId(), true); } catch (IdNotFoundException e) { try { impl.defineSensor(sensor.getId(), sensor.getName(), sensor.getUri(), sensor.getModelId(), sensor.getProperties(), sensor.getOrganizationId()); } catch (BadSlugException e1) { e1.printStackTrace(); } } } /** * @throws UniqueIdException if the MeasurementType is already defined. */ private void addMeasurementType() throws UniqueIdException { MeasurementType type = InstanceFactory.getMeasurementType(); try { impl.getMeasurementType(type.getId(), true); } catch (IdNotFoundException e1) { try { impl.defineMeasurementType(type.getId(), type.getName(), type.getUnits()); } catch (BadSlugException e) { e.printStackTrace(); } } } /** * @throws UniqueIdException if there is already a Depository defined. * @throws IdNotFoundException if there are problems with the ids. */ private void addDepository() throws UniqueIdException, IdNotFoundException { TestMeasurementGarbageCollector.depository = InstanceFactory.getDepository(); try { impl.getDepository(depository.getId(), depository.getOrganizationId(), true); } catch (IdNotFoundException e) { try { impl.defineDepository(depository.getId(), depository.getName(), depository.getMeasurementType(), depository.getOrganizationId()); } catch (BadSlugException e1) { e1.printStackTrace(); } } } /** * Adds the predefined MeasurementPruningDefinition. */ private void addMeasurementPruningDefinition() { TestMeasurementGarbageCollector.gcd = InstanceFactory.getMeasurementPruningDefinition(); try { impl.getMeasurementPruningDefinition(gcd.getId(), gcd.getOrganizationId(), true); } catch (IdNotFoundException e) { try { impl.defineMeasurementPruningDefinition(gcd.getId(), gcd.getName(), gcd.getDepositoryId(), gcd.getSensorId(), gcd.getOrganizationId(), gcd.getIgnoreWindowDays(), gcd.getCollectWindowDays(), gcd.getMinGapSeconds()); } catch (UniqueIdException e1) { e1.printStackTrace(); } catch (BadSlugException e1) { e1.printStackTrace(); } catch (IdNotFoundException e1) { e1.printStackTrace(); } } } /** * @param time The time of the measurement. * @return A fake measurement at the given time. */ private Measurement makeMeasurement(XMLGregorianCalendar time) { return new Measurement(InstanceFactory.getSensor().getId(), DateConvert.convertXMLCal(time), 123.0, Unit.valueOf(InstanceFactory.getMeasurementType().getUnits())); } /** * @param minBetween The number of minutes between measurements. * @throws MeasurementTypeException This shouldn't happen. * @throws IdNotFoundException If there is a problem with the ids. This * shouldn't happen. */ private void populateMeasurements(int minBetween) throws MeasurementTypeException, IdNotFoundException { // Need to add high frequency Measurements to the database. now = Tstamp.makeTimestamp(); start = Tstamp.incrementDays(now, -1 * gcd.getIgnoreWindowDays()); end = Tstamp.incrementDays(start, -1 * gcd.getCollectWindowDays()); List<XMLGregorianCalendar> measTimes = Tstamp.getTimestampList(end, now, minBetween); totalMeasurements = measTimes.size(); for (XMLGregorianCalendar cal : measTimes) { impl.putMeasurement(depository.getId(), depository.getOrganizationId(), makeMeasurement(cal)); } } }
gpl-3.0
romeikat/datamessie
datamessie-core/src/main/java/com/romeikat/datamessie/core/base/util/model/LongModel.java
1741
package com.romeikat.datamessie.core.base.util.model; /*- * ============================LICENSE_START============================ * data.messie (core) * ===================================================================== * Copyright (C) 2013 - 2017 Dr. Raphael Romeikat * ===================================================================== * This program is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program. If not, see <http://www.gnu.org/licenses/gpl-3.0.html>. * =============================LICENSE_END============================= */ import org.apache.wicket.model.IModel; import org.apache.wicket.model.LoadableDetachableModel; import org.apache.wicket.model.Model; import com.romeikat.datamessie.core.base.util.converter.LongConverter; public class LongModel extends LoadableDetachableModel<String> { private static final long serialVersionUID = 1L; private final IModel<Long> model; public LongModel(final IModel<Long> model) { this.model = model; } public LongModel(final Long value) { this(Model.of(value)); } @Override protected String load() { final Long i = model.getObject(); return LongConverter.INSTANCE.convertToString(i); } }
gpl-3.0
ENGYS/HELYX-OS
src/eu/engys/core/controller/KillCommandOS.java
2554
/******************************************************************************* * | o | * | o o | HELYX-OS: The Open Source GUI for OpenFOAM | * | o O o | Copyright (C) 2012-2016 ENGYS | * | o o | http://www.engys.com | * | o | | * |---------------------------------------------------------------------------| * | License | * | This file is part of HELYX-OS. | * | | * | HELYX-OS is free software; you can redistribute it and/or modify it | * | under the terms of the GNU General Public License as published by the | * | Free Software Foundation; either version 2 of the License, or (at your | * | option) any later version. | * | | * | HELYX-OS is distributed in the hope that it will be useful, but WITHOUT | * | ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or | * | FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License | * | for more details. | * | | * | You should have received a copy of the GNU General Public License | * | along with HELYX-OS; if not, write to the Free Software Foundation, | * | Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA | *******************************************************************************/ package eu.engys.core.controller; import javax.swing.JOptionPane; import eu.engys.util.ui.UiUtil; public class KillCommandOS implements Runnable { private Controller controller; public KillCommandOS(Controller controller) { this.controller = controller; } @Override public void run() { int retVal = JOptionPane.showConfirmDialog(UiUtil.getActiveWindow(), "Stop execution?", "Close Monitor", JOptionPane.YES_NO_OPTION, JOptionPane.WARNING_MESSAGE); if (retVal == JOptionPane.YES_OPTION) { controller.kill(); } } }
gpl-3.0
noqisofon/K-Visions
java/src/org/kvisions/mobius/Mobius.java
3256
package org.kvisions.mobius; import org.kvisions.geom.Complex; import org.kvisions.geom.schottky.TwinCircles; import org.kvisions.groups.SL2C; import org.kvisions.schottky.figure.Circle; public class Mobius { private Mobius(){ } public static Complex getPlusFixPoint(SL2C t){ Complex num = t.a.sub(t.d).add( Complex.sqrt(t.trace().mult(t.trace()).sub(4.0f))); return num.div(t.c.mult(2.0f)); } public static Complex getMinusFixPoint(SL2C t){ Complex num = t.a.sub(t.d).sub( Complex.sqrt(t.trace().mult(t.trace()).sub(4.0f))); return num.div(t.c.mult(2.0f)); } public static Complex onPoint(SL2C t, Complex z){ if(z.isInfinity()){ if(!t.c.isZero()){ return Complex.div(t.a, t.c); }else{ return Complex.INFINITY; } }else{ Complex numerix = Complex.add( Complex.mult(t.a, z), t.b); Complex denominator = Complex.add( Complex.mult(t.c, z), t.d); if(denominator.isZero()){ return Complex.INFINITY; }else{ return Complex.div( numerix, denominator); } } } public static SL2C getSymmetricTransformation(Circle c1, Circle c2){ Complex P = c1.getCenter(); double r = c1.getR(); Complex Q = c2.getCenter(); double s = c2.getR(); return new SL2C( Q, new Complex(r * s, 0).sub(P.mult(Q)), Complex.ONE, P.mult(-1)); } public static SL2C getSymmetricTransformation(Circle c1, Circle c2, Complex u, Complex v){ Complex P = c1.getCenter(); double r = c1.getR(); Complex Q = c2.getCenter(); double s = c2.getR(); return new SL2C( u.conjugate().mult(s), v.conjugate().mult(r).sub(u.conjugate().mult(P).mult(s)).sub(P.mult(Q).mult(u)).add(v.mult(Q.mult(r))), u, v.mult(r).sub(u.mult(P))); } public static Circle onCircle(SL2C t, Circle c){ Complex rad = new Complex(c.getR(), 0); Complex z = c.getCenter().sub( rad.mult(rad).div( Complex.conjugate(t.d.div(t.c).add(c.getCenter())))); Complex newCenter = onPoint(t, z); double newR = Complex.abs(newCenter.sub( onPoint(t, c.getCenter().add(c.getR())))); return new Circle(newCenter, newR); } public static SL2C getMobiusTransform(Circle c1, Circle c2){ Complex z1 = c1.getP1(); Complex z2 = c1.getP2(); Complex z3 = c1.getP3(); Complex w1 = c2.getP1(); Complex w2 = c2.getP2(); Complex w3 = c2.getP3(); SL2C m1 = new SL2C( z2.sub(z3), z1.mult(-1).mult(z2.sub(z3)), z2.sub(z1), z3.mult(-1).mult(z2.sub(z1))); SL2C m2 = new SL2C( w2.sub(w3), w1.mult(-1).mult(w2.sub(w3)), w2.sub(w1), w3.mult(-1).mult(w2.sub(w1))); return m2.inverse().mult(m1); } public static SL2C getMobiusTransform(TwinCircles tc){ Circle c1 = tc.getC1(); Circle c2 = tc.getC2(); Complex z1 = c1.getP1(); Complex z2 = c1.getP2(); Complex z3 = c1.getP3(); Complex w1 = c2.getP1(); Complex w2 = c2.getP2(); Complex w3 = c2.getP3(); // System.out.println("w2"+ w2); // System.out.println("w3"+ w3); SL2C m1 = new SL2C( z2.sub(z3), z1.mult(-1).mult(z2.sub(z3)), z2.sub(z1), z3.mult(-1).mult(z2.sub(z1))); // System.out.println("m1 "+ m1); SL2C m2 = new SL2C( w2.sub(w3), w1.mult(-1).mult(w2.sub(w3)), w2.sub(w1), w3.mult(-1).mult(w2.sub(w1))); // System.out.println("m2 inv"); // System.out.println(m2.inverse()); return m2.inverse().mult(m1); } }
gpl-3.0
TheBusyBiscuit/Slimefun4
src/main/java/io/github/thebusybiscuit/slimefun4/core/services/AutoSavingService.java
2884
package io.github.thebusybiscuit.slimefun4.core.services; import java.util.HashSet; import java.util.Iterator; import java.util.Set; import java.util.logging.Level; import javax.annotation.Nonnull; import org.bukkit.Bukkit; import org.bukkit.World; import org.bukkit.block.Block; import org.bukkit.entity.Player; import io.github.thebusybiscuit.slimefun4.api.player.PlayerProfile; import io.github.thebusybiscuit.slimefun4.implementation.SlimefunPlugin; import me.mrCookieSlime.Slimefun.api.BlockStorage; /** * This Service is responsible for automatically saving {@link Player} and {@link Block} * data. * * @author TheBusyBiscuit * */ public class AutoSavingService { private int interval; /** * This method starts the {@link AutoSavingService} with the given interval. * * @param plugin * The current instance of Slimefun * @param interval * The interval in which to run this task */ public void start(@Nonnull SlimefunPlugin plugin, int interval) { this.interval = interval; plugin.getServer().getScheduler().runTaskTimer(plugin, this::saveAllPlayers, 2000L, interval * 60L * 20L); plugin.getServer().getScheduler().runTaskTimerAsynchronously(plugin, this::saveAllBlocks, 2000L, interval * 60L * 20L); } /** * This method saves every {@link PlayerProfile} in memory and removes profiles * that were marked for deletion. */ private void saveAllPlayers() { Iterator<PlayerProfile> iterator = PlayerProfile.iterator(); int players = 0; while (iterator.hasNext()) { PlayerProfile profile = iterator.next(); if (profile.isDirty()) { players++; profile.save(); } if (profile.isMarkedForDeletion()) { iterator.remove(); } } if (players > 0) { SlimefunPlugin.logger().log(Level.INFO, "Auto-saved all player data for {0} player(s)!", players); } } /** * This method saves the data of every {@link Block} marked dirty by {@link BlockStorage}. */ private void saveAllBlocks() { Set<BlockStorage> worlds = new HashSet<>(); for (World world : Bukkit.getWorlds()) { BlockStorage storage = BlockStorage.getStorage(world); if (storage != null) { storage.computeChanges(); if (storage.getChanges() > 0) { worlds.add(storage); } } } if (!worlds.isEmpty()) { SlimefunPlugin.logger().log(Level.INFO, "Auto-saving block data... (Next auto-save: {0}m)", interval); for (BlockStorage storage : worlds) { storage.save(); } } BlockStorage.saveChunks(); } }
gpl-3.0
langurmonkey/rts-engine
core/src/rts/arties/util/validator/IValidator.java
275
/* * This file is part of Gaia Sky, which is released under the Mozilla Public License 2.0. * See the file LICENSE.md in the project root for full license details. */ package rts.arties.util.validator; public interface IValidator { boolean validate(String value); }
gpl-3.0
LegendOnline/InventoryAPI
src/main/java/com/minecraftlegend/inventoryapi/utils/Vector2i.java
3059
package com.minecraftlegend.inventoryapi.utils; import org.apache.commons.lang3.Validate; /** * @Author Sauerbier | Jan * @Copyright 2016 by Jan Hof * All rights reserved. **/ public class Vector2i implements Cloneable { private int x, y; public Vector2i( int x, int y ) { this.x = x; this.y = y; } public Vector2i( Vector2i vec ) { this.x = vec.getX(); this.y = vec.getY(); } public void add( Vector2i vector2i ) { x += vector2i.getX(); y += vector2i.getY(); } public void sub( Vector2i vec ) { this.x -= vec.getX(); this.y -= vec.getY(); } public void multiply( Vector2i vec ) { x *= vec.getX(); y *= vec.getY(); } public void multiply( int m ) { x *= m; y *= m; } public void divide( Vector2i vec ) { x /= vec.getX(); y /= vec.getY(); } public void divide( int m ) { x /= m; y /= m; } public int scalar( Vector2i vec ) { return ( x + vec.getX() ) * ( y + vec.getY() ); } public double distance( Vector2i vec ) { int dx = vec.getX() - x; int dy = vec.getY() - y; return new Vector2i( dx, dy ).length(); } public double angle( Vector2i vec ) { double dx = vec.getX() - x; double dy = vec.getY() - y; return Math.atan2( dy, dx ); } public Vector2i toPixelPrecision( int pixelMask ) { return new Vector2i( (int) x << pixelMask, (int) y << pixelMask ); } public Vector2i toBlockPrecision( int pixelMask ) { return new Vector2i( (int) x >> pixelMask, (int) y >> pixelMask ); } public int toInventoryPosition(){ return x + y * 9; } public Vector2i max( Vector2i vec ) { if ( x + y > vec.getX() + vec.getY() ) { return this; } else return vec; } public Vector2i min( Vector2i vec ) { if ( x + y < vec.getX() + vec.getY() ) { return this; } else return vec; } public double length() { return Math.sqrt( x * x + y * y ); } @Override public Vector2i clone() { try { return (Vector2i) super.clone(); } catch ( CloneNotSupportedException e ) { e.printStackTrace(); } return null; } @Override public boolean equals( Object obj ) { Validate.notNull( obj); Validate.isInstanceOf( Vector2i.class, obj, "Object has to be from type Vector2i" ); Vector2i other = (Vector2i) obj; if(other.getX() != x) return false; if(other.getY() != y) return false; return true; } @Override public String toString() { return "[x:" + x + ",y:" + y + "]"; } public int getX() { return x; } public void setX( int x ) { this.x = x; } public int getY() { return y; } public void setY( int y ) { this.y = y; } }
gpl-3.0
dumischbaenger/ews-example
src/main/java/de/dumischbaenger/ws/ClientAccessTokenTypeType.java
1455
package de.dumischbaenger.ws; import javax.xml.bind.annotation.XmlEnum; import javax.xml.bind.annotation.XmlEnumValue; import javax.xml.bind.annotation.XmlType; /** * <p>Java-Klasse für ClientAccessTokenTypeType. * * <p>Das folgende Schemafragment gibt den erwarteten Content an, der in dieser Klasse enthalten ist. * <p> * <pre> * &lt;simpleType name="ClientAccessTokenTypeType"&gt; * &lt;restriction base="{http://www.w3.org/2001/XMLSchema}string"&gt; * &lt;enumeration value="CallerIdentity"/&gt; * &lt;enumeration value="ExtensionCallback"/&gt; * &lt;enumeration value="ScopedToken"/&gt; * &lt;/restriction&gt; * &lt;/simpleType&gt; * </pre> * */ @XmlType(name = "ClientAccessTokenTypeType") @XmlEnum public enum ClientAccessTokenTypeType { @XmlEnumValue("CallerIdentity") CALLER_IDENTITY("CallerIdentity"), @XmlEnumValue("ExtensionCallback") EXTENSION_CALLBACK("ExtensionCallback"), @XmlEnumValue("ScopedToken") SCOPED_TOKEN("ScopedToken"); private final String value; ClientAccessTokenTypeType(String v) { value = v; } public String value() { return value; } public static ClientAccessTokenTypeType fromValue(String v) { for (ClientAccessTokenTypeType c: ClientAccessTokenTypeType.values()) { if (c.value.equals(v)) { return c; } } throw new IllegalArgumentException(v); } }
gpl-3.0
tdudziak/gps-lock-lock
src/com/github/tdudziak/gps_lock_lock/NotificationUi.java
3691
package com.github.tdudziak.gps_lock_lock; import android.app.Notification; import android.app.NotificationManager; import android.app.PendingIntent; import android.app.Service; import android.content.BroadcastReceiver; import android.content.Context; import android.content.Intent; import android.content.IntentFilter; import android.support.v4.content.LocalBroadcastManager; import android.util.Log; class NotificationUi { private static final String TAG = "NotificationUi"; private static final int NOTIFICATION_ID = 1; private Notification mNotification; private NotificationManager mNotificationManager; private PendingIntent mIntent; private BroadcastReceiver mReceiver; private Service mService; private boolean mServiceIsForeground = false; private boolean mIsEnabled = false; public NotificationUi(Service service) { mService = service; int icon = R.drawable.ic_stat_notification; CharSequence ticker = mService.getText(R.string.notification_ticker); mNotificationManager = (NotificationManager) mService.getSystemService(Context.NOTIFICATION_SERVICE); Intent notificationIntent = new Intent(mService, ControlActivity.class); mIntent = PendingIntent.getActivity(mService, 0, notificationIntent, 0); long now = System.currentTimeMillis(); mNotification = new Notification(icon, ticker, now); mReceiver = new BroadcastReceiver() { @Override public void onReceive(Context context, Intent intent) { int remaining = intent.getIntExtra(LockService.EXTRA_TIME_LEFT, -1); int last_fix = intent.getIntExtra(LockService.EXTRA_LAST_FIX, -1); redraw(remaining, last_fix); } }; IntentFilter filter = new IntentFilter(LockService.ACTION_UI_UPDATE); LocalBroadcastManager.getInstance(mService).registerReceiver(mReceiver, filter); } public void enable() { IntentFilter filter = new IntentFilter(LockService.ACTION_UI_UPDATE); LocalBroadcastManager.getInstance(mService).registerReceiver(mReceiver, filter); mIsEnabled = true; Log.i(TAG, "enable()"); } public void disable() { LocalBroadcastManager.getInstance(mService).unregisterReceiver(mReceiver); mServiceIsForeground = false; mIsEnabled = false; Log.i(TAG, "disable()"); } private void redraw(int remaining, int last_fix) { String title, text; if(!mIsEnabled) { // this sometimes happens when disabled while some messages are still pending return; } if(remaining <= 0) { // This *must* be the last message; hide the notification. mNotificationManager.cancel(NOTIFICATION_ID); return; } if(last_fix < 0) { title = mService.getString(R.string.notification_title_nofix); } else if(last_fix > 0) { title = String.format(mService.getString(R.string.notification_title), last_fix); } else { title = mService.getString(R.string.notification_title_1minfix); } text = String.format(mService.getString(R.string.notification_text), remaining); mNotification.setLatestEventInfo(mService, title, text, mIntent); if(mServiceIsForeground) { mNotificationManager.notify(NOTIFICATION_ID, mNotification); } else { Log.v(TAG, "First update after enable(); calling startForeground()"); mService.startForeground(NOTIFICATION_ID, mNotification); mServiceIsForeground = true; } } }
gpl-3.0
JulianKoch/de.persosim.simulator
de.persosim.simulator.test/gtTests/de/persosim/simulator/test/globaltester/perso/DefaultPersoTestPkiTemplate03Test.java
380
package de.persosim.simulator.test.globaltester.perso; import de.persosim.simulator.perso.Profile03; import de.persosim.simulator.perso.Personalization; public class DefaultPersoTestPkiTemplate03Test extends TestPersoTest { @Override public Personalization getPersonalization() { if(persoCache == null) { persoCache = new Profile03(); } return persoCache; } }
gpl-3.0