blob_id
stringlengths
40
40
directory_id
stringlengths
40
40
path
stringlengths
7
332
content_id
stringlengths
40
40
detected_licenses
listlengths
0
50
license_type
stringclasses
2 values
repo_name
stringlengths
7
115
snapshot_id
stringlengths
40
40
revision_id
stringlengths
40
40
branch_name
stringclasses
557 values
visit_date
timestamp[us]
revision_date
timestamp[us]
committer_date
timestamp[us]
github_id
int64
5.85k
684M
star_events_count
int64
0
77.7k
fork_events_count
int64
0
48k
gha_license_id
stringclasses
17 values
gha_event_created_at
timestamp[us]
gha_created_at
timestamp[us]
gha_language
stringclasses
82 values
src_encoding
stringclasses
28 values
language
stringclasses
1 value
is_vendor
bool
1 class
is_generated
bool
2 classes
length_bytes
int64
7
5.41M
extension
stringclasses
11 values
content
stringlengths
7
5.41M
authors
listlengths
1
1
author
stringlengths
0
161
a8674892dc722ad2d2dfff09bf2b5a07279aaee9
23053cc5befd6cde31111c84dfa42b115da87e27
/app/src/main/java/com/example/calculator/history.java
434a061afc67fef36b71b3fc5b67a4911332a482
[ "Apache-2.0" ]
permissive
Yadav420dilip/Calculator
46038d234ae9df7fc52630762bd269c627b0a824
c8be74ff442370b196542a3c41c9af0d642672f4
refs/heads/main
2020-12-01T17:32:25.602242
2020-10-30T06:42:13
2020-10-30T06:42:13
308,543,436
1
0
null
null
null
null
UTF-8
Java
false
false
1,841
java
package com.example.calculator; import android.database.Cursor; import android.os.Bundle; import android.view.Menu; import android.view.MenuInflater; import android.view.MenuItem; import android.widget.ArrayAdapter; import android.widget.ListView; import android.widget.SimpleCursorAdapter; import androidx.annotation.NonNull; import androidx.appcompat.app.AppCompatActivity; public class history extends AppCompatActivity { ListView listView; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_history); DatabaseHandler dbhandler=new DatabaseHandler(this); Cursor cursor =dbhandler.getAllContacts(); String[] fromColumns = {"Statement","Result_stmt"}; int[] toViews = {R.id.my_statement, R.id.my_result}; SimpleCursorAdapter adapter = new SimpleCursorAdapter(this, R.layout.activity_history, cursor, fromColumns, toViews, 0); listView =findViewById(R.id.my_list_view); listView.setAdapter(adapter); } @Override public boolean onCreateOptionsMenu(Menu menu) { MenuInflater inflater=getMenuInflater(); inflater.inflate(R.menu.history_clear,menu); return super.onCreateOptionsMenu(menu); } @Override public boolean onOptionsItemSelected(@NonNull MenuItem item) { if (item.getItemId() ==R.id.history_clear) { DatabaseHandler dbhandler=new DatabaseHandler(this); dbhandler.delete_contact(); String[] emptyarray= {""}; ArrayAdapter adp = new ArrayAdapter<>(this, R.layout.activity_history,R.id.my_statement, emptyarray); listView.setAdapter(adp); } return super.onOptionsItemSelected(item); } }
[ "dy7208451003@gmail.com" ]
dy7208451003@gmail.com
cb05c271256c5733c95d67f4e6e16d52a985783c
69c5b5486a6dd216d534b885be98dca0261fa21c
/xss-core-lib/src/ctr/stuba/xss/engine/EngineStatus.java
ea1fd1913a7d380201450a821fc9656edbce1787
[]
no_license
castorw/stuba-oop-xss
8d14864092978c31869b85b3cb7efd83ce0d1407
cef61e149d742fe0c96fdec7bf9669a90e49ec1d
refs/heads/master
2020-05-26T20:19:59.640968
2014-03-11T17:30:08
2014-03-11T17:30:08
null
0
0
null
null
null
null
UTF-8
Java
false
false
163
java
package ctr.stuba.xss.engine; /** * Engine runtime status. * * @author Lubomir Kaplan <castor@castor.sk> */ public enum EngineStatus { IDLE, ALARM }
[ "castor@castor.sk" ]
castor@castor.sk
723f7d12e5ffcd258a27a60c09943330ce7163aa
1fdc5ce5a3f75e6509714df5340f7336fc1b57fa
/src/bienvenida/Agregar.java
0439b260dfabce9eba725f29f90b549304e493eb
[]
no_license
Engelbert-2110/Serpientes-Escaleras
b62064b35e5a9307fe5275e4198ed2cc91238e56
dd1502e95ac69d3ec935a48bcd6c1b5204e5c38c
refs/heads/master
2023-06-05T09:32:59.259463
2021-06-30T00:58:32
2021-06-30T00:58:32
null
0
0
null
null
null
null
UTF-8
Java
false
false
12,828
java
package bienvenida; import java.io.BufferedReader; import java.io.File; import java.io.FileReader; import java.io.PrintWriter; import usuario.*; import java.util.ArrayList; import javax.swing.JOptionPane; public final class Agregar extends javax.swing.JFrame { private ArrayList<Persona>Lis; public Agregar() { Lis= new ArrayList<Persona>(); initComponents(); this.setLocationRelativeTo(Agregar.this); } @SuppressWarnings("unchecked") // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents private void initComponents() { jLabel3 = new javax.swing.JLabel(); jLabel1 = new javax.swing.JLabel(); jLabel2 = new javax.swing.JLabel(); jLabel4 = new javax.swing.JLabel(); TxtId = new javax.swing.JTextField(); TxtNombre = new javax.swing.JTextField(); TxtApellido = new javax.swing.JTextField(); BtnAgregar = new javax.swing.JButton(); BtnEliminar = new javax.swing.JButton(); BtnRegresar = new javax.swing.JButton(); jLabel5 = new javax.swing.JLabel(); jScrollPane1 = new javax.swing.JScrollPane(); JTablePersona = new javax.swing.JTable(); Fondo = new javax.swing.JLabel(); jLabel3.setText("jLabel3"); setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE); setFont(new java.awt.Font("Bahnschrift", 0, 12)); // NOI18N getContentPane().setLayout(new org.netbeans.lib.awtextra.AbsoluteLayout()); jLabel1.setBackground(new java.awt.Color(255, 255, 255)); jLabel1.setFont(new java.awt.Font("Dialog", 1, 14)); // NOI18N jLabel1.setForeground(new java.awt.Color(255, 255, 255)); jLabel1.setText("Id"); getContentPane().add(jLabel1, new org.netbeans.lib.awtextra.AbsoluteConstraints(70, 60, 30, 30)); jLabel2.setBackground(new java.awt.Color(255, 255, 255)); jLabel2.setFont(new java.awt.Font("Dialog", 1, 14)); // NOI18N jLabel2.setForeground(new java.awt.Color(255, 255, 255)); jLabel2.setText("Nombre"); getContentPane().add(jLabel2, new org.netbeans.lib.awtextra.AbsoluteConstraints(50, 110, 60, 30)); jLabel4.setBackground(new java.awt.Color(255, 255, 255)); jLabel4.setFont(new java.awt.Font("Dialog", 1, 14)); // NOI18N jLabel4.setForeground(new java.awt.Color(255, 255, 255)); jLabel4.setText("Apellido"); getContentPane().add(jLabel4, new org.netbeans.lib.awtextra.AbsoluteConstraints(50, 160, 60, 30)); TxtId.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { TxtIdActionPerformed(evt); } }); getContentPane().add(TxtId, new org.netbeans.lib.awtextra.AbsoluteConstraints(130, 60, 110, -1)); TxtNombre.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { TxtNombreActionPerformed(evt); } }); getContentPane().add(TxtNombre, new org.netbeans.lib.awtextra.AbsoluteConstraints(130, 110, 190, -1)); TxtApellido.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { TxtApellidoActionPerformed(evt); } }); getContentPane().add(TxtApellido, new org.netbeans.lib.awtextra.AbsoluteConstraints(130, 160, 190, -1)); BtnAgregar.setBackground(new java.awt.Color(255, 255, 255)); BtnAgregar.setFont(new java.awt.Font("Dialog", 1, 14)); // NOI18N BtnAgregar.setForeground(new java.awt.Color(0, 0, 0)); BtnAgregar.setText("Agregar"); BtnAgregar.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { BtnAgregarActionPerformed(evt); } }); getContentPane().add(BtnAgregar, new org.netbeans.lib.awtextra.AbsoluteConstraints(370, 70, 100, 30)); BtnEliminar.setBackground(new java.awt.Color(255, 255, 255)); BtnEliminar.setFont(new java.awt.Font("Dialog", 1, 14)); // NOI18N BtnEliminar.setForeground(new java.awt.Color(0, 0, 0)); BtnEliminar.setText("Eliminar"); BtnEliminar.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { BtnEliminarActionPerformed(evt); } }); getContentPane().add(BtnEliminar, new org.netbeans.lib.awtextra.AbsoluteConstraints(370, 120, 100, 30)); BtnRegresar.setBackground(new java.awt.Color(255, 255, 255)); BtnRegresar.setFont(new java.awt.Font("Dialog", 1, 14)); // NOI18N BtnRegresar.setForeground(new java.awt.Color(0, 0, 0)); BtnRegresar.setText("Regresar"); BtnRegresar.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { BtnRegresarActionPerformed(evt); } }); getContentPane().add(BtnRegresar, new org.netbeans.lib.awtextra.AbsoluteConstraints(480, 310, 110, 40)); jLabel5.setFont(new java.awt.Font("Dialog", 1, 18)); // NOI18N jLabel5.setForeground(new java.awt.Color(255, 255, 255)); jLabel5.setText("Sala Jugadores"); getContentPane().add(jLabel5, new org.netbeans.lib.awtextra.AbsoluteConstraints(220, 0, 150, 40)); JTablePersona.setForeground(new java.awt.Color(0, 0, 0)); JTablePersona.setModel(new javax.swing.table.DefaultTableModel( new Object [][] { {null, null, null}, {null, null, null}, {null, null, null}, {null, null, null} }, new String [] { "Id", "Nombre", "Apellido" } )); JTablePersona.setGridColor(new java.awt.Color(0, 0, 0)); jScrollPane1.setViewportView(JTablePersona); getContentPane().add(jScrollPane1, new org.netbeans.lib.awtextra.AbsoluteConstraints(10, 250, 460, 140)); Fondo.setFont(new java.awt.Font("Dialog", 1, 14)); // NOI18N Fondo.setForeground(new java.awt.Color(255, 255, 255)); Fondo.setIcon(new javax.swing.ImageIcon(getClass().getResource("/imagenes/Naturaleza.jpg"))); // NOI18N getContentPane().add(Fondo, new org.netbeans.lib.awtextra.AbsoluteConstraints(0, 0, 610, 420)); pack(); }// </editor-fold>//GEN-END:initComponents private void TxtNombreActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_TxtNombreActionPerformed // TODO add your handling code here: }//GEN-LAST:event_TxtNombreActionPerformed private void TxtApellidoActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_TxtApellidoActionPerformed // TODO add your handling code here: }//GEN-LAST:event_TxtApellidoActionPerformed private void TxtIdActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_TxtIdActionPerformed // TODO add your handling code here: }//GEN-LAST:event_TxtIdActionPerformed public void Cargar (){ File Archivo = new File ("Jugadores.txt"); FileReader Leer; BufferedReader Almacen; Persona per, aux = new Persona(); try { Leer = new FileReader(Archivo); Almacen = new BufferedReader(Leer); per = aux.cargar(Almacen); while (per != null) { Lis.add(per); } Almacen.close(); Leer.close(); } catch (Exception e) { } verDatos(); } private void limpiar(){ TxtId.setText(""); TxtNombre.setText(""); TxtApellido.setText(""); } private void BtnAgregarActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_BtnAgregarActionPerformed String Nom,Apell; int id; try{ Nom = TxtNombre.getText(); Apell = TxtApellido.getText(); id = Integer.parseInt(TxtId.getText()); Lis.add(new Persona(id, Nom, Apell) ); }catch (Exception e){ JOptionPane.showMessageDialog(null, "Verifica los datos"); } limpiar(); verDatos(); }//GEN-LAST:event_BtnAgregarActionPerformed private void BtnEliminarActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_BtnEliminarActionPerformed int c; try { c = JTablePersona.getSelectedRow(); Lis.remove(c); } catch (Exception e) { JOptionPane.showMessageDialog(null, "Favor escoja una fila"); } verDatos(); }//GEN-LAST:event_BtnEliminarActionPerformed //Guardar los jugadores agregados en archivos private void guardar(){ File file = new File("Jugadores.txt"); PrintWriter Escribe; //Crear archivos if (!file.exists()) { try { file.createNewFile(); } catch (Exception e) { } } //Guardar Archivos try { Persona auxiliar; Escribe = new PrintWriter(file, "utf-8"); for (int i = 0; i < Lis.size(); i++) { auxiliar = Lis.get(i); auxiliar.guardar(Escribe); } Escribe.close(); } catch (Exception e) { } } private void BtnRegresarActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_BtnRegresarActionPerformed String botones [] = {"Si", "No"}; int opcion = JOptionPane.showOptionDialog(null, "Desea guardar la informacion?", "Titulo", 0, 0, null, botones, null); if (opcion == 0) { guardar(); } Menu regresar = new Menu(); regresar.setVisible(true); dispose(); }//GEN-LAST:event_BtnRegresarActionPerformed private void verDatos(){ String Mat[][] = new String [Lis.size()][3]; Persona aux; for (int i = 0; i < Lis.size(); i++) { aux = Lis.get(i); Mat[i][0] = Integer.toString(aux.getId()); Mat[i][1] = aux.getNombre(); Mat[i][2] = aux.getApellido(); } JTablePersona.setModel(new javax.swing.table.DefaultTableModel( Mat, new String [] { "Id", "Nombre", "Apellido" } )); } public static void main(String args[]) { try { for (javax.swing.UIManager.LookAndFeelInfo info : javax.swing.UIManager.getInstalledLookAndFeels()) { if ("Nimbus".equals(info.getName())) { javax.swing.UIManager.setLookAndFeel(info.getClassName()); break; } } } catch (ClassNotFoundException ex) { java.util.logging.Logger.getLogger(Agregar.class.getName()).log(java.util.logging.Level.SEVERE, null, ex); } catch (InstantiationException ex) { java.util.logging.Logger.getLogger(Agregar.class.getName()).log(java.util.logging.Level.SEVERE, null, ex); } catch (IllegalAccessException ex) { java.util.logging.Logger.getLogger(Agregar.class.getName()).log(java.util.logging.Level.SEVERE, null, ex); } catch (javax.swing.UnsupportedLookAndFeelException ex) { java.util.logging.Logger.getLogger(Agregar.class.getName()).log(java.util.logging.Level.SEVERE, null, ex); } java.awt.EventQueue.invokeLater(new Runnable() { public void run() { new Agregar().setVisible(true); } }); } // Variables declaration - do not modify//GEN-BEGIN:variables private javax.swing.JButton BtnAgregar; private javax.swing.JButton BtnEliminar; private javax.swing.JButton BtnRegresar; private javax.swing.JLabel Fondo; private javax.swing.JTable JTablePersona; private javax.swing.JTextField TxtApellido; private javax.swing.JTextField TxtId; private javax.swing.JTextField TxtNombre; 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.JScrollPane jScrollPane1; // End of variables declaration//GEN-END:variables }
[ "engelbertestrada201930200@cunoc.edu.gt" ]
engelbertestrada201930200@cunoc.edu.gt
8d684c90ce9cd5fe5b93025118c84598f072a169
9ec935ce0b71dcd5fb9626ae8e8faeb51c654256
/jeecg/src/main/java/com/jason/ddoWeb/controller/monitor/MonitorController.java
c6d005096636b9a7140a8b0b59a7e639338a849f
[]
no_license
859162000/ddo_platform
5d047116d9143aaca70bcaf3ce33527680a11cb9
4e9ea4a328a4227fe866ac40e9357680adfa1e00
refs/heads/master
2021-05-29T17:13:06.735487
2015-06-17T00:39:54
2015-06-17T00:39:54
null
0
0
null
null
null
null
UTF-8
Java
false
false
2,993
java
/** * */ package com.jason.ddoWeb.controller.monitor; import java.io.IOException; import java.util.HashMap; import java.util.Map; import javax.servlet.http.HttpServletRequest; import org.apache.http.client.ClientProtocolException; import org.jeecgframework.core.common.model.json.AjaxJson; import org.jeecgframework.core.constant.Globals; import org.jeecgframework.core.util.ResourceUtil; import org.jeecgframework.web.system.service.SystemService; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.context.annotation.Scope; import org.springframework.stereotype.Controller; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.ResponseBody; import org.springframework.web.servlet.ModelAndView; import com.jason.ddoWeb.util.HttpUtils; /** * @author jasonzhang * */ @Scope("prototype") @Controller @RequestMapping("/monitorController") public class MonitorController { @Autowired private SystemService systemService; private String message; public String getMessage() { return message; } public void setMessage(String message) { this.message = message; } /** * 黑名单管理列表 页面跳转 * * @return */ @RequestMapping(params = "monitor") public ModelAndView monitor(HttpServletRequest request) { return new ModelAndView("com/jason/ddoWeb/monitor/monitor"); } /** * 查看收发引擎的运行状态,包括各个队列中的剩余数据及引擎的运行情况 * @param request * @return */ @RequestMapping(params = "ddoMsgStatus") @ResponseBody public AjaxJson ddoMsgStatus(HttpServletRequest request) { AjaxJson j = new AjaxJson(); String postUrl = ResourceUtil.getConfigByName("ddoMsg.url") + ResourceUtil.getConfigByName("ddoMsg.monitorPath"); Map<String, String> paramMap = new HashMap<String, String>(); String resp = null; try { resp = HttpUtils.post(postUrl, paramMap); } catch (ClientProtocolException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } if (resp != null) { j.setMsg(resp); } return j; } /** * 停止或启动收发引擎 * @param request * @return */ @RequestMapping(params = "controlDdoMsg") @ResponseBody public AjaxJson controlDdoMsg(HttpServletRequest request) { AjaxJson j = new AjaxJson(); String postUrl = ResourceUtil.getConfigByName("ddoMsg.url") + ResourceUtil.getConfigByName("ddoMsg.stopServicePath"); Map<String, String> paramMap = new HashMap<String, String>(); paramMap.put("command", request.getParameter("command")); String resp = null; try { resp = HttpUtils.post(postUrl, paramMap); } catch (ClientProtocolException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } if (resp != null) { j.setMsg(resp); } message = "停止/启动ddo收发引擎成功"; systemService.addLog(message, Globals.Log_Type_DEL, Globals.Log_Leavel_INFO); return j; } }
[ "z_jordon@163.com" ]
z_jordon@163.com
1901eb6e1de1fb75f9dd9d01814dead36a9bbab8
622c4eef62d22be3d899e06cb8677133a5594f5a
/app/src/main/java/com/zhj/retrofithelper/retrofit/SSLSocketClient.java
76062aced59e0b6d8346bef54ef52703691c2731
[]
no_license
zhj1993/RetrofitHelper
0c50c1bd19325015c11af21bf82aed125a31d5e8
92c43e4c870cbf6a93d03cfd6905fa0dfe4bfe8f
refs/heads/master
2020-03-29T05:37:47.660541
2019-01-23T06:52:36
2019-01-23T06:52:36
149,590,975
3
1
null
null
null
null
UTF-8
Java
false
false
1,869
java
package com.zhj.retrofithelper.retrofit; import java.security.SecureRandom; import java.security.cert.CertificateException; import java.security.cert.X509Certificate; import javax.net.ssl.HostnameVerifier; import javax.net.ssl.SSLContext; import javax.net.ssl.SSLSession; import javax.net.ssl.SSLSocketFactory; import javax.net.ssl.TrustManager; import javax.net.ssl.X509TrustManager; /** * 介绍: (https验证 暂时忽略认证) * 作者: zhahaijun * 邮箱: zhahaijun@bearead.cn * 时间: 2018/9/10 */ public class SSLSocketClient { public static SSLSocketFactory getSSLSocketFactory() { try { SSLContext sslContext = SSLContext.getInstance("SSL"); sslContext.init(null, getTrustManager(), new SecureRandom()); return sslContext.getSocketFactory(); } catch (Exception e) { throw new RuntimeException(e); } } public static TrustManager[] getTrustManager() { TrustManager[] trustAllCerts = new TrustManager[]{new X509TrustManager() { @Override public void checkClientTrusted(X509Certificate[] chain, String authType) throws CertificateException { } @Override public void checkServerTrusted(X509Certificate[] chain, String authType) throws CertificateException { } @Override public X509Certificate[] getAcceptedIssuers() { return new X509Certificate[0]; } }}; return trustAllCerts; } //信任host public static HostnameVerifier getHostnameVerifier() { HostnameVerifier hostnameVerifier = new HostnameVerifier() { @Override public boolean verify(String s, SSLSession sslSession) { return true; } }; return hostnameVerifier; } }
[ "zhahaijun@bearead.cn" ]
zhahaijun@bearead.cn
9f641e4fea1a48c2af1527e54ed0a4c0d5a98fbd
c0177ed70f8b7f87e72538c23904c66ef655b378
/src/db/MessageRepoImpl.java
7c6ab3a1ed8d05051b1b9e7d764c9681accc0d53
[]
no_license
manischewitz/webspringtest
bed3256c2e34f713c4960083c0274c06a5254d26
f427de04fe56611d9d61d927c7febc7366b4e5c7
refs/heads/master
2020-12-25T14:14:51.753035
2016-09-11T17:32:25
2016-09-11T17:32:25
67,883,058
0
0
null
null
null
null
UTF-8
Java
false
false
7,240
java
package db; import java.sql.Connection; import java.sql.PreparedStatement; import java.sql.ResultSet; import java.sql.SQLException; import java.sql.Statement; import java.util.ArrayList; import java.util.List; import javax.sql.DataSource; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.context.annotation.Profile; import org.springframework.stereotype.Component; import objects.Message; import web.AuthorityManager; @Profile("jdbc") @Component public class MessageRepoImpl implements MessagesRepository { public final static String TABLE_NAME = "messages"; private final static String SQL_SAVE_MESSAGE = "INSERT INTO "+TABLE_NAME+" (posted_by,message,latitude,longitude) VALUES(?,?,?,?)"; private final static String SQL_FIND_MESSAGES = "SELECT id,posted_by,message,post_date,latitude,longitude FROM "+TABLE_NAME+ " WHERE id<? ORDER BY id DESC LIMIT ?;"; private final static String SQL_FIND_BY_ID = "SELECT id,posted_by,message,post_date,latitude,longitude FROM "+TABLE_NAME+" WHERE id=?;"; private final static String SQL_DELETE_MESSAGE = "DELETE FROM "+TABLE_NAME+" WHERE id=?;"; private final static String SQL_FIND_MESSAGES_FOR_USER ="SELECT id,posted_by,message,post_date,latitude,longitude FROM "+TABLE_NAME+" WHERE posted_by = ?;"; private final static String SQL_UPDATE_MESSAGE = "UPDATE "+TABLE_NAME+" SET message=?,posted_by=? WHERE id=?;"; @Autowired private DataSource dataSource; @Override public List<Message> findLastMessages(long max, int count) { List<Message> messagesList = new ArrayList<Message>(count); Connection connection = null; PreparedStatement preparedStatement = null; ResultSet resultSet = null; try{ connection = this.dataSource.getConnection(); preparedStatement = connection.prepareStatement(SQL_FIND_MESSAGES); preparedStatement.setLong(1, max); preparedStatement.setInt(2, count); resultSet = preparedStatement.executeQuery(); Message message = null; for(int i =0;i<count ; i++){ if(resultSet.next()){ message = new Message(resultSet.getString("message"), resultSet.getTimestamp("post_date"), resultSet.getDouble("latitude"), resultSet.getDouble("longitude"), resultSet.getLong("id"),resultSet.getString("posted_by")); messagesList.add(message); } } return messagesList; }catch(SQLException sqle){ System.err.println("SQLException"); sqle.printStackTrace(); }finally{ this.catchExceptions(connection, preparedStatement, resultSet); } return null; } @Override public Message findOne(long id) { Connection connection = null; PreparedStatement preparedStatement = null; ResultSet resultSet = null; try{ connection = this.dataSource.getConnection(); preparedStatement = connection.prepareStatement(SQL_FIND_BY_ID); preparedStatement.setLong(1, id); resultSet = preparedStatement.executeQuery(); Message message = null; if(resultSet.next()){ message = new Message(resultSet.getString("message"), resultSet.getTimestamp("post_date"), resultSet.getDouble("latitude"), resultSet.getDouble("longitude"), id,resultSet.getString("posted_by")); } return message; }catch(SQLException sqle){ System.err.println("SQLException"); sqle.printStackTrace(); }finally{ this.catchExceptions(connection, preparedStatement, resultSet); } return null; } @Override public Message save(Message message) { AuthorityManager.instance().hasAuthorities(new String[] {"user","root"}); Connection connection = null; PreparedStatement preparedStatement = null; ResultSet resultSet = null; /*CREATE TABLE IF NOT EXISTS messages ( id BIGINT UNSIGNED NOT NULL AUTO_INCREMENT PRIMARY KEY , message VARCHAR(4096) NOT NULL, post_date timestamp DEFAULT CURRENT_TIMESTAMP, latitude FLOAT, longitude FLOAT);*/ try{ connection = this.dataSource.getConnection(); preparedStatement = connection.prepareStatement(SQL_SAVE_MESSAGE,Statement.RETURN_GENERATED_KEYS); preparedStatement.setString(1, message.getUsername()); preparedStatement.setString(2, message.getMessage()); preparedStatement.setDouble(3, message.getLatitude()); preparedStatement.setDouble(4, message.getLongitude()); preparedStatement.execute(); resultSet = preparedStatement.getGeneratedKeys(); if(resultSet.next()) message.setId(resultSet.getLong(1)); return message; }catch(SQLException sqle){ sqle.printStackTrace(); return null; }finally{ this.catchExceptions(connection, preparedStatement, resultSet); } } public boolean delete(long id){ AuthorityManager.instance().hasAuthorities(new String[] {"user","root"}); Connection connection = null; PreparedStatement preparedStatement = null; try{ connection = dataSource.getConnection(); preparedStatement = connection.prepareStatement(SQL_DELETE_MESSAGE); preparedStatement.setLong(1, id); preparedStatement.execute(); return true; }catch(SQLException sqle){ System.err.println("SQLException"); sqle.printStackTrace(); }finally{ this.catchExceptions(connection, preparedStatement,null); } return false; //add feature: write deleted message into another table for deleted messages } private void catchExceptions(Connection connection,PreparedStatement preparedStatement,ResultSet resultSet){ try{ if(resultSet != null) resultSet.close(); if(preparedStatement != null) preparedStatement.close(); if(connection != null) connection.close(); }catch(SQLException sqle){ System.err.println("SQLException"); sqle.printStackTrace(); } } @Override public List<Message> getMessagesForUser(String username) { Connection connection = null; PreparedStatement preparedStatement = null; ResultSet resultSet = null; try{ connection = this.dataSource.getConnection(); preparedStatement = connection.prepareStatement(SQL_FIND_MESSAGES_FOR_USER); preparedStatement.setString(1, username); resultSet = preparedStatement.executeQuery(); List<Message> messagesList = new ArrayList<>(100);; while(resultSet.next()){ messagesList.add(new Message()); } return messagesList; }catch(SQLException sqle){ System.err.println("SQLException"); sqle.printStackTrace(); }finally{ this.catchExceptions(connection, preparedStatement, resultSet); } return null; } public DataSource getDataSource() { return dataSource; } public void setDataSource(DataSource dataSource) { this.dataSource = dataSource; } @Override public Message updateMessage(Message updatedMessage) { Connection connection = null; PreparedStatement preparedStatement = null; try{ connection = this.dataSource.getConnection(); preparedStatement = connection.prepareStatement(SQL_UPDATE_MESSAGE); preparedStatement.setString(1, updatedMessage.getMessage()); preparedStatement.setString(2, updatedMessage.getUsername()); preparedStatement.setLong(3, updatedMessage.getId()); preparedStatement.executeUpdate(); return updatedMessage; }catch(SQLException sqle){ System.err.println("SQLException"); sqle.printStackTrace(); }finally{ this.catchExceptions(connection, preparedStatement, null); } return null; } }
[ "icktfwih@gmail.com" ]
icktfwih@gmail.com
b134c7313ef25dca9a9adb162246cdc629299e9f
5543a7030ffa5d494e8723958bcf34fdf3c5706b
/core/src/com/fs/game/ai/fsm/RiskFactors.java
339dd0e55723e91754aced0a991f019600917846
[]
no_license
iceycode/forward-strategy
f2e72002b3e17e99a85aa6ee3895b61b3d989db1
d4aa467466a262acc3026253fafc52cdbda37a8b
refs/heads/master
2021-01-22T13:46:48.726973
2015-06-02T19:56:50
2015-06-02T19:56:50
25,098,133
3
2
null
2015-06-02T19:56:50
2014-10-11T22:44:47
Java
UTF-8
Java
false
false
2,474
java
package com.fs.game.ai.fsm; import com.badlogic.gdx.utils.Array; import com.badlogic.gdx.utils.IntMap; import com.fs.game.units.Unit; import com.fs.game.data.GameData; /** RiskState contains information about * Agent Units' & Player Units' health & damageList * Created by Allen on 5/12/15. */ public class RiskFactors { private static RiskFactors instance; //flags for damage types - get factored into UnitAgent decision public final static int KILL_DAMAGE = 4; public final static int HIGH_DAMAGE = 3; public final static int MEDIUM_DAMAGE = 2; public final static int LOW_DAMAGE = 1; public final static int NO_DAMAGE = 0; //contains arrays of each unit's list of damage public static IntMap<Array<int[]>> damageMap = new IntMap<Array<int[]>>(); //contains health animState public static IntMap<Array<Integer>> healthMap = new IntMap<Array<Integer>>(); public RiskFactors(){ initHealthMap(GameData.enemyUnits.size + GameData.playerUnits.size); initDamageMap(GameData.enemyUnits, GameData.playerUnits); } public static RiskFactors getInstance() { if (instance == null) instance = new RiskFactors(); return instance; } /** sets up healthMap * NOTE: unitsCount is ALL units in game * * @param unitsCount : number of units on board TOTAL */ public void initHealthMap(int unitsCount){ Integer[] healths = new Integer[unitsCount]; //initalize array for (int i = 0; i < unitsCount; i++){ healths[i] = 4; } Array<Integer> healthArray1 = new Array<Integer>(healths); Array<Integer> healthArray2 = new Array<Integer>(healths); healthMap.put(0, healthArray1); healthMap.put(1, healthArray2); } public void initDamageMap(Array<Unit> agentUnits, Array<Unit> playerUnits){ Array<int[]> aUnitDamages = new Array<int[]>(); for (Unit unit : agentUnits){ aUnitDamages.add(unit.getUnitInfo().getDamageList()); } Array<int[]> pUnitDmgs = new Array<int[]>(); for (Unit unit : playerUnits){ pUnitDmgs.add(unit.getUnitInfo().getDamageList()); } damageMap.put(0, aUnitDamages); damageMap.put(1, pUnitDmgs); } // //scores relating to decision UnitAgent makes // public int[] initDecisionScores(){ // // } // // public int[] getFactorScores(){ // // } }
[ "allen.jagoda@gmail.com" ]
allen.jagoda@gmail.com
838b0724a071d1d3ae92ba5c33ca3afe97ce9199
e94edf09608ed9c261a425af0280d28beb59a194
/Exam/src/bakery/entities/drinks/Water.java
d00174f6c8b70b21c0ce8a7b66051334f37eddae
[]
no_license
uckpeH93/Java-OOP
3d3b06a57c08b85bcfd29099a20c91c9666513b9
9ca47d89dafb45ec37e493654f7c26a41fa3340b
refs/heads/master
2023-04-22T20:10:34.437141
2021-05-06T20:29:33
2021-05-06T20:29:33
null
0
0
null
null
null
null
UTF-8
Java
false
false
262
java
package bakery.entities.drinks; //created by J.M. public class Water extends BaseDrink { public static final double WATER_PRICE = 1.50; public Water(String name, int portion, String brand) { super(name, portion, WATER_PRICE, brand); } }
[ "Petrov.connect@gmail.com" ]
Petrov.connect@gmail.com
5a4bb7c06f8a6835de9d935b25eccb18b9559a4d
68a19507f18acff18aa4fa67d6611f5b8ac8913c
/plfx/plfx-jp/plfx-jp-application/src/main/java/plfx/jp/app/component/redisson/RedissonFactory.java
dee9436741c043f1a09a3679a68beefd74ab0fff
[]
no_license
ksksks2222/pl-workspace
cf0d0be2dfeaa62c0d4d5437f85401f60be0eadd
6146e3e3c2384c91cac459d25b27ffeb4f970dcd
refs/heads/master
2021-09-13T08:59:17.177105
2018-04-27T09:46:42
2018-04-27T09:46:42
null
0
0
null
null
null
null
UTF-8
Java
false
false
2,066
java
package plfx.jp.app.component.redisson; import org.redisson.ClusterServersConfig; import org.redisson.Config; import org.redisson.Redisson; import org.redisson.SingleServerConfig; /** * @类功能说明:Redisson工厂类 * @类修改者: * @修改日期:2015-7-15下午5:32:09 * @修改说明: * @公司名称:浙江汇购科技有限公司 * @作者:zhurz * @创建时间:2015-7-15下午5:32:09 */ public class RedissonFactory { private RedissonConfig redissonConfig; private static Redisson redisson; private void init() { Config config = new Config(); if (redissonConfig.getAddressList() == null || redissonConfig.getAddressList().size() == 0) { throw new RuntimeException("redis地址未配置"); } else if (redissonConfig.getAddressList().size() == 1) { SingleServerConfig singleServerConfig = config.useSingleServer(); singleServerConfig.setTimeout(redissonConfig.getTimeout()); singleServerConfig.setDatabase(redissonConfig.getDatabase()); singleServerConfig.setAddress(redissonConfig.getAddressList().get(0)); } else { ClusterServersConfig clusterServersConfig = config.useClusterServers(); clusterServersConfig.setTimeout(redissonConfig.getTimeout()); clusterServersConfig.setDatabase(redissonConfig.getDatabase()); clusterServersConfig.setMasterConnectionPoolSize(redissonConfig.getConnectionPoolSize()); clusterServersConfig.setSlaveConnectionPoolSize(redissonConfig.getConnectionPoolSize()); String[] addresses = new String[redissonConfig.getAddressList().size()]; redissonConfig.getAddressList().toArray(addresses); clusterServersConfig.addNodeAddress(addresses); } redisson = Redisson.create(config); } public Redisson getRedisson() { synchronized (this) { if (redisson == null) init(); } return redisson; } public RedissonConfig getRedissonConfig() { return redissonConfig; } public void setRedissonConfig(RedissonConfig redissonConfig) { this.redissonConfig = redissonConfig; } }
[ "cangsong6908@gmail.com" ]
cangsong6908@gmail.com
047ee6b9e2f0e6d58e489bba1b04c653cce67245
514d6469bad24b2ef672667df010d33f5ec43c5f
/src/com/lananh1/bai2/toptailieu/SachGiaoKhoa.java
bad072fd94b5c32bbed724da86c5e2a606b68fb1
[]
no_license
MocLan/b-i-t-p-v-nh-
7ee2505d42aa1275172c83af1fa4509f67734fd0
77080f3031cdfaa10f9ef0f4ae9fdf84f63c8904
refs/heads/master
2020-04-05T12:06:47.505141
2019-01-11T10:48:00
2019-01-11T10:48:00
156,859,132
0
0
null
null
null
null
UTF-8
Java
false
false
960
java
package com.lananh1.bai2.toptailieu; import java.util.Date; import java.util.Scanner; public class SachGiaoKhoa extends Sach { final int moi = 1; final int cu = 2; private int tinhTrang; public SachGiaoKhoa() { super(); } public SachGiaoKhoa(String maSach, Date ngayNhap, long donGia, int soLuong, String nhaXuatBan) { super(maSach, ngayNhap, donGia, soLuong, nhaXuatBan); } @Override public double thanhTien() { if (moi == tinhTrang) { return getSoLuong() * getDonGia(); } return (double) (getDonGia() * getSoLuong() * 0.5); } @Override public void nhap() { super.nhap(); System.out.println("nhập vào tính trạng"); this.tinhTrang = new Scanner(System.in).nextInt(); } @Override public String toString() { return "SachGiaoKhoa{" + "tinhTrang=" + tinhTrang + '}'; } }
[ "lannguyen20081998@gmail.com" ]
lannguyen20081998@gmail.com
d5430f05800c548c9d451746d4f8ed40545812ce
32fc1acbe2b040847424b11ba072275585499ecd
/app/src/main/java/vistas/SpinnerItems.java
f6e729ba390a591ec9805f6221e7e32639ca74ef
[]
no_license
edgarjvh/EBNDSR-REP
90d54065df8ef2d2e4e8a8fe76f2b767f0ddcaa5
e865b36cad13ee6643dbde700db2d6fd63c89d70
refs/heads/master
2021-01-13T14:56:16.712277
2017-01-16T06:51:25
2017-01-16T06:51:25
76,665,102
0
0
null
null
null
null
UTF-8
Java
false
false
2,050
java
package vistas; @SuppressWarnings("ALL") public class SpinnerItems { private int registrado; private int idDocente; private String apellidosDoc; private String nombresDoc; private int idAlumno; private String apellidosAl; private String nombresAl; private String imagen; public SpinnerItems(int registrado, int idDocente, String apellidosDoc, String nombresDoc, int idAlumno, String apellidosAl, String nombresAl, String imagen){ this.registrado = registrado; this.idDocente = idDocente; this.apellidosDoc = apellidosDoc; this.nombresDoc = nombresDoc; this.idAlumno = idAlumno; this.apellidosAl = apellidosAl; this.nombresAl = nombresAl; this.imagen = imagen; } public int getRegistrado() { return registrado; } public void setRegistrado(int registrado) { this.registrado = registrado; } public int getIdDocente() { return idDocente; } public void setIdDocente(int idDocente) { this.idDocente = idDocente; } public String getApellidosDoc() { return apellidosDoc; } public void setApellidosDoc(String apellidosDoc) { this.apellidosDoc = apellidosDoc; } public String getNombresDoc() { return nombresDoc; } public void setNombresDoc(String nombresDoc) { this.nombresDoc = nombresDoc; } public int getIdAlumno() { return idAlumno; } public void setIdAlumno(int idAlumno) { this.idAlumno = idAlumno; } public String getApellidosAl() { return apellidosAl; } public void setApellidosAl(String apellidosAl) { this.apellidosAl = apellidosAl; } public String getNombresAl() { return nombresAl; } public void setNombresAl(String nombresAl) { this.nombresAl = nombresAl; } public String getImagen() { return imagen; } public void setImagen(String imagen) { this.imagen = imagen; } }
[ "edgarjvh@gmail.com" ]
edgarjvh@gmail.com
e924aef865a7901d9e0ebb2b822b21a3ba8e5f72
1746dcf9a8932971ec1beb40426164c06df8d6c5
/DomainModel/src/main/java/ru/swimmasters/domain/EntryStatus.java
77ae033cd3bab61259d8e0f0ec4460280d634df1
[]
no_license
dedmajor/swimming
2df78dbabb7fe1b58ad242125cd3e753e128e264
0d5d88444f82fd1d8832948e9a6b1018859b7738
refs/heads/master
2021-01-01T20:06:34.006239
2011-12-07T07:23:01
2011-12-07T07:23:01
681,833
0
0
null
null
null
null
UTF-8
Java
false
false
250
java
package ru.swimmasters.domain; /** * User: dedmajor * Date: 3/13/11 */ public enum EntryStatus { REGULAR, //EXHIBITION, // TODO: LEN statuses REJECTED, //WITHDRAWN, // TODO: LEN statuses, constraint: entry have no heat or lane? }
[ "dedmajor@gmail.com" ]
dedmajor@gmail.com
ec002dd471a626264d69568f03119aaecd978693
d94c9e6ec81ae4d1bf633397ba655b50a51bcf2d
/git/Onedayclass/src/one/controller/classCategory/image/Image.java
9a8d951b3fd112837f86e90f39cc0dd915b6ddec
[]
no_license
jueunham/khsemi5_onedayclass
63c0dbdec5938a484b6ba4f5d0250c5391606897
3c1c18281584e34bce725b831ed114429e0cf328
refs/heads/master
2020-05-27T19:39:44.826189
2019-06-12T06:05:30
2019-06-12T06:05:30
188,763,780
0
5
null
2019-06-12T06:57:30
2019-05-27T03:18:44
Java
UTF-8
Java
false
false
667
java
package one.controller.classCategory.image; import java.io.IOException; import javax.servlet.ServletException; import javax.servlet.annotation.WebServlet; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; @WebServlet("/image/main") public class Image extends HttpServlet { private static final long serialVersionUID = 1L; @Override protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { req.getRequestDispatcher("/WEB-INF/views/classCategory/04_image/main.jsp").forward(req, resp); } }
[ "wlalsghek@naver.com" ]
wlalsghek@naver.com
3d2de84b7ed83c5a57a3c7505598f2e2ca49ae26
a6f412887b4053b3d0b8236a81be1f53f2953353
/src/main/java/com/evan/jc/reflect/HelloWorldImpl.java
932ff10794584415f8ba3a877ae956c26bc0bd79
[]
no_license
yataoXu/juc
c4d851ce5d2cf142c5be7d765b85608211e40012
2a36c72dcc3bd388b31b8dd70381b7f29a889f4a
refs/heads/master
2022-07-19T01:27:51.221954
2020-07-05T07:38:32
2020-07-05T07:38:32
238,196,296
0
0
null
2022-06-21T03:36:25
2020-02-04T12:04:46
Java
UTF-8
Java
false
false
275
java
package com.evan.jc.reflect; /** * @Description * @ClassName HelloWorldImpl * @Author Evan * @date 2020.07.04 02:36 */ public class HelloWorldImpl implements HelloWorld{ @Override public void sayHelloWorld() { System.out.println("HelloWorld!"); } }
[ "xuyt1992@163.com" ]
xuyt1992@163.com
efd3dc0fba2b1d56c7cf36d2898d70980cbd7eaf
8dc84558f0058d90dfc4955e905dab1b22d12c08
/third_party/android_tools/sdk/sources/android-25/java/io/Closeable.java
7f3cc8dcd0c507faba1819cb2a1b9da0b19bfe52
[ "LGPL-2.0-or-later", "GPL-1.0-or-later", "MIT", "Apache-2.0", "LicenseRef-scancode-unknown-license-reference", "BSD-3-Clause" ]
permissive
meniossin/src
42a95cc6c4a9c71d43d62bc4311224ca1fd61e03
44f73f7e76119e5ab415d4593ac66485e65d700a
refs/heads/master
2022-12-16T20:17:03.747113
2020-09-03T10:43:12
2020-09-03T10:43:12
263,710,168
1
0
BSD-3-Clause
2020-05-13T18:20:09
2020-05-13T18:20:08
null
UTF-8
Java
false
false
1,807
java
/* * Copyright (c) 2003, 2010, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it * under the terms of the GNU General Public License version 2 only, as * published by the Free Software Foundation. Oracle designates this * particular file as subject to the "Classpath" exception as provided * by Oracle in the LICENSE file that accompanied this code. * * This code is distributed in the hope that it will be useful, but WITHOUT * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License * version 2 for more details (a copy is included in the LICENSE file that * accompanied this code). * * You should have received a copy of the GNU General Public License version * 2 along with this work; if not, write to the Free Software Foundation, * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. * * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA * or visit www.oracle.com if you need additional information or have any * questions. */ package java.io; import java.io.IOException; /** * A {@code Closeable} is a source or destination of data that can be closed. * The close method is invoked to release resources that the object is * holding (such as open files). * * @since 1.5 */ public interface Closeable extends AutoCloseable { /** * Closes this stream and releases any system resources associated * with it. If the stream is already closed then invoking this * method has no effect. * * @throws IOException if an I/O error occurs */ public void close() throws IOException; }
[ "arnaud@geometry.ee" ]
arnaud@geometry.ee
92486754c9fca535ea15281a3e603b6eca38a9d0
4f8ee8a9e80a455319111210c3b82c2e1ea69360
/UdemyJUnit/src/main/java/com/utils/MyStringUtils.java
bf7e6c3371aa5f73095ae9c6dc17086bc702158b
[]
no_license
Lou4/tdd
4133a2b1cf9cc79d5dbe63e844ceace8dbdbbf63
9cf686f588678daf57a324e9fb8428230d029f88
refs/heads/master
2021-01-10T16:57:06.359835
2016-04-23T13:18:35
2016-04-23T13:18:35
55,183,690
0
0
null
null
null
null
UTF-8
Java
false
false
977
java
package com.utils; public class MyStringUtils { /* AACD -> CD, CACD -> CCD*/ public String truncateFirstTwoPos(String str) { String tmp = ""; for(int i = 0; i<str.length(); i++){ if(i < 2 && str.charAt(i) != 'A') tmp += str.charAt(i); else if(i>=2) tmp += str.charAt(i); } return tmp; } /* ABCD => false, ABAB => true*/ public Boolean areFirst2CharAndLast2TheSame(String str){ if(str.length() < 2) throw new IllegalArgumentException("String must be at least 4 chars length"); int strLen = str.length(); return str.subSequence(0, 2).equals(str.subSequence(strLen-2, strLen)); } /* OTTO => true */ public boolean isPalindrome(String string) { if(string == null) return false; string = string.toLowerCase(); for(int i = string.length()-1, j = 0; i>=j; i--, j++){ while(string.charAt(i) == ' ') i--; while(string.charAt(j) == ' ') j++; if(string.charAt(i) != string.charAt(j)) return false; } return true; } }
[ "tagliabue.luca@gmail.com" ]
tagliabue.luca@gmail.com
ea5fd27b8d5a69c7a52cfcfeb44ce56fabde6c68
6d8ffb3d8b23202bdc66e0f9d3c2dc364c2b5a17
/src/ddb/io/voxelnet/world/WorldSave.java
144d212a7a299a2c0dacbd0ed72a1d83b9a5f36b
[ "MIT" ]
permissive
DropDemBits/VoxelNet
a3db9883acea7e9dbd9e9193fe40f07d9b954a2c
1a2e2b179bfcf355a197581474ed899b78460131
refs/heads/master
2023-01-05T18:40:19.187072
2020-10-31T22:10:04
2020-10-31T22:10:04
265,440,491
0
0
MIT
2020-06-11T02:03:05
2020-05-20T03:32:31
Java
UTF-8
Java
false
false
13,883
java
package ddb.io.voxelnet.world; import ddb.io.voxelnet.util.Vec3i; import java.io.File; import java.io.FileInputStream; import java.io.FileOutputStream; import java.io.IOException; import java.nio.ByteBuffer; import java.nio.ByteOrder; import java.nio.file.Files; import java.nio.file.Paths; import java.nio.file.StandardCopyOption; /** * Class handling the world saving and loading process */ public class WorldSave { // TODO: Use ChunkManager's chunk list instead of World's loaded chunks private static final int SAVE_VERSION = 1; private static final byte[] SAVE_MAGIC = "VXNT".getBytes(); private static final int CHUNK_ENTRY_SIZE0 = 4*3 + 2 + 512 + 4096; // Save Format: // cX | cY | cZ | blockCount | blockLayers | blockLighting | blockData | blockMeta ~ tickablesCount | tickables private static final int CHUNK_FIXED_ENTRY_SIZE_V1 = Chunk.FIXED_SIZE; private static final int COLUMN_ENTRY_SIZE = 4 * 2 + 256; // The world to save / load private final World world; // The file to save / load the world in private final String saveFile; public WorldSave(World world, String saveFile) { this.world = world; this.saveFile = saveFile; } /** * Triggers a world save */ public void save() { if (canLoad()) { // Backup the old world if it can be loaded System.out.println("Backing up " + saveFile); try { Files.copy(Paths.get(saveFile), Paths.get(saveFile + ".bak"), StandardCopyOption.REPLACE_EXISTING); } catch (IOException e) { System.err.println("Unable to backup old world! Overwriting without a backup copy"); e.printStackTrace(); } } System.out.println("Saving world to " + saveFile); try (FileOutputStream stream = new FileOutputStream(saveFile)) { // All data is saved as big endian (because network order) // Format: // Header | ColumnCount | ColumnData | ChunkCount | ChunkData // Header: Defines metainfo on the file // ColumnCount (int): Number of column save entries // ColumnData: Variable length array holding the column data // ChunkCount (int): Number of chunk save entries // ChunkData: Variable length array holding the chunk data // Header: // magic | saveVersion | worldSeed // Magic (char[4]): "VXNT" in bytes // saveVersion (int): Save version (initially 0) // worldSeed (long): Seed used in world generation stream.write(SAVE_MAGIC); // Magic stream.write(serializeInt(SAVE_VERSION)); // Save Version stream.write(serializeLong(world.getWorldSeed())); // Seed /////////////////////////////////////////////////////////////////// // Write out the column entry count int columnEntries = world.chunkManager.chunkColumns.size(); stream.write(serializeInt(columnEntries)); // Column Entry Count // Iterate through all of the ChunkColumns for (ChunkColumn column : world.chunkManager.chunkColumns.values()) { // Need to save // Position (Cx, Cz) // Opaque heightmap (opaqueColumns) // Each column costs 264 bytes to store // cX, cZ: 4+4 bytes // opaqueColumns: 256 bytes // Save format // cX | cZ | opaqueColumns byte[] columnBytes = serializeColumn(column); stream.write(columnBytes); } /////////////////////////////////////////////////////////////////// // Iterate through all of the loaded chunks in the world to // determine the save count int chunkEntries = 0; for (Chunk chunk : world.chunkManager.loadedChunks.values()) { if (!chunk.isEmpty()) ++chunkEntries; } stream.write(serializeInt(chunkEntries)); // Chunk Entry Count // Iterate through all of the loaded chunks in the world again to // actually save them for (Chunk chunk : world.chunkManager.loadedChunks.values()) { // Skip empty chunks if (chunk.isEmpty()) continue; // Need to save // Position (Cx, Cy, Cz) // Block Lighting (blockLights) // Block Data (blockData) // Don't need to save but still save // Block count (blockCount, saved for compatibility) // blockLayers (blockLayers, saved for compatibility) // Don't need to save // isEmpty (implied in block count) // needsRebuild & isDirty (only used during runtime) // recentlyGenerated (only used to generate the chunk's ChunkModel) // Each chunk costs 4622 Bytes / ~4KiB to store // blockData: 4096 bytes // blockLighting: 512 bytes // chunkX, chunkY, chunkZ: 4+4+4 bytes // blockCount: 2 bytes // Save Format: // cX | cY | cZ | blockCount | blockLayers | blockLighting | blockData | blockMeta ~ tickablesCount | tickables // Always stored in big endian byte[] chunkBytes = serializeChunk(chunk); stream.write(chunkBytes); } } catch (IOException e) { e.printStackTrace(); } System.out.println("Finished saving world"); } /** * Loads a world from a file * @return True if the world was successfully loaded */ public boolean load() { System.out.println("Loading world from " + saveFile); // Build the chunk data try (FileInputStream fis = new FileInputStream(saveFile)) { // Temporary holder byte[] intBytes = new byte[4]; // Skip the header magic long skipped = fis.skip(SAVE_MAGIC.length); // Sanity check if (skipped != SAVE_MAGIC.length) { System.err.println("Error: save file is too small!"); return false; } // saveVersion (int): World's save version fis.read(intBytes); int saveVersion = deserializeInt(intBytes); // worldSeed (long): Seed used in world generation // Fetch the seed byte[] seedBytes = new byte[8]; fis.read(seedBytes); long seed = deserializeLong(seedBytes); world.setWorldSeed(seed); // Build the column data fis.read(intBytes); int columnEntries = deserializeInt(intBytes); byte[] columnData = new byte[COLUMN_ENTRY_SIZE]; for (int i = 0; i < columnEntries; i++) { fis.read(columnData); ChunkColumn column = deserializeColumn(columnData); world.chunkManager.chunkColumns.put(new Vec3i(column.columnX, 0, column.columnZ), column); } if (saveVersion == 0) loadChunksV0(fis); else loadChunksV1(fis); } catch (IOException e) { System.out.println("Failed to load a world from " + saveFile + ", generating a new one"); e.printStackTrace(); return false; } System.out.println("Successfully loaded world"); return true; } private void loadChunksV0(FileInputStream fis) throws IOException { // Temporary holder byte[] intBytes = new byte[4]; // Build the chunk data fis.read(intBytes); int chunkEntries = deserializeInt(intBytes); byte[] chunkData = new byte[CHUNK_ENTRY_SIZE0]; for (int i = 0; i < chunkEntries; i++) { fis.read(chunkData); Chunk chunk = deserializeChunkV0(chunkData); world.chunkManager.loadedChunks.put(new Vec3i(chunk.chunkX, chunk.chunkY, chunk.chunkZ), chunk); } } private void loadChunksV1(FileInputStream fis) throws IOException { byte[] intBytes = new byte[4]; // Build the chunk data fis.read(intBytes); int chunkEntries = deserializeInt(intBytes); byte[] chunkData = new byte[CHUNK_FIXED_ENTRY_SIZE_V1]; for (int i = 0; i < chunkEntries; i++) { // Read in fixed area (deserializeChunkV1 takes care of variable ended data) fis.read(chunkData); Chunk chunk = deserializeChunkV1(chunkData, fis); world.chunkManager.loadedChunks.put(new Vec3i(chunk.chunkX, chunk.chunkY, chunk.chunkZ), chunk); } } /** * Checks if the world can be loaded from a file * @return True if the world can be loaded, false for generation */ public boolean canLoad() { // Check if the file exists // TODO: Verify the magic & save version here return new File(saveFile).exists(); } /** * Serializes the chunk into a series of bytes * The byte order is always big endian * @param chunk The chunk to serialize * @return The serialized version of the chunk */ private byte[] serializeChunk(Chunk chunk) { // Save Format: // cX | cY | cZ | blockCount | blockLayers | blockLighting | blockData | blockMeta ~ tickablesCount | tickables int chunkSaveSize = CHUNK_FIXED_ENTRY_SIZE_V1 + chunk.tickables.size() * Chunk.TICKPOS_BYTES; byte[] data = new byte[chunkSaveSize]; ByteBuffer buf = ByteBuffer.allocate(data.length).order(ByteOrder.BIG_ENDIAN); // Serialize the chunk in the specified format buf.putInt(chunk.chunkX); buf.putInt(chunk.chunkY); buf.putInt(chunk.chunkZ); // Fixed area buf.putShort(chunk.getBlockCount()); for (short s : chunk.getLayerData()) buf.putShort(s); buf.put(chunk.getLightData()); buf.put(chunk.getData()); buf.put(chunk.getMetaData()); buf.putShort((short)chunk.tickables.size()); // Variable area for (int tickerPos : chunk.tickables) buf.put(serializeMedium(tickerPos)); buf.flip(); buf.get(data); buf.flip(); return data; } /** * Serializes the chunk column into a series of bytes * The byte order is always big endian * @param column The chunk colimn to serialize * @return The serialized version of the chunk column */ private byte[] serializeColumn(ChunkColumn column) { // Save format // cX | cZ | opaqueColumns byte[] data = new byte[COLUMN_ENTRY_SIZE]; ByteBuffer buf = ByteBuffer.allocate(data.length).order(ByteOrder.BIG_ENDIAN); // Serialize the chunk in the specified format buf.putInt(column.columnX); buf.putInt(column.columnZ); buf.put(column.getOpaqueColumnData()); buf.flip(); buf.get(data); buf.flip(); return data; } private byte[] serializeInt(int value) { return new byte[] { (byte)((value >> 24) & 0xFF), (byte)((value >> 16) & 0xFF), (byte)((value >> 8) & 0xFF), (byte)((value >> 0) & 0xFF), }; } // 3 byte num private byte[] serializeMedium(int value) { return new byte[] { (byte)((value >> 16) & 0xFF), (byte)((value >> 8) & 0xFF), (byte)((value >> 0) & 0xFF), }; } private byte[] serializeLong(long value) { return new byte[] { (byte)((value >> 56) & 0xFF), (byte)((value >> 48) & 0xFF), (byte)((value >> 40) & 0xFF), (byte)((value >> 32) & 0xFF), (byte)((value >> 24) & 0xFF), (byte)((value >> 16) & 0xFF), (byte)((value >> 8) & 0xFF), (byte)((value >> 0) & 0xFF), }; } private int deserializeInt(byte[] bytes) { return (Byte.toUnsignedInt(bytes[0]) << 24) | (Byte.toUnsignedInt(bytes[1]) << 16) | (Byte.toUnsignedInt(bytes[2]) << 8) | (Byte.toUnsignedInt(bytes[3]) << 0); } // 3 byte num private int deserializeMedium(byte[] bytes) { return (Byte.toUnsignedInt(bytes[1]) << 16) | (Byte.toUnsignedInt(bytes[2]) << 8) | (Byte.toUnsignedInt(bytes[3]) << 0); } private long deserializeLong(byte[] bytes) { return (Byte.toUnsignedLong(bytes[0]) << 56) | (Byte.toUnsignedLong(bytes[1]) << 48) | (Byte.toUnsignedLong(bytes[2]) << 40) | (Byte.toUnsignedLong(bytes[3]) << 32) | (Byte.toUnsignedLong(bytes[4]) << 24) | (Byte.toUnsignedLong(bytes[5]) << 16) | (Byte.toUnsignedLong(bytes[6]) << 8) | (Byte.toUnsignedLong(bytes[7]) << 0); } private Chunk deserializeChunkV0(byte[] data) { final ByteBuffer buf = ByteBuffer.allocate(CHUNK_ENTRY_SIZE0); buf.put(data); buf.flip(); // Save Format: // cX | cY | cZ | blockCount | blockLighting | blockData // Fetch the chunk position int cx = buf.getInt(); int cy = buf.getInt(); int cz = buf.getInt(); // Fetch the block count short blockCount = buf.getShort(); // TODO: Change this size when adding multiple levels of lighting byte[] blockLighting = new byte[2 * 16 * 16]; byte[] blockData = new byte[16 * 16 * 16]; buf.get(blockLighting); buf.get(blockData); Chunk chunk = new Chunk(world, cx, cy, cz); // Workaround to stop errors chunk.deserialize(blockData, blockLighting, new byte[0], new int[0]); return chunk; } private Chunk deserializeChunkV1(byte[] data, FileInputStream fis) throws IOException { ByteBuffer buf = ByteBuffer.allocate(data.length).order(ByteOrder.BIG_ENDIAN); buf.put(data); buf.flip(); // Save Format: // cX | cY | cZ | blockCount | blockLayers | blockLighting | blockData | blockMeta ~ tickablesCount | tickables // Fetch the chunk position int cx = buf.getInt(); int cy = buf.getInt(); int cz = buf.getInt(); // Fetch the block count (never used, always recalculated) short blockCount = buf.getShort(); short[] blockLayers = new short[Chunk.LAYER_DATA_SIZE]; byte[] blockLighting = new byte[Chunk.LIGHT_DATA_SIZE]; byte[] blockData = new byte[Chunk.BLOCK_DATA_SIZE]; byte[] blockMeta = new byte[Chunk.META_DATA_SIZE]; for(int i = 0; i < blockLayers.length; i++) blockLayers[i] = buf.getShort(); buf.get(blockLighting); buf.get(blockData); buf.get(blockMeta); // Fetch the tickables count int tickerCount = buf.getShort(); int[] tickables = new int[tickerCount]; byte[] tickPos = new byte[Chunk.TICKPOS_BYTES]; for (int i = 0; i < tickerCount; i++) { // Read from the file fis.read(tickPos); tickables[i] = deserializeMedium(tickPos); } Chunk chunk = new Chunk(world, cx, cy, cz); chunk.deserialize(blockData, blockLighting, blockMeta, tickables); return chunk; } private ChunkColumn deserializeColumn(byte[] data) { final ByteBuffer buf = ByteBuffer.allocate(COLUMN_ENTRY_SIZE); buf.put(data); buf.flip(); // Save format // cX | cZ | opaqueColumns // Fetch the column int cx = buf.getInt(); int cz = buf.getInt(); // Fetch the column data byte[] opaqueColumns = new byte[16 * 16]; buf.get(opaqueColumns); return new ChunkColumn(cx, cz, opaqueColumns); } }
[ "ring0hicc@gmail.com" ]
ring0hicc@gmail.com
f1a23bc175b7497f32dd94f7631d4dc7b636b9c4
730f5055192ef0acaf7f1b873f0c6a7f6665eb46
/backend/src/test/java/pl/net/divo/CalculatorTest.java
71be222200141fa2020d7cefdf7394adf029b974
[]
no_license
divo1/currency_calc
6638a8e389508d3b40b0e93b88e9a8afb891a933
7ae6f82c023054bd1958064a2ba3896c71e68560
refs/heads/master
2023-04-28T00:58:26.737082
2021-05-02T17:53:38
2021-05-02T17:53:38
103,134,722
0
1
null
2021-05-02T17:53:38
2017-09-11T12:44:52
Java
UTF-8
Java
false
false
807
java
package pl.net.divo; import org.junit.BeforeClass; import org.junit.Test; import pl.net.divo.helper.Calculator; import pl.net.divo.helper.CurrencyEnum; import pl.net.divo.helper.SimpleCalculator; import pl.net.divo.model.Currency; import static org.junit.Assert.*; public class CalculatorTest { private static Calculator calculator = new SimpleCalculator(); @BeforeClass public static void prepareCalculator() { calculator.setSourceCurrency(Currency.fromEnum(CurrencyEnum.EUR)); calculator.setTargetCurrency(Currency.fromEnum(CurrencyEnum.PLN)) ; } @Test public void testCorrectCalculation() { double eurCurrency = CurrencyEnum.EUR.getValue(); assertEquals(eurCurrency, calculator.getConverter(), 0.001); } }
[ "divo@divo.net.pl" ]
divo@divo.net.pl
defbcec0c36e4a2efc3ae22c46437183bb7611f6
7ca641fde25e40bc0930c2dd7db6c5098449ad47
/src/main/java/com/gs/shiro/MyRealm.java
a5d1e44148b1d66488a2abed5bdf62c71c226828
[]
no_license
ZongjieWu/Shiro
c53c856df4017a1094d35a0f5404c083d17b5add
c5297273c7fa4817b09e6b97c6eba0f8f07551b1
refs/heads/master
2021-07-19T16:38:25.881542
2017-10-28T14:43:27
2017-10-28T14:43:27
108,656,938
0
0
null
null
null
null
UTF-8
Java
false
false
1,354
java
package com.gs.shiro; import org.apache.shiro.authc.AuthenticationException; import org.apache.shiro.authc.AuthenticationInfo; import org.apache.shiro.authc.AuthenticationToken; import org.apache.shiro.authc.SimpleAuthenticationInfo; import org.apache.shiro.realm.AuthenticatingRealm; /** * Created by Administrator on 2017/9/27. */ public class MyRealm extends AuthenticatingRealm { /** * * @param authenticationToken 包含用户名及密码的令牌对象,是由Shiro传递过来的参数 * @return * @throws AuthenticationException */ protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken authenticationToken) throws AuthenticationException { String username = (String) authenticationToken.getPrincipal(); String password = String.valueOf((char[]) authenticationToken.getCredentials()); // userService.getByNamePwd(username, password), 如果返回了对象,则说明数据库里有此用户,则返回SimpleAuthenticationInfo对象 // 返回的null,说明数据库中没有此用户,则返回null,认证失败 if ("tom".equals(username) && "123456".equals(password)) { return new SimpleAuthenticationInfo(authenticationToken.getPrincipal(), authenticationToken.getCredentials(), "myReam"); } return null; } }
[ "2012293155@qq.com" ]
2012293155@qq.com
b76535aa94d32210b9a39cd051bd816c1d338985
dac3f07f6702ad78562ac598b3a303f614607ac0
/Magic8Weather/app/src/main/java/com/example/elaina/magic8weather/FetchForecast5.java
7dadffadfbb117caadaeec4a6ce3919a2c55f842
[]
no_license
elainamhill/CS4720-FinalProject
1adbc86d5cbf59d368ec6fec62fc38cce7263a16
377b0b92ca4a490df574f18079dbac5f12d911a9
refs/heads/master
2021-01-11T20:13:34.795694
2017-01-16T03:59:33
2017-01-16T03:59:33
79,069,873
0
0
null
null
null
null
UTF-8
Java
false
false
1,486
java
package com.example.elaina.magic8weather; import android.content.Context; import java.io.BufferedReader; import java.io.InputStreamReader; import java.net.HttpURLConnection; import java.net.URL; import org.json.JSONObject; import android.content.Context; import android.util.Log; public class FetchForecast5 { private static final String OPEN_WEATHER_MAP_API = "http://api.openweathermap.org/data/2.5/forecast?q=%s&units=imperial"; public static JSONObject getJSON(Context context, String city){ try { URL url = new URL(String.format(OPEN_WEATHER_MAP_API, city)); HttpURLConnection connection = (HttpURLConnection)url.openConnection(); connection.addRequestProperty("x-api-key", context.getString(R.string.open_weather_maps_app_id)); BufferedReader reader = new BufferedReader( new InputStreamReader(connection.getInputStream())); StringBuffer json = new StringBuffer(1024); String tmp=""; while((tmp=reader.readLine())!=null) json.append(tmp).append("\n"); reader.close(); JSONObject data = new JSONObject(json.toString()); // This value will be 404 if bad request if(data.getInt("cod") != 200){ return null; } return data; }catch(Exception e){ return null; } } }
[ "elainamhill@gmail.com" ]
elainamhill@gmail.com
cceae7d352a6a5bfbcaaa5c64c90726b987fd372
f3baabdf981b2d65f5adad28c78a65ac6c6a08be
/src/javaapplication1/JavaApplication1.java
3cd129fa34ddbbdb3d0aae03e12ba10583eee8e4
[]
no_license
vasilevvasko/Test
ececec483a044cfc4ab845417cd7fa2a6a1b976c
1e0df8641d2a36a2f866c23fd7da541d33178232
refs/heads/master
2020-05-19T14:21:51.607848
2019-05-05T17:03:58
2019-05-05T17:03:58
185,059,350
1
0
null
null
null
null
UTF-8
Java
false
false
1,457
java
// NOTE: // Code will be optimized and comented in the following days // Run with input 50 Lube :D package javaapplication1; import java.util.Scanner; public class JavaApplication1 { public static void main(String[] args) { Scanner scanner = new Scanner( System.in ); int size; size = scanner.nextInt(); int arrX = size + 1; int arrY = size * 10; int right; int points[] = {0, size * 2,size * 5, size * 7}; char[][] arr = new char[arrX][arrY]; for (int i = 0; i < arrX; i++) { for (int j = 0; j < arrY; j++) { arr[i][j] = '-'; } } for (int k = 0; k < 4; k++) { right = points[k]; for (int i = size; i >= 0; i--) { arr[i][right] = '*'; // 3 0, 2 1, 1 2, 0 3 for (int j = right; j < right + size; j++) { arr[i][j] = '*'; } right++; } right = points[k] + size; for (int i = 0; i <= size; i++) { arr[i][right] = '*'; for (int j = right; j < right + size; j++) { arr[i][j] = '*'; } right++; } } for (int i = 0; i < arrX; i++) { for (int j = 0; j < arrY; j++) { System.out.print(arr[i][j]); } System.out.println(); } } }
[ "noreply@github.com" ]
noreply@github.com
7510b67965d4b1ce755e737fe657a1ec2bfcfeb4
354903b332d31b69de4978cf52821ae906624c5e
/Day29_HashMap/src/Task5_2xComparator.java
ba08c73b99bfacaaa566f00288d2b4f5e9192542
[]
no_license
saravanakumarjsk/Java-training
bc95450c3c7c19fe3d9381660c3bda1655608f31
c1d28d9bd65c8bd01c9929c8120f787b6196a85d
refs/heads/master
2021-01-26T11:23:19.850876
2020-04-22T09:57:38
2020-04-22T09:57:38
243,420,835
1
0
null
null
null
null
UTF-8
Java
false
false
2,614
java
import java.util.*; import java.io.*; import java.time.LocalDate; import java.time.Period; import java.time.format.DateTimeFormatter; import java.time.format.DateTimeFormatterBuilder; import java.time.temporal.TemporalAccessor; class TicketBooking{ private String show; private LocalDate time; private String num; private double price; public TicketBooking() { } public TicketBooking(String show, LocalDate time, String num, double price) { this.show = show; this.time = time; this.num = num; this.price = price; } public String getShow() { return show; } public void setShow(String show) { this.show = show; } public LocalDate getTime() { return time; } public void setTime(LocalDate time) { this.time = time; } public String getNum() { return num; } public void setNum(String num) { this.num = num; } public double getPrice() { return price; } public void setPrice(double price) { this.price = price; } } class PriceAndBookingTimeComparator implements Comparator<TicketBooking>{ @Override public int compare(TicketBooking o1, TicketBooking o2) { if(o1.getPrice() > o2.getPrice()) { return 1; } else if(o1.getPrice() < o2.getPrice()) { return -1; } else { return o1.getTime().compareTo(o2.getTime()); } } } public class Task5_2xComparator { public static void main(String[] args) throws IOException { InputStreamReader ir = new InputStreamReader(System.in); BufferedReader br = new BufferedReader(ir); Scanner input = new Scanner(System.in); System.out.println("Enter the number of TicketBookings "); int n = input.nextInt(); List<TicketBooking> lt2 = new ArrayList<TicketBooking>(); DateTimeFormatter df = DateTimeFormatter.ofPattern("dd-MM-yyyy"); for(int i=0; i<n; i++) { // System.out.println("Enter the details of Booking "+ (i+1)); String s[] = br.readLine().split(","); lt2.add(new TicketBooking(s[0], LocalDate.parse(s[1], df), s[2], Double.parseDouble(s[3]))); } // System.out.println(); Collections.sort(lt2, new PriceAndBookingTimeComparator()); Iterator<TicketBooking> it = lt2.iterator(); System.out.format("%-20s%-20s%-20s%-20s\n","Name","Date", "Number", "Price"); while(it.hasNext()) { TicketBooking s = it.next(); System.out.format("%-20s%-20s%-20s%-20s\n",s.getShow(), s.getTime(), s.getNum(),s.getPrice()); } } } /* magic show,01-01-2018,10,200.0 cricket match,02-01-2018,25,200.0 seminar,02-01-2018,150,2500.0 */
[ "noreply@github.com" ]
noreply@github.com
bf0751e43ef832515faa73e58349f507943da6cd
179833039547de7a9bcb8e46f9301d225a6aa881
/ideaSpingbootTest/src/main/java/com/ideatest/demo/pojo/JsonResult.java
2b07c2ca7c1ffd013c8d5ed081b8f499f470947c
[]
no_license
ziran-m/airplane-front
786d0fcab51f491f6d1d90794a73f84ddcd2cb09
2bc046392b07628657b3286b8d54b7229aab3893
refs/heads/master
2022-11-11T00:36:34.371371
2020-07-01T04:00:16
2020-07-01T04:00:16
264,859,460
1
0
null
2020-05-18T07:26:52
2020-05-18T07:20:40
Vue
UTF-8
Java
false
false
1,785
java
package com.ideatest.demo.pojo; import com.ideatest.demo.exception.ErrorMsgEnum; /** * 统一返回对象 * @author ziran * @date 2020/6/11-10:40 */ public class JsonResult<T> { private T data; private String code; private String msg; /** * 若没有数据返回,默认状态码为0,提示信息为:操作成功! */ public JsonResult() { this.code = "0"; this.msg = "操作成功!"; } /** * 若没有数据返回,可以人为指定状态码和提示信息 * @param code * @param msg */ public JsonResult(String code, String msg) { this.code = code; this.msg = msg; } /** * 有数据返回时,状态码为0,默认提示信息为:操作成功! * @param data */ public JsonResult(T data) { this.data = data; this.code = "0"; this.msg = "操作成功!"; } /** * 有数据返回,状态码为0,人为指定提示信息 * @param data * @param msg */ public JsonResult(T data, String msg) { this.data = data; this.code = "0"; this.msg = msg; } /** * 使用自定义异常作为参数传递状态码和提示信息 * @param msgEnum */ public JsonResult(ErrorMsgEnum msgEnum) { this.code = msgEnum.code(); this.msg = msgEnum.msg(); } public T getData() { return data; } public void setData(T data) { this.data = data; } public String getCode() { return code; } public void setCode(String code) { this.code = code; } public String getMsg() { return msg; } public void setMsg(String msg) { this.msg = msg; } }
[ "1749172174@qq.com" ]
1749172174@qq.com
49e3cb62d6e778c45b51ee3199472e9643bfc08e
210d1cbc49296fe66052003cdc8fd53727280f12
/src/main/java/br/com/springboot/repositories/PedidoRepository.java
6c959730fcaca34cc3d254ead883093d1592a7df
[]
no_license
fabianosf/cursomc
3293006d79e998f23e97e818202a82347c0ba05e
017cb3317f2616cc6036644b290f1239992d1a05
refs/heads/master
2020-04-08T17:54:59.095630
2018-11-30T01:56:23
2018-11-30T01:56:23
159,586,357
0
0
null
null
null
null
UTF-8
Java
false
false
285
java
package br.com.springboot.repositories; import org.springframework.data.jpa.repository.JpaRepository; import org.springframework.stereotype.Repository; import br.com.springboot.domain.Pedido; @Repository public interface PedidoRepository extends JpaRepository<Pedido, Integer> { }
[ "fabiano.freitas@gmail.com" ]
fabiano.freitas@gmail.com
14c539166a3872411ebd2b5f318947d7a38d5a5a
e291a8508409f75c3bf8b319697fc61aaab2225e
/app/src/main/java/com/example/org/cafe_app/OrderVO.java
8ceaf3ed6019c81b2076eb526a1bc280f1c86a4e
[]
no_license
chaewon97/Cafe_App
642ec60e377a4df40afceb43c0a4185879d2a5d0
3049037242c2b561635b4c6141e9c9b83ab52810
refs/heads/master
2022-11-04T06:54:09.348637
2020-06-21T17:58:41
2020-06-21T17:58:41
269,954,297
0
0
null
null
null
null
UTF-8
Java
false
false
1,027
java
package com.example.org.cafe_app; import android.view.View; public class OrderVO { public String beverage_name; public String beverage_price; public String beverage_id; public String order_id; public String user_id; public View.OnClickListener onClickListener; public OrderVO(String name, String price, String id, String order_id, String user_id) { this.beverage_name = name; this.beverage_price = price; this.beverage_id = id; this.order_id = order_id; this.user_id = user_id; } public String getBeverage_name() {return beverage_name;} public String getBeverage_price() {return beverage_price;} public String getBeverage_id() {return beverage_id;} public String getOrder_id() {return order_id;} public String getUser_id() {return user_id;} public View.OnClickListener getOnClickListener() {return onClickListener;} public void setOnClickListener(View.OnClickListener listener){ onClickListener = listener; } }
[ "conpulake@sju.ac.kr" ]
conpulake@sju.ac.kr
03816544b7ce49debb14715bdadd8d14456f47bc
3bf3441513864a7187891a199485e1619ae8a201
/sdk/java/src/main/java/com/pulumi/linode/inputs/GetLinodeObjectStorageBucketArgs.java
d076b1c9ff4b08c8ec88e6b98c323635eceecdfb
[ "Apache-2.0", "MPL-2.0", "BSD-3-Clause" ]
permissive
pulumi/pulumi-linode
d52af7efdbfd2137cd6acbf9a9982fd17ada7cd4
ceeb1a0eed10e15e3a033b12f8da2dcca7b99681
refs/heads/master
2023-08-16T14:58:49.611491
2023-08-11T05:54:49
2023-08-11T05:54:49
172,126,915
26
6
Apache-2.0
2023-09-13T15:29:34
2019-02-22T19:57:52
Java
UTF-8
Java
false
false
2,324
java
// *** WARNING: this file was generated by pulumi-java-gen. *** // *** Do not edit by hand unless you're certain you know what you are doing! *** package com.pulumi.linode.inputs; import com.pulumi.core.Output; import com.pulumi.core.annotations.Import; import java.lang.String; import java.util.Objects; public final class GetLinodeObjectStorageBucketArgs extends com.pulumi.resources.InvokeArgs { public static final GetLinodeObjectStorageBucketArgs Empty = new GetLinodeObjectStorageBucketArgs(); @Import(name="cluster", required=true) private Output<String> cluster; public Output<String> cluster() { return this.cluster; } @Import(name="label", required=true) private Output<String> label; public Output<String> label() { return this.label; } private GetLinodeObjectStorageBucketArgs() {} private GetLinodeObjectStorageBucketArgs(GetLinodeObjectStorageBucketArgs $) { this.cluster = $.cluster; this.label = $.label; } public static Builder builder() { return new Builder(); } public static Builder builder(GetLinodeObjectStorageBucketArgs defaults) { return new Builder(defaults); } public static final class Builder { private GetLinodeObjectStorageBucketArgs $; public Builder() { $ = new GetLinodeObjectStorageBucketArgs(); } public Builder(GetLinodeObjectStorageBucketArgs defaults) { $ = new GetLinodeObjectStorageBucketArgs(Objects.requireNonNull(defaults)); } public Builder cluster(Output<String> cluster) { $.cluster = cluster; return this; } public Builder cluster(String cluster) { return cluster(Output.of(cluster)); } public Builder label(Output<String> label) { $.label = label; return this; } public Builder label(String label) { return label(Output.of(label)); } public GetLinodeObjectStorageBucketArgs build() { $.cluster = Objects.requireNonNull($.cluster, "expected parameter 'cluster' to be non-null"); $.label = Objects.requireNonNull($.label, "expected parameter 'label' to be non-null"); return $; } } }
[ "noreply@github.com" ]
noreply@github.com
da510c33aad755f920506d8f5043205adbbae254
5a1ba790e3ccbec04dbd77674dab3acd458bb745
/src/main/java/com/verdantartifice/thaumicwonders/common/network/packets/PacketLocalizedMessage.java
d90d6808934853e85522e0ed8189ee8533ad864e
[ "MIT" ]
permissive
daedalus4096/ThaumicWonders
b04bcea014b3d70c028a52da670a903315f4f9d5
251829dee76d72368d0ed0af1f2104121b781e63
refs/heads/master
2020-04-23T19:39:32.198037
2019-09-17T03:15:37
2019-09-17T03:15:37
171,411,944
6
14
MIT
2019-08-24T22:41:42
2019-02-19T05:37:38
Java
UTF-8
Java
false
false
1,981
java
package com.verdantartifice.thaumicwonders.common.network.packets; import io.netty.buffer.ByteBuf; import net.minecraft.client.Minecraft; import net.minecraft.client.resources.I18n; import net.minecraft.entity.player.EntityPlayer; import net.minecraft.util.text.TextComponentString; import net.minecraft.util.text.TextFormatting; import net.minecraftforge.fml.common.FMLCommonHandler; import net.minecraftforge.fml.common.network.ByteBufUtils; import net.minecraftforge.fml.common.network.simpleimpl.IMessage; import net.minecraftforge.fml.common.network.simpleimpl.IMessageHandler; import net.minecraftforge.fml.common.network.simpleimpl.MessageContext; import net.minecraftforge.fml.relauncher.Side; import net.minecraftforge.fml.relauncher.SideOnly; public class PacketLocalizedMessage implements IMessage { protected String translationKey; public PacketLocalizedMessage() { this.translationKey = ""; } public PacketLocalizedMessage(String key) { this.translationKey = key; } @Override public void fromBytes(ByteBuf buf) { this.translationKey = ByteBufUtils.readUTF8String(buf); } @Override public void toBytes(ByteBuf buf) { ByteBufUtils.writeUTF8String(buf, this.translationKey); } public static class Handler implements IMessageHandler<PacketLocalizedMessage, IMessage> { @Override public IMessage onMessage(PacketLocalizedMessage message, MessageContext ctx) { FMLCommonHandler.instance().getWorldThread(ctx.netHandler).addScheduledTask(() -> handle(message, ctx)); return null; } @SideOnly(Side.CLIENT) private void handle(PacketLocalizedMessage message, MessageContext ctx) { EntityPlayer entityPlayer = Minecraft.getMinecraft().player; entityPlayer.sendStatusMessage(new TextComponentString(TextFormatting.DARK_PURPLE + I18n.format(message.translationKey)), true); } } }
[ "michael.a.bunting@gmail.com" ]
michael.a.bunting@gmail.com
ff65198f2e67e4dc404b3f22dcf5d68324b167b3
5481a09fdc7a89e51ac66381888956ed2e0d8534
/app/src/main/java/com/example/dell/lift/MedGroupAdapter.java
89f391e477aca3ede0d73e504c6cce847ba0397c
[]
no_license
MKorashi/LiftApplication
aeb87a82bd2eec0560c6dc99a752fab324b43a06
340174af77256496144a0f865b4964bd2f7393ee
refs/heads/master
2020-03-23T16:43:55.083175
2018-07-21T15:39:19
2018-07-21T15:39:19
141,825,336
0
0
null
null
null
null
UTF-8
Java
false
false
1,108
java
package com.example.dell.lift; import android.support.v7.widget.RecyclerView; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import com.example.dell.lift.Entities.Medication_Group; import java.util.ArrayList; public class MedGroupAdapter extends RecyclerView.Adapter<MedGroupViewHolder> { private ArrayList<Medication_Group> list; public MedGroupAdapter(ArrayList<Medication_Group> Data) { list = Data; } @Override public MedGroupViewHolder onCreateViewHolder(ViewGroup parent, int viewType) { // create a new view View view = LayoutInflater.from(parent.getContext()) .inflate(R.layout.medgroup_card , parent, false); MedGroupViewHolder holder = new MedGroupViewHolder(view); return holder; } @Override public void onBindViewHolder(final MedGroupViewHolder holder, int position) { holder.titleTextView.setText(list.get(position).getName()); } @Override public int getItemCount() { return list.size(); } }
[ "mariam.korashi@gmail.com" ]
mariam.korashi@gmail.com
7a78f434810aefefae6d5548cf8fa646d252ee7d
e8a87e7910af9bae06f6b40740fd5a0c0ea27c81
/barcode-reader/src/main/java/com/notbytes/barcode_reader/BarcodeReaderFragment.java
75510716a5dea220e715b2b0d77e9eb43b453fb4
[]
no_license
FroHenK/BillsBills
359c7c13caba0ac3ef61f6b38ef10fd83dd27d33
23f2b938b8b6fa3684802b61c823660d5cb3b6d2
refs/heads/master
2020-05-25T02:42:39.772531
2019-05-28T17:30:45
2019-05-28T17:30:45
187,583,825
0
0
null
null
null
null
UTF-8
Java
false
false
25,751
java
package com.notbytes.barcode_reader; import android.Manifest; import android.annotation.SuppressLint; import android.app.AlertDialog; import android.app.Dialog; import android.content.*; import android.content.pm.PackageManager; import android.content.res.AssetFileDescriptor; import android.content.res.TypedArray; import android.hardware.Camera; import android.media.MediaPlayer; import android.net.Uri; import android.os.Bundle; import android.provider.Settings; import android.util.AttributeSet; import android.util.Log; import android.util.SparseArray; import android.view.*; import android.widget.Toast; import androidx.annotation.NonNull; import androidx.annotation.Nullable; import androidx.core.app.ActivityCompat; import androidx.fragment.app.Fragment; import com.google.android.gms.common.ConnectionResult; import com.google.android.gms.common.GoogleApiAvailability; import com.google.android.gms.common.api.CommonStatusCodes; import com.google.android.gms.vision.MultiProcessor; import com.google.android.gms.vision.barcode.Barcode; import com.google.android.gms.vision.barcode.BarcodeDetector; import com.notbytes.barcode_reader.camera.CameraSource; import com.notbytes.barcode_reader.camera.CameraSourcePreview; import com.notbytes.barcode_reader.camera.GraphicOverlay; import java.io.IOException; import java.util.List; public class BarcodeReaderFragment extends Fragment implements View.OnTouchListener, BarcodeGraphicTracker.BarcodeGraphicTrackerListener { protected static final String TAG = BarcodeReaderFragment.class.getSimpleName(); protected static final String KEY_AUTO_FOCUS = "key_auto_focus"; protected static final String KEY_USE_FLASH = "key_use_flash"; private static final String KEY_SCAN_OVERLAY_VISIBILITY = "key_scan_overlay_visibility"; // intent request code to handle updating play services if needed. private static final int RC_HANDLE_GMS = 9001; // constants used to pass extra data in the intent protected boolean autoFocus = false; protected boolean useFlash = false; private String beepSoundFile; public static final String BarcodeObject = "Barcode"; private boolean isPaused = false; private CameraSource mCameraSource; private CameraSourcePreview mPreview; private GraphicOverlay<BarcodeGraphic> mGraphicOverlay; // helper objects for detecting taps and pinches. private ScaleGestureDetector scaleGestureDetector; private GestureDetector gestureDetector; private BarcodeReaderListener mListener; private SharedPreferences permissionStatus; private static final int PERMISSION_CALLBACK_CONSTANT = 101; private static final int REQUEST_PERMISSION_SETTING = 102; private boolean sentToSettings = false; private ScannerOverlay mScanOverlay; private int scanOverlayVisibility; public BarcodeReaderFragment() { // Required empty public constructor } public static BarcodeReaderFragment newInstance(boolean autoFocus, boolean useFlash) { Bundle args = new Bundle(); args.putBoolean(KEY_AUTO_FOCUS, autoFocus); args.putBoolean(KEY_USE_FLASH, useFlash); BarcodeReaderFragment fragment = new BarcodeReaderFragment(); fragment.setArguments(args); return fragment; } public static BarcodeReaderFragment newInstance(boolean autoFocus, boolean useFlash, int scanOverlayVisibleStatus) { Bundle args = new Bundle(); args.putBoolean(KEY_AUTO_FOCUS, autoFocus); args.putBoolean(KEY_USE_FLASH, useFlash); args.putInt(KEY_SCAN_OVERLAY_VISIBILITY, scanOverlayVisibleStatus); BarcodeReaderFragment fragment = new BarcodeReaderFragment(); fragment.setArguments(args); return fragment; } /** * Use this listener if you want more callbacks * * @param barcodeReaderListener */ public void setListener(BarcodeReaderListener barcodeReaderListener) { mListener = barcodeReaderListener; } public void setBeepSoundFile(String fileName) { beepSoundFile = fileName; } public void pauseScanning() { isPaused = true; } public void resumeScanning() { isPaused = false; } @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); Bundle arguments = this.getArguments(); if (arguments != null) { this.autoFocus = arguments.getBoolean(KEY_AUTO_FOCUS, false); this.useFlash = arguments.getBoolean(KEY_USE_FLASH, false); this.scanOverlayVisibility = arguments.getInt(KEY_SCAN_OVERLAY_VISIBILITY, View.VISIBLE); } } @Override public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { // Inflate the layout for this fragment View view = inflater.inflate(R.layout.fragment_barcode_reader, container, false); permissionStatus = getActivity().getSharedPreferences("permissionStatus", getActivity().MODE_PRIVATE); mPreview = view.findViewById(R.id.preview); mGraphicOverlay = view.findViewById(R.id.graphicOverlay); mScanOverlay = view.findViewById(R.id.scan_overlay); mScanOverlay.setVisibility(scanOverlayVisibility); gestureDetector = new GestureDetector(getActivity(), new CaptureGestureListener()); scaleGestureDetector = new ScaleGestureDetector(getActivity(), new ScaleListener()); view.setOnTouchListener(this); return view; } @Override public void onInflate(Context context, AttributeSet attrs, Bundle savedInstanceState) { super.onInflate(context, attrs, savedInstanceState); TypedArray a = context.obtainStyledAttributes(attrs, R.styleable.BarcodeReaderFragment); autoFocus = a.getBoolean(R.styleable.BarcodeReaderFragment_auto_focus, true); useFlash = a.getBoolean(R.styleable.BarcodeReaderFragment_use_flash, false); a.recycle(); } @Override public void onAttach(Context context) { super.onAttach(context); if (context instanceof BarcodeReaderListener) { mListener = (BarcodeReaderListener) context; } } @Override public void onActivityCreated(@Nullable Bundle savedInstanceState) { super.onActivityCreated(savedInstanceState); permissionStatus = getActivity().getSharedPreferences("permissionStatus", getActivity().MODE_PRIVATE); if (ActivityCompat.checkSelfPermission(getActivity(), Manifest.permission.CAMERA) != PackageManager.PERMISSION_GRANTED) { if (ActivityCompat.shouldShowRequestPermissionRationale(getActivity(), Manifest.permission.CAMERA)) { //Show Information about why you need the permission AlertDialog.Builder builder = new AlertDialog.Builder(getActivity()); builder.setTitle(getString(R.string.grant_permission)); builder.setMessage(getString(R.string.permission_camera)); builder.setPositiveButton(R.string.grant, new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) { dialog.cancel(); requestPermissions(new String[]{Manifest.permission.CAMERA}, PERMISSION_CALLBACK_CONSTANT); } }); builder.setNegativeButton(android.R.string.cancel, new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) { dialog.cancel(); mListener.onCameraPermissionDenied(); } }); builder.show(); } else if (permissionStatus.getBoolean(Manifest.permission.CAMERA, false)) { AlertDialog.Builder builder = new AlertDialog.Builder(getActivity()); builder.setTitle(getString(R.string.grant_permission)); builder.setMessage(getString(R.string.permission_camera)); builder.setPositiveButton(R.string.grant, new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) { dialog.cancel(); sentToSettings = true; Intent intent = new Intent(Settings.ACTION_APPLICATION_DETAILS_SETTINGS); Uri uri = Uri.fromParts("package", getActivity().getPackageName(), null); intent.setData(uri); startActivityForResult(intent, REQUEST_PERMISSION_SETTING); } }); builder.setNegativeButton(R.string.cancel, new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) { dialog.cancel(); mListener.onCameraPermissionDenied(); } }); builder.show(); } else { //just request the permission requestPermissions(new String[]{Manifest.permission.CAMERA}, PERMISSION_CALLBACK_CONSTANT); } SharedPreferences.Editor editor = permissionStatus.edit(); editor.putBoolean(Manifest.permission.CAMERA, true); editor.apply(); } else { //You already have the permission, just go ahead. proceedAfterPermission(); } } private void proceedAfterPermission() { createCameraSource(autoFocus, useFlash); } /** * Creates and starts the camera. Note that this uses a higher resolution in comparison * to other detection examples to enable the barcode detector to detect small barcodes * at long distances. * <p> * Suppressing InlinedApi since there is a check that the minimum version is met before using * the constant. */ @SuppressLint("InlinedApi") private void createCameraSource(final boolean autoFocus, final boolean useFlash) { Log.e(TAG, "createCameraSource:"); Context context = getActivity(); // A barcode detector is created to track barcodes. An associated multi-processor instance // is set to receive the barcode detection results, track the barcodes, and maintain // graphics for each barcode on screen. The factory is used by the multi-processor to // create a separate tracker instance for each barcode. final BarcodeDetector barcodeDetector = new BarcodeDetector.Builder(context).build(); BarcodeTrackerFactory barcodeFactory = new BarcodeTrackerFactory(mGraphicOverlay, this); barcodeDetector.setProcessor( new MultiProcessor.Builder<>(barcodeFactory).build()); if (!barcodeDetector.isOperational()) { // Note: The first time that an app using the barcode or face API is installed on a // device, GMS will download a native libraries to the device in order to do detection. // Usually this completes before the app is run for the first time. But if that // download has not yet ready, then the above call will not detect any barcodes // and/or faces. // // isOperational() can be used to check if the required native libraries are currently // available. The detectors will automatically become operational once the library // downloads complete on device. Log.w(TAG, "Detector dependencies are not yet available."); // Check for low storage. If there is low storage, the native library will not be // downloaded, so detection will not become operational. IntentFilter lowstorageFilter = new IntentFilter(Intent.ACTION_DEVICE_STORAGE_LOW); boolean hasLowStorage = getActivity().registerReceiver(null, lowstorageFilter) != null; if (hasLowStorage) { Toast.makeText(getActivity(), R.string.low_storage_error, Toast.LENGTH_LONG).show(); Log.w(TAG, getString(R.string.low_storage_error)); } } // Creates and starts the camera. Note that this uses a higher resolution in comparison // to other detection examples to enable the barcode detector to detect small barcodes // at long distances. CameraSource.Builder builder = new CameraSource.Builder(getActivity(), barcodeDetector) .setFacing(CameraSource.CAMERA_FACING_BACK) .setRequestedPreviewSize(1600, 1024) .setRequestedFps(1.0f); // make sure that auto focus is an available option builder = builder.setFocusMode( autoFocus ? Camera.Parameters.FOCUS_MODE_CONTINUOUS_VIDEO : null); mCameraSource = builder .setFlashMode(useFlash ? Camera.Parameters.FLASH_MODE_TORCH : null) .build(); } /** * Trigger flash torch on and off, perhaps using a compound button. */ public void setUseFlash(boolean use){ useFlash = use; mCameraSource.setFlashMode(useFlash ? Camera.Parameters.FLASH_MODE_TORCH : Camera.Parameters.FLASH_MODE_OFF); } /** * Trigger auto focus mode, perhaps using a compound button. */ public void setAutoFocus(boolean continuous){ autoFocus = continuous; mCameraSource.setFocusMode(autoFocus ? Camera.Parameters.FOCUS_MODE_CONTINUOUS_VIDEO : Camera.Parameters.FOCUS_MODE_AUTO); } /** * Returns true if device supports flash. */ public boolean deviceSupportsFlash(){ if (getActivity().getPackageManager()==null) return false; return getActivity().getPackageManager().hasSystemFeature( PackageManager.FEATURE_CAMERA_FLASH); } /** * Restarts the camera. */ @Override public void onResume() { super.onResume(); startCameraSource(); if (sentToSettings) { if (ActivityCompat.checkSelfPermission(getActivity(), Manifest.permission.CAMERA) == PackageManager.PERMISSION_GRANTED) { //Got Permission proceedAfterPermission(); } else { mListener.onCameraPermissionDenied(); } } } /** * Stops the camera. */ @Override public void onPause() { super.onPause(); if (mPreview != null) { mPreview.stop(); } } /** * Releases the resources associated with the camera source, the associated detectors, and the * rest of the processing pipeline. */ @Override public void onDestroy() { super.onDestroy(); if (mPreview != null) { mPreview.release(); } } @Override public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) { super.onRequestPermissionsResult(requestCode, permissions, grantResults); if (requestCode == PERMISSION_CALLBACK_CONSTANT) { //check if all permissions are granted boolean allgranted = false; for (int i = 0; i < grantResults.length; i++) { if (grantResults[i] == PackageManager.PERMISSION_GRANTED) { allgranted = true; } else { allgranted = false; break; } } if (allgranted) { proceedAfterPermission(); } else if (ActivityCompat.shouldShowRequestPermissionRationale(getActivity(), Manifest.permission.CAMERA)) { AlertDialog.Builder builder = new AlertDialog.Builder(getActivity()); builder.setTitle(getString(R.string.grant_permission)); builder.setMessage(getString(R.string.permission_camera)); builder.setPositiveButton(R.string.grant, new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) { dialog.cancel(); requestPermissions(new String[]{Manifest.permission.CAMERA}, PERMISSION_CALLBACK_CONSTANT); } }); builder.setNegativeButton(R.string.cancel, new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) { dialog.cancel(); mListener.onCameraPermissionDenied(); } }); builder.show(); } else { mListener.onCameraPermissionDenied(); } } } @Override public void onActivityResult(int requestCode, int resultCode, Intent data) { super.onActivityResult(requestCode, resultCode, data); if (requestCode == REQUEST_PERMISSION_SETTING) { if (ActivityCompat.checkSelfPermission(getActivity(), Manifest.permission.CAMERA) == PackageManager.PERMISSION_GRANTED) { //Got Permission proceedAfterPermission(); } } } /** * Starts or restarts the camera source, if it exists. If the camera source doesn't exist yet * (e.g., because onResume was called before the camera source was created), this will be called * again when the camera source is created. */ private void startCameraSource() throws SecurityException { // check that the device has play services available. int code = GoogleApiAvailability.getInstance().isGooglePlayServicesAvailable( getActivity()); if (code != ConnectionResult.SUCCESS) { Dialog dlg = GoogleApiAvailability.getInstance().getErrorDialog(getActivity(), code, RC_HANDLE_GMS); dlg.show(); } if (mCameraSource != null) { try { mPreview.start(mCameraSource, mGraphicOverlay); } catch (IOException e) { Log.e(TAG, "Unable to start camera source.", e); mCameraSource.release(); mCameraSource = null; } } } /** * onTap returns the tapped barcode result to the calling Activity. * * @param rawX - the raw position of the tap * @param rawY - the raw position of the tap. * @return true if the activity is ending. */ private boolean onTap(float rawX, float rawY) { // Find tap point in preview frame coordinates. int[] location = new int[2]; mGraphicOverlay.getLocationOnScreen(location); float x = (rawX - location[0]) / mGraphicOverlay.getWidthScaleFactor(); float y = (rawY - location[1]) / mGraphicOverlay.getHeightScaleFactor(); // Find the barcode whose center is closest to the tapped point. Barcode best = null; float bestDistance = Float.MAX_VALUE; for (BarcodeGraphic graphic : mGraphicOverlay.getGraphics()) { Barcode barcode = graphic.getBarcode(); if (barcode.getBoundingBox().contains((int) x, (int) y)) { // Exact hit, no need to keep looking. best = barcode; break; } float dx = x - barcode.getBoundingBox().centerX(); float dy = y - barcode.getBoundingBox().centerY(); float distance = (dx * dx) + (dy * dy); // actually squared distance if (distance < bestDistance) { best = barcode; bestDistance = distance; } } if (best != null) { Intent data = new Intent(); data.putExtra(BarcodeObject, best); // TODO - pass the scanned value getActivity().setResult(CommonStatusCodes.SUCCESS, data); getActivity().finish(); return true; } return false; } @Override public boolean onTouch(View view, MotionEvent motionEvent) { boolean b = scaleGestureDetector.onTouchEvent(motionEvent); boolean c = gestureDetector.onTouchEvent(motionEvent); return b || c || view.onTouchEvent(motionEvent); } @Override public void onScanned(final Barcode barcode) { if (mListener != null && !isPaused) { if (getActivity() == null) { return; } getActivity().runOnUiThread(new Runnable() { @Override public void run() { mListener.onScanned(barcode); } }); } } @Override public void onScannedMultiple(final List<Barcode> barcodes) { if (mListener != null && !isPaused) { if (getActivity() == null) { return; } getActivity().runOnUiThread(new Runnable() { @Override public void run() { mListener.onScannedMultiple(barcodes); } }); } } @Override public void onBitmapScanned(final SparseArray<Barcode> sparseArray) { if (mListener != null) { if (getActivity() == null) { return; } getActivity().runOnUiThread(new Runnable() { @Override public void run() { mListener.onBitmapScanned(sparseArray); } }); } } @Override public void onScanError(final String errorMessage) { if (mListener != null) { if (getActivity() == null) { return; } getActivity().runOnUiThread(new Runnable() { @Override public void run() { mListener.onScanError(errorMessage); } }); } } private class CaptureGestureListener extends GestureDetector.SimpleOnGestureListener { @Override public boolean onSingleTapConfirmed(MotionEvent e) { return onTap(e.getRawX(), e.getRawY()) || super.onSingleTapConfirmed(e); } } private class ScaleListener implements ScaleGestureDetector.OnScaleGestureListener { /** * Responds to scaling events for a gesture in progress. * Reported by pointer motion. * * @param detector The detector reporting the event - use this to * retrieve extended info about event state. * @return Whether or not the detector should consider this event * as handled. If an event was not handled, the detector * will continue to accumulate movement until an event is * handled. This can be useful if an application, for example, * only wants to update scaling factors if the change is * greater than 0.01. */ @Override public boolean onScale(ScaleGestureDetector detector) { return false; } /** * Responds to the beginning of a scaling gesture. Reported by * new pointers going down. * * @param detector The detector reporting the event - use this to * retrieve extended info about event state. * @return Whether or not the detector should continue recognizing * this gesture. For example, if a gesture is beginning * with a focal point outside of a region where it makes * sense, onScaleBegin() may return false to ignore the * rest of the gesture. */ @Override public boolean onScaleBegin(ScaleGestureDetector detector) { return true; } /** * Responds to the end of a scale gesture. Reported by existing * pointers going up. * <p/> * Once a scale has ended, {@link ScaleGestureDetector#getFocusX()} * and {@link ScaleGestureDetector#getFocusY()} will return focal point * of the pointers remaining on the screen. * * @param detector The detector reporting the event - use this to * retrieve extended info about event state. */ @Override public void onScaleEnd(ScaleGestureDetector detector) { mCameraSource.doZoom(detector.getScaleFactor()); } } public void playBeep() { MediaPlayer m = new MediaPlayer(); try { if (m.isPlaying()) { m.stop(); m.release(); m = new MediaPlayer(); } AssetFileDescriptor descriptor = getActivity().getAssets().openFd(beepSoundFile != null ? beepSoundFile : "beep.mp3"); m.setDataSource(descriptor.getFileDescriptor(), descriptor.getStartOffset(), descriptor.getLength()); descriptor.close(); m.prepare(); m.setVolume(1f, 1f); m.start(); } catch (Exception e) { e.printStackTrace(); } } public interface BarcodeReaderListener { void onScanned(Barcode barcode); void onScannedMultiple(List<Barcode> barcodes); void onBitmapScanned(SparseArray<Barcode> sparseArray); void onScanError(String errorMessage); void onCameraPermissionDenied(); } }
[ "frohenk@gmail.com" ]
frohenk@gmail.com
eefd3c36527880608ddc0510306176e0ca230be6
c4bda1f63f71cc1db3e08d3a553364c51fbe4570
/generationEMSI/Technicien.java
e8b81ce180b06833efcb46239aedcfcd1d595e6d
[]
no_license
Emsists/TeamWork
971d79342e7a7ba2f3443fabd4c0b7b000384d50
aa6216f332e9c4857d8c84b76f1bba8e106a9961
refs/heads/master
2021-07-17T08:43:49.832795
2019-12-08T18:17:02
2019-12-08T18:17:02
211,571,117
0
0
null
2020-09-09T19:23:37
2019-09-28T22:55:41
Mercury
UTF-8
Java
false
false
437
java
/*********************************************************************** * Module: Technicien.java * Author: HP Omen * Purpose: Defines the Class Technicien ***********************************************************************/ import java.util.*; /** @pdOid 87a44105-0b33-4f93-a0f0-49163b841406 */ public class Technicien extends Personne { /** @pdOid 28a88167-b80e-4743-a187-df9386c45060 */ private String matricule; }
[ "naoufal.stage" ]
naoufal.stage
c87040c524d035c0b9c43af3bcc5bc4f350f8914
7ac5ad0421d3b41ba4287054572b8a56896a1cfe
/images/ObstacleBrick.java
470c9aebd80d4a6790cc8093fba947b063a79525
[]
no_license
dhivashini/DisneylandGame
6170145586d7ab14afd78c5c989364ff74c8cc02
e8f550619ac2851c4d8f21a2bd97c159cfba4253
refs/heads/master
2021-01-10T12:01:33.886697
2016-01-07T20:38:44
2016-01-07T20:38:44
49,228,989
1
0
null
null
null
null
UTF-8
Java
false
false
926
java
import greenfoot.*; // (World, Actor, GreenfootImage, Greenfoot and MouseInfo) /** * Write a description of class ObstacleBrick here. * * @author (your name) * @version (a version number or a date) */ public class ObstacleBrick extends Obstacle { /** * Act - do whatever the ObstacleBrick wants to do. This method is called whenever * the 'Act' or 'Run' button gets pressed in the environment. */ int x; ObstacleBrick(){ x=2; } public void updateSpeed(int speed) { this.speed = -speed; } public void act() { setLocationForObstacle(); removeObstacle(); } /*private void setLocationForObstacle(){ // setLocation(getX()-this.x,getY()); setLocation(getX()-this.speed,getY()); } private void removeObstacle(){ if(getX()==0) { getWorld().removeObject(this); } }*/ }
[ "dhivashini.jaganathan@sjsu.edu" ]
dhivashini.jaganathan@sjsu.edu
1500d6dd52ef3dafdf8ab1799bbe30bc35e96f6b
49398c8ed0de758d0d1df672fd4fcda461cbaa05
/bai_2_spring_controller/thuc_hanh/ung_dung_quan_ly_khach_hang/cms/src/main/java/cg/wbd/grandemonstration/controller/CustomerController.java
e746d18d6b84b3738a904284e6bcf8ada8dd9435
[]
no_license
HaiNguyen3112/C0420G1-NguyenVanHai-Module4
90d3a08c3f03ff9ac837754e38ceefd79fa18beb
8c0035ebbe68b62364d1284ff425caddeea4ed53
refs/heads/master
2022-12-26T02:12:00.572824
2020-09-30T08:41:16
2020-09-30T08:41:16
288,602,157
0
0
null
null
null
null
UTF-8
Java
false
false
2,004
java
package cg.wbd.grandemonstration.controller; import cg.wbd.grandemonstration.model.Customer; import cg.wbd.grandemonstration.service.CustomerService; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Controller; import org.springframework.web.bind.annotation.*; import org.springframework.web.servlet.ModelAndView; import java.util.List; @Controller @RequestMapping("/customers") public class CustomerController { @Autowired private CustomerService customerService; @GetMapping public ModelAndView showList() { ModelAndView modelAndView = new ModelAndView("customers/list"); List<Customer> customers = customerService.findAll(); modelAndView.addObject("customers", customers); return modelAndView; } // @GetMapping("/info") // public ModelAndView showInfo(@RequestParam long id){ // ModelAndView modelAndView = new ModelAndView("customers/info"); // Customer customer = customerService.findOne(id); // modelAndView.addObject("customer",customer); // return modelAndView; // } @GetMapping("/{id}") public ModelAndView showInformation(@PathVariable Long id) { ModelAndView modelAndView = new ModelAndView("customers/info"); Customer customer = customerService.findOne(id); modelAndView.addObject("customer", customer); return modelAndView; } @PostMapping public String updateCustomer(@RequestParam Long id, @RequestParam String name, @RequestParam String email, @RequestParam String address){ Customer customer = new Customer(id,name,email,address); customerService.save(customer); return "redirect:/customers"; } // @PostMapping // public String updateCustomer(Customer customer) { // customerService.save(customer); // return "redirect:/customers"; // } }
[ "nguyenhai311294@gmail.com" ]
nguyenhai311294@gmail.com
a657c054522053116323761698183e10994a4281
c7ffc31773b0e4a7ed01dad1303b38a310eef09f
/src/test/java/com/ql/util/express/test/ImportTest.java
c3044bb08b1e0b1f0994f3e0ec3e32e92ca8fa86
[]
no_license
wangzhiheng/QLExpress
04da19bd248b7c66f3aa4d49a5e53e2cec8400b9
f0540b683379f47ebedbbce1e769d3d8ce6fca5b
refs/heads/master
2020-04-06T03:45:22.937247
2016-05-20T09:11:44
2016-05-20T09:11:44
61,088,702
0
0
null
null
null
null
GB18030
Java
false
false
810
java
package com.ql.util.express.test; import org.junit.Assert; import org.junit.Test; import com.ql.util.express.DefaultContext; import com.ql.util.express.ExpressRunner; public class ImportTest { @Test public void testImport() throws Exception{ String express ="import java.math.*;" + "import com.ql.util.express.test.BeanExample;" + "abc = new BeanExample(\"张三\").unionName(\"李四\") ;" + "return new BigInteger(\"1000\");"; ExpressRunner runner = new ExpressRunner(false,true); DefaultContext<String, Object> context = new DefaultContext<String, Object>(); Object r = runner.execute(express,context, null, false,true); Assert.assertTrue("import 实现错误",r.toString().equals("1000")); System.out.println(r); System.out.println(context); } }
[ "qhlhl2010@gmail.com" ]
qhlhl2010@gmail.com
bf70650daee8b1203e203f591d4f139015bfa207
e3d092247f7f019fce4580806e43103bca069c7a
/src/main/java/com/my/project/T03Synchronized.java
adb07802ef2d6f9f42c2342826f2852686891269
[ "Apache-2.0" ]
permissive
yddgit/java-concurrent
4cc0765eb9e71a37ffadd10fefa6ef70b8a5041b
3434e9c72e8d9277949f97fffd170dc5387fdeb3
refs/heads/master
2021-06-25T19:02:34.138222
2020-06-11T01:58:06
2020-06-11T01:58:06
94,219,882
0
0
Apache-2.0
2020-10-12T23:55:35
2017-06-13T14:08:08
Java
UTF-8
Java
false
false
472
java
package com.my.project; /** * synchronized关键字 * 对某个对象加锁 * @author yang * */ public class T03Synchronized { private int count = 10; //当整个方法的代码都需要锁定时,可以直接在方法声明中加上synchronized关键字 public synchronized void m() { //等同于在方法的代码执行时要synchronized(this) count --; System.out.println(Thread.currentThread().getName() + " count = " + count); } }
[ "642444906@qq.com" ]
642444906@qq.com
11e48e7e3653ec6b407656ae9531908e82edcb1d
71a3d4639e4920b784e404d97279130ec7a03651
/app/build/generated/not_namespaced_r_class_sources/debug/processDebugResources/r/android/support/slidingpanelayout/R.java
dbdd97703a783ba2654c1605c6a8f537cb957726
[]
no_license
Inefable-Jazb/Inefable-APP
2ffe327227a4ef916cea43ffdda7c43ebfe3d1c3
925cc7ae1400f75e3b0c3826e0502460defbef79
refs/heads/master
2020-04-09T04:03:34.770903
2018-12-16T21:30:33
2018-12-16T21:30:33
160,008,675
0
0
null
2018-12-04T02:10:00
2018-12-02T03:06:44
Java
UTF-8
Java
false
false
10,464
java
/* AUTO-GENERATED FILE. DO NOT MODIFY. * * This class was automatically generated by the * gradle plugin from the resource data it found. It * should not be modified by hand. */ package android.support.slidingpanelayout; public final class R { private R() {} public static final class attr { private attr() {} public static final int alpha = 0x7f03002c; public static final int font = 0x7f0300e7; public static final int fontProviderAuthority = 0x7f0300e9; public static final int fontProviderCerts = 0x7f0300ea; public static final int fontProviderFetchStrategy = 0x7f0300eb; public static final int fontProviderFetchTimeout = 0x7f0300ec; public static final int fontProviderPackage = 0x7f0300ed; public static final int fontProviderQuery = 0x7f0300ee; public static final int fontStyle = 0x7f0300ef; public static final int fontVariationSettings = 0x7f0300f0; public static final int fontWeight = 0x7f0300f1; public static final int ttcIndex = 0x7f030221; } public static final class color { private color() {} public static final int notification_action_color_filter = 0x7f05007d; public static final int notification_icon_bg_color = 0x7f05007e; public static final int ripple_material_light = 0x7f05008d; public static final int secondary_text_default_material_light = 0x7f05008f; } public static final class dimen { private dimen() {} public static final int compat_button_inset_horizontal_material = 0x7f06005d; public static final int compat_button_inset_vertical_material = 0x7f06005e; public static final int compat_button_padding_horizontal_material = 0x7f06005f; public static final int compat_button_padding_vertical_material = 0x7f060060; public static final int compat_control_corner_material = 0x7f060061; public static final int compat_notification_large_icon_max_height = 0x7f060062; public static final int compat_notification_large_icon_max_width = 0x7f060063; public static final int notification_action_icon_size = 0x7f0600d0; public static final int notification_action_text_size = 0x7f0600d1; public static final int notification_big_circle_margin = 0x7f0600d2; public static final int notification_content_margin_start = 0x7f0600d3; public static final int notification_large_icon_height = 0x7f0600d4; public static final int notification_large_icon_width = 0x7f0600d5; public static final int notification_main_column_padding_top = 0x7f0600d6; public static final int notification_media_narrow_margin = 0x7f0600d7; public static final int notification_right_icon_size = 0x7f0600d8; public static final int notification_right_side_padding_top = 0x7f0600d9; public static final int notification_small_icon_background_padding = 0x7f0600da; public static final int notification_small_icon_size_as_large = 0x7f0600db; public static final int notification_subtext_size = 0x7f0600dc; public static final int notification_top_pad = 0x7f0600dd; public static final int notification_top_pad_large_text = 0x7f0600de; } public static final class drawable { private drawable() {} public static final int notification_action_background = 0x7f07008f; public static final int notification_bg = 0x7f070090; public static final int notification_bg_low = 0x7f070091; public static final int notification_bg_low_normal = 0x7f070092; public static final int notification_bg_low_pressed = 0x7f070093; public static final int notification_bg_normal = 0x7f070094; public static final int notification_bg_normal_pressed = 0x7f070095; public static final int notification_icon_background = 0x7f070096; public static final int notification_template_icon_bg = 0x7f070097; public static final int notification_template_icon_low_bg = 0x7f070098; public static final int notification_tile_bg = 0x7f070099; public static final int notify_panel_notification_icon_bg = 0x7f07009a; } public static final class id { private id() {} public static final int action_container = 0x7f08000e; public static final int action_divider = 0x7f080010; public static final int action_image = 0x7f080011; public static final int action_text = 0x7f080017; public static final int actions = 0x7f080018; public static final int async = 0x7f080021; public static final int blocking = 0x7f080025; public static final int chronometer = 0x7f080037; public static final int forever = 0x7f080061; public static final int icon = 0x7f08006a; public static final int icon_group = 0x7f08006b; public static final int info = 0x7f080070; public static final int italic = 0x7f080072; public static final int line1 = 0x7f08007c; public static final int line3 = 0x7f08007d; public static final int normal = 0x7f080092; public static final int notification_background = 0x7f080093; public static final int notification_main_column = 0x7f080094; public static final int notification_main_column_container = 0x7f080095; public static final int right_icon = 0x7f0800a8; public static final int right_side = 0x7f0800a9; public static final int tag_transition_group = 0x7f0800de; public static final int tag_unhandled_key_event_manager = 0x7f0800df; public static final int tag_unhandled_key_listeners = 0x7f0800e0; public static final int text = 0x7f0800e2; public static final int text2 = 0x7f0800e3; public static final int time = 0x7f080103; public static final int title = 0x7f080104; } public static final class integer { private integer() {} public static final int status_bar_notification_info_maxnum = 0x7f09000f; } public static final class layout { private layout() {} public static final int notification_action = 0x7f0b003b; public static final int notification_action_tombstone = 0x7f0b003c; public static final int notification_template_custom_big = 0x7f0b0043; public static final int notification_template_icon_group = 0x7f0b0044; public static final int notification_template_part_chronometer = 0x7f0b0048; public static final int notification_template_part_time = 0x7f0b0049; } public static final class string { private string() {} public static final int status_bar_notification_info_overflow = 0x7f0e004c; } public static final class style { private style() {} public static final int TextAppearance_Compat_Notification = 0x7f0f011e; public static final int TextAppearance_Compat_Notification_Info = 0x7f0f011f; public static final int TextAppearance_Compat_Notification_Line2 = 0x7f0f0121; public static final int TextAppearance_Compat_Notification_Time = 0x7f0f0124; public static final int TextAppearance_Compat_Notification_Title = 0x7f0f0126; public static final int Widget_Compat_NotificationActionContainer = 0x7f0f01d1; public static final int Widget_Compat_NotificationActionText = 0x7f0f01d2; } public static final class styleable { private styleable() {} public static final int[] ColorStateListItem = { 0x10101a5, 0x101031f, 0x7f03002c }; public static final int ColorStateListItem_android_color = 0; public static final int ColorStateListItem_android_alpha = 1; public static final int ColorStateListItem_alpha = 2; public static final int[] FontFamily = { 0x7f0300e9, 0x7f0300ea, 0x7f0300eb, 0x7f0300ec, 0x7f0300ed, 0x7f0300ee }; public static final int FontFamily_fontProviderAuthority = 0; public static final int FontFamily_fontProviderCerts = 1; public static final int FontFamily_fontProviderFetchStrategy = 2; public static final int FontFamily_fontProviderFetchTimeout = 3; public static final int FontFamily_fontProviderPackage = 4; public static final int FontFamily_fontProviderQuery = 5; public static final int[] FontFamilyFont = { 0x1010532, 0x1010533, 0x101053f, 0x101056f, 0x1010570, 0x7f0300e7, 0x7f0300ef, 0x7f0300f0, 0x7f0300f1, 0x7f030221 }; public static final int FontFamilyFont_android_font = 0; public static final int FontFamilyFont_android_fontWeight = 1; public static final int FontFamilyFont_android_fontStyle = 2; public static final int FontFamilyFont_android_ttcIndex = 3; public static final int FontFamilyFont_android_fontVariationSettings = 4; public static final int FontFamilyFont_font = 5; public static final int FontFamilyFont_fontStyle = 6; public static final int FontFamilyFont_fontVariationSettings = 7; public static final int FontFamilyFont_fontWeight = 8; public static final int FontFamilyFont_ttcIndex = 9; public static final int[] GradientColor = { 0x101019d, 0x101019e, 0x10101a1, 0x10101a2, 0x10101a3, 0x10101a4, 0x1010201, 0x101020b, 0x1010510, 0x1010511, 0x1010512, 0x1010513 }; public static final int GradientColor_android_startColor = 0; public static final int GradientColor_android_endColor = 1; public static final int GradientColor_android_type = 2; public static final int GradientColor_android_centerX = 3; public static final int GradientColor_android_centerY = 4; public static final int GradientColor_android_gradientRadius = 5; public static final int GradientColor_android_tileMode = 6; public static final int GradientColor_android_centerColor = 7; public static final int GradientColor_android_startX = 8; public static final int GradientColor_android_startY = 9; public static final int GradientColor_android_endX = 10; public static final int GradientColor_android_endY = 11; public static final int[] GradientColorItem = { 0x10101a5, 0x1010514 }; public static final int GradientColorItem_android_color = 0; public static final int GradientColorItem_android_offset = 1; } }
[ "johan@inefable.cl" ]
johan@inefable.cl
ffc1aecd3712a35f543ba7968f607b2834f8fc45
5a2699fc58ea9b23a6204ac3ab27d3bcb64ccc78
/HackerrankSort/InsertionSort1.java
59fc6af02038f9632d6a324cd9d65cd221cc0020
[]
no_license
e11438/Hackerrank-problems
f4666487c252b7bee56e9b0094025f95074fbecc
35f8fd49be54c38110b36eef1a13747db318db3b
refs/heads/master
2021-01-01T19:51:55.412877
2015-06-12T18:02:06
2015-06-12T18:02:06
37,248,987
0
0
null
null
null
null
UTF-8
Java
false
false
994
java
import java.util.Scanner; public class InsertionSort1 { public static void insertIntoSorted(int[] ar) { int len =ar.length; boolean t=true; // Fill up this function int min=Integer.MAX_VALUE; for(int i=len-1;i>0;i--){ if(ar[i]<min){ min=ar[i]; } if(min<ar[i-1]){ ar[i]=ar[i-1]; printArray(ar); } else{ t=false; ar[i]=min; printArray(ar); break; } } if(t){ ar[0]=min; printArray(ar); } } /* Tail starts here */ public static void main(String[] args) { Scanner in = new Scanner(System.in); int s = in.nextInt(); int[] ar = new int[s]; for(int i=0;i<s;i++){ ar[i]=in.nextInt(); } insertIntoSorted(ar); } private static void printArray(int[] ar) { for(int n: ar){ System.out.print(n+" "); } System.out.println(""); } }
[ "isankalpa7@gmail.com" ]
isankalpa7@gmail.com
56833a1cad644234be7bbca7b8df8596bca02ecc
4ab2794c9530f3a6884519c74b43df979b9c3f65
/controltheland/src/test/java/com/btxtech/game/services/utg/impl/TestUserGuidanceServiceImpl.java
60d605c46708de18912149bf20919247600366f4
[]
no_license
kurdoxxx/controltheland
759b825b9e19c95a27f8b3345f1f620a6f8f308d
22fb17ff19446a9ed7c91b5a8e6d091488bf475e
refs/heads/master
2021-01-19T06:58:47.541857
2014-07-25T22:05:37
2014-07-25T22:05:37
37,353,316
0
0
null
null
null
null
UTF-8
Java
false
false
26,577
java
package com.btxtech.game.services.utg.impl; import com.btxtech.game.jsre.client.common.Index; import com.btxtech.game.jsre.client.common.info.InvalidLevelStateException; import com.btxtech.game.jsre.client.common.info.RealGameInfo; import com.btxtech.game.jsre.client.common.info.SimulationInfo; import com.btxtech.game.jsre.client.dialogs.quest.QuestOverview; import com.btxtech.game.jsre.common.gameengine.itemType.BaseItemType; import com.btxtech.game.jsre.common.gameengine.syncObjects.SyncBaseItem; import com.btxtech.game.jsre.common.tutorial.GameFlow; import com.btxtech.game.services.AbstractServiceTest; import com.btxtech.game.services.item.itemType.DbBaseItemType; import com.btxtech.game.services.planet.PlanetSystemService; import com.btxtech.game.services.planet.db.DbPlanet; import com.btxtech.game.services.tutorial.DbTutorialConfig; import com.btxtech.game.services.tutorial.TutorialService; import com.btxtech.game.services.user.UserService; import com.btxtech.game.services.user.UserState; import com.btxtech.game.services.utg.DbLevel; import com.btxtech.game.services.utg.DbLevelTask; import com.btxtech.game.services.utg.UserGuidanceService; import com.btxtech.game.services.utg.XpService; import org.easymock.EasyMock; import org.junit.Assert; import org.junit.Test; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.test.annotation.DirtiesContext; import java.util.ArrayList; import java.util.Collection; import java.util.List; import java.util.Locale; /** * User: beat * Date: 23.01.2012 * Time: 11:37:41 */ public class TestUserGuidanceServiceImpl extends AbstractServiceTest { @Autowired private UserGuidanceService userGuidanceService; @Autowired private UserService userService; @Autowired private XpService xpService; @Autowired private PlanetSystemService planetSystemService; @Autowired private TutorialService tutorialService; @Test @DirtiesContext public void noBaseAllowed() throws Exception { configureMultiplePlanetsAndLevels(); beginHttpSession(); beginHttpRequestAndOpenSessionInViewFilter(); try { getMovableService().getRealGameInfo(START_UID_1, null); Assert.fail("InvalidLevelStateException expected"); } catch (InvalidLevelStateException invalidLevelStateException) { // Expected } endHttpRequestAndOpenSessionInViewFilter(); endHttpSession(); } @Test @DirtiesContext public void levelUp() throws Exception { configureMultiplePlanetsAndLevels(); beginHttpSession(); // Verify first level beginHttpRequestAndOpenSessionInViewFilter(); Assert.assertFalse(userGuidanceService.isStartRealGame()); int levelTaskId = userGuidanceService.getDefaultLevelTaskId(); Assert.assertEquals(TEST_LEVEL_1_SIMULATED_ID, levelTaskId); SimulationInfo simulationInfo = getMovableService().getSimulationGameInfo(levelTaskId); Assert.assertNotNull(simulationInfo); Assert.assertEquals(TEST_LEVEL_1_SIMULATED, userGuidanceService.getDbLevelCms().getNumber()); endHttpRequestAndOpenSessionInViewFilter(); // Level Up beginHttpRequestAndOpenSessionInViewFilter(); GameFlow gameFlow = userGuidanceService.onTutorialFinished(levelTaskId); Assert.assertEquals(GameFlow.Type.START_REAL_GAME, gameFlow.getType()); endHttpRequestAndOpenSessionInViewFilter(); // Verify second level beginHttpRequestAndOpenSessionInViewFilter(); Assert.assertEquals(TEST_LEVEL_2_REAL, userGuidanceService.getDbLevelCms().getNumber()); Assert.assertTrue(userGuidanceService.isStartRealGame()); createBase(new Index(1000,1000)); RealGameInfo realGameInfo = getMovableService().getRealGameInfo(START_UID_1, null); Assert.assertNotNull(realGameInfo); Assert.assertEquals(1, planetSystemService.getServerPlanetServices().getBaseService().getBases().size()); List<DbLevelTask> levelTask = new ArrayList<>(userGuidanceService.getDbLevelCms().getLevelTaskCrud().readDbChildren()); Assert.assertEquals(2, levelTask.size()); endHttpRequestAndOpenSessionInViewFilter(); // Level Up beginHttpRequestAndOpenSessionInViewFilter(); userGuidanceService.activateQuest(TEST_LEVEL_TASK_2_2_REAL_ID, Locale.ENGLISH); sendBuildCommand(getFirstSynItemId(TEST_START_BUILDER_ITEM_ID), new Index(200, 200), TEST_FACTORY_ITEM_ID); waitForActionServiceDone(); sendFactoryCommand(getFirstSynItemId(TEST_FACTORY_ITEM_ID), TEST_HARVESTER_ITEM_ID); waitForActionServiceDone(); userGuidanceService.activateQuest(TEST_LEVEL_TASK_1_2_REAL_ID, Locale.ENGLISH); sendCollectCommand(getFirstSynItemId(TEST_HARVESTER_ITEM_ID), getFirstSynItemId(TEST_RESOURCE_ITEM_ID)); waitForActionServiceDone(); endHttpRequestAndOpenSessionInViewFilter(); // Verify third level beginHttpRequestAndOpenSessionInViewFilter(); Assert.assertEquals(TEST_LEVEL_3_REAL, userGuidanceService.getDbLevelCms().getNumber()); Assert.assertTrue(userGuidanceService.isStartRealGame()); endHttpRequestAndOpenSessionInViewFilter(); endHttpSession(); } @Test @DirtiesContext public void levelUpUserOfflinePassivelyAttacksOtherUnit() throws Exception { BaseItemType mockBaseItemType = EasyMock.createStrictMock(BaseItemType.class); EasyMock.expect(mockBaseItemType.getXpOnKilling()).andReturn(1000); SyncBaseItem mockSyncBaseItem = EasyMock.createStrictMock(SyncBaseItem.class); EasyMock.expect(mockSyncBaseItem.getBaseItemType()).andReturn(mockBaseItemType); EasyMock.replay(mockBaseItemType, mockSyncBaseItem); configureMultiplePlanetsAndLevels(); beginHttpSession(); beginHttpRequestAndOpenSessionInViewFilter(); createAndLoginUser("U1"); UserState userState = userService.getUserState(); userGuidanceService.promote(userState, TEST_LEVEL_2_REAL_ID); sendBuildCommand(getFirstSynItemId(TEST_START_BUILDER_ITEM_ID), new Index(2000, 2000), TEST_FACTORY_ITEM_ID); waitForActionServiceDone(); sendFactoryCommand(getFirstSynItemId(TEST_FACTORY_ITEM_ID), TEST_ATTACK_ITEM_ID); waitForActionServiceDone(); sendMoveCommand(getFirstSynItemId(TEST_ATTACK_ITEM_ID), new Index(500, 500)); waitForActionServiceDone(); endHttpRequestAndOpenSessionInViewFilter(); endHttpSession(); // Condition: 220 XP Assert.assertEquals(TEST_LEVEL_2_REAL_ID, userState.getDbLevelId()); xpService.onItemKilled(userState.getBase().getSimpleBase(), mockSyncBaseItem, planetSystemService.getServerPlanetServices(TEST_PLANET_1_ID)); Thread.sleep(100); // TODO failed on 14.11.2012, 23.11.2012, 14.12.2012, 03.09.2013 Assert.assertEquals(TEST_LEVEL_3_REAL_ID, userState.getDbLevelId()); } @Test @DirtiesContext public void levelUpUserOfflineReward() throws Exception { configureMultiplePlanetsAndLevels(); beginHttpSession(); beginHttpRequestAndOpenSessionInViewFilter(); createAndLoginUser("U1"); UserState userState = userService.getUserState(); userGuidanceService.promote(userState, TEST_LEVEL_2_REAL_ID); sendBuildCommand(getFirstSynItemId(TEST_START_BUILDER_ITEM_ID), new Index(2000, 2000), TEST_FACTORY_ITEM_ID); waitForActionServiceDone(); sendFactoryCommand(getFirstSynItemId(TEST_FACTORY_ITEM_ID), TEST_ATTACK_ITEM_ID); waitForActionServiceDone(); sendMoveCommand(getFirstSynItemId(TEST_ATTACK_ITEM_ID), new Index(500, 500)); waitForActionServiceDone(); endHttpRequestAndOpenSessionInViewFilter(); endHttpSession(); // Condition: 220 XP Assert.assertEquals(TEST_LEVEL_2_REAL_ID, userState.getDbLevelId()); xpService.onReward(userState, 200); Assert.assertEquals(TEST_LEVEL_2_REAL_ID, userState.getDbLevelId()); xpService.onReward(userState, 19); Assert.assertEquals(TEST_LEVEL_2_REAL_ID, userState.getDbLevelId()); xpService.onReward(userState, 1); Assert.assertEquals(TEST_LEVEL_3_REAL_ID, userState.getDbLevelId()); } @Test @DirtiesContext public void gameFlow() throws Exception { beginHttpSession(); beginHttpRequestAndOpenSessionInViewFilter(); // Setup DbLevel dbSimLevel1 = userGuidanceService.getDbLevelCrud().createDbChild(); dbSimLevel1.setXp(2); dbSimLevel1.setNumber(1); DbLevelTask dbSimLevelTask11 = dbSimLevel1.getLevelTaskCrud().createDbChild(); dbSimLevelTask11.setDbTutorialConfig(createTutorial1()); dbSimLevelTask11.setXp(1); DbLevelTask dbSimLevelTask12 = dbSimLevel1.getLevelTaskCrud().createDbChild(); dbSimLevelTask12.setDbTutorialConfig(createTutorial1()); dbSimLevelTask12.setXp(1); userGuidanceService.getDbLevelCrud().updateDbChild(dbSimLevel1); DbLevel dbSimLevel2 = userGuidanceService.getDbLevelCrud().createDbChild(); dbSimLevel2.setXp(1); dbSimLevel2.setNumber(2); DbLevelTask dbSimLevelTask2 = dbSimLevel2.getLevelTaskCrud().createDbChild(); dbSimLevelTask2.setDbTutorialConfig(createTutorial1()); dbSimLevelTask2.setXp(1); userGuidanceService.getDbLevelCrud().updateDbChild(dbSimLevel2); DbPlanet dbPlanet = planetSystemService.getDbPlanetCrud().createDbChild(); DbBaseItemType dbBaseItemType = createSimpleBuilding(); dbPlanet.setStartItemType(dbBaseItemType); planetSystemService.getDbPlanetCrud().updateDbChild(dbPlanet); planetSystemService.activate(); DbLevel realGameLevel = userGuidanceService.getDbLevelCrud().createDbChild(); realGameLevel.setNumber(3); realGameLevel.setXp(Integer.MAX_VALUE); DbLevelTask dbLevelTask = realGameLevel.getLevelTaskCrud().createDbChild(); dbLevelTask.setDbTutorialConfig(createTutorial1()); realGameLevel.setDbPlanet(dbPlanet); userGuidanceService.getDbLevelCrud().updateDbChild(realGameLevel); userGuidanceService.activateLevels(); endHttpRequestAndOpenSessionInViewFilter(); endHttpSession(); // Verify beginHttpSession(); beginHttpRequestAndOpenSessionInViewFilter(); Assert.assertFalse(userGuidanceService.isStartRealGame()); Assert.assertEquals((int) dbSimLevelTask11.getId(), userGuidanceService.getDefaultLevelTaskId()); endHttpRequestAndOpenSessionInViewFilter(); endHttpSession(); beginHttpSession(); beginHttpRequestAndOpenSessionInViewFilter(); Assert.assertFalse(userGuidanceService.isStartRealGame()); Assert.assertEquals((int) dbSimLevelTask11.getId(), userGuidanceService.getDefaultLevelTaskId()); GameFlow gameFlow = userGuidanceService.onTutorialFinished(dbSimLevelTask11.getId()); Assert.assertEquals(GameFlow.Type.START_NEXT_LEVEL_TASK_TUTORIAL, gameFlow.getType()); Assert.assertEquals((int) dbSimLevelTask12.getId(), gameFlow.getNextTutorialLevelTaskId()); Assert.assertFalse(userGuidanceService.isStartRealGame()); Assert.assertEquals((int) dbSimLevelTask12.getId(), userGuidanceService.getDefaultLevelTaskId()); gameFlow = userGuidanceService.onTutorialFinished(dbSimLevelTask12.getId()); Assert.assertEquals(GameFlow.Type.START_NEXT_LEVEL_TASK_TUTORIAL, gameFlow.getType()); Assert.assertEquals((int) dbSimLevelTask2.getId(), gameFlow.getNextTutorialLevelTaskId()); Assert.assertFalse(userGuidanceService.isStartRealGame()); Assert.assertEquals((int) dbSimLevelTask2.getId(), userGuidanceService.getDefaultLevelTaskId()); gameFlow = userGuidanceService.onTutorialFinished(dbSimLevelTask2.getId()); Assert.assertEquals(GameFlow.Type.START_REAL_GAME, gameFlow.getType()); Assert.assertTrue(userGuidanceService.isStartRealGame()); gameFlow = userGuidanceService.onTutorialFinished(dbLevelTask.getId()); Assert.assertEquals(GameFlow.Type.START_REAL_GAME, gameFlow.getType()); Assert.assertTrue(userGuidanceService.isStartRealGame()); endHttpRequestAndOpenSessionInViewFilter(); endHttpSession(); } @Test @DirtiesContext public void getQuestOverview() throws Exception { beginHttpSession(); beginHttpRequestAndOpenSessionInViewFilter(); DbTutorialConfig dbTutorialConfig = tutorialService.getDbTutorialCrudRootServiceHelper().createDbChild(); //DbPlanet dbPlanet = userGuidanceService.getDbLevelCrud().createDbChild(); DbLevel dbLevel = userGuidanceService.getDbLevelCrud().createDbChild(); dbLevel.setXp(100); DbLevelTask dbLevelTask0 = dbLevel.getLevelTaskCrud().createDbChild(); dbLevelTask0.getI18nTitle().putString("dbLevelTask0"); DbLevelTask dbLevelTask1 = dbLevel.getLevelTaskCrud().createDbChild(); dbLevelTask1.getI18nTitle().putString("dbLevelTask1"); dbLevelTask1.setDbTutorialConfig(dbTutorialConfig); DbLevelTask dbLevelTask2 = dbLevel.getLevelTaskCrud().createDbChild(); dbLevelTask2.getI18nTitle().putString("dbLevelTask2"); DbLevelTask dbLevelTask3 = dbLevel.getLevelTaskCrud().createDbChild(); dbLevelTask3.getI18nTitle().putString("dbLevelTask3"); dbLevelTask3.setDbTutorialConfig(dbTutorialConfig); DbLevelTask dbLevelTask4 = dbLevel.getLevelTaskCrud().createDbChild(); dbLevelTask4.getI18nTitle().putString("dbLevelTask4"); DbLevelTask dbLevelTask5 = dbLevel.getLevelTaskCrud().createDbChild(); dbLevelTask5.getI18nTitle().putString("dbLevelTask5"); userGuidanceService.getDbLevelCrud().updateDbChild(dbLevel); userGuidanceService.activateLevels(); endHttpRequestAndOpenSessionInViewFilter(); endHttpSession(); UserGuidanceServiceImpl userGuidanceServiceImpl = (UserGuidanceServiceImpl) deAopProxy(userGuidanceService); beginHttpSession(); beginHttpRequestAndOpenSessionInViewFilter(); UserState userState = userService.getUserState(); QuestOverview questOverview = userGuidanceService.getQuestOverview(Locale.ENGLISH); Assert.assertEquals(0, questOverview.getQuestsDone()); Assert.assertEquals(4, questOverview.getTotalQuests()); Assert.assertEquals(0, questOverview.getMissionsDone()); Assert.assertEquals(2, questOverview.getTotalMissions()); Assert.assertEquals(6, questOverview.getQuestInfos().size()); Assert.assertEquals("dbLevelTask0", questOverview.getQuestInfos().get(0).getTitle()); Assert.assertEquals("dbLevelTask1", questOverview.getQuestInfos().get(1).getTitle()); Assert.assertEquals("dbLevelTask2", questOverview.getQuestInfos().get(2).getTitle()); Assert.assertEquals("dbLevelTask3", questOverview.getQuestInfos().get(3).getTitle()); Assert.assertEquals("dbLevelTask4", questOverview.getQuestInfos().get(4).getTitle()); Assert.assertEquals("dbLevelTask5", questOverview.getQuestInfos().get(5).getTitle()); userGuidanceServiceImpl.conditionPassed(userState, dbLevelTask0.getId()); questOverview = userGuidanceService.getQuestOverview(Locale.ENGLISH); Assert.assertEquals(1, questOverview.getQuestsDone()); Assert.assertEquals(4, questOverview.getTotalQuests()); Assert.assertEquals(0, questOverview.getMissionsDone()); Assert.assertEquals(2, questOverview.getTotalMissions()); Assert.assertEquals(5, questOverview.getQuestInfos().size()); Assert.assertEquals("dbLevelTask1", questOverview.getQuestInfos().get(0).getTitle()); Assert.assertEquals("dbLevelTask2", questOverview.getQuestInfos().get(1).getTitle()); Assert.assertEquals("dbLevelTask3", questOverview.getQuestInfos().get(2).getTitle()); Assert.assertEquals("dbLevelTask4", questOverview.getQuestInfos().get(3).getTitle()); Assert.assertEquals("dbLevelTask5", questOverview.getQuestInfos().get(4).getTitle()); userGuidanceService.activateQuest(dbLevelTask5.getId(), Locale.ENGLISH); userGuidanceServiceImpl.conditionPassed(userState, dbLevelTask5.getId()); questOverview = userGuidanceService.getQuestOverview(Locale.ENGLISH); Assert.assertEquals(2, questOverview.getQuestsDone()); Assert.assertEquals(4, questOverview.getTotalQuests()); Assert.assertEquals(0, questOverview.getMissionsDone()); Assert.assertEquals(2, questOverview.getTotalMissions()); Assert.assertEquals(4, questOverview.getQuestInfos().size()); Assert.assertEquals("dbLevelTask1", questOverview.getQuestInfos().get(0).getTitle()); Assert.assertEquals("dbLevelTask2", questOverview.getQuestInfos().get(1).getTitle()); Assert.assertEquals("dbLevelTask3", questOverview.getQuestInfos().get(2).getTitle()); Assert.assertEquals("dbLevelTask4", questOverview.getQuestInfos().get(3).getTitle()); userGuidanceService.activateQuest(dbLevelTask3.getId(), Locale.ENGLISH); userGuidanceServiceImpl.conditionPassed(userState, dbLevelTask3.getId()); questOverview = userGuidanceService.getQuestOverview(Locale.ENGLISH); Assert.assertEquals(2, questOverview.getQuestsDone()); Assert.assertEquals(4, questOverview.getTotalQuests()); Assert.assertEquals(1, questOverview.getMissionsDone()); Assert.assertEquals(2, questOverview.getTotalMissions()); Assert.assertEquals(3, questOverview.getQuestInfos().size()); Assert.assertEquals("dbLevelTask1", questOverview.getQuestInfos().get(0).getTitle()); Assert.assertEquals("dbLevelTask2", questOverview.getQuestInfos().get(1).getTitle()); Assert.assertEquals("dbLevelTask4", questOverview.getQuestInfos().get(2).getTitle()); userGuidanceService.activateQuest(dbLevelTask1.getId(), Locale.ENGLISH); userGuidanceServiceImpl.conditionPassed(userState, dbLevelTask1.getId()); questOverview = userGuidanceService.getQuestOverview(Locale.ENGLISH); Assert.assertEquals(2, questOverview.getQuestsDone()); Assert.assertEquals(4, questOverview.getTotalQuests()); Assert.assertEquals(2, questOverview.getMissionsDone()); Assert.assertEquals(2, questOverview.getTotalMissions()); Assert.assertEquals(2, questOverview.getQuestInfos().size()); Assert.assertEquals("dbLevelTask2", questOverview.getQuestInfos().get(0).getTitle()); Assert.assertEquals("dbLevelTask4", questOverview.getQuestInfos().get(1).getTitle()); userGuidanceService.activateQuest(dbLevelTask2.getId(), Locale.ENGLISH); userGuidanceServiceImpl.conditionPassed(userState, dbLevelTask2.getId()); questOverview = userGuidanceService.getQuestOverview(Locale.ENGLISH); Assert.assertEquals(3, questOverview.getQuestsDone()); Assert.assertEquals(4, questOverview.getTotalQuests()); Assert.assertEquals(2, questOverview.getMissionsDone()); Assert.assertEquals(2, questOverview.getTotalMissions()); Assert.assertEquals(1, questOverview.getQuestInfos().size()); Assert.assertEquals("dbLevelTask4", questOverview.getQuestInfos().get(0).getTitle()); userGuidanceService.activateQuest(dbLevelTask4.getId(), Locale.ENGLISH); userGuidanceServiceImpl.conditionPassed(userState, dbLevelTask4.getId()); questOverview = userGuidanceService.getQuestOverview(Locale.ENGLISH); Assert.assertEquals(4, questOverview.getQuestsDone()); Assert.assertEquals(4, questOverview.getTotalQuests()); Assert.assertEquals(2, questOverview.getMissionsDone()); Assert.assertEquals(2, questOverview.getTotalMissions()); Assert.assertEquals(0, questOverview.getQuestInfos().size()); } @Test @DirtiesContext public void setAndGetDoneDbLevelTasks() throws Exception { configureMultiplePlanetsAndLevels(); beginHttpSession(); beginHttpRequestAndOpenSessionInViewFilter(); createAndLoginUser("U1"); UserState userState = userService.getUserState(); userGuidanceService.promote(userState, TEST_LEVEL_3_REAL_ID); endHttpRequestAndOpenSessionInViewFilter(); endHttpSession(); beginHttpSession(); beginHttpRequestAndOpenSessionInViewFilter(); Assert.assertEquals(0, userGuidanceService.getDoneDbLevelTasks(userState).size()); Collection<DbLevelTask> dbLevelTasksDone = new ArrayList<>(); dbLevelTasksDone.add(userGuidanceService.getDbLevelTask4Id(TEST_LEVEL_TASK_1_3_REAL_ID)); dbLevelTasksDone.add(userGuidanceService.getDbLevelTask4Id(TEST_LEVEL_TASK_2_3_REAL_ID)); dbLevelTasksDone.add(userGuidanceService.getDbLevelTask4Id(TEST_LEVEL_TASK_3_3_SIMULATED_ID)); dbLevelTasksDone.add(userGuidanceService.getDbLevelTask4Id(TEST_LEVEL_TASK_4_3_SIMULATED_ID)); userGuidanceService.setDoneDbLevelTasks(dbLevelTasksDone, userState); Assert.assertEquals(4, userGuidanceService.getDoneDbLevelTasks(userState).size()); Assert.assertTrue(userGuidanceService.getDoneDbLevelTasks(userState).contains(userGuidanceService.getDbLevelTask4Id(TEST_LEVEL_TASK_1_3_REAL_ID))); Assert.assertTrue(userGuidanceService.getDoneDbLevelTasks(userState).contains(userGuidanceService.getDbLevelTask4Id(TEST_LEVEL_TASK_2_3_REAL_ID))); Assert.assertTrue(userGuidanceService.getDoneDbLevelTasks(userState).contains(userGuidanceService.getDbLevelTask4Id(TEST_LEVEL_TASK_3_3_SIMULATED_ID))); Assert.assertTrue(userGuidanceService.getDoneDbLevelTasks(userState).contains(userGuidanceService.getDbLevelTask4Id(TEST_LEVEL_TASK_4_3_SIMULATED_ID))); endHttpRequestAndOpenSessionInViewFilter(); endHttpSession(); beginHttpSession(); beginHttpRequestAndOpenSessionInViewFilter(); loginUser("U1"); QuestOverview questOverview = userGuidanceService.getQuestOverview(Locale.ENGLISH); Assert.assertEquals(2, questOverview.getQuestsDone()); Assert.assertEquals(2, questOverview.getMissionsDone()); endHttpRequestAndOpenSessionInViewFilter(); endHttpSession(); } @Test @DirtiesContext public void setDoneDbLevelTasksFail() throws Exception { configureMultiplePlanetsAndLevels(); beginHttpSession(); beginHttpRequestAndOpenSessionInViewFilter(); createAndLoginUser("U1"); UserState userState = userService.getUserState(); userGuidanceService.promote(userState, TEST_LEVEL_3_REAL_ID); endHttpRequestAndOpenSessionInViewFilter(); endHttpSession(); beginHttpSession(); beginHttpRequestAndOpenSessionInViewFilter(); Collection<DbLevelTask> dbLevelTasksDone = new ArrayList<>(); dbLevelTasksDone.add(userGuidanceService.getDbLevelTask4Id(TEST_LEVEL_TASK_1_2_REAL_ID)); try { userGuidanceService.setDoneDbLevelTasks(dbLevelTasksDone, userState); Assert.fail("IllegalArgumentException expected"); } catch (IllegalArgumentException e) { Assert.assertEquals("Quest does not belong to level: DbLevelTask{id=2, name='TEST_LEVEL_TASK_1_2_REAL_NAME}", e.getMessage()); } Assert.assertEquals(0, userGuidanceService.getDoneDbLevelTasks(userState).size()); endHttpRequestAndOpenSessionInViewFilter(); endHttpSession(); } @Test @DirtiesContext public void getLevelTaskState() throws Exception { configureMultiplePlanetsAndLevels(); beginHttpSession(); beginHttpRequestAndOpenSessionInViewFilter(); createAndLoginUser("U1"); UserState userState = userService.getUserState(); userGuidanceService.promote(userState, TEST_LEVEL_3_REAL_ID); endHttpRequestAndOpenSessionInViewFilter(); endHttpSession(); beginHttpSession(); beginHttpRequestAndOpenSessionInViewFilter(); Collection<DbLevelTask> dbLevelTasksDone = new ArrayList<>(); dbLevelTasksDone.add(userGuidanceService.getDbLevelTask4Id(TEST_LEVEL_TASK_2_3_REAL_ID)); userGuidanceService.setDoneDbLevelTasks(dbLevelTasksDone, userState); // Verify Assert.assertEquals(UserGuidanceService.QuestState.ACTIVE, userGuidanceService.getLevelTaskState(TEST_LEVEL_TASK_1_3_REAL_ID, userState)); Assert.assertEquals(UserGuidanceService.QuestState.DONE, userGuidanceService.getLevelTaskState(TEST_LEVEL_TASK_2_3_REAL_ID, userState)); Assert.assertEquals(UserGuidanceService.QuestState.OPEN, userGuidanceService.getLevelTaskState(TEST_LEVEL_TASK_3_3_SIMULATED_ID, userState)); Assert.assertEquals(UserGuidanceService.QuestState.OPEN, userGuidanceService.getLevelTaskState(TEST_LEVEL_TASK_4_3_SIMULATED_ID, userState)); userGuidanceService.setDoneDbLevelTasks(dbLevelTasksDone, userState); endHttpRequestAndOpenSessionInViewFilter(); endHttpSession(); } @Test @DirtiesContext public void getActiveQuest() throws Exception { configureMultiplePlanetsAndLevels(); beginHttpSession(); beginHttpRequestAndOpenSessionInViewFilter(); createAndLoginUser("U1"); UserState userState = userService.getUserState(); userGuidanceService.promote(userState, TEST_LEVEL_3_REAL_ID); endHttpRequestAndOpenSessionInViewFilter(); endHttpSession(); beginHttpSession(); beginHttpRequestAndOpenSessionInViewFilter(); Assert.assertEquals(TEST_LEVEL_TASK_1_3_REAL_ID, (int)userGuidanceService.getActiveQuest(userState).getId()); endHttpRequestAndOpenSessionInViewFilter(); endHttpSession(); } }
[ "beat.keller@btxtech.com" ]
beat.keller@btxtech.com
27a9b9b14abd083787dc1bb0b13f391d6451bea5
d69254cc53a56b8483cb063d4f505aa672e11e1d
/app/src/main/java/com/andeddo/lanchat/ChatMsgActivityView.java
be8ce17a79ae58c9730318912981824d7509b808
[ "Apache-2.0" ]
permissive
soulofhan/LANTalk
a65e0fcb7f03557e16bfc2cf8439f110d4b42dc8
2c39d1d01c2322816b93cb7e02c7ccb4f1d90959
refs/heads/master
2020-03-25T10:00:51.282112
2019-05-04T10:28:10
2019-05-04T10:28:10
143,681,807
1
0
null
null
null
null
UTF-8
Java
false
false
91
java
package com.andeddo.lanchat; public interface ChatMsgActivityView { void mHandle(); }
[ "hgj19950619@gmail.com" ]
hgj19950619@gmail.com
5b8a3834ccc7bedaf989d94c4be66ba36300b2d1
629ac9de92265b995881a9ac36e74a1aa308e670
/bebtea/src/main/java/com/shventurecapital/bebtea/repository/SupplyRepository.java
7f15bcb14469b758a40c267adeb224bbd341ad44
[]
no_license
SHVentureCapital/BebTea
7b719bba82e7d8d69a21fe5c9eda9a06d63bb559
d59edd6335ab4054b9eab2504cc5a61c7ba9c3c8
refs/heads/main
2023-03-08T03:54:34.666515
2021-02-19T09:01:08
2021-02-19T09:01:08
null
0
0
null
null
null
null
UTF-8
Java
false
false
390
java
package com.shventurecapital.bebtea.repository; import org.springframework.data.jpa.repository.JpaRepository; import org.springframework.stereotype.Repository; import com.shventurecapital.bebtea.models.Supply; /** * OOP Class 20-21 * @author Gerald Villaran */ @Repository public interface SupplyRepository extends JpaRepository<Supply, Long> { //User findByEmail(String email); }
[ "noreply@github.com" ]
noreply@github.com
4331ae0a70f02bdba82c33ca7ecf620ec8b0e3fe
df1c1f300b75a56be10cda0d0ed0bd4f46143c46
/okhttputils/src/main/java/com/zhy/http/okhttp/callback/BitmapCallback.java
46b3775258c52c922be2009dac3cd0ac6523ef42
[]
no_license
DeatHades/CallingLighting
65611511220e6359dc9e8c47c3c70d08abaace6e
76fe262c59c3968db07ceb917908b0336abc93fc
refs/heads/master
2020-12-08T09:30:42.627078
2017-04-29T03:10:31
2017-04-29T03:10:31
null
0
0
null
null
null
null
UTF-8
Java
false
false
418
java
package com.zhy.http.okhttp.callback; import android.graphics.Bitmap; import android.graphics.BitmapFactory; import okhttp3.Response; /** * Created by zhy on 15/12/14. */ public abstract class BitmapCallback extends Callback { @Override public Bitmap parseNetworkResponse(Response response , int id) throws Exception { return BitmapFactory.decodeStream(response.body().byteStream()); } }
[ "xuwei@njbandou.com" ]
xuwei@njbandou.com
d22b932c00768c23054bb8321a4f349abd55992a
30e19f7d71440aa41b794e5412255e442da2cf00
/20210630/src/co/yedam/StudentExample.java
3c59bb41887cbbfd33b0a6386963403e6c9a8797
[]
no_license
alfla132/firstProject
2e8087d083718beda49e903bfcacf88471ec17a6
c14c68b28c50ddecec88ba9cba55810ae5985e41
refs/heads/master
2023-07-03T17:50:38.916846
2021-08-09T07:56:18
2021-08-09T07:56:18
379,487,534
0
0
null
null
null
null
UTF-8
Java
false
false
1,353
java
package co.yedam; public class StudentExample { public static void main(String[] args) { Student s1 = new Student(); s1.setName("짱구"); s1.setStuNum(1); s1.setEngGrade(90); s1.setMathGrade(80); Student s2 = new Student(); s2.setName("철수"); s2.setStuNum(2); s2.setEngGrade(70); s2.setMathGrade(88); Student s3 = new Student(); s3.setName("맹구"); s3.setStuNum(3); s3.setEngGrade(99); s3.setMathGrade(90); Student[] students = { s1, s2, s3 }; int maxValue = 0; String name = ""; Student maxStudent = null; for (int i = 0; i < students.length; i++) { if (maxValue < students[i].getEngGrade()) { maxValue = students[i].getEngGrade(); maxStudent = students[i]; } } System.out.println("최고영어점수:" + maxStudent.getEngGrade() + " 이름:" + maxStudent.getName() + " 수학:" + maxStudent.getMathGrade()); int mathSum = 0; int engSum = 0; double mathAvg = 0; double engAvg = 0; for (int j = 0; j < students.length; j++) { mathSum = mathSum + students[j].getMathGrade(); mathAvg = mathSum / students.length; engSum = engSum + students[j].getEngGrade(); engAvg = engSum / students.length; } System.out.println("수학평균: " + mathAvg); System.out.println("영어평균: " + engAvg); } }
[ "Admin@DESKTOP-M4U617B" ]
Admin@DESKTOP-M4U617B
707a751bfcc1b215b31c70a925962adc8194cff7
6f858e8fc0a09b285070922a24868fb7b573b9f3
/rainbow/src/main/java/com/rainbow/web/member/MemberDTO.java
9681ad604d07dd7af1d62c44caba5ef50787e0db
[]
no_license
bingoori/NRainbow-Movie
e3a1f010b7865aabe197ba0b187cc14af83c6c2e
c0fd9d88466e3dc9a858eddb2d10841742dd2134
refs/heads/master
2021-01-19T21:37:34.078923
2016-08-09T03:40:58
2016-08-09T03:40:58
65,255,750
0
0
null
null
null
null
UTF-8
Java
false
false
1,593
java
package com.rainbow.web.member; import org.springframework.stereotype.Component; @Component public class MemberDTO { private int memberSeq; private String id; private String password; private String name; private String birth; private String addr; private String email; private int point; private String grade; private String regDate; private String cash; public String getCash() { return cash; } public void setCash(String cash) { this.cash = cash; } public int getMemberSeq() { return memberSeq; } public void setMemberSeq(int memberSeq) { this.memberSeq = memberSeq; } public String getId() { return id; } public void setId(String id) { this.id = id; } public String getPassword() { return password; } public void setPassword(String password) { this.password = password; } public String getName() { return name; } public void setName(String name) { this.name = name; } public String getBirth() { return birth; } public void setBirth(String birth) { this.birth = birth; } public String getAddr() { return addr; } public void setAddr(String addr) { this.addr = addr; } public String getEmail() { return email; } public void setEmail(String email) { this.email = email; } public int getPoint() { return point; } public void setPoint(int point) { this.point = point; } public String getGrade() { return grade; } public void setGrade(String grade) { this.grade = grade; } public String getRegDate() { return regDate; } public void setRegDate(String regDate) { this.regDate = regDate; } }
[ "useongdu@218.38.137.27" ]
useongdu@218.38.137.27
ab057c40a1834cfca5cff65ddbda15dea0a4ae44
8361c48221ae1b5627a22ba04b313b447feb933f
/src/LeetCode/MergeSortedArray.java
7377f9a7da1840dcdaaee8cb0231f68f36e8634c
[]
no_license
YesVen/CrackingTheCodingWithHackerRankAndLeetCode
07f92da263ef1930d80efbcabb84fc7976324bd0
113c57bb34e43dabb7bf8ccab27e11646faae611
refs/heads/master
2020-03-21T11:11:28.339119
2016-12-08T23:07:16
2016-12-08T23:07:16
null
0
0
null
null
null
null
UTF-8
Java
false
false
915
java
/** * Given two sorted integer arrays nums1 and nums2, merge nums2 * into nums1 as one sorted array. Note: You may assume that nums1 has enough space (size that is greater or equal to m + n) to hold additional elements from nums2. The number of elements initialized in nums1 and nums2 are m and n respectively. */ package LeetCode; public class MergeSortedArray { public static void main(String[] args){ } public static void arrayMerger(int[] array1, int size1, int[] array2, int size2){ while(size1>0 && size2>0){ if(array1[size1-1]>array2[size2-1]){ array1[size1+size2-1] =array1[size1-1]; size1--; }else{ array1[size1+size2-1] =array2[size2-1]; size2--; } } if(size1>0){ while(size1>0){ array1[size1+size2-1] =array1[size1-1]; size1--; } } if(size2>0){ while(size2>0){ array1[size1+size2-1] =array2[size2-1]; size2--; } } } }
[ "bharatbhavsar007@gmail.com" ]
bharatbhavsar007@gmail.com
b84d53d224fea5f0f95ff9976891c318e7c4e9f8
2d9ca7719dc2a20267cca543a905a83688afebd2
/android/Android-First-Steps/Calculations-Acochambrations/app/src/main/java/com/example/zapptsdev/calculations_acochambrations/Activities/SplashActivity.java
228a6db118906e2611cfcd5742dbb88cdf3f64b3
[ "MIT" ]
permissive
PauloKeller/Mobile-Development
8e83216d34052fa49641dedcfb19f08971245feb
d4976d8dc456da630276558da6933c80ae7688b8
refs/heads/main
2023-03-16T21:14:56.056971
2023-02-18T00:43:51
2023-02-18T00:43:51
196,060,935
1
0
null
null
null
null
UTF-8
Java
false
false
762
java
package com.example.zapptsdev.calculations_acochambrations.Activities; import android.content.Intent; import android.support.v7.app.AppCompatActivity; import android.os.Bundle; import com.example.zapptsdev.calculations_acochambrations.R; public class SplashActivity extends AppCompatActivity { @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_splash); try { Thread.sleep(1000); goToMain(); } catch (InterruptedException e) { e.printStackTrace(); } } private void goToMain(){ Intent i = new Intent(SplashActivity.this, MainActivity.class); startActivity(i); } }
[ "paulokeller@Paulos-MacBook-Pro.local" ]
paulokeller@Paulos-MacBook-Pro.local
c8aa8b35f17d296632ad1a14ccce0600c600622b
0971cf2060b6f5b78a8f9bfccd8dc4323b42f14c
/src/main/java/com/study/my/command/ProfileCommand.java
5d900a6d1d50723205585cffa940ba37ebd7da3f
[]
no_license
AndreyTut/admission
26bc983c6f57d07b3157a980c58f6bd57a84bbde
dc05ace04842dfbe72911467fbbe532f11971967
refs/heads/master
2023-03-23T10:38:19.919670
2021-03-04T08:17:17
2021-03-04T08:17:17
339,517,247
0
0
null
null
null
null
UTF-8
Java
false
false
2,771
java
package com.study.my.command; import com.study.my.model.Faculty; import com.study.my.model.User; import com.study.my.service.FacultyService; import com.study.my.service.UserService; import org.apache.log4j.Logger; import javax.servlet.http.HttpServletRequest; import java.util.List; import static com.study.my.util.Constants.*; import static com.study.my.util.Utils.putStudentToRequest; public class ProfileCommand implements Command { private static final Logger LOGGER = Logger.getLogger(ProfileCommand.class); private UserService userService; private FacultyService facultyService; public ProfileCommand(UserService userService, FacultyService facultyService) { this.userService = userService; this.facultyService = facultyService; } @Override public String execute(HttpServletRequest request) { if ("GET".equals(request.getMethod())) { User user = (User) request.getSession().getAttribute("user"); User student = userService.getFullStudent(user.getId()); List<Faculty> faculties = facultyService.getUserFaculty(user.getId()); student.setFaculties(faculties); putStudentToRequest(student, request); } if ("POST".equals(request.getMethod())) { int id = Integer.parseInt(request.getParameter("id")); String email = request.getParameter(EMAIL_FIELD); String password = request.getParameter(PASSWORD_FIELD); String city = request.getParameter(CITY_FIELD); String region = request.getParameter(REGION_FIELD); String patronymic = request.getParameter(PATRONYMIC_FIELD); String firstName = request.getParameter(FIRST_NAME_FIELD); String lastName = request.getParameter(LAST_NAME_FIELD); String schoolName = request.getParameter(SCHOOL_NAME_FIELD); User student = User.builder() .id(id) .password(password) .email(email) .firstName(firstName) .lastName(lastName) .patronymic(patronymic) .city(city) .region(region) .schoolName(schoolName) .isEnabled(true) .build(); LOGGER.debug("Sending student form: " + student); userService.update(student); User fullStudent = userService.getFullStudent(student.getId()); List<Faculty> faculties = facultyService.getUserFaculty(student.getId()); fullStudent.setFaculties(faculties); putStudentToRequest(fullStudent, request); } return "/WEB-INF/jsp/user.jsp"; } }
[ "andreww@ukr.net" ]
andreww@ukr.net
b26f9f1d22ed43a62dafecd705930c5f85d0b3a0
3141e4926627e6c7afbed91bef2048458aa03c18
/src/main/java/info/bowkett/bowling/io/Console.java
89b1c951f652443165675993f325ae639c85a292
[]
no_license
jbowkett/Bowling-Tech-Test
4586bed09decca0b20415ccd8a4a5040ad6f3570
a4cdfa73ec36766ab89d54585b58aeb1da8109df
refs/heads/master
2020-06-07T20:01:22.046338
2013-08-20T07:22:19
2013-08-20T07:22:19
null
0
0
null
null
null
null
UTF-8
Java
false
false
2,302
java
package info.bowkett.bowling.io; /** * Created by IntelliJ IDEA. * User: jbowkett * Date: Aug 16, 2013 * Time: 9:06:19 AM * Represents console input and output, and is responsible for checking the * types and boundaries of input, and whether quit was entered. * Methods continue to prompt until given valid input or "quit". */ public class Console { private final java.io.Console console; public Console(java.io.Console console) { this.console = console; } public String getStringPrompt(String prompt) throws QuitException { String input = null; while(isBlank(input)){ msg(prompt); input = console.readLine(); if(input.equalsIgnoreCase("QUIT")){ throw new QuitException(); } } return input; } private boolean isBlank(String input) { return input == null || input.trim().length() == 0; } public int getIntInput(String prompt, int minValue, int maxValue) throws QuitException { while(true){ final String input = getStringPrompt(prompt); try{ final int parsedValue = toInt(input); if(withinBounds(minValue, maxValue, parsedValue)){ return parsedValue; } throw new InvalidInputException("Invalid number input :["+input+"]"); } catch(InvalidInputException e) { exception(e, "Please enter a number between "+minValue+" & "+ maxValue); } } } private int toInt(String input) throws InvalidInputException { try{ return Integer.parseInt(input); } catch(NumberFormatException nfe){ throw new InvalidInputException("Invalid number input :["+input+"]"); } } private boolean withinBounds(int minValue, int maxValue, int parsedValue) { return isEqualToOneValidValue(minValue, maxValue, parsedValue) || parsedValue >= minValue && parsedValue <= maxValue; } private boolean isEqualToOneValidValue(int minValue, int maxValue, int parsedValue) { return minValue == maxValue && maxValue == parsedValue; } public Console msgln(String msg) { System.out.println(msg); return this; } public Console msg(String msg) { System.out.print(msg); return this; } public void exception(InvalidInputException e, String advice) { msgln(e.getMessage() + " :: " + advice); } }
[ "james_bowkett@lyagushka.co.uk" ]
james_bowkett@lyagushka.co.uk
0f0715a0d39ce385b6c7faf52efc4c5434f940dc
313831d5c12a142139be402d85f22aacff1bba80
/src/main/java/com/api/controller/MotorController.java
a1a7d775083e894dd6041c7bbb81f1019529c9d3
[]
no_license
Eugenio199226/SpringBootHibernateWithForeingKeyes
cb632587fbd608f65f43ab3d346c23682846810b
d0a8f0c485f0f460225082306388a81a46325b75
refs/heads/master
2021-03-17T20:29:46.354198
2020-03-17T12:49:18
2020-03-17T12:49:18
247,015,543
0
0
null
null
null
null
UTF-8
Java
false
false
2,966
java
package com.api.controller; import java.util.List; import java.util.Optional; import javax.validation.Valid; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.http.ResponseEntity; import org.springframework.web.bind.annotation.DeleteMapping; import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.PathVariable; import org.springframework.web.bind.annotation.PostMapping; import org.springframework.web.bind.annotation.PutMapping; import org.springframework.web.bind.annotation.RequestBody; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RestController; import com.api.Entity.EntityMotor; import com.api.Repository.MotorRepository; import com.api.Vehiculos.ApiVehiculo; import com.api.model.Motor; //Anotación que indica a spring boot que es un controlador @RestController //Raiz de la dirección de la api @RequestMapping("/api") public class MotorController { private static Logger LOG = LoggerFactory.getLogger(ApiVehiculo.class); @Autowired private MotorRepository motrep; //Grabar @PostMapping("/motor/grabar") public ResponseEntity<EntityMotor> createGenero( @RequestBody Motor mot) { LOG.info("Creating Motor...."); EntityMotor data = new EntityMotor(mot.getNombreMotor()); EntityMotor motorGuardado = motrep.save(data); LOG.info("Created Motor...."); return ResponseEntity.ok().body(motorGuardado); } //Lista Motores @GetMapping("/motores") public ResponseEntity<List<EntityMotor>> getallMotores() { LOG.info("Loading Motor...."); List<EntityMotor> motores = motrep.findAll(); LOG.info("Loaded Motor...."); return ResponseEntity.ok().body(motores); } //Lista Motores por id @GetMapping("/motores/{id}") public ResponseEntity<Optional<EntityMotor>> getMotorbyId(@PathVariable(value="id") int motId) { LOG.info("Loading Motor...."); Optional<EntityMotor> mot=motrep.findById(motId); LOG.info("Loaded Motor...."); return ResponseEntity.ok().body(mot); } //Modificar @PutMapping("/motores/actualizar/{id}") public ResponseEntity<EntityMotor> updateMotor(@PathVariable(value="id") int motId,@Valid @RequestBody Motor motDetails) { LOG.info("Updating Motor...."); Optional<EntityMotor> mot=motrep.findById(motId); mot.get().setNombreMotor(motDetails.getNombreMotor()); EntityMotor motorActualizado = mot.get(); EntityMotor actualizarMotor=motrep.save(motorActualizado); LOG.info("Updated Motor...."); return ResponseEntity.ok().body(actualizarMotor); } //Borrar @DeleteMapping("/motor/borrar/{id}") public ResponseEntity<EntityMotor> borrarMotor(@PathVariable(value="id")int motid) { LOG.info("Deleting Motor...."); motrep.deleteById(motid); LOG.info("Deleted Motor...."); return ResponseEntity.ok().build(); } }
[ "eugenio199226@gmail.com" ]
eugenio199226@gmail.com
4882840c899b3e5d180c97a26d2dd117e856613c
be67c83e574266e41510cb387c8b348ca1392297
/src/main/java/org/measure/platform/core/impl/repository/ProjectRepository.java
bdf49ec36cb75b1c187fd5ffee6ba8cd1a7e51fb
[]
no_license
franke-wu/MeasurePlatform
fd8a30547e1f7ae85b6a6d561f6ce1ced1cca422
b2d00b7e651aa01e55deb5c871216c6e992a8f74
refs/heads/master
2020-03-20T04:27:52.227663
2018-06-01T14:44:32
2018-06-01T14:44:32
null
0
0
null
null
null
null
UTF-8
Java
false
false
527
java
package org.measure.platform.core.impl.repository; import java.util.List; import org.measure.platform.core.entity.Project; import org.springframework.data.jpa.repository.JpaRepository; import org.springframework.data.jpa.repository.Query; /** * Spring Data JPA repository for the Project entity. */ public interface ProjectRepository extends JpaRepository<Project,Long> { @Query("select project from Project project where project.owner.login = ?#{principal.username}") List<Project> findByOwnerIsCurrentUser(); }
[ "antonin.abherve@softeam.fr" ]
antonin.abherve@softeam.fr
50f9271fb7384a085b8455169b039efebd2f6918
fc5004cb61df4488af15f73035545e999412c130
/comminucation_test/src/main/java/concurrent/ReentreLockTest.java
0a6c0ca9327f051f225262935f4226ad14b5a108
[]
no_license
horsezp/comminucation_test
f435d4df92de2ead0cc42c471992c23c5f3bcbe6
c203f2454f0668d1c50f634052956dbcd725140c
refs/heads/master
2021-07-20T10:09:29.339537
2017-10-27T09:49:07
2017-10-27T09:49:07
107,485,158
0
0
null
null
null
null
UTF-8
Java
false
false
4,791
java
package concurrent; import java.util.concurrent.CyclicBarrier; import java.util.concurrent.ExecutorService; import java.util.concurrent.Executors; import java.util.concurrent.Semaphore; import java.util.concurrent.atomic.AtomicLong; import java.util.concurrent.locks.Lock; import java.util.concurrent.locks.ReentrantLock; public class ReentreLockTest { private static long COUNT = 1000000; private static Lock lock = new ReentrantLock(); private static long lockCounter = 0; private static long syncCounter = 0; private static long semaCounter = 0; private static AtomicLong atomicCounter = new AtomicLong(0); private static Object syncLock = new Object(); private static Semaphore mutex = new Semaphore(1); public static void testLock(int num, int threadCount) { } static long getLock() { lock.lock(); try { return lockCounter; } finally { lock.unlock(); } } static long getSync() { synchronized (syncLock) { return syncCounter; } } static long getAtom() { return atomicCounter.get(); } static long getSemaphore() throws InterruptedException { mutex.acquire(); try { return semaCounter; } finally { mutex.release(); } } static long getLockInc() { lock.lock(); try { return ++lockCounter; } finally { lock.unlock(); } } static long getSyncInc() { synchronized (syncLock) { return ++syncCounter; } } static long getAtomInc() { return atomicCounter.getAndIncrement(); } static class SemaTest extends Test { public SemaTest(String id, CyclicBarrier barrier, long count, int threadNum, ExecutorService executor) { super(id, barrier, count, threadNum, executor); } @Override protected void test() { try { getSemaphore(); } catch (InterruptedException e) { e.printStackTrace(); } } } static class LockTest extends Test { public LockTest(String id, CyclicBarrier barrier, long count, int threadNum, ExecutorService executor) { super(id, barrier, count, threadNum, executor); } @Override protected void test() { getLock(); } } static class SyncTest extends Test { public SyncTest(String id, CyclicBarrier barrier, long count, int threadNum, ExecutorService executor) { super(id, barrier, count, threadNum, executor); } @Override protected void test() { getSync(); } } static class AtomicTest extends Test { public AtomicTest(String id, CyclicBarrier barrier, long count, int threadNum, ExecutorService executor) { super(id, barrier, count, threadNum, executor); } @Override protected void test() { getAtom(); } } public static void test(String id, long count, int threadNum, ExecutorService executor) { final CyclicBarrier barrier = new CyclicBarrier(threadNum + 1, new Thread() { @Override public void run() { } }); System.out.println("=============================="); System.out.println("count = " + count + "/t" + "Thread Count = " + threadNum); new LockTest("Lock ", barrier, COUNT, threadNum, executor).startTest(); new SyncTest("Sync ", barrier, COUNT, threadNum, executor).startTest(); new AtomicTest("Atom ", barrier, COUNT, threadNum, executor) .startTest(); new SemaTest("Sema ", barrier, COUNT, threadNum, executor) .startTest(); System.out.println("=============================="); } public static void main(String[] args) { for (int i = 1; i < 5; i++) { ExecutorService executor = Executors.newFixedThreadPool(10 * i); test("", COUNT * i, 10 * i, executor); } } }
[ "horsezp@163.com" ]
horsezp@163.com
49eb2d173eaba9a498504198073083185d5c3c88
2126f77e1cc13427e7133ad1dcf032a5a8ec1b85
/src/main/java/fr/wseduc/swift/utils/FileUtils.java
f4a15bff187ccdb315f5b447086e42087864bfbd
[ "Apache-2.0" ]
permissive
plutext/vertx-swift-client
640fd552ef506849abc667c5287bcc2557a0be1b
b0633b8ff7aacc33c0bc29595f55f791efea3cd2
refs/heads/master
2023-08-29T06:59:47.499424
2015-09-10T13:47:00
2015-09-10T13:47:00
null
0
0
null
null
null
null
UTF-8
Java
false
false
1,843
java
/* * Copyright © WebServices pour l'Éducation, 2014 * * 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 fr.wseduc.swift.utils; import org.vertx.java.core.http.HttpServerFileUpload; import org.vertx.java.core.json.JsonObject; public class FileUtils { public static String getNameWithExtension(String downloadName, JsonObject metadata) { String name = downloadName; if (metadata != null && metadata.getString("filename") != null) { String filename = metadata.getString("filename"); int fIdx = filename.lastIndexOf('.'); String fExt = null; if (fIdx >= 0) { fExt = filename.substring(fIdx); } int dIdx = downloadName.lastIndexOf('.'); String dExt = null; if (dIdx >= 0) { dExt = downloadName.substring(dIdx); } if (fExt != null && !fExt.equals(dExt)) { name += fExt; } } return name; } public static JsonObject metadata(HttpServerFileUpload upload) { JsonObject metadata = new JsonObject(); metadata.putString("name", upload.name()); metadata.putString("filename", upload.filename()); metadata.putString("content-type", upload.contentType()); metadata.putString("content-transfer-encoding", upload.contentTransferEncoding()); metadata.putString("charset", upload.charset().name()); metadata.putNumber("size", upload.size()); return metadata; } }
[ "damien.boissin@web-education.net" ]
damien.boissin@web-education.net
a4077cd98e4eaf5a5da1a9626294baa353cf5e29
6ab26132c87b9111199f58a6cac3a4f7bf348e28
/so-resources/src/main/java/com/pineone/icbms/so/resources/property/Condition.java
d5c7afb7085172476ad1f0d23d5c60fefacc9a9c
[ "BSD-2-Clause" ]
permissive
pahnjy/PineoneIoTProject
a7d5dc3339781565a6ff8c6e908cb340535ac475
b91ee88ffd2922a5e1869416630149dd14025d45
refs/heads/master
2021-01-10T05:20:31.934940
2016-03-30T05:50:34
2016-03-30T05:50:34
54,936,483
0
1
null
2016-03-30T05:44:21
2016-03-29T01:36:07
Java
UTF-8
Java
false
false
326
java
package com.pineone.icbms.so.resources.property; /** * Created by existmaster on 2015. 10. 30.. */ public class Condition { String conditionID; public String getConditionID() { return conditionID; } public void setConditionID(String conditionID) { this.conditionID = conditionID; } }
[ "pahnjy@naver.com" ]
pahnjy@naver.com
a9ae018bea7cfa15b696d32417c35ea771a4ecaa
7e06a1b1fd779bb8f7fee3cc98027d91a38b9c99
/PIA WebApp/src/java/piawebapp/NoMoreReservationsPage.java
38b3d27e20f65d9e030e6e81975836fe826173c3
[]
no_license
vjovanov/pia2123
c52574ab1cab21de144fd7df9d280fe9e2061dd5
749638c07f7d8c56fc9ee10066057ee55a2fe817
refs/heads/master
2020-05-04T15:42:03.678660
2009-09-28T20:09:24
2009-09-28T20:09:24
32,425,879
0
0
null
null
null
null
UTF-8
Java
false
false
4,948
java
/* * To change this template, choose Tools | Templates * and open the template in the editor. */ package piawebapp; import com.sun.rave.web.ui.appbase.AbstractPageBean; import javax.faces.FacesException; /** * <p>Page bean that corresponds to a similarly named JSP page. This * class contains component definitions (and initialization code) for * all components that you have defined on this page, as well as * lifecycle methods and event handlers where you may add behavior * to respond to incoming events.</p> * * @version NoMoreReservationsPage.java * @version Created on 27.09.2009., 09.49.43 * @author Administrator */ public class NoMoreReservationsPage extends AbstractPageBean { // <editor-fold defaultstate="collapsed" desc="Managed Component Definition"> /** * <p>Automatically managed component initialization. <strong>WARNING:</strong> * This method is automatically generated, so any user-specified code inserted * here is subject to being replaced.</p> */ private void _init() throws Exception { } // </editor-fold> /** * <p>Construct a new Page bean instance.</p> */ public NoMoreReservationsPage() { } /** * <p>Callback method that is called whenever a page is navigated to, * either directly via a URL, or indirectly via page navigation. * Customize this method to acquire resources that will be needed * for event handlers and lifecycle methods, whether or not this * page is performing post back processing.</p> * * <p>Note that, if the current request is a postback, the property * values of the components do <strong>not</strong> represent any * values submitted with this request. Instead, they represent the * property values that were saved for this view when it was rendered.</p> */ @Override public void init() { // Perform initializations inherited from our superclass super.init(); // Perform application initialization that must complete // *before* managed components are initialized // TODO - add your own initialiation code here // <editor-fold defaultstate="collapsed" desc="Managed Component Initialization"> // Initialize automatically managed components // *Note* - this logic should NOT be modified try { _init(); } catch (Exception e) { log("NoMoreReservationsPage Initialization Failure", e); throw e instanceof FacesException ? (FacesException) e: new FacesException(e); } // </editor-fold> // Perform application initialization that must complete // *after* managed components are initialized // TODO - add your own initialization code here } /** * <p>Callback method that is called after the component tree has been * restored, but before any event processing takes place. This method * will <strong>only</strong> be called on a postback request that * is processing a form submit. Customize this method to allocate * resources that will be required in your event handlers.</p> */ @Override public void preprocess() { } /** * <p>Callback method that is called just before rendering takes place. * This method will <strong>only</strong> be called for the page that * will actually be rendered (and not, for example, on a page that * handled a postback and then navigated to a different page). Customize * this method to allocate resources that will be required for rendering * this page.</p> */ @Override public void prerender() { } /** * <p>Callback method that is called after rendering is completed for * this request, if <code>init()</code> was called (regardless of whether * or not this was the page that was actually rendered). Customize this * method to release resources acquired in the <code>init()</code>, * <code>preprocess()</code>, or <code>prerender()</code> methods (or * acquired during execution of an event handler).</p> */ @Override public void destroy() { } /** * <p>Return a reference to the scoped data bean.</p> * * @return reference to the scoped data bean */ protected ApplicationBean1 getApplicationBean1() { return (ApplicationBean1) getBean("ApplicationBean1"); } /** * <p>Return a reference to the scoped data bean.</p> * * @return reference to the scoped data bean */ protected RequestBean1 getRequestBean1() { return (RequestBean1) getBean("RequestBean1"); } /** * <p>Return a reference to the scoped data bean.</p> * * @return reference to the scoped data bean */ protected SessionBean1 getSessionBean1() { return (SessionBean1) getBean("SessionBean1"); } }
[ "gvojin@81aa477e-aadd-11de-9f33-a79f98c9f2a6" ]
gvojin@81aa477e-aadd-11de-9f33-a79f98c9f2a6
9b4fe7ab6ad651b47e0e178bc9118f0d86b41f0c
f885278a3a2c0acbca4f04ba50712b373cb72714
/src/HighLow.java
e63f798f40ac6ddb9a629338cb9138775c4c45b2
[]
no_license
CodeupClassroom/voyageurs-java-exercises
a988ea805213b1fa65d31b7ffd7d348466ed02a2
f478fe297e52ea2cb5b8bfd9037744ea8405a7d0
refs/heads/master
2020-03-23T20:27:59.535377
2018-08-07T16:02:48
2018-08-07T16:02:48
142,043,195
1
1
null
2018-08-07T16:02:49
2018-07-23T16:54:06
Java
UTF-8
Java
false
false
2,526
java
import java.util.Scanner; // Exercise 5 public class HighLow { public static int numberOfGuesses; public static int gameNumber; public static void main(String[] args) { initGame(); } public static void initGame() { boolean programRunning; boolean gameRunning = true; Scanner sc = new Scanner(System.in); System.out.println("Welcome to the High / Low Guessing Game!"); do { gameNumber = randomWithRange(1, 100); System.out.println("The random number is: " + gameNumber); do { gameRunning = runRound(sc); } while (gameRunning); programRunning = getYesOrNo(sc).equals("y"); } while (programRunning); System.out.println("Good bye!"); } public static boolean runRound(Scanner sc) { boolean gameNotWon = false; System.out.print("Please enter a guess: "); int playerGuess = getInteger(1, 100, sc); if (playerGuess == gameNumber) { System.out.println("GOOD GUESS!"); gameNotWon = false; } else if (playerGuess > gameNumber) { System.out.println("LOWER"); numberOfGuesses++; gameNotWon = true; System.out.println("Number of guesses made: " + numberOfGuesses); } else { System.out.println("HIGHER"); gameNotWon = true; numberOfGuesses++; System.out.println("Number of guesses made: " + numberOfGuesses); } return gameNotWon; } public static int randomWithRange(int min, int max) { int range = (max - min) + 1; return (int)(Math.random() * range) + min; } public static int getInteger(int min, int max, Scanner sc) { if (!sc.hasNextInt()) { System.out.println("Not a number!"); return getInteger(min, max, sc); } int userInput = sc.nextInt(); if (userInput >= min && userInput <= max) { return userInput; } else { System.out.println("Number not in range!"); return getInteger(min, max, sc); } } public static String getYesOrNo(Scanner sc) { String userChoice; do { System.out.println("Do you wish to play again? [y/n]: "); userChoice = sc.next().trim(); } while (!userChoice.equalsIgnoreCase("y") && !userChoice.equalsIgnoreCase("n")); return userChoice; } }
[ "justinreich.dev@gmail.com" ]
justinreich.dev@gmail.com
bad4a506fa0cb29bb7bdeab23adc716366bb148c
a62d4964ca8a30dd5f2d95c6322e63e66888d6d6
/week-09/day1/restpractice/src/main/java/com/example/greenfoxacademy/restpractice/Service/AppendService.java
af5e278bc800738a1fa1c22870028d049b749c97
[]
no_license
green-fox-academy/krisztiankassai
c2081ae57754f26912cbe45ba6de6b472cb9c6ed
16ef20f22542488f96413f869d6f487bb2e1c428
refs/heads/master
2020-03-16T15:51:40.218165
2018-07-10T15:42:36
2018-07-10T15:42:36
132,761,694
0
0
null
null
null
null
UTF-8
Java
false
false
293
java
package com.example.greenfoxacademy.restpractice.Service; import com.example.greenfoxacademy.restpractice.Model.Append; import org.springframework.stereotype.Service; @Service public class AppendService { public Append appender(String append){ return new Append(append + "a"); } }
[ "krisztiankassai21@gmail.com" ]
krisztiankassai21@gmail.com
1877944373f3cecb05dbcab612900a7c06ffd734
9516a94c148cd874f319ddcfea90805c7e2a9ff0
/src/main/java/com/flyingbiz/utils/Config.java
d22ff4666429f89dad9b8e4c93a5635fba114cc7
[]
no_license
ledonglin/schoolfellow
b18d912801184b4d05955243a6098f0285bea262
81e9d753f0ea8dd920b4e1e380b441134c345d41
refs/heads/master
2021-01-19T18:03:44.914656
2015-01-29T11:15:53
2015-01-29T11:15:53
20,248,168
0
0
null
null
null
null
UTF-8
Java
false
false
3,446
java
package com.flyingbiz.utils; import java.io.FileNotFoundException; import java.io.IOException; import java.io.InputStream; import java.util.Properties; import java.util.Set; import org.slf4j.Logger; import org.slf4j.LoggerFactory; /** * 加载配置文件,默认加载 * @author ledong * */ public class Config { private static final Logger logger = LoggerFactory.getLogger(Config.class); private final static Properties properties = new Properties(); static { loadProperties("schoolFellow.properties"); } private static Config instance = new Config(); private Config() { } // // private void init() { // loadProperties("dingwa.properties"); // } /** * 加载配置文件 * * @param filename * 配置文件名。如果不再Classpath目录内,请输入全路径名 * */ public static boolean loadProperties(final String filename) { InputStream is = ClassLoader.getSystemResourceAsStream(filename); try { properties.load(is); logger.info(">>>>>Load Properties File : " + filename + " SUCCESS!"); return true; } catch (IOException e) { logger.error("Load Properties File : " + filename + " Error!\n Error details : \n" + e.getMessage()); return false; } catch (Exception e1) { logger.error("Load Properties File : " + filename + " Error!\n Error details : \n" + e1.getMessage()); return false; } } public static String getProperties(String key) { return getProperties(key, ""); } public static String getProperties(String key, String defaultValue) { String value = (String) properties.get(key); if (value == null) return defaultValue; return value; } public static Integer getPropertiesAsIntValue(String key) { return getPropertiesAsIntValue(key, Integer.MIN_VALUE); } public static Integer getPropertiesAsIntValue(String key, int defaultValue) { String value = (String) properties.get(key); if (value == null) return defaultValue; else return Integer.valueOf(value); } public static Double getPropertiesAsDoubleValue(String key) { return getPropertiesAsDoubleValue(key, Double.MIN_VALUE); } public static Double getPropertiesAsDoubleValue(String key, double defaultValue) { String value = (String) properties.get(key); if (value == null) return defaultValue; else return Double.valueOf(value); } public static Boolean getPropertiesAsBooleanValue(String key) { return getPropertiesAsBooleanValue(key, Boolean.FALSE); } public static Boolean getPropertiesAsBooleanValue(String key, Boolean defaultValue) { String value = (String) properties.get(key); if (value == null) return defaultValue; else return Boolean.valueOf(value); } public static synchronized Config getInstance() { if (instance == null) instance = new Config(); return instance; } @Override public String toString() { StringBuilder sb = new StringBuilder(); Set<Object> keySet = properties.keySet(); for (Object key : keySet) { sb.append(key); sb.append(":"); sb.append(properties.get(key)); sb.append(","); } return sb.toString(); } public static void main(String args[]) throws FileNotFoundException, IOException { // Config config = new Config("schoolFellow.properties"); Config.loadProperties("database1.properties"); System.out.println(Config.getInstance().toString()); System.out.println(Config.getPropertiesAsBooleanValue("compressImg.proportion")); } }
[ "ledonglin@gmail.com" ]
ledonglin@gmail.com
67569cefcb3e8aaaf77179bcc3be165ef0540e2a
f8e3063794972f49971ca099f5fd68ea4e2c8d27
/Letters.java
f072e9b74f003b3b5d1f8d3b0e27e0173fe08bdc
[]
no_license
Animesh9/JAVA
e2d6f0e0c3b477a3cf8f35df96273b82d8c1a107
aae8facc6f365baaf2bc0f00f3e0b1badf4d21ec
refs/heads/master
2022-06-06T23:44:34.682202
2022-05-16T12:46:11
2022-05-16T12:46:11
235,513,664
8
5
null
2022-05-16T12:46:12
2020-01-22T06:33:36
Java
UTF-8
Java
false
false
597
java
class Letters { static void convertOpposite(StringBuffer str) { int ln = str.length(); for (int i=0; i<ln; i++) { Character c = str.charAt(i); if (Character.isLowerCase(c)) str.replace(i, i+1, Character.toUpperCase(c)+""); else str.replace(i, i+1, Character.toLowerCase(c)+""); } } public static void main(String[] args) { StringBuffer str = new StringBuffer("hey how are you"); convertOpposite(str); System.out.println(str); } }
[ "noreply@github.com" ]
noreply@github.com
0e74d81e96ec123c058d437f85e2cc15ac21b03d
482451e9d9ead76ac2e3dfa4bde1081812262718
/cameleds/src/test/java/com/ecmdeveloper/eds/demo/ImportCountryInfo.java
4fa8b226a0f38b0093adf588b0483b9e3993f6fc
[]
no_license
ecmdeveloper/cameleds
f71e5395da6292e29ce03db431c58a2f124211e1
6e20d70483b463678ae1af02277b7727a39f8c82
refs/heads/master
2021-03-12T23:44:38.265745
2014-01-29T13:49:54
2014-01-29T13:49:54
null
0
0
null
null
null
null
UTF-8
Java
false
false
2,907
java
/** * */ package com.ecmdeveloper.eds.demo; import java.util.List; import org.apache.camel.Exchange; import org.apache.camel.builder.RouteBuilder; import org.apache.camel.dataformat.csv.CsvDataFormat; import org.apache.camel.test.spring.CamelSpringTestSupport; import org.junit.Test; import org.springframework.context.support.AbstractApplicationContext; import org.springframework.context.support.ClassPathXmlApplicationContext; /** * @author Ricardo Belfor * */ public class ImportCountryInfo extends CamelSpringTestSupport { public class CountryInfoToSQL { public String toSQL(Exchange exchange) { List<String> list = (List<String>) exchange.getIn().getBody(); StringBuilder sb = new StringBuilder(); sb.append("insert into country_info "); sb.append("(iso,iso3,iso_numeric,fips,country,capital,area_in_sq_km,population,continent,tld,currency_code,currency_name,phone,postal_code_format,postal_code_regex,languages,geoname_id,neighbours,equivalent_fips_code) values ("); String concat = ""; int columnIndex = 0; for (String value : list) { sb.append(concat); if ( !value.isEmpty() ) { if ( columnIndex == 2 || columnIndex == 6 || columnIndex == 7 || columnIndex == 16 ) { sb.append(value); } else { sb.append('\'').append(escaped(value)).append('\''); } } else { sb.append("null"); } concat = ", "; ++columnIndex; } sb.append(") "); return sb.toString(); } private String escaped(String value) { return value.replaceAll("'", "''"); } } @Override protected RouteBuilder createRouteBuilder() throws Exception { return new RouteBuilder() { public void configure() { CsvDataFormat dataFormat = new CsvDataFormat(); dataFormat.setDelimiter("\t"); dataFormat.setSkipFirstLine(true); from("direct:countries") .setBody( simple("delete from country_info") ) .to("jdbc:dataSource") .setBody(simple("resource:classpath:/countryInfoStripped.txt") ) .unmarshal(dataFormat) .split().body() .bean( new CountryInfoToSQL() ) // .log("${body}") .to("jdbc:dataSource"); } }; } /* (non-Javadoc) * @see org.apache.camel.test.spring.CamelSpringTestSupport#createApplicationContext() */ @Override protected AbstractApplicationContext createApplicationContext() { return new ClassPathXmlApplicationContext("META-INF/spring/derby-context.xml"); } @Test public void testImportCountries() throws Exception { Object body = context.createProducerTemplate().requestBody("direct:countries","Bla"); } }
[ "ricardo.belfor@ecmdeveloper.com" ]
ricardo.belfor@ecmdeveloper.com
9a0f73528a2aebd42b1d4916d1f787db855331d4
59e577bf6f35ac4ea1f53bad4aad0223c37d39e5
/app/src/main/java/com/shail/auctionapp/apiclients/BaseClient.java
b2c700a2f2cac4ef4ecca669ba55bab4d32cb7c9
[]
no_license
shailendra-singh-dev/Auction
f09ded2ba402276d6ef14eb4d19abb3bcfacfc80
2ae94f2f3c32d35c9da84fbc5dd61df39e80fdce
refs/heads/master
2021-01-17T20:25:31.119761
2016-12-07T02:46:37
2016-12-07T02:46:37
63,622,903
0
0
null
null
null
null
UTF-8
Java
false
false
1,907
java
package com.shail.auctionapp.apiclients; import java.io.IOException; import okhttp3.Interceptor; import okhttp3.OkHttpClient; import okhttp3.Request; import okhttp3.Response; import retrofit2.Retrofit; import retrofit2.converter.gson.GsonConverterFactory; public class BaseClient { protected static Retrofit getRetrofit() { Session session = Session.getInstance(); Retrofit.Builder builder = new Retrofit.Builder() .baseUrl(session.ApiBaseURL) .addConverterFactory(GsonConverterFactory.create()) ; final String sessionKey = session.sessionKey; if ((sessionKey != null) && (sessionKey.length() > 0)) { OkHttpClient authHttpClient = new OkHttpClient.Builder() .addInterceptor( new Interceptor() { @Override public Response intercept(Chain chain) throws IOException { Request request = chain.request().newBuilder() .addHeader("Authorization", sessionKey) .build(); return chain.proceed(request); } } ) .build(); builder.client(authHttpClient); } return builder.build(); } protected static <T> T create(Class<T> service) { Retrofit retrofit = getRetrofit(); return retrofit.create(service); } protected static <T> T create(Class<T> service, String apiBaseURL) { Retrofit retrofit = new Retrofit.Builder() .baseUrl(apiBaseURL) .addConverterFactory(GsonConverterFactory.create()) .build() ; return retrofit.create(service); } }
[ "ssingh@itexico.net" ]
ssingh@itexico.net
8f48874b0673284135289bdb9bbffc67fb074044
40d844c1c780cf3618979626282cf59be833907f
/src/testcases/CWE190_Integer_Overflow/s06/CWE190_Integer_Overflow__int_PropertiesFile_postinc_71a.java
9864832b2d961034fd82705569bb5f832d2a879a
[]
no_license
rubengomez97/juliet
f9566de7be198921113658f904b521b6bca4d262
13debb7a1cc801977b9371b8cc1a313cd1de3a0e
refs/heads/master
2023-06-02T00:37:24.532638
2021-06-23T17:22:22
2021-06-23T17:22:22
379,676,259
1
0
null
null
null
null
UTF-8
Java
false
false
5,703
java
/* TEMPLATE GENERATED TESTCASE FILE Filename: CWE190_Integer_Overflow__int_PropertiesFile_postinc_71a.java Label Definition File: CWE190_Integer_Overflow__int.label.xml Template File: sources-sinks-71a.tmpl.java */ /* * @description * CWE: 190 Integer Overflow * BadSource: PropertiesFile Read data from a .properties file (in property named data) * GoodSource: A hardcoded non-zero, non-min, non-max, even number * Sinks: increment * GoodSink: Ensure there will not be an overflow before incrementing data * BadSink : Increment data, which can cause an overflow * Flow Variant: 71 Data flow: data passed as an Object reference argument from one method to another in different classes in the same package * * */ package testcases.CWE190_Integer_Overflow.s06; import testcasesupport.*; import javax.servlet.http.*; import java.util.Properties; import java.io.FileInputStream; import java.io.IOException; import java.util.logging.Level; public class CWE190_Integer_Overflow__int_PropertiesFile_postinc_71a extends AbstractTestCase { public void bad() throws Throwable { int data; data = Integer.MIN_VALUE; /* Initialize data */ /* retrieve the property */ { Properties properties = new Properties(); FileInputStream streamFileInput = null; try { streamFileInput = new FileInputStream("../common/config.properties"); properties.load(streamFileInput); /* POTENTIAL FLAW: Read data from a .properties file */ String stringNumber = properties.getProperty("data"); if (stringNumber != null) // avoid NPD incidental warnings { try { data = Integer.parseInt(stringNumber.trim()); } catch(NumberFormatException exceptNumberFormat) { IO.logger.log(Level.WARNING, "Number format exception parsing data from string", exceptNumberFormat); } } } catch (IOException exceptIO) { IO.logger.log(Level.WARNING, "Error with stream reading", exceptIO); } finally { /* Close stream reading object */ try { if (streamFileInput != null) { streamFileInput.close(); } } catch (IOException exceptIO) { IO.logger.log(Level.WARNING, "Error closing FileInputStream", exceptIO); } } } (new CWE190_Integer_Overflow__int_PropertiesFile_postinc_71b()).badSink((Object)data ); } public void good() throws Throwable { goodG2B(); goodB2G(); } /* goodG2B() - use goodsource and badsink */ private void goodG2B() throws Throwable { int data; /* FIX: Use a hardcoded number that won't cause underflow, overflow, divide by zero, or loss-of-precision issues */ data = 2; (new CWE190_Integer_Overflow__int_PropertiesFile_postinc_71b()).goodG2BSink((Object)data ); } /* goodB2G() - use badsource and goodsink */ private void goodB2G() throws Throwable { int data; data = Integer.MIN_VALUE; /* Initialize data */ /* retrieve the property */ { Properties properties = new Properties(); FileInputStream streamFileInput = null; try { streamFileInput = new FileInputStream("../common/config.properties"); properties.load(streamFileInput); /* POTENTIAL FLAW: Read data from a .properties file */ String stringNumber = properties.getProperty("data"); if (stringNumber != null) // avoid NPD incidental warnings { try { data = Integer.parseInt(stringNumber.trim()); } catch(NumberFormatException exceptNumberFormat) { IO.logger.log(Level.WARNING, "Number format exception parsing data from string", exceptNumberFormat); } } } catch (IOException exceptIO) { IO.logger.log(Level.WARNING, "Error with stream reading", exceptIO); } finally { /* Close stream reading object */ try { if (streamFileInput != null) { streamFileInput.close(); } } catch (IOException exceptIO) { IO.logger.log(Level.WARNING, "Error closing FileInputStream", exceptIO); } } } (new CWE190_Integer_Overflow__int_PropertiesFile_postinc_71b()).goodB2GSink((Object)data ); } /* Below is the main(). It is only used when building this testcase on * its own for testing or for building a binary to use in testing binary * analysis tools. It is not used when compiling all the testcases as one * application, which is how source code analysis tools are tested. */ public static void main(String[] args) throws ClassNotFoundException, InstantiationException, IllegalAccessException { mainFromParent(args); } }
[ "you@example.com" ]
you@example.com
0ecb52b7b8e9b4ec122993eb07c4c35425f9ab99
7b28e777989b3790fa1751c2acfcfa434cfbf444
/src/LocalSearchs/LocalSearchAlgorithms/HillClimbing/StochasticHC.java
67c319f696e4fd2f5d5b937ec77e6f8b5fb263da
[]
no_license
mahdiabdollahpour/Classical-and-Beyond-Clasical-search
7a205fbf9e1c0f67719eeb9df5735a34c2133bb7
830fb2bddbe3da15c640f8d7c7dc9f288cc7bf9a
refs/heads/master
2020-04-14T13:24:14.872577
2019-01-02T17:05:59
2019-01-02T17:05:59
163,867,604
2
0
null
null
null
null
UTF-8
Java
false
false
1,002
java
package LocalSearchs.LocalSearchAlgorithms.HillClimbing; import LocalSearchs.LocalSearchAlgorithms.HillClimbing.SimpleHC; import LocalSearchs.Problem; import LocalSearchs.State; import java.util.ArrayList; import java.util.Random; public class StochasticHC extends SimpleHC { public StochasticHC(Problem problem) { super(problem); } protected State chooseNode(ArrayList<State> neighbors, State now) { visitedStatesNumber += neighbors.size(); double nowVal = problem.stateValue(now); ArrayList<State> goodStates = new ArrayList<>(); for (int i = 0; i < neighbors.size(); i++) { double val = problem.stateValue(neighbors.get(i)); if (val > nowVal) { goodStates.add(neighbors.get(i)); } } if (goodStates.size() > 0) { return goodStates.get(new Random(System.currentTimeMillis()).nextInt(goodStates.size())); } else { return null; } } }
[ "mohammadmahdiabdollahpoor@gmail.com" ]
mohammadmahdiabdollahpoor@gmail.com
628be05dcdeee73e70bda47b6b6377a1119299a8
52abb3f9d6f5747ba9a7abeda455767f524a0898
/sp/src/main/java/com/sp/web/model/Token.java
2b11c9ad260b85ec9c601eb203c97e440d9733b4
[]
no_license
srayapatipolarits/ECSandCFN
251e474be9e76126bdd9244a480087eb9e28c039
1c16f7eebc6856afc47ad712fe7c1d160ffd3e84
refs/heads/master
2020-03-17T06:32:43.155453
2018-05-01T13:19:34
2018-05-01T13:19:34
133,360,061
1
0
null
2018-05-14T12:51:34
2018-05-14T12:51:34
null
UTF-8
Java
false
false
5,448
java
package com.sp.web.model; import java.io.Serializable; import java.util.HashMap; import java.util.Map; import java.util.Optional; /** * Token bean captures the token details which are stored in the respository. * * @author pruhil * */ public class Token implements Serializable { /** * Default Serial version Id. */ private static final long serialVersionUID = 1445884914586731414L; /** Mongo ID. */ private String id; /** token ID. */ private String tokenId; /** token processor. */ private TokenProcessorType tokenProcessorType; /** token type for which this token belongs. */ private TokenType tokenType; /** creation time for this doc. */ private long createdTime; /** tokenCountUsed. */ private int tokenUsedCount; /** params map. */ private Map<String, Object> paramsMap = new HashMap<String, Object>(); /** Token status. */ private TokenStatus tokenStatus; /** The token URL. */ private String tokenUrl; /** The cause for the token invalidation. */ private String invalidationCause; /** * The view to redirect the user to complete the transaction. */ private String redirectToView; private String themeKey; public String getTokenId() { return tokenId; } public void setTokenId(String tokenId) { this.tokenId = tokenId; } public TokenProcessorType getTokenProcessorType() { return tokenProcessorType; } public void setTokenProcessorType(TokenProcessorType tokenProcessorType) { this.tokenProcessorType = tokenProcessorType; } public TokenType getTokenType() { return tokenType; } public void setTokenType(TokenType tokenType) { this.tokenType = tokenType; } public long getCreatedTime() { return createdTime; } public void setCreatedTime(long createdTime) { this.createdTime = createdTime; } public int getTokenUsedCount() { return tokenUsedCount; } public void setTokenUsedCount(int tokenUsedCount) { this.tokenUsedCount = tokenUsedCount; } public Map<String, Object> getParamsMap() { return paramsMap; } public void setParamsMap(Map<String, Object> paramsMap) { this.paramsMap = paramsMap; } public TokenStatus getTokenStatus() { return tokenStatus; } public void setTokenStatus(TokenStatus tokenStatus) { this.tokenStatus = tokenStatus; } public String getId() { return id; } public void setId(String id) { this.id = id; } public String getTokenUrl() { return tokenUrl; } public void setTokenUrl(String tokenUrl) { this.tokenUrl = tokenUrl; } /** * Helper method to get the parameter from the parameter map. * * @param paramName * - parameter name * @return the value for the given parameter */ public Object getParam(String paramName) { return paramsMap.get(paramName); } /** * Get the parameter value or send default if none exists. * * @param paramName * - parameter name * @param defaultValue * - default value if parameter is not available * @return * the response to the get request */ public Object getParam(String paramName, Object defaultValue) { return Optional.ofNullable(getParam(paramName)).orElse(defaultValue); } public String getInvalidationCause() { return invalidationCause; } public void setInvalidationCause(String invalidationCause) { this.invalidationCause = invalidationCause; } /** * Invalidates the token and sets the invalidation cause for the token. * * @param invalidationClause * - invalidation clause */ public void invalidate(String invalidationClause) { tokenStatus = TokenStatus.INVALID; this.invalidationCause = invalidationClause; } /** * Invalidates the token and sets the invalidation cause for the token, along with the redirection * url. * * @param invalidationClause * - invalidation clause * @param redirectToView * - the view to redirect to on subsequent request */ public void invalidate(String invalidationClause, String redirectToView) { invalidate(invalidationClause); this.redirectToView = redirectToView; } /** * Helper method to check if the token is in validated state. * * @return true if the toke is valid */ public boolean isValid() { return (tokenStatus == TokenStatus.ENABLED); } public String getRedirectToView() { return redirectToView; } public void setRedirectToView(String redirectToView) { this.redirectToView = redirectToView; } /** * Helper method to get the parameter as a string. * * @param paramName * - the parameter name * @return the string value for the parameter */ public String getParamAsString(String paramName) { return (String) getParam(paramName); } /** * Helper method to add the given parameter to the params map. * * @param name * - parameter name * @param value * - value */ public void addParam(String name, Object value) { if (paramsMap == null) { paramsMap = new HashMap<String, Object>(); } paramsMap.put(name, value); } public void setThemeKey(String themeKey) { this.themeKey = themeKey; } public String getThemeKey() { return themeKey; } }
[ "root@ip-10-0-1-253.ec2.internal" ]
root@ip-10-0-1-253.ec2.internal
b11db1c8da27d45beb6467cab1cab50c44cc0499
b3da2f546827696d2fd287370b8752ae55c2d229
/ImageProcessing/src/Example5.java
49a40b0bf2428d3ffc6c9c71a03fd9b2f4e8e3fe
[]
no_license
ddobervich/APImageProcessingTutorial
24e8f868be054b35a01eaa2d6fd364ea789c9f62
b96e0430f3b2c6228c03bac49ce767f2d76ddd6b
refs/heads/master
2020-12-30T09:51:40.675505
2014-02-18T19:49:56
2014-02-18T19:49:56
null
0
0
null
null
null
null
UTF-8
Java
false
false
1,433
java
import processing.core.PApplet; import processing.core.PImage; public class Example5 extends PApplet { // Declaring a variable of type PImage PImage before, after; public void setup() { size(544, 408); // Make a before and after image. before = loadImage("../images/example.jpg"); after = createImage(before.width, before.height, RGB); before.loadPixels(); // load pixel array after.loadPixels(); for (int x = 0; x < before.width; x++) { // loop through every column for (int y = 0; y < before.height; y++) { // loop through every row int loc = x + y * before.width; // find the 1D pixel array // location int c = before.pixels[loc]; // load the pixel value double dist = colorDistance(c, color(183, 185, 102)); // Calculate color distance from yellow if (dist < 20) { after.pixels[loc] = color(255); // White } else { after.pixels[loc] = color(0); // Black } } } after.updatePixels(); before.updatePixels(); // store the changes } public double colorDistance(int c1, int c2) { float red_diff = red(c1) - red(c2); float green_diff = green(c1) - green(c2); float blue_diff = blue(c1) - blue(c2); return Math.sqrt(red_diff*red_diff + green_diff*green_diff + blue_diff*blue_diff); } public void draw() { background(0); if (keyPressed) { image(after, 0, 0); } else { image(before, 0, 0); } } }
[ "david.dobervich@gmail.com" ]
david.dobervich@gmail.com
564c6c8c23a46b761ac89e543ab1be39a5ae7cfc
29f508e730f2794341593ad18cf352990888c067
/src/com/sun/corba/se/pept/transport/OutboundConnectionCache.java
cc43d05bb2980e101d1e25b02fe8b7d77cd17eb8
[]
no_license
nhchanh/jdk1.6.0_21
daf40144acd19d92d15561235038e6e0343f8dec
cdcaafc11122944545c51efc49bb9f884b1ad0d1
refs/heads/master
2021-01-10T19:05:13.011208
2014-01-07T23:10:19
2014-01-07T23:10:19
null
0
0
null
null
null
null
UTF-8
Java
false
false
540
java
/* * @(#)OutboundConnectionCache.java 1.4 10/03/23 * * Copyright (c) 2006, Oracle and/or its affiliates. All rights reserved. * ORACLE PROPRIETARY/CONFIDENTIAL. Use is subject to license terms. */ package com.sun.corba.se.pept.transport; /** * @author Harold Carr */ public interface OutboundConnectionCache extends ConnectionCache { public Connection get(ContactInfo contactInfo); public void put(ContactInfo contactInfo, Connection connection); public void remove(ContactInfo contactInfo); } // End of file.
[ "chanh.nguyen@verint.com" ]
chanh.nguyen@verint.com
b8c03650137143ad1efd7228285eedc7bd76f0ba
c59efd4d2f18b2c7004f74239773ec03a395d1a1
/app/src/main/java/chua/cs/meetcoffeebagelteam/controller/ProfileDetailController.java
06a2258ce134463c86ce5f6849aa31ef1159f81b
[]
no_license
cschua/MeetCoffeeBagelTeam
b8d36befb3f423dbb8879e12e0cd055f58147eed
746d186bb0879847aa64303e92a33c546586d37b
refs/heads/master
2021-08-17T10:03:22.460822
2017-11-21T03:10:03
2017-11-21T03:10:03
111,492,125
0
0
null
null
null
null
UTF-8
Java
false
false
2,275
java
package chua.cs.meetcoffeebagelteam.controller; import android.content.Context; import android.view.View; import com.vstechlab.easyfonts.EasyFonts; import chua.cs.meetcoffeebagelteam.model.LocalProfile; import chua.cs.meetcoffeebagelteam.view.ProfileDetailView; /** * Created by christopherchua on 11/19/17. */ public class ProfileDetailController implements View.OnClickListener { private final ProfileDetailView profileDetailView; private LocalProfile localProfile; private OnClickBioListener onClickBioListener; public ProfileDetailController(final Context context, ProfileDetailView profileDetailView) { this.profileDetailView = profileDetailView; init(context); } @Override public void onClick(final View view) { if (onClickBioListener != null) { onClickBioListener.onClickBioView(view, localProfile); } } public void setOnClickBioListener(final OnClickBioListener onClickBioListener) { this.onClickBioListener = onClickBioListener; } private void init(final Context context) { // set font typeface for textviews profileDetailView.setFullNameTypeface(EasyFonts.caviarDreamsBold(context)); profileDetailView.setTitleTypeface(EasyFonts.caviarDreamsBoldItalic(context)); profileDetailView.setBioTypeface(EasyFonts.robotoRegular(context)); profileDetailView.setOnBioClickListener(this); } public void update(final LocalProfile localProfile) { this.localProfile = localProfile; profileDetailView.setFullName(localProfile.getFullName()); profileDetailView.setTitle(localProfile.getTitle()); profileDetailView.setBio(localProfile.getBio()); profileDetailView.setImage(localProfile.getAvatar()); profileDetailView.setVisibility(View.VISIBLE); } /** * @param viewVisibility View.VISIBLE, View.VISIBLE, View.GONE */ public void setVisibility(final int viewVisibility) { profileDetailView.setVisibility(viewVisibility); } public void onDestroy() { localProfile = null; onClickBioListener = null; } public interface OnClickBioListener { void onClickBioView(View view, LocalProfile localProfile); } }
[ "cschua@gmail.com" ]
cschua@gmail.com
3c0548af00b5796555cc4f199725dd7bb9055e05
9b83529924d1f2744b442cf588ea5c1fabc56956
/app/src/main/java/io/github/haohoangtran/kimyennew/MainActivity.java
62f0eb3175ce1dd2017f20b149316e7721cabbd3
[]
no_license
haohoangtran/TimerMusic
4388d6f735aa45df9e1205cc9df2ebc10b3973e5
c1c4079c0acf14c3fd96f7a9d5bb6a7f734b4dc7
refs/heads/master
2020-04-16T09:11:18.699720
2019-04-10T07:42:04
2019-04-10T07:42:04
165,454,382
1
0
null
null
null
null
UTF-8
Java
false
false
4,675
java
package io.github.haohoangtran.kimyennew; import android.Manifest; import android.content.Intent; import android.content.pm.PackageManager; import android.net.Uri; import android.os.Build; import android.os.Bundle; import android.support.annotation.NonNull; import android.support.design.widget.BottomNavigationView; import android.support.v4.app.ActivityCompat; import android.support.v4.app.Fragment; import android.support.v4.app.FragmentManager; import android.support.v4.app.FragmentTransaction; import android.support.v7.app.AppCompatActivity; import android.util.Log; import android.view.MenuItem; import android.widget.TextView; import android.widget.Toast; public class MainActivity extends AppCompatActivity { private FragmentManager fragmentManager; private String TAG = this.getClass().getSimpleName(); private BottomNavigationView.OnNavigationItemSelectedListener mOnNavigationItemSelectedListener = new BottomNavigationView.OnNavigationItemSelectedListener() { @Override public boolean onNavigationItemSelected(@NonNull MenuItem item) { FragmentTransaction transaction = fragmentManager.beginTransaction(); switch (item.getItemId()) { case R.id.navigation_home: transaction.replace(R.id.main_container, new MusicFragment()); transaction.addToBackStack(null); transaction.commit(); return true; case R.id.navigation_dashboard: transaction.replace(R.id.main_container, new ScheduleFragment()); transaction.addToBackStack(null); transaction.commit(); return true; } return false; } }; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); fragmentManager = getSupportFragmentManager(); BottomNavigationView navigation = (BottomNavigationView) findViewById(R.id.navigation); navigation.setOnNavigationItemSelectedListener(mOnNavigationItemSelectedListener); if (!checkPermissionForReadExtertalStorage()) { requestPermision(); } else { DbContext.getInstance().readMusicFile(); FragmentTransaction transaction = fragmentManager.beginTransaction(); transaction.replace(R.id.main_container, new MusicFragment()); transaction.addToBackStack(null); transaction.commit(); Log.e(TAG, "onCreate: " + DbContext.getInstance().getSchedules()); Intent intent = new Intent(this, MusicServiceV2.class); startService(intent); } } private void requestPermision() { ActivityCompat.requestPermissions(MainActivity.this, new String[]{Manifest.permission.READ_EXTERNAL_STORAGE, Manifest.permission.WRITE_EXTERNAL_STORAGE}, 6969); } public boolean checkPermissionForReadExtertalStorage() { if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) { int result = this.checkSelfPermission(Manifest.permission.READ_EXTERNAL_STORAGE); return result == PackageManager.PERMISSION_GRANTED; } return false; } @Override public void onRequestPermissionsResult(int requestCode, String permissions[], int[] grantResults) { switch (requestCode) { case 6969: { FragmentTransaction transaction = fragmentManager.beginTransaction(); transaction.replace(R.id.main_container, new MusicFragment()); transaction.addToBackStack(null); transaction.commit(); // If request is cancelled, the result arrays are empty. if (grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED) { DbContext.getInstance().readMusicFile(); Intent intent = new Intent(this, MusicServiceV2.class); startService(intent); } else { // permission denied, boo! Disable the // functionality that depends on this permission. Toast.makeText(MainActivity.this, "Permission denied to read your External storage", Toast.LENGTH_SHORT).show(); } return; } // other 'case' lines to check for other // permissions this app might request } } }
[ "tranhaockpt@gmail.com" ]
tranhaockpt@gmail.com
245fcabbb7041b6a9d81f5ab96990c8c878d2fa9
48c53d391d13a4a802e72061d61354b9172f7e2d
/app/src/main/java/edu/sjsu/mathquiz/fragment/NumberPadFragment.java
cd80a133046b8975c4251d768bbc0a801f1d016f
[]
no_license
kamlendrachauhan/MathQuiz
7381958dd9398ae9e65999789bdcca2a50d2039d
78fbf2101d05bcd405e12fb49584d19747a597b6
refs/heads/master
2021-01-10T22:57:59.653501
2016-10-09T23:43:49
2016-10-09T23:43:49
70,436,851
0
0
null
null
null
null
UTF-8
Java
false
false
632
java
package edu.sjsu.mathquiz.fragment; import android.os.Bundle; import android.support.annotation.Nullable; import android.support.v4.app.Fragment; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import edu.sjsu.mathquiz.R; /** * Created by I074841 on 10/7/2016. */ public class NumberPadFragment extends Fragment { @Nullable @Override public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { View view = inflater.inflate(R.layout.fragment_numberpad, container, false); return view; } }
[ "noreply@github.com" ]
noreply@github.com
257fe433407a98976f311d0532b9637df141c8bb
828332d156d3289fc9cfdf5b7280fef22d1847ea
/autoupdatetable-mybatis-tkmapper/src/main/java/com/github/gonglb/tools/autoupdatetable/mapper/CreateMysqlTablesMapper.java
cae281c45d891867a8a512054d0cd2dc764850f2
[]
no_license
lixianglong3210/auto-update-table
b61fead069144dd61245fd751bbdb32d70a35fda
9cc07409eb6f7716766453e1b740e915d647754f
refs/heads/master
2020-05-09T21:52:55.597881
2018-05-23T08:40:42
2018-05-23T08:40:42
null
0
0
null
null
null
null
UTF-8
Java
false
false
2,249
java
package com.github.gonglb.tools.autoupdatetable.mapper; import java.util.List; import java.util.Map; import org.apache.ibatis.annotations.Param; import com.github.gonglb.tools.autoupdatetable.model.SysMysqlColumns; import tk.mybatis.mapper.common.Mapper; /** * 创建更新表结构的Mapper * @author gonglb * 2018年5月11日 下午2:48:53 */ public interface CreateMysqlTablesMapper extends Mapper<SysMysqlColumns>{ /** * 根据结构注解解析出来的信息创建表 * @param tableMap 表结构的map */ public void createTable(@Param("tableMap") Map<String, List<Object>> tableMap); /** * 根据表名查询表在库中是否存在,存在返回1,不存在返回0 * @param tableName 表结构的map * @return 存在返回1,不存在返回0 */ public int findTableCountByTableName(@Param("tableName") String tableName); /** * 根据表名查询库中该表的字段结构等信息 * @param tableName 表结构的map * @return 表的字段结构等信息 */ public List<SysMysqlColumns> findTableEnsembleByTableName(@Param("tableName") String tableName); /** * 增加字段 * @param tableMap 表结构的map */ public void addTableField(@Param("tableMap") Map<String, Object> tableMap); /** * 删除字段 * @param tableMap 表结构的map */ public void removeTableField(@Param("tableMap") Map<String, Object> tableMap); /** * 修改字段 * @param tableMap 表结构的map */ public void modifyTableField(@Param("tableMap") Map<String, Object> tableMap); /** * 删除主键约束,附带修改其他字段属性功能 * @param tableMap 表结构的map */ public void dropKeyTableField(@Param("tableMap") Map<String, Object> tableMap); /** * 删除唯一约束字段,不带修改其他字段属性的功能 * @param tableMap 表结构的map */ public void dropUniqueTableField(@Param("tableMap") Map<String, Object> tableMap); /** * 根据表名删除表 * @param tableName 表结构的map */ public void dorpTableByName(@Param("tableName") String tableName); /** * 根据表名获取sql * @param tableName 表名 * @return 获取创建表的sql */ public String getSqlByTableName(@Param("tableName") String tableName); }
[ "apple@appledemacbook.lan" ]
apple@appledemacbook.lan
410853fbdfc8fcdf0be0c82872ad379daeec0b48
ae0721336d382f91ec1bd4be91a37e30ff482364
/src/br/com/furb/comp/tela/FiltroArquivoCompilador.java
465f9c54c2171f4eceb79eb7dd01a887ac203c99
[]
no_license
aguilasa/compiladores_201301
6457f4fcccff6488e32d85cfc1e9e7d79dff048c
532cc79139de4af2b41dd54b86a5d328c3a5b037
refs/heads/master
2021-01-23T12:10:05.156451
2013-07-01T01:56:08
2013-07-01T01:56:08
null
0
0
null
null
null
null
UTF-8
Java
false
false
2,241
java
package br.com.furb.comp.tela; import java.io.File; import java.util.Locale; import javax.swing.filechooser.FileFilter; public class FiltroArquivoCompilador extends FileFilter { private final String description; private final String[] extensions; private final String[] lowerCaseExtensions; public FiltroArquivoCompilador() { this.description = "Arquivos ING"; this.extensions = new String[] { "ing" }; this.lowerCaseExtensions = new String[this.extensions.length]; for (int i = 0; i < this.extensions.length; i++) { this.lowerCaseExtensions[i] = this.extensions[i].toLowerCase(Locale.ENGLISH); } } public FiltroArquivoCompilador(String description, String... extensions) { if (extensions == null || extensions.length == 0) { throw new IllegalArgumentException("Extensions must be non-null and not empty"); } this.description = description; this.extensions = new String[extensions.length]; this.lowerCaseExtensions = new String[extensions.length]; for (int i = 0; i < extensions.length; i++) { if (extensions[i] == null || extensions[i].length() == 0) { throw new IllegalArgumentException("Each extension must be non-null and not empty"); } this.extensions[i] = extensions[i]; lowerCaseExtensions[i] = extensions[i].toLowerCase(Locale.ENGLISH); } } public boolean accept(File f) { if (f != null) { if (f.isDirectory()) { return true; } String fileName = f.getName(); int i = fileName.lastIndexOf('.'); if (i > 0 && i < fileName.length() - 1) { String desiredExtension = fileName.substring(i + 1).toLowerCase(Locale.ENGLISH); for (String extension : lowerCaseExtensions) { if (desiredExtension.equals(extension)) { return true; } } } } return false; } public String getDescription() { return description; } public String[] getExtensions() { String[] result = new String[extensions.length]; System.arraycopy(extensions, 0, result, 0, extensions.length); return result; } public String toString() { return super.toString() + "[description=" + getDescription() + " extensions=" + java.util.Arrays.asList(getExtensions()) + "]"; } }
[ "ingmar.aguiar@gmail.com" ]
ingmar.aguiar@gmail.com
278daaa3804feba23ece1b4d0eb188539867ae83
c624dc1ab334ca673c2c141694d01937fcb71ccb
/src/main/java/com/chenhai/educationsystem/vo/IdentityResult.java
c1096136d59d60da2947339aec0f273259195aaa
[]
no_license
shenzhiqiang1997/education-system
12a4ad1538fde7c4414749e4bb23b6698c37cf88
f13e51ecea76cf3a5bf820637605f5799c5b1889
refs/heads/master
2020-03-12T10:53:27.438916
2018-06-19T10:09:34
2018-06-19T10:09:34
130,583,545
0
0
null
null
null
null
UTF-8
Java
false
false
506
java
package com.chenhai.educationsystem.vo; public class IdentityResult { private String flag = "true"; private String identity; public IdentityResult(String identity) { this.identity = identity; } public String getFlag() { return flag; } public void setFlag(String flag) { this.flag = flag; } public String getIdentity() { return identity; } public void setIdentity(String identity) { this.identity = identity; } }
[ "1422537078@qq.com" ]
1422537078@qq.com
4a28990f93c3036a4adb2a8f1a546b57cb4c274d
cab1db71573791f2a34f5733a75ab33c93453d12
/src/com/zx/interceptor/LoginIninterceptor.java
28035b5c303d0ccb8db80f5bea494cc0b0b94724
[]
no_license
dyj2275986967/shopApp
fe73339db4d0e0f8480998056c1c9604ec2fa1e8
fa036114392e4deeef7cfb59565d2071d305ca23
refs/heads/master
2020-09-08T18:51:11.681837
2019-11-13T05:17:51
2019-11-13T05:17:51
221,215,098
2
0
null
null
null
null
GB18030
Java
false
false
775
java
package com.zx.interceptor; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import org.springframework.web.servlet.handler.HandlerInterceptorAdapter; import com.zx.vo.UserVo; public class LoginIninterceptor extends HandlerInterceptorAdapter { @Override public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception { UserVo user=(UserVo)request.getSession().getAttribute("userVo"); if (user!=null) { //放行 return true; } //重定向到登录页面 request.setAttribute("msg", "*请先登录"); request.getRequestDispatcher("/user/login").forward(request, response); return false; } }
[ "1009730494@qq.com" ]
1009730494@qq.com
0e4920b054660b96428b383fb4aa77dbc2d14a9b
6e2fefbce1e9172e6e79648d6053b40543b4065c
/src/main/java/org/backend/DTOs/WishListErrorDTO.java
5d1f448fb0a6c5f7e5c3c322745e2db7aa058f75
[]
no_license
tankudo/HikeMasterBackend
261add1aef78f1d89faa9029126c1b41f67b9894
4b21f6dad21f3b431be06fdc98a3ee559ff4f534
refs/heads/master
2023-01-04T02:49:30.906450
2020-11-02T16:38:33
2020-11-02T16:38:33
286,024,189
0
0
null
2020-08-08T10:45:28
2020-08-08T10:45:28
null
UTF-8
Java
false
false
144
java
package org.backend.DTOs; public class WishListErrorDTO extends ResponseDTO{ public WishListErrorDTO() { success = false; } }
[ "kbsz991@gmail.com" ]
kbsz991@gmail.com
fd8616a174133b7e651511ff1a3ac75b19f4cb70
ecd7340cadfd8d7c1b397944765544510b0bde20
/HelpMeRESTApplication/src/main/java/rvo/helpmerestapplication/rest/RestApplication.java
ac1bc7c5a311ced912ff4e612e0107c3cfdd9799
[]
no_license
voicurobert/JavaProjects
c26ec19532a504fa7e590f91e241bbc496bbcfa2
cc792b374f5e461135826f88bfec726c1ce0e8eb
refs/heads/master
2023-01-11T06:28:05.636484
2020-11-10T07:20:51
2020-11-10T07:20:51
237,036,237
1
0
null
null
null
null
UTF-8
Java
false
false
411
java
/* * 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 rvo.helpmerestapplication.rest; import javax.ws.rs.ApplicationPath; import javax.ws.rs.core.Application; /** * * @author Robert */ @ApplicationPath("api") public class RestApplication extends Application{ }
[ "voicu.eduardrobert@gmail.com" ]
voicu.eduardrobert@gmail.com
199a84df1cbd62f4426382abbd3828e4441cda58
2914682f0f01839a72fdd38be25816244cd30f24
/java/sintaxe-variaveis-e-fluxo/src/testeIR.java
d3b12e32ac992bae11898988bb7fa76b10d88a7c
[]
no_license
ju81br/others
aca91beba36755c97bce388c4031246df4370e10
15e70421763e4bd68fb3276002528ba198759d26
refs/heads/master
2021-02-27T23:14:18.123679
2020-04-16T11:34:15
2020-04-16T11:34:15
245,643,405
0
0
null
null
null
null
ISO-8859-1
Java
false
false
787
java
public class testeIR { public static void main(String[] args) { double salario = 3300.0; double salarioAno = salario * 12; System.out.println("Salário mensal: " + salario); System.out.println("Salário anual: " + salarioAno); if (1900.0 < salario && salario < 2800.0){ System.out.println("Primeira faixa. Dedução de 7,5%"); } else if (2801.0 < salario && salario < 3751.0){ System.out.println("Segunda faixa. Dedução de 15%"); } else if (3751.0 < salario && salario < 4664.0){ System.out.println("Terceira faixa. Dedução de 22,5%"); } else { System.out.println("Salário anual não está em nenhuma das 3 faixas"); } } }
[ "ju81br@gmail.com" ]
ju81br@gmail.com
f5f5e7939053be3139f9fd284f2b7a2baae99d72
701231448fbfb31d50d5d9a4f416c27ddbb67e72
/src/main/java/com/codecool/web/model/Poem.java
43557b4ef102b36e467970505fbf874f3af5e71c
[]
no_license
adamKonyari/Ajax_Poets
351b64fba498961305271e82fa908e21465984f9
6f41056f066404b35f31171a393405c8c6a03041
refs/heads/master
2022-12-09T15:17:07.074177
2019-06-27T09:25:55
2019-06-27T09:25:55
187,490,311
0
0
null
2022-11-16T12:23:19
2019-05-19T14:54:09
Java
UTF-8
Java
false
false
523
java
package com.codecool.web.model; public class Poem extends AbstractModel { private String title; private String content; private int poetId; public Poem(int id, String title, String content, int poetId) { super(id); this.title = title; this.content = content; this.poetId = poetId; } public String getTitle() { return title; } public String getContent() { return content; } public int getPoetId() { return poetId; } }
[ "adam.konyari@gmail.com" ]
adam.konyari@gmail.com
c53b09e8b16d37de72e7883273c2d993ac0fb4ab
5699c0786384cf3372edb927bfde58fdb5128fc5
/src/main/java/me/amplitudo/inventar/security/SecurityUtils.java
a8cfd7f0559fe9ffd80280a193680696d9fda6f0
[]
no_license
LukaMugosa/Inventar
dc3762375df57eedd91cb9b98b73fba65d1c9465
57d86cefae0d9a8dcfce55acc3d3722c587c61fb
refs/heads/master
2023-04-26T20:18:30.402870
2021-04-17T22:09:18
2021-04-17T22:09:18
358,985,635
0
0
null
null
null
null
UTF-8
Java
false
false
3,117
java
package me.amplitudo.inventar.security; import org.springframework.security.core.Authentication; import org.springframework.security.core.GrantedAuthority; import org.springframework.security.core.context.SecurityContext; import org.springframework.security.core.context.SecurityContextHolder; import org.springframework.security.core.userdetails.UserDetails; import java.util.Optional; import java.util.stream.Stream; /** * Utility class for Spring Security. */ public final class SecurityUtils { private SecurityUtils() { } /** * Get the login of the current user. * * @return the login of the current user. */ public static Optional<String> getCurrentUserLogin() { SecurityContext securityContext = SecurityContextHolder.getContext(); return Optional.ofNullable(extractPrincipal(securityContext.getAuthentication())); } private static String extractPrincipal(Authentication authentication) { if (authentication == null) { return null; } else if (authentication.getPrincipal() instanceof UserDetails) { UserDetails springSecurityUser = (UserDetails) authentication.getPrincipal(); return springSecurityUser.getUsername(); } else if (authentication.getPrincipal() instanceof String) { return (String) authentication.getPrincipal(); } return null; } /** * Get the JWT of the current user. * * @return the JWT of the current user. */ public static Optional<String> getCurrentUserJWT() { SecurityContext securityContext = SecurityContextHolder.getContext(); return Optional.ofNullable(securityContext.getAuthentication()) .filter(authentication -> authentication.getCredentials() instanceof String) .map(authentication -> (String) authentication.getCredentials()); } /** * Check if a user is authenticated. * * @return true if the user is authenticated, false otherwise. */ public static boolean isAuthenticated() { Authentication authentication = SecurityContextHolder.getContext().getAuthentication(); return authentication != null && getAuthorities(authentication).noneMatch(AuthoritiesConstants.ANONYMOUS::equals); } /** * If the current user has a specific authority (security role). * <p> * The name of this method comes from the {@code isUserInRole()} method in the Servlet API. * * @param authority the authority to check. * @return true if the current user has the authority, false otherwise. */ public static boolean isCurrentUserInRole(String authority) { Authentication authentication = SecurityContextHolder.getContext().getAuthentication(); return authentication != null && getAuthorities(authentication).anyMatch(authority::equals); } private static Stream<String> getAuthorities(Authentication authentication) { return authentication.getAuthorities().stream() .map(GrantedAuthority::getAuthority); } }
[ "lukamugosa1945@gmail.com" ]
lukamugosa1945@gmail.com
3c6afe21db9e0a604803b0df6e54e1c2f5c49253
b9648eb0f0475e4a234e5d956925ff9aa8c34552
/google-ads-stubs-v8/src/main/java/com/google/ads/googleads/v8/services/KeywordPlanServiceGrpc.java
e1b935b817b243322dbf2f7e321068d24980286e
[ "Apache-2.0" ]
permissive
wfansh/google-ads-java
ce977abd611d1ee6d6a38b7b3032646d5ffb0b12
7dda56bed67a9e47391e199940bb8e1568844875
refs/heads/main
2022-05-22T23:45:55.238928
2022-03-03T14:23:07
2022-03-03T14:23:07
460,746,933
0
0
Apache-2.0
2022-02-18T07:08:46
2022-02-18T07:08:45
null
UTF-8
Java
false
false
46,253
java
package com.google.ads.googleads.v8.services; import static io.grpc.MethodDescriptor.generateFullMethodName; /** * <pre> * Service to manage keyword plans. * </pre> */ @javax.annotation.Generated( value = "by gRPC proto compiler", comments = "Source: google/ads/googleads/v8/services/keyword_plan_service.proto") @io.grpc.stub.annotations.GrpcGenerated public final class KeywordPlanServiceGrpc { private KeywordPlanServiceGrpc() {} public static final String SERVICE_NAME = "google.ads.googleads.v8.services.KeywordPlanService"; // Static method descriptors that strictly reflect the proto. private static volatile io.grpc.MethodDescriptor<com.google.ads.googleads.v8.services.GetKeywordPlanRequest, com.google.ads.googleads.v8.resources.KeywordPlan> getGetKeywordPlanMethod; @io.grpc.stub.annotations.RpcMethod( fullMethodName = SERVICE_NAME + '/' + "GetKeywordPlan", requestType = com.google.ads.googleads.v8.services.GetKeywordPlanRequest.class, responseType = com.google.ads.googleads.v8.resources.KeywordPlan.class, methodType = io.grpc.MethodDescriptor.MethodType.UNARY) public static io.grpc.MethodDescriptor<com.google.ads.googleads.v8.services.GetKeywordPlanRequest, com.google.ads.googleads.v8.resources.KeywordPlan> getGetKeywordPlanMethod() { io.grpc.MethodDescriptor<com.google.ads.googleads.v8.services.GetKeywordPlanRequest, com.google.ads.googleads.v8.resources.KeywordPlan> getGetKeywordPlanMethod; if ((getGetKeywordPlanMethod = KeywordPlanServiceGrpc.getGetKeywordPlanMethod) == null) { synchronized (KeywordPlanServiceGrpc.class) { if ((getGetKeywordPlanMethod = KeywordPlanServiceGrpc.getGetKeywordPlanMethod) == null) { KeywordPlanServiceGrpc.getGetKeywordPlanMethod = getGetKeywordPlanMethod = io.grpc.MethodDescriptor.<com.google.ads.googleads.v8.services.GetKeywordPlanRequest, com.google.ads.googleads.v8.resources.KeywordPlan>newBuilder() .setType(io.grpc.MethodDescriptor.MethodType.UNARY) .setFullMethodName(generateFullMethodName(SERVICE_NAME, "GetKeywordPlan")) .setSampledToLocalTracing(true) .setRequestMarshaller(io.grpc.protobuf.ProtoUtils.marshaller( com.google.ads.googleads.v8.services.GetKeywordPlanRequest.getDefaultInstance())) .setResponseMarshaller(io.grpc.protobuf.ProtoUtils.marshaller( com.google.ads.googleads.v8.resources.KeywordPlan.getDefaultInstance())) .setSchemaDescriptor(new KeywordPlanServiceMethodDescriptorSupplier("GetKeywordPlan")) .build(); } } } return getGetKeywordPlanMethod; } private static volatile io.grpc.MethodDescriptor<com.google.ads.googleads.v8.services.MutateKeywordPlansRequest, com.google.ads.googleads.v8.services.MutateKeywordPlansResponse> getMutateKeywordPlansMethod; @io.grpc.stub.annotations.RpcMethod( fullMethodName = SERVICE_NAME + '/' + "MutateKeywordPlans", requestType = com.google.ads.googleads.v8.services.MutateKeywordPlansRequest.class, responseType = com.google.ads.googleads.v8.services.MutateKeywordPlansResponse.class, methodType = io.grpc.MethodDescriptor.MethodType.UNARY) public static io.grpc.MethodDescriptor<com.google.ads.googleads.v8.services.MutateKeywordPlansRequest, com.google.ads.googleads.v8.services.MutateKeywordPlansResponse> getMutateKeywordPlansMethod() { io.grpc.MethodDescriptor<com.google.ads.googleads.v8.services.MutateKeywordPlansRequest, com.google.ads.googleads.v8.services.MutateKeywordPlansResponse> getMutateKeywordPlansMethod; if ((getMutateKeywordPlansMethod = KeywordPlanServiceGrpc.getMutateKeywordPlansMethod) == null) { synchronized (KeywordPlanServiceGrpc.class) { if ((getMutateKeywordPlansMethod = KeywordPlanServiceGrpc.getMutateKeywordPlansMethod) == null) { KeywordPlanServiceGrpc.getMutateKeywordPlansMethod = getMutateKeywordPlansMethod = io.grpc.MethodDescriptor.<com.google.ads.googleads.v8.services.MutateKeywordPlansRequest, com.google.ads.googleads.v8.services.MutateKeywordPlansResponse>newBuilder() .setType(io.grpc.MethodDescriptor.MethodType.UNARY) .setFullMethodName(generateFullMethodName(SERVICE_NAME, "MutateKeywordPlans")) .setSampledToLocalTracing(true) .setRequestMarshaller(io.grpc.protobuf.ProtoUtils.marshaller( com.google.ads.googleads.v8.services.MutateKeywordPlansRequest.getDefaultInstance())) .setResponseMarshaller(io.grpc.protobuf.ProtoUtils.marshaller( com.google.ads.googleads.v8.services.MutateKeywordPlansResponse.getDefaultInstance())) .setSchemaDescriptor(new KeywordPlanServiceMethodDescriptorSupplier("MutateKeywordPlans")) .build(); } } } return getMutateKeywordPlansMethod; } private static volatile io.grpc.MethodDescriptor<com.google.ads.googleads.v8.services.GenerateForecastCurveRequest, com.google.ads.googleads.v8.services.GenerateForecastCurveResponse> getGenerateForecastCurveMethod; @io.grpc.stub.annotations.RpcMethod( fullMethodName = SERVICE_NAME + '/' + "GenerateForecastCurve", requestType = com.google.ads.googleads.v8.services.GenerateForecastCurveRequest.class, responseType = com.google.ads.googleads.v8.services.GenerateForecastCurveResponse.class, methodType = io.grpc.MethodDescriptor.MethodType.UNARY) public static io.grpc.MethodDescriptor<com.google.ads.googleads.v8.services.GenerateForecastCurveRequest, com.google.ads.googleads.v8.services.GenerateForecastCurveResponse> getGenerateForecastCurveMethod() { io.grpc.MethodDescriptor<com.google.ads.googleads.v8.services.GenerateForecastCurveRequest, com.google.ads.googleads.v8.services.GenerateForecastCurveResponse> getGenerateForecastCurveMethod; if ((getGenerateForecastCurveMethod = KeywordPlanServiceGrpc.getGenerateForecastCurveMethod) == null) { synchronized (KeywordPlanServiceGrpc.class) { if ((getGenerateForecastCurveMethod = KeywordPlanServiceGrpc.getGenerateForecastCurveMethod) == null) { KeywordPlanServiceGrpc.getGenerateForecastCurveMethod = getGenerateForecastCurveMethod = io.grpc.MethodDescriptor.<com.google.ads.googleads.v8.services.GenerateForecastCurveRequest, com.google.ads.googleads.v8.services.GenerateForecastCurveResponse>newBuilder() .setType(io.grpc.MethodDescriptor.MethodType.UNARY) .setFullMethodName(generateFullMethodName(SERVICE_NAME, "GenerateForecastCurve")) .setSampledToLocalTracing(true) .setRequestMarshaller(io.grpc.protobuf.ProtoUtils.marshaller( com.google.ads.googleads.v8.services.GenerateForecastCurveRequest.getDefaultInstance())) .setResponseMarshaller(io.grpc.protobuf.ProtoUtils.marshaller( com.google.ads.googleads.v8.services.GenerateForecastCurveResponse.getDefaultInstance())) .setSchemaDescriptor(new KeywordPlanServiceMethodDescriptorSupplier("GenerateForecastCurve")) .build(); } } } return getGenerateForecastCurveMethod; } private static volatile io.grpc.MethodDescriptor<com.google.ads.googleads.v8.services.GenerateForecastTimeSeriesRequest, com.google.ads.googleads.v8.services.GenerateForecastTimeSeriesResponse> getGenerateForecastTimeSeriesMethod; @io.grpc.stub.annotations.RpcMethod( fullMethodName = SERVICE_NAME + '/' + "GenerateForecastTimeSeries", requestType = com.google.ads.googleads.v8.services.GenerateForecastTimeSeriesRequest.class, responseType = com.google.ads.googleads.v8.services.GenerateForecastTimeSeriesResponse.class, methodType = io.grpc.MethodDescriptor.MethodType.UNARY) public static io.grpc.MethodDescriptor<com.google.ads.googleads.v8.services.GenerateForecastTimeSeriesRequest, com.google.ads.googleads.v8.services.GenerateForecastTimeSeriesResponse> getGenerateForecastTimeSeriesMethod() { io.grpc.MethodDescriptor<com.google.ads.googleads.v8.services.GenerateForecastTimeSeriesRequest, com.google.ads.googleads.v8.services.GenerateForecastTimeSeriesResponse> getGenerateForecastTimeSeriesMethod; if ((getGenerateForecastTimeSeriesMethod = KeywordPlanServiceGrpc.getGenerateForecastTimeSeriesMethod) == null) { synchronized (KeywordPlanServiceGrpc.class) { if ((getGenerateForecastTimeSeriesMethod = KeywordPlanServiceGrpc.getGenerateForecastTimeSeriesMethod) == null) { KeywordPlanServiceGrpc.getGenerateForecastTimeSeriesMethod = getGenerateForecastTimeSeriesMethod = io.grpc.MethodDescriptor.<com.google.ads.googleads.v8.services.GenerateForecastTimeSeriesRequest, com.google.ads.googleads.v8.services.GenerateForecastTimeSeriesResponse>newBuilder() .setType(io.grpc.MethodDescriptor.MethodType.UNARY) .setFullMethodName(generateFullMethodName(SERVICE_NAME, "GenerateForecastTimeSeries")) .setSampledToLocalTracing(true) .setRequestMarshaller(io.grpc.protobuf.ProtoUtils.marshaller( com.google.ads.googleads.v8.services.GenerateForecastTimeSeriesRequest.getDefaultInstance())) .setResponseMarshaller(io.grpc.protobuf.ProtoUtils.marshaller( com.google.ads.googleads.v8.services.GenerateForecastTimeSeriesResponse.getDefaultInstance())) .setSchemaDescriptor(new KeywordPlanServiceMethodDescriptorSupplier("GenerateForecastTimeSeries")) .build(); } } } return getGenerateForecastTimeSeriesMethod; } private static volatile io.grpc.MethodDescriptor<com.google.ads.googleads.v8.services.GenerateForecastMetricsRequest, com.google.ads.googleads.v8.services.GenerateForecastMetricsResponse> getGenerateForecastMetricsMethod; @io.grpc.stub.annotations.RpcMethod( fullMethodName = SERVICE_NAME + '/' + "GenerateForecastMetrics", requestType = com.google.ads.googleads.v8.services.GenerateForecastMetricsRequest.class, responseType = com.google.ads.googleads.v8.services.GenerateForecastMetricsResponse.class, methodType = io.grpc.MethodDescriptor.MethodType.UNARY) public static io.grpc.MethodDescriptor<com.google.ads.googleads.v8.services.GenerateForecastMetricsRequest, com.google.ads.googleads.v8.services.GenerateForecastMetricsResponse> getGenerateForecastMetricsMethod() { io.grpc.MethodDescriptor<com.google.ads.googleads.v8.services.GenerateForecastMetricsRequest, com.google.ads.googleads.v8.services.GenerateForecastMetricsResponse> getGenerateForecastMetricsMethod; if ((getGenerateForecastMetricsMethod = KeywordPlanServiceGrpc.getGenerateForecastMetricsMethod) == null) { synchronized (KeywordPlanServiceGrpc.class) { if ((getGenerateForecastMetricsMethod = KeywordPlanServiceGrpc.getGenerateForecastMetricsMethod) == null) { KeywordPlanServiceGrpc.getGenerateForecastMetricsMethod = getGenerateForecastMetricsMethod = io.grpc.MethodDescriptor.<com.google.ads.googleads.v8.services.GenerateForecastMetricsRequest, com.google.ads.googleads.v8.services.GenerateForecastMetricsResponse>newBuilder() .setType(io.grpc.MethodDescriptor.MethodType.UNARY) .setFullMethodName(generateFullMethodName(SERVICE_NAME, "GenerateForecastMetrics")) .setSampledToLocalTracing(true) .setRequestMarshaller(io.grpc.protobuf.ProtoUtils.marshaller( com.google.ads.googleads.v8.services.GenerateForecastMetricsRequest.getDefaultInstance())) .setResponseMarshaller(io.grpc.protobuf.ProtoUtils.marshaller( com.google.ads.googleads.v8.services.GenerateForecastMetricsResponse.getDefaultInstance())) .setSchemaDescriptor(new KeywordPlanServiceMethodDescriptorSupplier("GenerateForecastMetrics")) .build(); } } } return getGenerateForecastMetricsMethod; } private static volatile io.grpc.MethodDescriptor<com.google.ads.googleads.v8.services.GenerateHistoricalMetricsRequest, com.google.ads.googleads.v8.services.GenerateHistoricalMetricsResponse> getGenerateHistoricalMetricsMethod; @io.grpc.stub.annotations.RpcMethod( fullMethodName = SERVICE_NAME + '/' + "GenerateHistoricalMetrics", requestType = com.google.ads.googleads.v8.services.GenerateHistoricalMetricsRequest.class, responseType = com.google.ads.googleads.v8.services.GenerateHistoricalMetricsResponse.class, methodType = io.grpc.MethodDescriptor.MethodType.UNARY) public static io.grpc.MethodDescriptor<com.google.ads.googleads.v8.services.GenerateHistoricalMetricsRequest, com.google.ads.googleads.v8.services.GenerateHistoricalMetricsResponse> getGenerateHistoricalMetricsMethod() { io.grpc.MethodDescriptor<com.google.ads.googleads.v8.services.GenerateHistoricalMetricsRequest, com.google.ads.googleads.v8.services.GenerateHistoricalMetricsResponse> getGenerateHistoricalMetricsMethod; if ((getGenerateHistoricalMetricsMethod = KeywordPlanServiceGrpc.getGenerateHistoricalMetricsMethod) == null) { synchronized (KeywordPlanServiceGrpc.class) { if ((getGenerateHistoricalMetricsMethod = KeywordPlanServiceGrpc.getGenerateHistoricalMetricsMethod) == null) { KeywordPlanServiceGrpc.getGenerateHistoricalMetricsMethod = getGenerateHistoricalMetricsMethod = io.grpc.MethodDescriptor.<com.google.ads.googleads.v8.services.GenerateHistoricalMetricsRequest, com.google.ads.googleads.v8.services.GenerateHistoricalMetricsResponse>newBuilder() .setType(io.grpc.MethodDescriptor.MethodType.UNARY) .setFullMethodName(generateFullMethodName(SERVICE_NAME, "GenerateHistoricalMetrics")) .setSampledToLocalTracing(true) .setRequestMarshaller(io.grpc.protobuf.ProtoUtils.marshaller( com.google.ads.googleads.v8.services.GenerateHistoricalMetricsRequest.getDefaultInstance())) .setResponseMarshaller(io.grpc.protobuf.ProtoUtils.marshaller( com.google.ads.googleads.v8.services.GenerateHistoricalMetricsResponse.getDefaultInstance())) .setSchemaDescriptor(new KeywordPlanServiceMethodDescriptorSupplier("GenerateHistoricalMetrics")) .build(); } } } return getGenerateHistoricalMetricsMethod; } /** * Creates a new async stub that supports all call types for the service */ public static KeywordPlanServiceStub newStub(io.grpc.Channel channel) { io.grpc.stub.AbstractStub.StubFactory<KeywordPlanServiceStub> factory = new io.grpc.stub.AbstractStub.StubFactory<KeywordPlanServiceStub>() { @java.lang.Override public KeywordPlanServiceStub newStub(io.grpc.Channel channel, io.grpc.CallOptions callOptions) { return new KeywordPlanServiceStub(channel, callOptions); } }; return KeywordPlanServiceStub.newStub(factory, channel); } /** * Creates a new blocking-style stub that supports unary and streaming output calls on the service */ public static KeywordPlanServiceBlockingStub newBlockingStub( io.grpc.Channel channel) { io.grpc.stub.AbstractStub.StubFactory<KeywordPlanServiceBlockingStub> factory = new io.grpc.stub.AbstractStub.StubFactory<KeywordPlanServiceBlockingStub>() { @java.lang.Override public KeywordPlanServiceBlockingStub newStub(io.grpc.Channel channel, io.grpc.CallOptions callOptions) { return new KeywordPlanServiceBlockingStub(channel, callOptions); } }; return KeywordPlanServiceBlockingStub.newStub(factory, channel); } /** * Creates a new ListenableFuture-style stub that supports unary calls on the service */ public static KeywordPlanServiceFutureStub newFutureStub( io.grpc.Channel channel) { io.grpc.stub.AbstractStub.StubFactory<KeywordPlanServiceFutureStub> factory = new io.grpc.stub.AbstractStub.StubFactory<KeywordPlanServiceFutureStub>() { @java.lang.Override public KeywordPlanServiceFutureStub newStub(io.grpc.Channel channel, io.grpc.CallOptions callOptions) { return new KeywordPlanServiceFutureStub(channel, callOptions); } }; return KeywordPlanServiceFutureStub.newStub(factory, channel); } /** * <pre> * Service to manage keyword plans. * </pre> */ public static abstract class KeywordPlanServiceImplBase implements io.grpc.BindableService { /** * <pre> * Returns the requested plan in full detail. * List of thrown errors: * [AuthenticationError]() * [AuthorizationError]() * [HeaderError]() * [InternalError]() * [QuotaError]() * [RequestError]() * </pre> */ public void getKeywordPlan(com.google.ads.googleads.v8.services.GetKeywordPlanRequest request, io.grpc.stub.StreamObserver<com.google.ads.googleads.v8.resources.KeywordPlan> responseObserver) { io.grpc.stub.ServerCalls.asyncUnimplementedUnaryCall(getGetKeywordPlanMethod(), responseObserver); } /** * <pre> * Creates, updates, or removes keyword plans. Operation statuses are * returned. * List of thrown errors: * [AuthenticationError]() * [AuthorizationError]() * [DatabaseError]() * [FieldError]() * [HeaderError]() * [InternalError]() * [KeywordPlanError]() * [MutateError]() * [NewResourceCreationError]() * [QuotaError]() * [RequestError]() * [ResourceCountLimitExceededError]() * [StringLengthError]() * </pre> */ public void mutateKeywordPlans(com.google.ads.googleads.v8.services.MutateKeywordPlansRequest request, io.grpc.stub.StreamObserver<com.google.ads.googleads.v8.services.MutateKeywordPlansResponse> responseObserver) { io.grpc.stub.ServerCalls.asyncUnimplementedUnaryCall(getMutateKeywordPlansMethod(), responseObserver); } /** * <pre> * Returns the requested Keyword Plan forecast curve. * Only the bidding strategy is considered for generating forecast curve. * The bidding strategy value specified in the plan is ignored. * To generate a forecast at a value specified in the plan, use * KeywordPlanService.GenerateForecastMetrics. * List of thrown errors: * [AuthenticationError]() * [AuthorizationError]() * [HeaderError]() * [InternalError]() * [KeywordPlanError]() * [QuotaError]() * [RequestError]() * </pre> */ public void generateForecastCurve(com.google.ads.googleads.v8.services.GenerateForecastCurveRequest request, io.grpc.stub.StreamObserver<com.google.ads.googleads.v8.services.GenerateForecastCurveResponse> responseObserver) { io.grpc.stub.ServerCalls.asyncUnimplementedUnaryCall(getGenerateForecastCurveMethod(), responseObserver); } /** * <pre> * Returns a forecast in the form of a time series for the Keyword Plan over * the next 52 weeks. * (1) Forecasts closer to the current date are generally more accurate than * further out. * (2) The forecast reflects seasonal trends using current and * prior traffic patterns. The forecast period of the plan is ignored. * List of thrown errors: * [AuthenticationError]() * [AuthorizationError]() * [HeaderError]() * [InternalError]() * [KeywordPlanError]() * [QuotaError]() * [RequestError]() * </pre> */ public void generateForecastTimeSeries(com.google.ads.googleads.v8.services.GenerateForecastTimeSeriesRequest request, io.grpc.stub.StreamObserver<com.google.ads.googleads.v8.services.GenerateForecastTimeSeriesResponse> responseObserver) { io.grpc.stub.ServerCalls.asyncUnimplementedUnaryCall(getGenerateForecastTimeSeriesMethod(), responseObserver); } /** * <pre> * Returns the requested Keyword Plan forecasts. * List of thrown errors: * [AuthenticationError]() * [AuthorizationError]() * [HeaderError]() * [InternalError]() * [KeywordPlanError]() * [QuotaError]() * [RequestError]() * </pre> */ public void generateForecastMetrics(com.google.ads.googleads.v8.services.GenerateForecastMetricsRequest request, io.grpc.stub.StreamObserver<com.google.ads.googleads.v8.services.GenerateForecastMetricsResponse> responseObserver) { io.grpc.stub.ServerCalls.asyncUnimplementedUnaryCall(getGenerateForecastMetricsMethod(), responseObserver); } /** * <pre> * Returns the requested Keyword Plan historical metrics. * List of thrown errors: * [AuthenticationError]() * [AuthorizationError]() * [HeaderError]() * [InternalError]() * [KeywordPlanError]() * [QuotaError]() * [RequestError]() * </pre> */ public void generateHistoricalMetrics(com.google.ads.googleads.v8.services.GenerateHistoricalMetricsRequest request, io.grpc.stub.StreamObserver<com.google.ads.googleads.v8.services.GenerateHistoricalMetricsResponse> responseObserver) { io.grpc.stub.ServerCalls.asyncUnimplementedUnaryCall(getGenerateHistoricalMetricsMethod(), responseObserver); } @java.lang.Override public final io.grpc.ServerServiceDefinition bindService() { return io.grpc.ServerServiceDefinition.builder(getServiceDescriptor()) .addMethod( getGetKeywordPlanMethod(), io.grpc.stub.ServerCalls.asyncUnaryCall( new MethodHandlers< com.google.ads.googleads.v8.services.GetKeywordPlanRequest, com.google.ads.googleads.v8.resources.KeywordPlan>( this, METHODID_GET_KEYWORD_PLAN))) .addMethod( getMutateKeywordPlansMethod(), io.grpc.stub.ServerCalls.asyncUnaryCall( new MethodHandlers< com.google.ads.googleads.v8.services.MutateKeywordPlansRequest, com.google.ads.googleads.v8.services.MutateKeywordPlansResponse>( this, METHODID_MUTATE_KEYWORD_PLANS))) .addMethod( getGenerateForecastCurveMethod(), io.grpc.stub.ServerCalls.asyncUnaryCall( new MethodHandlers< com.google.ads.googleads.v8.services.GenerateForecastCurveRequest, com.google.ads.googleads.v8.services.GenerateForecastCurveResponse>( this, METHODID_GENERATE_FORECAST_CURVE))) .addMethod( getGenerateForecastTimeSeriesMethod(), io.grpc.stub.ServerCalls.asyncUnaryCall( new MethodHandlers< com.google.ads.googleads.v8.services.GenerateForecastTimeSeriesRequest, com.google.ads.googleads.v8.services.GenerateForecastTimeSeriesResponse>( this, METHODID_GENERATE_FORECAST_TIME_SERIES))) .addMethod( getGenerateForecastMetricsMethod(), io.grpc.stub.ServerCalls.asyncUnaryCall( new MethodHandlers< com.google.ads.googleads.v8.services.GenerateForecastMetricsRequest, com.google.ads.googleads.v8.services.GenerateForecastMetricsResponse>( this, METHODID_GENERATE_FORECAST_METRICS))) .addMethod( getGenerateHistoricalMetricsMethod(), io.grpc.stub.ServerCalls.asyncUnaryCall( new MethodHandlers< com.google.ads.googleads.v8.services.GenerateHistoricalMetricsRequest, com.google.ads.googleads.v8.services.GenerateHistoricalMetricsResponse>( this, METHODID_GENERATE_HISTORICAL_METRICS))) .build(); } } /** * <pre> * Service to manage keyword plans. * </pre> */ public static final class KeywordPlanServiceStub extends io.grpc.stub.AbstractAsyncStub<KeywordPlanServiceStub> { private KeywordPlanServiceStub( io.grpc.Channel channel, io.grpc.CallOptions callOptions) { super(channel, callOptions); } @java.lang.Override protected KeywordPlanServiceStub build( io.grpc.Channel channel, io.grpc.CallOptions callOptions) { return new KeywordPlanServiceStub(channel, callOptions); } /** * <pre> * Returns the requested plan in full detail. * List of thrown errors: * [AuthenticationError]() * [AuthorizationError]() * [HeaderError]() * [InternalError]() * [QuotaError]() * [RequestError]() * </pre> */ public void getKeywordPlan(com.google.ads.googleads.v8.services.GetKeywordPlanRequest request, io.grpc.stub.StreamObserver<com.google.ads.googleads.v8.resources.KeywordPlan> responseObserver) { io.grpc.stub.ClientCalls.asyncUnaryCall( getChannel().newCall(getGetKeywordPlanMethod(), getCallOptions()), request, responseObserver); } /** * <pre> * Creates, updates, or removes keyword plans. Operation statuses are * returned. * List of thrown errors: * [AuthenticationError]() * [AuthorizationError]() * [DatabaseError]() * [FieldError]() * [HeaderError]() * [InternalError]() * [KeywordPlanError]() * [MutateError]() * [NewResourceCreationError]() * [QuotaError]() * [RequestError]() * [ResourceCountLimitExceededError]() * [StringLengthError]() * </pre> */ public void mutateKeywordPlans(com.google.ads.googleads.v8.services.MutateKeywordPlansRequest request, io.grpc.stub.StreamObserver<com.google.ads.googleads.v8.services.MutateKeywordPlansResponse> responseObserver) { io.grpc.stub.ClientCalls.asyncUnaryCall( getChannel().newCall(getMutateKeywordPlansMethod(), getCallOptions()), request, responseObserver); } /** * <pre> * Returns the requested Keyword Plan forecast curve. * Only the bidding strategy is considered for generating forecast curve. * The bidding strategy value specified in the plan is ignored. * To generate a forecast at a value specified in the plan, use * KeywordPlanService.GenerateForecastMetrics. * List of thrown errors: * [AuthenticationError]() * [AuthorizationError]() * [HeaderError]() * [InternalError]() * [KeywordPlanError]() * [QuotaError]() * [RequestError]() * </pre> */ public void generateForecastCurve(com.google.ads.googleads.v8.services.GenerateForecastCurveRequest request, io.grpc.stub.StreamObserver<com.google.ads.googleads.v8.services.GenerateForecastCurveResponse> responseObserver) { io.grpc.stub.ClientCalls.asyncUnaryCall( getChannel().newCall(getGenerateForecastCurveMethod(), getCallOptions()), request, responseObserver); } /** * <pre> * Returns a forecast in the form of a time series for the Keyword Plan over * the next 52 weeks. * (1) Forecasts closer to the current date are generally more accurate than * further out. * (2) The forecast reflects seasonal trends using current and * prior traffic patterns. The forecast period of the plan is ignored. * List of thrown errors: * [AuthenticationError]() * [AuthorizationError]() * [HeaderError]() * [InternalError]() * [KeywordPlanError]() * [QuotaError]() * [RequestError]() * </pre> */ public void generateForecastTimeSeries(com.google.ads.googleads.v8.services.GenerateForecastTimeSeriesRequest request, io.grpc.stub.StreamObserver<com.google.ads.googleads.v8.services.GenerateForecastTimeSeriesResponse> responseObserver) { io.grpc.stub.ClientCalls.asyncUnaryCall( getChannel().newCall(getGenerateForecastTimeSeriesMethod(), getCallOptions()), request, responseObserver); } /** * <pre> * Returns the requested Keyword Plan forecasts. * List of thrown errors: * [AuthenticationError]() * [AuthorizationError]() * [HeaderError]() * [InternalError]() * [KeywordPlanError]() * [QuotaError]() * [RequestError]() * </pre> */ public void generateForecastMetrics(com.google.ads.googleads.v8.services.GenerateForecastMetricsRequest request, io.grpc.stub.StreamObserver<com.google.ads.googleads.v8.services.GenerateForecastMetricsResponse> responseObserver) { io.grpc.stub.ClientCalls.asyncUnaryCall( getChannel().newCall(getGenerateForecastMetricsMethod(), getCallOptions()), request, responseObserver); } /** * <pre> * Returns the requested Keyword Plan historical metrics. * List of thrown errors: * [AuthenticationError]() * [AuthorizationError]() * [HeaderError]() * [InternalError]() * [KeywordPlanError]() * [QuotaError]() * [RequestError]() * </pre> */ public void generateHistoricalMetrics(com.google.ads.googleads.v8.services.GenerateHistoricalMetricsRequest request, io.grpc.stub.StreamObserver<com.google.ads.googleads.v8.services.GenerateHistoricalMetricsResponse> responseObserver) { io.grpc.stub.ClientCalls.asyncUnaryCall( getChannel().newCall(getGenerateHistoricalMetricsMethod(), getCallOptions()), request, responseObserver); } } /** * <pre> * Service to manage keyword plans. * </pre> */ public static final class KeywordPlanServiceBlockingStub extends io.grpc.stub.AbstractBlockingStub<KeywordPlanServiceBlockingStub> { private KeywordPlanServiceBlockingStub( io.grpc.Channel channel, io.grpc.CallOptions callOptions) { super(channel, callOptions); } @java.lang.Override protected KeywordPlanServiceBlockingStub build( io.grpc.Channel channel, io.grpc.CallOptions callOptions) { return new KeywordPlanServiceBlockingStub(channel, callOptions); } /** * <pre> * Returns the requested plan in full detail. * List of thrown errors: * [AuthenticationError]() * [AuthorizationError]() * [HeaderError]() * [InternalError]() * [QuotaError]() * [RequestError]() * </pre> */ public com.google.ads.googleads.v8.resources.KeywordPlan getKeywordPlan(com.google.ads.googleads.v8.services.GetKeywordPlanRequest request) { return io.grpc.stub.ClientCalls.blockingUnaryCall( getChannel(), getGetKeywordPlanMethod(), getCallOptions(), request); } /** * <pre> * Creates, updates, or removes keyword plans. Operation statuses are * returned. * List of thrown errors: * [AuthenticationError]() * [AuthorizationError]() * [DatabaseError]() * [FieldError]() * [HeaderError]() * [InternalError]() * [KeywordPlanError]() * [MutateError]() * [NewResourceCreationError]() * [QuotaError]() * [RequestError]() * [ResourceCountLimitExceededError]() * [StringLengthError]() * </pre> */ public com.google.ads.googleads.v8.services.MutateKeywordPlansResponse mutateKeywordPlans(com.google.ads.googleads.v8.services.MutateKeywordPlansRequest request) { return io.grpc.stub.ClientCalls.blockingUnaryCall( getChannel(), getMutateKeywordPlansMethod(), getCallOptions(), request); } /** * <pre> * Returns the requested Keyword Plan forecast curve. * Only the bidding strategy is considered for generating forecast curve. * The bidding strategy value specified in the plan is ignored. * To generate a forecast at a value specified in the plan, use * KeywordPlanService.GenerateForecastMetrics. * List of thrown errors: * [AuthenticationError]() * [AuthorizationError]() * [HeaderError]() * [InternalError]() * [KeywordPlanError]() * [QuotaError]() * [RequestError]() * </pre> */ public com.google.ads.googleads.v8.services.GenerateForecastCurveResponse generateForecastCurve(com.google.ads.googleads.v8.services.GenerateForecastCurveRequest request) { return io.grpc.stub.ClientCalls.blockingUnaryCall( getChannel(), getGenerateForecastCurveMethod(), getCallOptions(), request); } /** * <pre> * Returns a forecast in the form of a time series for the Keyword Plan over * the next 52 weeks. * (1) Forecasts closer to the current date are generally more accurate than * further out. * (2) The forecast reflects seasonal trends using current and * prior traffic patterns. The forecast period of the plan is ignored. * List of thrown errors: * [AuthenticationError]() * [AuthorizationError]() * [HeaderError]() * [InternalError]() * [KeywordPlanError]() * [QuotaError]() * [RequestError]() * </pre> */ public com.google.ads.googleads.v8.services.GenerateForecastTimeSeriesResponse generateForecastTimeSeries(com.google.ads.googleads.v8.services.GenerateForecastTimeSeriesRequest request) { return io.grpc.stub.ClientCalls.blockingUnaryCall( getChannel(), getGenerateForecastTimeSeriesMethod(), getCallOptions(), request); } /** * <pre> * Returns the requested Keyword Plan forecasts. * List of thrown errors: * [AuthenticationError]() * [AuthorizationError]() * [HeaderError]() * [InternalError]() * [KeywordPlanError]() * [QuotaError]() * [RequestError]() * </pre> */ public com.google.ads.googleads.v8.services.GenerateForecastMetricsResponse generateForecastMetrics(com.google.ads.googleads.v8.services.GenerateForecastMetricsRequest request) { return io.grpc.stub.ClientCalls.blockingUnaryCall( getChannel(), getGenerateForecastMetricsMethod(), getCallOptions(), request); } /** * <pre> * Returns the requested Keyword Plan historical metrics. * List of thrown errors: * [AuthenticationError]() * [AuthorizationError]() * [HeaderError]() * [InternalError]() * [KeywordPlanError]() * [QuotaError]() * [RequestError]() * </pre> */ public com.google.ads.googleads.v8.services.GenerateHistoricalMetricsResponse generateHistoricalMetrics(com.google.ads.googleads.v8.services.GenerateHistoricalMetricsRequest request) { return io.grpc.stub.ClientCalls.blockingUnaryCall( getChannel(), getGenerateHistoricalMetricsMethod(), getCallOptions(), request); } } /** * <pre> * Service to manage keyword plans. * </pre> */ public static final class KeywordPlanServiceFutureStub extends io.grpc.stub.AbstractFutureStub<KeywordPlanServiceFutureStub> { private KeywordPlanServiceFutureStub( io.grpc.Channel channel, io.grpc.CallOptions callOptions) { super(channel, callOptions); } @java.lang.Override protected KeywordPlanServiceFutureStub build( io.grpc.Channel channel, io.grpc.CallOptions callOptions) { return new KeywordPlanServiceFutureStub(channel, callOptions); } /** * <pre> * Returns the requested plan in full detail. * List of thrown errors: * [AuthenticationError]() * [AuthorizationError]() * [HeaderError]() * [InternalError]() * [QuotaError]() * [RequestError]() * </pre> */ public com.google.common.util.concurrent.ListenableFuture<com.google.ads.googleads.v8.resources.KeywordPlan> getKeywordPlan( com.google.ads.googleads.v8.services.GetKeywordPlanRequest request) { return io.grpc.stub.ClientCalls.futureUnaryCall( getChannel().newCall(getGetKeywordPlanMethod(), getCallOptions()), request); } /** * <pre> * Creates, updates, or removes keyword plans. Operation statuses are * returned. * List of thrown errors: * [AuthenticationError]() * [AuthorizationError]() * [DatabaseError]() * [FieldError]() * [HeaderError]() * [InternalError]() * [KeywordPlanError]() * [MutateError]() * [NewResourceCreationError]() * [QuotaError]() * [RequestError]() * [ResourceCountLimitExceededError]() * [StringLengthError]() * </pre> */ public com.google.common.util.concurrent.ListenableFuture<com.google.ads.googleads.v8.services.MutateKeywordPlansResponse> mutateKeywordPlans( com.google.ads.googleads.v8.services.MutateKeywordPlansRequest request) { return io.grpc.stub.ClientCalls.futureUnaryCall( getChannel().newCall(getMutateKeywordPlansMethod(), getCallOptions()), request); } /** * <pre> * Returns the requested Keyword Plan forecast curve. * Only the bidding strategy is considered for generating forecast curve. * The bidding strategy value specified in the plan is ignored. * To generate a forecast at a value specified in the plan, use * KeywordPlanService.GenerateForecastMetrics. * List of thrown errors: * [AuthenticationError]() * [AuthorizationError]() * [HeaderError]() * [InternalError]() * [KeywordPlanError]() * [QuotaError]() * [RequestError]() * </pre> */ public com.google.common.util.concurrent.ListenableFuture<com.google.ads.googleads.v8.services.GenerateForecastCurveResponse> generateForecastCurve( com.google.ads.googleads.v8.services.GenerateForecastCurveRequest request) { return io.grpc.stub.ClientCalls.futureUnaryCall( getChannel().newCall(getGenerateForecastCurveMethod(), getCallOptions()), request); } /** * <pre> * Returns a forecast in the form of a time series for the Keyword Plan over * the next 52 weeks. * (1) Forecasts closer to the current date are generally more accurate than * further out. * (2) The forecast reflects seasonal trends using current and * prior traffic patterns. The forecast period of the plan is ignored. * List of thrown errors: * [AuthenticationError]() * [AuthorizationError]() * [HeaderError]() * [InternalError]() * [KeywordPlanError]() * [QuotaError]() * [RequestError]() * </pre> */ public com.google.common.util.concurrent.ListenableFuture<com.google.ads.googleads.v8.services.GenerateForecastTimeSeriesResponse> generateForecastTimeSeries( com.google.ads.googleads.v8.services.GenerateForecastTimeSeriesRequest request) { return io.grpc.stub.ClientCalls.futureUnaryCall( getChannel().newCall(getGenerateForecastTimeSeriesMethod(), getCallOptions()), request); } /** * <pre> * Returns the requested Keyword Plan forecasts. * List of thrown errors: * [AuthenticationError]() * [AuthorizationError]() * [HeaderError]() * [InternalError]() * [KeywordPlanError]() * [QuotaError]() * [RequestError]() * </pre> */ public com.google.common.util.concurrent.ListenableFuture<com.google.ads.googleads.v8.services.GenerateForecastMetricsResponse> generateForecastMetrics( com.google.ads.googleads.v8.services.GenerateForecastMetricsRequest request) { return io.grpc.stub.ClientCalls.futureUnaryCall( getChannel().newCall(getGenerateForecastMetricsMethod(), getCallOptions()), request); } /** * <pre> * Returns the requested Keyword Plan historical metrics. * List of thrown errors: * [AuthenticationError]() * [AuthorizationError]() * [HeaderError]() * [InternalError]() * [KeywordPlanError]() * [QuotaError]() * [RequestError]() * </pre> */ public com.google.common.util.concurrent.ListenableFuture<com.google.ads.googleads.v8.services.GenerateHistoricalMetricsResponse> generateHistoricalMetrics( com.google.ads.googleads.v8.services.GenerateHistoricalMetricsRequest request) { return io.grpc.stub.ClientCalls.futureUnaryCall( getChannel().newCall(getGenerateHistoricalMetricsMethod(), getCallOptions()), request); } } private static final int METHODID_GET_KEYWORD_PLAN = 0; private static final int METHODID_MUTATE_KEYWORD_PLANS = 1; private static final int METHODID_GENERATE_FORECAST_CURVE = 2; private static final int METHODID_GENERATE_FORECAST_TIME_SERIES = 3; private static final int METHODID_GENERATE_FORECAST_METRICS = 4; private static final int METHODID_GENERATE_HISTORICAL_METRICS = 5; private static final class MethodHandlers<Req, Resp> implements io.grpc.stub.ServerCalls.UnaryMethod<Req, Resp>, io.grpc.stub.ServerCalls.ServerStreamingMethod<Req, Resp>, io.grpc.stub.ServerCalls.ClientStreamingMethod<Req, Resp>, io.grpc.stub.ServerCalls.BidiStreamingMethod<Req, Resp> { private final KeywordPlanServiceImplBase serviceImpl; private final int methodId; MethodHandlers(KeywordPlanServiceImplBase serviceImpl, int methodId) { this.serviceImpl = serviceImpl; this.methodId = methodId; } @java.lang.Override @java.lang.SuppressWarnings("unchecked") public void invoke(Req request, io.grpc.stub.StreamObserver<Resp> responseObserver) { switch (methodId) { case METHODID_GET_KEYWORD_PLAN: serviceImpl.getKeywordPlan((com.google.ads.googleads.v8.services.GetKeywordPlanRequest) request, (io.grpc.stub.StreamObserver<com.google.ads.googleads.v8.resources.KeywordPlan>) responseObserver); break; case METHODID_MUTATE_KEYWORD_PLANS: serviceImpl.mutateKeywordPlans((com.google.ads.googleads.v8.services.MutateKeywordPlansRequest) request, (io.grpc.stub.StreamObserver<com.google.ads.googleads.v8.services.MutateKeywordPlansResponse>) responseObserver); break; case METHODID_GENERATE_FORECAST_CURVE: serviceImpl.generateForecastCurve((com.google.ads.googleads.v8.services.GenerateForecastCurveRequest) request, (io.grpc.stub.StreamObserver<com.google.ads.googleads.v8.services.GenerateForecastCurveResponse>) responseObserver); break; case METHODID_GENERATE_FORECAST_TIME_SERIES: serviceImpl.generateForecastTimeSeries((com.google.ads.googleads.v8.services.GenerateForecastTimeSeriesRequest) request, (io.grpc.stub.StreamObserver<com.google.ads.googleads.v8.services.GenerateForecastTimeSeriesResponse>) responseObserver); break; case METHODID_GENERATE_FORECAST_METRICS: serviceImpl.generateForecastMetrics((com.google.ads.googleads.v8.services.GenerateForecastMetricsRequest) request, (io.grpc.stub.StreamObserver<com.google.ads.googleads.v8.services.GenerateForecastMetricsResponse>) responseObserver); break; case METHODID_GENERATE_HISTORICAL_METRICS: serviceImpl.generateHistoricalMetrics((com.google.ads.googleads.v8.services.GenerateHistoricalMetricsRequest) request, (io.grpc.stub.StreamObserver<com.google.ads.googleads.v8.services.GenerateHistoricalMetricsResponse>) responseObserver); break; default: throw new AssertionError(); } } @java.lang.Override @java.lang.SuppressWarnings("unchecked") public io.grpc.stub.StreamObserver<Req> invoke( io.grpc.stub.StreamObserver<Resp> responseObserver) { switch (methodId) { default: throw new AssertionError(); } } } private static abstract class KeywordPlanServiceBaseDescriptorSupplier implements io.grpc.protobuf.ProtoFileDescriptorSupplier, io.grpc.protobuf.ProtoServiceDescriptorSupplier { KeywordPlanServiceBaseDescriptorSupplier() {} @java.lang.Override public com.google.protobuf.Descriptors.FileDescriptor getFileDescriptor() { return com.google.ads.googleads.v8.services.KeywordPlanServiceProto.getDescriptor(); } @java.lang.Override public com.google.protobuf.Descriptors.ServiceDescriptor getServiceDescriptor() { return getFileDescriptor().findServiceByName("KeywordPlanService"); } } private static final class KeywordPlanServiceFileDescriptorSupplier extends KeywordPlanServiceBaseDescriptorSupplier { KeywordPlanServiceFileDescriptorSupplier() {} } private static final class KeywordPlanServiceMethodDescriptorSupplier extends KeywordPlanServiceBaseDescriptorSupplier implements io.grpc.protobuf.ProtoMethodDescriptorSupplier { private final String methodName; KeywordPlanServiceMethodDescriptorSupplier(String methodName) { this.methodName = methodName; } @java.lang.Override public com.google.protobuf.Descriptors.MethodDescriptor getMethodDescriptor() { return getServiceDescriptor().findMethodByName(methodName); } } private static volatile io.grpc.ServiceDescriptor serviceDescriptor; public static io.grpc.ServiceDescriptor getServiceDescriptor() { io.grpc.ServiceDescriptor result = serviceDescriptor; if (result == null) { synchronized (KeywordPlanServiceGrpc.class) { result = serviceDescriptor; if (result == null) { serviceDescriptor = result = io.grpc.ServiceDescriptor.newBuilder(SERVICE_NAME) .setSchemaDescriptor(new KeywordPlanServiceFileDescriptorSupplier()) .addMethod(getGetKeywordPlanMethod()) .addMethod(getMutateKeywordPlansMethod()) .addMethod(getGenerateForecastCurveMethod()) .addMethod(getGenerateForecastTimeSeriesMethod()) .addMethod(getGenerateForecastMetricsMethod()) .addMethod(getGenerateHistoricalMetricsMethod()) .build(); } } } return result; } }
[ "noreply@github.com" ]
noreply@github.com
7a3f8981497b9d8397b2977031d99b1ec4e2d91f
b810558aa6c7c5c0302b0727d9c4d180d284a6ca
/src/lab5/BeanFactory.java
c0b1a2f9128004052f8e32db797882d4b296c7b1
[]
no_license
Toktar/JavaLab
6ff01511b863afc4f152a9a7cac165d7f8b41945
32920e48756e910cb5b5011e7a8fd3784acc6ae4
refs/heads/master
2020-05-21T16:05:33.776184
2017-04-07T14:28:14
2017-04-07T14:28:14
84,633,817
1
0
null
null
null
null
UTF-8
Java
false
false
1,394
java
package lab5; import lab5.Annotation.Autowired; import java.lang.reflect.Field; import java.util.HashMap; import java.util.Map; public final class BeanFactory { private static Map<String, Object> beanMap = new HashMap<>(); public static Object createBean(String beanName) throws ClassNotFoundException, IllegalAccessException, InstantiationException { Object bean = beanMap.get(beanName); if (bean == null) { bean = getBean(beanName); } return bean; } private static Object getBean(String beanName) throws ClassNotFoundException, InstantiationException, IllegalAccessException { Class<?> clazz = Class.forName(beanName); Object classInstance = clazz.newInstance(); inject(clazz, classInstance); beanMap.put(beanName, classInstance); return classInstance; } private static void inject(Class<?> clazz, Object classInstance) throws IllegalAccessException, InstantiationException, ClassNotFoundException { for (Field field : clazz.getDeclaredFields()) { if (field.isAnnotationPresent(Autowired.class)) { field.setAccessible(true); String fieldClassName = field.getType().getName(); Object bean = getBean(fieldClassName); field.set(classInstance, bean); } } } }
[ "dizkida@gmail.com" ]
dizkida@gmail.com
3c0e34054c0f2f9ecdd4f708e0c71ae9b6f8fa2b
d5ad6edfc5ffb0e1bc2a80725581e5abcacf7862
/CVE-2014-7911/cve20147911/bin/cve201479xx/classes_dex2jar/android/support/v4/content/Loader.java
74322511bd050ee3ddbaa1469890c1d175a9852c
[]
no_license
3kyo0/android-vuln
f3642ea9c3657c477bfefaeab7f9f1a35a8f4b22
d472b6ca2f4c188ee4b7665f3c07461e60cbdf7f
refs/heads/master
2020-05-30T07:00:57.455652
2019-04-27T09:29:33
2019-04-27T09:29:33
null
0
0
null
null
null
null
UTF-8
Java
false
false
5,168
java
package android.support.v4.content; import android.content.Context; import android.database.ContentObserver; import android.os.Handler; import android.support.v4.util.DebugUtils; import java.io.FileDescriptor; import java.io.PrintWriter; public class Loader<D> { boolean mAbandoned = false; boolean mContentChanged = false; Context mContext; int mId; OnLoadCompleteListener<D> mListener; boolean mProcessingChange = false; boolean mReset = true; boolean mStarted = false; public Loader(Context paramContext) { this.mContext = paramContext.getApplicationContext(); } public void abandon() { this.mAbandoned = true; onAbandon(); } public void commitContentChanged() { this.mProcessingChange = false; } public String dataToString(D paramD) { StringBuilder localStringBuilder = new StringBuilder(64); DebugUtils.buildShortClassTag(paramD, localStringBuilder); localStringBuilder.append("}"); return localStringBuilder.toString(); } public void deliverResult(D paramD) { if (this.mListener != null) { this.mListener.onLoadComplete(this, paramD); } } public void dump(String paramString, FileDescriptor paramFileDescriptor, PrintWriter paramPrintWriter, String[] paramArrayOfString) { paramPrintWriter.print(paramString); paramPrintWriter.print("mId="); paramPrintWriter.print(this.mId); paramPrintWriter.print(" mListener="); paramPrintWriter.println(this.mListener); if ((this.mStarted) || (this.mContentChanged) || (this.mProcessingChange)) { paramPrintWriter.print(paramString); paramPrintWriter.print("mStarted="); paramPrintWriter.print(this.mStarted); paramPrintWriter.print(" mContentChanged="); paramPrintWriter.print(this.mContentChanged); paramPrintWriter.print(" mProcessingChange="); paramPrintWriter.println(this.mProcessingChange); } if ((this.mAbandoned) || (this.mReset)) { paramPrintWriter.print(paramString); paramPrintWriter.print("mAbandoned="); paramPrintWriter.print(this.mAbandoned); paramPrintWriter.print(" mReset="); paramPrintWriter.println(this.mReset); } } public void forceLoad() { onForceLoad(); } public Context getContext() { return this.mContext; } public int getId() { return this.mId; } public boolean isAbandoned() { return this.mAbandoned; } public boolean isReset() { return this.mReset; } public boolean isStarted() { return this.mStarted; } protected void onAbandon() {} public void onContentChanged() { if (this.mStarted) { forceLoad(); return; } this.mContentChanged = true; } protected void onForceLoad() {} protected void onReset() {} protected void onStartLoading() {} protected void onStopLoading() {} public void registerListener(int paramInt, OnLoadCompleteListener<D> paramOnLoadCompleteListener) { if (this.mListener != null) { throw new IllegalStateException("There is already a listener registered"); } this.mListener = paramOnLoadCompleteListener; this.mId = paramInt; } public void reset() { onReset(); this.mReset = true; this.mStarted = false; this.mAbandoned = false; this.mContentChanged = false; this.mProcessingChange = false; } public void rollbackContentChanged() { if (this.mProcessingChange) { this.mContentChanged = true; } } public final void startLoading() { this.mStarted = true; this.mReset = false; this.mAbandoned = false; onStartLoading(); } public void stopLoading() { this.mStarted = false; onStopLoading(); } public boolean takeContentChanged() { boolean bool = this.mContentChanged; this.mContentChanged = false; this.mProcessingChange = (bool | this.mProcessingChange); return bool; } public String toString() { StringBuilder localStringBuilder = new StringBuilder(64); DebugUtils.buildShortClassTag(this, localStringBuilder); localStringBuilder.append(" id="); localStringBuilder.append(this.mId); localStringBuilder.append("}"); return localStringBuilder.toString(); } public void unregisterListener(OnLoadCompleteListener<D> paramOnLoadCompleteListener) { if (this.mListener == null) { throw new IllegalStateException("No listener register"); } if (this.mListener != paramOnLoadCompleteListener) { throw new IllegalArgumentException("Attempting to unregister the wrong listener"); } this.mListener = null; } public final class ForceLoadContentObserver extends ContentObserver { public ForceLoadContentObserver() { super(); } public boolean deliverSelfNotifications() { return true; } public void onChange(boolean paramBoolean) { Loader.this.onContentChanged(); } } public static abstract interface OnLoadCompleteListener<D> { public abstract void onLoadComplete(Loader<D> paramLoader, D paramD); } }
[ "tangsilian@users.noreply.github.com" ]
tangsilian@users.noreply.github.com
110ba2ecc84b175e90a6f109af299b209fc4c466
d55f13e3f1bedc8da175abd34458d859ee6c8c82
/app/src/androidTest/java/com/example/calcuclator/ExampleInstrumentedTest.java
a2785000ca8e5dc502dbfab533ca9ef8c8d82d41
[]
no_license
NhatLam/Cacultor
19a0f8d501a79f90d6fb7f1fd09ac4ca34f0ffa4
a1e63c67cc36a6c5866051cca27d2368a8ff6cea
refs/heads/master
2020-05-04T07:44:38.625129
2019-04-09T02:31:10
2019-04-09T02:31:10
179,034,424
0
0
null
null
null
null
UTF-8
Java
false
false
730
java
package com.example.calcuclator; import android.content.Context; import android.support.test.InstrumentationRegistry; import android.support.test.runner.AndroidJUnit4; import org.junit.Test; import org.junit.runner.RunWith; import static org.junit.Assert.*; /** * Instrumented test, which will execute on an Android device. * * @see <a href="http://d.android.com/tools/testing">Testing documentation</a> */ @RunWith(AndroidJUnit4.class) public class ExampleInstrumentedTest { @Test public void useAppContext() { // Context of the app under test. Context appContext = InstrumentationRegistry.getTargetContext(); assertEquals("com.example.calcuclator", appContext.getPackageName()); } }
[ "31428056+NhatLam@users.noreply.github.com" ]
31428056+NhatLam@users.noreply.github.com
681b4b4ed5f9e4e4c0699ada0a005ff073b3479f
f9de7aebe4442757dbd5aeb8c57ea5c7d72646e9
/src/test/java/org/apache/sysml/test/integration/functions/tensor/Conv2DTest.java
81fe1540562a3f6565ada2e5984a71090f93263e
[ "Apache-2.0" ]
permissive
aglne/incubator-systemml
17b18fb09f9e1696b2b9a913a0f2997a2b94c556
0ee113481cd7f9722971e7a3d5373533f485c945
refs/heads/master
2020-12-25T21:56:10.789129
2017-03-27T15:25:58
2017-03-27T15:25:58
55,514,057
1
0
null
2017-03-27T15:26:00
2016-04-05T14:18:38
Java
UTF-8
Java
false
false
10,754
java
/* * 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.sysml.test.integration.functions.tensor; import java.util.HashMap; import org.apache.sysml.api.DMLScript; import org.apache.sysml.api.DMLScript.RUNTIME_PLATFORM; import org.apache.sysml.lops.LopProperties.ExecType; import org.apache.sysml.runtime.matrix.data.LibMatrixDNN; import org.apache.sysml.runtime.matrix.data.MatrixValue.CellIndex; import org.apache.sysml.test.integration.AutomatedTestBase; import org.apache.sysml.test.integration.TestConfiguration; import org.apache.sysml.test.utils.TestUtils; import org.junit.Test; public class Conv2DTest extends AutomatedTestBase { private final static String TEST_NAME = "Conv2DTest"; private final static String TEST_DIR = "functions/tensor/"; private final static String TEST_CLASS_DIR = TEST_DIR + Conv2DTest.class.getSimpleName() + "/"; private final static double epsilon=0.0000000001; @Override public void setUp() { addTestConfiguration(TEST_NAME, new TestConfiguration(TEST_CLASS_DIR, TEST_NAME, new String[] {"B"})); } @Test public void testConv2DDense1() { int numImg = 5; int imgSize = 3; int numChannels = 3; int numFilters = 6; int filterSize = 2; int stride = 1; int pad = 0; runConv2DTest(ExecType.CP, imgSize, numImg, numChannels, numFilters, filterSize, stride, pad, false); } @Test public void testConv2DDense2() { int numImg = 1; int imgSize = 10; int numChannels = 4; int numFilters = 3; int filterSize = 4; int stride = 2; int pad = 0; runConv2DTest(ExecType.CP, imgSize, numImg, numChannels, numFilters, filterSize, stride, pad, false); } @Test public void testConv2DDense3() { int numImg = 1; int imgSize = 10; int numChannels = 4; int numFilters = 3; int filterSize = 4; int stride = 2; int pad = 1; runConv2DTest(ExecType.CP, imgSize, numImg, numChannels, numFilters, filterSize, stride, pad, false); } @Test public void testConv2DDense4() { int numImg = 3; int imgSize = 10; int numChannels = 1; int numFilters = 3; int filterSize = 2; int stride = 2; int pad = 1; runConv2DTest(ExecType.CP, imgSize, numImg, numChannels, numFilters, filterSize, stride, pad, false); } @Test public void testConv2DDense5() { int numImg = 3; int imgSize = 8; int numChannels = 2; int numFilters = 3; int filterSize = 3; int stride = 1; int pad = 2; runConv2DTest(ExecType.CP, imgSize, numImg, numChannels, numFilters, filterSize, stride, pad, false); } @Test public void testConv2DDense6() { int numImg = 1; int imgSize = 10; int numChannels = 4; int numFilters = 3; int filterSize = 4; int stride = 1; int pad = 0; runConv2DTest(ExecType.CP, imgSize, numImg, numChannels, numFilters, filterSize, stride, pad, false); } @Test public void testConv2DDense7() { int numImg = 3; int imgSize = 10; int numChannels = 1; int numFilters = 3; int filterSize = 2; int stride = 1; int pad = 0; runConv2DTest(ExecType.CP, imgSize, numImg, numChannels, numFilters, filterSize, stride, pad, false); } @Test public void testConv2DSparse1() { int numImg = 5; int imgSize = 3; int numChannels = 3; int numFilters = 6; int filterSize = 2; int stride = 1; int pad = 0; runConv2DTest(ExecType.CP, imgSize, numImg, numChannels, numFilters, filterSize, stride, pad, true); } @Test public void testConv2DSparse2() { int numImg = 1; int imgSize = 10; int numChannels = 4; int numFilters = 3; int filterSize = 4; int stride = 2; int pad = 0; runConv2DTest(ExecType.CP, imgSize, numImg, numChannels, numFilters, filterSize, stride, pad, true); } @Test public void testConv2DSparse3() { int numImg = 1; int imgSize = 10; int numChannels = 4; int numFilters = 3; int filterSize = 4; int stride = 2; int pad = 1; runConv2DTest(ExecType.CP, imgSize, numImg, numChannels, numFilters, filterSize, stride, pad, true); } public void testConv2DSparse4() { int numImg = 3; int imgSize = 10; int numChannels = 1; int numFilters = 3; int filterSize = 2; int stride = 2; int pad = 1; runConv2DTest(ExecType.CP, imgSize, numImg, numChannels, numFilters, filterSize, stride, pad, true); } @Test public void testConv2DSparse5() { int numImg = 3; int imgSize = 8; int numChannels = 2; int numFilters = 3; int filterSize = 3; int stride = 1; int pad = 2; runConv2DTest(ExecType.CP, imgSize, numImg, numChannels, numFilters, filterSize, stride, pad, true); } // -------------------------------------------- @Test public void testConv2DDense1SP() { int numImg = 5; int imgSize = 3; int numChannels = 3; int numFilters = 6; int filterSize = 2; int stride = 1; int pad = 0; runConv2DTest(ExecType.SPARK, imgSize, numImg, numChannels, numFilters, filterSize, stride, pad, false); } @Test public void testConv2DDense2SP() { int numImg = 1; int imgSize = 10; int numChannels = 4; int numFilters = 3; int filterSize = 4; int stride = 2; int pad = 0; runConv2DTest(ExecType.SPARK, imgSize, numImg, numChannels, numFilters, filterSize, stride, pad, false); } @Test public void testConv2DDense3SP() { int numImg = 1; int imgSize = 10; int numChannels = 4; int numFilters = 3; int filterSize = 4; int stride = 2; int pad = 1; runConv2DTest(ExecType.SPARK, imgSize, numImg, numChannels, numFilters, filterSize, stride, pad, false); } @Test public void testConv2DDense4SP() { int numImg = 3; int imgSize = 10; int numChannels = 1; int numFilters = 3; int filterSize = 2; int stride = 2; int pad = 1; runConv2DTest(ExecType.SPARK, imgSize, numImg, numChannels, numFilters, filterSize, stride, pad, false); } @Test public void testConv2DDense5SP() { int numImg = 3; int imgSize = 8; int numChannels = 2; int numFilters = 3; int filterSize = 3; int stride = 1; int pad = 2; runConv2DTest(ExecType.SPARK, imgSize, numImg, numChannels, numFilters, filterSize, stride, pad, false); } @Test public void testConv2DDense6SP() { int numImg = 1; int imgSize = 10; int numChannels = 4; int numFilters = 3; int filterSize = 4; int stride = 1; int pad = 0; runConv2DTest(ExecType.SPARK, imgSize, numImg, numChannels, numFilters, filterSize, stride, pad, false); } @Test public void testConv2DDense7SP() { int numImg = 3; int imgSize = 10; int numChannels = 1; int numFilters = 3; int filterSize = 2; int stride = 1; int pad = 0; runConv2DTest(ExecType.SPARK, imgSize, numImg, numChannels, numFilters, filterSize, stride, pad, false); } @Test public void testConv2DSparse1SP() { int numImg = 5; int imgSize = 3; int numChannels = 3; int numFilters = 6; int filterSize = 2; int stride = 1; int pad = 0; runConv2DTest(ExecType.SPARK, imgSize, numImg, numChannels, numFilters, filterSize, stride, pad, true); } @Test public void testConv2DSparse2SP() { int numImg = 1; int imgSize = 10; int numChannels = 4; int numFilters = 3; int filterSize = 4; int stride = 2; int pad = 0; runConv2DTest(ExecType.SPARK, imgSize, numImg, numChannels, numFilters, filterSize, stride, pad, true); } @Test public void testConv2DSparse3SP() { int numImg = 1; int imgSize = 10; int numChannels = 4; int numFilters = 3; int filterSize = 4; int stride = 2; int pad = 1; runConv2DTest(ExecType.SPARK, imgSize, numImg, numChannels, numFilters, filterSize, stride, pad, true); } public void testConv2DSparse4SP() { int numImg = 3; int imgSize = 10; int numChannels = 1; int numFilters = 3; int filterSize = 2; int stride = 2; int pad = 1; runConv2DTest(ExecType.SPARK, imgSize, numImg, numChannels, numFilters, filterSize, stride, pad, true); } @Test public void testConv2DSparse5SP() { int numImg = 3; int imgSize = 8; int numChannels = 2; int numFilters = 3; int filterSize = 3; int stride = 1; int pad = 2; runConv2DTest(ExecType.SPARK, imgSize, numImg, numChannels, numFilters, filterSize, stride, pad, true); } /** * * @param et * @param sparse */ public void runConv2DTest( ExecType et, int imgSize, int numImg, int numChannels, int numFilters, int filterSize, int stride, int pad, boolean sparse) { RUNTIME_PLATFORM oldRTP = rtplatform; boolean sparkConfigOld = DMLScript.USE_LOCAL_SPARK_CONFIG; synchronized(LibMatrixDNN.class) { try { LibMatrixDNN.TEST_SPARSE_INPUT = sparse; LibMatrixDNN.TEST_SPARSE_FILTER = sparse; TestConfiguration config = getTestConfiguration(TEST_NAME); if(et == ExecType.SPARK) { rtplatform = RUNTIME_PLATFORM.SPARK; } else { rtplatform = (et==ExecType.MR)? RUNTIME_PLATFORM.HADOOP : RUNTIME_PLATFORM.SINGLE_NODE; } if( rtplatform == RUNTIME_PLATFORM.SPARK ) DMLScript.USE_LOCAL_SPARK_CONFIG = true; loadTestConfiguration(config); /* This is for running the junit test the new way, i.e., construct the arguments directly */ String RI_HOME = SCRIPT_DIR + TEST_DIR; fullDMLScriptName = RI_HOME + TEST_NAME + ".dml"; programArgs = new String[]{"-explain", "recompile_runtime", "-args", "" + imgSize, "" + numImg, "" + numChannels, "" + numFilters, "" + filterSize, "" + stride, "" + pad, output("B")}; fullRScriptName = RI_HOME + TEST_NAME + ".R"; rCmd = "Rscript" + " " + fullRScriptName + " " + imgSize + " " + numImg + " " + numChannels + " " + numFilters + " " + filterSize + " " + stride + " " + pad + " " + expectedDir(); boolean exceptionExpected = false; int expectedNumberOfJobs = -1; runTest(true, exceptionExpected, null, expectedNumberOfJobs); // Run comparison R script runRScript(true); HashMap<CellIndex, Double> bHM = readRMatrixFromFS("B"); HashMap<CellIndex, Double> dmlfile = readDMLMatrixFromHDFS("B"); TestUtils.compareMatrices(dmlfile, bHM, epsilon, "B-DML", "B-R"); } finally { rtplatform = oldRTP; DMLScript.USE_LOCAL_SPARK_CONFIG = sparkConfigOld; LibMatrixDNN.TEST_SPARSE_INPUT = false; LibMatrixDNN.TEST_SPARSE_FILTER = false; } } } }
[ "npansar@us.ibm.com" ]
npansar@us.ibm.com
3c7e684324bd06185ca7ada7830e3ff461e6c403
bac2322b1c4748893676b8f60d255c2e13a76cfb
/Menu.java
9e9cb613c0d72a6c9780072eac67cc84411ae5e8
[]
no_license
IInsomnia/JavaZon-Wholesale-Store
ae8746333e918fd2cb831556403647224413318e
e9f900d408a75345c542f919f5cbf5d954052093
refs/heads/master
2021-07-07T19:32:56.324074
2017-09-29T21:57:17
2017-09-29T21:57:17
105,319,578
0
0
null
null
null
null
UTF-8
Java
false
false
1,596
java
package jjuproject1_javazon; // @author Johnson public class Menu { private Product menuItems[]; //Constructor public Menu() { menuItems = new Product[9]; Product book; book = new Product("BK100", "Book", "Java", 12.99); menuItems[0] = book; book = new Product("BK200", "Book", "VB", 16.99); menuItems[1] = book; book = new Product("BK300", "Book", "PHP", 15.99); menuItems[2] = book; Product CD; CD = new Product("CD100", "CD", "TOP 10", 20.99); menuItems[3] = CD; CD = new Product("CD200", "CD", "TOP 20", 22.99); menuItems[4] = CD; CD = new Product("CD300", "CD", "TOP 100", 24.99); menuItems[5] = CD; Product game; game = new Product("GM100", "Game", "Halo 1", 40.99); menuItems[6] = game; game = new Product("GM200", "Game", "Halo 2", 42.99); menuItems[7] = game; game = new Product("GM200", "Game", "Halo 3", 44.99); menuItems[8] = game; } //Method to return a product menu array public Product[] getMenu() { return menuItems; } //method to return an array of descriptions public String[] getMenuDescriptions() { String menuDescription[] = new String[menuItems.length]; //return the menuDescription back to the calling method for (int a = 0; a < menuItems.length; a++) { menuDescription[a] = menuItems[a].getDescription(); } return menuDescription; } } // @author Johnson
[ "JohnsonJu29@gmail.com" ]
JohnsonJu29@gmail.com
7d4d741aa99b7e8aa08631b49c505f4735feb5fe
285fadf10a08ddaa2281f4c82d759764b84a98eb
/baseframelib/src/main/java/com/tyxo/baseframelib/BaseRecyclerAdapter.java
901e4d6fa5b0f92e5d2bdee0fc20740cf9c7372e
[]
no_license
tyxo842/BaseFrameLib
2c1722fae997852ddf3697f8b5d833200347bdd2
c71f5ceb3d6629a9df919bb15844ff23b2686652
refs/heads/master
2021-01-11T02:55:54.411767
2018-02-23T06:30:08
2018-02-23T06:30:08
70,881,134
1
0
null
null
null
null
UTF-8
Java
false
false
5,472
java
package com.tyxo.baseframelib; import android.content.Context; import android.support.v7.widget.RecyclerView; import android.view.LayoutInflater; import android.view.View; import android.view.View.OnClickListener; import android.view.View.OnLongClickListener; import android.view.ViewGroup; import java.util.ArrayList; import java.util.List; /** * author tyxo * created at 2016/8/25 16:11 * des : recyclerView 的基类adapter */ /* 用法: * class GAdapter extends BaseRecyclerAdapter <MyHolder,NewslistBean>{...} * 参考 GAdaper 内的adapter用法. */ public abstract class BaseRecyclerAdapter<T extends RecyclerView.ViewHolder,E> extends RecyclerView.Adapter<T> { private Context context; protected ArrayList<E> mDatas = new ArrayList<>(); protected LayoutInflater mInflater; protected int layoutItemId; protected List<Integer> mHeights; //随机item的高度 protected OnItemClickLitener mOnItemClickLitener; public interface OnItemClickLitener<E> { void onItemClick(View view, E bean, int position); void onItemLongClick(View view, E bean, int position); } public void setOnItemClickLitener(OnItemClickLitener mOnItemClickLitener) { this.mOnItemClickLitener = mOnItemClickLitener; } public BaseRecyclerAdapter(Context context, ArrayList<E> datas, int layoutItemId) { this.context = context; //mInflater = LayoutInflater.from(context); mDatas = datas; this.layoutItemId = layoutItemId; } public void substituteDatas(ArrayList<E> datas){ mDatas = datas; }//置换集合数据 public void clearDatas(){ mDatas.clear(); }//清空集合数据 public void addDatas(ArrayList<E> datas){ mDatas.addAll(datas); }//添加集合数据 @Override public T onCreateViewHolder(ViewGroup parent, int viewType) { View itemView = View.inflate(context, layoutItemId, null); //MyViewHolder holder = new MyViewHolder(mInflater.inflate(layoutItemId, parent, false)); return getViewHolder(itemView); } @Override public void onBindViewHolder(final T holder, final int position) { final E bean = mDatas.get(position); initItemView(holder,bean,position); // 如果设置了回调,则设置点击事件 if (mOnItemClickLitener != null) { holder.itemView.setOnClickListener(new OnClickListener() { @Override public void onClick(View v) { int pos = holder.getLayoutPosition(); mOnItemClickLitener.onItemClick(holder.itemView,bean,pos); } }); holder.itemView.setOnLongClickListener(new OnLongClickListener() { @Override public boolean onLongClick(View v) { int pos = holder.getLayoutPosition(); mOnItemClickLitener.onItemLongClick(holder.itemView,bean,pos); return true; } }); } } @Override public int getItemCount() { if (mDatas != null && mDatas.size() >= 0) { return mDatas.size(); } else { return 0; } } /** 返回 viewHolder */ protected abstract T getViewHolder(View itemView); /** 设置数据 */ protected abstract void initItemView(T holder,E bean,int position); public void addData(int position,E bean) { mDatas.add(position, bean); mHeights.add((int) (100 + Math.random() * 300)); notifyItemInserted(position); } public void removeData(int position) { mDatas.remove(position); notifyItemRemoved(position); } } /* public class GAdapter extends BaseRecyclerAdapter<GAdapter.MyHolder,BeanGirls.ShowapiResBodyBean.NewslistBean> { protected List<Integer> mHeights;//随机item的高度 private Context context; public GAdapter(Context context, ArrayList <BeanGirls.ShowapiResBodyBean.NewslistBean> datas, int layoutItemId) { super(context, datas, layoutItemId); this.context = context; mHeights = new ArrayList<>(); for (int i = 0; i < mDatas.size(); i++) { mHeights.add((int) (100 + Math.random() * 300)); } } @Override protected MyHolder getViewHolder(View itemView) { return new MyHolder(itemView); } @Override protected void initItemView(MyHolder holder, BeanGirls.ShowapiResBodyBean.NewslistBean bean,int position) { //int position = holder.getLayoutPosition(); // 设置随机高度 ---> 报空了... //ViewGroup.LayoutParams lp = holder.mGirlImage.getLayoutParams(); //lp.height = mHeights.get(position); //holder.mGirlImage.setLayoutParams(lp); holder.itemView.setTag(position);//设置item的 view内容数据 Glide.with(context) .load(bean.getPicUrl()) .centerCrop() .placeholder(R.color.global_background) .into(holder.mGirlImage); } class MyHolder extends RecyclerView.ViewHolder{ RatioImageView mGirlImage; public MyHolder(View itemView) { super(itemView); mGirlImage = (RatioImageView) itemView.findViewById(R.id.girl_image_item); mGirlImage.setRatio(0.618f);// set the ratio to golden ratio. } } } */
[ "tyxo842@163.com" ]
tyxo842@163.com
b5df69921490c7caa1619df91d99269ec811e558
400ab3de6b15a6a1f785c0f056c595df5e566b01
/leetcode/medium/3SumClosest.java
dbeec91c6e1ea420faeaefd329c6919bdd006573
[]
no_license
mshah87/Programming-Exercises
e05555bcdf2f3512d99a013c71c793f468fad15c
e0f1e566c7cfaa87b3ae4470863330b80e524eb9
refs/heads/master
2023-03-10T22:55:01.205074
2021-03-01T07:23:31
2021-03-01T07:23:31
148,363,352
1
0
null
null
null
null
UTF-8
Java
false
false
1,046
java
/* Given array nums = [-1, 2, 1, -4], and target = 1. The sum that is closest to the target is 2. (-1 + 2 + 1 = 2). */ class Solution { public int threeSumClosest(int[] nums, int target) { if(nums.length < 3 || nums == null){ return -1; } Arrays.sort(nums); //sort least to greatest int closestSum = nums[0] + nums[1] + nums [2]; for(int i = 0 ; i < nums.length-2; i++){ int start = i+1; int end = nums.length - 1; while(start<end){ int sum = nums[i] + nums[start] + nums[end]; if(Math.abs(target-sum) < Math.abs(target-closestSum)){ //find the minimum difference closestSum = sum; } if(sum<target){ //if sum is lower than target, move start pointer up start++; } else { end--; //if sum is bigger than target, move end pointer down } } } return closestSum; } }
[ "mauliksc87@outlook.com" ]
mauliksc87@outlook.com
66f6359e2926992078e737b0a5547efa6ee7aa74
12bf54c47847eb34d3af2ae66344e6e664d5fb2e
/catalog/src/main/java/com/pubkart/catalog/model/User.java
2d8aa86cf2e655d929f8540379fb0110ccad6641
[]
no_license
PinkyMittal/OrderService
856d90393a35dcc81071086070cb3ff1557fc968
0e467ff38d73896e7f910ca1f229db479f29ae9a
refs/heads/master
2022-05-07T06:28:03.341932
2019-10-18T17:39:17
2019-10-18T17:39:17
214,977,192
0
1
null
null
null
null
UTF-8
Java
false
false
339
java
package com.pubkart.catalog.model; import org.springframework.data.annotation.Id; import org.springframework.data.elasticsearch.annotations.Document; import lombok.Data; @Data @Document(indexName = "user", type = "user") public class User { @Id private String userId; private Cart cart; public User() { } }
[ "pinmitta@publicisgroupe.net" ]
pinmitta@publicisgroupe.net
e22b268648c31a5b4b3c05493816c0821da90c15
575c19e81594666f51cceb55cb1ab094b218f66b
/octopusconsortium/src/main/java/OctopusConsortium/Models/RCSGB/AllInfrastructureRootTemplateId.java
d2558ef3c7470e0b1477d7092abfbe926ccc591b
[ "Apache-2.0" ]
permissive
uk-gov-mirror/111online.ITK-MessagingEngine
62b702653ea716786e2684e3d368898533e77534
011e8cbe0bcb982eedc2204318d94e2bb5d4adb2
refs/heads/master
2023-01-22T17:47:54.631879
2020-12-01T14:18:05
2020-12-01T14:18:05
null
0
0
null
null
null
null
UTF-8
Java
false
false
1,864
java
// // This file was generated by the JavaTM Architecture for XML Binding(JAXB) Reference Implementation, vhudson-jaxb-ri-2.1-257 // See <a href="http://java.sun.com/xml/jaxb">http://java.sun.com/xml/jaxb</a> // Any modifications to this file will be lost upon recompilation of the source schema. // Generated on: 2012.10.24 at 11:01:41 AM BST // package OctopusConsortium.Models.RCSGB; import javax.xml.bind.annotation.XmlAccessType; import javax.xml.bind.annotation.XmlAccessorType; import javax.xml.bind.annotation.XmlAttribute; import javax.xml.bind.annotation.XmlType; /** * <p>Java class for all.InfrastructureRoot.templateId complex type. * * <p>The following schema fragment specifies the expected content contained within this class. * * <pre> * &lt;complexType name="all.InfrastructureRoot.templateId"> * &lt;complexContent> * &lt;extension base="{urn:hl7-org:v3}II"> * &lt;attribute name="unsorted" type="{http://www.w3.org/2001/XMLSchema}boolean" default="false" /> * &lt;/extension> * &lt;/complexContent> * &lt;/complexType> * </pre> * * */ @XmlAccessorType(XmlAccessType.FIELD) @XmlType(name = "all.InfrastructureRoot.templateId") public class AllInfrastructureRootTemplateId extends II { @XmlAttribute protected Boolean unsorted; /** * Gets the value of the unsorted property. * * @return * possible object is * {@link Boolean } * */ public boolean isUnsorted() { if (unsorted == null) { return false; } else { return unsorted; } } /** * Sets the value of the unsorted property. * * @param value * allowed object is * {@link Boolean } * */ public void setUnsorted(Boolean value) { this.unsorted = value; } }
[ "tom.axworthy@nhs.net" ]
tom.axworthy@nhs.net
6f30852c1afbd8c2d212e36b29906696b2b7f7ad
ab4c5454b4d55f591253aea90354cd10cd57a12e
/Hello/src/SayHello.java
cfb7a03674f92ee77b0d159089af7ddcec3d9b13
[]
no_license
kusejiubei/HelloWord
e35a93f0178cb1e2c03ff55eea87691f98520067
6bebab44b16adcbca185c04b3bb5fece2c5d038c
refs/heads/master
2021-01-10T08:00:59.674819
2015-09-29T03:25:45
2015-09-29T03:25:45
43,282,088
0
0
null
null
null
null
UTF-8
Java
false
false
127
java
public class SayHello { public static void main(String[] args) { System.out.println("---ss-----ss---111--------"); } }
[ "kusejiubei@sina.com" ]
kusejiubei@sina.com
a4ae9b979886e31bb37ccdc68c5d6801cc8cda07
7be7e6c667e018875172fb81c705d0e3b73391b6
/R05-01-Rot-Pilha-FilaCircular-environment/src/main/java/adt/stack/StackImpl.java
5d66d65bd7d6a329cac4feaa999f477ee1ff6d76
[]
no_license
natansouzaa/LEDA
3ca3f3277153eb99faf697da3ef3485c172a3c65
ab16d46f2ca8e9dfadbd0c310a4d0d43c3455a1c
refs/heads/master
2021-07-09T05:01:21.003038
2019-08-19T02:06:27
2019-08-19T02:06:27
202,939,370
0
0
null
2020-10-13T15:25:42
2019-08-17T23:14:11
Java
UTF-8
Java
false
false
872
java
package adt.stack; public class StackImpl<T> implements Stack<T> { private T[] array; private int top; @SuppressWarnings("unchecked") public StackImpl(int size) { array = (T[]) new Object[size]; top = -1; } @Override public T top() { T result = null; if (!isEmpty()){ result = array[top]; } return result; } @Override public boolean isEmpty() { if (top == -1){ return true; } return false; } @Override public boolean isFull() { if (top == array.length-1){ return true; } return false; } @Override public void push(T element) throws StackOverflowException { if (isFull()){ throw new StackOverflowException(); } top++; array[top] = element; } @Override public T pop() throws StackUnderflowException { if (isEmpty()){ throw new StackUnderflowException(); } top--; return array[top + 1]; } }
[ "38672106+natansouzaa@users.noreply.github.com" ]
38672106+natansouzaa@users.noreply.github.com
bee24457ad9c9f19a6ebfcc5379410fc9cb34590
6c605a7b9c372d15161baf22676e6ee825576d24
/src/main/java/com/ntlsoft/controller/MpaUsrMemberController.java
8cb7e7ff09da6980a84c8928eac1d3f928dc79a6
[]
no_license
brad0520/PROJECT02-NTLsoft-WebService
c121dbe87edb5ef984080de01a74999fce45fd00
f3899bf63aa47f8c53bc797b887f52ed3cbd4d6b
refs/heads/master
2023-04-10T18:24:10.449985
2021-05-01T16:09:35
2021-05-01T16:09:35
360,071,174
0
0
null
null
null
null
UTF-8
Java
false
false
6,159
java
package com.ntlsoft.controller; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpSession; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Controller; import org.springframework.web.bind.annotation.RequestMapping; import com.ntlsoft.dto.Member; import com.ntlsoft.dto.ResultData; import com.ntlsoft.dto.Rq; import com.ntlsoft.service.MemberService; import com.ntlsoft.util.Util; @Controller public class MpaUsrMemberController { @Autowired private MemberService memberService; @RequestMapping("/mpaUsr/member/mypage") public String showMypage(HttpServletRequest req) { return "mpaUsr/member/mypage"; } @RequestMapping("/mpaUsr/member/login") public String showLogin(HttpServletRequest req) { return "mpaUsr/member/login"; } @RequestMapping("/mpaUsr/member/doLogin") public String doLogin(HttpServletRequest req, HttpSession session, String loginId, String loginPw, String redirectUri) { if (Util.isEmpty(redirectUri)) { redirectUri = "/"; } Member member = memberService.getMemberByLoginId(loginId); if (member == null) { return Util.msgAndBack(req, loginId + "(은)는 존재하지 않는 로그인아이디 입니다."); } if (member.getLoginPw().equals(loginPw) == false) { return Util.msgAndBack(req, "비밀번호가 일치하지 않습니다."); } //HttpSession session = req.getSession(); session.setAttribute("loginedMemberId", member.getId()); String msg = "환영합니다."; return Util.msgAndReplace(req, msg, redirectUri); } @RequestMapping("/mpaUsr/member/doLogout") public String doLogout(HttpServletRequest req, HttpSession session) { session.removeAttribute("loginedMemberId"); String msg = "로그아웃 되었습니다."; return Util.msgAndReplace(req, msg, "/mpaUsr/home/main"); } @RequestMapping("/mpaUsr/member/join") public String showJoin(HttpServletRequest req) { return "mpaUsr/member/join"; } @RequestMapping("/mpaUsr/member/doJoin") public String doJoin(HttpServletRequest req, String loginId, String loginPw, String name, String nickname, String cellphoneNo, String email) { Member oldMember = memberService.getMemberByLoginId(loginId); if (oldMember != null) { return Util.msgAndBack(req, loginId + "(은)는 이미 사용중인 로그인아이디 입니다."); } ResultData joinRd = memberService.join(loginId, loginPw, name, nickname, cellphoneNo, email); if (joinRd.isFail()) { return Util.msgAndBack(req, joinRd.getMsg()); } return Util.msgAndReplace(req, joinRd.getMsg(), "/"); } @RequestMapping("/mpaUsr/member/modify") public String showModify(HttpServletRequest req) { return "mpaUsr/member/modify"; } @RequestMapping("/mpaUsr/member/doModify") public String doModify(HttpServletRequest req, String loginPw, String name, String nickname, String cellphoneNo, String email) { if (loginPw != null && loginPw.trim().length() == 0) { loginPw = null; } int id = ((Rq) req.getAttribute("rq")).getLoginedMemberId(); ResultData modifyRd = memberService.modify(id, loginPw, name, nickname, cellphoneNo, email); if (modifyRd.isFail()) { return Util.msgAndBack(req, modifyRd.getMsg()); } return Util.msgAndReplace(req, modifyRd.getMsg(), "/"); } @RequestMapping("/mpaUsr/member/findLoginId") public String showFindLoginId(HttpServletRequest req) { return "mpaUsr/member/findLoginId"; } @RequestMapping("/mpaUsr/member/doFindLoginId") public String doFindLoginId(HttpServletRequest req, String name, String email, String redirectUri) { if (Util.isEmpty(redirectUri)) { redirectUri = "/"; } Member member = memberService.getMemberByNameAndEmail(name, email); if (member == null) { return Util.msgAndBack(req, "일치하는 회원이 존재하지 않습니다."); } return Util.msgAndBack(req, String.format("회원님의 아이디는 `%s` 입니다.", member.getLoginId())); } @RequestMapping("/mpaUsr/member/findLoginPw") public String showFindLoginPw(HttpServletRequest req) { return "mpaUsr/member/findLoginPw"; } @RequestMapping("/mpaUsr/member/doFindLoginPw") public String doFindLoginPw(HttpServletRequest req, String loginId, String name, String email, String redirectUri) { if (Util.isEmpty(redirectUri)) { redirectUri = "/"; } Member member = memberService.getMemberByLoginId(loginId); if (member == null) { return Util.msgAndBack(req, "일치하는 회원이 존재하지 않습니다."); } if (member.getName().equals(name) == false) { return Util.msgAndBack(req, "일치하는 회원이 존재하지 않습니다."); } if (member.getEmail().equals(email) == false) { return Util.msgAndBack(req, "일치하는 회원이 존재하지 않습니다."); } ResultData notifyTempLoginPwByEmailRs = memberService.notifyTempLoginPwByEmail(member); return Util.msgAndReplace(req, notifyTempLoginPwByEmailRs.getMsg(), redirectUri); } @RequestMapping("/mpaUsr/member/checkPassword") public String showCheckPassword(HttpServletRequest req) { return "mpaUsr/member/checkPassword"; } @RequestMapping("/mpaUsr/member/doCheckPassword") public String doCheckPassword(HttpServletRequest req, String loginPw, String redirectUri) { Member loginedMember = ((Rq) req.getAttribute("rq")).getLoginedMember(); if (loginedMember.getLoginPw().equals(loginPw) == false) { return Util.msgAndBack(req, "비밀번호가 일치하지 않습니다."); } return Util.msgAndReplace(req, "", redirectUri); } }
[ "brad0135@gmail.com" ]
brad0135@gmail.com
5f1333aef5141e350c9347fa06339d5cd4df3d0e
dc1dbb7e5a4b95bf44170d2f51fd08b3814f2ac9
/data_defect4j/preprossed_method_corpus/Lang/27/org/apache/commons/lang3/BooleanUtils_toBooleanObject_227.java
4b909137891d433af19081bbb5674fdf10c41158
[]
no_license
hvdthong/NetML
dca6cf4d34c5799b400d718e0a6cd2e0b167297d
9bb103da21327912e5a29cbf9be9ff4d058731a5
refs/heads/master
2021-06-30T15:03:52.618255
2020-10-07T01:58:48
2020-10-07T01:58:48
150,383,588
1
1
null
2018-09-26T07:08:45
2018-09-26T07:08:44
null
UTF-8
Java
false
false
1,556
java
org apach common lang3 oper primit boolean object handl code code input gracefulli except thrown code code input method document behaviour detail thread safe threadsaf author apach softwar foundat author matthew hawthorn author gari gregori version boolean util booleanutil convert boolean convent code code code code pre boolean util booleanutil boolean toboolean boolean fals boolean util booleanutil boolean toboolean boolean true boolean util booleanutil boolean toboolean boolean true pre param convert boolean true boolean fals code code code code boolean boolean object tobooleanobject boolean fals boolean true
[ "hvdthong@gmail.com" ]
hvdthong@gmail.com
6069b354310a7264bd0abc93c2b92f8b33261664
0a3a87201b5517140684133710e1e1899b3a526d
/Homework2/src/ahadji08/hw2/PlayTheGame.java
32f4eb0b404af15374e25a32e7c2d841e9c435a3
[]
no_license
AndreasHadjivasili/JavaCode-133
2cb9b0692553ccc031eae1668dbb8015e05ca1c8
05fb0968516cf4b6d4b849106089b46b5a7a60d4
refs/heads/master
2022-12-17T13:48:59.734547
2020-09-18T16:30:11
2020-09-18T16:30:11
296,674,100
0
0
null
null
null
null
UTF-8
Java
false
false
862
java
package ahadji08.hw2; /** * This is class that the user runs to play the game. * * This class contains only one method, the main method that creates * a Game table to prepare the Game Settings and after it starts the * game by running the move method from the class Gametable. * * * * @author Andreas Hadjivasili * @since 11/2/19 * * */ public class PlayTheGame { /** * This is the main method. * * This method creates a Game table to prepare the Game * Settings as the user wants and after it starts the * game by running the move method from the class Gametable. * * @param args Is the default parameter that contains everything * that the user give as an input in the command line. */ public static void main(String[] args) { Gametable letspaly = new Gametable(); letspaly.move(); } }
[ "49360948+AndreasHadjivasili@users.noreply.github.com" ]
49360948+AndreasHadjivasili@users.noreply.github.com
83fb151968432ad201fc7a444cba4a12b403cfbe
8e48955316fe57b3b84533345aff30a7e2a8a3ed
/src/main/java/org/raftent/impl/messages/AddEntryRequest.java
e4e247f5c823563b1e06bae12fc8531e989d81db
[ "Apache-2.0" ]
permissive
jyangbos/raftent
bca411160419096771a0a54419efe27b0b894a91
06e422abf5a5390a8ee98fc6bc934b860f5907e1
refs/heads/master
2021-01-19T11:34:40.806745
2017-05-02T19:29:52
2017-05-02T19:29:52
87,978,146
0
0
null
null
null
null
UTF-8
Java
false
false
739
java
package org.raftent.impl.messages; import com.fasterxml.jackson.annotation.JsonTypeInfo; public class AddEntryRequest extends RaftMessage { private String requestId; private int nodeId; private long timestamp; @JsonTypeInfo(use = JsonTypeInfo.Id.CLASS) private Object data; public AddEntryRequest() {} public AddEntryRequest(String fsmId, String requestId, int nodeId, long timestamp, Object data) { super(fsmId); this.requestId = requestId; this.nodeId = nodeId; this.data = data; this.timestamp = timestamp; } public String getRequestId() { return requestId; } public int getNodeId() { return nodeId; } public long getTimestamp() { return timestamp; } public Object getData() { return data; } }
[ "jimy@vmware.com" ]
jimy@vmware.com
8d474aaf03fe9fa2c56992b211a4e27112ffc7b2
a2737d0163886ffcf338f97c16c0958563b5c071
/src/main/java/me/giraffetree/java/boomjava/alg/searching/leetcode/tree/medium/Str2tree.java
e8631e84c25aac9c59545dbbe7e83c8bbcbe5bad
[ "MIT" ]
permissive
giraffe-tree/boom-java
5c160d7d4643995ef4c9805f1c3f9c23905c6068
fe6f9c7e82098a97625b9ad68cf1589484c58cf7
refs/heads/master
2023-06-25T07:39:45.067062
2023-05-12T08:25:45
2023-05-12T08:25:45
215,749,977
1
0
MIT
2023-06-14T22:43:50
2019-10-17T09:08:54
Java
UTF-8
Java
false
false
1,354
java
package me.giraffetree.java.boomjava.alg.searching.leetcode.tree.medium; import me.giraffetree.java.boomjava.alg.searching.leetcode.tree.TreeNode; import java.util.ArrayList; /** * 你需要从一个包括括号和整数的字符串构建一棵二叉树。 * <p> * 输入的字符串代表一棵二叉树。它包括整数和随后的0,1或2对括号。整数代表根的值,一对括号内表示同样结构的子树。 * <p> * 若存在左子结点,则从左子结点开始构建。 * <p> * 示例: * <p> * 输入: "4(2(3)(1))(6(5))" * 输出: 返回代表下列二叉树的根节点: * <p> * # 4 * # / \ * # 2 6 * # / \ / * # 3 1 5 * * <p> * 注意: * <p> * 输入字符串中只包含 '(', ')', '-' 和 '0' ~ '9'  * 空树由 "" 而非"()"表示。 * <p> * 来源:力扣(LeetCode) * 链接:https://leetcode-cn.com/problems/construct-binary-tree-from-string * 著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。 * * @author GiraffeTree * @date 2020/1/19 */ public class Str2tree { public static void main(String[] args) { } public TreeNode str2tree(String s) { ArrayList<TreeNode> list = new ArrayList<>(); for (int i = 0; i < s.length(); i++) { } return null; } }
[ "giraffetree1@gmail.com" ]
giraffetree1@gmail.com
69130bec0822a88d21fb15bcdda656ad4d8ece11
dec841ce431c03bcf5b1454eab34de21a35376a5
/slick2d/src/org/newdawn/slick/particles/ConfigurableEmitterFactory.java
f4a7f91427740e7648655a415b61b237a92c94c1
[]
no_license
guts2014/Geeksoc
277b74ea57964ebd177d29a3cb7eddee444dd374
a24d19a9e933bdbe5675b9afc5e54f35bfc3ed10
refs/heads/master
2016-09-05T11:37:55.748602
2014-10-17T15:57:05
2014-10-17T15:57:05
25,053,159
0
1
null
2014-10-11T23:06:18
2014-10-10T21:05:17
Java
UTF-8
Java
false
false
494
java
package org.newdawn.slick.particles; /** * A description of any class that can create Configurable Emitters during the * ParticleIO load phase. * * @author kevin */ public interface ConfigurableEmitterFactory { /** * Create a configurable emitter that will be populated with loaded data * * @param name * The name given to the emitter * @return The newly created configurable emitter */ public ConfigurableEmitter createEmitter(String name); }
[ "robert.wilson1717@gmail.com" ]
robert.wilson1717@gmail.com
cb919292e7e530efe37993ac09cbdf92dc2a1c00
73929c9e4db4a738260e73842fd2f960b9edfcad
/app/src/main/java/com/example/letschat/ui/home/HomeFragment.java
d3d1283966d1bc5bca99b04fe6aeed49731cf7b5
[]
no_license
MohitSharma0101/chat_app
cf45d8fbdd214a1c811b568aab1cb5b3084bc301
95ac8f73eec5210225f14c20682cbce149269b25
refs/heads/master
2022-12-22T03:23:34.964477
2020-10-03T16:10:22
2020-10-03T16:10:22
null
0
0
null
null
null
null
UTF-8
Java
false
false
13,056
java
package com.example.letschat.ui.home; import android.annotation.TargetApi; import android.content.Context; import android.content.DialogInterface; import android.content.Intent; import android.content.pm.PackageManager; import android.database.Cursor; import android.net.Uri; import android.os.Build; import android.os.Bundle; import android.provider.ContactsContract; import android.util.Log; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.view.animation.Animation; import android.view.animation.AnimationUtils; import android.view.animation.LayoutAnimationController; import android.widget.LinearLayout; import android.widget.TextView; import android.widget.Toast; import androidx.annotation.NonNull; import androidx.annotation.Nullable; import androidx.appcompat.app.AlertDialog; import androidx.core.app.ActivityCompat; import androidx.core.content.ContextCompat; import androidx.fragment.app.Fragment; import androidx.lifecycle.Observer; import androidx.lifecycle.ViewModelProviders; import androidx.recyclerview.widget.LinearLayoutManager; import androidx.recyclerview.widget.RecyclerView; import androidx.recyclerview.widget.StaggeredGridLayoutManager; import com.example.letschat.Contacts; import com.example.letschat.MainActivity; import com.example.letschat.R; import com.example.letschat.message; import com.example.letschat.model.Adapter; import com.google.android.material.floatingactionbutton.FloatingActionButton; import com.google.android.material.snackbar.Snackbar; import com.google.firebase.auth.FirebaseAuth; import com.google.firebase.auth.FirebaseUser; import com.google.firebase.database.ChildEventListener; import com.google.firebase.database.DataSnapshot; import com.google.firebase.database.DatabaseError; import com.google.firebase.database.DatabaseReference; import com.google.firebase.database.FirebaseDatabase; import com.google.firebase.database.Query; import com.google.firebase.database.ValueEventListener; import java.util.ArrayList; import java.util.List; import java.util.Objects; import static com.example.letschat.Contacts.PERMISSIONS_REQUEST_READ_CONTACTS; public class HomeFragment extends Fragment { FirebaseDatabase firebaseDatabase; DatabaseReference databaseReference, databaseReference2; FirebaseUser firebaseUser; List<String> titles = new ArrayList<>(); List<String> contents = new ArrayList<>(); List<String> phones = new ArrayList<>(); List<String> times = new ArrayList<>(); ChildEventListener childEventListener; private HomeViewModel homeViewModel; RecyclerView recyclerView; Adapter adapter; TextView toolbarText; public View onCreateView(@NonNull LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { homeViewModel = ViewModelProviders.of(this).get(HomeViewModel.class); final View root = inflater.inflate(R.layout.fragment_home, container, false); recyclerView = root.findViewById(R.id.recycler); // toolbarText = getActivity().findViewById(R.id.title_text); // toolbarText.setText("CHATS"); int resId = R.anim.layout_fall; LayoutAnimationController animation = AnimationUtils.loadLayoutAnimation(getContext(), resId); recyclerView.setLayoutAnimation(animation); firebaseUser = FirebaseAuth.getInstance().getCurrentUser(); firebaseDatabase = FirebaseDatabase.getInstance(); databaseReference = firebaseDatabase.getReference("Inbox").child(firebaseUser.getPhoneNumber()); adapter = new Adapter(titles, contents, phones,times); recyclerView.setLayoutManager(new LinearLayoutManager(getContext())); recyclerView.setAdapter(adapter); // databaseReference.addChildEventListener(new ChildEventListener() { // @Override // public void onChildAdded(@NonNull DataSnapshot snapshot0, @Nullable String previousChildName) { // // String key = snapshot0.getKey().toString(); // phones.add(key); // titles.add(getContactName(key, getContext())); // // // Log.d("check3", String.valueOf(titles)); // // // String contentRef = snapshot0.getValue(String.class); // // databaseReference2 = firebaseDatabase.getReference("Chats"); // // assert contentRef != null; // Query q = databaseReference2.child(contentRef).orderByKey().limitToLast(1); // // q.addChildEventListener(new ChildEventListener() { // @Override // public void onChildAdded(@NonNull DataSnapshot snapshot, @Nullable String previousChildName) { // Log.d("check3", "ecx"); // message message = snapshot.getValue(com.example.letschat.message.class); // assert message != null; // String Content = message.getMessage(); // contents.add(Content); // // // } // // @Override // public void onChildChanged(@NonNull DataSnapshot snapshot, @Nullable String previousChildName) { // // } // // @Override // public void onChildRemoved(@NonNull DataSnapshot snapshot) { // // } // // @Override // public void onChildMoved(@NonNull DataSnapshot snapshot, @Nullable String previousChildName) { // // } // // @Override // public void onCancelled(@NonNull DatabaseError error) { // Log.d("check3", error.getMessage()); // } // }); // } // // @Override // public void onChildChanged(@NonNull DataSnapshot snapshot, @Nullable String previousChildName) { // // } // // @Override // public void onChildRemoved(@NonNull DataSnapshot snapshot) { // // } // // @Override // public void onChildMoved(@NonNull DataSnapshot snapshot, @Nullable String previousChildName) { // // } // // @Override // public void onCancelled(@NonNull DatabaseError error) { // // } // // }); childEventListener = new ChildEventListener() { @Override public void onChildAdded(@NonNull final DataSnapshot snapshot0, @Nullable String previousChildName) { String Content= snapshot0.getValue().toString(); Log.d("check3" , Content); DatabaseReference dr = FirebaseDatabase.getInstance().getReference("Chats"); final Query q = dr.child(Content).orderByKey().limitToLast(1); q.addChildEventListener(new ChildEventListener() { @Override public void onChildAdded(@NonNull DataSnapshot snapshot, @Nullable String previousChildName) { message msg= snapshot.getValue(message.class); String name = getContactName(snapshot0.getKey(),getContext()); assert msg != null; String number =snapshot0.getKey(); String content = msg.getMessage(); String currentTime = msg.getTime(); if(!phones.contains(number)){ titles.add(name); contents.add(content); phones.add(number); times.add(currentTime); adapter.notifyDataSetChanged(); } else { int index = phones.indexOf(number); contents.remove(index); contents.add(index,content); times.remove(index); times.add(index,currentTime); adapter.notifyDataSetChanged(); } // int i=contains(chatArrayList,number); // if(i==-1){ // chatArrayList.add(0,chat); // }else{ // chatArrayList.remove(i); // chatArrayList.add(0,chat); // } // // index.put(snapshot0.getKey(),i); // myAdapter.notifyDataSetChanged(); // Log.d("snumber",number); } @Override public void onChildChanged(@NonNull DataSnapshot snapshot, @Nullable String previousChildName) { } @Override public void onChildRemoved(@NonNull DataSnapshot snapshot) { } @Override public void onChildMoved(@NonNull DataSnapshot snapshot, @Nullable String previousChildName) { } @Override public void onCancelled(@NonNull DatabaseError error) { } }); } @Override public void onChildChanged(@NonNull DataSnapshot snapshot, @Nullable String previousChildName) { } @Override public void onChildRemoved(@NonNull DataSnapshot snapshot) { } @Override public void onChildMoved(@NonNull DataSnapshot snapshot, @Nullable String previousChildName) { } @Override public void onCancelled(@NonNull DatabaseError error) { } }; databaseReference.addChildEventListener(childEventListener); FloatingActionButton fab = root.findViewById(R.id.fab); fab.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { // Boolean permissionGranted = requestContactPermission(); // if (permissionGranted) { Intent intent = new Intent(getActivity(), Contacts.class); startActivity(intent); // } } }); return root; } // public Boolean requestContactPermission() { // Boolean permissionGranted = false; // if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) { // if (ContextCompat.checkSelfPermission(getContext(), android.Manifest.permission.READ_CONTACTS) != PackageManager.PERMISSION_GRANTED) { // if (ActivityCompat.shouldShowRequestPermissionRationale(getActivity(), // android.Manifest.permission.READ_CONTACTS)) { // AlertDialog.Builder builder = new AlertDialog.Builder(getContext()); // builder.setTitle("Read Contacts permission"); // builder.setPositiveButton(android.R.string.ok, null); // builder.setMessage("Please enable access to contacts."); // builder.setOnDismissListener(new DialogInterface.OnDismissListener() { // @TargetApi(Build.VERSION_CODES.M) // @Override // public void onDismiss(DialogInterface dialog) { // requestPermissions( // new String[] // {android.Manifest.permission.READ_CONTACTS} // , PERMISSIONS_REQUEST_READ_CONTACTS); // } // }); // builder.show(); // } else { // ActivityCompat.requestPermissions(getActivity(), // new String[]{android.Manifest.permission.READ_CONTACTS}, // PERMISSIONS_REQUEST_READ_CONTACTS); // } // } else { // permissionGranted = true; // } // } else { // permissionGranted = true; // } // return permissionGranted; // } public String getContactName(final String phoneNumber, Context context) { Uri uri = Uri.withAppendedPath(ContactsContract.PhoneLookup.CONTENT_FILTER_URI, Uri.encode(phoneNumber)); String[] projection = new String[]{ContactsContract.PhoneLookup.DISPLAY_NAME}; String contactName = ""; Cursor cursor = context.getContentResolver().query(uri, projection, null, null, null); if (cursor != null) { if (cursor.moveToFirst()) { contactName = cursor.getString(0); } cursor.close(); } return contactName; } @Override public void onStart() { super.onStart(); } }
[ "tilwanil818@gmail.com" ]
tilwanil818@gmail.com
3a690833f1c4d4fea3f6d54b160fe9f06763da05
afe6db4769d4524b0c9933499c90eb4672a88cf6
/src/main/java/com/cl/crm/service/RoleService.java
8e1740bc11c68bd46f469d59078ba08885a2b0ca
[]
no_license
Cheneye/crm
dafa8e27880f388a97d44af8e8e8cc7073c7994e
55cae80a88f216d465e81c16ca1f3a424f5a8a9f
refs/heads/master
2022-07-05T21:07:46.521752
2020-04-19T12:56:41
2020-04-19T12:56:41
254,000,408
0
0
null
2022-06-17T03:06:34
2020-04-08T06:08:09
HTML
UTF-8
Java
false
false
3,422
java
package com.cl.crm.service; import com.cl.base.BaseService; import com.cl.crm.dao.ModuleMapper; import com.cl.crm.dao.PermissionMapper; import com.cl.crm.dao.RoleMapper; import com.cl.crm.po.Permission; import com.cl.crm.po.Role; import com.cl.crm.utils.AssertUtil; import org.apache.commons.lang3.StringUtils; import org.springframework.stereotype.Service; import org.springframework.transaction.annotation.Propagation; import org.springframework.transaction.annotation.Transactional; import javax.annotation.Resource; import java.util.ArrayList; import java.util.Date; import java.util.List; import java.util.Map; @Service public class RoleService extends BaseService<Role,Integer> { @Resource private RoleMapper roleMapper; @Resource private PermissionMapper permissionMapper; @Resource private ModuleMapper moduleMapper; public List<Map<String,Object>> queryAllRoles(){ return roleMapper.queryAllRoles(); } public void saveRole(Role role) { AssertUtil.isTrue(StringUtils.isBlank(role.getRoleName()),"角色不能为空!"); Role temp = roleMapper.queryRoleByRoleName(role.getRoleName()); AssertUtil.isTrue(temp!=null,"该角色已存在!"); role.setCreateDate(new Date()); role.setUpdateDate(new Date()); role.setIsValid(1); AssertUtil.isTrue(insertSelective(role)<1,"角色添加失败!"); } public void updateRole(Role role) { AssertUtil.isTrue(null==role.getId()||null==selectByPrimaryKey(role.getId()),"待更新角色记录不存在!"); AssertUtil.isTrue(StringUtils.isBlank(role.getRoleName()),"角色名不能为空!"); Role temp = roleMapper.queryRoleByRoleName(role.getRoleName()); AssertUtil.isTrue(!(temp.getId().equals(role.getId())) && null!=temp,"该角色已存在!"); role.setUpdateDate(new Date()); AssertUtil.isTrue(updateByPrimaryKeySelective(role)<1,"角色更新失败!"); } public void deleteRole(Integer id) { Role temp = selectByPrimaryKey(id); AssertUtil.isTrue(null==id || null==temp,"待删除的角色记录不存在"); temp.setIsValid(0); temp.setUpdateDate(new Date()); AssertUtil.isTrue(updateByPrimaryKeySelective(temp)<1,"角色删除失败!"); } @Transactional(propagation = Propagation.REQUIRED) public void addGrant(Integer roleId,Integer[] mids){ AssertUtil.isTrue(null==roleId || null==selectByPrimaryKey(roleId),"授权用户不存在!" ); Integer count = permissionMapper.countPermissionByRoleId(roleId); if(count>0){ AssertUtil.isTrue(permissionMapper.deletePermissionsByRoleId(roleId)<1,"权限分配失败!"); } if(null!=mids && mids.length>0){ List<Permission> permissions =new ArrayList<>(); for (Integer mid : mids){ Permission permission = new Permission(); permission.setRoleId(roleId); permission.setModuleId(mid); permission.setCreateDate(new Date()); permission.setUpdateDate(new Date()); permission.setAclValue(moduleMapper.selectByPrimaryKey(mid).getOptValue()); permissions.add(permission); } AssertUtil.isTrue(permissionMapper.insertBatch(permissions)<mids.length,"授权失败!"); } } }
[ "3328177285@qq.com" ]
3328177285@qq.com
0a60c95c6e649a9ccfcd143b0ca0b1ac5056768b
c71a8bc66af8995a72e597e6a2d577c67c48aff0
/customer/src/com/android/handyman/service/FileCache.java
156b6c678ec66b465282729eac67a8e7705c23e2
[]
no_license
joneyThot/ThomasNewPRoject
35338e3f364bddc994f355ba774f3dc83c9e2554
7a7a480da0ca355e118fa95842d32e2f85b85c72
refs/heads/master
2021-09-08T13:55:23.387494
2018-03-10T01:52:17
2018-03-10T01:52:17
124,610,673
0
0
null
null
null
null
UTF-8
Java
false
false
1,469
java
package com.android.handyman.service; import java.io.File; import android.content.Context; public class FileCache { private File cacheDir; public FileCache(Context context){ //Find the dir at SDCARD to save cached images if (android.os.Environment.getExternalStorageState().equals( android.os.Environment.MEDIA_MOUNTED)) { //if SDCARD is mounted (SDCARD is present on device and mounted) cacheDir = new File( android.os.Environment.getExternalStorageDirectory(),"LazyList"); } else { // if checking on simulator the create cache dir in your application context cacheDir=context.getCacheDir(); } if(!cacheDir.exists()){ // create cache dir in your application context cacheDir.mkdirs(); } } public File getFile(String url){ //Identify images by hashcode or encode by URLEncoder.encode. String filename=String.valueOf(url.hashCode()); File f = new File(cacheDir, filename); return f; } public void clear(){ // list all files inside cache directory File[] files=cacheDir.listFiles(); if(files==null) return; //delete all cache directory files for(File f:files) f.delete(); } }
[ "joney143pinky@gmail.com" ]
joney143pinky@gmail.com
ea64f569177a52f6cd50c128fde864a5a6d5988d
ede303bc5b514e53f1be9d2f5d98ff114bc5d855
/platform/built-in-server/src/org/jetbrains/io/jsonRpc/JsonRpcServer.java
73dee8c76ad68a2eb969f325403222f7a62068e9
[]
no_license
dexwest/intellij-community
1a4d4f79f5585961f3273ed404f8f0b8daf724f3
ca1d48070ffecba52970a7cb5568a8b38c82dfce
refs/heads/master
2020-12-29T03:19:29.672546
2015-02-11T21:55:31
2015-02-11T21:55:31
null
0
0
null
null
null
null
UTF-8
Java
false
false
12,107
java
package org.jetbrains.io.jsonRpc; import com.google.gson.*; import com.google.gson.internal.Streams; import com.google.gson.reflect.TypeToken; import com.google.gson.stream.JsonToken; import com.google.gson.stream.JsonWriter; import com.intellij.openapi.diagnostic.Logger; import com.intellij.openapi.util.AsyncResult; import com.intellij.openapi.util.NotNullLazyValue; import com.intellij.openapi.util.Pair; import com.intellij.openapi.util.Ref; import com.intellij.util.ArrayUtil; import com.intellij.util.ArrayUtilRt; import com.intellij.util.Consumer; import com.intellij.util.SmartList; import com.intellij.util.text.CharSequenceBackedByArray; import gnu.trove.THashMap; import gnu.trove.TIntArrayList; import gnu.trove.TIntProcedure; import io.netty.buffer.ByteBuf; import io.netty.buffer.Unpooled; import io.netty.util.CharsetUtil; import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.Nullable; import org.jetbrains.io.JsonReaderEx; import org.jetbrains.io.JsonUtil; import org.jetbrains.io.webSocket.Client; import org.jetbrains.io.webSocket.ExceptionHandler; import org.jetbrains.io.webSocket.MessageServer; import org.jetbrains.io.webSocket.WebSocketServer; import java.io.IOException; import java.lang.reflect.Method; import java.lang.reflect.Type; import java.util.List; import java.util.Map; import java.util.concurrent.atomic.AtomicInteger; public class JsonRpcServer implements MessageServer { protected static final Logger LOG = Logger.getInstance(JsonRpcServer.class); private static final TypeAdapterFactory INT_LIST_TYPE_ADAPTER_FACTORY = new TypeAdapterFactory() { private IntArrayListTypeAdapter<TIntArrayList> typeAdapter; @Nullable @Override public <T> TypeAdapter<T> create(Gson gson, TypeToken<T> type) { if (type.getType() != TIntArrayList.class) { return null; } if (typeAdapter == null) { typeAdapter = new IntArrayListTypeAdapter<TIntArrayList>(); } //noinspection unchecked return (TypeAdapter<T>)typeAdapter; } }; private final AtomicInteger messageIdCounter = new AtomicInteger(); private final WebSocketServer webSocketServer; private final ExceptionHandler exceptionHandler; private final Gson gson; private final Map<String, NotNullLazyValue> domains = new THashMap<String, NotNullLazyValue>(); public JsonRpcServer(@NotNull WebSocketServer webSocketServer, @NotNull ExceptionHandler exceptionHandler) { this.webSocketServer = webSocketServer; this.exceptionHandler = exceptionHandler; gson = new GsonBuilder().registerTypeAdapter(CharSequenceBackedByArray.class, new JsonSerializer<CharSequenceBackedByArray>() { @Override public JsonElement serialize(CharSequenceBackedByArray src, Type typeOfSrc, JsonSerializationContext context) { return new JsonPrimitive(src.toString()); } }).registerTypeAdapterFactory(INT_LIST_TYPE_ADAPTER_FACTORY).disableHtmlEscaping().create(); } public void registerDomain(@NotNull String name, @NotNull NotNullLazyValue commands) { registerDomain(name, commands, false); } public void registerDomain(@NotNull String name, @NotNull NotNullLazyValue commands, boolean overridable) { if (domains.containsKey(name)) { if (overridable) { return; } else { throw new IllegalArgumentException(name + " is already registered"); } } domains.put(name, commands); } @Override public void message(@NotNull Client client, String message) throws IOException { if (LOG.isDebugEnabled()) { LOG.debug("IN " + message); } JsonReaderEx reader = new JsonReaderEx(message); reader.beginArray(); int messageId = reader.peek() == JsonToken.NUMBER ? reader.nextInt() : -1; String domainName = reader.nextString(); if (domainName.length() == 1) { AsyncResult asyncResult = webSocketServer.removeAsyncResult(client, messageId); if (domainName.charAt(0) == 'r') { if (asyncResult == null) { LOG.error("Response with id " + messageId + " was already processed"); return; } //noinspection unchecked asyncResult.setDone(JsonUtil.nextAny(reader)); } else { asyncResult.setRejected(); } return; } NotNullLazyValue domainHolder = domains.get(domainName); if (domainHolder == null) { LOG.error("Cannot find domain " + domainName); return; } Object domain = domainHolder.getValue(); String command = reader.nextString(); if (domain instanceof JsonServiceInvocator) { ((JsonServiceInvocator)domain).invoke(command, client, reader, message, messageId); return; } Object[] parameters; if (reader.hasNext()) { List<Object> list = new SmartList<Object>(); JsonUtil.readListBody(reader, list); parameters = ArrayUtil.toObjectArray(list); } else { parameters = ArrayUtilRt.EMPTY_OBJECT_ARRAY; } reader.endArray(); LOG.assertTrue(reader.peek() == JsonToken.END_DOCUMENT); try { boolean isStatic = domain instanceof Class; Method[] methods; if (isStatic) { methods = ((Class)domain).getDeclaredMethods(); } else { methods = domain.getClass().getMethods(); } for (Method method : methods) { if (method.getName().equals(command)) { method.setAccessible(true); Object result = method.invoke(isStatic ? null : domain, parameters); if (messageId != -1) { ByteBuf response = encodeMessage(messageId, null, null, new Object[]{result}); if (response != null) { webSocketServer.sendResponse(client, response); } } return; } } throw new NoSuchMethodException(command); } catch (Throwable e) { throw new IOException(e); } } public void sendResponse(int messageId, @NotNull Client client, @Nullable CharSequence rawMessage) { ByteBuf response = encodeMessage(messageId, null, null, rawMessage, ArrayUtil.EMPTY_OBJECT_ARRAY); assert response != null; webSocketServer.sendResponse(client, response); } public void sendErrorResponse(int messageId, @NotNull Client client, @Nullable CharSequence rawMessage) { ByteBuf response = encodeMessage(messageId, "e", null, rawMessage, ArrayUtil.EMPTY_OBJECT_ARRAY); assert response != null; webSocketServer.sendResponse(client, response); } public void send(String domain, String name) { send(domain, name, null); } public <T> void send(String domain, String command, @Nullable final List<AsyncResult<Pair<Client, T>>> results, Object... params) { if (webSocketServer.hasClients()) { send(results == null ? -1 : messageIdCounter.getAndIncrement(), domain, command, results, params); } } @Nullable private ByteBuf encodeMessage(int messageId, @Nullable String domain, @Nullable String command, Object[] params) { return encodeMessage(messageId, domain, command, null, params); } @Nullable private ByteBuf encodeMessage(int messageId, @Nullable String domain, @Nullable String command, @Nullable CharSequence rawMessage, @Nullable Object[] params) { StringBuilder sb = new StringBuilder(); try { encodeCall(sb, messageId, domain, command, params, rawMessage); if (LOG.isDebugEnabled()) { LOG.debug("OUT " + sb.toString()); } return Unpooled.copiedBuffer(sb, CharsetUtil.UTF_8); } catch (IOException e) { exceptionHandler.exceptionCaught(e); return null; } } public boolean sendWithRawPart(Client client, String domain, String command, @Nullable CharSequence rawMessage, Object... params) { ByteBuf message = encodeMessage(-1, domain, command, rawMessage, params); if (message != null) { webSocketServer.send(client, -1, message); } return message != null; } public void send(Client client, String domain, String command, Object... params) { sendWithRawPart(client, domain, command, null, params); } public <T> AsyncResult<T> call(Client client, String domain, String command, Object... params) { int messageId = messageIdCounter.getAndIncrement(); ByteBuf message = encodeMessage(messageId, domain, command, params); if (message == null) { return new AsyncResult.Rejected<T>(); } AsyncResult<T> result = webSocketServer.send(client, messageId, message); return result == null ? new AsyncResult.Rejected<T>() : result; } private <T> void send(int messageId, @Nullable String domain, @Nullable String command, @Nullable final List<AsyncResult<Pair<Client, T>>> results, Object[] params) { ByteBuf message = encodeMessage(messageId, domain, command, params); if (message != null) { doSend(messageId, results, message); } } protected <T> void doSend(int messageId, List<AsyncResult<Pair<Client, T>>> results, ByteBuf message) { webSocketServer.send(messageId, message, results); } private void encodeCall(StringBuilder sb, int id, @Nullable String domain, @Nullable String command, @Nullable Object[] params, @Nullable CharSequence rawData) throws IOException { sb.append('['); boolean hasPrev = false; if (id != -1) { sb.append(id); hasPrev = true; } if (domain != null) { if (hasPrev) { sb.append(','); } sb.append('"').append(domain).append("\",\""); if (command == null) { if (rawData != null) { sb.append(rawData); } sb.append('"'); return; } else { sb.append(command).append('"'); } } encodeParameters(sb, params == null ? ArrayUtil.EMPTY_OBJECT_ARRAY : params, rawData); sb.append(']'); } private void encodeParameters(StringBuilder sb, Object[] params, @Nullable CharSequence rawData) throws IOException { if (params.length == 0 && rawData == null) { return; } JsonWriter writer = null; sb.append(',').append('['); boolean hasPrev = false; for (Object param : params) { if (hasPrev) { sb.append(','); } else { hasPrev = true; } // gson - SOE if param has type class com.intellij.openapi.editor.impl.DocumentImpl$MyCharArray, so, use hack if (param instanceof CharSequence) { JsonUtil.escape(((CharSequence)param), sb); } else if (param == null) { sb.append("null"); } else if (param instanceof Number || param instanceof Boolean) { sb.append(param.toString()); } else if (param instanceof Consumer) { //noinspection unchecked ((Consumer<StringBuilder>)param).consume(sb); } else { if (writer == null) { writer = new JsonWriter(Streams.writerForAppendable(sb)); } //noinspection unchecked ((TypeAdapter<Object>)gson.getAdapter(param.getClass())).write(writer, param); } } if (rawData != null) { if (hasPrev) { sb.append(','); } sb.append(rawData); } sb.append(']'); } private static class IntArrayListTypeAdapter<T> extends TypeAdapter<T> { @Override public void write(final JsonWriter out, T value) throws IOException { final Ref<IOException> error = new Ref<IOException>(); out.beginArray(); ((TIntArrayList)value).forEach(new TIntProcedure() { @Override public boolean execute(int value) { try { out.value(value); } catch (IOException e) { error.set(e); } return error.isNull(); } }); if (!error.isNull()) { throw error.get(); } out.endArray(); } @Override public T read(com.google.gson.stream.JsonReader in) throws IOException { throw new UnsupportedOperationException(); } } }
[ "vladimir.krivosheev@jetbrains.com" ]
vladimir.krivosheev@jetbrains.com
05ae766a39443e48ce792f8dbda31cf550bf2e06
485de0cd462ab8c38a49de124345ee6477007dec
/src/main/java/arun/spring/domain/Ingredient.java
8d7c74c49af6f1212405292b412236e99b1296e1
[]
no_license
arunhareesh/spring5-recipe-app
c98efdd9d5dc7cdee068a95a8e76c3ed461ae83e
9f75e53b0ca9244fa8373964d3a062efbf7c6dc2
refs/heads/master
2023-03-28T00:21:42.439859
2021-03-30T07:31:54
2021-03-30T07:31:54
307,618,097
0
0
null
null
null
null
UTF-8
Java
false
false
930
java
package arun.spring.domain; import lombok.Data; import lombok.EqualsAndHashCode; import javax.persistence.*; import java.math.BigDecimal; @Data @EqualsAndHashCode(exclude = {"recipe"}) @Entity public class Ingredient { @Id @GeneratedValue(strategy = GenerationType.IDENTITY) private Long id; private String description; private BigDecimal amount; @OneToOne(fetch = FetchType.EAGER) private UnitOfMeasure uom; @ManyToOne private Recipe recipe; public Ingredient() { } public Ingredient(String description, BigDecimal amount, UnitOfMeasure uom) { this.description = description; this.amount = amount; this.uom = uom; } public Ingredient(String description, BigDecimal amount, UnitOfMeasure uom, Recipe recipe) { this.description = description; this.amount = amount; this.uom = uom; this.recipe = recipe; } }
[ "arun_h@hotmail.com" ]
arun_h@hotmail.com
45c034a1b89e1c269e09e910d863921d6b6ea12c
edb3c8afbbabbaa70510877ca7623271b21332aa
/app/src/main/java/com/example/agriculturetabbed/sell_milk.java
22ca17384b7c030d9cfba7eeca7fccacfa768464
[]
no_license
vikash2021/Retail_Agri
5284a395a5bea05ddf553b8f687c926dbb191d5e
a7c65c4e7e1aff7e3ab14e7032ef113194fe4f73
refs/heads/master
2022-02-18T07:37:16.706322
2019-09-01T10:57:25
2019-09-01T10:57:25
null
0
0
null
null
null
null
UTF-8
Java
false
false
1,620
java
package com.example.agriculturetabbed; import androidx.appcompat.app.AppCompatActivity; import android.content.Intent; import android.os.Bundle; import android.os.Handler; import android.view.View; import android.widget.Button; import android.widget.EditText; public class sell_milk extends AppCompatActivity { EditText Amount,Name,Number,address1,address2; Button button; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_sell_milk); Amount=(EditText)findViewById(R.id.am1); Name=(EditText)findViewById(R.id.am2); Number=(EditText)findViewById(R.id.am3); address1=(EditText)findViewById(R.id.am4); address2=(EditText)findViewById(R.id.am5); button=(Button) findViewById(R.id.btn2); button.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { startActivity(new Intent(getApplicationContext(), sell_confirmation.class)); Amount.setText(""); Name.setText(""); Number.setText(""); address1.setText(""); address2.setText(""); final Handler handler = new Handler(); handler.postDelayed(new Runnable() { @Override public void run() { startActivity(new Intent(getApplicationContext(),milk_sell_purchase.class)); } }, 4000); } }); } }
[ "cshekhar11148@gmail.com" ]
cshekhar11148@gmail.com
84a595be1343aeebcbe1e39c3a3e0a8ecd1be690
b8bd4438f7d000cb7af3d7d433f9d5e1dcb60ae1
/preflight/src/main/java/org/apache/pdfbox/preflight/annotation/PrintMarkAnnotationValidator.java
ad9515d063941a9e1ed9855e6da61cba09e360e7
[ "Apache-2.0", "LicenseRef-scancode-unknown", "BSD-3-Clause", "LicenseRef-scancode-generic-cla", "APAFML", "Adobe-Glyph", "LicenseRef-scancode-unknown-license-reference" ]
permissive
balabit-deps/balabit-os-7-libpdfbox-java
32dacbfbb1658e1152e48e6d4d09c907122ebcf0
3ba7c1c0f139bcbd09292e695b1195e0cda61046
refs/heads/master
2021-06-07T16:05:20.916694
2019-04-18T11:15:26
2019-04-18T11:15:26
158,242,475
0
0
Apache-2.0
2021-04-26T18:40:17
2018-11-19T15:01:22
Java
UTF-8
Java
false
false
2,502
java
/***************************************************************************** * * 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.pdfbox.preflight.annotation; import static org.apache.pdfbox.preflight.PreflightConstants.ERROR_ANNOT_MISSING_FIELDS; import org.apache.pdfbox.cos.COSDictionary; import org.apache.pdfbox.cos.COSName; import org.apache.pdfbox.pdmodel.interactive.annotation.PDAnnotationUnknown; import org.apache.pdfbox.preflight.PreflightContext; import org.apache.pdfbox.preflight.ValidationResult.ValidationError; /** * Validation class for the PopupAnnotation */ public class PrintMarkAnnotationValidator extends AnnotationValidator { /** * PDFBox object which wraps the annotation dictionary */ protected PDAnnotationUnknown pdUnk = null; public PrintMarkAnnotationValidator(PreflightContext ctx, COSDictionary annotDictionary) { super(ctx, annotDictionary); this.pdUnk = new PDAnnotationUnknown(annotDictionary); this.pdAnnot = this.pdUnk; } /* * (non-Javadoc) * * @seenet.awl.edoc.pdfa.validation.annotation.AnnotationValidator# checkMandatoryFields(java.util.List) */ protected boolean checkMandatoryFields() { boolean subtype = this.annotDictionary.containsKey(COSName.SUBTYPE); boolean rect = this.annotDictionary.containsKey(COSName.RECT); boolean f = this.annotDictionary.containsKey(COSName.F); boolean result = (subtype && rect && f); if (!result) { ctx.addValidationError(new ValidationError(ERROR_ANNOT_MISSING_FIELDS)); } return result; } }
[ "testbot@balabit.com" ]
testbot@balabit.com