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
cc9af80a14522c5bcd95a1e74fffaa285b66d293
Java
matzefit/MasterThesisCodes
/ChangeBuildingYears/src/BuildingYearsClass.java
UTF-8
2,619
3
3
[]
no_license
import java.io.BufferedReader; import java.io.File; import java.io.FileReader; import java.io.FileWriter; import java.io.IOException; public class BuildingYearsClass { public static void main(String[] args) { modifyFile("C:\\Users\\Matthias\\Desktop\\MasterThesis\\Data\\whole LOD1 Model\\MergedAllYishun - Copy.gml", "creationDate", "bldg:yearOfConstruction"); System.out.println("done"); } static void modifyFile(String filePath, String oldString, String newString) { File fileToBeModified = new File(filePath); String oldContent = ""; BufferedReader reader = null; FileWriter writer = null; try { reader = new BufferedReader(new FileReader(fileToBeModified)); //Reading all the lines of input text file into oldContent String line = reader.readLine(); while (line != null) { oldContent = oldContent + line + System.lineSeparator(); line = reader.readLine(); } //Replacing oldString with newString in the oldContent String newContent = oldContent.replaceAll(oldString, newString); //Rewriting the input text file with newContent writer = new FileWriter(fileToBeModified); writer.write(newContent); } catch (IOException e) { e.printStackTrace(); } finally { try { //Closing the resources reader.close(); writer.close(); } catch (IOException e) { e.printStackTrace(); } } } } //public static void main(String[] args) throws IOException //{ // //PrintWriter printOutput = new PrintWriter("C:\\Users\\Matthias\\Desktop\\MasterThesis\\Data\\whole LOD1 Model\\Merged_ModBY_AllYishun.gml"); // BufferedReader br3=new BufferedReader(new FileReader("C:\\Users\\Matthias\\Desktop\\MasterThesis\\Data\\whole LOD1 Model\\MergedAllYishun.gml")); //String line=br3.readLine(); //StringBuffer inputBuffer = new StringBuffer(); //while (line != null) { // inputBuffer.append(line); // inputBuffer.append('\n'); //} //String inputStr=inputBuffer.toString(); //br3.close(); // //System.out.println(inputStr); ////printOutput.flush(); ////printOutput.close(); //System.out.println("end"); //}
true
09d3d4fc1448801781bbc508d3926588cd5aeddc
Java
new-javacc/new-javacc.github.io
/AddToHead.java
UTF-8
1,605
3.40625
3
[]
no_license
import java.util.Scanner; import java.io.File; import java.io.FileNotFoundException; import java.io.PrintWriter; import java.util.ArrayList; public class AddToHead { public static void main(String[] args) { Scanner kb = new Scanner(System.in); System.out.println("Enter what you would like to add to the head:"); String addition = kb.nextLine(); update(getAllHtmlFiles(), addition); } public static ArrayList<File> getAllHtmlFiles() { ArrayList<File> allFiles = new ArrayList<File>(); File folder = new File("."); File[] files1 = folder.listFiles(); for (int i = 0; i < files1.length; i++) { if (files1[i].getName().endsWith(".html")) allFiles.add(files1[i]); } return allFiles; } public static void update(ArrayList<File> files, String addition) { for (int i = 0; i < files.size(); i++) { File htmlFile = files.get(i); System.out.println("Updating file: " + htmlFile.getName()); Scanner input = null; try { input = new Scanner(htmlFile); } catch (FileNotFoundException e) { System.err.println("Failure"); continue; } String currentLine = ""; String wholeText = ""; while (input.hasNext()) { currentLine = input.nextLine(); wholeText += currentLine + "\n"; if (currentLine.indexOf("<head>") != -1) wholeText += "\t\t" + addition + "\n"; } PrintWriter output = null; try { output = new PrintWriter(htmlFile); } catch (FileNotFoundException e) { System.err.println("Failure"); continue; } output.print(wholeText); output.close(); input.close(); System.out.println("Success"); } } }
true
428a5d2f1904cc78327cf432858c2d013e215b32
Java
baba-beda/Java-Advanced
/src/ru/ifmo/ctddev/zenkova/concurrent/Any.java
UTF-8
813
2.875
3
[]
no_license
package ru.ifmo.ctddev.zenkova.concurrent; import java.util.List; import java.util.function.Predicate; /** * Worker that checks that there exists list element satisfying some predicate. * * @param <T> type parameter. * @see ru.ifmo.ctddev.zenkova.concurrent.Worker * @see ru.ifmo.ctddev.zenkova.concurrent.All */ public class Any<T> extends LazyWorker<Boolean> { private All<T> allWorker; public Any(List<? extends T> list, Predicate<? super T> predicate) { super(); allWorker = new All<>(list, predicate.negate()); } @Override public Boolean calcResult() { return !allWorker.getResult(); } @Override public Boolean mergeResults(List<Boolean> results) { return results.stream() .reduce(false, Boolean::logicalOr); } }
true
11d94b8a10f18cc4e2245e6371d8757cc9c3ab6f
Java
h579690/Dat108-Oblig4-Webapplikasjoner
/Oblig4/src/no/hvl/dat108/servlets/PaameldingsServlet.java
UTF-8
3,679
2.28125
2
[]
no_license
package no.hvl.dat108.servlets; import java.io.IOException; import javax.ejb.EJB; import javax.servlet.ServletException; import javax.servlet.annotation.WebServlet; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import no.hvl.dat108.hjelpeklasser.*; import no.hvl.dat108.model.Deltager; import no.hvl.dat108.model.DeltagerEAO; @WebServlet(name = "PaameldingsServlet", urlPatterns = { "/paamelding" }) public class PaameldingsServlet extends HttpServlet { private static final long serialVersionUID = 1L; private Validation val = new Validation(); private DeltagerForm deltagerForm = new DeltagerForm(); private PassordUtil passordUtil = new PassordUtil(); @EJB private DeltagerEAO deltagerEAO = new DeltagerEAO(); private CharForKjonn charForKjonn = new CharForKjonn(); protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { request.getRequestDispatcher("WEB-INF/jsp/paameldingsskjema.jsp").forward(request, response); } protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { String fornavn = val.escapeHtml(request.getParameter("fornavn")); String etternavn = val.escapeHtml(request.getParameter("etternavn")); String mobil = val.escapeHtml(request.getParameter("mobil")); String passord = val.escapeHtml(request.getParameter("passord")); String passordRepetert = val.escapeHtml(request.getParameter("passordRepetert")); String kjonn = request.getParameter("kjonn"); boolean paameldt = deltagerEAO.finnEnDeltager(mobil) != null; boolean gFnavn = false; boolean gEnavn = false; boolean gMobil = false; boolean gPass = true; boolean gPassRep = true; boolean gKjonn = false; if (!val.erGyldigNavn(fornavn)) { deltagerForm.setFornavnMelding("Ugyldig fornavn"); } else { deltagerForm.setFornavn(fornavn); gFnavn = true; } if (!val.erGyldigNavn(etternavn)) { deltagerForm.setEtternavnMelding("Ugyldig etternavn"); } else { deltagerForm.setEtternavn(etternavn); gEnavn = true; } if (!val.erGyldigMobil(mobil)) { deltagerForm.setMobilMelding("Ugyldig Mobil"); } else { deltagerForm.setMobil(mobil); gMobil = true; } if (!val.erGyldigPassord(passord)) { deltagerForm.setPassordMelding("Ugyldig Passord"); } else { gPass = true; } if (!val.erGyldigPassordRepetert(passord, passordRepetert)) { deltagerForm.setPassordRepetertMelding("Ikke like passord"); } else { gPassRep = true; } if (!val.erGyldigKjonn(kjonn)) { deltagerForm.setKjonn("ugyldig kjonn"); } else { deltagerForm.setKjonn(kjonn); gKjonn = true; } if ((gFnavn && gEnavn && gMobil && gPass && gPassRep && gKjonn && !paameldt)) { // bruke passordhash greiene String hashetPassord = passordUtil.krypterPassord(passord); // opprette Deltager element Deltager deltager = new Deltager(mobil, fornavn, etternavn, hashetPassord, charForKjonn.kjonn(kjonn)); // legge deltager inn i databasen deltagerEAO.leggTilDeltager2(deltager); request.getSession().setAttribute("fornavn", fornavn); request.getSession().setAttribute("etternavn", etternavn); request.getSession().setAttribute("mobil", mobil); request.getSession().setAttribute("kjonn", kjonn); request.getSession().setAttribute("innlogget", deltager); //Redirect til /bekreftelse response.sendRedirect("bekreftelse"); } else { request.getSession().setAttribute("deltagerForm", deltagerForm); response.sendRedirect("paamelding"); } } }
true
89ca88d518e99fb5567507442038c537c8f65390
Java
octanty/apriorimethod
/src/projectdatmin/ProjectDatminView.java
UTF-8
47,322
2.03125
2
[]
no_license
/* * ProjectDatminView.java */ package projectdatmin; import org.jdesktop.application.Action; import org.jdesktop.application.ResourceMap; import org.jdesktop.application.SingleFrameApplication; import org.jdesktop.application.FrameView; import org.jdesktop.application.TaskMonitor; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import javax.swing.Timer; import javax.swing.Icon; import javax.swing.JDialog; import javax.swing.JFrame; import javax.swing.JOptionPane; /** * The application's main frame. */ public class ProjectDatminView extends FrameView { static String transaksi1; static String transaksi2; static String transaksi3; static String transaksi4; static String transaksi5; static double minsuport; public ProjectDatminView(SingleFrameApplication app) { super(app); initComponents(); // status bar initialization - message timeout, idle icon and busy animation, etc ResourceMap resourceMap = getResourceMap(); int messageTimeout = resourceMap.getInteger("StatusBar.messageTimeout"); messageTimer = new Timer(messageTimeout, new ActionListener() { public void actionPerformed(ActionEvent e) { statusMessageLabel.setText(""); } }); messageTimer.setRepeats(false); int busyAnimationRate = resourceMap.getInteger("StatusBar.busyAnimationRate"); for (int i = 0; i < busyIcons.length; i++) { busyIcons[i] = resourceMap.getIcon("StatusBar.busyIcons[" + i + "]"); } busyIconTimer = new Timer(busyAnimationRate, new ActionListener() { public void actionPerformed(ActionEvent e) { busyIconIndex = (busyIconIndex + 1) % busyIcons.length; statusAnimationLabel.setIcon(busyIcons[busyIconIndex]); } }); idleIcon = resourceMap.getIcon("StatusBar.idleIcon"); statusAnimationLabel.setIcon(idleIcon); progressBar.setVisible(false); // connecting action tasks to status bar via TaskMonitor TaskMonitor taskMonitor = new TaskMonitor(getApplication().getContext()); taskMonitor.addPropertyChangeListener(new java.beans.PropertyChangeListener() { public void propertyChange(java.beans.PropertyChangeEvent evt) { String propertyName = evt.getPropertyName(); if ("started".equals(propertyName)) { if (!busyIconTimer.isRunning()) { statusAnimationLabel.setIcon(busyIcons[0]); busyIconIndex = 0; busyIconTimer.start(); } progressBar.setVisible(true); progressBar.setIndeterminate(true); } else if ("done".equals(propertyName)) { busyIconTimer.stop(); statusAnimationLabel.setIcon(idleIcon); progressBar.setVisible(false); progressBar.setValue(0); } else if ("message".equals(propertyName)) { String text = (String) (evt.getNewValue()); statusMessageLabel.setText((text == null) ? "" : text); messageTimer.restart(); } else if ("progress".equals(propertyName)) { int value = (Integer) (evt.getNewValue()); progressBar.setVisible(true); progressBar.setIndeterminate(false); progressBar.setValue(value); } } }); } @Action public void showAboutBox() { if (aboutBox == null) { JFrame mainFrame = ProjectDatminApp.getApplication().getMainFrame(); aboutBox = new Dataset(mainFrame); aboutBox.setLocationRelativeTo(mainFrame); } ProjectDatminApp.getApplication().show(aboutBox); } /** 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() { mainPanel = new javax.swing.JPanel(); menuBar = new javax.swing.JMenuBar(); javax.swing.JMenu fileMenu = new javax.swing.JMenu(); jMenuItem2 = new javax.swing.JMenuItem(); jMenuItem1 = new javax.swing.JMenuItem(); javax.swing.JMenu helpMenu = new javax.swing.JMenu(); javax.swing.JMenuItem aboutMenuItem = new javax.swing.JMenuItem(); statusPanel = new javax.swing.JPanel(); javax.swing.JSeparator statusPanelSeparator = new javax.swing.JSeparator(); statusMessageLabel = new javax.swing.JLabel(); statusAnimationLabel = new javax.swing.JLabel(); jPanel4 = new javax.swing.JPanel(); jPanel3 = new javax.swing.JPanel(); jButton3 = new javax.swing.JButton(); jLabel5 = new javax.swing.JLabel(); jScrollPane3 = new javax.swing.JScrollPane(); cetak3 = new javax.swing.JTextArea(); jPanel1 = new javax.swing.JPanel(); jLabel3 = new javax.swing.JLabel(); jButton1 = new javax.swing.JButton(); jScrollPane1 = new javax.swing.JScrollPane(); cetak = new javax.swing.JTextArea(); jLabel2 = new javax.swing.JLabel(); minsup = new javax.swing.JTextField(); jPanel2 = new javax.swing.JPanel(); jButton2 = new javax.swing.JButton(); jLabel4 = new javax.swing.JLabel(); jScrollPane2 = new javax.swing.JScrollPane(); cetak2 = new javax.swing.JTextArea(); jLabel1 = new javax.swing.JLabel(); trans5 = new javax.swing.JTextField(); trans2 = new javax.swing.JTextField(); trans1 = new javax.swing.JTextField(); trans4 = new javax.swing.JTextField(); trans3 = new javax.swing.JTextField(); progressBar = new javax.swing.JProgressBar(); jLabel6 = new javax.swing.JLabel(); jLabel7 = new javax.swing.JLabel(); jScrollPane4 = new javax.swing.JScrollPane(); akhir = new javax.swing.JTextArea(); mainPanel.setName("mainPanel"); // NOI18N javax.swing.GroupLayout mainPanelLayout = new javax.swing.GroupLayout(mainPanel); mainPanel.setLayout(mainPanelLayout); mainPanelLayout.setHorizontalGroup( mainPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGap(0, 1358, Short.MAX_VALUE) ); mainPanelLayout.setVerticalGroup( mainPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGap(0, 0, Short.MAX_VALUE) ); menuBar.setName("menuBar"); // NOI18N org.jdesktop.application.ResourceMap resourceMap = org.jdesktop.application.Application.getInstance(projectdatmin.ProjectDatminApp.class).getContext().getResourceMap(ProjectDatminView.class); fileMenu.setText(resourceMap.getString("fileMenu.text")); // NOI18N fileMenu.setName("fileMenu"); // NOI18N fileMenu.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { fileMenuActionPerformed(evt); } }); jMenuItem2.setIcon(resourceMap.getIcon("jMenuItem2.icon")); // NOI18N jMenuItem2.setText(resourceMap.getString("jMenuItem2.text")); // NOI18N jMenuItem2.setName("jMenuItem2"); // NOI18N jMenuItem2.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { jMenuItem2ActionPerformed(evt); } }); fileMenu.add(jMenuItem2); jMenuItem1.setIcon(resourceMap.getIcon("jMenuItem1.icon")); // NOI18N jMenuItem1.setText(resourceMap.getString("jMenuItem1.text")); // NOI18N jMenuItem1.setName("jMenuItem1"); // NOI18N jMenuItem1.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { jMenuItem1ActionPerformed(evt); } }); fileMenu.add(jMenuItem1); menuBar.add(fileMenu); helpMenu.setText(resourceMap.getString("helpMenu.text")); // NOI18N helpMenu.setName("helpMenu"); // NOI18N javax.swing.ActionMap actionMap = org.jdesktop.application.Application.getInstance(projectdatmin.ProjectDatminApp.class).getContext().getActionMap(ProjectDatminView.class, this); aboutMenuItem.setAction(actionMap.get("showAboutBox")); // NOI18N aboutMenuItem.setIcon(resourceMap.getIcon("aboutMenuItem.icon")); // NOI18N aboutMenuItem.setText(resourceMap.getString("aboutMenuItem.text")); // NOI18N aboutMenuItem.setName("aboutMenuItem"); // NOI18N helpMenu.add(aboutMenuItem); menuBar.add(helpMenu); statusPanel.setName("statusPanel"); // NOI18N statusPanelSeparator.setName("statusPanelSeparator"); // NOI18N statusMessageLabel.setName("statusMessageLabel"); // NOI18N statusAnimationLabel.setHorizontalAlignment(javax.swing.SwingConstants.LEFT); statusAnimationLabel.setName("statusAnimationLabel"); // NOI18N jPanel4.setName("jPanel4"); // NOI18N jPanel3.setBorder(javax.swing.BorderFactory.createLineBorder(new java.awt.Color(-16777216,true))); jPanel3.setName("jPanel3"); // NOI18N jButton3.setText(resourceMap.getString("jButton3.text")); // NOI18N jButton3.setName("jButton3"); // NOI18N jButton3.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { jButton3ActionPerformed(evt); } }); jLabel5.setText(resourceMap.getString("jLabel5.text")); // NOI18N jLabel5.setName("jLabel5"); // NOI18N jScrollPane3.setName("jScrollPane3"); // NOI18N cetak3.setColumns(20); cetak3.setRows(5); cetak3.setName("cetak3"); // NOI18N jScrollPane3.setViewportView(cetak3); 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.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(jPanel3Layout.createSequentialGroup() .addComponent(jScrollPane3, javax.swing.GroupLayout.DEFAULT_SIZE, 334, Short.MAX_VALUE) .addContainerGap()) .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, jPanel3Layout.createSequentialGroup() .addComponent(jLabel5) .addGap(165, 165, 165))) .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, jPanel3Layout.createSequentialGroup() .addComponent(jButton3) .addGap(144, 144, 144)))) ); jPanel3Layout.setVerticalGroup( jPanel3Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, jPanel3Layout.createSequentialGroup() .addComponent(jLabel5) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addComponent(jScrollPane3, javax.swing.GroupLayout.DEFAULT_SIZE, 309, Short.MAX_VALUE) .addGap(7, 7, 7) .addComponent(jButton3) .addContainerGap()) ); jPanel1.setBorder(javax.swing.BorderFactory.createLineBorder(new java.awt.Color(-16777216,true))); jPanel1.setName("jPanel1"); // NOI18N jLabel3.setText(resourceMap.getString("jLabel3.text")); // NOI18N jLabel3.setName("jLabel3"); // NOI18N jButton1.setText(resourceMap.getString("jButton1.text")); // NOI18N jButton1.setName("jButton1"); // NOI18N jButton1.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { jButton1ActionPerformed(evt); } }); jScrollPane1.setName("jScrollPane1"); // NOI18N cetak.setColumns(20); cetak.setRows(5); cetak.setName("cetak"); // NOI18N jScrollPane1.setViewportView(cetak); javax.swing.GroupLayout jPanel1Layout = new javax.swing.GroupLayout(jPanel1); jPanel1.setLayout(jPanel1Layout); jPanel1Layout.setHorizontalGroup( jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(jPanel1Layout.createSequentialGroup() .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(jPanel1Layout.createSequentialGroup() .addGap(98, 98, 98) .addComponent(jLabel3)) .addGroup(jPanel1Layout.createSequentialGroup() .addGap(80, 80, 80) .addComponent(jButton1)) .addGroup(jPanel1Layout.createSequentialGroup() .addContainerGap() .addComponent(jScrollPane1, javax.swing.GroupLayout.DEFAULT_SIZE, 337, Short.MAX_VALUE))) .addContainerGap()) ); jPanel1Layout.setVerticalGroup( jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(jPanel1Layout.createSequentialGroup() .addComponent(jLabel3) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addComponent(jScrollPane1, javax.swing.GroupLayout.DEFAULT_SIZE, 309, Short.MAX_VALUE) .addGap(18, 18, 18) .addComponent(jButton1)) ); jLabel2.setText(resourceMap.getString("jLabel2.text")); // NOI18N jLabel2.setName("jLabel2"); // NOI18N minsup.setText(resourceMap.getString("minsup.text")); // NOI18N minsup.setToolTipText(resourceMap.getString("minsup.toolTipText")); // NOI18N minsup.setName("minsup"); // NOI18N jPanel2.setBorder(javax.swing.BorderFactory.createLineBorder(new java.awt.Color(-16777216,true))); jPanel2.setName("jPanel2"); // NOI18N jButton2.setText(resourceMap.getString("jButton2.text")); // NOI18N jButton2.setName("jButton2"); // NOI18N jButton2.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { jButton2ActionPerformed(evt); } }); jLabel4.setText(resourceMap.getString("jLabel4.text")); // NOI18N jLabel4.setName("jLabel4"); // NOI18N jScrollPane2.setName("jScrollPane2"); // NOI18N cetak2.setColumns(20); cetak2.setRows(5); cetak2.setName("cetak2"); // NOI18N jScrollPane2.setViewportView(cetak2); javax.swing.GroupLayout jPanel2Layout = new javax.swing.GroupLayout(jPanel2); jPanel2.setLayout(jPanel2Layout); jPanel2Layout.setHorizontalGroup( jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(jPanel2Layout.createSequentialGroup() .addGroup(jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(jPanel2Layout.createSequentialGroup() .addGap(92, 92, 92) .addComponent(jButton2)) .addGroup(jPanel2Layout.createSequentialGroup() .addContainerGap() .addComponent(jScrollPane2, javax.swing.GroupLayout.DEFAULT_SIZE, 337, Short.MAX_VALUE)) .addGroup(jPanel2Layout.createSequentialGroup() .addGap(158, 158, 158) .addComponent(jLabel4))) .addContainerGap()) ); jPanel2Layout.setVerticalGroup( jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, jPanel2Layout.createSequentialGroup() .addComponent(jLabel4) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addComponent(jScrollPane2, javax.swing.GroupLayout.DEFAULT_SIZE, 309, Short.MAX_VALUE) .addGap(18, 18, 18) .addComponent(jButton2)) ); jLabel1.setText(resourceMap.getString("jLabel1.text")); // NOI18N jLabel1.setName("jLabel1"); // NOI18N trans5.setText(resourceMap.getString("trans5.text")); // NOI18N trans5.setToolTipText(resourceMap.getString("trans5.toolTipText")); // NOI18N trans5.setName("trans5"); // NOI18N trans2.setText(resourceMap.getString("trans5.text")); // NOI18N trans2.setName("trans2"); // NOI18N trans1.setText(resourceMap.getString("trans5.text")); // NOI18N trans1.setToolTipText(resourceMap.getString("trans1.toolTipText")); // NOI18N trans1.setName("trans1"); // NOI18N trans4.setText(resourceMap.getString("trans5.text")); // NOI18N trans4.setToolTipText(resourceMap.getString("trans4.toolTipText")); // NOI18N trans4.setName("trans4"); // NOI18N trans3.setText(resourceMap.getString("trans5.text")); // NOI18N trans3.setToolTipText(resourceMap.getString("trans3.toolTipText")); // NOI18N trans3.setName("trans3"); // NOI18N progressBar.setName("progressBar"); // NOI18N jLabel6.setText(resourceMap.getString("jLabel6.text")); // NOI18N jLabel6.setName("jLabel6"); // NOI18N jLabel7.setText(resourceMap.getString("jLabel7.text")); // NOI18N jLabel7.setName("jLabel7"); // NOI18N jScrollPane4.setName("jScrollPane4"); // NOI18N akhir.setColumns(20); akhir.setRows(5); akhir.setName("akhir"); // NOI18N jScrollPane4.setViewportView(akhir); javax.swing.GroupLayout jPanel4Layout = new javax.swing.GroupLayout(jPanel4); jPanel4.setLayout(jPanel4Layout); jPanel4Layout.setHorizontalGroup( jPanel4Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, jPanel4Layout.createSequentialGroup() .addContainerGap() .addComponent(progressBar, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)) .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, jPanel4Layout.createSequentialGroup() .addContainerGap(355, Short.MAX_VALUE) .addComponent(jLabel6) .addGap(211, 211, 211)) .addGroup(jPanel4Layout.createSequentialGroup() .addGap(16, 16, 16) .addGroup(jPanel4Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(jPanel4Layout.createSequentialGroup() .addGap(9, 9, 9) .addComponent(jLabel1) .addGap(18, 18, 18) .addComponent(trans1, javax.swing.GroupLayout.PREFERRED_SIZE, 75, javax.swing.GroupLayout.PREFERRED_SIZE) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED) .addComponent(trans2, javax.swing.GroupLayout.PREFERRED_SIZE, 75, javax.swing.GroupLayout.PREFERRED_SIZE) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED) .addComponent(trans3, javax.swing.GroupLayout.PREFERRED_SIZE, 75, javax.swing.GroupLayout.PREFERRED_SIZE) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addComponent(trans4, javax.swing.GroupLayout.PREFERRED_SIZE, 75, javax.swing.GroupLayout.PREFERRED_SIZE) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addComponent(trans5, javax.swing.GroupLayout.PREFERRED_SIZE, 75, javax.swing.GroupLayout.PREFERRED_SIZE) .addGap(538, 538, 538)) .addGroup(jPanel4Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, jPanel4Layout.createSequentialGroup() .addGap(6, 6, 6) .addComponent(jLabel2) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addComponent(minsup, javax.swing.GroupLayout.PREFERRED_SIZE, 74, javax.swing.GroupLayout.PREFERRED_SIZE) .addContainerGap(971, Short.MAX_VALUE)) .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, jPanel4Layout.createSequentialGroup() .addComponent(jPanel1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, 33, Short.MAX_VALUE) .addComponent(jPanel2, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE) .addGap(29, 29, 29) .addComponent(jPanel3, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)) .addGroup(jPanel4Layout.createSequentialGroup() .addComponent(jLabel7) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED) .addComponent(jScrollPane4, javax.swing.GroupLayout.DEFAULT_SIZE, 1048, Short.MAX_VALUE))))) ); jPanel4Layout.setVerticalGroup( jPanel4Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(jPanel4Layout.createSequentialGroup() .addContainerGap() .addComponent(jLabel6) .addGap(32, 32, 32) .addGroup(jPanel4Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE) .addComponent(trans1, javax.swing.GroupLayout.PREFERRED_SIZE, 20, javax.swing.GroupLayout.PREFERRED_SIZE) .addComponent(trans2, javax.swing.GroupLayout.PREFERRED_SIZE, 20, javax.swing.GroupLayout.PREFERRED_SIZE) .addComponent(trans3, javax.swing.GroupLayout.PREFERRED_SIZE, 20, javax.swing.GroupLayout.PREFERRED_SIZE) .addComponent(trans4, javax.swing.GroupLayout.PREFERRED_SIZE, 20, javax.swing.GroupLayout.PREFERRED_SIZE) .addComponent(trans5, javax.swing.GroupLayout.PREFERRED_SIZE, 20, javax.swing.GroupLayout.PREFERRED_SIZE) .addComponent(jLabel1)) .addGap(16, 16, 16) .addGroup(jPanel4Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE) .addComponent(minsup, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE) .addComponent(jLabel2)) .addGap(18, 18, 18) .addGroup(jPanel4Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addComponent(jPanel3, 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) .addComponent(jPanel2, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)) .addGroup(jPanel4Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(jPanel4Layout.createSequentialGroup() .addGap(28, 28, 28) .addComponent(jLabel7) .addGap(18, 18, 18) .addComponent(progressBar, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE) .addContainerGap()) .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, jPanel4Layout.createSequentialGroup() .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, 14, Short.MAX_VALUE) .addComponent(jScrollPane4, javax.swing.GroupLayout.PREFERRED_SIZE, 173, javax.swing.GroupLayout.PREFERRED_SIZE) .addContainerGap()))) ); javax.swing.GroupLayout statusPanelLayout = new javax.swing.GroupLayout(statusPanel); statusPanel.setLayout(statusPanelLayout); statusPanelLayout.setHorizontalGroup( statusPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(statusPanelLayout.createSequentialGroup() .addContainerGap() .addGroup(statusPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(statusPanelLayout.createSequentialGroup() .addComponent(jPanel4, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE) .addGap(196, 196, 196)) .addGroup(statusPanelLayout.createSequentialGroup() .addComponent(statusMessageLabel) .addGap(1219, 1219, 1219) .addGroup(statusPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addComponent(statusPanelSeparator, javax.swing.GroupLayout.DEFAULT_SIZE, 129, Short.MAX_VALUE) .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, statusPanelLayout.createSequentialGroup() .addComponent(statusAnimationLabel) .addContainerGap()))))) ); statusPanelLayout.setVerticalGroup( statusPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, statusPanelLayout.createSequentialGroup() .addComponent(statusPanelSeparator, javax.swing.GroupLayout.PREFERRED_SIZE, 2, javax.swing.GroupLayout.PREFERRED_SIZE) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, 979, Short.MAX_VALUE) .addGroup(statusPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE) .addComponent(statusMessageLabel) .addComponent(statusAnimationLabel)) .addGap(11, 11, 11)) .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, statusPanelLayout.createSequentialGroup() .addContainerGap(280, Short.MAX_VALUE) .addComponent(jPanel4, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE) .addContainerGap()) ); setComponent(mainPanel); setMenuBar(menuBar); setStatusBar(statusPanel); }// </editor-fold>//GEN-END:initComponents private void jButton2ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton2ActionPerformed // TODO add your handling code here: minsuport = Double.parseDouble(minsup.getText()); transaksi1 = trans1.getText(); transaksi2 = trans2.getText(); transaksi3 = trans3.getText(); transaksi4 = trans4.getText(); transaksi5 = trans5.getText(); rumus rms = new rumus(); rms.datmin(); rms.proses1(); rms.datmin1(); rms.proses2(); rms.datmin2(); if (rms.jumlah1 > minsuport && rms.jumlah2 > minsuport && rms.jumlah11 >= minsuport) { cetak2.append(rms.kataygdicari1 + "," + rms.kataygdicari2 + ":" + rms.jumlah11 + "\n"); } else { cetak2.append(rms.kataygdicari1 + "," + rms.kataygdicari2 + ":" + rms.jumlah11 + " dieliminasi \n"); } if (rms.jumlah1 > minsuport && rms.jumlah3 > minsuport && rms.jumlah12 >= minsuport) { cetak2.append(rms.kataygdicari1 + "," + rms.kataygdicari3 + ":" + rms.jumlah12 + "\n"); } else { cetak2.append(rms.kataygdicari1 + "," + rms.kataygdicari3 + ":" + rms.jumlah12 + " dieliminasi \n"); } if (rms.jumlah1 > minsuport && rms.jumlah4 > minsuport && rms.jumlah13 >= minsuport) { cetak2.append(rms.kataygdicari1 + "," + rms.kataygdicari4 + ":" + rms.jumlah13 + "\n"); } else { cetak2.append(rms.kataygdicari1 + "," + rms.kataygdicari4 + ":" + rms.jumlah13 + " dieliminasi \n"); } if (rms.jumlah1 > minsuport && rms.jumlah5 > minsuport && rms.jumlah14 >= minsuport) { cetak2.append(rms.kataygdicari1 + "," + rms.kataygdicari5 + ":" + rms.jumlah14 + "\n"); } else { cetak2.append(rms.kataygdicari1 + "," + rms.kataygdicari5 + ":" + rms.jumlah14 + " dieliminasi \n"); } if (rms.jumlah2 > minsuport && rms.jumlah3 > minsuport && rms.jumlah15 >= minsuport) { cetak2.append(rms.kataygdicari2 + "," + rms.kataygdicari3 + ":" + rms.jumlah15 + "\n"); } else { cetak2.append(rms.kataygdicari2 + "," + rms.kataygdicari3 + ":" + rms.jumlah15 + " dieliminasi \n"); } if (rms.jumlah2 > minsuport && rms.jumlah4 > minsuport && rms.jumlah16 >= minsuport) { cetak2.append(rms.kataygdicari2 + "," + rms.kataygdicari4 + ":" + rms.jumlah16 + "\n"); } else { cetak2.append(rms.kataygdicari2 + "," + rms.kataygdicari4 + ":" + rms.jumlah16 + " dieliminasi \n"); } if (rms.jumlah2 > minsuport && rms.jumlah5 > minsuport && rms.jumlah17 >= minsuport) { cetak2.append(rms.kataygdicari2 + "," + rms.kataygdicari5 + ":" + rms.jumlah17 + "\n"); } else { cetak2.append(rms.kataygdicari1 + "," + rms.kataygdicari4 + ":" + rms.jumlah17 + " dieliminasi \n"); } if (rms.jumlah3 > minsuport && rms.jumlah4 > minsuport && rms.jumlah18 >= minsuport) { cetak2.append(rms.kataygdicari3 + "," + rms.kataygdicari4 + ":" + rms.jumlah18 + "\n"); } else { cetak2.append(rms.kataygdicari3 + "," + rms.kataygdicari4 + ":" + rms.jumlah18 + " dieliminasi \n"); } if (rms.jumlah3 > minsuport && rms.jumlah5 > minsuport && rms.jumlah19 >= minsuport) { cetak2.append(rms.kataygdicari3 + "," + rms.kataygdicari5 + ":" + rms.jumlah19 + "\n"); } else { cetak2.append(rms.kataygdicari3 + "," + rms.kataygdicari5 + ":" + rms.jumlah19 + " dieliminasi \n"); } if (rms.jumlah4 > minsuport && rms.jumlah5 > minsuport && rms.jumlah20 >= minsuport) { cetak2.append(rms.kataygdicari4 + "," + rms.kataygdicari5 + ":" + rms.jumlah20 + "\n"); } else { cetak2.append(rms.kataygdicari4 + "," + rms.kataygdicari5 + ":" + rms.jumlah20 + " dieliminasi \n"); } }//GEN-LAST:event_jButton2ActionPerformed private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton1ActionPerformed // TODO add your handling code here: //Proses pertama minsuport = Double.parseDouble(minsup.getText()); transaksi1 = trans1.getText(); transaksi2 = trans2.getText(); transaksi3 = trans3.getText(); transaksi4 = trans4.getText(); transaksi5 = trans5.getText(); rumus rms = new rumus(); rms.datmin(); rms.proses1(); rms.datmin1(); rms.proses2(); rms.datmin2(); cetak.append(rms.kataygdicari1 + ":" + rms.jumlah1 + "\n"); cetak.append(rms.kataygdicari2 + ":" + rms.jumlah2 + "\n"); cetak.append(rms.kataygdicari3 + ":" + rms.jumlah3 + "\n"); cetak.append(rms.kataygdicari4 + ":" + rms.jumlah4 + "\n"); cetak.append(rms.kataygdicari5 + ":" + rms.jumlah5 + "\n"); Math.max(rms.jumlah1, rms.jumlah2); }//GEN-LAST:event_jButton1ActionPerformed @SuppressWarnings("static-access") private void jButton3ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton3ActionPerformed // TODO add your handling code here: minsuport = Double.parseDouble(minsup.getText()); transaksi1 = trans1.getText(); transaksi2 = trans2.getText(); transaksi3 = trans3.getText(); transaksi4 = trans4.getText(); transaksi5 = trans5.getText(); float jumlaha = 0; float jumlahb = 0; float jumlahc = 0; float jumlahd = 0; float jumlahe = 0; float jumlahf = 0; float jumlahall; rumus rms = new rumus(); rms.datmin(); rms.proses1(); rms.datmin1(); rms.proses2(); rms.datmin2(); if (rms.jumlah1 > minsuport && rms.jumlah2 > minsuport && rms.jumlah3 > minsuport && rms.jumlah21 >= minsuport) { cetak3.append(rms.kataygdicari1 + "," + rms.kataygdicari2 + "," + rms.kataygdicari3 + ":" + rms.jumlah21 + "\n"); akhir.setText("Hasil Akhir:" + rms.kataygdicari1 + "," + rms.kataygdicari2 + "," + rms.kataygdicari3 + "\n"); jumlaha = rms.jumlah1; jumlahb = rms.jumlah2; jumlahc = rms.jumlah3; jumlahd = rms.jumlah11; jumlahe = rms.jumlah12; jumlahf = rms.jumlah15; jumlahall = rms.jumlah21; rms.fungsi3(rms.kataygdicari1, rms.kataygdicari2, rms.kataygdicari3, jumlaha, jumlahb, jumlahc, jumlahd, jumlahe, jumlahf, jumlahall); } else { cetak3.append(rms.kataygdicari1 + "," + rms.kataygdicari2 + "," + rms.kataygdicari3 + ":" + rms.jumlah21 + " dieliminasi \n"); } if (rms.jumlah1 > minsuport && rms.jumlah2 > minsuport && rms.jumlah4 > minsuport && rms.jumlah22 >= minsuport) { cetak3.append(rms.kataygdicari1 + "," + rms.kataygdicari2 + "," + rms.kataygdicari4 + ":" + rms.jumlah22 + "\n"); akhir.setText("Hasil Akhir:" + rms.kataygdicari1 + "," + rms.kataygdicari2 + "," + rms.kataygdicari4 + "\n"); jumlaha = rms.jumlah1; jumlahb = rms.jumlah2; jumlahc = rms.jumlah4; jumlahd = rms.jumlah11; jumlahe = rms.jumlah13; jumlahf = rms.jumlah16; jumlahall = rms.jumlah22; rms.fungsi3(rms.kataygdicari1, rms.kataygdicari2, rms.kataygdicari4, jumlaha, jumlahb, jumlahc, jumlahd, jumlahe, jumlahf, jumlahall); } else { cetak3.append(rms.kataygdicari1 + "," + rms.kataygdicari2 + "," + rms.kataygdicari4 + ":" + rms.jumlah22 + " dieliminasi \n"); } if (rms.jumlah1 > minsuport && rms.jumlah2 > minsuport && rms.jumlah5 > minsuport && rms.jumlah23 >= minsuport) { cetak3.append(rms.kataygdicari1 + "," + rms.kataygdicari2 + "," + rms.kataygdicari5 + ":" + rms.jumlah23 + "\n"); akhir.setText("Hasil Akhir:" + rms.kataygdicari1 + "," + rms.kataygdicari2 + "," + rms.kataygdicari5+ "\n"); jumlaha = rms.jumlah1; jumlahb = rms.jumlah2; jumlahc = rms.jumlah5; jumlahd = rms.jumlah11; jumlahe = rms.jumlah14; jumlahf = rms.jumlah17; jumlahall = rms.jumlah23; rms.fungsi3(rms.kataygdicari1, rms.kataygdicari2, rms.kataygdicari5, jumlaha, jumlahb, jumlahc, jumlahd, jumlahe, jumlahf, jumlahall); } else { cetak3.append(rms.kataygdicari1 + "," + rms.kataygdicari2 + "," + rms.kataygdicari5 + ":" + rms.jumlah23 + " dieliminasi \n"); } if (rms.jumlah1 > minsuport && rms.jumlah3 > minsuport && rms.jumlah4 > minsuport && rms.jumlah24 >= minsuport) { cetak3.append(rms.kataygdicari1 + "," + rms.kataygdicari3 + "," + rms.kataygdicari4 + ":" + rms.jumlah24 + "\n"); akhir.setText("Hasil Akhir:" + rms.kataygdicari1 + "," + rms.kataygdicari3 + "," + rms.kataygdicari4+ "\n"); jumlaha = rms.jumlah1; jumlahb = rms.jumlah3; jumlahc = rms.jumlah4; jumlahd = rms.jumlah12; jumlahe = rms.jumlah13; jumlahf = rms.jumlah18; jumlahall = rms.jumlah24; rms.fungsi3(rms.kataygdicari1, rms.kataygdicari3, rms.kataygdicari4, jumlaha, jumlahb, jumlahc, jumlahd, jumlahe, jumlahf, jumlahall); } else { cetak3.append(rms.kataygdicari1 + "," + rms.kataygdicari3 + "," + rms.kataygdicari4 + ":" + rms.jumlah24 + " dieliminasi \n"); } if (rms.jumlah1 > minsuport && rms.jumlah3 > minsuport && rms.jumlah5 > minsuport && rms.jumlah25 >= minsuport) { cetak3.append(rms.kataygdicari1 + "," + rms.kataygdicari3 + "," + rms.kataygdicari5 + ":" + rms.jumlah25 + "\n"); akhir.setText("Hasil Akhir:" + rms.kataygdicari1 + "," + rms.kataygdicari3 + "," + rms.kataygdicari5+ "\n"); jumlaha = rms.jumlah1; jumlahb = rms.jumlah2; jumlahc = rms.jumlah5; jumlahd = rms.jumlah12; jumlahe = rms.jumlah14; jumlahf = rms.jumlah19; jumlahall = rms.jumlah25; rms.fungsi3(rms.kataygdicari1, rms.kataygdicari3, rms.kataygdicari5, jumlaha, jumlahb, jumlahc, jumlahd, jumlahe, jumlahf, jumlahall); } else { cetak3.append(rms.kataygdicari1 + "," + rms.kataygdicari3 + "," + rms.kataygdicari5 + ":" + rms.jumlah25 + " dieliminasi \n"); } if (rms.jumlah2 > minsuport && rms.jumlah3 > minsuport && rms.jumlah4 > minsuport && rms.jumlah26 >= minsuport) { cetak3.append(rms.kataygdicari2 + "," + rms.kataygdicari3 + "," + rms.kataygdicari4 + ":" + rms.jumlah26 + "\n"); akhir.setText("Hasil Akhir:" + rms.kataygdicari2 + "," + rms.kataygdicari3 + "," + rms.kataygdicari4+ "\n"); jumlaha = rms.jumlah2; jumlahb = rms.jumlah3; jumlahc = rms.jumlah4; jumlahd = rms.jumlah15; jumlahe = rms.jumlah16; jumlahf = rms.jumlah18; jumlahall = rms.jumlah26; rms.fungsi3(rms.kataygdicari2, rms.kataygdicari3, rms.kataygdicari4, jumlaha, jumlahb, jumlahc, jumlahd, jumlahe, jumlahf, jumlahall); } else { cetak3.append(rms.kataygdicari2 + "," + rms.kataygdicari3 + "," + rms.kataygdicari4 + ":" + rms.jumlah26 + " dieliminasi \n"); } if (rms.jumlah2 > minsuport && rms.jumlah3 > minsuport && rms.jumlah5 > minsuport && rms.jumlah27 >= minsuport) { cetak3.append(rms.kataygdicari2 + "," + rms.kataygdicari3 + "," + rms.kataygdicari5 + ":" + rms.jumlah27 + "\n"); akhir.setText("Hasil Akhir:" + rms.kataygdicari2 + "," + rms.kataygdicari3 + "," + rms.kataygdicari5+ "\n"); jumlaha = rms.jumlah2; jumlahb = rms.jumlah3; jumlahc = rms.jumlah5; jumlahd = rms.jumlah15; jumlahe = rms.jumlah17; jumlahf = rms.jumlah19; jumlahall = rms.jumlah27; rms.fungsi3(rms.kataygdicari2, rms.kataygdicari3, rms.kataygdicari5, jumlaha, jumlahb, jumlahc, jumlahd, jumlahe, jumlahf, jumlahall); } else { cetak3.append(rms.kataygdicari2 + "," + rms.kataygdicari3 + "," + rms.kataygdicari5 + ":" + rms.jumlah27 + " dieliminasi \n"); } if (rms.jumlah2 > minsuport && rms.jumlah4 > minsuport && rms.jumlah5 > minsuport && rms.jumlah28 >= minsuport) { cetak3.append(rms.kataygdicari2 + "," + rms.kataygdicari4 + "," + rms.kataygdicari5 + ":" + rms.jumlah28 + "\n"); akhir.setText("Hasil Akhir:" + rms.kataygdicari2 + "," + rms.kataygdicari4 + "," + rms.kataygdicari5+ "\n"); jumlaha = rms.jumlah2; jumlahb = rms.jumlah4; jumlahc = rms.jumlah5; jumlahd = rms.jumlah16; jumlahe = rms.jumlah17; jumlahf = rms.jumlah20; jumlahall = rms.jumlah28; rms.fungsi3(rms.kataygdicari2, rms.kataygdicari4, rms.kataygdicari5, jumlaha, jumlahb, jumlahc, jumlahd, jumlahe, jumlahf, jumlahall); } else { cetak3.append(rms.kataygdicari2 + "," + rms.kataygdicari4 + "," + rms.kataygdicari5 + ":" + rms.jumlah28 + " dieliminasi \n"); } if (rms.jumlah1 > minsuport && rms.jumlah4 > minsuport && rms.jumlah5 > minsuport && rms.jumlah30 >= minsuport) { cetak3.append(rms.kataygdicari1 + "," + rms.kataygdicari4 + "," + rms.kataygdicari5 + ":" + rms.jumlah30 + "\n"); akhir.setText("Hasil Akhir:" + rms.kataygdicari1 + "," + rms.kataygdicari4 + "," + rms.kataygdicari5+ "\n"); jumlaha = rms.jumlah1; jumlahb = rms.jumlah4; jumlahc = rms.jumlah5; jumlahd = rms.jumlah13; jumlahe = rms.jumlah14; jumlahf = rms.jumlah20; jumlahall = rms.jumlah30; rms.fungsi3(rms.kataygdicari1, rms.kataygdicari4, rms.kataygdicari5, jumlaha, jumlahb, jumlahc, jumlahd, jumlahe, jumlahf, jumlahall); } else { cetak3.append(rms.kataygdicari1 + "," + rms.kataygdicari4 + "," + rms.kataygdicari5 + ":" + rms.jumlah30 + " dieliminasi \n"); } if (rms.jumlah3 > minsuport && rms.jumlah4 > minsuport && rms.jumlah5 > minsuport && rms.jumlah29 >= minsuport) { cetak3.append(rms.kataygdicari3 + "," + rms.kataygdicari4 + "," + rms.kataygdicari5 + ":" + rms.jumlah29 + "\n"); akhir.setText("Hasil Akhir:" + rms.kataygdicari3 + "=>" + rms.kataygdicari4 + "," + rms.kataygdicari5+ "\n"); jumlaha = rms.jumlah3; jumlahb = rms.jumlah4; jumlahc = rms.jumlah5; jumlahd = rms.jumlah18; jumlahe = rms.jumlah19; jumlahf = rms.jumlah20; jumlahall = rms.jumlah30; rms.fungsi3(rms.kataygdicari1, rms.kataygdicari4, rms.kataygdicari5, jumlaha, jumlahb, jumlahc, jumlahd, jumlahe, jumlahf, jumlahall); } else { cetak3.append(rms.kataygdicari3 + "," + rms.kataygdicari4 + "," + rms.kataygdicari5 + ":" + rms.jumlah29 + " dieliminasi \n"); } akhir.append("Penjabaran Aturan dari Hasil Akhir \n"); akhir.append(rms.hslkata1 + "=>" + rms.hslkata2 + "," + rms.hslkata3 + " dengan jumlah support : " + rms.s1 + " dan jumlah confidence : " + rms.c1 + "\n"); akhir.append(rms.hslkata2 + "=>" + rms.hslkata1 + "," + rms.hslkata3 + " dengan jumlah support : " + rms.s1 + " dan jumlah confidence : " + rms.c2 + "\n"); akhir.append(rms.hslkata3 + "=>" + rms.hslkata1 + "," + rms.hslkata2 + " dengan jumlah support : " + rms.s1 + " dan jumlah confidence : " + rms.c3 + "\n"); akhir.append(rms.hslkata1 + "," + rms.hslkata2 + "=>" + rms.hslkata3 + " dengan jumlah support : " + rms.s1 + " dan jumlah confidence : " + rms.c4 + "\n"); akhir.append(rms.hslkata1 + "," + rms.hslkata3 + "=>" + rms.hslkata2 + " dengan jumlah support : " + rms.s1 + " dan jumlah confidence : " + rms.c5 + "\n"); akhir.append(rms.hslkata2 + "," + rms.hslkata3 + "=>" + rms.hslkata1 + " dengan jumlah support : " + rms.s1 + " dan jumlah confidence : " + rms.c6 + "\n"); }//GEN-LAST:event_jButton3ActionPerformed private void fileMenuActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_fileMenuActionPerformed // TODO add your handling code here: System.exit(busyIconIndex); }//GEN-LAST:event_fileMenuActionPerformed private void jMenuItem1ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jMenuItem1ActionPerformed // TODO add your handling code here: JOptionPane.showMessageDialog(mainPanel, " Kelompk 1 APLIKASI PENENTUAN PENEMPATAN BUKU BERDASARKAN KATEGORI PADA PERPUSTAKAAN DENGAN METODE APRIORI \n" + " Nama Kelompok : \n " + "M.Zatiar Erwan Kalam 105060807111062\n" + " Rr Octanty M 105060800111035\n" + " M.Hilman Fatah 105060807111093\n" + " Sriningsih 105060813111002\n" + " Anastasia Chandra U 105060801111073\n"); }//GEN-LAST:event_jMenuItem1ActionPerformed private void jMenuItem2ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jMenuItem2ActionPerformed // TODO add your handling code here: }//GEN-LAST:event_jMenuItem2ActionPerformed // Variables declaration - do not modify//GEN-BEGIN:variables private javax.swing.JTextArea akhir; private javax.swing.JTextArea cetak; private javax.swing.JTextArea cetak2; private javax.swing.JTextArea cetak3; private javax.swing.JButton jButton1; private javax.swing.JButton jButton2; private javax.swing.JButton jButton3; private javax.swing.JLabel jLabel1; private javax.swing.JLabel jLabel2; private javax.swing.JLabel jLabel3; private javax.swing.JLabel jLabel4; private javax.swing.JLabel jLabel5; private javax.swing.JLabel jLabel6; private javax.swing.JLabel jLabel7; private javax.swing.JMenuItem jMenuItem1; private javax.swing.JMenuItem jMenuItem2; private javax.swing.JPanel jPanel1; private javax.swing.JPanel jPanel2; private javax.swing.JPanel jPanel3; private javax.swing.JPanel jPanel4; private javax.swing.JScrollPane jScrollPane1; private javax.swing.JScrollPane jScrollPane2; private javax.swing.JScrollPane jScrollPane3; private javax.swing.JScrollPane jScrollPane4; private javax.swing.JPanel mainPanel; private javax.swing.JMenuBar menuBar; private javax.swing.JTextField minsup; private javax.swing.JProgressBar progressBar; private javax.swing.JLabel statusAnimationLabel; private javax.swing.JLabel statusMessageLabel; private javax.swing.JPanel statusPanel; private javax.swing.JTextField trans1; private javax.swing.JTextField trans2; private javax.swing.JTextField trans3; private javax.swing.JTextField trans4; private javax.swing.JTextField trans5; // End of variables declaration//GEN-END:variables private final Timer messageTimer; private final Timer busyIconTimer; private final Icon idleIcon; private final Icon[] busyIcons = new Icon[15]; private int busyIconIndex = 0; private JDialog aboutBox; }
true
2baee79139d08a300045c0356ae6b524648e0b69
Java
yuriizhurakovskyi/spring-data-jpa
/src/main/java/ua/yurii/zhurakovskyi/spring/data/jpa/springdatajpa/Application.java
UTF-8
1,717
2.640625
3
[]
no_license
package ua.yurii.zhurakovskyi.spring.data.jpa.springdatajpa; import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.SpringBootApplication; import org.springframework.context.ConfigurableApplicationContext; import ua.yurii.zhurakovskyi.spring.data.jpa.springdatajpa.model.University; import ua.yurii.zhurakovskyi.spring.data.jpa.springdatajpa.service.UniversityService; @SpringBootApplication public class Application { public static void main(String[] args) { ConfigurableApplicationContext ctx = SpringApplication.run(Application.class, args); UniversityService universityService = ctx.getBean(UniversityService.class); University university = new University(); university.setName("Lviv Polytechnic National University"); university.setAddress("Ukraine, 79000, Lviv, Stepana Bandera st., 12"); university.setLevel(4); university.setNumberOfInstitutes(18); university.setNumberOfStudents(35000); System.out.println("Creating...\n"); universityService.save(university); System.out.println("Reading...\n"); System.out.println(universityService.findById(1L)); universityService.findByLevel(4).stream().forEach(System.out::println); universityService.findByName("Lviv Polytechnic National University"); System.out.println(); System.out.println("Updating...\n"); University updateUniversity = universityService.findById(1L); updateUniversity.setNumberOfInstitutes(19); universityService.update(updateUniversity); universityService.getAll().stream().forEach(System.out::println); System.out.println("\nDeleting... \n"); universityService.deleteById(1L); universityService.getAll().stream().forEach(System.out::println); } }
true
e19cd530798c758c77afff813b013370246b173f
Java
chippingaway/MobileConnect-Support-Apps
/SupportedApps/SmsAutoReaderDemo/SmsAutoReaderDemo/app/src/main/java/com/example/chinmay/smsautoreaderdemo/MainActivity.java
UTF-8
8,806
1.929688
2
[]
no_license
package com.example.chinmay.smsautoreaderdemo; import android.Manifest; import android.app.ProgressDialog; import android.content.Context; import android.content.Intent; import android.content.pm.PackageManager; import android.os.Build; import android.os.Bundle; import android.os.IBinder; import android.support.annotation.NonNull; import android.support.v4.app.ActivityCompat; import android.support.v7.app.AppCompatActivity; import android.util.Base64; import android.view.View; import android.view.inputmethod.InputMethodManager; import android.widget.EditText; import android.widget.Toast; import com.android.volley.AuthFailureError; import com.android.volley.Request; import com.android.volley.RequestQueue; import com.android.volley.Response; import com.android.volley.VolleyError; import com.android.volley.toolbox.StringRequest; import com.android.volley.toolbox.Volley; import org.json.JSONArray; import org.json.JSONException; import org.json.JSONObject; import java.io.UnsupportedEncodingException; import java.util.HashMap; import java.util.Map; import java.util.Random; public class MainActivity extends AppCompatActivity { private static EditText mobile_number; private static String number,href_auth,nonce; private ProgressDialog loading; // These are the credentials private static final String Discovery_key = "88ae3b5d-18f1-4fc5-a97e-a6c5eae9cd5a"; private static final String Discovery_Secret = "5d6c7979-7851-4b45-a81a-1acb12ba334d"; private static final String Redirect_url = "http://localhost:8080/MCIndiaDummy/callback"; private static final String Discovery_url = "https://india.discover.mobileconnect.io/gsma/v2/discovery"; private static final String Token_key = "x-88ae3b5d-18f1-4fc5-a97e-a6c5eae9cd5a"; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); // Check sms permission // Grant if not given if (android.os.Build.VERSION.SDK_INT >= Build.VERSION_CODES.M){ if(!checkSmsPermission()) ActivityCompat.requestPermissions(MainActivity.this,new String[]{Manifest.permission.READ_SMS,Manifest.permission.RECEIVE_SMS},123); } mobile_number = (EditText)findViewById(R.id.Enter_Number); (findViewById(R.id.Login)).setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { if (!mobile_number.getText().toString().equals("") && mobile_number.getText().length() == 10) { number = mobile_number.getText().toString(); closeKeyboard(MainActivity.this, mobile_number.getWindowToken()); startDiscovery(); } else if (mobile_number.getText().toString().equals("")) Toast.makeText(MainActivity.this, "Enter number", Toast.LENGTH_SHORT).show(); else Toast.makeText(MainActivity.this, "Incorrect number entered", Toast.LENGTH_SHORT).show(); } }); } // Method to check sms permission private boolean checkSmsPermission() { String permission = "android.permission.READ_SMS"; int res = checkCallingOrSelfPermission(permission); return (res == PackageManager.PERMISSION_GRANTED); } @Override public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) { //Checking the request code of our request if(requestCode == 123){ //If permission is granted if(grantResults.length >0 && grantResults[0] == PackageManager.PERMISSION_GRANTED){ }else{ //Displaying another toast if permission is not granted android.os.Process.killProcess(android.os.Process.myPid()); System.exit(1); } } } // Discovering the operator private void startDiscovery() { loading = ProgressDialog.show(this,"Please wait...","Discovering...",false,false); StringRequest stringRequest = new StringRequest(Request.Method.POST,Discovery_url, new Response.Listener<String>() { @Override public void onResponse(String response) { loading.dismiss(); try { try { new JSONObject(response).getString("error"); Toast.makeText(getApplicationContext(),new JSONObject(response).getString("description"),Toast.LENGTH_SHORT).show(); return; } catch (JSONException e) { } JSONObject jsonObject = new JSONObject(response).getJSONObject("response").getJSONObject("apis").getJSONObject("operatorid"); JSONArray jsonArray = jsonObject.getJSONArray("link"); Random random = new Random(); nonce = String.valueOf(random.nextInt(100000)+9999); href_auth = jsonArray.getJSONObject(0).getString("href")+"?client_id="+Token_key+"&response_type=code&scope=openid+mc_india_tc&redirect_uri="+Redirect_url+"&acr_values=2&state="+nonce+"123456&nonce="+nonce+"&login_hint=MSISDN:91"+number; // Start webview activity and pass autherize url along with it Intent i = new Intent(MainActivity.this,Webview.class); Bundle bundle = new Bundle(); bundle.putString("url",href_auth); i.putExtras(bundle); startActivity(i); } catch (JSONException e) { Toast.makeText(getApplicationContext(),e.toString(),Toast.LENGTH_SHORT).show(); } } }, new Response.ErrorListener() { @Override public void onErrorResponse(VolleyError error) { loading.dismiss(); if(error instanceof com.android.volley.NoConnectionError){ Toast.makeText(getApplicationContext(),"NO INTERNET CONNECTION",Toast.LENGTH_SHORT).show(); return; } String responseBody = null; try { responseBody = new String( error.networkResponse.data, "utf-8" ); JSONObject jsonObject = new JSONObject( responseBody ); Toast.makeText(MainActivity.this,jsonObject.getString("description"),Toast.LENGTH_SHORT).show(); return; } catch (UnsupportedEncodingException e) {} catch (JSONException e) {} catch (Exception e){Toast.makeText(getApplicationContext(),e.toString(),Toast.LENGTH_SHORT).show();} if(!(error instanceof com.android.volley.NoConnectionError)){ Toast.makeText(getApplicationContext(), error.toString(),Toast.LENGTH_SHORT).show(); return; } } }){ @Override protected Map<String,String> getParams(){ Map<String,String> params = new HashMap<String, String>(); params.put("Redirect_URL",Redirect_url); params.put("MSISDN","91"+number); return params; } @Override public Map<String, String> getHeaders() throws AuthFailureError { Map<String,String> headers = new HashMap<String, String>(); String credentials = Discovery_key+":"+Discovery_Secret; String auth = "Basic " + Base64.encodeToString(credentials.getBytes(), Base64.NO_WRAP); headers.put("Accept", "application/json"); headers.put("Authorization", auth); return headers; } }; RequestQueue requestQueue = Volley.newRequestQueue(this); requestQueue.add(stringRequest); } public static void closeKeyboard(Context c, IBinder windowToken) { InputMethodManager mgr = (InputMethodManager) c.getSystemService(Context.INPUT_METHOD_SERVICE); mgr.hideSoftInputFromWindow(windowToken, 0); } }
true
e5cb85af664b031d147f6d0d1d2a53dc22d242fc
Java
marcosptf/ejb3-webServices
/chapter11/src/ejb/client/actionbazaar/buslogic/BazaarAdminClient.java
UTF-8
816
2.1875
2
[]
no_license
package actionbazaar.buslogic; import javax.naming.Context; import javax.naming.InitialContext; import actionbazaar.persistence.*; import javax.ejb.EJB; public class BazaarAdminClient { public static void main(String [] args) { try { Context context = new InitialContext(); BazaarAdmin bazaarAdmin = (BazaarAdmin)context.lookup("BazaarAdmin#actionbazaar.buslogic.BazaarAdmin"); Category category = bazaarAdmin.createCategory("test category","idiot2"); System.out.println("Category created with Id:"+category.getCategoryId()); } catch (Exception ex) { ex.printStackTrace(); } } }
true
cb9a0a4896cb10804a64cf283ba34b10aedfc8fd
Java
mddowlin/mp-extra-measureconverter
/app/src/main/java/com/example/mdowlin/converta/MainActivity.java
UTF-8
2,489
2.5625
3
[]
no_license
package com.example.mdowlin.converta; import android.os.Bundle; import android.support.design.widget.FloatingActionButton; import android.support.v4.view.ViewPager; import android.support.v4.app.Fragment; import android.support.v4.app.FragmentPagerAdapter; import android.support.v7.app.AppCompatActivity; import android.support.v4.app.FragmentManager; import android.support.v7.widget.Toolbar; import android.os.Bundle; import android.view.View; import android.view.Menu; import android.view.MenuItem; public class MainActivity extends AppCompatActivity { ViewPager viewPager; FragTemp tempfrag; FragLength lengthfrag; FragWeight weightfrag; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); tempfrag = new FragTemp(); lengthfrag = new FragLength(); weightfrag = new FragWeight(); FragmentManager fragmentManager = getSupportFragmentManager(); viewPager = findViewById(R.id.pager); viewPager.setAdapter(new ThreeFragmentPagerAdapter(fragmentManager)); viewPager.setCurrentItem(1); } public class ThreeFragmentPagerAdapter extends FragmentPagerAdapter { int PAGE_COUNT = 3; //required constructor that simply supers. public ThreeFragmentPagerAdapter(FragmentManager fm) { super(fm); } // return the correct fragment based on where in pager we are. @Override public Fragment getItem(int position) { switch (position) { case 0: return tempfrag; case 1: return lengthfrag; case 2: return weightfrag; default: return null; } } //how many total pages in the viewpager there are. 3 in this case. @Override public int getCount() { return PAGE_COUNT; } //getPageTitle required for the PageStripe to work and have a value. @Override public CharSequence getPageTitle(int position) { if(position == 0) { return "Tempurature"; } else if(position == 1) { return "Length"; } else { return "Weight"; } } } }
true
a4e228b9e460b29d03279397477c2cd370441ac2
Java
caniblossom/TiKaPe
/src/main/java/tikape/tikape/Varauskeraaja.java
UTF-8
700
2.21875
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 tikape.tikape; import java.sql.*; /** * * @author Jani Salo */ public class Varauskeraaja implements Collector<Varaus> { @Override public Varaus collect(ResultSet rs) throws SQLException { String rekisterinro = rs.getString("pyora"); String varaaja = rs.getString("varaaja"); String varausAlkaa = rs.getString("varaus_alkaa"); String varausLoppuu = rs.getString("varaus_loppuu"); return new Varaus(rekisterinro, varaaja, varausAlkaa, varausLoppuu); } }
true
1c28c4b5d2f28b3804387a36f5eb05c228933fad
Java
PlayersCommittee/gemp-swccg-public
/gemp-swccg-logic/src/main/java/com/gempukku/swccgo/logic/effects/PutCardFromVoidInUsedPileEffect.java
UTF-8
881
2.75
3
[ "MIT" ]
permissive
package com.gempukku.swccgo.logic.effects; import com.gempukku.swccgo.common.Zone; import com.gempukku.swccgo.game.PhysicalCard; import com.gempukku.swccgo.logic.GameUtils; import com.gempukku.swccgo.logic.timing.Action; /** * An effect to put the specified card from void in Lost Pile. */ public class PutCardFromVoidInUsedPileEffect extends PutOneCardFromVoidInCardPileEffect { /** * Creates an effect that causes the player to put the specified card from void in Used Pile. * @param action the action performing this effect * @param playerId the player * @param card the card */ public PutCardFromVoidInUsedPileEffect(Action action, String playerId, PhysicalCard card) { super(action, card, Zone.USED_PILE, false, ((playerId != null) ? playerId : card.getOwner()) + " puts " + GameUtils.getCardLink(card) + " in Used Pile"); } }
true
aba253c5155529a311ccf182f9e9fa275f4f197e
Java
Robin2000/MaNGOS_CMS
/src/com/ficus/query/item/TotemCategory.java
UTF-8
2,805
2.421875
2
[]
no_license
package com.ficus.query.item; import java.util.ArrayList; import javax.servlet.http.HttpServletRequest; import com.ficus.query.KeyValue; import com.ficus.query.QueryItemInterface; public class TotemCategory extends ArrayList<KeyValue> implements QueryItemInterface{ public TotemCategory(){ add(new KeyValue(-1,"ๅ…จ้ƒจ")); add(new KeyValue(1,"Skinning Knife (OLD)")); add(new KeyValue(2,"Earth Totem")); add(new KeyValue(3,"Air Totem")); add(new KeyValue(4,"Fire Totem")); add(new KeyValue(5,"Water Totem")); add(new KeyValue(6,"Runed Copper Rod")); add(new KeyValue(7,"Runed Silver Rod")); add(new KeyValue(8,"Runed Golden Rod")); add(new KeyValue(9,"Runed Truesilver Rod")); add(new KeyValue(10,"Runed Arcanite Rod")); add(new KeyValue(11,"Mining Pick (OLD)")); add(new KeyValue(12,"Philosopher's Stone")); add(new KeyValue(13,"Blacksmith Hammer (OLD)")); add(new KeyValue(14,"Arclight Spanner")); add(new KeyValue(15,"Gyromatic Micro-Adjustor")); add(new KeyValue(21,"Master Totem")); add(new KeyValue(41,"Runed Fel Iron Rod")); add(new KeyValue(62,"Runed Adamantite Rod")); add(new KeyValue(63,"Runed Eternium Rod")); add(new KeyValue(81,"Hollow Quill")); add(new KeyValue(101,"Runed Azurite Rod")); add(new KeyValue(121,"Virtuoso Inking Set")); add(new KeyValue(141,"Drums")); add(new KeyValue(161,"Gnomish Army Knife")); add(new KeyValue(162,"Blacksmith Hammer")); add(new KeyValue(165,"Mining Pick")); add(new KeyValue(166,"Skinning Knife")); add(new KeyValue(167,"Hammer Pick")); add(new KeyValue(168,"Bladed Pickaxe")); add(new KeyValue(169,"Flint and Tinder")); add(new KeyValue(189,"Runed Cobalt Rod")); add(new KeyValue(190,"Runed Titanium Rod")); } /*็”Ÿๆˆ็•Œ้ขhtmlไพ›ๆœ€็ปˆ็”จๆˆทไฝฟ็”จ๏ผŒไบคไบ’ๆž„้€ ๆŸฅ่ฏขๆกไปถ*/ public String getQueryHtml(){ StringBuilder sb=new StringBuilder("<nobr>ๅ›พ่…พ็ฑป๏ผš<select onchange='reload()' id='TotemCategory'>"); for(KeyValue kv:this){ sb.append("<option value='").append(kv.key).append("'>").append(kv.key).append(".").append(kv.value).append("</option>"); } sb.append("</select></nobr>"); return sb.toString(); } /*javascriptไปŽ็•Œ้ขๅ…ƒ็ด ๅ–ๅ€ผ๏ผŒไบง็”ŸPOSTๅ‚ๆ•ฐ*/ public String getJavaScript(){ return "d.TotemCategory = $('#TotemCategory').val();\n"; } /*ๆœๅŠก็ซฏไปŽHttpServletRequestๅ–ๆไบค็š„ๅ€ผ๏ผŒไบง็”ŸๆŸฅ่ฏขๆกไปถ*/ public String parseQueryParameter(HttpServletRequest request){ String type=request.getParameter("TotemCategory"); if(type!=null&&!"-1".equals(type)) return "TotemCategory="+type; else return ""; } public String getFilterTable(){ return "item_template"; } @Override public boolean useAjaxRetriveHtml() { // TODO Auto-generated method stub return false; } }
true
3f717e25c0406c8158bee3bc0311baf764477103
Java
skoechle/sobek
/integration-test/short-running-operation-ejb/src/main/java/com/test/operation/shortrunning/ShortRunningOperationMDB.java
UTF-8
3,484
2.390625
2
[ "MIT" ]
permissive
package com.test.operation.shortrunning; import java.util.logging.Logger; import javax.ejb.MessageDriven; import javax.jms.JMSException; import javax.jms.Message; import javax.jms.MessageListener; import javax.jms.ObjectMessage; import javax.jms.TextMessage; import com.sobek.client.operation.OperationClient; import com.sobek.client.operation.request.OperationRequestMessage; import com.sobek.client.operation.status.CompletionState; import com.sobek.client.operation.status.OperationStatus; import com.sobek.common.util.SystemProperties; @MessageDriven(mappedName="jms/ShortRunningOperationQueueJNDIName") public class ShortRunningOperationMDB implements MessageListener { private static final Logger logger = Logger.getLogger(ShortRunningOperationMDB.class.getPackage().getName()); @Override public void onMessage(Message message) { StringBuilder builder = new StringBuilder(); OperationRequestMessage request = null; builder.append("================================================================================").append(SystemProperties.NEW_LINE); builder.append("Received message [" + message + "].").append(SystemProperties.NEW_LINE); builder.append("================================================================================").append(SystemProperties.NEW_LINE); if(message instanceof TextMessage) { try { builder.append(((TextMessage)message).getText()).append(SystemProperties.NEW_LINE); // TODO: Convert text message into an operation status. For not just log an // error. } catch (JMSException e) { e.printStackTrace(); } } else if (message instanceof ObjectMessage) { try { Object object = ((ObjectMessage)message).getObject(); if(object instanceof OperationRequestMessage) { request = (OperationRequestMessage)object; } else { builder.append("Message did not contain an operation request. Contained object was : " + object).append(SystemProperties.NEW_LINE); } } catch (JMSException e) { e.printStackTrace(); } } else { builder.append("Message was not a text message").append(SystemProperties.NEW_LINE); } builder.append("================================================================================").append(SystemProperties.NEW_LINE); builder.append("================================================================================").append(SystemProperties.NEW_LINE); logger.finest(builder.toString()); OperationClient client = new OperationClient(request); client.sendStatusMessage(25, OperationStatus.WORKING, "Some randome details for 25% complete."); try { Thread.sleep(5000); } catch (InterruptedException e) { e.printStackTrace(); } client.sendStatusMessage(50, OperationStatus.WORKING, "Some randome details for 50% complete."); try { Thread.sleep(5000); } catch (InterruptedException e) { e.printStackTrace(); } client.sendStatusMessage(75, OperationStatus.WORKING, "Some randome details for 75% complete."); try { Thread.sleep(5000); } catch (InterruptedException e) { e.printStackTrace(); } client.sendCompletionMessage("finishedProduct", "Returned material... for now just using a string. Later we will do something cool.", CompletionState.COMPLETE, "Some randome details for 100% complete."); client.close(); logger.severe("\n\n\nCOMPLETION MESSAGE SENT\n\n\n"); } }
true
d5625285f68c81e9802b8dbbbbd0837f841b55d5
Java
Svetozar99/ElasticSearch2021
/src/main/java/com/ftn/elastic/ElasticSearch2021/model/Tag.java
UTF-8
740
2.09375
2
[]
no_license
package com.ftn.elastic.ElasticSearch2021.model; import lombok.AllArgsConstructor; import lombok.Getter; import lombok.NoArgsConstructor; import lombok.Setter; import javax.persistence.*; import java.util.Set; @Entity @Table(name = "tags") @NoArgsConstructor @AllArgsConstructor @Getter @Setter public class Tag { @Id @GeneratedValue(strategy = GenerationType.IDENTITY) @Column(name = "tag_id", nullable = false) private Integer id; @Column(name = "tag_name", nullable = false, length = 100) private String name; @ManyToOne @JoinColumn(name = "user_id", referencedColumnName = "user_id", nullable = false) private User user; @ManyToMany(mappedBy = "tags") private Set<Message> messages; }
true
200422d683770592dc74c29ae4015da33691c2aa
Java
Jayaraj342/restaurant-h2-auth
/src/main/java/surabi/restaurants/config/AuditLogConfiguration.java
UTF-8
1,537
2.125
2
[]
no_license
package surabi.restaurants.config; import lombok.AllArgsConstructor; import lombok.extern.slf4j.Slf4j; import org.aspectj.lang.JoinPoint; import org.aspectj.lang.annotation.AfterReturning; import org.aspectj.lang.annotation.Aspect; import org.springframework.context.annotation.Configuration; import org.springframework.security.core.context.SecurityContextHolder; import org.springframework.security.core.userdetails.User; import surabi.restaurants.dto.AuditDTO; import surabi.restaurants.service.SurabiRestaurantService; import java.util.Date; @Aspect @Configuration @Slf4j @AllArgsConstructor public class AuditLogConfiguration { private final SurabiRestaurantService surabiRestaurantService; @AfterReturning(value = "execution(* surabi.restaurants.controller.SurabiRestaurantsController.selectMenuWithBill(..))", returning = "result") public void afterReturning(JoinPoint joinPoint, String result) { User user = (User) SecurityContextHolder.getContext().getAuthentication().getPrincipal(); String[] itemsWithTotal = result.split("selected &"); String items = itemsWithTotal[0].trim(); String total = itemsWithTotal[1].replace("Final bill is โ‚น", "").trim(); surabiRestaurantService.addLogToAudit( AuditDTO.builder() .user(user.getUsername()) .items(items) .totalPrice(Integer.parseInt(total)) .time(new Date()) .build() ); } }
true
9f64b23ae4dbc62f5efb1396c8b402f6e349714e
Java
JADC1971/prueba-repositorio1
/ConvertirTitulo/src/com/CapitalizarTitulo/Main.java
UTF-8
1,013
3.203125
3
[]
no_license
package com.CapitalizarTitulo; import javax.swing.*; import java.awt.*; public class Main { public static void main(String [] args){ JFrame aplicacion = crearGui(); aplicacion.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE); aplicacion.setVisible(true); } private static JFrame crearGui(){ JTextField entrada = new JTextField(); entrada.setPreferredSize(new Dimension(300,40)); JButton boton = new JButton("Convertir"); JLabel salida = new JLabel(); salida.setPreferredSize(new Dimension(300,40)); boton.addActionListener(e -> { salida.setText(ConvertirTituloMayuscula.convertirAMayuscula(entrada.getText())); }); JFrame gui = new JFrame("Pantalla covierte titulo a Mayusculas"); gui.setLayout(new FlowLayout()); gui.add(entrada); gui.add(boton); gui.add(salida); gui.pack(); gui.setLocationRelativeTo(null); return gui; } }
true
86bf8c54a3b2022fb337876a1f4fe62fbe23fa8b
Java
samirtf/postofficemanager-lp2
/PostOfficeManager/src/correios/util/EncomendaRegistrada.java
UTF-8
3,063
3.34375
3
[]
no_license
package correios.util; /** * Classe que implementa comportamento de encomendas registradas. * @author Marcus Vinicius Souza de Oliveira<br> * Rafael Oliveira Vieira<br> * Samir Trajano Feitosa<br> * Werton Vinicius Guimaraes Gomes * */ public class EncomendaRegistrada extends Encomenda { protected String codigoDeRegistro; /** * Encomenda Registrada com valor declarado. * @param cepRemetente - Conjunto de 8 numeros, para formar o CEP do Remetente * @param cepDestinatario - Conjunto de .8 numeros, para formar o CEP do Destinatario * @param dataEnvio - Conjunto de 8 numeros, para formar a data. * @param atendente - nome da(o) atendente. * @param cidade - Nome de uma cidade. * @param estado - Nome de um estado. * @param peso - pega um valor de peso (em gramas). * @param valorDeclarado - pega um valor declarado * @throws IllegalArgumentException - quando algum parรขmetro รฉ invรกlido. * TipoDeEncomendaException - Quando o peso ou valor declarado da encomenda, a caracterizam de outro tipo. */ public EncomendaRegistrada(String cepRemetente, String cepDestinatario, String dataEnvio, String atendente, String cidade, String estado, double peso, double valorDeclarado) throws Exception { super(cepRemetente, cepDestinatario, dataEnvio, atendente, cidade, estado, peso, valorDeclarado); codigoDeRegistro = "PB" + getId().substring(3,12) + "BR"; } /** * Encomenda registrada sem valor declarado. * @param cepRemetente - Conjunto de 8 numeros, para formar o CEP do Remetente * @param cepDestinatario - Conjunto de .8 numeros, para formar o CEP do Destinatario * @param dataEnvio - Conjunto de 8 numeros, para formar a data. * @param atendente - nome da(o) atendente. * @param cidade - Nome de uma cidade. * @param estado - Nome de um estado. * @param peso - pega um valor de peso (em gramas). * @throws IllegalArgumentException - quando algum parรขmetro รฉ invรกlido. * TipoDeEncomendaException - Quando o peso ou valor declarado da encomenda, a caracterizam de outro tipo. */ public EncomendaRegistrada(String cepRemetente, String cepDestinatario, String dataEnvio, String atendente, String cidade, String estado, double peso) throws Exception { super(cepRemetente, cepDestinatario, dataEnvio, atendente, cidade, estado, peso); codigoDeRegistro = "PB" + getId().substring(3,12) + "BR"; } /** * Retorna o codigo de registro de uma encomenda. * @return String - cรณdigo de registro */ public String getCodigoDeRegistro() { return codigoDeRegistro; } /**Calcula o valor da encomenda registrada e o retorna. * Tantos encomendas com valor declarado, * como as simples. * @return double - valor */ @Override public double valorDaEncomenda() { return 1.4 + (peso/10)*0.2 + (getValorDeclarado()/100); } @Override public String toString() { return "id: " + id + "\n" + cidade + "\n" + estado + "\nCEP destinatario: " + cepDestinatario + "\nCEP remetente: " + cepRemetente + "\n" + String.format("%.0f gramas\nValor: %.2f", peso, valorDaEncomenda()) + "\n" + getCodigoDeRegistro(); } }
true
1e24f95ba0f95a2213d651036fd222ad4a8c399d
Java
sandraolsson/HostipalSystem
/HostpitalSystem/src/Server/Patient.java
UTF-8
952
2.84375
3
[]
no_license
package Server; import java.util.ArrayList; import java.util.HashSet; public class Patient { private String pNbr, name, division; private Journal journal; private HashSet<String> staff; public Patient(String pnbr, String name, String division) { this.pNbr = pnbr; this.name = name; this.division = division; this.journal = new Journal(); staff = new HashSet<String>(); } public void addJournal(String text, String docPnbr, String nursePnbr) { journal.update(text); staff.add(docPnbr); staff.add(nursePnbr); } public String getPnbr() { return pNbr; } public String getName() { return name; } public String getDivision() { return division; } public boolean isTreatedBy(String pNbr) { return staff.contains(pNbr); } public void updateJournal(String newtext) { journal.update(newtext); } public Journal getJournal() { return journal; } public void addStaff(String pnbr) { staff.add(pnbr); } }
true
dc4e1684aede1eea9d59a1dbe9042c9baf05b3e2
Java
tenacious-joy/pigeon-post
/src/main/java/com/pigeon/post/messaging/messagingdemo/utils/NumberFinder.java
UTF-8
647
2.109375
2
[ "MIT" ]
permissive
package com.pigeon.post.messaging.messagingdemo.utils; import com.pigeon.post.messaging.messagingdemo.services.MessagingService; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; import javax.validation.ConstraintValidator; import javax.validation.ConstraintValidatorContext; @Service public class NumberFinder implements ConstraintValidator<isFound, String> { @Autowired MessagingService messagingService; @Override public boolean isValid(String value, ConstraintValidatorContext context) { return messagingService.fetchContactNumber(value) != null; } }
true
6a1336c16d78cb0f9f936fb1219b734f6754b04d
Java
cha63506/CompSecurity
/sound-cloud_source/src/com/google/android/gms/analytics/internal/r.java
UTF-8
527
1.539063
2
[]
no_license
// Decompiled by Jad v1.5.8e. Copyright 2001 Pavel Kouznetsov. // Jad home page: http://www.geocities.com/kpdus/jad.html // Decompiler options: braces fieldsfirst space lnc package com.google.android.gms.analytics.internal; // Referenced classes of package com.google.android.gms.analytics.internal: // n, F, X final class r implements Runnable { final X a; final n b; r(n n1, X x) { b = n1; a = x; super(); } public final void run() { b.a.a(a); } }
true
8c5bb19da46cb431207137ef49cfb41fdea60591
Java
kkomaweb83/danacom_client01
/danacom_client01/src/com/da/na/MakerVo.java
UTF-8
1,174
1.867188
2
[]
no_license
package com.da.na; import java.io.Serializable; import java.util.List; public class MakerVo implements Serializable { public static final long serialVersionUID = 39394L; private int mkr_no; private String mkr_name; private String mkr_pcl_no; private String mkr_insert; private String pcl_name; private List ist; public MakerVo() { } public int getMkr_no() { return mkr_no; } public void setMkr_no(int mkr_no) { this.mkr_no = mkr_no; } public String getMkr_name() { return mkr_name; } public void setMkr_name(String mkr_name) { this.mkr_name = mkr_name; } public String getMkr_pcl_no() { return mkr_pcl_no; } public void setMkr_pcl_no(String mkr_pcl_no) { this.mkr_pcl_no = mkr_pcl_no; } public String getMkr_insert() { return mkr_insert; } public void setMkr_insert(String mkr_insert) { this.mkr_insert = mkr_insert; } public String getPcl_name() { return pcl_name; } public void setPcl_name(String pcl_name) { this.pcl_name = pcl_name; } public List getIst() { return ist; } public void setIst(List ist) { this.ist = ist; } }
true
19635c785cd065df20b67c2686b60c7c765726f1
Java
ganeshravikumar/data-strucutre-training
/src/main/java/data/structure/linkedlist/Node.java
UTF-8
118
2.015625
2
[]
no_license
package data.structure.linkedlist; public class Node { public int nodeValue; public Node nextReference; }
true
21faa753fcaf3bda9bc359f12a8a4556c543d0d2
Java
iamscratches/ScratchPad
/app/src/main/java/com/iamscratches/scratchpad/DBManager.java
UTF-8
4,164
2.421875
2
[]
no_license
package com.iamscratches.scratchpad; import android.content.ContentValues; import android.content.Context; import android.database.Cursor; import android.database.sqlite.SQLiteDatabase; import android.database.sqlite.SQLiteOpenHelper; import android.database.sqlite.SQLiteQueryBuilder; import android.widget.Toast; import java.util.Date; public class DBManager { private SQLiteDatabase sqlDB; static final String DBName = "ScratchPad"; static final String TName = "Notepads"; static final String tableName = "tableName"; static final String DateTime = " dateTime text "; static final String Item = " item text "; static final String Quantity = " quantity text "; static final String Amount = " amount real "; static final int DBVersion = 1; static Context context; static class DatabaseHelper extends SQLiteOpenHelper{ Context context; DatabaseHelper(Context context){ super(context, DBName, null, DBVersion); this.context = context; } @Override public void onCreate(SQLiteDatabase db) { db.execSQL("Create table IF NOT EXISTS " + TName + "(ID integer primary key autoincrement, " + tableName + " text Unique);"); Toast.makeText(context, "Note Pad is ready to use", Toast.LENGTH_LONG).show(); } @Override public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) { onCreate(db); } } public DBManager(Context context){ DatabaseHelper db = new DatabaseHelper(context); sqlDB = db.getWritableDatabase(); this.context = context; } public DBManager(){ DatabaseHelper db = new DatabaseHelper(context); sqlDB = db.getWritableDatabase(); } public Cursor getNotepads(){ SQLiteQueryBuilder qb = new SQLiteQueryBuilder(); qb.setTables(TName); String selectAll[] = {"*"}; Cursor cursor = qb.query(sqlDB, selectAll, null, null, null, null, tableName); return cursor; } public void enterTableData(String dbName, String item, String quantity, float amount){ sqlDB.execSQL("Create table IF NOT EXISTS " + dbName + "(ID integer primary key autoincrement, " + DateTime + "," + Item + "," + Quantity + "," + Amount + ");"); ContentValues values = new ContentValues(); values.put(tableName,dbName); Insert(TName,values); Date d = new Date(); values = new ContentValues(); values.put("item", item); values.put("quantity", quantity); values.put("amount", amount); values.put("dateTime",d.toString()); Insert(dbName,values); } private long Insert(String tableName, ContentValues values){ try{ long ID = sqlDB.insert(tableName,"",values);// if fails to insert then ID = 0 if(ID!=-1) Toast.makeText(context,"Data recorded succesfully with ID : " + String.valueOf(ID), Toast.LENGTH_LONG).show(); return ID; }catch (Exception e){}; return 0; } public Cursor query(String tableName){ SQLiteQueryBuilder qb = new SQLiteQueryBuilder(); qb.setTables(tableName); String selectAll[] = {"*"}; Cursor cursor = qb.query(sqlDB, selectAll, null, null, null, null, null); return cursor; } public Cursor query(String tableName, String item, String[] selectionArgs){ SQLiteQueryBuilder qb = new SQLiteQueryBuilder(); qb.setTables(tableName); String selectAll[] = {"*"}; item = item; Cursor cursor = qb.query(sqlDB, selectAll, item, selectionArgs, null, null, null); return cursor; } public int Delete(String tableName, String selection, String[] selectionArgs){ int count = sqlDB.delete(tableName, selection, selectionArgs); return count; } public void drop(String notepad){ sqlDB.execSQL("drop table " + notepad); String selectionArgs[] = {notepad}; Delete(TName, "tableName like ? ", selectionArgs); } }
true
2177a704e499adb1285042d92b9afaa83ffba181
Java
MiLinSoQ/DataStructures
/src/SegmentTree/Main.java
UTF-8
599
3.015625
3
[]
no_license
public class Main { public static void main(String args[]) { Integer[] nums = { 5, 0, -2, 6, 7 }; SegmentTree<Integer> tree = new SegmentTree<>(nums, new Merger<Integer>() { @Override public Integer merge(Integer a, Integer b) { return a + b; } }); System.out.println(tree.toString()); System.out.println("Query: " + tree.query(1, 4)); System.out.println("Query: " + tree.query(0, 4)); System.out.println("Query: " + tree.query(3, 4)); tree.set(0, 3); System.out.println(tree.toString()); System.out.println("Query: " + tree.query(0, 4)); } }
true
001ce868a6bd53c5cb80f893325f8d777a93092e
Java
ddieterly/monasca-api
/src/test/java/com/hpcloud/mon/app/command/CreateNotificationMethodTest.java
UTF-8
1,955
2.21875
2
[ "Apache-2.0" ]
permissive
package com.hpcloud.mon.app.command; import static com.hpcloud.dropwizard.JsonHelpers.jsonFixture; import static org.testng.Assert.assertEquals; import org.testng.annotations.Test; import com.fasterxml.jackson.databind.JsonMappingException; import com.hpcloud.mon.app.command.CreateNotificationMethodCommand; import com.hpcloud.mon.domain.model.AbstractModelTest; import com.hpcloud.mon.domain.model.notificationmethod.NotificationMethodType; @Test public class CreateNotificationMethodTest extends AbstractModelTest { public void shouldDeserializeFromJson() throws Exception { CreateNotificationMethodCommand newNotificationMethod = new CreateNotificationMethodCommand("MySMS", NotificationMethodType.SMS, "9228675309"); String json = jsonFixture("fixtures/newNotificationMethod.json"); CreateNotificationMethodCommand other = fromJson(json, CreateNotificationMethodCommand.class); assertEquals(other, newNotificationMethod); } public void shouldDeserializeFromJsonLowerCaseEnum() throws Exception { CreateNotificationMethodCommand newNotificationMethod = new CreateNotificationMethodCommand("MySMS", NotificationMethodType.SMS, "9228675309"); String json = jsonFixture("fixtures/newNotificationMethodWithLowercaseEnum.json"); CreateNotificationMethodCommand other = fromJson(json, CreateNotificationMethodCommand.class); assertEquals(other, newNotificationMethod); } @Test(expectedExceptions = JsonMappingException.class) public void shouldDeserializeFromJsonEnumError() throws Exception { CreateNotificationMethodCommand newNotificationMethod = new CreateNotificationMethodCommand("MySMS", NotificationMethodType.SMS, "9228675309"); String json = jsonFixture("fixtures/newNotificationMethodWithInvalidEnum.json"); CreateNotificationMethodCommand other = fromJson(json, CreateNotificationMethodCommand.class); assertEquals(other, newNotificationMethod); } }
true
372a49d08bceed34d04d111bd3c504bce0d20f1f
Java
DavFromNL/comp2005-winter20-group12
/Group 12 Iteration 4/Final Release/PlayerSettingsButtons.java
UTF-8
791
2.71875
3
[]
no_license
import java.awt.event.ActionListener; import java.awt.event.ActionEvent; import javax.swing.*; //This is what happens when you click on each button which is of type PlayerSettings. public class PlayerSettingsButtons extends JButton implements ActionListener { public PlayerSettingsButtons() { this.addActionListener(this); } public void actionPerformed(ActionEvent event) { String name = event.getActionCommand(); switch (name) { case "Number Of Players": new NumberOfPlayers(); break; case "Difficulty": new Difficulty(); break; case "Hint": new Hint(); break; } } }
true
3dcf04e910af9df609bc5a54fa63cf4cc5bf5ce6
Java
gabrielsmartins/libex7
/adapters/gui/src/main/java/br/edu/utfpr/adapters/gui/handlers/commons/MenuItemSearchStudentHandler.java
UTF-8
1,177
2.34375
2
[]
no_license
package br.edu.utfpr.adapters.gui.handlers.commons; import br.edu.utfpr.adapters.gui.controllers.users.students.SearchStudentController; import br.edu.utfpr.adapters.gui.controllers.users.students.StudentController; import br.edu.utfpr.adapters.gui.views.users.students.SearchStudentView; import javafx.event.ActionEvent; import javafx.event.EventHandler; import javafx.scene.control.TextField; public class MenuItemSearchStudentHandler implements EventHandler<ActionEvent> { private final StudentController studentController; public MenuItemSearchStudentHandler(StudentController studentController) { this.studentController = studentController; } @Override public void handle(ActionEvent event) { SearchStudentController searchStudentController = studentController.getSearchStudentController(); SearchStudentView searchStudentView = searchStudentController.getView(); TextField txtID = searchStudentView.getTxtID(); TextField txtName = searchStudentView.getTxtName(); TextField txtStudentNumber = searchStudentView.getTxtStudentNumber(); txtID.clear(); txtName.clear(); txtStudentNumber.clear(); searchStudentView.show(); } }
true
f0a6d3c1cde8b0d77efcc66c8dc2d6a36719030d
Java
hhuuyy/MimityStore
/MimityStore/src/mimity/admin/controller/LoginController.java
UTF-8
2,257
2.078125
2
[]
no_license
package mimity.admin.controller; import java.util.List; import javax.servlet.http.HttpServletResponse; import javax.servlet.http.HttpSession; import org.hibernate.Query; import org.hibernate.Session; import org.hibernate.SessionFactory; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Controller; import org.springframework.transaction.annotation.Transactional; 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; import mimity.entity.security.Master; @Transactional @Controller @RequestMapping("role/login") public class LoginController { @Autowired SessionFactory factory; @RequestMapping("login") public String login() { return "role/login/login"; } @RequestMapping(value = "login", method = RequestMethod.POST) public String login(ModelMap model, @RequestParam("id") String id, @RequestParam("password") String pw, HttpSession httpSession, HttpServletResponse response) { Session session = factory.getCurrentSession(); String url = ""; try { Master master = (Master) session.get(Master.class, id); if (!master.getPassword().equals(pw)) { model.addAttribute("message", "Invalid password !"); url = "role/login/login"; } else { model.addAttribute("message", "Login successfully"); httpSession.setAttribute("master", master); String hql = "Select p.category.nameVN," + " sum(p.quantity)," + " sum(p.quantity*p.unitPrice)," + " min(p.unitPrice)," + " max(p.unitPrice)," + " avg(p.unitPrice)" + " From Product p group by p.category.nameVN"; Query query = session.createQuery(hql); List<Object[]> list = query.list(); model.addAttribute("group", "Category"); model.addAttribute("items", list); url = "admin/home/index"; } } catch (Exception e) { model.addAttribute("message", "Invalid username !"); url = "role/login/login"; } return url; } @RequestMapping("logoff") public String logoff(HttpSession httpSession) { httpSession.removeAttribute("master"); return "redirect:/role/login/login.php"; } }
true
7a66198a8e551e39d3722c052bd1cf2ee784082d
Java
cp612sh/com.heytz.gwsdkDevice
/src/android/gwsdkDevice.java
UTF-8
4,603
2.0625
2
[]
no_license
package com.heytz.gwsdkDevice; import android.content.Context; import com.xtremeprog.xpgconnect.XPGWifiDevice; import com.xtremeprog.xpgconnect.XPGWifiDeviceListener; import com.xtremeprog.xpgconnect.XPGWifiSDK; import com.xtremeprog.xpgconnect.XPGWifiSDKListener; import org.apache.cordova.CallbackContext; import org.apache.cordova.CordovaInterface; import org.apache.cordova.CordovaPlugin; import org.apache.cordova.CordovaWebView; import org.json.JSONArray; import org.json.JSONException; import org.json.JSONObject; import java.util.List; /** * This class wrapping Gizwits WifiSDK called from JavaScript. */ public class gwsdkDevice extends CordovaPlugin { private CallbackContext airLinkCallbackContext; private Context context; @Override public void initialize(CordovaInterface cordova, CordovaWebView webView) { super.initialize(cordova, webView); // your init code here context = cordova.getActivity().getApplicationContext(); } @Override public boolean execute(String action, JSONArray args, CallbackContext callbackContext) throws JSONException { airLinkCallbackContext = callbackContext; if (action.equals("deviceControl")) { /** * uid, token, mac, key, value */ this.getBoundDevice(args.getString(0), args.getString(1)); this.deviceLogin(args.getString(0), args.getString(1), args.getString(2), args.getString(3), args.getString(4)); return true; } return false; } List<XPGWifiDevice> xpgWifiDeviceList; private void getBoundDevice(String uid, String token, String... specialPoductKeys) { XPGWifiSDK.sharedInstance().setListener(new XPGWifiSDKListener() { @Override public void didDiscovered(int error, List<XPGWifiDevice> deviceList) { if (deviceList.size() > 0) xpgWifiDeviceList = deviceList; // else // } }); XPGWifiSDK.sharedInstance().getBoundDevices(uid, token, specialPoductKeys); } private void cWrite(XPGWifiDevice xpgWifiDevice, String key, Object value) { try { //ๅˆ›ๅปบJSONObject ๅฏน่ฑก๏ผŒ็”จไบŽๅฐ่ฃ…ๆ‰€ๆœ‰ๆ•ฐๆฎ final JSONObject jsonsend = new JSONObject(); //ๅ†™ๅ…ฅๅ‘ฝไปคๅญ—ๆฎต๏ผˆๆ‰€ๆœ‰ไบงๅ“ไธ€่‡ด๏ผ‰ jsonsend.put("cmd", 1); //ๅˆ›ๅปบJSONObject ๅฏน่ฑก๏ผŒ็”จไบŽๅฐ่ฃ…ๆ•ฐๆฎ็‚น JSONObject jsonparam = new JSONObject(); //ๅ†™ๅ…ฅๆ•ฐๆฎ็‚นๅญ—ๆฎต jsonparam.put(key, value); //ๅ†™ๅ…ฅไบงๅ“ๅญ—ๆฎต๏ผˆๆ‰€ๆœ‰ไบงๅ“ไธ€่‡ด๏ผ‰ jsonsend.put("entity0", jsonparam); //่ฐƒ็”จๅ‘้€ๆŒ‡ไปคๆ–นๆณ• xpgWifiDevice.write(jsonsend.toString()); airLinkCallbackContext.success("success"); } catch (JSONException e) { e.printStackTrace(); airLinkCallbackContext.error("error"); } } public void deviceLogin(String uid, String token, String mac, String key, String value) { XPGWifiDevice d = null; for (int i = 0; i < xpgWifiDeviceList.size(); i++) { XPGWifiDevice device = xpgWifiDeviceList.get(i); if (device != null) { if (device != null && device.getMacAddress().equals(mac)) { d = device; break; } } } (d).login(uid, token); final XPGWifiDevice finalD = d; d.setListener(new XPGWifiDeviceListener() { @Override public void didLogin(XPGWifiDevice device, int result) { cWrite(finalD, key, value); } @Override public void didDeviceOnline(XPGWifiDevice device, boolean isOnline) { } @Override public void didDisconnected(XPGWifiDevice device) { } @Override public void didReceiveData(XPGWifiDevice device, java.util.concurrent.ConcurrentHashMap<String, Object> dataMap, int result) { } @Override public void didQueryHardwareInfo(XPGWifiDevice device, int result, java.util.concurrent.ConcurrentHashMap<String, String> hardwareInfo) { } }); } }
true
3e6e43ae9fd40346ea07bf22e41b610a9dfe4bb0
Java
18237257328/java_code
/็ฌฌ5็ซ ๅคš็บฟ็จ‹็š„ไพ‹้ข˜ไปฃ็ /1ๆ™ฎ้€š็š„ๅ•็บฟ็จ‹.java
UTF-8
324
3.140625
3
[]
no_license
package hello5; class MyThread{ public void run() { while(true) { System.out.println("MyThread็ฑป็š„runๆ–นๆณ•ๅœจ่ฟ่กŒ"); } } } public class Main{ public static void main(String[] args) { MyThread myThread = new MyThread(); myThread.run(); while(true) { System.out.println("mainๆ–นๆณ•ๅœจ่ฟ่กŒ"); } } }
true
1bed72eb87f01d2615b248c11ef0bfaf86377101
Java
nicknavin/Shaily
/app/src/main/java/com/app/session/activity/AddBriefCVActivity.java
UTF-8
41,130
1.539063
2
[]
no_license
package com.app.session.activity; import android.Manifest; import android.app.AlertDialog; import android.app.Dialog; import android.content.Context; import android.content.DialogInterface; import android.content.Intent; import android.database.Cursor; import android.graphics.Bitmap; import android.net.Uri; import android.os.Build; import android.os.Bundle; import android.os.Environment; import android.os.Handler; import android.provider.MediaStore; import android.provider.Settings; import android.text.Editable; import android.text.TextWatcher; import android.util.Base64; import android.util.Log; import android.view.Gravity; import android.view.View; import android.view.ViewGroup; import android.view.Window; import android.view.WindowManager; import android.widget.CheckBox; import android.widget.ImageView; import android.widget.LinearLayout; import android.widget.ProgressBar; import android.widget.RelativeLayout; import com.app.session.R; import com.app.session.adapter.TitleAddAdapter; import com.app.session.api.Urls; import com.app.session.base.BaseActivity; import com.app.session.customview.CircleImageView; import com.app.session.customview.CustomEditText; import com.app.session.customview.CustomTextView; import com.app.session.interfaces.ApiItemCallback; import com.app.session.interfaces.RequestCallback; import com.app.session.interfaces.ServiceResultReceiver; import com.app.session.data.model.Brief_CV; import com.app.session.data.model.TitleRef; import com.app.session.data.model.UpdateBriefReq; import com.app.session.data.model.User; import com.app.session.data.model.UserId; import com.app.session.data.model.UserLangauges; import com.app.session.data.model.UserRoot; import com.app.session.network.ApiClientNew; import com.app.session.network.ApiInterface; import com.app.session.network.BaseAsych; import com.app.session.service.CountingRequestBody; import com.app.session.service.FileUploadService; import com.app.session.thumby.MainActivitythumby; import com.app.session.thumbyjava.ThumbyUtils; import com.app.session.utility.Constant; import com.app.session.utility.PermissionsUtils; import com.app.session.utility.Utility; import com.app.session.utils.MIMEType; import com.squareup.picasso.Picasso; import com.theartofdev.edmodo.cropper.CropImage; import org.json.JSONArray; import org.json.JSONException; import org.json.JSONObject; import java.io.ByteArrayOutputStream; import java.io.File; import java.io.IOException; import java.util.ArrayList; import androidx.core.content.FileProvider; import androidx.recyclerview.widget.LinearLayoutManager; import androidx.recyclerview.widget.RecyclerView; import io.reactivex.FlowableEmitter; import okhttp3.MediaType; import okhttp3.MultipartBody; import okhttp3.RequestBody; import okhttp3.ResponseBody; import retrofit2.Call; import retrofit2.Callback; import retrofit2.Response; import static com.app.session.service.FileUploadService.FAIL; import static com.app.session.service.FileUploadService.SHOW_RESULT; import static com.app.session.service.FileUploadService.STATUS; import static com.app.session.thumby.ThumbyActivity.EXTRA_THUMBNAIL_POSITION; import static com.app.session.thumby.ThumbyActivity.EXTRA_URI; import static com.app.session.thumby.ThumbyActivity.VIDEO_PATH; import static com.app.session.utility.Utility.isConnectingToInternet; public class AddBriefCVActivity extends BaseActivity implements View.OnClickListener, ServiceResultReceiver.Receiver { CustomEditText edt_brief; CustomTextView txtUsercv, txtUserName_dilog, txtCvName, btn_update, txtSelectImagCover, txtSelectVideo, txtUploading; CircleImageView imgProfile_di; Context context; String imageUrl = "", language_cd = "",language_id = "", language_name = ""; int position = 0; private ArrayList<Brief_CV> brief_cvList = new ArrayList<>(); private ArrayList<Brief_CV> langList = new ArrayList<>(); ArrayList<Brief_CV> languageArrayList = new ArrayList<>(); ImageView img_flag; Brief_CV brief_cv_param; LinearLayout layUploadVideo; LinearLayout layVideothumb; private ServiceResultReceiver mServiceResultReceiver; String mFileName = ""; LinearLayout layPlayVideo, layImgVideoSelection; ImageView imgVideoThumb; Bitmap videoThumb, imgThumb; ImageView imgVideoCover; String videoUrl = "", PicturePath = ""; CheckBox checkDropSelection; private Dialog dialogSelect; public boolean isForCamera = false; private Uri mCameraImageUri, mImageCaptureUri; byte[] ByteArray; CustomEditText edit_specify_title; ArrayList<TitleRef> titleRefsList = new ArrayList<>(); String title_cd = "0", titleName = ""; LinearLayout layProgress; ProgressBar progressBar; Brief_CV brief_cv; /* A/c 100048577176 IFSC Code INDB0000878 Branch Name :- VIJAY NAGAR INDORE Bank name : Indusind bank*/ UpdateBriefReq updateBriefReq; String videoPath=""; File imageFile =null; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_add_brief_cv); context = this; position = getIntent().getIntExtra("POSITION", 0); if (getIntent().getParcelableExtra("DATA") != null) { brief_cv = getIntent().getParcelableExtra("DATA"); } initView(); updateView(brief_cv); } public void initView() { txtUploading = (CustomTextView) findViewById(R.id.txtUploading); edit_specify_title = (CustomEditText) findViewById(R.id.edit_specify_title); checkDropSelection = (CheckBox) findViewById(R.id.checkDropSelection); checkDropSelection.setOnClickListener(this); imgVideoCover = (ImageView) findViewById(R.id.imgVideoCover); imgVideoCover.setOnClickListener(this); layPlayVideo = (LinearLayout) findViewById(R.id.layPlayVideo); layImgVideoSelection = (LinearLayout) findViewById(R.id.layImgVideoSelection); layVideothumb = (LinearLayout) findViewById(R.id.layVideothumb); layProgress = (LinearLayout) findViewById(R.id.layProgress); progressBar = (ProgressBar) findViewById(R.id.progressBar); img_flag = (ImageView) findViewById(R.id.img_flag); imgVideoThumb = (ImageView) findViewById(R.id.imgVideoThumb); ((ImageView) findViewById(R.id.imgBack)).setOnClickListener(this); ((CustomTextView) findViewById(R.id.btn_update)).setOnClickListener(this); ((CustomTextView) findViewById(R.id.btn_cancel)).setOnClickListener(this); layUploadVideo = (LinearLayout) findViewById(R.id.layUploadVideo); layUploadVideo.setOnClickListener(this); edt_brief = (CustomEditText) findViewById(R.id.edt_cv); txtUserName_dilog = (CustomTextView) findViewById(R.id.txtUserName); txtUsercv = (CustomTextView) findViewById(R.id.txtUsercv); txtCvName = (CustomTextView) findViewById(R.id.txtCvName); txtSelectVideo = (CustomTextView) findViewById(R.id.txtSelectVideo); txtSelectVideo.setOnClickListener(this); txtSelectImagCover = (CustomTextView) findViewById(R.id.txtSelectImagCover); txtSelectImagCover.setOnClickListener(this); imgProfile_di = (CircleImageView) findViewById(R.id.imgProfile); edt_brief.addTextChangedListener(new TextWatcher() { @Override public void beforeTextChanged(CharSequence s, int start, int count, int after) { } @Override public void onTextChanged(CharSequence s, int start, int before, int count) { txtUsercv.setText("" + s); } @Override public void afterTextChanged(Editable s) { } }); // if (isConnectingToInternet(context)) { // getUserDetail(); // } } public void updateView(Brief_CV brief_cv) { if (brief_cv != null) { language_id=brief_cv.getLanguage_id().get_id(); language_cd = brief_cv.getLanguage_id().getCode(); mFileName = language_cd + "introduction.mp4"; edt_brief.setText(brief_cv.getBrief_cv()); edt_brief.setHint(context.getResources().getString(R.string.brief_cv_txt) +brief_cv.getLanguage_id().getName()); edt_brief.setSelection(brief_cv.getBrief_cv().length()); txtUsercv.setText(brief_cv.getBrief_cv()); txtCvName.setText("Bio " + brief_cv.getLanguage_id().getName()); edit_specify_title.setText(brief_cv.getTitle_name()); if (brief_cv.getVideo_thumbnail() != null && !brief_cv.getVideo_thumbnail().isEmpty()) { String url = Urls.BASE_IMAGES_URL + brief_cv.getVideo_thumbnail(); Picasso.with(context).load(url).placeholder(R.mipmap.profile_large).into(imgVideoCover); } if (brief_cv.getVideo_url() != null && !brief_cv.getVideo_url().isEmpty()) { videoUrl = Urls.BASE_IMAGES_URL + brief_cv.getVideo_url(); layVideothumb.setVisibility(View.VISIBLE); layUploadVideo.setVisibility(View.GONE); } else { layVideothumb.setVisibility(View.GONE); layUploadVideo.setVisibility(View.VISIBLE); } //getTitleRef(); } } @Override protected void onResume() { super.onResume(); } private int progressStatus = 0; public void initProgress(int value) { txtUploading.setText("" + value + "%" + "uploaded...Please wait"); layProgress.setVisibility(View.VISIBLE); progressBar.setProgress(value); } public void setBriefCV(final ArrayList<Brief_CV> list) { String lang_id = "", check_lang_id = ""; if (list.size() > 0) { for (int i = 0; i < list.size(); i++) { Brief_CV brief_cv = list.get(i); lang_id = brief_cv.getLanguage_id().getCode(); for (int j = 0; j < langList.size(); j++) { Brief_CV cv = langList.get(j); check_lang_id = cv.getLanguage_cd(); if (check_lang_id.equals(lang_id)) { langList.remove(cv); } } } } for (int j = 0; j < langList.size(); j++) { Brief_CV brief_cv = langList.get(j); list.add(brief_cv); } brief_cv_param = list.get(position); if (brief_cv_param.getBrief_cv() != null) { language_cd = brief_cv_param.getLanguage_cd(); mFileName = language_cd + "introduction.mp4"; edt_brief.setText(brief_cv_param.getBrief_cv()); edt_brief.setHint(context.getResources().getString(R.string.brief_cv_txt) + brief_cv_param.getNative_name()); edt_brief.setSelection(brief_cv_param.getBrief_cv().length()); txtUsercv.setText(brief_cv_param.getBrief_cv()); txtCvName.setText("Bio " + brief_cv_param.getNative_name()); edit_specify_title.setText(brief_cv_param.getTitle_name()); if (brief_cv_param.getVideo_thumbnail() != null && !brief_cv_param.getVideo_thumbnail().isEmpty()) { String url = Urls.BASE_IMAGES_URL + brief_cv_param.getVideo_thumbnail(); Picasso.with(context).load(url).placeholder(R.mipmap.profile_large).into(imgVideoCover); } if (brief_cv_param.getVideo_url() != null && !brief_cv_param.getVideo_url().isEmpty()) { videoUrl = Urls.BASE_IMAGES_URL + brief_cv_param.getVideo_url(); layVideothumb.setVisibility(View.VISIBLE); layUploadVideo.setVisibility(View.GONE); } else { layVideothumb.setVisibility(View.GONE); layUploadVideo.setVisibility(View.VISIBLE); } //getTitleRef(); } } private void callUpdateBriefCv() { if (isConnectingToInternet(context)) { showLoading(); ApiInterface apiInterface = ApiClientNew.getClient().create(ApiInterface.class); Call<ResponseBody> call= apiInterface.reqUpdateBriefCv(accessToken,updateBriefReq); call.enqueue(new Callback<ResponseBody>() { @Override public void onResponse(Call<ResponseBody> call, Response<ResponseBody> response) { dismiss_loading(); if(response.body()!=null) { try { ResponseBody root = response.body(); String data =root.string(); JSONObject object=new JSONObject(data); if(object.getInt("status")==200) { Intent intent = new Intent(); setResult(Constant.PAGE_REFRESH, intent); finish(); } System.out.println("ds"); } catch (IOException e) { e.printStackTrace(); } catch (JSONException e) { e.printStackTrace(); } } else { } } @Override public void onFailure(Call<ResponseBody> call, Throwable t) { dismiss_loading(); } }); } else { showInternetConnectionToast(); } } private void callUpdateBriefCvImage() { if (isConnectingToInternet(context)) { showLoading(); RequestBody usercd=RequestBody.create( MediaType.parse("text/plain"),userId); RequestBody languageId=RequestBody.create( MediaType.parse("text/plain"),language_id); MultipartBody.Part productimg= null; RequestBody requestfile=null; if (imageFile !=null) { requestfile=RequestBody.create(MediaType.parse("image/jpeg"),imageFile); productimg = MultipartBody.Part.createFormData("image",imageFile.getName(),requestfile); } ApiInterface apiInterface = ApiClientNew.getClient().create(ApiInterface.class); Call<ResponseBody> call= apiInterface.reqUpdateBriefThumbnail(accessToken,usercd,languageId,productimg); call.enqueue(new Callback<ResponseBody>() { @Override public void onResponse(Call<ResponseBody> call, Response<ResponseBody> response) { dismiss_loading(); if(response.body()!=null) { errorBody(response,true); try { ResponseBody responseBody=null; responseBody = response.errorBody(); if(responseBody!=null) { String data = responseBody.string(); System.out.println("error1" + data); JSONObject jsonObject = new JSONObject(data); if (jsonObject.getInt("status") == 200) { showToast(jsonObject.getString("message")); } } } catch (IOException e) { e.printStackTrace(); } catch (JSONException e) { e.printStackTrace(); } } else { errorBody(response,false); } } @Override public void onFailure(Call<ResponseBody> call, Throwable t) { } }); } else { showInternetConnectionToast(); } } private MultipartBody.Part createMultipartBody(String filePath, FlowableEmitter<Double> emitter) { File file = new File(filePath); return MultipartBody.Part.createFormData("image", mFileName, createCountingRequestBody(file, MIMEType.IMAGE.value, emitter)); } private RequestBody createCountingRequestBody(File file, String mimeType, final FlowableEmitter<Double> emitter) { RequestBody requestBody = createRequestBodyFromFile(file, mimeType); return new CountingRequestBody(requestBody, new CountingRequestBody.Listener() { @Override public void onRequestProgress(long bytesWritten, long contentLength) { double progress = (1.0 * bytesWritten) / contentLength; emitter.onNext(progress); } }); } private RequestBody createRequestBodyFromFile(File file, String mimeType) { return RequestBody.create(MediaType.parse(mimeType), file); } @Override public void onClick(View v) { Intent intent; switch (v.getId()) { case R.id.edit_specify_title: intent = new Intent(context, SearchAddTitleActivity.class); intent.putExtra("language_cd", language_cd); startActivityForResult(intent, Constant.REQUEST_RESULT); break; case R.id.checkDropSelection: if (checkDropSelection.isChecked()) { layImgVideoSelection.setVisibility(View.VISIBLE); } else { layImgVideoSelection.setVisibility(View.GONE); } break; case R.id.txtSelectImagCover: layImgVideoSelection.setVisibility(View.GONE); checkDropSelection.setChecked(false); dialog(); break; case R.id.imgTake_photo: layImgVideoSelection.setVisibility(View.GONE); checkDropSelection.setChecked(false); setCameraPermission(); isForCamera = true; if (dialogSelect != null && dialogSelect.isShowing()) dialogSelect.dismiss(); break; case R.id.imgTake_gallery: setGalleryPermission(); isForCamera = false; if (dialogSelect != null && dialogSelect.isShowing()) dialogSelect.dismiss(); break; case R.id.txtSelectVideo: callVideoFrameThumb(); break; case R.id.imgBack: onBackPressed(); break; case R.id.btn_cancel: onBackPressed(); break; case R.id.btn_update: if (isConnectingToInternet(context)) { // brief_cv_param.setBrief_cv(edt_brief.getText().toString()); // brief_cvList.set(position, brief_cv_param); updateBriefReq=new UpdateBriefReq(); updateBriefReq.setLanguage_id(language_id); updateBriefReq.setUserId(userId); updateBriefReq.setTitleName(edit_specify_title.getText().toString()); updateBriefReq.setBriefCv(edt_brief.getText().toString()); callUpdateBriefCv(); } else { showInternetPop(context); } break; case R.id.layUploadVideo: callVideoFrameThumb(); break; case R.id.imgVideoCover: //navin nimade comment if (!videoUrl.isEmpty() && videoUrl != null) { mlog("videoUrl "+videoUrl); intent = new Intent(context, VideoPlayerActivity.class); intent.putExtra("URL", videoUrl); startActivity(intent); } break; } } @Override public void onReceiveResult(int resultCode, Bundle resultData) { switch (resultCode) { case SHOW_RESULT: if (resultData != null) { initProgress(resultData.getInt("progress")); } break; case STATUS: layProgress.setVisibility(View.GONE); callUpdateBriefCvImage(); break; case FAIL: showToast("uploading is fail, please try again"); layProgress.setVisibility(View.GONE); break; } } public static final String RECEIVER = "receiver"; private static final String ACTION_DOWNLOAD = "action.DOWNLOAD_DATA"; private void callService(String path) { if (isConnectingToInternet(context)) { mServiceResultReceiver = new ServiceResultReceiver(new Handler()); mServiceResultReceiver.setReceiver(this); Intent mIntent = new Intent(this, FileUploadService.class); mIntent.putExtra("mFilePath", path); mIntent.putExtra("FileName", mFileName); mIntent.putExtra("LANGUAGE_ID", language_id); mIntent.putExtra("USER_ID", userId); mIntent.putExtra("TOKEN", accessToken); mIntent.putExtra(RECEIVER, mServiceResultReceiver); mIntent.setAction(ACTION_DOWNLOAD); FileUploadService.enqueueWork(context, mIntent); } else { showInternetConnectionToast(); } } public void callVideoFrameThumb() { Intent intent = new Intent(context, MainActivitythumby.class); startActivityForResult(intent, Constant.PICK_VIDEO_THUMB); } public String getPath(Uri uri) { String[] projection = {MediaStore.Video.Media.DATA}; Cursor cursor = getContentResolver().query(uri, projection, null, null, null); if (cursor != null) { // HERE YOU WILL GET A NULLPOINTER IF CURSOR IS NULL // THIS CAN BE, IF YOU USED OI FILE MANAGER FOR PICKING THE MEDIA int column_index = cursor .getColumnIndexOrThrow(MediaStore.Video.Media.DATA); cursor.moveToFirst(); return cursor.getString(column_index); } else return null; } public void dialog() { dialogSelect = new Dialog(context, R.style.MaterialDialogSheet); dialogSelect.requestWindowFeature(Window.FEATURE_NO_TITLE); dialogSelect.setContentView(R.layout.dialog_pick_image); dialogSelect.getWindow().setBackgroundDrawableResource(android.R.color.transparent); dialogSelect.getWindow().setGravity(Gravity.BOTTOM); WindowManager.LayoutParams lp = new WindowManager.LayoutParams(); Window window = dialogSelect.getWindow(); lp.copyFrom(window.getAttributes()); lp.width = WindowManager.LayoutParams.MATCH_PARENT; lp.height = WindowManager.LayoutParams.WRAP_CONTENT; window.setAttributes(lp); int i = Utility.getScreenWidth(this); ((ImageView) dialogSelect.findViewById(R.id.imgTake_photo)).setTranslationX(-i); ((ImageView) dialogSelect.findViewById(R.id.imgTake_gallery)).setTranslationX(-i); // ((View) dialogSelect.findViewById(R.id.view1)).setTranslationX(-i); // ((View) dialogSelect.findViewById(R.id.view2)).setTranslationX(-i); ((ImageView) dialogSelect.findViewById(R.id.imgTake_photo)).animate().translationX(0).setDuration(500).setStartDelay(400); // ((View) dialogSelect.findViewById(R.id.view1)).animate().translationX(0).setDuration(500).setStartDelay(500); ((ImageView) dialogSelect.findViewById(R.id.imgTake_gallery)).animate().translationX(0).setDuration(500).setStartDelay(600); // ((View) dialogSelect.findViewById(R.id.view2)).animate().translationX(0).setDuration(500).setStartDelay(700); ((ImageView) dialogSelect.findViewById(R.id.imgTake_photo)).setOnClickListener(this); ((ImageView) dialogSelect.findViewById(R.id.imgTake_gallery)).setOnClickListener(this); dialogSelect.show(); } public void TakePic() { try { isForCamera = true; Intent cameraIntent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE); File f = new File(Environment.getExternalStorageDirectory() + "/consultlot.png"); if (Build.VERSION.SDK_INT < Build.VERSION_CODES.LOLLIPOP) { mCameraImageUri = Uri.fromFile(f); } else { mCameraImageUri = FileProvider.getUriForFile(context, context.getApplicationContext().getPackageName() + ".provider", f); } cameraIntent.putExtra(MediaStore.EXTRA_OUTPUT, mCameraImageUri); cameraIntent.putExtra("return-data", true); startActivityForResult(cameraIntent, Constant.REQUEST_CODE_CAMERA); } catch (Exception e) { e.printStackTrace(); } } public void setCameraPermission() { if (Build.VERSION.SDK_INT >= PermissionsUtils.SDK_INT_MARSHMALLOW) { if (!PermissionsUtils.getInstance(context).isPermissionGranted(context, Manifest.permission.CAMERA, "Camera")) { return; } if (Build.VERSION.SDK_INT >= PermissionsUtils.SDK_INT_MARSHMALLOW) { if (!PermissionsUtils.getInstance(context).isPermissionGranted(context, Manifest.permission.WRITE_EXTERNAL_STORAGE, "Write External Storage")) { return; } } } TakePic(); } public void setGalleryPermission() { if (Build.VERSION.SDK_INT >= PermissionsUtils.SDK_INT_MARSHMALLOW) { if (!PermissionsUtils.getInstance(context).isPermissionGranted(context, Manifest.permission.READ_EXTERNAL_STORAGE, "Read External Storage")) { return; } } Gallery(); } //REQUEST_CODE_ALBUM public void Gallery() { if (Build.VERSION.SDK_INT < 19) { Intent intent = new Intent(Intent.ACTION_GET_CONTENT); intent.setType("image/*"); startActivityForResult(intent, Constant.REQUEST_CODE_ALBUM); } else { Intent i = new Intent(Intent.ACTION_PICK, MediaStore.Images.Media.EXTERNAL_CONTENT_URI); startActivityForResult(i, Constant.REQUEST_CODE_ALBUM); } } private void goToSettings() { Intent myAppSettings = new Intent(Settings.ACTION_APPLICATION_DETAILS_SETTINGS, Uri.parse("package:" + getPackageName())); myAppSettings.addCategory(Intent.CATEGORY_DEFAULT); myAppSettings.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK); startActivity(myAppSettings); } public void checkIfPermissionsGranted() { AlertDialog alertDialog; AlertDialog.Builder alertDialogBuilder = new AlertDialog.Builder(context); alertDialogBuilder.setMessage(getString(R.string.permission)); alertDialogBuilder.setPositiveButton("Settings", new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface arg0, int arg1) { goToSettings(); } }); alertDialogBuilder.setNegativeButton("Dismiss", new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) { } }); alertDialog = alertDialogBuilder.create(); alertDialog.show(); alertDialog.getButton(alertDialog.BUTTON_POSITIVE).setTextColor(getResources().getColor(R.color.colorPrimary)); alertDialog.getButton(alertDialog.BUTTON_NEGATIVE).setTextColor(getResources().getColor(R.color.colorPrimary)); } private void getTitleRef() { if (isInternetConnected()) { showLoading(); new BaseAsych(Urls.GET_TITLE_REF, getParamTitleReg(), new RequestCallback() { @Override public void onSuccess(JSONObject js, String success) { dismiss_loading(); try { JSONObject jsonObject = js.getJSONObject("result"); if (jsonObject.getString("rstatus").equals("1")) { titleRefsList = new ArrayList<>(); if (!js.isNull("title_reflist")) { JSONArray jsonArray = js.getJSONArray("title_reflist"); for (int i = 0; i < jsonArray.length(); i++) { JSONObject object = jsonArray.getJSONObject(i); TitleRef titleRef = new TitleRef(); titleRef.setLanguage_cd(object.getString("language_cd")); titleRef.setTitle_cd(object.getString("title_cd")); titleRef.setTitle_name(object.getString("title_name")); titleRefsList.add(titleRef); System.out.println("dsfsd" + titleRefsList.size()); } } } } catch (JSONException e) { e.printStackTrace(); } showToast(success); } @Override public void onFailed(JSONObject js, String failed, int status) { dismiss_loading(); showToast(failed); } @Override public void onNull(JSONObject js, String nullp) { dismiss_loading(); } @Override public void onException(JSONObject js, String exception) { dismiss_loading(); } }).execute(); } else { showInternetConnectionToast(); } } private String getParamTitleReg() { JSONObject jsonObject = new JSONObject(); try { jsonObject.put("language_cd", language_cd); return jsonObject.toString(); } catch (JSONException e) { e.printStackTrace(); } return ""; } public void callAddTitleDialog() { final Dialog dd = new Dialog(context); try { dd.getWindow().requestFeature(Window.FEATURE_NO_TITLE); dd.getWindow().setBackgroundDrawableResource(android.R.color.transparent); dd.setContentView(R.layout.dialog_add_title); dd.getWindow().setLayout(-1, -2); dd.getWindow().setLayout(RelativeLayout.LayoutParams.MATCH_PARENT, RelativeLayout.LayoutParams.WRAP_CONTENT); RecyclerView recyclerView = (RecyclerView) dd.findViewById(R.id.recyclerView); TitleAddAdapter titleAddAdapter = new TitleAddAdapter(context, titleRefsList, new ApiItemCallback() { @Override public void result(int x) { TitleRef titleRef = titleRefsList.get(x); title_cd = titleRef.getTitle_cd(); edit_specify_title.setText(titleRef.getTitle_name()); callAddTitleUpdate(titleRef.getTitle_name()); dd.dismiss(); } }); recyclerView.setLayoutManager(new LinearLayoutManager(context)); recyclerView.setAdapter(titleAddAdapter); if (titleRefsList.size() > 4) { ViewGroup.LayoutParams params = recyclerView.getLayoutParams(); params.height = 150; recyclerView.setLayoutParams(params); } ((CustomTextView) dd.findViewById(R.id.txtAddNewTitle)).setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { callAddNewTitleDialog(); dd.dismiss(); } }); dd.show(); } catch (Exception e) { e.printStackTrace(); // Log.d(TAG, "Exception: " + e.getMessage()); } } public void callAddNewTitleDialog() { final Dialog dd = new Dialog(context); try { dd.getWindow().requestFeature(Window.FEATURE_NO_TITLE); dd.getWindow().setBackgroundDrawableResource(android.R.color.transparent); dd.setContentView(R.layout.dialog_add_new_title); dd.getWindow().setLayout(-1, -2); dd.getWindow().setLayout(RelativeLayout.LayoutParams.MATCH_PARENT, RelativeLayout.LayoutParams.WRAP_CONTENT); CustomEditText editTitle = (CustomEditText) dd.findViewById(R.id.editTitle); ((CustomTextView) dd.findViewById(R.id.yes)).setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { String titleNew = editTitle.getText().toString(); if (!titleNew.isEmpty()) { callAddTitleUpdate(titleNew); //callAddNewCategory(languageCd, categoryNew); } else { editTitle.setError("please insert category"); } dd.dismiss(); } }); dd.show(); } catch (Exception e) { e.printStackTrace(); // Log.d(TAG, "Exception: " + e.getMessage()); } } private void callAddTitleUpdate(String titleName) { if (isInternetConnected()) { showLoading(); new BaseAsych(Urls.ADD_TITLE_REF, getParamAddTitle(titleName), new RequestCallback() { @Override public void onSuccess(JSONObject js, String success) { dismiss_loading(); try { JSONObject jsonObject = js.getJSONObject("result"); if (jsonObject.getString("rstatus").equals("1")) { } } catch (JSONException e) { e.printStackTrace(); } showToast(success); } @Override public void onFailed(JSONObject js, String failed, int status) { dismiss_loading(); showToast(failed); } @Override public void onNull(JSONObject js, String nullp) { dismiss_loading(); } @Override public void onException(JSONObject js, String exception) { dismiss_loading(); } }).execute(); } else { showInternetConnectionToast(); } } private String getParamAddTitle(String titleName) { JSONObject jsonObject = new JSONObject(); try { jsonObject.put("language_cd", language_cd); jsonObject.put("title_name", titleName); return jsonObject.toString(); } catch (JSONException e) { e.printStackTrace(); } return ""; } @Override protected void onActivityResult(int requestCode, int resultCode, Intent data) { super.onActivityResult(requestCode, resultCode, data); if (resultCode == RESULT_OK) { switch (requestCode) { case Constant.REQUEST_CODE_CAMERA: CropImage.activity(mCameraImageUri) .start(this); break; case Constant.REQUEST_CODE_ALBUM: try { mImageCaptureUri = data.getData(); CropImage.activity(mImageCaptureUri) .start(this); } catch (Exception e) { e.printStackTrace(); } break; case CropImage.CROP_IMAGE_ACTIVITY_REQUEST_CODE: CropImage.ActivityResult result = CropImage.getActivityResult(data); if (resultCode == RESULT_OK) { Uri resultUri = result.getUri(); try { ByteArray = null; Bitmap bm = MediaStore.Images.Media.getBitmap(context.getContentResolver(), resultUri); imgVideoCover.setImageBitmap(bm); try { imageFile =Utility.getFileByBitmap(context,bm,"thumb"); callUpdateBriefCvImage(); } catch (Exception e) { e.printStackTrace(); } // ByteArrayOutputStream datasecond = new ByteArrayOutputStream(); // bm.compress(Bitmap.CompressFormat.JPEG, 50, datasecond); // ByteArray = datasecond.toByteArray(); // String coverImg = base64String(datasecond.toByteArray()); // // callUploadImage(coverImg, language_cd + "_" + userId + "_thumbnail"); } catch (IOException e) { e.printStackTrace(); } } else if (resultCode == CropImage.CROP_IMAGE_ACTIVITY_RESULT_ERROR_CODE) { Exception error = result.getError(); } break; default: break; } } if (requestCode == Constant.REQUEST_CODE_ALBUM_Gallery) { if (data != null) { Uri contentURI = data.getData(); String selectedVideoPath = getPath(contentURI); callService(selectedVideoPath); Log.d("path", selectedVideoPath); } } if (requestCode == Constant.PICK_VIDEO_THUMB) { if (data != null) { long location = data.getLongExtra(EXTRA_THUMBNAIL_POSITION, 0); Uri uri = data.getParcelableExtra(EXTRA_URI); Bitmap bitmap = ThumbyUtils.getBitmapAtFrame(context, uri, location, 200, 200); imgVideoCover.setImageBitmap(bitmap); try { imageFile =Utility.getFileByBitmap(context,bitmap,"thumb"); } catch (Exception e) { e.printStackTrace(); } ByteArrayOutputStream datasecond = new ByteArrayOutputStream(); bitmap.compress(Bitmap.CompressFormat.PNG, 100, datasecond); byte[] ByteArray = datasecond.toByteArray(); String imgbase = base64String(ByteArray); String selectedVideoPath = data.getStringExtra(VIDEO_PATH); videoPath=selectedVideoPath; imgVideoThumb.setVisibility(View.GONE); //callUploadImage(imgbase, language_cd + "_" + userId + "_thumbnail"); callService(selectedVideoPath); } } if (requestCode == Constant.REQUEST_RESULT) { if (data != null) { String result = data.getStringExtra("result"); title_cd = data.getStringExtra("id"); edit_specify_title.setText(result); } } } private String base64String(byte[] b) { String imgString = Base64.encodeToString(b, Base64.NO_WRAP); System.out.println("imgString " + imgString); return imgString; } } /* * [21:23, 11/05/2020] Ratufa Pankaj: Sir actually my expectations for salary was more, but ashok sir always convey to me that he will increase the salary but he always increase the date that we will discuss it later and never increased my salary. [21:35, 11/05/2020] Ratufa Pankaj: I joined this company because of my friend tarun, he told me that we need you and we will give u a good salary and also time to time promotion but when i left old company and joined this one ashok sir told me that he will give me 38k and i got struck because of relationship and at that time i have no more option, but only because of good relationship with you i was working here. [21:38, 11/05/2020] Ratufa Pankaj: And at the time of joining i asked for 45k but he says that we will increment that but give some time, but that time never came sir after 1 year in incremented 6k.*/
true
a2871dda4901ff56b52c668248080d7e182fa06e
Java
jewelbao/JLib
/app/src/main/java/com/jewel/sample/AppUtilActivity.java
UTF-8
1,881
2.390625
2
[ "Apache-2.0" ]
permissive
package com.jewel.sample; import android.app.Activity; import android.os.Bundle; import android.support.annotation.Nullable; import android.support.v7.widget.RecyclerView; import com.jewel.lib.android.AppUtil; import com.jewel.lib.android.HandlerUtil; import com.jewel.lib.android.recyclerView.RecyclerViewUtil; import com.jewel.lib.android.recyclerView.SimpleAdapter; import com.jewel.lib.java.StringUtil; public class AppUtilActivity extends Activity { private SimpleAdapter<AppUtil.AppInfo> simpleAdapter; @Override protected void onCreate(@Nullable Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_list); RecyclerView recyclerView = findViewById(R.id.recyclerView); simpleAdapter = new SimpleAdapter<AppUtil.AppInfo>(R.layout.layout_application) { @Override public void bindView(SimpleViewHolder viewHolder, AppUtil.AppInfo data, int position) { viewHolder .setText(R.id.tv_name, data.isSystem() ? StringUtil.get(getApplicationContext(), R.string.system, data.getName()) : data.getName()) .setText(R.id.tv_install, data.getInstallLocation() == AppUtil.AppInfo.INSTALL_EXTERNAL ? R.string.external : R.string.internal) .setImageDrawable(R.id.iv_launcher, data.getLauncherIcon()); } }; RecyclerViewUtil.setupListView(recyclerView, simpleAdapter, android.R.color.darker_gray); HandlerUtil.runOnUiThreadDelay(new Runnable() { @Override public void run() { getData(); } }, 2000); } public void getData() { try { simpleAdapter.setData(AppUtil.getAppList(this)); } catch (Exception e) { e.printStackTrace(); } } }
true
20fbe96ef24f5d2c37300739d934c82f17ef0ab3
Java
amelieko/McDonalds-java
/sources/com/google/android/gms/maps/GoogleMapOptions.java
UTF-8
8,127
1.804688
2
[]
no_license
package com.google.android.gms.maps; import android.content.Context; import android.content.res.TypedArray; import android.os.Parcel; import android.util.AttributeSet; import com.google.android.gms.C2063R; import com.google.android.gms.common.internal.safeparcel.SafeParcelable; import com.google.android.gms.maps.internal.zza; import com.google.android.gms.maps.model.CameraPosition; public final class GoogleMapOptions implements SafeParcelable { public static final zza CREATOR = new zza(); private final int mVersionCode; private Boolean zzaZf; private Boolean zzaZg; private int zzaZh; private CameraPosition zzaZi; private Boolean zzaZj; private Boolean zzaZk; private Boolean zzaZl; private Boolean zzaZm; private Boolean zzaZn; private Boolean zzaZo; private Boolean zzaZp; private Boolean zzaZq; private Boolean zzaZr; public GoogleMapOptions() { this.zzaZh = -1; this.mVersionCode = 1; } GoogleMapOptions(int i, byte b, byte b2, int i2, CameraPosition cameraPosition, byte b3, byte b4, byte b5, byte b6, byte b7, byte b8, byte b9, byte b10, byte b11) { this.zzaZh = -1; this.mVersionCode = i; this.zzaZf = zza.zza(b); this.zzaZg = zza.zza(b2); this.zzaZh = i2; this.zzaZi = cameraPosition; this.zzaZj = zza.zza(b3); this.zzaZk = zza.zza(b4); this.zzaZl = zza.zza(b5); this.zzaZm = zza.zza(b6); this.zzaZn = zza.zza(b7); this.zzaZo = zza.zza(b8); this.zzaZp = zza.zza(b9); this.zzaZq = zza.zza(b10); this.zzaZr = zza.zza(b11); } public static GoogleMapOptions createFromAttributes(Context context, AttributeSet attributeSet) { if (attributeSet == null) { return null; } TypedArray obtainAttributes = context.getResources().obtainAttributes(attributeSet, C2063R.styleable.MapAttrs); GoogleMapOptions googleMapOptions = new GoogleMapOptions(); if (obtainAttributes.hasValue(C2063R.styleable.MapAttrs_mapType)) { googleMapOptions.mapType(obtainAttributes.getInt(C2063R.styleable.MapAttrs_mapType, -1)); } if (obtainAttributes.hasValue(C2063R.styleable.MapAttrs_zOrderOnTop)) { googleMapOptions.zOrderOnTop(obtainAttributes.getBoolean(C2063R.styleable.MapAttrs_zOrderOnTop, false)); } if (obtainAttributes.hasValue(C2063R.styleable.MapAttrs_useViewLifecycle)) { googleMapOptions.useViewLifecycleInFragment(obtainAttributes.getBoolean(C2063R.styleable.MapAttrs_useViewLifecycle, false)); } if (obtainAttributes.hasValue(C2063R.styleable.MapAttrs_uiCompass)) { googleMapOptions.compassEnabled(obtainAttributes.getBoolean(C2063R.styleable.MapAttrs_uiCompass, true)); } if (obtainAttributes.hasValue(C2063R.styleable.MapAttrs_uiRotateGestures)) { googleMapOptions.rotateGesturesEnabled(obtainAttributes.getBoolean(C2063R.styleable.MapAttrs_uiRotateGestures, true)); } if (obtainAttributes.hasValue(C2063R.styleable.MapAttrs_uiScrollGestures)) { googleMapOptions.scrollGesturesEnabled(obtainAttributes.getBoolean(C2063R.styleable.MapAttrs_uiScrollGestures, true)); } if (obtainAttributes.hasValue(C2063R.styleable.MapAttrs_uiTiltGestures)) { googleMapOptions.tiltGesturesEnabled(obtainAttributes.getBoolean(C2063R.styleable.MapAttrs_uiTiltGestures, true)); } if (obtainAttributes.hasValue(C2063R.styleable.MapAttrs_uiZoomGestures)) { googleMapOptions.zoomGesturesEnabled(obtainAttributes.getBoolean(C2063R.styleable.MapAttrs_uiZoomGestures, true)); } if (obtainAttributes.hasValue(C2063R.styleable.MapAttrs_uiZoomControls)) { googleMapOptions.zoomControlsEnabled(obtainAttributes.getBoolean(C2063R.styleable.MapAttrs_uiZoomControls, true)); } if (obtainAttributes.hasValue(C2063R.styleable.MapAttrs_liteMode)) { googleMapOptions.liteMode(obtainAttributes.getBoolean(C2063R.styleable.MapAttrs_liteMode, false)); } if (obtainAttributes.hasValue(C2063R.styleable.MapAttrs_uiMapToolbar)) { googleMapOptions.mapToolbarEnabled(obtainAttributes.getBoolean(C2063R.styleable.MapAttrs_uiMapToolbar, true)); } if (obtainAttributes.hasValue(C2063R.styleable.MapAttrs_ambientEnabled)) { googleMapOptions.ambientEnabled(obtainAttributes.getBoolean(C2063R.styleable.MapAttrs_ambientEnabled, false)); } googleMapOptions.camera(CameraPosition.createFromAttributes(context, attributeSet)); obtainAttributes.recycle(); return googleMapOptions; } public GoogleMapOptions ambientEnabled(boolean z) { this.zzaZr = Boolean.valueOf(z); return this; } public GoogleMapOptions camera(CameraPosition cameraPosition) { this.zzaZi = cameraPosition; return this; } public GoogleMapOptions compassEnabled(boolean z) { this.zzaZk = Boolean.valueOf(z); return this; } public int describeContents() { return 0; } public CameraPosition getCamera() { return this.zzaZi; } public int getMapType() { return this.zzaZh; } /* Access modifiers changed, original: 0000 */ public int getVersionCode() { return this.mVersionCode; } public GoogleMapOptions liteMode(boolean z) { this.zzaZp = Boolean.valueOf(z); return this; } public GoogleMapOptions mapToolbarEnabled(boolean z) { this.zzaZq = Boolean.valueOf(z); return this; } public GoogleMapOptions mapType(int i) { this.zzaZh = i; return this; } public GoogleMapOptions rotateGesturesEnabled(boolean z) { this.zzaZo = Boolean.valueOf(z); return this; } public GoogleMapOptions scrollGesturesEnabled(boolean z) { this.zzaZl = Boolean.valueOf(z); return this; } public GoogleMapOptions tiltGesturesEnabled(boolean z) { this.zzaZn = Boolean.valueOf(z); return this; } public GoogleMapOptions useViewLifecycleInFragment(boolean z) { this.zzaZg = Boolean.valueOf(z); return this; } public void writeToParcel(Parcel parcel, int i) { zza.zza(this, parcel, i); } public GoogleMapOptions zOrderOnTop(boolean z) { this.zzaZf = Boolean.valueOf(z); return this; } public GoogleMapOptions zoomControlsEnabled(boolean z) { this.zzaZj = Boolean.valueOf(z); return this; } public GoogleMapOptions zoomGesturesEnabled(boolean z) { this.zzaZm = Boolean.valueOf(z); return this; } /* Access modifiers changed, original: 0000 */ public byte zzDA() { return zza.zze(this.zzaZo); } /* Access modifiers changed, original: 0000 */ public byte zzDB() { return zza.zze(this.zzaZp); } /* Access modifiers changed, original: 0000 */ public byte zzDC() { return zza.zze(this.zzaZq); } /* Access modifiers changed, original: 0000 */ public byte zzDD() { return zza.zze(this.zzaZr); } /* Access modifiers changed, original: 0000 */ public byte zzDt() { return zza.zze(this.zzaZf); } /* Access modifiers changed, original: 0000 */ public byte zzDu() { return zza.zze(this.zzaZg); } /* Access modifiers changed, original: 0000 */ public byte zzDv() { return zza.zze(this.zzaZj); } /* Access modifiers changed, original: 0000 */ public byte zzDw() { return zza.zze(this.zzaZk); } /* Access modifiers changed, original: 0000 */ public byte zzDx() { return zza.zze(this.zzaZl); } /* Access modifiers changed, original: 0000 */ public byte zzDy() { return zza.zze(this.zzaZm); } /* Access modifiers changed, original: 0000 */ public byte zzDz() { return zza.zze(this.zzaZn); } }
true
fbee4d1935a66c1a40e3901146e8a8da84c36aa2
Java
jcmatase/vacations-manager
/back-end/src/main/java/com/vacationManager/VacationManagerAPI/service/VacationServiceImpl.java
UTF-8
1,040
2.265625
2
[]
no_license
package com.vacationManager.VacationManagerAPI.service; import java.util.List; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; import com.vacationManager.VacationManagerAPI.domain.Vacation; import com.vacationManager.VacationManagerAPI.repositories.VacationRepository; @Service public class VacationServiceImpl implements VacationService { @Autowired VacationRepository vacationRepository; @Override public List<Vacation> findAll() { return vacationRepository.findAll(); } @Override public List<Vacation> findByMonthAndYear(String month, int year) { return vacationRepository.findByMonthAndYear(month, year); } @Override public void saveOrUpdateVacation(Vacation vacation) { vacationRepository.save(vacation); } @Override public void deleteVacation(String id) { vacationRepository.delete(id); } @Override public List<Vacation> findByYear(int year) { return vacationRepository.findByYear(year); } }
true
3894b67584296ef8842d3ef48d870db189b501ad
Java
raoravik/herospin
/app/src/main/java/com/visa/r4r/poc/herospin/customview/BezierView.java
UTF-8
10,187
2.078125
2
[]
no_license
/* * Copyright (c) 2016. Ravi Rao. * * This file is created as part of VISA POC and 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.visa.r4r.poc.herospin.customview; import android.animation.Animator; import android.animation.TimeInterpolator; import android.annotation.TargetApi; import android.content.Context; import android.graphics.Canvas; import android.graphics.Color; import android.graphics.Paint; import android.graphics.Path; import android.os.Build; import android.support.v4.view.ViewCompat; import android.util.AttributeSet; import android.util.DisplayMetrics; import android.view.View; import android.view.WindowManager; import java.util.ArrayList; import java.util.List; /** * @author LiYanZhao * @date 16-3-19 ไธŠๅˆ10:50 */ public class BezierView extends View implements DataAnimationListener { public static final int TYPE_ONE = 1; public static final int TYPE_SECOND = 2; public static final int TYPE_THIRD = 3; public List<Point> line = new ArrayList<>(); private Paint paint = new Paint(); private Path path = new Path(); private DataAnimation dataAnimation; public static final int ANIMATION_DURATION = 400; private int screenHeight; float screenWidth = 780f; public static final float RANGE = 200f; private int lineColor = Color.parseColor("#E1E8F8"); private static final float LINE_SMOOTHNESS = 0.16f; private float baseLine = 0; //ๆจชๅ‘ๅŸบๅ‡†็บฟ private DataAnimationListener mDataAnimationListener; public BezierView(Context context) { super(context); init(); } public BezierView(Context context, AttributeSet attrs) { super(context, attrs); init(); } public BezierView(Context context, AttributeSet attrs, int defStyleAttr) { super(context, attrs, defStyleAttr); init(); } @TargetApi(Build.VERSION_CODES.LOLLIPOP) public BezierView(Context context, AttributeSet attrs, int defStyleAttr, int defStyleRes) { super(context, attrs, defStyleAttr, defStyleRes); init(); } public void init(){ paint.setAntiAlias(true); paint.setStyle(Paint.Style.STROKE); paint.setStrokeCap(Paint.Cap.ROUND); paint.setStrokeWidth(3); paint.setColor(lineColor); dataAnimation = new DataAnimation(); dataAnimation.setDataAnimationListener(this); WindowManager wm = (WindowManager) this.getContext().getSystemService(Context.WINDOW_SERVICE); DisplayMetrics metrics = new DisplayMetrics(); wm.getDefaultDisplay().getMetrics(metrics); screenHeight = metrics.heightPixels; screenWidth = metrics.widthPixels; line = getLevelLine(); } @Override public void draw(Canvas canvas) { super.draw(canvas); drawBesizer(canvas); } public void drawBesizer(Canvas canvas){ float prePreviousPointX = Float.NaN; float prePreviousPointY = Float.NaN; float previousPointX = Float.NaN; float previousPointY = Float.NaN; float currentPointX = Float.NaN; float currentPointY = Float.NaN; float nextPointX = Float.NaN; float nextPointY = Float.NaN; for(int index = 0; index < line.size(); index++){ if(Float.isNaN(currentPointX)){ Point point = line.get(index); currentPointX = point.getX(); currentPointY = point.getY() + baseLine; } if(Float.isNaN(previousPointX)){ if(index > 0){ Point point = line.get(index - 1); previousPointX = point.getX(); previousPointY = point.getY() + baseLine; }else{ previousPointX = currentPointX; previousPointY = currentPointY; } } if(Float.isNaN(prePreviousPointX)){ if(index > 1){ Point point = line.get(index - 2); prePreviousPointX = point.getX(); prePreviousPointY = point.getY() + baseLine; }else{ prePreviousPointX = previousPointX; prePreviousPointY = previousPointY; } } if(index < line.size() - 1){ Point point = line.get(index + 1); nextPointX = point.getX(); nextPointY = point.getY() + baseLine; }else{ nextPointX = currentPointX; nextPointY = currentPointY; } if(index == 0){ path.moveTo(currentPointX,currentPointY); }else{ final float firstDiffX = (currentPointX - prePreviousPointX); final float firstDiffY = (currentPointY - prePreviousPointY); final float secondDiffX = (nextPointX - previousPointX); final float secondDiffY = (nextPointY - previousPointY); final float firstControlPointX = previousPointX + (LINE_SMOOTHNESS * firstDiffX); final float firstControlPointY = previousPointY + (LINE_SMOOTHNESS * firstDiffY); final float secondControlPointX = currentPointX - (LINE_SMOOTHNESS * secondDiffX); final float secondControlPointY = currentPointY - (LINE_SMOOTHNESS * secondDiffY); path.cubicTo(firstControlPointX, firstControlPointY, secondControlPointX, secondControlPointY, currentPointX, currentPointY); } prePreviousPointX = previousPointX; prePreviousPointY = previousPointY; previousPointX = currentPointX; previousPointY = currentPointY; currentPointX = nextPointX; currentPointY = nextPointY; } canvas.drawPath(path, paint); path.lineTo(line.get(line.size() - 1).getX(), screenHeight); path.lineTo(line.get(0).getX(), screenHeight); path.close(); paint.setColor(Color.WHITE); paint.setStyle(Paint.Style.FILL); //paint.setAlpha(64); canvas.drawPath(path, paint); paint.setStyle(Paint.Style.STROKE); path.reset(); } public void switchLine(int type){ switchLine(type,ANIMATION_DURATION); } /** * ๅˆ‡ๆขๆ›ฒ็บฟ */ public void switchLine(int type,int duration){ List<Point> newLine; switch (type){ case TYPE_SECOND: newLine = getBottomLine(); break; case TYPE_THIRD: newLine = getUpLine(); break; default: newLine = getLevelLine(); break; } if(newLine.size() != line.size()){ line = newLine; ViewCompat.postInvalidateOnAnimation(this); return; } for(int i = 0; i < newLine.size(); i++){ Point point = newLine.get(i); line.get(i).setTarget(point.getX(),point.getY()); } dataAnimation.startAnimation(duration); } public void setInterpolator(TimeInterpolator interpolator){ dataAnimation.setInterpolator(interpolator); } public void setStartDelay(long startDelay){ dataAnimation.setStartDelay(startDelay); } private List<Point> getBottomLine(){ List<Point> line = new ArrayList<>(); line.add(new Point(0.0f,RANGE / 5)); line.add(new Point(screenWidth /4,0f)); line.add(new Point(screenWidth /2,RANGE / 2)); line.add(new Point(screenWidth /4*3,RANGE)); line.add(new Point(screenWidth,RANGE / 5 * 4 )); return line; } private List<Point> getUpLine(){ List<Point> line = new ArrayList<>(); line.add(new Point(0.0f,0f)); line.add(new Point(screenWidth /4,RANGE)); line.add(new Point(screenWidth /8 * 5,RANGE/3*2)); line.add(new Point(screenWidth /10*8.5f,RANGE / 10 * 9)); line.add(new Point(screenWidth,RANGE / 5 * 3)); return line; } private List<Point> getLevelLine(){ List<Point> line = new ArrayList<>(); line.add(new Point(0.0f,0f)); line.add(new Point(screenWidth /4,0f)); line.add(new Point(screenWidth /8 * 5,0f)); line.add(new Point(screenWidth /10*8.5f,0f)); line.add(new Point(screenWidth,0f)); return line; } @Override public void onAnimationUpdate(float scale) { for(Point point : line){ point.update(scale); } ViewCompat.postInvalidateOnAnimation(this); } @Override public void onAnimationFinish() { for(Point point : line){ point.finish(); } ViewCompat.postInvalidateOnAnimation(this); if(mDataAnimationListener != null){ mDataAnimationListener.onAnimationFinish(); } } @Override public void onAnimationStart(Animator animation) { if(mDataAnimationListener != null){ mDataAnimationListener.onAnimationStart(animation); } } public float getBaseLine() { return baseLine; } public void setBaseLine(float baseLine) { this.baseLine = baseLine; ViewCompat.postInvalidateOnAnimation(this); } public DataAnimationListener getDataAnimationListener() { return mDataAnimationListener; } public void setDataAnimationListener(DataAnimationListener mDataAnimationListener) { this.mDataAnimationListener = mDataAnimationListener; } }
true
5f2eb49f531e30e7b520999974554a7d8604e04a
Java
consulo/consulo-groovy
/groovy-impl/src/main/java/org/jetbrains/plugins/groovy/impl/refactoring/rename/RenameGrAccessorProcessor.java
UTF-8
2,399
1.648438
2
[ "Apache-2.0" ]
permissive
/* * Copyright 2000-2011 JetBrains s.r.o. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.jetbrains.plugins.groovy.impl.refactoring.rename; import com.intellij.java.impl.refactoring.rename.RenameJavaMethodProcessor; import com.intellij.java.language.psi.PsiField; import com.intellij.java.language.psi.PsiMethod; import consulo.content.scope.SearchScope; import consulo.language.editor.refactoring.event.RefactoringElementListener; import consulo.language.psi.PsiElement; import consulo.language.util.IncorrectOperationException; import consulo.usage.UsageInfo; import org.jetbrains.plugins.groovy.lang.psi.api.statements.typedef.members.GrAccessorMethod; import org.jetbrains.plugins.groovy.lang.psi.util.GroovyPropertyUtils; import javax.annotation.Nonnull; import javax.annotation.Nullable; import java.util.Map; import static org.jetbrains.plugins.groovy.lang.psi.util.GroovyPropertyUtils.isSimplePropertyAccessor; /** * @author Maxim.Medvedev */ public class RenameGrAccessorProcessor extends RenameJavaMethodProcessor { @Override public boolean canProcessElement(@Nonnull PsiElement element) { return element instanceof PsiMethod && !(element instanceof GrAccessorMethod) && isSimplePropertyAccessor((PsiMethod)element); } @Override public void renameElement(PsiElement psiElement, String newName, UsageInfo[] usages, @Nullable RefactoringElementListener listener) throws IncorrectOperationException { } @Override public void prepareRenaming(PsiElement element, String newName, Map<PsiElement, String> allRenames, SearchScope scope) { super.prepareRenaming(element, newName, allRenames, scope); final PsiField field = GroovyPropertyUtils.findFieldForAccessor((PsiMethod)element, false); if (field != null) { } } }
true
5bc574a578fb3907b207e49515588fa3b2ce948f
Java
melges-morgen/fitgraph
/src/main/java/ru/fitgraph/rest/elements/DateParameter.java
UTF-8
914
2.5
2
[ "MIT" ]
permissive
package ru.fitgraph.rest.elements; import javax.ws.rs.WebApplicationException; import javax.ws.rs.core.Response; import java.text.ParseException; import java.text.SimpleDateFormat; import java.util.Date; /** * Created by melges on 19.01.15. */ public class DateParameter { private static final SimpleDateFormat dateTimeFormat = new SimpleDateFormat("dd.MM.yyyy HH:mm:ss"); private Date date; public DateParameter() { this.date = new Date(); } public DateParameter(String date) { try { this.date = dateTimeFormat.parse(date); } catch (ParseException e) { throw new WebApplicationException(Response .status(Response.Status.BAD_REQUEST) .entity(new ErrorResponse("InvalidParameterException", e.getLocalizedMessage())).build()); } } public Date getDate() { return date; } }
true
2b8cf023e493dab05b6961cd89e2692dbe8cd4df
Java
karanp2302/ZestMoneyAutomationAssignment
/src/main/java/com/zest/qa/pages/HomePage.java
UTF-8
4,349
2.578125
3
[]
no_license
package com.zest.qa.pages; import java.net.SocketOption; import java.util.ArrayList; import java.util.concurrent.TimeUnit; import org.openqa.selenium.WebElement; import org.openqa.selenium.support.FindBy; import org.openqa.selenium.support.PageFactory; import org.openqa.selenium.support.ui.WebDriverWait; import com.zest.qa.base.TestBase; public class HomePage extends TestBase{ public static String AmazonPrice; public static String FlipkartPrice; public static int FinalAmazonPrice,FinalFlipkartPrice; //Page factory - OR(Object Repository) of Amazon @FindBy(name="field-keywords") WebElement searchProductInAmazon; @FindBy(xpath="//input[@type='submit']") WebElement clickSearchBtInAmazon; @FindBy(xpath="//*[@id=\"search\"]/div[1]/div[2]/div/span[4]/div[1]/div[1]/div/span/div/div/div[2]/div[2]/div/div[1]/div/div/div[1]/h2/a/span") WebElement selectProductInAmazon; @FindBy(xpath="//*[@id=\"priceblock_ourprice\"]") WebElement getPriceInAmazon; //Page factory - OR(Object Repository) of Flipkart @FindBy(xpath="/html/body/div[2]/div/div/button") WebElement cancelLoginInFlipkart; @FindBy(className="LM6RPg") WebElement searchProductInFlipkart; @FindBy(className="vh79eN") WebElement clickSearchBtnInFlipkart; @FindBy(className="_3wU53n") WebElement selectProductInFlipkart; @FindBy(xpath="//*[@id=\"container\"]/div/div[3]/div[2]/div[1]/div[2]/div[2]/div/div[3]/div[1]/div/div[1]") WebElement getPriceInFlipkart; public HomePage() { PageFactory.initElements(driver, this); } public void searchProductGetPriceInAmazon(String sp) throws InterruptedException { driver.get(prop.getProperty("urlAmazon")); searchProductInAmazon.sendKeys(sp); clickSearchBtInAmazon.click(); selectProductInAmazon.click(); ArrayList<String> newTab = new ArrayList<String>(driver.getWindowHandles()); System.out.println(newTab.size()); Thread.sleep(5000); //Switch from one window to another driver.switchTo().window(newTab.get(1)); driver.manage().timeouts().implicitlyWait(300, TimeUnit.SECONDS); AmazonPrice=getPriceInAmazon.getText(); //Using StringBuilder to eliminate the special characters from received price String str = AmazonPrice; str= str.substring(0, str.indexOf(".")); int QuePos = str.indexOf("?"); String res1 = removeByIndex(str, QuePos + 1); res1=res1.replaceAll("[?.,]",""); res1=res1.replaceAll("\\s", ""); //Converting retrieved string value to int FinalAmazonPrice=Integer.parseInt(res1); System.out.println("Amazon Price for iPhone XR (64GB)-Yellow:" + FinalAmazonPrice); } public void searchProductAndPriceInFlipkart(String sp) throws InterruptedException { driver.get(prop.getProperty("urlFlipkart")); cancelLoginInFlipkart.click(); searchProductInFlipkart.sendKeys(sp); clickSearchBtnInFlipkart.click(); selectProductInFlipkart.click(); ArrayList<String> childTab = new ArrayList<String>(driver.getWindowHandles()); driver.switchTo().window(childTab.get(1)); Thread.sleep(5000); WebDriverWait wait = new WebDriverWait(driver, 500); FlipkartPrice=getPriceInFlipkart.getText(); //Using StringBuilder to eliminate the special characters from received price String str = FlipkartPrice; int QuePos = str.indexOf("?"); String res1 = removeByIndex(str, QuePos + 1); res1=res1.replaceAll("[?.,]",""); FinalFlipkartPrice=Integer.parseInt(res1); System.out.println("Flipkart Price for iPhone XR (64GB)-Yellow:" + FinalFlipkartPrice); } //Comparing received prices from Amazon and Flipkart public void comparePrice() { if( FinalAmazonPrice < FinalFlipkartPrice) { System.out.println("Amazon Offers lesser price then flipkart at Rs" + FinalAmazonPrice); }else { System.out.println("Flipkart Offers lesser price then Amazon at Rs" + FinalFlipkartPrice); } } //Method to remove special characters using StringBuilder private static String removeByIndex(String str, int index) { return new StringBuilder(str).deleteCharAt(index).toString(); } }
true
924ad96676922bcce74a697c6d6d459c7b6704ac
Java
verdure0448/hdac-java-sdk
/src/main/java/com/hdactech/object/PreviousTx.java
UTF-8
1,223
2.3125
2
[]
no_license
package com.hdactech.object; /** * @author Justin * */ public class PreviousTx { private String txid; private long vout; private String scriptPubKey; private String redeemScript; private boolean cache; public PreviousTx(String txid, long vout, String scriptPubKey, String redeemScript, boolean cache) { super(); this.txid = txid; this.vout = vout; this.scriptPubKey = scriptPubKey; this.redeemScript = redeemScript; this.cache = cache; } public String getTxid() { return txid; } public void setTxid(String txid) { this.txid = txid; } public long getVout() { return vout; } public void setVout(long vout) { this.vout = vout; } public String getScriptPubKey() { return scriptPubKey; } public void setScriptPubKey(String scriptPubKey) { this.scriptPubKey = scriptPubKey; } public String getRedeemScript() { return redeemScript; } public void setRedeemScript(String redeemScript) { this.redeemScript = redeemScript; } /** * @return the cache */ public boolean isCache() { return cache; } /** * @param cache the cache to set */ public void setCache(boolean cache) { this.cache = cache; } }
true
9ef77f167bac8199a025b25d5e40cbf49d24502c
Java
dipeshji/javaWorkSpace
/HibernateWorkSpace/Relationships/src/com/almirahclothsdelete/Almirah.java
UTF-8
720
2.171875
2
[]
no_license
package com.almirahclothsdelete; import java.util.Set; public class Almirah { private Integer aId; private String aName; private Set children; /** * @return the aId */ public Integer getaId() { return aId; } /** * @param aId the aId to set */ public void setaId(Integer aId) { this.aId = aId; } /** * @return the aName */ public String getaName() { return aName; } /** * @param aName the aName to set */ public void setaName(String aName) { this.aName = aName; } /** * @return the children */ public Set getChildren() { return children; } /** * @param children the children to set */ public void setChildren(Set children) { this.children = children; } }
true
fe3d84664d9d7a9d06049f896070c18499e49409
Java
psiphon/geometry
/src/main/java/com/sportdataconnect/geometry/Triangle2D.java
UTF-8
2,531
3.09375
3
[ "Apache-2.0" ]
permissive
package com.sportdataconnect.geometry; import com.google.common.collect.ImmutableList; import java.util.List; import org.apache.logging.log4j.LogManager; import org.apache.logging.log4j.Logger; /** * Representation of a 2D triangle that also implements Polygon2D * * @author sportdataconnect */ public final class Triangle2D implements Polygon2D { private Point2D pt1; private Point2D pt2; private Point2D pt3; private ImmutableList<Triangle2D> thisAsList = null; public Triangle2D(final Point2D pt1, final Point2D pt2, final Point2D pt3) { this.pt1 = pt1; this.pt2 = pt2; this.pt3 = pt3; } public Point2D getPt1() { return pt1; } public Point2D getPt2() { return pt2; } public Point2D getPt3() { return pt3; } public Point2D get(final int ix) { switch (ix) { case 0: return pt1; case 1: return pt2; case 2: return pt3; default: throw new IndexOutOfBoundsException("Expected point index of 0..2 but encountered " + ix); } } public int numPoints() { return 3; } public List<Triangle2D> toTriangles() { if (thisAsList == null) { thisAsList = ImmutableList.of(this); } return thisAsList; } /** * Returns whether or not the point is contained withing the triangle * * @param pt * @return Returns whether or not the point is contained withing the triangle */ public boolean contains(final Point2D pt) { Point2D ab = pt2.subtract(pt1); Point2D bc = pt3.subtract(pt2); Point2D ca = pt1.subtract(pt3); Point2D ap = pt.subtract(pt1); Point2D bp = pt.subtract(pt2); Point2D cp = pt.subtract(pt3); double cpa = ab.crossProduct(ap); double cpb = bc.crossProduct(bp); double cpc = ca.crossProduct(cp); if (cpa < 0 && cpb < 0 && cpc < 0) { return true; } else { return (cpa > 0 && cpb > 0 && cpc > 0); } } public Bounds2D getBounds() { double minX = Math.min(pt1.getX(), Math.min(pt2.getX(), pt3.getX())); double minY = Math.min(pt1.getY(), Math.min(pt2.getY(), pt3.getY())); double maxX = Math.max(pt1.getX(), Math.max(pt2.getX(), pt3.getX())); double maxY = Math.max(pt1.getY(), Math.max(pt2.getY(), pt3.getY())); return new Bounds2D(minX, maxX, minY, maxY); } }
true
4dd13c3fce290c7e96964ba1aca954ed339452e2
Java
3353144974/project1
/SE-day02/src/operation/As2_2/Test8.java
UTF-8
820
3.125
3
[]
no_license
package operation.As2_2; public class Test8 { public static int xzt(int[] arr){ int[] answer={'A','D','B','C','D'}; int fens=0; for (int i = 0; i < answer.length; i++) { if(answer[i]==arr[i]){ fens+=2; } } return fens; } public static void main(String[] args) { int[] xm={'D','C','B','A','D'}; int[] xo={'A','D','B','C','D'}; int[] xh={'A','D','B','C','A'}; int[] xq={'A','B','C','D','D'}; System.out.println("ๆปกๅˆ†10ๅˆ†๏ผŒๅฐๆ˜Ž:ๅพ—ๅˆ†:"+xzt(xm)+"ๅˆ†"); System.out.println("ๆปกๅˆ†10ๅˆ†๏ผŒๅฐ็บข:ๅพ—ๅˆ†:"+xzt(xo)+"ๅˆ†"); System.out.println("ๆปกๅˆ†10ๅˆ†๏ผŒๅฐ้ป„:ๅพ—ๅˆ†:"+xzt(xh)+"ๅˆ†"); System.out.println("ๆปกๅˆ†10ๅˆ†๏ผŒๅฐๅผบ:ๅพ—ๅˆ†:"+xzt(xq)+"ๅˆ†"); } }
true
4a9c293a5ef0346a9d65d0b0b6c7cb57d162667f
Java
IamFonky/colab
/colab-api/src/main/java/ch/colabproject/colab/api/model/user/LocalAccount.java
UTF-8
8,241
2.21875
2
[ "MIT" ]
permissive
/* * The coLAB project * Copyright (C) 2021 AlbaSim, MEI, HEIG-VD, HES-SO * * Licensed under the MIT License */ package ch.colabproject.colab.api.model.user; import ch.colabproject.colab.api.Helper; import ch.colabproject.colab.api.exceptions.ColabMergeException; import ch.colabproject.colab.api.model.ColabEntity; import javax.json.bind.annotation.JsonbTransient; import javax.persistence.Column; import javax.persistence.Entity; import javax.persistence.EnumType; import javax.persistence.Enumerated; import javax.persistence.Index; import javax.persistence.NamedQuery; import javax.persistence.Table; import javax.validation.constraints.NotNull; /** * Password based authentication. * * @author maxence */ @Entity @NamedQuery(name = "LocalAccount.findByEmail", query = "SELECT a from LocalAccount a where a.email = :email") @Table( indexes = { @Index(columnList = "email", unique = true) }) public class LocalAccount extends Account { private static final long serialVersionUID = 1L; /** * username-like email address */ @NotNull private String email; /** * salt+password hash. Hashed with currentDbHashMethod and dbSalt. */ @JsonbTransient @NotNull private byte[] hashedPassword; /** * Has the email address been verified with a VerificationToken ? */ @NotNull private Boolean verified; /** * Salt to used before hashing the password */ @JsonbTransient @NotNull private byte[] dbSalt; /** * Hash method to use to hashedPassword the salt+password */ @Column(length = 100) @Enumerated(value = EnumType.STRING) @JsonbTransient @NotNull private HashMethod currentDbHashMethod; /** * New hash method to use to hash the salt+password. If not null, rotate hash method on next * successful authentication */ @Column(length = 100) @Enumerated(value = EnumType.STRING) @JsonbTransient private HashMethod nextDbHashMethod; /** * Salt the client shall use to before hashing its password. Salt is hex-encoded byte array */ @NotNull @JsonbTransient private String clientSalt; /** * New salt the client shall use to prefix its password before hashing it. * <p> * In case this is not null, client shall send two hashes. First one is the plain_password * prefixed with clientSalt and hashed with currentClientHashMethod (to authenticate), second is * its password prefixed with this new salt and hashed with nextClientHashMethod if set, current * otherwise. successful authentication (to rotate salt and/or method) */ @JsonbTransient private String newClientSalt; /** * Hash method the client shall use to hashedPassword the clientSalt+plain_password */ @Column(length = 100) @Enumerated(value = EnumType.STRING) @NotNull @JsonbTransient private HashMethod currentClientHashMethod; /** * New hash method the client shall use to hash its clientSalt+plain_password. * <p> * In case this is not null, client shall send two hashes. First one is its plain_password * prefixed clientSalt and hashed with currentClientHashMethod (to authenticate), second is its * password prefixed with the new_salt (if set)or the current salt and hashed with this method */ @Column(length = 100) @Enumerated(value = EnumType.STRING) @JsonbTransient private HashMethod nextClientHashMethod; /** * * @return email associated with this account */ public String getEmail() { return email; } /** * update email. If the email is not the same, this account will not be verified any longer * * @param email new email to use. */ public void setEmail(String email) { if (Helper.isEmailAddress(email)) { if (!email.equals(this.email)) { this.verified = false; } this.email = email; } } /** * get the stored hashedPassword to challenge authentication against * * @return hashedPassword hashedPassword to challenge authentication against */ public byte[] getHashedPassword() { return hashedPassword; } /** * Update hashedPassword * * @param hashedPassword new hashedPassword */ public void setHashedPassword(byte[] hashedPassword) { this.hashedPassword = hashedPassword; } /** * has the email address been verified ? * * @return true if the account is verified */ public Boolean isVerified() { return verified; } /** * Set if the account has been verified or not * * @param verified yes or no ? */ public void setVerified(Boolean verified) { this.verified = verified; } /** * @return the salt to used server-side */ public byte[] getDbSalt() { return dbSalt; } /** * Update the server-side hashedPassword * * @param dbSalt new server-side salt */ public void setDbSalt(byte[] dbSalt) { this.dbSalt = dbSalt; } /** * * @return the current hashedPassword method to used to hashedPassword provided password */ public HashMethod getCurrentDbHashMethod() { return currentDbHashMethod; } /** * Set the method to use to hashedPassword provided password * * @param currentDbHashMethod hashedPassword method */ public void setCurrentDbHashMethod(HashMethod currentDbHashMethod) { this.currentDbHashMethod = currentDbHashMethod; } /** * @return the next hashedPassword method to use. If not null, hashedPassword methods will be * rotated on next authentication */ public HashMethod getNextDbHashMethod() { return nextDbHashMethod; } /** * change the next hashedPassword method to used * * @param nextDbHashMethod next hashedPassword method */ public void setNextDbHashMethod(HashMethod nextDbHashMethod) { this.nextDbHashMethod = nextDbHashMethod; } /** * @return the salt the user shall use before client-side plain_password hashedPassword */ public String getClientSalt() { return clientSalt; } /** * Update the salt the client shall use * * @param clientSalt client salt */ public void setClientSalt(String clientSalt) { this.clientSalt = clientSalt; } /** * @return the salt to use to rotate authentication */ public String getNewClientSalt() { return newClientSalt; } /** * set a next client-side salt * * @param newClientSalt new salt we want the client to use */ public void setNewClientSalt(String newClientSalt) { this.newClientSalt = newClientSalt; } /** * @return the hashedPassword method the client shall use to hashedPassword its * salt+plain_password */ public HashMethod getCurrentClientHashMethod() { return currentClientHashMethod; } /** * CHange hashedPassword method the client shall use * * @param currentClientHashMethod hashedPassword method the client shall use */ public void setCurrentClientHashMethod(HashMethod currentClientHashMethod) { this.currentClientHashMethod = currentClientHashMethod; } /** * @return the next hashedPassword method the client shall use */ public HashMethod getNextClientHashMethod() { return nextClientHashMethod; } /** * Update the next client-side hashedPassword method * * @param nextClientHashMethod new next client hashedPassword method */ public void setNextClientHashMethod(HashMethod nextClientHashMethod) { this.nextClientHashMethod = nextClientHashMethod; } @Override public void merge(ColabEntity other) throws ColabMergeException { // TODO } @Override public String toString() { return "LocalAccount{" + "id=" + this.getId() + ", email=" + email + ", verified=" + verified + '}'; } }
true
5c5c763514490ca0c7e6f42a9e10888817bb590e
Java
ifnul/ums-backend
/is-lnu-rest-api/src/main/java/org/lnu/is/web/rest/controller/timeperiod/TimePeriodController.java
UTF-8
3,589
2.21875
2
[ "Apache-2.0" ]
permissive
package org.lnu.is.web.rest.controller.timeperiod; import javax.annotation.Resource; import javax.validation.Valid; import org.lnu.is.annotations.Limit; import org.lnu.is.facade.facade.Facade; import org.lnu.is.resource.message.MessageResource; import org.lnu.is.resource.message.MessageType; import org.lnu.is.resource.search.PagedRequest; import org.lnu.is.resource.search.PagedResultResource; import org.lnu.is.resource.timeperiod.TimePeriodResource; import org.lnu.is.web.rest.constant.Request; import org.lnu.is.web.rest.controller.BaseController; import org.lnu.is.web.rest.controller.CrudController; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.http.HttpStatus; import org.springframework.web.bind.annotation.PathVariable; import org.springframework.web.bind.annotation.RequestBody; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestMethod; import org.springframework.web.bind.annotation.ResponseStatus; import org.springframework.web.bind.annotation.RestController; import com.wordnik.swagger.annotations.Api; import com.wordnik.swagger.annotations.ApiOperation; /** * Time Period Controller. * @author ivanursul * */ @RestController @RequestMapping("/timeperiods") @Api("Time Periods") public class TimePeriodController extends BaseController implements CrudController<TimePeriodResource, TimePeriodResource> { private static final Logger LOG = LoggerFactory.getLogger(TimePeriodController.class); @Resource(name = "timePeriodFacade") private Facade<TimePeriodResource, TimePeriodResource, Long> facade; @Override @ResponseStatus(HttpStatus.CREATED) @RequestMapping(method = RequestMethod.POST) @ApiOperation(value = "Create Person") public TimePeriodResource createResource(@Valid @RequestBody final TimePeriodResource resource) { LOG.info("Creating timePeriod: {}", resource); return facade.createResource(resource); } @Override @ResponseStatus(HttpStatus.OK) @RequestMapping(value = Request.ID, method = RequestMethod.PUT) @ApiOperation(value = "Update TimePeriod") public MessageResource updateResource(@PathVariable("id") final Long id, @Valid @RequestBody final TimePeriodResource resource) { LOG.info("Updating timePeriod with id: {}, {}", id, resource); facade.updateResource(id, resource); return new MessageResource(MessageType.INFO, "TimePeriod Updated"); } @Override @ResponseStatus(HttpStatus.OK) @RequestMapping(value = Request.ID, method = RequestMethod.GET) @ApiOperation(value = "Get TimePeriod by id") public TimePeriodResource getResource(@PathVariable("id") final Long id) { LOG.info("Retrieving timePeriod with id: {}", id); return facade.getResource(id); } @Override @ResponseStatus(HttpStatus.NO_CONTENT) @RequestMapping(value = Request.ID, method = RequestMethod.DELETE) @ApiOperation(value = "Delete TimePeriod") public MessageResource removeResource(@PathVariable("id") final Long id) { LOG.info("Removing timePeriod with id: {}", id); facade.removeResource(id); return new MessageResource(MessageType.INFO, "TimePeriod removed"); } @Override @ResponseStatus(HttpStatus.OK) @RequestMapping(method = RequestMethod.GET) @ApiOperation(value = "Get Time Periods") public PagedResultResource<TimePeriodResource> getPagedResource(@Limit(defaultValue = "38") final PagedRequest<TimePeriodResource> request) { LOG.info("Getting Paged Result of enrolment subject with offset: {}, limit: {}", request.getOffset(), request.getLimit()); return facade.getResources(request); } }
true
2d92024f52fc3be9e5283a8ed1a12e08b37e71bc
Java
subes/DockingFrames
/docking-frames-common/testing/bibliothek/test/inspect/CControlDockStationsInspectable.java
UTF-8
1,004
2.4375
2
[]
no_license
package bibliothek.test.inspect; import java.util.List; import bibliothek.gui.dock.common.CControl; import bibliothek.gui.dock.common.CStation; import bibliothek.test.Inspect; import bibliothek.test.Inspectable; import bibliothek.test.InspectionGraph; public class CControlDockStationsInspectable implements Inspectable{ private CControl control; public CControlDockStationsInspectable( CControl control ){ this.control = control; } public Inspect inspect( InspectionGraph graph ){ return new DefaultInspect( graph ) { private int size = 0; public boolean update(){ setName( "Stations" ); setValue( control.getRegister() ); int count = 0; List<CStation<?>> stations = control.getStations(); for( CStation<?> station : stations ){ put( String.valueOf( count++ ), station.getUniqueId(), station.getStation() ); } while( size > count ){ remove( String.valueOf( --size ) ); } size = count; return true; } }; } }
true
ae2803f7826de09e5832d214095d991fda1e63a5
Java
jianghe314/Demo
/app/src/main/java/com/kangzhan/student/School/Edu/Edu_Training_Stu.java
UTF-8
7,006
1.757813
2
[]
no_license
package com.kangzhan.student.School.Edu; import android.content.Intent; import android.os.Handler; import android.os.Message; import android.support.v7.app.ActionBar; import android.support.v7.app.AppCompatActivity; import android.os.Bundle; import android.support.v7.widget.LinearLayoutManager; import android.support.v7.widget.Toolbar; import android.util.Log; import android.view.LayoutInflater; import android.view.MenuItem; import com.google.gson.Gson; import com.holenzhou.pullrecyclerview.PullRecyclerView; import com.holenzhou.pullrecyclerview.layoutmanager.XLinearLayoutManager; import com.kangzhan.student.Debug.mLog; import com.kangzhan.student.R; import com.kangzhan.student.School.Adapter.TrainingAdapter; import com.kangzhan.student.School.Bean.TrainingStu; import com.kangzhan.student.ShowUI.mToast; import com.kangzhan.student.ShowUI.showMessage; import com.kangzhan.student.ShowUI.showProgress; import com.kangzhan.student.com.BaseActivity; import com.kangzhan.student.mInterface.SchoolInterface.school; import com.yanzhenjie.nohttp.NoHttp; import com.yanzhenjie.nohttp.RequestMethod; import com.yanzhenjie.nohttp.rest.OnResponseListener; import com.yanzhenjie.nohttp.rest.Request; import com.yanzhenjie.nohttp.rest.RequestQueue; import com.yanzhenjie.nohttp.rest.Response; import org.json.JSONArray; import org.json.JSONException; import org.json.JSONObject; import java.util.ArrayList; public class Edu_Training_Stu extends BaseActivity { private PullRecyclerView recycler; private TrainingAdapter adapter; private String Id,mmsg; private ArrayList<TrainingStu> data=new ArrayList<>(); private Gson gson; private Handler handler=new Handler(){ @Override public void handleMessage(Message msg) { switch (msg.what){ case 1111: runOnUiThread(new Runnable() { @Override public void run() { recycler.stopRefresh(); adapter.notifyDataSetChanged(); } }); break; case 2222: runOnUiThread(new Runnable() { @Override public void run() { recycler.stopRefresh(); mToast.showText(getApplicationContext(),"ๅŠ ่ฝฝๅคฑ่ดฅ"); } }); break; case 3333: runOnUiThread(new Runnable() { @Override public void run() { recycler.stopRefresh(); mToast.showText(getApplicationContext(),"ๆฒกๆœ‰ๆ•ฐๆฎ"); } }); break; case 9999: runOnUiThread(new Runnable() { @Override public void run() { recycler.stopRefresh(); showMessage.showMsg(Edu_Training_Stu.this,"็ฝ‘็ปœ่ฟžๆŽฅๅผ‚ๅธธ๏ผŒ่ฏทๆฃ€ๆŸฅ็ฝ‘็ปœ่ฟžๆŽฅ"); } }); break; } } }; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_edu__training__stu); Toolbar toolbar= (Toolbar) findViewById(R.id.school_training_stu); setSupportActionBar(toolbar); ActionBar actionBar=getSupportActionBar(); if(actionBar!=null){ actionBar.setDisplayHomeAsUpEnabled(true); } Intent getData=getIntent(); Id=getData.getStringExtra("Id"); gson=new Gson(); initView(); } private void initView() { adapter=new TrainingAdapter(Edu_Training_Stu.this,R.layout.item_fragment_edu_training_stu,data); recycler= (PullRecyclerView) findViewById(R.id.fragment_school_edu_training_stu_recycler); recycler.setAdapter(adapter); recycler.setEmptyView(LayoutInflater.from(this).inflate(R.layout.item_no_data,null)); recycler.setLayoutManager(new XLinearLayoutManager(this, LinearLayoutManager.VERTICAL,false)); recycler.setColorSchemeResources(R.color.swipe_color1,R.color.swipe_color2,R.color.swipe_color3); recycler.enablePullRefresh(true); //่ฎพ็ฝฎๅฏไปฅไธ‹ๆ‹‰ recycler.enableLoadMore(true); recycler.setOnRecyclerRefreshListener(new PullRecyclerView.OnRecyclerRefreshListener() { @Override public void onPullRefresh() { new Thread(new Runnable() { @Override public void run() { sendRequest(); } }).start(); } @Override public void onLoadMore() { recycler.stopLoadMore(); } }); recycler.postRefreshing(); } private void sendRequest() { Request<JSONObject> request=NoHttp.createJsonObjectRequest(school.EduTeacherDetail(), RequestMethod.GET); request.add("key",school.schoolKey(getApplicationContext())); request.add("coach_id",Id); getRequestQueue().add(1, request, new OnResponseListener<JSONObject>() { @Override public void onStart(int what) { } @Override public void onSucceed(int what, Response<JSONObject> response) { try { JSONObject object=new JSONObject(response.get().toString()); mLog.e("response","->"+response.get().toString()); if(object.getString("code").equals("200")){ JSONArray array=new JSONArray(object.getString("student")); if(array.length()>0){ data.clear(); for (int i = 0; i <array.length(); i++) { TrainingStu stu=gson.fromJson(array.getJSONObject(i).toString(),TrainingStu.class); data.add(stu); handler.sendEmptyMessage(1111); } }else { data.clear(); handler.sendEmptyMessage(3333); } }else { handler.sendEmptyMessage(2222); } } catch (JSONException e) { e.printStackTrace(); } } @Override public void onFailed(int what, Response<JSONObject> response) { handler.sendEmptyMessage(9999); } @Override public void onFinish(int what) { } }); } }
true
71247e161669dbabe2f68fa66ff1755b4a90778a
Java
karthickvel21/string-repo
/Assignments/src/findchariName/CharinName.java
UTF-8
282
2.515625
3
[]
no_license
package findchariName; public class CharinName { public static void main(String[] args) { String name="karthick a Aa"; String cName=name.replaceAll("[^a]", "".trim()); System.out.println("count is:"+cName); System.out.println("Number of a in your name:"+cName.length()); } }
true
f19bb0d5f277b4f6f6cc7e7d9d9729dd75a7c1af
Java
vaibhav1seth/ITrack
/app/src/main/java/com/example/vaibhav/itrack/MainActivity.java
UTF-8
1,418
2.140625
2
[ "Apache-2.0" ]
permissive
package com.example.vaibhav.itrack; import android.content.Intent; import android.support.v7.app.AppCompatActivity; import android.os.Bundle; import android.view.View; import android.widget.ImageButton; public class MainActivity extends AppCompatActivity { private ImageButton admin; private ImageButton studentbtn; private ImageButton faculty; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); admin = (ImageButton)findViewById(R.id.admin); faculty = (ImageButton)findViewById(R.id.teacher); studentbtn = (ImageButton)findViewById(R.id.student); admin.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { startActivity(new Intent(MainActivity.this,Admin.class)); } }); faculty.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { startActivity(new Intent(MainActivity.this, FacultyActivity.class)); } }); studentbtn.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { startActivity(new Intent(MainActivity.this,StudentActivity.class)); } }); } }
true
db031fec2ae2a29f7a1531e8d68ca8c4f7796af7
Java
mry1/LoadingView
/app/src/main/java/com/liuyi/ResourceUtils.java
UTF-8
2,412
2.421875
2
[]
no_license
package com.liuyi; import android.content.Context; import android.content.res.Resources; import android.util.DisplayMetrics; import android.util.Log; import android.view.WindowManager; import com.liuyi.loadingview.R; import java.lang.reflect.Field; public class ResourceUtils { /** * ่Žทๅ–ๅ›พ็‰‡ๅ็งฐ่Žทๅ–ๅ›พ็‰‡็š„่ต„ๆบid็š„ๆ–นๆณ• * * @param imageName * @return */ public static int getResourceId(Context ctx, String imageName) { int resId = ctx.getResources().getIdentifier(imageName, "drawable", ctx.getPackageName()); return resId; } /** * ่Žทๅ–ๅ›พ็‰‡ๅ็งฐ่Žทๅ–ๅ›พ็‰‡็š„่ต„ๆบid็š„ๆ–นๆณ• * * @param imageName * @param defaultId ่Žทๅ–ๅคฑ่ดฅๆ—ถ้ป˜่ฎค็š„่ต„ๆบid * @return */ public static int getResourceIdByReflect(String imageName, int defaultId) { Class drawable = R.drawable.class; Field field = null; int r_id; try { field = drawable.getField(imageName); r_id = field.getInt(field.getName()); } catch (Exception e) { // r_id = R.drawable.b_nothing; r_id = defaultId; Log.e("ERROR", "PICTURE NOTใ€€FOUND๏ผ"); } return r_id; } /** * ๆ นๆฎ่ต„ๆบid่Žทๅ–ๆ–‡ไปถๅ * * @param context * @param resid * @return */ public static String getResourceName(Context context, int resid) { return context.getResources().getResourceName(resid); } public static int getScreenWidth(Context context) { // WindowManager manager = context.getWindowManager(); // DisplayMetrics outMetrics = new DisplayMetrics(); // manager.getDefaultDisplay().getMetrics(outMetrics); // int width = outMetrics.widthPixels; // int height = outMetrics.heightPixels; Resources resources = context.getResources(); DisplayMetrics dm = resources.getDisplayMetrics(); float density = dm.density; int width = dm.widthPixels; int height = dm.heightPixels; return width; } public static int getScreenHeight(Context context) { Resources resources = context.getResources(); DisplayMetrics dm = resources.getDisplayMetrics(); float density = dm.density; int width = dm.widthPixels; int height = dm.heightPixels; return height; } }
true
db65d924d6dde5a83552b3937b800111a1d5685d
Java
myliwenbo/Springboot
/springboot-integrate/springboot-validation/avlidation-test/src/main/java/vip/xjdai/avlidationtest/controller/ValidatedController.java
UTF-8
1,273
2.078125
2
[]
no_license
package vip.xjdai.avlidationtest.controller; import org.springframework.validation.annotation.Validated; import org.springframework.web.bind.annotation.RequestBody; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RestController; import vip.xjdai.avlidationtest.model.pojo.BasePOJO; import vip.xjdai.avlidationtest.model.pojo.UserPOJO; @RestController @RequestMapping("differenceValidatedController") public class ValidatedController { /** * ๆทปๅŠ ็š„ๆ—ถๅ€™ID ๅ’Œๅ็งฐๆฏ•็ฉฟ * * @param userPOJO * @return */ @RequestMapping("add") public UserPOJO add(@RequestBody @Validated({BasePOJO.Add.class}) UserPOJO userPOJO) { return userPOJO; } /** * ไฟฎๆ”น็š„ๆ—ถๅ€™๏ผŒๅช้œ€่ฆไผ ้€’ID ๅณๅฏ * * @param userPOJO * @return */ @RequestMapping("update") public UserPOJO update(@RequestBody @Validated({BasePOJO.Update.class}) UserPOJO userPOJO) { return userPOJO; } /** * ไธไฝฟ็”จๅˆ†็ป„๏ผŒๆ‰€ๆœ‰ๆ•ฐๆฎ้ƒฝ่ฟ›่กŒๆ ก้ชŒ * * @param userPOJO * @return */ @RequestMapping("delete") public UserPOJO delete(@RequestBody @Validated UserPOJO userPOJO) { return userPOJO; } }
true
a695e5a3c356589550bc993c493cf6d5d81138fc
Java
rashmi-pallavi/ValidationExample
/Rashmi Pallavi(118555)/src/ques3/RentalApplication.java
UTF-8
970
3.140625
3
[]
no_license
package ques3; import java.util.Scanner; public class RentalApplication { public static void main(String[] args) { ChennaiRentals cr = new ChennaiRentals(); Items i =null; int key=0; int days=0; int quantity=0; Scanner s = new Scanner(System.in); do{ System.out.println("Enter the serial number:"); System.out.println("1. Fan"); System.out.println("2. Furnitures"); System.out.println("3. AC"); System.out.println("4. Vessels"); System.out.println("5. Exit"); key= s.nextInt(); System.out.println("Enter the no of days:"); days=s.nextInt(); System.out.println("Enter the quantity of item required:"); quantity=s.nextInt(); if(key<4){ i= cr.getSerialNum(key); cr.printDetails(i,days,quantity); } else if(key== 5) System.out.print("Thanks for visiting!"); else System.out.println("Invalid choice!"); }while(key<=5); s.close(); } }
true
434cf551a559f747290cd68301ae679a419d1435
Java
treasure-data/digdag
/digdag-standards/src/main/java/io/digdag/standards/td/TdConfigSecretStore.java
UTF-8
2,152
1.992188
2
[ "EPL-1.0", "Classpath-exception-2.0", "MIT", "LGPL-2.0-or-later", "MPL-2.0", "LGPL-2.1-only", "GPL-2.0-only", "Apache-2.0" ]
permissive
package io.digdag.standards.td; import com.google.common.base.Optional; import com.google.common.collect.ImmutableMap; import com.google.inject.Inject; import com.treasuredata.client.ProxyConfig; import com.treasuredata.client.TDClientConfig; import io.digdag.spi.SecretAccessContext; import io.digdag.spi.SecretStore; import javax.annotation.Nullable; import java.util.Map; class TdConfigSecretStore implements SecretStore { private final Map<String, String> secrets; private final boolean enabled = Boolean.parseBoolean(System.getProperty("io.digdag.standards.td.secrets.enabled", "true")); @Inject public TdConfigSecretStore(@Nullable TDClientConfig clientConfig) { this.secrets = (!enabled || clientConfig == null) ? ImmutableMap.of() : secrets(clientConfig); } private static ImmutableMap<String, String> secrets(TDClientConfig clientConfig) { ImmutableMap.Builder<String, String> secrets = ImmutableMap.builder(); secrets.put("td.endpoint", clientConfig.endpoint); if (clientConfig.apiKey.isPresent()) { secrets.put("td.apikey", clientConfig.apiKey.get()); } secrets.put("td.use_ssl", String.valueOf(clientConfig.useSSL)); secrets.put("td.proxy.enabled", String.valueOf(clientConfig.proxy.isPresent())); if (clientConfig.proxy.isPresent()) { ProxyConfig proxy = clientConfig.proxy.get(); secrets.put("td.proxy.host", proxy.getHost()); secrets.put("td.proxy.port", String.valueOf(proxy.getPort())); Optional<String> user = proxy.getUser(); if (user.isPresent()) { secrets.put("td.proxy.user", user.get()); } Optional<String> password = proxy.getPassword(); if (password.isPresent()) { secrets.put("td.proxy.password", password.get()); } } return secrets.build(); } @Override public Optional<String> getSecret(int projectId, String scope, String key) { return Optional.fromNullable(secrets.get(key)); } }
true
0b043e5c3960c1972a4de87a2dad71d462cc4217
Java
Emmptee/dounat
/Pandora/app/src/main/java/com/donut/app/mvp/BasePresenterImpl.java
UTF-8
3,633
1.96875
2
[]
no_license
package com.donut.app.mvp; import android.support.annotation.UiThread; import android.util.Log; import android.util.SparseArray; import com.android.volley.manager.LoadController; import com.android.volley.manager.RequestManager; import com.donut.app.R; import com.donut.app.http.HeaderRequest; import com.donut.app.http.SendNetRequestManager; import com.donut.app.http.message.BaseResponse; import com.donut.app.http.message.shakestar.MyLikeResponse; import com.donut.app.http.message.wish.CommendLikeRequest; import com.donut.app.utils.JsonUtils; import com.donut.app.utils.L; import java.util.Map; /** * Created by Qi on 2017/3/16. * Description : <br> */ public abstract class BasePresenterImpl<V extends BaseView> implements BasePresenter<V>, RequestManager.RequestListener { private static final String TAG = "BasePresenterImpl"; protected V mView; private boolean showLoadingView; private SparseArray<LoadController> mSparseArray = new SparseArray<>(); protected static final String COMMON_SUCCESS = "0000";// ่ฏทๆฑ‚ๆˆๅŠŸ private static final String COMMON_NOT_LOGIN = "0002";// ๆœช็™ปๅฝ• @Override public void attachView(V view) { mView = view; } @Override public void detachView() { mView = null; } public void loadData(Object request, final String header, final int requestCode, final boolean showLoadingView) { this.showLoadingView = showLoadingView; SendNetRequestManager requestManager = new SendNetRequestManager(this); LoadController loadController = requestManager.sendNetRequest(request, header, requestCode); mSparseArray.put(requestCode, loadController); } @Override public void cancelLoad() { if (mSparseArray.size() > 0) { for (int i = 0; i < mSparseArray.size(); i++) { LoadController controller = mSparseArray.valueAt(i); if (controller != null) { controller.cancel(); } } } } protected void showToast(String message) { mView.showToastMsg(message); } protected void showToast(int messageRes) { mView.showToastMsg(messageRes); } @UiThread @Override public void onRequest() { if (showLoadingView) { mView.showLoadingDialog(); showLoadingView = false; } } @Override public void onLoading(long total, long count, String filePath) { } @Override @UiThread public void onSuccess(String response, Map<String, String> headers, String url, int actionId) { L.i("====", response); if (mView == null) { return; } mView.dismissLoadingDialog(); mSparseArray.delete(actionId); BaseResponse res = JsonUtils.fromJson(response, BaseResponse.class); if (res != null && COMMON_NOT_LOGIN.equals(res.getCode())) { showToast(R.string.login_timeout_msg); mView.expiresToken(); return; } onSuccess(response, url, actionId); } @UiThread @Override public void onError(String errorMsg, String url, int actionId) { mView.dismissLoadingDialog(); mSparseArray.delete(actionId); showToast(R.string.connect_failuer_toast); } public abstract void onSuccess(String responseJson, String url, int actionId); }
true
8b24778ff06ad33d2dbac6e1e4684f7f973da1c8
Java
skyone5/springboot-api-and-vue-admin
/springboot-web/src/main/java/com/sicy/system/controller/MenuController.java
UTF-8
3,420
2.0625
2
[]
no_license
package com.sicy.system.controller; import com.alibaba.fastjson.JSONObject; import com.sicy.common.ReturnMsg; import com.sicy.common.interceptor.RequestUtils; import com.sicy.system.service.AuthService; import com.sicy.system.service.MenuService; import com.sicy.system.vo.MenuVo; import com.sicy.system.vo.User; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.util.StringUtils; import org.springframework.web.bind.annotation.PostMapping; import org.springframework.web.bind.annotation.RequestBody; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RestController; import java.util.List; import java.util.Map; /** * ่œๅ•ๆŽงๅˆถๅฑ‚ * * @author github.com/sicy * @version 1.0 * <p/> * <br/> * <br/>ไฟฎ่ฎขไบบ ไฟฎ่ฎขๆ—ถ้—ด ๆ่ฟฐไฟกๆฏ * <br/>----------------------------------------------------- * <br/>github.com/sicy 2017/11/11 ๅˆๅง‹ๅˆ›ๅปบ */ @RestController @RequestMapping("/api/menu") public class MenuController { private static final String SYMBOL = ","; @Autowired private MenuService menuService; @Autowired private AuthService authService; @PostMapping("/save") public ReturnMsg save(@RequestBody MenuVo vo) { return menuService.saveMenu(vo); } @PostMapping("/delete") public ReturnMsg delete(@RequestBody JSONObject req) { int id = req.getIntValue("id"); return menuService.deleteMenu(id); } @PostMapping("/update") public ReturnMsg update(@RequestBody MenuVo vo) { return menuService.updateMenu(vo); } @PostMapping("/query") public ReturnMsg query(@RequestBody JSONObject req) { MenuVo menu = new MenuVo(); Integer level = req.getInteger("level"); if(level != null){ menu.setLevel(level); } Integer fid = req.getInteger("fid"); if (fid != null && fid != -1) { menu.setFid(fid); } return new ReturnMsg(true, "", menuService.queryByCondition(menu)); } @SuppressWarnings("unchecked") @PostMapping("/queryForLogin") public ReturnMsg queryForLogin() { User user = RequestUtils.getSessionAttribte(User.SYS_LOGIN_INFO); int userId = user.getId(); int groupId = user.getGroup_id(); StringBuilder modules = new StringBuilder(); if (groupId != 0) { List<Map<String, Object>> auths = (List<Map<String, Object>>) authService.queryAuth(userId).getData(); for (Map<String, Object> m : auths) { modules.append(Integer.parseInt(m.get("menu_id") + "")).append(","); } if (modules.toString().endsWith(SYMBOL)) { modules = new StringBuilder(modules.substring(0, modules.length() - 1)); } } if (StringUtils.isEmpty(modules.toString()) && groupId != 0) { //ๆฒกๆœ‰ๆƒ้™ไธ”ไธๆ˜ฏ็ฎก็†ๅ‘˜ๆ—ถ๏ผŒไธ่ฟ”ๅ›ž่œๅ• return new ReturnMsg(true, "", null); } return new ReturnMsg(true, "", menuService.queryForLogin(modules.toString())); } @PostMapping("/queryMenusInTree") public ReturnMsg queryMenusInTree(@RequestBody JSONObject req) { Integer group_id = req.getInteger("group_id"); return menuService.queryMenuInTree(group_id); } }
true
7d65968e58a51dcff42622120c5b2c4b91a191a1
Java
RetepRelleum/SunSpecReader
/app/src/main/java/ch/gr/relleum/retep/sunspec/SunSpecScan.java
UTF-8
6,424
1.804688
2
[]
no_license
/* * Copyright ยฉ 2017 , Peter Mรผller. All rights reserved. * * * THE SOFTWARE IS PROVIDED 'AS IS', WITHOUT WARRANTY OF ANY * KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES * OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND * NONINFRINGEMENT. IN NO EVENT SHALL THE CONTRIBUTORS OR COPYRIGHT * HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER * IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR * IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS WITH THE * SOFTWARE. */ package ch.gr.relleum.retep.sunspec; import android.os.AsyncTask; import android.text.InputFilter; import android.view.View; import android.widget.Button; import android.widget.EditText; import android.widget.ImageButton; import android.widget.ListView; import android.widget.ProgressBar; import java.net.InetAddress; import java.net.UnknownHostException; import java.util.Iterator; import ch.gr.relleum.retep.sunspec.util.InputFilterMinMax; import ch.gr.relleum.retep.sunspec.util.IpListAdapter; import ch.gr.relleum.retep.sunspec.util.SunSpecListAdapter; import ch.retep.relleum.network.LocalNet; import ch.retep.relleum.sunspec.SunSpecAdressItem; /** * Created by Peter on 28.01.2017. */ public class SunSpecScan { private EditText[] editTextsIP = new EditText[4]; private EditText numberPickerPort; private EditText numberPickerUnitId; private EditText numberPickerStartingAdress; private ProgressBar progressBar; private static Iterator<InetAddress> inetAddressIterator; private SunSpecActivity sunSpecActivity; private InetAddress inetAddress; private IpListAdapter ipListAdapter; public void onCreate(SunSpecActivity aSunSpecActivity) { sunSpecActivity=aSunSpecActivity ; InetAddress inetAddress = LocalNet.getLocalIpAddress(); SunSpecListAdapter sunSpecListAdapter = new SunSpecListAdapter(sunSpecActivity); ipListAdapter = new IpListAdapter(sunSpecActivity, sunSpecListAdapter); ListView listView_ip = (ListView) aSunSpecActivity.findViewById(R.id.id_ip_list); listView_ip.setAdapter(ipListAdapter); ListView listView_Host = (ListView) aSunSpecActivity.findViewById(R.id.id_listView); listView_Host.setAdapter(sunSpecListAdapter); editTextsIP[0] = (EditText) aSunSpecActivity.findViewById(R.id.Id_numberPicker1); editTextsIP[1] = (EditText) aSunSpecActivity.findViewById(R.id.Id_numberPicker2); editTextsIP[2] = (EditText) aSunSpecActivity.findViewById(R.id.Id_numberPicker3); editTextsIP[3] = (EditText) aSunSpecActivity.findViewById(R.id.Id_numberPicker4); for (int i = 0; i < editTextsIP.length; i++) { editTextsIP[i].setFilters(new InputFilter[]{new InputFilterMinMax(0, 255)}); editTextsIP[i].setText(String.valueOf((inetAddress != null ? inetAddress.getAddress() : new byte[0])[i] & 0Xff)); } numberPickerPort = (EditText) aSunSpecActivity.findViewById(R.id.numberPicker_Port); numberPickerPort.setFilters(new InputFilter[]{new InputFilterMinMax(0, 65535)}); numberPickerPort.setText(R.string.t502); numberPickerUnitId = (EditText) aSunSpecActivity.findViewById(R.id.Id_numberPicker_Unit_Id); numberPickerUnitId.setFilters(new InputFilter[]{new InputFilterMinMax(0, 255)}); numberPickerUnitId.setText(R.string.t126); numberPickerStartingAdress = (EditText) aSunSpecActivity.findViewById(R.id.Id_numberPicker_Starting_Adresse); numberPickerStartingAdress.setFilters(new InputFilter[]{new InputFilterMinMax(0, 90000)}); numberPickerStartingAdress.setText(R.string.t40000); progressBar = (ProgressBar) aSunSpecActivity.findViewById(R.id.id_progressBarScan); progressBar.setVisibility(ProgressBar.INVISIBLE); ImageButton buttonScan = (ImageButton) aSunSpecActivity.findViewById(R.id.id_Button_ScanNetwork); buttonScan.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { SunSpecSan sunSpecSan = new SunSpecSan(); sunSpecSan.execute(); } }); Button buttonErneuern = (Button) sunSpecActivity.findViewById(R.id.ID_button_erneuern1); buttonErneuern.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { sunSpecActivity.updateList(); } }); } class SunSpecSan extends AsyncTask<String, String, String> { byte[] bytes; int port; boolean scan = true; @Override protected void onPreExecute() { progressBar.setVisibility(ProgressBar.VISIBLE); bytes = new byte[]{(byte) (Integer.parseInt(editTextsIP[0].getText().toString()) & 0XFF), (byte) (Integer.parseInt(editTextsIP[1].getText().toString()) & 0XFF), (byte) (Integer.parseInt(editTextsIP[2].getText().toString()) & 0XFF), (byte) (Integer.parseInt(editTextsIP[3].getText().toString()) & 0XFF)}; port = Integer.parseInt(numberPickerPort.getText().toString()); } @Override protected String doInBackground(String... params) { if (inetAddressIterator == null || !inetAddressIterator.hasNext()) { try { inetAddressIterator = LocalNet.scanNetoworkAtPort(InetAddress.getByAddress(bytes), port); } catch (UnknownHostException e) { e.printStackTrace(); } } return null; } @Override protected void onPostExecute(String result) { ipListAdapter.clear(); progressBar.setVisibility(ProgressBar.INVISIBLE); if (!(inetAddressIterator == null || !inetAddressIterator.hasNext())) { while (inetAddressIterator.hasNext()) { InetAddress inetAddress = inetAddressIterator.next(); SunSpecAdressItem item = new SunSpecAdressItem(inetAddress.getHostName(),inetAddress.getHostAddress(),Integer.parseInt(numberPickerPort.getText().toString()),Integer.parseInt(numberPickerUnitId.getText().toString()),Integer.parseInt(numberPickerStartingAdress.getText().toString())); ipListAdapter.add(item); } } } } }
true
5b2649efa091eb114eeebd3c7c7a7687e6f74395
Java
pvkshanuka/Spring
/SpringProjects/SpringFinalProject/Backend/ChannellingService/src/main/java/e_channelling/channelling_service/commonModels/Appointment.java
UTF-8
578
1.992188
2
[]
no_license
package e_channelling.channelling_service.commonModels; import lombok.AllArgsConstructor; import lombok.Data; import lombok.NoArgsConstructor; import javax.persistence.Entity; import javax.persistence.GeneratedValue; import javax.persistence.GenerationType; import javax.persistence.Id; import javax.validation.constraints.NotNull; import java.time.Instant; @Data @AllArgsConstructor @NoArgsConstructor public class Appointment { private Integer id; private Client client; private Integer channelling; private Instant date; private String status; }
true
cc41ad6cfab82a56bd7ec6084416c1e1653d95db
Java
AnujPancholi/codingQuestionSolutions
/leetcode/algorithms/matrix/max-area-of-island.java
UTF-8
997
3.1875
3
[]
no_license
class Solution { boolean[][] seen; int[][] grid; int LAND_NUM = 1; private int areaImpl(int r,int c){ if((r<0 || r>=this.grid.length) || (c<0 || c>=this.grid[0].length) || this.seen[r][c]){ return 0; } this.seen[r][c] = true; if(this.grid[r][c]!=LAND_NUM){ return 0; } return 1 + areaImpl(r,c+1) + areaImpl(r+1,c) + areaImpl(r-1,c) + areaImpl(r,c-1); } public int maxAreaOfIsland(int[][] grid) { this.grid = grid; this.seen = new boolean[this.grid.length][this.grid[0].length]; int maxArea = 0; for(int r = 0;r<this.grid.length;++r){ for(int c = 0;c<this.grid[0].length;++c){ if(!this.seen[r][c] && this.grid[r][c]==LAND_NUM){ maxArea = Math.max(maxArea,areaImpl(r,c)); } } } return maxArea; } }
true
4ba9fe9d2c46967913e46a26ac99d9cad52dcbff
Java
JayGrey/TEHome
/src/te/homework/lab3/task8/Main.java
UTF-8
942
3.0625
3
[]
no_license
/* ะ’ะฒะตัั‚ะธ ั‚ะตะบัั‚, ั‰ะพ ะบั€ั–ะผ ะปั–ั‚ะตั€ ั‚ะฐ ะฟั€ะพะฟัƒัะบั–ะฒ ะผะพะถะต ะผั–ัั‚ะธั‚ะธ ั–ะฝัˆั– ัะธะผะฒะพะปะธ. ะ’ะธะปัƒั‡ะธั‚ะธ ะท ะฝัŒะพะณะพ ะฒัั– ัะธะผะฒะพะปะธ, ะบั€ั–ะผ ะฟั€ะพะฟัƒัะบั–ะฒ, ัะบั– ะฝะต ั” ะปั–ั‚ะตั€ะฐะผะธ. ะœั–ะถ ะฟะพัะปั–ะดะพะฒะฝะพัั‚ัะผะธ ะปั–ั‚ะตั€, ั‰ะพ ะนะดัƒั‚ัŒ ะฑะตะทะฟะพัะตั€ะตะดะฝัŒะพ ะพะดะฝะฐ ะทะฐ ะพะดะฝะพัŽ, ะทะฐะปะธัˆะธั‚ะธ ั…ะพั‡ะฐ ะฑะธ ะฟะพ ะพะดะฝะพะผัƒ ะฟั€ะพะฟัƒัะบัƒ. ะ’ะธะฒะตัั‚ะธ ั€ัะดะพะบ ะดะพ ั‚ะฐ ะฟั–ัะปั ะพะฟั€ะฐั†ัŽะฒะฐะฝะฝั. */ package te.homework.lab3.task8; import java.util.Scanner; public class Main { public static void main(String[] args) { Scanner scanner = new Scanner(System.in); System.out.print("input: "); String input = scanner.nextLine(); String output = new Task8().removeNonAlphaCharsInWords(input); System.out.println("input: " + input); System.out.println("output: " + output); } }
true
d9403e1f67bdf49c88a363f2cf9ea82e00402039
Java
rjha/algo
/queen8.java
UTF-8
2,881
3.71875
4
[]
no_license
/* * 8-queen problem using brute force searching * This solutions uses following strategies * * 1 - fix one queen in one column and generate all * non-conflicting permutations - N! in total * this is akin to solving the N-rook problem * 2- eliminate from N! permutations - that do not * pass the additional diagonal test * * @author Rajeev Jha * @version 1.0 * */ import java.util.Set; import java.util.HashSet; public class queen8 { private int[] columns ; private char[] colNames ; private int size ; private int solutions ; public queen8(int N) { this.columns = new int[N] ; for(int i=0 ; i < N ; i++) this.columns[i] = i+1 ; this.colNames = new char[N] ; char a = 'A' ; for(int i=0 ; i < N ; i++) this.colNames[i] = (char) (a + i) ; this.size = N ; this.solutions = 0 ; } private void solve() { this.generate(this.size); } /* * permutation generator using a backtracking algo * from http://www.cs.princeton.edu/~rs/talks/perms.pdf */ private void generate(int N){ int c ; /* factorial 1, 1! case,just one possibility,print that ..*/ if ( N == 0 ) test_diagonal(); //algorithm adjusted for zero-based indexes .. for(c = 0 ; c < N ; c++){ swap(c,N-1); generate(N-1); swap(c,N-1); } } /* swap for permutation */ private void swap(int x, int y){ int tmp = this.columns[x] ; this.columns[x] = this.columns[y] ; this.columns[y] = tmp ; } /* for position of a queen in a column (a permutation) * diagonal positions are given by moving * one row up in next column and one row down in * previous column */ private void test_diagonal(){ int x ; for(int i = 0 ; i < this.columns.length ; i++) { x = this.columns[i] ; for(int j = i+1, k = 1; j < this.columns.length ; j++, k++) { if((x+k) == this.columns[j]) return ; if((x-k) == this.columns[j]) return ; } } // diagonal test passed print_board(); } private void print_board() { for(int i = 0 ; i < this.columns.length ; i++) { System.out.print(this.colNames[i]); System.out.print(this.columns[i] + " "); } System.out.println(); this.solutions++ ; } private int getNumSolutions() { return this.solutions ; } public static void main(String[] args) throws Exception { queen8 board = new queen8(8); board.solve(); System.out.println(" \n Total " + board.getNumSolutions() + " solutions " ); } }
true
b270b78e3a373b819dfed422f3130eba80f8f78f
Java
sandrocheng/sandro
/project/BatteryTest/src/com/tencent/one/battery/core/powerrank/proxy/PowerProfileProxy.java
UTF-8
15,827
2.3125
2
[]
no_license
package com.tencent.one.battery.core.powerrank.proxy; import java.lang.reflect.Constructor; import java.lang.reflect.InvocationTargetException; import java.lang.reflect.Method; import com.tencent.one.battery.core.util.ReflectUtil; import android.content.Context; import android.util.Log; /** * * @ClassName: PowerProfileProxy * @Description:้€š่ฟ‡ๅๅฐ„com.android.internal.os.PowerProfile็ฑปๅบ“่Žทๅ–ๅฎžไพ‹ * @author: Sandro * @date: 2013-1-16 ไธŠๅˆ09:52:26 * */ public class PowerProfileProxy { private String TAG = "PowerProfileProxy"; /** * ๅๅฐ„ com.android.internal.os.PowerProfile็ฑปๅบ“็š„ๅฏน่ฑกๅฎžไพ‹ */ private Object powerProfileInstance = null; /** * ๅๅฐ„ com.android.internal.os.PowerProfile็ฑป */ private Class<?> powerProfileClass = null; /** * PowerProfile.POWER_CPU_ACTIVE Power consumption when CPU is in power * collapse mode. public static final String POWER_CPU_ACTIVE = * "cpu.active"; */ private String POWER_CPU_ACTIVE = null; /** * PowerProfile.POWER_RADIO_ACTIVE Power consumption when talking on the * phone. public static final String POWER_RADIO_ACTIVE = "radio.active"; */ private String POWER_RADIO_ACTIVE = null; /** * PowerProfile.POWER_WIFI_ACTIVE Power consumption when WiFi driver is * transmitting/receiving. public static final String POWER_WIFI_ACTIVE = * "wifi.active"; */ private String POWER_WIFI_ACTIVE = null; /** * Power consumption when CPU is awake (when a wake lock is held). This * should be 0 on devices that can go into full CPU power collapse even when * a wake lock is held. Otherwise, this is the power consumption in addition * to POWERR_CPU_IDLE due to a wake lock being held but with no CPU * activity. */ private String POWER_CPU_AWAKE = null; /** * Power consumption when WiFi driver is on. public static final String * POWER_WIFI_ON = "wifi.on"; */ private String POWER_WIFI_ON = null; /** * Power consumption when GPS is on. * public static final String POWER_GPS_ON = "gps.on"; */ private String POWER_GPS_ON = null; /** * Power consumption when Bluetooth driver is on. * public static final String POWER_BLUETOOTH_ON = "bluetooth.on"; */ private String POWER_BLUETOOTH_ON = null; /** * Power consumption when CPU is in power collapse mode. */ public String POWER_CPU_IDLE = null; /** * Power consumption when Bluetooth driver gets an AT command. */ public String POWER_BLUETOOTH_AT_CMD = null; /** * Power consumption when cell radio is on but not on a call. */ public String POWER_RADIO_ON = null; /** * Power consumption when cell radio is hunting for a signal. */ public String POWER_RADIO_SCANNING = null; /** * Power consumption when screen is on, not including the backlight power. */ public String POWER_SCREEN_ON = null; /** * Power consumption at full backlight brightness. If the backlight is at * 50% brightness, then this should be multiplied by 0.5 */ public String POWER_SCREEN_FULL = null; public PowerProfileProxy(Context context) { reflectPowerProfile(context); POWER_CPU_ACTIVE = getPowerCpuActive(); POWER_RADIO_ACTIVE = getPowerRadioActive(); POWER_WIFI_ACTIVE = getPowerWifiActive(); POWER_CPU_AWAKE = getPowerCpuAwake(); POWER_WIFI_ON = getPowerWifiOn(); POWER_GPS_ON = getPowerGpsOn(); POWER_BLUETOOTH_ON = this.getPowerBlueToothOn(); POWER_RADIO_ON = getPowerRadioOn(); POWER_RADIO_SCANNING = getPowerRadioScanning(); POWER_SCREEN_FULL = getPowerScreenFull(); POWER_SCREEN_ON = getPowerScreenOn(); POWER_CPU_IDLE = getPowerCpuIdle(); POWER_BLUETOOTH_AT_CMD = getPower_BlueToothAtCmd(); } private void reflectPowerProfile(Context context) { try { powerProfileClass = Class.forName("com.android.internal.os.PowerProfile"); } catch (Exception e) { Log.e(TAG, "reflectPowerProfile powerProfileClass Exception : " + e.toString()); return; } // ๅ–ๅพ—ๅ…จ้ƒจ็š„ๆž„้€ ๅ‡ฝๆ•ฐ Constructor<?> cons[] = powerProfileClass.getConstructors(); try { for (Constructor<?> con : cons) { powerProfileInstance = (Object) con.newInstance(context); break; } } catch (IllegalArgumentException e) { Log.e(TAG, "reflectPowerProfile.newInstance.IllegalArgumentException : " + e.toString()); return; } catch (InstantiationException e) { Log.e(TAG, "reflectPowerProfile.newInstance.InstantiationException : " + e.toString()); return; } catch (IllegalAccessException e) { Log.e(TAG, "reflectPowerProfile.newInstance.IllegalAccessException : " + e.toString()); return; } catch (InvocationTargetException e) { Log.e(TAG, "reflectPowerProfile.newInstance.InvocationTargetException : " + e.toString()); return; } } /** * ้€š่ฟ‡ๅๅฐ„PowerFile.getNumSpeedSteps Returns the number of speeds that the CPU * can be run at. * * @return */ public int getNumSpeedSteps() { if (powerProfileClass == null || powerProfileInstance == null) { return 0; } Method getNumSpeedStepsMethod = null; try { getNumSpeedStepsMethod = powerProfileClass.getMethod("getNumSpeedSteps"); } catch (SecurityException e) { Log.e(TAG, "getNumSpeedSteps SecurityException : " + e.toString()); return 0; } catch (NoSuchMethodException e) { Log.e(TAG, "getNumSpeedSteps NoSuchMethodException : " + e.toString()); return 0; } try { return (Integer) getNumSpeedStepsMethod.invoke(powerProfileInstance); } catch (IllegalArgumentException e) { Log.e(TAG, "getNumSpeedSteps IllegalArgumentException : " + e.toString()); } catch (IllegalAccessException e) { Log.e(TAG, "getNumSpeedSteps IllegalAccessException : " + e.toString()); } catch (InvocationTargetException e) { Log.e(TAG, "getNumSpeedSteps InvocationTargetException : " + e.toString()); } return 0; } public Object getPowerProfileInstance() { return powerProfileInstance; } public Class<?> getPowerProfileClass() { return powerProfileClass; } public String get_POWER_CPU_ACTIVE() { return POWER_CPU_ACTIVE; } public String get_POWER_RADIO_ACTIVE() { return POWER_RADIO_ACTIVE; } public String get_POWER_WIFI_ACTIVE() { return POWER_WIFI_ACTIVE; } public String get_POWER_CPU_AWAKE() { return POWER_CPU_AWAKE; } public String get_POWER_WIFI_ON() { return POWER_WIFI_ON; } public String get_POWER_GPS_ON() { return POWER_GPS_ON; } public String getPOWER_BLUETOOTH_ON(){ return POWER_BLUETOOTH_ON; } public String get_POWER_CPU_IDLE() { return POWER_CPU_IDLE; } public String get_POWER_SCREEN_ON() { return POWER_SCREEN_ON; } public String get_POWER_SCREEN_FULL() { return POWER_SCREEN_FULL; } public String get_POWER_BLUETOOTH_ON() { return POWER_BLUETOOTH_ON; } public String get_POWER_BLUETOOTH_AT_CMD() { return POWER_BLUETOOTH_AT_CMD; } public String get_POWER_RADIO_ON() { return POWER_RADIO_ON; } public String get_POWER_RADIO_SCANNING() { return POWER_RADIO_SCANNING; } /** * ๅๅฐ„่Žทๅ–PowerProfile.POWER_BLUETOOTH_ON็š„ๅ€ผ * @return */ private String getPowerBlueToothOn(){ if (powerProfileClass == null || powerProfileInstance == null) { return null; } return (String) ReflectUtil.ReflectFieldValue(powerProfileClass, powerProfileInstance, "POWER_BLUETOOTH_ON"); } /** * ๅๅฐ„่Žทๅ–PowerProfile.POWER_CPU_ACTIVE็š„ๅ€ผ * * @return */ private String getPowerCpuActive() { if (powerProfileClass == null || powerProfileInstance == null) { return null; } return (String) ReflectUtil.ReflectFieldValue(powerProfileClass, powerProfileInstance, "POWER_CPU_ACTIVE"); } /** * ๅๅฐ„่Žทๅ–PowerProfile.POWER_RADIO_ACTIVE็š„ๅ€ผ * * @return */ private String getPowerRadioActive() { if (powerProfileClass == null || powerProfileInstance == null) { return null; } return (String) ReflectUtil.ReflectFieldValue(powerProfileClass, powerProfileInstance, "POWER_RADIO_ACTIVE"); } /** * ๅๅฐ„่Žทๅ–PowerProfile.POWER_WIFI_ACTIVE็š„ๅ€ผ * * @return */ private String getPowerWifiActive() { if (powerProfileClass == null || powerProfileInstance == null) { return null; } return (String) ReflectUtil.ReflectFieldValue(powerProfileClass, powerProfileInstance, "POWER_WIFI_ACTIVE"); } /** * ๅๅฐ„่Žทๅ–POWER_SCREEN_FULL็š„ๅ€ผ * * @return */ private String getPowerScreenFull() { if (powerProfileClass == null || powerProfileInstance == null) { return null; } return (String) ReflectUtil.ReflectFieldValue(powerProfileClass, powerProfileInstance, "POWER_SCREEN_FULL"); } /** * ๅๅฐ„่Žทๅ–POWER_SCREEN_ON็š„ๅ€ผ * * @return */ private String getPowerScreenOn() { if (powerProfileClass == null || powerProfileInstance == null) { return null; } return (String) ReflectUtil.ReflectFieldValue(powerProfileClass, powerProfileInstance, "POWER_SCREEN_ON"); } /** * ๅๅฐ„่Žทๅ–POWER_CPU_IDLE็š„ๅ€ผ * * @return */ private String getPowerCpuIdle() { if (powerProfileClass == null || powerProfileInstance == null) { return null; } return (String) ReflectUtil.ReflectFieldValue(powerProfileClass, powerProfileInstance, "POWER_CPU_IDLE"); } /** * ๅๅฐ„่Žทๅ–PowerProfile.POWER_CPU_AWAKE็š„ๅ€ผ * * @return */ private String getPowerCpuAwake() { if (powerProfileClass == null || powerProfileInstance == null) { return null; } return (String) ReflectUtil.ReflectFieldValue(powerProfileClass, powerProfileInstance, "POWER_CPU_AWAKE"); } /** * ๅๅฐ„่Žทๅ–PowerProfile.POWER_BLUETOOTH_AT_CMD็š„ๅ€ผ * * @return */ private String getPower_BlueToothAtCmd() { if (powerProfileClass == null || powerProfileInstance == null) { return null; } return (String) ReflectUtil.ReflectFieldValue(powerProfileClass, powerProfileInstance, "POWER_BLUETOOTH_AT_CMD"); } /** * ๅๅฐ„่Žทๅ–PowerProfile.POWER_BLUETOOTH_AT_CMD็š„ๅ€ผ * * @return */ private String getPowerWifiOn() { if (powerProfileClass == null || powerProfileInstance == null) { return null; } return (String) ReflectUtil.ReflectFieldValue(powerProfileClass, powerProfileInstance, "POWER_WIFI_ON"); } /** * ๅๅฐ„่Žทๅ–PowerProfile.POWER_GPS_ON็š„ๅ€ผ * * @return */ private String getPowerGpsOn() { if (powerProfileClass == null || powerProfileInstance == null) { return null; } return (String) ReflectUtil.ReflectFieldValue(powerProfileClass, powerProfileInstance, "POWER_GPS_ON"); } /** * ๅๅฐ„่Žทๅ–PowerProfile.POWER_RADIO_ON็š„ๅ€ผ * * @return */ private String getPowerRadioOn() { if (powerProfileClass == null || powerProfileInstance == null) { return null; } return (String) ReflectUtil.ReflectFieldValue(powerProfileClass, powerProfileInstance, "POWER_RADIO_ON"); } /** * ๅๅฐ„่Žทๅ–PowerProfile.POWER_RADIO_SCANNING็š„ๅ€ผ * * @return */ private String getPowerRadioScanning() { if (powerProfileClass == null || powerProfileInstance == null) { return null; } return (String) ReflectUtil.ReflectFieldValue(powerProfileClass, powerProfileInstance, "POWER_RADIO_SCANNING"); } /** * Returns the average current in mA consumed by the subsystem * * @param type * the subsystem type * @return the average current in milliAmps.(ๅ•ไฝไธบmA/h) */ public double getAveragePower(String type) { if (type == null) { return 0d; } Method getAveragePowerMethod = null; try { getAveragePowerMethod = powerProfileClass.getMethod("getAveragePower", String.class); return (Double) getAveragePowerMethod.invoke(powerProfileInstance, type); } catch (SecurityException e) { Log.e(TAG, "getAveragePower SecurityException : " + e.toString()); } catch (NoSuchMethodException e) { Log.e(TAG, "getAveragePower NoSuchMethodException : " + e.toString()); } catch (IllegalArgumentException e) { Log.e(TAG, "getAveragePower IllegalArgumentException : " + e.toString()); } catch (IllegalAccessException e) { Log.e(TAG, "getAveragePower IllegalAccessException : " + e.toString()); } catch (InvocationTargetException e) { Log.e(TAG, "getAveragePower InvocationTargetException : " + e.toString()); } return 0d; } /** * Returns the average current in mA consumed by the subsystem for the given * level. * * @param type * the subsystem type * @param level * the level of power at which the subsystem is running. For * instance, the signal strength of the cell network between 0 * and 4 (if there are 4 bars max.) If there is no data for * multiple levels, the level is ignored. * @return the average current in milliAmps.(ๅ•ไฝไธบmA/h) */ public double getAveragePower(String type, int level) { if (type == null) { return 0d; } Method getAveragePowerMethod = null; try { getAveragePowerMethod = powerProfileClass.getMethod("getAveragePower", String.class, int.class); return (Double) getAveragePowerMethod.invoke(powerProfileInstance, type, level); } catch (SecurityException e) { Log.e(TAG, "getAveragePower SecurityException : " + e.toString()); } catch (NoSuchMethodException e) { Log.e(TAG, "getAveragePower NoSuchMethodException : " + e.toString()); } catch (IllegalArgumentException e) { Log.e(TAG, "getAveragePower IllegalArgumentException : " + e.toString()); } catch (IllegalAccessException e) { Log.e(TAG, "getAveragePower IllegalAccessException : " + e.toString()); } catch (InvocationTargetException e) { Log.e(TAG, "getAveragePower InvocationTargetException : " + e.toString()); } return 0d; } /** * ้€š่ฟ‡ๅๅฐ„่Žทๅ–PowerProfile็ฑปไธญ public double getAveragePower(String type, int * level)ๆ–นๆณ• POWER_CPU_ACTIVEๅฏนๅบ”็ฑปๅž‹็š„ๅ€ผ Returns the average current in mA * consumed by the subsystem for the given level. * * @param type * the subsystem type * @param level * the level of power at which the subsystem is running. For * instance, the signal strength of the cell network between 0 * and 4 (if there are 4 bars max.) If there is no data for * multiple levels, the level is ignored. * @return the average current in milliAmps. * @param speedSteps * @return */ public double getAveragePower(int speedSteps) { if (POWER_CPU_ACTIVE == null) { return 0d; } return getAveragePower(POWER_CPU_ACTIVE, speedSteps); } /** * ่Žทๅ–็”ตๆฑ ๅฎน้‡๏ผŒๅฆ‚ๆžœๅญ˜ๅœจ่ฟ”ๅ›žmAh,ๅฆๅˆ™่ฟ”ๅ›ž0<br> * ๅ–Power_profile.xmlไธญ"battery.capacity"็š„ๅ€ผ<br> * ไธบๅŽ‚ๅ•†ๅ‡บๅŽ‚ๅ†…็ฝฎๆ–‡ไปถ๏ผŒๅฆ‚ๆ›ดๆข็”ตๆฑ ๆˆ–่€…xmlๆ–‡ไปถๆ”นๅ˜๏ผŒๅˆ™่ฏฅๅ€ผไธไธ€ๅฎšๅ‡†็กฎใ€‚ * * @return ็”ตๆฑ ๅฎน้‡(mAh) * @since 1.0 * @author LionLiu */ public double getBatteryCapacity() { Method getBatteryCapacityMethod = null; try { getBatteryCapacityMethod = powerProfileClass.getMethod("getBatteryCapacity"); return (Double)getBatteryCapacityMethod.invoke(powerProfileInstance); } catch (SecurityException e) { Log.e(TAG, "getBatteryCapacity SecurityException : " + e.toString()); } catch (NoSuchMethodException e) { Log.e(TAG, "getBatteryCapacity NoSuchMethodException : " + e.toString()); } catch (IllegalArgumentException e) { Log.e(TAG, "getBatteryCapacity IllegalArgumentException : " + e.toString()); } catch (IllegalAccessException e) { Log.e(TAG, "getBatteryCapacity IllegalAccessException : " + e.toString()); } catch (InvocationTargetException e) { Log.e(TAG, "getBatteryCapacity InvocationTargetException : " + e.toString()); } return 0d; } /** Added by Lionliu End */ }
true
e8a34ce7c9e301f9dc8310f707c1a928d4f76485
Java
heshangbuxitou/mytest
/src/com/zy/designs/composite/Util.java
UTF-8
264
2.65625
3
[]
no_license
package com.zy.designs.composite; public class Util { public static String getNumString(String s,int num){ StringBuffer sb = new StringBuffer(); for(int i=0;i<num;i++){ sb.append(s); } return sb.toString(); } }
true
4a71cbe8e437a02595de55fe99b4220f89f187e1
Java
ALAxHxC/AndroidSQL
/app/src/main/java/org/gestioncatalogo/vistas/mensajes/Mensajes.java
UTF-8
9,620
1.976563
2
[]
no_license
package org.gestioncatalogo.vistas.mensajes; import android.app.Dialog; import android.content.Context; import android.view.View; import android.widget.ArrayAdapter; import android.widget.AutoCompleteTextView; import android.widget.Button; import android.widget.DatePicker; import android.widget.EditText; import android.widget.Spinner; import android.widget.Toast; import org.gestioncatalogo.R; import org.gestioncatalogo.controlador.persistencia.ControladorMarcas; import org.gestioncatalogo.controlador.persistencia.ControladorProducto; import org.gestioncatalogo.modelo.Marca; import org.gestioncatalogo.modelo.Producto; import org.gestioncatalogo.modelo.Talla; import org.gestioncatalogo.vistas.MainActivity; import java.util.ArrayList; import java.util.List; /** * Created by Daniel on 11/07/2016. */ public class Mensajes { private Context context; private MainActivity mainActivity; private ControladorMarcas baseDeDatos; private ControladorProducto baseDeDatosProducto; public Mensajes(Context context, MainActivity mainActivity) { this.context = context; this.mainActivity = mainActivity; baseDeDatos = new ControladorMarcas(context); baseDeDatosProducto = new ControladorProducto(context); } public void Calendario() { final Dialog dialog = new Dialog(context); dialog.setContentView(R.layout.fecha_ingreso); dialog.setTitle(context.getString(R.string.ingresa_fecha)); final DatePicker datePicker = (DatePicker) dialog.findViewById(R.id.datePicker); datePicker.setSpinnersShown(true); Button botonpositivo = (Button) dialog.findViewById(R.id.buttonAceptar); botonpositivo.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { mainActivity.getFecha().setText(datePicker.getYear() + "-" + datePicker.getMonth() + "-" + datePicker.getDayOfMonth()); dialog.dismiss(); } }); Button negativo = (Button) dialog.findViewById(R.id.buttonCancelar); ConfigurarCancelar(negativo, dialog); dialog.show(); } public void registrarMarca() { final Dialog dialog = new Dialog(context); dialog.setContentView(R.layout.registro_marca); final EditText idmarca = (EditText) dialog.findViewById(R.id.editTextIDmarca); idmarca.setEnabled(false); idmarca.setText(mainActivity.getMarcas().getMarcaList().size() + 1 + ""); final EditText nombreamarca = (EditText) dialog.findViewById(R.id.editTextNameMarca); nombreamarca.setText(""); nombreamarca.setHint(context.getString(R.string.nombre_marca)); Button negativo = (Button) dialog.findViewById(R.id.buttonCancelarMarca); ConfigurarCancelar(negativo, dialog); Button positivo = (Button) dialog.findViewById(R.id.buttonRegistrarMarca); botonRegistrarMarca(positivo, dialog, idmarca, nombreamarca); dialog.show(); } public void BuscarMarcas() { final Dialog dialog = new Dialog(context); dialog.setContentView(R.layout.buscar_marca); final EditText idMarca = (EditText) dialog.findViewById(R.id.editTextBuscarMarcaID); final EditText nombreMarca = (EditText) dialog.findViewById(R.id.editTextBuscarNombreMarca); Button cancelar = (Button) dialog.findViewById(R.id.buttonBuscarMarcaCancelar); ConfigurarCancelar(cancelar, dialog); Button buscar = (Button) dialog.findViewById(R.id.buttonBuscarMarcaBuscar); botonBuscarMarca(buscar, dialog, idMarca, nombreMarca); dialog.show(); } public void BuscarProductos() { final Dialog dialog = new Dialog(context); dialog.setContentView(R.layout.buscar_producto); final EditText nombre = (EditText) dialog.findViewById(R.id.editTextBuscarProductoNombre); final AutoCompleteTextView marca = (AutoCompleteTextView) dialog.findViewById(R.id.autoCompleteTextViewBuscarProductoTalla); configurarAutoCompletarMarca(marca); final Spinner talla = (Spinner) dialog.findViewById(R.id.spinnerBuscarProductoTalla); configurarSpinnerTallas(talla); final Button negativo = (Button) dialog.findViewById(R.id.buttonBuscarProductoCancelar); ConfigurarCancelar(negativo, dialog); final Button positivo = (Button) dialog.findViewById(R.id.buttonBuscarProductoBuscar); botonBuscarProducto(positivo, dialog, nombre, talla, marca); dialog.show(); } //vistas public void configurarAutoCompletarMarca(AutoCompleteTextView marca) { ArrayAdapter<Marca> adapterMarca = new ArrayAdapter<Marca>(context, R.layout.item_spinner, R.id.spinnerTarget, mainActivity.getMarcas().getMarcaList()); marca.setAdapter(adapterMarca); } public void configurarSpinnerTallas(Spinner talla) { List<String> tallas = new ArrayList<>(); tallas.add(""); for (Talla t : Talla.values()) { tallas.add(t.talla); } ArrayAdapter<String> adapterTalla = new ArrayAdapter<String>(context , R.layout.item_spinner, R.id.spinnerTarget, tallas); talla.setAdapter(adapterTalla); } //botones private void botonRegistrarMarca(Button positivo, final Dialog dialog, final EditText idmarca, final EditText nombreamarca) { positivo.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { if (validadRegistroMarca(idmarca, nombreamarca)) { if (baseDeDatos.RegistrarMarca(idmarca.getEditableText().toString(), nombreamarca.getEditableText().toString()) >= 1) { mainActivity.getMarcas().getMarcaList().add(new Marca(idmarca.getEditableText().toString(), nombreamarca.getEditableText().toString())); mainActivity.validarMarcas(); dialog.dismiss(); } } } }); } private void botonBuscarProducto(Button buscar, final Dialog dialog, final EditText nombre, final Spinner talla, final AutoCompleteTextView marca) { buscar.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { if (validadBusquedaProducto(nombre, talla, marca)) { List<Producto> lista = baseDeDatosProducto.filtrarProductos(nombre.getEditableText().toString(), ((String) talla.getSelectedItem()), marca.getEditableText().toString()); if (lista.size() > 0) { mainActivity.cargarProductos(lista); dialog.dismiss(); } else { ToastMensaje(context.getString(R.string.sin_resultados)); } } else { ToastMensaje(context.getString(R.string.campos_busqueda_marca)); } } }); } private void botonBuscarMarca(Button buscar, final Dialog dialog, final EditText idMarca, final EditText nombreMarca) { buscar.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { if (validarBusquedaMarca(idMarca, nombreMarca)) { List<Marca> marcaList = baseDeDatos.filtrarMarcas(idMarca.getEditableText().toString(), nombreMarca.getEditableText().toString()); if (marcaList.size() > 0) { mainActivity.cargarMarcas(marcaList); dialog.dismiss(); } else { ToastMensaje(context.getString(R.string.sin_resultados)); } } else { ToastMensaje(context.getString(R.string.campos_busqueda_marca)); } } }); } //validaciones private boolean validadRegistroMarca(EditText id, EditText marca) { if (marca.getText().toString().isEmpty() || marca.getText().length() <= 3) { ToastMensaje(context.getString(R.string.name_nulo)); return false; } return true; } private boolean validarBusquedaMarca(EditText id, EditText nombre) { if ((id.getEditableText().toString().isEmpty() || id.getEditableText().toString().equalsIgnoreCase("")) && (nombre.getEditableText().toString().isEmpty() || nombre.getEditableText().toString().equalsIgnoreCase(""))) { return false; } return true; } private boolean validadBusquedaProducto(EditText nombre, Spinner talla, AutoCompleteTextView marca) { String texto = (String) talla.getSelectedItem(); String marcatext = marca.getEditableText().toString(); if ((nombre.getEditableText().toString().isEmpty() || nombre.getEditableText().toString().equalsIgnoreCase("")) && (texto.isEmpty() || texto.equalsIgnoreCase("")) && (marcatext.isEmpty() || marcatext.equalsIgnoreCase("")) ) { return false; } return true; } public void ToastMensaje(String mensaje) { Toast.makeText(context, mensaje, Toast.LENGTH_SHORT).show(); } private void ConfigurarCancelar(Button cancelar, final Dialog dialog) { cancelar.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { dialog.dismiss(); } }); } }
true
a972edb78aa8903537cb019957573eee59e0fe84
Java
rudilgr/appconfiguration-java-sdk
/ibm-appconfiguration/src/test/java/com/ibm/cloud/appconfiguration/sdk/test/AppConfigurationTest.java
UTF-8
3,976
1.960938
2
[ "Apache-2.0" ]
permissive
/** * Copyright 2021 IBM Corp. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.ibm.cloud.appconfiguration.sdk.test; import com.ibm.cloud.appconfiguration.sdk.AppConfiguration; import com.ibm.cloud.appconfiguration.sdk.configurations.ConfigurationUpdateListener; import com.ibm.cloud.appconfiguration.sdk.configurations.models.Feature; import com.ibm.cloud.appconfiguration.sdk.configurations.models.Property; import org.json.JSONObject; import org.junit.jupiter.api.Test; import java.nio.file.Path; import java.nio.file.Paths; import java.util.concurrent.TimeUnit; import static org.junit.jupiter.api.Assertions.*; public class AppConfigurationTest { @Test public void testConfigurationHandler() throws InterruptedException { AppConfiguration appConfiguration = AppConfiguration.getInstance(); AppConfiguration.overrideServerHost = "http://overrideServerHost"; assertTrue(AppConfiguration.overrideServerHost == "http://overrideServerHost"); appConfiguration.setContext("collectionId", "environmentId"); appConfiguration.setContext("collectionId", "environmentId","",true); appConfiguration.init("","guid","apikey"); appConfiguration.init("region","","apikey"); appConfiguration.init("region","guid",""); appConfiguration.init("region","guid","apikey"); appConfiguration.setContext("", "envid"); appConfiguration.setContext("collection_id", ""); appConfiguration.setContext("collection_id", "env_id"); appConfiguration.setContext("collection_id", "env_id", "", false); final Boolean[] onData = {false}; appConfiguration.registerConfigurationUpdateListener(new ConfigurationUpdateListener() { @Override public void onConfigurationUpdate() { onData[0] = true; } }); Path resourceDirectory = Paths.get("src","test","resources"); String absolutePath = resourceDirectory.toFile().getAbsolutePath(); appConfiguration.setContext("collectionId", "environmentId", absolutePath + "/user.json",false); appConfiguration.fetchConfigurations(); appConfiguration.enableDebug(true); assertTrue(appConfiguration.getFeatures().size() >= 0); assertTrue(appConfiguration.getProperties().size() >= 0); assertNotNull(appConfiguration.getProperty("numericproperty")); assertNotNull(appConfiguration.getFeature("defaultfeature")); assertNull(appConfiguration.getProperty("numericproperty1")); assertNull(appConfiguration.getFeature("defaultfeature2")); appConfiguration.fetchConfigurations(); assertTrue(appConfiguration.getFeatures().size() == 3); Feature feature = appConfiguration.getFeature("defaultfeature"); String idVal = feature.getFeatureId(); assertTrue(idVal.equals("defaultfeature")); assertTrue(appConfiguration.getProperties().size() == 1); JSONObject attributes = new JSONObject(); attributes.put("email", "dev@tester.com"); Property property = appConfiguration.getProperty("numericproperty"); assertTrue(property.getPropertyId().equals("numericproperty")); property.getCurrentValue("", attributes); assertEquals("Welcome",feature.getCurrentValue("pqvr", attributes)); assertEquals(81,property.getCurrentValue("pqvr", attributes)); } }
true
ced5897bfe043fbe52c271e9b64fc9c94e99144e
Java
HarneetSingh/GSYSocial
/src/main/java/com/motionapps/GSYSocial/dao/vo/NotificationRequestVO.java
UTF-8
760
2.015625
2
[]
no_license
package com.motionapps.GSYSocial.dao.vo; import javax.xml.bind.annotation.XmlRootElement; @XmlRootElement public class NotificationRequestVO { private String to; private Notification notification; private NotificationDataVO data; public NotificationDataVO getData() { return data; } public void setData(NotificationDataVO data) { this.data = data; } public String getTo() { return to; } public void setTo(String to) { this.to = to; } public Notification getNotification() { return notification; } public void setNotification(Notification notification) { this.notification = notification; } @Override public String toString() { return "{ to :"+to+notification.toString()+data.toString()+ "}"; } }
true
4d16b8f24b57243af58f8b6afc4f82e775a814c5
Java
xin321536/HomeWork
/Day03/ไปฃ็ /Android_YX/app/src/main/java/com/example/android_yx/Activity/WebViewActivity.java
UTF-8
979
2.15625
2
[]
no_license
package com.example.android_yx.Activity; import android.content.Intent; import android.os.Bundle; import android.webkit.WebView; import android.webkit.WebViewClient; import android.widget.Toast; import androidx.appcompat.app.AppCompatActivity; import com.example.android_yx.R; public class WebViewActivity extends AppCompatActivity { private WebView web_View; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_web_view); initView(); } public void showShort(String s) { Toast.makeText(this, s, Toast.LENGTH_SHORT).show(); } private void initView() { web_View = (WebView) findViewById(R.id.web_View); //ๆŽฅๅ—ๅ‘้€่ฟ‡ๆฅ็š„ไฟกๆฏ Intent intent = getIntent(); String url = intent.getStringExtra("url"); web_View.loadUrl(url); web_View.setWebViewClient(new WebViewClient()); } }
true
9c09ea72fc84277676676b5f2a2603452a592e3b
Java
Denis-chen/gallerygoogle.apk.decode
/src/com/android/gallery3d/data/ActionImage.java
UTF-8
2,067
1.992188
2
[]
no_license
package com.android.gallery3d.data; import android.graphics.Bitmap; import android.graphics.BitmapFactory; import android.graphics.BitmapRegionDecoder; import android.net.Uri; import com.android.gallery3d.app.GalleryApp; import com.android.gallery3d.common.BitmapUtils; import com.android.gallery3d.common.Utils; import com.android.gallery3d.util.ThreadPool.Job; import com.android.gallery3d.util.ThreadPool.JobContext; public class ActionImage extends MediaItem { private GalleryApp mApplication; private int mResourceId; public ActionImage(Path paramPath, GalleryApp paramGalleryApp, int paramInt) { super(paramPath, nextVersionNumber()); this.mApplication = ((GalleryApp)Utils.checkNotNull(paramGalleryApp)); this.mResourceId = paramInt; } public Uri getContentUri() { return null; } public int getHeight() { return 0; } public int getMediaType() { return 1; } public String getMimeType() { return ""; } public int getSupportedOperations() { return 32768; } public int getWidth() { return 0; } public ThreadPool.Job<Bitmap> requestImage(int paramInt) { return new BitmapJob(paramInt); } public ThreadPool.Job<BitmapRegionDecoder> requestLargeImage() { return null; } private class BitmapJob implements ThreadPool.Job<Bitmap> { private int mType; protected BitmapJob(int arg2) { int i; this.mType = i; } public Bitmap run(ThreadPool.JobContext paramJobContext) { int i = MediaItem.getTargetSize(this.mType); Bitmap localBitmap = BitmapFactory.decodeResource(ActionImage.this.mApplication.getResources(), ActionImage.this.mResourceId); if (this.mType == 2) return BitmapUtils.resizeAndCropCenter(localBitmap, i, true); return BitmapUtils.resizeDownBySideLength(localBitmap, i, true); } } } /* Location: D:\camera42_patched_v2\dex2jar-0.0.9.15\classes_dex2jar.jar * Qualified Name: com.android.gallery3d.data.ActionImage * JD-Core Version: 0.5.4 */
true
cf18974842618078d911278981d9024272402166
Java
hashsdn/hashsdn-netconf
/netconf/tools/netconf-cli/src/main/java/org/opendaylight/netconf/cli/writer/impl/ContainerNodeCliSerializer.java
UTF-8
2,059
1.898438
2
[]
no_license
/* * Copyright (c) 2013 Cisco Systems, Inc. and others. All rights reserved. * * This program and the accompanying materials are made available under the * terms of the Eclipse Public License v1.0 which accompanies this distribution, * and is available at http://www.eclipse.org/legal/epl-v10.html */ package org.opendaylight.netconf.cli.writer.impl; import com.google.common.base.Preconditions; import java.util.Collections; import org.opendaylight.netconf.cli.writer.OutFormatter; import org.opendaylight.yangtools.yang.data.api.schema.ContainerNode; import org.opendaylight.yangtools.yang.data.impl.schema.transform.base.serializer.ContainerNodeBaseSerializer; import org.opendaylight.yangtools.yang.data.impl.schema.transform.base.serializer.NodeSerializerDispatcher; import org.opendaylight.yangtools.yang.model.api.ContainerSchemaNode; final class ContainerNodeCliSerializer extends ContainerNodeBaseSerializer<String> { private final NodeSerializerDispatcher<String> dispatcher; private final OutFormatter out; ContainerNodeCliSerializer(final OutFormatter out, final NodeSerializerDispatcher<String> dispatcher) { this.out = Preconditions.checkNotNull(out); this.dispatcher = Preconditions.checkNotNull(dispatcher); } @Override public Iterable<String> serialize(final ContainerSchemaNode schema, final ContainerNode containerNode) { final StringBuilder output = new StringBuilder(); out.increaseIndent(); out.addStringWithIndent(output, containerNode.getNodeType().getLocalName()); out.openComposite(output); out.newLine(output); for (final String childOutput : super.serialize(schema, containerNode)) { output.append(childOutput); out.newLine(output); } out.closeCompositeWithIndent(output); out.decreaseIndent(); return Collections.singletonList(output.toString()); } @Override protected NodeSerializerDispatcher<String> getNodeDispatcher() { return dispatcher; } }
true
8ae3cc863b1cccf45245db09bbe391574d26ccdc
Java
fidusio/zoxweb-core
/src/main/java/org/zoxweb/server/util/JarTool.java
UTF-8
6,377
2.5
2
[ "Apache-2.0" ]
permissive
/* * Copyright (c) 2012-2017 ZoxWeb.com LLC. * * Licensed under the Apache License, Version 2.0 (the "License"); you may not * use this file except in compliance with the License. You may obtain a copy of * the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the * License for the specific language governing permissions and limitations under * the License. */ package org.zoxweb.server.util; import java.io.File; import java.io.FileNotFoundException; import java.io.FileOutputStream; import java.io.IOException; import java.io.InputStream; import java.io.OutputStream; import java.net.URL; import java.net.URLClassLoader; import java.util.Enumeration; import java.util.HashMap; import java.util.Map; import java.util.jar.JarEntry; import java.util.jar.JarFile; import org.zoxweb.server.io.IOUtil; import org.zoxweb.shared.filters.MatchPatternFilter; import org.zoxweb.shared.util.SharedStringUtil; public class JarTool { private JarTool() { } public static URL findClassJarURL( Class<?> entryPointClass) throws IOException { return entryPointClass.getProtectionDomain().getCodeSource().getLocation(); } public static Map<String, URL> findFilesInJarAndExpandAsTempFiles(String jarFilename, boolean deleteOnExit, String... searchCriteria) throws IOException { HashMap<String, URL> jarURLs = new HashMap<String, URL>(); MatchPatternFilter mpf = MatchPatternFilter.createMatchFilter(searchCriteria); File jarFile = new File(jarFilename); JarFile jf = null; try { jf = new JarFile( jarFile); Enumeration < JarEntry> eje = jf.entries(); jarURLs.put( jarFilename, jarFile.toURI().toURL()); FileOutputStream fos = null; while(eje.hasMoreElements()) { JarEntry je = eje.nextElement(); // look up for embedded jar files if (mpf.match(je.getName())) { //System.out.println("jar found:" + je.getName()); try { String fileExt = SharedStringUtil.valueAfterRightToken(je.getName(), "."); if (fileExt.equals(je.getName())) { fileExt = ""; } int length = je.getName().length() - fileExt.length(); // replace / with _ File tempFile = File.createTempFile(je.getName().substring(0, length), fileExt); if (deleteOnExit) { tempFile.deleteOnExit(); } fos = new FileOutputStream(tempFile); IOUtil.relayStreams(jf.getInputStream( je), fos, true); jarURLs.put(je.getName(), tempFile.toURI().toURL()); } catch( Exception e) { e.printStackTrace(); } finally { IOUtil.close(fos); } } } } finally { IOUtil.close(jf); } return jarURLs; } /** * Loads library from current JAR archive * * The file from JAR is copied into system temporary directory and then loaded. The temporary file is deleted after exiting. * Method uses String as filename because the pathname is "abstract", not system-dependent. * * @param path The filename inside JAR as absolute path (beginning with '/'), e.g. /package/File.ext * @throws IOException If temporary file creation or read/write operation fails * @throws IllegalArgumentException If source file (param path) does not exist * @throws IllegalArgumentException If the path is not absolute or if the filename is shorter than three characters (restriction). */ public static void loadLibraryFromJar(String path) throws IOException { if (!path.startsWith("/")) { throw new IllegalArgumentException("The path to be absolute (start with '/')."); } // Obtain filename from path String[] parts = path.split("/"); String filename = (parts.length > 1) ? parts[parts.length - 1] : null; // Split filename to prexif and suffix (extension) String prefix = ""; String suffix = null; if (filename != null) { parts = filename.split("\\.", 2); prefix = parts[0]; suffix = (parts.length > 1) ? "."+parts[parts.length - 1] : null; // Thanks, davs! :-) } // Check if the filename is okay if (filename == null || prefix.length() < 3) { throw new IllegalArgumentException("The filename has to be at least 3 characters long."); } // Prepare temporary file File temp = File.createTempFile(prefix, suffix); temp.deleteOnExit(); if (!temp.exists()) { throw new FileNotFoundException("File " + temp.getAbsolutePath() + " does not exist."); } // Prepare buffer for data copying byte[] buffer = new byte[1024]; int readBytes; // Open and check input stream InputStream is = JarTool.class.getResourceAsStream(path); if (is == null) { throw new FileNotFoundException("File " + path + " was not found inside JAR."); } // Open output stream and copy data between source file in JAR and the temporary file OutputStream os = new FileOutputStream(temp); try { while ((readBytes = is.read(buffer)) != -1) { os.write(buffer, 0, readBytes); } } finally { // If read/write fails, close streams safely before throwing an exception os.close(); is.close(); } // Finally, load the library System.load(temp.getAbsolutePath()); } public static ClassLoader createClassLoader( HashMap<String, URL> urls, ClassLoader parent) { URL[] all = urls.entrySet().toArray( new URL[0]); if (parent == null) { return new URLClassLoader( all); } else { return new URLClassLoader( all, parent); } } }
true
4a415aa0f8f8d4ec5742ed69d63803a00b81e19e
Java
joker-xjh/crawlers
/crawler/src/main/java/demo25/Singletons.java
UTF-8
1,427
3.1875
3
[]
no_license
package demo25; import java.lang.reflect.Constructor; import java.lang.reflect.InvocationTargetException; import java.util.Map; import java.util.concurrent.ConcurrentHashMap; @SuppressWarnings("all") public class Singletons { private static final Map<Class<?>, Object> singletonMap = new ConcurrentHashMap<>(); public static <T> T get(Class<?> clazz) { if(clazz == null) { throw new IllegalArgumentException(" class can not be null"); } if(!singletonMap.containsKey(clazz)) register(clazz); Object obj = singletonMap.get(clazz); if(clazz.isInstance(obj)) return (T) obj; throw new SingletonException("The singleton object " + clazz.getName() + " is not registered"); } private static void register(Class<?> clazz) { if(clazz.isAnnotationPresent(Singleton.class)) { try { Constructor<?> constructor = clazz.getDeclaredConstructor(); singletonMap.put(clazz, constructor.newInstance()); } catch (NoSuchMethodException e) { e.printStackTrace(); } catch (SecurityException e) { e.printStackTrace(); } catch (InstantiationException e) { e.printStackTrace(); } catch (IllegalAccessException e) { e.printStackTrace(); } catch (IllegalArgumentException e) { e.printStackTrace(); } catch (InvocationTargetException e) { e.printStackTrace(); } } throw new SingletonException(""); } }
true
db23532ab037e73929ca3d768e6222509363d0ac
Java
JehQueiroz/SistemaRestaurante
/app/src/main/java/br/edu/iff/pooa20162/sistemarestaurante/Activity/EscolhaCardapio.java
UTF-8
1,185
1.960938
2
[]
no_license
package br.edu.iff.pooa20162.sistemarestaurante.Activity; import android.content.Intent; import android.support.v7.app.AppCompatActivity; import android.os.Bundle; import android.widget.ArrayAdapter; import android.widget.Button; import android.widget.Spinner; import java.util.ArrayList; import br.edu.iff.pooa20162.sistemarestaurante.Model.Cardapio; import br.edu.iff.pooa20162.sistemarestaurante.R; public class EscolhaCardapio extends AppCompatActivity { Spinner pratos; Button btCriar, btSalvar; int id=0; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_escolha_cardapio); Intent intent = getIntent(); id = (int) intent.getSerializableExtra("id"); final ArrayList<Cardapio> burg = (ArrayList) Cardapio.listAll(Cardapio.class); ArrayAdapter<Cardapio> adapterB = new ArrayAdapter<Burguer>(this, android.R.layout.simple_spinner_item, burg); adapterB.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item); spB = (Spinner) findViewById(R.id.spinB); spB.setAdapter(adapterB); } }
true
cd3964c702f7499739a9df868a6df80fb878d72a
Java
KShashankReddy/Coushbase_Dagger
/TodoAdapter.java
UTF-8
1,733
2.453125
2
[]
no_license
package com.example.shashankreddy.couachbase_dagger_demo; import android.content.Context; import android.view.View; import android.view.ViewGroup; import android.widget.BaseAdapter; import android.widget.TextView; import com.couchbase.lite.Document; import java.util.ArrayList; /** * Created by shashank reddy on 2/8/2017. */ public class TodoAdapter extends BaseAdapter { private Context context; private ArrayList<Document> documentList; public TodoAdapter(Context context, ArrayList<Document> documentList) { this.context = context; this.documentList = documentList; } public int getCount() { return this.documentList.size(); } public Object getItem(int position) { return this.documentList.get(position); } public long getItemId(int position) { return 0; } public int getIndexOf(String id) { for(int i = 0; i < this.documentList.size(); i++) { if(this.documentList.get(i).getId().equals(id)) { return i; } } return -1; } public View getView(int position, View convertView, ViewGroup parent) { TextView todoTitle = null; Document currentDocument; try { if(convertView == null) { todoTitle = new TextView(this.context); todoTitle.setPadding(10, 25, 10, 25); } else { todoTitle = (TextView) convertView; } currentDocument = this.documentList.get(position); todoTitle.setText(String.valueOf(currentDocument.getProperty("todo"))); } catch (Exception e) { e.printStackTrace(); } return todoTitle; } }
true
4ef43e995f1599b4ec1d242f2567242d26d460e2
Java
josephEbolo/TP2Akinator
/src/UtilitaireFichier.java
ISO-8859-1
2,541
3.078125
3
[]
no_license
/** * Classe qui permet la gestion du fichier pour projet de jeu du divinateur (voir nonc tp2 e2018). * * @author pbelisle * @coauthor mnayrolles * @version E 2018 * */ import java.io.File; import java.io.FileInputStream; import java.io.FileNotFoundException; import java.io.FileOutputStream; import java.io.IOException; import java.io.ObjectInputStream; import java.io.ObjectOutputStream; import java.io.PrintStream; import java.nio.file.FileSystems; import java.nio.file.Files; import java.nio.file.Path; public class UtilitaireFichier { /** * Tente d'ouvrir le fichier NOM_FICHIER_BD. S'il n'existe pas, * la bd est vide. */ public static BdQuestionsReponses obtenirBd(){ /* * Stratgie : On utilise un FileInputStream qui permet de lire * la bd d'un coup, (comme elle a t sauvegarde). */ FileInputStream fic; BdQuestionsReponses bd = null; try { fic = new FileInputStream(Constantes.NOM_FICHIER_BD); // ouverture du tampon logique ObjectInputStream tampon = null; tampon = new ObjectInputStream(fic); bd = (BdQuestionsReponses)tampon.readObject(); tampon.close(); } // Si le fichier n'existe pas, on s'assure que tout est initialis. catch(FileNotFoundException e){ bd = new BdQuestionsReponses(); } // Problme lors de la lecture. On arrte. catch (ClassNotFoundException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } return bd; } /** * Sauvegarde la bd dans le fichier nomm par NOM_FICHIER_BD. * */ public static void sauvegarde(BdQuestionsReponses bd, String nomFic){ /* * Stratgie : On utilise un FileOutputStream qui permet de lire * la bd d'un coup. */ FileOutputStream fic; ObjectOutputStream tampon = null; try { //Cre le fichier fic = new FileOutputStream(nomFic); //Ouverture du tampon d'criture tampon = new ObjectOutputStream(fic); tampon.writeObject(bd); tampon.close(); } catch (FileNotFoundException e1) { e1.printStackTrace(); // Une erreur de lecture, on dtruit le fichier. } catch (IOException e) { // On obtient le chemin du fichier pour le dtruire. Path path = FileSystems.getDefault().getPath(Constantes.NOM_FICHIER_BD); try { tampon.close(); Files.delete(path); } catch (IOException e1) { e1.printStackTrace(); } e.printStackTrace(); } } }
true
ed622b89623a3dcfa5f40d639d2cdcbce207cd0f
Java
stiven-metrio/back-end-hulksotre
/src/main/java/com/jssm/kardex/KardexApplication.java
UTF-8
506
1.734375
2
[]
no_license
package com.jssm.kardex; import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.SpringBootApplication; import org.springframework.context.annotation.ComponentScan; @SpringBootApplication @ComponentScan(basePackages = {"com.sealor.kardex.controller", "com.sealor.kardex.service", "com.sealor.kardex.repository"}) public class KardexApplication { public static void main(String[] args) { SpringApplication.run(KardexApplication.class, args); } }
true
cfa66d8756f37a6e8a81172108730106a6ef6dd8
Java
de-tu-berlin-tfs/Henshin-Editor
/de.tub.tfs.agg/src/agg/gui/treeview/TreeViewActionAdapter.java
UTF-8
3,357
2.46875
2
[]
no_license
package agg.gui.treeview; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import javax.swing.JCheckBoxMenuItem; import javax.swing.JMenuItem; public class TreeViewActionAdapter implements ActionListener { private final GraGraTreeView treeView; public TreeViewActionAdapter(GraGraTreeView treeview) { super(); this.treeView = treeview; } public GraGraTreeView getTreeView() { return this.treeView; } @Override /* Implements the actionPerformed method of the ActionListener */ public void actionPerformed(ActionEvent e) { String command = e.getActionCommand(); if (command.equals("undirectedArcs")) { this.treeView.setUndirectedArcsOfGraphs(e); } else if (command.equals("nonparallelArcs")) { this.treeView.setNoParallelArcsOfGraphs(e); } else if (command.equals("checkEmptyAttrs")) { this.treeView.setCheckEmptyAttrs(e); } else if (command.equals("layered")) { this.treeView.setGraTraOption_layered(e); } else if (command.equals("priority")) { this.treeView.setGraTraOption_priority(e); } else if (command.equals("ruleSequence")) { this.treeView.setGraTraOption_ruleSequence(e); } else if (command.equals("nondeterministically")) { this.treeView.setGraTraOption_nondeterministically(); } else if (command.equals("disableRuleScheme")) { if (e.getSource() instanceof JCheckBoxMenuItem) { if (((JMenuItem) e.getSource()).isSelected()) this.treeView.executeCommand("disableRuleScheme"); else this.treeView.executeCommand("enableRuleScheme"); } } else if (command.equals("disableRule")) { if (e.getSource() instanceof JCheckBoxMenuItem) { if (((JMenuItem) e.getSource()).isSelected()) this.treeView.executeCommand("disableRule"); else this.treeView.executeCommand("enableRule"); } } else if (command.equals("disableNAC")) { if (e.getSource() instanceof JCheckBoxMenuItem) { if (((JMenuItem) e.getSource()).isSelected()) this.treeView.executeCommand("disableNAC"); else this.treeView.executeCommand("enableNAC"); } } else if (command.equals("disablePAC")) { if (e.getSource() instanceof JCheckBoxMenuItem) { if (((JMenuItem) e.getSource()).isSelected()) this.treeView.executeCommand("disablePAC"); else this.treeView.executeCommand("enablePAC"); } } else if (command.equals("disableNestedAC")) { if (e.getSource() instanceof JCheckBoxMenuItem) { if (((JMenuItem) e.getSource()).isSelected()) this.treeView.executeCommand("disableNestedAC"); else this.treeView.executeCommand("enableNestedAC"); } } else if (command.equals("disableAttrCondition")) { if (e.getSource() instanceof JCheckBoxMenuItem) { if (((JMenuItem) e.getSource()).isSelected()) this.treeView.executeCommand("disableAttrCondition"); else this.treeView.executeCommand("enableAttrCondition"); } } else if (command.equals("disableConstraint")) { if (e.getSource() instanceof JCheckBoxMenuItem) { if (((JMenuItem) e.getSource()).isSelected()) this.treeView.executeCommand("disableConstraint"); else this.treeView.executeCommand("enableConstraint"); } } else this.treeView.executeCommand(command); } }
true
010c29ea3c7c8daa5d038069b986ae7a7980942a
Java
snadschlaeger-faw-jku/task2-results
/atm-2/src/main/java/Test.java
UTF-8
3,607
2.65625
3
[]
no_license
package main.java; import main.java.model.Clause; import main.java.model.Fact; import main.java.model.Rule; import main.java.model.Slot; public class Test { private static BruteForceIE b = new BruteForceIE(); private static void initData() { Fact fact = new Fact("creditCard"); Slot slot = new Slot("cardNumber", "java.lang.String", "123", true); fact.slots.add(slot); Slot slot1 = new Slot("cardActive", "java.lang.Boolean", true,false); fact.slots.add(slot1); // Fact fact2 = new Fact("pin"); // Slot slot2 = new Slot("cardNumber", "java.lang.String", "123", true); // fact2.slots.add(slot2); // Slot slot3 = new Slot("pinCode", "java.lang.String", "123",true); // fact2.slots.add(slot3); KnowledgeBase.facts.add(fact); // KnowledgeBase.facts.add(fact2); } private static void initRules() { Rule rule = new Rule(); rule.logicalOperator=RuleOperator.AND; rule.name = "checkCard"; Fact card123Fact = new Fact("creditCard"); Slot card123Slot = new Slot("cardNumber", "java.lang.String", "123", true); card123Fact.slots.add(card123Slot); Slot card123ActiveSlot = new Slot("active", "java.lang.Boolean", true, false); card123Fact.slots.add(card123ActiveSlot); Clause condition = new Clause(ClauseOperators.exists, card123Fact); Clause consequence = new Clause(ClauseOperators.print, "Hello world"); rule.conditions.add(condition); rule.consequences.add(consequence); KnowledgeBase.rules.add(rule); } private static void initRules1() { Rule rule = new Rule(); rule.logicalOperator=RuleOperator.AND; rule.name = "checkCard"; Fact card123Fact = new Fact("creditCard"); Slot card123Slot = new Slot("cardNumber", "java.lang.String", "123", true); card123Fact.slots.add(card123Slot); Slot card123ActiveSlot = new Slot("active", "java.lang.Boolean", true, false); card123Fact.slots.add(card123ActiveSlot); Clause condition = new Clause(ClauseOperators.exists, card123Fact); Fact card123Pin = new Fact("pin"); //Slot card123CardNumber = new Slot("cardNumber", "java.lang.String", "123", true); Slot card123PinCode = new Slot("pinCode", "java.lang.String", null, true); card123Pin.slots.add(card123PinCode); //card123Pin.slots.add(card123CardNumber); Clause consequence = new Clause(ClauseOperators.assertFact, card123Pin); rule.conditions.add(condition); rule.consequences.add(consequence); KnowledgeBase.rules.add(rule); } private static void initRules2() { Rule rule = new Rule(); rule.logicalOperator=RuleOperator.AND; rule.name = "checkCard"; Fact card123Fact = new Fact("creditCard"); Slot card123Slot = new Slot("cardNumber", "java.lang.String", "123", true); card123Fact.slots.add(card123Slot); Slot card123ActiveSlot = new Slot("active", "java.lang.Boolean", true, false); card123Fact.slots.add(card123ActiveSlot); Clause condition = new Clause(ClauseOperators.exists, card123Fact); Fact card123Pin = new Fact("pin"); //Slot card123PinCardNumber = new Slot("cardNumber", "java.lang.String", "123", true); //card123Pin.slots.add(card123PinCardNumber); Slot card123PinCode = new Slot("pinCode", "java.lang.String", "123", true); card123Pin.slots.add(card123PinCode); Clause condition2 = new Clause(ClauseOperators.exists, card123Pin); rule.conditions.add(condition); rule.conditions.add(condition2); Clause consequence = new Clause(ClauseOperators.print, "OK"); rule.consequences.add(consequence); KnowledgeBase.rules.add(rule); } public static void main(String[] args) { initData(); initRules1(); initRules2(); b.checkRules(); } }
true
8494a26df892fa2f91633f36a39601b4f9f3ab01
Java
peter-stephen-stiles/one-edd
/src/main/java/com/nobbysoft/first/server/dao/EquipmentClassDAO.java
UTF-8
9,350
2.21875
2
[]
no_license
package com.nobbysoft.first.server.dao; import java.lang.invoke.MethodHandles; import java.sql.Connection; import java.sql.PreparedStatement; import java.sql.ResultSet; import java.sql.SQLException; import java.util.ArrayList; import java.util.List; import org.apache.logging.log4j.LogManager; import org.apache.logging.log4j.Logger; import com.nobbysoft.first.common.entities.equipment.EquipmentClass; import com.nobbysoft.first.common.entities.equipment.EquipmentClassKey; import com.nobbysoft.first.common.utils.CodedListItem; import com.nobbysoft.first.common.utils.ReturnValue; import com.nobbysoft.first.common.views.ViewClassEquipment; import com.nobbysoft.first.server.utils.DbUtils; public class EquipmentClassDAO extends AbstractDAO<EquipmentClass, EquipmentClassKey> implements DAOI<EquipmentClass, EquipmentClassKey> { private static final Logger LOGGER = LogManager.getLogger(MethodHandles.lookup().lookupClass()); private String tableName = "equipment_class"; public EquipmentClassDAO() { } @Override public void createTable(Connection con) throws SQLException { String sql = "CREATE TABLE " + tableName + " (type varchar(20), code varchar(20) , class_id varchar(20) , " + "PRIMARY KEY (type, code, class_id) )"; if (DbUtils.doesTableExist(con, tableName)) { } else { try (PreparedStatement ps = con.prepareStatement(sql);) { ps.execute(); } } } public void createConstraints(Connection con) throws SQLException { String sql; { // add constraints String column = "class_id"; String constraintName = "ect_to_class"; if (!DbUtils.isTableColumnFK(con, tableName, column, "character_class")) { String otherColumn = "class_id"; String otherTable = "character_class"; sql = "ALTER TABLE " + tableName + " add constraint " + constraintName + " foreign key (" + column + ") references " + otherTable + "(" + otherColumn + ") "; try (PreparedStatement ps = con.prepareStatement(sql);) { ps.execute(); } catch (Exception ex) { LOGGER.error("Error running SQL\n" + sql, ex); throw ex; } } } }; private String[] keys = new String[] { "type", "code", "class_id" }; private String[] data = new String[] {}; String[] getKeys() { return keys; } String[] getData() { return data; } String addOrderByClause(String sql) { sql = sql + "ORDER BY type,code,class_id "; return sql; } EquipmentClass dtoFromRS(ResultSet rs) throws SQLException { EquipmentClass dto = new EquipmentClass(); int col = 1; dto.setType(rs.getString(col++)); dto.setCode(rs.getString(col++)); dto.setClassId(rs.getString(col++)); return dto; } void setPSFromKey(PreparedStatement ps, EquipmentClassKey key) throws SQLException { ps.setString(1, key.getType()); ps.setString(2, key.getCode()); ps.setString(3, key.getClassId()); } String getTableName() { return tableName; } int setPSFromKeys(EquipmentClass value, PreparedStatement ps, int col) throws SQLException { ps.setString(col++, value.getType()); ps.setString(col++, value.getCode()); ps.setString(col++, value.getClassId()); return col; } int setPSFromData(EquipmentClass value, PreparedStatement ps, int col) throws SQLException { return col; } String getSELECTForCodedList() { return "SELECT type,code,class_id FROM " + getTableName() + " ORDER BY type,code,class_id"; } void setCodedListItemFromRS(CodedListItem<EquipmentClassKey> dto, ResultSet rs) throws SQLException { EquipmentClassKey eck = new EquipmentClassKey(rs.getString(1), rs.getString(2), rs.getString(3)); dto.setItem(eck); dto.setDescription(eck.toString()); } String getFilterWhere() { return " ? = class_id "; }; void setFilterParameters(PreparedStatement ps, String filter) throws SQLException { ps.setString(1, filter); } private String viewSelect = "select type,code,equipment_name,class_id,class_name,true from view_equipment_class "; public List<ViewClassEquipment> getViewForClass(Connection con, String classId0 )throws SQLException{ List<ViewClassEquipment> list = new ArrayList<>(); String sql = viewSelect + " WHERE class_id = ?"; try(PreparedStatement ps = con.prepareStatement(sql)){ ps.setString(1, classId0); readView(list, ps); } return list; } private void readView(List<ViewClassEquipment> list, PreparedStatement ps) throws SQLException { try(ResultSet rs = ps.executeQuery()){ while(rs.next()) { int col=1; String type = rs.getString(col++); String code = rs.getString(col++); String equipmentName = rs.getString(col++); String classId = rs.getString(col++); String className = rs.getString(col++); boolean assigned=rs.getBoolean(col++); EquipmentClass equipmentClass = new EquipmentClass(); equipmentClass.setClassId(classId); equipmentClass.setCode(code); equipmentClass.setType(type); ViewClassEquipment vce = new ViewClassEquipment(); vce.setClassName(className); vce.setEquipmentClass(equipmentClass); vce.setEquipmentName(equipmentName); vce.setAssigned(assigned); list.add(vce); } } } public List<ViewClassEquipment> getViewForEquipmentType(Connection con, String type) throws SQLException{ List<ViewClassEquipment> list = new ArrayList<>(); String sql = viewSelect + " WHERE type = ?"; try(PreparedStatement ps = con.prepareStatement(sql)){ ps.setString(1, type); readView(list, ps); } return list; } public List<ViewClassEquipment> getViewForEquipment(Connection con, String type,String code) throws SQLException{ List<ViewClassEquipment> list = new ArrayList<>(); String sql = viewSelect + " WHERE type = ? AND code = ?"; try(PreparedStatement ps = con.prepareStatement(sql)){ ps.setString(1, type); ps.setString(2, code); readView(list, ps); } return list; } private String viewSelectAll0 = "select ve.type,ve.code,ve.name as equipment_name, cc.class_id, cc.name as class_name ," + "((select count(*) " + " from view_equipment_class vec " + " where vec.type = ve.type " + " and vec.code = ve.code " + " and vec.equipment_name = ve.name " + " and vec.class_id = cc.class_id) = 1) as is_there " + " from view_equipment ve " + "cross join character_class cc " + " WHERE cc.class_id = ? "; public List<ViewClassEquipment> getViewForClassAll(Connection con, String classId0 )throws SQLException{ List<ViewClassEquipment> list = new ArrayList<>(); { String sql = viewSelectAll0; try(PreparedStatement ps = con.prepareStatement(sql)){ ps.setString(1, classId0); readView(list, ps); } } return list; } public ReturnValue<String> updateViewForEquipmentAll(Connection con, String type,String code,List<ViewClassEquipment> list) throws SQLException{ // remove all for class int rc = 0; { String del = "DELETE FROM "+tableName+" WHERE type = ? AND code = ?"; try(PreparedStatement ps = con.prepareStatement(del)){ ps.setString(1, type); ps.setString(2, code); rc = ps.executeUpdate(); } } int ins =0; { for(ViewClassEquipment vce: list) { // if(!vce.getEquipmentClass().getType().name().equals(type)) { // throw new SQLException("Wrong type on "+vce); // } if(!vce.getEquipmentClass().getCode().equals(code)) { throw new SQLException("Wrong code on "+vce); } if(vce.isAssigned()) { insert(con,vce.getEquipmentClass()); ins++; } } } String results = "Deleted "+rc+ " inserted "+ins+" valid classes for equipment."; // all good :) Do a Billy Joel return new ReturnValue<>(results); } public ReturnValue<String> updateViewForClassAll(Connection con, String classId, List<ViewClassEquipment> list )throws SQLException{ // remove all for class int rc = 0; { String del = "DELETE FROM "+tableName+" WHERE class_id = ?"; try(PreparedStatement ps = con.prepareStatement(del)){ ps.setString(1, classId); rc = ps.executeUpdate(); } } int ins =0; { for(ViewClassEquipment vce: list) { if(!vce.getEquipmentClass().getClassId().equals(classId)) { throw new SQLException("Wrong class id on "+vce); } if(vce.isAssigned()) { insert(con,vce.getEquipmentClass()); ins++; } } } String results = "Deleted "+rc+ " inserted "+ins+" valid equipment for class ."; // all good :) Do a Billy Joel return new ReturnValue<>(results); } private String viewSelectAll2 = "select ve.type,ve.code,ve.name as equipment_name, cc.class_id, cc.name as class_name ," + "((select count(*) " + " from view_equipment_class vec " + " where vec.type = ve.type " + " and vec.code = ve.code " + " and vec.equipment_name = ve.name " + " and vec.class_id = cc.class_id) = 1) as is_there " + " from view_equipment ve " + "cross join character_class cc " + " WHERE ve.type= ? "+ " AND ve.code= ? "; public List<ViewClassEquipment> getViewForEquipmentAll(Connection con, String type,String code) throws SQLException{ List<ViewClassEquipment> list = new ArrayList<>(); String sql = viewSelectAll2; try(PreparedStatement ps = con.prepareStatement(sql)){ ps.setString(1, type); ps.setString(2, code); readView(list, ps); } return list; } }
true
36f5caf02d809252dfad2b19e86b1b13da1c46ca
Java
riadhmoussa/Agenda-Sport
/app/src/main/java/com/pfeisims/riadh/notessport/AdapterIMC.java
UTF-8
461
1.992188
2
[]
no_license
package com.pfeisims.riadh.notessport; /** * Created by Riadh on 07/12/2017. */ public class AdapterIMC { public String ID; public String Date; public String Poids; public String Taille; public String CalImc; //for news details AdapterIMC(String ID,String Date, String Poids, String Taille,String CalImc) { this. Date=Date; this. Poids=Poids; this.Taille=Taille; this.CalImc=CalImc; } }
true
b0bf69ce71b16ac6ce0fc0cce711bafe20f15c02
Java
wang346490410/renren_fast_pro
/renren-fast/src/main/java/io/renren/modules/job/entity/QuartzInfoModel.java
UTF-8
3,145
2.46875
2
[ "Apache-2.0" ]
permissive
package io.renren.modules.job.entity; import java.io.Serializable; import java.util.Date; /** * @Discription * @Date Create in 2017/12/18 14:09 * @Author wdl * @Modified by: */ public class QuartzInfoModel implements Serializable { private static final long serialVersionUID = 1L; /** * ไธป้”ฎId */ private Long id; /** * ๅฎšๆ—ถไปปๅŠกๅ็งฐ */ private String name; /** * ๅฎšๆ—ถไปปๅŠกๆ ‡่ฏ† */ private String code; /** * ๅฎšๆ—ถไปปๅŠกๆ‰ง่กŒๅ‘จๆœŸ */ private String cycle; /** * ๅฎšๆ—ถไปปๅŠกๆ‰ง่กŒ็ฑป */ private String className; /** * ๆˆๅŠŸๆ‰ง่กŒๆฌกๆ•ฐ */ private Integer succeed; /** * ๅคฑ่ดฅๆ‰ง่กŒๆฌกๆ•ฐ */ private Integer fail; /** * ๆ˜ฏๅฆๅฏ็”จ 10-ๅฏ็”จ 20-็ฆ็”จ */ private String state; /** * ๅˆ›ๅปบๆ—ถ้—ด */ private Date createTime; /** * ไปปๅŠก็Šถๆ€ๆ่ฟฐ */ private String stateStr; /** * ไธŠๆฌกๆ‰ง่กŒๆ—ถ้—ด */ private Date lastStartTime; public Long getId() { return id; } public void setId(Long id) { this.id=id; } public String getName() { return name; } public void setName(String name) { this.name=name; } public String getCode() { return code; } public void setCode(String code) { this.code=code; } public String getCycle() { return cycle; } public void setCycle(String cycle) { this.cycle=cycle; } public String getClassName() { return className; } public void setClassName(String className) { this.className=className; } public Integer getSucceed() { return succeed; } public void setSucceed(Integer succeed) { this.succeed=succeed; } public Integer getFail() { return fail; } public void setFail(Integer fail) { this.fail=fail; } public String getState() { return state; } public void setState(String state) { this.state=state; } public Date getCreateTime() { return createTime; } public void setCreateTime(Date createTime) { this.createTime=createTime; } public String getStateStr() { return stateStr; } /** * ่ฎพ็ฝฎไปปๅŠก็Šถๆ€ๆ่ฟฐ * @param stateStr */ public void setStateStr(String stateStr) { this.stateStr = stateStr; } /** * ่Žทๅ–ไธŠๆฌกๆ‰ง่กŒๆ—ถ้—ด * * @return lastStartTime */ public Date getLastStartTime() { return lastStartTime; } /** * ่ฎพ็ฝฎไธŠๆฌกๆ‰ง่กŒๆ—ถ้—ด * * @param lastStartTime */ public void setLastStartTime(Date lastStartTime) { this.lastStartTime = lastStartTime; } /** * ็Šถๆ€ไธญๆ–‡่ฝฌๆข * @return */ // public void stateConvert() { // if (QuartzStateEnum.ENABLED.getState().equals(state)) { // stateStr = "ๅฏ็”จ"; // } else { // stateStr = "็ฆ็”จ"; // } // } }
true
cf7048b364305665a0a76e1b32732522c0a2e997
Java
sophinewman/SHPRC-POS-new
/src/HelveticaJLabel.java
UTF-8
626
3.421875
3
[]
no_license
import java.awt.Font; import javax.swing.BorderFactory; import javax.swing.JLabel; /** * Creates a JLabel with the font pre-set to bold Helvetica of the specified size. * Used for convenience; has no additional functionality. * * @author Sophi Newman * @version 1.0 03/20/2013 */ public class HelveticaJLabel extends JLabel { /** * Class constructor. * @param str the text to be displayed * @param size the desired font size */ public HelveticaJLabel(String str, int size) { super(str); this.setBorder(BorderFactory.createEmptyBorder(1, 4, 1, 4)); this.setFont(new Font("Helvetica", Font.BOLD, size)); } }
true
9b0b26cc7ef01fdcf31300b0f0cda9638f396f4e
Java
Albouvard/AppBoiteAOutil
/AndroidProject4/app/src/main/java/com/example/bilal/androidproject/model/Country.java
UTF-8
746
2.6875
3
[]
no_license
package com.example.bilal.androidproject.model; import java.util.List; import androidx.annotation.NonNull; public class Country { public String alpha3,currencyName; public Country(String alpha3, String currencyName){ this.alpha3=alpha3; this.currencyName=currencyName; } public String getAlpha3() { return alpha3; } public String getCurrencyName() { return currencyName; } public void setAlpha3(String alpha3) { this.alpha3 = alpha3; } public void setCurrencyName(String currencyName) { this.currencyName = currencyName; } @NonNull @Override public String toString() { return getAlpha3() + " - " + getCurrencyName(); } }
true
3dba3e8ad300421ba4d1ed328f5c9cc9f4728c2f
Java
danielau/Network-Project
/Board.java
UTF-8
14,891
3.609375
4
[]
no_license
//BOARD MODULE package player; import java.util.Arrays; import list.*; /** * A class that is extended by all Network players (human and machine). * This is the player's internal representation of the board. * This representation of the board is intended for the Game Tree Search Module to get and set contents on the board. */ //Constructor for Board class - constructs an 8 by 8 2D array public class Board { public final static int EMPTY = -1; public final static int BLACK = 0; public final static int WHITE = 1; private int[][] gameBoard = new int[8][8]; private int whitePiecesLeft = 10; private int blackPiecesLeft = 10; //Board Corners private final static int[] BOTTOM_RIGHT = {7, 7}; private final static int[] TOP_RIGHT = {7, 0}; private final static int[] BOTTOM_LEFT = {0, 7}; private final static int[] TOP_LEFT = {0, 0}; // More Fields to include : Goal Areas, Rows, Columns, Diagonals private static final Object GOAL = new Object(); private static final Object BEENHERE = new Object(); public Board() { for (int x = 0; x<8; x++) { for (int y =0; y<8; y++) { gameBoard[x][y] = Board.EMPTY; } } } //DO END CHECKING FOR THESE?? /**Gets all chips in the specified column * @param x the x coordinate of the column being accesseed * @return an array of ints representing every chip in the row */ private DList getColumn(int x){ DList col = new DList(); for (int j =0; j<8;j++){ int[] item = {x, j}; col.insertBack(item); } return col; } /** * Gets all chips in the specified row * @param y the y coordinate of the row being accessed * @return an array of ints representing every chip in the row */ private DList getRow(int y){ DList row = new DList(); for (int i=0;i<8;i++){ int[] item = {i,y}; row.insertBack(item); } return row; } /** * Gets all the position of the diagonals of the specified point, in all 4 directions * @param x the x coordinate of the point you wish to start at * @param y the y coordinate of the point you wish to start at * @return a list of ints representing every position in the diagonals */ private DList[] getDiagonals(int x, int y){ DList[] diags = new DList[4]; //up left DList upLeft = new DList(); i=x-1; j=y-1; int[] item = {i,j}; while(i>0 && j>0){ upLeft.insertBack(item); i--; j--; } diags[0] = upLeft; //up right DList upRight = new DList(); i=x+1; j=y-1; while(i<7 && j>0){ upRight.insertBack(item); i++; j--; } diags[1] = upRight; //low left DList lowLeft = new DList(); i=x-1; j=y+1; while(i>0 && j<7){ lowLeft.insertBack(item); i--; j++; } diags[2] = lowLeft; //low right DList lowRight= new DList(); i=x+1; j=y+1; while (i<7 && j<7){ lowRight.insertBack(item); i++; j++; } diags[3] = lowRight; return diags; } private boolean isCorner(int x, int y){ int[] coord = {x,y}; if (Arrays.equals(coord, TOP_RIGHT) || Arrays.equals(coord, TOP_LEFT) || Arrays.equals(coord, BOTTOM_RIGHT) || Arrays.equals(coord, BOTTOM_LEFT)){ return true; }else return false; } private int[][] neighbors(int x, int y){ int[][] n = {{x,y+1}, {x,y-1}, {x+1,y+1}, {x+1,y-1}, {x+1,y},{x-1,y},{x-1,y-1},{x-1,y+1}}; /*int[] n ={getSquare(x, y+1), getSquare(x,y-1), getSqaure(x+1,y+1), getSquare(x+1,y-1), getSquare(x+1,y), getSquare(x-1,y),getSquare(x-1,y-1), getSquare(x-1,y+1)};*/ return n; } private boolean isClustered(int x, int y){ int playerColor = getSquare(x,y); int[][] n= neighbors(x,y); for (int i =0; i<neighbors(x,y).length;i++){ if (getSquare(n[i][0],n[i][1])== playerColor){ int[][] b = neighbors(); } } } //VALID MOVES MODULE /*Uses the rules of the game and positions of the current chips *to generate a list of valid moves *@return an array of Move objects which represent valid moves for the current game situation */ private DList validMoves(int playerColor){ //Implemented for add move type only DList moves = new DList(); for (int i = 0; i<8; i++){ for (int j =0;j<8;j++){ Move m = new Move(i,j); if(isValidMove(m,playerColor)){ moves.insertBack(m); } } } } /*Determines whether a move is valid or not *@return a Move object if the move requested is valid *null otherwise */ protected Move isValidMove(Move m, int playerColor) { //implemented for add move type only if (getSquare(m.x1,m.y1) == -1 && !isCorner(m.x1,m,y1)){ if (playerColor == BLACK){ if (!inGoalArea(WHITE) && !isClustered(m.x1,m.y1,BLACK)){ return true; } }else if (playerColor == WHITE){ if (!inGoalArea(BLACK) && !isClustered(m.x1,m.y1,WHITE)){ return true; } }else return false; } return false; } //Methods to Include - makeMove, getSquare, hasNetwork, inGoalArea, currentConnections // More Methods - getRows, getColumns, isCorner, isOccupied, getSurroundings, getDiagonals // /* makeMove takes a legal move and an int player and changes the board. It can make an add move or a step move and it labels the move as which it is. It adds the piece and needs to decrement the amount of pieces left for each player. @param m - Takse in a move to make @ param playerColor - Determines which player the move is made for for chip color */ protected void makeMove(Move m, int playerColor){ if (m.moveKind == Move.ADD) { gameBoard[m.x1][m.y1] = playerColor; if (playerColor == Board.WHITE) { whitePiecesLeft--; } if (playerColor == Board.BLACK) { blackPiecesLeft--; } } else if (m.moveKind == Move.STEP) { gameBoard[m.x2][m.y2] = Board.EMPTY; gameBoard[m.x1][m.y1] = playerColor; } } /* hasNetwork returns true if this board has a network with 6 or greater length. It otherwise *returns false. It takes in a player because it is called on the board. *@param player the player whose network is being determined *@return true is this board has a network with 6 or greater length *false otherwise * */ protected boolean hasNetwork (int playerColor){ /* 1. Create Start dlist 2. Create end dlist Make them hashtables 3. call currentconnections on the start point for max ten times for each point check if in end hashtables, otherwise */ if (playerColor == WHITE){ if (this.whitePiecesLeft > 4 || !inGoalArea(playerColor)) { return false; } } if (playerColor == BLACK){ if (this.blackPiecesLeft > 4 || !inGoalArea(playerColor)){ return false; } } else { DList startGoals = this.goalPieces(player, 0); DList endGoals = this.goalPieces(player, 7); HashTable start = new HashTable(startGoals.length()); DListNode current = startGoals.front(); while (current != null) { start.insert(Arrays.hashCode((int[]) current.item()), GOAL); current = current.next(); } HashTable end = new HashTable(endGoals.length()); DListNode otherCurrent = endGoals.front(); while (otherCurrent != null) { end.insert(Arrays.hashCode((int[]) otherCurrent.item()), GOAL); otherCurrent = otherCurrent.next(); } HashTable possibleConnections = new HashTable(11); // Prime Number greater than 8 for all connections DListNode first = startGoals.front(); while (first != null) { int[] firstCoordinate = (int[]) first.item(); if (playerColor == WHITE){ HashTable currentNetworkTracker = new HashTable(10 - this.whitePiecesLeft); }else{ HashTable currentNetworkTracker = new HashTable (10 - this.blackPiecesLeft); } currentNetworkTracker.insert(Arrays.hashCode(firstCoordinate), BEENHERE); // Visited this coordinate already DList connectionsToVisit = this.currentConnections(firstCoordinate[0], firstCoordinate[1]); possibleConnections.insert(Arrays.hashCode(firstCoordinate), connectionsToVisit); if (travel(firstCoordinate, 2, start,end,possibleConnections,currentNetworkTracker)) { return true; } first = first.next(); } return false; } } private boolean travel(int[] startCoord, int piecesUsed, HashTable start, HashTable end, HashTable connections, HashTable currentNetwork) { DList currentconnections = (DList) connections.find(Arrays.hashCode(startCoord)).value(); DListNode counter = currentconnections.front(); while (counter != null){ boolean insideGoalArea = false; next = (int[]) counter.item(); int nextKey = Arrays.hashCode(next); Entry startPosition = start.find(nextKey); if (startPosition != null && startPosition.value() == GOAL) { insideGoalArea = true; } Entry middlePoint = currentNetwork.find(nextKey); if (middlePoint == null && !insideGoalArea) { currentNetwork.insert(nextKey, BEENHERE); if (connections.find(nextKey) == null) { DList newconnections = this.currentConnections(next[0], next[1]); connections.insert(nextKey,newconnections); } Entry endPosition= end.find(nextKey); if (endPosition != null && endPosition.value() == GOAL) { if (piecesUsed >= 6){ return true; } else currentNetwork.remove(nextKey); return false; } if (travel(next, piecesUsed + 1, start, end, connections, currentNetwork)) { return true; } else { currentNetwork.remove(nextKey); } } counter = counter.next(); } return false; } /* inGoalArea is called on this board and takes in a player. It checks if that player has any chips in the goal area. @param player is the player we are checking if they have pieces in the goal area. @returns true if there are pieces in the goal area or false if there are none. */ protected boolean inGoalArea(int playerColor) { boolean goalarea1 = false; boolean goalarea2 = false; if (playerColor == WHITE){ for (int y = 1; y < 7; y++){ if (this.getSquare(0,y) == WHITE){ goalarea1 = true; } } for (int y = 1; y < 7; y++){ if (this.getSquare(7,y) == playerColor){ goalarea2 = true; } } } if (playerColor == BLACK){ for (int x = 1; x < 7; x++){ if(this.getSquare(x,0) == BLACK){ goalarea1 = true; } } for (int x = 1; x < 7; x++){ if (this.getSquare(x,7) == BLACK){ goalarea2 = true; } } } return goalarea1 && goalarea2; } private DList goalPieces (int playerColor, int x) { DList piecesInGoalArea = new DList(); for (int y = 1; y < 7; y++) { if (playerColor == WHITE) { if (this.getSquare(x, y) == WHITE) { int[] coordinate = {x, y}; piecesInGoalArea.insertBack(coordinate); } } else{ if (this.getSquare(y, x) == BLACK) { int[] coordinate = {y, x}; piecesInGoalArea.insertBack(coordinate); } } } return piecesInGoalArea; } /* currentConnections returns a DList with all the pieces containing a connection to given coordinate. * This is used to build a network. *@param x the x coordinate of the board *@param y the y coordinate of the board *@return a DList with all the spots on the board (Move items) containing a connection to the coordinate */ protected DList currentConnections(int x, int y){ int piece = getSquare(x,y); int opp; DList row = getRow(x); DList col = getColumn(y); DList[] diagonals = getDaigonals(x,y); DList connections = new DList(); if (piece == 0){ opp = 1; }else if (piece == 1){ opp=0; }else{ //the positinon is empty, so can have no connections return connections; } //search through the row starting at the y //if you hit a chip of the same color, add its coordinate to the list //going forward in row DListNode n = row.front(); for (int i=0; i<x;i++){ n=n.next(); } while (n != null){ if (getSquare(n.item()[0], n.item()[1]) == piece){ connections.insertFront(n.item); break; }else if (getSquare(n.item()[0], n.item()[1]) == opp){ break; } n=n.next(); } //going backward in row DListNode n = row.front(); for (int i=0; i<x;i++){ n=n.next(); } while (n != null){ if (getSquare(n.item()[0], n.item()[1]) == piece){ connections.insertFront(n.item); break; }else if (getSquare(n.item()[0], n.item()[1]) == opp){ break; } n=n.prev(); } //going up in column DListNode n = col.front(); for (int i=0; i<y;i++){ n=n.next(); } while (n != null){ if (getSquare(n.item()[0], n.item()[1]) == piece){ connections.insertFront(n.item); break; }else if (getSquare(n.item()[0], n.item()[1]) == opp){ break; } n=n.next(); } //going down in column DListNode n = col.front(); for (int i=0; i<y;i++){ n=n.next(); } while (n != null){ if (getSquare(n.item()[0], n.item()[1]) == piece){ connections.insertFront(n.item); break; }else if (getSquare(n.item()[0], n.item()[1]) == opp){ break; } n=n.prev(); } //diagonals for (int i=0;i<4;i++){ DListNode n = diagonasl[i].front(); while (n != null){ if (getSquare(n.item()[0], n.item()[1]) == piece){ connections.insertFront(n.item); break; }else if (getSquare(n.item()[0], n.item()[1]) == opp){ break; } n=n.next(); } } return connections; } /* getSquare determines the contents of the board at a given coordinate *@param x the x coordinate of the spot *@param y the y coordinate of the spot *@return the contents of the board in that spot (-1, 0, 1 for empty, black, or white) */ protected int getSquare(int x, int y) { if (x<0 || x>7 || y<0 || y>7) { return Board.EMPTY; } else { return gameBoard[x][y]; } } }
true
56cf2482a4e908fcadacc4bbcbd2e34bef51967f
Java
testify-project/testify
/modules/junit4/junit4-core/src/test/java/org/testifyproject/junit4/core/TestifyJUnit4RunNotifierTest.java
UTF-8
6,327
1.820313
2
[ "Apache-2.0" ]
permissive
/* * Copyright 2016-2017 Testify Project. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.testifyproject.junit4.core; import static org.mockito.ArgumentMatchers.any; import static org.mockito.BDDMockito.given; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.verify; import java.util.List; import org.junit.Before; import org.junit.Test; import org.junit.internal.AssumptionViolatedException; import org.junit.runner.Description; import org.junit.runner.notification.Failure; import org.junit.runner.notification.RunNotifier; import org.junit.runners.model.MultipleFailureException; import org.testifyproject.guava.common.collect.ImmutableList; /** * * @author saden */ public class TestifyJUnit4RunNotifierTest { TestifyJUnit4RunNotifier sut; RunNotifier runNotifier; Description testDescription; @Before public void init() { runNotifier = mock(RunNotifier.class); testDescription = mock(Description.class); sut = TestifyJUnit4RunNotifier.of(runNotifier, testDescription); } @Test(expected = NullPointerException.class) public void givenNullFailureFireTestAssumptionsFailedShouldThrowException() { sut.fireTestAssumptionFailed(null); } @Test @SuppressWarnings("ThrowableResultIgnored") public void givenFailureWithMethodNameFireTestAssumptionsFailedShouldFireAssumptionFailed() { Failure failure = mock(Failure.class); Description failureDescription = mock(Description.class); String methodName = "methodName"; Throwable exception = mock(Throwable.class); given(failure.getDescription()).willReturn(failureDescription); given(failureDescription.getMethodName()).willReturn(methodName); given(failure.getException()).willReturn(exception); sut.fireTestAssumptionFailed(failure); verify(failure).getDescription(); verify(failureDescription).getMethodName(); verify(failure).getException(); verify(runNotifier).fireTestAssumptionFailed(failure); } @Test @SuppressWarnings("ThrowableResultIgnored") public void givenFailureWithoutMethodNameFireTestAssumptionsFailedShouldFireAssumptionFailed() { Failure failure = mock(Failure.class); Description failureDescription = mock(Description.class); Throwable exception = mock(Throwable.class); given(failure.getDescription()).willReturn(failureDescription); given(failure.getException()).willReturn(exception); sut.fireTestAssumptionFailed(failure); verify(failure).getDescription(); verify(failureDescription).getMethodName(); verify(failure).getException(); verify(runNotifier).fireTestAssumptionFailed(failure); } @Test @SuppressWarnings("ThrowableResultIgnored") public void givenFailureWithMethodNameFireTestFailureShouldFireAssumptionFailed() { Failure failure = mock(Failure.class); Description failureDescription = mock(Description.class); String methodName = "methodName"; Throwable exception = mock(Throwable.class); given(failure.getDescription()).willReturn(failureDescription); given(failureDescription.getMethodName()).willReturn(methodName); given(failure.getException()).willReturn(exception); sut.fireTestFailure(failure); verify(failure).getDescription(); verify(failureDescription).getMethodName(); verify(failure).getException(); verify(runNotifier).fireTestFailure(failure); } @Test @SuppressWarnings("ThrowableResultIgnored") public void givenFailureWithoutMethodNameFireTestFailureShouldFireAssumptionFailed() { Failure failure = mock(Failure.class); Description failureDescription = mock(Description.class); Throwable exception = mock(Throwable.class); given(failure.getDescription()).willReturn(failureDescription); given(failure.getException()).willReturn(exception); sut.fireTestFailure(failure); verify(failure).getDescription(); verify(failureDescription).getMethodName(); verify(failure).getException(); verify(runNotifier).fireTestFailure(failure); } @Test public void givenDescriptionFireTestIgnoredShouldFireTestIgnored() { Description description = mock(Description.class); sut.fireTestIgnored(description); verify(runNotifier).fireTestIgnored(description); } @Test public void givenDescriptionFireTestStartedShouldFireTestStarted() { Description description = mock(Description.class); sut.fireTestStarted(description); verify(runNotifier).fireTestStarted(description); } @Test public void givenDescriptionFireTestFinishedShouldFireTestFinished() { Description description = mock(Description.class); sut.fireTestFinished(description); verify(runNotifier).fireTestFinished(description); } @Test public void givenAssumptionViolatedExceptionAddFailedAssumptionShouldFireTestAssumptionFailed() { AssumptionViolatedException exception = mock(AssumptionViolatedException.class); sut.addFailedAssumption(exception); verify(runNotifier).fireTestAssumptionFailed(any(Failure.class)); } @Test public void givenMultipleFailureExceptionAddFailureShouldAddFailure() { MultipleFailureException exception = mock(MultipleFailureException.class); Exception failure = mock(Exception.class); List<Throwable> failures = ImmutableList.of(failure); given(exception.getFailures()).willReturn(failures); sut.addFailure(exception); verify(runNotifier).fireTestFailure(any(Failure.class)); } }
true
fc8ec4fbe46af378f2f8ff4cf29ba5e4126fabfd
Java
BKuso/SomeName
/src/main/java/old/models/User.java
UTF-8
1,427
2.734375
3
[]
no_license
package old.models; import org.apache.logging.log4j.LogManager; import org.apache.logging.log4j.Logger; import java.util.Date; public class User extends Record{ private final static Logger LOG = LogManager.getLogger("ะŸะพะปัŒะทะพะฒะฐั‚ะตะปัŒ"); private String username; private String password; private Date created; private static int countOfUsers = 0; public User(String username, String password) { super(countOfUsers); this.username = username; this.password = password; this.created = new Date(); countOfUsers++; LOG.debug(String.format("Created user: %s. Created at: %s. Current count of users: %s", username, created, countOfUsers)); } public User(){ super(countOfUsers); LOG.debug("Created new empty user"); } public String getUsername() { return username; } public void setUsername(String username) { this.username = username; } public String getPassword() { return password; } public String getPassword(boolean isForReporting){ if (isForReporting){ return getSecretField(this.password); } else { return password; } } public void setPassword(String password) { this.password = password; } @Override public void printId() { LOG.info("Id: " + this.getId()); } }
true
da0ee6ac9d6b085e1cb951fbb2f58dd129469416
Java
whitecold/Usee_server
/src/usee/com/servlet/GetMessageList.java
UTF-8
2,759
2.328125
2
[]
no_license
package usee.com.servlet; import java.io.IOException; import java.io.PrintWriter; import javax.servlet.ServletException; import javax.servlet.annotation.WebServlet; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import org.apache.log4j.Logger; import usee.com.service.MessageService; import usee.com.utils.LogUtils; /** * Servlet implementation class GetMessagesList */ @WebServlet("/GetMessageList") public class GetMessageList extends HttpServlet { private static final long serialVersionUID = 1L; private static Logger logger = Logger.getLogger(GetMessageList.class); /** * @see HttpServlet#HttpServlet() */ public GetMessageList() { super(); // TODO Auto-generated constructor stub } /** * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse * response) */ protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { // TODO Auto-generated method stub request.setCharacterEncoding("UTF-8"); response.setCharacterEncoding("utf-8"); response.setContentType("application/json;charset=utf-8"); String lon = request.getParameter("lon"); String lat = request.getParameter("lat"); String address = request.getParameter("location"); if (null != address) { address = new String(address.getBytes("iso8859-1"), "utf-8"); } // System.out.println(address); String kind = request.getParameter("kind"); // if(null!=kind){ // kind=new String(kind.getBytes("iso8859-1"), "utf-8"); // } System.out.println(kind); logger.info(LogUtils.logRequest(request)); MessageService ms = new MessageService(); String result = ms.getMessages(lon, lat, address, kind); PrintWriter out = response.getWriter(); out.print(result); } /** * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse * response) */ protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { // TODO Auto-generated method stub request.setCharacterEncoding("UTF-8"); response.setCharacterEncoding("utf-8"); response.setContentType("application/json;charset=utf-8"); String lon = request.getParameter("lon"); String lat = request.getParameter("lat"); // String kind = new String(request.getParameter("kind").getBytes( // "iso8859-1"), "utf-8"); String address = request.getParameter("location"); String kind = request.getParameter("kind"); // logger.info(LogUtils.logRequest(request)); MessageService ms = new MessageService(); String result = ms.getMessages(lon, lat, address, kind); PrintWriter out = response.getWriter(); out.print(result); } }
true
067eea6a578db0ed6edaf5b5667320c991d3d17a
Java
CyberSys/gtasa-savegame-editor
/cli/src/main/java/nl/paulinternet/gtasaveedit/cli/module/ModuleOpenSavegameDir.java
UTF-8
746
2.53125
3
[ "MIT" ]
permissive
package nl.paulinternet.gtasaveedit.cli.module; import nl.paulinternet.gtasaveedit.cli.Dir; import java.awt.*; import java.io.File; /** * @author Lukas Fรผlling (lukas@k40s.net) */ public class ModuleOpenSavegameDir implements Module { @Override public String getName() { return "savedir"; } @Override public String getDescription() { return "Opens the savegame dir"; } @Override public void execute(String[] args) throws Exception { if (Desktop.isDesktopSupported()) { Desktop.getDesktop().open(new File(Dir.get().SAVEGAME_PATH)); } else { Runtime.getRuntime().exec(new String[]{"explorer", new File(Dir.get().SAVEGAME_PATH).getCanonicalPath()}); } } }
true
0293a33481517dc744f995c77eef5c015660c5f3
Java
apache/cxf
/rt/ws/security/src/test/java/org/apache/cxf/ws/security/wss4j/StaxToDOMEncryptionIdentifierTest.java
UTF-8
12,282
1.898438
2
[ "LicenseRef-scancode-unknown", "Apache-2.0" ]
permissive
/** * 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. */ package org.apache.cxf.ws.security.wss4j; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.Properties; import org.apache.cxf.endpoint.Client; import org.apache.cxf.endpoint.Server; import org.apache.cxf.ext.logging.LoggingInInterceptor; import org.apache.cxf.ext.logging.LoggingOutInterceptor; import org.apache.cxf.frontend.ClientProxy; import org.apache.cxf.jaxws.JaxWsProxyFactoryBean; import org.apache.cxf.jaxws.JaxWsServerFactoryBean; import org.apache.cxf.service.Service; import org.apache.cxf.transport.local.LocalTransportFactory; import org.apache.wss4j.common.ConfigurationConstants; import org.apache.wss4j.common.crypto.CryptoFactory; import org.apache.wss4j.stax.ext.WSSConstants; import org.apache.wss4j.stax.ext.WSSSecurityProperties; import org.apache.wss4j.stax.securityToken.WSSecurityTokenConstants; import org.apache.xml.security.stax.ext.XMLSecurityConstants; import org.junit.Test; import static org.junit.Assert.assertEquals; /** * In these test-cases, the client is using StaX and the service is using DOM. The tests are * for different Encryption Key Identifier methods. */ public class StaxToDOMEncryptionIdentifierTest extends AbstractSecurityTest { @Test public void testEncryptDirectReference() throws Exception { // Create + configure service Service service = createService(); Map<String, Object> inProperties = new HashMap<>(); inProperties.put(ConfigurationConstants.ACTION, ConfigurationConstants.ENCRYPTION); inProperties.put(ConfigurationConstants.PW_CALLBACK_REF, new TestPwdCallback()); inProperties.put(ConfigurationConstants.DEC_PROP_FILE, "insecurity.properties"); WSS4JInInterceptor inInterceptor = new WSS4JInInterceptor(inProperties); service.getInInterceptors().add(inInterceptor); // Create + configure client Echo echo = createClientProxy(); Client client = ClientProxy.getClient(echo); client.getInInterceptors().add(new LoggingInInterceptor()); client.getOutInterceptors().add(new LoggingOutInterceptor()); WSSSecurityProperties properties = new WSSSecurityProperties(); List<WSSConstants.Action> actions = new ArrayList<>(); actions.add(XMLSecurityConstants.ENCRYPTION); properties.setActions(actions); properties.setEncryptionUser("myalias"); properties.setEncryptionKeyIdentifier( WSSecurityTokenConstants.KEYIDENTIFIER_SECURITY_TOKEN_DIRECT_REFERENCE ); properties.setEncryptionSymAlgorithm(XMLSecurityConstants.NS_XENC_AES128); Properties cryptoProperties = CryptoFactory.getProperties("outsecurity.properties", this.getClass().getClassLoader()); properties.setEncryptionCryptoProperties(cryptoProperties); properties.setCallbackHandler(new TestPwdCallback()); WSS4JStaxOutInterceptor ohandler = new WSS4JStaxOutInterceptor(properties); client.getOutInterceptors().add(ohandler); assertEquals("test", echo.echo("test")); } @Test public void testEncryptIssuerSerial() throws Exception { // Create + configure service Service service = createService(); Map<String, Object> inProperties = new HashMap<>(); inProperties.put(ConfigurationConstants.ACTION, ConfigurationConstants.ENCRYPTION); inProperties.put(ConfigurationConstants.PW_CALLBACK_REF, new TestPwdCallback()); inProperties.put(ConfigurationConstants.DEC_PROP_FILE, "insecurity.properties"); WSS4JInInterceptor inInterceptor = new WSS4JInInterceptor(inProperties); service.getInInterceptors().add(inInterceptor); // Create + configure client Echo echo = createClientProxy(); Client client = ClientProxy.getClient(echo); client.getInInterceptors().add(new LoggingInInterceptor()); client.getOutInterceptors().add(new LoggingOutInterceptor()); WSSSecurityProperties properties = new WSSSecurityProperties(); List<WSSConstants.Action> actions = new ArrayList<>(); actions.add(XMLSecurityConstants.ENCRYPTION); properties.setActions(actions); properties.setEncryptionUser("myalias"); properties.setEncryptionKeyIdentifier( WSSecurityTokenConstants.KeyIdentifier_IssuerSerial ); properties.setEncryptionSymAlgorithm(XMLSecurityConstants.NS_XENC_AES128); Properties cryptoProperties = CryptoFactory.getProperties("outsecurity.properties", this.getClass().getClassLoader()); properties.setEncryptionCryptoProperties(cryptoProperties); properties.setCallbackHandler(new TestPwdCallback()); WSS4JStaxOutInterceptor ohandler = new WSS4JStaxOutInterceptor(properties); client.getOutInterceptors().add(ohandler); assertEquals("test", echo.echo("test")); } @Test public void testEncryptThumbprint() throws Exception { // Create + configure service Service service = createService(); Map<String, Object> inProperties = new HashMap<>(); inProperties.put(ConfigurationConstants.ACTION, ConfigurationConstants.ENCRYPTION); inProperties.put(ConfigurationConstants.PW_CALLBACK_REF, new TestPwdCallback()); inProperties.put(ConfigurationConstants.DEC_PROP_FILE, "insecurity.properties"); WSS4JInInterceptor inInterceptor = new WSS4JInInterceptor(inProperties); service.getInInterceptors().add(inInterceptor); // Create + configure client Echo echo = createClientProxy(); Client client = ClientProxy.getClient(echo); client.getInInterceptors().add(new LoggingInInterceptor()); client.getOutInterceptors().add(new LoggingOutInterceptor()); WSSSecurityProperties properties = new WSSSecurityProperties(); List<WSSConstants.Action> actions = new ArrayList<>(); actions.add(XMLSecurityConstants.ENCRYPTION); properties.setActions(actions); properties.setEncryptionUser("myalias"); properties.setEncryptionKeyIdentifier( WSSecurityTokenConstants.KEYIDENTIFIER_THUMBPRINT_IDENTIFIER ); properties.setEncryptionSymAlgorithm(XMLSecurityConstants.NS_XENC_AES128); Properties cryptoProperties = CryptoFactory.getProperties("outsecurity.properties", this.getClass().getClassLoader()); properties.setEncryptionCryptoProperties(cryptoProperties); properties.setCallbackHandler(new TestPwdCallback()); WSS4JStaxOutInterceptor ohandler = new WSS4JStaxOutInterceptor(properties); client.getOutInterceptors().add(ohandler); assertEquals("test", echo.echo("test")); } @Test public void testEncryptX509() throws Exception { // Create + configure service Service service = createService(); Map<String, Object> inProperties = new HashMap<>(); inProperties.put(ConfigurationConstants.ACTION, ConfigurationConstants.ENCRYPTION); inProperties.put(ConfigurationConstants.PW_CALLBACK_REF, new TestPwdCallback()); inProperties.put(ConfigurationConstants.DEC_PROP_FILE, "insecurity.properties"); inProperties.put(ConfigurationConstants.IS_BSP_COMPLIANT, "false"); WSS4JInInterceptor inInterceptor = new WSS4JInInterceptor(inProperties); service.getInInterceptors().add(inInterceptor); // Create + configure client Echo echo = createClientProxy(); Client client = ClientProxy.getClient(echo); client.getInInterceptors().add(new LoggingInInterceptor()); client.getOutInterceptors().add(new LoggingOutInterceptor()); WSSSecurityProperties properties = new WSSSecurityProperties(); List<WSSConstants.Action> actions = new ArrayList<>(); actions.add(XMLSecurityConstants.ENCRYPTION); properties.setActions(actions); properties.setEncryptionUser("myalias"); properties.setEncryptionKeyIdentifier( WSSecurityTokenConstants.KeyIdentifier_X509KeyIdentifier ); properties.setEncryptionSymAlgorithm(XMLSecurityConstants.NS_XENC_AES128); Properties cryptoProperties = CryptoFactory.getProperties("outsecurity.properties", this.getClass().getClassLoader()); properties.setEncryptionCryptoProperties(cryptoProperties); properties.setCallbackHandler(new TestPwdCallback()); WSS4JStaxOutInterceptor ohandler = new WSS4JStaxOutInterceptor(properties); client.getOutInterceptors().add(ohandler); assertEquals("test", echo.echo("test")); } @Test public void testEncryptEncryptedKeySHA1() throws Exception { // Create + configure service Service service = createService(); Map<String, Object> inProperties = new HashMap<>(); inProperties.put(ConfigurationConstants.ACTION, ConfigurationConstants.ENCRYPTION); inProperties.put(ConfigurationConstants.PW_CALLBACK_REF, new TestPwdCallback()); inProperties.put(ConfigurationConstants.DEC_PROP_FILE, "insecurity.properties"); WSS4JInInterceptor inInterceptor = new WSS4JInInterceptor(inProperties); service.getInInterceptors().add(inInterceptor); // Create + configure client Echo echo = createClientProxy(); Client client = ClientProxy.getClient(echo); client.getInInterceptors().add(new LoggingInInterceptor()); client.getOutInterceptors().add(new LoggingOutInterceptor()); WSSSecurityProperties properties = new WSSSecurityProperties(); List<WSSConstants.Action> actions = new ArrayList<>(); actions.add(XMLSecurityConstants.ENCRYPTION); properties.setActions(actions); properties.setEncryptionUser("myalias"); properties.setEncryptionKeyIdentifier( WSSecurityTokenConstants.KEYIDENTIFIER_ENCRYPTED_KEY_SHA1_IDENTIFIER ); properties.setEncryptionSymAlgorithm(XMLSecurityConstants.NS_XENC_AES128); Properties cryptoProperties = CryptoFactory.getProperties("outsecurity.properties", this.getClass().getClassLoader()); properties.setEncryptionCryptoProperties(cryptoProperties); properties.setCallbackHandler(new TestPwdCallback()); WSS4JStaxOutInterceptor ohandler = new WSS4JStaxOutInterceptor(properties); client.getOutInterceptors().add(ohandler); assertEquals("test", echo.echo("test")); } private Service createService() { // Create the Service JaxWsServerFactoryBean factory = new JaxWsServerFactoryBean(); factory.setServiceBean(new EchoImpl()); factory.setAddress("local://Echo"); factory.setTransportId(LocalTransportFactory.TRANSPORT_ID); Server server = factory.create(); Service service = server.getEndpoint().getService(); service.getInInterceptors().add(new LoggingInInterceptor()); service.getOutInterceptors().add(new LoggingOutInterceptor()); return service; } private Echo createClientProxy() { JaxWsProxyFactoryBean proxyFac = new JaxWsProxyFactoryBean(); proxyFac.setServiceClass(Echo.class); proxyFac.setAddress("local://Echo"); proxyFac.getClientFactoryBean().setTransportId(LocalTransportFactory.TRANSPORT_ID); return (Echo)proxyFac.create(); } }
true
79c5028bf1928036cfd7ba53b71a30164cded9fc
Java
3ooowojtooo/geogames
/app/src/main/java/com/kurocho/geogames/di/modules/SignInUtilsModule.java
UTF-8
700
2.09375
2
[ "BSD-3-Clause" ]
permissive
package com.kurocho.geogames.di.modules; import android.content.Context; import android.content.SharedPreferences; import com.kurocho.geogames.di.qualifiers.ApplicationContext; import com.kurocho.geogames.di.qualifiers.SignInSharedPreferences; import dagger.Module; import dagger.Provides; import javax.inject.Singleton; @Module public abstract class SignInUtilsModule { public static final String SHARED_PREFERENCES_FILENAME = "signin"; @Provides @Singleton @SignInSharedPreferences static SharedPreferences signInSharedPreferences(@ApplicationContext Context context){ return context.getSharedPreferences(SHARED_PREFERENCES_FILENAME, Context.MODE_PRIVATE); } }
true
6613d7aef62db5d5175e6992b909ff65580f5085
Java
vinscom/api-framework
/src/main/java/in/erail/common/FrameworkConstants.java
UTF-8
1,382
1.703125
2
[ "MIT" ]
permissive
package in.erail.common; /** * * @author vinay */ public class FrameworkConstants { public static class Session { public static final String PRINCIPAL = "user"; } public static class RoutingContext { public static class Json { public static final String COOKIES = "cookies"; public static class Cookie { public static final String NAME = "name"; public static final String VALUE = "value"; public static final String HTTP_ONLY = "httpOnly"; public static final String SECURE = "secure"; public static final String PATH = "path"; public static final String MAX_AGE = "maxAge"; public static final String DOMAIN = "domain"; } public static final String HEADERS = "headers"; public static final String MULTI_VALUE_HEADERS = "multiValueHeaders"; public static final String PATH_PARAM = "pathParameters"; public static final String QUERY_STRING_PARAM = "queryStringParameters"; public static final String BODY = "body"; public static final String STATUS_CODE = "statusCode"; public static final String IS_BASE64_ENCODED = "isBase64Encoded"; } } public static class SockJS { public static final String BRIDGE_EVENT_RAW_MESSAGE_ADDRESS = "address"; public static final String BRIDGE_EVENT_RAW_MESSAGE_HEADERS = "headers"; } }
true
92aedb0e229313bbc904ecbadce93134a8a3fc47
Java
ewelinka/miceta
/core/src/main/java/miceta/game/core/util/Constants.java
UTF-8
1,125
1.757813
2
[]
no_license
package miceta.game.core.util; /** * Created by ewe on 8/10/17. */ public class Constants { public static final float WAIT_AFTER_KNOCK = 2; // in seconds public static final float READ_ONE_UNIT_DURATION = 0.57f; public static final float READ_NUMBER_DURATION = 0.7f; //Range: 0.495f - 0.90 public static final float DELAY_FOR_YUJU = 0.91f; //0.5f; public static final float DELAY_FOR_TADA = 2.0f;//0.5f; //2.0 is large public static final int BASE = 40; public static final int STRIKE = 3; public static final int P_STRIKE = 3; public static final int INACTIVITY_LIMIT = 30; public static final int ERRORS_FOT_HINT = 2; public static final int ERRORS_FOR_REPEAT_TUTORIAL = 20; public static final int WAIT_AFTER_CORRECT_ANSWER = 1; public static final String PREFERENCES = "settings.prefs"; public static final int DESKTOP_WIDTH = 1366; public static final int DESKTOP_HEIGHT = 768; public static final int ANDROID_WIDTH = 600; public static final int ANDROID_HEIGHT = 1024; public static final String TEXTURE_ATLAS_OBJECTS ="images/pack.atlas"; }
true
16ea4dbc4c4aca193e466ccb7f01b0a38a4a9626
Java
wesfree163/cs-hu
/CSC-252/HW3PriorityQueues/PriorityQueue.java
UTF-8
1,328
3.8125
4
[ "MIT" ]
permissive
/** * Base interface for priority queue implementations for doubles. * Throw exceptions as appropriate. */ public interface PriorityQueue { /** * Returns true if priority queue has no elements * * @return true if the priority queue has no elements */ public boolean isEmpty(); /** * Returns the number of elements in this priority queue. * * @return the number of elements in this priority queue. */ public int size(); /** * Returns the minimum element in the priority queue * * @return the minimum element * @throws EmptyPQException * if priority queue contains no elements */ public double findMin(); /** * Inserts a new element into the priority queue. Duplicate values ARE * allowed. * * @param x * element to be inserted into the priority queue. */ public void insert(double x); /** * Removes and returns the minimum element from the priority queue. * * @return the minimum element * @throws EmptyPQException * if priority queue contains no elements */ public double deleteMin(); /** * Resets the priority queue to appear as not containing any elements. */ public void makeEmpty(); }
true
4c619fd01de9d5bb45fddef53b760b4351fc347f
Java
sullah5577/CucumberBddProject
/src/test/java/com/ninjastore/automation/runner/TestRunner.java
UTF-8
748
1.742188
2
[]
no_license
package com.ninjastore.automation.runner; import org.junit.runner.RunWith; import com.cucumber.listener.Reporter; import cucumber.api.CucumberOptions; import cucumber.api.junit.Cucumber; import java.io.File; @RunWith(Cucumber.class) @CucumberOptions( features = {"src/test/resources/FeatureFiles"}, glue = {"classpath:com.ninjastore.automation.stepdef"}, //plugin = {"html:target/cucumber_html_report"}, plugin = { "com.cucumber.listener.ExtentCucumberFormatter:target/cucumber-reports/report.html"}, tags = {"@Orders,@Register,@Login"} ) public class TestRunner { public static void writeExtentReport() { Reporter.loadXMLConfig(new File("ConfigurationFile/extent-config.xml")); } }
true
5117a0f1c644d3aeea0091c6f55115028461c1f1
Java
no2key/YangMuStudyCode-eclipse
/src/cn/edu/bupt/reflect/Private2Test.java
UTF-8
657
2.9375
3
[]
no_license
package cn.edu.bupt.reflect; import java.lang.reflect.Field; import java.lang.reflect.Method; public class Private2Test { public static void main(String[] args) throws Exception{ Class<?> private2ClassType = Private2.class; Object private2Object = private2ClassType.newInstance(); Field field = private2ClassType.getDeclaredField("name"); field.setAccessible(true); field.set(private2Object, "lisi"); //======================================= Method method = private2ClassType.getMethod("getName", new Class<?>[]{}); Object getName = method.invoke(private2Object, new Object[]{}); System.out.println((String)getName); } }
true
f7e735a092a360af9c4ed16f1cb3b3c88e4e334e
Java
trabajoalminuto17/trabajoalminutov2
/trabajo_al_minuto/trabajo_al_minuto-web/src/main/java/com/basp/trabajo_al_minuto/web/view/DetalleEvaluacionView.java
UTF-8
3,215
1.757813
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 com.basp.trabajo_al_minuto.web.view; import com.basp.trabajo_al_minuto.model.business.BusinessException; import com.basp.trabajo_al_minuto.service.entity.Evaluacion; import com.basp.trabajo_al_minuto.service.entity.PerfilHasPrueba; import com.basp.trabajo_al_minuto.service.entity.Respuesta; import com.basp.trabajo_al_minuto.web.model.ComponenteWeb; import static com.basp.trabajo_al_minuto.web.model.UtilWeb.doubleFormat; import static com.basp.trabajo_al_minuto.web.model.UtilWeb.evaluarPrueba; import java.io.Serializable; import java.util.List; import java.util.logging.Level; import java.util.logging.Logger; import javax.annotation.PostConstruct; import javax.faces.view.ViewScoped; import javax.inject.Named; /** * * @author Bryan.Silva */ @Named @ViewScoped public class DetalleEvaluacionView extends ComponenteWeb implements Serializable { private static final long serialVersionUID = 1L; private PerfilHasPrueba perfilHasPrueba; private Evaluacion evaluacion; private List<Respuesta> respuestas; private String porcentajeresultado; private Boolean aproboPrueba; @PostConstruct public void init() { if (getPruebaPerfil() != null && getEvaluacionId() != null) { try { perfilHasPrueba = getPruebaPerfil(); evaluacion = pruebaEjb.findEvaluacion(getEvaluacionId()); respuestas = citacionEjb.getRespuestasByEvaluacionPrueba(evaluacion.getEvaluacionId(), perfilHasPrueba.getPrueba().getPruebaId()); Double d = evaluarPrueba(respuestas, perfilHasPrueba.getPrueba()); aproboPrueba = perfilHasPrueba.getPrueba().getPorcentajeMinimo() < d; porcentajeresultado = doubleFormat(d); } catch (BusinessException ex) { Logger.getLogger(DetalleEvaluacionView.class.getName()).log(Level.SEVERE, ex.developerException()); } } } // @Getter and Setter public PerfilHasPrueba getPerfilHasPrueba() { return perfilHasPrueba; } public void setPerfilHasPrueba(PerfilHasPrueba perfilHasPrueba) { this.perfilHasPrueba = perfilHasPrueba; } public Evaluacion getEvaluacion() { return evaluacion; } public void setEvaluacion(Evaluacion evaluacion) { this.evaluacion = evaluacion; } public List<Respuesta> getRespuestas() { return respuestas; } public void setRespuestas(List<Respuesta> respuestas) { this.respuestas = respuestas; } public String getPorcentajeresultado() { return porcentajeresultado; } public void setPorcentajeresultado(String porcentajeresultado) { this.porcentajeresultado = porcentajeresultado; } public Boolean getAproboPrueba() { return aproboPrueba; } public void setAproboPrueba(Boolean aproboPrueba) { this.aproboPrueba = aproboPrueba; } }
true
6ef1950393ec133693175f1a308d249136cb25e1
Java
SSAFY-Daejeon6-Algo4/Namwook-Algorithm-Study
/10์›”6์ผ ์ˆ˜์š”์ผ/Shortest_game_map.java
UTF-8
2,854
3.484375
3
[]
no_license
package Algo_1006; import java.util.*; import java.io.*; public class Shortest_game_map { /** * ํ”„๋กœ๊ทธ๋ž˜๋จธ์Šค ๊ฒŒ์ž„ ๋งต ์ตœ๋‹จ ๊ฑฐ๋ฆฌ bfs, dfs ๋‘˜๋‹ค ์—ฐ์Šตํ•ด๋ณด๊ณ  ์ฐจ์ด๋ฅผ ํ™•์‹คํžˆ ๋А๋‚„ ๊ฒƒ * * ์ž…๋ ฅ์„ ๋ฐ›์•„์„œ n๊ณผ m์„ ์•Œ์•„์„œ ์‚ฐ์ถœํ•ด์•ผํ•จ */ static int n, m; static int[][] maps; static int[] dx = {-1,1,0,0}; static int[] dy = {0,0,-1,1}; static boolean[][] visited; static class Point{ //2์ฐจ์› ๋ฐฐ์—ด ์•ˆ์—์„œ ์›€์ง์ด๋Š” ์ขŒํ‘œ ๊ณ„์‚ฐํ• ๋•Œ ํด๋ž˜์Šค๋ฅผ ์„ ์–ธํ•ด์ฃผ๋Š” ๊ฒƒ์ด ํŽธํ•ฉ๋‹ˆ๋‹ค. int x; int y; int answer; public Point(int x, int y, int answer) { super(); this.x = x; this.y = y; this.answer = answer; } } public static void initVisited() {//์ดˆ๊ธฐํ™” for(int i=0; i<visited.length; ++i) { for(int j=0; j<visited[i].length; ++j) { visited[i][j]=false; } } } public static int bfs(int start_x, int start_y, int[][] maps) { //ํ ํ™œ์šฉ Queue<Point> queue = new LinkedList<>(); queue.offer(new Point(start_x, start_y, 1));//ํ์— ๋„ฃ๊ณ  visited[start_x][start_y]=true;//ํ•ด๋‹น์œ„์น˜ ๋ฐฉ๋ฌธ๋ฐฐ์—ด ์ดˆ๊ธฐํ™” while(!queue.isEmpty()) {//ํ๊ฐ€ ๋นŒ๋•Œ๊นŒ์ง€ ๋ฐ˜๋ณตํ•˜๋ฉด์„œ Point tmp = queue.poll(); //๋‹ค์Œ ์œ„์น˜ ๋“ค์–ด๊ฐ€๊ธฐ ์ „ ํ˜„์žฌ ์œ„์น˜๊ฐ€ ๋ชฉ์ ์ง€ ์ธ์ง€ ํ•œ๋ฒˆ ํ™•์ธ : ์ธ๋ฑ์Šค๋Š” 0๋ถ€ํ„ฐ ์‹œ์ž‘ํ•˜๋‹ˆ๊น if(tmp.x==(n-1) && tmp.y==(m-1)) {//๋ชฉ์ ์ง€์— ๋„์ฐฉํ–ˆ์œผ๋ฉด ๊ทธ๋•Œ ํšŸ์ˆ˜ ๊ฐ€์ง€๊ณ  break return tmp.answer; } //๋‹ค์Œ ์œ„์น˜๋กœ ์ด๋™ํ•˜๊ธฐ ์œ„ํ•œ ๊ณ„์‚ฐ : ๋ฒ”์œ„๋ฅผ ๋ฒ—์–ด๋‚˜๋ฉด ์•ˆ๋˜๊ณ , 0์ด๋ฉด ์ด๋™ํ•  ์ˆ˜ ์—†์Œ for(int i=0; i<4; ++i) { int nx = tmp.x + dx[i]; int ny = tmp.y + dy[i]; if(nx>=0 && ny>=0 && nx<n && ny<m) { if(maps[nx][ny]==1 && !visited[nx][ny]) {//๋ฐฉ๋ฌธ๊ฐ€๋Šฅํ•œ ์ง€์ ์ด๊ณ  ๋‚ด๊ฐ€ ๋ฐฉ๋ฌธํ•œ ์ ์ด ์—†๋‹ค๋ฉด visited[nx][ny]=true; queue.offer(new Point(nx, ny, 1+tmp.answer)); } } } } //๋‹ค ๋Œ๊ณ  ๋‚˜์™“๋Š”๋ฐ return -1; } public static void dfs(int start_x, int start_y, boolean[][] visited, int[][] maps) { //์Šคํƒ, ์žฌ๊ท€ ํ™œ์šฉ initVisited(); } public static int solution(int[][] maps) { //์ž์ฒด์ ์œผ๋กœ maps๋ฅผ ๋„˜๊ฒจ๋ฐ›์€ ๋‹ค์Œ์—, n๊ณผ m์„ ์ธก์ •ํ•ด์„œ ๋ถ€์—ฌํ•˜์—ฌ ์ง€ํ‘œ๋ฅผ ๋งŒ๋“ค์–ด์ค€๋‹ค. //๋„˜๊ฒจ๋ฐ›์•„์„œ ๋งŒ๋“ค์–ธ mapsํฌ๊ธฐ๋งŒํผ visited๋ฅผ ์„ ์–ธํ•ด์ค€๋‹ค. //ํฌ์ธํŠธ ํด๋ž˜์Šค๋ฅผ ๋งŒ๋“œ๋Š” ๋ฐฉ๋ฒ•๋„ ์žˆ์ง€๋งŒ ์‹œ์ž‘์ขŒํ‘œ๋ฅผ ๋„˜๊ฒจ์ค˜๋ณธ๋‹ค. n = maps.length; m = maps[0].length; visited = new boolean[n][m]; initVisited();//์ดˆ๊ธฐํ™” return bfs(0,0,maps); } public static void main(String[] args) throws IOException { maps = new int[][]{{1,0,1,1,1},{1,0,1,0,1},{1,0,1,1,1},{1,1,1,0,1},{0,0,0,0,1}}; //maps = new int[][]{{1,0,1,1,1},{1,0,1,0,1},{1,0,1,1,1},{1,1,1,0,0},{0,0,0,0,1}}; System.out.println(solution(maps)); } }
true
a3f2a3164b3aaed09c6769763ba5d838c5d49910
Java
azarnovdaniil/ai-aas
/bica/src/main/java/ru/daniilazarnov/bot/core/memory/MemoryDao.java
UTF-8
764
1.875
2
[ "MIT" ]
permissive
package ru.daniilazarnov.bot.core.memory; import ru.daniilazarnov.common.model.entity.Action; import ru.daniilazarnov.common.model.entity.Actor; import ru.daniilazarnov.common.model.entity.State; import java.util.Set; public interface MemoryDao { boolean isInitSession(String sessionId); void updateAppraisal(String sessionId, Actor actor, Actor target, Action action); void updateAllAppraisal(String sessionId, Actor actor, Action action); void updateSelfAppraisal(String sessionId, Actor actor, Action action); Set<State> getAppraisalState(String sessionId); void initSession(String sessionId); void initMemoryForActorInSession(String sessionId, Actor actor); boolean isNotDetermined(String sessionId, Actor actor); }
true
f11b3eccdc1182cc9263c726a9fbb7b81ac1f953
Java
Tajammul81/Robot_Configuration_Java
/src/com/app/robot/Main.java
UTF-8
2,114
3.46875
3
[]
no_license
package com.app.robot; import java.awt.Point; import java.io.BufferedReader; import java.io.InputStreamReader; public class Main { public static void main(String[] args) { try { //Room ThisRoom = new Room(5, 5, new Robot(), new Point(1, 2)); CircleRoom ThisRoom = new CircleRoom(5, new Robot(), new Point(5, 5)); System.out.println("Select your preferred Language. ENG for English / SV for Swedish"); BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); String LanguageCode = br.readLine().trim().toUpperCase(); if (LanguageCode.equals("ENG") || LanguageCode.equals("SV")) { System.out.println("you have chosen " + LanguageCode); } else { System.out.println("Please next time choose either Eng or Sv as a Language"); System.exit(0); } System.out.println("Please enter direction command in " + LanguageCode + " to move the robot"); br = new BufferedReader(new InputStreamReader(System.in)); String Commands = br.readLine(); System.out.println("X : " + ThisRoom.getRobot().getDisplayPosition().x + ", Y : " + ThisRoom.getRobot().getDisplayPosition().y + ", Direction : " + ThisRoom.getRobot().getDisplayDirection(LanguageCode)); for (char SingleCommand : Commands.toUpperCase().toCharArray()) { if (LanguageCode.equals("SV")) { switch (SingleCommand) { case 'V': ThisRoom.TurnLeft(); break; case 'H': ThisRoom.TurnRight(); break; case 'G': ThisRoom.MoveForward(); break; } } else { switch (SingleCommand) { case 'L': ThisRoom.TurnLeft(); break; case 'R': ThisRoom.TurnRight(); break; case 'F': ThisRoom.MoveForward(); break; } } System.out.println("X : " + ThisRoom.getRobot().getDisplayPosition().x + ", Y : " + ThisRoom.getRobot().getDisplayPosition().y + ", Direction : " + ThisRoom.getRobot().getDisplayDirection(LanguageCode)); } } catch (Exception e) { e.printStackTrace(); } } }
true
4974c07705612f84054390a74e0e13080e862ec5
Java
Lolva/NexusBORD
/src/main/java/com/atossyntel/springboot/controller/ModulesController.java
UTF-8
8,729
1.960938
2
[]
no_license
package com.atossyntel.springboot.controller; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; import javax.mail.MessagingException; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpSession; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.core.io.Resource; import org.springframework.http.HttpHeaders; import org.springframework.http.ResponseEntity; import org.springframework.stereotype.Controller; import org.springframework.ui.Model; import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.ModelAttribute; import org.springframework.web.bind.annotation.PathVariable; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestMethod; import org.springframework.web.bind.annotation.RequestParam; import org.springframework.web.multipart.MultipartFile; import org.springframework.web.servlet.mvc.support.RedirectAttributes; import com.atossyntel.springboot.model.InstructorAssignmentsBean; import com.atossyntel.springboot.model.ModuleBean; import com.atossyntel.springboot.service.ModuleDAO; import com.atossyntel.springboot.storage.StorageService; @Controller public class ModulesController { @Autowired ModuleDAO moduledao; @Autowired StorageService storageService; @RequestMapping(value = "/Modules", method = RequestMethod.GET) public String init(Model model, HttpSession session) { List<Map<String, Object>> classes = moduledao.getClasses(session.getAttribute("username").toString()); model.addAttribute("classes", classes); model.addAttribute("modules", moduledao.getModuleList(session.getAttribute("username").toString())); model.addAttribute("modulefiles", moduledao.getModuleFiles(session.getAttribute("username").toString())); model.addAttribute("moduleassigns", moduledao.getAssignments(session.getAttribute("username").toString())); /* * Map<String, Object> mom = new HashMap<String, Object>(); for (Map<String, * Object> m : classes) { String classid =m.get("class_id").toString(); * List<List<Map<String, Object>>> modules = new ArrayList<List<Map<String, * Object>>>(); //List<Map<String, Object>> res = new ArrayList<Map<String, * Object>>(); * modules.add(moduledao.getModuleList(m.get("class_id").toString())); * Map<String, Object> modulemap = new HashMap<String, Object>(); * for(List<Map<String,Object>> a : modules) { //List<List<List<Map<String, * Object>>>> assigns= new ArrayList<List<List<Map<String,Object>>>>(); * for(Map<String, Object> z: a) { List<List<Map<String, Object>>> assigns = new * ArrayList<List<Map<String, Object>>>(); String moduleid = * z.get("module_id").toString(); System.out.println(moduleid); * assigns.add(moduledao.getModuleName(moduleid)); * assigns.add(moduledao.getModuleFiles(moduleid)); * assigns.add(moduledao.getAssignments(moduleid)); * * modulemap.put(moduleid, assigns); } } mom.put(classid, modulemap); } * * * * System.out.println(mom.toString()); * * model.addAttribute("modules", mom); */ return "Modules"; } @RequestMapping(value = "/addModule", method = RequestMethod.POST) public String newModule(Model model, @ModelAttribute("newmodule") ModuleBean module) { System.out.println(module.toString()); System.out.println(moduledao.insertModule(module.getModule_name(), module.getStream_id())); // assignment.setModule_id(result.getParameter("module")); // model.addAttribute("module_id", module.getCourse_id()); // model.addAttribute("module_name", module.getModule_name()); return "redirect:Modules"; } @RequestMapping(value = "/deleteAssignment", method = RequestMethod.POST) public String deleteAssignment(Model model, @ModelAttribute("deleteassignment") InstructorAssignmentsBean assignment) { System.out.println(assignment.toString()); System.out.println(moduledao.deleteAssignment(assignment.getAssignment_id())); // System.out.println(moduledao.insertStream(module.getStream_id())); // assignment.setModule_id(result.getParameter("module")); // model.addAttribute("module_id", module.getCourse_id()); // model.addAttribute("module_name", module.getModule_name()); return "redirect:Modules"; } @RequestMapping(value = "/deleteModule", method = RequestMethod.POST) public String deleteModule(Model model, @ModelAttribute("module") ModuleBean module) { System.out.println(module.toString()); System.out.println(moduledao.deleteModule(module.getModule_id())); // System.out.println(moduledao.insertStream(module.getStream_id())); // assignment.setModule_id(result.getParameter("module")); // model.addAttribute("module_id", module.getCourse_id()); // model.addAttribute("module_name", module.getModule_name()); return "redirect:Modules"; } @RequestMapping(value = "/deleteModuleFile", method = RequestMethod.POST) public String deleteModuleFile(Model model, @ModelAttribute("module") ModuleBean module) { System.out.println(module.toString()); System.out.println(moduledao.deleteModuleFile(module.getModule_file_id())); // System.out.println(moduledao.insertStream(module.getStream_id())); // assignment.setModule_id(result.getParameter("module")); // model.addAttribute("module_id", module.getCourse_id()); // model.addAttribute("module_name", module.getModule_name()); return "redirect:Modules"; } @RequestMapping(value = "/updateModule", method = RequestMethod.POST) public String updateModule(Model model, @ModelAttribute("module") ModuleBean module) { System.out.println(module.toString()); System.out.println(moduledao.updateModule(module.getModule_name(), module.getModule_id())); // System.out.println(moduledao.insertStream(module.getStream_id())); // assignment.setModule_id(result.getParameter("module")); // model.addAttribute("module_id", module.getCourse_id()); // model.addAttribute("module_name", module.getModule_name()); return "redirect:Modules"; } @RequestMapping(value = "/addModuleFile", method = RequestMethod.POST) public String newModuleFile(Model model, HttpServletRequest request, @RequestParam("module_id") int module_id, @RequestParam("class_id") int class_id, @RequestParam("stream_id") int stream_id, @RequestParam("fileName") MultipartFile file) { System.out.println(request.getParameter("module_id")); System.out.println(request.getParameter("stream_id")); System.out.println(request.getParameter("class_id")); System.out.println(moduledao.insertModuleFile(request.getParameter("module_id"), file)); storageService.store(file, "/" + stream_id + "/" + class_id + "/" + module_id + "/"); return "redirect:Modules"; } @GetMapping("/download/{streamid}/{classid}/{moduleid}/{modulefile}/{filetype}") public ResponseEntity<Resource> submit(Model model, @PathVariable("streamid") String streamid, @PathVariable("classid") String classid, @PathVariable("moduleid") String moduleid, @PathVariable("modulefile") String filename, @PathVariable("filetype") String type) throws MessagingException { System.out.println(streamid + " " + classid + " " + moduleid + " " + filename); System.out.println("Download is starting..."); StringBuilder folder = new StringBuilder("/" + streamid + "/" + classid + "/" + moduleid + "/"); Resource file = storageService.loadAsResource(filename + "." + type,folder.toString()); System.out.println("Downloading done"); return ResponseEntity.ok().header(HttpHeaders.CONTENT_DISPOSITION, "attachment; filename=\"" + file.getFilename() + "\"").body(file); //System.out.print("going to new page"); //smtpMailSender.send("umezaki.tatsuya@gmail.com,alfabenojar@yahoo.com,jacob-gp@hotmail.com", 999); } //String name, MultipartFile file, String dueDate, String moduleId, String classId, String desc, String status @RequestMapping(value = "/addAssignmentFile", method = RequestMethod.POST) public String newAssignmentFile(Model model, HttpServletRequest request, @RequestParam("name") String name, @RequestParam("module_id") String module_id, @RequestParam("class_id") String class_id, @RequestParam("stream_id") int stream_id, @RequestParam("fileName") MultipartFile file, @RequestParam("due_date") String due_date, @RequestParam("desc") String desc, @RequestParam("status") String status) { System.out.println(name + " " + file.toString() + " " + module_id + " " + class_id + " " + due_date + " " + desc + " " + status); System.out.println(moduledao.newAssignment(name, file, due_date, module_id, class_id, desc, status)); storageService.store(file, "/" + stream_id + "/" + class_id + "/" + module_id + "/"); return "redirect:Modules"; } }
true
97129b8234add1717a5fa9987a06dbb7bb786cd1
Java
bellmit/pinenut
/storage/src/test/java/jdk/me/mybatis/SqlSessionFactoryBuilderXML.java
UTF-8
1,588
2.328125
2
[]
no_license
package jdk.me.mybatis; import org.apache.ibatis.io.Resources; import org.apache.ibatis.io.VFS; import org.apache.ibatis.session.Configuration; import org.apache.ibatis.session.SqlSession; import org.apache.ibatis.session.SqlSessionFactory; import org.apache.ibatis.session.SqlSessionFactoryBuilder; import org.junit.Test; import java.io.IOException; import java.io.InputStream; import java.util.List; /** * Created by admin on 2015/11/5. */ public class SqlSessionFactoryBuilderXML { @Test public void sqlSessionFactoryTest() throws Exception { String resource = "mybatis-config.xml"; InputStream inputStream = Resources.getResourceAsStream(resource); SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(inputStream); //configuration Configuration configuration = sqlSessionFactory.getConfiguration(); configuration.setObjectFactory(new ExampleObjectFactory()); configuration.addInterceptor(new ExamplePlugin()); SqlSession sqlSession = sqlSessionFactory.openSession(); UserMapper userMapper = sqlSession.getMapper(UserMapper.class); User user = userMapper.selectByPrimaryKey(1); System.out.println(user); } @Test public void testVFS() throws IOException { System.out.println(VFS.getInstance().getClass()); List<String> children = VFS.getInstance().list("me"); for (String string : children) System.out.println(string); System.out.println(Byte[].class); System.out.println(Byte.class); } }
true
028f57ca206c2d453217a6e266250999e43b79e6
Java
wpalomo/EJBShrimp
/src/java/contabilidad/TO/ConEstructuraTO.java
UTF-8
2,003
2.546875
3
[]
no_license
/* * To change this template, choose Tools | Templates * and open the template in the editor. */ package contabilidad.TO; import java.io.Serializable; /** * * @author jack */ public class ConEstructuraTO implements Serializable{ private String empCodigo; private short estGrupo1; private short estGrupo2; private short estGrupo3; private short estGrupo4; private short estGrupo5; private short estGrupo6; public ConEstructuraTO() { } public ConEstructuraTO(String empCodigo, short estGrupo1, short estGrupo2, short estGrupo3, short estGrupo4, short estGrupo5, short estGrupo6) { this.empCodigo = empCodigo; this.estGrupo1 = estGrupo1; this.estGrupo2 = estGrupo2; this.estGrupo3 = estGrupo3; this.estGrupo4 = estGrupo4; this.estGrupo5 = estGrupo5; this.estGrupo6 = estGrupo6; } public String getEmpCodigo() { return empCodigo; } public void setEmpCodigo(String empCodigo) { this.empCodigo = empCodigo; } public short getEstGrupo1() { return estGrupo1; } public void setEstGrupo1(short estGrupo1) { this.estGrupo1 = estGrupo1; } public short getEstGrupo2() { return estGrupo2; } public void setEstGrupo2(short estGrupo2) { this.estGrupo2 = estGrupo2; } public short getEstGrupo3() { return estGrupo3; } public void setEstGrupo3(short estGrupo3) { this.estGrupo3 = estGrupo3; } public short getEstGrupo4() { return estGrupo4; } public void setEstGrupo4(short estGrupo4) { this.estGrupo4 = estGrupo4; } public short getEstGrupo5() { return estGrupo5; } public void setEstGrupo5(short estGrupo5) { this.estGrupo5 = estGrupo5; } public short getEstGrupo6() { return estGrupo6; } public void setEstGrupo6(short estGrupo6) { this.estGrupo6 = estGrupo6; } }
true
eebd5c167c77e767ab8785930dafec4ab154b0e8
Java
HelAsia/MojePrzepisy
/mobile/app/src/main/java/com/moje/przepisy/mojeprzepisy/recipeDetails/commentDetails/commentEdit/CommentEditActivity.java
UTF-8
3,739
1.921875
2
[]
no_license
package com.moje.przepisy.mojeprzepisy.recipeDetails.commentDetails.commentEdit; import android.content.Intent; import android.support.v7.app.ActionBar; import android.support.v7.app.AppCompatActivity; import android.os.Bundle; import android.view.MenuItem; import android.view.View; import android.widget.Button; import android.widget.EditText; import android.support.v7.widget.Toolbar; import android.widget.TextView; import com.moje.przepisy.mojeprzepisy.R; import com.moje.przepisy.mojeprzepisy.data.repositories.recipe.RecipeRepository; import com.moje.przepisy.mojeprzepisy.recipeDetails.recipeDisplay.MainDetailsTabActivity; import butterknife.BindView; import butterknife.ButterKnife; public class CommentEditActivity extends AppCompatActivity implements CommentEditContract.View{ @BindView(R.id.toolbar_comment_edit) Toolbar toolbar; @BindView(R.id.commentEditText) EditText commentEditText; @BindView(R.id.updateCommentButton) Button updateCommentButton; @BindView(R.id.cancelCommentButton) Button cancelCommentButton; @BindView(R.id.errorEditCommentTextView) TextView errorEditCommentTextView; private CommentEditContract.Presenter presenter; private String comment; private int commentId; private int recipeId; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_comment_edit); ButterKnife.bind(this); presenter = new CommentEditPresenter(this, new RecipeRepository(this)); presenter.setFirstScreen(); } @Override public void setComment(){ if(getIntent().getExtras() != null){ comment = getIntent().getExtras().getString("comment"); } } @Override public void setCommentId(){ if(getIntent().getExtras() != null){ commentId = getIntent().getExtras().getInt("commentId"); } } @Override public void setRecipeId(){ if(getIntent().getExtras() != null){ recipeId = getIntent().getExtras().getInt("recipeId"); } } public void setCommentEditText(){ commentEditText.setText(comment); } public String getCommentAfterEdit(){ return commentEditText.getText().toString(); } public void goToMainDetailsTabActivity(){ Intent intent = new Intent(this, MainDetailsTabActivity.class); Bundle data = new Bundle(); data.putBoolean("isLogged", true); data.putInt("id", recipeId); data.putInt("position", 3); intent.putExtras(data); startActivity(intent); CommentEditActivity.this.finish(); } @Override public void setListeners() { updateCommentButton.setOnClickListener(view -> presenter.sendCommentToServer(commentId, getCommentAfterEdit())); cancelCommentButton.setOnClickListener(view -> goToMainDetailsTabActivity()); } @Override public void setErrorTextView(String message) { errorEditCommentTextView.setVisibility(View.VISIBLE); errorEditCommentTextView.setText(message); } public void setToolbar() { toolbar.setSubtitle(R.string.edit_comment); setSupportActionBar(toolbar); ActionBar actionbar = getSupportActionBar(); if(actionbar != null){ actionbar.setDisplayHomeAsUpEnabled(true); actionbar.setHomeAsUpIndicator(R.drawable.ic_arrow_back); } } public boolean onOptionsItemSelected(MenuItem item){ goToMainDetailsTabActivity(); return true; } @Override public void onBackPressed() { goToMainDetailsTabActivity(); } }
true