text
stringlengths 10
2.72M
|
|---|
package com.sourceit.converter.jaxb;
import com.sourceit.entity.Employee;
import javax.xml.bind.annotation.XmlElement;
import javax.xml.bind.annotation.XmlRootElement;
import java.util.ArrayList;
import java.util.List;
@XmlRootElement(name = "Employees")
public class EmployeeList {
private List<Employee> employeeList = new ArrayList<Employee>();
public EmployeeList() {
}
public EmployeeList(List<Employee> employeeList) {
this.employeeList = employeeList;
}
@XmlElement(name = "employee")
public List<Employee> getEmployeeList() {
return employeeList;
}
public void setEmployeeList(ArrayList<Employee> employeeList) {
this.employeeList = employeeList;
}
@Override
public String toString() {
return employeeList.toString();
}
}
|
package br.com.formacao.java.collections.java;
/**
* Classe que representa o Teste de Cursos com alunos
*
* @author Guilherme Vilela
* @version 0.1
*/
public class TestaCursoComAluno {
/**
*
* @param args
*/
public static void main(String[] args) {
Curso javaColecoes = new Curso("Dominando as cole��es", "Paulo Silveira");
javaColecoes.adiciona(new Aula("Trabalhando com ArrayList", 21));
javaColecoes.adiciona(new Aula("Criando uma aula", 20));
javaColecoes.adiciona(new Aula("Modelando com cole��es", 24));
Aluno a1 = new Aluno("Rodrigo Turini", 34672);
Aluno a2 = new Aluno("Guilherme Silveira", 5617);
Aluno a3 = new Aluno("Mauricio Aniche", 17645);
javaColecoes.matricular(a1);
javaColecoes.matricular(a2);
javaColecoes.matricular(a3);
System.out.println("Todos os alunos matriculados nesse curso: ");
javaColecoes.getAlunos().forEach(a -> {
System.out.println(a);
});
System.out.println("O aluno: " + a1 + " est� matriculado");
System.out.println(javaColecoes.estaMatriculado(a1));
Aluno turini = new Aluno("Rodrigo Turini", 34672);
System.out.println("E ese Turini, est� matriculado?");
System.out.println(javaColecoes.estaMatriculado(turini));
System.out.println("O a1 � equals ao Turino?");
System.out.println(a1.equals(turini));
}
}
|
package todo.entity;
import javax.xml.bind.annotation.XmlRootElement;
@XmlRootElement
public class StockJSON {
private int quantity;
private int itemID;
private int branchID;
/**
*
*/
public StockJSON() {
}
@Override
public String toString() {
return "StockJSON [quantity=" + quantity + ", itemID=" + itemID
+ ", branchID=" + branchID + "]";
}
public int getQuantity() {
return quantity;
}
public void setQuantity(int quantity) {
this.quantity = quantity;
}
public int getItemID() {
return itemID;
}
public void setItemID(int itemID) {
this.itemID = itemID;
}
public int getBranchID() {
return branchID;
}
public void setBranchID(int branchID) {
this.branchID = branchID;
}
/**
* @param quantity
* @param itemID
* @param branchID
*/
public StockJSON(int quantity, int itemID, int branchID) {
super();
this.quantity = quantity;
this.itemID = itemID;
this.branchID = branchID;
}
}
|
package main;
import modelo.Respuesta;
import modelo.RestCall;
import persistencia.EnArchivo;
import persistencia.EnBD;
public class Main4 {
public static void main(String[] args) {
// RestCall rest = new RestCall("https://jsonplaceholder.typicode.com/posts");
// System.out.println(rest.run());
Respuesta resp = new EnBD(new EnArchivo(new RestCall()));
resp.run();
}
}
|
package com.gsrikar.roomconnectiontest;
import android.content.Intent;
import android.os.Bundle;
import android.os.Looper;
import android.os.Process;
import android.support.v7.app.AppCompatActivity;
import android.util.Log;
import static com.gsrikar.roomconnectiontest.utils.DatabaseUtils.insertPersonData;
public class MainActivity extends AppCompatActivity {
private static final String TAG = MainActivity.class.getSimpleName();
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
startService(new Intent(this, Pro1Service.class));
startService(new Intent(this, Pro2Service.class));
for (int h = 0; h < 4; h++) {
final int finalH = h;
final Thread thread1 = new Thread() {
@Override
public void run() {
for (int i = 0; i < 500; i++) {
if (i % 10 == 0) {
for (int j = 0; j < 10; j++) {
Log.d(TAG, "Thread 1 (" + finalH + "), i: " + i + " running at " + Process.myTid()
+ " which is main thread " +
(Looper.myLooper() == Looper.getMainLooper()));
insertPersonData(getApplicationContext());
}
} else {
Log.d(TAG, "Thread 1 (" + finalH + "), j: " + i + " running at " + Process.myTid()
+ " which is main thread " +
(Looper.myLooper() == Looper.getMainLooper()));
insertPersonData(getApplicationContext());
}
}
}
};
thread1.start();
final Thread thread2 = new Thread() {
@Override
public void run() {
for (int i = 0; i < 500; i++) {
if (i % 10 == 0) {
for (int j = 0; j < 10; j++) {
Log.d(TAG, "Thread 2 (" + finalH + "), i: " + i + " running at " + Process.myTid()
+ " which is main thread " +
(Looper.myLooper() == Looper.getMainLooper()));
insertPersonData(getApplicationContext());
}
} else {
Log.d(TAG, "Thread 2 (" + finalH + "), j: " + i + " running at " + Process.myTid()
+ " which is main thread " +
(Looper.myLooper() == Looper.getMainLooper()));
insertPersonData(getApplicationContext());
}
}
}
};
thread2.start();
}
}
}
|
package trainedge.scoop.Model;
import com.google.firebase.database.DataSnapshot;
/**
* Created by hp on 19-Apr-17.
*/
public class FavModel {
private final String title;
private final String link;
private final String image;
public FavModel(DataSnapshot snapshot) {
title = snapshot.child("title").getValue(String.class);
link = snapshot.child("link").getValue(String.class);
image = snapshot.child("image").getValue(String.class);
}
public String getTitle() {
return title;
}
public String getLink() {
return link;
}
public String getImage() {
return image;
}
}
|
package com.mysql.cj;
import com.mysql.cj.exceptions.CJException;
import com.mysql.cj.exceptions.ExceptionFactory;
import com.mysql.cj.exceptions.ExceptionInterceptor;
import com.mysql.cj.protocol.a.NativeConstants;
import com.mysql.cj.protocol.a.NativePacketPayload;
import com.mysql.cj.util.StringUtils;
import java.sql.Timestamp;
import java.util.Calendar;
import java.util.Date;
import java.util.Locale;
import java.util.TimeZone;
public class ServerPreparedQueryBindValue extends ClientPreparedQueryBindValue implements BindValue {
public long boundBeforeExecutionNum = 0L;
public int bufferType;
public Calendar calendar;
private TimeZone defaultTimeZone;
protected String charEncoding = null;
public ServerPreparedQueryBindValue(TimeZone defaultTZ) {
this.defaultTimeZone = defaultTZ;
}
public ServerPreparedQueryBindValue clone() {
return new ServerPreparedQueryBindValue(this);
}
private ServerPreparedQueryBindValue(ServerPreparedQueryBindValue copyMe) {
super(copyMe);
this.defaultTimeZone = copyMe.defaultTimeZone;
this.bufferType = copyMe.bufferType;
this.calendar = copyMe.calendar;
this.charEncoding = copyMe.charEncoding;
}
public void reset() {
super.reset();
this.calendar = null;
this.charEncoding = null;
}
public boolean resetToType(int bufType, long numberOfExecutions) {
boolean sendTypesToServer = false;
reset();
if (bufType != 6 || this.bufferType == 0)
if (this.bufferType != bufType) {
sendTypesToServer = true;
this.bufferType = bufType;
}
this.isSet = true;
this.boundBeforeExecutionNum = numberOfExecutions;
return sendTypesToServer;
}
public String toString() {
return toString(false);
}
public String toString(boolean quoteIfNeeded) {
if (this.isStream)
return "' STREAM DATA '";
if (this.isNull)
return "NULL";
switch (this.bufferType) {
case 1:
case 2:
case 3:
case 8:
return String.valueOf(((Long)this.value).longValue());
case 4:
return String.valueOf(((Float)this.value).floatValue());
case 5:
return String.valueOf(((Double)this.value).doubleValue());
case 7:
case 10:
case 11:
case 12:
case 15:
case 253:
case 254:
if (quoteIfNeeded)
return "'" + String.valueOf(this.value) + "'";
return String.valueOf(this.value);
}
if (this.value instanceof byte[])
return "byte data";
if (quoteIfNeeded)
return "'" + String.valueOf(this.value) + "'";
return String.valueOf(this.value);
}
public long getBoundLength() {
if (this.isNull)
return 0L;
if (this.isStream)
return this.streamLength;
switch (this.bufferType) {
case 1:
return 1L;
case 2:
return 2L;
case 3:
return 4L;
case 8:
return 8L;
case 4:
return 4L;
case 5:
return 8L;
case 11:
return 9L;
case 10:
return 7L;
case 7:
case 12:
return 11L;
case 0:
case 15:
case 246:
case 253:
case 254:
if (this.value instanceof byte[])
return ((byte[])this.value).length;
return ((String)this.value).length();
}
return 0L;
}
public void storeBinding(NativePacketPayload intoPacket, boolean isLoadDataQuery, String characterEncoding, ExceptionInterceptor interceptor) {
synchronized (this) {
try {
switch (this.bufferType) {
case 1:
intoPacket.writeInteger(NativeConstants.IntegerDataType.INT1, ((Long)this.value).longValue());
return;
case 2:
intoPacket.writeInteger(NativeConstants.IntegerDataType.INT2, ((Long)this.value).longValue());
return;
case 3:
intoPacket.writeInteger(NativeConstants.IntegerDataType.INT4, ((Long)this.value).longValue());
return;
case 8:
intoPacket.writeInteger(NativeConstants.IntegerDataType.INT8, ((Long)this.value).longValue());
return;
case 4:
intoPacket.writeInteger(NativeConstants.IntegerDataType.INT4, Float.floatToIntBits(((Float)this.value).floatValue()));
return;
case 5:
intoPacket.writeInteger(NativeConstants.IntegerDataType.INT8, Double.doubleToLongBits(((Double)this.value).doubleValue()));
return;
case 11:
storeTime(intoPacket);
return;
case 7:
case 10:
case 12:
storeDateTime(intoPacket);
return;
case 0:
case 15:
case 246:
case 253:
case 254:
if (this.value instanceof byte[]) {
intoPacket.writeBytes(NativeConstants.StringSelfDataType.STRING_LENENC, (byte[])this.value);
} else if (!isLoadDataQuery) {
intoPacket.writeBytes(NativeConstants.StringSelfDataType.STRING_LENENC, StringUtils.getBytes((String)this.value, characterEncoding));
} else {
intoPacket.writeBytes(NativeConstants.StringSelfDataType.STRING_LENENC, StringUtils.getBytes((String)this.value));
}
return;
}
} catch (CJException uEE) {
throw ExceptionFactory.createException(Messages.getString("ServerPreparedStatement.22") + characterEncoding + "'", uEE, interceptor);
}
}
}
private void storeTime(NativePacketPayload intoPacket) {
intoPacket.ensureCapacity(9);
intoPacket.writeInteger(NativeConstants.IntegerDataType.INT1, 8L);
intoPacket.writeInteger(NativeConstants.IntegerDataType.INT1, 0L);
intoPacket.writeInteger(NativeConstants.IntegerDataType.INT4, 0L);
if (this.calendar == null)
this.calendar = Calendar.getInstance(this.defaultTimeZone, Locale.US);
this.calendar.setTime((Date)this.value);
intoPacket.writeInteger(NativeConstants.IntegerDataType.INT1, this.calendar.get(11));
intoPacket.writeInteger(NativeConstants.IntegerDataType.INT1, this.calendar.get(12));
intoPacket.writeInteger(NativeConstants.IntegerDataType.INT1, this.calendar.get(13));
}
private void storeDateTime(NativePacketPayload intoPacket) {
synchronized (this) {
if (this.calendar == null)
this.calendar = Calendar.getInstance(this.defaultTimeZone, Locale.US);
this.calendar.setTime((Date)this.value);
if (this.value instanceof java.sql.Date) {
this.calendar.set(11, 0);
this.calendar.set(12, 0);
this.calendar.set(13, 0);
}
byte length = 7;
if (this.value instanceof Timestamp)
length = 11;
intoPacket.ensureCapacity(length);
intoPacket.writeInteger(NativeConstants.IntegerDataType.INT1, length);
int year = this.calendar.get(1);
int month = this.calendar.get(2) + 1;
int date = this.calendar.get(5);
intoPacket.writeInteger(NativeConstants.IntegerDataType.INT2, year);
intoPacket.writeInteger(NativeConstants.IntegerDataType.INT1, month);
intoPacket.writeInteger(NativeConstants.IntegerDataType.INT1, date);
if (this.value instanceof java.sql.Date) {
intoPacket.writeInteger(NativeConstants.IntegerDataType.INT1, 0L);
intoPacket.writeInteger(NativeConstants.IntegerDataType.INT1, 0L);
intoPacket.writeInteger(NativeConstants.IntegerDataType.INT1, 0L);
} else {
intoPacket.writeInteger(NativeConstants.IntegerDataType.INT1, this.calendar.get(11));
intoPacket.writeInteger(NativeConstants.IntegerDataType.INT1, this.calendar.get(12));
intoPacket.writeInteger(NativeConstants.IntegerDataType.INT1, this.calendar.get(13));
}
if (length == 11)
intoPacket.writeInteger(NativeConstants.IntegerDataType.INT4, (((Timestamp)this.value).getNanos() / 1000));
}
}
public byte[] getByteValue() {
if (!this.isStream)
return (this.charEncoding != null) ? StringUtils.getBytes(toString(), this.charEncoding) : toString().getBytes();
return null;
}
}
/* Location: C:\Users\BSV\AppData\Local\Temp\Rar$DRa6216.20396\Preview\Preview.jar!\com\mysql\cj\ServerPreparedQueryBindValue.class
* Java compiler version: 8 (52.0)
* JD-Core Version: 1.1.3
*/
|
package br.ufla.lemaf.ti.lemaf4j.common;
import br.ufla.lemaf.ti.lemaf4j.common.messaging.ResourceBundleMessageProducer;
import org.junit.After;
import org.junit.Test;
import java.util.ResourceBundle;
import static org.assertj.core.api.Assertions.assertThat;
public class ContractTest {
@After
public void cleanUp() {
Contract.removeMessageProducer();
}
@Test
public final void testRequireArgNotNull() {
// TEST
try {
Contract.requireArgNotNull("name", null);
} catch (final ConstraintViolationException ex) {
assertThat(ex.getMessage()).isEqualTo("Error: ARGUMENTO NULO");
}
// TEST
var resource = ResourceBundle.getBundle("messages");
Contract.setMessageProducer(new ResourceBundleMessageProducer(resource));
try {
Contract.requireArgNotNull("name", null);
} catch (final ConstraintViolationException ex) {
assertThat(ex.getMessage()).isEqualTo("O argumento 'name' não pode ser nulo!");
}
}
@Test
public final void testRequireArgNotEmpty() {
// TEST
try {
Contract.requireArgNotEmpty("name", "");
} catch (final ConstraintViolationException ex) {
assertThat(ex.getMessage()).isEqualTo("Error: ARGUMENTO VAZIO");
}
// TEST
var resource = ResourceBundle.getBundle("messages");
Contract.setMessageProducer(new ResourceBundleMessageProducer(resource));
try {
Contract.requireArgNotEmpty("name", "");
} catch (final ConstraintViolationException ex) {
assertThat(ex.getMessage()).isEqualTo("O argumento 'name' não pode ser vazio!");
}
}
@Test
public void testRequireArgMaxLength() {
// TEST
Contract.requireArgMaxLength("name", "123", 3);
// TEST
Contract.requireArgMaxLength("name", "12", 3);
// TEST
try {
Contract.requireArgMaxLength("name", "123", 2);
} catch (final ConstraintViolationException ex) {
assertThat(ex.getMessage()).isEqualTo("Error: TAMANHO MAXIMO ATINGIDO");
}
// TEST
var resource = ResourceBundle.getBundle("messages");
Contract.setMessageProducer(new ResourceBundleMessageProducer(resource));
try {
Contract.requireArgMaxLength("name", "123", 2);
} catch (final ConstraintViolationException ex) {
assertThat(ex.getMessage()).isEqualTo("O tamanho máximo para o argumento 'name' é 2, mas foi: 3");
}
}
@Test
public void testRequireArgMinLength() {
// TEST
Contract.requireArgMinLength("name", "1234", 4);
// TEST
try {
Contract.requireArgMinLength("name", "123", 4);
} catch (final ConstraintViolationException ex) {
assertThat(ex.getMessage()).isEqualTo("Error: TAMANHO MINIMO NAO ALCANCADO");
}
// TEST
var resource = ResourceBundle.getBundle("messages");
Contract.setMessageProducer(new ResourceBundleMessageProducer(resource));
try {
Contract.requireArgMinLength("name", "123", 5);
} catch (final ConstraintViolationException ex) {
assertThat(ex.getMessage()).isEqualTo("O tamanho mínimo para o argumento 'name' é 5, mas foi: 3");
}
}
@Test
public void testRequireArgMin() {
// TEST
Contract.requireArgMin("name1", 5, 4);
Contract.requireArgMin("name3", 4, 4);
Contract.requireArgMin("name3", Integer.valueOf(5), Integer.valueOf(4));
Contract.requireArgMin("name4", 5L, 4L);
Contract.requireArgMin("name5", Long.valueOf(5), Long.valueOf(4));
// TEST
try {
Contract.requireArgMin("name6", 3, 4);
} catch (final ConstraintViolationException ex) {
assertThat(ex.getMessage()).isEqualTo("Error: VALOR MINIMO NAO ALCANCADO");
}
// TEST
var resource = ResourceBundle.getBundle("messages");
Contract.setMessageProducer(new ResourceBundleMessageProducer(resource));
try {
Contract.requireArgMin("name6", 3, 4);
} catch (final ConstraintViolationException ex) {
assertThat(ex.getMessage()).isEqualTo("O valor mínimo para o argumento 'name6' é 4, mas foi: 3");
}
}
@Test
public void testRequireArgMax() {
// TEST
Contract.requireArgMax("name1", 5, 6);
Contract.requireArgMax("name3", 4, 5);
Contract.requireArgMax("name3", Integer.valueOf(5), Integer.valueOf(9));
Contract.requireArgMax("name4", 5L, 6L);
Contract.requireArgMax("name5", Long.valueOf(5), Long.valueOf(8));
// TEST
try {
Contract.requireArgMax("name6", 3, 1);
} catch (final ConstraintViolationException ex) {
assertThat(ex.getMessage()).isEqualTo("Error: VALOR MAXIMO ATINGIDO");
}
// TEST
var resource = ResourceBundle.getBundle("messages");
Contract.setMessageProducer(new ResourceBundleMessageProducer(resource));
try {
Contract.requireArgMax("name6", 3, 1);
} catch (final ConstraintViolationException ex) {
assertThat(ex.getMessage()).isEqualTo("O valor máximo para o argumento 'name6' é 1, mas foi: 3");
}
}
}
|
/*
* 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 axc.g1l3.cliente;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import static java.lang.Math.random;
import java.util.ArrayList;
import java.util.Vector;
import javax.swing.DefaultComboBoxModel;
import javax.swing.JComboBox;
import javax.swing.Timer;
/**
*
* @author aline
*/
public class vistaCliente extends javax.swing.JFrame
{
private static int n_grupo;
private static Cliente c = new Cliente();
/**
* Creates new form viestaCliente
*/
public vistaCliente(Cliente c)
{
initComponents();
n_grupo = 0;
this.c = c;
comboBoxItems = new Vector();
model = new DefaultComboBoxModel(comboBoxItems);
}
/**
* This method is called from within the constructor to initialize the form.
* WARNING: Do NOT modify this code. The content of this method is always
* regenerated by the Form Editor.
*/
@SuppressWarnings("unchecked")
// <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
private void initComponents()
{
jInternalFrame1 = new javax.swing.JInternalFrame();
botonDesconectar = new javax.swing.JButton();
botonAceptar = new javax.swing.JButton();
jLabel1 = new javax.swing.JLabel();
comboBoxSelec = new javax.swing.JComboBox();
jScrollPane2 = new javax.swing.JScrollPane();
textAreaInfo = new javax.swing.JTextArea();
jLabel2 = new javax.swing.JLabel();
botonSalir = new javax.swing.JButton();
textoX = new javax.swing.JTextField();
textoY = new javax.swing.JTextField();
jLabel3 = new javax.swing.JLabel();
jLabel4 = new javax.swing.JLabel();
jButton1 = new javax.swing.JButton();
jButton2 = new javax.swing.JButton();
jButton3 = new javax.swing.JButton();
jButton4 = new javax.swing.JButton();
jLabel5 = new javax.swing.JLabel();
setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);
jInternalFrame1.setDefaultCloseOperation(javax.swing.WindowConstants.DO_NOTHING_ON_CLOSE);
jInternalFrame1.setVisible(true);
botonDesconectar.setText("Salir de Sala");
botonDesconectar.setEnabled(false);
botonDesconectar.addActionListener(new java.awt.event.ActionListener()
{
public void actionPerformed(java.awt.event.ActionEvent evt)
{
botonDesconectarActionPerformed(evt);
}
});
botonAceptar.setText("Acceder a Sala");
botonAceptar.setEnabled(false);
botonAceptar.addActionListener(new java.awt.event.ActionListener()
{
public void actionPerformed(java.awt.event.ActionEvent evt)
{
botonAceptarActionPerformed(evt);
}
});
jLabel1.setText("Lista de grupos:");
comboBoxSelec.setModel(new javax.swing.DefaultComboBoxModel(new String[] { }));
textAreaInfo.setColumns(20);
textAreaInfo.setRows(5);
textAreaInfo.setEnabled(false);
jScrollPane2.setViewportView(textAreaInfo);
jLabel2.setText("Posición de los clientes");
botonSalir.setText("Cerrar Programa");
botonSalir.addActionListener(new java.awt.event.ActionListener()
{
public void actionPerformed(java.awt.event.ActionEvent evt)
{
botonSalirActionPerformed(evt);
}
});
textoX.setText(String.valueOf((int)(100+random()*200)));
textoX.setEnabled(false);
textoY.setText(String.valueOf((int)(100+random()*200)));
textoY.setEnabled(false);
jLabel3.setText("x:");
jLabel4.setText("y:");
jButton1.setText("Más X");
jButton1.addActionListener(new java.awt.event.ActionListener()
{
public void actionPerformed(java.awt.event.ActionEvent evt)
{
jButton1ActionPerformed(evt);
}
});
jButton2.setText("Más Y");
jButton2.addActionListener(new java.awt.event.ActionListener()
{
public void actionPerformed(java.awt.event.ActionEvent evt)
{
jButton2ActionPerformed(evt);
}
});
jButton3.setText("Menos X");
jButton3.addActionListener(new java.awt.event.ActionListener()
{
public void actionPerformed(java.awt.event.ActionEvent evt)
{
jButton3ActionPerformed(evt);
}
});
jButton4.setText("Menos Y");
jButton4.addActionListener(new java.awt.event.ActionListener()
{
public void actionPerformed(java.awt.event.ActionEvent evt)
{
jButton4ActionPerformed(evt);
}
});
jLabel5.setText("Posicion Propia");
javax.swing.GroupLayout jInternalFrame1Layout = new javax.swing.GroupLayout(jInternalFrame1.getContentPane());
jInternalFrame1.getContentPane().setLayout(jInternalFrame1Layout);
jInternalFrame1Layout.setHorizontalGroup(
jInternalFrame1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(jInternalFrame1Layout.createSequentialGroup()
.addGap(34, 34, 34)
.addGroup(jInternalFrame1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING)
.addGroup(jInternalFrame1Layout.createSequentialGroup()
.addGroup(jInternalFrame1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(jInternalFrame1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING, false)
.addComponent(jButton1, javax.swing.GroupLayout.Alignment.LEADING, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
.addComponent(jButton3, javax.swing.GroupLayout.Alignment.LEADING))
.addGroup(jInternalFrame1Layout.createSequentialGroup()
.addComponent(jLabel3, javax.swing.GroupLayout.PREFERRED_SIZE, 12, javax.swing.GroupLayout.PREFERRED_SIZE)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
.addComponent(textoX, javax.swing.GroupLayout.PREFERRED_SIZE, 52, javax.swing.GroupLayout.PREFERRED_SIZE)))
.addGap(18, 18, 18)
.addGroup(jInternalFrame1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(jInternalFrame1Layout.createSequentialGroup()
.addComponent(jLabel4)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(textoY, javax.swing.GroupLayout.PREFERRED_SIZE, 0, Short.MAX_VALUE))
.addGroup(javax.swing.GroupLayout.Alignment.TRAILING, jInternalFrame1Layout.createSequentialGroup()
.addGap(0, 0, Short.MAX_VALUE)
.addComponent(jButton4))
.addComponent(jButton2, javax.swing.GroupLayout.Alignment.TRAILING, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
.addGap(18, 18, 18))
.addGroup(jInternalFrame1Layout.createSequentialGroup()
.addGroup(jInternalFrame1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING)
.addComponent(botonAceptar, javax.swing.GroupLayout.Alignment.LEADING, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
.addGroup(jInternalFrame1Layout.createSequentialGroup()
.addGap(0, 0, Short.MAX_VALUE)
.addGroup(jInternalFrame1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false)
.addComponent(jLabel1, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
.addComponent(comboBoxSelec, javax.swing.GroupLayout.PREFERRED_SIZE, 150, javax.swing.GroupLayout.PREFERRED_SIZE))))
.addGap(30, 30, 30))
.addGroup(javax.swing.GroupLayout.Alignment.LEADING, jInternalFrame1Layout.createSequentialGroup()
.addGap(50, 50, 50)
.addComponent(jLabel5)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)))
.addGroup(jInternalFrame1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING)
.addComponent(jLabel2, javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(jInternalFrame1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING, false)
.addGroup(jInternalFrame1Layout.createSequentialGroup()
.addComponent(botonDesconectar)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
.addComponent(botonSalir))
.addComponent(jScrollPane2, javax.swing.GroupLayout.PREFERRED_SIZE, 399, javax.swing.GroupLayout.PREFERRED_SIZE)))
.addGap(211, 211, 211))
);
jInternalFrame1Layout.setVerticalGroup(
jInternalFrame1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(jInternalFrame1Layout.createSequentialGroup()
.addGap(27, 27, 27)
.addGroup(jInternalFrame1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(jLabel1)
.addComponent(jLabel2))
.addGap(18, 18, 18)
.addGroup(jInternalFrame1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false)
.addComponent(jScrollPane2, javax.swing.GroupLayout.PREFERRED_SIZE, 206, javax.swing.GroupLayout.PREFERRED_SIZE)
.addGroup(jInternalFrame1Layout.createSequentialGroup()
.addComponent(comboBoxSelec, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addGap(18, 18, 18)
.addComponent(botonAceptar)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
.addComponent(jLabel5)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
.addGroup(jInternalFrame1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(jInternalFrame1Layout.createSequentialGroup()
.addComponent(textoY, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addGap(14, 14, 14)
.addComponent(jButton2)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(jButton4))
.addGroup(jInternalFrame1Layout.createSequentialGroup()
.addGroup(jInternalFrame1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(textoX, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(jLabel3)
.addComponent(jLabel4))
.addGap(14, 14, 14)
.addComponent(jButton1)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(jButton3)))))
.addGap(18, 18, 18)
.addGroup(jInternalFrame1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(botonSalir)
.addComponent(botonDesconectar))
.addContainerGap(31, Short.MAX_VALUE))
);
javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
getContentPane().setLayout(layout);
layout.setHorizontalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(jInternalFrame1)
);
layout.setVerticalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(jInternalFrame1)
);
pack();
}// </editor-fold>//GEN-END:initComponents
private void botonAceptarActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_botonAceptarActionPerformed
// TODO add your handling code here:
System.out.println("Aceptar");
// Se debe enviar el número de grupo al servidor
if (c.seleccionadoGrupo(getGrupo()));
{
botonAceptar.setEnabled(false);
botonDesconectar.setEnabled(true);
timer.start();
}
}//GEN-LAST:event_botonAceptarActionPerformed
private void botonSalirActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_botonSalirActionPerformed
// TODO add your handling code here:
System.out.println("Salir");
System.exit(0);
}//GEN-LAST:event_botonSalirActionPerformed
private void botonDesconectarActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_botonDesconectarActionPerformed
// TODO add your handling code here:
System.out.println("Desconectar");
botonDesconectar.setEnabled(false);
}//GEN-LAST:event_botonDesconectarActionPerformed
private void jButton1ActionPerformed(java.awt.event.ActionEvent evt)//GEN-FIRST:event_jButton1ActionPerformed
{//GEN-HEADEREND:event_jButton1ActionPerformed
String SX = textoX.getText();
int v = Integer.parseInt(SX) + 1;
textoX.setText(String.valueOf(v));
}//GEN-LAST:event_jButton1ActionPerformed
private void jButton3ActionPerformed(java.awt.event.ActionEvent evt)//GEN-FIRST:event_jButton3ActionPerformed
{//GEN-HEADEREND:event_jButton3ActionPerformed
String SX = textoX.getText();
int v = Integer.parseInt(SX) - 1;
textoX.setText(String.valueOf(v));
}//GEN-LAST:event_jButton3ActionPerformed
private void jButton2ActionPerformed(java.awt.event.ActionEvent evt)//GEN-FIRST:event_jButton2ActionPerformed
{//GEN-HEADEREND:event_jButton2ActionPerformed
String SY = textoY.getText();
int v = Integer.parseInt(SY) + 1;
textoY.setText(String.valueOf(v));
}//GEN-LAST:event_jButton2ActionPerformed
private void jButton4ActionPerformed(java.awt.event.ActionEvent evt)//GEN-FIRST:event_jButton4ActionPerformed
{//GEN-HEADEREND:event_jButton4ActionPerformed
String SY = textoY.getText();
int v = Integer.parseInt(SY) - 1;
textoY.setText(String.valueOf(v));
}//GEN-LAST:event_jButton4ActionPerformed
public int getPosX()
{
return Integer.parseInt(textoX.getText());
}
public int getPosY()
{
return Integer.parseInt(textoY.getText());
}
/**
* @param args the command line arguments
*/
public static void main(String args[])
{
/* Set the Nimbus look and feel */
//<editor-fold defaultstate="collapsed" desc=" Look and feel setting code (optional) ">
/* If Nimbus (introduced in Java SE 6) is not available, stay with the default look and feel.
* For details see http://download.oracle.com/javase/tutorial/uiswing/lookandfeel/plaf.html
*/
try {
for (javax.swing.UIManager.LookAndFeelInfo info : javax.swing.UIManager.getInstalledLookAndFeels()) {
if ("Nimbus".equals(info.getName())) {
javax.swing.UIManager.setLookAndFeel(info.getClassName());
break;
}
}
} catch (ClassNotFoundException ex) {
java.util.logging.Logger.getLogger(vistaCliente.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (InstantiationException ex) {
java.util.logging.Logger.getLogger(vistaCliente.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (IllegalAccessException ex) {
java.util.logging.Logger.getLogger(vistaCliente.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (javax.swing.UnsupportedLookAndFeelException ex) {
java.util.logging.Logger.getLogger(vistaCliente.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
}
//</editor-fold>
/* Create and display the form */
java.awt.EventQueue.invokeLater(new Runnable()
{
@Override
public void run()
{
new vistaCliente(c).setVisible(true);
}
});
}
// Función que escribe la información sobre el text area (en nuestro caso, los grupos disponibles)
// Función que guarda el grupo seleccionado
public static void setGrupo(int number)
{
n_grupo = number;
System.out.println("Numero de grupo: " + n_grupo);
}
public static int getGrupo()
{
return comboBoxSelec.getSelectedIndex();
}
// Función que introduce el número de grupos que se puede seleccionar
// dependiendo de la lista recibida.
public static void setComboBox(int num_grupos)
{
for (int i = 1; i != num_grupos + 1; i++) {
comboBoxSelec.addItem("Grupo " + i);
}
}
// Variables declaration - do not modify//GEN-BEGIN:variables
private javax.swing.JButton botonAceptar;
private javax.swing.JButton botonDesconectar;
private javax.swing.JButton botonSalir;
private static javax.swing.JComboBox comboBoxSelec;
private javax.swing.JButton jButton1;
private javax.swing.JButton jButton2;
private javax.swing.JButton jButton3;
private javax.swing.JButton jButton4;
private javax.swing.JInternalFrame jInternalFrame1;
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 jScrollPane2;
private javax.swing.JTextArea textAreaInfo;
private javax.swing.JTextField textoX;
private javax.swing.JTextField textoY;
// End of variables declaration//GEN-END:variables
Vector comboBoxItems;
DefaultComboBoxModel model;
void ActivarSeleccionSala()
{
botonAceptar.setEnabled(true);
}
void ConectarServidor()
{
botonDesconectar.setEnabled(true);
botonDesconectar.setText("Conectar a Servidor");
}
void DesconectarSala()
{
botonDesconectar.setEnabled(false);
botonDesconectar.setText("Salir de Sala");
}
public void setListaDesplegable(String Mensaje)
{
comboBoxItems = new Vector();
String nombre = "";
for (int i = 0; i < Mensaje.length(); i++) {
if (Mensaje.charAt(i) == '/') {
comboBoxItems.add(nombre);
nombre = "";
} else {
nombre = nombre + Mensaje.charAt(i);
}
}
model = new DefaultComboBoxModel(comboBoxItems);
comboBoxSelec.setModel(model);
}
public void actualizarPosiciones(ArrayList<Vecino> vecinos)
{
String cadena= "";
for(int i=0;i<vecinos.size();i++)
cadena=cadena+vecinos.get(i).toString()+"\n";
textAreaInfo.setText(cadena);
}
Timer timer = new Timer (1000, new ActionListener ()
{
public void actionPerformed(ActionEvent e)
{
actualizarPosiciones(c.getVecinos());
}
});
}
|
package com.sneaker.mall.api.service;
import com.sneaker.mall.api.model.ERPConfigDetail;
import com.sneaker.mall.api.model.Order;
import com.sneaker.mall.api.model.OrderOper;
import java.util.Date;
import java.util.List;
/**
* 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
* <p>
* http://www.apache.org/licenses/LICENSE-2.0
* <p>
* 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.
*/
public interface OrderService {
/**
* 保存订单信息
*
* @param orderList
*/
public void saveOrder(List<Order> orderList);
/**
* 分页面读取订单信息
*
* @param page
* @param limit
* @return
*/
public List<Order> getOrderByPages(long cid, int page, int limit);
/**
* 读取某个业务员给该客户下的订单
*
* @param uid
* @param cid
* @param page
* @param limit
* @return
*/
public List<Order> getOrderByUidAndPages(long uid, long cid, int page, int limit);
/**
* 统计公司订单数量
*
* @param cid
* @return
*/
public int countOrderByCompany(long cid);
/**
* 统计某个业务为客户下的订单数据
*
* @param uid
* @param cid
* @return
*/
public int countOrderByCompanyAndUid(long uid, long cid);
/**
* 按状态分页面读取订单信息
*
* @param status
* @param page
* @param limit
* @return
*/
public List<Order> getOrderByPagesAndStatus(long cid, int status, int page, int limit);
/**
* 按状态获取某个业务为该客户下的单
*
* @param uid
* @param cid
* @param status
* @param page
* @param limit
* @return
*/
public List<Order> getOrderByPagesAndStatusAndUid(long uid, long cid, int status, int page, int limit);
/**
* 根据超级订单号获取订单信息
*
* @param superOrderId
* @return
*/
public List<Order> getOrderBySuperOrderId(String superOrderId);
/**
* 根据订单号读取订单信息
*
* @param id
* @return
*/
public Order getOrderById(long id);
/**
* 根据公司和订单统计
*
* @param cid
* @param status
* @return
*/
public int countOrderByStatusAndCompany(long cid, int status);
/**
* 统计时间段内的根据公司与状态的订单数据
*
* @param start
* @param end
* @param status
* @return
*/
public int countOrderByTimeAndStatusAndCompany(Date start, Date end, int status);
/**
* 查询时间段的根据状态与公司查询订单
*
* @param start
* @param end
* @param status
* @param pages
* @param size
* @return
*/
public List<Order> getOrderByTimeAndStatus(Date start, Date end, int status, int pages, int size);
/**
* 统计某业务为该客户下的订单数据
*
* @param uid
* @param cid
* @param status
* @return
*/
public int countOrderByStatusAndCompanyAndUid(long uid, long cid, int status);
/**
* 根据业务员及状态读取订单信息
*
* @param suid
* @param status
* @param page
* @param limit
* @return
*/
public List<Order> getOrderBySalemanAndStatusAndPage(long suid, int status, int page, int limit);
/**
* 获取条数
*
* @param suid
* @param status
* @return
*/
public int countOrderBySalemanAndStatusAndPage(long suid, int status);
/**
* 统计业务订单数
*
* @param suid
* @return
*/
public int countOrderBySaleman(long suid);
/**
* 根据状态查询订单
*
* @param status
* @return
*/
public List<Order> getOrderByStatus(int status);
/**
* 更新订单状态
*
* @param orderno
* @param status
*/
public void updateOrderStatus(String orderno, int status);
/**
* 是否已经支付
*
* @param orderno
* @param ispay
*/
public void updateOrderIsPay(String orderno, int ispay);
/**
* 更新派车状态
*
* @param orderno
* @param status
*/
public void updateSendCar(String orderno, int status);
/**
* 根据商城订单号更新ERP订单号
*
* @param orderno
* @param erp_order_no
*/
public void updateErpOrderId(String orderno, String erp_order_no);
/**
* 取消订单
*
* @param id
* @param cid
*/
public void cancelOrder(long id, long cid);
/**
* 取消订单根据用户判断
*
* @param id
* @param uid
*/
public void cancelOrderByUid(long id, long uid);
/**
* 添加订单的操作信息记录
*
* @param erp_order_id
* @param orderOper
*/
public void addOrderOper(String erp_order_id, OrderOper orderOper);
/**
* 获取订单的跟踪信息
*
* @param id
* @return
*/
public List<OrderOper> getOrderTraceInfoById(long id);
/**
* 获取订单的跟踪信息
*
* @param orderNo
* @return
*/
public List<OrderOper> getOrderTraceInfoByOrderNo(String orderNo);
/**
* 获取送紧急程序
*
* @return
*/
public List<ERPConfigDetail> getDeliverGoods();
/**
* 根据ERP订单号查询订单信息
* @param erp_id
* @return
*/
public Order getOrderByErpId(String erp_id);
}
|
package org.apache.commons.net.bsd;
import java.io.IOException;
public class RLoginClient extends RCommandClient {
public static final int DEFAULT_PORT = 513;
public RLoginClient() {
setDefaultPort(513);
}
public void rlogin(String localUsername, String remoteUsername, String terminalType, int terminalSpeed) throws IOException {
rexec(localUsername, remoteUsername, String.valueOf(terminalType) + "/" + terminalSpeed,
false);
}
public void rlogin(String localUsername, String remoteUsername, String terminalType) throws IOException {
rexec(localUsername, remoteUsername, terminalType, false);
}
}
/* Location: C:\Users\BSV\AppData\Local\Temp\Rar$DRa6216.20396\Preview\Preview.jar!\org\apache\commons\net\bsd\RLoginClient.class
* Java compiler version: 8 (52.0)
* JD-Core Version: 1.1.3
*/
|
package com.cyclight;
import java.util.ArrayList;
import org.newdawn.slick.Animation;
import org.newdawn.slick.SpriteSheet;
import org.newdawn.slick.geom.Circle;
import org.newdawn.slick.geom.Polygon;
import org.newdawn.slick.geom.Shape;
public class WGun implements Weapon {
private String weaponName= "V-Bow";
private Shape weaponHitbox;
private Animation weaponAnimation;
private final int delay = 300;
private int currentDelay;
private int numPierce=1;
private final float projectileSpeed = .5f;
private final float projectileYSpeed = .1f;
//damage?
// private boolean active;
//Tween movement;
public WGun(Shape shape, SpriteSheet sheet)
{
currentDelay = 0;
// active=false;
//weaponHitbox=shape;
for (int frame = 0; frame < 3; frame++)
{
// weaponAnimation.addFrame(sheet.getSprite(0, 0), 150);
}
}
public Boolean canAttack()
{
return currentDelay <= 0;
}
public int attack(ArrayList<Projectile> projList, Polygon hitbox, boolean direction)
{
currentDelay = delay;
Circle shot, shot2, shot3;
if(direction)
{
shot = new Circle(hitbox.getMaxX(), hitbox.getCenterY(), 5);
shot2 = new Circle(hitbox.getMaxX(), hitbox.getCenterY(), 5);
shot3 = new Circle(hitbox.getMaxX(), hitbox.getCenterY(), 5);
}
else
{
shot = new Circle(hitbox.getMinX(), hitbox.getCenterY(), 5);
shot2 = new Circle(hitbox.getMinX(), hitbox.getCenterY(), 5);
shot3 = new Circle(hitbox.getMaxX(), hitbox.getCenterY(), 5);
}
projList.add(new Projectile(shot, direction, projectileSpeed, -projectileYSpeed, numPierce)); //up
projList.add(new Projectile(shot2, direction, projectileSpeed, projectileYSpeed, numPierce)); //down
projList.add(new Projectile(shot3, direction, projectileSpeed, 0, numPierce)); //forward
return 0;
}
public Shape getWeaponHitbox()
{
return weaponHitbox;
}
public void update(int delta)
{
if(currentDelay > 0)
currentDelay -= delta;
}
@Override
public String getName() {
return weaponName;
}
@Override
public int getPiercing() {
return numPierce;
}
}
|
class for_Test2 {
public static void main (String ar[]) {
int a=0;
int t=0;
for (a=3; a<=100; a+=3)
{
t+=a;
}
System.out.println(t);
}
}2
|
package org.idea.plugin.atg.config;
import com.google.common.cache.Cache;
import com.google.common.cache.CacheBuilder;
import com.google.common.util.concurrent.UncheckedExecutionException;
import com.intellij.ide.util.DirectoryUtil;
import com.intellij.openapi.command.WriteCommandAction;
import com.intellij.openapi.project.Project;
import com.intellij.openapi.roots.ContentEntry;
import com.intellij.openapi.roots.ModifiableRootModel;
import com.intellij.openapi.util.Pair;
import com.intellij.openapi.vfs.VfsUtilCore;
import com.intellij.openapi.vfs.VirtualFile;
import com.intellij.openapi.vfs.VirtualFileVisitor;
import com.intellij.psi.PsiDirectory;
import com.intellij.psi.PsiFile;
import com.intellij.psi.PsiManager;
import com.intellij.psi.PsiPackage;
import com.intellij.psi.xml.XmlFile;
import com.intellij.psi.xml.XmlTag;
import org.idea.plugin.atg.AtgToolkitBundle;
import org.idea.plugin.atg.module.AtgModuleFacet;
import org.idea.plugin.atg.module.AtgModuleFacetConfiguration;
import org.jetbrains.annotations.NotNull;
import java.util.*;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.TimeUnit;
import java.util.regex.Pattern;
import java.util.stream.Collectors;
import java.util.stream.Stream;
public class AtgConfigHelper {
private static final Cache<VirtualFile, String> webRootsContextCache = CacheBuilder.newBuilder()
.expireAfterWrite(2, TimeUnit.MINUTES)
.build();
private AtgConfigHelper() {
}
public static PsiDirectory getComponentConfigPsiDirectory(AtgModuleFacet atgModuleFacet, PsiPackage srcPackage) {
PsiManager psiManager = srcPackage.getManager();
Collection<VirtualFile> configRoots = atgModuleFacet.getConfiguration().getConfigRoots();
Collection<VirtualFile> configLayerRoots = atgModuleFacet.getConfiguration().getConfigLayerRoots().keySet();
VirtualFile targetDirVfile = configRoots.stream().findFirst().orElse(configLayerRoots.stream().findFirst().orElse(null));
if (targetDirVfile != null) {
String targetDirStr = targetDirVfile.getCanonicalPath();
return WriteCommandAction.writeCommandAction(srcPackage.getProject())
.withName(AtgToolkitBundle.message("create.directory.command"))
.compute(() -> DirectoryUtil.mkdirs(psiManager, targetDirStr + "/" + srcPackage.getQualifiedName().replace('.', '/')));
}
return null;
}
public static List<Pattern> convertToPatternList(@NotNull String str) {
String[] patternStrArray = str.replace(".", "\\.")
.replace("?", ".?")
.replace("*", "[\\w-]+")
.split("[,;]");
return Stream.of(patternStrArray)
.map(s -> s + "$")
.map(Pattern::compile)
.collect(Collectors.toList());
}
@NotNull
public static Map<VirtualFile, String> detectWebRootsForModule(@NotNull ModifiableRootModel model) {
return Arrays.stream(model.getContentEntries())
.map(ContentEntry::getFile)
.filter(Objects::nonNull)
.map(f -> AtgConfigHelper.collectWebRoots(f, model.getProject()).entrySet())
.flatMap(Set::stream)
.collect(Collectors.toMap(Map.Entry::getKey, Map.Entry::getValue));
}
private static Map<VirtualFile, String> collectWebRoots(@NotNull final VirtualFile contentEntryRoot,@NotNull final Project project) {
Map<VirtualFile, String> result = new HashMap<>();
VfsUtilCore.visitChildrenRecursively(contentEntryRoot, new VirtualFileVisitor<Void>() {
@Override
public boolean visitFile(@NotNull VirtualFile root) {
Optional<Pair<VirtualFile, String>> webRoot = suggestWebRootForRoot(root, project);
if (webRoot.isPresent()) {
result.put(webRoot.get().getFirst(), webRoot.get().getSecond());
return false;
}
return true;
}
});
return result;
}
@NotNull
public static Set<Pair<VirtualFile, String>> getWebRootsWithContexts(@NotNull AtgModuleFacetConfiguration atgModuleFacetConfiguration, @NotNull Project project) {
return atgModuleFacetConfiguration.getWebRoots().stream()
.map(f -> {
try {
return new Pair<>(f, webRootsContextCache.get(f, () -> {
Optional<Pair<VirtualFile, String>> virtualFileStringPair = suggestWebRootForRoot(f, project);
if (virtualFileStringPair.isPresent()) {
return virtualFileStringPair.get().second;
}
return "/";
}));
} catch (ExecutionException | UncheckedExecutionException e) {
return new Pair<>(f, "/");
}
})
.collect(Collectors.toSet());
}
@NotNull
public static Optional<Pair<VirtualFile, String>> suggestWebRootForRoot(@NotNull final VirtualFile root, final Project project) {
if (root.isDirectory()) {
VirtualFile webInfFolder = root.findChild("WEB-INF");
if (webInfFolder != null) {
VirtualFile webXml = webInfFolder.findChild("web.xml");
if (webXml != null) {
return Optional.of(new Pair<>(root, detectContextRootFromWebXml(webXml, project)));
}
}
}
return Optional.empty();
}
public static List<VirtualFile> collectRootsMatchedPatterns(final VirtualFile contentEntryRoot, final List<Pattern> patterns) {
List<VirtualFile> result = new ArrayList<>();
VfsUtilCore.visitChildrenRecursively(contentEntryRoot, new VirtualFileVisitor<Void>() {
@Override
public boolean visitFile(@NotNull VirtualFile file) {
if (file.isDirectory() && file.getCanonicalPath() != null) {
if (patterns.stream().anyMatch(p -> p.matcher(file.getCanonicalPath()).find())) {
result.add(file);
return false;
}
}
return true;
}
});
return result;
}
@NotNull
public static String detectContextRootFromWebXml(final VirtualFile webXml, final Project project) {
PsiFile psiWebXml = PsiManager.getInstance(project).findFile(webXml);
if (psiWebXml instanceof XmlFile) {
XmlTag rootTag = ((XmlFile) psiWebXml).getRootTag();
if (rootTag != null) {
XmlTag[] contextParamTags = rootTag.findSubTags("context-param");
for (XmlTag contextParamTag : contextParamTags) {
XmlTag[] paramNameTags = contextParamTag.findSubTags("param-name");
if (paramNameTags.length > 0 && "context-root".equals(paramNameTags[0].getValue().getTrimmedText())) {
XmlTag[] contextRootValue = contextParamTag.findSubTags("param-value");
if (contextRootValue.length > 0) {
String contextStr = contextRootValue[0].getValue().getTrimmedText();
if (!contextStr.startsWith("/")) {
contextStr = "/" + contextStr;
}
return contextStr;
}
}
}
}
}
return "/";
}
}
|
package com.gtfs.service.impl;
import java.io.Serializable;
import java.util.List;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.gtfs.bean.LicPremWvr;
import com.gtfs.dao.interfaces.LicPremWvrDao;
import com.gtfs.service.interfaces.LicPremWvrService;
@Service
public class LicPremWvrServiceImpl implements LicPremWvrService,Serializable {
@Autowired
private LicPremWvrDao licPremWvrDao;
@Override
public List<LicPremWvr> findLoadAmountByPropAgeTermProdId(Integer propAge,Long PremumPayingTerm, Long prodId) {
return licPremWvrDao.findLoadAmountByPropAgeTermProdId(propAge, PremumPayingTerm, prodId);
}
}
|
package app.base.service;
import java.util.List;
import app.base.pojo.po.Sysuser;
import app.base.pojo.po.Usergys;
import app.base.pojo.po.Userjd;
import app.base.pojo.po.Useryy;
import app.base.pojo.vo.SysuserCustom;
import app.base.pojo.vo.SysuserQueryVo;
public interface UserService {
// 根据条件查询用户信息
public List<SysuserCustom> findSysuserList(SysuserQueryVo sysuserQueryVo) throws Exception;
// 根据条件查询列表的总数
public int findSysuserCount(SysuserQueryVo sysuserQueryVo) throws Exception;
// 根据用户账号查询用户信息
public Sysuser findSysuserByUserid(String userId) throws Exception;
// 根据单位名称 查询单位信息
public Userjd findUserjdByMc(String mc) throws Exception;
public Useryy findUseryyByMc(String mc) throws Exception;
public Usergys findUsergysByMc(String mc) throws Exception;
// 添加用户
public void insertSysuser(SysuserCustom sysuserCustom) throws Exception;
}
|
package com.tencent.mm.plugin.luckymoney.appbrand.ui.prepare;
import com.tencent.mm.plugin.luckymoney.appbrand.ui.prepare.WxaLuckyMoneyPrepareUI.8;
class WxaLuckyMoneyPrepareUI$8$1 implements Runnable {
final /* synthetic */ 8 kMt;
WxaLuckyMoneyPrepareUI$8$1(8 8) {
this.kMt = 8;
}
public final void run() {
this.kMt.kMq.kMk.setVisibility(0);
this.kMt.eCI.requestFocus();
if (this.kMt.kMq.mKeyboard != null) {
this.kMt.kMq.mKeyboard.setInputEditText(this.kMt.eCH);
}
WxaLuckyMoneyPrepareUI.b(this.kMt.kMq, this.kMt.eCJ);
}
}
|
package Networkstuuff;
import java.io.IOException;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.ArrayList;
public class Accept extends Thread {
private Socket sock = null;
private ServerSocket servSock = null;
public Accept() {
// TODO Auto-generated constructor stub
}
public void update(ServerSocket ss, Socket s) {
// TODO Auto-generated method stub
sock = s;
servSock = ss;
}
@Override
public void run() {
// TODO Auto-generated method stub
try {
sock = servSock.accept();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
public Socket getSock() {
return sock;
}
}
|
package com.it.userportrait.log;
/**
* 广告
*/
public class AdvisterOpertor {
private long adviId;//广告id
private long productId;//商品id
private String clickTime;//点击时间
private String pulishTime;//分发时间
private String stayTime;//停留时间
private long userid;
private int diviceType;//(1、pc端,2微信小程序 3、app,4、快应用)
private String deviceId;//
private int advType;//0、动画; 1、纯文字 ; 2、视屏 ; 3、文字加动画
private int isMingxing;//0没有明星 1有明星
public long getAdviId() {
return adviId;
}
public void setAdviId(long adviId) {
this.adviId = adviId;
}
public long getProductId() {
return productId;
}
public void setProductId(long productId) {
this.productId = productId;
}
public String getClickTime() {
return clickTime;
}
public void setClickTime(String clickTime) {
this.clickTime = clickTime;
}
public String getPulishTime() {
return pulishTime;
}
public void setPulishTime(String pulishTime) {
this.pulishTime = pulishTime;
}
public String getStayTime() {
return stayTime;
}
public void setStayTime(String stayTime) {
this.stayTime = stayTime;
}
public long getUserid() {
return userid;
}
public void setUserid(long userid) {
this.userid = userid;
}
public int getDiviceType() {
return diviceType;
}
public void setDiviceType(int diviceType) {
this.diviceType = diviceType;
}
public String getDeviceId() {
return deviceId;
}
public void setDeviceId(String deviceId) {
this.deviceId = deviceId;
}
public int getAdvType() {
return advType;
}
public void setAdvType(int advType) {
this.advType = advType;
}
public int getIsMingxing() {
return isMingxing;
}
public void setIsMingxing(int isMingxing) {
this.isMingxing = isMingxing;
}
}
|
package com.joseph.MemberDatabse;
import java.util.List;
public class Controller {
//new objects
private UserPanel myUI;
private Database members;
private IdGenerator idGen;
public void Configure(UserPanel myUI, Database members, IdGenerator idGen) {
this.myUI = myUI;
this.members = members;
this.idGen = idGen;
}
public void mainController(){
userChoice myUserChoice = myUI.userMenu();
switch (myUserChoice) {
case SETUP -> {doSetup();}
case ADD -> {doAdd();}
case FIND -> {doFindAndShowMember();}
case REMOVE -> {doFindAndRemoveMember();}
case LIST -> {doListMembers();}
case BACKUP -> {doBackupFile();}
case EXIT -> {doExit();}
}
}
private void doSetup() {
members.createFile(MemberList.DEFAULT_FILE_PATH);
idGen.createIDFile();
idGen.writeId(0);
}
private void doAdd() {
MemberList.currentList = members.downloadFromFile();
Member newMember = myUI.getNewMember();
members.addMember(newMember);
members.writeMemberToFile(newMember, MemberList.DEFAULT_FILE_PATH);
idGen.writeId(newMember.id);
}
private void doFindAndShowMember() {
MemberList.currentList = members.downloadFromFile();
int id = myUI.getIdToSearch();
Member foundMember = members.findMember(id);
if (foundMember == null)
myUI.userNotFoundMessage();
else
myUI.showMember(foundMember);
}
private void doFindAndRemoveMember() {
MemberList.currentList = members.downloadFromFile();
int id = myUI.getIdToSearch();
Member foundMember = members.findMember(id);
if (foundMember == null)
myUI.userNotFoundMessage();
else {
members.removeMember(id);
System.out.println(foundMember.name_first +" "+foundMember.name_last+" removed.");
doSetup();
members.uploadToFile(MemberList.currentList, MemberList.DEFAULT_FILE_PATH);
}
}
private void doListMembers() {
MemberList.currentList = members.downloadFromFile();
for (Member item: MemberList.currentList
) {
myUI.showMember(item);
}
}
private void doBackupFile() {
String path = myUI.getFilePath();
List<Member> currentList = members.downloadFromFile();
members.createFile(path);
members.uploadToFile(currentList, path);
}
public void doExit(){
myUI.exitMessage();
System.exit(0);
}
}
|
package com.tencent.mm.ui.video;
import android.media.MediaPlayer;
import android.media.MediaPlayer.OnErrorListener;
import com.tencent.mm.sdk.platformtools.x;
class VideoView$4 implements OnErrorListener {
final /* synthetic */ VideoView uFz;
VideoView$4(VideoView videoView) {
this.uFz = videoView;
}
public final boolean onError(MediaPlayer mediaPlayer, int i, int i2) {
x.d("MicroMsg.VideoView", "Error: " + i + "," + i2);
if (VideoView.m(this.uFz) == null || !VideoView.m(this.uFz).onError(VideoView.e(this.uFz), i, i2)) {
this.uFz.getWindowToken();
}
return true;
}
}
|
package com.training.pom;
import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.support.FindBy;
import org.openqa.selenium.support.PageFactory;
public class MemberloginPOM {
private WebDriver driver;
public MemberloginPOM(WebDriver driver) {
this.driver = driver;
PageFactory.initElements(driver, this);
}
@FindBy(id="cyclosUsername")
private WebElement userName;
@FindBy(id="cyclosPassword")
private WebElement password;
@FindBy(xpath="//*[@class='button' and @value='Submit']")
private WebElement loginBtn;
@FindBy(xpath="//input[@id='memberUsername']")
private WebElement memberUsername;
@FindBy(xpath="//*[@linkurl='accountOverview?memberId=13' and @value='Submit']")
private WebElement accountinfo;
@FindBy(xpath="//select[@name='query(paymentFilter)']")
private WebElement paymenttype;
@FindBy(xpath="//option[contains(text(),'Commission payments')]")
private WebElement commission;
@FindBy(xpath="//*[@class='button' and @value='Search']")
private WebElement Searching;
public void sendUserName(String userName) {
this.userName.clear();
this.userName.sendKeys(userName);
}
public void sendPassword(String password) {
driver.findElement(By.xpath("//*[@class='virtualKeyboardButton virtualKeyboardContrastNormal' and @value='1']")).click();
driver.findElement(By.xpath("//*[@class='virtualKeyboardButton virtualKeyboardContrastNormal' and @value='2']")).click();
driver.findElement(By.xpath("//*[@class='virtualKeyboardButton virtualKeyboardContrastNormal' and @value='3']")).click();
driver.findElement(By.xpath("//*[@class='virtualKeyboardButton virtualKeyboardContrastNormal' and @value='4']")).click(); ;
}
public void clickLoginBtn() {
this.loginBtn.click();
}
public void memberUsername(String mu)
{
this.memberUsername.sendKeys(mu);
}
public void account()
{
this.accountinfo.click();
}
public void payment()
{
this.paymenttype.click();
}
public void commissiontype()
{
this.commission.click();
}
public void searchbutton()
{
this.Searching.click();
}
}
|
package zystudio.cases.prepare;
/**
* 为了实验activity与fragment的onSaveInstanceState与onRestoreInstanceState的,<br>
* 见:http://gundumw100.iteye.com/blog/1115080 <br>
* 主要原因是 这个"容易销毁"的时机确实不好整..我需要试一试之类的,而且使用场景是什么也不好想像
*/
public class CaseInstanceState {
private static CaseInstanceState sCase;
public static CaseInstanceState obtain() {
if (sCase == null) {
sCase = new CaseInstanceState();
}
return sCase;
}
public void work() {
}
}
|
package com.bin.spring.transaction.xml;
import java.util.List;
import org.springframework.stereotype.Service;
@Service("cashier")
public class CashierImpl implements Cashier{
private BookShopService bookShopService ;
public void setBookShopService(BookShopService bookShopService) {
this.bookShopService = bookShopService;
}
@Override
public void checkout(String username, List<String> isbns) {
for (String isbn:isbns) {
bookShopService.purchase(username, isbn);
}
}
}
|
package com.wxapp.bean;
//加好友必须的信息
public class Friend {
private String userNameV1;
private String antispamTicket;
private String origin = "0";
public Friend() {
}
public Friend(String userNameV1, String antispamTicket) {
this.userNameV1 = userNameV1;
this.antispamTicket = antispamTicket;
}
public Friend(String userNameV1, String antispamTicket, String origin) {
this.userNameV1 = userNameV1;
this.antispamTicket = antispamTicket;
this.origin = origin;
}
public String getUserNameV1() {
return userNameV1;
}
public void setUserNameV1(String userNameV1) {
this.userNameV1 = userNameV1;
}
public String getAntispamTicket() {
return antispamTicket;
}
public void setAntispamTicket(String antispamTicket) {
this.antispamTicket = antispamTicket;
}
public String getOrigin() {
return origin;
}
public void setOrigin(String origin) {
this.origin = origin;
}
}
|
//Given a non-empty array of integers, every element appears three times except for one, which appears exactly once. Find that single one.
//refer to post: https://leetcode.com/problems/single-number-ii/discuss/43295/Detailed-explanation-and-generalization-of-the-bitwise-operation-method-for-single-numbers
class Solution {
public int singleNumber(int[] nums) {
int x1 = 0;
int x2 = 0;
int mask = 0;
for (int n : nums) {
x2 ^= x1 & n;
x1 ^= n;
mask = ~(x1 & x2);
x1 &= mask;
x2 &= mask;
}
return x1;
}
}
|
package annotation.hibernate;
import java.lang.reflect.Method;
/**
* @author malf
* @description 解析注解并运用
* @project how2jStudy
* @since 2020/9/15
*/
public class ParseAnnotation {
public static void main(String[] args) {
Class<Hero> clazz = Hero.class;
MyEntity entity = (MyEntity) clazz.getAnnotation(MyEntity.class);
if (null == entity) {
System.out.println("Hero 不是实体类");
} else {
MyTable table = (MyTable) clazz.getAnnotation(MyTable.class);
String tableName = table.name();
System.out.println("对应的表名:" + tableName);
Method[] methods = clazz.getMethods();
Method primaryKeyMethod = null;
for (Method m : methods) {
MyId id = m.getAnnotation(MyId.class);
if (null != id) {
primaryKeyMethod = m;
break;
}
}
if (null != primaryKeyMethod) {
System.out.println("主键:" + primaryKeyMethod.getName());
MyGeneratedValue generatedValue = primaryKeyMethod.getAnnotation(MyGeneratedValue.class);
System.out.println("自增策略时:" + generatedValue.strategy());
MyColumn column = primaryKeyMethod.getAnnotation(MyColumn.class);
System.out.println("对应的字段:" + column.value());
}
}
}
}
|
package edu.htu.ap.lesson11;
public class Test {
public static void main(String[] args) {
PotatoMaker pm=new PotatoMaker(3, 5, 100);
pm.makePotato();
System.out.println("==================");
CirclesPotatoMaker cpm=new CirclesPotatoMaker();
cpm.makePotato();
System.out.println("==================");
FlowerPotatoMaker fpm=new FlowerPotatoMaker();
fpm.makePotato();
}
}
|
package madotuki.comanda.shared.model;
/**
* Created by madotuki on 5/22/16.
*/
public enum OrderItemStatus {
NEW("New"),
SENT("Sent"),
READY("Ready"),
DONE("Done");
private String description;
OrderItemStatus(String description) {
this.description = description;
}
@Override
public String toString() {
return description;
}
}
|
package com.example.ty_en.ires;
import android.content.Intent;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.Spinner;
import android.widget.TextView;
import java.util.ArrayList;
import java.util.List;
public class EntranceActivity extends AppCompatActivity implements View.OnClickListener {
//人数選択のArray
private ArrayAdapter<List<String>> askPeopleArrayAdapter ;
//人数選択のArray用List
private List<String> askPeopleArrayList ;
//店舗許容人数の最大数
static int peopleMax = 12 ;
//喫煙選択のArray
private ArrayAdapter<List<String>> askSmokeArrayAdapter ;
//喫煙選択のArray用List
private List<String> askSmokeArrayList ;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_entrance);
Intent intent = getIntent() ;
//QRコードから読み取った文字列の取得
//String qrText =intent.getStringExtra("qr_text") ;
//TextView qrTextView = (TextView)findViewById(R.id.qr_text) ;
//qrTextView.setText(qrText) ;
// 人数選択のSpineer設定
Spinner askPeopleSpinner = (Spinner)findViewById(R.id.ask_people_spinner) ;
askPeopleArrayList = new ArrayList<String>() ;
getPeopleArrayListContents() ;
askPeopleArrayAdapter = new ArrayAdapter(this,android.R.layout.simple_spinner_item,askPeopleArrayList) ;
askPeopleArrayAdapter.setDropDownViewResource(R.layout.common_dropdown);
askPeopleSpinner.setAdapter(askPeopleArrayAdapter);
// 喫煙選択のSpineer設定
Spinner askSmokeSpinner = (Spinner)findViewById(R.id.ask_smoke_spinner) ;
askSmokeArrayList = new ArrayList<String>() ;
getSmokeArrayListContents() ;
askSmokeArrayAdapter = new ArrayAdapter(this,android.R.layout.simple_spinner_item,askSmokeArrayList) ;
askSmokeArrayAdapter.setDropDownViewResource(R.layout.common_dropdown);
askSmokeSpinner.setAdapter(askSmokeArrayAdapter);
//ボタンのリスナー登録
Button okButton = (Button)findViewById(R.id.entrance_ok) ;
okButton.setOnClickListener(this);
}
//人数選択用の選択肢を作成
public void getPeopleArrayListContents(){
//最大人数まで選択肢を作成
for(int i=1;i<=peopleMax;i++){
askPeopleArrayList.add(String.valueOf(i)) ;
}
System.out.println(askPeopleArrayList);
}
//喫煙選択用の選択肢を作成
public void getSmokeArrayListContents(){
askSmokeArrayList.add("Yes") ;
askSmokeArrayList.add("No") ;
askSmokeArrayList.add("Whichever") ;
}
//ボタンクリックイベント(Wait画面に遷移)
@Override
public void onClick(View view) {
Intent intent = new Intent(this, WaitActivity.class);
startActivity(intent);
}
}
|
package org.example.ratpack;
import org.example.ratpack.handlers.CorsHandler;
import ratpack.server.RatpackServer;
public class Application {
public static void main(String[] args) throws Exception {
RatpackServer.start(server ->
server.handlers(chain -> chain
.all(new CorsHandler())
.get(ctx -> ctx.render("Ratpack is a GO!!!"))));
}
}
|
package com.onplan.service;
import java.io.Serializable;
import static com.onplan.util.MorePreconditions.checkNotNullOrEmpty;
public class ServiceConnectionInfo implements Serializable {
private final String providerName;
private final boolean isConnected;
private final Long connectionUpdateTimestamp;
public ServiceConnectionInfo(String providerName, boolean isConnected, Long connectionDate) {
this.providerName = checkNotNullOrEmpty(providerName);
this.isConnected = isConnected;
this.connectionUpdateTimestamp = connectionDate;
}
/**
* Returns the provider displayName.
*/
public String getProviderName() {
return providerName;
}
/**
* Returns true if the service is connected.
*/
public boolean getIsConnected() {
return isConnected;
}
/**
* Returns the timestamp of the last connection / disconnection. Returns null if any connection
* attempt has ever been established.
*/
public Long getConnectionUpdateTimestamp() {
return connectionUpdateTimestamp;
}
}
|
import biuoop.DrawSurface;
import java.util.ArrayList;
import java.util.List;
/**
* Created by user on 12/05/2017.
*/
public class SpriteCollection {
private List list = new ArrayList();
/**
*
* @return this list of Sprites.
*/
public List getList() {
return this.list;
}
/**
*adding the Sprite to the list of Sprites.
* @param s a Sprite to add.
*/
public void addSprite(Sprite s) {
this.list.add(s);
}
/**
*calling to TimePassed of all Sprites.
* @param dt dt.
*/
public void notifyAllTimePassed(double dt) {
for (int i = 0; i < this.list.size(); i++) {
Sprite sprite = (Sprite) this.list.get(i);
sprite.timePassed(dt);
}
}
/**
* calling to drawOn of all Sprites.
* @param d the object that we use to draw things.
*/
public void drawAllOn(DrawSurface d) {
for (int i = 0; i < this.list.size(); i++) {
Sprite sprite = (Sprite) this.list.get(i);
sprite.drawOn(d);
}
}
}
|
package dbmining;
import edu.stanford.nlp.hcoref.CorefCoreAnnotations.CorefChainAnnotation;
import edu.stanford.nlp.hcoref.data.CorefChain;
import edu.stanford.nlp.ling.CoreAnnotations.NamedEntityTagAnnotation;
import edu.stanford.nlp.ling.CoreAnnotations.PartOfSpeechAnnotation;
import edu.stanford.nlp.ling.CoreAnnotations.SentencesAnnotation;
import edu.stanford.nlp.ling.CoreAnnotations.TextAnnotation;
import edu.stanford.nlp.ling.CoreAnnotations.TokensAnnotation;
import edu.stanford.nlp.ling.CoreLabel;
import edu.stanford.nlp.pipeline.Annotation;
import edu.stanford.nlp.pipeline.StanfordCoreNLP;
import edu.stanford.nlp.semgraph.SemanticGraph;
import edu.stanford.nlp.semgraph.SemanticGraphCoreAnnotations.CollapsedCCProcessedDependenciesAnnotation;
import edu.stanford.nlp.trees.Tree;
import edu.stanford.nlp.trees.TreeCoreAnnotations.TreeAnnotation;
import edu.stanford.nlp.util.CoreMap;
import java.io.BufferedReader;
import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.ServerSocket;
import java.net.Socket;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.ResultSetMetaData;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Properties;
import java.util.concurrent.ConcurrentHashMap;
import java.util.logging.Level;
import java.util.logging.Logger;
import org.apache.commons.math3.stat.descriptive.DescriptiveStatistics;
import com.google.common.collect.HashBasedTable;
import com.google.common.collect.Table;
import com.google.common.collect.Table.Cell;
import java.io.BufferedWriter;
import java.io.FileWriter;
public class DBMining implements Runnable {
public ArrayList<String> rows = new ArrayList<String>();
public String query;
public ArrayList<String> QueryWords;
public ArrayList<relevance> queryColumnsRel;
// "How many discoveries Martin has made after 1990?";
public static String question = "How many discoveries Martin has made after 1990?";
public static String groundTruthQuery;
public static ArrayList<String> QuestionWords;
public static ConcurrentHashMap<StringKey, Double> SimiliartiesHashMap = new ConcurrentHashMap<StringKey, Double>();
public static ConcurrentHashMap<String, Float[]> vectors = new ConcurrentHashMap<String, Float[]>();
public Statement stmt;
public static Boolean storeRelevanceScores = false;
public static ArrayList<String> SQL = new ArrayList<String>();
public static ConcurrentHashMap<String, String> WORDSTAGS = new ConcurrentHashMap<>();
public static HashMap<String, Boolean> testedQueries = new HashMap<String, Boolean>();
public static BufferedWriter bw;
public static Table<String, String, String> ALL = HashBasedTable.create();
public static Table<String, String, String> GT = HashBasedTable.create();
public class StringKey {
public String str1;
public String str2;
public StringKey(String s1, String s2) {
str1 = s1;
str2 = s2;
}
@Override
public boolean equals(Object obj) {
if (obj != null && obj instanceof StringKey) {
StringKey s = (StringKey) obj;
return str1.equals(s.str1) && str2.equals(s.str2);
}
return false;
}
@Override
public int hashCode() {
return (str1 + str2).hashCode();
}
}
//Input Question.
public static void main(String[] args) throws SQLException, IOException {
bw = new BufferedWriter(new FileWriter("coverages.csv"));
if (args.length == 2) {
question = args[0];
groundTruthQuery = args[1];
} else {
System.out.println("Some of the inputs are missing!");
return;
}
try {
loadNumberBatch();
QuestionWords = extractQuestionWords();
} catch (SQLException ex) {
Logger.getLogger(DBMining.class.getName()).log(Level.SEVERE, null, ex);
}
try {
MyService = new ServerSocket(1506);
} catch (IOException ex) {
Logger.getLogger(DBMining.class.getName()).log(Level.SEVERE, null, ex);
}
System.out.println("Question is: " + question);
//System.out.println("Now enter the best query for this question:");
//Scanner scanner = new Scanner(System.in);
//String groundTruthQuery = scanner.nextLine();
System.out.println("The ground truth has a fitness of: " + getQueryFitness(groundTruthQuery));
storeRelevanceScores = true;
System.out.println("The fitness for all the tables is: " + getQueryFitness("SELECT * FROM species.insectdiscoveries;"));
storeRelevanceScores = false;
saveRelevanceScores();
System.out.println("Press any key to continue...");
System.in.read();
System.out.println("Coverage of ground truth vs all table is: " + getQueryCoverage(groundTruthQuery, "SELECT * FROM species.insectdiscoveries;"));
//=========================================================================================
DBMining dbb = new DBMining();
ResultSet result = dbb.getResultSet("SELECT * FROM species.insectdiscoveries;");
ResultSetMetaData rsmd = result.getMetaData();
while (result.next()) {
String ID = result.getString(1);
for (int i = 1; i <= rsmd.getColumnCount(); i++) {
String name = rsmd.getColumnName(i);
ALL.put(ID, name, result.getString(name));
}
}
//=========================================================================================
result = dbb.getResultSet(groundTruthQuery);
rsmd = result.getMetaData();
while (result.next()) {
String ID = result.getString(1);
for (int i = 1; i <= rsmd.getColumnCount(); i++) {
String name = rsmd.getColumnName(i);
GT.put(ID, name, result.getString(name));
}
}
//=========================================================================================
//=========================================================================================
//-----------------------------------------------------------------------------------------
int threads = 8;
DBMining[] db = new DBMining[8];
Thread[] t = new Thread[threads];
for (int i = 0; i < threads; i++) {
db[i] = new DBMining();
t[i] = new Thread(db[i]);
t[i].start();
}
//-----------------------------------------------------------------------------------------
}
public static void saveRelevanceScores() throws SQLException {
Statement s = OpenConnectionMYSQL("species");
s.executeUpdate("truncate table insectdiscoveriesrel;");
for (int i = 0; i < SQL.size(); i++) {
//System.out.println(SQL.get(i));
s.executeUpdate(SQL.get(i));
}
s.close();
}
public static double getQueryCoverage(String groundTruthQuery, String query) throws SQLException {
query = query.replaceAll("SELECT ", "SELECT `ID`,");
//=========================================================================================
Table<String, String, String> ALL = HashBasedTable.create();
DBMining db = new DBMining();
ResultSet result = db.getResultSet("SELECT * FROM species.insectdiscoveries;");
ResultSetMetaData rsmd = result.getMetaData();
while (result.next()) {
String ID = result.getString(1);
for (int i = 1; i <= rsmd.getColumnCount(); i++) {
String name = rsmd.getColumnName(i);
ALL.put(ID, name, result.getString(name));
}
}
//=========================================================================================
Table<String, String, String> GT = HashBasedTable.create();
result = db.getResultSet(groundTruthQuery);
rsmd = result.getMetaData();
while (result.next()) {
String ID = result.getString(1);
for (int i = 1; i <= rsmd.getColumnCount(); i++) {
String name = rsmd.getColumnName(i);
GT.put(ID, name, result.getString(name));
}
}
//=========================================================================================
Table<String, String, String> Q = HashBasedTable.create();
result = db.getResultSet(query);
rsmd = result.getMetaData();
while (result.next()) {
String ID = result.getString(1);
for (int i = 1; i <= rsmd.getColumnCount(); i++) {
String name = rsmd.getColumnName(i);
Q.put(ID, name, result.getString(name));
}
}
//=========================================================================================
Iterator it = ALL.cellSet().iterator();
double FP = 0;
double FN = 0;
double N = 0;
while (it.hasNext()) {
Cell<String, String, String> c = (Cell) it.next();
String rowKey = c.getRowKey();
String colKey = c.getColumnKey();
if (GT.contains(rowKey, colKey) && Q.contains(rowKey, colKey)) {
} else if (!GT.contains(rowKey, colKey) && Q.contains(rowKey, colKey)) {
FP++;
} else if (GT.contains(rowKey, colKey) && !Q.contains(rowKey, colKey)) {
FN++;
} else if (!GT.contains(rowKey, colKey) && !Q.contains(rowKey, colKey)) {
}
N++;
}
//=========================================================================================
return 1 - ((double) FP / N) - (2 * (double) FN / N);
}
public double getQueryCoverage() throws SQLException {
//=========================================================================================
Table<String, String, String> QUERY = HashBasedTable.create();
ResultSet result = this.getResultSet(query);
ResultSetMetaData rsmd = result.getMetaData();
while (result.next()) {
String ID = result.getString(1);
for (int i = 1; i <= rsmd.getColumnCount(); i++) {
String name = rsmd.getColumnName(i);
QUERY.put(ID, name, result.getString(name));
}
}
//=========================================================================================
Iterator it = ALL.cellSet().iterator();
double FP = 0;
double FN = 0;
double N = ALL.size();
while (it.hasNext()) {
Cell<String, String, String> c = (Cell) it.next();
String rowKey = c.getRowKey();
String colKey = c.getColumnKey();
if (GT.contains(rowKey, colKey) && QUERY.contains(rowKey, colKey)) {
} else if (!GT.contains(rowKey, colKey) && QUERY.contains(rowKey, colKey)) {
FP++;
} else if (GT.contains(rowKey, colKey) && !QUERY.contains(rowKey, colKey)) {
FN++;
} else if (!GT.contains(rowKey, colKey) && !QUERY.contains(rowKey, colKey)) {
}
}
//=========================================================================================
return 1 - ((double) FP / N) - (2 * (double) FN / N);
}
public static double getQueryFitness(String query) throws SQLException {
DBMining db = new DBMining(query);
return db.getFitness();
}
public static ServerSocket MyService;
@Override
public void run() {
try {
while (true) {
Socket mySocket = MyService.accept();
System.out.println("Connected");
DataInputStream input = new DataInputStream(mySocket.getInputStream());
BufferedReader r = new BufferedReader(new InputStreamReader(input));
String st = r.readLine();
System.out.println(st);
if (st.equals("DIE")) {
break;
}
this.setQuery(st);
String response = "0\n";
double fitness = 0;
query = query.replaceAll("SELECT ", "SELECT `ID`,");
double coverage = this.getQueryCoverage();
System.out.println("Fitness : " + fitness + "---" + "Coverage: " + coverage);
if (!testedQueries.containsKey(this.query)) {
synchronized (this) {
bw.write("\"" + this.query + "\",\"" + fitness + "\",\"" + coverage + "\"\n");
bw.flush();
}
}
testedQueries.put(this.query, true);
try {
fitness = this.getFitness();
response = Double.toString(fitness) + "\n" + coverage + "\n";
} catch (Exception ex) {
System.out.println(ex.getStackTrace().toString());
System.out.println("Query was not valid. Using zero fitness instead!");
//System.in.read();
}
//send the response to the client and close the stream as well as the socket.
DataOutputStream output = new DataOutputStream(mySocket.getOutputStream());
output.writeUTF(response);
output.flush();
output.close();
mySocket.close();
}
} catch (IOException ex) {
Logger.getLogger(DBMining.class.getName()).log(Level.SEVERE, null, ex);
} catch (SQLException ex) {
Logger.getLogger(DBMining.class.getName()).log(Level.SEVERE, null, ex);
}
}
private void setQuery(String quer) {
query = quer;
}
private DBMining() throws SQLException {
stmt = OpenConnectionMYSQL("species");
queryColumnsRel = new ArrayList<>();
}
private DBMining(String quer) throws SQLException {
query = quer;
stmt = OpenConnectionMYSQL("species");
queryColumnsRel = new ArrayList<>();
}
public Float[] getVector(String word) {
return vectors.get(word);
}
public double getFitness() throws SQLException {
QueryWords = extractQueryColumns(query);
System.out.println("---------------------------------------------------");
System.out.println("Query: " + QueryWords);
System.out.println("Question: " + QuestionWords);
queryColumnsRel = getColumnsRelevance();
return Fitness(query, queryColumnsRel);
}
public ArrayList<ArrayList<relevance>> getRowsRelevance() throws SQLException {
ArrayList<ArrayList<relevance>> str = new ArrayList<ArrayList<relevance>>();
ResultSet result = getResultSet(query);
if (result == null) {
System.out.println("Result set is null.");
}
while (result.next()) {
ArrayList<relevance> temp = new ArrayList<relevance>();
String[] t = new String[QueryWords.size()];
for (int i = 1; i <= QueryWords.size(); i++) {
relevance rel = new relevance();
rel.word = result.getString(i + 1);
rel.value = cellRelevanceScore(rel.word);
//t[i - 1] = rel.word + ":" + (rel.value + queryColumnsRel.get(i - 1).value);
t[i - 1] = rel.word + ":" + rel.value;
temp.add(rel);
}
str.add(temp);
if (storeRelevanceScores) {
SQL.add(createInsertQuery(t));
}
}
return str;
}
public ArrayList<relevance> getColumnsRelevance() throws SQLException {
ArrayList<DescriptiveStatistics> desc = new ArrayList<DescriptiveStatistics>();
for (int j = 0; j < QueryWords.size(); j++) {
DescriptiveStatistics temp = new DescriptiveStatistics();
for (int i = 0; i < QuestionWords.size(); i++) {
double sim = cosineSimilarity(QuestionWords.get(i), QueryWords.get(j));
//System.out.println(Question.get(i) + "," + Query.get(j) + " : " + sim);
temp.addValue(sim);
}
desc.add(temp);
}
ArrayList<relevance> str = new ArrayList<>();
String[] t = new String[QueryWords.size()];
for (int j = 0; j < QueryWords.size(); j++) {
relevance rel = new relevance();
rel.word = QueryWords.get(j);
rel.value = desc.get(j).getMean();
t[j] = rel.word + ":" + rel.value;
str.add(rel);
}
if (storeRelevanceScores) {
SQL.add(createInsertQuery(t));
}
return str;
}
public String createInsertQuery(String[] t) throws SQLException {
String sql = "Insert into " + "species.insectdiscoveriesrel";
sql += "( "
+ "`" + QueryWords.get(0) + "`" + ","
+ "`" + QueryWords.get(1) + "`" + ","
+ "`" + QueryWords.get(2) + "`" + ","
+ "`" + QueryWords.get(3) + "`" + ","
+ "`" + QueryWords.get(4) + "`" + ","
+ "`" + QueryWords.get(5) + "`" + ","
+ "`" + QueryWords.get(6) + "`" + ","
+ "`" + QueryWords.get(7) + "`" + ","
+ "`" + QueryWords.get(8) + "`" + ","
+ "`" + QueryWords.get(9) + "`" + ","
+ "`" + QueryWords.get(10) + "`" + ","
+ "`" + QueryWords.get(11) + "`" + ","
+ "`" + QueryWords.get(12) + "`" + ","
+ "`" + QueryWords.get(13) + "`" + ","
+ "`" + QueryWords.get(14) + "`" + ","
+ "`" + QueryWords.get(15) + "`" + ","
+ "`" + QueryWords.get(16) + "`" + ","
+ "`" + QueryWords.get(17) + "`" + ","
+ "`" + QueryWords.get(18) + "`" + ","
+ "`" + QueryWords.get(19) + "`" + ","
+ "`" + QueryWords.get(20) + "`" + ","
+ "`" + QueryWords.get(21) + "`"
+ " )"
+ "Values ( "
+ " '" + t[0] + "', "
+ " '" + t[1] + "', "
+ " '" + t[2] + "', "
+ " '" + t[3] + "', "
+ " '" + t[4] + "', "
+ " '" + t[5] + "', "
+ " '" + t[6] + "', "
+ " '" + t[7] + "', "
+ " '" + t[8] + "', "
+ " '" + t[9] + "', "
+ " '" + t[10] + "', "
+ " '" + t[11] + "', "
+ " '" + t[12] + "', "
+ " '" + t[13] + "', "
+ " '" + t[14] + "', "
+ " '" + t[15] + "', "
+ " '" + t[16] + "', "
+ " '" + t[17] + "', "
+ " '" + t[18] + "', "
+ " '" + t[19] + "', "
+ " '" + t[20] + "', "
+ " '" + t[21] + "' "
+ " );";
return sql;
}
public class relevance {
String word;
Double value;
}
public double cellRelevanceScore(String cell) {
DescriptiveStatistics temp = new DescriptiveStatistics();
for (int i = 0; i < QuestionWords.size(); i++) {
double sim = 0;
try {
sim = cosineSimilarity(QuestionWords.get(i), cell);
} catch (Exception Ex) {
System.out.println("calculating sim failed.");
}
temp.addValue(sim);
}
return temp.getMean();
}
public class TableCell {
int ID;
String Name;
String Value;
Double Relevance;
public TableCell(int id, String name, String value) {
ID = id;
Name = name;
Value = value;
}
public void setcellRelevanceScore() {
DescriptiveStatistics temp = new DescriptiveStatistics();
for (int i = 0; i < QuestionWords.size(); i++) {
double sim = 0;
try {
sim = cosineSimilarity(QuestionWords.get(i), this.Value);
} catch (Exception Ex) {
System.out.println("calculating sim failed.");
}
temp.addValue(sim);
}
Relevance = temp.getMean();
}
}
//================================================================================================
public static ArrayList<String> extractQuestionWords() {
HashMap<String, String> QuestionColumns;
ArrayList<String> QuestionColumnsList = new ArrayList<>();
QuestionColumns = parseText(question);
Iterator it = QuestionColumns.keySet().iterator();
while (it.hasNext()) {
QuestionColumnsList.add((String) it.next());
}
ArrayList<String> temp = new ArrayList<>();
for (int i = 0; i < QuestionColumnsList.size(); i++) {
String tag = QuestionColumns.get(QuestionColumnsList.get(i));
System.out.println(QuestionColumnsList.get(i) + " " + tag);
if (tag.contains("CD")) {
int num = Integer.parseInt(QuestionColumnsList.get(i));
if (num >= 1700 && num <= 2020) {
temp.add(Integer.toString(num));
}
} else if (tag.contains("NN")) {
temp.add(QuestionColumnsList.get(i));
}
}
return temp;
}
public double Fitness(String query, ArrayList<relevance> colrel) throws SQLException {
//System.out.println(colrel);
ArrayList<ArrayList<relevance>> rowsrel = getRowsRelevance();
//System.out.println(rowsrel);
DescriptiveStatistics stat = new DescriptiveStatistics();
for (int i = 0; i < rowsrel.size(); i++) {
double temp = 0;
ArrayList<relevance> rowrel = rowsrel.get(i);
for (int j = 0; j < colrel.size(); j++) {
double d1 = colrel.get(j).value;
double d2 = rowrel.get(j).value;
temp += d1 + d2;
}
stat.addValue(temp);
}
Double out = (double) stat.getSum();
return out.isNaN() ? 0.0 : out;
}
public ArrayList<String> extractQueryColumns(String query) throws SQLException {
ResultSet result = getResultSet(query);
System.out.println("Result set ready.");
ArrayList<String> ResultsColumns = new ArrayList<>();
ResultSetMetaData rsmd = result.getMetaData();
for (int i = 2; i <= rsmd.getColumnCount(); i++) {
String name = rsmd.getColumnName(i);
//System.out.println(name);
ResultsColumns.add(name);
}
return ResultsColumns;
}
public synchronized ResultSet getResultSet(String query) throws SQLException {
return stmt.executeQuery(query);
}
public static HashMap<String, String> parseText(String text) {
HashMap<String, String> output = new HashMap();
// creates a StanfordCoreNLP object, with POS tagging, lemmatization, NER, parsing, and coreference resolution
Properties props = new Properties();
props.put("annotators", "tokenize, ssplit, pos, lemma, ner, parse, dcoref");
StanfordCoreNLP pipeline = new StanfordCoreNLP(props);
// create an empty Annotation just with the given text
Annotation document = new Annotation(text);
// run all Annotators on this text
pipeline.annotate(document);
// these are all the sentences in this document
// a CoreMap is essentially a Map that uses class objects as keys and has values with custom types
List<CoreMap> sentences = document.get(SentencesAnnotation.class);
for (CoreMap sentence : sentences) {
// traversing the words in the current sentence
// a CoreLabel is a CoreMap with additional token-specific methods
for (CoreLabel token : sentence.get(TokensAnnotation.class)) {
// this is the text of the token
String word = token.get(TextAnnotation.class);
// this is the POS tag of the token
String pos = token.get(PartOfSpeechAnnotation.class);
WORDSTAGS.put(word, pos);
output.put(word, pos);
// this is the NER label of the token
String ne = token.get(NamedEntityTagAnnotation.class);
}
// this is the parse tree of the current sentence
Tree tree = sentence.get(TreeAnnotation.class);
// this is the Stanford dependency graph of the current sentence
SemanticGraph dependencies = sentence.get(CollapsedCCProcessedDependenciesAnnotation.class);
}
// This is the coreference link graph
// Each chain stores a set of mentions that link to each other,
// along with a method for getting the most representative mention
// Both sentence and token offsets start at 1!
Map<Integer, CorefChain> graph = document.get(CorefChainAnnotation.class);
return output;
}
public static Statement OpenConnectionMYSQL(String Dataset) throws SQLException {
String url = "jdbc:mysql://localhost:3306/" + Dataset + "?useSSL=false";
String username = "root";
String password = "farhad";
Connection connection = DriverManager.getConnection(url, username, password);
Statement stmt = connection.createStatement();
return (Statement) stmt;
}
//================================================================================================
public static void loadNumberBatch() throws SQLException {
System.out.println("Loading the numberbatch started!");
Statement stmt = OpenConnectionMYSQL("conceptnet");
String sql = "select * from conceptnet.numberbatch;";
ResultSet rs = stmt.executeQuery(sql);
//**************************************
while (rs.next()) {
String[] vecs = rs.getString(2).split(" ");
if (vecs.length != 300) {
System.out.println("Vecs less than 300, Vecs: " + vecs.length + " for " + rs.getString(1));
continue;
}
Float[] numVecs = new Float[vecs.length];
for (int i = 0; i < vecs.length; i++) {
numVecs[i] = Float.parseFloat(vecs[i]);
}
vectors.put(rs.getString(1), numVecs);
}
System.out.println("Loading the numberbatch finished!");
}
public double cosineSimilarity(String word1, String word2) {
try {
int num1 = Integer.parseInt(word1);
int num2 = Integer.parseInt(word2);
if (num1 >= 1700 && num1 <= 2020 && num2 >= 1700 && num2 <= 2020) {
return Math.abs(num1 - num2);
}
} catch (Exception Ex) {
if (word1.toLowerCase().equals(word2.toLowerCase())) {
return 1;
}
}
if (WORDSTAGS.contains(word1)) {
if (WORDSTAGS.get(word1).equals("NNP")) {
if (word1.toLowerCase().equals(word2.toLowerCase())) {
return 1;
} else {
return -1;
}
}
}
if (WORDSTAGS.contains(word2)) {
if (WORDSTAGS.get(word2).equals("NNP")) {
if (word1.toLowerCase().equals(word2.toLowerCase())) {
return 1;
} else {
return -1;
}
}
}
StringKey key = new StringKey(word1, word2);
if (SimiliartiesHashMap.containsKey(key)) {
Double temp = SimiliartiesHashMap.get(key);
return temp;
} else {
Float[] wordAvec = null;
Float[] wordBvec = null;
try {
wordAvec = getVector(word1.toLowerCase());
wordBvec = getVector(word2.toLowerCase());
} catch (Exception Ex) {
System.out.println("Failed getting vector: " + Ex.getMessage());
return -1;
}
if (wordAvec == null || wordBvec == null) {
//System.out.println("The word " + word1 + " or " + word2 + " is not in conceptnet.");
return -1;
}
double dotProduct = 0.0;
double normA = 0.0;
double normB = 0.0;
for (int i = 0; i < wordAvec.length; i++) {
dotProduct += wordAvec[i] * wordBvec[i];
//TODO Fix strings
normA += Math.pow(wordAvec[i], 2);
normB += Math.pow(wordBvec[i], 2);
}
double temp = dotProduct / (Math.sqrt(normA) * Math.sqrt(normB));
SimiliartiesHashMap.put(key, temp);
return temp;
}
}
public double eulideanSimilarity(String word1, String word2) {
Float[] wordAvec = null;
Float[] wordBvec = null;
try {
wordAvec = getVector(word1.toLowerCase());
wordBvec = getVector(word2.toLowerCase());
} catch (Exception Ex) {
System.out.println("Failed getting vector: " + Ex.getMessage());
return -1;
}
if (wordAvec == null || wordBvec == null) {
System.out.println("The word " + word1 + " or " + word2 + " is not in conceptnet.");
return -1;
}
double diff_square_sum = 0.0;
for (int i = 0; i < wordAvec.length; i++) {
diff_square_sum += (wordAvec[i] - wordBvec[i]) * (wordAvec[i] - wordBvec[i]);
}
return Math.sqrt(diff_square_sum);
}
//================================================================================================
}
|
package com.ssm.wechatpro.dao;
import java.util.List;
import java.util.Map;
/**
* 购物车所有相关的dao操作
* @author yinzengxiang
*
*/
public interface MWechatShoppingCartMapper {
//向购物车中添加一个商品
public void addProduct(Map<String, Object> map) throws Exception;
//删除购物车中的一种商品
public void deleteProduct(Map<String, Object> map ) throws Exception;
//更改购物车中一个商品的数量
public void updateProductCount(Map<String, Object> map) throws Exception;
//获取该用户购物车中的商品信息(商品id 商品类型, 商品所在商店, 商品数量)
public List<Map<String, Object>> getCartProductInfo(Map<String, Object> map) throws Exception;
//根据用户id清除该 用户购物车中的所有信息
public void deleteCartAllInfo (Map<String, Object> map) throws Exception;
//获取该购物车中的商店
public List<Map<String, Object>> getShopIds(Map<String, Object> map) throws Exception;
//商品数量增加一个
public void productCountUp (Map<String, Object> map) throws Exception;
//商品数量减少一个
public void productCOuntDown (Map<String,Object> map) throws Exception;
//根据商店id 获取商店的名称 和id
public Map<String, Object> getShopName(Map<String, Object> map) throws Exception;
/**
*获取商品的详细信息
*/
//产品的详细信息
public Map<String, Object> getProductByCartInfo(Map<String, Object> map) throws Exception;
//套餐的详细信息
public Map<String, Object> getPackageByCartInfo(Map<String, Object> map) throws Exception;
//获取可选套餐的详细信息
public Map<String, Object> getChooPackageByCartInfo(Map<String, Object> map) throws Exception;
//查询当前登录人购物车中所有商品
public List<Map<String,Object>> selectAllProduct(Map<String,Object> map) throws Exception;
}
|
package com.silver.mynews;
import android.app.SearchManager;
import android.app.SearchableInfo;
import android.content.Intent;
import android.os.Bundle;
import android.support.v4.content.ContextCompat;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.DividerItemDecoration;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.util.Log;
import android.util.TypedValue;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.ViewGroup;
import android.webkit.WebSettings;
import android.widget.LinearLayout;
import android.widget.SearchView;
import android.widget.Toast;
import android.widget.Toolbar;
import com.dinuscxj.refresh.RecyclerRefreshLayout;
import com.facebook.ads.Ad;
import com.facebook.ads.AdError;
import com.facebook.ads.AdSize;
import com.facebook.ads.AdView;
import com.facebook.ads.InterstitialAd;
import com.facebook.ads.InterstitialAdListener;
import com.facebook.ads.NativeAd;
import com.facebook.ads.NativeAdsManager;
import com.silver.mynews.api.EverythingApi;
import com.silver.mynews.model.Article;
import com.silver.mynews.model.Everything;
import com.thefinestartist.finestwebview.FinestWebView;
import java.util.ArrayList;
import java.util.List;
import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;
import static com.silver.mynews.api.Constants.*;
public class MainActivity extends AppCompatActivity implements NewsAdapter.OnItemClickListener {
//public static final String EXTRA_MESSAGE = "com.example.myfirstapp.MESSAGE";
private static final String TAG = MainActivity.class.getSimpleName();
private RecyclerRefreshLayout mRecyclerRefreshLayout;
private RecyclerView rvNews;
private NewsAdapter mNewsAdapter;
private final CustomOnScrollListener mCustomOnScrollListener = new CustomOnScrollListener();
private boolean mIsLoading;
private boolean mIsTheEnd;
private int mPage = 1;
private int mTotalPages = 0;
private List<Article> mArticles = new ArrayList<>();
private List<NativeAd> mAds = new ArrayList<>();
private NativeAdsManager mAdsManager;
// private InterstitialAd interstitialAd;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
handleIntent(getIntent());
setupAdsManager();
setupRecycleView();
setupData();
// interstitialAd = new InterstitialAd(this, INTERSTITIAL_AD_PLACEMENT_ID);
// // Set listeners for the Interstitial Ad
// interstitialAd.setAdListener(new InterstitialAdListener() {
// @Override
// public void onInterstitialDisplayed(Ad ad) {
// // Interstitial displayed callback
// }
//
// @Override
// public void onInterstitialDismissed(Ad ad) {
// // Interstitial dismissed callback
// }
//
// @Override
// public void onError(Ad ad, AdError adError) {
// // Ad error callback
// Toast.makeText(MainActivity.this, "Error: " + adError.getErrorMessage(),
// Toast.LENGTH_LONG).show();
// }
//
// @Override
// public void onAdLoaded(Ad ad) {
// // Show the ad when it's done loading.
// interstitialAd.show();
// }
//
// @Override
// public void onAdClicked(Ad ad) {
// // Ad clicked callback
// }
//
// @Override
// public void onLoggingImpression(Ad ad) {
// // Ad impression logged callback
// }
// });
//
// // For auto play video ads, it's recommended to load the ad
// // at least 30 seconds before it is shown
// interstitialAd.loadAd();
}
@Override
protected void onNewIntent(Intent intent) {
setIntent(intent);
handleIntent(intent);
}
private void handleIntent(Intent intent) {
if (Intent.ACTION_SEARCH.equals(intent.getAction())) {
String query = intent.getStringExtra(SearchManager.QUERY);
performSearchQuery(query);
}
}
@Override
protected void onDestroy() {
rvNews.removeOnScrollListener(mCustomOnScrollListener);
rvNews = null;
mAdsManager.setListener(null);
mAdsManager = null;
mRecyclerRefreshLayout.setOnRefreshListener(null);
mRecyclerRefreshLayout = null;
super.onDestroy();
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
MenuInflater inflater = getMenuInflater();
inflater.inflate(R.menu.main, menu);
SearchView searchView = (SearchView)menu.findItem(R.id.menu_search).getActionView();
searchView.setMaxWidth(Integer.MAX_VALUE);
searchView.setOnQueryTextListener(new SearchView.OnQueryTextListener() {
@Override
public boolean onQueryTextSubmit(String s) {
performSearchQuery(s);
return false;
}
@Override
public boolean onQueryTextChange(String s) {
return false;
}
});
searchView.setOnCloseListener(new SearchView.OnCloseListener() {
@Override
public boolean onClose() {
refreshData();
return false;
}
});
return true;
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
switch(item.getItemId()) {
case R.id.menu_search:
//onSearchRequested();
return true;
case R.id.menu_sort:
// TODO Add sort function
//Intent intent = new Intent(this, DisplayMessageActivity.class);
//intent.putExtra(EXTRA_MESSAGE, message);
//startActivity(intent);
return true;
}
return false;
}
@Override
public void onItemClick(Article item) {
new FinestWebView.Builder(this)
.titleDefault("Loading...")
.iconDefaultColorRes(R.color.Color_White)
.webViewUseWideViewPort(true)
.webViewSaveFormData(true)
.webViewSavePassword(true)
.webViewDomStorageEnabled(true)
.webViewAppCacheEnabled(true)
.webViewEnableSmoothTransition(true)
.webViewCacheMode(WebSettings.LOAD_CACHE_ELSE_NETWORK)
.webViewRenderPriority(WebSettings.RenderPriority.HIGH)
.webViewLayoutAlgorithm(WebSettings.LayoutAlgorithm.NARROW_COLUMNS)
.show(item.getUrl());
}
public class CustomOnScrollListener extends RecyclerView.OnScrollListener {
@Override
public void onScrolled(RecyclerView view, int dx, int dy) {
RecyclerView.LayoutManager manager = view.getLayoutManager();
if (manager.getChildCount() > 0) {
int count = manager.getItemCount();
int last = ((RecyclerView.LayoutParams) manager
.getChildAt(manager.getChildCount() - 1).getLayoutParams()).getViewAdapterPosition();
if (last == count - 5 && mArticles.size() > 0 && !mIsLoading && !mIsTheEnd) {
loadMoreData();
}
}
}
}
private void setupAdsManager() {
mAdsManager = new NativeAdsManager(this, NATIVE_AD_PLACEMENT_ID, NUM_ADS);
mAdsManager.setListener(new NativeAdsManager.Listener() {
@Override
public void onAdsLoaded() {
if (mAdsManager.getUniqueNativeAdCount() != 0) {
mAds.clear();
for (int i = 0; i < mAdsManager.getUniqueNativeAdCount(); i++) {
mAds.add(mAdsManager.nextNativeAd());
}
mNewsAdapter.notifyDataSetChanged();
}
}
@Override
public void onAdError(AdError adError) {
Log.w(TAG, "Facebook Ad Error: '" + adError.getErrorMessage() + "'");
}
});
mAdsManager.loadAds(NativeAd.MediaCacheFlag.ALL);
}
private void setupRecycleView() {
mRecyclerRefreshLayout = findViewById(R.id.refreshLayout);
mRecyclerRefreshLayout.setNestedScrollingEnabled(true);
mRecyclerRefreshLayout.setRefreshView(new RefreshView(this), new ViewGroup.LayoutParams(
(int) TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP, 30, getResources().getDisplayMetrics()),
(int) TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP, 30, getResources().getDisplayMetrics())
));
mRecyclerRefreshLayout.setOnRefreshListener(new RecyclerRefreshLayout.OnRefreshListener() {
@Override
public void onRefresh() {
refreshData();
}
});
LinearLayoutManager layoutManager = new LinearLayoutManager(this);
rvNews = findViewById(R.id.rvNews);
rvNews.setLayoutManager(layoutManager);
//rvNews.setHasFixedSize(true);
rvNews.addOnScrollListener(mCustomOnScrollListener);
DividerItemDecoration itemDecorator = new DividerItemDecoration(this, DividerItemDecoration.VERTICAL);
itemDecorator.setDrawable(ContextCompat.getDrawable(this, R.drawable.news_item_divider));
rvNews.addItemDecoration(itemDecorator);
mNewsAdapter = new NewsAdapter(this, mArticles, mAds, this, getResources().getInteger(R.integer.ad_position));
rvNews.setAdapter(mNewsAdapter);
}
private void setupData() {
mIsLoading = true;
mRecyclerRefreshLayout.setRefreshing(true);
callEverythingApi(new Callback<Everything>() {
@Override
public void onResponse(Call<Everything> call, Response<Everything> response) {
mIsLoading = false;
mRecyclerRefreshLayout.setRefreshing(false);
Everything body = response.body();
if (body != null) {
mTotalPages = body.getTotalResults();
mArticles.addAll(body.getArticles());
mNewsAdapter.notifyDataSetChanged();
}
}
@Override
public void onFailure(Call<Everything> call, Throwable t) {
mIsLoading = false;
mRecyclerRefreshLayout.setRefreshing(false);
Toast.makeText(MainActivity.this, t.getMessage(), Toast.LENGTH_SHORT).show();
}
});
}
private void refreshData() {
mPage = 1;
mIsTheEnd = false;
mIsLoading = true;
callEverythingApi(new Callback<Everything>() {
@Override
public void onResponse(Call<Everything> call, Response<Everything> response) {
mIsLoading = false;
mRecyclerRefreshLayout.setRefreshing(false);
Everything body = response.body();
if (body != null) {
mTotalPages = body.getTotalResults();
mArticles.clear();
mArticles.addAll(body.getArticles());
mNewsAdapter.notifyDataSetChanged();
}
}
@Override
public void onFailure(Call<Everything> call, Throwable t) {
mIsLoading = false;
mRecyclerRefreshLayout.setRefreshing(false);
Toast.makeText(MainActivity.this, t.getMessage(), Toast.LENGTH_SHORT).show();
}
});
}
private void loadMoreData() {
if (mPage * DEFAULT_PAGE_SIZE >= mTotalPages) {
mIsTheEnd = true;
return;
}
mPage += 1;
mIsLoading = true;
callEverythingApi(new Callback<Everything>() {
@Override
public void onResponse(Call<Everything> call, Response<Everything> response) {
mIsLoading = false;
Everything body = response.body();
if (body != null) {
mArticles.addAll(body.getArticles());
mNewsAdapter.notifyDataSetChanged();
}
}
@Override
public void onFailure(Call<Everything> call, Throwable t) {
mIsLoading = false;
Toast.makeText(MainActivity.this, t.getMessage(), Toast.LENGTH_SHORT).show();
}
});
}
private void performSearchQuery(String query) {
mPage = 1;
mIsTheEnd = false;
mIsLoading = true;
mRecyclerRefreshLayout.setRefreshing(true);
callEverythingApiWithQuery(query, new Callback<Everything>() {
@Override
public void onResponse(Call<Everything> call, Response<Everything> response) {
mIsLoading = false;
mRecyclerRefreshLayout.setRefreshing(false);
Everything body = response.body();
if (body != null) {
mTotalPages = body.getTotalResults();
mArticles.clear();
mArticles.addAll(body.getArticles());
mNewsAdapter.notifyDataSetChanged();
}
}
@Override
public void onFailure(Call<Everything> call, Throwable t) {
mIsLoading = false;
mRecyclerRefreshLayout.setRefreshing(false);
Toast.makeText(MainActivity.this, t.getMessage(), Toast.LENGTH_SHORT).show();
}
});
}
private void callEverythingApi(Callback<Everything> callback) {
callEverythingApiWithQuery(null, callback);
}
private void callEverythingApiWithQuery(String query, Callback<Everything> callback) {
Call<Everything> call = EverythingApi.ApiClient().get(mPage, DEFAULT_PAGE_SIZE, "bbc.co.uk,wsj.com,techcrunch.com,engadget.com,nytimes.com", "en", null, query);
call.enqueue(callback);
}
}
|
package org.sacc.SaccHome.mbg.model;
import lombok.Data;
import java.util.Date;
@Data
public class Order {
private Integer id;
private Date startTime;
private Date endTime;
private Integer number;
private String nameList;
private Integer userId;
private Date createdAt;
private Date updatedAt;
}
|
package com.tencent.mm.plugin.gai;
public interface Plugin$a {
void CP(String str);
}
|
package com.bowlong.util;
import java.util.Calendar;
import java.util.Date;
import com.bowlong.lang.NumEx;
/*** 日期对象数据操作 **/
public class DateEx extends DateFmtEx {
static public final int year() {
return year(nowDate());
}
static public final int year(Date v) {
return NumEx.stringToInt(format(v, fmt_yyyy));
}
static public final int month() {
return month(nowDate());
}
static public final int month(Date v) {
return NumEx.stringToInt(format(v, fmt_MM));
}
static public final int day() {
return day(nowDate());
}
static public final int day(Date v) {
return NumEx.stringToInt(format(v, fmt_dd));
}
static public final int hour() {
return hour(nowDate());
}
static public final int hour(Date v) {
return NumEx.stringToInt(format(v, fmt_HH));
}
static public final int minute() {
return minute(nowDate());
}
static public final int minute(Date v) {
return NumEx.stringToInt(format(v, fmt_mm));
}
static public final int second() {
return second(nowDate());
}
static public final int second(Date v) {
return NumEx.stringToInt(format(v, fmt_ss));
}
static public final int ms() {
return ms(nowDate());
}
static public final int ms(Date v) {
return NumEx.stringToInt(format(v, fmt_SSS));
}
static public final int week() {
return week(nowDate());
}
/*** 星期数(0~6) **/
static public final int week(Date v) {
return CalendarEx.week(parse2Cal(v));
}
static public final boolean isWeek() {
return isWeek(nowDate());
}
static public final boolean isWeek(long nowtime) {
if (nowtime == 0)
return false;
return isWeek(parse2Date(nowtime));
}
/*** 是否为周末(星期六,星期天) **/
static public final boolean isWeek(Date dt) {
if (dt == null)
return false;
int week = week(dt);
boolean r = week == 0 || week == 6;
return r;
}
static public final int weekInYear(Date v) {
return NumEx.stringToInt(format(v, fmt_wInYear));
}
static public final int weekInYear() {
return weekInYear(nowDate());
}
static public final int weekInMonth(Date v) {
return NumEx.stringToInt(format(v, fmt_WInMonth));
}
static public final int weekInMonth() {
return weekInMonth(nowDate());
}
static public final int dayInYear(Date v) {
return NumEx.stringToInt(format(v, fmt_DInYear));
}
static public final int dayInYear() {
return dayInYear(nowDate());
}
static public final int dayInMonth(Date v) {
return NumEx.stringToInt(format(v, fmt_dInMonth));
}
static public final int dayInMonth() {
return dayInMonth(nowDate());
}
public static final Date addYear(Date date, int v) {
Calendar c = CalendarEx.addYear(parse2Cal(date), v);
return c.getTime();
}
public static final Date addMonth(Date date, int v) {
Calendar c = CalendarEx.addMonth(parse2Cal(date), v);
return c.getTime();
}
public static final Date addWeek(Date date, int v) {
Calendar c = CalendarEx.addWeek(parse2Cal(date), v);
return c.getTime();
}
public static final Date addDay(Date date, int v) {
Calendar c = CalendarEx.addDay(parse2Cal(date), v);
return c.getTime();
}
public static final Date addHour(Date date, int v) {
Calendar c = CalendarEx.addHour(parse2Cal(date), v);
return c.getTime();
}
public static final Date addMinute(Date date, int v) {
Calendar c = CalendarEx.addMinute(parse2Cal(date), v);
return c.getTime();
}
public static final Date addSecond(Date date, int v) {
Calendar c = CalendarEx.addSecond(parse2Cal(date), v);
return c.getTime();
}
public static final Date addMilliSecond(Date date, int v) {
Calendar c = CalendarEx.addMilliSecond(parse2Cal(date), v);
return c.getTime();
}
}
|
package com.example.InventoryManagementSystem.Controller;
import com.example.InventoryManagementSystem.MainApplication;
import javafx.fxml.FXML;
import javafx.scene.web.HTMLEditor;
import javafx.scene.web.WebEngine;
import javafx.scene.web.WebView;
import javafx.stage.Stage;
public class TextInputController {
public static String text;
@FXML
private HTMLEditor editor;
@FXML
protected void saveAndExit() {
text = editor.getHtmlText();
Stage thisStage = (Stage)editor.getScene().getWindow();
thisStage.close();
}
@FXML
public void initialize() {
WebView webView = (WebView) (editor.lookup("WebView"));
WebEngine webEngine = webView.getEngine();
webEngine.setUserStyleSheetLocation(MainApplication.class.getResource("webview.css").toExternalForm());
}
}
|
package ist.es.puzzles;
/**
* Why is the compiler complaining about 2147483648?
*
* Numeric constants are Integers by default.
*/
public class IntegerByDefault {
/*
* Compiles all right
*/
long i = -2147483648;
/*
* Compiler error
*/
long j = -(2147483648);
/*
* Another error
*/
long k = 2147483648;
/*
* No error
*/
long l = 2147483648L;
}
|
package com.mx.profuturo.bolsa.model.service.vacancies.dto;
public class AsignarResponsabilidadDTO {
private String idEmpleado;
private int idPublicacion;
public String getIdEmpleado() {
return idEmpleado;
}
public void setIdEmpleado(String idEmpleado) {
this.idEmpleado = idEmpleado;
}
public int getIdPublicacion() {
return idPublicacion;
}
public void setIdPublicacion(int idPublicacion) {
this.idPublicacion = idPublicacion;
}
}
|
package leecode.other;
/*
在并查集的基础上加一些辅助变量的练习题目
https://leetcode-cn.com/problems/number-of-operations-to-make-network-connected/solution/wang-luo-lian-jie-bing-cha-ji-by-yexiso-1nd4/
*/
public class 连通网络的操作次数_1319 {
public int makeConnected(int n, int[][] connections) {
//链接n台电脑需要n-1条线,connections.length为线的数量
if(connections.length<n-1){
return -1;
}
count=n;//连通分量的个数初始化为n
int[]size=new int[n];
int[]parent=new int[n];
for (int i = 0; i <n ; i++) {
size[i]=1;
parent[i]=i;
}
for(int[]conection:connections){
int x=conection[0];
int y=conection[1];
union(x,y,parent,size);
}
//看这个解释 https://leetcode-cn.com/problems/number-of-operations-to-make-network-connected/solution/shou-hua-tu-jie-kao-cha-bing-cha-ji-1319-u9nb/
return --count;
}
int count;
private void union(int x,int y,int[]parent,int[]size){
int fx=findParent(x,parent);
int fy=findParent(y,parent);
if(fx==fy){
return;
}else {
if(size[fx]>=size[fy]){
parent[fy]=fx;
size[fx]+=size[fy];
}else {
parent[fx]=fy;
size[fy]+=size[fx];
}
count--;//
}
}
private int findParent(int x,int[]parent){
if(parent[x]!=x){
int father = findParent(parent[x],parent);
parent[x]=father;//路径压缩
}
return parent[x];
}
}
|
package com.monitora.monitoralog.api.mapper;
import java.util.List;
import java.util.stream.Collectors;
import org.modelmapper.ModelMapper;
import org.springframework.stereotype.Component;
import com.monitora.monitoralog.api.model.EntregaModel;
import com.monitora.monitoralog.api.model.input.EntregaInput;
import com.monitora.monitoralog.domain.model.Entrega;
import lombok.AllArgsConstructor;
@AllArgsConstructor
@Component
public class EntregaModelMapper {
private ModelMapper modelMapper;
public EntregaModel toModel(Entrega entrega) {
return modelMapper.map(entrega, EntregaModel.class);
}
public List<EntregaModel> toCollectionModel(List<Entrega> entregas) {
return entregas.stream()
.map(entrega -> this.toModel(entrega))
.collect(Collectors.toList());
}
public Entrega toEntity(EntregaInput entrega) {
return modelMapper.map(entrega, Entrega.class);
}
}
|
package com.lbs.ui;
import java.awt.Rectangle;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.text.SimpleDateFormat;
import java.util.Date;
import javax.swing.JFrame;
import javax.swing.JScrollPane;
import javax.swing.JTextPane;
import javax.swing.Timer;
import javax.swing.UIManager;
import javax.swing.text.BadLocationException;
import javax.swing.text.Document;
import javax.swing.text.StyledDocument;
public class AppendingTextPane extends JTextPane {
public AppendingTextPane() {
super();
}
public AppendingTextPane(StyledDocument doc) {
super(doc);
}
// Appends text to the document and ensure that it is visible
public void appendText(String text) {
try {
Document doc = getDocument();
// Move the insertion point to the end
setCaretPosition(doc.getLength());
// Insert the text
replaceSelection(text);
// Convert the new end location
// to view co-ordinates
Rectangle r = modelToView(doc.getLength());
// Finally, scroll so that the new text is visible
if (r != null) {
scrollRectToVisible(r);
}
} catch (BadLocationException e) {
System.out.println("Failed to append text: " + e);
}
}
// Testing method
public static void main(String[] args) {
try {
UIManager.setLookAndFeel("com.sun.java.swing.plaf.windows.WindowsLookAndFeel");
} catch (Exception evt) {}
JFrame f = new JFrame("Text Pane with Scrolling Append");
final AppendingTextPane atp = new AppendingTextPane();
f.getContentPane().add(new JScrollPane(atp));
f.setSize(200, 200);
f.setVisible(true);
// Add some text every second
Timer t = new Timer(1000, new ActionListener() {
public void actionPerformed(ActionEvent evt) {
String timeString = fmt.format(new Date());
atp.appendText(timeString + "\n");
}
SimpleDateFormat fmt = new SimpleDateFormat("HH:mm:ss");
});
t.start();
}
}
|
package com.skylerburwell.ilex.Screens;
import com.badlogic.gdx.Screen;
import com.skylerburwell.ilex.Ilex;
public abstract class ScreenBase implements Screen {
protected Ilex mGame;
public ScreenBase(Ilex game) {
mGame = game;
}
@Override
public abstract void show();
@Override
public abstract void render(float delta);
public abstract void update(float delta);
@Override
public abstract void resize(int width, int height);
@Override
public abstract void pause();
@Override
public abstract void resume();
@Override
public abstract void hide();
@Override
public abstract void dispose();
public Ilex getGame() {
return mGame;
}
}
|
2017.04.20.
9. Java EA
List<T> interface
sorozat adattípus nyilvános interfésze
pl. void add(T item);
boolean reverse(T item);
T get(int index);
...
Iterator<T> iterator();
- sorrendiség az elemek között
- egy eée, többször is szerepelhet
Iterator<T> interface
adatszerkezet bejárásához nyilvános interfész
boolean hasNext()
T next()
boolean remove()
- nincs sorrendiség
- egy elem egyszer
-> szétválasztjuk az adatszerkezetet és a bejárását két külön objektumra
List<String> names = ... // pl. ArrayList v. LinkedList
Iterator<String> iter = names.iterator(); // nem érdekes a ontos osztálya, elég h Iterator
while (iter.hasNext()) {
String name = iter.next();
// do something
} // idióma adatszerkezet bejárásához
szép sítlus, használjunk interface-eket ahol lehet
ArrayList-het és LinkedList-hez más Iterator implementációk
Set<T> halmaz adattípus interface
HashSet<T> és TreeSet<T> implementáló osztályok
megint teljesen más Iterator implementációval
Collection<T> interface
ennek spec esetei a List<T> és a Set<T>
package java.util;
public interface List<T> extends Collection<T> {...}
^interface-ek származhatnak egymásból
public interface Collection<T> extends Iterable<T> {...}
Iterable<T> interface
Iterator<T> iterator();
szabványos programkönyvtárban van, de kihat magára a nyelvre, a for-utasításon
-> enhanced for-loop <- főnök
List<String> names = new ...
for (String name : names) {
// do sth
}
class Point extends java.lang.Object {...}
^osztályok közötti származtatás
(osztály)öröklődés inherit? -> altípusosság -> interface extends
-> class implements interface
-> kódátörökítés
is-a (is-egy) kapcsolat fogalmak között
-> ekviv:
class Point {...}
Iterable<T>
| [k]
java.lang.Object Collection<T>
| [p] | [p] | [p] | [k] | [k]
Point java.lang.Number TreeSet<T> -------------------------> [f] Set<T> List<T>
(mély fa) |[p] | [p] "interface-ek közötti öröklődés" = (ekviv) kiterjesztés
java.lang.Integer java.lang.Double
[p]
irányított fa gyökere az Object
osztályhierarchia
típushierarchia
[p] + [f] + [k]
irányított körmentes gráf
A <: B (részbenrendezés)
A altípusa a B (bázis)típusnak, ha A-ból vezet út B-be [f][p][k] ???k mentén (irányított)
altípusosság
LSP: Liskov's Substitutions Principle, Liskov-féle helyettesítési elv '
A egy altípusa B-nek, ha a programjainkban B típusú objektumok helyett nyugodtan használhatunk A típusú objektumokat is, nem lesz baj
OOP nyelvekben az altípusosságot az öröklődés indukálja (extends [p], implements [f], extends [k])
List<String> names = new ArrayList<>(); // <> elhagyható a String
ArrayList<string> < List<String>
hivatkozott objektum változó deklarált típusa,
létrehozható osztálya lehet interface
(intreface nem new-olható)
azaz a változók lehetnek polimorfak, de a dinamikus típus altípusa kell legyen a statikus stípusnak
^referenciák
dinamikus típus változhat
dinamukis -> változó típusa <- statikus
futás közben változhat állandók, nem változnak
pl. names = new LinkedList<String>();
megváltoztatja a hivatkozott objektumot
void m(List<String> names) {
names = new LinkedList<String>();
}
osztályöröklés -> altípusképzés
(extends) -> kód átörökítése
- megöröklöm a szülőosztály tagjait (attribútumok, metódusok)
pl. bázisosztályban implementált műveletek hívhatók az alosztályon is, pl public int hashCode()
- újabb tagokkal bővíthetem a megörökölt dolgokhoz lépest
pl. private int x, y mezők
public void move (int dx, int dx) {...}
(osztály megadása a különbségek felsorolásával)
- megváltoztathatom a megörökölt máveletek implementációját (felüldefiniálás) (különbség, specifikáció)
felüldefiniálás:
----------------
egy metódusnak több imeplementációja lehet, kül osztályokban
pl. Object-ben definiált a toString metódus, saját osztályaink felülír(hat)ják
dinamikus kötés: (dinamic binding, late binding)
----------------
metódushívásnál a híváshoz használt referencia dinamikus típusa alapján választódik ki h melyik implementáció hajtódjon végre
(a dinamikus típushoz legközelebbi)
(kitüntetett paraméter, p.move(...) -> p)
Java stb: csak a kitüntetett pm dinamikus típusa számít a kiválasztásban
statikus típus: milyen metódusok hívhatók meg?
dinamukus típus: melyik implementációt?
statikus típus fordítási időben ismert:
statikus típus ellenőrzés a statikus szemantikai szabályok ellenőrzésére használt,pl. meghívható egy metódus egy referencián?
ha nem, fordítási hiba
dinamikus típus futási időben ismert:
futási idejű döntés
alapvető OOP jellemvonás
rugalmas (+), lassú (-)
dinamikus típus speciálisabb lehet (altípus), futás közben pontosabb típusinformációk állnek rendelkezésre
Java lehetőséget ad dinamikus típusellenőrzésre is a pontosabb dinamikus típusok figyelembe vételével => rugalmasság
ha a d.t.e elbukik, az dinamikus szemantikai hiba, ClassCastException kivétel
|
package com.liyinghua.service;
import java.util.List;
import com.liyinghua.entity.Category;
public interface CategoryService {
/**
*
* @Title: getCategoryByChannelId
* @Description: 通过频道获得分类
* @param channelId
* @return
* @return: List
*/
List<Category> getCategoryByChannelId(Integer channelId);
}
|
package Day12;
public class Day12_4 {
public static void main(String[] args) throws Exceptionㅁ {
//예외처리 : 오류 발생시에 처리 코드
//1. 일반적인 오류는 코드에서 처리
//2. 예상치 못한 오류 발생시 => 예외처리
//1. 코드상 문제가 없는 경우
//3. 형태
//try{오류발생 예상코드}
//catch(예외클래스 객체명) {오류발생시 대체 코드}
//finally {무조건 실행되는 코드}
//4.예외클래스
//1.예외 이유를 알고 있는 경우 : 예외클래스 사용
//NullPointerException
//NumberFormatException
//ArrayIndexOutOfBoundsException
//등등
//2.예외 이유를 다양하거나 모르는 경우 : Exception 클래스 사용
//Exception : 모든 Exception 처리 할수 있음 [슈퍼클래스]
//1. 변수가 null인 경우 출력시
try { //오류 발생할것 같은 코드 => 오류발생시 catch로 이동
//=> 오류가 없을경우 try 모두 실행
String data = null;
System.out.println(data.toString()); //toString : 객체 정보 반환
}
catch (NullPointerException e) { //try에서 오류 발생시 catch 문 처리
System.out.println("예외발생 : " + e);
}
//2. 배열오류
try {
String[]문자배열 = new String[2]; // string 객체를 2개 저장할수있는 배열
문자배열[0] = "강호동";
문자배열[1] = "신동엽";
문자배열[3] = "서장훈"; //오류 발생 : 배열의 크기가 부족
} catch (ArrayIndexOutOfBoundsException e) {
System.out.println("예외발생 : " + e);
}
//3. 숫자 => 문자 변경 가능 //문자 => 숫자 변경 불가능
try {
String data1 = "100"; // 문자열
String data2 = "a100"; //문자열
//문자열 => 숫자열 반환 [Integer.parseInt(문자열)]
System.out.println(Integer.parseInt(data1)); //"100"-> 100가능
System.out.println(Integer.parseInt(data2)); //"a100"-> a100불가능
}
//4. 다중 예외처리
try {
//1.
String data = null;
System.out.println(data.toString()); //toString : 객체 정보 반환
//2.
String[]문자배열 = new String[2]; // string 객체를 2개 저장할수있는 배열
문자배열[0] = "강호동";
문자배열[1] = "신동엽";
문자배열[3] = "서장훈"; //오류 발생 : 배열의 크기가 부족
//3.
String data1 = "100"; // 문자열
String data2 = "a100"; //문자열
}
// catch (NullPointerException | ArrayIndexOutOfBoundsExceptoin e)
// System.out.println("예외발생 : " + e);
// }
catch (Exception e2) {
System.out.println("예외발생 : " + e2);
}
finally {
System.out.println("코드 종료");
//5.예외 떠넘기기
try {
Day12_5.예외던지기();
}
catch (Exception e) {
//TODO : handle exception
}
}
}
|
//*********************************************************
// Copyright (c) Microsoft Corporation
// All rights reserved.
//
// Licensed under the Apache License, Version 2.0 (the ""License"");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
// http://www.apache.org/licenses/LICENSE-2.0
//
// THIS CODE IS PROVIDED ON AN *AS IS* BASIS, WITHOUT
// WARRANTIES OR CONDITIONS OF ANY KIND, EITHER EXPRESS
// OR IMPLIED, INCLUDING WITHOUT LIMITATION ANY IMPLIED
// WARRANTIES OR CONDITIONS OF TITLE, FITNESS FOR A PARTICULAR
// PURPOSE, MERCHANTABLITY OR NON-INFRINGEMENT.
//
// See the Apache Version 2.0 License for specific language
// governing permissions and limitations under the License.
//*********************************************************
package com.example.onenoteservicecreatepageexample;
import com.example.onenoteservicecreatepageexample.R;
import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.support.v4.app.NavUtils;
import android.text.Html;
import android.text.method.LinkMovementMethod;
import android.view.Menu;
import android.view.MenuItem;
import android.widget.TextView;
public class ResultsActivity extends Activity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_results);
// Show the Up button in the action bar.
setupActionBar();
//Get messages from the intent
Intent intent = getIntent();
String clientUrl = intent.getStringExtra(Constants.CLIENT_URL).replaceAll(
//This regular expression adds curly braces before and after the section identifier and page identifier values in the client URL
"=([0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{12})&",
"={$1}&");
TextView clientLinkView = (TextView) findViewById(R.id.lbl_clientLink);
clientLinkView.setText(Html.fromHtml("<a href = \'" + clientUrl + "\'>" + clientUrl + "</a>"));
clientLinkView.setMovementMethod(LinkMovementMethod.getInstance());
//Set the messages
((TextView) findViewById(R.id.lbl_Response)).setText(intent.getStringExtra(Constants.RESPONSE));
((TextView) findViewById(R.id.lbl_webLink)).setText(intent.getStringExtra(Constants.WEB_URL));
}
/**
* Set up the {@link android.app.ActionBar}.
*/
private void setupActionBar() {
getActionBar().setDisplayHomeAsUpEnabled(true);
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.results, menu);
return true;
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case android.R.id.home:
// This ID represents the Home or Up button. In the case of this
// activity, the Up button is shown. Use NavUtils to allow users
// to navigate up one level in the application structure. For
// more details, see the Navigation pattern on Android Design:
//
// http://developer.android.com/design/patterns/navigation.html#up-vs-back
//
NavUtils.navigateUpFromSameTask(this);
return true;
}
return super.onOptionsItemSelected(item);
}
}
|
package com.arevve.vietnews.main.container;
import android.app.SearchManager;
import android.os.Bundle;
import android.support.design.widget.TabLayout;
import android.support.v4.view.ViewPager;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.Toolbar;
import android.view.Menu;
import android.widget.ImageView;
import android.widget.SearchView;
import com.arevve.vietnews.R;
public class MainActivity extends AppCompatActivity
implements NavigationDrawerFragment.NavigationDrawerCallbacks {
private static final String STATE_CURR_PAGE = MainActivity.class.getName() + ".currpage";
/**
* Fragment managing the behaviors, interactions and presentation of the navigation drawer.
*/
private NavigationDrawerFragment mNavigationDrawerFragment;
private Toolbar toolbar;
private ViewPager pager;
private MainPagerAdapter adapter;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
// mNavigationDrawerFragment = (NavigationDrawerFragment)
// getFragmentManager().findFragmentById(R.id.navigation_drawer);
// mTitle = getTitle();
toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
setTitle(R.string.pager_page_news);
// // Set up the drawer.
// mNavigationDrawerFragment.setUp(
// R.id.navigation_drawer,
// (DrawerLayout) findViewById(R.id.drawer_layout),
// toolbar
// );
pager = (ViewPager) findViewById(R.id.pager);
adapter = new MainPagerAdapter(this, getFragmentManager());
pager.setAdapter(adapter);
pager.addOnPageChangeListener(new ViewPager.OnPageChangeListener() {
@Override
public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {
}
@Override
public void onPageSelected(int position) {
setTitle(adapter.getPageTitle(position));
}
@Override
public void onPageScrollStateChanged(int state) {
}
});
TabLayout tabLayout = (TabLayout) findViewById(R.id.tabbar);
tabLayout.setupWithViewPager(pager);
ImageView imageView = new ImageView(this);
imageView.setImageResource(R.drawable.ic_whatshot_white_24dp);
tabLayout.getTabAt(0).setCustomView(imageView);
imageView = new ImageView(this);
imageView.setImageResource(R.drawable.ic_apps_white_24dp);
tabLayout.getTabAt(1).setCustomView(imageView);
imageView = new ImageView(this);
imageView.setImageResource(R.drawable.ic_public_white_24dp);
tabLayout.getTabAt(2).setCustomView(imageView);
imageView = new ImageView(this);
imageView.setImageResource(R.drawable.ic_account_circle_white_24dp);
tabLayout.getTabAt(3).setCustomView(imageView);
if(savedInstanceState != null) {
int page = savedInstanceState.getInt(STATE_CURR_PAGE);
pager.setCurrentItem(page, false);
}
}
@Override
public void onNavigationDrawerItemSelected(int position) {
// update the browser content by replacing fragments
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.main, menu);
SearchManager searchManager = (SearchManager) getSystemService(SEARCH_SERVICE);
SearchView searchView = (SearchView) menu.findItem(R.id.menu_search).getActionView();
searchView.setSearchableInfo(searchManager.getSearchableInfo(getComponentName()));
searchView.setIconifiedByDefault(true);
return super.onCreateOptionsMenu(menu);
}
@Override
protected void onSaveInstanceState(Bundle outState) {
super.onSaveInstanceState(outState);
outState.putInt(STATE_CURR_PAGE, pager.getCurrentItem());
}
}
|
package javascriptExecuter;
import java.util.concurrent.TimeUnit;
import org.openqa.selenium.Alert;
import org.openqa.selenium.By;
import org.openqa.selenium.JavascriptExecutor;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.chrome.ChromeDriver;
public class JvaScrpt {
static WebDriver driver;
public static void main(String[] args) throws Exception {
System.setProperty("webdriver.chrome.driver", "chromedriver.exe");
driver = new ChromeDriver();
driver.get("file:///C:/Users/rajat/Downloads/Selenium%20Softwares/Offline%20Website/Offline%20Website/index.html");
driver.manage().window().maximize();
driver.manage().timeouts().pageLoadTimeout(20, TimeUnit.SECONDS);
JavascriptExecutor js = (JavascriptExecutor) driver;
System.out.println(js.executeScript("return document.URL;"));
System.out.println(js.executeScript("return document.title;"));
js.executeScript("document.title='Geet';");
System.out.println(js.executeScript("return document.title;"));
WebElement email = driver.findElement(By.id("email"));
js.executeScript("arguments[0].click()", email);
js.executeScript("document.getElementById('email').value='kiran@gmail.com';");
js.executeScript("alert('Ready to Email');");
Alert al = driver.switchTo().alert();
System.out.println(al.getText());
Thread.sleep(2000);
al.accept();
WebElement pass = driver.findElement(By.id("password"));
js.executeScript("arguments[0].click()", pass);
js.executeScript("document.getElementById('password').value='123456';");
//js.executeScript("document.getElement(By.xpath('//input[@id='password']')).value='123456';");
WebElement signIn = driver.findElement(By.xpath("//button"));
js.executeScript("arguments[0].click()", signIn);
js.executeScript("alert('GoodMorning');");
Alert al1 = driver.switchTo().alert();
System.out.println(al1.getText());
Thread.sleep(3000);
al1.accept();
}
}
|
package by.epam.parser.service;
import by.epam.parser.entity.Attribute;
import by.epam.parser.entity.Document;
import by.epam.parser.entity.Element;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.Reader;
import java.util.ArrayDeque;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import static by.epam.parser.service.Constant.*;
/**
* <p>Parse xml file to elements tree structure.
* Form total document object.</p>
*
* @author VeronikaChigir
*/
public class DOMParser implements Parser{
/**
* Help to work with elements
* during looking for new tags.
*/
private ArrayDeque<Element> tagsStack;
/**
* Help to work with elements
* during formation of the document.
*/
private ArrayDeque<Element> documentStack;
private int fullCloseTagGroup = 1;
private int closeTagNameGroup = 2;
private int fullOpenTagGroup = 3;
private int openTagNameGroup = 4;
private int openTagAttributesGroup = 5;
private int fullSingleTagGroup = 6;
private int singleTagNameGroup = 7;
private int singleTagAttributesGroup = 8;
private int tagContentGroup = 9;
public DOMParser(){}
/**
* <p>Parse xml file to elements tree structure.
* Form total document object.</p>
*
* @param reader for reading character streams
* @return total document object
* @throws ParseException if something wrong with parsing
*/
@Override
public Document parse(Reader reader) throws ParseException {
Document document=new Document();
BufferedReader read = new BufferedReader(reader);
String line;
try{
tagsStack=new ArrayDeque<>();
documentStack=new ArrayDeque<>();
line = read.readLine();
Pattern pattern = Pattern.compile(FIND_TAGS);
Matcher matcher;
int currentRange = 1;
do{
matcher=pattern.matcher(line);
while (matcher.find()){
if (matcher.group(fullOpenTagGroup) != null) {//поиск и запись открывающих тегов
Element e = new Element();
parseOpenTag(matcher,currentRange,e);
currentRange++;
}
if (matcher.group(tagContentGroup) != null) {//содержимое тегов
if(notInstructionAndComment(matcher.group(tagContentGroup))) {
parseContent(matcher);
}
}
if (matcher.group(fullCloseTagGroup) != null) {//поиск закрывающего тега и запись элемента
Element e = tagsStack.pop();
currentRange--;
parseCloseTag(matcher, currentRange, e);
}
if (matcher.group(fullSingleTagGroup) != null) {//одиночные теги
parseSingleTag(matcher,currentRange);
}
}
line=read.readLine();
}while (line!=null);
document.setRoot(documentStack.pop());
}catch (Exception e){
throw new ParseException(e);
}finally {
try {
read.close();
} catch (IOException e) {
e.printStackTrace();
}
}
return document;
}
/**
* <p>For element form list of attributes.
* Regard that in input xml file attributes split by spaces.</p>
*
* @param inputStringWithAttributes
* @param currentElement
*/
public void createAttributesList(String inputStringWithAttributes, Element currentElement){
String[] result=inputStringWithAttributes.split(SPACES);
for(String str: result){
String[] s = str.split(ASSIGNMENT);
String name = s[0];
String value = s[1];
currentElement.addAttribute(new Attribute(name,value));
}
}
/**
* <p>Add content to current element.</p>
*
* @param tagMatcher is matcher
*/
public void parseContent(Matcher tagMatcher){
String currentContent=tagMatcher.group(tagContentGroup);
Element e = tagsStack.pop();
if(!currentContent.contains(SPACE)) {
e.setContent(currentContent);
}else{
e.setContent(EMPTY_STRING);
}
tagsStack.push(e);
}
/**
* <p>Parse and add single tag to document stack.</p>
*
* @param tagMatcher is matcher
* @param tagRange is range - to monitor necessity wrapping child elements in the parent element
*/
public void parseSingleTag(Matcher tagMatcher, int tagRange){
Element e = new Element();
e.setOpenName(tagMatcher.group(singleTagNameGroup));
if (tagMatcher.group(singleTagAttributesGroup) != null) {
createAttributesList(tagMatcher.group(singleTagAttributesGroup), e);
}
e.setContent(EMPTY_STRING);
e.setRange(tagRange);
e.setCloseName(tagMatcher.group(singleTagNameGroup));
documentStack.push(e);
}
/**
* <p>Parse open tag and its attributes.
* Form tags stack.</p>
*
* @param tagMatcher is matcher
* @param tagRange is range - to monitor necessity wrapping child elements in the parent element
* @param element is current element
*/
public void parseOpenTag(Matcher tagMatcher, int tagRange, Element element){
element.setOpenName(tagMatcher.group(openTagNameGroup));
if (tagMatcher.group(openTagAttributesGroup) != null) {
createAttributesList(tagMatcher.group(openTagAttributesGroup), element);
}
element.setRange(tagRange);
tagsStack.push(element);
}
/**
* <p>Parse close tag. Form document stack.
* Loop monitors necessity wrapping child elements
* in the parent element</p>
*
* @param tagMatcher is matcher
* @param tagRange is range - to monitor necessity wrapping child elements in the parent element
*/
public void parseCloseTag(Matcher tagMatcher, int tagRange, Element e){
String currentCloseTagName = tagMatcher.group(closeTagNameGroup);
if (e.getOpenName().equals(currentCloseTagName)){//имена совпали
e.setCloseName(currentCloseTagName);
if (!documentStack.isEmpty()) {
if (e.getRange() < documentStack.peek().getRange()) {//ранг текущего эл-а < верхнего на documentStack
for (Element el : documentStack) {//упаковываем эл-ты с documentStack в текущий элемент
el = documentStack.pop();
e.addElement(el);
}
}
}
documentStack.push(e);
}else{
try {
throw new ParseException("Invalid document. Parsing is incorrect.", new Exception());
} catch (ParseException ex) {
throw new RuntimeException(ex);//stop running
}
}
}
/**
*
* @param current
* @return true if string contains tags or content,
* false - if string is process instruction or comment
*/
public boolean notInstructionAndComment(String current){
if(current.contains(INSTRUCTION)){
return false;
}
if(current.contains(COMMENT)){
return false;
}
return true;
}
}
|
package com.tencent.mm.plugin.appbrand.wxawidget.console;
import android.app.Activity;
import android.content.Context;
import android.support.v7.widget.LinearLayoutManager;
import android.util.AttributeSet;
import android.view.LayoutInflater;
import android.view.MotionEvent;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.FrameLayout;
import com.tencent.mm.modelappbrand.LogInfo;
import com.tencent.mm.plugin.appbrand.widget.recyclerview.MRecyclerView;
import com.tencent.mm.plugin.appbrand.wxawidget.a;
import com.tencent.mm.plugin.appbrand.wxawidget.b.b;
import com.tencent.mm.plugin.appbrand.wxawidget.b.c;
import com.tencent.mm.sdk.platformtools.bi;
import java.util.LinkedList;
import java.util.List;
public class ConsolePanel extends FrameLayout implements a {
final List<LogInfo> gQl = new LinkedList();
EditText gQr;
Button[] gQs;
Button gQt;
Button gQu;
a gQv;
int gQw;
String gQx;
MRecyclerView gvH;
static /* synthetic */ void a(ConsolePanel consolePanel) {
consolePanel.gQv.gQl.clear();
int i = 0;
while (true) {
int i2 = i;
if (i2 < consolePanel.gQl.size()) {
LogInfo logInfo = (LogInfo) consolePanel.gQl.get(i2);
if ((consolePanel.gQw <= 0 || logInfo.level == consolePanel.gQw) && !consolePanel.wr(logInfo.message)) {
consolePanel.gQv.gQl.add(logInfo);
}
i = i2 + 1;
} else {
consolePanel.gQv.RR.notifyChanged();
return;
}
}
}
public ConsolePanel(Context context, AttributeSet attributeSet) {
super(context, attributeSet);
initialize();
}
public ConsolePanel(Context context, AttributeSet attributeSet, int i) {
super(context, attributeSet, i);
initialize();
}
private void initialize() {
LayoutInflater.from(getContext()).inflate(c.console_panel, this, true);
this.gQr = (EditText) findViewById(b.console_dt);
this.gQr.clearFocus();
this.gQs = new Button[5];
cd(0, b.log_all_btn);
cd(1, b.log_log_btn);
cd(2, b.log_info_btn);
cd(3, b.log_warn_btn);
cd(4, b.log_error_btn);
this.gQs[0].setSelected(true);
this.gQw = 0;
this.gQt = (Button) findViewById(b.clear_log_btn);
this.gQu = (Button) findViewById(b.save_log_btn);
this.gQu.setEnabled(false);
this.gQt.setOnClickListener(new OnClickListener() {
public final void onClick(View view) {
ConsolePanel.this.gQl.clear();
ConsolePanel.this.gQv.gQl.clear();
ConsolePanel.this.gQv.RR.notifyChanged();
}
});
this.gQu.setOnClickListener(new 2(this));
this.gQr.addTextChangedListener(new 3(this));
this.gQr.setOnKeyListener(new 4(this));
this.gQr.setOnFocusChangeListener(new 5(this));
findViewById(b.do_filter_btn).setOnClickListener(new OnClickListener() {
public final void onClick(View view) {
ConsolePanel.this.gQx = ConsolePanel.this.gQr.getText().toString();
ConsolePanel.a(ConsolePanel.this);
}
});
setOnTouchListener(new 7(this));
this.gvH = (MRecyclerView) findViewById(b.log_rv);
this.gQv = new a(getContext());
MRecyclerView mRecyclerView = this.gvH;
getContext();
mRecyclerView.setLayoutManager(new LinearLayoutManager());
this.gvH.setItemAnimator(null);
this.gvH.setAdapter(this.gQv);
}
public boolean dispatchTouchEvent(MotionEvent motionEvent) {
if (motionEvent.getAction() == 0) {
int i;
View currentFocus = ((Activity) getContext()).getCurrentFocus();
if (currentFocus != null && (currentFocus instanceof EditText)) {
int[] iArr = new int[]{0, 0};
currentFocus.getLocationInWindow(iArr);
int i2 = iArr[0];
i = iArr[1];
int height = currentFocus.getHeight() + i;
int width = currentFocus.getWidth() + i2;
if (motionEvent.getX() <= ((float) i2) || motionEvent.getX() >= ((float) width) || motionEvent.getY() <= ((float) i) || motionEvent.getY() >= ((float) height)) {
i = 1;
if (i != 0) {
f.ck(currentFocus);
}
}
}
i = 0;
if (i != 0) {
f.ck(currentFocus);
}
}
return super.dispatchTouchEvent(motionEvent);
}
private void cd(int i, int i2) {
Button button = (Button) findViewById(i2);
button.setOnClickListener(new 8(this));
this.gQs[i] = button;
}
public final void at(List<LogInfo> list) {
if (list != null) {
List linkedList = new LinkedList();
int i = 0;
while (true) {
int i2 = i;
if (i2 >= list.size()) {
break;
}
LogInfo logInfo = (LogInfo) list.get(i2);
this.gQl.add(logInfo);
if ((logInfo.level == this.gQw || this.gQw == 0) && !wr(logInfo.message)) {
linkedList.add(logInfo);
}
i = i2 + 1;
}
if (!linkedList.isEmpty()) {
com.tencent.mm.bu.a.ab(new 9(this, linkedList));
}
}
}
private boolean wr(String str) {
return !bi.oW(this.gQx) && (str == null || !str.toLowerCase().contains(this.gQx.toLowerCase()));
}
}
|
package com.dais.mapper;
import com.dais.model.Fees;
import com.dais.model.FeesExample;
import java.util.List;
import org.apache.ibatis.annotations.Param;
public interface FeesMapper {
int countByExample(FeesExample example);
int deleteByExample(FeesExample example);
int deleteByPrimaryKey(Integer id);
int insert(Fees record);
int insertSelective(Fees record);
List<Fees> selectByExample(FeesExample example);
Fees selectByPrimaryKey(Integer id);
int updateByExampleSelective(@Param("record") Fees record, @Param("example") FeesExample example);
int updateByExample(@Param("record") Fees record, @Param("example") FeesExample example);
int updateByPrimaryKeySelective(Fees record);
int updateByPrimaryKey(Fees record);
}
|
package com.company.string;
import java.util.*;
/**
* Function Description
*
* Complete the isAnagram function in the editor.
*
* isAnagram has the following parameters:
*
* string a: the first string
* string b: the second string
* Returns
*
* boolean: If a and b are case-insensitive anagrams, return true. Otherwise, return false.
* Input Format
*
* The first line contains a string a.
* The second line contains a string b.
*
* Constraints
*
* 1 <= length(a), length(b), <= 50
* Strings a and b consist of English alphabetic characters.
* The comparison should NOT be case sensitive.
*
* @author Argishti_Tigranyan
*/
public class SecondTask {
public static void isAnagram(){
Scanner scanner = new Scanner(System.in);
System.out.print("Please enter the first string: ");
String firstString = scanner.nextLine();
System.out.print("Please enter the second string: ");
String secondString = scanner.nextLine();
char[] firstStringArray = firstString.toLowerCase().toCharArray();
char[] secondStringArray = secondString.toLowerCase().toCharArray();
Arrays.sort(firstStringArray);
Arrays.sort(secondStringArray);
System.out.println(Arrays.equals(firstStringArray, secondStringArray));
}
}
|
package com.lec.ex1_runnable;
public class TargetEx01 implements Runnable {
@Override
public void run() {
for(int i=0; i<10; i++) {
System.out.println("안녕하세요-"+i);
try {
Thread.sleep(500); //0.5초 동안 대기상태
} catch (InterruptedException e) {
}
}
}
//interface 안에 추상 메소드
}
|
package gr.athena.innovation.fagi;
import gr.athena.innovation.fagi.core.POIFuser;
import gr.athena.innovation.fagi.core.function.FunctionRegistry;
import gr.athena.innovation.fagi.core.function.IFunction;
import gr.athena.innovation.fagi.core.function.literal.AbbreviationAndAcronymResolver;
import gr.athena.innovation.fagi.core.function.literal.TermResolver;
import gr.athena.innovation.fagi.core.function.phone.CallingCodeResolver;
import gr.athena.innovation.fagi.evaluation.Evaluation;
import gr.athena.innovation.fagi.exception.ApplicationException;
import gr.athena.innovation.fagi.exception.WrongInputException;
import gr.athena.innovation.fagi.model.LinkedPair;
import gr.athena.innovation.fagi.learning.Trainer;
import gr.athena.innovation.fagi.model.AmbiguousDataset;
import gr.athena.innovation.fagi.preview.FrequencyCalculationProcess;
import gr.athena.innovation.fagi.preview.LightContainer;
import gr.athena.innovation.fagi.preview.LightStatisticsProcessor;
import gr.athena.innovation.fagi.preview.RDFInputSimilarityViewer;
import gr.athena.innovation.fagi.preview.RDFStatisticsCollector;
import gr.athena.innovation.fagi.preview.statistics.StatisticsContainer;
import gr.athena.innovation.fagi.preview.statistics.StatisticsExporter;
import gr.athena.innovation.fagi.repository.AbstractRepository;
import gr.athena.innovation.fagi.repository.CSVRepository;
import gr.athena.innovation.fagi.repository.GenericRDFRepository;
import gr.athena.innovation.fagi.rule.RuleSpecification;
import gr.athena.innovation.fagi.rule.RuleProcessor;
import gr.athena.innovation.fagi.specification.Configuration;
import gr.athena.innovation.fagi.specification.SpecificationConstants;
import gr.athena.innovation.fagi.specification.ConfigurationParser;
import gr.athena.innovation.fagi.utils.InputValidator;
import gr.athena.innovation.fagi.repository.ResourceFileLoader;
import gr.athena.innovation.fagi.specification.Namespace;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.text.ParseException;
import java.util.List;
import java.util.Map;
import java.util.Properties;
import java.util.Set;
import java.util.concurrent.TimeUnit;
import javax.xml.parsers.ParserConfigurationException;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.xml.sax.SAXException;
/**
* Reads the specification and rules, validates input and starts the fusion process.
*
* @author nkarag
*/
public class FagiInstance {
private static final Logger LOG = LogManager.getLogger(FagiInstance.class);
private final String config;
private final boolean runEvaluation = false;
private final boolean exportFrequencies = false;
private final boolean exportSimilaritiesPerLink = false;
private final boolean train = false;
private final boolean fuse = true;
/**
* FagiInstance Constructor. Expects the absolute path of the configuration XML file.
*
* @param config The path of the configuration file.
*/
public FagiInstance(String config) {
this.config = config;
}
/**
*
* Initiates the fusion process.
*
* @throws javax.xml.parsers.ParserConfigurationException Indicates configuration error.
* @throws org.xml.sax.SAXException Encapsulate a general SAX error or warning.
* @throws java.io.IOException Signals that an I/O exception of some sort has occurred.
* @throws java.text.ParseException Signals that an error has been reached unexpectedly while parsing.
* @throws gr.athena.innovation.fagi.exception.WrongInputException Wrong input exception.
* @throws org.json.simple.parser.ParseException Json parsing exception.
*/
public void run() throws ParserConfigurationException, SAXException, IOException, ParseException, WrongInputException,
ApplicationException, org.json.simple.parser.ParseException {
long startTimeInput = System.currentTimeMillis();
//Validate input
FunctionRegistry functionRegistry = new FunctionRegistry();
functionRegistry.init();
Set<String> functionSet = functionRegistry.getFunctionMap().keySet();
InputValidator validator = new InputValidator(config, functionSet);
LOG.info("Validating input..");
if (!validator.isValidConfigurationXSD()) {
LOG.info(SpecificationConstants.HELP);
System.exit(-1);
}
//Parse specification and rules
ConfigurationParser configurationParser = new ConfigurationParser();
Configuration configuration = configurationParser.parse(config);
if (!validator.isValidRulesWithXSD(configuration.getRulesPath())) {
LOG.info(SpecificationConstants.HELP);
System.exit(-1);
}
if (!validator.isValidFunctions(configuration.getRulesPath())) {
LOG.info(SpecificationConstants.HELP);
System.exit(-1);
}
//validate output filepath:
if(!validator.isValidOutputDirPath(configuration.getOutputDir())){
LOG.info("Please specify a file output in specification.");
LOG.info(SpecificationConstants.HELP);
System.exit(-1);
}
LOG.info("XML files seem syntactically valid.");
LOG.info("Rules: " + configuration.getRulesPath());
RuleProcessor ruleProcessor = new RuleProcessor();
RuleSpecification ruleSpec = ruleProcessor.parseRules(configuration.getRulesPath());
ruleSpec.setFunctionRegistry(functionRegistry);
long stopTimeInput = System.currentTimeMillis();
//Load datasets
long startTimeReadFiles = System.currentTimeMillis();
AbstractRepository genericRDFRepository = new GenericRDFRepository();
genericRDFRepository.parseLeft(configuration.getPathDatasetA());
genericRDFRepository.parseRight(configuration.getPathDatasetB());
LOG.info("Source datasets loaded.");
Integer initialLinksCount = 0;
switch(configuration.getLinksFormat()){
case SpecificationConstants.Config.NT: {
genericRDFRepository.parseLinks(configuration.getPathLinks());
initialLinksCount = AbstractRepository.getInitialCount();
break;
}
case SpecificationConstants.Config.CSV: {
CSVRepository csvRepository = new CSVRepository();
csvRepository.parseLinks(configuration.getPathLinks());
initialLinksCount = CSVRepository.getInitialCount();
break;
}
case SpecificationConstants.Config.CSV_UNIQUE_LINKS:{
CSVRepository.extractUniqueLinks(configuration.getPathLinks());
initialLinksCount = CSVRepository.getInitialCount();
break;
}
case SpecificationConstants.Config.CSV_ENSEMBLES:{
CSVRepository.extractEnsembles(configuration.getPathLinks());
initialLinksCount = CSVRepository.getInitialCount();
break;
}
}
LOG.info("Links file loaded.");
AmbiguousDataset.getAmbiguousDataset().getModel();
long stopTimeReadFiles = System.currentTimeMillis();
//Load resources
ResourceFileLoader resourceFileLoader = new ResourceFileLoader();
Map<String, String> knownAbbreviations = resourceFileLoader.getKnownAbbreviationsMap();
List<String> rdfProperties = resourceFileLoader.getRDFProperties();
Set<String> specialTerms = resourceFileLoader.getSpecialTerms();
Map<String, String> codes = resourceFileLoader.getExitCodes();
AbbreviationAndAcronymResolver.setKnownAbbreviationsAndAcronyms(knownAbbreviations);
AbbreviationAndAcronymResolver.setLocale(configuration.getLocale());
TermResolver.setTerms(specialTerms);
CallingCodeResolver.setCodes(codes);
LOG.info("Resource files loaded.");
if(exportFrequencies){
LOG.info("Exporting frequencies...");
FrequencyCalculationProcess freqProcess = new FrequencyCalculationProcess();
freqProcess.run(configuration, rdfProperties);
}
if(exportSimilaritiesPerLink){
//similarity viewer for each pair and a, b, c, d normalization
RDFInputSimilarityViewer qualityViewer = new RDFInputSimilarityViewer();
try {
qualityViewer.printRDFSimilarityResults(rdfProperties);
} catch (com.vividsolutions.jts.io.ParseException | IOException ex) {
LOG.error(ex);
throw new ApplicationException(ex.getMessage());
}
}
//Produce quality metric results for previewing, if enabled
if (runEvaluation) {
LOG.info("Running evaluation...");
Evaluation evaluation = new Evaluation();
String csvPath = "";
evaluation.run(configuration, csvPath);
}
if(train){
LOG.info("Training...");
String trainingCsvPath = "";
configuration.setTrainingSetCsvPath(trainingCsvPath);
Trainer trainer = new Trainer(configuration);
trainer.train();
}
//Start fusion process
long startTimeFusion = System.currentTimeMillis();
if(fuse){
LOG.info("Initiating fusion process...");
POIFuser fuser = new POIFuser();
Map<String, IFunction> functionRegistryMap = functionRegistry.getFunctionMap();
List<LinkedPair> fusedEntities = fuser.fuseAll(configuration, ruleSpec, functionRegistryMap);
long stopTimeFusion = System.currentTimeMillis();
//Combine result datasets and write to file
long startTimeWrite = System.currentTimeMillis();
LOG.info("Writing results...");
fuser.combine(configuration, fusedEntities, ruleSpec.getDefaultDatasetAction());
long stopTimeWrite = System.currentTimeMillis();
long startTimeComputeStatistics = System.currentTimeMillis();
Integer rejected = fuser.getRejectedCount();
Integer fused = fuser.getFusedPairsCount();
StatisticsContainer container;
StatisticsExporter exporter = new StatisticsExporter();
LightContainer lightContainer = new LightContainer();
LightStatisticsProcessor lightStatProcessor = new LightStatisticsProcessor(lightContainer);
String finalStats = "";
if (configuration.getStats().equals(SpecificationConstants.Config.DETAILED_STATS)) {
LOG.info("Calculating statistics...");
//statistics obtained using RDF
RDFStatisticsCollector collector = new RDFStatisticsCollector();
container = collector.collect();
if(!container.isValid() && !container.isComplete()){
LOG.warn("Could not export statistics. Input dataset(s) do not contain "
+ Namespace.SOURCE + " property that is being used to count the entities.");
}
finalStats = container.toJsonMap();
} else if(configuration.getStats().equals(SpecificationConstants.Config.LIGHT_STATS)){
lightContainer.setAverageConfidence(fuser.getAverageConfidence());
lightContainer.setAverageGain(fuser.getAverageGain());
lightContainer.setMaxGain(fuser.getMaxGain());
lightContainer.setInitialLinks(initialLinksCount.toString());
lightContainer.setFusedPOIs(fused.toString());
lightContainer.setFusedPath(configuration.getFused());
lightContainer.setPathA(configuration.getPathDatasetA());
lightContainer.setPathB(configuration.getPathDatasetB());
if(configuration.getLinksFormat().equals(SpecificationConstants.Config.CSV_UNIQUE_LINKS)){
LOG.info("Unique links: " + CSVRepository.getUniqueCount());
Integer uniqueLinks = CSVRepository.getUniqueCount();
lightContainer.setUniqueLinks(uniqueLinks.toString());
} else {
lightContainer.setUniqueLinks(initialLinksCount.toString());
}
lightContainer.setRejectedLinks(rejected.toString());
lightStatProcessor = new LightStatisticsProcessor(lightContainer);
lightStatProcessor.compute();
} else {
finalStats = "";
LOG.info("Statistics will not be computed. Select a value in the \"stats\" field.");
}
long stopTimeComputeStatistics = System.currentTimeMillis();
Long datasetLoadTime = stopTimeReadFiles - startTimeReadFiles;
Long statisticsTime = stopTimeComputeStatistics - startTimeComputeStatistics;
Long fusionTime = stopTimeFusion - startTimeFusion;
Long totalTime = stopTimeWrite - startTimeInput;
Properties prop = new Properties();
prop.setProperty("fused", fused.toString());
prop.setProperty("rejected", rejected.toString());
prop.setProperty("dataset-load-time(ms)", datasetLoadTime.toString());
prop.setProperty("statistics-time(ms)", statisticsTime.toString());
prop.setProperty("fusion(ms)", fusionTime.toString());
prop.setProperty("total-time(ms)", totalTime.toString());
if(configuration.isVerbose()){
prop.setProperty("average-gain", fuser.getAverageGain().toString());
prop.setProperty("max-gain", fuser.getMaxGain().toString());
prop.setProperty("average-confidence", fuser.getAverageConfidence().toString());
} else {
prop.setProperty("average-gain", "available in verbose execution");
prop.setProperty("max-gain", "available in verbose execution");
prop.setProperty("average-confidence", "available in verbose execution");
}
OutputStream st = new FileOutputStream(configuration.getOutputDir() + "/" + "fusion.properties", false);
prop.store(st, null);
if(configuration.getStats().equals("light")){
lightStatProcessor.updateExecutionTimes(datasetLoadTime.toString(), fusionTime.toString(), statisticsTime.toString());
finalStats = lightStatProcessor.getStats();
}
exporter.exportStatistics(finalStats, configuration.getStatsFilepath());
LOG.info(configuration.toString());
LOG.info("####### ###### ##### #### ### ## # Results # ## ### #### ##### ###### #######");
LOG.info("Interlinked (might contain multiples): " + initialLinksCount);
if(configuration.getLinksFormat().equals(SpecificationConstants.Config.CSV_UNIQUE_LINKS)){
LOG.info("Unique links: " + CSVRepository.getUniqueCount());
} else if(configuration.getLinksFormat().equals(SpecificationConstants.Config.CSV_ENSEMBLES)){
LOG.info("Ensembles (including one-to-one): " + CSVRepository.getEnsemblesCount());
LOG.info("Initial links: " + CSVRepository.getInitialCount());
}
LOG.info("Fused: " + fused + ", Rejected links: " + rejected);
LOG.info("Linked Entities not found: " + fuser.getLinkedEntitiesNotFoundInDataset());
LOG.info("Analyzing/validating input and configuration completed in " + (stopTimeInput - startTimeInput) + "ms.");
LOG.info("Datasets loaded in " + datasetLoadTime + "ms.");
LOG.info("Statistics computed in " + statisticsTime + "ms.");
LOG.info("Fusion completed in " + fusionTime + "ms.");
LOG.info("Combining files and write to disk completed in " + (stopTimeWrite - startTimeWrite) + "ms.");
LOG.info("Total time {}ms.", totalTime);
LOG.info("####### ###### ##### #### ### ## # # # # # # ## ### #### ##### ###### #######");
}
}
/**
* Computes the selected statistics if the list. Returns a JSON string with the selected statistics.
*
* @param selected the selected statistics as a list.
* @return a JSON string containing the statistics.
* @throws WrongInputException wrong input exception.
* @throws ParserConfigurationException error parsing the configuration.
* @throws SAXException SAXException.
* @throws IOException I/O exception.
* @throws ParseException exception parsing the links file.
*/
public String computeStatistics(List<String> selected)
throws WrongInputException, ParserConfigurationException, SAXException, IOException, ParseException{
LOG.info("Initiating statistics process...");
long startInit = System.currentTimeMillis();
//Validate input
FunctionRegistry functionRegistry = new FunctionRegistry();
functionRegistry.init();
Set<String> functionSet = functionRegistry.getFunctionMap().keySet();
InputValidator validator = new InputValidator(config, functionSet);
LOG.info("Validating input..");
if (!validator.isValidConfigurationXSD()) {
LOG.info(SpecificationConstants.HELP);
System.exit(-1);
}
//Parse specification and rules
ConfigurationParser configurationParser = new ConfigurationParser();
Configuration configuration = configurationParser.parse(config);
if (!validator.isValidRulesWithXSD(configuration.getRulesPath())) {
LOG.info(SpecificationConstants.HELP);
System.exit(-1);
}
if (!validator.isValidFunctions(configuration.getRulesPath())) {
LOG.info(SpecificationConstants.HELP);
System.exit(-1);
}
//validate output filepath:
if(!validator.isValidOutputDirPath(configuration.getOutputDir())){
LOG.info("Please specify a file output in specification.");
LOG.info(SpecificationConstants.HELP);
System.exit(-1);
}
LOG.info("XML files seem syntactically valid.");
long stopInit = System.currentTimeMillis();
long initTime = stopInit - startInit;
LOG.info("Initialization time: " + initTime + "ms.");
//Load datasets
long startTimeReadFiles = System.currentTimeMillis();
AbstractRepository genericRDFRepository = new GenericRDFRepository();
genericRDFRepository.parseLeft(configuration.getPathDatasetA());
genericRDFRepository.parseRight(configuration.getPathDatasetB());
//genericRDFRepository.parseLinks(configuration.getPathLinks());
switch(configuration.getLinksFormat()){
case SpecificationConstants.Config.NT: {
genericRDFRepository.parseLinks(configuration.getPathLinks());
break;
}
case SpecificationConstants.Config.CSV: {
CSVRepository csvRepository = new CSVRepository();
csvRepository.parseLinks(configuration.getPathLinks());
break;
}
case SpecificationConstants.Config.CSV_UNIQUE_LINKS:{
CSVRepository.extractUniqueLinks(configuration.getPathLinks());
break;
}
}
long stopTimeReadFiles = System.currentTimeMillis();
long readTime = stopTimeReadFiles - startTimeReadFiles;
LOG.info("Datasets loaded in " + readTime + "ms.");
LOG.info("Calculating statistics...");
long startCompute = System.currentTimeMillis();
RDFStatisticsCollector collector = new RDFStatisticsCollector();
StatisticsContainer container = collector.collect(selected);
long stopCompute = System.currentTimeMillis();
long computeTime = stopCompute - startCompute;
if(!container.isValid() && !container.isComplete()){
LOG.warn("Could not export statistics. Input dataset(s) do not contain "
+ Namespace.SOURCE + " property that is being used to count the entities.");
}
LOG.info(container.toJsonMap());
LOG.info("Statistics computed in " + computeTime + "ms.");
return container.toJsonMap();
}
/**
* Produces formatted time from milliseconds.
*
* @param millis the milliseconds.
* @return the formatted time string.
*/
public static String getFormattedTime(long millis) {
String time = String.format("%02d min, %02d sec",
TimeUnit.MILLISECONDS.toMinutes(millis),
TimeUnit.MILLISECONDS.toSeconds(millis) -
TimeUnit.MINUTES.toSeconds(TimeUnit.MILLISECONDS.toMinutes(millis))
);
return time;
}
}
|
package recycle_bin;
import android.hardware.camera2.CameraManager;
import android.support.annotation.NonNull;
import recycle_bin.camera2.ShrampCamManager;
import sci.crayfis.shramp.logging.ShrampLogger;
/**
*
*/
public class MaineShrampCam {
//**********************************************************************************************
// Class Variables
//----------------
private ShrampCamManager mCameraManager;
// logging
private static ShrampLogger mLogger = new ShrampLogger(ShrampLogger.DEFAULT_STREAM);
//**********************************************************************************************
// Class Methods
//--------------
public MaineShrampCam(@NonNull CameraManager cameraManager) {
mLogger.log("Loading ShrampCamManager");
mCameraManager = ShrampCamManager.getInstance(cameraManager);
assert mCameraManager != null;
//ShrampCamManager.Callback.mmSurfaces = new ArrayList<>();
//ShrampCamManager.Callback.mmSurfaces.add(surface);
if (mCameraManager.hasFrontCamera()) {
// do nothing for now
}
if (mCameraManager.hasBackCamera()) {
// try to open it and do capture
mCameraManager.openBackCamera();
}
if (mCameraManager.hasExternalCamera()) {
// do nothing for now
}
}
private void createCaptureSession() {
// configure camera to go here after onOpened()
// make the surfaces and handlers you want
// tell camera device to create capture session
}
private void startRepeatingRequest() {
// configure cameracapturesession to come here when configured
}
private void startFrontCapture() {
if (mCameraManager.hasFrontCamera()) {
mLogger.log("Opening front camera");
mCameraManager.openFrontCamera();
} else {
mLogger.log("No front camera detected");
}
}
private void stopFrontCapture() {
mLogger.log("Closing front camera");
mCameraManager.closeFrontCamera();
}
private void startBackCapture() {
if (mCameraManager.hasBackCamera()) {
mLogger.log("Opening back camera");
mCameraManager.openBackCamera();
}
else {
mLogger.log("No back camera detected");
}
}
private void stopBackCapture() {
mLogger.log("Closing back camera");
mCameraManager.closeBackCamera();
}
private void startExternalCapture() {
if (mCameraManager.hasExternalCamera()) {
mLogger.log("Opening external camera");
mCameraManager.openExternalCamera();
}
else {
mLogger.log("No external camera detected");
}
mLogger.log("return;");
}
private void stopExternalCapture() {
mLogger.log("Closing external camera");
mCameraManager.closeExternalCamera();
}
}
|
package com.ha.cn.model;
import com.baomidou.mybatisplus.annotations.TableField;
import com.baomidou.mybatisplus.annotations.TableId;
import com.baomidou.mybatisplus.annotations.TableName;
import com.baomidou.mybatisplus.enums.FieldFill;
import com.sun.xml.internal.ws.spi.db.DatabindingException;
import org.sonatype.guice.plexus.config.Roles;
import java.util.Date;
/**
* @program: wisdomside
* @description: 用户模型
* user's model
* @author: zan.Kang
* @create: 2018-04-06 16:50
**/
@TableName("sec_user")
public class Users {
@TableId
private Long user_id;
private String user_name;
private String password;
private Integer is_enabled;//禁用状态
private Date update_time;//修改时间
private Date created_time;//创建时间
private Long belong_id;//上级id
private Integer sex;//性别
private String user_address;//用户地址
private Integer user_type;//用户类型
private String email;//用户邮箱
private String user_phone;//用户手机
private String user_old_phone;//用户旧手机
private String login_account;//登录账号
private String old_login_account;//旧登录账号
private Integer role_id;//权限id
private String role_name;
public String getRole_name() {
return role_name;
}
public void setRole_name(String role_name) {
this.role_name = role_name;
}
@TableField(exist =false)//不存在于数据库中
private String kaptchaCode;//登录验证码 非数据库中对象
public Long getUser_id() {
return user_id;
}
public void setUser_id(Long user_id) {
this.user_id = user_id;
}
public String getUser_name() {
return user_name;
}
public void setUser_name(String user_name) {
this.user_name = user_name;
}
public String getPassword() {
return password;
}
public void setPassword(String password) {
this.password = password;
}
public Integer getIs_enabled() {
return is_enabled;
}
public void setIs_enabled(Integer is_enabled) {
this.is_enabled = is_enabled;
}
public Date getUpdate_time() {
return update_time;
}
public void setUpdate_time(Date update_time) {
this.update_time = update_time;
}
public Date getCreated_time() {
return created_time;
}
public void setCreated_time(Date created_time) {
this.created_time = created_time;
}
public Long getBelong_id() {
return belong_id;
}
public void setBelong_id(Long belong_id) {
this.belong_id = belong_id;
}
public Integer getSex() {
return sex;
}
public void setSex(Integer sex) {
this.sex = sex;
}
public String getUser_address() {
return user_address;
}
public void setUser_address(String user_address) {
this.user_address = user_address;
}
public Integer getUser_type() {
return user_type;
}
public void setUser_type(Integer user_type) {
this.user_type = user_type;
}
public String getEmail() {
return email;
}
public void setEmail(String email) {
this.email = email;
}
public String getUser_phone() {
return user_phone;
}
public void setUser_phone(String user_phone) {
this.user_phone = user_phone;
}
public String getUser_old_phone() {
return user_old_phone;
}
public void setUser_old_phone(String user_old_phone) {
this.user_old_phone = user_old_phone;
}
public String getLogin_account() {
return login_account;
}
public void setLogin_account(String login_account) {
this.login_account = login_account;
}
public String getOld_login_account() {
return old_login_account;
}
public void setOld_login_account(String old_login_account) {
this.old_login_account = old_login_account;
}
public Integer getRole_id() {
return role_id;
}
public void setRole_id(Integer role_id) {
this.role_id = role_id;
}
public String getKaptchaCode() {
return kaptchaCode;
}
public void setKaptchaCode(String kaptchaCode) {
this.kaptchaCode = kaptchaCode;
}
}
|
package ua.nure.makieiev.brainfuck.application;
import org.junit.Assert;
import org.junit.Before;
import org.junit.Test;
import ua.nure.makieiev.brainfuck.command.Command;
import ua.nure.makieiev.brainfuck.factory.CommandFactory;
import ua.nure.makieiev.brainfuck.factory.SymbolStrategyFactory;
import java.util.List;
public class BrainFuckParserTest {
private BrainFuckParser brainFuckParser;
@Before
public void setUp() {
CommandFactory commandFactory = new CommandFactory();
SymbolStrategyFactory symbolStrategyFactory = new SymbolStrategyFactory(commandFactory);
brainFuckParser = new BrainFuckParser(symbolStrategyFactory);
}
@Test
public void shouldReturnTenCommands() {
int expected = 10;
List<Command> commands = brainFuckParser.parse("++++++++++");
int actual = commands.size();
Assert.assertEquals(expected, actual);
}
@Test
public void shouldReturnElevenCommands() {
int expected = 11;
List<Command> commands = brainFuckParser.parse("++++++++++[>+++++++>++++++++++>+++>+<<<<-]");
int actual = commands.size();
Assert.assertEquals(expected, actual);
}
}
|
package uk.gov.digital.ho.hocs.search.domain.model;
import org.junit.Test;
import uk.gov.digital.ho.hocs.search.api.dto.*;
import java.util.UUID;
import static org.assertj.core.api.Assertions.assertThat;
public class SomuItemTest {
private final UUID somuItemUUID = UUID.randomUUID();
private final UUID somuTypeUUID = UUID.randomUUID();
private final SomuItemDto validSomuItemDto = new SomuItemDto(somuItemUUID, somuTypeUUID, "{}");
@Test
public void shouldCreateCaseDataConstructor() {
SomuItem somuItem = SomuItem.from(validSomuItemDto);
assertThat(somuItem.getUuid()).isEqualTo(somuItemUUID);
assertThat(somuItem.getSomuUuid()).isEqualTo(somuTypeUUID);
assertThat(somuItem.getData()).isEqualTo("{}");
}
}
|
package com.tkb.elearning.dao;
import java.util.List;
import com.tkb.elearning.model.Zone;
/**
* 地區資料Dao介面接口
* @author Admin
* @version 創建時間:2016-03-11
*/
public interface ZoneDao {
/**
* 取得地區資料清單(分頁)
* @param pageCount
* @param pageStart
* @param zone
* @return List<Zone>
*/
public List<Zone> getList(int pageCount, int pageStart, Zone zone);
/**
* 取得地區資料總筆數
* @param zone
* @return Integer
*/
public Integer getCount(Zone zone);
/**
* 取得單筆地區資料
* @param zone
* @return Zone
*/
public Zone getData(Zone zone);
/**
* 新增地區資料
* @param qa
*/
public void add(Zone zone);
/**
* 修改地區資料排序
* @param zone
*/
public void updateSort(Zone zone);
/**
* 修改地區資料
* @param zone
*/
public void update(Zone zone);
/**
* 刪除地區資料
* @param id
*/
public void delete(Integer id);
/**
* 重新排序地區資料
*/
public void resetSort();
/**
* 檢查地區名稱
*/
public String checkZonename(Zone zone);
/**
* 地區form下拉選單的list
*/
public List<Zone> getZoneList();
}
|
package com.roflcopter.airmont.match;
import com.roflcopter.airmont.Airmont;
public class TaskTimer implements Runnable{
public void run (){
if (Airmont.getCurrentMatch () != null){
Airmont.getCurrentMatch ().onTick ();
}
}
}
|
package com.tencent.tinker.lib.d;
import android.content.Context;
import com.tencent.tinker.lib.e.d;
import com.tencent.tinker.lib.f.c;
import com.tencent.tinker.loader.shareutil.SharePatchFileUtil;
import com.tencent.tinker.loader.shareutil.SharePatchInfo;
import com.tencent.tinker.loader.shareutil.ShareTinkerInternals;
import java.io.File;
import org.xwalk.core.XWalkResourceClient;
public class a implements c {
public final Context context;
public a(Context context) {
this.context = context;
}
public void c(File file, int i) {
com.tencent.tinker.lib.f.a.i("Tinker.DefaultLoadReporter", "patch loadReporter onLoadPatchListenerReceiveFail: patch receive fail: %s, code: %d", new Object[]{file.getAbsolutePath(), Integer.valueOf(i)});
}
public void a(String str, String str2, File file, String str3) {
int i = 0;
com.tencent.tinker.lib.f.a.i("Tinker.DefaultLoadReporter", "patch loadReporter onLoadPatchVersionChanged: patch version change from " + str + " to " + str2, new Object[0]);
if (str != null && str2 != null && !str.equals(str2) && com.tencent.tinker.lib.e.a.hL(this.context).ons) {
com.tencent.tinker.lib.f.a.i("Tinker.DefaultLoadReporter", "onLoadPatchVersionChanged, try kill all other process", new Object[0]);
ShareTinkerInternals.ie(this.context);
c hQ = c.hQ(this.context);
if (!hQ.vtb) {
com.tencent.tinker.lib.f.a.w("Tinker.UpgradePatchRetry", "onPatchResetMaxCheck retry disabled, just return", new Object[0]);
} else if (!hQ.vtc.exists()) {
com.tencent.tinker.lib.f.a.w("Tinker.UpgradePatchRetry", "onPatchResetMaxCheck retry file is not exist, just return", new Object[0]);
} else if (str2 == null) {
com.tencent.tinker.lib.f.a.w("Tinker.UpgradePatchRetry", "onPatchResetMaxCheck md5 is null, just return", new Object[0]);
} else {
c$a ae = c$a.ae(hQ.vtc);
if (str2.equals(ae.bKg)) {
com.tencent.tinker.lib.f.a.i("Tinker.UpgradePatchRetry", "onPatchResetMaxCheck, reset max check to 1", new Object[0]);
ae.vtf = "1";
c$a.a(hQ.vtc, ae);
}
}
File[] listFiles = file.listFiles();
if (listFiles != null) {
int length = listFiles.length;
while (i < length) {
File file2 = listFiles[i];
String name = file2.getName();
if (file2.isDirectory() && !name.equals(str3)) {
SharePatchFileUtil.k(file2);
}
i++;
}
}
}
}
public void d(int i, Throwable th) {
com.tencent.tinker.lib.f.a.i("Tinker.DefaultLoadReporter", "patch loadReporter onLoadInterpret: type: %d, throwable: %s", new Object[]{Integer.valueOf(i), th});
switch (i) {
case 0:
com.tencent.tinker.lib.f.a.i("Tinker.DefaultLoadReporter", "patch loadReporter onLoadInterpret ok", new Object[0]);
break;
case 1:
com.tencent.tinker.lib.f.a.e("Tinker.DefaultLoadReporter", "patch loadReporter onLoadInterpret fail, can get instruction set from existed oat file", new Object[0]);
break;
case 2:
com.tencent.tinker.lib.f.a.e("Tinker.DefaultLoadReporter", "patch loadReporter onLoadInterpret fail, command line to interpret return error", new Object[0]);
break;
}
cGV();
}
public void a(File file, int i, boolean z) {
com.tencent.tinker.lib.f.a.i("Tinker.DefaultLoadReporter", "patch loadReporter onLoadFileNotFound: patch file not found: %s, fileType: %d, isDirectory: %b", new Object[]{file.getAbsolutePath(), Integer.valueOf(i), Boolean.valueOf(z)});
if (i == 4) {
cGV();
} else {
cGU();
}
}
public void a(File file, int i) {
com.tencent.tinker.lib.f.a.i("Tinker.DefaultLoadReporter", "patch load Reporter onLoadFileMd5Mismatch: patch file md5 mismatch file: %s, fileType: %d", new Object[]{file.getAbsolutePath(), Integer.valueOf(i)});
cGU();
}
public void a(String str, String str2, File file) {
com.tencent.tinker.lib.f.a.i("Tinker.DefaultLoadReporter", "patch loadReporter onLoadPatchInfoCorrupted: patch info file damage: %s, from version: %s to version: %s", new Object[]{file.getAbsolutePath(), str, str2});
cGU();
}
public void a(File file, int i, long j) {
com.tencent.tinker.lib.f.a.i("Tinker.DefaultLoadReporter", "patch loadReporter onLoadResult: patch load result, path:%s, code: %d, cost: %dms", new Object[]{file.getAbsolutePath(), Integer.valueOf(i), Long.valueOf(j)});
}
public void a(Throwable th, int i) {
switch (i) {
case XWalkResourceClient.ERROR_AUTHENTICATION /*-4*/:
com.tencent.tinker.lib.f.a.i("Tinker.DefaultLoadReporter", "patch loadReporter onLoadException: patch load unCatch exception: %s", new Object[]{th});
ShareTinkerInternals.ia(this.context);
com.tencent.tinker.lib.f.a.i("Tinker.DefaultLoadReporter", "unCaught exception disable tinker forever with sp", new Object[0]);
String hY = SharePatchFileUtil.hY(this.context);
if (!ShareTinkerInternals.oW(hY)) {
SharePatchFileUtil.aj(SharePatchFileUtil.hX(this.context));
com.tencent.tinker.lib.f.a.e("Tinker.DefaultLoadReporter", "tinker uncaught real exception:" + hY, new Object[0]);
break;
}
break;
case -3:
if (th.getMessage().contains("checkResInstall failed")) {
com.tencent.tinker.lib.f.a.e("Tinker.DefaultLoadReporter", "patch loadReporter onLoadException: tinker res check fail:" + th.getMessage(), new Object[0]);
} else {
com.tencent.tinker.lib.f.a.i("Tinker.DefaultLoadReporter", "patch loadReporter onLoadException: patch load resource exception: %s", new Object[]{th});
}
ShareTinkerInternals.ia(this.context);
com.tencent.tinker.lib.f.a.i("Tinker.DefaultLoadReporter", "res exception disable tinker forever with sp", new Object[0]);
break;
case -2:
if (th.getMessage().contains("checkDexInstall failed")) {
com.tencent.tinker.lib.f.a.e("Tinker.DefaultLoadReporter", "patch loadReporter onLoadException: tinker dex check fail:" + th.getMessage(), new Object[0]);
} else {
com.tencent.tinker.lib.f.a.i("Tinker.DefaultLoadReporter", "patch loadReporter onLoadException: patch load dex exception: %s", new Object[]{th});
}
ShareTinkerInternals.ia(this.context);
com.tencent.tinker.lib.f.a.i("Tinker.DefaultLoadReporter", "dex exception disable tinker forever with sp", new Object[0]);
break;
case -1:
com.tencent.tinker.lib.f.a.i("Tinker.DefaultLoadReporter", "patch loadReporter onLoadException: patch load unknown exception: %s", new Object[]{th});
break;
}
com.tencent.tinker.lib.f.a.e("Tinker.DefaultLoadReporter", "tinker load exception, welcome to submit issue to us: https://github.com/Tencent/tinker/issues", new Object[0]);
com.tencent.tinker.lib.f.a.printErrStackTrace("Tinker.DefaultLoadReporter", th, "tinker load exception", new Object[0]);
com.tencent.tinker.lib.e.a.hL(this.context).tinkerFlags = 0;
cGU();
}
public void b(File file, int i) {
com.tencent.tinker.lib.f.a.i("Tinker.DefaultLoadReporter", "patch loadReporter onLoadPackageCheckFail: load patch package check fail file path: %s, errorCode: %d", new Object[]{file.getAbsolutePath(), Integer.valueOf(i)});
cGU();
}
public final void cGU() {
com.tencent.tinker.lib.e.a hL = com.tencent.tinker.lib.e.a.hL(this.context);
if (hL.ons) {
d dVar = hL.vsD;
if (dVar.vsK) {
SharePatchInfo sharePatchInfo = dVar.patchInfo;
if (!(sharePatchInfo == null || ShareTinkerInternals.oW(sharePatchInfo.vvF))) {
com.tencent.tinker.lib.f.a.w("Tinker.DefaultLoadReporter", "checkAndCleanPatch, oldVersion %s is not null, try kill all other process", new Object[]{sharePatchInfo.vvF});
ShareTinkerInternals.ie(this.context);
}
}
}
hL.aWt();
}
public final boolean cGV() {
com.tencent.tinker.lib.e.a hL = com.tencent.tinker.lib.e.a.hL(this.context);
if (!hL.ons) {
return false;
}
File file = hL.vsD.vsO;
if (file == null || !c.hQ(this.context).acP(SharePatchFileUtil.ak(file))) {
return false;
}
com.tencent.tinker.lib.f.a.i("Tinker.DefaultLoadReporter", "try to repair oat file on patch process", new Object[0]);
com.tencent.tinker.lib.e.c.bP(this.context, file.getAbsolutePath());
return true;
}
}
|
package com.example.hp.above;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.TextView;
public class InsertionsortActivity extends AppCompatActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_insertionsort);
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case android.R.id.home:
finish();
return true;
}
return super.onOptionsItemSelected(item);
}
public boolean onCreateOptionsMenu(Menu menu) {
return true;
}
public void insertion_code(View view) {
TextView tv = (TextView) findViewById(R.id.insertion_code);
tv.setText("Algorithm\n" +
"// Sort an arr[] of size n\n" +
"insertionSort(arr, n)\n" +
"Loop from i = 1 to n-1.\n" +
"……a) Pick element arr[i] and insert it into sorted sequence arr[0…i-1]\n" +
"Example: \n" +
"12, 11, 13, 5, 6\n" +
"Let us loop for i = 1 (second element of the array) to 5 (Size of input array)\n" +
"i = 1. Since 11 is smaller than 12, move 12 and insert 11 before 12\n" +
"11, 12, 13, 5, 6\n" +
"i = 2. 13 will remain at its position as all elements in A[0..I-1] are smaller than 13\n" +
"11, 12, 13, 5, 6\n" +
"i = 3. 5 will move to the beginning and all other elements from 11 to 13 will move one position ahead of their current position.\n" +
"5, 11, 12, 13, 6\n" +
"i = 4. 6 will move to position after 5, and elements from 11 to 13 will move one position ahead of their current position.\n" +
"5, 6, 11, 12, 13" +
"\n\n// C program for insertion sort\n" +
"#include <stdio.h>\n" +
"#include <math.h>\n" +
" \n" +
"/* Function to sort an array using insertion sort*/\n" +
"void insertionSort(int arr[], int n)\n" +
"{\n" +
" int i, key, j;\n" +
" for (i = 1; i < n; i++)\n" +
" {\n" +
" key = arr[i];\n" +
" j = i-1;\n" +
" \n" +
" /* Move elements of arr[0..i-1], that are\n" +
" greater than key, to one position ahead\n" +
" of their current position */\n" +
" while (j >= 0 && arr[j] > key)\n" +
" {\n" +
" arr[j+1] = arr[j];\n" +
" j = j-1;\n" +
" }\n" +
" arr[j+1] = key;\n" +
" }\n" +
"}\n" +
" \n" +
"// A utility function ot print an array of size n\n" +
"void printArray(int arr[], int n)\n" +
"{\n" +
" int i;\n" +
" for (i=0; i < n; i++)\n" +
" printf(\"%d \", arr[i]);\n" +
" printf(\"\\n\");\n" +
"}\n" +
" \n" +
" \n" +
" \n" +
"/* Driver program to test insertion sort */\n" +
"int main()\n" +
"{\n" +
" int arr[] = {12, 11, 13, 5, 6};\n" +
" int n = sizeof(arr)/sizeof(arr[0]);\n" +
" \n" +
" insertionSort(arr, n);\n" +
" printArray(arr, n);\n" +
" \n" +
" return 0;\n" +
"}" +
"\n\nOutput:\n" +
"5 6 11 12 13\n" +
"Time Complexity: O(n*n)\n" +
"Auxiliary Space: O(1)\n" +
"Boundary Cases: Insertion sort takes maximum time to sort if elements are sorted in reverse order. And it takes minimum time (Order of n) when elements are already sorted.\n" +
"Algorithmic Paradigm: Incremental Approach\n" +
"Sorting In Place: Yes\n" +
"Stable: Yes\n" +
"Online: Yes\n" +
"Uses: Insertion sort is uses when number of elements is small. It can also be useful when input array is almost sorted, only few elements are misplaced in complete big array.\n" +
"What is Binary Insertion Sort?\n" +
"We can use binary search to reduce the number of comparisons in normal insertion sort. Binary Insertion Sort find use binary search to find the proper location to insert the selected item at each iteration. In normal insertion, sort it takes O(i) (at ith iteration) in worst case. we can reduce it to O(logi) by using binary search. The algorithm as a whole still has a running worst case running time of O(n2) because of the series of swaps required for each insertion. Refer this for implementation.\n" +
"How to implement Insertion Sort for Linked List?\n" +
"Below is simple insertion sort algorithm for linked list.\n" +
"1) Create an empty sorted (or result) list\n" +
"2) Traverse the given list, do following for every node.\n" +
"......a) Insert current node in sorted way in sorted or result list.\n" +
"3) Change head of given linked list to head of sorted (or result) list. \n");
}
}
|
// ============================================================================
// Floxp.com : Java Enum Source File
// ============================================================================
//
// Enum: ResizePolicy
// Package: FloXP.com Android APIs (com.floxp.api) -
// Graphics API (com.floxp.api.graphics) -
// Layout Managers (org.fuusio.api.graphics.layout)
//
// Author: Marko Salmela
//
// Copyright (C) Marko Salmela, 2000-2011. All Rights Reserved.
//
// This software is the proprietary information of Marko Salmela.
// Use is subject to license terms. This software is protected by
// copyright and distributed under licenses restricting its use,
// copying, distribution, and decompilation. No part of this software
// or associated documentation may be reproduced in any form by any
// means without prior written authorization of Marko Salmela.
//
// Disclaimer:
// -----------
//
// This software is provided by the author 'as is' and any express or implied
// warranties, including, but not limited to, the implied warranties of
// merchantability and fitness for a particular purpose are disclaimed.
// In no event shall the author be liable for any direct, indirect,
// incidental, special, exemplary, or consequential damages (including, but
// not limited to, procurement of substitute goods or services, loss of use,
// data, or profits; or business interruption) however caused and on any
// theory of liability, whether in contract, strict liability, or tort
// (including negligence or otherwise) arising in any way out of the use of
// this software, even if advised of the possibility of such damage.
// ============================================================================
package org.fuusio.api.graphics.layout;
/**
* {@code ResizePolicy} defines an enumerated type for representing the various resize policies for
* {@link LayoutCell} instances defined in a {@link CellLayout}.
*
* @author Marko Salmela
*/
public enum ResizePolicy {
/**
* In Fixed policy, the width or height of a {@link LayoutCell} is not resizeable but has a
* fixed width or height.
*/
FIXED("Fixed"),
/**
* In Minimum policy, the width or height of a {@link LayoutCell} is the minimum width or
* height.
*/
MINIMUM("Minimum"),
/**
* In Preferred policy, the width or height of a {@link LayoutCell} is the preferred width or
* height.
*/
PREFERRED("Preferred");
/**
* The displayable label of {@code ResizePolicy} item values.
*/
private final String mLabel;
/**
* Constructs a new instance of {@code ResizePolicy} with the given displayable label.
*
* @param label A {@link String} for the displayable label.
*/
ResizePolicy(final String label) {
mLabel = label;
}
/**
* Gets the displayable label for this {@code ResizePolicy}.
*
* @return A {@link String} for displayable label.
*/
public String getLabel() {
return mLabel;
}
/**
* Returns a {@link String} representation of this {@code ResizePolicy}.
*
* @return A {@link String} representation of this @code ResizePolicy}.
*/
@Override
public String toString() {
return mLabel;
}
}
|
package Player;
import Deck.Card;
public class Dealer {
Hand hand = new Hand();
public Dealer(){
}
public void resetHand(){
hand.resetHand();
}
public Dealer(Card c, Card d){
Deal(c, d);
}
public void Deal(Card c, Card d){
drawCard(c);
drawCard(d);
}
public void drawCard(Card c){
hand.addCard(c);
}
public int handValue(){
return hand.getTotalValue();
}
public void displayHand(){
System.out.printf("Dealer has ");
hand.displayHand();
System.out.printf("\n");
}
public void displayUpdatedHand(){
System.out.printf("Dealer now has ");
hand.displayHand();
System.out.printf("\n");
}
}
|
package com.pds.rn.nav;
import com.pds.rn.route.BaseRouter;
import java.util.HashMap;
import java.util.Map;
/**
* @author: pengdaosong
* CreateTime: 2019-11-05 17:46
* Email:pengdaosong@medlinker.com
* Description:
*/
public class RoutePathMap {
private static final Map<String, Class<? extends BaseRouter>> ROUTER_MAP = new HashMap<>();
static Class<? extends BaseRouter> getRouteClass(String path) {
return ROUTER_MAP.get(path);
}
}
|
package com.ssm.lab.controller.admin;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.ssm.lab.bean.Article;
import com.ssm.lab.bean.Category;
import com.ssm.lab.bean.User;
import com.ssm.lab.common.Constants;
import com.ssm.lab.service.ArticleService;
import com.ssm.lab.service.CategoryService;
import com.ssm.lab.service.UserService;
import com.ssm.lab.utils.FileUtil;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.UUID;
@Controller("articleController")
@RequestMapping("/manage/article")
public class ArticleController {
@Autowired
private ArticleService articleService;
@Autowired
private CategoryService categoryService;
@RequestMapping("/to_add")
public String toAdd(Model model){
model.addAttribute("categoryList", categoryService.getAll());
model.addAttribute("article", new Article());
return "admin/article_add";
}
@RequestMapping("/add")
public String add(Article article, HttpSession session, HttpServletRequest request) throws IOException {
//文章作者为当前登录的用户
User loginUser = (User) session.getAttribute("user");
article.setUserSn(loginUser.getSn());
saveFile(article, request);
articleService.add(article);
return "redirect:list";
}
@RequestMapping(value = "to_update", params = "id")
public String toUpdate(Long id, Model model) {
model.addAttribute("categoryList", categoryService.getAll());
model.addAttribute("article", articleService.getByid(id));
return "admin/article_update";
}
@RequestMapping("update")
public String update(Article article,HttpServletRequest request) throws IOException {
saveFile(article, request);
articleService.edit(article);
return "redirect:list";
}
//上传文件不为空,则保存到指定照片路径下
private void saveFile(Article article,HttpServletRequest request) throws IOException {
if (!article.getImage().isEmpty()) {
//文件上传路径
String path = request.getServletContext().getRealPath(Constants.CAROUSEL_PATH);
//上传文件名
String filename = article.getImage().getOriginalFilename();
String suffix = filename.substring(filename.lastIndexOf("."));
filename = System.currentTimeMillis() + suffix;
File filepath = new File(path, filename);
//判断路径是否存在
if(!filepath.getParentFile().exists()){
filepath.getParentFile().mkdirs();
}
//将上传文件保存到一个目标文件中
article.getImage().transferTo(new File(path+File.separator+filename));
article.setShowImage(Constants.CAROUSEL_PATH + "/" + filename);
}
}
@RequestMapping("/list")
public String list(@RequestParam(value = "pn", defaultValue = "1") Integer pn,
@RequestParam(value = "type", required = false) String type,
@RequestParam(value = "keywords", required = false)String keywords,
Model model){
// 在查询之前只需要调用,传入页码,以及每页的大小
PageHelper.startPage(pn, 10);
if(StringUtils.isNotBlank(type) && StringUtils.isNotBlank(keywords)){
keywords=keywords.trim();
PageInfo page = new PageInfo(articleService.getByType(type, keywords), 5);
model.addAttribute("pageInfo",page);
} else {
PageInfo page = new PageInfo(articleService.getAll(), 5);
model.addAttribute("pageInfo",page);
}
return "admin/article_list";
}
@RequestMapping(value = "/remove",params = "id")
public String remove(String id,HttpServletRequest request){
List<Article> articles = articleService.getAllDeleted(id);
for (Article article : articles) {
if (StringUtils.isNotBlank(article.getShowImage())) {
String fileName = request.getServletContext().getRealPath(article.getShowImage());
FileUtil.deleteFile(fileName);
}
}
articleService.remove(id);
return "redirect:list";
}
}
|
package com.mythosapps.time15.storage;
import com.mythosapps.time15.types.BeginEndTask;
import com.mythosapps.time15.types.DaysDataNew;
import com.mythosapps.time15.types.KindOfDay;
import com.mythosapps.time15.types.Time15;
import java.util.Random;
/**
* Created by andreas on 02.03.16.
*/
public class TestDataFactory {
public static final Random RANDOM = new Random();
public static DaysDataNew newRandom(String id) {
DaysDataNew data1 = new DaysDataNew(id);
BeginEndTask task0 = new BeginEndTask();
switch (RANDOM.nextInt(4)) {
case 0:
task0.setKindOfDay(KindOfDay.WORKDAY);
task0.setBegin(8);
task0.setBegin15(0);
task0.setEnd(16);
task0.setEnd15(0);
data1.addTask(task0);
break;
case 1:
task0.setKindOfDay(KindOfDay.WORKDAY);
task0.setBegin(11);
task0.setBegin15(0);
task0.setEnd(16);
task0.setEnd15(30);
data1.addTask(task0);
BeginEndTask task1 = new BeginEndTask();
task1.setKindOfDay(KindOfDay.VACATION);
task1.setTotal(Time15.fromMinutes(4 * 60));
data1.addTask(task1);
break;
case 2:
task0.setKindOfDay(KindOfDay.VACATION);
data1.addTask(task0);
break;
case 3:
task0.setKindOfDay(KindOfDay.HOLIDAY);
data1.addTask(task0);
break;
case 4:
task0.setKindOfDay(KindOfDay.SICKDAY);
data1.addTask(task0);
break;
}
return data1;
}
}
|
package com.giraldo.parqueo.model;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.JoinColumn;
import javax.persistence.ManyToOne;
import javax.persistence.Table;
@Entity
@Table(name="TBL_VEHICULOS")
public class Vehiculo {
@Id
@GeneratedValue(strategy = GenerationType.AUTO)
private long id;
@Column(name="PLACA")
private String placa;
//*******************************************hice aqui
@ManyToOne
@JoinColumn(name="ID_TIPOVEHICULO")
private TipoVehiculo tipoVehiculo;
//*******************************************
@ManyToOne
@JoinColumn(name="ID_PROPIETARIO")
private Propietario propietario;
//se crean los gett y los sett
public long getId() {
return id;
}
public void setId(long id) {
this.id = id;
}
public String getPlaca() {
return placa;
}
public void setPlaca(String placa) {
this.placa = placa;
}
public Propietario getPropietario() {
return propietario;
}
public void setPropietario(Propietario propietario) {
this.propietario = propietario;
}
public TipoVehiculo getTipoVehiculo() {
return tipoVehiculo;
}
public void setTipoVehiculo(TipoVehiculo tipoVehiculo) {
this.tipoVehiculo = tipoVehiculo;
}
protected Vehiculo(String placa, TipoVehiculo tipoVehiculo, Propietario propietario) {
super();
this.placa = placa;
this.tipoVehiculo = tipoVehiculo;
this.propietario = propietario;
}
@Override
public String toString() {
return "Vehiculo [id=" + id + ", placa=" + placa + ", tipoVehiculo=" + tipoVehiculo.toString() + ", propietario="
+ propietario.toString() + "]";
}
protected Vehiculo() {
super();
// TODO Auto-generated constructor stub
}
}
|
package iiitb.timesheet.action;
import iiitb.timesheet.model.Client;
import iiitb.timesheet.service.AddClientService;
import com.opensymphony.xwork2.ActionSupport;
public class AddClient extends ActionSupport{
private String ClientName;
private String City;
private String email;
private long phone;
public String getEmail() {
return email;
}
public void setEmail(String email) {
this.email = email;
}
public long getPhone() {
return phone;
}
public void setPhone(long phone) {
this.phone = phone;
}
public String getCity() {
return City;
}
public void setCity(String city) {
City = city;
}
public String getClientName() {
return ClientName;
}
public void setClientName(String clientName) {
ClientName = clientName;
}
public String execute(){
/*System.out.println(ClientName);
System.out.println(City);
System.out.println(email);
System.out.println(phone);
AddClientService acs=new AddClientService();
int i=acs.addClient(ClientName,email,phone,City);
return SUCCESS;*/
Client client = new Client();
client.setCity(City);
client.setClient_name(ClientName);
client.setPhone_num(phone);
client.setEmail(email);
System.out.println(ClientName);
System.out.println(City);
System.out.println(email);
System.out.println(phone);
AddClientService acs=new AddClientService();
Boolean val = AddClientService.checkForDuplicateClient(client);
if(val==true) {
int i=acs.addClient(ClientName,email,phone,City);
if(i>0){
addActionMessage(getText("Client successfully added."));
return SUCCESS;
}else{
addActionError(getText("Error adding client. Please try again."));
return "duplicate";
}
} else {
addActionError(getText("Client already exists!!"));
return "duplicate";
}
}
}
|
package businesscode;
/**
*
* @Filename PerCapComp.java
*
* @Version $Id: PerCapComp.java,v 1.0 2014/02/25 09:23:00 $
*
* @Revisions
* Initial Revision
*/
import connect.JDBCMySQLMain;
import gui.Graph;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
/**
* <p/>
* The analysis file for determing the results
*
* @author Omkar Hegde
*/
public class PerCapComp {
String query = null;
// constructor
public PerCapComp() {
query = "SELECT\n" +
" c.county_name as cn," +
" c.state ," +
" c.year," +
" c.per_capita_income," +
" h.obesity_rate," +
" Sum(r.count) as Restaurant_count " +
" FROM" +
" county as c, " +
" restaurant as r, " +
" healthstatistics as h" +
" where c.county_name=r.county_name" +
" and c.state=r.state " +
" and c.year = r.year" +
" and c.county_name=h.county_name " +
" and c.state=h.state" +
" and c.year = h.year" +
" and h.obesity_rate is not null " +
" and c.per_capita_income is not null " +
" group by cn, c.state, c.year;";
}
/**
* Result set for the query is extracted and iterated
*/
public void getResults() {
JDBCMySQLMain connectToDB = new JDBCMySQLMain();
ResultSet resultSet = connectToDB.executeQuery(query);
HashMap<Integer, HashMap> collection = new HashMap<Integer, HashMap>();
List<String> countyStateList = new ArrayList<String>();
HashMap<String, Double> obesityRate11 = new HashMap<String, Double>();
HashMap<String, Double> per_capita_income11 = new HashMap<String, Double>();
HashMap<String, Integer> restaurant_count11 = new HashMap<String, Integer>();
HashMap<String, Double> obesityRate12 = new HashMap<String, Double>();
HashMap<String, Double> per_capita_income12 = new HashMap<String, Double>();
HashMap<String, Integer> restaurant_count12 = new HashMap<String, Integer>();
HashMap<String, Double> obesityRate13 = new HashMap<String, Double>();
HashMap<String, Double> per_capita_income13 = new HashMap<String, Double>();
HashMap<String, Integer> restaurant_count13 = new HashMap<String, Integer>();
try {
while (resultSet.next()) {
int year = resultSet.getInt("year");
String countyState = resultSet.getString("cn") + " " + resultSet.getString("state");
double per_capita_income = resultSet.getDouble("per_capita_income");
double obesity_rate = resultSet.getDouble("obesity_rate");
int rest_count = resultSet.getInt("Restaurant_count");
if (!countyStateList.contains(countyState)) {
countyStateList.add(countyState);
}
if (year == 2011) {
obesityRate11.put(countyState, obesity_rate);
per_capita_income11.put(countyState, per_capita_income);
restaurant_count11.put(countyState, rest_count);
} else if (year == 2012) {
obesityRate12.put(countyState, obesity_rate);
per_capita_income12.put(countyState, per_capita_income);
restaurant_count12.put(countyState, rest_count);
} else if (year == 2013) {
obesityRate13.put(countyState, obesity_rate);
per_capita_income13.put(countyState, per_capita_income);
restaurant_count13.put(countyState, rest_count);
}
}
} catch (SQLException exception) {
exception.printStackTrace();
}
collection.put(20111, obesityRate11);
collection.put(20112, per_capita_income11);
collection.put(20113, restaurant_count11);
collection.put(20121, obesityRate12);
collection.put(20122, per_capita_income12);
collection.put(20123, restaurant_count12);
collection.put(20131, obesityRate13);
collection.put(20132, per_capita_income13);
collection.put(20133, restaurant_count13);
calculate(collection, countyStateList);
}
/**
* Analysis of the data is done here
*
* @param collection
* @param countyStateList
*/
public void calculate(HashMap<Integer, HashMap> collection, List<String> countyStateList) {
HashMap<String, Double> obesityRate11 = (HashMap<String, Double>) collection.get(20111);
HashMap<String, Double> per_capita_income11 = (HashMap<String, Double>) collection.get(20112);
HashMap<String, Integer> restaurant_count11 = (HashMap<String, Integer>) collection.get(20113);
HashMap<String, Double> obesityRate12 = (HashMap<String, Double>) collection.get(20121);
HashMap<String, Double> per_capita_income12 = (HashMap<String, Double>) collection.get(20122);
HashMap<String, Integer> restaurant_count12 = (HashMap<String, Integer>) collection.get(20123);
HashMap<String, Double> obesityRate13 = (HashMap<String, Double>) collection.get(20131);
HashMap<String, Double> per_capita_income13 = (HashMap<String, Double>) collection.get(20132);
HashMap<String, Integer> restaurant_count13 = (HashMap<String, Integer>) collection.get(20133);
int increasing1 = 0;
int decreasing1 = 0;
int incorrectCount1 = 0;
int increasing2 = 0;
int decreasing2 = 0;
int incorrectCount2 = 0;
int increasing3 = 0;
int decreasing3 = 0;
int incorrectCount3 = 0;
for (String countyState : countyStateList) {
if ((per_capita_income11.get(countyState) <= per_capita_income12.get(countyState)) || (restaurant_count11.get(countyState) <= restaurant_count12.get(countyState))) {
if (obesityRate11.get(countyState) <= obesityRate12.get(countyState)) {
increasing1++;
} else {
incorrectCount1++;
}
}
}
for (String countyState : countyStateList) {
if ((per_capita_income12.get(countyState) <= per_capita_income13.get(countyState)) || (restaurant_count12.get(countyState) <= restaurant_count13.get(countyState))) {
if (obesityRate12.get(countyState) <= obesityRate13.get(countyState)) {
increasing2++;
} else {
incorrectCount2++;
}
}
}
for (String countyState : countyStateList) {
if ((per_capita_income11.get(countyState) <= per_capita_income13.get(countyState)) || (restaurant_count11.get(countyState) <= restaurant_count13.get(countyState))) {
if (obesityRate11.get(countyState) <= obesityRate13.get(countyState)) {
increasing3++;
} else {
incorrectCount3++;
}
}
}
System.out.println("Increasing 11-12: " + increasing1);
System.out.println("Decreasing 11-12: " + decreasing1);
System.out.println("Incorrect 11-12: " + incorrectCount1);
System.out.println("");
System.out.println("");
System.out.println("Increasing 12-13: " + increasing2);
System.out.println("Decreasing 12-13: " + decreasing2);
System.out.println("Incorrect 12-13: " + incorrectCount2);
System.out.println("");
System.out.println("");
System.out.println("Increasing 11-13: " + increasing3);
System.out.println("Decreasing 11-13: " + decreasing3);
System.out.println("Incorrect 11-13: " + incorrectCount3);
//FOR GRAPH
ArrayList<Double> list;
list = new ArrayList();
// double increase=increasing1+increasing2+increasing3;
// double decrease=decreasing1+decreasing2+decreasing3;
// double incorrect=incorrectCount1+incorrectCount2+incorrectCount3;
double total1 = increasing1 + decreasing1 + incorrectCount1;
double total2 = increasing2 + decreasing2 + incorrectCount2;
double total3 = increasing3 + decreasing3 + incorrectCount3;
list.add((increasing1 / total1) * 100);
list.add((increasing2 / total2) * 100);
list.add((double) ((increasing3 / total3) * 100));
list.add((decreasing1 / total1) * 100);
list.add((decreasing2 / total2) * 100);
list.add((decreasing3 / total3) * 100);
list.add((incorrectCount1 / total1) * 100);
list.add((incorrectCount2 / total2) * 100);
list.add((incorrectCount3 / total3) * 100);
// System.out.println(list);
ArrayList<String> label;
label = new ArrayList();
label.add("2011-2012");
label.add("2012-2013");
label.add("2011-2013");
ArrayList<String> symbRep;
symbRep = new ArrayList();
symbRep.add("Increasing");
symbRep.add("Decreasing");
symbRep.add("Incorrect");
new Graph().plot(list, 3, label, symbRep, "Number of Restaurants, Per Capita Income and Obesity Rate");
// new Graph().pie(list,symbRep,this.getClass().getSimpleName());
// new Graph().USAStates(average13);
}
public String getQuery() {
return query;
}
}
|
package com.lspring.annotation;
public interface IPersonDao {
void savePerson(Person p);
Person get(Long id);
}
|
package memory;
import java.io.BufferedWriter;
import java.io.FileWriter;
import java.io.IOException;
import java.io.PrintWriter;
public class MemoryWriter {
private final String MEM_FILEPATH = "memories/";
/**
* The {@code Buffered Reader} representation of this.
*/
private PrintWriter fileOut;
/*
* Instantiate the BufferedReader reading from the desired text file.
*/
public MemoryWriter(String fileName) {
try {
this.fileOut = new PrintWriter(new BufferedWriter(new FileWriter(MEM_FILEPATH + fileName)));
} catch (IOException e) {
System.err.println("Error creating MemoryWriter");
}
}
public void appendLine(String line) {
this.fileOut.append(line + "\n");
}
public void close() {
this.fileOut.close();
}
}
|
package zm.gov.moh.common.submodule.form.model.widgetModel;
public class TextBoxTwoModel extends AbstractEditTextModel {
public TextBoxTwoModel(){
super();
}
}
|
package com.wanglu.movcat.util;
import com.wanglu.movcat.model.Result;
/**
* Created by wangl on 2017/10/12 0012.
*/
public class ResultUtil {
public static Result success(Object object){
Result result = new Result();
result.setSuccess(true);
result.setMsg("请求成功");
result.setData(object);
return result;
}
public static Result error(String msg){
Result result = new Result();
result.setSuccess(false);
result.setMsg(msg);
return result;
}
}
|
package com.aitest.web.mapper;
import java.util.List;
import org.apache.ibatis.annotations.Param;
import org.springframework.stereotype.Repository;
import org.springframework.transaction.annotation.Transactional;
import com.aitest.web.entity.PermissionEntity;
import com.aitest.web.entity.RoleEntity;
@Repository
@Transactional
public interface UserRolePermissionMapper {
public List<RoleEntity> getAllRole();
public RoleEntity getRoleById(@Param(value="roleId")String roleId);
public List<PermissionEntity> getPermissionByRoleId(@Param(value="roleId")String roleId);
public RoleEntity getRoleByUserId(@Param(value="userId")String userId);
public List<PermissionEntity> getPermissionByUserId(@Param(value="userId")int userId);
}
|
package com.example.homestay_kha.Adapers;
import androidx.fragment.app.Fragment;
import androidx.fragment.app.FragmentManager;
import androidx.fragment.app.FragmentPagerAdapter;
import com.example.homestay_kha.Views.Fragments.History_Fragment;
import com.example.homestay_kha.Views.Fragments.Hotel_Fragment;
public class Adapter_viewpaper_Home extends FragmentPagerAdapter {
Hotel_Fragment homeFragment;
History_Fragment historyFragment;
public Adapter_viewpaper_Home(FragmentManager fm) {
super(fm);
homeFragment = new Hotel_Fragment();
historyFragment = new History_Fragment();
}
@Override
public Fragment getItem(int position) {
switch (position) {
case 0:
return homeFragment;
case 1:
return historyFragment;
default:
return null;
}
}
@Override
public int getCount() {
return 2;
}
}
|
package LinkedList;
/**
* @author admin
* @version 1.0.0
* @ClassName findLoopNode.java
* @Description 判断单向链表有没有环,没有返回null,有的话返回入环的节点
* 注意: 单向链表如果有环就一定走不出去了,因为只有一个next。所以有环的链表没有null
* 主要使用快慢指针的做法
* 归结一句话:
* 快走2,慢走1,如果有环,一定会相遇。且走过的路一定< 2*list.length(追逐赛,速度两倍,不可能超过2圈)
* 相遇后,就让其中一个指针回到链表的头部,另一个不动,然后两个指针再一起走,每次1步,再相遇的节点就是入环节点
* @createTime 2021年02月28日 13:02:00
*/
public class findLoopNode {
public static ListNode findLoopNode(ListNode head){
if (head == null || head.next == null || head.next.next == null){ //有环的链表长度至少为3
return null;
}
ListNode slow = head.next;
ListNode fast = head.next.next;
while (fast != slow){ // 快指针和慢指针在环中相遇的时候就停
//快指针肯定走的快,要是快指针首先触碰到null就代表没环
if(fast.next == null || fast.next.next == null){
return null;
}
fast = fast.next.next;
slow = slow.next;
}
//此时,如果运行到这里,代表快慢指针在环中相遇(同时验证必有还)
//相遇后,就让其中一个指针回到链表的头部,另一个不动
fast = head;
//然后两个指针再一起走,每次1步,再相遇的节点就是入环节点
while (fast != slow){
slow = slow.next;
fast = fast.next;
}
//运行到这里,已经找到入环节点了且fast = slow,返回哪个指针都可以
return slow;
}
}
|
package org.sbbs.app.demo.service.impl;
import org.sbbs.app.demo.dao.DictionaryItemDao;
import org.sbbs.app.demo.model.DictionaryItem;
import org.sbbs.app.demo.service.DictionaryItemManager;
import org.sbbs.base.service.impl.BaseManagerImpl;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
@Service( "dictionaryItemManager" )
public class DictionaryItemManagerImpl
extends BaseManagerImpl<DictionaryItem, Long>
implements DictionaryItemManager {
DictionaryItemDao dictionaryItemDao;
@Autowired
public DictionaryItemManagerImpl( DictionaryItemDao dictionaryItemDao ) {
super( dictionaryItemDao );
this.dictionaryItemDao = dictionaryItemDao;
}
}
|
package com.yinghai.a24divine_user.module.divine.book.pay.mvp;
import com.example.fansonlib.base.BaseModel;
import com.example.fansonlib.http.HttpResponseCallback;
import com.example.fansonlib.http.HttpUtils;
import com.example.fansonlib.utils.SharePreferenceHelper;
import com.yinghai.a24divine_user.bean.SubmitOrderBean;
import com.yinghai.a24divine_user.constant.ConHttp;
import com.yinghai.a24divine_user.constant.ConResultCode;
import com.yinghai.a24divine_user.constant.ConstantPreference;
import com.yinghai.a24divine_user.utils.ValidateAPITokenUtil;
import java.util.HashMap;
import java.util.Map;
/**
* @author Created by:fanson
* Created Time: 2017/11/16 14:07
* Describe:提交订单M层实现
*/
public class SubmitOrderModel extends BaseModel implements ContractSubmitOrder.IModel {
private ISubmitCallback mCallback;
@Override
public void submitOrder(int masterId,int businessId,int sex,String appointmentTime,String birthday,String describe,ISubmitCallback callback) {
mCallback = callback;
String time = String.valueOf(System.currentTimeMillis());
Map<String,Object> maps = new HashMap<>(10);
maps.put("userId", SharePreferenceHelper.getInt(ConstantPreference.I_USER_ID,0));
maps.put("masterId",masterId);
maps.put("sex",sex);
maps.put("appointmentTime",appointmentTime);
maps.put("businessId",businessId);
maps.put("name",SharePreferenceHelper.getString(ConstantPreference.S_USER_NAME,null));
maps.put("birthday",birthday);
if (describe.length()!=0){
maps.put("describe",describe);
}
maps.put("apiSendTime", time);
maps.put("apiToken", ValidateAPITokenUtil.ctreatTokenStringByTimeString(time));
HttpUtils.getHttpUtils().post(ConHttp.SUBMIT_ORDER,maps, new HttpResponseCallback<SubmitOrderBean>() {
@Override
public void onSuccess(SubmitOrderBean bean) {
if (mCallback ==null){
return;
}
switch (bean.getCode()) {
case ConResultCode.SUCCESS:
mCallback.onSubmitSuccess(bean.getData());
break;
default:
mCallback.handlerResultCode(bean.getCode());
break;
}
}
@Override
public void onFailure(String errorMsg) {
if (mCallback!=null){
mCallback.onSubmitFailure(errorMsg);
}
}
});
}
@Override
public void onDestroy() {
super.onDestroy();
mCallback = null;
}
}
|
import com.awrzosek.ski_station.basic.BasicConsts;
import com.awrzosek.ski_station.basic.BasicUtils;
import com.awrzosek.ski_station.initializers.InitializerUtils;
import com.awrzosek.ski_station.tables.ski.skipass.SkipassDao;
import javafx.application.Application;
import javafx.application.Platform;
import javafx.fxml.FXMLLoader;
import javafx.scene.Parent;
import javafx.scene.Scene;
import javafx.stage.Stage;
import java.sql.Connection;
import java.util.Objects;
public class Main extends Application {
@Override
public void start(Stage primaryStage) throws Exception
{
//TODO zrób ile się da w src (dodawanie i tak dalej ale już z wymaganiami, jakieś mockupy innych
// funkcji) + dopisz co potrzebne w functional requirements
//TODO jak już będzie interfejs graficzny to ogarnąć pokazywanie błędów
//TODO jak już przejdziesz przez func rec to popraw też use cases
InitializerUtils.run();
try (Connection connection = BasicUtils.getConnection())
{
BasicConsts.ACTIVE_NO_OF_CLIENTS = new SkipassDao(connection).getAllActive().size();
}
Parent parent = FXMLLoader.load(Objects.requireNonNull(getClass().getResource("login_window.fxml")));
primaryStage.setTitle("Stacja narciarska");
primaryStage.setScene(new Scene(parent));
primaryStage.show();
primaryStage.setMaximized(false);
primaryStage.onCloseRequestProperty().setValue(e -> Platform.exit());
}
public static void main(String[] args)
{
launch(args);
}
}
|
package cn.wolfcode.crm.shiro.filter;
import cn.wolfcode.crm.util.JsonResult;
import com.alibaba.fastjson.JSON;
import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.AuthenticationToken;
import org.apache.shiro.subject.Subject;
import org.apache.shiro.web.filter.authc.FormAuthenticationFilter;
import org.springframework.stereotype.Component;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import java.io.IOException;
@Component("formFilter")//crm专用表单过滤器
public class CRMFormFilter extends FormAuthenticationFilter {
/**
* @param token
* @param subject
* @param request
* @param response
* @return
* @throws Exception
*/
@Override
//登陆成功后调用该方法,只要在该方法中返回JSON即可
protected boolean onLoginSuccess(AuthenticationToken token, Subject subject, ServletRequest request, ServletResponse response) throws Exception {
response.setContentType("text/json;charset=UTF-8");//设置相应类型
response.getWriter().print(JSON.toJSON(new JsonResult()));
return false;
}
//登陆失败后调用该方法,只要在该方法中返回JSON即可
@Override
protected boolean onLoginFailure(AuthenticationToken token, AuthenticationException e, ServletRequest request, ServletResponse response) {
try {
response.setContentType("text/json;charset=UTF-8");//设置相应类型
JsonResult json = new JsonResult();
json.mark("账号或者密码不正确");//设置错误信息
response.getWriter().print(JSON.toJSON(json));
} catch (IOException e1) {
e1.printStackTrace();
}
return false;
}
}
|
package ru.mmk.okpposad.server.service;
import java.util.List;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import ru.mmk.okpposad.server.dao.PosadDao;
import ru.mmk.okpposad.server.domain.Posad;
@Service
public class PosadServiceImpl implements PosadService {
@Autowired
PosadDao posadDao;
@Override
public List<Posad> getPosadListByDate(String dateFrom, String dateTo) {
dateFrom = dateFrom.split("T")[0];
dateTo = dateTo.split("T")[0] + " 23:59:59";
return posadDao.listByDate(dateFrom, dateTo);
}
@Override
public void updateReasonById(Integer id, String userName, String reason) {
posadDao.updateReasonById(id, userName, reason);
}
@Override
public void removeById(Integer id, String userName) {
posadDao.removeById(id, userName);
}
}
|
package ga.selection;
import ga.Population;
public class SelectionRankBasedElitist extends Selection {
private int numElitist = 1;// keeps n best individuals
@Override
public void select(Population population) {
super.select(population);
// keep 'n' best individuals for next generation
for (int rank = 0; rank < numElitist; rank++) {
plan.reserve(population.getIndividuals().get(rank));
}
// select parents until target MatingPlan size is reached
int rank = 0;
while (plan.size() < returnSize) {
if (rank >= population.size())
rank = 1;
// continue to move to less fit individuals when selecting from the population
plan.add(population.getIndividuals().get(rank++), population.getIndividuals().get(rank++));
}
}
}
|
package com.tencent.liteav.beauty;
class b$4 implements Runnable {
final /* synthetic */ b a;
b$4(b bVar) {
this.a = bVar;
}
public void run() {
if (b.h(this.a) != null) {
a.a().d();
}
if (b.h(this.a) == null) {
if (b.a(this.a) != null) {
b.a(this.a).d();
b.a(this.a, null);
}
} else if (b.a(this.a) == null) {
b.a(this.a, b.f(this.a), b.g(this.a), b.h(this.a));
} else {
b.a(this.a).a(b.h(this.a));
}
}
}
|
package round.first.templete;
import round.first.binaryTree.TreeNode;
import java.util.ArrayList;
import java.util.List;
import java.util.Stack;
public class binaryTreeInorderTraversal {
public static void main(String[] args) {
TreeNode root = new TreeNode(1);
root.left = new TreeNode(2);
root.right = new TreeNode(3);
root.left.left = new TreeNode(4);
root.left.right = new TreeNode(5);
System.out.println(nonRecursion(root));
ArrayList<Integer> result = new ArrayList<>();
traverse(root, result);
System.out.println(result);
System.out.println(divideConquer(root));
}
public static List<Integer> nonRecursion(TreeNode root) {
List<Integer> result = new ArrayList<>();
Stack<TreeNode> stack = new Stack<>();
while (root != null) {
stack.push(root);
root = root.left;
}
while (!stack.isEmpty()) {
TreeNode node = stack.peek();
result.add(node.val);
if (node.right == null) {
node = stack.pop();
while (!stack.isEmpty() && stack.peek().right == node) {
node = stack.pop();
}
} else {
node = node.right;
while (node != null) {
stack.push(node);
node = node.left;
}
}
}
return result;
}
public static void traverse(TreeNode root, ArrayList<Integer> result){
if(root == null){
return;
}
traverse(root.left, result);
result.add(root.val);
traverse(root.right, result);
}
public static ArrayList<Integer> divideConquer(TreeNode root){
ArrayList<Integer> result = new ArrayList<>();
if(root == null){
return result;
}
ArrayList<Integer> leftResult = divideConquer(root.left);
ArrayList<Integer> rightResult = divideConquer(root.right);
result.addAll(leftResult);
result.add(root.val);
result.addAll(rightResult);
return result;
}
}
|
package com.globalrelay.exception;
public class HealthCheckConfigurationAlreadyExistsException extends RuntimeException{
public HealthCheckConfigurationAlreadyExistsException(String message) {
super(message);
}
}
|
package de.zarncke.lib.money;
import java.math.BigDecimal;
import java.util.Collection;
import java.util.Currency;
import de.zarncke.lib.err.Warden;
import de.zarncke.lib.util.Misc;
/**
* Mutable Money object.
*
* @author Gunnar Zarncke
*/
public class Cash implements Money {
public static MAmount plus(final Money a, final Money b) {
if (!Misc.equals(a.getCurrency(), b.getCurrency())) {
throw Warden.spot(new IllegalArgumentException("cannot add Money of different currencies " + a + "+" + b));
}
return new MAmount(a.getAmount().add(b.getAmount()), a.getCurrency());
}
public static MAmount times(final Money a, final int factor) {
if (factor == 0) {
return MAmount.zero(a.getCurrency());
}
if (factor == 1) {
return MAmount.of(a);
}
if (factor == -1) {
return new MAmount(a.getAmount().negate(), a.getCurrency());
}
return new MAmount(a.getAmount().multiply(BigDecimal.valueOf(factor)), a.getCurrency());
}
public static MAmount negate(final Money a) {
return new MAmount(a.getAmount().negate(), a.getCurrency());
}
public static Cash with(final MAmount... amounts) {
if(amounts.length==0) {
throw Warden.spot(new IllegalArgumentException("at least one amount must be given"));
}
Cash c = new Cash(amounts[0].getCurrency());
c.add(amounts);
return c;
}
public static Cash with(final Collection<? extends Money> amounts) {
if (amounts.size() == 0) {
throw Warden.spot(new IllegalArgumentException("at least one amount must be given"));
}
Cash c = new Cash(amounts.iterator().next().getCurrency());
c.add(amounts);
return c;
}
private Money money;
public Cash(final Currency currency) {
this.money = MAmount.zero(currency);
}
public MAmount toMAmount() {
return MAmount.of(this.money);
}
public void add(final Money... monies) {
for (Money monie : monies) {
this.money = plus(this.money, monie);
}
}
public void add(final Collection<? extends Money> monies) {
for (Money monie : monies) {
this.money = plus(this.money, monie);
}
}
public void subtract(final Money c) {
this.money = plus(this.money, times(c, -1));
}
@Override
public Currency getCurrency() {
return this.money.getCurrency();
}
@Override
public BigDecimal getAmount() {
return this.money.getAmount();
}
@Override
public String toString() {
return this.money.toString();
}
@Override
public int hashCode() {
final int prime = 31;
int result = 1;
result = prime * result + (this.money == null ? 0 : this.money.hashCode());
return result;
}
@Override
public boolean equals(final Object obj) {
if (this == obj) {
return true;
}
if (obj == null) {
return false;
}
if (getClass() != obj.getClass()) {
return false;
}
Cash other = (Cash) obj;
if (this.money == null) {
if (other.money != null) {
return false;
}
} else if (!this.money.equals(other.money)) {
return false;
}
return true;
}
@Override
public int compareTo(final Money o) {
return this.money.compareTo(o);
}
}
|
package game.elements;
import com.jme3.bullet.collision.shapes.BoxCollisionShape;
import com.jme3.bullet.collision.shapes.CollisionShape;
import com.jme3.bullet.control.RigidBodyControl;
import com.jme3.material.Material;
import com.jme3.material.RenderState;
import com.jme3.math.Vector3f;
import com.jme3.renderer.queue.RenderQueue;
import com.jme3.scene.Geometry;
import com.jme3.scene.Node;
import com.jme3.scene.shape.Box;
import static core.Core.*;
public class MyBox extends WorldObject {
public MyBox(float x, float y, float z,String TextureFileName,float width, float height, float depth) {
Box box = new Box(width, height, depth);
geom = new Geometry("<NAME>", box);
// geom.setQueueBucket(RenderQueue.Bucket.Transparent);
this.texture = globalAssetManager.loadTexture(TextureFileName);
mat = new Material(globalAssetManager, "Common/MatDefs/Misc/Unshaded.j3md");
// mat.getAdditionalRenderState().setBlendMode(RenderState.BlendMode.Alpha);
mat.setTexture("ColorMap", texture);
geom.setMaterial(mat);
geom.setLocalTranslation(new Vector3f(x, y, z));
//pivot = new Node("pivot");
//pivot.attachChild(geom);
//pivot.setLocalTranslation(new Vector3f(x, y, z));
globalRootNode.attachChild(geom);
}
}
|
package com.rishi.baldawa.iq;
import org.junit.Test;
import static org.junit.Assert.assertEquals;
public class ClimbStairsTest {
@Test
public void solution() throws Exception {
assertEquals(new ClimbStairs().solution(1), 1);
assertEquals(new ClimbStairs().solution(2), 2);
assertEquals(new ClimbStairs().solution(3), 3);
assertEquals(new ClimbStairs().solution(4), 5);
assertEquals(new ClimbStairs().solution(44), 1134903170);
}
}
|
package br.com.pcmaker.entity;
import javax.persistence.Column;
import javax.persistence.MappedSuperclass;
import javax.persistence.Transient;
import br.com.pcmaker.common.util.StringUtils;
import br.com.pcmaker.enums.StatusRegistro;
@MappedSuperclass
public abstract class StatusRegistroEntity extends AutoIncrementIdEntity {
/**
*
*/
private static final long serialVersionUID = 1L;
private String statusRegistro;
@Column(name = "status_registro", nullable = false, length = 1)
public String getStatusRegistro() {
return this.statusRegistro;
}
public void setStatusRegistro(String statusRegistro) {
this.statusRegistro = statusRegistro;
}
@Transient
public String getDescricaoStatusRegistro(){
if(StringUtils.isBlank(statusRegistro)){
return null;
}
return StatusRegistro.getStatusRegistro(statusRegistro).toString();
}
}
|
package com.example.caroline.countme;
import android.content.Context;
import android.util.Log;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
public class CsvReader {
String filename = "DataFile.csv";
//constructor
public CsvReader() {
}
public String[] readCsvFile(Context context) {
String csvString;
try {
BufferedReader inputReader = new BufferedReader(new InputStreamReader(
context.openFileInput(filename)));
String inputString;
StringBuffer stringBuffer = new StringBuffer();
while ((inputString = inputReader.readLine()) != null) {
stringBuffer.append(inputString + "\n");
}
Log.d("CsvReadString", stringBuffer.toString());
csvString = stringBuffer.toString();
String[] csvArray = csvString.split(",");
return csvArray;
} catch (IOException e) {
e.printStackTrace();
Project def = new Project(); // messy way of hopefully avoiding error when no file
return def.getData();
}
}
}
|
package task16;
import java.math.BigInteger;
/**
* @author Igor
*/
public class Main16a {
public static void main(String[] args) {
BigInteger a = new BigInteger("2").shiftLeft(999);
String str = a.toString();
int sum = 0;
for (int i = 0; i < str.length(); i++) {
sum += Integer.parseInt(str.charAt(i) + "");
}
System.out.println(sum);
}
}
|
package com.aprendoz_test.data;
/**
* aprendoz_test.FacturacionSapiens
* 01/19/2015 07:58:53
*
*/
public class FacturacionSapiens {
private FacturacionSapiensId id;
public FacturacionSapiensId getId() {
return id;
}
public void setId(FacturacionSapiensId id) {
this.id = id;
}
}
|
/**
*
*/
package com.badlogic.gdx.sqlite.desktop;
import java.io.InputStream;
import java.sql.Blob;
import java.sql.ResultSet;
import java.sql.SQLException;
import com.badlogic.gdx.sql.DatabaseCursor;
import com.badlogic.gdx.sql.SQLiteGdxException;
/** @author cycloneqi */
public class PreparedStatement implements com.badlogic.gdx.sql.PreparedStatement {
private java.sql.PreparedStatement statement;
public PreparedStatement (java.sql.PreparedStatement preparedStatement) {
this.statement = preparedStatement;
}
@Override
public DatabaseCursor executeQuery () throws SQLiteGdxException {
try {
ResultSet _result = statement.executeQuery();
DesktopCursor _cursor = new DesktopCursor();
_cursor.setNativeCursor(_result);
return _cursor;
} catch (SQLException e) {
throw new SQLiteGdxException("There is an error in executing the prepared statement", e);
}
}
@Override
public void execute () throws SQLiteGdxException {
try {
statement.execute();
} catch (SQLException e) {
throw new SQLiteGdxException("There is an error in executing the prepared statement", e);
}
}
@Override
public long executeInsert () throws SQLiteGdxException {
try {
statement.execute();
return statement.getGeneratedKeys().getLong(1);
} catch (SQLException e) {
throw new SQLiteGdxException("There is an error in executing the prepared statement", e);
}
}
@Override
public int executeUpdateDelete () throws SQLiteGdxException {
try {
return statement.executeUpdate();
} catch (SQLException e) {
throw new SQLiteGdxException("There is an error in executing the prepared statement", e);
}
}
@Override
public void clearParameters () throws SQLiteGdxException {
try {
statement.clearParameters();
} catch (SQLException e) {
throw new SQLiteGdxException("There is an error in clearing parameters the prepared statement", e);
}
}
@Override
public void close () throws SQLiteGdxException {
try {
statement.close();
} catch (SQLException e) {
throw new SQLiteGdxException("Prepared statement not closed correctly", e);
}
}
@Override
public void setNull (int parameterIndex, int type) throws SQLiteGdxException {
try {
statement.setNull(parameterIndex, type);
} catch (SQLException e) {
throw new SQLiteGdxException("Can't set null value tostatement for parameter index : " + parameterIndex, e);
}
}
@Override
public void setInt (int parameterIndex, int value) throws SQLiteGdxException {
try {
statement.setInt(parameterIndex, value);
} catch (SQLException e) {
throw new SQLiteGdxException("Can't set int value to statement for parameter index : " + parameterIndex, e);
}
}
@Override
public void setLong (int parameterIndex, long value) throws SQLiteGdxException {
try {
statement.setLong(parameterIndex, value);
} catch (SQLException e) {
throw new SQLiteGdxException("Can't set long value to statement for parameter index : " + parameterIndex, e);
}
}
@Override
public void setFloat (int parameterIndex, float value) throws SQLiteGdxException {
try {
statement.setFloat(parameterIndex, value);
} catch (SQLException e) {
throw new SQLiteGdxException("Can't set float value to statement for parameter index : " + parameterIndex, e);
}
}
@Override
public void setDouble (int parameterIndex, double value) throws SQLiteGdxException {
try {
statement.setDouble(parameterIndex, value);
} catch (SQLException e) {
throw new SQLiteGdxException("Can't set double value to statement for parameter index : " + parameterIndex, e);
}
}
@Override
public void setString (int parameterIndex, String value) throws SQLiteGdxException {
try {
statement.setString(parameterIndex, value);
} catch (SQLException e) {
throw new SQLiteGdxException("Can't set string value to statement for parameter index : " + parameterIndex, e);
}
}
@Override
public void setBlob (int parameterIndex, Blob blob) throws SQLiteGdxException {
try {
statement.setBlob(parameterIndex, blob);
} catch (SQLException e) {
throw new SQLiteGdxException("Can't set blob to statement for parameter index : " + parameterIndex, e);
}
}
@Override
public void setBlob (int parameterIndex, InputStream stream) throws SQLiteGdxException {
try {
statement.setBlob(parameterIndex, stream);
} catch (SQLException e) {
throw new SQLiteGdxException("Can't set blob to statement for parameter index : " + parameterIndex, e);
}
}
@Override
public void setBytes (int parameterIndex, byte[] b) throws SQLiteGdxException {
try {
statement.setBytes(parameterIndex, b);
} catch (SQLException e) {
throw new SQLiteGdxException("Can't set bytes to statement for parameter index : " + parameterIndex, e);
}
}
public void setStatement (java.sql.PreparedStatement statement) {
this.statement = statement;
}
@Override
public String toString () {
return statement.toString();
}
}
|
package com.insta.entities;
// Generated Aug 2, 2015 3:40:21 PM by Hibernate Tools 4.3.1
import java.util.Date;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.FetchType;
import javax.persistence.Id;
import javax.persistence.JoinColumn;
import javax.persistence.ManyToOne;
import javax.persistence.Table;
import javax.persistence.Temporal;
import javax.persistence.TemporalType;
/**
* InstaImageMetadata generated by hbm2java
*/
@Entity
@Table(name = "insta_image_metadata", schema = "public")
public class InstaImageMetadata implements java.io.Serializable {
private long imageMetadataId;
private InstaImage instaImage;
private String propertyName;
private String propertyValue;
private Date imageMetadataCreatedDate;
public InstaImageMetadata() {
}
public InstaImageMetadata(long imageMetadataId, InstaImage instaImage,
String propertyName, String propertyValue,
Date imageMetadataCreatedDate) {
this.imageMetadataId = imageMetadataId;
this.instaImage = instaImage;
this.propertyName = propertyName;
this.propertyValue = propertyValue;
this.imageMetadataCreatedDate = imageMetadataCreatedDate;
}
@Id
@Column(name = "image_metadata_id", unique = true, nullable = false)
public long getImageMetadataId() {
return this.imageMetadataId;
}
public void setImageMetadataId(long imageMetadataId) {
this.imageMetadataId = imageMetadataId;
}
@ManyToOne(fetch = FetchType.LAZY)
@JoinColumn(name = "image_id", nullable = false)
public InstaImage getInstaImage() {
return this.instaImage;
}
public void setInstaImage(InstaImage instaImage) {
this.instaImage = instaImage;
}
@Column(name = "property_name", nullable = false, length = 1000)
public String getPropertyName() {
return this.propertyName;
}
public void setPropertyName(String propertyName) {
this.propertyName = propertyName;
}
@Column(name = "property_value", nullable = false, length = 1000)
public String getPropertyValue() {
return this.propertyValue;
}
public void setPropertyValue(String propertyValue) {
this.propertyValue = propertyValue;
}
@Temporal(TemporalType.TIMESTAMP)
@Column(name = "image_metadata_created_date", nullable = false, length = 29)
public Date getImageMetadataCreatedDate() {
return this.imageMetadataCreatedDate;
}
public void setImageMetadataCreatedDate(Date imageMetadataCreatedDate) {
this.imageMetadataCreatedDate = imageMetadataCreatedDate;
}
}
|
/**
* OpenKM, Open Document Management System (http://www.openkm.com)
* Copyright (c) 2006-2015 Paco Avila & Josep Llort
*
* No bytes were intentionally harmed during the development of this application.
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 2 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License along
* with this program; if not, write to the Free Software Foundation, Inc.,
* 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
*/
package com.openkm.bean.kea;
import java.io.Serializable;
/**
* Term
*
* @author jllort
*
*/
public class Term implements Serializable {
private static final long serialVersionUID = 290660580424913769L;
private String text;
private String uid;
/**
* Term
*/
public Term() {
}
/**
* Term
* @param text
* @param uid
*/
public Term(String uid, String text) {
this.uid = uid;
this.text = text;
}
public String getText() {
return text;
}
public void setText(String text) {
this.text = text;
}
public String getUid() {
return uid;
}
public void setUid(String uid) {
this.uid = uid;
}
public boolean equals(Object o) {
if (this == o) return true;
if ((o == null) || !(o instanceof Term)) return false;
Term term = (Term) o;
if (uid != null ? !uid.equals(term.uid) : term.uid != null) return false;
if (text != null ? !text.equals(term.text) : term.text != null) return false;
return true;
}
public int hashCode() {
int result;
result = (text != null ? text.hashCode() : 0);
result = 31 * result + (uid != null ? uid.hashCode() : 0);
return result;
}
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.