blob_id
stringlengths
40
40
language
stringclasses
1 value
repo_name
stringlengths
5
132
path
stringlengths
2
382
src_encoding
stringclasses
34 values
length_bytes
int64
9
3.8M
score
float64
1.5
4.94
int_score
int64
2
5
detected_licenses
listlengths
0
142
license_type
stringclasses
2 values
text
stringlengths
9
3.8M
download_success
bool
1 class
2eaa884b57d1ea3ef2fa1a16195bd42627266c98
Java
andryspo/Neuron-Network
/src/sample/iris/Iris.java
UTF-8
725
2.90625
3
[]
no_license
package sample.iris; import java.util.ArrayList; import java.util.List; public class Iris { public static final int COUNT_OF_PARAMS = 4; private List<Double> parameters; public Iris(List<Double> parameters) { this.parameters = parameters; } public Iris(String[] params) { parameters = new ArrayList<>(); if(params.length >= COUNT_OF_PARAMS) { parameters.add(Double.parseDouble(params[0])); parameters.add(Double.parseDouble(params[1])); parameters.add(Double.parseDouble(params[2])); parameters.add(Double.parseDouble(params[3])); } } public List<Double> getParameters() { return parameters; } }
true
d89e64ab06c216a3def130dea932a4b692e1d484
Java
toughie88/Machine-Learning-for-Malware-Data-Analysis
/WuKong/com/adobe/reader/PARSecurityManager.java
UTF-8
5,641
1.882813
2
[]
no_license
package com.adobe.reader; import android.content.Context; import android.content.res.Resources; import android.view.Display; import android.view.LayoutInflater; import android.view.MotionEvent; import android.view.OrientationEventListener; import android.view.View; import android.view.View.OnClickListener; import android.view.View.OnTouchListener; import android.view.WindowManager; import android.widget.ImageButton; import android.widget.LinearLayout; import android.widget.PopupWindow; import android.widget.PopupWindow.OnDismissListener; class PARSecurityManager implements View.OnClickListener { public static final int SECURITYLOCK_BUTTON_WIDTH = 45; private ARViewer mARContext = null; private PopupWindow mMenu; private OrientationEventListener mOrientationListener; private int mRotation; private LinearLayout mSecurityViewLayout; private boolean mShowSecurityLock = false; public PARSecurityManager(ARViewer paramARViewer, boolean paramBoolean) { this.mARContext = paramARViewer; paramARViewer = (ImageButton)this.mARContext.findViewById(2131492914); this.mShowSecurityLock = paramBoolean; if (this.mShowSecurityLock) { paramARViewer.setOnClickListener(this); paramARViewer.setVisibility(0); } for (;;) { this.mOrientationListener = new OrientationEventListener(this.mARContext) { public void onOrientationChanged(int paramAnonymousInt) { if (PARSecurityManager.this.mRotation != PARSecurityManager.this.mARContext.getWindowManager().getDefaultDisplay().getRotation()) { PARSecurityManager.this.hideSecurityView(); } } }; this.mOrientationListener.disable(); return; paramARViewer.setVisibility(8); } } private void hideSecurityView() { if (this.mMenu == null) { return; } this.mARContext.unlockToolbar(); this.mMenu.setOnDismissListener(null); this.mMenu.dismiss(); this.mSecurityViewLayout.setVisibility(8); if (!this.mARContext.isRunningOnTablet()) { this.mSecurityViewLayout.findViewById(2131493081).setVisibility(8); } ImageButton localImageButton = (ImageButton)this.mARContext.findViewById(2131492914); localImageButton.setImageResource(2130837721); localImageButton.setBackgroundResource(2130837870); this.mARContext.findViewById(2131492882).setVisibility(8); this.mMenu = null; this.mSecurityViewLayout = null; this.mOrientationListener.disable(); } private boolean isSecurityViewVisible() { if (this.mMenu == null) { return false; } return this.mMenu.isShowing(); } public void onClick(View paramView) { switch (paramView.getId()) { default: return; } if (isSecurityViewVisible()) { hideSecurityView(); return; } showSecurityView(); } public void release() { if (isSecurityViewVisible()) { hideSecurityView(); } this.mOrientationListener = null; } public boolean shouldShowSecurityLock() { return this.mShowSecurityLock; } public void showSecurityView() { if (!this.mShowSecurityLock) { return; } this.mARContext.lockToolbar(); this.mARContext.findViewById(2131492882).setVisibility(0); Object localObject = (ImageButton)this.mARContext.findViewById(2131492914); ((ImageButton)localObject).setImageResource(2130837722); ((ImageButton)localObject).setBackgroundResource(2130837869); this.mSecurityViewLayout = new LinearLayout(this.mARContext); LayoutInflater.from(this.mARContext).inflate(2130903078, this.mSecurityViewLayout); if (!this.mARContext.isRunningOnTablet()) { localObject = this.mSecurityViewLayout.findViewById(2131493081); ((View)localObject).setVisibility(0); ((View)localObject).setOnClickListener(new View.OnClickListener() { public void onClick(View paramAnonymousView) { PARSecurityManager.this.hideSecurityView(); } }); } this.mMenu = new PopupWindow(this.mARContext); this.mMenu.setBackgroundDrawable(this.mARContext.getResources().getDrawable(2130837869)); this.mMenu.setContentView(this.mSecurityViewLayout); this.mMenu.setOnDismissListener(new PopupWindow.OnDismissListener() { public void onDismiss() { PARSecurityManager.this.hideSecurityView(); } }); this.mMenu.setFocusable(true); this.mMenu.setOutsideTouchable(true); this.mMenu.setTouchInterceptor(new View.OnTouchListener() { public boolean onTouch(View paramAnonymousView, MotionEvent paramAnonymousMotionEvent) { return false; } }); this.mRotation = this.mARContext.getWindowManager().getDefaultDisplay().getRotation(); this.mOrientationListener.enable(); int i; if (this.mARContext.isRunningOnTablet()) { this.mSecurityViewLayout.measure(0, 0); i = this.mSecurityViewLayout.getMeasuredWidth(); } for (int j = this.mSecurityViewLayout.getMeasuredHeight();; j = this.mARContext.getScreenHeight()) { this.mMenu.setWidth(i); this.mMenu.setHeight(j); if (!this.mARContext.isRunningOnTablet()) { break; } localObject = (LinearLayout)this.mARContext.findViewById(2131492902); this.mMenu.showAtLocation(this.mARContext.getPageView(), 0, this.mARContext.getScreenWidth() - i, ((LinearLayout)localObject).getTop() - j); return; i = this.mARContext.getScreenWidth(); } this.mMenu.showAtLocation(this.mARContext.getPageView(), 0, 0, 0); } }
true
9a1456ca8d95c6fea9ccc1bbe37e796402787aa4
Java
AzulVega/Comision-2-Grupo-9-InstitutoAbierto
/src/instituto/vistas/AlumnosPorCurso.java
UTF-8
9,411
2.671875
3
[]
no_license
package instituto.vistas; import instituto.controlador.CursoData; import instituto.modelo.Conexion; import instituto.modelo.Curso; import java.util.ArrayList; public class AlumnosPorCurso extends javax.swing.JFrame { ArrayList<String> listaDeCursos = new ArrayList(); Conexion conexion = new Conexion(); CursoData cursoData = new CursoData(conexion); private String nombreCurso; public AlumnosPorCurso() { initComponents(); this.setLocationRelativeTo(null); this.setSize(800, 600); this.setResizable(false); llenarComboBox(); } public ArrayList<String> obtenerNombreCursos(){ ArrayList<Curso> cursos = cursoData.obtenerCursos(); // AQUI BUSCA LA LISTA DE TODOS LOS CURSOS QUE HAYA EN LA BASE DE DATOS(EL CURSODATA VA A LA BASE DE DATOS Y BUSCA TODOS LOS CURSOS Y LOS METE EN UNA IISTA DE CURSOS) for(int i=0; i < cursos.size(); i++){ // LO QUE HACE ES CON ESA LISTA DE CURSOS (CURSOS DE TIPO CURSOS) POR CADA UNO DE ELLOS LE PIDE EL NOMRBRE nombreCurso = cursos.get(i).getNombre();// ACA LE PIDE EL NOMBRE CON EL GETTTER GETNOMBRE listaDeCursos.add(nombreCurso); // A LA LSITA DE STRING (LISTADECRUSOS) LE AGREGO CADA UNO DE LOS NOMBRE DE LOS CURSOS } return listaDeCursos; } public void llenarComboBox(){ listaDeCursos = this.obtenerNombreCursos(); // ACA LLENO ESA LISTA DE NOMBRES CON TODOS LOS NOMBRES DE LOS CURSOS for(String nombreCurso:listaDeCursos){ jcbCursos.addItem(nombreCurso); // AGREGO ITEMS A LA COMBO BOX CON TODOS LOS NOMBRES DE LOS CURSOS } } @SuppressWarnings("unchecked") // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents private void initComponents() { jPanel1 = new javax.swing.JPanel(); jLabel1 = new javax.swing.JLabel(); jcbCursos = new javax.swing.JComboBox<>(); jButton1 = new javax.swing.JButton(); jbAtras = new javax.swing.JButton(); setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE); jPanel1.setBackground(new java.awt.Color(28, 134, 192)); jLabel1.setFont(new java.awt.Font("Microsoft YaHei UI Light", 1, 18)); // NOI18N jLabel1.setText("Seleccione un curso para acceder al listado de alumnos:"); jcbCursos.setFont(new java.awt.Font("Tahoma", 0, 18)); // NOI18N jcbCursos.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { jcbCursosActionPerformed(evt); } }); jButton1.setText("Aceptar"); jButton1.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { jButton1ActionPerformed(evt); } }); jbAtras.setText("Atrás"); jbAtras.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { jbAtrasActionPerformed(evt); } }); javax.swing.GroupLayout jPanel1Layout = new javax.swing.GroupLayout(jPanel1); jPanel1.setLayout(jPanel1Layout); jPanel1Layout.setHorizontalGroup( jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(jPanel1Layout.createSequentialGroup() .addGap(145, 145, 145) .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(jPanel1Layout.createSequentialGroup() .addComponent(jbAtras, javax.swing.GroupLayout.PREFERRED_SIZE, 153, javax.swing.GroupLayout.PREFERRED_SIZE) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE) .addComponent(jButton1, javax.swing.GroupLayout.PREFERRED_SIZE, 143, javax.swing.GroupLayout.PREFERRED_SIZE) .addGap(122, 122, 122)) .addGroup(jPanel1Layout.createSequentialGroup() .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addComponent(jLabel1, javax.swing.GroupLayout.DEFAULT_SIZE, 643, Short.MAX_VALUE) .addComponent(jcbCursos, javax.swing.GroupLayout.PREFERRED_SIZE, 508, javax.swing.GroupLayout.PREFERRED_SIZE)) .addContainerGap()))) ); jPanel1Layout.setVerticalGroup( jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(jPanel1Layout.createSequentialGroup() .addGap(118, 118, 118) .addComponent(jLabel1, javax.swing.GroupLayout.PREFERRED_SIZE, 33, javax.swing.GroupLayout.PREFERRED_SIZE) .addGap(18, 18, 18) .addComponent(jcbCursos, javax.swing.GroupLayout.PREFERRED_SIZE, 54, javax.swing.GroupLayout.PREFERRED_SIZE) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, 248, Short.MAX_VALUE) .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE) .addComponent(jButton1, javax.swing.GroupLayout.PREFERRED_SIZE, 59, javax.swing.GroupLayout.PREFERRED_SIZE) .addComponent(jbAtras, javax.swing.GroupLayout.PREFERRED_SIZE, 59, javax.swing.GroupLayout.PREFERRED_SIZE)) .addGap(70, 70, 70)) ); 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 private void jcbCursosActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jcbCursosActionPerformed }//GEN-LAST:event_jcbCursosActionPerformed private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton1ActionPerformed ListaDeAlumnosPorCurso listaDeAlumnosPorCurso = new ListaDeAlumnosPorCurso(); listaDeAlumnosPorCurso.setVisible(true); String cursoSeleccionado = (String)jcbCursos.getSelectedItem(); listaDeAlumnosPorCurso.setNombreCurso(cursoSeleccionado); this.dispose(); }//GEN-LAST:event_jButton1ActionPerformed private void jbAtrasActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jbAtrasActionPerformed MenuPrincipal menuPrincipal = new MenuPrincipal(); menuPrincipal.setVisible(true); this.dispose(); }//GEN-LAST:event_jbAtrasActionPerformed /** * @param args the command line arguments */ public static void main(String args[]) { /* Set the Nimbus look and feel */ //<editor-fold defaultstate="collapsed" desc=" Look and feel setting code (optional) "> /* If Nimbus (introduced in Java SE 6) is not available, stay with the default look and feel. * For details see http://download.oracle.com/javase/tutorial/uiswing/lookandfeel/plaf.html */ try { for (javax.swing.UIManager.LookAndFeelInfo info : javax.swing.UIManager.getInstalledLookAndFeels()) { if ("Nimbus".equals(info.getName())) { javax.swing.UIManager.setLookAndFeel(info.getClassName()); break; } } } catch (ClassNotFoundException ex) { java.util.logging.Logger.getLogger(AlumnosPorCurso.class.getName()).log(java.util.logging.Level.SEVERE, null, ex); } catch (InstantiationException ex) { java.util.logging.Logger.getLogger(AlumnosPorCurso.class.getName()).log(java.util.logging.Level.SEVERE, null, ex); } catch (IllegalAccessException ex) { java.util.logging.Logger.getLogger(AlumnosPorCurso.class.getName()).log(java.util.logging.Level.SEVERE, null, ex); } catch (javax.swing.UnsupportedLookAndFeelException ex) { java.util.logging.Logger.getLogger(AlumnosPorCurso.class.getName()).log(java.util.logging.Level.SEVERE, null, ex); } //</editor-fold> /* Create and display the form */ java.awt.EventQueue.invokeLater(new Runnable() { public void run() { new AlumnosPorCurso().setVisible(true); } }); } // Variables declaration - do not modify//GEN-BEGIN:variables private javax.swing.JButton jButton1; private javax.swing.JLabel jLabel1; private javax.swing.JPanel jPanel1; private javax.swing.JButton jbAtras; private javax.swing.JComboBox<String> jcbCursos; // End of variables declaration//GEN-END:variables }
true
0d26ae1cca991f254d1bea0144d71a4333556941
Java
ddd5733/MVC-Pattern
/김성용_eclipse_source/JSL_pjt/src/packAB/fpstb.java
UTF-8
647
2.921875
3
[]
no_license
package packAB; import java.util.ArrayList; public class fpstb { public static void main(String[] args) { sub sub = new sub(); sub.test(); String a ="aaWW"; if(a.equalsIgnoreCase("AAww")) System.out.println("같드아"); if(a.equals("Y")) System.out.println("같다"); ArrayList<String> arr = new ArrayList(); if(arr.size()==0) System.out.println("없다111111111"+arr.size()); if(arr.isEmpty()) System.out.println("없다222222222"+arr.isEmpty()); for(int k=0; k<4; k++) { for(int j=0; j<5; j++) { if(j==3) return; System.out.println(" j "+j); } System.out.println(" test() "+k); } } }
true
33aa03cb5989a4c46e619284a7bcbdc30feb88d9
Java
swdevbali/A-Tactical-RPG-Engine
/src/editor/editors/UnitsPanel.java
UTF-8
19,191
2.0625
2
[]
no_license
package editor.editors; import java.awt.BorderLayout; import java.awt.Color; import java.awt.Component; import java.awt.LayoutManager; import java.awt.event.*; import java.io.File; import java.util.*; import javax.swing.*; import javax.swing.event.*; import javax.swing.text.DefaultFormatter; import org.apache.log4j.Logger; import org.jvnet.inflector.Noun; import sun.util.logging.resources.logging; import net.miginfocom.layout.AC; import net.miginfocom.layout.CC; import net.miginfocom.layout.LC; import net.miginfocom.swing.MigLayout; import com.javarichclient.icon.tango.actions.*; import common.enums.Direction; import common.gui.ResourceManager; import common.interfaces.IWeapon; import common.spritesheet.SpriteSheet; import config.Config; import config.assets.*; import editor.Editor; import editor.map.EditorSpriteSheet; import editor.map.MapEditor; import editor.ui.HeaderPanel; import editor.ui.TButton; import editor.util.EditorResources; import engine.skills.ISkill; import engine.unit.AiUnit; import engine.unit.IMutableUnit; import engine.unit.Unit; import engine.unit.SpriteSheetData; /** * Editor for units * @author Bilal Hussain */ public class UnitsPanel<E extends IMutableUnit> extends JPanel implements IRefreshable { private static final Logger log = Logger.getLogger(UnitsPanel.class); private static final long serialVersionUID = 6590057554995017334L; protected JList unitsList; protected DefaultListModel unitsListModel; protected E currentUnit; // Infopanel controls protected JTextField infoName; protected JComboBox infoWeapon; protected JSpinner infoStrength; protected JSpinner infoDefence; protected JSpinner infoSpeed; protected JSpinner infoMove; protected JSpinner infoHp; // protected JSpinner infoMp; protected JList skillsList; protected DefaultListModel skillsListModel; protected JList allSkillsList; protected DefaultListModel allSkillsListModel; protected JComboBox infoSpriteSheet; protected JLabel[] infoSprites; protected java.util.Map<UUID, EditorSpriteSheet> spriteSheets; protected SpriteSheet unitSprites; protected boolean listOnLeft; protected String displayName; public UnitsPanel(java.util.Map<UUID, EditorSpriteSheet> spriteSheets){ this(spriteSheets, true, "Unit"); } public UnitsPanel(java.util.Map<UUID, EditorSpriteSheet> spriteSheets, boolean listOnLeft, String displayName){ super(new BorderLayout()); this.spriteSheets = spriteSheets; this.listOnLeft = listOnLeft; this.displayName = displayName; createMainPane(); } public Units getUnits(){ Units ws = new Units(); for (Object o: unitsListModel.toArray()) { ws.put((IMutableUnit) o); } return ws; } public synchronized void setUnits(Units ws){ ListSelectionListener lsl = unitsList.getListSelectionListeners()[0]; unitsList.removeListSelectionListener(lsl); unitsListModel.clear(); for (IMutableUnit u : ws.values()) { unitsListModel.addElement(u); } unitsList.addListSelectionListener(lsl); unitsList.setSelectedIndex(0); } public void setCurrentUnit(E u){ assert u != null; currentUnit = u; infoName.setText(u.getName()); infoWeapon.setSelectedItem(u.getWeapon()); infoStrength.setValue(u.getStrength()); infoDefence.setValue(u.getDefence()); infoSpeed.setValue(u.getSpeed()); infoMove.setValue(u.getMove()); infoHp.setValue(u.getMaxHp()); for (int i = 0; i < skillsListModel.size(); i++) { Object o = skillsListModel.get(i); if (!allSkillsListModel.contains(o)) allSkillsListModel.addElement(o); } skillsListModel.clear(); assert currentUnit != null; assert currentUnit.getSkills() != null : currentUnit; for (ISkill s : currentUnit.getSkills()) { skillsListModel.addElement(s); allSkillsListModel.removeElement(s); } SpriteSheetData ui = currentUnit.getImageData(); log.debug(u); log.debug(spriteSheets); EditorSpriteSheet ess; if (ui == null || (ess = spriteSheets.get(ui.getUuid())) == null){ assert false : spriteSheets.size() + " "+ ui.getUuid() + "\n" + spriteSheets + "\n" + currentUnit; throw new IllegalStateException("No spritesheets"); }else{ unitSprites = ess.getSpriteSheet(); infoSpriteSheet.setSelectedItem(ui); } assert infoSprites != null; loadUnitImages(); } private void changeName(){ currentUnit.setName(infoName.getText()); unitsList.repaint(); } private void changeWeapon(IWeapon w){ assert currentUnit != null; currentUnit.setWeapon(w); } private void changeStrength(int value){ currentUnit.setStrength(value); } private void changeDefence(int value){ currentUnit.setDefence(value); } private void changeSpeed(int value){ currentUnit.setSpeed(value); } private void changeMove(int value){ currentUnit.setMove(value); } private void changeHp(int value){ currentUnit.setMaxHp(value); } private void changeSkills(){ ArrayList<ISkill> skills =new ArrayList<ISkill>(); for (int i = 0; i < skillsListModel.size(); i++) { skills.add((ISkill) skillsListModel.get(i)); } currentUnit.setSkills(skills); } private void changeUnitImages(SpriteSheetData images){ String path = images.getAnimationPath(); currentUnit.setImageData(path,images); unitSprites = spriteSheets.get(images.getUuid()).getSpriteSheet(); loadUnitImages(); } private void loadUnitImages(){ for (ImageDirection d : ImageDirection.values()) { assert unitSprites.getSpriteImage(d.getImageRef()) != null; assert infoSprites[d.ordinal()] != null; infoSprites[d.ordinal()].setIcon(new ImageIcon(unitSprites.getSpriteImage(d.getImageRef()))); } } @Override public synchronized void panelSelected(Editor editor) { spriteSheets = editor.getUnitsSprites(); ItemListener il = infoWeapon.getItemListeners()[0]; infoWeapon.removeItemListener(il); infoWeapon.removeAllItems(); Weapons ww = editor.getWeapons(); AssetStore.instance().loadWeapons(ww); // TODO chanage? List<IWeapon> s = new ArrayList<IWeapon>(ww.values()); Collections.sort(s,new Comparator<IWeapon>() { @Override public int compare(IWeapon o1, IWeapon o2) { return o1.getName().compareTo(o2.getName()); } }); for (IWeapon w : s) { infoWeapon.addItem(w); } infoWeapon.addItemListener(il); if (currentUnit != null){ setCurrentUnit(currentUnit); } allSkillsListModel.removeAllElements(); Skills ss = editor.getSkills(); AssetStore.instance().loadSkill(ss); List<ISkill> l = new ArrayList<ISkill>(ss.values()); Collections.sort(l,new Comparator<ISkill>() { @Override public int compare(ISkill o1, ISkill o2) { return o1.getName().compareTo(o2.getName()); } }); for (ISkill is :l) { allSkillsListModel.addElement(is); } il = infoSpriteSheet.getItemListeners()[0]; infoSpriteSheet.removeItemListener(il); infoSpriteSheet.removeAllItems(); SpriteSheetsData images = editor.getUnitImages(); List<SpriteSheetData> ll = AbstractSpriteSheetOrganiser.sortedSprites(images.values()); for (SpriteSheetData ui :ll) { infoSpriteSheet.addItem(ui); } infoSpriteSheet.setSelectedItem(currentUnit.getImageData()); infoSpriteSheet.addItemListener(il); assert currentUnit.getImageData().equals(infoSpriteSheet.getSelectedItem()); } protected void createMainPane() { JPanel p = createInfoPanel(); JSplitPane mainSplit; if (listOnLeft){ mainSplit = new JSplitPane( JSplitPane.HORIZONTAL_SPLIT, true, createLeftPane(), p); mainSplit.setResizeWeight(0.05); }else{ mainSplit = new JSplitPane( JSplitPane.HORIZONTAL_SPLIT, true, p, createLeftPane()); mainSplit.setResizeWeight(0.95); } mainSplit.setOneTouchExpandable(true); mainSplit.setBorder(null); this.add(mainSplit, BorderLayout.CENTER); } protected JComponent createLeftPane(){ unitsListModel = new DefaultListModel(); unitsList = new JList(unitsListModel); unitsList.setCellRenderer(new UnitListRenderer()); unitsList.addListSelectionListener(new ListSelectionListener() { @Override public void valueChanged(ListSelectionEvent e) { E u = (E) unitsList.getSelectedValue(); if (u == null){ log.debug(displayName + " "+ u); return; } setCurrentUnit(u); } }); // unitsList.setSelectedIndex(0); unitsList.addKeyListener(new KeyAdapter() { @Override public void keyPressed(KeyEvent e) { if (unitsListModel.size() <= 1) return; if ((e.getKeyCode() == KeyEvent.VK_DELETE || e.getKeyCode() == KeyEvent.VK_BACK_SPACE)) { deleteFromList(unitsList.getSelectedIndex()); } } }); JScrollPane slist = new JScrollPane(unitsList); slist.setColumnHeaderView(createHeader("All " + Noun.pluralOf(displayName))); JPanel p = new JPanel(new BorderLayout()); p.add(slist, BorderLayout.CENTER); JPanel buttons =new JPanel(); buttons.add(new TButton(new DeleteAction())); buttons.add(new TButton(new AddAction())); p.add(buttons, BorderLayout.SOUTH); return p; } private void deleteFromList(int index){ assert unitsListModel.size() >=2; assert index != -1; int nextIndex = index == 0 ? unitsListModel.size()-1 : index - 1; System.out.printf("(%d,%d)\n", index, nextIndex ); unitsList.setSelectedIndex(nextIndex); unitsListModel.remove(index); } private class DeleteAction extends AbstractAction { private static final long serialVersionUID = 4069963919157697524L; public DeleteAction() { putValue(NAME, "Delete the selected " + displayName); // putValue(ACCELERATOR_KEY, KeyStroke.getKeyStroke("control EQUALS")); putValue(SMALL_ICON, new ListRemoveIcon(16, 16)); } @Override public void actionPerformed(ActionEvent e) { // Must have at lest one unit if (unitsListModel.size() <= 1) { return; } deleteFromList(unitsList.getSelectedIndex()); } } private class AddAction extends AbstractAction { private static final long serialVersionUID = 4069963919157697524L; public AddAction() { putValue(NAME, "Add a new " + displayName); // putValue(ACCELERATOR_KEY, KeyStroke.getKeyStroke("control EQUALS")); putValue(SMALL_ICON, new ListAllIcon(16, 16)); } @Override public void actionPerformed(ActionEvent e) { IMutableUnit w = createUnit(currentUnit); int index = unitsListModel.size(); w.setName("New " + displayName + " " + (index + 1)); unitsListModel.addElement(w); unitsList.setSelectedIndex(index); } } protected IMutableUnit createUnit(IMutableUnit old){ return new Unit(old); } public static LayoutManager createLayout() { LC layC = new LC().fill().wrap(); AC colC = new AC().align("right", 1).fill(1, 3).grow(100, 1, 3).align("right", 3).gap("15", 1,3); AC rowC = new AC().align("top", 10).gap("15!", 10).grow(100, 10); return new MigLayout(layC, colC, rowC); } protected JPanel createInfoPanel() { JPanel p = new JPanel(createLayout()); addSeparator(p,"General"); p.add(new JLabel("Name:")); p.add((infoName = new JTextField(15)), "span, growx"); infoName.setText("New " + displayName); infoName.getDocument().addDocumentListener(new DocumentListener() { @Override public void removeUpdate(DocumentEvent e) { changeName(); } @Override public void insertUpdate(DocumentEvent e) { changeName(); } @Override public void changedUpdate(DocumentEvent e) { changeName(); } }); p.add(new JLabel("Weapon:")); infoWeapon = new JComboBox(new IWeapon[]{}); infoWeapon.setRenderer(new WeaponDropDownListRenderer()); infoWeapon.setEditable(false); infoWeapon.addItemListener(new ItemListener() { @Override public void itemStateChanged(ItemEvent e) { if (infoWeapon.getItemCount() <= 0) return; IWeapon w= (IWeapon) e.getItem(); changeWeapon(w); } }); p.add(infoWeapon, "span, growx"); p.add(new JLabel("Strength:")); infoStrength = new JSpinner(new SpinnerNumberModel(10, 1, 1000, 1)); infoStrength.addChangeListener(new ChangeListener() { @Override public void stateChanged(ChangeEvent e) { changeStrength(((Number)infoStrength.getValue()).intValue()); } }); p.add(infoStrength, new CC().alignX("leading").maxWidth("70")); AbstractResourcesPanel.makeJSpinnerSaveOnType(infoStrength); p.add(new JLabel("Defence:"), "gap unrelated"); infoDefence = new JSpinner(new SpinnerNumberModel(10, 1, 1000, 1)); AbstractResourcesPanel.makeJSpinnerSaveOnType(infoDefence); infoDefence.addChangeListener(new ChangeListener() { @Override public void stateChanged(ChangeEvent e) { changeDefence(((Number)infoDefence.getValue()).intValue()); } }); p.add(infoDefence, new CC().alignX("leading").maxWidth("70").wrap()); p.add(new JLabel("Speed:")); infoSpeed = new JSpinner(new SpinnerNumberModel(10, 1, 1000, 1)); AbstractResourcesPanel.makeJSpinnerSaveOnType(infoSpeed); infoSpeed.addChangeListener(new ChangeListener() { @Override public void stateChanged(ChangeEvent e) { changeSpeed(((Number)infoSpeed.getValue()).intValue()); } }); p.add(infoSpeed, new CC().alignX("leading").maxWidth("70")); p.add(new JLabel("Move:"), "gap unrelated"); infoMove = new JSpinner(new SpinnerNumberModel(5, 2, 20, 1)); AbstractResourcesPanel.makeJSpinnerSaveOnType(infoMove); infoMove.addChangeListener(new ChangeListener() { @Override public void stateChanged(ChangeEvent e) { changeMove(((Number)infoMove.getValue()).intValue()); } }); p.add(infoMove, new CC().alignX("leading").maxWidth("70").wrap()); p.add(new JLabel("Hp:")); infoHp = new JSpinner(new SpinnerNumberModel(20, 1, 10000, 10)); AbstractResourcesPanel.makeJSpinnerSaveOnType(infoHp); infoHp.addChangeListener(new ChangeListener() { @Override public void stateChanged(ChangeEvent e) { changeHp(((Number)infoHp.getValue()).intValue()); } }); p.add(infoHp, new CC().alignX("leading").maxWidth("70").wrap()); extraComponents(p); addSeparator(p,"Sprites"); infoSprites = new JLabel[ImageDirection.values().length]; for (ImageDirection d : ImageDirection.values()) { String s = d.toString().toLowerCase(); infoSprites[d.ordinal()] = new JLabel(Character.toUpperCase(s.charAt(0)) + s.substring(1)); infoSprites[d.ordinal()].setHorizontalTextPosition(SwingConstants.CENTER); infoSprites[d.ordinal()].setVerticalTextPosition(SwingConstants.BOTTOM); p.add(infoSprites[d.ordinal()]); } infoSpriteSheet = new JComboBox(new IWeapon[]{}); infoSpriteSheet.setEditable(false); infoSpriteSheet.addItemListener(new ItemListener() { @Override public void itemStateChanged(ItemEvent e) { if (infoSpriteSheet.getItemCount() <= 0) return; SpriteSheetData w= (SpriteSheetData) e.getItem(); changeUnitImages(w); } }); p.add(infoSpriteSheet, "span, growx, wrap"); addSeparator(p,"Skills"); skillsListModel = new DefaultListModel(); skillsList = new JList(skillsListModel); skillsList.setCellRenderer(new SkillsPanel.SkillListRenderer()); JScrollPane ssp = new JScrollPane(skillsList); ssp.setColumnHeaderView(createHeader("Unit's Skills")); p.add(ssp, new CC().alignX("leading").spanX(2).grow()); p.add(new TButton(new AddSkillAction()),new CC().alignY("center").alignX("center").split(2).flowY()); p.add(new TButton(new RemoveSkillAction()),new CC().alignY("center").alignX("center")); allSkillsListModel = new DefaultListModel(); allSkillsList = new JList(allSkillsListModel); allSkillsList.setCellRenderer(new SkillsPanel.SkillListRenderer()); JScrollPane assp = new JScrollPane(allSkillsList); assp.setColumnHeaderView(createHeader("All Skills")); p.add(assp, new CC().gap("unrelated").alignX("leading").spanX(2).grow().wrap()); p.setBorder(BorderFactory.createEtchedBorder()); //TODO fix border return p; } protected void extraComponents(JPanel p) { } private class AddSkillAction extends AbstractAction { private static final long serialVersionUID = -6538170935544736252L; public AddSkillAction() { putValue(NAME, "Add to " + displayName + "'s Skill"); // putValue(ACCELERATOR_KEY, KeyStroke.getKeyStroke("control EQUALS")); putValue(SMALL_ICON, new GoPreviousIcon(16, 16)); } @Override public void actionPerformed(ActionEvent e) { ISkill s = (ISkill) allSkillsList.getSelectedValue(); if (s == null) return; skillsListModel.addElement(s); allSkillsListModel.removeElement(s); changeSkills(); } } private class RemoveSkillAction extends AbstractAction { private static final long serialVersionUID = -8604147798296984257L; public RemoveSkillAction() { putValue(NAME, "Remove " + displayName + "'s Skill"); // putValue(ACCELERATOR_KEY, KeyStroke.getKeyStroke("control EQUALS")); putValue(SMALL_ICON, new GoNextIcon(16, 16)); } @Override public void actionPerformed(ActionEvent e) { ISkill s = (ISkill) skillsList.getSelectedValue(); if (s == null) return; allSkillsListModel.addElement(s); skillsListModel.removeElement(s); changeSkills(); } } void addSeparator(JPanel p, String title){ JLabel pTitle = new JLabel(title); pTitle.setForeground(Color.BLUE.brighter()); p.add(pTitle, new CC().split().spanX().gapTop("4")); p.add(new JSeparator(), new CC().growX().wrap().gapTop("4")); } // creates a header for the panel. protected JPanel createHeader(String text){ JPanel header = new HeaderPanel(new BorderLayout()); header.add(new JLabel("<HTML>"+text+"<BR></HTML>"), BorderLayout.CENTER); return header; } // Gui elements to display information about a asset. enum ImageDirection { NORTH ("north0"), SOUTH ("south0"), EAST ("east0"), WEST ("west0"); final String imageRef; private ImageDirection(String name) { this.imageRef = name; } public String getImageRef() { return imageRef; } } public static class WeaponDropDownListRenderer extends DefaultListCellRenderer { private static final long serialVersionUID = 7730726867980301916L; @Override public Component getListCellRendererComponent(JList list, Object value, int index, boolean isSelected, boolean cellHasFocus) { JLabel label = (JLabel) super.getListCellRendererComponent(list, value, index, isSelected,cellHasFocus); IWeapon w = (IWeapon) value; label.setText(String.format("%s - Strength:%s Range:%s", w.getName(), w.getStrength(), w.getDetails() )); label.setIcon(new ImageIcon(ResourceManager.instance().getItem(w.getImageRef()))); return label; } } public static class UnitListRenderer extends DefaultListCellRenderer { private static final long serialVersionUID = 5874522377321012662L; @Override public Component getListCellRendererComponent(JList list, Object value, int index, boolean isSelected, boolean cellHasFocus) { JLabel label = (JLabel) super.getListCellRendererComponent(list, value, index, isSelected,cellHasFocus); if (value == null){ label.setText("None"); }else{ IMutableUnit w= (IMutableUnit) value; label.setText(w.getName()); } return label; } } }
true
80dae830d0ad64e8789482adcf459d57998bff3a
Java
vicpebarragan/Taller-Refactoring
/TalllerRefactoring/src/modelos/Profesor.java
UTF-8
575
2.875
3
[ "Apache-2.0" ]
permissive
package modelos; import java.util.ArrayList; public class Profesor extends Persona{ private String codigo; private ArrayList<Paralelo> paralelos; private int añosdeTrabajo; private String facultad; private double BonoFijo; public Profesor(String codigo, String nombre, String apellido, int edad, String direccion, String telefono) { this.codigo = codigo; super(nombre,apellido,edad,direccion, telefono) paralelos= new ArrayList<>(); } public void anadirParalelos(Paralelo p){ paralelos.add(p); } }
true
f24d27ccd00b309d149e8ca38fa16d795863cfc2
Java
benbenben20/midaipay
/test/.svn/pristine/d8/d847ac70ee4b3011eeb330a69f1210fb30d160e0.svn-base
UTF-8
716
2.046875
2
[]
no_license
package com.fncat.xswipe.a_thread; import android.os.Handler; import com.fncat.xswipe.MainActivity; import com.fncat.xswipe.controller.POSManage; import com.fncat.xswipe.utils.Utils; /** * 获取电子现金余额 * * @author Fncat * @data 2014-4-24上午11:37:10 */ public class Balance extends Thread { private Handler mHandler; private POSManage pm; public Balance(Handler mHandler, POSManage pm) { this.mHandler = mHandler; this.pm = pm; } @Override public void run() { long timer = System.nanoTime(); int r = pm.getBankIcCardBalance(MainActivity.moneys); Utils.HandData(mHandler, (System.nanoTime() - timer) / 1000000 + "毫秒", 0xA0E6); Utils.HandData(mHandler, r, 0xA1E6); } }
true
f560d6b9974c908fb8d2ae283ea2c4789579b35d
Java
Selvanegra22/vidge
/org.vidge.test/src/org/vidge/test/form/TestForm3.java
UTF-8
4,490
2.203125
2
[]
no_license
package org.vidge.test.form; import java.io.File; import java.util.ArrayList; import java.util.Date; import java.util.List; import org.eclipse.swt.graphics.Color; import org.langcom.locale.LocalizedString; import org.vidge.form.IForm; import org.vidge.test.entity.FormTestClass; import org.vidge.test.entity.FormTestClass2; import org.vidge.test.entity.TestEnum; import org.vidge.util.VisualControlType; import org.vidge.util.VisualProperty; public class TestForm3 implements IForm<FormTestClass> { private FormTestClass input; public TestForm3() { } public TestForm3(FormTestClass input) { this.input = input; } @Override public void setInput(FormTestClass input) { this.input = input; } @Override public FormTestClass getInput() { return input; } @VisualProperty(order = 0) public String getName() { return input.getName(); } @VisualProperty(order = 1) public LocalizedString getLocalizedString() { return input.getLocalizedString(); } public void setLocalizedString(LocalizedString localizedString) { input.setLocalizedString(localizedString); } @VisualProperty(order = 6, control = VisualControlType.OBJECT_EDITOR) public FormTestClass2 getReference() { return input.getReference(); } public void setReference(FormTestClass2 reference) { input.setReference(reference); } @VisualProperty(order = 7) public TestEnum getEnumValue() { return input.getEnumValue(); } public void setEnumValue(TestEnum enumValue) { input.setEnumValue(enumValue); } public List getChildValidValues() { List<FormTestClass> objectList = new ArrayList<FormTestClass>(); objectList.add(new FormTestClass("xxx", "ffffffffffffgggggggggg", 456, new Long(34L), new Date(), null)); objectList.add(new FormTestClass("53xxx", "ffffffffffffgggggggfhfhggg", 456, new Long(34L), new Date(), null)); objectList.add(new FormTestClass("678xxx", "ffffffffffffggggggfhggggg", 456, new Long(34L), new Date(), null)); objectList.add(new FormTestClass("78888xxx", "ffffffffffffgggggggggg", 456, new Long(34L), new Date(), null)); return objectList; } @VisualProperty(order = 11) public FormTestClass getChild() { return input.getChild(); } public void setChild(FormTestClass child) { input.setChild(child); } @VisualProperty(order = 8) public List<FormTestClass2> getTestList() { return input.getTestList(); } @VisualProperty(order = 9) public List<FormTestClass> getTestList2333() { return input.getTestList2(); } public void setName(String name) { input.setName(name); } @VisualProperty(order = 12) public Integer getInvalue() { return input.getInvalue(); } public void setInvalue(Integer invalue) { input.setInvalue(invalue); } @VisualProperty(order = 13) public Long getLongValue() { return input.getLongValue(); } public void setLongValue(Long longValue) { input.setLongValue(longValue); } @VisualProperty(order = 14) public Date getDatevalue() { return input.getDatevalue(); } public void setDatevalue(Date datevalue) { input.setDatevalue(datevalue); } @VisualProperty(order = 15) public File getFilevalue() { return input.getFilevalue(); } public void setFilevalue(File filevalue) { input.setFilevalue(filevalue); } @VisualProperty(order = 16) public Color getColor() { return input.getColor(); } public void setColor(Color color) { input.setColor(color); } public void setTestList(List<FormTestClass2> testList) { input.setTestList(testList); } @VisualProperty(order = 17) public Boolean getBooleanValue() { return input.getBooleanValue(); } public void setBooleanValue(Boolean booleanValue) { input.setBooleanValue(booleanValue); } @VisualProperty(order = 18) public List<FormTestClass> getTestList2() { return input.getTestList2(); } public void setTestList2(List<FormTestClass> testList2) { input.setTestList2(testList2); } @VisualProperty(order = 19) public Double getDoubleValue() { return input.getDoubleValue(); } public void setDoubleValue(Double doubleValue) { input.setDoubleValue(doubleValue); } @VisualProperty(order = 22, control = VisualControlType.TEXTAREA) public String getDescription() { return input.getDescription(); } public void setDescription(String description) { input.setDescription(description); } }
true
8f0e1f22896c43893d9cfd65a79cec82fcdd2486
Java
ankur-mishra-07/papple
/java/com/ifocus/papple/activity/SignUpActivity.java
UTF-8
13,315
1.914063
2
[ "Apache-2.0" ]
permissive
package com.ifocus.papple.activity; import android.app.Activity; import android.app.DatePickerDialog; import android.app.ProgressDialog; import android.content.Intent; import android.os.Bundle; import android.support.design.widget.CoordinatorLayout; import android.support.v7.app.AppCompatActivity; import android.view.View; import android.widget.AdapterView; import android.widget.Button; import android.widget.DatePicker; import android.widget.EditText; import android.widget.LinearLayout; import android.widget.Spinner; import android.widget.Toast; import com.ifocus.papple.R; import com.ifocus.papple.Utils.AndroidUtils; import com.ifocus.papple.Utils.RetroService; import com.ifocus.papple.adapter.SignupSpinnerAdapter; import com.ifocus.papple.database.DBUserDetailsHelper; import com.ifocus.papple.helpers.Constant; import com.ifocus.papple.helpers.StringHelpers; import com.ifocus.papple.helpers.ViewHelpers; import com.ifocus.papple.interfaces.IRetroTaskCompleteListener; import com.ifocus.papple.manager.Signupmanager; import java.util.Calendar; import java.util.HashMap; import java.util.List; import java.util.Map; import retrofit.Retrofit; public class SignUpActivity extends AppCompatActivity implements IRetroTaskCompleteListener { public static final int USERNAME_MIN_LENGTH = 6; public static final int USERNAME_MAX_LENGTH = 20; public static final int PASSWORD_MIN_LENGTH = 6; public static final int PASSWORD_MAX_LENGTH = 22; private final String USER_TYPE_CORP = "corporator"; private final String USER_TYPE_GEN = "general"; private EditText usernameEt; private EditText passwordEt; private EditText emailEt; private EditText fNameEt; private EditText lNameEt; private EditText phoneNoEt; private EditText proofNoEt; private EditText birthDateEt; private EditText birthMonthEt; private EditText birthYearEt; private CoordinatorLayout root; private Spinner bloodGroupSp; private Spinner martialStatusSp; private Spinner wardNameSp; private Spinner proofTypeSp; private Spinner userTypeSp; private int selectedYear; private int selectedMonth; private int selectedDate; private ProgressDialog progressDialog; private Activity activity; private DBUserDetailsHelper userDetailsHelper; /** * Interface for result */ private IRetroTaskCompleteListener taskCompleted; /** * PostParams */ private Map<String, String> postParams = new HashMap<>(); // Retrofit object for initializing the base url private Retrofit retrofit; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_sign_up); userDetailsHelper = new DBUserDetailsHelper(this, null, null, 1); //RetroFit Creation retrofit = RetroService.returnRestadapter(this); taskCompleted = this; activity = this; initViews(); initListeners(); } private void initListeners() { Button backtoLoginBtn = (Button) findViewById(R.id.backtoLoginButton); backtoLoginBtn.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { Intent intent = new Intent(SignUpActivity.this, LoginActivity.class); startActivity(intent); } }); LinearLayout birthdateLayout = (LinearLayout) findViewById(R.id.signupBirthdateLayout); final DatePickerDialog.OnDateSetListener datePickListener = new DatePickerDialog.OnDateSetListener() { @Override public void onDateSet(DatePicker view, int year, int monthOfYear, int dayOfMonth) { selectedDate = dayOfMonth; selectedMonth = monthOfYear; selectedYear = year; birthDateEt.setText(String.valueOf(dayOfMonth)); birthYearEt.setText(String.valueOf(year)); birthMonthEt.setText(String.valueOf(monthOfYear + 1)); } }; View.OnClickListener dateListener = new View.OnClickListener() { @Override public void onClick(View v) { DatePickerDialog datePickerDialog = new DatePickerDialog(SignUpActivity.this, datePickListener, (birthYearEt.getText().toString().equals("")) ? 1991 : Integer.parseInt(birthYearEt.getText().toString()), (birthMonthEt.getText().toString().equals("")) ? 0 : Integer.parseInt(birthMonthEt.getText().toString()) - 1, (birthDateEt.getText().toString().equals("")) ? 1 : Integer.parseInt(birthDateEt.getText().toString())); datePickerDialog.show(); } }; birthdateLayout.setOnClickListener(dateListener); birthDateEt.setOnClickListener(dateListener); birthYearEt.setOnClickListener(dateListener); birthMonthEt.setOnClickListener(dateListener); Button registerBtn = (Button) findViewById(R.id.registerButton); registerBtn.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { progressDialog = new ProgressDialog(SignUpActivity.this, ProgressDialog.STYLE_HORIZONTAL); progressDialog.setMessage("Registering your details. Please wait..."); progressDialog.setIndeterminate(true); progressDialog.setProgress(0); progressDialog.show(); progressDialog.setCancelable(false); registerUser(v); progressDialog.dismiss(); } }); userTypeSp.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() { @Override public void onItemSelected(AdapterView<?> parent, View view, int position, long id) { if (parent.getSelectedItem().toString().toLowerCase().equals(USER_TYPE_CORP)) { proofTypeSp.setAdapter(new SignupSpinnerAdapter(SignUpActivity.this, R.layout.signup_list_item, getResources().getStringArray(R.array.corporatorProofTypes))); } else { proofTypeSp.setAdapter(new SignupSpinnerAdapter(SignUpActivity.this, R.layout.signup_list_item, getResources().getStringArray(R.array.proofTypes))); } } @Override public void onNothingSelected(AdapterView<?> parent) { } }); } private void initViews() { root = (CoordinatorLayout) findViewById(R.id.root); usernameEt = (EditText) findViewById(R.id.signupUsername); passwordEt = (EditText) findViewById(R.id.signupPassword); emailEt = (EditText) findViewById(R.id.signupEmail); fNameEt = (EditText) findViewById(R.id.signupFname); lNameEt = (EditText) findViewById(R.id.signupLname); phoneNoEt = (EditText) findViewById(R.id.signupPhoneNumber); proofNoEt = (EditText) findViewById(R.id.signupProofDetail); birthDateEt = (EditText) findViewById(R.id.signupBirthDate); birthMonthEt = (EditText) findViewById(R.id.signupBirthMonth); birthYearEt = (EditText) findViewById(R.id.signupBirthYear); bloodGroupSp = (Spinner) findViewById(R.id.signupBgroup); bloodGroupSp.setAdapter(new SignupSpinnerAdapter(this, R.layout.signup_list_item, getResources().getStringArray(R.array.bloodGroups))); martialStatusSp = (Spinner) findViewById(R.id.signupMstatus); martialStatusSp.setAdapter(new SignupSpinnerAdapter(this, R.layout.signup_list_item, getResources().getStringArray(R.array.martialStatus))); wardNameSp = (Spinner) findViewById(R.id.signupWardname); wardNameSp.setAdapter(new SignupSpinnerAdapter(this, R.layout.signup_list_item, getResources().getStringArray(R.array.wardNames))); proofTypeSp = (Spinner) findViewById(R.id.signupProoftype); userTypeSp = (Spinner) findViewById(R.id.signupUserType); userTypeSp.setAdapter(new SignupSpinnerAdapter(this, R.layout.signup_list_item, getResources().getStringArray(R.array.userTypes))); } public void registerUser(View view) {//TODO: Implement WS List<EditText> emptyEditTexts = ViewHelpers.validatePresenceEditText(true, getString(R.string.error_required), usernameEt, passwordEt, emailEt, phoneNoEt, proofNoEt, birthDateEt, birthMonthEt, birthYearEt); if (!emptyEditTexts.isEmpty()) { Toast.makeText(this, R.string.error_correction, Toast.LENGTH_LONG).show(); return; } String email = String.valueOf(emailEt.getText()).trim(); String username = String.valueOf(usernameEt.getText()).trim(); String password = String.valueOf(passwordEt.getText()); String fName = String.valueOf(fNameEt.getText()).trim(); String lName = String.valueOf(lNameEt.getText()).trim(); String phoneNumber = String.valueOf(phoneNoEt.getText()).trim(); String proofNumber = String.valueOf(proofNoEt.getText()).trim(); Calendar dateOfBirth = Calendar.getInstance(); dateOfBirth.set(selectedYear, selectedMonth, selectedDate); String dob = dateOfBirth.toString(); String wardname = wardNameSp.getSelectedItem().toString(); String martial_status = martialStatusSp.getSelectedItem().toString(); String blood_group = bloodGroupSp.getSelectedItem().toString(); String proof_type = proofTypeSp.getSelectedItem().toString(); if (!StringHelpers.isValidEmail(email)) { emailEt.setError(getString(R.string.error_email_invalid)); return; } else if (username.isEmpty()) { usernameEt.setError(getString(R.string.error_username_exists)); return; } else if (password.length() < PASSWORD_MIN_LENGTH || password.length() > PASSWORD_MAX_LENGTH) { passwordEt.setError("Password must contain atleast " + PASSWORD_MIN_LENGTH + " and max " + PASSWORD_MAX_LENGTH); return; } else if (phoneNumber.length() != 10) { phoneNoEt.setError("Invalid phone number"); return; } else if (dob.isEmpty()) { birthDateEt.setError("Date is mandatory"); return; } else if (wardname.isEmpty()) { wardNameSp.setFocusable(true); return; } else if (martial_status.isEmpty()) { martialStatusSp.setFocusable(true); return; } else if (blood_group.isEmpty()) { bloodGroupSp.setFocusable(true); return; } else if (proof_type.isEmpty()) { proofTypeSp.setFocusable(true); return; } /** * calling Login server for updating user data */ if (AndroidUtils.isNetworkAvailable(SignUpActivity.this)) { //Making Retro Fit call setProgressBarIndeterminateVisibility(true); // call Network Handler postParams.clear(); postParams.put(getString(R.string.email_), email); postParams.put(getString(R.string.username), username); postParams.put(getString(R.string.password), password); postParams.put(getString(R.string.user_type), "user"); postParams.put(getString(R.string.fname), fName); postParams.put(getString(R.string.lname), lName); postParams.put(getString(R.string.ward_name), "2"); postParams.put(getString(R.string.prompt_martialstatus), martial_status); postParams.put(getString(R.string.prompt_bloodgroup), blood_group); postParams.put(getString(R.string.prompt_prooftype), "1"); postParams.put(getString(R.string.phone1), phoneNumber); postParams.put(getString(R.string.proofnumber), proofNumber); postParams.put(getString(R.string.ward_no1), wardNameSp.getSelectedItem().toString()); new Signupmanager(activity, Constant.AGENT_REGISTRATION, taskCompleted, retrofit, postParams, false); } else { AndroidUtils.showSnackBar(getString(R.string.networkError), root); } } @Override public void onResponseLanded(int serviceCode, String Response) { setProgressBarIndeterminateVisibility(false); Toast.makeText(this, Response, Toast.LENGTH_LONG).show(); /*Intent intent = new Intent(this, LoginActivity.class); intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP); setResult(LoginActivity.USER_SIGNUP_REQUEST, intent); finish();*/ } @Override public void onFailureLanded(int serviceCode, String Failure) { setProgressBarIndeterminateVisibility(false); } }
true
15bd218e9395f0c001b71956765388f8843afe2a
Java
ymyurdakul/Selcuk-Universitesi-Mobi-Uygulamas-
/MyApplication18/app/src/main/java/com/example/mustafa/myapplication/PhonePerson.java
UTF-8
678
2.75
3
[]
no_license
package com.example.mustafa.myapplication; public class PhonePerson { private String name,phone,detail; public PhonePerson(String name,String detail, String phone ) { this.name = name; this.phone = phone; this.detail = detail; } public String getName() { return name; } public void setName(String name) { this.name = name; } public String getPhone() { return phone; } public void setPhone(String phone) { this.phone = phone; } public String getDetail() { return detail; } public void setDetail(String detail) { this.detail = detail; } }
true
56ce863295298d96d731e2f90a7aabf0817f210e
Java
Arhind/HackerRank
/LeftRotation.java
UTF-8
968
3.828125
4
[]
no_license
/* HackerRank Problem * Left rotation of array * https://www.hackerrank.com/challenges/array-left-rotation/problem?h_r=next-challenge&h_v=zen */ package hackerRank; import java.util.*; public class LeftRotation{ public static void main(String[] args) { Scanner sc = new Scanner(System.in); System.out.print("Enter length of array : "); int n = sc.nextInt(); System.out.print("Enter left rotations : "); int rotation = sc.nextInt(); int[] arr = new int[100]; for(int i=0; i<n; i++) arr[i] = sc.nextInt(); //Rotate the given array by rotation times toward left for(int i=0; i<rotation; i++) { int first = arr[0]; for(int j=0; j<n; j++) { arr[j] = arr[j+1]; } arr[n-1] = first; } // Display Left rotated array System.out.println("Final Array"); for(int i=0; i<n; i++) System.out.print(arr[i]+" "); sc.close(); // Saving from memory leak } }
true
93d5d30654f00e898dc9d9df2b67f5a9473353b1
Java
irresistible0202/untitled32
/src/entity/Enemy.java
UTF-8
1,376
2.84375
3
[]
no_license
package entity; import window.Game; import javax.imageio.ImageIO; import java.awt.*; import java.awt.image.BufferedImage; import java.io.File; import java.io.IOException; public class Enemy extends GameObject { BufferedImage image; public Enemy(Game game, int x, int y) { super(game, x, y); this.width = 64; this.height = 96; try { image = ImageIO.read(new File("images/zombie.png")); }catch (IOException e) { e.printStackTrace(); } this.id = RpgObjectType.ENEMY_ZOMBE; } @Override public void move() { if (x>game.player.x) x--; if (x<game.player.x) x++; if (y>game.player.x) y--; if (y<game.player.x) y++; } @Override public void render(Graphics g) {if (game.keyManager.isRight) g.drawImage(image.getSubimage(0, 96, 48, 48), x-game.offsetX, y-game.offsetY, width, height, null); else if (game.keyManager.isLeft) g.drawImage(image.getSubimage(0, 48, 48, 48), x-game.offsetX, y-game.offsetY, width, height, null); else if (game.keyManager.isUP) g.drawImage(image.getSubimage(0, 144, 48, 48), x-game.offsetX, y-game.offsetY, width, height, null); else g.drawImage(image.getSubimage(48, 0, 48, 48), x-game.offsetX, y-game.offsetY, width, height, null); } }
true
d3cd671d5878ac089177110dc9613b6c7788210d
Java
TsRebornz/unimirea-client-extensions-ver2.0
/unimirea_code/src/main/java/ru/tandemservice/uniclient/unimirea_code/migration/MS_unimirea_code_1x0x0_10to11.java
UTF-8
1,413
1.820313
2
[]
no_license
package ru.tandemservice.uniclient.unimirea_code.migration; import org.tandemframework.dbsupport.ddl.DBTool; import org.tandemframework.dbsupport.migration.IndependentMigrationScript; import org.tandemframework.dbsupport.migration.ScriptDependency; /** * Автоматически сгенерированная миграция */ @SuppressWarnings({"unused", "deprecation"}) public class MS_unimirea_code_1x0x0_10to11 extends IndependentMigrationScript { @Override public ScriptDependency[] getBoundaryDependencies() { return new ScriptDependency[] { new ScriptDependency("org.tandemframework", "1.6.18"), new ScriptDependency("org.tandemframework.shared", "1.10.0"), new ScriptDependency("ru.tandemservice.nsiclient", "2.10.0"), new ScriptDependency("ru.tandemservice.uni.product", "2.10.0"), new ScriptDependency("ru.tandemservice.uni.project", "2.10.0") }; } @Override public void run(DBTool tool) throws Exception { //////////////////////////////////////////////////////////////////////////////// // сущность costsChangesStuExtract // у сущности больше нет своей таблицы { // удалить таблицу tool.dropTable("costschangesstuextract_t", true /* - игнорировать ссылающиеся таблицы (в них удалятся foreign keys) */); } } }
true
0ec44df42c669ecf48b2f14265bfe3086fa26e29
Java
junaidp/supervisor
/src/com/wbc/supervisor/shared/dashboardutilities/switchprobe/SwtichprobeReportInfo.java
UTF-8
597
1.703125
2
[]
no_license
package com.wbc.supervisor.shared.dashboardutilities.switchprobe; import com.wbc.supervisor.shared.dashboardutilities.ErrorInfo; import java.util.ArrayList; public interface SwtichprobeReportInfo { ErrorInfo getErrorInfo(); void setErrorInfo( ErrorInfo errorInfo ); GeneralInfoImpl getGeneralData(); void setGeneralData( GeneralInfoImpl generalData ); ArrayList<String> getWarningMessages(); void setWarningMessages( ArrayList<String> warningMessages ); ArrayList<String> getErrorMessages(); void setErrorMessages( ArrayList<String> errorMessages ); }
true
330098a4efbeea26d1fa2bf6e7355b01896df97d
Java
pandaria/farmland
/gifts-biz/src/main/java/com/pandaria/farmland/biz/component/ControllerResponseAdvice.java
UTF-8
787
2.015625
2
[ "Apache-2.0" ]
permissive
package com.pandaria.farmland.biz.component; import com.pandaria.farmland.biz.component.exception.RecordAlreadyExistsException; import com.pandaria.farmland.biz.component.exception.RecordNotFoundException; import org.springframework.http.ResponseEntity; import org.springframework.web.bind.annotation.ExceptionHandler; import org.springframework.web.bind.annotation.ResponseBody; import org.springframework.web.bind.annotation.RestControllerAdvice; import javax.servlet.http.HttpServletResponse; @RestControllerAdvice public class ControllerResponseAdvice { @ExceptionHandler({RecordAlreadyExistsException.class, RecordNotFoundException.class}) @ResponseBody public ResponseEntity wrapperResponse(Exception e, HttpServletResponse response) { return null; } }
true
77e36e7260a2bf79051d4d0367d2f927d6760d15
Java
sruegg/LicenseKeeperEJB
/ejbModule/session/LicenseKeeperBean.java
UTF-8
5,913
2.296875
2
[]
no_license
package session; import java.util.List; import javax.ejb.Stateless; import javax.persistence.EntityManager; import javax.persistence.PersistenceContext; import javax.persistence.PersistenceException; import persistance.*; @Stateless public class LicenseKeeperBean implements LicenseKeeper, LicenseKeeperRemote { @PersistenceContext private EntityManager em; public Category getCategory(int id) { return em.find(Category.class, id); } @SuppressWarnings("unchecked") public List<Category> getCategories() throws PersistException { try { return em.createQuery("SELECT c FROM Category c").getResultList(); } catch (PersistenceException ex) { ex.printStackTrace(); throw new PersistException(); } } public void saveCategory(Category category) { em.merge(category); } @SuppressWarnings("unchecked") @Override public List<User> getUsers() throws PersistException { try { return em.createQuery("SELECT c FROM User c").getResultList(); } catch (PersistenceException ex) { ex.printStackTrace(); throw new PersistException(); } } public void saveUser(User user) throws PersistException { em.merge(user); } @Override public User getUser(int id) throws PersistException { return em.find(User.class, id); } @Override public User getUser(String username) throws PersistException{ try { return (User) em.createQuery("SELECT c FROM User c WHERE username='" + username + "'").getResultList().get(0); } catch (PersistenceException ex) { ex.printStackTrace(); throw new PersistException(); } } @SuppressWarnings("unchecked") @Override public List<UserGroup> getUserGroups() throws PersistException { try { return em.createQuery("SELECT c FROM UserGroup c").getResultList(); } catch (PersistenceException ex) { ex.printStackTrace(); throw new PersistException(); } } @Override public void saveUserGroup(UserGroup usergroup) throws PersistException { em.merge(usergroup); } @Override public UserGroup getUserGroup(int id) throws PersistException { return em.find(UserGroup.class, id); } @SuppressWarnings("unchecked") @Override public List<LicensedObject> getLicensedObjects() throws PersistException { try { return em.createQuery("SELECT c FROM LicensedObject c").getResultList(); } catch (PersistenceException ex) { ex.printStackTrace(); throw new PersistException(); } } @SuppressWarnings("unchecked") @Override public List<LicensedObjectOperatingSystem> getLicensedObjectsOperatingSystem() throws PersistException { try { return em.createQuery("SELECT c FROM LicensedObjectOperatingSystem c").getResultList(); } catch (PersistenceException ex) { ex.printStackTrace(); throw new PersistException(); } } @SuppressWarnings("unchecked") @Override public List<LicensedObjectSoftware> getLicensedObjectsSoftware() throws PersistException { try { return em.createQuery("SELECT c FROM LicensedObjectSoftware c").getResultList(); } catch (PersistenceException ex) { ex.printStackTrace(); throw new PersistException(); } } @Override public void saveLicensedObject(LicensedObject licensedObject) throws PersistException { em.merge(licensedObject); } @Override public LicensedObject getLicensedObject(int id) throws PersistException { return em.find(LicensedObject.class, id); } @Override public LicensedObjectOperatingSystem getLicensedObjectOperatingSystem(int id) throws PersistException { return em.find(LicensedObjectOperatingSystem.class, id); } @Override public LicensedObjectSoftware getLicensedObjectSoftware(int id) throws PersistException { return em.find(LicensedObjectSoftware.class, id); } @SuppressWarnings("unchecked") @Override public List<LicensedObjectVersion> getLicensedObjectVersions() throws PersistException { try { return em.createQuery("SELECT c FROM LicensedObjectVersion c").getResultList(); } catch (PersistenceException ex) { ex.printStackTrace(); throw new PersistException(); } } @Override public void saveLicensedObjectVersion( LicensedObjectVersion licensedObjectVersion) throws PersistException { em.merge(licensedObjectVersion); } @Override public LicensedObjectVersion getLicensedObjectVersion(int id) throws PersistException { return em.find(LicensedObjectVersion.class, id); } @SuppressWarnings("unchecked") @Override public List<LicensedObjectKey> getLicensedObjectKeys() throws PersistException { try { return em.createQuery("SELECT c FROM LicensedObjectKey c").getResultList(); } catch (PersistenceException ex) { ex.printStackTrace(); throw new PersistException(); } } @Override public void saveLicensedObjectKey(LicensedObjectKey licensedObjectKey) throws PersistException { em.merge(licensedObjectKey); } @Override public LicensedObjectKey getLicensedObjectKey(int id) throws PersistException { return em.find(LicensedObjectKey.class, id); } @SuppressWarnings("unchecked") @Override public List<LicensedObjectVersion> getLicensedObjectVersions(int id) throws PersistException { try { return em.createQuery("SELECT c FROM LicensedObjectVersion c WHERE licensedObject_id=" + id).getResultList(); } catch (PersistenceException ex) { ex.printStackTrace(); throw new PersistException(); } } @SuppressWarnings("unchecked") @Override public List<LicensedObjectKey> getLicensedObjectKeys(int id) throws PersistException { try { return em.createQuery("SELECT c FROM LicensedObjectKey c WHERE licensedObjectKeys_id=" + id).getResultList(); } catch (PersistenceException ex) { ex.printStackTrace(); throw new PersistException(); } } }
true
b05312b5e95ee3f02c04b3d90597f0b3428a4e34
Java
COdiwuor/BoostGym
/app/src/main/java/com/example/android/boostgym/GyminstructorActivity.java
UTF-8
1,875
2.3125
2
[]
no_license
package com.example.android.boostgym; import android.support.v7.app.AppCompatActivity; import android.os.Bundle; import android.support.v7.widget.DefaultItemAnimator; import android.support.v7.widget.DividerItemDecoration; import android.support.v7.widget.LinearLayoutManager; import android.support.v7.widget.RecyclerView; import java.util.ArrayList; import java.util.List; public class GyminstructorActivity extends AppCompatActivity { private List<Instructors> gyminstructorList; private RecyclerView recyclerView; private GymAdapter gAdapter; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_gyminstructor); gyminstructorList=new ArrayList<>(); recyclerView = findViewById(R.id.recyclerview); recyclerView.setHasFixedSize(true); recyclerView.setLayoutManager(new LinearLayoutManager(this)); // recyclerView.setItemAnimator(new DefaultItemAnimator()); // recyclerView.addItemDecoration(new DividerItemDecoration(this, LinearLayoutManager.VERTICAL)); gyminstructorList.add(new Instructors("John", "0771252134", "John@gmail.com", "male")); gyminstructorList.add(new Instructors("Mary", "0702252133", "Mary@gmail.com", "female")); gyminstructorList.add(new Instructors("Rose", "0703262134", "Rose@gmail.com", "female")); gyminstructorList.add(new Instructors("Sam", "0710233134", "Sam@gmail.com", "male")); gyminstructorList.add(new Instructors("David", "0701952334", "David@gmail.com", "male")); gyminstructorList.add(new Instructors("Rachael", "0704252334", "Rachael@gmail.com", "female")); gyminstructorList.add(new Instructors("Brian", "0705242334", "Brian@gmail.com", "male")); gAdapter = new GymAdapter(gyminstructorList,this); recyclerView.setAdapter(gAdapter); } }
true
030f8c0fdbf7cc8063610b9018ee3347f4751b96
Java
henrik242/openiam-idm
/openiam-webconsole/src/main/java/org/openiam/webadmin/access/PolicyAction.java
UTF-8
18,910
1.960938
2
[]
no_license
/** * ------------------------------------------------------------------------------ * Title: PolicyAction Author: APS 04-09-2004 Overview:Handles all functions * like adding , updating, deleting and viewing Policies for available Services. * ------------------------------------------------------------------------------ * Copyright (c) 2000-2004 Diamelle Inc. All Rights Reserved. * * This SOURCE CODE FILE, which has been provided by Diamelle Technologies as * part of a Diamelle Software product for use ONLY by licensed users of the * product, includes CONFIDENTIAL and PROPRIETARY information of Diamelle * Technologies. * * This code or parts or derivatives of it cannot be used for any commercial * products without written permission from Diamelle Technologies. * * USE OF THIS SOFTWARE IS GOVERNED BY THE TERMS AND CONDITIONS OF THE LICENSE * STATEMENT FURNISHED WITH THE PRODUCT. * * IN PARTICULAR, YOU WILL INDEMNIFY AND HOLD Diamelle Technologies, ITS RELATED * COMPANIES AND ITS SUPPLIERS, HARMLESS FROM AND AGAINST ANY CLAIMS OR * LIABILITIES ARISING OUT OF THE USE, REPRODUCTION, OR DISTRIBUTION OF YOUR * PROGRAMS, INCLUDING ANY CLAIMS OR LIABILITIES ARISING OUT OF OR RESULTING * FROM THE USE, MODIFICATION, OR DISTRIBUTION OF PROGRAMS OR FILES CREATED * FROM, BASED ON, AND/OR DERIVED FROM THIS SOURCE CODE FILE. * ------------------------------------------------------------------------------ * CHANGE CONTROL: * * ------------------------------------------------------------------------------ */ package org.openiam.webadmin.access; import java.io.*; import java.text.*; import java.util.*; import javax.servlet.*; import javax.servlet.http.*; import org.springframework.web.struts.DispatchActionSupport; import org.openiam.idm.srvc.policy.dto.Policy; import org.openiam.idm.srvc.policy.dto.PolicyAttribute; import org.openiam.idm.srvc.policy.dto.PolicyConstants; import org.openiam.idm.srvc.policy.dto.PolicyDef; import org.openiam.idm.srvc.policy.dto.PolicyDefParam; import org.openiam.idm.srvc.policy.service.PolicyDataService; import org.openiam.idm.srvc.secdomain.service.SecurityDomainDataService; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; import org.apache.struts.action.*; import org.apache.struts.util.*; public class PolicyAction extends DispatchActionSupport { protected SecurityDomainDataService secDomainService; protected PolicyDataService policyDS; private static final String GROUP = "Group"; private static final Log log = LogFactory.getLog(PolicyAction.class); /* * Description: Populate the intial screen so that the user can select a * policy type to view a list of policies. */ public ActionForward init(ActionMapping mapping, ActionForm form, HttpServletRequest request, HttpServletResponse response) throws IOException, ServletException { log.info("In Policy init..."); ActionErrors errors = new ActionErrors(); HttpSession session = request.getSession(); session.removeAttribute("sideMenus"); session.removeAttribute("categories"); session.removeAttribute("menus"); session.removeAttribute("topLevelMenus"); try { List policyTypes = this.policyTypesToLabels(); request.setAttribute("policyTypes", policyTypes); } catch (Exception e) { e.printStackTrace(); errors.add(ActionMessages.GLOBAL_MESSAGE,new ActionMessage("error.ejb")); } if (!errors.isEmpty()) { saveErrors(request, errors); } return mapping.findForward("policies"); } public ActionForward searchDelete(ActionMapping mapping, ActionForm form, HttpServletRequest request, HttpServletResponse response) throws IOException, ServletException { DynaActionForm f = (DynaActionForm) form; String submit = (String) f.get("submit"); if ((submit != null) && (submit.length() > 0)) { if (submit.equalsIgnoreCase("Delete")) return removePolicies(mapping, form, request, response); } return search(mapping, form, request, response); } /* * Description: Returns a list of polices for the selected service or group */ public ActionForward search(ActionMapping mapping, ActionForm form, HttpServletRequest request, HttpServletResponse response) throws IOException, ServletException { log.info("Policy search is called.. "); //List policyList = null; ActionErrors errors = new ActionErrors(); HttpSession session = request.getSession(); DynaActionForm dynForm = (DynaActionForm) form; String policyDefId = (String) dynForm.get("policyDefId"); log.info("Policy DefId = " + policyDefId); log.info("PolicyDS=" + policyDS); session.setAttribute("policyDefId", policyDefId); try { List<Policy> policyList = policyDS.getAllPolicies(policyDefId); request.setAttribute("policies", policyList); init(mapping, form, request, response); } catch (Exception e) { e.printStackTrace(); errors.add(ActionMessages.GLOBAL_MESSAGE,new ActionMessage("error.ejb")); } return mapping.findForward("policies"); } public ActionForward removePolicies(ActionMapping mapping, ActionForm form, HttpServletRequest request, HttpServletResponse response) throws IOException, ServletException { String[] arr = request.getParameterValues("policyId"); if (arr != null) { for (int i = 0; i < arr.length; i++) { policyDS.removePolicy(arr[i]); } } search(mapping, form, request, response); return mapping.findForward("policies"); } public ActionForward newPolicy(ActionMapping mapping, ActionForm form, HttpServletRequest request, HttpServletResponse response) throws IOException, ServletException { ActionErrors err = new ActionErrors(); try { HttpSession session = request.getSession(true); String policyDefId = (String)session.getAttribute("policyDefId"); if (policyDefId == null) { // policy def was not selected. notify the user String msg = "Please select a policy type"; request.setAttribute("msg", msg); init(mapping, form, request, response); return mapping.findForward("policies"); } if (policyDefId.equals( PolicyConstants.ATTRIBUTE_POLICY )) { return mapping.findForward("attrPolicy"); } request.setAttribute("tabOptions", initTabOptions("Policy", null)); init(mapping, form, request, response); } catch (Exception e) { e.printStackTrace(); //err.add(ActionErrors.GLOBAL_ERROR, new ActionError("error.ejb")); } if (!err.isEmpty()) { saveErrors(request, err); } return mapping.findForward("policy"); } public ActionForward savePolicy(ActionMapping mapping, ActionForm form, HttpServletRequest request, HttpServletResponse response) throws IOException, ServletException { ActionErrors err = new ActionErrors(); Locale locale = getLocale(request); HttpSession session = request.getSession(); try { DynaActionForm f = (DynaActionForm) form; Policy val = getPolicyValue(f); // from auth filter String uid = (String) session.getAttribute("userId"); if (uid != null) { val.setLastUpdatedBy(uid); } String policyId = (String) f.get("policyId"); if ((policyId != null) && (policyId.length() > 0)) { // leave policyDefId, create fields unchanged from old value Policy modVal = policyDS.getPolicy(policyId); modVal.setDescription(val.getDescription()); modVal.setName(val.getName()); modVal.setLastUpdatedBy(val.getLastUpdatedBy()); modVal.setLastUpdate(val.getLastUpdate()); policyDS.updatePolicy(modVal); } else { String policyDefId = (String) f.get("policyDefId"); if ((policyDefId == null) || (policyDefId.equals("-1"))) err.add(ActionMessages.GLOBAL_MESSAGE,new ActionMessage("error.missingPolicyDefId")); //err.add(ActionErrors.GLOBAL_ERROR, new ActionError( // "error.missingPolicyDefId")); else { if (uid != null) { val.setCreatedBy(uid); } policyDS.addPolicy(val); policyId = val.getPolicyId(); f.set("policyId", policyId); // rules method will need this // insert policy definition as attributes for this policy: PolicyDef policyDef = policyDS.getPolicyDefinition(val.getPolicyDefId()); Set<PolicyDefParam> defParams = policyDef.getPolicyDefParams(); Set<PolicyAttribute> attrSet = val.getPolicyAttributes(); Iterator<PolicyDefParam> it = defParams.iterator(); while (it.hasNext()) { PolicyDefParam defParam = it.next(); PolicyAttribute attr = new PolicyAttribute(); attr.setName(defParam.getName()); attr.setOperation(defParam.getOperation()); // attr.setPolicyDefParam(defParam); // attr.setPolicy(val); attr.setValue1(defParam.getValue1()); attr.setValue2(defParam.getValue2()); attrSet.add(attr); } val.setPolicyAttributes(attrSet); policyDS.updatePolicy(val); } } policy(mapping, form, request, response); } catch (Exception e) { e.printStackTrace(); err.add(ActionMessages.GLOBAL_MESSAGE,new ActionMessage("error.databaseselect")); //err.add(ActionErrors.GLOBAL_ERROR, new ActionError("error.ejb")); } return mapping.findForward("policy"); } public ActionForward policy(ActionMapping mapping, ActionForm form, HttpServletRequest request, HttpServletResponse response) throws IOException, ServletException { ActionErrors errors = new ActionErrors(); HttpSession session = request.getSession(); try { session.setAttribute("domainList", secDomainService.getAllDomainsWithExclude("IDM")); DynaActionForm f = (DynaActionForm) form; String policyId = (String) f.get("policyId"); Policy policyVal = policyDS.getPolicy(policyId); request.setAttribute("policy", policyVal); populatePolicyForm(policyVal, f); String policyDefId = policyVal.getPolicyDefId(); request.setAttribute("tabOptions", initTabOptions("Policy", policyDefId)); List policyTypes = this.policyTypesToLabels(); request.setAttribute("policyTypes", policyTypes); } catch (Exception e) { e.printStackTrace(); errors.add(ActionMessages.GLOBAL_MESSAGE,new ActionMessage("error.ejb")); } if (!errors.isEmpty()) { saveErrors(request, errors); } return mapping.findForward("policy"); } public ActionForward rules(ActionMapping mapping, ActionForm form, HttpServletRequest request, HttpServletResponse response) throws IOException, ServletException { ActionErrors errors = new ActionErrors(); HttpSession session = request.getSession(); session.setAttribute("domainList", secDomainService.getAllDomainsWithExclude("IDM")); try { DynaActionForm f = (DynaActionForm) form; String policyId = (String) f.get("policyId"); Policy policyVal = policyDS.getPolicy(policyId); request.setAttribute("policy", policyVal); String policyDefId = policyVal.getPolicyDefId(); request.setAttribute("tabOptions", initTabOptions("Rules", policyDefId)); //passwordPolicy(mapping, form, request, response); String submit = (String) f.get("submit"); if ((submit != null) && (submit.length() > 0)) { if (submit.equalsIgnoreCase("Save")) saveRules(mapping, form, request, response); } //this.viewPasswordPolicy(mapping, form, request, response); Set<PolicyAttribute> attrSet = policyVal.getPolicyAttributes(); //List policyAttr = policyAccess.getPolicyAttributes(policyId); if (attrSet != null) { Iterator<PolicyAttribute> it = attrSet.iterator(); while (it.hasNext()) { PolicyAttribute val = it.next(); f.set(val.getName(), val.getValue1()); if ((val.getOperation() != null) && (val.getOperation().equalsIgnoreCase("RANGE"))) { f.set(val.getName() + "_MAX", val.getValue2()); } } } } catch (Exception e) { e.printStackTrace(); errors.add(ActionMessages.GLOBAL_MESSAGE,new ActionMessage("error.ejb")); } if (!errors.isEmpty()) { saveErrors(request, errors); } return mapping.findForward("policy"); } /* * public ActionForward viewPasswordPolicy(ActionMapping mapping, ActionForm * form, HttpServletRequest request, HttpServletResponse response) throws * IOException, ServletException { * * ActionErrors errors = new ActionErrors(); * * try { DynaActionForm f = (DynaActionForm) form; String policyId = * (String) f.get("policyId"); List policyAttr = * policyAccess.getPolicyAttributes(policyId); * * Iterator it = policyAttr.iterator(); while (it.hasNext()) { * PolicyAttrValue val = (PolicyAttrValue) it.next(); f.set(val.getName(), * val.getValue1()); * * if ((val.getOperation() != null) && * (val.getOperation().equalsIgnoreCase("RANGE"))) { f.set(val.getName() + * "_MAX", val.getValue2()); } } } catch (Exception e) { * e.printStackTrace(); errors.add(ActionErrors.GLOBAL_ERROR, new * ActionError("error.ejb")); } if (!errors.isEmpty()) { saveErrors(request, * errors); return mapping.findForward("failure"); } return * mapping.findForward("policy"); } */ public ActionForward saveRules(ActionMapping mapping, ActionForm form, HttpServletRequest request, HttpServletResponse response) throws IOException, ServletException { ActionErrors errors = new ActionErrors(); try { DynaActionForm f = (DynaActionForm) form; String policyId = (String) f.get("policyId"); Policy policy = policyDS.getPolicy(policyId); Set<PolicyAttribute> attrSet = policy.getPolicyAttributes(); //List policyAttr = policyAccess.getPolicyAttributes(policyId); Iterator<PolicyAttribute> it = attrSet.iterator(); while (it.hasNext()) { PolicyAttribute val = it.next(); String attrName = val.getName(); String attrValue1 = request.getParameter(attrName); val.setValue1(attrValue1); if (val.getOperation() != null) { if (val.getOperation().equalsIgnoreCase("RANGE")) { String attrValue2 = request.getParameter(attrName + "_MAX"); val.setValue2(attrValue2); } if ((attrValue1 != null) && (val.getOperation().equalsIgnoreCase("boolean"))) { if ((attrValue1.equalsIgnoreCase("on")) || (attrValue1.equalsIgnoreCase("true"))) val.setValue1("true"); else val.setValue1("false"); } } attrSet.add(val); } policyDS.updatePolicy(policy); } catch (Exception e) { e.printStackTrace(); errors.add(ActionMessages.GLOBAL_MESSAGE,new ActionMessage("error.ejb")); } if (!errors.isEmpty()) { saveErrors(request, errors); } return null; } /* * public ActionForward passwordPolicy(ActionMapping mapping, ActionForm * form, HttpServletRequest request, HttpServletResponse response) throws * IOException, ServletException { * * DynaActionForm f = (DynaActionForm) form; String submit = (String) * f.get("submit"); * * if ((submit != null) && (submit.length() > 0)) { if * (submit.equalsIgnoreCase("Save")) savePasswordPolicy(mapping, form, * request, response); } return viewPasswordPolicy(mapping, form, request, * response); } */ // ---------- helper methods -------------- private void populatePolicyForm(Policy val, DynaActionForm form) { DateFormat df = new SimpleDateFormat("MM-DD-yyyy"); if (val == null) { System.out.println("Val was null. "); } if (val.getCreateDate() != null) { form.set("createDate", df.format(val.getCreateDate())); } else form.set("createDate", df.format(Calendar.getInstance().getTime())); form.set("createdBy", val.getCreatedBy()); form.set("description", val.getDescription()); if (val.getLastUpdate() != null) { form.set("lstUpdate", df.format(val.getLastUpdate())); } form.set("lstUpdateBy", val.getLastUpdatedBy()); form.set("policyName", val.getName()); form.set("policyDefId", val.getPolicyDefId()); form.set("policyId", val.getPolicyId()); } private Policy getPolicyValue(DynaActionForm f) { Policy val = new Policy(); if (f != null) { Calendar calendar = new GregorianCalendar(); java.sql.Date date = new java.sql.Date(calendar.getTimeInMillis()); val.setCreatedBy((String) f.get("createdBy")); val.setDescription((String) f.get("description")); val.setLastUpdate(date); val.setLastUpdatedBy((String) f.get("lstUpdateBy")); val.setName((String) f.get("policyName")); val.setPolicyDefId((String) f.get("policyDefId")); val.setPolicyId((String) f.get("policyId")); } return val; } // to build drop down in jsp page private List policyTypesToLabels() { List labels = new java.util.ArrayList(); LabelValueBean emptybean = new LabelValueBean("<Select a value>", "-1"); labels.add(emptybean); PolicyDef[] defAry = policyDS.getAllPolicyDef(); if (defAry == null) { return labels; } int size = defAry.length; for (int i=0; i<size; i++) { labels.add(new LabelValueBean(defAry[i].getName(), defAry[i].getPolicyDefId())); } return labels; } private List initTabOptions(String activeTab, String policyDefId) { List l = new ArrayList(); /* TabOption option = new TabOption("Policy", false, "security/policy.do?method=policy", "/policy/policyhdr.jsp"); if (activeTab.equalsIgnoreCase("Policy")) { option.setActive(true); } l.add(option); if (policyDefId != null) { option = new TabOption("Rules", false, "security/rulesPolicy.do?method=rules", getPolicyPage(policyDefId)); if (activeTab.equalsIgnoreCase("Rules")) { option.setActive(true); } l.add(option); } */ return l; } private String getPolicyPage(String policyDefId) { String activeJsp = "/policy/pswdpolicy.jsp"; if (policyDefId.equalsIgnoreCase("100")) { activeJsp = "/policy/pswdpolicy.jsp"; } if (policyDefId.equalsIgnoreCase("101")) { activeJsp = ""; } if (policyDefId.equalsIgnoreCase("102")) { activeJsp = "/policy/auditpolicy.jsp"; } if (policyDefId.equalsIgnoreCase("103")) { activeJsp = "/policy/accountpolicy.jsp"; } return activeJsp; } public SecurityDomainDataService getSecDomainService() { return secDomainService; } public void setSecDomainService(SecurityDomainDataService secDomainService) { this.secDomainService = secDomainService; } public PolicyDataService getPolicyDS() { return policyDS; } public void setPolicyDS(PolicyDataService policyDS) { this.policyDS = policyDS; } }
true
3e32b93e9beab1824d4fb43f9b7fa30fb6132bba
Java
ZhixingZhou/RuleMiningApplication
/src/seu/zzx/panel/DataSourceInfoPanel.java
UTF-8
25,975
1.984375
2
[]
no_license
/* * 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 seu.zzx.panel; import java.awt.Color; import java.awt.event.ComponentEvent; import java.awt.event.ComponentListener; import java.awt.event.ItemEvent; import javax.swing.BorderFactory; import javax.swing.ComboBoxModel; import javax.swing.JPanel; import javax.swing.SwingConstants; import javax.swing.border.Border; import javax.swing.border.TitledBorder; import javax.swing.table.DefaultTableCellRenderer; import javax.swing.table.DefaultTableModel; import seu.zzx.constant.ConstantLibrary; import seu.zzx.dbc.EditTable; import seu.zzx.frame.HistogramFrame; import seu.zzx.frame.MainFunction; import seu.zzx.table.OperateJTable; import seu.zzx.util.UserDefineComboBoxModel; /** * * @author zzx_seu */ public class DataSourceInfoPanel extends JPanel implements ComponentListener{ /** * Creates new form DataSourceInfoPanel */ public DataSourceInfoPanel(MainFunction mf) { this.mf = mf; initComponents(); this.addComponentListener(this); this.jPanel2.addComponentListener(this); this.jLabel3.setText(String.valueOf(ConstantLibrary.record)); this.jLabel4.setText(String.valueOf(ConstantLibrary.columnNames.length)); myTableModel dtModel = new myTableModel(OperateJTable.getTableData(),OperateJTable.getTableColNames()){ public boolean isCellEditable(int row, int column) { if(column==2){ return false; }else{ return true; } } }; this.jTable1.setModel(dtModel); DefaultTableCellRenderer hr = (DefaultTableCellRenderer) this.jTable1.getTableHeader().getDefaultRenderer(); hr.setHorizontalAlignment(DefaultTableCellRenderer.CENTER);//列名居中 DefaultTableCellRenderer tcr = new DefaultTableCellRenderer();// 设置table内容居中 tcr.setHorizontalAlignment(SwingConstants.CENTER);// 这句和上句作用一样 this.jTable1.setDefaultRenderer(Object.class, tcr); this.jTable1.setShowGrid(true); String str = this.jTable1.getModel().getValueAt(0, 2).toString(); String columnName = ConstantLibrary.columnMap2.get(str); int count = EditTable.getNullCount(columnName); this.jLabel10.setText(str); this.jLabel11.setText(String.valueOf(count)); EditTable.getDiffientAndUniqueValueCount(columnName); this.jLabel12.setText(String.valueOf(EditTable.diffienceCount)); this.jLabel13.setText(String.valueOf(EditTable.uniqueCount)); DefaultTableModel dtModel2 = new DefaultTableModel(EditTable.dataValue,EditTable.columnValue){ public boolean isCellEditable(int row, int column) { return false; } }; this.jTable2.setModel(dtModel2); DefaultTableCellRenderer hr2 = (DefaultTableCellRenderer) this.jTable2.getTableHeader().getDefaultRenderer(); hr2.setHorizontalAlignment(DefaultTableCellRenderer.CENTER);//列名居中 DefaultTableCellRenderer tcr2 = new DefaultTableCellRenderer();// 设置table内容居中 tcr2.setHorizontalAlignment(SwingConstants.CENTER);// 这句和上句作用一样 this.jTable2.setDefaultRenderer(Object.class, tcr2); this.jTable2.setShowGrid(true); this.jcbm = new UserDefineComboBoxModel(); this.jComboBox1.setModel(this.jcbm); this.jComboBox1.setSelectedIndex(0); this.jSplitPane1.setLeftComponent(null); this.jSplitPane1.setRightComponent(null); } /** * 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(); jLabel1 = new javax.swing.JLabel(); jLabel2 = new javax.swing.JLabel(); jLabel3 = new javax.swing.JLabel(); jLabel4 = new javax.swing.JLabel(); jPanel2 = new javax.swing.JPanel(); jScrollPane1 = new javax.swing.JScrollPane(); jTable1 = new javax.swing.JTable(); jButton1 = new javax.swing.JButton(); jPanel3 = new javax.swing.JPanel(); jLabel5 = new javax.swing.JLabel(); jLabel6 = new javax.swing.JLabel(); jLabel7 = new javax.swing.JLabel(); jLabel10 = new javax.swing.JLabel(); jLabel8 = new javax.swing.JLabel(); jLabel11 = new javax.swing.JLabel(); jLabel12 = new javax.swing.JLabel(); jLabel13 = new javax.swing.JLabel(); jScrollPane2 = new javax.swing.JScrollPane(); jTable2 = new javax.swing.JTable(); jPanel4 = new javax.swing.JPanel(); jComboBox1 = new javax.swing.JComboBox<>(); jPanel5 = new javax.swing.JPanel(); jSplitPane1 = new javax.swing.JSplitPane(); jPanel1.setBorder(javax.swing.BorderFactory.createTitledBorder("数据信息")); jLabel1.setText("记录数:"); jLabel2.setText("属性个数:"); jLabel3.setText("jLabel3"); jLabel4.setText("jLabel4"); 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) .addGroup(jPanel1Layout.createSequentialGroup() .addComponent(jLabel1) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addComponent(jLabel3, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)) .addGroup(jPanel1Layout.createSequentialGroup() .addComponent(jLabel2) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addComponent(jLabel4, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))) .addContainerGap()) ); jPanel1Layout.setVerticalGroup( jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(jPanel1Layout.createSequentialGroup() .addContainerGap() .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE) .addComponent(jLabel1) .addComponent(jLabel3)) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, 17, Short.MAX_VALUE) .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE) .addComponent(jLabel2) .addComponent(jLabel4)) .addContainerGap()) ); jPanel2.setBorder(javax.swing.BorderFactory.createTitledBorder("属性信息")); jTable1.setModel(new javax.swing.table.DefaultTableModel( new Object [][] { }, new String [] { } )); jTable1.setSelectionMode(javax.swing.ListSelectionModel.SINGLE_SELECTION); jTable1.addMouseListener(new java.awt.event.MouseAdapter() { public void mouseClicked(java.awt.event.MouseEvent evt) { jTable1MouseClicked(evt); } }); jScrollPane1.setViewportView(jTable1); jButton1.setText("移除"); jButton1.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { jButton1ActionPerformed(evt); } }); javax.swing.GroupLayout jPanel2Layout = new javax.swing.GroupLayout(jPanel2); jPanel2.setLayout(jPanel2Layout); jPanel2Layout.setHorizontalGroup( jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(jPanel2Layout.createSequentialGroup() .addContainerGap() .addComponent(jScrollPane1, javax.swing.GroupLayout.DEFAULT_SIZE, 284, Short.MAX_VALUE) .addContainerGap()) .addGroup(jPanel2Layout.createSequentialGroup() .addGap(122, 122, 122) .addComponent(jButton1) .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)) ); jPanel2Layout.setVerticalGroup( jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(jPanel2Layout.createSequentialGroup() .addComponent(jScrollPane1, javax.swing.GroupLayout.PREFERRED_SIZE, 0, Short.MAX_VALUE) .addGap(18, 18, 18) .addComponent(jButton1) .addContainerGap()) ); jPanel3.setBorder(javax.swing.BorderFactory.createTitledBorder("被选属性详细信息")); jLabel5.setText("属性名:"); jLabel6.setText("空值个数:"); jLabel7.setText("不同值个数:"); jLabel10.setText("label10"); jLabel10.setAutoscrolls(true); jLabel8.setText("唯一值个数:"); jLabel11.setText("label11"); jLabel12.setText("label12"); jLabel13.setText("lable13"); jTable2.setModel(new javax.swing.table.DefaultTableModel( new Object [][] { }, new String [] { } )); jScrollPane2.setViewportView(jTable2); javax.swing.GroupLayout jPanel3Layout = new javax.swing.GroupLayout(jPanel3); jPanel3.setLayout(jPanel3Layout); jPanel3Layout.setHorizontalGroup( jPanel3Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(jPanel3Layout.createSequentialGroup() .addContainerGap() .addGroup(jPanel3Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(jPanel3Layout.createSequentialGroup() .addComponent(jLabel5) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addComponent(jLabel10, javax.swing.GroupLayout.PREFERRED_SIZE, 140, javax.swing.GroupLayout.PREFERRED_SIZE)) .addGroup(jPanel3Layout.createSequentialGroup() .addComponent(jLabel6) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addComponent(jLabel11, javax.swing.GroupLayout.PREFERRED_SIZE, 128, javax.swing.GroupLayout.PREFERRED_SIZE)) .addGroup(jPanel3Layout.createSequentialGroup() .addComponent(jLabel7) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addComponent(jLabel12, javax.swing.GroupLayout.PREFERRED_SIZE, 116, javax.swing.GroupLayout.PREFERRED_SIZE)) .addGroup(jPanel3Layout.createSequentialGroup() .addComponent(jLabel8) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addComponent(jLabel13, javax.swing.GroupLayout.PREFERRED_SIZE, 116, javax.swing.GroupLayout.PREFERRED_SIZE))) .addGap(18, 18, 18) .addComponent(jScrollPane2, javax.swing.GroupLayout.DEFAULT_SIZE, 251, Short.MAX_VALUE) .addContainerGap()) ); jPanel3Layout.setVerticalGroup( jPanel3Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(jPanel3Layout.createSequentialGroup() .addContainerGap() .addGroup(jPanel3Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE) .addComponent(jLabel5) .addComponent(jLabel10)) .addGap(18, 18, 18) .addGroup(jPanel3Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE) .addComponent(jLabel6) .addComponent(jLabel11)) .addGap(22, 22, 22) .addGroup(jPanel3Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE) .addComponent(jLabel7) .addComponent(jLabel12)) .addGap(23, 23, 23) .addGroup(jPanel3Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE) .addComponent(jLabel8) .addComponent(jLabel13)) .addGap(33, 33, 33)) .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, jPanel3Layout.createSequentialGroup() .addGap(0, 0, Short.MAX_VALUE) .addComponent(jScrollPane2, javax.swing.GroupLayout.PREFERRED_SIZE, 144, javax.swing.GroupLayout.PREFERRED_SIZE) .addGap(22, 22, 22)) ); jPanel4.setBorder(javax.swing.BorderFactory.createTitledBorder("属性信息统计分析")); jComboBox1.setModel(new javax.swing.DefaultComboBoxModel<>(new String[] { "选择属性" })); jComboBox1.addItemListener(new java.awt.event.ItemListener() { public void itemStateChanged(java.awt.event.ItemEvent evt) { jComboBox1ItemStateChanged(evt); } }); jPanel5.setBorder(javax.swing.BorderFactory.createLineBorder(new java.awt.Color(0, 0, 0))); jSplitPane1.setDividerLocation(0); jSplitPane1.setDividerSize(0); javax.swing.GroupLayout jPanel5Layout = new javax.swing.GroupLayout(jPanel5); jPanel5.setLayout(jPanel5Layout); jPanel5Layout.setHorizontalGroup( jPanel5Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addComponent(jSplitPane1, javax.swing.GroupLayout.DEFAULT_SIZE, 481, Short.MAX_VALUE) ); jPanel5Layout.setVerticalGroup( jPanel5Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addComponent(jSplitPane1, javax.swing.GroupLayout.DEFAULT_SIZE, 271, Short.MAX_VALUE) ); javax.swing.GroupLayout jPanel4Layout = new javax.swing.GroupLayout(jPanel4); jPanel4.setLayout(jPanel4Layout); jPanel4Layout.setHorizontalGroup( jPanel4Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addComponent(jPanel5, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE) .addGroup(jPanel4Layout.createSequentialGroup() .addContainerGap() .addComponent(jComboBox1, 0, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE) .addContainerGap()) ); jPanel4Layout.setVerticalGroup( jPanel4Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(jPanel4Layout.createSequentialGroup() .addContainerGap() .addComponent(jComboBox1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addComponent(jPanel5, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)) ); javax.swing.GroupLayout layout = new javax.swing.GroupLayout(this); this.setLayout(layout); layout.setHorizontalGroup( layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(layout.createSequentialGroup() .addContainerGap() .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING, false) .addComponent(jPanel2, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE) .addComponent(jPanel1, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED) .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addComponent(jPanel4, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE) .addComponent(jPanel3, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)) .addContainerGap()) ); layout.setVerticalGroup( layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(layout.createSequentialGroup() .addContainerGap() .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(layout.createSequentialGroup() .addComponent(jPanel3, javax.swing.GroupLayout.PREFERRED_SIZE, 178, javax.swing.GroupLayout.PREFERRED_SIZE) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addComponent(jPanel4, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)) .addGroup(layout.createSequentialGroup() .addComponent(jPanel1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addComponent(jPanel2, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))) .addContainerGap()) ); }// </editor-fold>//GEN-END:initComponents private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton1ActionPerformed // TODO add your handling code here: for(int i=0;i<this.jTable1.getRowCount();++i){ if((Boolean)this.jTable1.getModel().getValueAt(i, 1)){ String str = this.jTable1.getModel().getValueAt(i, 2).toString(); String columnName = ConstantLibrary.columnMap2.get(str); EditTable.deleteColumn(columnName); } } myTableModel dtModel = new myTableModel(OperateJTable.getTableData(),OperateJTable.getTableColNames()){ public boolean isCellEditable(int row, int column) { if(column==2){ return false; }else{ return true; } } }; this.jTable1.setModel(dtModel); this.jLabel4.setText(String.valueOf(ConstantLibrary.columnNames.length)); String str = this.jTable1.getModel().getValueAt(0, 2).toString(); String columnName = ConstantLibrary.columnMap2.get(str); int count = EditTable.getNullCount(columnName); this.jLabel10.setText(str); this.jLabel11.setText(String.valueOf(count)); EditTable.getDiffientAndUniqueValueCount(columnName); this.jLabel12.setText(String.valueOf(EditTable.diffienceCount)); this.jLabel13.setText(String.valueOf(EditTable.uniqueCount)); DefaultTableModel dtModel2 = new DefaultTableModel(EditTable.dataValue,EditTable.columnValue){ public boolean isCellEditable(int row, int column) { return false; } }; this.jTable2.setModel(dtModel2); DefaultTableCellRenderer hr2 = (DefaultTableCellRenderer) this.jTable2.getTableHeader().getDefaultRenderer(); hr2.setHorizontalAlignment(DefaultTableCellRenderer.CENTER);//列名居中 DefaultTableCellRenderer tcr2 = new DefaultTableCellRenderer();// 设置table内容居中 tcr2.setHorizontalAlignment(SwingConstants.CENTER);// 这句和上句作用一样 this.jTable2.setDefaultRenderer(Object.class, tcr2); this.jTable2.setShowGrid(true); this.jcbm = new UserDefineComboBoxModel(); this.jComboBox1.setModel(this.jcbm); this.jComboBox1.setSelectedIndex(0); this.jSplitPane1.setRightComponent(null); }//GEN-LAST:event_jButton1ActionPerformed private void jTable1MouseClicked(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_jTable1MouseClicked // TODO add your handling code here: int row = this.jTable1.getSelectedRow(); String str = this.jTable1.getModel().getValueAt(row, 2).toString(); String columnName = ConstantLibrary.columnMap2.get(str); int count = EditTable.getNullCount(columnName); this.jLabel10.setText(str); this.jLabel11.setText(String.valueOf(count)); EditTable.getDiffientAndUniqueValueCount(columnName); this.jLabel12.setText(String.valueOf(EditTable.diffienceCount)); this.jLabel13.setText(String.valueOf(EditTable.uniqueCount)); DefaultTableModel dtMode = new DefaultTableModel(EditTable.dataValue,EditTable.columnValue){ public boolean isCellEditable(int row, int column) { return false; } }; this.jTable2.setModel(dtMode); DefaultTableCellRenderer hr = (DefaultTableCellRenderer) this.jTable2.getTableHeader().getDefaultRenderer(); hr.setHorizontalAlignment(DefaultTableCellRenderer.CENTER);//列名居中 DefaultTableCellRenderer tcr = new DefaultTableCellRenderer();// 设置table内容居中 tcr.setHorizontalAlignment(SwingConstants.CENTER);// 这句和上句作用一样 this.jTable2.setDefaultRenderer(Object.class, tcr); this.jTable2.setShowGrid(true); }//GEN-LAST:event_jTable1MouseClicked private void jComboBox1ItemStateChanged(java.awt.event.ItemEvent evt) {//GEN-FIRST:event_jComboBox1ItemStateChanged // TODO add your handling code here: if(evt.getStateChange() == ItemEvent.SELECTED){ System.out.println(this.jComboBox1.getSelectedItem()); //String colNameTemp = ConstantLibrary.columnMap2.get(this.jComboBox1.getSelectedItem()); this.jSplitPane1.setRightComponent(DataStatisticsPane.CreatePane(this.jComboBox1.getSelectedItem().toString())); } }//GEN-LAST:event_jComboBox1ItemStateChanged private ComboBoxModel jcbm = null; private MainFunction mf = null; // Variables declaration - do not modify//GEN-BEGIN:variables private javax.swing.JButton jButton1; private javax.swing.JComboBox<String> jComboBox1; private javax.swing.JLabel jLabel1; private javax.swing.JLabel jLabel10; private javax.swing.JLabel jLabel11; private javax.swing.JLabel jLabel12; private javax.swing.JLabel jLabel13; private javax.swing.JLabel jLabel2; private javax.swing.JLabel jLabel3; private javax.swing.JLabel jLabel4; private javax.swing.JLabel jLabel5; private javax.swing.JLabel jLabel6; private javax.swing.JLabel jLabel7; private javax.swing.JLabel jLabel8; private javax.swing.JPanel jPanel1; private javax.swing.JPanel jPanel2; private javax.swing.JPanel jPanel3; private javax.swing.JPanel jPanel4; private javax.swing.JPanel jPanel5; private javax.swing.JScrollPane jScrollPane1; private javax.swing.JScrollPane jScrollPane2; private javax.swing.JSplitPane jSplitPane1; private javax.swing.JTable jTable1; private javax.swing.JTable jTable2; // End of variables declaration//GEN-END:variables @Override public void componentResized(ComponentEvent e) { //throw new UnsupportedOperationException("Not supported yet."); //To change body of generated methods, choose Tools | Templates. int height = this.getHeight(); int height2 = this.jPanel2.getHeight(); this.jScrollPane1.setSize(this.jScrollPane1.getWidth(), height2-80); this.jButton1.setLocation(this.jPanel2.getWidth()/2-this.jButton1.getWidth()/2, height2-45); this.jTable1.setSize(this.jScrollPane1.getWidth(),this.jScrollPane1.getHeight()); this.jTable2.setSize(this.jScrollPane2.getWidth(),this.jScrollPane2.getHeight()); } @Override public void componentMoved(ComponentEvent e) { throw new UnsupportedOperationException("Not supported yet."); //To change body of generated methods, choose Tools | Templates. } @Override public void componentShown(ComponentEvent e) { throw new UnsupportedOperationException("Not supported yet."); //To change body of generated methods, choose Tools | Templates. } @Override public void componentHidden(ComponentEvent e) { throw new UnsupportedOperationException("Not supported yet."); //To change body of generated methods, choose Tools | Templates. } class myTableModel extends DefaultTableModel{ public myTableModel(Object[][] data,Object[] columnNames){ super(data,columnNames); } public Class getColumnClass(int c) { return getValueAt(0,c).getClass(); } } }
true
daf56b5ad285a3030c94ef7e33811c041817eaff
Java
braisdom/ObjectiveSql-IntelliJ-Plugin
/src/main/java/com/github/braisdom/objsql/intellij/ModelMethodBuilder.java
UTF-8
3,086
2.203125
2
[ "Apache-2.0" ]
permissive
package com.github.braisdom.objsql.intellij; import com.intellij.openapi.project.Project; import com.intellij.psi.PsiClass; import com.intellij.psi.PsiModifier; import com.intellij.psi.PsiType; import com.intellij.psi.impl.light.LightFieldBuilder; import java.util.List; import static com.github.braisdom.objsql.intellij.ObjSqlPsiAugmentProvider.*; final class ModelMethodBuilder { static void buildField(PsiClass psiClass, List result) { buildTableName(psiClass, result); buildRawAttributes(psiClass, result); } static void buildMethod(PsiClass psiClass, List result) { buildGetRawAttributes(psiClass, result); buildGetRawAttribute(psiClass, result); } private static void buildRawAttributes(PsiClass psiClass, List result) { PsiType fieldType = createParameterType(psiClass.getProject(), "java.util.Map", "java.lang.String", "java.lang.Object"); ObjsqlLightFieldBuilder primaryBuilder = new ObjsqlLightFieldBuilder("rawAttributes", fieldType, psiClass); primaryBuilder.setNavigationElement(psiClass); primaryBuilder.setModifiers(PsiModifier.PRIVATE, PsiModifier.FINAL); primaryBuilder.setContainingClass(psiClass); result.add(primaryBuilder); } private static void buildTableName(PsiClass psiClass, List result) { PsiType fieldType = createParameterType(psiClass.getProject(), "java.lang.String"); ObjsqlLightFieldBuilder tableNameBuilder = new ObjsqlLightFieldBuilder("TABLE_NAME", fieldType, psiClass); tableNameBuilder.setModifiers(PsiModifier.PUBLIC, PsiModifier.STATIC, PsiModifier.FINAL); tableNameBuilder.setContainingClass(psiClass); tableNameBuilder.setNavigationElement(tableNameBuilder); result.add(tableNameBuilder); } private static void buildGetRawAttributes(PsiClass psiClass, List result) { Project project = psiClass.getProject(); ObjSqlLightMethodBuilder methodBuilder = new ObjSqlLightMethodBuilder(psiClass.getManager(), "getRawAttributes"); PsiType psiType = getProjectType("java.util.Map", project); methodBuilder.withMethodReturnType(psiType) .withContainingClass(psiClass) .withModifier(PsiModifier.PUBLIC, PsiModifier.FINAL); if(!checkMethodExists(psiClass, methodBuilder)) { result.add(methodBuilder); } } private static void buildGetRawAttribute(PsiClass psiClass, List result) { Project project = psiClass.getProject(); ObjSqlLightMethodBuilder methodBuilder = new ObjSqlLightMethodBuilder(psiClass.getManager(), "getRawAttribute"); PsiType psiType = getProjectType("java.lang.Object", project); methodBuilder.withParameter("key", "java.lang.String") .withMethodReturnType(psiType) .withContainingClass(psiClass) .withModifier(PsiModifier.PUBLIC, PsiModifier.FINAL); if(!checkMethodExists(psiClass, methodBuilder)) { result.add(methodBuilder); } } }
true
3906a4b55236571278aa23d1e6b36256567b007d
Java
prathaphegde/Playground
/Checking for Perfect Batch/Main.java
UTF-8
755
3.234375
3
[]
no_license
import java.util.Scanner; class Main { public static void main(String args[]) { Scanner in = new Scanner(System.in); int n = in.nextInt(); int list[] = new int[n]; for(int i = 0;i<=n-1;i++) { list[i] = in.nextInt(); } int sum = 0; int next = 0; int div = n/2; for(int j = 0;j<=n-1;j++) { if(j<=div) { sum = sum +list[j]; } if(j>=div) { next = next + list[j]; } } if( sum == next) { System.out.print("Perfect Batch"); //System.out.println(sum); //System.out.println(next); } else System.out.print("Not a Perfect Batch"); } }
true
b51cf27fc4e3316b0d5833916f631b4f103fd121
Java
Rajeeveie/java
/src/tightCoupling/TestMusic.java
UTF-8
442
2.796875
3
[]
no_license
package tightCoupling; import java.util.Scanner; public class TestMusic { public static void main(String[] args) { AviPlayer a =new AviPlayer(); Scanner sc=new Scanner(System.in); System.out.println("please type a song to listen in Avi format"); String song=sc.nextLine(); a.play(song); Mp4Player m=new Mp4Player(); System.out.println("please type a song to listen in Mp4 format"); song =sc.nextLine(); m.play(song); } }
true
29fb4ffc167a791f05dee6da8924bfb69f923c2c
Java
chuanjiabao1981/check_v3_android
/src/com/check/v3/ui/dialog/ProgressDialogFragment.java
UTF-8
2,319
2.28125
2
[]
no_license
package com.check.v3.ui.dialog; import android.app.Dialog; import android.app.ProgressDialog; import android.content.DialogInterface; import android.os.Bundle; import android.text.TextUtils; import com.actionbarsherlock.app.SherlockDialogFragment; import com.check.v3.ui.dialog.DatePickerDialogFragment.DatePickerDialogFragmentListener; public class ProgressDialogFragment extends SherlockDialogFragment { private static final String ARG_DIALOG_ID = "dialog_id"; protected static final String ARG_TITLE = "title"; protected static final String ARG_MESSAGE = "message"; public static ProgressDialogFragment newInstance(int dialogId, String title, String message) { ProgressDialogFragment fragment = new ProgressDialogFragment(); Bundle args = new Bundle(); args.putInt(ARG_DIALOG_ID, dialogId); args.putString(ARG_TITLE, title); args.putString(ARG_MESSAGE, message); fragment.setArguments(args); return fragment; } @Override public Dialog onCreateDialog(Bundle savedInstanceState) { Bundle args = getArguments(); String title = args.getString(ARG_TITLE); String message = args.getString(ARG_MESSAGE); ProgressDialog dialog = new ProgressDialog(getActivity()); dialog.setIndeterminate(true); dialog.setCancelable(false); dialog.setCanceledOnTouchOutside(false); if(!TextUtils.isEmpty(title)){ dialog.setTitle(title); } if(!TextUtils.isEmpty(message)){ dialog.setMessage(message); } return dialog; } private int getDialogId() { return getArguments().getInt(ARG_DIALOG_ID); } @Override public void onCancel(DialogInterface dialog) { super.onCancel(dialog); getListener().dialogCancelled(getDialogId()); } public interface ProgressDialogFragmentListener { void dialogCancelled(int dialogId); } private ProgressDialogFragmentListener getListener() { try { return (ProgressDialogFragmentListener) getTargetFragment(); } catch (ClassCastException e) { throw new ClassCastException(getTargetFragment().getClass() + " must implement ProgressDialogFragmentListener"); } } }
true
43841514edc6ca14c6555b54d38b211a14a768d1
Java
OleksZamkovyi/Practice4
/src/Test.java
UTF-8
1,409
3.21875
3
[]
no_license
import com.epam.rd.java.basic.practice4.Part1; import java.io.File; import java.io.IOException; import java.io.PrintWriter; import java.util.Scanner; public class Test { public static String getInput(String fileName) { StringBuilder sb = new StringBuilder(); try { Scanner scanner = new Scanner(new File(fileName), "Cp1251"); while (scanner.hasNextLine()) { sb.append(scanner.nextLine()).append(System.lineSeparator()); } scanner.close(); return sb.toString().trim(); } catch (IOException ex) { ex.printStackTrace(); } return sb.toString(); } public static void main(String[] args) { try (PrintWriter file = new PrintWriter(System.getProperty("user.dir") + "\\part6.txt", "Cp1251")) { file.print("Is there anybody going to listen to my story \n" + "Лягає день. Він віддає свої надії ночі. \n" + "Робітники \n" + "Заморились працювати. \n" + "С барабаном ходит ёжик. Бум-бум-бум."); } catch (IOException ex) { System.out.println(ex.getMessage()); } System.out.println(getInput("part1.txt")); Part1.main(new String[]{"", ""}); } }
true
f1325802508f8f34621ae1877fd054b0360b4e28
Java
krishna-rao-g/CoreJavaTraining
/src/com/core/java/oops/AbstractArea.java
UTF-8
1,070
3.984375
4
[]
no_license
package com.core.java.oops; public class AbstractArea extends Object{ public static void main(String[] args) { //Figure f = new Figure(2,3 ); Rectangle r = new Rectangle(2,4); System.out.println(r); System.out.println(r.area()); Triangle t = new Triangle(3, 4); t.area(); System.out.println(t); System.out.println(t.area()); } } abstract class Figure{ double dim1; double dim2; Figure(double dim1, double dim2){ this.dim1 = dim1; this.dim2 = dim2; System.out.println("Figure"); } abstract double area(); } class Rectangle extends Figure{ Rectangle(double a, double b){ super(a, b); System.out.println("Rectangle"); } @Override double area() { return dim1*dim2; } @Override public String toString() { return "dim1: " + dim1 + " dim2: " + dim2; } } class Triangle extends Figure{ Triangle(double a, double b){ super(a, b); System.out.println("Triangle"); } @Override double area() { return dim1*dim2/2; } @Override public String toString() { return "dim1: " + dim1 + " dim2: " + dim2; } }
true
d64ee4e4dd31dd73e39577b6565c3f836448b7d0
Java
Matdev94/Application_JEE7
/Chapitre1a8/src/chapitre4/Rectangle.java
ISO-8859-2
1,234
3.640625
4
[]
no_license
package chapitre4; public class Rectangle { private float largeur; private float longueur; // Position du centre du rectangle (X,Y) dans le plan. private int x; private int y; private float angle; public Rectangle(float l, float L, int X, int Y){ longueur = L ; largeur = l ; x = X ; y = Y ; } public Rectangle(float l, float L){ largeur = l ; longueur = L ; } public Rectangle() { largeur=10; longueur = 20; } /* Les oprations = mthodes = fonctions membres */ public int compareSurface(Rectangle r) { float s1 = largeur * longueur ; float s2 = r.largeur * r.longueur ; if (s1 > s2) return 1 ; if (s1==s2) return 0 ; return -1; } void tourner(float a) { /* A coder */ } void agrandir(float a) { if (a > 1) { largeur = largeur * a ; longueur = longueur * a ; } } void reduire(float a) { if (a < 1) { largeur = largeur * a ; longueur = longueur * a ; } } void translater(int dx, int dy) { x = x + dx; y = y + dy; } void afficher() { System.out.println("Ma longueur= " + longueur + " et ma largeur= " + largeur); System.out.println("Je suis en X = " + x + " et en Y = " + y); } }
true
469277d289e786ddd94cc5013b5f17794f92fd0c
Java
tambepallavi/JavaPrograms
/src/OOP_Abstract/TestPage.java
UTF-8
483
2.375
2
[]
no_license
package OOP_Abstract; public class TestPage { public static void main(String[] args) { LoginPage lp =new LoginPage(); lp.header(); lp.footer(); lp.title(); lp.DoLogin("pallavi", "1234"); page.logo(); page p =new LoginPage(); p.header(); p.footer(); p.title(); //page p1 =new page(); ///Page is the abstract class we can not create object of abstract class } }
true
cd7b7e98767af31b6f35f4ba9047eb4f620fc227
Java
arraycto/hspaas
/hsmms/src/main/java/com/huashi/mms/template/service/MmsTemplateService.java
UTF-8
12,392
1.867188
2
[]
no_license
package com.huashi.mms.template.service; import java.util.Date; import java.util.HashMap; import java.util.List; import java.util.Map; import org.apache.commons.collections.CollectionUtils; import org.apache.commons.lang3.StringUtils; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.transaction.annotation.Transactional; import org.apache.dubbo.config.annotation.Reference; import org.apache.dubbo.config.annotation.Service; import com.alibaba.fastjson.JSON; import com.huashi.common.user.service.IUserMmsConfigService; import com.huashi.common.user.service.IUserService; import com.huashi.common.util.IdGenerator; import com.huashi.common.vo.BossPaginationVo; import com.huashi.common.vo.PaginationVo; import com.huashi.constants.CommonContext.AppType; import com.huashi.mms.template.constant.MmsTemplateContext.ApproveStatus; import com.huashi.mms.template.dao.MmsMessageTemplateMapper; import com.huashi.mms.template.domain.MmsMessageTemplate; import com.huashi.mms.template.domain.MmsMessageTemplateBody; import com.huashi.mms.template.exception.ModelApplyException; import com.huashi.sms.passage.context.PassageContext.RouteType; /** * 彩信模板服务实现 * * @author zhengying * @version V1.0 * @date 2019年1月20日 下午10:06:27 */ @Service public class MmsTemplateService implements IMmsTemplateService { @Autowired private IdGenerator idGenerator; @Reference private IUserService userService; @Reference private IUserMmsConfigService userMmsConfigService; @Autowired private MmsMediaFileService mmsMediaFileService; @Autowired private MmsMessageTemplateMapper mmsMessageTemplateMapper; @Reference private IMmsTemplateBodyService mmsTemplateBodyService; private final Logger logger = LoggerFactory.getLogger(getClass()); @Override public PaginationVo<MmsMessageTemplate> findPage(int userId, String status, String title, String currentPage) { int _currentPage = PaginationVo.parse(currentPage); Map<String, Object> params = new HashMap<>(); params.put("userId", userId); if (StringUtils.isNotEmpty(status)) { params.put("status", status); } if (StringUtils.isNotEmpty(title)) { params.put("title", title); } int totalRecord = mmsMessageTemplateMapper.getCountByUserId(params); if (totalRecord == 0) { return null; } params.put("startPage", PaginationVo.getStartPage(_currentPage)); params.put("pageRecord", PaginationVo.DEFAULT_RECORD_PER_PAGE); List<MmsMessageTemplate> list = mmsMessageTemplateMapper.findPageListByUserId(params); if (list == null || list.isEmpty()) { return null; } return new PaginationVo<>(list, _currentPage, totalRecord); } @Override public boolean update(MmsMessageTemplate template) throws ModelApplyException { if (StringUtils.isEmpty(template.getName())) { throw new ModelApplyException("模板名称不能为空"); } if (StringUtils.isEmpty(template.getTitle())) { throw new ModelApplyException("模板标题不能为空"); } if (CollectionUtils.isEmpty(template.getBodies())) { throw new ModelApplyException("多媒体结构体数据为空"); } MmsMessageTemplate originTemplate = null; try { originTemplate = isAllowAccess(template.getUserId(), template.getId()); } catch (IllegalArgumentException e) { logger.error("模板数据鉴权失败 : {}", e.getMessage()); return false; } // template.setRegexValue(parseContent2Regex(template.getContent())); template.setCreateTime(originTemplate.getCreateTime()); try { template.setCreateTime(new Date()); // 融合平台判断 后台添加 状态默认 if (AppType.WEB.getCode() == template.getAppType()) { template.setStatus(ApproveStatus.WAITING.getValue()); } // if (template.getStatus() == ApproveStatus.SUCCESS.getValue()) { // pushToRedis(template.getUserId(), template); // } boolean isOk = mmsTemplateBodyService.delete(template.getId()); if (!isOk) { logger.error("模板数据[" + JSON.toJSONString(template) + "]删除模板内容失败"); throw new ModelApplyException("数据操作异常"); } isOk = mmsTemplateBodyService.batchSave(template.getBodies()); if (!isOk) { logger.error("模板多媒体结构数据[" + JSON.toJSONString(template.getBodies()) + "]插入失败"); throw new ModelApplyException(); } isOk = mmsMessageTemplateMapper.updateByPrimaryKey(template) > 0; if (!isOk) { logger.error("模板数据[" + JSON.toJSONString(template) + "]更新失败"); throw new ModelApplyException(); } return isOk; } catch (Exception e) { logger.error("模板数据:{" + JSON.toJSONString(template) + "]修改失败", e); throw new ModelApplyException("模板修改失败"); } } /** * 是否允许被访问(针对用户ID进行鉴权,防止恶意使用userID来篡改其他userId数据) * * @param userId * @param templateId * @return */ private MmsMessageTemplate isAllowAccess(int userId, long templateId) { MmsMessageTemplate template = get(templateId); if (template == null) { throw new IllegalArgumentException("模板 [" + templateId + "]信息为空"); } // 仅针对WEB用户自己添加的模板进行过滤 if (AppType.WEB.getCode() == template.getAppType() && template.getUserId() != userId) { throw new IllegalArgumentException("用户模板[" + templateId + "]数据不匹配,原模板用户ID:[" + template.getUserId() + "] , 本次用户ID:[" + userId + "]"); } if (AppType.WEB.getCode() == template.getAppType() && template.getStatus() != ApproveStatus.WAITING.getValue()) { throw new IllegalArgumentException("用户模板[" + templateId + "]模板状态为非待审核状态[" + template.getStatus() + "]不能修改"); } return template; } @Override public boolean deleteById(long id) { MmsMessageTemplate template = get(id); if (template == null) { logger.error("用户彩信模板为空,删除失败, ID:{}", id); return false; } return mmsMessageTemplateMapper.deleteByPrimaryKey(id) > 0; } @Override public MmsMessageTemplate get(long id) { return mmsMessageTemplateMapper.selectByPrimaryKey(id); } @Override public BossPaginationVo<MmsMessageTemplate> findPageBoos(int pageNum, String keyword, String status, String userId) { BossPaginationVo<MmsMessageTemplate> page = new BossPaginationVo<>(); Map<String, Object> paramMap = new HashMap<>(); paramMap.put("keyword", keyword); paramMap.put("status", status); paramMap.put("userId", userId); int count = mmsMessageTemplateMapper.findCount(paramMap); page.setCurrentPage(pageNum); page.setTotalCount(count); paramMap.put("start", page.getStartPosition()); paramMap.put("end", page.getPageSize()); List<MmsMessageTemplate> list = mmsMessageTemplateMapper.findList(paramMap); if (CollectionUtils.isEmpty(list)) { return null; } for (MmsMessageTemplate t : list) { if (t == null) { continue; } t.setUserModel(userService.getByUserId(t.getUserId())); t.setApptypeText(AppType.parse(t.getAppType()).getName()); t.setRouteTypeText(RouteType.parse(t.getRouteType()).getName()); } page.setList(list); return page; } @Override public boolean approve(long id, int status, String remark) { MmsMessageTemplate template = get(id); template.setStatus(status); template.setRemark(remark); template.setApproveTime(new Date()); return mmsMessageTemplateMapper.updateByPrimaryKeySelective(template) > 0; } @Override public boolean delete(long id, int userId) { try { isAllowAccess(userId, id); } catch (IllegalArgumentException e) { logger.error("模板数据鉴权失败 : {}", e.getMessage()); return false; } return mmsMessageTemplateMapper.deleteByPrimaryKey(id) > 0; } @Override public MmsMessageTemplate getWithUserId(Long id, int userId) { try { MmsMessageTemplate template = isAllowAccess(userId, id); if (template == null) { return null; } template.setBodies(mmsTemplateBodyService.getBodiesByTemplateId(id)); return template; } catch (Exception e) { logger.error("模板[" + id + "] 用户ID:[" + userId + "] 获取模板数据失败 ", e); return null; } } @Override public MmsMessageTemplate getByModelId(String modelId) { return mmsMessageTemplateMapper.selectByModelId(modelId); } @Override public boolean isModelIdAvaiable(String modelId, int userId) { MmsMessageTemplate template = getByModelId(modelId); if (template == null) { logger.error("模板ID[" + modelId + "]数据为空"); return false; } if (userId == 0 || template.getUserId() != userId) { logger.error("模板ID[" + modelId + "] 用户[" + userId + "]数据权限不符"); return false; } if (ApproveStatus.SUCCESS.getValue() != template.getStatus()) { logger.error("模板ID[" + modelId + "] 状态[" + template.getStatus() + "]下不可用"); return false; } return true; } @Override @Transactional(rollbackFor = ModelApplyException.class) public String save(MmsMessageTemplate template) throws ModelApplyException { if (StringUtils.isEmpty(template.getName())) { throw new ModelApplyException("模板名称不能为空"); } if (StringUtils.isEmpty(template.getTitle())) { throw new ModelApplyException("模板标题不能为空"); } if (CollectionUtils.isEmpty(template.getBodies())) { throw new ModelApplyException("多媒体结构体数据为空"); } try { template.setCreateTime(new Date()); // 融合平台判断 后台添加 状态默认 if (AppType.WEB.getCode() == template.getAppType()) { template.setStatus(ApproveStatus.WAITING.getValue()); } // if (template.getStatus() == ApproveStatus.SUCCESS.getValue()) { // pushToRedis(template.getUserId(), template); // } template.setModelId(idGenerator.generateStr()); boolean isOk = mmsMessageTemplateMapper.insertSelective(template) > 0; if (!isOk) { logger.error("模板数据[" + JSON.toJSONString(template) + "]插入失败"); throw new ModelApplyException(); } for (MmsMessageTemplateBody body : template.getBodies()) { body.setTemplateId(template.getId()); } isOk = mmsTemplateBodyService.batchSave(template.getBodies()); if (!isOk) { logger.error("模板多媒体结构数据[" + JSON.toJSONString(template.getBodies()) + "]插入失败"); throw new ModelApplyException(); } return template.getModelId(); } catch (Exception e) { logger.error("模板数据:{" + JSON.toJSONString(template) + "]报备失败", e); throw new ModelApplyException("模板报备失败"); } } }
true
662baa11b40dd936271f472a9ea1c80c8572cb94
Java
HistoricalValue/spawncamping-octo-ninja
/lib/Polyglot/src/polyglot/ext/jl/ast/ClassLit_c.java
UTF-8
2,031
2.6875
3
[]
no_license
package polyglot.ext.jl.ast; import polyglot.ast.ClassLit; import polyglot.ast.Expr; import polyglot.ast.Node; import polyglot.ast.TypeNode; import polyglot.types.SemanticException; import polyglot.util.CodeWriter; import polyglot.util.Position; import polyglot.visit.NodeVisitor; import polyglot.visit.PrettyPrinter; import polyglot.visit.TypeChecker; /** * A <code>ClassLit</code> represents a class literal expression. * A class literal expressions is an expression consisting of the * name of a class, interface, array, or primitive type followed by a period (.) * and the token class. */ public class ClassLit_c extends Lit_c implements ClassLit { protected TypeNode typeNode; public ClassLit_c(Position pos, TypeNode typeNode) { super(pos); this.typeNode = typeNode; } public TypeNode typeNode() { return this.typeNode; } public ClassLit typeNode(TypeNode typeNode) { if (this.typeNode == typeNode) { return this; } ClassLit_c n = (ClassLit_c) copy(); n.typeNode = typeNode; return n; } /** * Cannot return the correct object (except for maybe * some of the primitive arrays), so we just return null here. */ public Object objValue() { return null; } public Node visitChildren(NodeVisitor v) { TypeNode tn = (TypeNode)visitChild(this.typeNode, v); return this.typeNode(tn); } /** Type check the expression. */ public Node typeCheck(TypeChecker tc) throws SemanticException { return type(tc.typeSystem().Class()); } public String toString() { return typeNode.toString() + ".class"; } /** Write the expression to an output file. */ public void prettyPrint(CodeWriter w, PrettyPrinter tr) { w.begin(0); print(typeNode, w, tr); w.write(".class"); w.end(); } /** * According to the JLS 2nd Ed, sec 15.28, a class literal * is not a compile time constant. */ public boolean isConstant() { return false; } public Object constantValue() { return null; } }
true
1c1e2a90378a4b175fe5eba97f158bd79d9e51e8
Java
msfj/msjf-cas
/cas-core/src/main/java/com/msjf/finance/cas/modules/branch/service/BranchService.java
UTF-8
668
1.898438
2
[]
no_license
package com.msjf.finance.cas.modules.branch.service; import com.msjf.finance.cas.common.dao.entity.BranchEntity; import com.msjf.finance.msjf.core.response.Response; import java.util.List; import java.util.Map; /** * Created by cheng on 2019/1/24. */ public interface BranchService { /** * 新增部门基本信息表 */ Response insBranchInfo(BranchEntity branchEntity) throws RuntimeException; Response delBranchInfo(Map<String, Object> mapParams)throws RuntimeException; Response updBranchInfo(BranchEntity branchEntity)throws RuntimeException; Response queryBranch(Map<String, Object> mapParams)throws RuntimeException; }
true
c151c7834c6b516ce3103a9b60509260903371d8
Java
momosv/wx
/src/main/java/com/cn/xt/mp/feedback/wxSecurity/wxentity/js/JsapiTicket.java
UTF-8
584
1.914063
2
[]
no_license
package com.cn.xt.mp.feedback.wxSecurity.wxentity.js; import java.io.Serializable; /** * @author linshengwen * @version 1.0 * @description * @date 2018/12/17 10:26 **/ public class JsapiTicket implements Serializable { private String ticket; private String expiresIn; public String getTicket() { return ticket; } public void setTicket(String ticket) { this.ticket = ticket; } public String getExpiresIn() { return expiresIn; } public void setExpiresIn(String expiresIn) { this.expiresIn = expiresIn; } }
true
94952918e30a4d5952aec95d8ddc8cb0d8043107
Java
TTLProject/Incubation
/Incubation/src/objectrepository/CollegeFeedback_objects.java
UTF-8
879
2.34375
2
[]
no_license
package objectrepository; import org.openqa.selenium.By; import org.openqa.selenium.WebDriver; import org.openqa.selenium.WebElement; public class CollegeFeedback_objects extends BaseClass { public CollegeFeedback_objects(WebDriver driver) { super(driver); } static By feedback = By.xpath(""); static By domain = By.xpath(""); static By trainername = By.xpath(""); static By comments = By.xpath(""); public static WebElement feedback() { element =driver.findElement(feedback); return element; } public static WebElement domain() { element =driver.findElement(domain); return element; } public static WebElement trainerName() { element = driver.findElement(trainername); return element; } public static WebElement comments() { element = driver.findElement(comments); return element; } }
true
4acfef01f40b27b7c54befa4d78bd9b53921b639
Java
youp911/modelibra
/Educ/TravelImpression/src/travel/wicket/app/home/HomePageMenuPanel.java
UTF-8
5,724
1.851563
2
[]
no_license
package travel.wicket.app.home; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; import org.apache.wicket.markup.html.link.Link; import org.apache.wicket.markup.html.panel.Panel; import org.modelibra.wicket.concept.CountryLanguageChoicePanel; import org.modelibra.wicket.container.DmPage; import org.modelibra.wicket.container.DmPanel; import org.modelibra.wicket.security.AppSession; import org.modelibra.wicket.view.View; import org.modelibra.wicket.view.ViewModel; import travel.Travel; import travel.impression.Impression; import travel.impression.message.Messages; import travel.impression.place.Places; import travel.impression.traveler.Traveler; import travel.impression.traveler.Travelers; import travel.reference.Reference; import travel.reference.countrylanguage.CountryLanguage; import travel.reference.countrylanguage.CountryLanguages; import travel.wicket.app.TravelApp; import travel.wicket.app.about.AboutPage; import travel.wicket.app.upload.UploadPage; import travel.wicket.impression.traveler.EntityUpdateTablePage; /** * Application home page menu panel. * * @author Dzenan Ridjanovic * @version 2007-05-01 */ public class HomePageMenuPanel extends DmPanel { private static Log log = LogFactory.getLog(HomePageMenuPanel.class); public HomePageMenuPanel(final String wicketId, DmPage dmPage) { super(wicketId); try { TravelApp travelApp = (TravelApp) getApplication(); Travel travel = travelApp.getTravel(); Impression impression = travel.getImpression(); Reference reference = travel.getReference(); final AppSession appSession = getAppSession(); // Update Places ViewModel placesViewModel = new ViewModel(); placesViewModel.setModel(impression); Places places = impression.getPlaces(); Places travelersOrderedByName = places.getPlacesOrderedByName(true); placesViewModel.setEntities(travelersOrderedByName); View placesView = new View(); placesView.setWicketId("placeUpdateTable"); // placesView.setContextPage(dmPage); placesView.setPage(dmPage); placesView.setUpdate(true); Link placeUpdateTableLink = EntityUpdateTablePage.link( placesViewModel, placesView); add(placeUpdateTableLink); // Update Travelers ViewModel travelersViewModel = new ViewModel(); travelersViewModel.setModel(impression); Travelers travelers = impression.getTravelers(); Travelers travelersOrderedByLastFirstName = travelers .getTravelersOrderedByLastFirstName(true); travelersViewModel.setEntities(travelersOrderedByLastFirstName); View travelersView = new View(); travelersView.setWicketId("travelerUpdateTable"); // travelersView.setContextPage(dmPage); travelersView.setPage(dmPage); travelersView.setUpdate(true); Link travelerUpdateTableLink = EntityUpdateTablePage.link( travelersViewModel, travelersView); add(travelerUpdateTableLink); // Update Messages of the signed in traveler ViewModel travelerMessagesViewModel = new ViewModel(); travelerMessagesViewModel.setModel(impression); View travelerMessagesView = new View(); travelerMessagesView.setWicketId("messageUpdateTable"); Traveler traveler = (Traveler) appSession.getSignedInUser(); if (traveler != null) { Messages messages = traveler.getMessages(); travelerMessagesViewModel.setEntities(messages); // travelerMessagesView.setContextPage(dmPage); travelerMessagesView.setPage(dmPage); travelerMessagesView.setUpdate(true); } Link messageUpdateTableLink = EntityUpdateTablePage.link( travelerMessagesViewModel, travelerMessagesView); add(messageUpdateTableLink); if (traveler == null) { messageUpdateTableLink.setVisible(false); } // Sign out Link signoutLink = new Link("signout") { public void onClick() { appSession.invalidate(); setResponsePage(HomePage.class); } }; add(signoutLink); if (!appSession.isUserSignedIn()) { signoutLink.setVisible(false); } add(new Link("about") { public void onClick() { setResponsePage(AboutPage.class); } }); // I18n ViewModel languageViewModel = new ViewModel(); languageViewModel.setModel(reference); CountryLanguages languages = reference.getCountryLanguages(); languageViewModel.setEntities(languages); String languageCode = null; CountryLanguage defaultLanguage = null; languageCode = appSession.getLocale().getLanguage(); defaultLanguage = (CountryLanguage) languages .retrieveByCode(languageCode); if (defaultLanguage == null) { defaultLanguage = (CountryLanguage) languages .retrieveByCode("en"); } languageViewModel.setEntity(defaultLanguage); languageViewModel.getUserProperties().addUserProperty( "getLanguageMethod", "getLanguage"); languageViewModel.getUserProperties().addUserProperty( "getLanguageListMethod", "getLanguageList"); languageViewModel.getUserProperties().addUserProperty( "getLanguageCodeMethod", "getLanguageCode"); View countryLanguageView = new View(); countryLanguageView.setWicketId("languageChoiceSection"); Panel languageChoicePanel = new CountryLanguageChoicePanel( languageViewModel, countryLanguageView); add(languageChoicePanel); if (!travel.getDomainConfig().isI18n()) { languageChoicePanel.setVisible(false); } // Upload add(new Link("upload") { public void onClick() { setResponsePage(UploadPage.class); } }); } catch (Exception e) { log.error("Error in HomePageMenuPanel: " + e.getMessage()); } } }
true
dc7553005815fad2aa5510922e19ef0aac4c7fb8
Java
AndriiUsatov/simple_linked_list
/src/main/java/Main.java
UTF-8
882
3.515625
4
[]
no_license
import java.util.Iterator; /** * Created by andrii on 13.08.17. */ public class Main { public static void main(String[] args) { SimpleLinkedList<Integer> list = new SimpleLinkedList<Integer>(); list.add(1); // list.add(2); for (int i = 0; i < 100; i++) { list.add((int)(Math.random() * 1000)); } // list.add(1000); // print(list); // System.out.println(list.getLast() + " " + list.getFirst() + " " + list.get(list.size()-1)); Iterator iterator = list.iterator(); while (iterator.hasNext()){ System.out.println(iterator.next()); } } // static void print(SimpleLinkedList list){ // for (int i = 0; i < list.size(); i++) { // System.out.println(list.get(i)); // } // System.out.println("List size is: " + list.size()); // } }
true
3f4bd352af9b778efefbecede983f1ecaa2c208c
Java
DimitarMilevski/Homework1
/src/Race/truck.java
UTF-8
1,153
3.75
4
[]
no_license
package Race; public class truck { static int speed = 0; //static variable to hold initial speed String type ; String engineType; String driverName; //constructor accepting 3 arguments- name, car type, and engine type public truck(String driverName,String type, String engineType){ this.driverName = "Lewis Hamilton"; this.type ="Dodge Ram"; this.engineType = "SRT-10"; System.out.println("Driver: "+ driverName + " driving " + type + " with engine " + engineType); } //constructor accepting driver's name and car type public truck(String driverName,String type){ this.driverName = "Lewis Hamilton"; this.type ="Dodge Ram"; System.out.println("Driver: "+ driverName + " driving " + type); } // method to accelerate the speed by 46 mph public int accelerateSpeed(){ speed += 46; return speed; } // method returning the current speed of the car public int getCurrentSpeed(int speed){ return speed; } //method that multiply the speed by 1.5 public int nitro(){ return speed *= 1.5; } //stop method public void stop(int speed){ speed = 0; System.out.println("The current speed of " + type + " is " + speed); } }
true
225f1dfa2f7ea8db485149615d7f3c6e412e23c2
Java
ShawnSWu/RollCall
/app/src/main/java/com/shawn/newrollcall/MainView/Profile/store/AccountInfoStore.java
UTF-8
855
2
2
[ "MIT" ]
permissive
package com.shawn.newrollcall.MainView.Profile.store; import com.shawn.newrollcall.MainView.Profile.action.AccountInfoType; import com.shawn.newrollcall.FluxCenter.action.FluxAction; import com.shawn.newrollcall.FluxCenter.store.Store; /** * Created by Shawn Wu on 2017/11/31. * */ public class AccountInfoStore extends Store { @Override public void onFluxActionHandling(FluxAction fluxAction) { switch (fluxAction.getType()){ case AccountInfoType.GET_ACCOUNT_GROUP_AND_DEVICE_DATA_SUCCESS: case AccountInfoType.GET_ACCOUNT_GROUP_AND_DEVICE_DATA: case AccountInfoType.UPLOAD_PROFILE_IMAGE_IMGUR: case AccountInfoType.GET_ACCOUNT_INFO_SUCCESS: case AccountInfoType.SAVE_IMGUR_URI_SUCCESS: emitted(fluxAction); break; } } }
true
b6943a369848322d86dd0478eef9d96af4a5d811
Java
pdphuoc7072/C0721G1-PhanDaiPhuoc
/module2/src/bai_tap_huong_doi_tuong/bai_2/CandidateManager.java
UTF-8
1,794
3.328125
3
[]
no_license
package bai_tap_huong_doi_tuong.bai_2; import java.util.ArrayList; import java.util.List; import java.util.Scanner; public class CandidateManager { List<Candidate> candidateList = new ArrayList<>(); public void addCandidate () { Scanner scanner = new Scanner(System.in); System.out.print("Hãy nhập số thí sinh bạn muốn nhập: "); int numberOfCandidate = Integer.parseInt(scanner.nextLine()); for (int i = 0; i < numberOfCandidate; i++) { int id = i+1; System.out.print("Hãy nhập họ và tên của thí sinh thứ " + (i+1) + ": " ); String fullName = scanner.nextLine(); System.out.print("Hãy nhập ngày tháng năm sinh của thí sinh: "); String birthday = scanner.nextLine(); System.out.print("Hãy nhập điểm số môn Toán: "); double scoreOfMath = Double.parseDouble(scanner.nextLine()); System.out.print("Hãy nhập điểm số môn Ngữ Văn: "); double scoreOFLiterature = Double.parseDouble(scanner.nextLine()); System.out.print("Hãy nhập điểm số môn tiếng Anh: "); double scoreOfEnglish = Double.parseDouble(scanner.nextLine()); candidateList.add(new Candidate(id, fullName, birthday, scoreOfMath, scoreOFLiterature, scoreOfEnglish)); } } public void displayCandidateOfTotalScore15 () { System.out.println("Những thí sinh có tổng điểm 3 môn lớn hơn 15 là: "); for (Candidate candidate : candidateList) { if (candidate.getScoreOfMath() + candidate.getScoreOFLiterature() + candidate.getScoreOfEnglish() > 15) { System.out.println(candidate.toString()); } } } }
true
1eb802514d9d58881bf61829e5fd45981a7ae43d
Java
drochett/Cascade-NonDXL
/Website/Code/Java/com/cascorp/SearchSiteBean.java
UTF-8
17,338
1.914063
2
[]
no_license
package com.cascorp; import java.io.Serializable; import java.util.ArrayList; import java.util.Collections; import java.util.Comparator; import java.util.Date; import java.util.List; import java.util.Map; import java.util.Vector; import javax.faces.context.FacesContext; import org.openntf.xsp.debugtoolbar.beans.DebugToolbarBean; import lotus.domino.Database; import lotus.domino.DateTime; import lotus.domino.Session; import lotus.domino.View; import lotus.domino.ViewEntry; import lotus.domino.ViewEntryCollection; import com.ibm.xsp.extlib.util.ExtLibUtil; import com.ibm.xsp.model.domino.DominoUtils; public class SearchSiteBean implements Serializable { //this code searches the "site" for requested documents //the SiteSearch page will set the requested search term (setSearchPhrase) //then the page calls doSearch, which does the searching //the results are put in the searchResults and returned in getSearchResults private static final long serialVersionUID = 1L; private static boolean showDBar = true; String searchPhrase; List<ViewItem> searchResults; ConfigBean configBean; Integer returnedResultsHome = new Integer(0); Integer returnedResultsDownloads = new Integer(0); // DSR 1-30-19 Added blog to search Integer returnedResultsBlog = new Integer(0); Integer maxResults; String totalResultsDisplay; String maxResultsDisplay; private Integer maxResultsPerPage; public Integer getReturnedResultsHome() { return returnedResultsHome; } public void setReturnedResultsHome(Integer returnedResultsHome) { this.returnedResultsHome = returnedResultsHome; } public Integer getReturnedResultsDownloads() { return returnedResultsDownloads; } public void setReturnedResultsDownloads(Integer returnedResultsDownloads) { this.returnedResultsDownloads = returnedResultsDownloads; } //DSR 1-30-19 Added blog to search public Integer getReturnedResultsBlog() { return returnedResultsBlog; } public void setReturnedResultsBlog(Integer returnedResultsBlog) { this.returnedResultsBlog = returnedResultsBlog; } public String getSearchPhrase() { debugMsg("getting searchphrase " + searchPhrase); return searchPhrase; } public void setSearchPhrase(String searchPhrase) { //the SiteSearch page will set the requested search term debugMsg("setting searchphrase " + searchPhrase); this.searchPhrase = searchPhrase; } public String getTotalResultsDisplay() { //adds the two result values together and outputs as a String Integer foundResults = this.returnedResultsHome + this.returnedResultsDownloads + this.returnedResultsBlog; String numberAsString = String.format ("%d", foundResults); return numberAsString; } public String getMaxResultsDisplay() { //add together the max from downloads and home Integer totalMaxResults = this.maxResults * 2; String numberAsString = String.format ("%d", totalMaxResults); return numberAsString; } public List<ViewItem> getSearchResults() { debugMsg("starting getSearchResults and count is " + searchResults.size()); return searchResults; } public class ViewItem implements Serializable { //each found search item is put in a ViewItem class //the repeat repeats over a list of ViewItems private static final long serialVersionUID = 1L; String url; Integer fTSearchScore; String subject; Date lastModified; String iconURL; String language; boolean isHomeDoc; String mediaType; public String getMediaType() { return mediaType; } public void setMediaType(String mediaType) { this.mediaType = mediaType; } public boolean isHomeDoc() { return isHomeDoc; } public void setHomeDoc(boolean isHomeDoc) { this.isHomeDoc = isHomeDoc; } public String getLanguage() { return language; } public void setLanguage(String language) { this.language = language; } public Date getLastModified() { return lastModified; } public void setLastModified(Date lastModified) { this.lastModified = lastModified; } public String getIconURL() { return iconURL; } public void setIconURL(String iconURL) { this.iconURL = iconURL; } public Integer getFTSearchScore() { return fTSearchScore; } public void setFTSearchScore(Integer searchScore) { fTSearchScore = searchScore; } public String getUrl() { return url; } public void setUrl(String url) { this.url = url; } public String getSubject() { return subject; } public void setSubject(String subject) { this.subject = subject; } public ViewItem(Integer FTSearchScore, String subject, String url, String iconURL,String language, Date lastMod, boolean isHomeDoc, String mediaType) { this.fTSearchScore = FTSearchScore; this.subject = subject; this.url = url; this.iconURL = iconURL; this.lastModified = lastMod; this.language = language; this.isHomeDoc = isHomeDoc; this.mediaType = mediaType; } } public static Comparator<ViewItem> COMPARE_BY_SCORE2 = new Comparator<ViewItem>() { //not currently used, can be used to compare by FTScore and then by subject if the same public int compare(ViewItem one, ViewItem other) { if (other.fTSearchScore != one.fTSearchScore){ return other.fTSearchScore.compareTo(one.fTSearchScore); } else { //if they are the same compare by subject return other.subject.compareTo(one.subject); } } }; public static Comparator<ViewItem> COMPARE_BY_SCORE = new Comparator<ViewItem>() { public int compare(ViewItem one, ViewItem other) { return other.fTSearchScore.compareTo(one.fTSearchScore); } }; public static Comparator<ViewItem> COMPARE_BY_NAME = new Comparator<ViewItem>() { //not currently used, but could be used to sort by subject public int compare(ViewItem one, ViewItem other) { return one.subject.compareTo(other.subject); } }; public void sortSearchResults(){ //this is the one that is current used, sorted by FTScore Collections.sort(searchResults, COMPARE_BY_SCORE); } public void sortSearchResults2(){ //not currently used Collections.sort(searchResults, COMPARE_BY_SCORE2); } public void sortResultsByName(){ //not currently used Collections.sort(searchResults, COMPARE_BY_NAME); } @SuppressWarnings("unchecked") public void doSearch() { //does all the work! String searchPhrase = this.searchPhrase; String subject = new String(""); String url = new String(""); String iconUrl = new String(""); String language = new String(""); Integer score = new Integer(0); String mediaType = new String(""); boolean isHomeDoc; int resultNum; Date modDate = null; DateTime NotesDate; // get the locations of the two databases to search in String homeDbPath = getConfigValueString("HomeDbPath"); String downloadsDbPath = getConfigValueString("DownloadsDbPath"); String homeURL = getConfigValueString("HomeURL"); String downloadsURL = getConfigValueString("DownloadsURL"); String HostURL = getConfigValueString("HostURL"); // DSR - 1-30-19 Added Blog to Search String blogDbPath = getConfigValueString("BlogDbPath"); String blogURL = getConfigValueString("BlogURL"); debugMsg("config values are : " + homeDbPath + ", " + homeURL + ", " + downloadsDbPath + ", " + downloadsURL + ", " + blogDbPath + ", " + blogURL + ", " + HostURL); // init results array this.searchResults = new ArrayList<ViewItem>(); if (!searchPhrase.isEmpty()) { // variables for looping through views ViewEntry viewEntry; ViewEntry tempviewEntry; try { Session session = DominoUtils.getCurrentSession(); Database homeDb = session.getDatabase(session.getServerName(), homeDbPath); if (homeDb.isOpen()) { // search in the home db View lookupVw = homeDb.getView("SiteSearchView"); if (lookupVw != null) { if (homeDb.isFTIndexed()) { // only search if ft indexed resultNum = lookupVw.FTSearch(searchPhrase, maxResults); debugMsg("results are " + resultNum); this.returnedResultsHome = resultNum; ViewEntryCollection vwEntryCol = lookupVw .getAllEntries(); viewEntry = vwEntryCol.getFirstEntry(); if (resultNum > 0) { while (viewEntry != null) { // create a new ViewItem and add to // ArrayList Vector colValues = viewEntry .getColumnValues(); url = HostURL.concat((String) colValues .elementAt(0)); language = (String) colValues.elementAt(1); subject = (String) colValues.elementAt(2); NotesDate = (DateTime) colValues .elementAt(3); modDate = NotesDate.toJavaDate(); score = viewEntry.getFTSearchScore(); isHomeDoc = true; ViewItem vwItem = new ViewItem(score, subject, url, iconUrl, language, modDate, isHomeDoc, mediaType); searchResults.add(vwItem); // get next document // recycle the vector per Paul Withers blog // since there // was // a DateTime column session.recycle(colValues); tempviewEntry = vwEntryCol .getNextEntry(viewEntry); viewEntry.recycle(); viewEntry = tempviewEntry; } } } else { // database is not FT Indexed // view is not available debugMsg("Home Database is not FT Indexed"); throw new RuntimeException( "Home Database is not FT Indexed"); } } else { // view is not available debugMsg("SiteSearchView in Home Database is not open"); throw new RuntimeException( "SiteSearchView in Home Database is not open"); } } else { // home database is not open debugMsg("Home Database is not open: " + homeDbPath); throw new RuntimeException("Home Database is not open: " + homeDbPath); } // start search in downloads database Database downloadsDb = session.getDatabase(session .getServerName(), downloadsDbPath); if (downloadsDb.isOpen()) { // search in the home db View lookupVw = downloadsDb.getView("SiteSearchView"); if (lookupVw != null) { if (downloadsDb.isFTIndexed()) { // do the search!!! resultNum = lookupVw.FTSearch(searchPhrase, maxResults); debugMsg("results are " + resultNum); this.returnedResultsDownloads = resultNum; ViewEntryCollection vwEntryCol = lookupVw .getAllEntries(); viewEntry = vwEntryCol.getFirstEntry(); if (resultNum > 0) { while (viewEntry != null) { // create a new ViewItem and add to // ArrayList Vector colValues = viewEntry .getColumnValues(); url = downloadsURL .concat((String) colValues .elementAt(0)); url = HostURL.concat(url); language = (String) colValues.elementAt(1); subject = (String) colValues.elementAt(2); NotesDate = (DateTime) colValues .elementAt(3); modDate = NotesDate.toJavaDate(); iconUrl = "/".concat((String) colValues .elementAt(4)); mediaType = (String) colValues.elementAt(5); score = viewEntry.getFTSearchScore(); isHomeDoc = false; ViewItem vwItem = new ViewItem(score, subject, url, iconUrl, language, modDate, isHomeDoc, mediaType); searchResults.add(vwItem); // get next document // recycle the vector per Paul Withers blog // since there was a DateTime column session.recycle(colValues); tempviewEntry = vwEntryCol .getNextEntry(viewEntry); viewEntry.recycle(); viewEntry = tempviewEntry; } } } else { // database is not FT Indexed // view is not available debugMsg("Download Database is not FT Indexed"); throw new RuntimeException( "Download Database is not FT Indexed"); } } else { // view is not available debugMsg("SiteSearchView in Download Database is not open"); throw new RuntimeException( "SiteSearchView in Download Database is not open"); } } else { // downloads db is not open debugMsg("Downloads Database is not open: " + downloadsDbPath); throw new RuntimeException( "Downloads Database is not open: " + downloadsDbPath); } //DSR 1-30-19 Added Blog db to search Database blogDb = session.getDatabase(session .getServerName(), blogDbPath); if (blogDb.isOpen()) { // search in the home db View lookupVw = blogDb.getView("SiteSearchView"); if (lookupVw != null) { if (blogDb.isFTIndexed()) { // do the search!!! resultNum = lookupVw.FTSearch(searchPhrase, maxResults); debugMsg("blog results are " + resultNum); this.returnedResultsBlog = resultNum; ViewEntryCollection vwEntryCol = lookupVw .getAllEntries(); viewEntry = vwEntryCol.getFirstEntry(); if (resultNum > 0) { while (viewEntry != null) { // create a new ViewItem and add to // ArrayList Vector colValues = viewEntry .getColumnValues(); url = HostURL.concat((String) colValues .elementAt(0)); language = (String) colValues.elementAt(1); subject = (String) colValues.elementAt(2); NotesDate = (DateTime) colValues .elementAt(3); modDate = NotesDate.toJavaDate(); score = viewEntry.getFTSearchScore(); isHomeDoc = true; ViewItem vwItem = new ViewItem(score, subject, url, iconUrl, language, modDate, isHomeDoc, mediaType); searchResults.add(vwItem); // get next document // recycle the vector per Paul Withers blog // since there // was // a DateTime column session.recycle(colValues); tempviewEntry = vwEntryCol .getNextEntry(viewEntry); viewEntry.recycle(); viewEntry = tempviewEntry; } } } else { // database is not FT Indexed // view is not available debugMsg("Blog Database is not FT Indexed"); throw new RuntimeException( "Blog Database is not FT Indexed"); } } else { // view is not available debugMsg("SiteSearchView in Blog Database is not open"); throw new RuntimeException( "SiteSearchView in Blog Database is not open"); } } else { // blog db is not open debugMsg("Blog Database is not open: " + blogDbPath); throw new RuntimeException( "blog Database is not open: " + blogDbPath); } // sort the results by relevance sortSearchResults(); } catch (Exception e) { debugMsg("error : " + e.toString()); DebugToolbarBean.get().error(e); } } else { // search phrase was empty debugMsg("Search Phrase was empty"); } } private String getConfigValueString(String configName){ if (configBean == null){ //initialize configBean variable configBean = (ConfigBean) ExtLibUtil.resolveVariable(FacesContext.getCurrentInstance(), "configBean"); } String rtnValue = (String) configBean.getValue(configName); return rtnValue; } private Integer getConfigValueInteger(String configName){ Integer rtnValue ; if (configBean == null){ //initialize configBean variable configBean = (ConfigBean) ExtLibUtil.resolveVariable(FacesContext.getCurrentInstance(), "configBean"); } String rtnValueString = (String) configBean.getValue(configName); //convert days to integer try{ rtnValue = Integer.parseInt(rtnValueString); } catch (NumberFormatException nfe) { //default to 50 if a bad date debugMsg("Bad Number, setting to 50"); rtnValue = 50; } return rtnValue; } //constructor public SearchSiteBean() { //initialize the search results //this gets the max results per the config doc searchResults = new ArrayList<ViewItem>(); //set the max results value for each database this.maxResults = getConfigValueInteger("MaxSiteSearchResults"); this.setMaxResultsPerPage(getConfigValueInteger("MaxSiteSearchResultsPerPage")); debugMsg("max search is " + this.maxResults + " max per page is " + this.maxResultsPerPage); } @SuppressWarnings("unchecked") private static void debugMsg(String msg){ Map viewscope = (Map) ExtLibUtil.resolveVariable(FacesContext.getCurrentInstance(), "viewScope"); if (viewscope.containsKey("debug")){ if ( ((String) viewscope.get("debug")).equalsIgnoreCase("true") ){ DebugToolbarBean.get().info(msg); } } else if (showDBar){ DebugToolbarBean.get().info(msg); } } public void setMaxResultsPerPage(Integer maxResultsPerPage) { this.maxResultsPerPage = maxResultsPerPage; } public Integer getMaxResultsPerPage() { return maxResultsPerPage; } public boolean hasResults(){ //called to determine if there are results to show debugMsg("Starting hasResults - " + !searchResults.isEmpty()); return !searchResults.isEmpty(); } }
true
37a42df90f09df52319d4f13306677ef9995b9d7
Java
wellrain-xrx/simple-polygon-generator
/src/main/java/polygonsSWP/geometry/OrderedListPolygon.java
UTF-8
8,873
3.3125
3
[]
no_license
package polygonsSWP.geometry; import java.util.ArrayList; import java.util.Collections; import java.util.List; import polygonsSWP.util.Random; import polygonsSWP.util.MathUtils; /** * Implementation of Polygon using ordered counter-clockwise list. The * assumption is, that the list of polygons is ordered in order of appearance. * So the polygon is drawn from point one to point two to .. to point n to point * 1. So be sure your self added point list meets the assumption otherwise it * won't work. * * (c) 2011-2012 * @author Steve Dierker <dierker.steve@fu-berlin.de> * @author Marcel Ehrhardt <marehr@zedat.fu-berlin.de> * @author Jannis Ihrig <jannis.ihrig@fu-berlin.de> * @author Malte Rohde <malte.rohde@inf.fu-berlin.de> * @author Sebastian Thobe <s.thobe@fu-berlin.de> * @author Kadir Tugan <kadir.tugan@gmail.com> */ public class OrderedListPolygon extends Polygon { List<Point> _coords; List<Triangle> _triangles; /** * Generates an empty polygon object which will contain no statistics or * history. */ public OrderedListPolygon() { this(new ArrayList<Point>()); } /** * Generates an polygon object which consists of the given points, carrying no * statistics object. */ public OrderedListPolygon(List<Point> coords) { _coords = coords; } public List<Point> getPoints() { return _coords; } /** * @param coords Sets a new list of ordered points. */ public void setPoints(List<Point> coords) { _coords = coords; } /** * Adds a point to the end of the list. * * @param p The new point. */ public void addPoint(Point p) { _coords.add(p); } /** * Deletes the given point. * * @param p Point to delete. */ public void deletePoint(Point p) { _coords.remove(p); } /** * Creates a new polygon of the same set of points by creating a random * permutation of the points and linking them in order. The resulting polygon * is very likely to be complex. */ public void permute() { Collections.shuffle(_coords); } /** * Reverses the polygon's order. Polygon keeps its simplicity. */ public void reverse() { Collections.reverse(_coords); } /** * Determines whether a given ordered list of points forms a simple polygon. * * @return true, if the polygon is simple, otherwise false. */ public boolean isSimple() { return findIntersections().size() == 0; } /** * Calculates the set of all intersections found in the polygon. * * @return a list of intersections, where each item is an array of the two * indices defining an intersection. [x,y] --> edge(x,x+1) intersects * edge(y,y+1) */ public List<Integer[]> findIntersections() { /* * Remark: The approach used here is very naive. As Held writes in his * paper, "The simplicity test for a polygon is not done in linear time; * rather we implemented a straightforward quadratic approach. (As we will * see later this has no influence on the test results.)", I also decided to * let alone [Cha91] for now and simply check for crossing lines. However, * since we're going to implement polygon triangulation anyway, we should * definitely come back here later and improve this. Maybe, instead of the * proposed [Cha91], we could also use the Bentley-Ottmann algorithm, see * http://en.wikipedia.org/wiki/Bentley%E2%80%93Ottmann_algorithm for * explanation. */ List<Integer[]> retval = new ArrayList<Integer[]>(); int size = _coords.size(); Point[] isect = new Point[1]; LineSegment a = new LineSegment(new Point(0,0),new Point(0,0)); LineSegment b = new LineSegment(new Point(0,0),new Point(0,0)); for (int i = 0; i < size - 1; i++) { a._a = _coords.get(i); a._b = _coords.get(i + 1); // Then test the remaining line segments for intersections for (int j = i + 1; j < size; j++) { b._a = _coords.get(j); b._b = _coords.get((j + 1) % size); isect = a.intersect(b); if (isect != null) { boolean coincident; boolean ab = false; boolean ba = false; // Check for coincidence (--> intersection) if (!(coincident = (isect.length == 0))) { // Check whether the intersection is a shared endpoint (--> no // intersection) ab = isect[0].equals(_coords.get(i)) && _coords.get(i).equals(_coords.get((j + 1) % size)); ba = isect[0].equals(_coords.get(j)) && _coords.get(j).equals(_coords.get(i + 1)); } if (coincident || !(ab || ba)) retval.add(new Integer[] { i, j }); } } } return retval; } /** * Returns a randomly chosen intersection of the polygon. * * @return 2-element array determining the intersection (see above) null, if * there is no intersection */ public Integer[] findRandomIntersection() { List<Integer[]> is = findIntersections(); if (is.size() == 0) return null; return is.get(Random.create().nextInt(is.size())); } /** * @return the number of vertices in the polygon */ public int size() { return _coords.size(); } @Override public OrderedListPolygon clone() { List<Point> nList = new ArrayList<Point>(_coords.size()); for (Point item : _coords) nList.add(item.clone()); return new OrderedListPolygon(nList); } /** * Tests if p is vertex of the given Polygon. * * @param p point * @return true, if p is a vertex of the given Polygon */ public boolean containsVertex(Point p) { return getPoints().contains(p); } /** * @author Steve Dierker <dierker.steve@fu-berlin.de> * @see http://www.flipcode.com/archives/Efficient_Polygon_Triangulation.shtml * @category Ear-Clipping-Algorithm * @return List of triangulars */ public List<Triangle> triangulate() { if (_triangles != null) return _triangles; assert size() >= 3; //assert (isSimple()); if(isClockwise() != -1) reverse(); assert (isClockwise() == -1); _triangles = new ArrayList<Triangle>(); if (size() == 3) { _triangles.add(new Triangle(getPoints())); return _triangles; } /* Manage a list of indices. */ int[] V = new int[size()]; for (int v = 0; v < size(); v++) V[v] = v; int nv = size(); for (int v = nv - 1; nv > 2;) { /* Three consecutive vertices in current polygon, <u,v,w>. */ int u = v; if (nv <= u) u = 0; /* previous */ v = u + 1; if (nv <= v) v = 0; /* new v */ int w = v + 1; if (nv <= w) w = 0; /* next */ /* Build a triangle of the three vertices. */ Point a = _coords.get(V[u]); Point b = _coords.get(V[v]); Point c = _coords.get(V[w]); Triangle triangle = new Triangle(a, b, c); /* Test whether triangle <u,v,w> is a snip. */ boolean isSnip = true; /* * 1st condition: Counterclockwise rotation of triangle, which means that * v is a convex vertex of the polygon. */ if (MathUtils.checkOrientation(a, b, c) == -1) isSnip = false; /* * 2nd condition: No other vertex lies of the polygon lies inside the * triangle <u,v,w>. */ if (isSnip) { for (int p = 0; p < nv; p++) { if ((p == u) || (p == v) || (p == w)) continue; if (triangle.containsPoint(_coords.get(V[p]), true)) { isSnip = false; break; } } } if (isSnip) { /* output Triangle */ _triangles.add(triangle); /* remove v from remaining polygon */ for (int s = v, t = v + 1; t < nv; s++, t++) V[s] = V[t]; nv--; } } return _triangles; } /** * Creates a random Point in Polygon. Uses Triangularization, randomly chooses * Triangle, creates random Point in Triangle. * * @author Jannis Ihrig <jannis.ihrig@fu-berlin.de> * @param polygon Polygon to create random point in * @return random Point in given Polygon */ public Point createRandomPoint() { assert (size() >= 3); Point point; // If polygon is a triangle if (this.size() == 3) { Triangle triangle = new Triangle(this.getPoints()); point = triangle.createRandomPoint(); } else { // Triangulate given Polygon. List<Triangle> triangularization = this.triangulate(); // Choose one triangle of triangularization randomly weighted by their // Surface Area. Triangle chosenTriangle = Triangle.selectRandomTriangleBySize(triangularization); System.out.println(chosenTriangle); // Return randomly chosen Point in chosen Triangle. point = chosenTriangle.createRandomPoint(); } return point; } }
true
cd967dcbf4a83269ef40c7d70839b9efc3a6a6d4
Java
anpavlo/ukrresources
/src/main/java/org/registrator/community/config/SecurityConfiguration.java
UTF-8
2,484
2.078125
2
[]
no_license
package org.registrator.community.config; import javax.sql.DataSource; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Qualifier; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; import org.springframework.security.authentication.AuthenticationProvider; import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder; import org.springframework.security.config.annotation.method.configuration.EnableGlobalMethodSecurity; import org.springframework.security.config.annotation.web.builders.HttpSecurity; import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity; import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter; import org.springframework.security.core.userdetails.UserDetailsService; import org.springframework.security.web.authentication.rememberme.JdbcTokenRepositoryImpl; import org.springframework.security.web.authentication.rememberme.PersistentTokenRepository; @Configuration @EnableWebSecurity @EnableGlobalMethodSecurity(prePostEnabled = true) public class SecurityConfiguration extends WebSecurityConfigurerAdapter { @Autowired @Qualifier("userDetailsService") private UserDetailsService userDetailsService; @Autowired private DataSource dataSource; @Autowired @Qualifier("authenticationProvider") AuthenticationProvider authenticationProvider; @Autowired public void configureGlobal(AuthenticationManagerBuilder auth) throws Exception { auth.authenticationProvider(authenticationProvider); } @Override protected void configure(HttpSecurity http) throws Exception { http.csrf().disable().formLogin().loginPage("/login").permitAll() .failureUrl("/login?error").usernameParameter("login").passwordParameter("password").and().logout() .logoutUrl("/logout").permitAll().logoutSuccessUrl("/login?logout").and().exceptionHandling() .accessDeniedPage("/denied").and().authorizeRequests().and().rememberMe() .rememberMeParameter("_spring_security_remember_me").tokenRepository(persistentTokenRepository()) .tokenValiditySeconds(87400); } @Bean public PersistentTokenRepository persistentTokenRepository() { JdbcTokenRepositoryImpl tokenRepositoryImpl = new JdbcTokenRepositoryImpl(); tokenRepositoryImpl.setDataSource(dataSource); return tokenRepositoryImpl; } }
true
dade56cf63aa465301862cc4e64488a3e060224d
Java
shanghaif/Stock_ZZFIN
/StockAndroid/app/src/main/java/com/xt/lxl/stock/model/reponse/StockUserCompletionResponse.java
UTF-8
317
1.625
2
[]
no_license
package com.xt.lxl.stock.model.reponse; import com.xt.lxl.stock.model.ServiceResponse; import com.xt.lxl.stock.model.model.StockUserModel; public class StockUserCompletionResponse extends ServiceResponse { public int serviceCode = 3002;//服务号 public StockUserModel userModel = new StockUserModel(); }
true
d4ec5fff228176fb19d3e613cb5a502428a2a053
Java
Toqiin/spreadsheet-app
/view/InputPanel.java
UTF-8
2,669
3.03125
3
[]
no_license
package edu.cs3500.spreadsheets.view; import java.awt.Dimension; import java.awt.FlowLayout; import java.awt.Font; import java.awt.Insets; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import javax.swing.JButton; import javax.swing.JPanel; import javax.swing.JTextField; import edu.cs3500.spreadsheets.model.Coord; import edu.cs3500.spreadsheets.model.ReadableWorksheet; /** * Represents the panel at the top of the Interactive edu.cs3500.spreadsheets.view that enables users to edit the content * of cells. */ public class InputPanel extends JPanel { private JButton accept; private JButton reject; private JTextField formula; private Coord selected; private ReadableWorksheet ws; private boolean isSelect = false; /** * Constructs a InputPanel. * @param ws the worksheet whose cells the input panel can display */ public InputPanel(ReadableWorksheet ws) { super(); this.ws = ws; this.setSize(885, 60); this.setLayout(new FlowLayout()); this.accept = new JButton("✓"); this.accept.setPreferredSize(new Dimension(60, 50)); this.accept.setFont(new Font("Sans Serif", Font.PLAIN, 32)); this.add(this.accept); this.reject = new JButton("X"); this.reject.setPreferredSize(new Dimension(60, 50)); this.reject.setFont(new Font("Sans Serif", Font.PLAIN, 32)); this.add(this.reject); this.formula = new JTextField(); this.formula.setPreferredSize(new Dimension(675, 50)); this.formula.setFont(new Font("Sans Serif", Font.PLAIN, 32)); this.formula.setMargin(new Insets(0, 10, 0, 0)); this.add(this.formula); this.reject.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent e) { if (isSelect) { formula.setText(ws.getCellAt(selected).getString()); } else { if (ws.getCellAt(selected) == null) { formula.setText(""); } } formula.repaint(); } }); } JButton getCheckButton() { return this.accept; } JTextField getTextField() { return this.formula; } /** * Selects the cell at the given coordinate and displays the contents in the text field. * @param sel the cell to be selected */ void setSelected(Coord sel) { this.isSelect = true; this.selected = sel; if (ws.getCellAt(selected) == null) { formula.setText(""); } else { formula.setText(ws.getCellAt(selected).getString()); } } /** * Deselects the currently selected cell and clears the text field. */ void deselect() { this.isSelect = false; formula.setText(""); } }
true
21f3e3f8f8b66ba3642a919c47df333428f1b014
Java
PhilippePeeters/exjava
/exC3/exC3.java
UTF-8
909
3.703125
4
[]
no_license
import java.util.Scanner; import java.util.ArrayList; public class exC3 { public static void main(String[] args) { ArrayList<Integer> intergerArray = new ArrayList<Integer>(); String inputNumberStringUser = null; boolean endEntry = true; Scanner scanner = new Scanner( System.in ); do { System.out.print( "Enter numbers (X to terminate) : " ); inputNumberStringUser = scanner.nextLine(); try { Double.parseDouble(inputNumberStringUser); intergerArray.add(Integer.parseInt(inputNumberStringUser)); endEntry = true; } catch(NumberFormatException e){ endEntry = false; } } while (endEntry); // DoMath calculateAverage = new DoMath(); // float averageNumbers = calculateAverage.calculateAverage(intergerArray); float averageNumbers = DoMath.calculateAverage(intergerArray); System.out.println("Average :"+ averageNumbers); } }
true
1f7993672f41a3fc0cbb4c64e01edeb42d6833c8
Java
takashizeroum/CamDia
/app/src/main/java/com/example/camdia/ViewUser.java
UTF-8
7,862
1.671875
2
[]
no_license
package com.example.camdia; import androidx.appcompat.app.AppCompatActivity; import androidx.appcompat.widget.SwitchCompat; import androidx.core.app.ActivityCompat; import androidx.core.app.ActivityOptionsCompat; import android.content.Intent; import android.database.Cursor; import android.os.AsyncTask; import android.os.Bundle; import android.os.Handler; import android.util.Log; import android.view.View; import android.widget.Button; import android.widget.CompoundButton; import android.widget.ImageView; import android.widget.Spinner; import android.widget.Switch; import android.widget.TextView; import android.widget.Toast; import org.json.JSONArray; import org.json.JSONException; import org.json.JSONObject; import java.util.ArrayList; import java.util.HashMap; public class ViewUser extends AppCompatActivity { TextView nome, desc,rank, km; String urlimg; ModelUser user ; Switch sw ; int comp; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_user); //adapta switch sw = findViewById(R.id.btncompperfil); sw.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() { public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) { if (isChecked) { comp = 1; } else { comp = 0 ; } DBLocalController controller = new DBLocalController(getApplicationContext()); ModelUser user = controller.resgata(); HashMap<String, String> params = new HashMap<>(); params.put("comp", String.valueOf(comp)); params.put("id", String.valueOf(user.getId())); RequestNET request = new RequestNET(API.URL_UPDATE, params,API.CODE_POST_REQUEST); request.execute(); Log.d("testing", "onCheckedChanged: url : "+params); } }); DBLocalController controller = new DBLocalController(getApplicationContext()); ModelUser usr = controller.resgata(); HashMap<String, String> params = new HashMap<>(); params.put("login", usr.getLogin()); params.put("senha", usr.getSenha()); ViewUser.PNRViewP request = new ViewUser.PNRViewP(API.URL_veri, params,API.CODE_POST_REQUEST); request.execute(); //escutador do botão voltar final Button btnvolt = findViewById(R.id.sairbtndeuser); btnvolt.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { finish(); startActivity(new Intent(getApplicationContext(), ViewPrincipal.class)); } }); final Button btnperfil = findViewById(R.id.perfilbtndeuser); btnperfil.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { } }); final Button btnmap = findViewById(R.id.simuladorbtndeuser); btnmap.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { finish(); Intent go = new Intent(ViewUser.this, MapsActivity.class); ActivityOptionsCompat activityOptionsCompat = ActivityOptionsCompat.makeCustomAnimation(getApplicationContext(),R.anim.fade_in,R.anim.move_direita); ActivityCompat.startActivity(ViewUser.this,go,activityOptionsCompat.toBundle()); } }); final Button btmur = findViewById(R.id.muralpaginabtndeuser); btmur.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { finish(); Intent go = new Intent(ViewUser.this, ViewPrincipal.class); ActivityOptionsCompat activityOptionsCompat = ActivityOptionsCompat.makeCustomAnimation(getApplicationContext(),R.anim.fade_in,R.anim.move_direita); ActivityCompat.startActivity(ViewUser.this,go,activityOptionsCompat.toBundle()); } }); } //botões de histórico e ranking public void historico(View view) { Intent go = new Intent(ViewUser.this, ViewHistorico.class); ActivityOptionsCompat activityOptionsCompat = ActivityOptionsCompat.makeCustomAnimation(getApplicationContext(),R.anim.fade_in,R.anim.move_direita); ActivityCompat.startActivity(ViewUser.this,go,activityOptionsCompat.toBundle()); } public void ranking(View view) { Intent go = new Intent(ViewUser.this, ViewRanking.class); ActivityOptionsCompat activityOptionsCompat = ActivityOptionsCompat.makeCustomAnimation(getApplicationContext(),R.anim.fade_in,R.anim.move_direita); ActivityCompat.startActivity(ViewUser.this,go,activityOptionsCompat.toBundle()); } public void VUCarrega(JSONArray array) throws JSONException { for (int i = 0; i < array.length(); i++) { JSONObject obj = array.getJSONObject(i); user = new ModelUser(obj.getString("nome"), obj.getString("login"), obj.getString("empresa") , obj.getString("senha"), obj.getInt("id"), obj.getString("desc"), obj.getInt("rank"), obj.getDouble("km"), obj.getInt("comp"), obj.getDouble("temp"), obj.getString("extra")); } nome = findViewById(R.id.usrNameUsr); desc = findViewById(R.id.usrempUsr); rank = findViewById(R.id.usrcolocaUsr); km = findViewById(R.id.usrkmUsr); nome.setText(user.getNome()); desc.setText(user.getEmpresa()); rank.setText(String.valueOf(user.getRank())); km.setText(user.getKm().toString()); urlimg = user.getExtras(); // chama classe que carrega imagem de perfil ImageView i = findViewById(R.id.imgPerfil); VoleiAPImg img = new VoleiAPImg(); img.carregaImg(i, getApplicationContext(),urlimg); //verifica switch if (user.getCompete()==1){ sw.setChecked(true); }else{ sw.setChecked(false); } } public class PNRViewP extends AsyncTask<Void, Void, String> { String url; HashMap<String, String> params; int requestCode; public PNRViewP(String url, HashMap<String, String> params, int requestCode) { this.url = url; this.params = params; this.requestCode = requestCode; } @Override protected void onPreExecute() { super.onPreExecute(); } @Override protected void onPostExecute(String s) { super.onPostExecute(s); try { final JSONObject jsonObject = new JSONObject(s); VUCarrega(jsonObject.getJSONArray("users")); Log.d("djsdjsdsjdhsjdhsjdhsdj", "onPostExecute: "+jsonObject); } catch (JSONException e) { e.printStackTrace(); Toast.makeText(getApplicationContext(), "Falha ao Sincronizar ", Toast.LENGTH_SHORT).show(); } } @Override protected String doInBackground(Void... voids) { RequestHandler requestHandler = new RequestHandler(); if (requestCode == API.CODE_POST_REQUEST) return requestHandler.sendPostRequest(url, params); if (requestCode == API.CODE_GET_REQUEST) return requestHandler.sendGetRequest(url); return null; } } @Override public void finish() { super.finish(); overridePendingTransition(R.anim.move_esquerda,R.anim.fade_out); } }
true
a4c31e76a7ab294d6d978bb1f745bc971b0cbcfa
Java
littleBoyCanHaveAFuture/ZY_Manager
/src/main/java/com/zyh5games/controller/RechargeSummaryControllr.java
UTF-8
9,003
2.15625
2
[ "Apache-2.0" ]
permissive
package com.zyh5games.controller; import com.zyh5games.common.Constants; import com.zyh5games.entity.GameInfo; import com.zyh5games.entity.PageBean; import com.zyh5games.entity.RechargeSummary; import com.zyh5games.jedis.JedisRechargeCache; import com.zyh5games.service.RechargeSummaryService; import com.zyh5games.util.DateUtil; import com.zyh5games.util.ResponseUtil; import net.sf.json.JSONArray; import net.sf.json.JSONObject; import org.apache.log4j.Logger; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Controller; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestMethod; import org.springframework.web.bind.annotation.ResponseBody; import javax.annotation.Resource; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import javax.servlet.http.HttpSession; import java.text.DecimalFormat; import java.util.*; /** * @author song minghua * @date 2019/11/26 */ @Controller @RequestMapping("/rechargeSummary") public class RechargeSummaryControllr { private static final Logger log = Logger.getLogger(RechargeSummaryControllr.class); @Autowired JedisRechargeCache cache; @Resource(name = "RechargeSummaryService") private RechargeSummaryService rsService; @Autowired private HttpServletRequest request; /** * 获取当前用户 session */ private Integer getUserId() { HttpSession session = request.getSession(); return (Integer) session.getAttribute("userId"); } /** * @param type 1/2/3 全服-时间排序/全区服-区服排序/全渠道-渠道排序 * @param gameId 游戏id 不为空 * @param serverId 区服id 查询对应游戏的区服 可为空,则查询数据库该游戏所有区服 * @param channelId 渠道id 查询对应游戏渠道 可为空 * @param startTime 开始时间 jsp内格式:yyyy-MM-dd HH:mm * @param endTime 结束时间 jsp内格式:yyyy-MM-dd HH:mm */ @RequestMapping(value = "/getRS", method = RequestMethod.POST) @ResponseBody public void getRechargeSummary(Integer type, Integer gameId, Integer channelId, Integer serverId, String startTime, String endTime, String page, String rows, HttpServletResponse response) throws Exception { log.info("getRS"); Integer userId = getUserId(); if (userId == null) { ResponseUtil.writeRelogin(response); return; } //可能用到的页数 int pageStart = 0; int pageSize = 10; if (page != null && rows != null) { PageBean pageBean = new PageBean(Integer.parseInt(page), Integer.parseInt(rows)); pageStart = pageBean.getStart(); pageSize = pageBean.getPageSize(); } long start = System.currentTimeMillis(); JSONObject result = new JSONObject(); do { if (gameId == null || gameId == -1) { result.put("message", "游戏id为空或未选择"); result.put("state", false); break; } if (startTime == null || endTime == null) { result.put("message", "日期为空"); result.put("state", false); break; } //查询的日期天数 List<String> timeList = DateUtil.transTimes(startTime, endTime, DateUtil.FORMAT_YYYY_MMDD_HHmm); System.out.println(timeList); //需要查询的游戏、渠道、区服信息 Map<String, GameInfo> gameInfoMap = rsService.getGameInfo(gameId, channelId, serverId); if (gameInfoMap == null) { result.put("message", "无此游戏、渠道或区服"); result.put("state", false); break; } GameInfo gameInfo = gameInfoMap.get(String.valueOf(gameId)); //查询结果 List<RechargeSummary> res = null; switch (type) { case 1: res = rsService.getDayResult(gameInfoMap, timeList); break; case 2: if (channelId == null) { result.put("message", "渠道id为空"); result.put("state", false); break; } res = rsService.getChannelResult(gameInfo, timeList); break; case 3: //剑秋:不同渠道在同一游戏服务器里游戏 if (serverId == null) { result.put("message", "区服id为空"); result.put("state", false); break; } res = rsService.getServerResult(gameInfo, timeList); break; default: break; } if (res != null) { result.put("rows", JSONArray.fromObject(res)); result.put("total", res.size()); result.put("state", true); result.put("message", "查询成功"); } } while (false); result.put("time", new DecimalFormat("0.00").format((double) (System.currentTimeMillis() - start) / 1000)); result.put("resultCode", Constants.RESULT_CODE_SUCCESS); ResponseUtil.write(response, result); } void getGameInfo(Integer gameId, Integer channelId, Integer serverId, Map<String, Set<String>> channelMap, Set<String> serverAllSet) { Set<String> gameInfoSet = cache.getGAMEIDInfo(); if (gameId != -1) { gameInfoSet.clear(); gameInfoSet.add(String.valueOf(gameId)); } for (String fGameId : gameInfoSet) { Set<String> channelSet = cache.getSPIDInfo(fGameId); if (channelId != -1) { channelSet.clear(); channelSet.add(String.valueOf(channelId)); } channelMap.put(fGameId, channelSet); for (String fChannelId : channelSet) { Set<String> serverSet = cache.getServerInfo(fGameId, fChannelId); if (serverId != -1) { serverSet.clear(); serverSet.add(String.valueOf(serverId)); } serverAllSet.addAll(serverSet); } } } @RequestMapping(value = "/day", method = RequestMethod.POST) @ResponseBody public void Day(Integer type, Integer gameId, Integer channelId, Integer serverId, String startTime, String endTime, HttpServletResponse response) throws Exception { long start = System.currentTimeMillis(); JSONObject result = new JSONObject(); do { if (gameId == null || gameId == -1) { result.put("message", "游戏id为空或未选择"); result.put("state", false); break; } if (startTime == null || endTime == null) { result.put("message", "日期为空"); result.put("state", false); break; } List<String> timeList = DateUtil.transTimes(startTime, endTime, DateUtil.FORMAT_YYYY_MMDD_HHmm); System.out.println(timeList); Map<String, Set<String>> channelMap = new HashMap<>(); Set<String> serverAllSet = new LinkedHashSet<>(); getGameInfo(gameId, channelId, serverId, channelMap, serverAllSet); if (type == 1) { List<RechargeSummary> res = rsService.rsDay(channelMap, serverAllSet, timeList); if (res != null) { result.put("rows", JSONArray.fromObject(res)); result.put("total", res.size()); result.put("state", true); result.put("message", "查询成功"); } } else if (type == 2) { List<RechargeSummary> res = rsService.rsChannel(channelMap, serverAllSet, timeList); if (res != null) { result.put("rows", JSONArray.fromObject(res)); result.put("total", res.size()); result.put("state", true); result.put("message", "查询成功"); } } } while (false); long end = System.currentTimeMillis(); result.put("time", new DecimalFormat("0.00").format((double) (System.currentTimeMillis() - start) / 1000)); result.put("resultCode", Constants.RESULT_CODE_SUCCESS); ResponseUtil.write(response, result); } }
true
8b35b37fad63a79fd439f1138ce6477ad8824117
Java
jackvvv/Entertainer
/app/src/main/java/sinia/com/entertainer/bean/TokenBean.java
UTF-8
674
2.453125
2
[]
no_license
package sinia.com.entertainer.bean; import java.io.Serializable; /** * Created by byw on 2017/1/12. */ public class TokenBean implements Serializable{ private int state; private int isSuccessful; private String token; public String getToken() { return token; } public void setToken(String token) { this.token = token; } public int getState() { return state; } public int getIsSuccessful() { return isSuccessful; } public void setState(int state) { this.state = state; } public void setIsSuccessful(int isSuccessful) { this.isSuccessful = isSuccessful; } }
true
5b2e591d0742964ac5489afea73531366af255a8
Java
jackbryan1/Collections-Performance-Analysis-Project
/Entry.java
UTF-8
765
2.796875
3
[]
no_license
public class Entry { private String Surname; private String Initials; private String Extension; public Entry(String Surname, String Initials, String Extension){ this.Surname = Surname; this.Initials = Initials; this.Extension = Extension; } public String getSurname() { return this.Surname; } public void setSurname(String surname) { this.Surname = surname; } public String getInitials() { return this.Initials; } public void setInitials(String initials) { this.Initials = initials; } public String getExtension() { return this.Extension; } public void setExtension(String extension) { this.Extension = extension; } }
true
2d206b53d34e66e4b5baba7cc106bb9ef14eb136
Java
Cifer1993/springclould-test
/message-server/src/main/java/com/MessageServerApplication.java
UTF-8
890
1.578125
2
[]
no_license
package com; import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.EnableAutoConfiguration; import org.springframework.boot.autoconfigure.SpringBootApplication; import org.springframework.boot.autoconfigure.jdbc.DataSourceAutoConfiguration; import org.springframework.boot.autoconfigure.orm.jpa.HibernateJpaAutoConfiguration; import org.springframework.cloud.client.discovery.EnableDiscoveryClient; import org.springframework.cloud.netflix.feign.EnableFeignClients; import org.springframework.scheduling.annotation.EnableAsync; @EnableDiscoveryClient @SpringBootApplication @EnableFeignClients @EnableAutoConfiguration //@SpringBootApplication(exclude = {DataSourceAutoConfiguration.class}) public class MessageServerApplication { public static void main(String[] args) { SpringApplication.run(MessageServerApplication.class, args); } }
true
85682d2a9c1022bc38f1ad80163480470a47f8dd
Java
HiEveryBodyWorld/workflow
/workflow-service-flowable/src/main/java/cn/com/workflow/user/UserManagerService.java
UTF-8
3,663
2.234375
2
[]
no_license
package cn.com.workflow.user; import java.util.ArrayList; import java.util.Collection; import java.util.List; import org.apache.logging.log4j.LogManager; import org.apache.logging.log4j.Logger; import org.flowable.idm.api.Group; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.context.MessageSource; import org.springframework.security.core.GrantedAuthority; import org.springframework.security.core.authority.SimpleGrantedAuthority; import org.springframework.security.core.userdetails.UserDetails; import org.springframework.security.core.userdetails.UserDetailsService; import org.springframework.security.core.userdetails.UsernameNotFoundException; import org.springframework.stereotype.Component; @Component("userManagerService") public class UserManagerService implements UserDetailsService{ private static Logger log = LogManager.getLogger(); // @Autowired // private TbSysSecurityRelUserPosMapper tbSysSecurityRelUserPosMapperImpl; // @Autowired // private TbSysSecurityUsersMapper tbSysSecurityUsersMapperImpl; @Autowired(required = true) private UserServiceImpl us; @Autowired private MessageSource messageSource; @Override public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException { UserDetails user = null; log.debug("loadUserByUsername=={}",username); try { // TbSysSecurityUsers u=tbSysSecurityUsersMapperImpl.selectByPrimaryKey(username); org.flowable.idm.api.User u=us.findUserById(username); if(null==u){ throw new UsernameNotFoundException("\u7528\u6237\u672a\u627e\u5230"+username); } User dbUser = new User(); List<Group> list=us.findGroupsByUser(u.getId()); // List<TbSysSecurityRelUserPos> list=tbSysSecurityRelUserPosMapperImpl.selectPositionForUserId(u.getUserId()); // user = new org.springframework.security.core.userdetails.User(username, u.getUserPassword() // .toLowerCase(), true, true, true, true, // getAuthorities(list)); user = new org.springframework.security.core.userdetails.User(username, u.getPassword() .toLowerCase(), true, true, true, true, getAuthorities(list)); log.debug("login is ok:"); } catch (Exception e) { e.printStackTrace(); log.error("Error in retrieving user"); throw new UsernameNotFoundException(e.getMessage()); } return user; } /** * 鑾峰緱璁块棶瑙掕壊鏉冮檺 * * @param access * @return */ public Collection<GrantedAuthority> getAuthorities(List<Group> _list) { List<GrantedAuthority> authList = new ArrayList<GrantedAuthority>(); authList.add(new SimpleGrantedAuthority("ROLE_USER")); for(Group group:_list){ log.debug("Grant "+group.getId()+" to this user"); authList.add(new SimpleGrantedAuthority(group.getId())); } return authList; } public Collection<GrantedAuthority> getAuthorities2(List<Group> _list) { List<GrantedAuthority> authList = new ArrayList<GrantedAuthority>(); authList.add(new SimpleGrantedAuthority("ROLE_USER")); for(Group group:_list){ authList.add(new SimpleGrantedAuthority(group.getName())); } return authList; } }
true
d60364eb72fdaf04df8ac7f6e06e77d44669a79a
Java
sho25/pdfbox
/pdfbox/src/main/java/org/apache/pdfbox/pdmodel/interactive/form/PDPushButton.java
UTF-8
4,168
1.851563
2
[ "Apache-2.0", "LicenseRef-scancode-unknown", "BSD-3-Clause", "LicenseRef-scancode-generic-cla", "APAFML", "LicenseRef-scancode-apple-excl", "LicenseRef-scancode-unknown-license-reference" ]
permissive
begin_unit|revision:0.9.5;language:Java;cregit-version:0.0.1 begin_comment comment|/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You 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. */ end_comment begin_package package|package name|org operator|. name|apache operator|. name|pdfbox operator|. name|pdmodel operator|. name|interactive operator|. name|form package|; end_package begin_import import|import name|java operator|. name|io operator|. name|IOException import|; end_import begin_import import|import name|java operator|. name|util operator|. name|Collections import|; end_import begin_import import|import name|java operator|. name|util operator|. name|List import|; end_import begin_import import|import name|org operator|. name|apache operator|. name|pdfbox operator|. name|cos operator|. name|COSDictionary import|; end_import begin_comment comment|/** * A pushbutton is a purely interactive control that responds immediately to user * input without retaining a permanent value. * * @author sug */ end_comment begin_class specifier|public class|class name|PDPushButton extends|extends name|PDButton block|{ comment|/** * @see PDField#PDField(PDAcroForm) * * @param acroForm The acroform. */ specifier|public name|PDPushButton parameter_list|( name|PDAcroForm name|acroForm parameter_list|) block|{ name|super argument_list|( name|acroForm argument_list|) expr_stmt|; name|setPushButton argument_list|( literal|true argument_list|) expr_stmt|; block|} comment|/** * Constructor. * * @param acroForm The form that this field is part of. * @param field the PDF object to represent as a field. * @param parent the parent node of the node */ name|PDPushButton parameter_list|( name|PDAcroForm name|acroForm parameter_list|, name|COSDictionary name|field parameter_list|, name|PDNonTerminalField name|parent parameter_list|) block|{ name|super argument_list|( name|acroForm argument_list|, name|field argument_list|, name|parent argument_list|) expr_stmt|; block|} annotation|@ name|Override specifier|public name|List argument_list|< name|String argument_list|> name|getExportValues parameter_list|() block|{ return|return name|Collections operator|. name|emptyList argument_list|() return|; block|} annotation|@ name|Override specifier|public name|void name|setExportValues parameter_list|( name|List argument_list|< name|String argument_list|> name|values parameter_list|) block|{ if|if condition|( name|values operator|!= literal|null operator|&& operator|! name|values operator|. name|isEmpty argument_list|() condition|) block|{ throw|throw operator|new name|IllegalArgumentException argument_list|( literal|"A PDPushButton shall not use the Opt entry in the field dictionary" argument_list|) throw|; block|} block|} annotation|@ name|Override specifier|public name|String name|getValue parameter_list|() block|{ return|return literal|"" return|; block|} annotation|@ name|Override specifier|public name|String name|getDefaultValue parameter_list|() block|{ return|return literal|"" return|; block|} annotation|@ name|Override specifier|public name|String name|getValueAsString parameter_list|() block|{ return|return name|getValue argument_list|() return|; block|} annotation|@ name|Override name|void name|constructAppearances parameter_list|() throws|throws name|IOException block|{ comment|// TODO: add appearance handler to generate/update appearance block|} block|} end_class end_unit
true
990db270a6869f1fb34f2e487270cb4582676d75
Java
Denchik80/TASKS
/Class and Object/src/Air/company/AircraftWork.java
UTF-8
1,594
3.3125
3
[]
no_license
package Air.company; import java.util.Random; public class AircraftWork { public static class Main { public static int SIZE = 4; public static Aircraft[] Array = new Aircraft[SIZE]; public static void main(String[] args) { AircraftMaker maker1 = new AircraftMakerAirbusA310(); AircraftMaker maker2 = new AircraftMakerBoeing747(); AircraftMaker maker3 = new AircraftMakerTU204(); Aircraft aircraft1 = maker1.createAircraft(); Aircraft aircraft2 = maker2.createAircraft(); Aircraft aircraft3 = maker3.createAircraft(); aircraft1.fly(); aircraft2.fly(); aircraft3.fly(); System.out.println("Output array without objects: "); for (int i = 1; i < Array.length; i++) { System.out.print(Array[i] + " "); } System.out.println(); Array[1] = aircraft1;//copy the object into an array Array[2] = aircraft2;//copy the object into an array Array[3] = aircraft3;//copy the object into an array System.out.println("Output array with objects: "); for (int i = 1; i < Array.length; i++) { System.out.print(Array[i] + " "); } System.out.println(); System.out.println(getRandomItem(Array)); } private static Object getRandomItem(Aircraft[]Array) { int itemIndex = (int)(Math.random()*Array.length); return Array[itemIndex]; } } }
true
eb746b296b0aa5b6af0221540c1a9841a887acf8
Java
androidfanatic/Buddy
/app/src/main/java/manish/buddy/utils/ShellUtil.java
UTF-8
1,089
2.21875
2
[]
no_license
package manish.buddy.utils; import java.util.List; import eu.chainfire.libsuperuser.Shell; import timber.log.Timber; public class ShellUtil { public static boolean isLayoutBound() { List<String> result = Shell.SU.run("getprop debug.layout"); return result.size() > 0 && result.get(0).equalsIgnoreCase("true"); } public static void setLayoutBound(boolean mode) { Shell.SU.run("setprop debug.layout " + (mode ? "true" : "false")); } public static boolean isWirelessAdb() { List<String> result = Shell.SU.run("getprop service.adb.tcp.port"); return result.size() > 0 && result.get(0).equalsIgnoreCase("5555"); } public static void setWirelessAdb(boolean mode) { Shell.SU.run("setprop service.adb.tcp.port " + (mode ? "5555" : "-1")); Shell.SU.run(new String[]{"stop adbd", "start adbd"}); } public static void setStayAwake(boolean mode) { Timber.d("1svc power stayon " + (mode ? " true " : " false ")); Shell.SU.run("svc power stayon " + (mode ? "true" : "false")); } }
true
8b90ee2776cc32ebef7d6e0759fd979e6a1a8d81
Java
ehsun7b/v3m
/src/main/java/com/ehsunbehravesh/varzesh3mobile/entity/NewspaperCollection.java
UTF-8
1,540
2.171875
2
[]
no_license
package com.ehsunbehravesh.varzesh3mobile.entity; import java.io.Serializable; import java.util.ArrayList; import java.util.Date; import java.util.List; import javax.persistence.CascadeType; import javax.persistence.Column; import javax.persistence.Entity; import javax.persistence.FetchType; import javax.persistence.GeneratedValue; import javax.persistence.GenerationType; import javax.persistence.Id; import javax.persistence.OneToMany; import javax.persistence.Temporal; import javax.xml.bind.annotation.XmlAccessType; import javax.xml.bind.annotation.XmlAccessorType; import javax.xml.bind.annotation.XmlRootElement; /** * * @author ehsun7b */ @Entity @XmlRootElement @XmlAccessorType(XmlAccessType.FIELD) public class NewspaperCollection implements Serializable { @Id @GeneratedValue(strategy = GenerationType.IDENTITY) private Long id; @OneToMany(mappedBy = "collection", cascade = CascadeType.ALL, fetch = FetchType.EAGER) private List<NewspaperPage> newspapers; @Column(nullable = false) @Temporal(javax.persistence.TemporalType.TIMESTAMP) private final Date fetchTime; public NewspaperCollection() { newspapers = new ArrayList<>(); fetchTime = new Date(); } public List<NewspaperPage> getNewspapers() { return newspapers; } public void setNewspapers(List<NewspaperPage> newspapers) { this.newspapers = newspapers; } public Long getId() { return id; } public void setId(Long id) { this.id = id; } public Date getFetchTime() { return fetchTime; } }
true
fd1599672c1c9af9f7cea4c6b98a8bf35fa03dca
Java
pannous/blueprints-netbase
/src/main/java/com/pannous/netbase/blueprints/LocalNetbase.java
UTF-8
6,939
2.03125
2
[]
no_license
package com.pannous.netbase.blueprints; import com.sun.jna.Native; import com.sun.jna.Pointer; import com.sun.jna.ptr.IntByReference; /** * * Copyright 2013 Pannous GmbH * * <p/> * * User: info@pannous.com / me * * Date: 21/01/14 * * Time: 17:36 */ public class LocalNetbase implements NetbaseAdapter{ static { Native.setProtected(true); // Native.setPreserveLastError(true); // Native.setPreserveLastError(false);// throw LastErrorException! Native.register("Netbase");// libNetbase.so | libNetbase.dylib // LocalNetbase.init(false);// testing LocalNetbase.init(true);// live // Native.getLastError() LastErrorException // NativeLibrary.getGlobalVariableAddress(java.lang.String symbolName) ! } // public static native int atol(String s); OK!! public static native int test2(); public static native void init(boolean relations); public static Node get(int id){ // if(!testing&& id<1000) return Relation.byId(id); // int i = getNodeI(id).getInt(0); return getNode(id); // return getNodeS(id); // return getNode(id).load(); } // public static native Node getAbstract(String name); public static native Node getAbstract(String name); public static native Node getThe(String name); // public static native Node getNew(String name,Node kind); public static native Node getNew(String name);// C Default parameters do NOT work with Jna !!! // public static Node getNew(String name) { // return getNew(name, Relation.Object); // } // public static native Pointer getAbstract(String name); // public static native Pointer getAbstract(String name);// just id! // public static native int getAbstract(String name);// just id! // public static native String query2(String s, int limit); public static native String getName(int id); public static native long setLabel(Node node, String label,boolean addInstance/*=true*/,boolean renameInstances/*false*/); public static native void setName(int node, String label); public static native int statementCount(); public static native int nodeCount(); public static native int nextId(); public static native boolean hasNode(String node); public static native Node getNode(int id); // public static Node getNode(int id) { // return getNodeS(id); // return new Node(id); // }; public static native int getId(String name); // public static native Pointer getNodeP(int id); // public static native NodeStruct getNodeS(int id); // public static native Node getNodeS(int id); public static native void save(Node node); // public static native void save(NodeStruct node); // public static Node getNode(int i) { // return new Node(Netbase.getNode(i)); // } public static native void showNode(int id); // public static native StatementStruct nextStatement(Node n, StatementStruct current);//,bool stopAtInstances=false); public static native StatementStruct nextStatement(int node,StatementStruct current);//,bool stopAtInstances=false); // public static native Node has(Node n, Node m); public static native StatementStruct addStatement4(int contextId, int subjectId, int predicateId, int objectId, boolean checkNodes); // Swiss Army knife // public static native StatementStruct findStatement(Node subject, Node predicate, Node object, int recurse, boolean semantic, boolean symmetric, boolean semanticPredicate, boolean matchName); public static native StatementStruct findStatement(int subject, int predicate, int object, int recurse, boolean semantic, boolean symmetric, boolean semanticPredicate, boolean matchName); // public static native int has(int n, int m); public static native void deleteNode(int id); public static native void deleteStatement(int id); // public static native NodeStruct value(String name, double v, Node unit); public static native int valueId(String name, double v, int unit); // public static Node getThe(String value) { // return getAbstract("" + value); //// return get(getAbstract("" + value).id); // } // public static <T> T getValue(int nodeId) { //// if(Double.class.isAssignableFrom(T.class))return 0; // try { // return (T) getNode(nodeId).value.getTypedValue(Double.class); // } catch (Exception x){} // try { // return (T) getNode(nodeId).value.getTypedValue(String.class); // } catch (Exception x){} // try { // return (T) getNode(nodeId).value.getTypedValue(Node.class); // } catch (Exception x){} // try { // return (T) getNode(nodeId).value.getTypedValue(StatementStruct.class); // } catch (Exception x){} // throw new RuntimeException("Unknown value type "+nodeId+" " +getNode(nodeId).value); // } public static native StatementStruct getStatement(int id); public static native int getStatementId(StatementStruct struct);/// ugly long pointer // public static native Node add(String key, int kind,int context); public static native void setKind(int id,int kind); public static native void showStatement(int id); public static native Node add(String s,int kind); public static void showNodes(Node... nodes) { for (Node node : nodes) { showNode(node.id); } } public static native Pointer execute(String s,IntByReference hits);// -> Node[] : public static Node[] doExecute(String sql) { IntByReference hitRef = new IntByReference(); Pointer n= LocalNetbase.execute(sql, hitRef); int hits = hitRef.getValue(); Node[] nodes = new Node[hits]; if(hits==0) return nodes; if(hits==1)nodes=new Node[]{new Node(n).load()}; else for (Pointer p : n.getPointerArray(0, hits)) { Node node = new Node(p); node.load(); // showNode(node.id); nodes[--hits] = node; } // Node[] nodes = (Node[]) n.toArray(2);// hits.getValue()); return nodes; } // data= byte[] bytes public static native void saveData(int node, byte[] data, int size, boolean copy); // public static native void saveData(int node, Pointer data, int size, boolean copy); // public static native byte[] getData(int node);//, data, int size); public static native Pointer getData(int node);//, data, int size); public static native Value getValue(int node); // public static native void showStatement(Statement s); // public static native int addNode(String hi); // public static native String query2(String s, int limit); // public static native String getLabel(int i); // public static native boolean setLabel(int id, String label); // public static native Pointer getStatement(int i); }
true
f7b2675027cf11313343e7a6e3f58a466a53b159
Java
lpf87383577/greendao
/app/src/main/java/com/shinhoandroid/test0909/db/CreditCardDao.java
UTF-8
5,109
2.28125
2
[]
no_license
package com.shinhoandroid.test0909.db; import java.util.List; import android.database.Cursor; import android.database.sqlite.SQLiteStatement; import org.greenrobot.greendao.AbstractDao; import org.greenrobot.greendao.Property; import org.greenrobot.greendao.internal.DaoConfig; import org.greenrobot.greendao.database.Database; import org.greenrobot.greendao.database.DatabaseStatement; import org.greenrobot.greendao.query.Query; import org.greenrobot.greendao.query.QueryBuilder; import com.shinhoandroid.test0909.bean.CreditCard; // THIS CODE IS GENERATED BY greenDAO, DO NOT EDIT. /** * DAO for table "CREDIT_CARD". */ public class CreditCardDao extends AbstractDao<CreditCard, Void> { public static final String TABLENAME = "CREDIT_CARD"; /** * Properties of entity CreditCard.<br/> * Can be used for QueryBuilder and for referencing column names. */ public static class Properties { public final static Property Id = new Property(0, Long.class, "id", false, "ID"); public final static Property UserName = new Property(1, String.class, "userName", false, "USER_NAME"); public final static Property CardNum = new Property(2, String.class, "cardNum", false, "CARD_NUM"); } private Query<CreditCard> student_MCreditCardsQuery; public CreditCardDao(DaoConfig config) { super(config); } public CreditCardDao(DaoConfig config, DaoSession daoSession) { super(config, daoSession); } /** Creates the underlying database table. */ public static void createTable(Database db, boolean ifNotExists) { String constraint = ifNotExists? "IF NOT EXISTS ": ""; db.execSQL("CREATE TABLE " + constraint + "\"CREDIT_CARD\" (" + // "\"ID\" INTEGER," + // 0: id "\"USER_NAME\" TEXT," + // 1: userName "\"CARD_NUM\" TEXT);"); // 2: cardNum } /** Drops the underlying database table. */ public static void dropTable(Database db, boolean ifExists) { String sql = "DROP TABLE " + (ifExists ? "IF EXISTS " : "") + "\"CREDIT_CARD\""; db.execSQL(sql); } @Override protected final void bindValues(DatabaseStatement stmt, CreditCard entity) { stmt.clearBindings(); Long id = entity.getId(); if (id != null) { stmt.bindLong(1, id); } String userName = entity.getUserName(); if (userName != null) { stmt.bindString(2, userName); } String cardNum = entity.getCardNum(); if (cardNum != null) { stmt.bindString(3, cardNum); } } @Override protected final void bindValues(SQLiteStatement stmt, CreditCard entity) { stmt.clearBindings(); Long id = entity.getId(); if (id != null) { stmt.bindLong(1, id); } String userName = entity.getUserName(); if (userName != null) { stmt.bindString(2, userName); } String cardNum = entity.getCardNum(); if (cardNum != null) { stmt.bindString(3, cardNum); } } @Override public Void readKey(Cursor cursor, int offset) { return null; } @Override public CreditCard readEntity(Cursor cursor, int offset) { CreditCard entity = new CreditCard( // cursor.isNull(offset + 0) ? null : cursor.getLong(offset + 0), // id cursor.isNull(offset + 1) ? null : cursor.getString(offset + 1), // userName cursor.isNull(offset + 2) ? null : cursor.getString(offset + 2) // cardNum ); return entity; } @Override public void readEntity(Cursor cursor, CreditCard entity, int offset) { entity.setId(cursor.isNull(offset + 0) ? null : cursor.getLong(offset + 0)); entity.setUserName(cursor.isNull(offset + 1) ? null : cursor.getString(offset + 1)); entity.setCardNum(cursor.isNull(offset + 2) ? null : cursor.getString(offset + 2)); } @Override protected final Void updateKeyAfterInsert(CreditCard entity, long rowId) { // Unsupported or missing PK type return null; } @Override public Void getKey(CreditCard entity) { return null; } @Override public boolean hasKey(CreditCard entity) { // TODO return false; } @Override protected final boolean isEntityUpdateable() { return true; } /** Internal query to resolve the "mCreditCards" to-many relationship of Student. */ public List<CreditCard> _queryStudent_MCreditCards(Long id) { synchronized (this) { if (student_MCreditCardsQuery == null) { QueryBuilder<CreditCard> queryBuilder = queryBuilder(); queryBuilder.where(Properties.Id.eq(null)); student_MCreditCardsQuery = queryBuilder.build(); } } Query<CreditCard> query = student_MCreditCardsQuery.forCurrentThread(); query.setParameter(0, id); return query.list(); } }
true
09eb613510cc68525e0c3a3d91e96c99d53b526c
Java
aliOsm3n/Phone_Strore
/app/src/main/java/com/phonedeals/ascom/phonestrore/data/model/ChatRoom.java
UTF-8
802
2.34375
2
[]
no_license
package com.phonedeals.ascom.phonestrore.data.model; public class ChatRoom { String from; public ChatRoom(String id, String chat_id, String from, String time, String content,String photo) { this.from = from; this.chat_id = chat_id; this.id = id; this.time = time; this.content = content; this.photo = photo; } public ChatRoom() { } String chat_id; String id; public String getPhoto() { return photo; } public String getChat_id() { return chat_id; } String photo; public String getFrom() { return from; } public String getTime() { return time; } public String getContent() { return content; } String time; String content; }
true
3413eec321488570fa817cd480f25b998a2be562
Java
Werdio66/ProgrammerInterviewCollection
/src/com/_520/offer/字符串的排列.java
UTF-8
1,328
3.515625
4
[]
no_license
package com._520.offer; import java.util.ArrayList; import java.util.Arrays; import java.util.HashSet; import java.util.Set; import java.util.stream.Collectors; /** * @author Werdio丶 * @since 2020-08-30 20:33:07 */ public class 字符串的排列 { static ArrayList<String> list = new ArrayList<>(); static int count = 0; public static ArrayList<String> permutation(String str) { dfs(0, str.toCharArray()); return list; } // 递归 private static void dfs(int index, char[] chars) { count++; // 递归结束条件 if (index + 1 == chars.length) { String s = new String(chars); if (!list.contains(s)) { list.add(s); } return; } // 固定一个交换其他的即可 for (int i = index; i < chars.length; i++) { swap(chars, i, index); dfs(index + 1, chars); // 回溯 swap(chars, i, index); } } private static void swap(char[] chars, int left, int right){ char temp = chars[left]; chars[left] = chars[right]; chars[right] = temp; } public static void main(String[] args) { System.out.println(permutation("abc")); System.out.println(count); } }
true
063d33e3d306e9ad0087a85f21d65876b0c90c7b
Java
DeanKuhne/FractalViewer
/src/code/EscapeTimeAlgorithm.java
UTF-8
8,117
3.21875
3
[]
no_license
package code; public class EscapeTimeAlgorithm { private static double xRangeStart; private static double yRangeStart; private static double xRangeEnd; private static double yRangeEnd; private static double xCalc; private static double yCalc; private static double xCurrent; private static double yCurrent; private static double xTemp; private static double yTemp; private static int width; private static int height; private static int steps; public static double getxVal(int x, int choice) { // method to show x value's translation to the column double xVal; dataInput(choice); double xStep = Math.abs(xRangeStart - xRangeEnd) / 2048;// x is row if (choice == 1) {// mandelbrot set xVal = x * xStep + xRangeStart; } else if (choice == 2) {// julia set xVal = x * xStep + xRangeStart; } else if (choice == 3) {// burning ship set xVal = x * xStep + xRangeStart; } else if (choice == 4) {// multibrot set xVal = x * xStep + xRangeStart; } else { return 0; } return xVal; } public static double getyVal(int y, int choice) { // method to show y value's translation to the row double yVal; dataInput(choice); double yStep = Math.abs(yRangeStart - yRangeEnd) / 2048;// y is column if (choice == 1) {// mandelbrot set yVal = y * yStep + yRangeStart; } else if (choice == 2) {// julia set yVal = y * yStep + yRangeStart; } else if (choice == 3) {// burning ship set yVal = y * yStep + yRangeStart; } else if (choice == 4) {// multibrot set yVal = y * yStep + yRangeStart; } else { return 0; } return yVal; } public static void dataInput(int choice) { // method to fill values based on which fractal was chosen if (choice == 1) { // mandelbrot // X-coordinate range from -2.15 to 0.6 // Y-coordinate range from -1.3 to 1.3 xRangeStart = -2.15; xRangeEnd = 0.6; yRangeStart = -1.3; yRangeEnd = 1.3; } if (choice == 2) { // julia // X-coordinate range from -1.7 to 1.7 // Y-coordinate range from -1.0 to 1.0 xRangeStart = -1.7; xRangeEnd = 1.7; yRangeStart = -1.0; yRangeEnd = 1.0; } if (choice == 3) { // burning ship // X-coordinate range from -1.8 to -1.7 // Y-coordinate range from -0.08 to 0.025 xRangeStart = -1.8; xRangeEnd = -1.7; yRangeStart = -0.08; yRangeEnd = 0.025; } if (choice == 4) { // multibrot // X-coordinate range from -1 to 1 // Y-coordinate range from -1.3 to 1.3 xRangeStart = -1; xRangeEnd = 1; yRangeStart = -1.3; yRangeEnd = 1.3; } } public static void updateXY(int choice) { // defines the way each function calculates xCalc and yCalc, specific to // each function if (choice == 1) {// mandelbrot update function xTemp = Math.pow(xCalc, 2) - Math.pow(yCalc, 2) + xCurrent; yTemp = 2 * xCalc * yCalc + yCurrent; } if (choice == 2) {// julia update function xTemp = Math.pow(xCalc, 2) - Math.pow(yCalc, 2) - 0.72689; yTemp = 2 * xCalc * yCalc + 0.188887; } if (choice == 3) {// burning ship update function xTemp = Math.pow(xCalc, 2) - Math.pow(yCalc, 2) + xCurrent; yTemp = Math.abs(2 * xCalc * yCalc) + yCurrent; } if (choice == 4) {// multibrot update function xTemp = Math.pow(xCalc, 3) - (3 * xCalc * Math.pow(yCalc, 2)) + xCurrent; yTemp = (3 * Math.pow(xCalc, 2) * yCalc) - Math.pow(yCalc, 3) + yCurrent; } } public int escTimeCoords(double x, double y, int escDist, int pass, int choice) { // method which is used to test the escape time of a single coordinate xCurrent = x; yCurrent = y; xCalc = xCurrent; yCalc = yCurrent; int passes = 0; double dist = Math.sqrt(Math.pow(xCurrent, 2) + Math.pow(yCurrent, 2)); while (dist <= escDist && passes < pass) { updateXY(choice); xCalc = xTemp; yCalc = yTemp; passes++; dist = Math.sqrt(Math.pow(xCalc, 2) + Math.pow(yCalc, 2)); } return passes; } // The problem with incorrect display IS because of this method... public int[][] escTimeCalculatorArea(double xS, double xE, double yS, double yE, int escDist, int maxStep, int choice) { xRangeStart = xS; xRangeEnd = xE; yRangeStart = yS; yRangeEnd = yE; steps = maxStep; int escTimeArray[][] = new int[width][width]; double xStep = Math.abs(xRangeStart - xRangeEnd) / 2048;// x is row double yStep = Math.abs(yRangeStart - yRangeEnd) / 2048;// y is column double xStart = xRangeStart; double yStart = yRangeStart; // Ended BT Here BRB xCalc = xStart; yCalc = yStart; xCurrent = xCalc; yCurrent = yCalc; double distance; for (int cols = 0; cols < 2048; cols++) { yCurrent = yStart + (yStep * cols); xCurrent = xStart; for (int rows = 0; rows < 2048; rows++) { xCurrent = xStart + (xStep * rows); int passes = 0; xCalc = xCurrent; yCalc = yCurrent; distance = (Math.sqrt((xCurrent * xCurrent) + (yCurrent * yCurrent))); while (distance <= escDist && passes < steps) { updateXY(choice); xCalc = xTemp; yCalc = yTemp; passes++; distance = (Math.sqrt((xCalc * xCalc) + (yCalc * yCalc))); } escTimeArray[rows][cols] = passes; } } return escTimeArray; } public int[][] escTimeCalculatorPart(double xS, double xE, double yS, double yE, int escDist, int maxStep, int choice, int length) { double xRangeStart1 = xS; double xRangeEnd1 = xE; yRangeStart = yS; yRangeEnd = yE; steps = maxStep; int escTimeArray[][] = new int[length][2048]; double xStep = Math.abs(xRangeStart1 - xRangeEnd1) / length;// x is row double yStep = Math.abs(yRangeStart - yRangeEnd) / 2048;// y is column double[] row = new double[length]; double[] col = new double[2048]; double row_start = xRangeStart1; for (int i = 0; i < length; i++) { row[i] = row_start + xStep; row_start += xStep; } double col_start = yRangeStart; for (int j = 0; j < 2048; j++) { col[j] = col_start + yStep; col_start += yStep; } for (int i = 0; i < length; i++) { for (int j = 0; j < 2048; j++) { escTimeArray[i][j] = someFun(row[i], col[j],choice, escDist); } } return escTimeArray; } private int someFun(double d, double e,int choice, double escDist) { int passes = 0; xCurrent = d; yCurrent = e; xCalc = xCurrent; yCalc = yCurrent; double distance = (Math.sqrt((xCurrent * xCurrent) + (yCurrent * yCurrent))); while (distance <= escDist && passes < steps) { updateXY(choice); xCalc = xTemp; yCalc = yTemp; passes++; distance = (Math.sqrt((xCalc * xCalc) + (yCalc * yCalc))); } // System.out.println("each time passes is: " + passes); return passes; } public int[][] escTimeCalculatorChoice(int colAmt, int rowAmt, int escDist, int maxStep, int choice) { // method that will return an entire 2d array of escape times dataInput(choice); width = colAmt; height = rowAmt; steps = maxStep; int escTimeArray[][] = new int[width][width]; double xStep = Math.abs(xRangeStart - xRangeEnd) / rowAmt;// x is row double yStep = Math.abs(yRangeStart - yRangeEnd) / colAmt;// y is column double xStart = xRangeStart; double yStart = yRangeStart; xCalc = xStart; yCalc = yStart; xCurrent = xCalc; yCurrent = yCalc; double distance; for (int cols = 0; cols < width; cols++) { yCurrent = yStart + (yStep * cols); xCurrent = xStart; for (int rows = 0; rows < height; rows++) { xCurrent = xStart + (xStep * rows); int passes = 0; xCalc = xCurrent; yCalc = yCurrent; distance = (Math.sqrt((xCurrent * xCurrent) + (yCurrent * yCurrent))); while (distance <= escDist && passes < steps) { updateXY(choice); xCalc = xTemp; yCalc = yTemp; passes++; distance = (Math.sqrt((xCalc * xCalc) + (yCalc * yCalc))); } escTimeArray[rows][cols] = passes; } } return escTimeArray; } }
true
1cc6b4ece1d8d6810d971d1c26f9a2d42b6f867f
Java
LincolnCamarini/workspace_java
/ContaBancaria/src/ContaBancaria.java
ISO-8859-1
723
3.109375
3
[]
no_license
public class ContaBancaria { int numeroConta; int digitoVerif; String cpfTitular; String nomeTitular; double saldo; void creditar(double valor) --> basicamente soma ao saldo o valor System.out.println("saldo =" +saldo); System.out.println("Info =" +saldo); System.out.println("saldo =" +saldo); } + void creditar(double valor) --> basicamente soma ao saldo o valor + void exibirInfo() --> mostra todos os dados na tela + double consultarSaldo() --> apenas retorna o valor do saldo + boolean debitar(double valor) --> se o valor for inferior ou igual ao saldo, atualiza o saldo e retorna "true", indicando que deu certo, se o valor for superior, retorna "false" e no modifica o saldo
true
bec55c2a5092534176eafb90653c8a9cf32d7d08
Java
DSpace-Labs/dspace-sandbox
/modules/dspace-srw/trunk/src/main/java/ORG/oclc/os/SRW/DSpaceLucene/LuceneQueryResult.java
UTF-8
5,069
1.914063
2
[]
no_license
/* Copyright 2006 OCLC Online Computer Library Center, Inc. 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. LuceneQueryResult.java Created January 15, 2006, 2:11 PM */ package ORG.oclc.os.SRW.DSpaceLucene; import ORG.oclc.os.SRW.QueryResult; import ORG.oclc.os.SRW.RecordIterator; import gov.loc.www.zing.srw.ExtraDataType; import java.rmi.RemoteException; import java.util.ArrayList; import java.util.List; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; import org.dspace.content.Item; import org.dspace.core.Constants; import org.dspace.core.Context; import org.dspace.handle.HandleManager; import org.dspace.search.DSQuery; import org.dspace.search.QueryArgs; import org.dspace.search.QueryResults; /** * * @author levan */ public class LuceneQueryResult extends QueryResult { static Log log=LogFactory.getLog(LuceneQueryResult.class); public Item[] resultItems; QueryArgs qArgs; QueryResults result=null; public LuceneQueryResult() { } public LuceneQueryResult(QueryArgs qArgs) throws InstantiationException { this.qArgs=qArgs; Context dspaceContext=null; try { dspaceContext=new Context(); if(log.isDebugEnabled()) { log.debug("dspaceContext.isValid()="+dspaceContext.isValid()); log.debug("getPageSize="+qArgs.getPageSize()+", getQuery="+qArgs.getQuery()+", getStart="+qArgs.getStart()); // new Exception().printStackTrace(); } result=DSQuery.doQuery(dspaceContext, qArgs); if(log.isDebugEnabled())log.debug(result.getHitHandles().size()+" handles found"); // now instantiate the results and put them in their buckets Integer myType; List collectionHandles=new ArrayList(), communityHandles=new ArrayList(), itemHandles=new ArrayList(); String myHandle; for(int i=0; i<result.getHitHandles().size(); i++) { myHandle = (String )result.getHitHandles().get(i); myType = (Integer)result.getHitTypes().get(i); // add the handle to the appropriate lists switch( myType.intValue() ) { case Constants.ITEM: itemHandles.add(myHandle); break; case Constants.COLLECTION: collectionHandles.add(myHandle); break; case Constants.COMMUNITY: communityHandles.add(myHandle); break; } } int numItems=itemHandles.size(); if(log.isDebugEnabled())log.debug(numItems+" items found"); resultItems=new Item[numItems]; for(int i=0; i<numItems; i++) { myHandle = (String)itemHandles.get(i); if(log.isDebugEnabled())log.debug("about to resolveToObject"); Object o = HandleManager.resolveToObject(dspaceContext, myHandle); if(log.isDebugEnabled())log.debug("did resolveToObject"); resultItems[i] = (Item)o; if (resultItems[i] == null) throw new RemoteException("Query \"" + qArgs.getQuery() + "\" returned unresolvable handle: " + myHandle); } int postings=result.getHitCount(); // int postings=itemHandles.size(); dspaceContext.complete(); if(log.isDebugEnabled())log.debug("'" + qArgs.getQuery() + "'==> " + postings); } catch(Exception e) { if(dspaceContext!=null) dspaceContext.abort(); throw new InstantiationException(e.getMessage()); } } public long getNumberOfRecords() { if(result==null) // probably just holding diagnostics return 0; return result.getHitCount(); } public RecordIterator newRecordIterator(long startPoint, int numRecs, String schemaID, ExtraDataType edt) throws InstantiationException { if(result==null) throw new InstantiationException("No results created"); if(startPoint==qArgs.getStart()) return new LuceneRecordIterator(this, startPoint, numRecs, edt); qArgs.setStart((int)startPoint-1); qArgs.setPageSize(numRecs); return new LuceneRecordIterator(new LuceneQueryResult(qArgs), startPoint, numRecs, edt); } }
true
34f0f6fa45560b0460d04e87ec37bceea228b28e
Java
AlexhahahaDrag/arithmetic
/src/twoDimensionalArray/MaxValue.java
UTF-8
1,335
4
4
[]
no_license
package twoDimensionalArray; /** *description: * *面试题47. 礼物的最大价值 * 在一个 m*n 的棋盘的每一格都放有一个礼物,每个礼物都有一定的价值(价值大于 0)。你可以从棋盘的左上角开始拿格子里的礼物,并每次向右或者向下移动一格、直到到达棋盘的右下角。给定一个棋盘及其上面的礼物的价值,请计算你最多能拿到多少价值的礼物? * * * * 示例 1: * * 输入: * [ * [1,3,1], * [1,5,1], * [4,2,1] * ] * 输出: 12 * 解释: 路径 1→3→5→2→1 可以拿到最多价值的礼物 * * * 提示: * * 0 < grid.length <= 200 * 0 < grid[0].length <= 200 *author: alex *createDate: 2020/2/23 10:19 *version: 1.0.0 */ public class MaxValue { public int maxValue(int[][] grid) { for (int i = 0; i < grid.length; i++) { for (int j = 0; j < grid[i].length; j++) { grid[i][j] += Math.max((i - 1 < 0 ? 0 : grid[i - 1][j]), (j - 1 < 0 ? 0 : grid[i][j - 1])); } } return grid[grid.length - 1][grid[0].length - 1]; } public static void main(String[] args) { int[][] grid = {{1,3,1},{1,5,1},{4,2,1}}; MaxValue maxValue = new MaxValue(); System.out.println(maxValue.maxValue(grid)); } }
true
9c04939a121c4b5fffaf3dc5e7fde54819ca5d87
Java
moradSleman/vero_app_android_mySql
/adroid_my_sql/veroFrontEnd/app/src/main/java/com/example/user010/vero_project/Fragments/ProfileFragment.java
UTF-8
4,070
2.09375
2
[]
no_license
package com.example.user010.vero_project.Fragments; import android.app.Activity; import android.app.Fragment; import android.app.FragmentTransaction; import android.content.Context; import android.os.Bundle; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.EditText; import android.widget.ImageButton; import android.widget.ImageView; import com.example.user010.vero_project.Fragments.FollowFragment; import com.example.user010.vero_project.Main; import com.example.user010.vero_project.R; import com.example.user010.vero_project.controller.MyInfoManager; import com.example.user010.vero_project.core.Post; public class ProfileFragment extends Fragment { private Context context = null; private ImageButton follow = null; private ImageButton requests = null; private ImageButton myPosts = null; private Activity ctx; @Override public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { final View rootView = inflater.inflate(R.layout.fragment_profile, container, false); //fill Profile stats ImageView profilePic = (ImageView) rootView.findViewById( R.id.profilePic ); EditText fullName = (EditText) rootView.findViewById( R.id.fullname ); EditText phoneNum = (EditText) rootView.findViewById( R.id.phonenum ); EditText birthdate = (EditText) rootView.findViewById( R.id.birthdateU ); EditText bio = (EditText) rootView.findViewById( R.id.bio ); profilePic.setImageBitmap( MyInfoManager.getLogedUser().getProfilePhoto() ); fullName.setText( MyInfoManager.getLogedUser().getFirstName() ); phoneNum.setText( ((Integer)MyInfoManager.getLogedUser().getPhoneNum()).toString() ); birthdate.setText( MyInfoManager.getLogedUser().getDateOfBirth().toString() ); bio.setText( MyInfoManager.getLogedUser().getBiography() ); context = rootView.getContext(); ctx = getActivity(); if (ctx != null) { ctx.setTitle(ctx.getResources().getString(R.string.Profile)); } follow = (ImageButton) rootView.findViewById(R.id.followButton); follow.setVisibility(View.VISIBLE); follow.setOnClickListener(followListener); requests = (ImageButton) rootView.findViewById(R.id.requestsButton); requests.setVisibility(View.VISIBLE); requests.setOnClickListener(requestListener); myPosts = (ImageButton) rootView.findViewById(R.id.myposts); myPosts.setVisibility(View.VISIBLE); myPosts.setOnClickListener(postsListener); return rootView; } private View.OnClickListener followListener = new View.OnClickListener() { @Override public void onClick(View arg0) { FollowFragment followFragment = new FollowFragment(); FragmentTransaction ftransaction = Main.fManager.beginTransaction(); ftransaction.replace( R.id.rootview , followFragment ); ftransaction.commit(); } }; private View.OnClickListener requestListener = new View.OnClickListener() { @Override public void onClick(View arg0) { RequestsFragment requestsFragment = new RequestsFragment(); FragmentTransaction ftransaction = Main.fManager.beginTransaction(); ftransaction.replace( R.id.rootview , requestsFragment ); ftransaction.commit(); } }; private View.OnClickListener postsListener = new View.OnClickListener() { @Override public void onClick(View arg0) { /* MyInfoManager.getInstance().getAllPostsFromServer(context); MyInfoManager.getInstance().getAllPostRepliesFromServer(context);*/ PostListFragment myPosts = new PostListFragment(); FragmentTransaction ftransaction = Main.fManager.beginTransaction(); ftransaction.replace( R.id.rootview , myPosts ); ftransaction.commit(); } }; }
true
6bede8ea824441a757fa9bbc065729d38f09d9ac
Java
seanchrishungerford/JavaProjects
/FileSystem/src/filesystem/FileSystem.java
UTF-8
3,736
3.5
4
[]
no_license
/* * Author: Sean Hungerford * Note: This application was written on a Mac, and must be run on a Mac computer. * Change the directory name for the application, for it to work properly, if needed. */ package filesystem; import java.io.File; import java.io.IOException; import java.nio.file.Files; import java.nio.file.Paths; import java.util.ArrayList; import java.util.Arrays; import java.util.Collections; import java.util.Scanner; import java.util.stream.Collectors; public class FileSystem { static void fileFinder(String fname, File theFile) { File[] listOfFiles = theFile.listFiles(); if(listOfFiles!=null) for (File fi : listOfFiles) { if (fi.isDirectory()) { fileFinder(fname,theFile); } else if (fname.equalsIgnoreCase(fi.getName())) { System.out.println(fi.getParentFile() + "/" + fname); } } } //Works Cited: https://stackoverflow.com/questions/15624226/java-search-for-files-in-a-directory public static void main(String[] args) throws IOException { File f = new File("/Users/seanhungerford/Desktop/Testing"); int option = 0; Scanner sc = new Scanner(System.in); File dir = new File("/Users/seanhungerford/Desktop/Testing"); File[] files = f.listFiles(); while(option != 6) { System.out.println("Welcome to FileSystem!"); System.out.println("Developer: Sean Hungerford."); System.out.println("You can select between 6 options, shown below with their respective fuctionality:\n"); System.out.println("1) Retrieve file names in ascending order."); System.out.println("2) Add a file."); System.out.println("3) Delete a file."); System.out.println("4) Search for a file."); System.out.println("5) Return to main menu. "); System.out.println("6) Close the application. "); System.out.println("Select from above options: "); option = sc.nextInt(); f = new File("/Users/seanhungerford/Desktop/Testing"); if(!f.exists()){ f.mkdir();} f.createNewFile(); if(option == 1) { f = new File("/Users/seanhungerford/Desktop/Testing"); if(!f.exists()){ f.mkdir();} f.createNewFile(); ArrayList<File> alFiles = new ArrayList<File>(); files = f.listFiles(); //Used to sort the files. for(File eachFile : files) { alFiles.add(eachFile); } Collections.sort(alFiles); //Sort. //Display: System.out.println("The files in the directory are: "); System.out.println(alFiles); } if(option == 2) { System.out.println("Enter file name to add: "); Scanner fileSc = new Scanner(System.in); String s = fileSc.nextLine(); f=new File(dir + "/" +s); if (f.createNewFile()) { System.out.println("File created."); } else { System.out.println("File already exists."); } files = f.listFiles(); } if(option == 3) { Scanner scnr2 = new Scanner(System.in); System.out.println("Which file would you like to delete: "); String fileToDelete = scnr2.nextLine(); try { File f2=new File(dir + "/" + fileToDelete); boolean deleted = f2.delete(); f = f2; } catch(Exception e) { System.out.println("File is not valid"); } } if(option == 4) { System.out.println("Enter a file you would like to search for: "); Scanner s3 = new Scanner(System.in); String fileToSearch = s3.nextLine(); fileFinder(fileToSearch, dir); } if(option == 5) { continue; } if(option == 6) { //Do nothing } } System.out.println("Thank you for using FileSystem. Goodbye."); } }
true
365698407da7fa66b4a676d0cdcc8f18c5caf004
Java
Lusky87/gas_bpm
/uengine/src/main/java/com/webdeninteractive/xbotts/Mapping/compiler/PathUtils.java
UTF-8
3,314
2.65625
3
[ "GPL-3.0-or-later", "GPL-1.0-or-later", "GPL-3.0-only", "EPL-2.0", "Apache-2.0", "LGPL-2.1-or-later", "LicenseRef-scancode-warranty-disclaimer", "LGPL-2.0-or-later", "LicenseRef-scancode-proprietary-license" ]
permissive
/* ------------------------------------------------------------------- BIE is Copyright 2001-2004 Brunswick Corp. ------------------------------------------------------------------- Please read the legal notices (docs/legal.txt) and the license (docs/bie_license.txt) that came with this distribution before using this software. ------------------------------------------------------------------- */ /* * LinkPath.java * * Created on August 1, 2002, 1:16 PM */ package com.webdeninteractive.xbotts.Mapping.compiler; import java.util.*; /** Contains an XPath path represented as a linked list. * XPath paths are backslash seperated strings representing each nested level, * terminated by an @attribute or #text nodeic element. * @author bmadigan */ public class PathUtils{ public static String getPath(Linkable node){ if(node.getName( ).equals("/")) return node.getName( ); //walk from node to root, creating a path LinkedList list = new LinkedList( ); list.addFirst(node); //walk tree to root, add nodes root first; Linkable o = (Linkable)node.getOwner( ); if(null!=o) { list.addFirst(o); Linkable tmp; while((tmp = o.getOwner())!=null){ o=tmp; list.addFirst(o); } } StringBuffer sb = new StringBuffer( ); Iterator iter = list.iterator(); while(iter.hasNext()){ Linkable current = (Linkable)iter.next( ); Linkable owner = current.getOwner( ); if(owner==null){ //sb.append(current.getName( )); continue; } Iterator siblings = owner.getChildren( ).iterator( ); int index = 0; while(siblings.hasNext( )){ Linkable sibling = (Linkable) siblings.next( ); if(sibling.getName( ).equals(current.getName( ))){ if(!sibling.equals(current)){ //add index to path index++; }else{ break; } } } sb.append("/"); if(current.getChildren( ).size( )==0){ if(current.getNodeType( ).equals(Linkable.ATTR_NODE)){ sb.append("@"); } } if(index>0){ sb.append(current.getName( )).append("[").append(index).append("]"); }else{ sb.append(current.getName( )); } } return sb.toString( ); } public static Linkable find(String path, Linkable root){ //search for a node in a tree. // System.out.println("searching for: "+path); StringTokenizer tok = new StringTokenizer(path, "/"); Linkable current = root; while(tok.hasMoreTokens( )){ String next = tok.nextToken( ); if(next.startsWith("@")){//strip attributes (may accur in path) next=next.substring((next.indexOf("@")+1), next.length( )); } if(next.equals("/")) continue; current = current.getChild(next); } // System.out.println("found: "+current.getName( )); return current; } }
true
b2b8bf634a55a67f1d5e97d140b2428e42fffb5a
Java
DORcode/JackFruit
/imageselector_lib/src/main/java/com/lib/imageselector/ui/widget/FolderWindow.java
UTF-8
6,609
1.96875
2
[]
no_license
package com.lib.imageselector.ui.widget; import android.animation.Animator; import android.animation.AnimatorSet; import android.animation.ObjectAnimator; import android.content.Context; import android.graphics.Color; import android.graphics.drawable.ColorDrawable; import android.support.v7.widget.LinearLayoutManager; import android.support.v7.widget.RecyclerView; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.view.ViewTreeObserver; import android.view.WindowManager; import android.view.animation.AccelerateDecelerateInterpolator; import android.view.animation.AnimationSet; import android.widget.LinearLayout; import android.widget.PopupWindow; import com.lib.imageselector.R; import com.lib.imageselector.utils.ScreenUtils; import com.lib.imageselector.beans.MediaFolder; import com.lib.imageselector.ui.adapter.ImageFolderAdapter; import java.util.List; import butterknife.OnClick; /** * @项目名称 JackFruit * @类:com.lib.imageselector.ui.widget * @描述 describe * @创建者 kh * @日期 2017/1/23 11:01 * @修改 * @修改时期 2017/1/23 11:01 */ public class FolderWindow extends PopupWindow implements View.OnClickListener{ private Context context; private View view; private RecyclerView recyclerView; private View marginView; private ImageFolderAdapter folderAdapter; private List<MediaFolder> folderList; private OnFolderSelectedListener onFolderSelectedListener; private int marginPx; public FolderWindow(Context context, List<MediaFolder> folderList) { super(context); this.context = context; this.folderList = folderList; initView(); } private void initView() { view = LayoutInflater.from(context).inflate(R.layout.layout_folders_dialog, null); view.setOnClickListener(this); recyclerView = (RecyclerView) view.findViewById(R.id.rv_folder_list); marginView = view.findViewById(R.id.margin); folderAdapter = new ImageFolderAdapter(context, folderList); LinearLayoutManager layoutManager = new LinearLayoutManager(context); layoutManager.setOrientation(LinearLayoutManager.VERTICAL); recyclerView.setLayoutManager(layoutManager); recyclerView.setHasFixedSize(true); recyclerView.setAdapter(folderAdapter); //外部点击 setOutsideTouchable(true); //设置高度 setHeight(LinearLayout.LayoutParams.MATCH_PARENT); //设置宽度 setWidth(LinearLayout.LayoutParams.MATCH_PARENT); //setAnimationStyle(R.style.popup); setFocusable(true); setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_ADJUST_RESIZE); setBackgroundDrawable(new ColorDrawable(Color.TRANSPARENT)); setContentView(view); update(); view.getViewTreeObserver().addOnGlobalLayoutListener(new ViewTreeObserver.OnGlobalLayoutListener() { @Override public void onGlobalLayout() { view.getViewTreeObserver().removeGlobalOnLayoutListener(this); int maxHeight = view.getHeight() * 5 / 8; int realHeight = recyclerView.getHeight(); ViewGroup.LayoutParams listParams = recyclerView.getLayoutParams(); listParams.height = realHeight > maxHeight ? maxHeight : realHeight; recyclerView.setLayoutParams(listParams); LinearLayout.LayoutParams marginParams = (LinearLayout.LayoutParams) marginView.getLayoutParams(); marginParams.height = marginPx; marginView.setLayoutParams(marginParams); enterAnimator(); } }); folderAdapter.setOnItemClickListener(new ImageFolderAdapter.OnItemClickListener() { @Override public void onItemClick(int position) { onFolderSelectedListener.onFolderSelect(position); dismiss(); } }); } @Override public void dismiss() { exitAnimator(); } private void enterAnimator() { ObjectAnimator listTranslate = ObjectAnimator.ofInt(recyclerView, "translationY", recyclerView.getHeight(), 0); ObjectAnimator listAlpha = ObjectAnimator.ofFloat(recyclerView, "alpha", 0, 1); AnimatorSet animatorSet = new AnimatorSet(); animatorSet.setDuration(300); //animatorSet.play(listAlpha).with(listTranslate); animatorSet.setInterpolator(new AccelerateDecelerateInterpolator()); animatorSet.playTogether(listAlpha, listTranslate); animatorSet.start(); } private void exitAnimator() { ObjectAnimator listTranslate = ObjectAnimator.ofInt(recyclerView, "translationY", 0, recyclerView.getHeight()); ObjectAnimator listAlpha = ObjectAnimator.ofFloat(recyclerView, "alpha", 1, 0); AnimatorSet animatorSet = new AnimatorSet(); animatorSet.setDuration(300); animatorSet.setInterpolator(new AccelerateDecelerateInterpolator()); animatorSet.addListener(new Animator.AnimatorListener() { @Override public void onAnimationStart(Animator animation) { } @Override public void onAnimationEnd(Animator animation) { FolderWindow.super.dismiss(); } @Override public void onAnimationCancel(Animator animation) { } @Override public void onAnimationRepeat(Animator animation) { } }); animatorSet.play(listAlpha).with(listTranslate); animatorSet.start(); } public void setFolderList(List<MediaFolder> folderList) { this.folderList = folderList; folderAdapter.setFolderList(folderList); } @Override public void showAtLocation(View parent, int gravity, int x, int y) { super.showAtLocation(parent, gravity, x, y); enterAnimator(); } @Override public void showAsDropDown(View anchor, int xoff, int yoff, int gravity) { super.showAsDropDown(anchor, xoff, yoff, gravity); } public void setOnFolderSelectedListener(OnFolderSelectedListener onFolderSelectedListener) { this.onFolderSelectedListener = onFolderSelectedListener; } @Override public void onClick(View v) { dismiss(); } public interface OnFolderSelectedListener { void onFolderSelect(int position); } public void setMarginPx(int marginPx) { this.marginPx = marginPx; } }
true
9b0c15913162944450cf9012f245a93a4015a4c5
Java
sandeepkondi/sandeep_new
/entity/ClaimTransactionClaim.java
UTF-8
10,991
1.625
2
[]
no_license
package com.beyontec.mol.entity; import java.util.Date; import javax.persistence.Column; import javax.persistence.Entity; import javax.persistence.FetchType; import javax.persistence.Id; import javax.persistence.JoinColumn; import javax.persistence.MapsId; import javax.persistence.OneToOne; import javax.persistence.Table; @Entity @Table(name = "CTDS_LEVEL_C") public class ClaimTransactionClaim { @Id @Column(name = "CLC_CLF_SGS_ID") private Long fnolSgsId; @OneToOne(fetch = FetchType.LAZY) @MapsId @JoinColumn(name = "CLC_CLF_SGS_ID") private ClaimTransactionFNOL fnol; @Column(name = "CLC_NO", nullable = false) private String claimNo; @Column(name = "CLC_CLF_NO") private String fnolNo; @Column(name = "CLC_CID") private Date claimIntimationDate; @Column(name = "CLC_CLD") private Date lossDate; @Column(name = "CLC_CDD") private Date discoveryDate; @Column(name = "CLC_LOSS_DESC") private String lossDescription; @Column(name = "CLC_ULM_SGS_ID") private int policySgsId; @Column(name = "CLC_ULM_NO") private String policyNo; @Column(name = "CLC_STATUS") private String claimStatus; @Column(name = "CLC_CUST_ID") private String customerId; @Column(name = "CLC_PROD_ID") private String productId; @Column(name = "CLC_LOSS_LOC") private String lossLocation; @Column(name = "CLC_CLOSE_YN") private String closeYN; @Column(name = "CLC_CLOSE_RSN_ID") private String closeReasonId; @Column(name = "CLC_CLOSE_RSN_REMARKS") private String closeReasonRemarks; private String CLC_TP_TYP; private String CLC_TL_TYP; private String CLC_CAT_CODE; private String CLC_CAT_NUMBER; @Column(name = "CLC_CRU") private String createdUser; @Column(name = "CLC_CRD") private Date createdDate; @Column(name = "CLC_HANDLER_ID") private String userLoginId; private String CLC_SPL_ACCESS_YN; @Column(name = "CLC_LEGAL_YN") private String litigation; private int CLC_LINK_REF_ID; private String CLC_AUTH_REP_RECD; private String CLC_AUTH_REP_ORDD; private Date CLC_CATD; private String CLC_AUTH_REP_NO; private String CLC_CLOS_REOP_TYP; private int CLC_XS_AMT; private String CLC_XS_REC_YN; private String CLC_REP_DIVN_ID; private String CLC_INS_FAULT_YN; @Column(name = "CLC_POLICE_ID") private String policeId; private String CLC_ACC_TYP_DESC; @Column(name = "CLC_COINS_FLAG") private String coInsuranceFlag; private String CLC_CAUSE_OF_ACC; private String CLC_INS_CLM_NO; private Date CLC_CIID; @Column(name = "CLC_GROUP_ID") private String groupId; @Column(name = "CLC_CLM_REASON_2") private String claimReason2; @Column(name = "CLC_REMARKS") private String remarks; public ClaimTransactionFNOL getFnol() { return fnol; } public void setFnol(ClaimTransactionFNOL fnol) { this.fnol = fnol; } @Column(name = "CLC_COMP_ID") private String companyId; @Column(name = "CLC_DIVN_ID") private String divisionId; @Column(name = "CLC_DEPT_ID") private String departmentId; private String CLC_CED_CLM_REF; @Column(name = "CLC_CLM_REASON") private String claimReason; public String getGroupId() { return groupId; } public void setGroupId(String groupId) { this.groupId = groupId; } public String getClaimReason2() { return claimReason2; } public void setClaimReason2(String claimReason2) { this.claimReason2 = claimReason2; } public String getRemarks() { return remarks; } public void setRemarks(String remarks) { this.remarks = remarks; } public Long getFnolSgsId() { return fnolSgsId; } public void setFnolSgsId(Long fnolSgsId) { this.fnolSgsId = fnolSgsId; } public String getClaimNo() { return claimNo; } public void setClaimNo(String claimNo) { this.claimNo = claimNo; } public String getFnolNo() { return fnolNo; } public void setFnolNo(String fnolNo) { this.fnolNo = fnolNo; } public Date getClaimIntimationDate() { return claimIntimationDate; } public void setClaimIntimationDate(Date claimIntimationDate) { this.claimIntimationDate = claimIntimationDate; } public Date getLossDate() { return lossDate; } public void setLossDate(Date lossDate) { this.lossDate = lossDate; } public Date getDiscoveryDate() { return discoveryDate; } public void setDiscoveryDate(Date discoveryDate) { this.discoveryDate = discoveryDate; } public String getLossDescription() { return lossDescription; } public void setLossDescription(String lossDescription) { this.lossDescription = lossDescription; } public int getPolicySgsId() { return policySgsId; } public void setPolicySgsId(int policySgsId) { this.policySgsId = policySgsId; } public String getPolicyNo() { return policyNo; } public void setPolicyNo(String policyNo) { this.policyNo = policyNo; } public String getClaimStatus() { return claimStatus; } public void setClaimStatus(String claimStatus) { this.claimStatus = claimStatus; } public String getCustomerId() { return customerId; } public void setCustomerId(String customerId) { this.customerId = customerId; } public String getProductId() { return productId; } public void setProductId(String productId) { this.productId = productId; } public String getLossLocation() { return lossLocation; } public void setLossLocation(String lossLocation) { this.lossLocation = lossLocation; } public String getCloseYN() { return closeYN; } public void setCloseYN(String closeYN) { this.closeYN = closeYN; } public String getCloseReasonId() { return closeReasonId; } public void setCloseReasonId(String closeReasonId) { this.closeReasonId = closeReasonId; } public String getCloseReasonRemarks() { return closeReasonRemarks; } public void setCloseReasonRemarks(String closeReasonRemarks) { this.closeReasonRemarks = closeReasonRemarks; } public String getCLC_TP_TYP() { return CLC_TP_TYP; } public void setCLC_TP_TYP(String cLC_TP_TYP) { CLC_TP_TYP = cLC_TP_TYP; } public String getCLC_TL_TYP() { return CLC_TL_TYP; } public void setCLC_TL_TYP(String cLC_TL_TYP) { CLC_TL_TYP = cLC_TL_TYP; } public String getCLC_CAT_CODE() { return CLC_CAT_CODE; } public void setCLC_CAT_CODE(String cLC_CAT_CODE) { CLC_CAT_CODE = cLC_CAT_CODE; } public String getCLC_CAT_NUMBER() { return CLC_CAT_NUMBER; } public void setCLC_CAT_NUMBER(String cLC_CAT_NUMBER) { CLC_CAT_NUMBER = cLC_CAT_NUMBER; } public String getCreatedUser() { return createdUser; } public void setCreatedUser(String createdUser) { this.createdUser = createdUser; } public Date getCreatedDate() { return createdDate; } public void setCreatedDate(Date createdDate) { this.createdDate = createdDate; } public String getUserLoginId() { return userLoginId; } public void setUserLoginId(String userLoginId) { this.userLoginId = userLoginId; } public String getCLC_SPL_ACCESS_YN() { return CLC_SPL_ACCESS_YN; } public void setCLC_SPL_ACCESS_YN(String cLC_SPL_ACCESS_YN) { CLC_SPL_ACCESS_YN = cLC_SPL_ACCESS_YN; } public String getLitigation() { return litigation; } public void setLitigation(String litigation) { this.litigation = litigation; } public int getCLC_LINK_REF_ID() { return CLC_LINK_REF_ID; } public void setCLC_LINK_REF_ID(int cLC_LINK_REF_ID) { CLC_LINK_REF_ID = cLC_LINK_REF_ID; } public String getCLC_AUTH_REP_RECD() { return CLC_AUTH_REP_RECD; } public void setCLC_AUTH_REP_RECD(String cLC_AUTH_REP_RECD) { CLC_AUTH_REP_RECD = cLC_AUTH_REP_RECD; } public String getCLC_AUTH_REP_ORDD() { return CLC_AUTH_REP_ORDD; } public void setCLC_AUTH_REP_ORDD(String cLC_AUTH_REP_ORDD) { CLC_AUTH_REP_ORDD = cLC_AUTH_REP_ORDD; } public Date getCLC_CATD() { return CLC_CATD; } public void setCLC_CATD(Date cLC_CATD) { CLC_CATD = cLC_CATD; } public String getCLC_AUTH_REP_NO() { return CLC_AUTH_REP_NO; } public void setCLC_AUTH_REP_NO(String cLC_AUTH_REP_NO) { CLC_AUTH_REP_NO = cLC_AUTH_REP_NO; } public String getCLC_CLOS_REOP_TYP() { return CLC_CLOS_REOP_TYP; } public void setCLC_CLOS_REOP_TYP(String cLC_CLOS_REOP_TYP) { CLC_CLOS_REOP_TYP = cLC_CLOS_REOP_TYP; } public int getCLC_XS_AMT() { return CLC_XS_AMT; } public void setCLC_XS_AMT(int cLC_XS_AMT) { CLC_XS_AMT = cLC_XS_AMT; } public String getCLC_XS_REC_YN() { return CLC_XS_REC_YN; } public void setCLC_XS_REC_YN(String cLC_XS_REC_YN) { CLC_XS_REC_YN = cLC_XS_REC_YN; } public String getCLC_REP_DIVN_ID() { return CLC_REP_DIVN_ID; } public void setCLC_REP_DIVN_ID(String cLC_REP_DIVN_ID) { CLC_REP_DIVN_ID = cLC_REP_DIVN_ID; } public String getCLC_INS_FAULT_YN() { return CLC_INS_FAULT_YN; } public void setCLC_INS_FAULT_YN(String cLC_INS_FAULT_YN) { CLC_INS_FAULT_YN = cLC_INS_FAULT_YN; } public String getPoliceId() { return policeId; } public void setPoliceId(String policeId) { this.policeId = policeId; } public String getCLC_ACC_TYP_DESC() { return CLC_ACC_TYP_DESC; } public void setCLC_ACC_TYP_DESC(String cLC_ACC_TYP_DESC) { CLC_ACC_TYP_DESC = cLC_ACC_TYP_DESC; } public String getCoInsuranceFlag() { return coInsuranceFlag; } public void setCoInsuranceFlag(String coInsuranceFlag) { this.coInsuranceFlag = coInsuranceFlag; } public String getCLC_CAUSE_OF_ACC() { return CLC_CAUSE_OF_ACC; } public void setCLC_CAUSE_OF_ACC(String cLC_CAUSE_OF_ACC) { CLC_CAUSE_OF_ACC = cLC_CAUSE_OF_ACC; } public String getCLC_INS_CLM_NO() { return CLC_INS_CLM_NO; } public void setCLC_INS_CLM_NO(String cLC_INS_CLM_NO) { CLC_INS_CLM_NO = cLC_INS_CLM_NO; } public Date getCLC_CIID() { return CLC_CIID; } public void setCLC_CIID(Date cLC_CIID) { CLC_CIID = cLC_CIID; } public String getCompanyId() { return companyId; } public void setCompanyId(String companyId) { this.companyId = companyId; } public String getDivisionId() { return divisionId; } public void setDivisionId(String divisionId) { this.divisionId = divisionId; } public String getDepartmentId() { return departmentId; } public void setDepartmentId(String departmentId) { this.departmentId = departmentId; } public String getCLC_CED_CLM_REF() { return CLC_CED_CLM_REF; } public void setCLC_CED_CLM_REF(String cLC_CED_CLM_REF) { CLC_CED_CLM_REF = cLC_CED_CLM_REF; } public String getClaimReason() { return claimReason; } public void setClaimReason(String claimReason) { this.claimReason = claimReason; } }
true
fb58a770f15ec64f70e86c92ddf6f6b178095259
Java
secharte/ab
/jason/src/jason/asSyntax/directives/FunctionRegister.java
UTF-8
3,659
2.640625
3
[]
no_license
package jason.asSyntax.directives; import jason.asSemantics.Agent; import jason.asSemantics.ArithFunction; import jason.asSyntax.NumberTerm; import jason.asSyntax.Pred; import jason.asSyntax.StringTerm; import jason.functions.Abs; import jason.functions.Length; import jason.functions.Max; import jason.functions.Min; import jason.functions.Random; import jason.functions.Round; import jason.functions.Sqrt; import jason.functions.ceil; import jason.functions.e; import jason.functions.floor; import jason.functions.log; import jason.functions.pi; import jason.functions.time; import java.util.HashMap; import java.util.Map; import java.util.logging.Level; import java.util.logging.Logger; /** * This class maintains the set of arithmetic functions available for the AS parser. * * @author Jomi */ public class FunctionRegister implements Directive { static Logger logger = Logger.getLogger(FunctionRegister.class.getName()); private static Map<String,ArithFunction> functions = new HashMap<String,ArithFunction>(); // add known global functions (can be computed without an agent reference) static { addFunction(Abs.class); addFunction(Max.class); addFunction(Min.class); addFunction(Length.class); addFunction(Random.class); addFunction(Round.class); addFunction(Sqrt.class); addFunction(pi.class); addFunction(e.class); addFunction(floor.class); addFunction(ceil.class); addFunction(log.class); addFunction(time.class); } private static void addFunction(Class<? extends ArithFunction> c) { try { ArithFunction af = c.newInstance(); functions.put(af.getName(), af); } catch (Exception e) { logger.log(Level.SEVERE, "Error registering function "+c.getName(),e); } } public static String checkFunctionName(String fName) { if (functions.get(fName) != null) return "Can not register the function "+fName+" twice!"; else if (fName.indexOf(".") < 0) return "The function "+fName+" was not registered! A function must have a '.' in its name."; else if (fName.startsWith(".")) return "The function "+fName+" was not registered! An user function name can not start with '.'."; else return null; } public static ArithFunction getFunction(String function, int arity) { ArithFunction af = functions.get(function); if (af != null && af.checkArity(arity)) return af; else return null; } @SuppressWarnings("unchecked") public Agent process(Pred directive, Agent outerContent, Agent innerContent) { if (outerContent == null) return null; try { String id = ((StringTerm)directive.getTerm(0)).getString(); if (directive.getArity() == 1) { // it is implemented in java outerContent.addFunction((Class<ArithFunction>)Class.forName(id)); } else if (directive.getArity() == 3) { // is is implemented in AS int arity = (int)((NumberTerm)directive.getTerm(1)).solve(); String predicate = ((StringTerm)directive.getTerm(2)).getString(); outerContent.addFunction(id, arity, predicate); } else { // error logger.log(Level.SEVERE, "Wrong number of arguments for register_function "+directive); } } catch (Exception e) { logger.log(Level.SEVERE, "Error processing directive register_function.",e); } return null; } }
true
adc4f15642e55da5f46c19061fb4bd3ec409342d
Java
Undin/RecommenderSystem
/src/main/java/com/ifmo/recommendersystem/JSONConverted.java
UTF-8
709
2.453125
2
[]
no_license
package com.ifmo.recommendersystem; import org.json.JSONObject; public interface JSONConverted { public JSONObject toJSON(); public interface JSONCreator<T> { public T fromJSON(JSONObject jsonObject); } public static class IllegalJSONFormatException extends IllegalArgumentException { public IllegalJSONFormatException() { super(); } public IllegalJSONFormatException(String s) { super(s); } public IllegalJSONFormatException(String message, Throwable cause) { super(message, cause); } public IllegalJSONFormatException(Throwable cause) { super(cause); } } }
true
62428544e7141740841b53c0a4cb68cc9f54221a
Java
mcstangl/Capstone-Projectplanner
/backend/src/test/java/de/mcstangl/projectplanner/config/SpringTestContextConfiguration.java
UTF-8
1,294
2.015625
2
[]
no_license
package de.mcstangl.projectplanner.config; import de.mcstangl.projectplanner.repository.ProjectRepository; import de.mcstangl.projectplanner.repository.UserRepository; import org.springframework.boot.autoconfigure.EnableAutoConfiguration; import org.springframework.boot.test.context.TestConfiguration; import org.springframework.context.annotation.*; import org.springframework.jdbc.datasource.embedded.EmbeddedDatabase; import org.springframework.jdbc.datasource.embedded.EmbeddedDatabaseBuilder; import org.springframework.jdbc.datasource.embedded.EmbeddedDatabaseType; import static org.mockito.Mockito.mock; @EnableAutoConfiguration @ComponentScan(basePackages = {"de.mcstangl.projectplanner"}) @Import({JpaConfig.class}) @TestConfiguration public class SpringTestContextConfiguration { public static final String MOCKED_PROJECT_REPOSITORY = "mockedProjectRepository"; @Primary @Bean(name = "dataSource", destroyMethod = "shutdown") public EmbeddedDatabase dataSource() { return new EmbeddedDatabaseBuilder() .setType(EmbeddedDatabaseType.H2) .build(); } @Primary @Bean @Profile(MOCKED_PROJECT_REPOSITORY) public ProjectRepository projectRepository() { return mock(ProjectRepository.class); } }
true
6a9658a55856f9d96ee715a9f534002940bf0e48
Java
entilo/crm-oa
/src/main/java/com/crm/www/entity/Function.java
UTF-8
612
2.15625
2
[]
no_license
package com.crm.www.entity; public class Function { private Integer functionId; private String fName; private String fUrls; public Integer getFunctionId() { return functionId; } public void setFunctionId(Integer functionId) { this.functionId = functionId; } public String getfName() { return fName; } public void setfName(String fName) { this.fName = fName; } public String getfUrls() { return fUrls; } public void setfUrls(String fUrls) { this.fUrls = fUrls; } }
true
ecb26c3267381cbe2a067bafac3c767055e31588
Java
sergejSDA/testProjekt
/kleiner_prototyp/anna_b/Taschenrechner/src/main/java/Form/WebController.java
UTF-8
832
2.40625
2
[]
no_license
package Form; import org.springframework.stereotype.Controller; import org.springframework.ui.ModelMap; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestMethod; import org.springframework.web.bind.annotation.RequestParam; @Controller public class WebController { @RequestMapping(value="/form", method=RequestMethod.GET) public String Show() { return "form"; } @RequestMapping(value="/ergebnis", method=RequestMethod.POST) public String Calc(ModelMap model, @RequestParam ("zahl1") int zahl1,@RequestParam ("zahl2") int zahl2 ) { model.addAttribute("zahl1",zahl1); model.addAttribute("zahl2", zahl2); int zahl3 = zahl1 % zahl2; model.addAttribute("zahl3", zahl3); return "ergebnis"; } }
true
2f04d3ea9c4eea81bef77df9a1c7a9bc3d329950
Java
Ampretuzo/PDI_scraper_input_steps
/pdi-scraper-step-base/src/main/java/ge/hamamlo/pentaho/di/trans/steps/scraper/base/ScraperBaseMeta.java
UTF-8
8,097
1.789063
2
[]
no_license
package ge.hamamlo.pentaho.di.trans.steps.scraper.base; import ge.hamamlo.pentaho.di.ui.trans.steps.scraper.base.ScraperDialog; import org.pentaho.di.core.database.DatabaseMeta; import org.pentaho.di.core.exception.KettleException; import org.pentaho.di.core.exception.KettlePluginException; import org.pentaho.di.core.exception.KettleStepException; import org.pentaho.di.core.exception.KettleXMLException; import org.pentaho.di.core.row.RowMetaInterface; import org.pentaho.di.core.row.ValueMetaInterface; import org.pentaho.di.core.row.value.ValueMetaFactory; import org.pentaho.di.core.variables.VariableSpace; import org.pentaho.di.core.xml.XMLHandler; import org.pentaho.di.repository.Repository; import org.pentaho.di.trans.Trans; import org.pentaho.di.trans.TransMeta; import org.pentaho.di.trans.step.*; import org.pentaho.metastore.api.IMetaStore; import org.w3c.dom.Node; import java.util.List; import static org.pentaho.di.core.row.ValueMetaInterface.*; public class ScraperBaseMeta extends BaseStepMeta implements StepMetaInterface { private String sourceUrl; private Class<? extends Scraper> scraperClass; private boolean reProcessing; private String mongoHost; private Integer mongoPort; private String mongoDbName; private String mongoCollectionName; public ScraperBaseMeta() { super(); } /** * Override this method to set {@code scraperClass} at the startup. */ @Override public void setDefault() { sourceUrl = null; reProcessing = true; mongoHost = null; mongoPort = null; mongoDbName = null; mongoCollectionName = null; } @Override public Object clone() { // For the user it does not really make sense to duplicate this step... ScraperBaseMeta newScraperBaseMeta = (ScraperBaseMeta) super.clone(); // Strings are immutable, it's safe to set same newScraperBaseMeta.setSourceUrl(this.sourceUrl); newScraperBaseMeta.setMongoHost(this.mongoHost); newScraperBaseMeta.setMongoPort(this.mongoPort); newScraperBaseMeta.setMongoDbName(this.mongoDbName); newScraperBaseMeta.setMongoCollectionName(this.mongoCollectionName); newScraperBaseMeta.setReProcessing(this.reProcessing); return newScraperBaseMeta; } @Override public String getXML() throws KettleException { StringBuilder retval = new StringBuilder(300); retval.append(" " + XMLHandler.addTagValue("sourceUrl", sourceUrl) ); if (mongoHost != null) { retval.append(" " + XMLHandler.addTagValue("mongoHost", mongoHost) ); } if (mongoPort != null) { retval.append(" " + XMLHandler.addTagValue("mongoPort", mongoPort) ); } if (mongoDbName != null) { retval.append(" " + XMLHandler.addTagValue("mongoDb", mongoDbName) ); } if (mongoCollectionName != null) { retval.append(" " + XMLHandler.addTagValue("mongoCollection", mongoCollectionName) ); } retval.append(" " + XMLHandler.addTagValue("reProcessing", reProcessing) ); return retval.toString(); } @Override public void loadXML(Node stepnode, List<DatabaseMeta> databases, IMetaStore metaStore) throws KettleXMLException { super.loadXML(stepnode, databases, metaStore); this.sourceUrl = XMLHandler.getTagValue(stepnode, "sourceUrl"); this.mongoHost = XMLHandler.getTagValue(stepnode, "mongoHost"); String mongoPortString = XMLHandler.getTagValue(stepnode, "mongoPort"); if (mongoPortString != null && !mongoPortString.equals("") ) this.mongoPort = Integer.parseInt(mongoPortString); this.mongoDbName = XMLHandler.getTagValue(stepnode, "mongoDb"); this.mongoCollectionName = XMLHandler.getTagValue(stepnode, "mongoCollection"); String reProcessingString = XMLHandler.getTagValue(stepnode, "reProcessing"); if (reProcessingString != null) { this.reProcessing = reProcessingString.equalsIgnoreCase("y"); } else { this.reProcessing = true; // just in case reprocess everything } } public Scraper instantiateScraper() throws ReflectiveOperationException { Class<? extends Scraper> clazz = getScraperClass(); // Use the no-arg ctor return clazz.getConstructor().newInstance(); } @Override public String getDialogClassName() { return ScraperDialog.class.getName(); } @Override public StepInterface getStep(StepMeta stepMeta, StepDataInterface stepDataInterface, int copyNr, TransMeta transMeta, Trans trans) { return new ScraperBase(stepMeta, stepDataInterface, copyNr, transMeta, trans); } @Override public StepDataInterface getStepData() { return new ScraperBaseData(); } @Override public void getFields(RowMetaInterface inputRowMeta, String name, RowMetaInterface[] info, StepMeta nextStep, VariableSpace space, Repository repository, IMetaStore metaStore) throws KettleStepException { super.getFields(inputRowMeta, name, info, nextStep, space, repository, metaStore); Scraper scraper = null; try { scraper = instantiateScraper(); } catch (ReflectiveOperationException e) { logError("Could not instantiate " + getScraperClass().getSimpleName() + " instance, make sure there is such class in classpath and it has a no-arg ctor!"); throw new KettleStepException(e); } FieldDef[] fieldDefs = scraper.fields(); for (FieldDef fieldDef : fieldDefs) { try { int type = getFieldType(fieldDef); ValueMetaInterface outputField = ValueMetaFactory.createValueMeta(type); outputField.setName(fieldDef.getName() ); inputRowMeta.addValueMeta(outputField); } catch (KettlePluginException e) { throw new KettleStepException(e); } } } private int getFieldType(FieldDef fieldDef) { int type = -1; switch (fieldDef.getFieldType() ) { case STRING: type = TYPE_STRING; break; case NUMBER: type = TYPE_NUMBER; break; case BOOLEAN: type = TYPE_BOOLEAN; break; case DATE: type = TYPE_DATE; break; default: throw new RuntimeException("Unhandled field type!"); } return type; } // ***************************************************************************************************************** // getters and setters below public String getSourceUrl() { return sourceUrl; } public void setSourceUrl(String sourceUrl) { this.sourceUrl = sourceUrl; } public Class<? extends Scraper> getScraperClass() { return scraperClass; } public void setScraperClass(Class<? extends Scraper> scraperClass) { this.scraperClass = scraperClass; } public boolean isReProcessing() { return reProcessing; } public void setReProcessing(boolean reProcessing) { this.reProcessing = reProcessing; } public String getMongoHost() { return mongoHost; } public void setMongoHost(String mongoHost) { this.mongoHost = mongoHost; } public Integer getMongoPort() { return mongoPort; } public void setMongoPort(Integer mongoPort) { this.mongoPort = mongoPort; } public String getMongoDbName() { return mongoDbName; } public void setMongoDbName(String mongoDbName) { this.mongoDbName = mongoDbName; } public String getMongoCollectionName() { return mongoCollectionName; } public void setMongoCollectionName(String mongoCollectionName) { this.mongoCollectionName = mongoCollectionName; } }
true
da6970bb15eb5ab000a34d55752de1e91f30add3
Java
ontop/ontop
/core/optimization/src/test/java/it/unibz/inf/ontop/iq/optimizer/PreventDistinctTest.java
UTF-8
15,864
1.726563
2
[ "CC-BY-4.0", "Apache-2.0" ]
permissive
package it.unibz.inf.ontop.iq.optimizer; import com.google.common.collect.ImmutableList; import com.google.common.collect.ImmutableMap; import com.google.common.collect.ImmutableSet; import it.unibz.inf.ontop.dbschema.RelationDefinition; import it.unibz.inf.ontop.iq.IQ; import it.unibz.inf.ontop.iq.IQTree; import it.unibz.inf.ontop.iq.UnaryIQTree; import it.unibz.inf.ontop.iq.node.*; import it.unibz.inf.ontop.model.atom.DistinctVariableOnlyDataAtom; import it.unibz.inf.ontop.model.term.ImmutableTerm; import it.unibz.inf.ontop.model.term.TermFactory; import it.unibz.inf.ontop.model.term.Variable; import it.unibz.inf.ontop.model.term.functionsymbol.FunctionSymbol; import it.unibz.inf.ontop.model.term.functionsymbol.db.impl.AbstractTypedDBFunctionSymbol; import it.unibz.inf.ontop.model.type.*; import it.unibz.inf.ontop.model.type.impl.DBTermTypeImpl; import it.unibz.inf.ontop.substitution.Substitution; import org.junit.Test; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import java.util.Optional; import java.util.function.Function; import static it.unibz.inf.ontop.OptimizationTestingTools.*; import static org.junit.Assert.assertEquals; public class PreventDistinctTest { private static final Logger LOGGER = LoggerFactory.getLogger(PreventDistinctTest.class); public final static RelationDefinition T1_AR2; private final static DBTermType ALLOW_DISTINCT_TYPE; private final static DBTermType PREVENT_DISTINCT_TYPE; private final static FunctionSymbol KEEP_PREVENT_FUNCTION; private final static FunctionSymbol SANITIZE_FUNCTION; private final static FunctionSymbol UNARY_FUNCTION; private final static FunctionSymbol BINARY_FUNCTION; private final static FunctionSymbol UNSAFE_BINARY_FUNCTION; private final static Variable PUSH_PREVENT_DISTINCT; private final static Variable PUSH_PREVENT_DISTINCT2; static { OfflineMetadataProviderBuilder3 builder = createMetadataProviderBuilder(); T1_AR2 = builder.createRelationWithFD(1, 2, true); var ancestry = TYPE_FACTORY.getDBTypeFactory().getDBStringType().getAncestry(); ALLOW_DISTINCT_TYPE = makeType("ALLOW_DISTINCT", ancestry, true); PREVENT_DISTINCT_TYPE = makeType("PREVENT_DISTINCT", ancestry, false); SANITIZE_FUNCTION = makeFunctionSymbol("SANITIZE", ImmutableList.of(PREVENT_DISTINCT_TYPE), ALLOW_DISTINCT_TYPE); KEEP_PREVENT_FUNCTION = makeFunctionSymbol("KEEP_PREVENT", ImmutableList.of(PREVENT_DISTINCT_TYPE), PREVENT_DISTINCT_TYPE); UNARY_FUNCTION = makeFunctionSymbol("UNARY", ImmutableList.of(ALLOW_DISTINCT_TYPE), ALLOW_DISTINCT_TYPE); BINARY_FUNCTION = makeFunctionSymbol("BINARY", ImmutableList.of(ALLOW_DISTINCT_TYPE, ALLOW_DISTINCT_TYPE), ALLOW_DISTINCT_TYPE); UNSAFE_BINARY_FUNCTION = makeFunctionSymbol("UNSAFE_BINARY", ImmutableList.of(PREVENT_DISTINCT_TYPE, PREVENT_DISTINCT_TYPE), ALLOW_DISTINCT_TYPE); PUSH_PREVENT_DISTINCT = TERM_FACTORY.getVariable("f0"); PUSH_PREVENT_DISTINCT2 = TERM_FACTORY.getVariable("f1"); } @Test public void testPreventDistinctDirect() { DistinctVariableOnlyDataAtom projectionAtom = ATOM_FACTORY.getDistinctVariableOnlyDataAtom(ANS1_AR2_PREDICATE, X, A); ExtensionalDataNode dataNode = IQ_FACTORY.createExtensionalDataNode(T1_AR2, ImmutableMap.of(0, A, 1, B)); DistinctNode distinctNode = IQ_FACTORY.createDistinctNode(); Substitution<ImmutableTerm> substitution = SUBSTITUTION_FACTORY.getSubstitution(X, TERM_FACTORY.getImmutableFunctionalTerm(SANITIZE_FUNCTION, B)); ConstructionNode constructionNode = IQ_FACTORY.createConstructionNode(ImmutableSet.of(A, X), substitution); UnaryIQTree tree = IQ_FACTORY.createUnaryIQTree( constructionNode, IQ_FACTORY.createUnaryIQTree( distinctNode, dataNode )); IQ initialQuery = IQ_FACTORY.createIQ( projectionAtom, tree); IQTree expectedResult = IQ_FACTORY.createUnaryIQTree( IQ_FACTORY.createConstructionNode(ImmutableSet.of(A, X), SUBSTITUTION_FACTORY.getSubstitution()), IQ_FACTORY.createUnaryIQTree( IQ_FACTORY.createDistinctNode(), IQ_FACTORY.createUnaryIQTree( IQ_FACTORY.createConstructionNode(ImmutableSet.of(A, X), SUBSTITUTION_FACTORY.getSubstitution(X, TERM_FACTORY.getImmutableFunctionalTerm( SANITIZE_FUNCTION, B ))), dataNode ) ) ); optimizeAndCompare(initialQuery, IQ_FACTORY.createIQ(projectionAtom, expectedResult)); } @Test public void testPreventDistinctMoreVariables() { DistinctVariableOnlyDataAtom projectionAtom = ATOM_FACTORY.getDistinctVariableOnlyDataAtom(ANS1_AR3_PREDICATE, X, A, Y); ExtensionalDataNode dataNode = IQ_FACTORY.createExtensionalDataNode(T1_AR2, ImmutableMap.of(0, A, 1, B)); DistinctNode distinctNode = IQ_FACTORY.createDistinctNode(); Substitution<ImmutableTerm> substitution = SUBSTITUTION_FACTORY.getSubstitution(X, TERM_FACTORY.getImmutableFunctionalTerm(SANITIZE_FUNCTION, B), Y, A); ConstructionNode constructionNode = IQ_FACTORY.createConstructionNode(ImmutableSet.of(A, X, Y), substitution); UnaryIQTree tree = IQ_FACTORY.createUnaryIQTree( constructionNode, IQ_FACTORY.createUnaryIQTree( distinctNode, dataNode )); IQ initialQuery = IQ_FACTORY.createIQ( projectionAtom, tree); IQTree expectedResult = IQ_FACTORY.createUnaryIQTree( IQ_FACTORY.createConstructionNode(ImmutableSet.of(A, X, Y), SUBSTITUTION_FACTORY.getSubstitution(Y, A)), IQ_FACTORY.createUnaryIQTree( IQ_FACTORY.createDistinctNode(), IQ_FACTORY.createUnaryIQTree( IQ_FACTORY.createConstructionNode(ImmutableSet.of(A, X), SUBSTITUTION_FACTORY.getSubstitution(X, TERM_FACTORY.getImmutableFunctionalTerm( SANITIZE_FUNCTION, B ))), dataNode ) ) ); optimizeAndCompare(initialQuery, IQ_FACTORY.createIQ(projectionAtom, expectedResult)); } @Test public void testPreventDistinctIndirect() { DistinctVariableOnlyDataAtom projectionAtom = ATOM_FACTORY.getDistinctVariableOnlyDataAtom(ANS1_AR2_PREDICATE, X, A); ExtensionalDataNode dataNode = IQ_FACTORY.createExtensionalDataNode(T1_AR2, ImmutableMap.of(0, A, 1, B)); DistinctNode distinctNode = IQ_FACTORY.createDistinctNode(); Substitution<ImmutableTerm> substitution = SUBSTITUTION_FACTORY.getSubstitution(X, TERM_FACTORY.getImmutableFunctionalTerm(UNARY_FUNCTION, TERM_FACTORY.getImmutableFunctionalTerm(SANITIZE_FUNCTION, B))); ConstructionNode constructionNode = IQ_FACTORY.createConstructionNode(ImmutableSet.of(A, X), substitution); UnaryIQTree tree = IQ_FACTORY.createUnaryIQTree( constructionNode, IQ_FACTORY.createUnaryIQTree( distinctNode, dataNode )); IQ initialQuery = IQ_FACTORY.createIQ( projectionAtom, tree); IQTree expectedResult = IQ_FACTORY.createUnaryIQTree( IQ_FACTORY.createConstructionNode(ImmutableSet.of(A, X), SUBSTITUTION_FACTORY.getSubstitution(X, TERM_FACTORY.getImmutableFunctionalTerm( UNARY_FUNCTION, PUSH_PREVENT_DISTINCT ))), IQ_FACTORY.createUnaryIQTree( IQ_FACTORY.createDistinctNode(), IQ_FACTORY.createUnaryIQTree( IQ_FACTORY.createConstructionNode(ImmutableSet.of(A, PUSH_PREVENT_DISTINCT), SUBSTITUTION_FACTORY.getSubstitution(PUSH_PREVENT_DISTINCT, TERM_FACTORY.getImmutableFunctionalTerm( SANITIZE_FUNCTION, B ))), dataNode ) ) ); optimizeAndCompare(initialQuery, IQ_FACTORY.createIQ(projectionAtom, expectedResult)); } @Test public void testPreventMultiple() { DistinctVariableOnlyDataAtom projectionAtom = ATOM_FACTORY.getDistinctVariableOnlyDataAtom(ANS1_AR2_PREDICATE, X, A); ExtensionalDataNode dataNode = IQ_FACTORY.createExtensionalDataNode(T1_AR2, ImmutableMap.of(0, A, 1, B)); DistinctNode distinctNode = IQ_FACTORY.createDistinctNode(); Substitution<ImmutableTerm> substitution = SUBSTITUTION_FACTORY.getSubstitution(X, TERM_FACTORY.getImmutableFunctionalTerm(UNSAFE_BINARY_FUNCTION, TERM_FACTORY.getImmutableFunctionalTerm(KEEP_PREVENT_FUNCTION, B), TERM_FACTORY.getImmutableFunctionalTerm(KEEP_PREVENT_FUNCTION, B))); ConstructionNode constructionNode = IQ_FACTORY.createConstructionNode(ImmutableSet.of(A, X), substitution); UnaryIQTree tree = IQ_FACTORY.createUnaryIQTree( constructionNode, IQ_FACTORY.createUnaryIQTree( distinctNode, dataNode )); IQ initialQuery = IQ_FACTORY.createIQ( projectionAtom, tree); IQTree expectedResult = IQ_FACTORY.createUnaryIQTree( IQ_FACTORY.createConstructionNode(ImmutableSet.of(A, X), SUBSTITUTION_FACTORY.getSubstitution()), IQ_FACTORY.createUnaryIQTree( IQ_FACTORY.createDistinctNode(), IQ_FACTORY.createUnaryIQTree( IQ_FACTORY.createConstructionNode(ImmutableSet.of(A, X), SUBSTITUTION_FACTORY.getSubstitution(X, TERM_FACTORY.getImmutableFunctionalTerm( UNSAFE_BINARY_FUNCTION, TERM_FACTORY.getImmutableFunctionalTerm(KEEP_PREVENT_FUNCTION, B), TERM_FACTORY.getImmutableFunctionalTerm(KEEP_PREVENT_FUNCTION, B) ))), dataNode ) ) ); optimizeAndCompare(initialQuery, IQ_FACTORY.createIQ(projectionAtom, expectedResult)); } @Test public void testPreventMultipleDifferent() { DistinctVariableOnlyDataAtom projectionAtom = ATOM_FACTORY.getDistinctVariableOnlyDataAtom(ANS1_AR2_PREDICATE, X, A); ExtensionalDataNode dataNode = IQ_FACTORY.createExtensionalDataNode(T1_AR2, ImmutableMap.of(0, A, 1, B)); DistinctNode distinctNode = IQ_FACTORY.createDistinctNode(); Substitution<ImmutableTerm> substitution = SUBSTITUTION_FACTORY.getSubstitution(X, TERM_FACTORY.getImmutableFunctionalTerm(BINARY_FUNCTION, TERM_FACTORY.getImmutableFunctionalTerm(SANITIZE_FUNCTION, B), TERM_FACTORY.getImmutableFunctionalTerm(SANITIZE_FUNCTION, B))); ConstructionNode constructionNode = IQ_FACTORY.createConstructionNode(ImmutableSet.of(A, X), substitution); UnaryIQTree tree = IQ_FACTORY.createUnaryIQTree( constructionNode, IQ_FACTORY.createUnaryIQTree( distinctNode, dataNode )); IQ initialQuery = IQ_FACTORY.createIQ( projectionAtom, tree); IQTree expectedResult = IQ_FACTORY.createUnaryIQTree( IQ_FACTORY.createConstructionNode(ImmutableSet.of(A, X), SUBSTITUTION_FACTORY.getSubstitution(X, TERM_FACTORY.getImmutableFunctionalTerm( BINARY_FUNCTION, PUSH_PREVENT_DISTINCT, PUSH_PREVENT_DISTINCT2 ))), IQ_FACTORY.createUnaryIQTree( IQ_FACTORY.createDistinctNode(), IQ_FACTORY.createUnaryIQTree( IQ_FACTORY.createConstructionNode(ImmutableSet.of(A, PUSH_PREVENT_DISTINCT, PUSH_PREVENT_DISTINCT2), SUBSTITUTION_FACTORY.getSubstitution( PUSH_PREVENT_DISTINCT, TERM_FACTORY.getImmutableFunctionalTerm( SANITIZE_FUNCTION, B ), PUSH_PREVENT_DISTINCT2, TERM_FACTORY.getImmutableFunctionalTerm( SANITIZE_FUNCTION, B ) )), dataNode ) ) ); optimizeAndCompare(initialQuery, IQ_FACTORY.createIQ(projectionAtom, expectedResult)); } private void optimizeAndCompare(IQ initialQuery, IQ expectedQuery) { IQ optimizedQuery = GENERAL_STRUCTURAL_AND_SEMANTIC_IQ_OPTIMIZER.optimize(initialQuery); LOGGER.debug("Initial query: {}", initialQuery); assertEquals(expectedQuery, optimizedQuery); LOGGER.debug("Optimized query: {}", optimizedQuery); } private static FunctionSymbol makeFunctionSymbol(String name, ImmutableList<TermType> types, DBTermType targetType) { return new AbstractTypedDBFunctionSymbol(name, types, targetType) { @Override protected boolean isAlwaysInjectiveInTheAbsenceOfNonInjectiveFunctionalTerms() { return true; } @Override public boolean canBePostProcessed(ImmutableList<? extends ImmutableTerm> arguments) { return false; } @Override public String getNativeDBString(ImmutableList<? extends ImmutableTerm> terms, Function<ImmutableTerm, String> termConverter, TermFactory termFactory) { return name; } }; } private static DBTermType makeType(String name, TermTypeAncestry ancestry, boolean allowDistinct) { return new DBTermTypeImpl(name, ancestry, false, DBTermType.Category.OTHER) { @Override public boolean isPreventDistinctRecommended() { return !allowDistinct; } @Override public Optional<RDFDatatype> getNaturalRDFDatatype() { return Optional.empty(); } @Override public boolean isNeedingIRISafeEncoding() { return false; } @Override public boolean areEqualitiesStrict() { return false; } @Override public Optional<Boolean> areEqualitiesStrict(DBTermType otherType) { return Optional.empty(); } @Override public boolean areEqualitiesBetweenTwoDBAttributesStrict() { return false; } }; } }
true
2d8fce3ef18fffbc829576fa8e596c813c195c77
Java
hechuan73/config-manager
/src/main/java/com/fdse/config_manager/bean/Metrics/PodMetrics/V1beta1PodItemsMetadata.java
UTF-8
405
1.703125
2
[]
no_license
package com.fdse.config_manager.bean.Metrics.PodMetrics; import com.fdse.config_manager.bean.Metrics.NodeMetrics.V1beta1NodeItemsMetadata; public class V1beta1PodItemsMetadata extends V1beta1NodeItemsMetadata { private String namespace; public String getNamespace() { return namespace; } public void setNamespace(String namespace) { this.namespace = namespace; } }
true
15a8003f00fda18b7f53ea262a2a63e06e3ecbad
Java
jhartono/Appointment_Scheduler
/src/main/java/com/bluetree/indonesia/appointment/service/impl/LocationServiceImpl.java
UTF-8
1,887
2.03125
2
[]
no_license
package com.bluetree.indonesia.appointment.service.impl; import java.util.List; import javax.inject.Inject; import org.springframework.stereotype.Service; import org.springframework.transaction.annotation.Transactional; import com.bluetree.indonesia.appointment.domain.Location; import com.bluetree.indonesia.appointment.domain.Topic; import com.bluetree.indonesia.appointment.dto.LocationDto; import com.bluetree.indonesia.appointment.dto.TopicDto; import com.bluetree.indonesia.appointment.repository.LocationRepository; import com.bluetree.indonesia.appointment.service.LocationService; @Service public class LocationServiceImpl extends AbstractTranslatingService<Location, LocationDto> implements LocationService { private static final long serialVersionUID = -1833603552284773653L; @Inject public LocationServiceImpl(LocationRepository locationRepository) { super(locationRepository); } @Override @Transactional(readOnly = true) public List<LocationDto> findByTopicAndZipCode(TopicDto topicDto, String zipCode) { Topic topic = getMapper().map(topicDto, Topic.class); return translateFromEntity(((LocationRepository) getRepository()). findByTopicsTextAndZipCode(topic.getText(), zipCode)); } @Override @Transactional(readOnly = true) public List<LocationDto> findByTopicAndCity(TopicDto topicDto, String city) { Topic topic = getMapper().map(topicDto, Topic.class); return translateFromEntity(((LocationRepository) getRepository()). findByTopicsTextAndCity(topic.getText(), city)); } @Override @Transactional(readOnly = true) public List<LocationDto> findByTopicAndZipCodeAndCity(TopicDto topicDto, String zipCode, String city) { Topic topic = getMapper().map(topicDto, Topic.class); return translateFromEntity(((LocationRepository) getRepository()). findByTopicsTextAndZipCodeAndCity(topic.getText(), zipCode, city)); } }
true
dbb0f08bc6224901d9327b50f9836442671765dc
Java
zhouziwen/College
/university/src/main/java/com/zhiyou/colleageapp/appui/person/adapter/VideoAdapter.java
UTF-8
3,202
2.234375
2
[]
no_license
package com.zhiyou.colleageapp.appui.person.adapter; import android.content.Context; import android.support.v4.content.ContextCompat; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.AbsListView; import android.widget.BaseAdapter; import android.widget.ImageView; import android.widget.LinearLayout; import android.widget.RelativeLayout; import android.widget.TextView; import com.zhiyou.colleageapp.R; import com.zhiyou.colleageapp.appui.model.TreeHole; import com.zhiyou.colleageapp.utils.DisplayUtils; import java.util.ArrayList; import java.util.List; /** * Created by chuyh on 2015/12/23. */ public class VideoAdapter extends BaseAdapter implements View.OnClickListener { private List list; private LayoutInflater layoutInflater; private Callback mCallback; private Context mContext; /** * 自定义接口,用于回调按钮点击事件到Activity * * @author chuyh * 2014-11-26 */ public interface Callback { void click(View v); } public VideoAdapter(Context context, Callback callback) { list = new ArrayList(); list.add(1); list.add(1); list.add(1); list.add(1); list.add(1); list.add(1); layoutInflater = LayoutInflater.from(context); mCallback = callback; mContext = context; } public void bindData(List data) { if (data != null) { this.list = data; this.notifyDataSetChanged(); } } @Override public int getCount() { return list.size(); } @Override public Object getItem(int i) { return list.get(i); } @Override public long getItemId(int i) { return i; } @Override public View getView(int position, View convertView, ViewGroup parent) { ViewHolder holder; if (convertView == null) { holder = new ViewHolder(); convertView = layoutInflater.inflate(R.layout.love_item_video, null); holder.zan = (RelativeLayout) convertView.findViewById(R.id.life_common_zan); holder.comment = (LinearLayout) convertView.findViewById(R.id.life_common_comment); holder.avar = (ImageView) convertView.findViewById(R.id.love_item_avar); convertView.setLayoutParams(new AbsListView.LayoutParams(AbsListView.LayoutParams.MATCH_PARENT, DisplayUtils.getHeightPx() - 80 - (int) (mContext.getResources().getDimension(R.dimen.title_bar_height)))); convertView.setTag(holder); } else { holder = (ViewHolder) convertView.getTag(); } holder.zan.setOnClickListener(this); holder.zan.setTag(position); holder.comment.setOnClickListener(this); holder.comment.setTag(position); holder.avar.setOnClickListener(this); holder.avar.setTag(position); return convertView; } @Override public void onClick(View view) { mCallback.click(view); } private static class ViewHolder { RelativeLayout zan; LinearLayout comment; ImageView avar; } }
true
20e948a67996ed404568855325f1943cec8c76aa
Java
rcclas/agenzia-viaggi
/src/main/java/agenzia/integration/ViaggiRestCtrl.java
UTF-8
1,529
2.15625
2
[]
no_license
package agenzia.integration; import java.util.List; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.web.bind.annotation.DeleteMapping; import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.PathVariable; import org.springframework.web.bind.annotation.PostMapping; import org.springframework.web.bind.annotation.PutMapping; import org.springframework.web.bind.annotation.RequestBody; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RestController; import agenzia.entities.Viaggio; import agenzia.services.ViaggioService; @RestController @RequestMapping("/api/viaggi") public class ViaggiRestCtrl { @Autowired private ViaggioService service; @PostMapping(value = "/aggiungi", consumes = "application/json") public Viaggio aggiungiViaggio(@RequestBody Viaggio viaggio) { return service.creaViaggio(viaggio); } @GetMapping("/{id}") public Viaggio trovaViaggio(@PathVariable("id") int id) { return service.trovaViaggio(id); } @GetMapping("/tutti") public List<Viaggio> tutti(){ return service.trovaTuttiViaggi(); } @PutMapping(value = "/modifica", consumes = "application/json") public Viaggio modificaViaggio(@RequestBody Viaggio viaggio) { return service.modificaViaggio(viaggio); } @DeleteMapping(value = "/elimina", consumes = "application/json") public void cancellaViaggio(@RequestBody int id) { service.eliminaViaggio(id); } }
true
621dcef60191428ea7c587b1fdb5260ccae1cf40
Java
JoyPanda/wangxian_server
/server/src/com/fy/engineserver/newtask/service/SealTaskEventTransact.java
UTF-8
4,897
1.984375
2
[]
no_license
package com.fy.engineserver.newtask.service; import java.util.Random; import com.fy.engineserver.chat.ChatMessage; import com.fy.engineserver.chat.ChatMessageService; import com.fy.engineserver.core.Game; import com.fy.engineserver.core.GameManager; import com.fy.engineserver.datasource.language.Translate; import com.fy.engineserver.message.GameMessageFactory; import com.fy.engineserver.message.HINT_REQ; import com.fy.engineserver.newtask.Task; import com.fy.engineserver.seal.SealManager; import com.fy.engineserver.sprite.Player; import com.fy.engineserver.sprite.npc.MemoryNPCManager; import com.fy.engineserver.sprite.npc.NPC; import com.fy.engineserver.sprite.npc.NPCManager; import com.fy.engineserver.sprite.npc.SealTaskFlushNPC; /** * 封印任务 * * */ public class SealTaskEventTransact extends AbsTaskEventTransact { public static String[] maps = new String[]{"bianjing"}; public static Random random = new Random(); public static int 封印npcID = 30000000; public static int[][] 坐标 = new int[][]{{272,2729},{1532,3698},{2059,1420}}; @Override public String[] getWannaDealWithTaskNames(Taskoperation action) { switch (action) { case accept: return new String[] { Translate.封印任务}; } return null; } public void init() { } @Override public void handleAccept(Player player, Task task, Game game) { String[] taskNames = getWannaDealWithTaskNames(Taskoperation.accept); if (taskNames != null) { for (String taskName : taskNames) { if (task.getName().equals(taskName)) { HINT_REQ hreq = new HINT_REQ(GameMessageFactory.nextSequnceNum(), (byte)5, Translate.translateString(Translate.您接受了任务,new String[][]{{Translate.STRING_1,taskName}})); player.addMessageToRightBag(hreq); //地图刷新封印任务奸细 GameManager gm = GameManager.getInstance(); if(gm != null){ String mapName = maps[0]; Game flushGame = gm.getGameByName(mapName,player.getCountry()); if(flushGame != null){ try{ NPCManager npcm = MemoryNPCManager.getNPCManager(); NPC newNpc = npcm.createNPC(封印npcID); if(newNpc instanceof SealTaskFlushNPC){ SealTaskFlushNPC sealNPC = (SealTaskFlushNPC)newNpc; int[] xy = 坐标[random.nextInt(坐标.length)]; sealNPC.setX(xy[0]); sealNPC.setY(xy[1]); sealNPC.flushPlayerId = player.getId(); sealNPC.sealLevel = SealManager.getInstance().getSealLevel(); sealNPC.setCountry(player.getCountry()); sealNPC.setTitle("("+player.getName()+")"); flushGame.addSprite(sealNPC); String description = Translate.translateString(Translate.在地图刷出奸细1, new String[][]{{Translate.PLAYER_NAME_1,player.getName()},{Translate.STRING_1,flushGame.gi.displayName}}); ChatMessageService cms = ChatMessageService.getInstance(); ChatMessage msg = new ChatMessage(); msg.setMessageText(description); cms.sendMessageToCountry(player.getCountry(), msg); String description2 = Translate.translateString(Translate.在地图刷出奸细2, new String[][]{{Translate.PLAYER_NAME_1,player.getName()},{Translate.STRING_1,flushGame.gi.displayName}}); ChatMessageService cms2 = ChatMessageService.getInstance(); ChatMessage msg2 = new ChatMessage(); msg2.setMessageText(description2); cms2.sendMessageToCountry2(player.getCountry(), msg2); if(Game.logger.isInfoEnabled()){ Game.logger.info("[刷新奸细] [在{}的({},{})位置上产生一个id为{}的npc]",new Object[]{mapName,xy[0],xy[1],newNpc.getId()}); } }else{ if(Game.logger.isWarnEnabled()) Game.logger.warn("[刷新奸细] [错误] [!newNpc instanceof SealTaskFlushNPC]"); } }catch(Exception ex){ if(Game.logger.isWarnEnabled()) Game.logger.warn("[刷新奸细] [异常]",ex); } }else{ if(Game.logger.isWarnEnabled()) Game.logger.warn("[刷新奸细] [错误] [刷新地图不存在]"); } }else{ if(Game.logger.isWarnEnabled()) Game.logger.warn("[刷新奸细] [错误] [gm == null]"); } break; } } } } @Override public void handleDone(Player player, Task task, Game game) { String[] taskNames = getWannaDealWithTaskNames(Taskoperation.accept); if (taskNames != null) { for (String taskName : taskNames) { if (task.getName().equals(taskName)) { player.sendError(Translate.translateString(Translate.你完成了任务快去找交付任务, new String[][]{{Translate.STRING_1,taskName},{Translate.STRING_2,task.getEndNpc()}})); } } } } @Override public void handleDeliver(Player player, Task task, Game game) { } @Override public void handleDrop(Player player, Task task, Game game) { // TODO Auto-generated method stub } }
true
8eaa965c02ecc0c456e4a10c95e100fd25e8c97d
Java
dev-jangjaeyong/Spring-boot-Rest-Api-Framework
/api_admin_1.0.0/src/main/java/com/atonm/kblease/api/file/fileStorageUtil/service/FileStorageUtilService.java
UTF-8
41,830
1.960938
2
[]
no_license
package com.atonm.kblease.api.file.fileStorageUtil.service; import com.atonm.kblease.api.common.base.BoardDTO; import com.atonm.kblease.api.config.generate.CodeConfig; import com.atonm.kblease.api.config.property.ImageServerProperty; import com.atonm.kblease.api.file.fileStorageUtil.dto.FileStorageUtilDTO; import com.atonm.kblease.api.file.fileStorageUtil.exception.FileStorageUtilException; import com.atonm.kblease.api.file.fileStorageUtil.property.FileStorageUtilProperties; import com.atonm.kblease.api.file.fileUploadInfo.dto.FileUploadInfoDTO; import com.atonm.kblease.api.file.fileUploadInfo.mapper.FileUploadMapper; import com.atonm.kblease.api.utils.DateUtil; import com.atonm.kblease.api.utils.FtpUtil; import com.atonm.kblease.api.utils.ImageUtil; import com.atonm.kblease.api.utils.StringUtil; import com.atonm.core.common.constant.Constant; import com.jcraft.jsch.SftpException; import lombok.extern.slf4j.Slf4j; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; import org.springframework.util.StringUtils; import org.springframework.web.multipart.MultipartFile; import javax.imageio.ImageIO; import java.awt.*; import java.awt.image.BufferedImage; import java.io.ByteArrayInputStream; import java.io.ByteArrayOutputStream; import java.io.File; import java.io.IOException; import java.net.UnknownHostException; import java.nio.file.Files; import java.nio.file.Path; import java.nio.file.Paths; import java.nio.file.StandardCopyOption; import java.nio.file.attribute.FileAttribute; import java.nio.file.attribute.PosixFilePermission; import java.nio.file.attribute.PosixFilePermissions; import java.time.LocalDate; import java.time.format.DateTimeFormatter; import java.util.*; import java.util.List; /** * @author jang jea young * @since 2018-08-09. */ @Slf4j @Service public class FileStorageUtilService { private final FileStorageUtilProperties fileStorageUtilProperties; private final String todayDate; private final String todayYear; private final String todayMonthDay; private Path fileTempStorageLocation; private Path fileRegularStorageLocation; @Autowired FileUploadMapper fileUploadMapper; @Autowired private ImageServerProperty imageServerProperty; @Autowired private CodeConfig codeConfig; @Autowired public FileStorageUtilService(FileStorageUtilProperties fileStorageUtilProperties) { this.todayDate = LocalDate.now().format(DateTimeFormatter.BASIC_ISO_DATE); this.todayYear = DateUtil.getDateFormat("YYYY"); this.todayMonthDay = DateUtil.getDateFormat("MMdd"); this.fileStorageUtilProperties = fileStorageUtilProperties; } /** * 외부 파일저장 * @param category * @param file * @param type * @return */ public String storeOuterFile(String category, MultipartFile file, String type) { if(file.getSize() == 0) { throw new FileStorageUtilException("File size is Zero"); } // make file Temp Storage Location fileTempStorageLocation = Paths.get(this.fileStorageUtilProperties.getOuterUploadDir() + "/board/" + category + "/" + todayYear + "/" + todayMonthDay + "/").toAbsolutePath().normalize(); createDirectories(Paths.get(this.fileStorageUtilProperties.getOuterUploadDir() + "/board/" + category + "/").toAbsolutePath().normalize()); createDirectories(Paths.get(this.fileStorageUtilProperties.getOuterUploadDir() + "/board/" + category + "/" + todayYear + "/").toAbsolutePath().normalize()); // Create Temp Storage Directories createDirectories(fileTempStorageLocation); // Normalize file name String fileName = StringUtils.cleanPath(file.getOriginalFilename()); // fileName 재정의 String fileNameReal = DateUtil.getDateFormat("dd") + StringUtil.getRandom("abc", 8) + "." + type; try { // Check if the file's name contains invalid characters if(fileName.contains("..")) { throw new FileStorageUtilException("Sorry! Filename contains invalid path sequence " + fileName); } // Copy file to the target location (Replacing existing file with the same name) Path targetLocation = fileTempStorageLocation.resolve(fileNameReal); Files.copy(file.getInputStream(), targetLocation, StandardCopyOption.REPLACE_EXISTING); Set<PosixFilePermission> perms = new HashSet<PosixFilePermission>(); //add owners permission perms.add(PosixFilePermission.OWNER_READ); perms.add(PosixFilePermission.OWNER_WRITE); perms.add(PosixFilePermission.OWNER_EXECUTE); //add group permissions perms.add(PosixFilePermission.GROUP_READ); perms.add(PosixFilePermission.GROUP_WRITE); perms.add(PosixFilePermission.GROUP_EXECUTE); //add others permissions perms.add(PosixFilePermission.OTHERS_READ); perms.add(PosixFilePermission.OTHERS_WRITE); perms.add(PosixFilePermission.OTHERS_EXECUTE); try { Files.setPosixFilePermissions(targetLocation, perms); } catch (Exception e) { new File(targetLocation.toString()).mkdir(); } //ftpFileUpload(fileTempStorageLocation.toString(), targetLocation.toString()); return this.fileStorageUtilProperties.getOuterUploadDir() + "/board/" + category + "/" + todayYear + "/" + todayMonthDay + "/" + fileNameReal; } catch (IOException ex) { throw new FileStorageUtilException("Could not store file " + fileName + ". Please try again!", ex); } /*catch (SftpException e) { throw new FileStorageUtilException("Could not ftp store file " + fileName + ". Please try again!", e); }*/ } /** * 내부 파일 저장 * @param category * @param file * @param type * @return */ public String storeLocalFile(String category, MultipartFile file, String type) { if(file.getSize() == 0) { throw new FileStorageUtilException("File size is Zero"); } // make file Temp Storage Location //fileTempStorageLocation = Paths.get(this.fileStorageUtilProperties.getUploadDir() + "/temp/" + this.todayDate + "/" + type).toAbsolutePath().normalize(); String _path = this.fileStorageUtilProperties.getInnerUploadDir() + "/" + category + "/" + todayYear + "/" + todayMonthDay + "/" ; fileTempStorageLocation = Paths.get(_path).toAbsolutePath().normalize(); createDirectories(Paths.get( _path).toAbsolutePath().normalize()); createDirectories(Paths.get( _path + category + "/" + todayYear + "/" + todayMonthDay + "/" ).toAbsolutePath().normalize()); // Create Temp Storage Directories createDirectories(fileTempStorageLocation); // Normalize file name String fileName = StringUtils.cleanPath(file.getOriginalFilename()); // fileName 재정의 String fileNameReal = DateUtil.getDateFormat("dd") + StringUtil.getRandom("abc", 8) + "." + type; try { // Check if the file's name contains invalid characters if(fileName.contains("..")) { throw new FileStorageUtilException("Sorry! Filename contains invalid path sequence " + fileName); } // Copy file to the target location (Replacing existing file with the same name) Path targetLocation = fileTempStorageLocation.resolve(fileNameReal); Files.copy(file.getInputStream(), targetLocation, StandardCopyOption.REPLACE_EXISTING); /* Set<PosixFilePermission> perms = new HashSet<PosixFilePermission>(); //add owners permission perms.add(PosixFilePermission.OWNER_READ); perms.add(PosixFilePermission.OWNER_WRITE); perms.add(PosixFilePermission.OWNER_EXECUTE); //add group permissions perms.add(PosixFilePermission.GROUP_READ); perms.add(PosixFilePermission.GROUP_WRITE); perms.add(PosixFilePermission.GROUP_EXECUTE); //add others permissions perms.add(PosixFilePermission.OTHERS_READ); perms.add(PosixFilePermission.OTHERS_WRITE); perms.add(PosixFilePermission.OTHERS_EXECUTE); try { Files.setPosixFilePermissions(targetLocation, perms); } catch (Exception e) { new File(targetLocation.toString()).mkdir(); } */ // ftpFileUpload(fileTempStorageLocation.toString(), targetLocation.toString()); // return this.fileStorageUtilProperties.getInnerUploadDir() + "/" + category + "/" + todayYear + "/" + todayMonthDay + "/" + fileNameReal; return _path + fileNameReal; } catch (IOException ex) { throw new FileStorageUtilException("Could not store file " + fileName + ". Please try again!", ex); } /*catch (SftpException e) { throw new FileStorageUtilException("Could not ftp store file " + fileName + ". Please try again!", e); }*/ } /** * 차량 이미지 등록 * @param file * @param carNo * @return */ public HashMap<String, String> storeOnCarImage(MultipartFile file, Long carNo) { if(file.getSize() == 0) { throw new FileStorageUtilException("File size is Zero"); } // make file Temp Storage Location fileTempStorageLocation = Paths.get(this.fileStorageUtilProperties.getOuterUploadDir() + "/carimage/" + String.valueOf(carNo) + "/" + todayYear + "/" + todayMonthDay + "/").toAbsolutePath().normalize(); createDirectories(Paths.get(this.fileStorageUtilProperties.getOuterUploadDir() + "/carimage/").toAbsolutePath().normalize()); createDirectories(Paths.get(this.fileStorageUtilProperties.getOuterUploadDir() + "/carimage/" + String.valueOf(carNo) + "/").toAbsolutePath().normalize()); createDirectories(Paths.get(this.fileStorageUtilProperties.getOuterUploadDir() + "/carimage/" + String.valueOf(carNo) + "/" + todayYear + "/").toAbsolutePath().normalize()); // Create Temp Storage Directories createDirectories(fileTempStorageLocation); // Normalize file name String fileName = StringUtils.cleanPath(file.getOriginalFilename()); String type = fileName.substring(fileName.lastIndexOf(".") + 1); // fileName 재정의 String fileNameReal = DateUtil.getDateFormat("dd") + StringUtil.getRandom("abc", 10) + "." + type; String thumbFileNameReal = DateUtil.getDateFormat("dd") + StringUtil.getRandom("abc", 10) + "_TH." + type; try { // Check if the file's name contains invalid characters if(fileName.contains("..")) { throw new FileStorageUtilException("Sorry! Filename contains invalid path sequence " + fileName); } // Copy file to the target location (Replacing existing file with the same name) Path targetLocation = fileTempStorageLocation.resolve(fileNameReal); Files.copy(file.getInputStream(), targetLocation, StandardCopyOption.REPLACE_EXISTING); Path targetThumbnailLocation = fileTempStorageLocation.resolve(thumbFileNameReal); ImageUtil imageUtil = new ImageUtil(file.getInputStream()); BufferedImage thumbBuffer = imageUtil.resize(640, 480).getBuffer(); ByteArrayOutputStream os = new ByteArrayOutputStream(); ImageIO.write(thumbBuffer, type, os); Files.copy(new ByteArrayInputStream(os.toByteArray()), targetThumbnailLocation, StandardCopyOption.REPLACE_EXISTING); HashMap<String, String> onCarImageMap = new HashMap<>(); onCarImageMap.put("oncarImagePath", this.fileStorageUtilProperties.getImageUrl() + String.valueOf(carNo) + "/" + todayYear + "/" + todayMonthDay + "/" + fileNameReal); onCarImageMap.put("oncarThumbImagePath", this.fileStorageUtilProperties.getImageUrl() + String.valueOf(carNo) + "/" + todayYear + "/" + todayMonthDay + "/" + thumbFileNameReal); Set<PosixFilePermission> perms = new HashSet<PosixFilePermission>(); //add owners permission perms.add(PosixFilePermission.OWNER_READ); perms.add(PosixFilePermission.OWNER_WRITE); perms.add(PosixFilePermission.OWNER_EXECUTE); //add group permissions perms.add(PosixFilePermission.GROUP_READ); perms.add(PosixFilePermission.GROUP_WRITE); perms.add(PosixFilePermission.GROUP_EXECUTE); //add others permissions perms.add(PosixFilePermission.OTHERS_READ); perms.add(PosixFilePermission.OTHERS_WRITE); perms.add(PosixFilePermission.OTHERS_EXECUTE); try { Files.setPosixFilePermissions(targetLocation, perms); Files.setPosixFilePermissions(targetThumbnailLocation, perms); } catch (Exception e) { // TODO: handle exception } //ftpFileUpload(fileTempStorageLocation.toString(), targetLocation.toString()); //ftpFileUpload(fileTempStorageLocation.toString(), targetThumbnailLocation.toString()); return onCarImageMap; } catch (IOException ex) { throw new FileStorageUtilException("Could not store file " + fileName + ". Please try again!", ex); } /*catch (SftpException e) { throw new FileStorageUtilException("Could not ftp store file " + fileName + ". Please try again!", e); }*/ } public void fileNormalization(FileStorageUtilDTO fileStorageUtilDTO, String type){ fileRegularStorageLocation = Paths.get(this.fileStorageUtilProperties.getUploadDir() + "/regular/" + type + "/" + fileStorageUtilDTO.getBoardNo()).toAbsolutePath().normalize(); createDirectories(fileRegularStorageLocation); List<String> fileNames = fileStorageUtilDTO.getFileNames(); try { for (String fileName : fileNames) { Path tempFile = Paths.get(this.fileStorageUtilProperties.getUploadDir() + "/temp/" + this.todayDate + "/" + type + "/" + fileName).toAbsolutePath().normalize(); if (fileRegularStorageLocation.resolve(tempFile.getFileName()).toFile().exists()) { Files.delete(fileRegularStorageLocation.resolve(fileName)); } Files.move(tempFile, fileRegularStorageLocation.resolve(tempFile.getFileName())); } } catch (IOException e) { e.printStackTrace(); throw new FileStorageUtilException("Could not move the files from temp storage directory", e); } } private void createDirectories(Path storageLocation) { // ::todo Exception 처리 - 디렉토리 쓰기 권한이 없을 경우 예외 처리 추가 필요! try { Set<PosixFilePermission> perms = new HashSet<PosixFilePermission>(); //add owners permission perms.add(PosixFilePermission.OWNER_READ); perms.add(PosixFilePermission.OWNER_WRITE); perms.add(PosixFilePermission.OWNER_EXECUTE); //add group permissions perms.add(PosixFilePermission.GROUP_READ); perms.add(PosixFilePermission.GROUP_WRITE); perms.add(PosixFilePermission.GROUP_EXECUTE); //add others permissions perms.add(PosixFilePermission.OTHERS_READ); perms.add(PosixFilePermission.OTHERS_WRITE); perms.add(PosixFilePermission.OTHERS_EXECUTE); //Set<PosixFilePermission> permis = PosixFilePermissions.fromString("rwxrwxrwx"); // 파일 속성 FileAttribute<Set<PosixFilePermission>> attrib = PosixFilePermissions.asFileAttribute(perms); try { Files.createDirectories(storageLocation, attrib); // Files.createDirectories(storageLocation); //outputLS(storageLocation); Files.setPosixFilePermissions(storageLocation, perms); //outputLS(storageLocation); } catch (Exception e) { new File(storageLocation.toString()).mkdir(); } } catch (Exception ex) { throw new FileStorageUtilException("Could not create the directory where the uploaded files will be stored.", ex); } } public FileUploadInfoDTO getFileById(FileStorageUtilDTO fileStorageUtilDTO) { return fileUploadMapper.getFileById(fileStorageUtilDTO); } /** * FTP 파일 업로드(For L4) * @param uploadPath * @return * @throws UnknownHostException * @throws SftpException */ private boolean ftpFileUpload(String uploadPath, String uploadFile) throws UnknownHostException, SftpException { boolean _isSuccess = false; try{ String _serverType = codeConfig.getServerType(); // System.out.println("my _serverType : " + _serverType); if(_serverType.equalsIgnoreCase("live")) { _serverType = "live-second"; }else{ _serverType = "live"; } HashMap<String, String> ftpConfig = new HashMap<>(); ftpConfig = getFtpConfig(_serverType); String host = ftpConfig.get("url"); int port = Integer.parseInt(ftpConfig.get("port")); String userName = ftpConfig.get("username"); String password = ftpConfig.get("password"); String dir = uploadPath; //접근할 폴더가 위치할 경로 FtpUtil util = new FtpUtil(); util.init(host, userName, password, port); File _uploadFile = new File(uploadFile); util.upload(dir, _uploadFile); util.disconnect(); _isSuccess = true; }catch (Exception e) { _isSuccess = false; } return _isSuccess; } /** * 이미지파일 FTP 파일 업로드 ( 2019-10-29 added by 온병옥 ) * * @param uploadPath * @return * @throws UnknownHostException * @throws SftpException */ private boolean imageFileFtpUpload(String uploadPath, String uploadFile) throws UnknownHostException, SftpException { boolean _isSuccess = false; try{ String host = imageServerProperty.getUrl(); int port = Integer.parseInt ( imageServerProperty.getPort() ); String userName = imageServerProperty.getUsername(); String password = imageServerProperty.getPassword(); String dir = imageServerProperty.getPath() + "/" + uploadPath; //접근할 폴더가 위치할 경로 FtpUtil util = new FtpUtil(); util.init(host, userName, password, port); System.out.println("################### _uploadFile "); File _uploadFile = new File(uploadFile); util.upload(dir, _uploadFile); System.out.println("################### _uploadFile "); util.disconnect(); _isSuccess = true; }catch (Exception e) { _isSuccess = false; } return _isSuccess; } public HashMap<String, String> getFtpConfig(String serverType) { HashMap<String, String> ftpConfig = new HashMap<String, String>(); if(serverType.equalsIgnoreCase("dev")) { ftpConfig = codeConfig.getFtp().get("dev"); }else if(serverType.equalsIgnoreCase("live")){ ftpConfig = codeConfig.getFtp().get("live"); }else if(serverType.equalsIgnoreCase("live-second")) { ftpConfig = codeConfig.getFtp().get("live-second"); } // 이미지 서버 FTP를 위한 설정값 가져오기 else if (serverType.equalsIgnoreCase("image-server")) { ftpConfig = codeConfig.getFtp().get("image-server"); } return ftpConfig; } /** * 서비스용 파일 업로드. * @param request * @param file * @return */ public String storeServiceOuterFile(BoardDTO request, MultipartFile file, String type) { String dir = this.fileStorageUtilProperties.getUploadDir() ; if(request.getServiceBoard().equals("003")) { dir += "/event"; } String subDir = ""; if ( request.getServiceBoard().equals( Constant.IMG_UPLOAD_SYS_PASS ) ) { subDir = Constant.IMAGE_UPLOAD_PATH.PASS_CAR.getValue() + "/"; } else if ( request.getServiceBoard().equals( Constant.IMG_UPLOAD_SYS_DELAER ) ) { subDir = Constant.IMAGE_UPLOAD_PATH.PASS_DEALER.getValue() + "/"; } else if ( request.getServiceBoard().equals( Constant.CM_DEALER_IMAGE_PATH ) ) { subDir = Constant.IMAGE_UPLOAD_PATH.CM_DEALER.getValue() + "/"; } else if ( request.getServiceBoard().equals( Constant.IMG_UPLOAD_SYS_ADMIN ) ) { subDir = Constant.IMAGE_UPLOAD_PATH.PASS_ADMIN.getValue() + "/"; } else if ( request.getServiceBoard().equals( Constant.IMG_UPLOAD_SYS_CUSTOM_ADMIN ) ) { subDir = Constant.IMAGE_UPLOAD_PATH.PASS_CUS_ADMIN.getValue() + "/"; } else { subDir = "/nt/"; } String _path = dir + subDir + todayYear + todayMonthDay + "/"; fileTempStorageLocation = Paths.get(_path).toAbsolutePath().normalize(); createDirectories(Paths.get(dir).toAbsolutePath().normalize()); //createDirectories(Paths.get(dir + todayYear + todayMonthDay + "/").toAbsolutePath().normalize()); // Create Temp Storage Directories createDirectories(fileTempStorageLocation); // Normalize file name String fileName = StringUtils.cleanPath(file.getOriginalFilename()); // fileName 재정의 String renameFileName = DateUtil.getDateFormat("dd") + StringUtil.getRandom("abc", 8); String fileNameReal = renameFileName + "." + type; try { // Check if the file's name contains invalid characters if(fileName.contains("..")) { throw new FileStorageUtilException("Sorry! Filename contains invalid path sequence " + fileName); } // Copy file to the target location (Replacing existing file with the same name) Path targetLocation = fileTempStorageLocation.resolve(fileNameReal); Files.copy(file.getInputStream(), targetLocation, StandardCopyOption.REPLACE_EXISTING); Set<PosixFilePermission> perms = new HashSet<PosixFilePermission>(); //add owners permission perms.add(PosixFilePermission.OWNER_READ); perms.add(PosixFilePermission.OWNER_WRITE); perms.add(PosixFilePermission.OWNER_EXECUTE); //add group permissions perms.add(PosixFilePermission.GROUP_READ); perms.add(PosixFilePermission.GROUP_WRITE); perms.add(PosixFilePermission.GROUP_EXECUTE); //add others permissions perms.add(PosixFilePermission.OTHERS_READ); perms.add(PosixFilePermission.OTHERS_WRITE); perms.add(PosixFilePermission.OTHERS_EXECUTE); try { Files.setPosixFilePermissions(targetLocation, perms); } catch (Exception e) { new File(targetLocation.toString()).mkdir(); } // 워터마크 적용. File waterMarkFile = ImageUtil.addImageWatermark( new File(fileStorageUtilProperties.getPassWatermarkFilePath()), new File(targetLocation.toString()), new File(targetLocation.toString() ) ); /** * 리사이즈 이미지 가로 X 세로 * = ( 원본이미지 가로 / 3 ) X ( 원본이미지 세로 / 3 ) */ // 원본 이미지 리사이징 String imgOriginalPath = waterMarkFile.toString(); // 원본 이미지 파일명 String imgTargetPath = _path + renameFileName + "_resize" + "." + type; // 새 이미지 파일명 String imgFormat = type; // 새 이미지 포맷. jpg, gif 등 int resizeRate = 3; int newWidth = ImageIO.read(waterMarkFile).getWidth() / resizeRate; // 변경 할 넓이 int newHeigt = ImageIO.read(waterMarkFile).getHeight() / resizeRate; // 변경 할 높이 // 원본 이미지 가져오기 Image image = ImageIO.read(new File(imgOriginalPath)); Image resizeImage = image.getScaledInstance(newWidth, newHeigt, Image.SCALE_SMOOTH); // 새 이미지 저장하기 BufferedImage newImage = new BufferedImage(newWidth, newHeigt, BufferedImage.TYPE_INT_RGB); Graphics graphics = newImage.getGraphics(); graphics.drawImage(resizeImage, 0, 0, null); graphics.dispose(); File targetPathFile = new File(imgTargetPath); ImageIO.write(newImage, imgFormat, targetPathFile); imageFileFtpUpload(subDir + todayYear + todayMonthDay + "/", targetPathFile.toString()); return _path + targetPathFile.getName(); } catch (IOException ex) { throw new FileStorageUtilException("Could not store file " + fileName + ". Please try again!", ex); }catch (SftpException e) { throw new FileStorageUtilException("Could not ftp store file " + fileName + ". Please try again!", e); } } /** * 서비스용 파일 내부 업로드. * @param request * @param file * @return */ public String storeServiceInnerFile(BoardDTO request, MultipartFile file, String type) { String dir = this.fileStorageUtilProperties.getUploadDir() ; if(request.getServiceBoard().equals("003")) { dir += "/event"; } String subDir = ""; if ( request.getServiceBoard().equals( Constant.IMG_UPLOAD_SYS_PASS ) ) { subDir = Constant.IMAGE_UPLOAD_PATH.PASS_CAR.getValue() + "/"; } else if ( request.getServiceBoard().equals( Constant.IMG_UPLOAD_SYS_DELAER ) ) { subDir = Constant.IMAGE_UPLOAD_PATH.PASS_DEALER.getValue() + "/"; } else if ( request.getServiceBoard().equals( Constant.IMG_UPLOAD_SYS_ADMIN ) ) { subDir = Constant.IMAGE_UPLOAD_PATH.PASS_ADMIN.getValue() + "/"; } else if ( request.getServiceBoard().equals( Constant.IMG_UPLOAD_SYS_CUSTOM_ADMIN ) ) { subDir = Constant.IMAGE_UPLOAD_PATH.PASS_CUS_ADMIN.getValue() + "/"; } else { subDir = "/nt/"; } String _path = dir + subDir + todayYear + todayMonthDay + "/"; fileTempStorageLocation = Paths.get(_path).toAbsolutePath().normalize(); createDirectories(Paths.get( dir ).toAbsolutePath().normalize()); // createDirectories(Paths.get(dir + todayYear + todayMonthDay + "/").toAbsolutePath().normalize()); // Create Temp Storage Directories createDirectories ( fileTempStorageLocation ); // Normalize file name String fileName = StringUtils.cleanPath(file.getOriginalFilename()); // fileName 재정의 String fileNameReal = DateUtil.getDateFormat("dd") + StringUtil.getRandom("abc", 8) + "." + type; try { // Check if the file's name contains invalid characters if(fileName.contains("..")) { throw new FileStorageUtilException("Sorry! Filename contains invalid path sequence " + fileName); } // Copy file to the target location (Replacing existing file with the same name) Path targetLocation = fileTempStorageLocation.resolve(fileNameReal); Files.copy(file.getInputStream(), targetLocation, StandardCopyOption.REPLACE_EXISTING); Set<PosixFilePermission> perms = new HashSet<PosixFilePermission>(); //add owners permission perms.add(PosixFilePermission.OWNER_READ); perms.add(PosixFilePermission.OWNER_WRITE); perms.add(PosixFilePermission.OWNER_EXECUTE); //add group permissions perms.add(PosixFilePermission.GROUP_READ); perms.add(PosixFilePermission.GROUP_WRITE); perms.add(PosixFilePermission.GROUP_EXECUTE); //add others permissions perms.add(PosixFilePermission.OTHERS_READ); perms.add(PosixFilePermission.OTHERS_WRITE); perms.add(PosixFilePermission.OTHERS_EXECUTE); try { Files.setPosixFilePermissions(targetLocation, perms); } catch (Exception e) { new File(targetLocation.toString()).mkdir(); } // 워터마크 적용. // File waterMarkFile = ImageUtil.addImageWatermark( new File(fileStorageUtilProperties.getPassWatermarkFilePath()), new File(targetLocation.toString()), new File(targetLocation.toString() ) ); // FTP를 통한 이미지파일을 웹서버에 업로드 수행 // dir = StringUtil.replaceAll(dir, this.fileStorageUtilProperties.getUploadDir(),""); imageFileFtpUpload(subDir + todayYear + todayMonthDay + "/", targetLocation.toString()); return _path + fileNameReal; } catch (IOException ex) { throw new FileStorageUtilException("Could not store file " + fileName + ". Please try again!", ex); } catch (SftpException e) { throw new FileStorageUtilException("Could not ftp store file " + fileName + ". Please try again!", e); } } /** * 해당 경로에 파일이 존재하는지 체크. * @param path * @return */ public boolean fileExist(String path) { boolean result = false; try { File file = new File(path); result = file.isFile(); } catch (Exception e) { result = false; } return result; } /*public String storeTempFile(MultipartFile file, String type) { // make file Temp Storage Location fileTempStorageLocation = Paths.get(this.fileStorageUtilProperties.getUploadDir() + "/temp/" + this.todayDate + "/" + type).toAbsolutePath().normalize(); // Create Temp Storage Directories createDirectories(fileTempStorageLocation); // Normalize file name String fileName = StringUtils.cleanPath(file.getOriginalFilename()); try { // Check if the file's name contains invalid characters if(fileName.contains("..")) { throw new FileStorageUtilException("Sorry! Filename contains invalid path sequence " + fileName); } // Copy file to the target location (Replacing existing file with the same name) Path targetLocation = fileTempStorageLocation.resolve(fileName); Files.copy(file.getInputStream(), targetLocation, StandardCopyOption.REPLACE_EXISTING); return fileName; } catch (IOException ex) { throw new FileStorageUtilException("Could not store file " + fileName + ". Please try again!", ex); } } public Resource loadFileAsResource(String fileName) { try { Path filePath = fileTempStorageLocation.resolve(fileName).normalize(); Resource resource = new UrlResource(filePath.toUri()); if(resource.exists()) { return resource; } else { throw new MyFileNotFoundException("File not found " + fileName); } } catch (MalformedURLException ex) { throw new MyFileNotFoundException("File not found " + fileName, ex); } } public void fileNormalization(FileStorageUtilDTO fileStorageUtilDTO, String type){ fileRegularStorageLocation = Paths.get(this.fileStorageUtilProperties.getUploadDir() + "/regular/" + type + "/" + fileStorageUtilDTO.getBoardNo()).toAbsolutePath().normalize(); createDirectories(fileRegularStorageLocation); List<String> fileNames = fileStorageUtilDTO.getFileNames(); try { for (String fileName : fileNames) { Path tempFile = Paths.get(this.fileStorageUtilProperties.getUploadDir() + "/temp/" + this.todayDate + "/" + type + "/" + fileName).toAbsolutePath().normalize(); if (fileRegularStorageLocation.resolve(tempFile.getFileName()).toFile().exists()) { Files.delete(fileRegularStorageLocation.resolve(fileName)); } Files.move(tempFile, fileRegularStorageLocation.resolve(tempFile.getFileName())); } } catch (IOException e) { e.printStackTrace(); throw new FileStorageUtilException("Could not move the files from temp storage directory", e); } } private void createDirectories(Path storageLocation) { // ::todo Exception 처리 - 디렉토리 쓰기 권한이 없을 경우 예외 처리 추가 필요! try { Files.createDirectories(storageLocation); } catch (Exception ex) { throw new FileStorageUtilException("Could not create the directory where the uploaded files will be stored.", ex); } }*/ /** * 차량 이미지 등록 * @param file * @param carNo * @return HashMap */ public HashMap<String, String> OnCarImage(MultipartFile file, String carNo) { if(file.getSize() == 0) { throw new FileStorageUtilException("File size is Zero"); } if(carNo.equals("")) { throw new FileStorageUtilException("carNo is null"); } // make file Temp Storage Location String dir = this.fileStorageUtilProperties.getOuterUploadDir() ; String path = dir + "/carimage/" + String.valueOf(carNo) + "/" + todayYear + todayMonthDay + "/"; fileTempStorageLocation = Paths.get(path).toAbsolutePath().normalize(); createDirectories(Paths.get(dir + "/carimage/").toAbsolutePath().normalize()); createDirectories(Paths.get(dir + "/carimage/" + String.valueOf(carNo) + "/").toAbsolutePath().normalize()); createDirectories(Paths.get(dir + "/carimage/" + String.valueOf(carNo) + "/" + todayYear + todayMonthDay + "/").toAbsolutePath().normalize()); createDirectories(fileTempStorageLocation); //로컬 테스트 File fileDir = new File(path); if (!fileDir.isDirectory()) { fileDir.mkdirs(); } // Normalize file name String fileName = StringUtils.cleanPath(file.getOriginalFilename()); String type = fileName.substring(fileName.lastIndexOf(".") + 1); // fileName 재정의 String fileNameReal = DateUtil.getDateFormat("dd") + StringUtil.getRandom("abc", 10) + "." + type; String thumbFileNameReal = DateUtil.getDateFormat("dd") + StringUtil.getRandom("abc", 10) + "_TH." + type; try { // Check if the file's name contains invalid characters if(fileName.contains("..")) { throw new FileStorageUtilException("Sorry! Filename contains invalid path sequence " + fileName); } // Copy file to the target location (Replacing existing file with the same name) Path targetLocation = fileTempStorageLocation.resolve(fileNameReal); Files.copy(file.getInputStream(), targetLocation, StandardCopyOption.REPLACE_EXISTING); Path targetThumbnailLocation = fileTempStorageLocation.resolve(thumbFileNameReal); ImageUtil imageUtil = new ImageUtil(file.getInputStream()); BufferedImage thumbBuffer = imageUtil.resize(640, 480).getBuffer(); ByteArrayOutputStream os = new ByteArrayOutputStream(); ImageIO.write(thumbBuffer, type, os); Files.copy(new ByteArrayInputStream(os.toByteArray()), targetThumbnailLocation, StandardCopyOption.REPLACE_EXISTING); HashMap<String, String> onCarImageMap = new HashMap<>(); String imgUrl = this.fileStorageUtilProperties.getImageUrl() + Constant.CM_DEALER_IMAGE_PATH + "/" +String.valueOf(carNo) + "/"; onCarImageMap.put("carImagePath", imgUrl + todayYear + todayMonthDay + "/" + fileNameReal); onCarImageMap.put("carImageThumbnailPath", imgUrl + todayYear + todayMonthDay + "/" + thumbFileNameReal); onCarImageMap.put("carImageDscrp", fileName); Set<PosixFilePermission> perms = new HashSet<PosixFilePermission>(); //add owners permission perms.add(PosixFilePermission.OWNER_READ); perms.add(PosixFilePermission.OWNER_WRITE); perms.add(PosixFilePermission.OWNER_EXECUTE); //add group permissions perms.add(PosixFilePermission.GROUP_READ); perms.add(PosixFilePermission.GROUP_WRITE); perms.add(PosixFilePermission.GROUP_EXECUTE); //add others permissions perms.add(PosixFilePermission.OTHERS_READ); perms.add(PosixFilePermission.OTHERS_WRITE); perms.add(PosixFilePermission.OTHERS_EXECUTE); try { Files.setPosixFilePermissions(targetLocation, perms); Files.setPosixFilePermissions(targetThumbnailLocation, perms); } catch (Exception e) { // TODO: handle exception } //이미지 ftp 전송 String subDir = Constant.CM_DEALER_IMAGE_PATH + "/"; imageFileFtpUpload(subDir + String.valueOf(carNo) + "/" + todayYear + todayMonthDay + "/", targetLocation.toString()); imageFileFtpUpload(subDir + String.valueOf(carNo) + "/" + todayYear + todayMonthDay + "/", targetThumbnailLocation.toString()); return onCarImageMap; } catch (IOException ex) { throw new FileStorageUtilException("Could not store file " + fileName + ". Please try again!", ex); } catch (SftpException e) { throw new FileStorageUtilException("Could not ftp store file " + fileName + ". Please try again!", e); } } /** * 첨부파일 업로드. * @param request * @param file * @return */ public String storeServiceOuterAttachFileUpload ( FileUploadInfoDTO request, MultipartFile file, String type) { String dir = this.fileStorageUtilProperties.getUploadDir() ; String subDir = ""; if( request.getServiceBoard() != null ) { subDir = "/" + request.getServiceBoard() + "/"; } String _path = dir + subDir + todayYear + todayMonthDay + "/"; fileTempStorageLocation = Paths.get(_path).toAbsolutePath().normalize(); createDirectories(Paths.get(dir).toAbsolutePath().normalize()); // Create Temp Storage Directories createDirectories(fileTempStorageLocation); //로컬 테스트 File fileDir = new File(_path); if (!fileDir.isDirectory()) { fileDir.mkdirs(); } // Normalize file name String fileName = StringUtils.cleanPath ( file.getOriginalFilename() ); // fileName 재정의 String renameFileName = DateUtil.getDateFormat("dd") + StringUtil.getRandom("abc", 8); String fileNameReal = renameFileName + "." + type; try { // Check if the file's name contains invalid characters if(fileName.contains("..")) { throw new FileStorageUtilException("Sorry! Filename contains invalid path sequence " + fileName); } // Copy file to the target location (Replacing existing file with the same name) Path targetLocation = fileTempStorageLocation.resolve(fileNameReal); Files.copy(file.getInputStream(), targetLocation, StandardCopyOption.REPLACE_EXISTING); Set<PosixFilePermission> perms = new HashSet<PosixFilePermission>(); //add owners permission perms.add(PosixFilePermission.OWNER_READ); perms.add(PosixFilePermission.OWNER_WRITE); perms.add(PosixFilePermission.OWNER_EXECUTE); //add group permissions perms.add(PosixFilePermission.GROUP_READ); perms.add(PosixFilePermission.GROUP_WRITE); perms.add(PosixFilePermission.GROUP_EXECUTE); //add others permissions perms.add(PosixFilePermission.OTHERS_READ); perms.add(PosixFilePermission.OTHERS_WRITE); perms.add(PosixFilePermission.OTHERS_EXECUTE); try { Files.setPosixFilePermissions(targetLocation, perms); } catch (Exception e) { new File(targetLocation.toString()).mkdir(); } File targetFile = new File(_path + fileNameReal); imageFileFtpUpload(subDir + todayYear + todayMonthDay + "/", targetFile.toString()); return _path + fileNameReal; } catch (IOException ex) { throw new FileStorageUtilException("Could not store file " + fileName + ". Please try again!", ex); }catch (SftpException e) { throw new FileStorageUtilException("Could not ftp store file " + fileName + ". Please try again!", e); } } }
true
54acc8013d9150d9b47ed855f805c62656dc0ebf
Java
xlreconlx/DUGLASPILOTO
/src/java/Interface/InterfaceProductos.java
UTF-8
883
2.09375
2
[]
no_license
/* * 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 Interface; import Pojos.Productos; import java.util.List; import org.hibernate.Session; /** * * @author KevinArnold */ public interface InterfaceProductos { public boolean registrar(Session session, Productos productos) throws Exception; public Productos getByIdProducto(Session session, Integer idproductos) throws Exception; public List<Productos> getAll(Session session) throws Exception; public Productos getByCodigoBarras(Session session, String codigoBarras) throws Exception; public boolean update(Session session, Productos productos) throws Exception; public Productos getByCodidoProducto(Session session, String codigoProducto); }
true
688b3648fd5d305d1c888bbf1a72f9be7c56711e
Java
lineboy23/switchboard
/src/main/java/com/jartein/switchboard/beans/gson/FpkjBean.java
UTF-8
2,419
1.796875
2
[]
no_license
package com.jartein.switchboard.beans.gson; import java.io.Serializable; import java.util.List; /** * Created by JohnnyLeung on 2017/1/12. */ public class FpkjBean implements Serializable { private String type; private String nsrmc; private String nsrsbh; private String dzdh; private String yhzh; private String gfnsrsbh; private String gfmc; private String gfdzdh; private String gfyhzh; private String bz; private String kpr; private String skr; private String fhr; private List<SpBean> sps; public String getType() { return type; } public void setType(String type) { this.type = type; } public String getNsrmc() { return nsrmc; } public void setNsrmc(String nsrmc) { this.nsrmc = nsrmc; } public String getNsrsbh() { return nsrsbh; } public void setNsrsbh(String nsrsbh) { this.nsrsbh = nsrsbh; } public String getDzdh() { return dzdh; } public void setDzdh(String dzdh) { this.dzdh = dzdh; } public String getYhzh() { return yhzh; } public void setYhzh(String yhzh) { this.yhzh = yhzh; } public String getBz() { return bz; } public void setBz(String bz) { this.bz = bz; } public List<SpBean> getSps() { return sps; } public String getGfnsrsbh() { return gfnsrsbh; } public void setGfnsrsbh(String gfnsrsbh) { this.gfnsrsbh = gfnsrsbh; } public String getGfdzdh() { return gfdzdh; } public void setGfdzdh(String gfdzdh) { this.gfdzdh = gfdzdh; } public String getGfyhzh() { return gfyhzh; } public void setGfyhzh(String gfyhzh) { this.gfyhzh = gfyhzh; } public String getGfmc() { return gfmc; } public void setGfmc(String gfmc) { this.gfmc = gfmc; } public void setSps(List<SpBean> sps) { this.sps = sps; } public String getKpr() { return kpr; } public void setKpr(String kpr) { this.kpr = kpr; } public String getSkr() { return skr; } public void setSkr(String skr) { this.skr = skr; } public String getFhr() { return fhr; } public void setFhr(String fhr) { this.fhr = fhr; } }
true
e90e90d4a53600500f8ac4b05581ac7d36530e38
Java
qinluyan89/themis
/themis-coprocessor/src/main/java/org/apache/hadoop/hbase/themis/cp/ThemisEndpointClient.java
UTF-8
21,514
1.585938
2
[ "Apache-2.0" ]
permissive
package org.apache.hadoop.hbase.themis.cp; import java.io.IOException; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; import org.apache.hadoop.hbase.HConstants; import org.apache.hadoop.hbase.client.Get; import org.apache.hadoop.hbase.client.HConnection; import org.apache.hadoop.hbase.client.HTableInterface; import org.apache.hadoop.hbase.client.Result; import org.apache.hadoop.hbase.ipc.BlockingRpcCallback; import org.apache.hadoop.hbase.ipc.CoprocessorRpcChannel; import org.apache.hadoop.hbase.ipc.ServerRpcController; import org.apache.hadoop.hbase.protobuf.ProtobufUtil; import org.apache.hadoop.hbase.protobuf.generated.ClientProtos; import org.apache.hadoop.hbase.themis.columns.ColumnCoordinate; import org.apache.hadoop.hbase.themis.columns.ColumnMutation; import org.apache.hadoop.hbase.themis.columns.RowMutation; import org.apache.hadoop.hbase.themis.cp.generated.ThemisProtos.EraseLockRequest; import org.apache.hadoop.hbase.themis.cp.generated.ThemisProtos.EraseLockResponse; import org.apache.hadoop.hbase.themis.cp.generated.ThemisProtos.LockExpiredRequest; import org.apache.hadoop.hbase.themis.cp.generated.ThemisProtos.LockExpiredResponse; import org.apache.hadoop.hbase.themis.cp.generated.ThemisProtos.ThemisBatchCommitSecondaryRequest; import org.apache.hadoop.hbase.themis.cp.generated.ThemisProtos.ThemisBatchCommitSecondaryResponse; import org.apache.hadoop.hbase.themis.cp.generated.ThemisProtos.ThemisBatchCommitSecondaryResult; import org.apache.hadoop.hbase.themis.cp.generated.ThemisProtos.ThemisBatchPrewriteSecondaryRequest; import org.apache.hadoop.hbase.themis.cp.generated.ThemisProtos.ThemisBatchPrewriteSecondaryResponse; import org.apache.hadoop.hbase.themis.cp.generated.ThemisProtos.ThemisCommit; import org.apache.hadoop.hbase.themis.cp.generated.ThemisProtos.ThemisCommitRequest; import org.apache.hadoop.hbase.themis.cp.generated.ThemisProtos.ThemisCommitResponse; import org.apache.hadoop.hbase.themis.cp.generated.ThemisProtos.ThemisGetRequest; import org.apache.hadoop.hbase.themis.cp.generated.ThemisProtos.ThemisGetRequest.Builder; import org.apache.hadoop.hbase.themis.cp.generated.ThemisProtos.ThemisPrewrite; import org.apache.hadoop.hbase.themis.cp.generated.ThemisProtos.ThemisPrewriteRequest; import org.apache.hadoop.hbase.themis.cp.generated.ThemisProtos.ThemisPrewriteResponse; import org.apache.hadoop.hbase.themis.cp.generated.ThemisProtos.ThemisPrewriteResult; import org.apache.hadoop.hbase.themis.cp.generated.ThemisProtos.ThemisService.Stub; import org.apache.hadoop.hbase.themis.exception.LockCleanedException; import org.apache.hadoop.hbase.themis.exception.WriteConflictException; import org.apache.hadoop.hbase.themis.lock.ThemisLock; import org.apache.hadoop.hbase.util.Bytes; import com.google.protobuf.ByteString; import com.google.protobuf.HBaseZeroCopyByteString; import static org.apache.hadoop.hbase.themis.cp.generated.ThemisProtos.*; // coprocessor client for ThemisProtocol public class ThemisEndpointClient { private final HConnection conn; private static final Log LOG = LogFactory.getLog(ThemisEndpointClient.class); public ThemisEndpointClient(HConnection connection) { this.conn = connection; } static abstract class CoprocessorCallable<R> { private HConnection conn; private byte[] tableName; private byte[] row; private HTableInterface table = null; public CoprocessorCallable(HConnection conn, byte[] tableName, byte[] row) { this.conn = conn; this.tableName = tableName; this.row = row; } public R run() throws IOException { try { table = conn.getTable(tableName); CoprocessorRpcChannel channel = table.coprocessorService(row); Stub stub = (Stub) ProtobufUtil.newServiceStub(ThemisService.class, channel); return invokeCoprocessor(stub); } catch (Throwable e) { throw new IOException(e); } finally { if (table != null) { table.close(); } } } public abstract R invokeCoprocessor(Stub stub) throws Throwable; } public Result themisGet(final byte[] tableName, final Get get, final long startTs) throws IOException { return themisGet(tableName, get, startTs, false); } protected static void checkRpcException(ServerRpcController controller) throws IOException { if (controller.getFailedOn() != null) { throw controller.getFailedOn(); } } public Result themisGet(final byte[] tableName, final Get get, final long startTs, final boolean ignoreLock) throws IOException { return new CoprocessorCallable<Result>(conn, tableName, get.getRow()) { @Override public Result invokeCoprocessor(Stub instance) throws Throwable { Builder builder = ThemisGetRequest.newBuilder(); builder.setGet(ProtobufUtil.toGet(get)); builder.setStartTs(startTs); builder.setIgnoreLock(ignoreLock); ServerRpcController controller = new ServerRpcController(); BlockingRpcCallback<ClientProtos.Result> rpcCallback = new BlockingRpcCallback<ClientProtos.Result>(); instance.themisGet(controller, builder.build(), rpcCallback); checkRpcException(controller); return ProtobufUtil.toResult(rpcCallback.get()); } }.run(); } public List<Result> themisBatchGet(final byte[] tableName, final List<Get> gets, final long startTs, final boolean ignoreLock) throws IOException { if (gets.size() == 0) { return null; } ThemisBatchGetResponse batchGetResponse = new CoprocessorCallable<ThemisBatchGetResponse>(conn, tableName, gets.get(0).getRow()){ @Override public ThemisBatchGetResponse invokeCoprocessor(Stub instance) throws Throwable { ThemisBatchGetRequest.Builder builder = ThemisBatchGetRequest.newBuilder(); for (Get g : gets) { builder.addGets(ProtobufUtil.toGet(g)); } builder.setStartTs(startTs); builder.setIgnoreLock(ignoreLock); ServerRpcController controller = new ServerRpcController(); BlockingRpcCallback<ThemisBatchGetResponse> rpcCallback = new BlockingRpcCallback<ThemisBatchGetResponse>(); instance.themisBatchGet(controller, builder.build(), rpcCallback); checkRpcException(controller); return rpcCallback.get(); } }.run(); // if contain results if (batchGetResponse.getRsCount() > 0) { List<Result> results = new ArrayList<Result>(); for (ClientProtos.Result r : batchGetResponse.getRsList()) { results.add(ProtobufUtil.toResult(r)); } return results; } return null; } public ThemisLock prewriteSecondaryRow(final byte[] tableName, final byte[] row, final List<ColumnMutation> mutations, final long prewriteTs, final byte[] secondaryLock) throws IOException { return prewriteRow(tableName, row, mutations, prewriteTs, null, secondaryLock, -1); } public Map<byte[], ThemisLock> batchPrewriteSecondaryRows(final byte[] tblName, final List<RowMutation> rows, final long prewriteTs, final byte[] secondaryLock) throws IOException { final Map<byte[], ThemisLock> lockMap = new HashMap<byte[], ThemisLock>(); CoprocessorCallable<List<ThemisPrewriteResult>> callable = new CoprocessorCallable<List<ThemisPrewriteResult>>(conn, tblName, rows.get(0).getRow()) { @Override public List<ThemisPrewriteResult> invokeCoprocessor(Stub instance) throws Throwable { ThemisBatchPrewriteSecondaryRequest.Builder builder = ThemisBatchPrewriteSecondaryRequest.newBuilder(); ThemisPrewrite.Builder b = null; for (RowMutation row : rows) { b = ThemisPrewrite.newBuilder(); b.setRow(HBaseZeroCopyByteString.wrap(row.getRow())); for (ColumnMutation mutation : row.mutationList()) { b.addMutations(ColumnMutation.toCell(mutation)); } builder.addThemisPrewrite(b); } builder.setPrewriteTs(prewriteTs); builder.setSecondaryLock( HBaseZeroCopyByteString.wrap(secondaryLock == null ? HConstants.EMPTY_BYTE_ARRAY : secondaryLock)); ServerRpcController controller = new ServerRpcController(); BlockingRpcCallback<ThemisBatchPrewriteSecondaryResponse> rpcCallback = new BlockingRpcCallback<ThemisBatchPrewriteSecondaryResponse>(); instance.batchPrewriteSecondaryRows(controller, builder.build(), rpcCallback); checkRpcException(controller); // Perhaps, part row has not in a region, sample : when region split, // then need try List<ByteString> rowsNotInRegion = rpcCallback.get().getRowsNotInRegionList(); if (rowsNotInRegion != null && rowsNotInRegion.size() > 0) { Map<byte[], List<ColumnMutation>> rowMap = list2Map4Batch(rows); for (ByteString rowkey : rowsNotInRegion) { ThemisLock l = prewriteRow(tblName, rowkey.toByteArray(), rowMap.get(rowkey.toByteArray()), prewriteTs, null, secondaryLock, -1); if (l != null) { lockMap.put(rowkey.toByteArray(), l); } } } return rpcCallback.get().getThemisPrewriteResultList(); } }; batchJudgePerwriteResultRow(lockMap, tblName, rows, callable.run(), prewriteTs); return lockMap; } private Map<byte[], List<ColumnMutation>> list2Map4Batch(List<RowMutation> rows) { Map<byte[], List<ColumnMutation>> rowMap = new HashMap<>(); for (RowMutation rowM : rows) { rowMap.put(rowM.getRow(), rowM.mutationList()); } return rowMap; } public ThemisLock prewriteRow(final byte[] tableName, final byte[] row, final List<ColumnMutation> mutations, final long prewriteTs, final byte[] primaryLock, final byte[] secondaryLock, final int primaryIndex) throws IOException { return prewriteRow(tableName, row, mutations, prewriteTs, primaryLock, secondaryLock, primaryIndex, false); } public ThemisLock prewriteSingleRow(final byte[] tableName, final byte[] row, final List<ColumnMutation> mutations, final long prewriteTs, final byte[] primaryLock, final byte[] secondaryLock, final int primaryIndex) throws IOException { return prewriteRow(tableName, row, mutations, prewriteTs, primaryLock, secondaryLock, primaryIndex, true); } protected ThemisLock prewriteRow(final byte[] tableName, final byte[] row, final List<ColumnMutation> mutations, final long prewriteTs, final byte[] primaryLock, final byte[] secondaryLock, final int primaryIndex, final boolean isSingleRow) throws IOException { CoprocessorCallable<ThemisPrewriteResult> callable = new CoprocessorCallable<ThemisPrewriteResult>(conn, tableName, row) { @Override public ThemisPrewriteResult invokeCoprocessor(Stub instance) throws Throwable { ThemisPrewriteRequest.Builder builder = ThemisPrewriteRequest.newBuilder(); ThemisPrewrite.Builder preBuilder = builder.getThemisPrewriteBuilder(); preBuilder.setRow(HBaseZeroCopyByteString.wrap(row)); for (ColumnMutation mutation : mutations) { preBuilder.addMutations(ColumnMutation.toCell(mutation)); } builder.setPrewriteTs(prewriteTs); builder.setPrimaryLock(HBaseZeroCopyByteString .wrap(primaryLock == null ? HConstants.EMPTY_BYTE_ARRAY : primaryLock)); builder.setSecondaryLock(HBaseZeroCopyByteString .wrap(secondaryLock == null ? HConstants.EMPTY_BYTE_ARRAY : secondaryLock)); builder.setPrimaryIndex(primaryIndex); ServerRpcController controller = new ServerRpcController(); BlockingRpcCallback<ThemisPrewriteResponse> rpcCallback = new BlockingRpcCallback<>(); if (isSingleRow) { instance.prewriteSingleRow(controller, builder.build(), rpcCallback); } else { instance.prewriteRow(controller, builder.build(), rpcCallback); } checkRpcException(controller); return rpcCallback.get().getThemisPrewriteResult(); } }; return judgePerwriteResultRow(tableName, row, callable.run(), prewriteTs); } protected void batchJudgePerwriteResultRow(Map<byte[], ThemisLock> lockMap, byte[] tableName, List<RowMutation> rows, List<ThemisPrewriteResult> prewriteResults, long prewriteTs) throws IOException { if (prewriteResults == null || prewriteResults.size() == 0) { return; } byte[] row = null; ThemisLock lock = null; for (ThemisPrewriteResult result : prewriteResults) { row = result.getRow().toByteArray(); lock = judgePerwriteResultRow(tableName, row, result, prewriteTs); if (lock != null) { lockMap.put(row, lock); } } } protected ThemisLock judgePerwriteResultRow(byte[] tableName, byte[] row, ThemisPrewriteResult prewriteResult, long prewriteTs) throws IOException { if (prewriteResult != null && prewriteResult.hasExistLock()) { long commitTs = prewriteResult.getNewerWriteTs(); if (commitTs != 0) { throw new WriteConflictException( "encounter write with larger timestamp than prewriteTs=" + prewriteTs + ", commitTs=" + commitTs); } else { ThemisLock lock = ThemisLock.parseFromByte(prewriteResult.getExistLock().toByteArray()); ColumnCoordinate column = new ColumnCoordinate(tableName, row, prewriteResult.getFamily().toByteArray(), prewriteResult.getQualifier().toByteArray()); lock.setColumn(column); lock.setLockExpired(prewriteResult.getLockExpired()); return lock; } } return null; } public void commitSecondaryRow(final byte[] tableName, final byte[] row, List<ColumnMutation> mutations, final long prewriteTs, final long commitTs) throws IOException { commitRow(tableName, row, mutations, prewriteTs, commitTs, -1); } public void batchCommitSecondaryRows(final byte[] tableName, final List<RowMutation> rows, final long prewriteTs, final long commitTs) throws IOException { CoprocessorCallable<List<ThemisBatchCommitSecondaryResult>> callable = new CoprocessorCallable<List<ThemisBatchCommitSecondaryResult>>( conn, tableName, rows.get(0).getRow()) { @Override public List<ThemisBatchCommitSecondaryResult> invokeCoprocessor(Stub instance) throws Throwable { ThemisBatchCommitSecondaryRequest.Builder builder = ThemisBatchCommitSecondaryRequest.newBuilder(); ThemisCommit.Builder cb; for (RowMutation rowMutation : rows) { cb = ThemisCommit.newBuilder(); cb.setRow(HBaseZeroCopyByteString.wrap(rowMutation.getRow())); for (ColumnMutation mutation : rowMutation.mutationList()) { cb.addMutations(ColumnMutation.toCell(mutation)); } cb.setPrewriteTs(prewriteTs); cb.setCommitTs(commitTs); cb.setPrimaryIndex(-1); builder.addThemisCommit(cb); } ServerRpcController controller = new ServerRpcController(); BlockingRpcCallback<ThemisBatchCommitSecondaryResponse> rpcCallback = new BlockingRpcCallback<ThemisBatchCommitSecondaryResponse>(); instance.batchCommitSecondaryRows(controller, builder.build(), rpcCallback); checkRpcException(controller); return rpcCallback.get().getBatchCommitSecondaryResultList(); } }; List<ThemisBatchCommitSecondaryResult> results = callable.run(); StringBuilder failRows = new StringBuilder(); if (results != null && results.size() > 0) { for (ThemisBatchCommitSecondaryResult r : results) { if (!r.getSuccess()) { failRows.append(Bytes.toString(r.getRow().toByteArray()) + ","); } } } if (failRows.length() > 0) { throw new IOException("secondary row commit fail, should not happend!, fail rows:" + failRows); } } public void commitRow(final byte[] tableName, final byte[] row, final List<ColumnMutation> mutations, final long prewriteTs, final long commitTs, final int primaryIndex) throws IOException { CoprocessorCallable<Boolean> callable = new CoprocessorCallable<Boolean>(conn, tableName, row) { @Override public Boolean invokeCoprocessor(Stub instance) throws Throwable { ThemisCommitRequest.Builder builder = ThemisCommitRequest.newBuilder(); ThemisCommit.Builder cb = ThemisCommit.newBuilder(); cb.setRow(HBaseZeroCopyByteString.wrap(row)); for (ColumnMutation mutation : mutations) { cb.addMutations(ColumnMutation.toCell(mutation)); } cb.setPrewriteTs(prewriteTs); cb.setCommitTs(commitTs); cb.setPrimaryIndex(primaryIndex); builder.setThemisCommit(cb); ServerRpcController controller = new ServerRpcController(); BlockingRpcCallback<ThemisCommitResponse> rpcCallback = new BlockingRpcCallback<ThemisCommitResponse>(); instance.commitRow(controller, builder.build(), rpcCallback); checkRpcException(controller); return rpcCallback.get().getResult(); } }; if (!callable.run()) { if (primaryIndex < 0) { throw new IOException("secondary row commit fail, should not happend!"); } else { ColumnMutation primaryMutation = mutations.get(primaryIndex); throw new LockCleanedException("lock has been cleaned, column=" + new ColumnCoordinate(tableName, row, primaryMutation.getFamily(), primaryMutation.getQualifier()) + ", prewriteTs=" + prewriteTs); } } } public void commitSingleRow(final byte[] tableName, final byte[] row, final List<ColumnMutation> mutations, final long prewriteTs, final long commitTs, final int primaryIndex) throws IOException { CoprocessorCallable<Boolean> callable = new CoprocessorCallable<Boolean>(conn, tableName, row) { @Override public Boolean invokeCoprocessor(Stub instance) throws Throwable { ThemisCommitRequest.Builder builder = ThemisCommitRequest.newBuilder(); ThemisCommit.Builder cb = ThemisCommit.newBuilder(); cb.setRow(HBaseZeroCopyByteString.wrap(row)); for (ColumnMutation mutation : mutations) { cb.addMutations(ColumnMutation.toCell(mutation)); } cb.setPrewriteTs(prewriteTs); cb.setCommitTs(commitTs); cb.setPrimaryIndex(primaryIndex); builder.setThemisCommit(cb); ServerRpcController controller = new ServerRpcController(); BlockingRpcCallback<ThemisCommitResponse> rpcCallback = new BlockingRpcCallback<ThemisCommitResponse>(); instance.commitSingleRow(controller, builder.build(), rpcCallback); checkRpcException(controller); return rpcCallback.get().getResult(); } }; if (!callable.run()) { if (primaryIndex < 0) { throw new IOException("secondary row commit fail, should not happend!"); } else { ColumnMutation primaryMutation = mutations.get(primaryIndex); throw new LockCleanedException("lock has been cleaned, column=" + new ColumnCoordinate(tableName, row, primaryMutation.getFamily(), primaryMutation.getQualifier()) + ", prewriteTs=" + prewriteTs); } } } public ThemisLock getLockAndErase(final ColumnCoordinate columnCoordinate, final long prewriteTs) throws IOException { CoprocessorCallable<byte[]> callable = new CoprocessorCallable<byte[]>(conn, columnCoordinate.getTableName(), columnCoordinate.getRow()) { @Override public byte[] invokeCoprocessor(Stub instance) throws Throwable { EraseLockRequest.Builder builder = EraseLockRequest.newBuilder(); builder.setRow(HBaseZeroCopyByteString.wrap(columnCoordinate.getRow())); builder.setFamily(HBaseZeroCopyByteString.wrap(columnCoordinate.getFamily())); builder.setQualifier(HBaseZeroCopyByteString.wrap(columnCoordinate.getQualifier())); builder.setPrewriteTs(prewriteTs); ServerRpcController controller = new ServerRpcController(); BlockingRpcCallback<EraseLockResponse> rpcCallback = new BlockingRpcCallback<EraseLockResponse>(); instance.getLockAndErase(controller, builder.build(), rpcCallback); checkRpcException(controller); return rpcCallback.get().hasLock() ? rpcCallback.get().getLock().toByteArray() : null; } }; byte[] result = callable.run(); return result == null ? null : ThemisLock.parseFromByte(result); } public boolean isLockExpired(final byte[] tableName, final byte[] row, final long timestamp) throws IOException { return new CoprocessorCallable<Boolean>(conn, tableName, row) { @Override public Boolean invokeCoprocessor(Stub instance) throws Throwable { LockExpiredRequest.Builder builder = LockExpiredRequest.newBuilder(); builder.setTimestamp(timestamp); ServerRpcController controller = new ServerRpcController(); BlockingRpcCallback<LockExpiredResponse> rpcCallback = new BlockingRpcCallback<LockExpiredResponse>(); instance.isLockExpired(controller, builder.build(), rpcCallback); checkRpcException(controller); return rpcCallback.get().getExpired(); } }.run(); } }
true
c106ef16c387394d05f1fdf800b8579c5e2701ba
Java
grouzen/quoridor
/quoridor-base/src/com/grouzen/quoridor/scene/node/SceneNode.java
UTF-8
208
2.15625
2
[]
no_license
package com.grouzen.quoridor.scene.node; public abstract class SceneNode { private SceneNode parent; public SceneNode(SceneNode parent) { this.parent = parent; } public abstract void render(); }
true
76fa62f87472bf1f3b894827e27a5066c13d21d7
Java
flywind2/joeis
/src/irvine/oeis/a221/A221051.java
UTF-8
534
2.125
2
[]
no_license
package irvine.oeis.a221; // Generated by gen_pattern.pl - DO NOT EDIT here! import irvine.oeis.GeneratingFunctionSequence; /** * A221051 The hyper-Wiener index of the nanostar dendrimer <code>D_1[n]</code>, defined pictorially in the Eslahchi et al. reference. * @author Georg Fischer */ public class A221051 extends GeneratingFunctionSequence { /** Construct the sequence. */ public A221051() { super(0, new long[] {71, 2347, 4376, -17716, -17696, 2752}, new long[] {1, -19, 150, -636, 1560, -2208, 1664, -512}); } }
true
122c3080c1f967e5e76a0eebd1a8a0a4a6967060
Java
spectra-cluster/clustering-file-reader
/src/main/java/uk/ac/ebi/pride/spectracluster/clusteringfilereader/objects/PeakMzComparator.java
UTF-8
413
2.328125
2
[ "Apache-2.0" ]
permissive
package uk.ac.ebi.pride.spectracluster.clusteringfilereader.objects; import java.util.Comparator; /** * Created by jg on 05.01.15. */ public class PeakMzComparator implements Comparator<ClusteringFileSpectrumReference.Peak> { @Override public int compare(ClusteringFileSpectrumReference.Peak o1, ClusteringFileSpectrumReference.Peak o2) { return Float.compare(o1.getMz(), o2.getMz()); } }
true
339f58f83d02e170caeecefff379abb12d6be906
Java
antonsemanyk/hecate
/hecate-cql3/src/main/java/com/savoirtech/hecate/cql3/persistence/def/DefaultPojoDelete.java
UTF-8
3,063
1.796875
2
[ "Apache-2.0" ]
permissive
/* * Copyright (c) 2012-2015 Savoir Technologies, Inc. * * 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.savoirtech.hecate.cql3.persistence.def; import com.datastax.driver.core.ResultSetFuture; import com.datastax.driver.core.querybuilder.Delete; import com.google.common.util.concurrent.Futures; import com.google.common.util.concurrent.ListenableFuture; import com.savoirtech.hecate.cql3.mapping.PojoMapping; import com.savoirtech.hecate.cql3.persistence.Evaporator; import com.savoirtech.hecate.cql3.persistence.PojoDelete; import static com.datastax.driver.core.querybuilder.QueryBuilder.*; public class DefaultPojoDelete extends DefaultPersistenceStatement implements PojoDelete { //---------------------------------------------------------------------------------------------------------------------- // Constructors //---------------------------------------------------------------------------------------------------------------------- public DefaultPojoDelete(DefaultPersistenceContext persistenceContext, PojoMapping mapping) { super(persistenceContext, createDelete(mapping), mapping, mapping.getIdentifierMapping()); } private static Delete.Where createDelete(PojoMapping mapping) { return delete().from(mapping.getTableName()).where(in(mapping.getIdentifierMapping().getFacetMetadata().getColumnName(), bindMarker())); } //---------------------------------------------------------------------------------------------------------------------- // PojoDelete Implementation //---------------------------------------------------------------------------------------------------------------------- public void execute(Iterable<Object> keys) { execute(getPersistenceContext().newEvaporator(), keys).getUninterruptibly(); } @Override public ListenableFuture<Void> executeAsync(Iterable<Object> keys) { return Futures.transform(execute(getPersistenceContext().newEvaporator(), keys), toVoid()); } //---------------------------------------------------------------------------------------------------------------------- // Other Methods //---------------------------------------------------------------------------------------------------------------------- public ResultSetFuture execute(Evaporator evaporator, Iterable<Object> keys) { getPersistenceContext().findForDelete(getPojoMapping().getPojoMetadata().getPojoType(), getPojoMapping().getTableName()).execute(keys, evaporator); return executeStatementArgs(toList(keys)); } }
true
c97f69729dbe89d59c8ec2ef12b8f2a02232abdc
Java
Serm97/AbstractFactory
/AbstractFactoryPattern/src/connection/DAOFactory.java
UTF-8
1,196
2.84375
3
[]
no_license
/* * 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 connection; /** * * @author Sergio Ramirez */ // Abstract class DAO Factory public abstract class DAOFactory { // List of DAO types supported by the factory public static final int CLOUDSCAPE = 1; public static final int ORACLE = 2; public static final int SYBASE = 3; // There will be a method for each DAO that can be // created. The concrete factories will have to // implement these methods. public abstract CustomerDAO getCustomerDAO(); //public abstract AccountDAO getAccountDAO(); //public abstract OrderDAO getOrderDAO(); public static DAOFactory getDAOFactory(int whichFactory) { switch (whichFactory) { case CLOUDSCAPE: return new CloudscapeDAOFactory(); case ORACLE: return new OracleDAOFactory(); case SYBASE: return new SybaseDAOFactory(); default: return null; } } }
true
41dbf927a9c54daae32b6d466fac0f61b5ee6dee
Java
tenos200/codeforces
/brainsphotots.java
UTF-8
416
3.03125
3
[]
no_license
import java.util.Scanner; public class brainsphotos{ public static void main(String[] args) { Scanner in = new Scanner(System.in); String ans = "#Black&White"; int n = in.nextInt(); int n2 = in.nextInt(); for (int i = 0; i < n*n2; i++) { String s = in.next(); if (s.equals("C") || s.equals("M") || s.equals("Y")) { ans = "#Color"; } } System.out.println(ans); } }
true
735d5686b0fb2d4396282a09bfa5db5ebd6a48e8
Java
empresasoftware/tiendaonline
/src/main/java/empresa/software/tiendaonline/repository/RatingTiendaRepository.java
UTF-8
546
1.609375
2
[]
no_license
/* * 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 empresa.software.tiendaonline.repository; import empresa.software.tiendaonline.model.TiendaRatingKey; import empresa.software.tiendaonline.model.RatingTienda; import org.springframework.data.jpa.repository.JpaRepository; /** * * @author pedro */ public interface RatingTiendaRepository extends JpaRepository<RatingTienda, TiendaRatingKey> { }
true
8ec7200240f3b1f03f8b68b3a1dd1af3ee1182dd
Java
tectronics/librapro
/libra/src/main/java/com/zhy/libra/controller/InformationController.java
UTF-8
970
2.09375
2
[]
no_license
package com.zhy.libra.controller; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.web.servlet.ModelAndView; import org.springframework.web.servlet.mvc.multiaction.MultiActionController; import com.zhy.libra.bean.User; import com.zhy.libra.spider.InformationSpider; /** * 外网搜索控制器 * * @author zhy19890221@gmail.com * */ public class InformationController extends MultiActionController { @Autowired private InformationSpider informationSpider; /** * 进入投票 * * @param request * @param response * @return */ public ModelAndView searchInformation(HttpServletRequest request, HttpServletResponse response) { informationSpider.getInfoByKeyWord("刘翔", ((User) request.getAttribute("user")).getId()); return null; } }
true
012bf0961d284da47492c7cf198fec54b9cb0a61
Java
gabor7d2/PCBuilder
/src/net/gabor6505/java/pcbuilder/PCBuilder.java
UTF-8
195
1.703125
2
[]
no_license
package net.gabor6505.java.pcbuilder; import net.gabor6505.java.pcbuilder.gui.MainFrame; public class PCBuilder { public static void main(String[] args) { new MainFrame(); } }
true
11eca4e6ff3c13506f9b999736fcab9bb5a346f6
Java
atopion/sokoban
/sokoban-java/src/distanceboard/Board.java
UTF-8
8,356
2.890625
3
[]
no_license
package distanceboard; import distanceboard.grid.GridCell; import distanceboard.grid.GridPane; import javax.swing.*; import java.awt.*; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import java.util.LinkedList; public class Board extends JFrame implements ActionListener, GridCell.CellClickedListener { private GridPane gridPane; private JPanel panel; private JRadioButton modeWall; private JRadioButton modeExec; private JRadioButton alg1; private JRadioButton alg2; private JCheckBox boxTargetMode; private JRadioButton placeBox; private JRadioButton placeWall; private JRadioButton placeTarget; private JButton execute; private JButton resetButton; private int mode = 0; // 0 - calculate for every cell, 1 - calculate paths private int selectMode = 0; // 0 - execute, 1 - place wall, 2 - place target, 3 - place box private int alg = 1; private int cols = 11; private int rows = 11; private GridCell boxCell = null; public Board() { super(); this.setTitle("Algorithm Preview Board"); this.setVisible(true); this.setLayout(new BorderLayout(10, 0)); this.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE); this.setBackground(Color.gray); this.setPreferredSize(new Dimension(1200, 1000)); gridPane = new GridPane(this, cols, rows); gridPane.setLocation(0, 0); this.add(gridPane, BorderLayout.CENTER); panel = new JPanel(); panel.setLayout(new BoxLayout(panel, BoxLayout.Y_AXIS)); panel.add(Box.createRigidArea(new Dimension(0, 20))); modeWall = new JRadioButton("Place Walls"); modeWall.setFont(modeWall.getFont().deriveFont(25f)); modeWall.addActionListener(this); panel.add(modeWall); modeExec = new JRadioButton("Execute"); modeExec.setFont(modeExec.getFont().deriveFont(25f)); modeExec.addActionListener(this); panel.add(modeExec); panel.add(Box.createRigidArea(new Dimension(0, 50))); alg1 = new JRadioButton("Algorithm 1"); alg1.setFont(alg1.getFont().deriveFont(25f)); alg1.setSelected(this.alg == 1); alg1.addActionListener(this); panel.add(alg1); alg2 = new JRadioButton("Algorithm 2"); alg2.setFont(alg2.getFont().deriveFont(25f)); alg2.setSelected(this.alg == 2); alg2.addActionListener(this); panel.add(alg2); panel.add(Box.createRigidArea(new Dimension(0, 50))); boxTargetMode = new JCheckBox("Box and Target mode"); boxTargetMode.setFont(boxTargetMode.getFont().deriveFont(25f)); boxTargetMode.setSelected(false); boxTargetMode.addActionListener(this); panel.add(boxTargetMode); placeBox = new JRadioButton("Place Box"); placeBox.setFont(placeBox.getFont().deriveFont(25f)); placeBox.addActionListener(this); placeBox.setEnabled(false); placeBox.setSelected(true); panel.add(placeBox); placeTarget = new JRadioButton("Place Targets"); placeTarget.setFont(placeTarget.getFont().deriveFont(25f)); placeTarget.addActionListener(this); placeTarget.setEnabled(false); placeTarget.setSelected(false); panel.add(placeTarget); placeWall = new JRadioButton("Place Walls"); placeWall.setFont(placeWall.getFont().deriveFont(25f)); placeWall.addActionListener(this); placeWall.setEnabled(false); placeWall.setSelected(false); panel.add(placeWall); execute = new JButton("Execute"); execute.setFont(execute.getFont().deriveFont(25f)); execute.addActionListener(this); execute.setEnabled(false); panel.add(execute); panel.add(Box.createVerticalGlue()); resetButton = new JButton("Reset"); resetButton.setFont(resetButton.getFont().deriveFont(25f)); resetButton.addActionListener(this); panel.add(resetButton); panel.add(Box.createRigidArea(new Dimension(0, 30))); this.add(panel, BorderLayout.LINE_END); this.pack(); } @Override public void actionPerformed(ActionEvent e) { if(e.getSource().equals(modeWall)) { selectMode = 1; modeExec.setSelected(false); } else if(e.getSource().equals(modeExec)) { selectMode = 0; modeWall.setSelected(false); } else if(e.getSource().equals(alg1)) { alg = 1; alg2.setSelected(false); } else if(e.getSource().equals(alg2)) { alg = 2; alg1.setSelected(false); } else if(e.getSource().equals(resetButton)) { gridPane.resetAll(); } else if(e.getSource().equals(boxTargetMode)) { if(boxTargetMode.isSelected()) { mode = 1; selectMode = 3; modeWall.setEnabled(false); modeExec.setEnabled(false); alg1.setEnabled(false); alg2.setEnabled(false); placeBox.setEnabled(true); placeBox.setSelected(true); placeWall.setEnabled(true); placeWall.setSelected(false); placeTarget.setEnabled(true); placeTarget.setSelected(false); if(boxCell != null) execute.setEnabled(true); else execute.setEnabled(false); } else { mode = 0; selectMode = 1; modeWall.setEnabled(true); modeWall.setSelected(true); modeExec.setEnabled(true); modeExec.setSelected(false); alg1.setEnabled(true); alg2.setEnabled(true); placeBox.setEnabled(false); placeWall.setEnabled(false); placeTarget.setEnabled(false); execute.setEnabled(false); } } else if(e.getSource().equals(placeWall)) { selectMode = 1; placeWall.setSelected(true); placeTarget.setSelected(false); placeBox.setSelected(false); } else if(e.getSource().equals(placeTarget)) { selectMode = 2; placeTarget.setSelected(true); placeWall.setSelected(false); placeBox.setSelected(false); } else if(e.getSource().equals(placeBox)) { selectMode = 3; placeBox.setSelected(true); placeTarget.setSelected(false); placeWall.setSelected(false); } else if(e.getSource().equals(execute)) { LinkedList<GridCell> targets = new LinkedList<>(); for(int i = 0; i < cols; i++) for(int j = 0; j < rows; j++) if(gridPane.get(i, j).isTarget()) targets.addLast(gridPane.get(i, j)); if(boxCell != null) Algorithm.calculatePath2(gridPane, cols, rows, boxCell, targets.toArray(new GridCell[targets.size()])); } } @Override public void clicked(GridCell cell) { if(selectMode == 0) { if(alg == 1) Algorithm.calculatePath1(gridPane, cols, rows, cell); else if(alg == 2) Algorithm.calculatePath2(gridPane, cols, rows, cell, null); } else if(selectMode == 1) { if(!cell.isWall()) cell.setWall(); else cell.reset(); } else if(selectMode == 2) { if(!cell.isTarget()) cell.setTarget(); else cell.reset(); } else if(selectMode == 3) { if(!cell.isBox()) { gridPane.moveBox(cell); boxCell = cell; execute.setEnabled(true); } else { cell.reset(); boxCell = null; execute.setEnabled(false); } } } public static void main(String[] args) { Board board = new Board(); } }
true
bb63e7f80828c395727748c51a8c9118ad5dcdca
Java
Group-10-Studios/Mission-Control
/src/main/java/nz/ac/vuw/engr300/gui/controllers/GraphController.java
UTF-8
24,224
2.03125
2
[ "MIT" ]
permissive
package nz.ac.vuw.engr300.gui.controllers; import javafx.scene.Scene; import javafx.scene.control.Alert; import javafx.scene.layout.Border; import javafx.scene.layout.BorderStroke; import javafx.scene.layout.BorderStrokeStyle; import javafx.scene.layout.BorderWidths; import javafx.scene.layout.CornerRadii; import javafx.scene.layout.Region; import javafx.scene.paint.Color; import javafx.stage.FileChooser; import javafx.stage.Modality; import javafx.stage.Stage; import javafx.stage.StageStyle; import nz.ac.vuw.engr300.communications.importers.CsvConfiguration; import nz.ac.vuw.engr300.communications.importers.OpenRocketImporter; import nz.ac.vuw.engr300.communications.importers.PastFlightImporter; import nz.ac.vuw.engr300.communications.importers.SerialCommunications; import nz.ac.vuw.engr300.communications.model.CsvTableDefinition; import nz.ac.vuw.engr300.communications.model.RocketData; import nz.ac.vuw.engr300.communications.model.RocketStatus; import nz.ac.vuw.engr300.gui.components.RocketDataAngle; import nz.ac.vuw.engr300.gui.components.RocketDataAngleLineChart; import nz.ac.vuw.engr300.gui.components.RocketDataLineChart; import nz.ac.vuw.engr300.gui.components.RocketDataLocation; import nz.ac.vuw.engr300.gui.components.RocketGraph; import nz.ac.vuw.engr300.gui.model.BatteryMasterList; import nz.ac.vuw.engr300.gui.model.GraphMasterList; import nz.ac.vuw.engr300.gui.model.GraphType; import nz.ac.vuw.engr300.gui.views.GraphView; import nz.ac.vuw.engr300.gui.views.View; import nz.ac.vuw.engr300.model.LaunchParameters; import org.apache.log4j.Logger; import java.io.File; import java.lang.reflect.InvocationTargetException; import java.lang.reflect.Method; import java.util.ArrayList; import java.util.List; /** * Represents the GraphController for interacting with the graph components for their required actions. * All functionality the user can have will be created in here to distinguish from the view code. * * @author Nathan Duckett */ public class GraphController { /** * Define the SubscriptionType this GraphController will listen to. */ public enum SubscriptionType { SERIAL, SIMULATION, PAST_FLIGHT } private static final Logger LOGGER = Logger.getLogger(GraphController.class); private final OpenRocketImporter simulationImporter = new OpenRocketImporter(); private final PastFlightImporter pastFlightImporter = new PastFlightImporter(); private final SerialCommunications serialCommunications = new SerialCommunications(); private static final GraphController instance = new GraphController(); private final List<Stage> extractedGraphs = new ArrayList<>(); private List<RocketGraph> graphs; private List<RocketGraph> allGraphs; private View view; private String highlightedGraphLabel; private SubscriptionType simulationMode = SubscriptionType.SERIAL; /** * Private constructor to prevent Graph controller being created outside of in here. */ private GraphController() { this.allGraphs = new ArrayList<>(); } /** * Get the GraphController instance. * * @return GraphController instance for the app. */ public static GraphController getInstance() { return instance; } /** * Set the graph list stored within this controller which corresponds to the list in the view. * * @param graphs List of RocketGraphs to be displayed to the user. */ public void setGraphs(List<RocketGraph> graphs) { this.graphs = graphs; // Makes assumption that view is type GraphView. This can be fixed later but for now keeping generic // for expandability if required later. GraphView gv = (GraphView) view; gv.updateGraphs(graphs); // Must first alias the unregisteredGraphs before clearing all graphs. List<RocketGraph> unregisteredGraphs = getGraphsBasedOnMasterList(GraphMasterList.getInstance() .getUnregisteredGraphs()); // Clear the current all graphs and add the graphs back in their correct order. allGraphs.clear(); allGraphs.addAll(graphs); allGraphs.addAll(unregisteredGraphs); } /** * Makes sure the graphs in GraphMasterList syncs its changes with graph list in the view. */ public void syncGraphOrder() { setGraphs(getGraphsBasedOnMasterList(GraphMasterList.getInstance().getGraphs())); } /** * Get the graphs from the instance (RocketGraph contents) based on a list of GraphTypes from the master list. * This will create a list of references to these graphs, in the order matching the GraphType retrieved from * the masterListCopy. This can be used to reorder the graphs, or alias their copies to keep within allGraphs. * * @param masterListCopy An extracted list of GraphTypes from the Master list. This contains an ordered list to * retrieve the specific GraphType's corresponding graph. * @return List of RocketGraph objects in the order of the provided GraphType's. */ private List<RocketGraph> getGraphsBasedOnMasterList(List<GraphType> masterListCopy) { List<RocketGraph> listOfGraphs = new ArrayList<>(); for (GraphType g : masterListCopy) { listOfGraphs.add(getGraphByGraphType(g.getLabel())); } return listOfGraphs; } /** * Attach a view to this controller specifically for calling update view when a change has been made. * * @param view View to be attached to this controller. */ public void attachView(View view) { this.view = view; } /** * Hide or show a specific graph based on its' label. * * @param label The label of the graph to be updated to be either visible or hidden. */ public void hideGraph(String label) { RocketGraph graph = getGraphByGraphType(label); if (graph == null) { throw new RuntimeException("An invalid graph was selected with the label <" + label + "> which doesn't exist."); } graph.toggleVisibility(); // Makes assumption that view is type GraphView. This can be fixed later but for now keeping generic // for expandability if required later. GraphView gv = (GraphView) view; gv.updateGraphs(graphs); } /** * Subscribe all of the graphs to their appropriate data sources from the Simulation Listener. * * @param tableName String definition name from the communications.json file to match against incoming data. * @param type The SubscriptionType to be used for this graph structure. */ public void subscribeGraphs(String tableName, SubscriptionType type) { this.simulationMode = type; // Must reset extracted graphs before subscribing new graphs. resetExtractedGraphs(); CsvTableDefinition table = CsvConfiguration.getInstance().getTable(tableName); if (type == SubscriptionType.SIMULATION) { simulationImporter.subscribeObserver(this::graphSimulationSubscription); } else if (type == SubscriptionType.SERIAL) { // Ensure both graphs are subscribed and battery listeners. serialCommunications.subscribeObserver(data -> { graphSubscription(data, table); BatteryMasterList.getInstance().updateBatteryValue(data, table); }); } else if (type == SubscriptionType.PAST_FLIGHT) { // Ensure both graphs are subscribed and battery listeners. pastFlightImporter.subscribeObserver(data -> { graphSubscription(data, table); BatteryMasterList.getInstance().updateBatteryValue(data, table); }); } LOGGER.debug("All graphs have been subscribed for " + type); } /** * Handle translating the incoming {@code List<Object>} data which is coming in from the serial observer. * * @param data Incoming data from the serialCommunications observer to be drawn on the graphs. * @param table The CSV table definition to match the data against. */ private void graphSubscription(List<Object> data, CsvTableDefinition table) { long timestamp = table.matchValueToColumn(data.get(table.getCsvIndexOf("timestamp")), "timestamp", Long.class); for (RocketGraph rg: this.allGraphs) { if (rg instanceof RocketDataAngleLineChart) { RocketDataAngleLineChart rgC = (RocketDataAngleLineChart) rg; String dataType = rgC.getGraphType().getLabel(); int index = table.getCsvIndexOf(dataType); if (index < 0) { continue; } double value = table.matchValueToColumn(data.get(index), dataType, Double.class); rgC.addValue(timestamp, value); } else if (rg instanceof RocketDataLineChart) { RocketDataLineChart rgC = (RocketDataLineChart) rg; String dataType = rgC.getGraphType().getLabel(); int index = table.getCsvIndexOf(dataType); if (index < 0) { continue; } double value = table.matchValueToColumn(data.get(index), dataType, Double.class); rgC.addValue(timestamp, value); } else if (rg instanceof RocketDataLocation) { RocketDataLocation rgL = (RocketDataLocation) rg; // Runs under the assumption that columns are specifically named this. int indexLat = table.getCsvIndexOf("lat"); int indexLong = table.getCsvIndexOf("long"); // Skip if values don't exist on the table. if (indexLat < 0 || indexLong < 0) { continue; } double latitude = table.matchValueToColumn(data.get(indexLat), "lat", Double.class); double longitude = table.matchValueToColumn(data.get(indexLong), "long", Double.class); rgL.updateAngleDistanceInfo(latitude, longitude); } } } /** * Handle translating the incoming RocketData from the simulation listener and drawing it on the graphs. * * @param data Incoming data from the simulationListener observer to be drawn on the graphs. */ private void graphSimulationSubscription(RocketData data) { if (data instanceof RocketStatus) { double timestamp = data.getTime(); for (RocketGraph rg: this.allGraphs) { if (rg instanceof RocketDataAngleLineChart) { RocketDataAngleLineChart rgC = (RocketDataAngleLineChart) rg; String dataType = rgC.getGraphType().getLabel(); double value = getDataFromRocketData((RocketStatus) data, dataType); rgC.addValue(timestamp, value); } else if (rg instanceof RocketDataLineChart) { RocketDataLineChart rgC = (RocketDataLineChart) rg; String dataType = rgC.getGraphType().getLabel(); double value = getDataFromRocketData((RocketStatus) data, dataType); rgC.addValue(timestamp, value); } } } } /** * Helper function to retrieve the values from the RocketStatus based on the name of the graph. * This is performed through reflection to ensure that each graph can access its' data correctly * while being dynamically loaded into the application. * * @param data Incoming RocketStatus data object which contains the values we want to retrieve from. * @param dataType The String name of the graph we need the data type from which will be converted. * @return Double value stored within the RocketStatus for the dataType. */ private double getDataFromRocketData(RocketStatus data, String dataType) { try { String functionLabel = "get" + dataType.replace(" ", ""); Method getMethod = RocketStatus.class.getDeclaredMethod(functionLabel); return (double) getMethod.invoke(data); } catch (NoSuchMethodException | IllegalAccessException | InvocationTargetException e) { e.printStackTrace(); } return 0; } /** * Start listening to the serial device. */ public void startListeningOnSerial() { serialCommunications.startListening(); } /** * Set the wind angle graph to the specified wind angle. * * @param currentWindAngle Double value of the Wind Angle to be set on the RocketGraph. */ public void setWindAngle(double currentWindAngle) { // getAngleByGraphType(GraphType.WINDDIRECTION).setAngle(currentWindAngle); LOGGER.debug("The wind angle has been updated to: " + currentWindAngle); } /** * Highlight the specified graphType provided. If this graph type is already highlighted it will unhighlight it. * This also assumes only one graph can be highlighted at a time. * * @param graphTypeLabel The specific label for the GraphType which we want highlighted. */ public void highlight(String graphTypeLabel) { for (RocketGraph graph : this.graphs) { Region chart = (Region) graph; if (graph.getGraphType().getLabel().equals(graphTypeLabel)) { if (graphTypeLabel.equals(this.highlightedGraphLabel)) { chart.setBorder(null); this.highlightedGraphLabel = null; } else { chart.setBorder(new Border(new BorderStroke(Color.PURPLE, BorderStrokeStyle.SOLID, new CornerRadii(5.0), new BorderWidths(2.0)))); this.highlightedGraphLabel = graphTypeLabel; } } else { chart.setBorder(null); } } } /** * Find a graph by its' graph type. This will O(n) search through the graphs list to find a graph which matches * the type provided. If this is not found it will return null. * * @param label GraphType to match against inside RocketGraphs. * @return A RocketGraph which matches the expected type. */ public RocketGraph getGraphByGraphType(String label) { for (RocketGraph g : allGraphs) { if (g.getGraphType().getLabel().equals(label)) { return g; } } return null; } /** * Function interface to getGraphByGraphType which returns an UNCHECKED conversion to a RocketDataLineChart. * This is not checked and therefore could result in exceptions if used on a RocketGraph which doesn't match * the expected type. * * @param label GraphType to match against inside RocketGraphs. * @return A RocketDataLineChart which matches the expected type. */ private RocketDataLineChart getLineChartByGraphType(String label) { return (RocketDataLineChart) getGraphByGraphType(label); } /** * Function interface to getGraphByGraphType which returns an UNCHECKED conversion to a RocketDataAngle. * This is not checked and therefore could result in exceptions if used on a RocketGraph which doesn't match * the expected type. * * @param label GraphType to match against inside RocketGraphs. * @return A RocketDataAngle which matches the expected type. */ private RocketDataAngle getAngleByGraphType(String label) { return (RocketDataAngle) getGraphByGraphType(label); } /** * Function interface to getGraphByGraphType which returns an UNCHECKED conversion to a RocketDataAngleLineChart. * This is not checked and therefore could result in exceptions if used on a RocketGraph which doesn't match * the expected type. * * @param label GraphType to match against inside RocketGraphs. * @return A RocketDataAngleLineChart which matches the expected type. */ private RocketDataAngleLineChart getAngleLineChartByGraphType(String label) { return (RocketDataAngleLineChart) getGraphByGraphType(label); } /** * Callback function for run simulation in main view, this function will open a * file dialog to select a simulation data file. It will then load it into the * data importer and run the simulation as if it was live. */ public void runSim() { simulationImporter.stop(); pastFlightImporter.stop(); FileChooser fileChooser = new FileChooser(); fileChooser.setTitle("Select a simulation to run."); fileChooser.setInitialDirectory(new File("src/main/resources/")); File selectedFile = fileChooser.showOpenDialog(null); if (selectedFile != null) { try { simulationImporter.importData(selectedFile.getAbsolutePath()); } catch (Exception e) { Alert alert = new Alert(Alert.AlertType.WARNING); alert.initStyle(StageStyle.DECORATED); alert.setTitle("Warning"); alert.setHeaderText("Failed to import simulation data!"); alert.setContentText(e.getMessage()); alert.showAndWait(); return; } // Reconstruct graphs if they are not already in simulation mode if (this.simulationMode != SubscriptionType.SIMULATION) { String tableName = "previousSimulation"; ((GraphView) view).updateGraphStructureDefinition(tableName, SubscriptionType.SIMULATION); } allGraphs.forEach(RocketGraph::clear); simulationImporter.start(); } LOGGER.debug("Simulation started"); } /** * Callback function for past flights in main view, this function will open a * file dialog to select a past flight log file. It will then load it into the * data importer and run the simulation as if it was live. */ public void runPastFlights() { simulationImporter.stop(); pastFlightImporter.stop(); FileChooser fileChooser = new FileChooser(); fileChooser.setTitle("Select a simulation to run."); fileChooser.setInitialDirectory(new File("src/main/resources/")); File selectedFile = fileChooser.showOpenDialog(null); if (selectedFile != null) { try { pastFlightImporter.importData(selectedFile.getAbsolutePath()); } catch (Exception e) { Alert alert = new Alert(Alert.AlertType.WARNING); alert.initStyle(StageStyle.DECORATED); alert.setTitle("Warning"); alert.setHeaderText("Failed to import PastFlight log data!"); alert.setContentText(e.getMessage()); alert.showAndWait(); return; } allGraphs.forEach(RocketGraph::clear); ((GraphView) view).updateGraphStructureDefinition(pastFlightImporter.getTableName(), SubscriptionType.PAST_FLIGHT); pastFlightImporter.start(); } LOGGER.debug("Past flight started"); } /** * Update the map location to the new value within the LaunchParameters. Deletes the old * map from the graphs to update. */ public void updateMapLocation() { GraphType gt = new GraphType("Location", "map"); // Must unregister first in case location is popped out GraphMasterList.getInstance().unRegisterGraph(gt); GraphMasterList.getInstance().registerGraph(gt); // Create a new RocketDataLocation graph - Uses the current lat/long from LaunchParameters // Defaulting to image width/height of 400 as we don't specify this elsewhere and is default. RocketDataLocation newGraph = new RocketDataLocation( LaunchParameters.getInstance().getLatitude().getValue(), LaunchParameters.getInstance().getLongitude().getValue(), 400, 400, gt ); int oldPos = 0; // Remove the old graph for (int i = 0; i < this.graphs.size(); i++) { if (this.graphs.get(i).getGraphType().getLabel().equals("Location")) { this.graphs.remove(i); oldPos = i; break; } } this.graphs.add(oldPos, newGraph); setGraphs(this.graphs); } /** * Callback for when the cross at top right gets pressed, this function should * be used to cleanup any resources and close any ongoing threads. */ public void shutdown() { simulationImporter.stop(); pastFlightImporter.stop(); LOGGER.debug("GraphController shutdown called"); simulationImporter.unsubscribeAllObservers(); serialCommunications.stopListening(); serialCommunications.unsubscribeAllObservers(); // Close all extra windows to finish the application. resetExtractedGraphs(); } /** * Get the Simulation Importer for this application. * * @return OpenRocketImporter which runs the simulation for the application. */ public OpenRocketImporter getSimulationImporter() { return this.simulationImporter; } /** * Get the serial communications listener for this application. * * @return SerialCommunications instance which is listening for this application. */ public SerialCommunications getSerialCommunications() { return this.serialCommunications; } /** * Reset the observers on the incoming data streams to be reset/loaded on new definition. */ public void resetObservers() { this.serialCommunications.unsubscribeAllObservers(); //TODO: Check if we need to unsubscribe simulation listeners here. } /** * Create a pop out graph view with the provided graph. * * @param graph Graph to display in a pop out view. */ public void popOutGraph(RocketGraph graph) { Stage popupWindow = new Stage(); popupWindow.initModality(Modality.NONE); popupWindow.setTitle(graph.getGraphType().getLabel()); GraphMasterList.getInstance().unRegisterGraph(graph.getGraphType()); syncGraphsPopUp(); // Ensure the graph position is reset to zero for the pop up window to prevent down shifting // If this is not done it will match the y position from the dynamic grid pane when clicked. Region graphRegion = (Region) graph; graphRegion.setLayoutX(0); graphRegion.setLayoutY(0); Scene scene = new Scene(graphRegion, 300, 300); popupWindow.setScene(scene); extractedGraphs.add(popupWindow); LOGGER.info("Extracting pop out window for <" + graph.getGraphType().getLabel() + ">"); LOGGER.info("Total pop out windows is now <" + extractedGraphs.size() + ">"); // Ensure on pop up close that the graph is added back into the main application. popupWindow.setOnCloseRequest((event) -> { GraphMasterList.getInstance().registerGraph(graph.getGraphType()); this.graphs.add(graph); syncGraphsPopUp(); }); // Must be show not showAndWait to keep the application running popupWindow.show(); } /** * Sync the graphs for a pop up. Based on the function popOutGraph with specification to sync the master list * with a new value within the graphs. */ private void syncGraphsPopUp() { this.syncGraphOrder(); this.setGraphs(graphs); ButtonController.getInstance().updateButtons(); } /** * Reset the extracted graphs, clearing the list and closing all opened windows. */ private void resetExtractedGraphs() { LOGGER.info("Closing extracted graphs - Unregistering external graphs"); this.extractedGraphs.forEach(Stage::close); this.extractedGraphs.clear(); } }
true
d3e3ea87e1deb484a0bf1ed1dcde9197096b449b
Java
jorgetown/foundation-logparser
/src/main/java/org/logparser/time/InfiniteTimeInterval.java
UTF-8
354
2.296875
2
[]
no_license
package org.logparser.time; import java.util.Date; import net.jcip.annotations.Immutable; /** * Represents a time window of infinite length. * * @author jorge.decastro * */ @Immutable public final class InfiniteTimeInterval implements ITimeInterval { public boolean isBetweenInstants(final Date date) { return true; } }
true
0b11d8654871c15226ffb6e8a44e09099cc31e0a
Java
ayufan/hackwaw
/hackwaw-java-example/src/main/java/pl/hackwaw/disrupt/context/domain/health/State.java
UTF-8
121
1.75
2
[]
no_license
package pl.hackwaw.disrupt.context.domain.health; public enum State { OPERATIONAL, DOWN, SLOW, ERROR, UNNECESSARY }
true
cfce8a0bb1777ef3a69dd71ae2028835cd251cb2
Java
MahmoudBashir97/Chat_Ho
/app/src/main/java/com/chatho/chatho/Adapter/Owen_adpt.java
UTF-8
2,159
2.296875
2
[]
no_license
package com.chatho.chatho.Adapter; import android.content.Context; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.ImageView; import androidx.annotation.NonNull; import androidx.recyclerview.widget.RecyclerView; import com.chatho.chatho.R; import com.chatho.chatho.pojo.Stories; import com.google.firebase.database.DatabaseReference; import com.google.firebase.database.FirebaseDatabase; import com.squareup.picasso.Picasso; import java.util.List; import de.hdodenhof.circleimageview.CircleImageView; public class Owen_adpt extends RecyclerView.Adapter<Owen_adpt.ViewHolder> { private Context context; private List<Stories> list; private String CurrentUID; public Owen_adpt(Context context, List<Stories> list,String CurrentUID) { this.context = context; this.list = list; CurrentUID=CurrentUID; } @NonNull @Override public ViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) { View v= LayoutInflater.from(parent.getContext()).inflate(R.layout.owen_single_item,parent,false); return new ViewHolder(v); } @Override public void onBindViewHolder(@NonNull ViewHolder holder, int position) { Stories st=list.get(position); Picasso.get().load(st.getImageURI()).resize(90,90).centerInside().into(holder.img_st); holder.deleteimg.setOnClickListener(view -> { deleting(position); }); } @Override public int getItemCount() { return list.size(); } public class ViewHolder extends RecyclerView.ViewHolder { CircleImageView img_st; ImageView deleteimg; public ViewHolder(@NonNull View itemView) { super(itemView); img_st=itemView.findViewById(R.id.img_st); deleteimg=itemView.findViewById(R.id.deleteimg); } } public void deleting(int i){ DatabaseReference stories_ref; stories_ref= FirebaseDatabase.getInstance().getReference().child("Stories"); stories_ref.child(CurrentUID).child("U"+i).removeValue(); } }
true
1459926e1cee546da1c4dde1f6818b9829355343
Java
huandc/leetcode
/src/_14最长公共前缀longestCommonPrefix/Solution.java
UTF-8
998
3.234375
3
[]
no_license
package _14最长公共前缀longestCommonPrefix; import java.util.Arrays; public class Solution { public static void main(String[] args) { System.out.println(longestCommonPrefix(new String[]{"flower", "flow", "flight"})); System.out.println(longestCommonPrefix(new String[]{"dog", "racecar", "car"})); System.out.println(longestCommonPrefix(new String[]{"bdddd", "bddddccccc", "bd"})); System.out.println(longestCommonPrefix(new String[]{})); } public static String longestCommonPrefix(String[] strs) { if(strs.length == 0) return ""; if(strs.length == 1) return strs[0]; Arrays.sort(strs); strs = new String[]{strs[0],strs[strs.length-1]}; String res=""; for (int i = 0; i < strs[0].length(); i++) { if (strs[0].charAt(i) == strs[1].charAt(i)){ res += strs[0].charAt(i); }else { break; } } return res; } }
true
9d266d1c72d105c24bf791853d1844e2702747c0
Java
tonycheng93/YunShuWeather
/ChanWeather/app/src/main/java/com/chan/chanweather/bus/InitErrorEvent.java
UTF-8
445
2.359375
2
[ "Apache-2.0" ]
permissive
package com.chan.chanweather.bus; /** * Created by chan on 16/3/27. */ public class InitErrorEvent { private String m_message; private Throwable m_throwable; public InitErrorEvent(String message, Throwable throwable) { m_message = message; m_throwable = throwable; } public String getMessage() { return m_message; } public Throwable getThrowable() { return m_throwable; } }
true
4f48867786cdf4d20dd9ffd6966ea2bb89762972
Java
zhangweicheng555/lte
/src/main/java/com/boot/kaizen/util/CacheUtil.java
UTF-8
748
2.234375
2
[]
no_license
package com.boot.kaizen.util; import org.springframework.cache.ehcache.EhCacheCacheManager; import net.sf.ehcache.Cache; import net.sf.ehcache.CacheManager; /** * * @author weichengz * @date 2019年5月31日 上午11:37:09 */ public class CacheUtil { public static Cache getCacheManager(String cacheKey) { //获取EhCacheCacheManager类 EhCacheCacheManager cacheCacheManager=SpringUtil.getApplicationContext().getBean(EhCacheCacheManager.class); //获取CacheManager类 CacheManager cacheManager = cacheCacheManager.getCacheManager(); //获取Cache Cache cache = cacheManager.getCache(cacheKey); // cache.put(new Element("Hello", "123")); //System.out.println(cache.get("Hello").getObjectValue()); return cache; } }
true
98cef5a027103e9a039addb9f910d009c7ed46d0
Java
leoclog/Spring5recipe
/src/test/java/com/zelidre/spring5recipeapp/services/ImageServiceImplTest.java
UTF-8
1,810
2.375
2
[]
no_license
package com.zelidre.spring5recipeapp.services; import static org.junit.Assert.assertEquals; import static org.mockito.Mockito.times; import static org.mockito.Mockito.verify; import static org.mockito.Mockito.when; import static org.mockito.Mockito.anyLong; import java.util.Optional; import org.junit.Before; import org.junit.Test; import org.mockito.ArgumentCaptor; import org.mockito.Mock; import org.mockito.MockitoAnnotations; import org.springframework.mock.web.MockMultipartFile; import org.springframework.web.multipart.MultipartFile; import com.zelidre.spring5recipeapp.domain.Recipe; import com.zelidre.spring5recipeapp.repositories.RecipeRepository; public class ImageServiceImplTest { ImageService imageService; @Mock RecipeRepository recipeRepository; @Before public void setUp() throws Exception{ MockitoAnnotations.initMocks(this); imageService = new ImageServiceImpl(recipeRepository); } @Test public void saveImageFile() throws Exception{ //given MultipartFile multiPartFile = new MockMultipartFile("imagefile", "testing.txt", "plain/txt", "com Zelidre".getBytes()); Recipe recipe = new Recipe(); recipe.setId(1L); Optional<Recipe> recipeOptional = Optional.of(recipe); when(recipeRepository.findById(anyLong())).thenReturn(recipeOptional); ArgumentCaptor<Recipe> argumentCaptor = ArgumentCaptor.forClass(Recipe.class); //when imageService.saveImageFile(1L, multiPartFile); //then verify(recipeRepository, times(1)).save(argumentCaptor.capture()); Recipe saveRecipe = argumentCaptor.getValue(); assertEquals(multiPartFile.getBytes().length, saveRecipe.getImage().length); } }
true