text stringlengths 10 2.72M |
|---|
package com.tencent.mm.plugin.collect.reward.ui;
import com.tencent.mm.ab.l;
import com.tencent.mm.kernel.g;
import com.tencent.mm.plugin.collect.reward.a.a.a;
import com.tencent.mm.plugin.collect.reward.a.h;
import com.tencent.mm.sdk.platformtools.x;
import com.tencent.mm.storage.aa;
class QrRewardMainUI$3 implements a {
final /* synthetic */ QrRewardMainUI hWf;
final /* synthetic */ h hWg;
QrRewardMainUI$3(QrRewardMainUI qrRewardMainUI, h hVar) {
this.hWf = qrRewardMainUI;
this.hWg = hVar;
}
public final void i(l lVar) {
x.i("MicroMsg.QrRewardMainUI", "set succ: %s, %s", new Object[]{this.hWg.hqp, QrRewardMainUI.l(this.hWf).getText()});
if (this.hWg.hqp.equals(QrRewardMainUI.m(this.hWf))) {
g.Ei().DT().a(aa.a.sYP, QrRewardMainUI.m(this.hWf));
QrRewardMainUI.i(this.hWf);
}
}
}
|
package com.tt.miniapp.view.dialog;
import android.content.Context;
import android.os.IBinder;
import android.view.View;
import android.view.ViewGroup;
import android.view.WindowManager;
import com.tt.miniapphost.AppBrandLogger;
public abstract class WindowBase {
protected Context mContext;
private long mLastShowTime;
private WindowManager.LayoutParams mLayoutParams;
private boolean mShow;
private View mView;
private WindowManager mWindowManager;
public WindowBase(Context paramContext) {
this.mContext = paramContext;
this.mWindowManager = (WindowManager)this.mContext.getSystemService("window");
this.mLayoutParams = initLayoutParams();
if (this.mLayoutParams != null)
return;
throw new NullPointerException("initLayoutParams() can't return null");
}
private boolean checkInterval() {
long l = System.currentTimeMillis();
if (l - this.mLastShowTime < 20L)
return true;
this.mLastShowTime = l;
return false;
}
public WindowManager.LayoutParams getLayoutParams() {
return this.mLayoutParams;
}
public WindowManager getWindowManager() {
return this.mWindowManager;
}
protected abstract WindowManager.LayoutParams initLayoutParams();
boolean isShowing() {
return this.mShow;
}
public void remove() {
if (this.mShow) {
if (checkInterval())
return;
WindowManager windowManager = this.mWindowManager;
if (windowManager != null) {
View view = this.mView;
if (view != null)
try {
windowManager.removeViewImmediate(view);
this.mShow = false;
return;
} catch (Exception exception) {
AppBrandLogger.stacktrace(6, "WindowBase", exception.getStackTrace());
}
}
}
}
public void show(View paramView, int paramInt1, int paramInt2, IBinder paramIBinder) {
if (!this.mShow) {
if (checkInterval())
return;
this.mView = paramView;
if (this.mWindowManager != null && this.mView != null) {
if (paramIBinder != null) {
try {
this.mLayoutParams.token = paramIBinder;
this.mLayoutParams.x = paramInt1;
this.mLayoutParams.y = paramInt2;
this.mWindowManager.addView(this.mView, (ViewGroup.LayoutParams)this.mLayoutParams);
this.mShow = true;
return;
} catch (Exception exception) {
AppBrandLogger.stacktrace(6, "WindowBase", exception.getStackTrace());
}
return;
}
} else {
return;
}
} else {
return;
}
this.mLayoutParams.x = paramInt1;
this.mLayoutParams.y = paramInt2;
this.mWindowManager.addView(this.mView, (ViewGroup.LayoutParams)this.mLayoutParams);
this.mShow = true;
}
public void show(View paramView, IBinder paramIBinder) {
show(paramView, 0, 0, paramIBinder);
}
public void update(int paramInt1, int paramInt2) {
if (this.mShow) {
WindowManager windowManager = this.mWindowManager;
if (windowManager != null) {
View view = this.mView;
if (view != null)
try {
this.mLayoutParams.x = paramInt1;
this.mLayoutParams.y = paramInt2;
windowManager.updateViewLayout(view, (ViewGroup.LayoutParams)this.mLayoutParams);
return;
} catch (Exception exception) {
AppBrandLogger.stacktrace(6, "WindowBase", exception.getStackTrace());
}
}
}
}
public void update(WindowManager.LayoutParams paramLayoutParams) {
if (this.mShow) {
WindowManager windowManager = this.mWindowManager;
if (windowManager != null) {
View view = this.mView;
if (view != null)
try {
this.mLayoutParams = paramLayoutParams;
windowManager.updateViewLayout(view, (ViewGroup.LayoutParams)this.mLayoutParams);
return;
} catch (Exception exception) {
AppBrandLogger.stacktrace(6, "WindowBase", exception.getStackTrace());
}
}
}
}
}
/* Location: C:\Users\august\Desktop\tik\df_miniapp\classes.jar!\com\tt\miniapp\view\dialog\WindowBase.class
* Java compiler version: 6 (50.0)
* JD-Core Version: 1.1.3
*/ |
package ve.com.mastercircuito.components;
import java.sql.SQLException;
import java.util.HashSet;
import java.util.Vector;
import javax.swing.table.DefaultTableModel;
import javax.swing.table.TableModel;
import ve.com.mastercircuito.db.Db;
public class MyTableModel extends DefaultTableModel {
/**
*
*/
private static final long serialVersionUID = -7291256884024381770L;
private String[] columnNames;
private String query;
private String table;
private HashSet<Integer> editableColumns;
public MyTableModel(String query, String[] columnNames, String table, HashSet<Integer> editableColumns) {
this(queryToObject(query), columnNames);
this.query = query;
this.columnNames = columnNames;
this.table = table;
this.editableColumns = editableColumns;
}
public MyTableModel(Object[][] data, String[] columnNames) {
super(data, columnNames);
this.columnNames = columnNames;
}
public MyTableModel(Object[][] data, String[] columnNames, String table) {
this(data, columnNames);
this.table = table;
}
public MyTableModel(Object[][] data, String[] columnNames, String table, HashSet<Integer> editableColumns) {
this(data, columnNames, table);
this.editableColumns = editableColumns;
}
public TableModel getTableModel() {
return this;
}
protected static Object[][] queryToObject(String query) {
if (query == null) {
return null;
}
Db db = new Db();
Object[][] localObject = db.fetchAll(db.select(query));
try {
db.getConnection().close();
} catch (SQLException e) {
e.printStackTrace();
}
return localObject;
}
protected static Object[][] queryToObjectBoolean(String query, int booleanColumn) {
if (query == null) {
return null;
}
Db db = new Db();
Object[][] localObject = db.fetchAllAddBoolean(db.select(query), booleanColumn);
try {
db.getConnection().close();
} catch (SQLException e) {
e.printStackTrace();
}
return localObject;
}
public void setQuery(String query) {
Object[][] objectData = queryToObject(query);
this.setData(objectData);
}
public void setQueryAddBoolean(String query, int booleanColumn) {
Object[][] objectData = queryToObjectBoolean(query, booleanColumn);
this.setData(objectData);
}
private void setData(Object[][] objectData) {
if (objectData.length > 0) {
this.setDataVector(convertToVector(objectData), this.columnIdentifiers);
if (this.getDataVector().size() > 0) {
fireTableDataChanged();
}
} else {
this.setRowCount(0);
}
}
@Override
public int getRowCount() {
return this.getDataVector().size();
}
// @Override
// public int getColumnCount() {
// return this.columnNames.length;
// }
@Override
public Object getValueAt(int row, int col) {
@SuppressWarnings("unchecked")
Vector<Object> localVector = (Vector<Object>) this.getDataVector().elementAt(row);
return localVector.elementAt(col);
}
public Object getValueAt(int row, String colName) {
@SuppressWarnings("unchecked")
Vector<Object> localVector = (Vector<Object>) this.getDataVector().elementAt(row);
return localVector.elementAt(this.findColumn(colName));
}
@Override
public String getColumnName(int col) {
return this.columnNames[col];
}
@Override
public Class<?> getColumnClass(int c) {
if(this.getRowCount() > 0) {
return this.getValueAt(0, c).getClass();
} else {
return null;
}
}
public HashSet<Integer> getEditableColumns() {
return this.editableColumns;
}
public void setEditableColumns(HashSet<Integer> editableColumns) {
this.editableColumns = editableColumns;
}
// public void makeColumnEditable(Integer column) {
// this.editableColumns.add(column);
// }
@Override
public boolean isCellEditable(int row, int col) {
HashSet<Integer> editableColumns = this.getEditableColumns();
if(null != editableColumns && editableColumns.contains(new Integer(col))) {
return true;
} else {
return false;
}
}
@Override
public void setValueAt(Object value, int row, int col) {
Class<?> columnClass = this.getColumnClass(col);
if(columnClass.equals(Boolean.class)) {
boolean hasMain = false;
//Map<Integer,Boolean> mainSwitchesMap = new HashMap<Integer,Boolean>();
for(int i = 0; i < this.dataVector.size(); i++) {
@SuppressWarnings("unchecked")
Vector<Object> localVector = (Vector<Object>) this.dataVector.elementAt(i);
if(localVector.elementAt(col).equals(Boolean.TRUE)) {
hasMain = true;
}
}
@SuppressWarnings("unchecked")
Vector<Object> localVector = (Vector<Object>) this.dataVector.elementAt(row);
if (((!hasMain && value.equals(Boolean.TRUE)) || (hasMain && value.equals(Boolean.FALSE))) && Integer.valueOf((String) localVector.elementAt(2)) == 1) {
Integer switchId = Integer.valueOf(String.valueOf(localVector.elementAt(0)));
updateBoolean(switchId, (Boolean) value);
localVector.setElementAt((Boolean) value, col);
fireTableCellUpdated(row, col);
}
} else {
if(!editableColumns.isEmpty()) {
boolean cellChanged = false;
@SuppressWarnings("unchecked")
Vector<Object> localVector = (Vector<Object>) this.dataVector.elementAt(row);
if(localVector.elementAt(col) != value) {
cellChanged = true;
}
localVector.setElementAt(value, col);
fireTableCellUpdated(row, col);
String columnName = this.getColumnName(col);
String field = "";
switch(columnName.toLowerCase()) {
case "precio":
case "precio costo":
field = "price";
break;
case "cantidad":
field = "quantity";
break;
case "factor":
field = "factor";
break;
case "%mo":
field = "mo";
break;
case "%gi":
field = "gi";
break;
case "%ga":
field = "ga";
break;
case "referencia":
field = "reference";
break;
case "descripcion":
field = "material";
break;
case "cliente":
field = "client";
break;
case "codigo cliente":
field = "client_code";
break;
case "representante":
field = "representative";
break;
case "rif":
field = "rif";
break;
}
if(cellChanged && !field.isEmpty()) {
String sql = "";
Db db = new Db();
switch(table) {
case "board_switches":
case "board_materials":
case "control_board_switches":
case "control_board_materials":
case "budget_switches":
case "budget_boxes":
case "budget_boards":
case "budget_control_boards":
case "budget_materials":
case "materials":
case "clients":
sql = "UPDATE " + table + " SET " + field + " = '" + value + "' WHERE id = " + localVector.elementAt(0);
Db.update(sql);
this.setDataVector(convertToVector(db.fetchAll(db.select(query))), this.columnIdentifiers);
fireTableDataChanged();
break;
}
try {
db.getConnection().close();
} catch (SQLException e) {
e.printStackTrace();
}
}
}
}
}
public void setTable(String table) {
this.table = table;
}
private void updateBoolean(int switchId, Boolean value) {
Db db = new Db();
if(value.equals(Boolean.FALSE)) {
db.removeMainSwitch(table, switchId);
} else {
db.addMainSwitch(table, switchId);
}
try {
db.getConnection().close();
} catch (SQLException e) {
e.printStackTrace();
}
}
// public void add(Object[] value) {
// for(int i = 0; i < value.length; i++) {
// this.addRow(value);
// this.data[getRowCount()][i] = value[i];
// }
// }
}
|
package net.sourceforge.vrapper.utils;
public enum CaretType {
VERTICAL_BAR, RECTANGULAR, LEFT_SHIFTED_RECTANGULAR, HALF_RECT, UNDERLINE;
}
|
package main.java.com.comviva.flowone.client;
import javax.xml.bind.annotation.XmlAccessType;
import javax.xml.bind.annotation.XmlAccessorType;
import javax.xml.bind.annotation.XmlElement;
import javax.xml.bind.annotation.XmlSchemaType;
import javax.xml.bind.annotation.XmlType;
import javax.xml.datatype.XMLGregorianCalendar;
/**
* Notification is an intermediate message object that InstantLink may send during request processing to response service. Notifications may be produced by Business Service Tool, Network Element Interface or InstantLink internally.
*
* <p>Clase Java para Notification complex type.
*
* <p>El siguiente fragmento de esquema especifica el contenido que se espera que haya en esta clase.
*
* <pre>
* <complexType name="Notification">
* <complexContent>
* <restriction base="{http://www.w3.org/2001/XMLSchema}anyType">
* <sequence>
* <element ref="{http://soa.comptel.com/2011/02/instantlink}OrderNo"/>
* <element ref="{http://soa.comptel.com/2011/02/instantlink}RequestId"/>
* <element ref="{http://soa.comptel.com/2011/02/instantlink}Level"/>
* <element name="TimeStamp" type="{http://www.w3.org/2001/XMLSchema}dateTime"/>
* <element name="MessageId" type="{http://www.w3.org/2001/XMLSchema}string"/>
* <element name="Message" type="{http://www.w3.org/2001/XMLSchema}string"/>
* </sequence>
* </restriction>
* </complexContent>
* </complexType>
* </pre>
*
*
*/
@XmlAccessorType(XmlAccessType.FIELD)
@XmlType(name = "Notification", propOrder = {
"orderNo",
"requestId",
"level",
"timeStamp",
"messageId",
"message"
})
public class Notification {
@XmlElement(name = "OrderNo", required = true)
protected String orderNo;
@XmlElement(name = "RequestId")
protected long requestId;
@XmlElement(name = "Level")
protected int level;
@XmlElement(name = "TimeStamp", required = true)
@XmlSchemaType(name = "dateTime")
protected XMLGregorianCalendar timeStamp;
@XmlElement(name = "MessageId", required = true)
protected String messageId;
@XmlElement(name = "Message", required = true)
protected String message;
/**
* The OSS/BSS identifier of the request
*
* @return
* possible object is
* {@link String }
*
*/
public String getOrderNo() {
return orderNo;
}
/**
* Define el valor de la propiedad orderNo.
*
* @param value
* allowed object is
* {@link String }
*
*/
public void setOrderNo(String value) {
this.orderNo = value;
}
/**
* Unique request Id given by InstantLink
*
*/
public long getRequestId() {
return requestId;
}
/**
* Define el valor de la propiedad requestId.
*
*/
public void setRequestId(long value) {
this.requestId = value;
}
/**
* The notification level of this notification. 3 = BST notification, 4 = NEI phase message, 5 and above = System message
*
*/
public int getLevel() {
return level;
}
/**
* Define el valor de la propiedad level.
*
*/
public void setLevel(int value) {
this.level = value;
}
/**
* Obtiene el valor de la propiedad timeStamp.
*
* @return
* possible object is
* {@link XMLGregorianCalendar }
*
*/
public XMLGregorianCalendar getTimeStamp() {
return timeStamp;
}
/**
* Define el valor de la propiedad timeStamp.
*
* @param value
* allowed object is
* {@link XMLGregorianCalendar }
*
*/
public void setTimeStamp(XMLGregorianCalendar value) {
this.timeStamp = value;
}
/**
* Obtiene el valor de la propiedad messageId.
*
* @return
* possible object is
* {@link String }
*
*/
public String getMessageId() {
return messageId;
}
/**
* Define el valor de la propiedad messageId.
*
* @param value
* allowed object is
* {@link String }
*
*/
public void setMessageId(String value) {
this.messageId = value;
}
/**
* Obtiene el valor de la propiedad message.
*
* @return
* possible object is
* {@link String }
*
*/
public String getMessage() {
return message;
}
/**
* Define el valor de la propiedad message.
*
* @param value
* allowed object is
* {@link String }
*
*/
public void setMessage(String value) {
this.message = value;
}
}
|
package org.webmaple.common.model;
/**
* @author lyifee
* on 2021/1/12
*/
public class SpiderJobDTO {
/**
* 任务所在机器ip
*/
private String ip;
/**
* 任务所在worker名称
*/
private String worker;
/**
* 任务开启的spider uuid
*/
private String spiderUUID;
/**
* 任务定时类型
*/
private String type;
/**
* 任务定时数
*/
private int maintain;
/**
* 任务当前状态
*/
private String state;
/**
* 任务名称
*/
private String jobName;
/**
* QuartzJobBean类型的全限定名
*/
private String jobClazz;
/**
* 任务开始时间
*/
private String startTime;
/**
* corn表达式
*/
private String cronExpression;
/**
* 需要传递的参数
*/
private String extraInfo;
public String getIp() {
return ip;
}
public void setIp(String ip) {
this.ip = ip;
}
public String getWorker() {
return worker;
}
public void setWorker(String worker) {
this.worker = worker;
}
public String getSpiderUUID() {
return spiderUUID;
}
public void setSpiderUUID(String spiderUUID) {
this.spiderUUID = spiderUUID;
}
public String getType() {
return type;
}
public void setType(String type) {
this.type = type;
}
public int getMaintain() {
return maintain;
}
public void setMaintain(int maintain) {
this.maintain = maintain;
}
public String getState() {
return state;
}
public void setState(String state) {
this.state = state;
}
public String getJobName() {
return jobName;
}
public void setJobName(String jobName) {
this.jobName = jobName;
}
public String getJobClazz() {
return jobClazz;
}
public void setJobClazz(String jobClazz) {
this.jobClazz = jobClazz;
}
public String getStartTime() {
return startTime;
}
public void setStartTime(String startTime) {
this.startTime = startTime;
}
public String getCronExpression() {
return cronExpression;
}
public void setCronExpression(String cronExpression) {
this.cronExpression = cronExpression;
}
public String getExtraInfo() {
return extraInfo;
}
public void setExtraInfo(String extraInfo) {
this.extraInfo = extraInfo;
}
}
|
package com.developpez.lmauzaize.java.concurrence.ch03_structure_donnees;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Map;
import java.util.Random;
import java.util.TimeZone;
import java.util.concurrent.Callable;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.stream.Collectors;
import java.util.stream.IntStream;
import com.developpez.lmauzaize.java.concurrence.Logger;
public class ConcurrentHashMapConcurrence {
static Map<String, String> map;
public static void main(String[] args) throws Exception {
//////////////////////////////////////////
TimeZone.setDefault(TimeZone.getTimeZone("UTC"));
// Paramètres
int thread = 16;
int taille = 2_000_000;
int limite = 1_024;
// Génération des valeurs possibles
String[] cache = IntStream.range(0, limite).mapToObj(String::valueOf).toArray(String[]::new);
// Génère une liste fixe de tâches pour tous les tests
List<Callable<String>> tasks = new ArrayList<>(thread);
Random random = new Random();
for (int i = 0; i < thread; i++) {
List<String> list = random.ints(0, limite).limit(taille).mapToObj(key -> cache[key]).collect(Collectors.toCollection(() -> new ArrayList<>(taille)));
Callable<String> task = () -> {
String name = Thread.currentThread().getName();
for (String item : list) {
map.put(item, name);
}
return name;
};
tasks.add(task);
}
ExecutorService threadpool = Executors.newFixedThreadPool(thread);
for (int concurrence = 1; concurrence <= 256; concurrence*=2) {
map = new ConcurrentHashMap<>(limite, 1.0f, concurrence);
int count = 0;
int total = 0;
for (int i = 0; i < 50; i++) {
map.clear();
long start = System.currentTimeMillis();
threadpool.invokeAll(tasks);
long spent = System.currentTimeMillis() - start;
if (i >= 20) {
count++;
total += spent;
}
}
Logger.println("test: %04d, classe: %17s temps: %tT.%<tL", concurrence, map.getClass().getSimpleName(), new Date(total / count));
}
threadpool.shutdownNow();
//////////////////////////////////////////
}
}
|
package com.tyss.cg.exceptions;
import java.io.FileReader;
import java.util.Properties;
public class ThrowsClassEx {
public static void main(String[] args) throws Exception {
//public static void main(String[] args) throws IOException {
Properties properties=new Properties();
//new Properties().load(new FileReader("application.properties"));
properties.load(new FileReader("application.properties"));
System.out.println(properties.getProperty("name"));
System.out.println("Some name...");
}
}
|
package com.geekhelp.controller;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
/**
* Created by V.Odahovskiy.
* Date 09.02.2015
* Time 16:23
* Package com.geekhelp.controller
*/
@Controller
@RequestMapping(value = "/login")
public class LoginController {
@RequestMapping(method = RequestMethod.GET)
public String login() {
return "login";
}
}
|
package com.kodilla.kodillacoursecalculatormk;
public interface CalculatorInterface {
double operation(double val1, double val2);
String getOperator();
}
|
package com.scottehboeh.glc.utils;
import java.awt.*;
import java.awt.image.BufferedImage;
/**
* Created by 1503257 on 08/12/2017.
* <p>
* GuiUtils
* <p>
* This utility class functions as a toolbox for different useful UI-related
* methods and techniques.
*/
public class GuiUtils {
/**
* Get Scaled Image - Convert an image into a new Scaled Version
*
* @param srcImg - Given Original Image
* @param w - Given Width
* @param h - Given Height
* @return - Returned Scaled Image (Image)
*/
private Image getScaledImage(Image srcImg, int w, int h) {
BufferedImage resizedImg = new BufferedImage(w, h, BufferedImage.TYPE_INT_ARGB);
Graphics2D g2 = resizedImg.createGraphics();
g2.setRenderingHint(RenderingHints.KEY_INTERPOLATION, RenderingHints.VALUE_INTERPOLATION_BILINEAR);
g2.drawImage(srcImg, 0, 0, w, h, null);
g2.dispose();
return resizedImg;
}
}
|
package org.adn.ceiba.ceibarest.utils;
import java.util.ArrayList;
import java.util.Collection;
import org.adn.ceiba.ceibarest.dto.TipoVehiculoDTO;
import org.adn.ceiba.ceibarest.entity.TipoVehiculo;
/**
*
* @author jose.lozano
*
*/
public final class TipoVehiculoConstante {
public static final Integer ID = 1;
public static final String VEHICULO = "AUTOMOVIL";
public static final String CODIGO_MOTO = "M1";
public static final String CODIGO_CARRO = "C1";
public static final Integer CUPO_MOTO = 20;
public static final Integer CUPO_CARRO = 20;
public static final String DIAS_PERMITIDOS = "LU-MI";
public static final String PLACA_BLOQUEADA = "A";
public static final Collection<TipoVehiculo> TIPO_VEHICULO_LISTA_NULL = null;
private TipoVehiculoConstante() {}
public static final TipoVehiculo TIPO_VEHICULO_MOTO = TipoVehiculo.builder()
.id(ID)
.vehiculo(VEHICULO)
.placaBloqueada(PLACA_BLOQUEADA)
.codigo(CODIGO_MOTO)
.build();
public static final TipoVehiculo TIPO_VEHICULO_CARRO = TipoVehiculo.builder()
.id(ID)
.vehiculo(VEHICULO)
.codigo(CODIGO_CARRO)
.placaBloqueada(PLACA_BLOQUEADA)
.build();
public static final TipoVehiculoDTO TIPO_VEHICULO_DTO_CARRO = TipoVehiculoDTO.builder()
.id(ID)
.vehiculo(VEHICULO)
.codigo(CODIGO_CARRO)
.placaBloqueada(PLACA_BLOQUEADA)
.cupo(CUPO_CARRO)
.diasPermitidos(DIAS_PERMITIDOS)
.build();
public static final TipoVehiculoDTO TIPO_VEHICULO_DTO_MOTO = TipoVehiculoDTO.builder()
.id(ID)
.vehiculo(VEHICULO)
.codigo(CODIGO_MOTO)
.placaBloqueada(PLACA_BLOQUEADA)
.cupo(CUPO_MOTO)
.diasPermitidos(DIAS_PERMITIDOS)
.build();
/**
* Metodo static final el cual retorna lista de tipos de vehiculo
*/
public static final Collection<TipoVehiculo> getTipoVehiculoLista() {
Collection<TipoVehiculo> tipoVehiculoLista = new ArrayList<>();
TipoVehiculo tipoVehiculo = TipoVehiculo.builder()
.id(ID)
.codigo(CODIGO_MOTO)
.cupo(CUPO_MOTO)
.diasPermitidos(DIAS_PERMITIDOS)
.placaBloqueada(PLACA_BLOQUEADA)
.vehiculo(VEHICULO)
.build();
tipoVehiculoLista.add(tipoVehiculo);
return tipoVehiculoLista;
}
}
|
package io.github.gronnmann.utils.pagedinventory.coinflipper;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.ListIterator;
import org.bukkit.Bukkit;
import org.bukkit.ChatColor;
import org.bukkit.Location;
import org.bukkit.Material;
import org.bukkit.entity.HumanEntity;
import org.bukkit.event.inventory.InventoryType;
import org.bukkit.inventory.Inventory;
import org.bukkit.inventory.InventoryHolder;
import org.bukkit.inventory.ItemStack;
import io.github.gronnmann.utils.coinflipper.Debug;
import io.github.gronnmann.utils.coinflipper.ItemUtils;
import io.github.gronnmann.utils.coinflipper.ReflectionUtils;
public class PagedInventory implements Inventory{
protected static ArrayList<PagedInventory> pagedInventories = new ArrayList<PagedInventory>();
public static PagedInventory getByInventory(Inventory inv){
for (PagedInventory pInv : pagedInventories){
if (pInv.containsInventory(inv)){
return pInv;
}
}
return null;
}
private HashMap<Integer, Inventory> invs = new HashMap<Integer, Inventory>();
private Inventory copyFrom;
private String id;
protected Inventory redirectToBack;
private boolean unloadOnClose;
public static int NEXT = 50, PREV = 48, CURRENT = 49, BACK = 45;
public static int usableSlots = 45;
public PagedInventory(String name, ItemStack next, ItemStack last, ItemStack back, String id, Inventory redirectToBack, boolean unloadOnClose){
this.id = id;
this.redirectToBack = redirectToBack;
this.unloadOnClose = unloadOnClose;
pagedInventories.add(this);
copyFrom = Bukkit.createInventory(new PagedInventoryHolder(), 54, name);
copyFrom.setItem(NEXT, next);
copyFrom.setItem(PREV, last);
copyFrom.setItem(CURRENT, ItemUtils.createItem(Material.THIN_GLASS, "0"));
if (redirectToBack != null) {
copyFrom.setItem(BACK, back);
}
addPage();
}
public String getId(){
return id;
}
public int sizePages(){
return invs.size();
}
public boolean unloadOnClose() {
return unloadOnClose;
}
public int addPage(){
int count = sizePages();
Inventory nextPage = Bukkit.createInventory(copyFrom.getHolder(), copyFrom.getSize(), ReflectionUtils.getInventoryName(copyFrom));
nextPage.setContents(copyFrom.getContents());
int preview = count;
if (preview > 64){
preview = 64;
}
if (preview < 0){
preview = 1;
}
ItemStack current = new ItemStack(Material.THIN_GLASS, preview);
ItemUtils.setName(current, ChatColor.YELLOW.toString() + count);
nextPage.setItem(CURRENT, current);
invs.put(count, nextPage);
return count;
}
public ArrayList<Inventory> getPages(){
ArrayList<Inventory> pages = new ArrayList<Inventory>();
for (Inventory inv : invs.values()){
pages.add(inv);
}
return pages;
}
public Inventory getPage(int num){
return invs.get(num);
}
public int getNumber(Inventory inv){
for (int num : invs.keySet()){
if (invs.get(num).equals(inv)){
return num;
}
}
return -1;
}
public boolean containsInventory(Inventory inv){
for (Inventory toCompare : invs.values()){
if (toCompare.equals(inv))return true;
}
return false;
}
public void setReturnInventory(Inventory inv) {
this.redirectToBack = inv;
}
public static PagedInventory fromClone(PagedInventory inv, String name) {
PagedInventory clone = new PagedInventory(name, inv.getPage(0).getItem(NEXT), inv.getPage(0).getItem(PREV),
inv.getPage(0).getItem(BACK), inv.getId(), inv.redirectToBack, inv.unloadOnClose());
Debug.print(clone.toString());
clone.setContents(inv.getContents());
Debug.print(clone.getPages().toString());
return clone;
}
public HashMap<Integer, ItemStack> addItem(ItemStack... arg0) throws IllegalArgumentException {
for (int invNumbers : invs.keySet()){
Inventory inv = invs.get(invNumbers);
for (int i = 0; i < usableSlots; i++){
ItemStack item = inv.getItem(i);
if (item == null || item.getType().equals(Material.AIR)){
inv.addItem(arg0);
return null;
}
}
}
int newP = addPage();
invs.get(newP).addItem(arg0);
return null;
}
public HashMap<Integer, ? extends ItemStack> all(int arg0) {
// TODO Auto-generated method stub
return null;
}
public HashMap<Integer, ? extends ItemStack> all(Material arg0) throws IllegalArgumentException {
// TODO Auto-generated method stub
return null;
}
public HashMap<Integer, ? extends ItemStack> all(ItemStack arg0) {
// TODO Auto-generated method stub
return null;
}
public void clear() {
// TODO Auto-generated method stub
}
public void clear(int arg0) {
// TODO Auto-generated method stub
}
public boolean contains(int arg0) {
// TODO Auto-generated method stub
return false;
}
public boolean contains(Material arg0) throws IllegalArgumentException {
// TODO Auto-generated method stub
return false;
}
public boolean contains(ItemStack arg0) {
// TODO Auto-generated method stub
return false;
}
public boolean contains(int arg0, int arg1) {
// TODO Auto-generated method stub
return false;
}
public boolean contains(Material arg0, int arg1) throws IllegalArgumentException {
// TODO Auto-generated method stub
return false;
}
public boolean contains(ItemStack arg0, int arg1) {
// TODO Auto-generated method stub
return false;
}
public boolean containsAtLeast(ItemStack arg0, int arg1) {
// TODO Auto-generated method stub
return false;
}
public int first(int arg0) {
// TODO Auto-generated method stub
return 0;
}
public int first(Material arg0) throws IllegalArgumentException {
// TODO Auto-generated method stub
return 0;
}
public int first(ItemStack arg0) {
// TODO Auto-generated method stub
return 0;
}
public int firstEmpty() {
// TODO Auto-generated method stub
return 0;
}
public ItemStack[] getContents() {
ArrayList<ItemStack> contents = new ArrayList<ItemStack>();
for (int invNumbers : invs.keySet()) {
Inventory inv = invs.get(invNumbers);
for (int i = 0; i < usableSlots; i++) {
ItemStack item = inv.getItem(i);
if (item != null) {
contents.add(item);
}
}
}
return contents.toArray(new ItemStack[0]);
}
public InventoryHolder getHolder() {
// TODO Auto-generated method stub
return null;
}
public ItemStack getItem(int arg0) {
int invToUse = arg0/usableSlots;
int slotToUse = arg0-invToUse*usableSlots;
return invs.get(invToUse).getItem(slotToUse);
}
public Location getLocation() {
// TODO Auto-generated method stub
return null;
}
public int getMaxStackSize() {
// TODO Auto-generated method stub
return 0;
}
public String getName() {
return ReflectionUtils.getInventoryName(copyFrom);
}
public int getSize() {
// TODO Auto-generated method stub
return 0;
}
public ItemStack[] getStorageContents() {
// TODO Auto-generated method stub
return null;
}
public String getTitle() {
return ReflectionUtils.getInventoryName(copyFrom);
}
public InventoryType getType() {
return InventoryType.CHEST;
}
public List<HumanEntity> getViewers() {
// TODO Auto-generated method stub
return null;
}
public ListIterator<ItemStack> iterator() {
// TODO Auto-generated method stub
return null;
}
public ListIterator<ItemStack> iterator(int arg0) {
// TODO Auto-generated method stub
return null;
}
public void remove(int arg0) {
// TODO Auto-generated method stub
}
public void remove(Material arg0) throws IllegalArgumentException {
// TODO Auto-generated method stub
}
public void remove(ItemStack arg0) {
for (Inventory inv : invs.values()){
if (inv.contains(arg0)){
inv.remove(arg0);
}
}
}
public HashMap<Integer, ItemStack> removeItem(ItemStack... arg0) throws IllegalArgumentException {
// TODO Auto-generated method stub
return null;
}
public void setContents(ItemStack[] arg0) throws IllegalArgumentException {
for (Inventory inv : invs.values()){
for (int i = 0; i < usableSlots; i++){
inv.setItem(i, new ItemStack(Material.AIR));
}
}
for (ItemStack i : arg0) {
this.addItem(i);
}
}
public void setItem(int arg0, ItemStack arg1) {
int invToUse = arg0/usableSlots;
int slotToUse = arg0-invToUse*usableSlots;
invs.get(invToUse).setItem(slotToUse, arg1);
}
public void setMaxStackSize(int arg0) {
// TODO Auto-generated method stub
}
public void setStorageContents(ItemStack[] arg0) throws IllegalArgumentException {
// TODO Auto-generated method stub
}
public boolean isEmpty() {
return false;
}
}
class PagedInventoryHolder implements InventoryHolder{
public Inventory getInventory() {
return null;
}
} |
package simplejava.concurrent.lock;
public class ReentrantLock {
private boolean isLocked;
private Thread ownerThread;
private int lockCount;
public synchronized void lock() throws InterruptedException {
while(isLocked && Thread.currentThread() != ownerThread) {
this.wait();
}
isLocked = true;
ownerThread = Thread.currentThread();
lockCount = 1;
}
public synchronized void unlock() {
if(Thread.currentThread() == ownerThread) {
-- lockCount;
if(lockCount == 0) {
ownerThread = null;
isLocked = false;
this.notify();
}
} else {
throw new IllegalStateException("This thread does not own this lock");
}
}
}
|
package govdatahub;
import java.util.*;
import java.sql.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
@Service
public class EntityStatService {
@Autowired
private DatabaseService databaseService;
public EntityStat getEntityStat (Long id) throws Exception {
Connection conn = databaseService.getConnection();
PreparedStatement st = conn.prepareStatement("SELECT * FROM entity_stats WHERE id = ?");
st.setLong(1, id);
ResultSet rs = st.executeQuery();
EntityStat entityStat = null;
if (rs.next()) {
entityStat = new EntityStat(rs.getLong("id"), rs.getLong("entity_id"), rs.getString("name"), rs.getDouble("value"), rs.getString("str_value"), rs.getDate("start_time"), rs.getDate("end_time"), rs.getString("src"), rs.getString("description"));
}
rs.close();
st.close();
conn.close();
return entityStat;
}
public List<EntityStat> listEntityStats () throws Exception {
List<EntityStat> entityStats = new ArrayList<EntityStat>();
Connection conn = databaseService.getConnection();
Statement st = conn.createStatement();
ResultSet rs = st.executeQuery("SELECT * FROM entity_stats");
while (rs.next()) {
entityStats.add(new EntityStat(rs.getLong("id"), rs.getLong("entity_id"), rs.getString("name"), rs.getDouble("value"), rs.getString("str_value"), rs.getDate("start_time"), rs.getDate("end_time"), rs.getString("src"), rs.getString("description")));
}
rs.close();
st.close();
conn.close();
return entityStats;
}
public void createEntityStat (EntityStat entityStat) throws Exception {
Connection conn = databaseService.getConnection();
this.createEntityStat(entityStat, conn);
conn.close();
}
public void createEntityStats (List<EntityStat> entityStats) throws Exception {
Connection conn = databaseService.getConnection();
for (EntityStat entityStat : entityStats) {
this.createEntityStat(entityStat);
}
conn.close();
}
private void createEntityStat (EntityStat entityStat, Connection conn) throws Exception {
PreparedStatement st = conn.prepareStatement("INSERT INTO entity_stats (entity_id, name, value, str_value, start_time, end_time, src, description) VALUES (?, ?, ?, ?, ?, ?, ?, ?)");
st.setLong(1, entityStat.getEntityId());
st.setString(2, entityStat.getName());
st.setDouble(3, entityStat.getValue());
st.setString(4, entityStat.getStrValue());
java.util.Date startTime = entityStat.getStartTime();
if (startTime == null) {
st.setDate(5, null);
} else {
st.setDate(5, new java.sql.Date(startTime.getTime()));
}
java.util.Date endTime = entityStat.getEndTime();
if (endTime == null) {
st.setDate(6, null);
} else {
st.setDate(6, new java.sql.Date(endTime.getTime()));
}
st.setString(7, entityStat.getSrc());
st.setString(8, entityStat.getDescription());
st.executeUpdate();
st.close();
}
}
|
package cl.tesoreria.sae.retenciones.vo;
public class OtrasRetencionesVO {
private String otrasRetenId;
private String folio;
private String observacion;
private String fechaIngre;
private String personaId;
private String rut;
private String dv;
private String nombre;
private String appPat;
private String appMat;
private String retenYear;
private String grupoEgreso;
private String estado;
public String getRut() {
return rut;
}
public String getDv() {
return dv;
}
public String getNombre() {
return nombre;
}
public String getAppPat() {
return appPat;
}
public String getAppMat() {
return appMat;
}
public String getFolio() {
return folio;
}
public String getFechaIngre() {
return fechaIngre;
}
public String getObservacion() {
return observacion;
}
public String getPersonaId() {
return personaId;
}
public String getOtrasRetenId() {
return otrasRetenId;
}
public String getRetenYear() {
return retenYear;
}
public String getGrupoEgreso() {
return grupoEgreso;
}
public String getEstado() {
return estado;
}
public void setRut(String rut) {
this.rut = rut;
}
public void setDv(String dv) {
this.dv = dv;
}
public void setNombre(String nombre) {
this.nombre = nombre;
}
public void setAppPat(String appPat) {
this.appPat = appPat;
}
public void setAppMat(String appMat) {
this.appMat = appMat;
}
public void setFolio(String folio) {
this.folio = folio;
}
public void setFechaIngre(String fechaIngre) {
this.fechaIngre = fechaIngre;
}
public void setObservacion(String observacion) {
this.observacion = observacion;
}
public void setPersonaId(String personaId) {
this.personaId = personaId;
}
public void setOtrasRetenId(String otrasRetenId) {
this.otrasRetenId = otrasRetenId;
}
public void setRetenYear(String retenYear) {
this.retenYear = retenYear;
}
public void setGrupoEgreso(String grupoEgreso) {
this.grupoEgreso = grupoEgreso;
}
public void setEstado(String estado) {
this.estado = estado;
}
}
|
package club.eridani.cursa.module.modules.combat;
import club.eridani.cursa.client.FriendManager;
import club.eridani.cursa.client.GUIManager;
import club.eridani.cursa.common.annotations.Module;
import club.eridani.cursa.event.events.network.PacketEvent;
import club.eridani.cursa.event.events.render.RenderEvent;
import club.eridani.cursa.mixin.mixins.accessor.AccessorCPacketPlayer;
import club.eridani.cursa.module.Category;
import club.eridani.cursa.module.ModuleBase;
import club.eridani.cursa.setting.Setting;
import club.eridani.cursa.utils.*;
import net.minecraft.client.Minecraft;
import net.minecraft.entity.Entity;
import net.minecraft.entity.EntityLivingBase;
import net.minecraft.entity.item.EntityEnderCrystal;
import net.minecraft.entity.player.EntityPlayer;
import net.minecraft.init.Blocks;
import net.minecraft.init.Items;
import net.minecraft.init.SoundEvents;
import net.minecraft.network.play.client.CPacketPlayer;
import net.minecraft.network.play.client.CPacketPlayerTryUseItemOnBlock;
import net.minecraft.network.play.server.SPacketSoundEffect;
import net.minecraft.util.EnumFacing;
import net.minecraft.util.EnumHand;
import net.minecraft.util.NonNullList;
import net.minecraft.util.SoundCategory;
import net.minecraft.util.math.AxisAlignedBB;
import net.minecraft.util.math.BlockPos;
import net.minecraft.util.math.Vec3d;
import java.awt.*;
import java.util.Comparator;
import java.util.List;
import java.util.stream.Collectors;
import static club.eridani.cursa.utils.CrystalUtil.calculateDamage;
import static org.lwjgl.opengl.GL11.GL_QUADS;
@Module(name = "AutoCrystal", category = Category.COMBAT)
public class AutoCrystal extends ModuleBase {
Setting<Boolean> autoSwitch = setting("AutoSwitch", false);
Setting<Boolean> multiPlace = setting("MultiPlace", false);
Setting<Boolean> autoPlace = setting("Place", true);
Setting<Boolean> autoExplode = setting("Explode", true);
Setting<Integer> placeDelay = setting("PlaceDelay", 50, 0, 1000);
Setting<Integer> explodeDelay = setting("ExplodeDelay", 35, 0, 1000);
Setting<Double> placeRange = setting("PlaceRange", 4.5, 0, 8);
Setting<Double> breakRange = setting("PlaceRange", 5.5, 0, 8);
Setting<Double> distance = setting("Distance", 7.0, 0, 16);
Setting<Double> placeMinDmg = setting("PlaceMinDmg", 6.0, 0, 36);
Setting<Double> placeMaxSelf = setting("PlaceMaxSelf", 8.0, 0, 36);
Setting<Double> breakMinDmg = setting("BreakMinDmg", 4.0, 0, 36);
Setting<Double> breakMaxSelf = setting("BreakMaxSelf", 8.0, 0, 36);
Setting<Boolean> facePlace = setting("FacePlace", false);
Setting<Double> blastHealth = setting("BlastHealth", 2.0, 0.0, 8).whenTrue(facePlace);
Setting<Boolean> spoofRotations = setting("SpoofRotation", true);
Setting<Boolean> renderPlace = setting("RenderBlock", true);
Timer placeTimer = new Timer();
Timer breakTimer = new Timer();
int placements = 0;
boolean isSpoofingAngles = false;
boolean togglePitch = false;
BlockPos renderBlock = null;
float yaw, pitch;
@Override
public void onTick() {
if (mc.player == null || mc.world == null) return;
renderBlock = null;
if (autoExplode.getValue() && breakTimer.passed(explodeDelay.getValue())) {
breakTimer.reset();
EntityEnderCrystal explodeTarget = getHittableCrystal();
if (explodeTarget != null) {
explodeCrystal(explodeTarget);
if (!multiPlace.getValue()) return;
if (placements >= 3) {
placements = 0;
return;
}
} else resetRotation();
}
if (autoPlace.getValue()) {
BlockPos placeTarget = getPlaceTargetPos();
renderBlock = placeTarget;
if (placeTimer.passed(placeDelay.getValue())) {
placeTimer.reset();
if (placeTarget != null) {
placeCrystal(placeTarget);
if (isSpoofingAngles && spoofRotations.getValue()) {
if (togglePitch) {
mc.player.rotationPitch += (float) 4.0E-4;
togglePitch = false;
} else {
mc.player.rotationPitch -= (float) 4.0E-4;
togglePitch = true;
}
}
} else resetRotation();
}
}
}
@Override
public void onRenderWorld(RenderEvent event) {
int color = new Color(GUIManager.getRed(), GUIManager.getGreen(), GUIManager.getBlue(), 60).getRGB();
if (renderPlace.getValue() && renderBlock != null) {
CursaTessellator.prepare(GL_QUADS);
CursaTessellator.drawFullBox(renderBlock, 1f, color);
CursaTessellator.release();
}
}
private void setYawAndPitch(float yaw1, float pitch1) {
yaw = yaw1;
pitch = pitch1;
isSpoofingAngles = true;
}
private void resetRotation() {
if (isSpoofingAngles) {
yaw = mc.player.rotationYaw;
pitch = mc.player.rotationPitch;
isSpoofingAngles = false;
}
}
private void lookAtPacket(double px, double py, double pz, EntityPlayer me) {
float[] v = EntityUtil.calculateLookAt(px, py, pz, me);
setYawAndPitch(v[0], v[1]);
}
@Override
public void onEnable() {
placements = 0;
}
@Override
public void onDisable() {
placeTimer.restart();
breakTimer.restart();
resetRotation();
renderBlock = null;
}
@Override
public void onPacketSend(PacketEvent.Send event) {
if (mc.player == null || mc.world == null) return;
if (spoofRotations.getValue()) {
if (event.packet instanceof CPacketPlayer) {
CPacketPlayer packet = (CPacketPlayer) event.getPacket();
if (isSpoofingAngles) {
((AccessorCPacketPlayer) packet).setYaw(yaw);
((AccessorCPacketPlayer) packet).setPitch(pitch);
}
}
}
}
@Override
public void onPacketReceive(PacketEvent.Receive event) {
if (mc.player == null || mc.world == null) return;
if (event.packet instanceof SPacketSoundEffect) {
SPacketSoundEffect packet = (SPacketSoundEffect) event.packet;
if (packet.getCategory() == SoundCategory.BLOCKS && packet.getSound() == SoundEvents.ENTITY_GENERIC_EXPLODE) {
for (Entity e : Minecraft.getMinecraft().world.loadedEntityList) {
if (e instanceof EntityEnderCrystal) {
if (e.getDistance(packet.getX(), packet.getY(), packet.getZ()) <= 6.0f) {
e.setDead();
}
}
}
}
}
}
public EntityEnderCrystal getHittableCrystal() {
return mc.world.loadedEntityList.stream()
.filter(it -> it instanceof EntityEnderCrystal)
.filter(it -> mc.player.getDistance(it) <= breakRange.getValue())
.filter(it -> canHitCrystal(it.getPositionVector()))
.map(e -> (EntityEnderCrystal) e)
.min(Comparator.comparing(e -> mc.player.getDistance(e))).orElse(null);
}
public boolean canHitCrystal(Vec3d crystal) {
float selfDamage = CrystalUtil.calculateDamage(crystal.x, crystal.y, crystal.z, mc.player, mc.player.getPositionVector());
if (selfDamage >= mc.player.getHealth() + mc.player.getAbsorptionAmount()) return false;
List<EntityPlayer> entities = mc.world.playerEntities.stream()
.filter(e -> mc.player.getDistance(e) <= distance.getValue())
.filter(e -> mc.player != e)
.filter(e -> !FriendManager.isFriend(e))
.sorted(Comparator.comparing(e -> mc.player.getDistance(e)))
.collect(Collectors.toList());
for (EntityPlayer player : entities) {
if (player.isDead || (player.getHealth() + player.getAbsorptionAmount()) <= 0.0f) continue;
double minDamage = breakMinDmg.getValue();
if (canFacePlace(player, blastHealth.getValue())) minDamage = 1;
double targetDamage = CrystalUtil.calculateDamage(crystal.x, crystal.y, crystal.z, player, player.getPositionVector());
if (targetDamage > player.getHealth() + player.getAbsorptionAmount()
&& selfDamage < mc.player.getHealth() + mc.player.getAbsorptionAmount()
) return true;
if (selfDamage > breakMaxSelf.getValue()) continue;
if (targetDamage < minDamage) continue;
if (selfDamage > targetDamage) continue;
return true;
}
return false;
}
public boolean canFacePlace(EntityLivingBase target, double blast) {
float healthTarget = target.getHealth() + target.getAbsorptionAmount();
return healthTarget <= blast;
}
public void explodeCrystal(EntityEnderCrystal crystal) {
lookAtPacket(crystal.posX, crystal.posY, crystal.posZ, mc.player);
mc.playerController.attackEntity(mc.player, crystal);
mc.player.swingArm(mc.player.getHeldItemOffhand().getItem() == Items.END_CRYSTAL ? EnumHand.OFF_HAND : EnumHand.MAIN_HAND);
mc.player.resetCooldown();
}
public BlockPos getPlaceTargetPos() {
BlockPos targetPos;
List<BlockPos> blockPoses = findCrystalBlocks();
List<EntityPlayer> players = mc.world.playerEntities.stream()
.filter(e -> mc.player.getDistance(e) <= distance.getValue())
.filter(e -> mc.player != e)
.filter(e -> !FriendManager.isFriend(e))
.sorted(Comparator.comparing(e -> mc.player.getDistance(e)))
.collect(Collectors.toList());
targetPos = calculateTargetPlace(blockPoses, players);
return targetPos;
}
public BlockPos calculateTargetPlace(List<BlockPos> crystalBlocks, List<EntityPlayer> players) {
double maxDamage = 0.5;
BlockPos targetBlock = null;
for (EntityLivingBase it : players) {
if (it != mc.player) {
if (it.getHealth() <= 0.0f) continue;
for (BlockPos blockPos : crystalBlocks) {
if (it.getDistanceSq(blockPos) >= distance.getValue() * distance.getValue()) continue;
if (mc.player.getDistance(blockPos.getX(), blockPos.getY(), blockPos.getZ()) > placeRange.getValue())
continue;
double targetDamage = calculateDamage(blockPos.getX() + 0.5, blockPos.getY() + 1, blockPos.getZ() + 0.5, it);
if (targetDamage < maxDamage) continue;
if (targetDamage < (facePlace.getValue() ? (canFacePlace(it, blastHealth.getValue()) ? 1 : placeMinDmg.getValue()) : placeMinDmg.getValue()))
continue;
float healthTarget = it.getHealth() + it.getAbsorptionAmount();
float healthSelf = mc.player.getHealth() + mc.player.getAbsorptionAmount();
double selfDamage = calculateDamage(blockPos.getX() + 0.5, blockPos.getY() + 1, blockPos.getZ() + 0.5, mc.player);
if (selfDamage > targetDamage && targetDamage < healthTarget) continue;
if (selfDamage - 0.5 > healthSelf) continue;
if (selfDamage > placeMaxSelf.getValue()) continue;
maxDamage = targetDamage;
targetBlock = blockPos;
}
if (targetBlock != null) break;
}
}
return targetBlock;
}
public boolean canPlaceCrystal(BlockPos blockPos) {
BlockPos boost = blockPos.add(0, 1, 0);
BlockPos boost2 = blockPos.add(0, 2, 0);
if (mc.world.getBlockState(blockPos).getBlock() != Blocks.BEDROCK && mc.world.getBlockState(blockPos).getBlock() != Blocks.OBSIDIAN)
return false;
if (mc.world.getBlockState(boost).getBlock() != Blocks.AIR || mc.world.getBlockState(boost2).getBlock() != Blocks.AIR)
return false;
return mc.world.getEntitiesWithinAABB(Entity.class, new AxisAlignedBB(boost)).isEmpty()
&& mc.world.getEntitiesWithinAABB(Entity.class, new AxisAlignedBB(boost2)).isEmpty();
}
private List<BlockPos> findCrystalBlocks() {
double range = distance.getValue();
NonNullList<BlockPos> positions = NonNullList.create();
positions.addAll(BlockInteractionHelper.getSphere(CrystalUtil.getPlayerPos(), (float) range, (int) range, false, true, 0)
.stream()
.filter(this::canPlaceCrystal)
.sorted(Comparator.comparing(it -> mc.player.getDistance(it.getX(), it.getY(), it.getZ())))
.collect(Collectors.toList()));
return positions;
}
public void placeCrystal(BlockPos blockPos) {
boolean isOffhand = mc.player.getHeldItemOffhand().getItem() == Items.END_CRYSTAL;
EnumHand enumHand = isOffhand ? EnumHand.OFF_HAND : EnumHand.MAIN_HAND;
if (autoSwitch.getValue() && !isOffhand && mc.player.getHeldItemMainhand().getItem() != Items.END_CRYSTAL) {
int crystalSlot = -1;
for (int l = 0; l < 9; ++l) {
if (mc.player.inventory.getStackInSlot(l).getItem() == Items.END_CRYSTAL) {
crystalSlot = l;
break;
}
}
if (crystalSlot != -1) mc.player.inventory.currentItem = crystalSlot;
resetRotation();
return;
}
if (isOffhand || mc.player.getHeldItemMainhand().getItem() == Items.END_CRYSTAL) {
lookAtPacket(blockPos.getX() + 0.5, blockPos.getY() - 0.5, blockPos.getZ() + 0.5, mc.player);
mc.player.connection.sendPacket(new CPacketPlayerTryUseItemOnBlock(blockPos, EnumFacing.UP, enumHand, 0, 0, 0));
}
placements++;
}
}
|
package com.tencent.mm.protocal.c;
import com.tencent.mm.bk.a;
import java.util.LinkedList;
public final class bnx extends a {
public int lOS;
public cf rII;
public String rmM;
public LinkedList<bbs> slP = new LinkedList();
public um slQ;
public LinkedList<bfm> slR = new LinkedList();
public int slS;
protected final int a(int i, Object... objArr) {
int fQ;
byte[] bArr;
if (i == 0) {
f.a.a.c.a aVar = (f.a.a.c.a) objArr[0];
aVar.fT(1, this.lOS);
aVar.d(2, 8, this.slP);
if (this.slQ != null) {
aVar.fV(3, this.slQ.boi());
this.slQ.a(aVar);
}
if (this.rII != null) {
aVar.fV(4, this.rII.boi());
this.rII.a(aVar);
}
aVar.d(5, 8, this.slR);
aVar.fT(6, this.slS);
if (this.rmM != null) {
aVar.g(7, this.rmM);
}
return 0;
} else if (i == 1) {
fQ = (f.a.a.a.fQ(1, this.lOS) + 0) + f.a.a.a.c(2, 8, this.slP);
if (this.slQ != null) {
fQ += f.a.a.a.fS(3, this.slQ.boi());
}
if (this.rII != null) {
fQ += f.a.a.a.fS(4, this.rII.boi());
}
fQ = (fQ + f.a.a.a.c(5, 8, this.slR)) + f.a.a.a.fQ(6, this.slS);
if (this.rmM != null) {
return fQ + f.a.a.b.b.a.h(7, this.rmM);
}
return fQ;
} else if (i == 2) {
bArr = (byte[]) objArr[0];
this.slP.clear();
this.slR.clear();
f.a.a.a.a aVar2 = new f.a.a.a.a(bArr, unknownTagHandler);
for (fQ = a.a(aVar2); fQ > 0; fQ = a.a(aVar2)) {
if (!super.a(aVar2, this, fQ)) {
aVar2.cJS();
}
}
return 0;
} else if (i != 3) {
return -1;
} else {
f.a.a.a.a aVar3 = (f.a.a.a.a) objArr[0];
bnx bnx = (bnx) objArr[1];
int intValue = ((Integer) objArr[2]).intValue();
LinkedList IC;
int size;
f.a.a.a.a aVar4;
boolean z;
switch (intValue) {
case 1:
bnx.lOS = aVar3.vHC.rY();
return 0;
case 2:
IC = aVar3.IC(intValue);
size = IC.size();
for (intValue = 0; intValue < size; intValue++) {
bArr = (byte[]) IC.get(intValue);
bbs bbs = new bbs();
aVar4 = new f.a.a.a.a(bArr, unknownTagHandler);
for (z = true; z; z = bbs.a(aVar4, bbs, a.a(aVar4))) {
}
bnx.slP.add(bbs);
}
return 0;
case 3:
IC = aVar3.IC(intValue);
size = IC.size();
for (intValue = 0; intValue < size; intValue++) {
bArr = (byte[]) IC.get(intValue);
um umVar = new um();
aVar4 = new f.a.a.a.a(bArr, unknownTagHandler);
for (z = true; z; z = umVar.a(aVar4, umVar, a.a(aVar4))) {
}
bnx.slQ = umVar;
}
return 0;
case 4:
IC = aVar3.IC(intValue);
size = IC.size();
for (intValue = 0; intValue < size; intValue++) {
bArr = (byte[]) IC.get(intValue);
cf cfVar = new cf();
aVar4 = new f.a.a.a.a(bArr, unknownTagHandler);
for (z = true; z; z = cfVar.a(aVar4, cfVar, a.a(aVar4))) {
}
bnx.rII = cfVar;
}
return 0;
case 5:
IC = aVar3.IC(intValue);
size = IC.size();
for (intValue = 0; intValue < size; intValue++) {
bArr = (byte[]) IC.get(intValue);
bfm bfm = new bfm();
aVar4 = new f.a.a.a.a(bArr, unknownTagHandler);
for (z = true; z; z = bfm.a(aVar4, bfm, a.a(aVar4))) {
}
bnx.slR.add(bfm);
}
return 0;
case 6:
bnx.slS = aVar3.vHC.rY();
return 0;
case 7:
bnx.rmM = aVar3.vHC.readString();
return 0;
default:
return -1;
}
}
}
}
|
package com.qd.mystudy.sbweb;
import com.qd.mystudy.sbweb.mybatis.dao.PersonMapper;
import com.qd.mystudy.sbweb.mybatis.model.PersonExample;
import org.apache.ibatis.session.SqlSessionFactory;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.context.support.AbstractApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
import org.springframework.jdbc.datasource.DataSourceTransactionManager;
import org.springframework.transaction.PlatformTransactionManager;
import org.springframework.transaction.TransactionDefinition;
import org.springframework.transaction.support.DefaultTransactionDefinition;
import java.util.Arrays;
//import org.mybatis.spring.SqlSessionFactoryBean;
/**
* Created by tony on 7/19/15.
*/
public class SpringTest {
public final static Logger logger = LoggerFactory.getLogger(SpringTest.class);
public final static AbstractApplicationContext ctx = new ClassPathXmlApplicationContext("classpath:bean1.xml");;
public static PlatformTransactionManager tm = (DataSourceTransactionManager) ctx.getBean("transactionManager");
public static DefaultTransactionDefinition df = new DefaultTransactionDefinition(DefaultTransactionDefinition.PROPAGATION_REQUIRED);
public static SqlSessionFactory sqlSessionFactory = (SqlSessionFactory) ctx.getBean("sqlSessionFactory");
static {
df.setIsolationLevel(TransactionDefinition.ISOLATION_REPEATABLE_READ);
}
public static void main(String[] args){
String[] beanNames = ctx.getBeanDefinitionNames();
Arrays.sort(beanNames);
for (String beanName : beanNames) {
if(!beanName.contains("org.springframework")) {
logger.info("all beans:" + beanName + "," + ctx.getBean(beanName));
}
}
PersonMapper personMapper = (PersonMapper) ctx.getBean("personMapper");
PersonExample personExample = new PersonExample();
personExample.createCriteria().andAGEEqualTo(22);
logger.info("selectByExample:{}", personMapper.selectByExample(personExample));
ctx.destroy();
}
}
|
package ua.nure.timoshenko.summaryTask4.web.command.admin;
import org.apache.log4j.Logger;
import ua.nure.timoshenko.summaryTask4.Path;
import ua.nure.timoshenko.summaryTask4.db.DBManager;
import ua.nure.timoshenko.summaryTask4.db.bean.UserBean;
import ua.nure.timoshenko.summaryTask4.web.command.Command;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.util.Comparator;
import java.util.List;
/**
* List users command.
*
* @author L.Timoshenko
*
*/
public class ListUsersCommand extends Command {
private static final long serialVersionUID = 1094133346815712353L;
private static final Logger LOG = Logger.getLogger(ListUsersCommand.class);
@Override
public String execute(HttpServletRequest request, HttpServletResponse response) {
LOG.debug("Command starts");
HttpSession session = request.getSession();
List<UserBean> userBeans = DBManager.getInstance().getAllUserBeans();
LOG.trace("Found in DB: userBeans --> " + userBeans);
userBeans.sort(Comparator.comparingInt(UserBean::getUserId));
session.setAttribute("userBeans", userBeans);
LOG.trace("Set the request attribute: userBeans --> " + userBeans);
LOG.debug("Command finished");
return Path.PAGE_LIST_USERS;
}
}
|
/**
* 9. Palindrome Number
* very easy ←_←
*/
class Solution {
public boolean isPalindrome(int x) {
if (x < 0)
return false;
int r = 0, t = x;
while (t > 0) {
r = r * 10 + t % 10;
t /= 10;
}
return r == x;
}
public static void main(String[] args) {
Solution s = new Solution();
int[] nums = {121, 1231, 0, -121, 100};
for (int i = 0; i < nums.length; i++) {
System.out.println(s.isPalindrome(nums[i]));
}
}
} |
package dv606.rw222ci.rssreader;
import android.os.Bundle;
import android.preference.PreferenceFragment;
/**
* Preference fragment.
*
* @author Robin Wassbjer (rw222ci)
* @since 2015-10-30
*/
public class RssReaderPreferenceFragment extends PreferenceFragment {
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
addPreferencesFromResource(R.xml.rssreader_preferences);
}
}
|
package ventanapruebatiempo;
import java.text.DecimalFormat;
/*
* 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.
*/
/**
*
* @author Julia Ramos Lopez
*/
public class Tiempo {
private int hora;
private int minuto;
private int segundo;
private static DecimalFormat dosDigitos =new DecimalFormat("00");
public Tiempo(){
this(0,0,0);
}
public Tiempo (int h){
this(h,0,0);
}
public Tiempo (int h, int m){
this(h,m,0);
}
public Tiempo (int h, int m, int s){
establecerTiempo(h,m,s);
}
public Tiempo (Tiempo tiempo){
this(tiempo.obtenerHora(), tiempo.obtenerMinuto(), tiempo.obtenerSegundo());
}
private void establecerTiempo(int h, int m, int s) {
establecerHora(h);
establecerMinuto(m);
establecerSegundo(s);
}
private void establecerHora(int h) {
hora=((h>=0&&h<24)?h:0);
}
private void establecerMinuto(int m) {
minuto=((m>=0&&m<60)?m:0);
}
private void establecerSegundo(int s) {
segundo=((s>=0&&s<60)?s:0);
}
public int obtenerHora(){
return hora;
}
public int obtenerMinuto(){
return minuto;
}
public int obtenerSegundo(){
return segundo;
}
public String aStringUniversal(){
return dosDigitos.format(obtenerHora())+":"
+dosDigitos.format(obtenerMinuto())+ ":"
+dosDigitos.format(obtenerSegundo());
}
public String toString(){
return((obtenerHora()==12||obtenerHora()==0)?
12: obtenerHora()%12)+":"+
dosDigitos.format(obtenerMinuto())
+":"+dosDigitos.format(obtenerSegundo())
+(obtenerHora()<12?"AM":"PM");
}
}
|
/*
* [y] hybris Platform
*
* Copyright (c) 2018 SAP SE or an SAP affiliate company. All rights reserved.
*
* This software is the confidential and proprietary information of SAP
* ("Confidential Information"). You shall not disclose such Confidential
* Information and shall use it only in accordance with the terms of the
* license agreement you entered into with SAP.
*/
package de.hybris.platform.acceleratorfacades.cart.action;
import de.hybris.platform.acceleratorfacades.cart.action.exceptions.CartEntryActionException;
import java.util.List;
import java.util.Optional;
/**
* Facade interface for executing accelerator cart entry actions.
*/
public interface CartEntryActionFacade
{
/**
* This method will trigger {@link CartEntryActionHandler#handleAction(List)} on the {@link CartEntryActionHandler}
* configured for the given {@Link CartEntryAction}.
*
* @param action
* the action you want to execute.
* @param entryNumbers
* the cart entry numbers for which the action is executed.
* @return An empty optional to signal the controller to apply the default behaviour: redisplay the cart page with a
* success message. Otherwise return a custom redirect URL to navigate elsewhere upon the action completion.
* The expected url format is the format used as SpringMVC controller method return values.
* @throws CartEntryActionException
* when an error occurs during the action execution.
*/
Optional<String> executeAction(CartEntryAction action, List<Long> entryNumbers) throws CartEntryActionException;
/**
* Provides the key to the message that should be displayed when an action runs with success.
*
* @param action
* the action you want the message key for
* @return the success message key.
*/
Optional<String> getSuccessMessageKey(CartEntryAction action);
/**
* Provides the key to the message that should be displayed when a CartEntryActionException is thrown.
*
* @param action
* the action you want the message key for.
* @return the error message key.
*/
Optional<String> getErrorMessageKey(CartEntryAction action);
}
|
package samples;
import java.util.ArrayList;
public class Parking {
int type;
String slotnum;
int time;
public Parking(int type, String slotnum, int time) {
this.type = type;
this.slotnum = slotnum;
this.time = time;
}
public static void addVehicle(ArrayList<Parking> p, Parking obj){
if(p.size()<3){
p.add(obj);
System.out.println("After Adding");
display(p);
}
else {
System.out.println("All slots are occupied!");
}
}
public static void display(ArrayList<Parking> p){
System.out.println("---------------------------");
for (Parking obj:p) {
System.out.print(obj.slotnum+" | ");
}
System.out.println("\n---------------------------");
}
public static void remove(ArrayList<Parking> p,String num){
for (Parking a:p) {
if(a.slotnum.equals(num)){
System.out.println("Amount= "+a.time*10 +"Rs.");
p.remove(a) ;
break;
}
}
}
}
|
package com.tencent.mm.modelmulti;
import com.tencent.mm.plugin.report.f;
import com.tencent.mm.sdk.platformtools.al.a;
class k$2 implements a {
final /* synthetic */ k dZT;
final /* synthetic */ k$a dZU;
k$2(k kVar, k$a k_a) {
this.dZT = kVar;
this.dZU = k_a;
}
public final boolean vD() {
k.a(this.dZT);
f.mDy.a(99, 231, 1, false);
this.dZT.a(-1, 0, 0, "", this.dZU, null);
return false;
}
}
|
package com.fleet.mybatis.pagehelper.dao;
import com.fleet.mybatis.pagehelper.entity.User;
import org.apache.ibatis.annotations.Mapper;
import java.util.List;
import java.util.Map;
@Mapper
public interface UserDao {
Integer insert(User user);
Integer delete(User user);
Integer update(User user);
User get(User user);
List<User> list(Map<String, Object> map);
}
|
/*
* 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.
*/
import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.List;
import javax.persistence.*;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
/**
*
* @author Greg
*/
@WebServlet(urlPatterns = {"/PullFriends"})
public class PullFriends extends HttpServlet {
/**
* Processes requests for both HTTP <code>GET</code> and <code>POST</code>
* methods.
*
* @param request servlet request
* @param response servlet response
* @throws ServletException if a servlet-specific error occurs
* @throws IOException if an I/O error occurs
*/
protected void processRequest(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
// pull and assign existing session
HttpSession session = request.getSession();
// assign and cast session user object
User sessionUser = (User)session.getAttribute("user");
// Create Factory
EntityManagerFactory emf = Persistence.createEntityManagerFactory("lolfriendsPersistenceUnit");
EntityManager em = emf.createEntityManager();
// create query to pull ONLY the session user's friends
Query query = em.createQuery("SELECT u FROM User u WHERE u.user_name = :username").setParameter("username", sessionUser.getUser_name());
// cast result to User Type
sessionUser = (User) query.getSingleResult();
// create League API
LeagueAPI api = new LeagueAPI();
// for each friend, pull his data from the API
for(Friend friend : sessionUser.getFriends())
{
// returns games of summoner from API
String reply = api.getGames(Integer.toString(friend.getSummoner().getId()));
// Add games to summoner class
friend.getSummoner().addGames(reply);
}
System.out.println("Should have pulled friends");
// put user back on session
request.setAttribute("user", sessionUser);
// forward to Welcome
request.getRequestDispatcher("Welcome.jsp").forward(request, response);
em.close();
}
// <editor-fold defaultstate="collapsed" desc="HttpServlet methods. Click on the + sign on the left to edit the code.">
/**
* Handles the HTTP <code>GET</code> method.
*
* @param request servlet request
* @param response servlet response
* @throws ServletException if a servlet-specific error occurs
* @throws IOException if an I/O error occurs
*/
@Override
protected void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
processRequest(request, response);
}
/**
* Handles the HTTP <code>POST</code> method.
*
* @param request servlet request
* @param response servlet response
* @throws ServletException if a servlet-specific error occurs
* @throws IOException if an I/O error occurs
*/
@Override
protected void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
processRequest(request, response);
}
/**
* Returns a short description of the servlet.
*
* @return a String containing servlet description
*/
@Override
public String getServletInfo() {
return "Short description";
}// </editor-fold>
}
|
package com.pkjiao.friends.mm.activity;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import com.pkjiao.friends.mm.R;
import com.pkjiao.friends.mm.broadcast.receive.AuthCodeBroadcastReceiver;
import com.pkjiao.friends.mm.common.CommonDataStructure;
import com.pkjiao.friends.mm.utils.AuthCodeUtils;
import com.pkjiao.friends.mm.utils.MD5SecretUtils;
import com.pkjiao.friends.mm.utils.Utils;
import android.app.Activity;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.SharedPreferences;
import android.content.SharedPreferences.Editor;
import android.os.Bundle;
import android.os.CountDownTimer;
import android.os.Handler;
import android.os.Message;
import android.view.View;
import android.view.Window;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;
public class ChangePasswordActivity extends Activity implements OnClickListener {
private static final String TAG = "ChangePasswordActivity";
private static final int POOL_SIZE = 10;
private static final int CHANGE_PASSWORD_SUCCESS = 100;
private static final int NETWORK_INVALID = 101;
private static final int START_TO_SEND_AUTH_CODE = 102;
private static final int START_TO_CHANGE_PASSWORD = 103;
private EditText mPhoneNumEditText;
private EditText mPasswordEditText;
private EditText mVerifyCodeEditText;
private Button mGetVerifyCodeBtn;
private Button mConfrimBtn;
private RelativeLayout mReturnBtn;
private TextView mChangePasswordTitle;
private String mUid;
private String mPhoneNum;
private String mPassword;
private CountTimer mCountTimer;
private ExecutorService mExecutorService;
private AuthCodeBroadcastReceiver mBroadcastReceiver;
private SharedPreferences mPrefs;
private Handler mHandler = new Handler() {
@Override
public void handleMessage(Message msg) {
switch (msg.what) {
case CHANGE_PASSWORD_SUCCESS: {
ChangePasswordActivity.this.finish();
break;
}
case NETWORK_INVALID: {
Toast.makeText(ChangePasswordActivity.this,
R.string.network_not_available, Toast.LENGTH_SHORT)
.show();
break;
}
case START_TO_SEND_AUTH_CODE: {
String macAddr = Utils
.getMacAddress(ChangePasswordActivity.this);
String authCode = AuthCodeUtils.randAuthCode(6);
Editor editor = mPrefs.edit();
editor.putString(CommonDataStructure.AUTH_CODE, authCode);
editor.commit();
mPhoneNum = mPhoneNumEditText.getText().toString();
mExecutorService.execute(new SendAuthCode(mPhoneNum, macAddr,
authCode));
break;
}
case START_TO_CHANGE_PASSWORD: {
mPassword = MD5SecretUtils.encrypt(mPasswordEditText.getText()
.toString());
String macAddr = Utils.getMacAddress(ChangePasswordActivity.this);
mPhoneNum = mPhoneNumEditText.getText().toString();
mExecutorService.execute(new ChangePassword(mPhoneNum, mPassword,
macAddr));
break;
}
default:
break;
}
}
};
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
requestWindowFeature(Window.FEATURE_NO_TITLE);
setContentView(R.layout.change_password_layout);
Intent intent = getIntent();
String actionBarTitle = intent.getStringExtra(CommonDataStructure.PASSWORD);
mReturnBtn = (RelativeLayout) findViewById(R.id.change_password_return);
mChangePasswordTitle = (TextView) findViewById(R.id.change_password_title);
mPhoneNumEditText = (EditText) findViewById(R.id.change_password_phone_num);
mPasswordEditText = (EditText) findViewById(R.id.change_password_new_password);
mVerifyCodeEditText = (EditText) findViewById(R.id.change_password_input_verify_code);
mGetVerifyCodeBtn = (Button) findViewById(R.id.change_password_get_verify_code);
mConfrimBtn = (Button) findViewById(R.id.change_password_btn);
mReturnBtn.setOnClickListener(this);
mGetVerifyCodeBtn.setOnClickListener(this);
mConfrimBtn.setOnClickListener(this);
mChangePasswordTitle.setText(actionBarTitle);
mCountTimer = new CountTimer(60000, 1000);
mExecutorService = Executors.newFixedThreadPool(Runtime.getRuntime()
.availableProcessors() * POOL_SIZE);
mPrefs = getSharedPreferences(
CommonDataStructure.PREFS_LAIQIAN_DEFAULT, MODE_PRIVATE);
mBroadcastReceiver = new AuthCodeBroadcastReceiver();
mBroadcastReceiver.setOnReceivedMessageListener(mBroadcastListener);
registerReceiver(mBroadcastReceiver, getIntentFilter());
}
@Override
public void onClick(View arg0) {
switch (arg0.getId()) {
case R.id.change_password_btn: {
if (!Utils.isActiveNetWorkAvailable(this)) {
mHandler.sendEmptyMessage(NETWORK_INVALID);
return;
}
if (!isPhoneNumValid()) {
mPhoneNumEditText.requestFocus();
return;
}
if (!isPasswordValid()) {
mPasswordEditText.requestFocus();
return;
}
if (!isAuthCodeValid()) {
return;
}
mHandler.sendEmptyMessage(START_TO_CHANGE_PASSWORD);
break;
}
case R.id.change_password_return: {
this.finish();
break;
}
case R.id.change_password_get_verify_code: {
if (!Utils.isActiveNetWorkAvailable(this)) {
mHandler.sendEmptyMessage(NETWORK_INVALID);
return;
}
if (!isPhoneNumValid()) {
mPhoneNumEditText.requestFocus();
break;
}
// if (!isPasswordValid()) {
// mPasswordEditText.requestFocus();
// break;
// }
mCountTimer.start();
mHandler.sendEmptyMessage(START_TO_SEND_AUTH_CODE);
break;
}
default:
break;
}
}
private boolean isPhoneNumValid() {
if (!Utils.isMobilePhoneNum(mPhoneNumEditText.getText().toString())) {
Toast.makeText(this, "不是有效手机号码", 500).show();
return false;
}
return true;
}
private boolean isPasswordValid() {
if (!Utils.isPassworkValid(mPasswordEditText.getText().toString())) {
Toast.makeText(this, "密码长度必须大于6位", 500).show();
return false;
}
return true;
}
private boolean isAuthCodeValid() {
String authCode = mPrefs.getString(CommonDataStructure.AUTH_CODE, "");
String confirmCode = mVerifyCodeEditText.getText().toString();
if (authCode == null || authCode.length() == 0 || confirmCode == null
|| confirmCode.length() == 0) {
Toast.makeText(this, "验证码不能为空", 500).show();
return false;
}
if (!confirmCode.equalsIgnoreCase(authCode)) {
Toast.makeText(this, "验证码已经失效", 500).show();
return false;
}
return true;
}
class CountTimer extends CountDownTimer {
public CountTimer(long millisInFuture, long countDownInterval) {
super(millisInFuture, countDownInterval);
}
@Override
public void onFinish() {
mGetVerifyCodeBtn.setText("重获验证码");
mGetVerifyCodeBtn.setClickable(true);
}
@Override
public void onTick(long millisUntilFinished) {
mGetVerifyCodeBtn.setClickable(false);
mGetVerifyCodeBtn.setText("重获验证码 (" + millisUntilFinished / 1000
+ "s" + ")");
}
}
class ChangePassword implements Runnable {
private String phoneNum;
private String password;
private String macAddr;
public ChangePassword(String phoneNum, String password, String macAddr) {
this.phoneNum = phoneNum;
this.password = password;
this.macAddr = macAddr;
}
@Override
public void run() {
boolean result = Utils.changePassword(
CommonDataStructure.URL_CHANGE_PASSWORD, phoneNum, password,
macAddr);
if (result) {
mHandler.sendEmptyMessage(CHANGE_PASSWORD_SUCCESS);
}
}
}
@Override
protected void onDestroy() {
super.onDestroy();
unregisterReceiver(mBroadcastReceiver);
}
class SendAuthCode implements Runnable {
private String phoneNum;
private String authCode;
private String macAddr;
public SendAuthCode(String phoneNum, String macAddr, String authCode) {
this.phoneNum = phoneNum;
this.macAddr = macAddr;
this.authCode = authCode;
}
@Override
public void run() {
Boolean result = Utils.sendAuthCode(
CommonDataStructure.URL_SEND_AUTHCODE, phoneNum, macAddr,
authCode);
// if (result) {
// }
}
}
private AuthCodeBroadcastReceiver.MessageListener mBroadcastListener = new AuthCodeBroadcastReceiver.MessageListener() {
@Override
public void onMsgReceived(String message) {
mVerifyCodeEditText.setText(message);
mCountTimer.cancel();
}
};
private IntentFilter getIntentFilter() {
IntentFilter intentFilter = new IntentFilter();
intentFilter.addAction(AuthCodeBroadcastReceiver.SMS_RECEIVED_ACTION);
return intentFilter;
}
}
|
package app.integro.sjbhs.adapters;
import android.content.Context;
import android.content.Intent;
import android.net.Uri;
import androidx.recyclerview.widget.RecyclerView;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.TextView;
import com.bumptech.glide.Glide;
import java.util.ArrayList;
import app.integro.sjbhs.R;
import app.integro.sjbhs.models.Sjbhs_videos1;
public class VideosAdapter1 extends RecyclerView.Adapter<VideosAdapter1.MyViewHolder> {
private final Context context;
private final ArrayList<Sjbhs_videos1> videos1ArrayList;
public VideosAdapter1(Context context, ArrayList<Sjbhs_videos1> videos1ArrayList) {
this.context = context;
this.videos1ArrayList = videos1ArrayList;
}
@Override
public MyViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
View view = LayoutInflater.from(context).inflate(R.layout.card_video, parent, false);
return new MyViewHolder(view);
}
@Override
public void onBindViewHolder(MyViewHolder holder, int position) {
final Sjbhs_videos1 sjbhs_videos1Item = videos1ArrayList.get(position);
holder.name.setText(sjbhs_videos1Item.getTitle());
String image_url="http://img.youtube.com/vi/"+sjbhs_videos1Item.getV_id()+"/0.jpg";
Glide.with(context)
.load(image_url)
.into(holder.ivImage);
holder.ivImage.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
Intent intent=new Intent(Intent.ACTION_VIEW);
intent.setData(Uri.parse("http://www.youtube.com/watch?v=" + sjbhs_videos1Item.getV_id()));
intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
context.startActivity(intent);
Log.i("Video", "Video Playing...." + sjbhs_videos1Item.getV_id());
}
});
}
@Override
public int getItemCount() {
return videos1ArrayList.size();
}
public class MyViewHolder extends RecyclerView.ViewHolder {
private final TextView name;
private final ImageView ivImage;
public MyViewHolder(View itemView) {
super(itemView);
name = (TextView) itemView.findViewById(R.id.tvTitle);
ivImage = (ImageView) itemView.findViewById(R.id.ivImage);
}
}
} |
/*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
package org.apache.webbeans.test.unittests.config;
import java.util.ArrayList;
import java.util.List;
import java.util.Set;
import org.junit.Assert;
import org.apache.webbeans.lifecycle.test.OpenWebBeansTestMetaDataDiscoveryService;
import org.apache.webbeans.test.AbstractUnitTest;
import org.junit.Test;
public class WebBeansScannerTest extends AbstractUnitTest
{
public WebBeansScannerTest()
{
}
@Test
public void testWebBeansScanner() throws Exception
{
List<Class<?>> classes = new ArrayList<Class<?>>();
classes.add(ScannerTestBean.class);
//Start test container
startContainer(classes);
OpenWebBeansTestMetaDataDiscoveryService scanner = (OpenWebBeansTestMetaDataDiscoveryService) getWebBeansContext().getScannerService();
scanner.deployClasses(classes);
scanner.scan();
Set<Class<?>> classMap = scanner.getBeanClasses();
Assert.assertNotNull(classMap);
Assert.assertFalse(classMap.isEmpty());
//Stop test container
shutDownContainer();
}
}
|
package il.ac.afeka.cloud.enums;
public enum SortByEnumaration {
postingTimestamp,
user,
product,
language
}
|
package org.vaadin.alump.distributionbar.gwt.client.shared;
import java.io.Serializable;
import java.util.ArrayList;
import java.util.List;
import com.vaadin.shared.AbstractComponentState;
@SuppressWarnings("serial")
public class DistributionBarState extends AbstractComponentState {
public boolean sendClicks = false;
private List<Part> parts = new ArrayList<Part>();
public boolean zeroVisible = true;
public double minWidth = 30.0;
/**
* Internal storage class for part details
*/
public static class Part implements Serializable {
private double size;
private String caption;
private String title;
private String tooltip;
private String styleName;
public Part() {
title = new String();
tooltip = new String();
}
public Part(int size) {
setSize(size);
title = new String();
}
public void setSize(double size) {
this.size = size;
}
public double getSize() {
return size;
}
public void setCaption(String caption) {
this.caption = caption;
}
public String getCaption() {
return caption;
}
public void setTitle(String title) {
this.title = title;
}
public String getTitle() {
return title;
}
public void setTooltip(String tooltip) {
this.tooltip = tooltip;
}
public String getTooltip() {
return tooltip;
}
public String getStyleName() {
return styleName;
}
public void setStyleName(String styleName) {
this.styleName = styleName;
}
}
public List<Part> getParts() {
return parts;
}
public void setParts(List<Part> parts) {
this.parts = parts;
}
}
|
package p4_group_8_repo.Start_model;
import javafx.event.ActionEvent;
import javafx.event.EventHandler;
import javafx.scene.control.Alert;
import javafx.scene.control.Button;
import javafx.scene.control.Alert.AlertType;
import javafx.scene.effect.DropShadow;
import javafx.scene.image.Image;
import javafx.scene.image.ImageView;
import javafx.scene.input.MouseEvent;
/**
* Class of Instruction Button
* @author Jun Yuan
*
*/
public class WASD_butt{
private String image_link = "/graphic_animation/WASD_button.png";
private Button button;
Alert alert = new Alert(AlertType.INFORMATION);
/**
* Construct an instance of instruction button
*/
public WASD_butt() {
button = new Button();
alert_design();
design_button();
EventHandler<ActionEvent> event = new EventHandler<ActionEvent>() {
@Override
public void handle(ActionEvent e) {
System.out.println("\nWASD instruction button is pressed\n");
alert.show();
}
};
button.setOnAction(event);
}
/**
* Design for alert message
*/
public void alert_design() {
alert.setTitle("Instructions");
alert.setHeaderText("WASD keys to control Frogger character");
alert.setContentText("W - to move up\n"
+"S - to move down\n"
+"A - to move left\n"
+"D - to move down");
}
/**
* Design and settings of button
*/
public void design_button() {
Image image = new Image(image_link, 155, 155, true, true);
ImageView start_image = new ImageView(image);
button.setStyle("-fx-background-color: transparent;");
button.setGraphic(start_image);
button.setTranslateY(266);
button.setTranslateX(45);
//Button Shadow Effect
DropShadow shadow = new DropShadow();
//Adding the shadow when the mouse cursor is on
button.addEventHandler(MouseEvent.MOUSE_ENTERED,
new EventHandler<MouseEvent>() {
@Override public void handle(MouseEvent e) {
button.setEffect(shadow);
}
});
//Removing the shadow when the mouse cursor is off
button.addEventHandler(MouseEvent.MOUSE_EXITED,
new EventHandler<MouseEvent>() {
@Override public void handle(MouseEvent e) {
button.setEffect(null);
}
});
}
/**
* Method to get Button
* @return button (Display instruction button)
*/
public Button getButton() {
return button;
}
}
|
package com.dishcuss.foodie.hub.Models;
import io.realm.RealmObject;
/**
* Created by Naeem Ibrahim on 7/29/2016.
*/
public class User extends RealmObject{
int id;
String name;
String username;
String email;
String avatar;
String gender;
String dob;
String location;
String provider;
String token;
String referral_code;
public User() {
}
public String getLocation() {
return location;
}
public void setLocation(String location) {
this.location = location;
}
public String getDob() {
return dob;
}
public void setDob(String dob) {
this.dob = dob;
}
public String getAvatar() {
return avatar;
}
public void setAvatar(String avatar) {
this.avatar = avatar;
}
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getUsername() {
return username;
}
public void setUsername(String username) {
this.username = username;
}
public String getEmail() {
return email;
}
public void setEmail(String email) {
this.email = email;
}
public String getGender() {
return gender;
}
public void setGender(String gender) {
this.gender = gender;
}
public String getProvider() {
return provider;
}
public void setProvider(String provider) {
this.provider = provider;
}
public String getToken() {
return token;
}
public void setToken(String token) {
this.token = token;
}
public String getReferral_code() {
return referral_code;
}
public void setReferral_code(String referral_code) {
this.referral_code = referral_code;
}
}
|
/*
* Minesweeper Project
* by Group3 : Arnaud BABOL, Guillaume SIMMONEAU
*/
package Model.Scores;
import java.io.Serializable;
import java.util.Calendar;
/**
*
* @author nono
*/
public class Score implements Comparable, Serializable {
private String pseudo;
private int time;
private Calendar date;
/**
*
* @param pseudo
* @param time
* @param date
*/
public Score(String pseudo, int time, Calendar date) {
this.pseudo = pseudo;
this.time = time;
this.date = date;
}
/**
*
* @return
*/
public String getPseudo() {
return pseudo;
}
/**
*
* @return
*/
public int getTime() {
return time;
}
/**
*
* @return
*/
public Calendar getDate() {
return date;
}
/**
*
* @param o
* @return
*/
@Override
public int compareTo(Object o) {
int time1 = ((Score) o).getTime();
int time2 = this.getTime();
if (time1 > time2) {
return -1;
}
else if(time1 == time2) {
return 0;
}
else {
return 1;
}
}
}
|
package sy.task;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.net.URL;
import java.net.URLConnection;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.test.context.ContextConfiguration;
import sy.service.CompanyService;
import sy.model.Company;
import com.mysql.jdbc.Connection;
import com.mysql.jdbc.PreparedStatement;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;
@ContextConfiguration({ "classpath:spring-mybatis.xml", "classpath:spring.xml" })
public class GetDetailRunnable implements Runnable {
private CompanyService companyService;
@Autowired
public void setCompanyService(CompanyService companyService) {
this.companyService = companyService;
}
public CompanyService getCompanyService() {
return companyService;
}
String html_code = "<td colspan=\"3\" data-header=\"统一社会信用代码\">";
String html_boss = "<td data-header=\"企业法定代表人\">";
String html_place = "<td data-header=\"企业登记注册类型\">";
private String url;
public String getUrl() {
return url;
}
public void setUrl(String url) {
this.url = url;
}
@Override
public void run() {
// TODO Auto-generated method stub
PrintWriter pout = null;
BufferedReader pin = null;
try {
URL realUrl = new URL(url);
// 打开和URL之间的连接
URLConnection conn = realUrl.openConnection();
// 设置通用的请求属性
conn.setRequestProperty("accept", "*/*");
conn.setRequestProperty("connection", "Keep-Alive");
conn.setRequestProperty("user-agent",
"Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1;SV1)");
// 发送POST请求必须设置如下两行
conn.setDoOutput(true);
conn.setDoInput(true);
// 获取URLConnection对象对应的输出流
pout = new PrintWriter(conn.getOutputStream());
// flush输出流的缓冲
pout.flush();
// 定义BufferedReader输入流来读取URL的响应
pin = new BufferedReader(
new InputStreamReader(conn.getInputStream(),"utf-8"));
String line;
boolean print = false;
StringBuilder sb = new StringBuilder("");
Company com = new Company();
while ((line = pin.readLine()) != null) {
if(line.contains("<tbody>")) {
print = true;
continue;
}
if(print) {
System.out.println(line);
if(line.contains(html_code)) {
com.setCode(line.replace(html_code, "")
.replace("</td>", "")
.replace("\t", ""));
}
if(line.contains(html_boss)) {
com.setBoss(line.replace(html_boss, "")
.replace("</td>", "")
.replace("\t", ""));
}
}
if(line.contains("</tbody>")) {
break;
}
}
insert(com);
// companyService.insert(com);
} catch (Exception e) {
pout.println("发送 POST 请求出现异常!"+e);
e.printStackTrace();
}
//使用finally块来关闭输出流、输入流
finally{
try{
if(pout != null){
pout.close();
}
if(pin != null){
pin.close();
}
}
catch(IOException ex){
ex.printStackTrace();
}
}
}
private Connection getConn() {
String driver = "com.mysql.jdbc.Driver";
String url = "jdbc:mysql://localhost:3306/easyui";
String username = "root";
String password = "phpmysql";
Connection conn = null;
try {
Class.forName(driver); //classLoader,加载对应驱动
conn = (Connection) DriverManager.getConnection(url, username, password);
} catch (ClassNotFoundException e) {
e.printStackTrace();
} catch (SQLException e) {
e.printStackTrace();
}
return conn;
}
private int insert(Company com) {
Connection conn = getConn();
int i = 0;
String sql = "insert into Company(boss,name,code,wid,place) values(?,?,?,?,?)";
PreparedStatement pstmt;
try {
pstmt = (PreparedStatement) conn.prepareStatement(sql);
pstmt.setString(1, com.getBoss());
pstmt.setString(2, com.getName());
pstmt.setString(3, com.getCode());
pstmt.setString(4, com.getWid());
pstmt.setString(5, com.getPlace());
i = pstmt.executeUpdate();
pstmt.close();
conn.close();
} catch (SQLException e) {
e.printStackTrace();
}
return i;
}
}
|
import java.util.List;
import java.util.Random;
public class QuickSortList {
public static <T extends Comparable<? super T>> void sort(List<T> arrayToBeSorted) {
quickSort(arrayToBeSorted, 0, arrayToBeSorted.size() - 1);
}
private static <T extends Comparable<? super T>> void quickSort(List<T> arrayToBeSorted, int begin, int end) {
if (begin < end) {
int pivotIndex = partition(arrayToBeSorted, begin, end);
quickSort(arrayToBeSorted, begin, pivotIndex - 1);
quickSort(arrayToBeSorted, pivotIndex + 1, end);
}
}
private static <T extends Comparable<? super T>> int partition(List<T> arrayToBeSorted, int begin, int end) {
Random random = new Random();
int pivotIndex = begin + random.nextInt(end - begin + 1);
T pivot = arrayToBeSorted.get(pivotIndex);
swap(arrayToBeSorted, pivotIndex, end);
int i = begin;
pivotIndex = begin;
while (i < end) {
if (arrayToBeSorted.get(i).compareTo(pivot) < 0) {
swap(arrayToBeSorted, pivotIndex, i);
pivotIndex++;
}
i++;
}
swap(arrayToBeSorted, pivotIndex, end);
return pivotIndex;
}
private static <T> void swap(List<T> list, int firstIndex, int secondIndex) {
T temp = list.get(firstIndex);
list.set(firstIndex, list.get(secondIndex));
list.set(secondIndex, temp);
}
}
|
package pl.ark.chr.buginator.rest;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestBody;
import pl.ark.chr.buginator.domain.BaseEntity;
import pl.ark.chr.buginator.app.exceptions.RestException;
import pl.ark.chr.buginator.rest.annotations.DELETE;
import pl.ark.chr.buginator.rest.annotations.GET;
import pl.ark.chr.buginator.rest.annotations.POST;
import pl.ark.chr.buginator.service.CrudService;
import pl.ark.chr.buginator.util.SessionUtil;
import javax.annotation.PostConstruct;
import javax.servlet.http.HttpServletRequest;
import java.lang.reflect.ParameterizedType;
import java.util.List;
/**
* Created by Arek on 2016-09-29.
*/
public abstract class CrudRestController<T extends BaseEntity> {
private final static Logger logger = LoggerFactory.getLogger(CrudRestController.class);
protected String className;
@PostConstruct
private void init() {
ParameterizedType thisType = (ParameterizedType) getClass().getGenericSuperclass();
Class<T> domainClass = (Class<T>) thisType.getActualTypeArguments()[0];
this.className = domainClass.getSimpleName();
}
protected abstract CrudService<T> getService();
protected abstract SessionUtil getHttpSessionUtil();
@GET("/")
public List<T> getAll(HttpServletRequest request) throws RestException {
logger.info("Getting all " + className + " with user: " + getHttpSessionUtil().getCurrentUserEmail(request));
return getService().getAll();
}
@GET("/{id}")
public T get(@PathVariable("id") Long id, HttpServletRequest request) throws RestException {
logger.info("Getting " + className + " with id: " + id + " with user: " + getHttpSessionUtil().getCurrentUserEmail(request));
return getService().get(id);
}
@POST("/")
public T save(@RequestBody T entity, HttpServletRequest request) throws RestException {
logger.info("Saving " + className + " with id: " + entity.getId() + " with user: " + getHttpSessionUtil().getCurrentUserEmail(request));
return getService().save(entity);
}
@DELETE("/{id}")
public void delete(@PathVariable("id") Long id, HttpServletRequest request) throws RestException {
logger.info("Deleting " + className + " with id: " + id + " with user: " + getHttpSessionUtil().getCurrentUserEmail(request));
getService().delete(id);
}
}
|
package com.tencent.mm.plugin.game.wepkg.utils;
import com.tencent.mm.ab.b;
public interface WepkgRunCgi$a {
void a(int i, int i2, String str, b bVar);
}
|
package com.tencent.mm.plugin.wallet.pwd.ui;
import android.content.Intent;
import android.view.View;
import com.tencent.mm.wallet_core.ui.d;
class WalletDigitalCertUI$1 extends d {
final /* synthetic */ WalletDigitalCertUI phy;
WalletDigitalCertUI$1(WalletDigitalCertUI walletDigitalCertUI) {
this.phy = walletDigitalCertUI;
}
public final void onClick(View view) {
Intent intent = new Intent();
intent.setClass(this.phy, WalletIdCardCheckUI.class);
this.phy.startActivityForResult(intent, 1);
}
}
|
package lotto.step3.domain;
import java.util.Objects;
public class LottoNumber {
private static final int LOTTO_MIN_NUMBER = 1;
private static final int LOTTO_MAX_NUMBER = 45;
private int lottoNumber;
public LottoNumber(int number) {
if (number < LOTTO_MIN_NUMBER || number > LOTTO_MAX_NUMBER) {
throw new IllegalArgumentException("로또 숫자는 " + LOTTO_MIN_NUMBER + "~" + LOTTO_MAX_NUMBER + "만 가능합니다.");
}
lottoNumber = number;
}
@Override
public boolean equals(Object o) {
if (this == o) return true;
if (o == null || getClass() != o.getClass()) return false;
LottoNumber that = (LottoNumber) o;
return lottoNumber == that.lottoNumber;
}
@Override
public int hashCode() {
return Objects.hash(lottoNumber);
}
@Override
public String toString() {
return String.valueOf(lottoNumber);
}
}
|
package April.Loops;
public class PrintOddEvenNumbers {
public static void main(String[] args) {
for (int i = 1;i <= 100;i++){
int even ;
//even =i % 2 ==0;
if(i % 2 ==0){
System.out.println("even numbers - " +i);
}else{
// System.out.println("odd numbers - " +i);
}
}
}
}
|
package com.framework.service;
import java.util.List;
import com.framework.bean.common.Page;
import com.framework.bean.common.TreeViewNode;
import com.framework.bean.vo.SysMenuVo;
import com.framework.model.SysMenu;
public interface MenuService {
void queryMenuList(Page<SysMenu> page, SysMenu menu) throws Exception;
List<TreeViewNode> queryMenuTree() throws Exception;
boolean deleteMenus(List<Integer> ids) throws Exception;
void addMenu(SysMenuVo menu) throws Exception;
List<SysMenuVo> queryMenuListByPCode(String pCode) throws Exception;
void saveMenu(List<SysMenuVo> menus) throws Exception;
}
|
package model.service;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import model.dao.AdminDao;
import model.dao.MovieDao;
import model.dao.ReserVationDao;
import model.dao.TheaterDao;
import model.vo.movie.CountryVO;
import model.vo.movie.GenreVO;
import model.vo.movie.MovieGradeInfo;
import model.vo.movie.MovieVO;
import model.vo.movie.StaticsVO;
import model.vo.mycinema.ListVOGenericMap;
import model.vo.mycinema.PagingBean;
import model.vo.reservation.ScreeningMovieVO;
import model.vo.theater.LocalInfoVO;
import model.vo.theater.PlayRoomTypeVO;
import model.vo.theater.PlayRoomVO;
import model.vo.theater.TheaterVO;
public class AdminService {
private AdminDao adminDao;
private ReserVationDao resDao;
private MovieDao movieDao;
private TheaterDao theaterDao;
public AdminService() {
super();
// TODO Auto-generated constructor stub
}
public void setAdminDao(AdminDao adminDao) {
this.adminDao = adminDao;
}
public void setResDao(ReserVationDao resDao) {
this.resDao = resDao;
}
public void setMovieDao(MovieDao movieDao) {
this.movieDao = movieDao;
}
public void setTheaterDao(TheaterDao theaterDao) {
this.theaterDao = theaterDao;
}
public ArrayList<GenreVO> getGenreInfo() throws SQLException {
System.out.println("adminService..getGenreInfo");
return adminDao.getGenreInfo();
}
public ArrayList<CountryVO> getCountryInfo() throws SQLException {
System.out.println("adminService..getCountryInfo");
return adminDao.getCountryInfo();
}
//영화관 정보 입력을 위해 초기 지역 정보 리스트를 로딩 : 신일
public ArrayList<LocalInfoVO> getLocalInfo() throws SQLException {
ArrayList<LocalInfoVO> lList=new ArrayList<LocalInfoVO>();
lList=resDao.getLocalList();
System.out.println("adminService..getLocalInfoVO "+lList);
return lList;
}
//영화관 등록 메서드 : 신일
public void registerTheater(TheaterVO theaterVO) throws SQLException {
adminDao.registerTheater(theaterVO);
}
//상영관 등록 메서드 : 신일
public void registerPlayRoom(PlayRoomVO playRoomVO) throws SQLException {
adminDao.registerPlayRoom(playRoomVO);
}
//상영관 삭제 메서드 : 신일
public void delPlayRoom(int playRoomNo) throws SQLException {
adminDao.delPlayRoom(playRoomNo);
}
//상영관의 유니크 넘버를 가져옴 : 신일
public int getPlayRoomNoByPlayRoomUniqNo(int playRoomNo) throws SQLException{
return adminDao.getPlayRoomNoByPlayRoomUniqNo(playRoomNo);
}
//영화관 수정을 위해 영화관 정보를 리턴 TheaterVO 타입으로 로딩 : 신일
public TheaterVO getTheaterVObyTNo(TheaterVO theaterVO) throws Exception{
return adminDao.getTheaterVObyTNo(theaterVO);
}
//영화관 정보 수정 : 인자값 - TheaterVO : 신일
public ArrayList<PlayRoomVO> modifyTheaterInfo(TheaterVO theaterVO) throws SQLException{
adminDao.modifyTheaterVObyTheaterVO(theaterVO);
return adminDao.getPlayRoomVObyTNO(theaterVO.getTheater_no());
}
//상영관 리스트 로딩 : 신일
public ArrayList<PlayRoomVO> getPlayRoomVOList(TheaterVO theaterVO) throws SQLException{
return adminDao.getPlayRoomVObyTNO(theaterVO.getTheater_no());
}
//상영관 타입 리스트를 로딩 : 신일
public ArrayList<PlayRoomTypeVO> getPlayRoomTypeVO() throws SQLException{
return adminDao.getPlayRoomTypeVO();
}
public ArrayList<MovieGradeInfo> getGradeInfo() throws SQLException {
System.out.println("adminService..getGradeInfo");
return adminDao.getGradeInfo();
}
public void registerMovie(MovieVO movieVO) throws SQLException {
int movie_no=adminDao.registerMovie(movieVO);
System.out.println("service에서 movie 등록 완료!!");
movieVO.setMovie_no(movie_no); //등록한 영화번호
movieVO.setOrgfileName(movie_no+""); //그 영화의 포스터 번호
//2. 통계테이블에 등록하기
this.regMovieToStatics(movieVO); //성별별로 statics table에 등록
System.out.println("service에서 movie 등록 후 statics table에 등록 완료!");
}
public ArrayList<TheaterVO> getTheaterInfo() throws SQLException {
return adminDao.getTheaterInfo();
}
public ArrayList<MovieVO> getMovieInfo() throws SQLException {
return adminDao.getMovieInfo();
}
public void registerScreeningMovie(ScreeningMovieVO movieVO) throws SQLException {
adminDao.registerScreeningMovie(movieVO);
}
public void regScreeningMovie(ScreeningMovieVO movieVO) throws SQLException {
System.out.println("service : "+movieVO);
adminDao.regScreeningMovie(movieVO);
}
public ArrayList<HashMap> getTheaterListByLocalNo(int local_no) throws SQLException {
return resDao.getTheaterListByLocal(local_no);
}
public ArrayList<HashMap> getPublicDayByMovieNo(int movie_no) throws SQLException {
return adminDao.getPublicDayByMovieNo(movie_no);
}
public ArrayList<HashMap> getScreeningMovieList() throws SQLException {
return adminDao.getScreeningMovieList();
}
/**
* 관리자메뉴 - 상영표관리 - 상영표관리
* 상영표 등록시 screening_movie 테이블에 있는 등록가능한
* 영화,지역,영화관 목록들을 가져온다.
* @throws SQLException
*/
public HashMap timetable_admin_info(String pageNo) {
HashMap map = new HashMap();
try {
map.put("movie", adminDao.getRegisterPossibleMovie());
map.put("local", adminDao.getRegisterPossibleLocal());
map.put("theater", adminDao.getRegisterPossibleTheater());
if (pageNo == null || pageNo == "")
pageNo = "1";
List<Map> list = adminDao.getTimeTable(pageNo);
int total = adminDao.getTotalTimeTable();
PagingBean paging = new PagingBean(total, Integer.parseInt(pageNo));
ListVOGenericMap tlvo = new ListVOGenericMap(list, paging);
map.put("time_table", tlvo);
map.put("total", total);
} catch (SQLException e) {
e.printStackTrace();
}
return map;
}
/**
* 관리자메뉴 - 상영표관리 - 상영표관리
* 상영표 등록시 (영화선택)에 따라서
* screening_movie 테이블에 있는 상영 가능한 (지역정보)를 가져온다.
*/
public HashMap getLocalAsMovieNo(String movie_no) {
HashMap map = new HashMap();
ArrayList<Map> list= null;
try {
map.put("list",adminDao.getLocalAsMovieNo(movie_no));
map.put("tlist",adminDao.getTimeTableAsMovieNo(movie_no));
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return map;
}
/**
* 관리자메뉴 - 상영표관리 - 상영표관리
* 상영표 등록시 (지역선택)에 따라서
* screening_movie 테이블에 있는 상영 가능한 (영화관정보)를 가져온다.
*/
public HashMap getTheaterAsLocalNoAndMovleNo(Map map) {
HashMap map2 = new HashMap();
try {
map2.put("list",adminDao.getTheaterAsLocalNoAndMovleNo(map));
map2.put("tlist",adminDao.getTimeTableAsMovieNoAndLocalNo(map));
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return map2;
}
/**
* 관리자메뉴 - 상영표관리 - 상영표관리
* 상영표 등록시 (영화관 선택)에 따라서
* play_room 테이블에 있는 해당 영화관의 (상영관목록)을 가져온다.
*/
public ArrayList<Map> getPlayRoomAsTheaterNo(String theater_no) {
ArrayList<Map> list= null;
try {
list = adminDao.getPlayRoomAsTheaterNo(theater_no);
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return list;
}
/**
* 관리자메뉴 - 상영표관리 - 상영표관리
* 상영표 등록시 (영화선택)에 따라서
* play_room 테이블에 있는 해당 영화관의 (등록가능기간)을 가져온다.
*/
public HashMap getPossibleDateAsMovieNo(Map queryMap) {
HashMap map = new HashMap();
try {
map = adminDao.getPossibleDateAsMovieNo(queryMap);
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return map;
}
/**
* 관리자메뉴 - 상영표관리 - 상영표관리
* 상영표 등록시 입력받은 정보를 time_table 에 하루치 insert
*/
public void timeTableOneDayRegister(HashMap map) {
int hour = Integer.parseInt((String) map.get("hour"));
int minute = Integer.parseInt((String) map.get("minute"));
int running_time = 0;
try {
running_time = adminDao.getRunninTimeAsMovieNo((String) map.get("movie_no"));
for (;;) {
String starting_time = map.get("day") + " " + numberFormat(hour) + ":" + numberFormat(minute);
map.put("starting_time", starting_time);
hour = hour + running_time / 60;
minute = minute + running_time % 60;
if (minute >= 60) {
hour++;
minute -= 60;
}
if(hour>=24)
break;
String ending_time = map.get("day") + " " + numberFormat(hour)+ ":" + numberFormat(minute);
map.put("ending_time", ending_time);
map.put("play_room_uniq_no", adminDao.getPlayRoomUniqNoAsTheaterNoAndPlayRoomNo(map));
adminDao.timeTableRegister(map);
minute = minute + 25;
if (minute >= 60) {
hour++;
minute -= 60;
}
}
} catch (SQLException e) {
e.printStackTrace();
}
}
/**
* 관리자메뉴 - 상영표관리 - 상영표관리
* 상영표 등록시 입력받은 정보를 time_table 에 insert
*/
public void timeTableRegister(HashMap map) {
int hour = Integer.parseInt((String) map.get("hour"));
int minute = Integer.parseInt((String) map.get("minute"));
map.put("starting_time", map.get("day") + " " + numberFormat(hour) + ":" + numberFormat(minute));
int running_time = 0;
try {
running_time = adminDao.getRunninTimeAsMovieNo((String) map.get("movie_no"));
hour = hour + running_time / 60;
minute = minute + running_time % 60;
if (minute >= 60) {
hour++;
minute -= 60;
}
map.put("ending_time", map.get("day") + " " + numberFormat(hour) + ":" + numberFormat(minute));
map.put("play_room_uniq_no", adminDao.getPlayRoomUniqNoAsTheaterNoAndPlayRoomNo(map));
adminDao.timeTableRegister(map);
} catch (SQLException e) {
e.printStackTrace();
}
}
/**
* 날짜 type을 mm,dd 로 하기위한
* numberForamt 메서드
* ex) 1/11 = 01/11 , 1/3 = 01/03
*/
public String numberFormat(int number){
String str ="";
if((number+"").length()==1)
str="0"+number;
else
str=""+number;
return str;
}
/**
* 관리자메뉴 - 상영표관리 - 상영표관리
* 상영표 등록시 (영화관, 영화선택)에 따라서
* play_room 테이블에 있는 해당 영화관의 (상영관목록과 등록가능시간)을 가져온다.
*/
public ArrayList<HashMap> getTimeTableAsMovieNoAndLocalNoAndTheaterNo(HashMap queryMap) {
ArrayList<HashMap> list = null;
try {
list = adminDao.getTimeTableAsMovieNoAndLocalNoAndTheaterNo(queryMap);
} catch (SQLException e) {
e.printStackTrace();
}
return list;
}
/**
* 관리자메뉴 - 상영표관리 - 상영표관리
* 상영관번호 선택시에 ajax로 해당 상영관에 time_table을 보여줌.
*/
public ArrayList<HashMap> getTimeTableAsAllNo(HashMap map) {
ArrayList<HashMap> list = null;
try {
list = adminDao.getTimeTableAsAllNo(map);
} catch (SQLException e) {
e.printStackTrace();
}
return list;
}
public MovieVO showMovieDetail(int movie_no) throws SQLException {
return movieDao.getMovieInfo(movie_no);
}
public ArrayList<HashMap> getAllMovieList() throws SQLException {
return movieDao.getAllMovieList();
}
/**
* 관리자메뉴 - 상영표관리 - 상영표관리
* 선택삭제시 선택한 list 를 StringFormat으로 ArrayList에 담고 삭제한다.
*/
public HashMap delTimeTable(ArrayList<String> list) {
StringBuffer sb1 = new StringBuffer();
StringBuffer sb2 = new StringBuffer();
HashMap map = new HashMap();
for(String str : list ){
try {
adminDao.delTimeTable(str);
sb1.append(" "+str);
} catch (SQLException e) {
sb2.append(" "+str);
}
}
map.put("success",sb1.toString());
map.put("fail",sb2.toString());
return map;
}
/**
* 관리자메뉴 - 상영표관리 - 상영표관리
* 삭제시 time_Table 에 있는 모든 time_table_no 를 가져온다.
*/
public ArrayList<String> getAllTimeTableNo() {
ArrayList<String> list = null;
try {
list = adminDao.getAllTimeTableNo();
} catch (SQLException e) {
e.printStackTrace();
}
return list;
}
/**
* 5/8아영추가사항
* @throws SQLException
*/
public void regMovieToStatics(MovieVO vo) throws SQLException {
adminDao.regMovieToStatics(vo);
}
/**
* 여기서부터 시작 아영
*/
public void updateBoxOffice() throws SQLException {
//1. sysdate 이전의 예매정보(즉, 이미 끝난 영화에 대한) 를 가져온다.
ArrayList<StaticsVO> list = movieDao.getBeforeBoxUpdateRM();
if(list!=null){ //reservation table에 내용이 있을 경우
//2. 예매정보를 statics 테이블에 update 한다
for(StaticsVO statics:list){
//DB에 저장되어있던 특정 영화에 대한 누적관객수 불러오기
int total = adminDao.getBoxOfficeCount(statics);
System.out.println(statics.getMovie_no()+"업데이트 전 누적 관객 수 : "+total);
total+=statics.getTotal_member();
System.out.println("누적 후 관객 수 :"+total);
statics.setTotal_member(total); //관객수 누적 시키기
adminDao.updateBoxOffice(statics);
}
//3. reservation table 지우기
adminDao.deleteReservationWeek();
//4. time_table 지우기
adminDao.deleteTimeTableWeek();
}
}
/**
* 박스오피스 리스트
*/
public ArrayList<HashMap> getBoxOfficeList() throws SQLException {
return movieDao.getBoxOfficeList();
}
public void screeningMovieDel(Map map) throws SQLException {
adminDao.screeningMovieDel(map);
}
/**
* 영화검색
* @throws SQLException
*/
public ArrayList<MovieVO> getSearchMovie(String method, String search_title) throws SQLException {
ArrayList<MovieVO> list=null;
if(method.equals("title")){
list = movieDao.getSearchMovieByTitle(search_title);
}else if(method.equals("genre")){
list = movieDao.getSearchMovieByGenre(search_title);
}else if(method.equals("country")){
list = movieDao.getSearchMovieByCountry(search_title);
}
return list;
}
public boolean todayCheck(String day) {
boolean flag = false;
try {
String today = adminDao.todayCheck();
flag = todayCompareAsInsertDay(day, today);
} catch (SQLException e) {
e.printStackTrace();
}
return flag;
}
public boolean todayCompareAsInsertDay(String day, String today){
boolean flag = false;
StringBuffer sb1 = new StringBuffer(day);
StringBuffer sb2 = new StringBuffer(today);
int y1 = Integer.parseInt(sb1.substring(0,4));
int m1 = Integer.parseInt(sb1.substring(5,7));
int d1 = Integer.parseInt(sb1.substring(8,10));
int y2 = Integer.parseInt(sb2.substring(0,4));
int m2 = Integer.parseInt(sb2.substring(5,7));
int d2 = Integer.parseInt(sb2.substring(8,10));
System.out.println("day : "+y1+" "+m1+" "+d1);
System.out.println("today : "+y2+" "+m2+" "+d2);
if(y1>=y2){
if(m1>m2){
flag = true;
}else if(m1==m2){
if(d1>=d2){
flag = true;
}
}
}
return flag;
}
}
|
package at.fhv.team3.presentation.customermanagement;
import at.fhv.team3.application.ServerIP;
import at.fhv.team3.domain.dto.BookDTO;
import at.fhv.team3.domain.dto.CustomerDTO;
import at.fhv.team3.domain.dto.DTO;
import at.fhv.team3.presentation.detailbook.DetailBookPresenter;
import at.fhv.team3.presentation.detailbook.DetailBookView;
import at.fhv.team3.rmi.interfaces.RMICustomer;
import javafx.collections.FXCollections;
import javafx.collections.ObservableList;
import javafx.event.ActionEvent;
import javafx.event.EventHandler;
import javafx.fxml.FXML;
import javafx.fxml.Initializable;
import javafx.scene.Scene;
import javafx.scene.control.*;
import javafx.scene.image.Image;
import javafx.scene.input.KeyCode;
import javafx.scene.input.KeyEvent;
import javafx.scene.input.MouseEvent;
import javafx.stage.Stage;
import javafx.util.StringConverter;
import java.net.URL;
import java.rmi.registry.LocateRegistry;
import java.rmi.registry.Registry;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Optional;
import java.util.ResourceBundle;
public class CustomerManagementPresenter implements Initializable {
private ObservableList<CustomerDTO> _customers;
private Label placeholder;
CustomerDTO selectedItemfromComboBox;
private ServerIP serverIP;
private String host;
public void initialize(URL location, ResourceBundle resources) {
placeholder = new Label("Bitte suchen!");
resultCustomer.setPlaceholder(placeholder);
serverIP = ServerIP.getInstance();
host = serverIP.getServer();
resultCustomer.setOnAction((event) -> {
selectedItemfromComboBox = resultCustomer.getSelectionModel().getSelectedItem();
setInfo();
});
}
@FXML
private Button CostumerManagementCancelButton;
@FXML
private TextField searchCostumerField;
@FXML
private TextField fistname;
@FXML
private TextField secondname;
@FXML
private TextField tel;
@FXML
private TextField email;
@FXML
private TextField subscription;
@FXML
private Button searchCostumerButton;
@FXML
private ComboBox<CustomerDTO> resultCustomer;
// Kundenverwaltung wird abgebrochen
@FXML
private void handleButtonActionCostumerManagementCancel(ActionEvent event) {
Alert alert = new Alert(Alert.AlertType.WARNING, "Ihre Eingaben gehen verloren", ButtonType.CANCEL, ButtonType.OK);
alert.setTitle("Attention");
alert.setHeaderText("Wollen Sie wirklich abbrechen?");
Optional<ButtonType> result = alert.showAndWait();
if (result.get() == ButtonType.OK) {
Stage stage = (Stage) CostumerManagementCancelButton.getScene().getWindow();
stage.close();
}
}
@FXML
public void findCustomerTroughEnter() {
searchCostumerButton.getScene().setOnKeyPressed(new EventHandler<KeyEvent>() {
@Override
public void handle(KeyEvent event) {
if(event.getCode().equals(KeyCode.ENTER)) {
findCustomer();
}
}
});
}
// Es wird durch das betätigen der Enter Taste, die Kundensuche gestartet.
@FXML
public void findCustomer(){
if((!(searchCostumerField.getText().trim().equals("")))) {
try {
Registry registry = LocateRegistry.getRegistry(host, 1099);
RMICustomer rmiCustomer = (RMICustomer) registry.lookup("Customer");
ArrayList<DTO> CustomersFound = rmiCustomer.findCustomer(searchCostumerField.getText());
_customers = FXCollections.observableArrayList();
for (int i = 0; i < CustomersFound.size(); i++) {
HashMap<String, String> customerResult = CustomersFound.get(i).getAllData();
CustomerDTO tempCustomer = new CustomerDTO(Integer.parseInt(customerResult.get("id")), customerResult.get("firstname"), customerResult.get("lastname"),
Boolean.parseBoolean(customerResult.get("subscription")), customerResult.get("email"), customerResult.get("phonenumber"));
_customers.add(tempCustomer);
}
resultCustomer.setItems(null);
resultCustomer.setItems(_customers);
renderCustomer();
} catch (Exception e) {
System.out.println("HelloClient exception: " + e.getMessage());
e.printStackTrace();
}
}else{
resultCustomer.setItems(null);
placeholder = new Label("Falsche Eingabe!");
resultCustomer.setPlaceholder(placeholder);
resultCustomer.show();
}
}
// Alle gefundenen Kunden werden im Dropdown angezeigt
public void renderCustomer(){
if(resultCustomer.getItems().isEmpty()){
resultCustomer.setItems(null);
placeholder = new Label("Keine Ergebnisse!");
resultCustomer.setPlaceholder(placeholder);
resultCustomer.show();
} else {
resultCustomer.setCellFactory((ComboBox) -> {
return new ListCell<CustomerDTO>() {
@Override
protected void updateItem(CustomerDTO item, boolean empty) {
super.updateItem(item, empty);
if (item == null || empty) {
setText(null);
} else {
setText(item.getFirstName() + " " + item.getLastName());
}
}
};
});
resultCustomer.setConverter(new StringConverter<CustomerDTO>() {
@Override
public String toString(CustomerDTO person) {
if (person == null) {
return null;
} else {
return person.getFirstName() + " " + person.getLastName();
}
}
@Override
public CustomerDTO fromString(String personString) {
return null;
}
});
resultCustomer.show();
}
}
// Die Informationen des Kunden werden in den dazugehörigen Feldern angezeigt
public void setInfo(){
if(selectedItemfromComboBox != null) {
if (selectedItemfromComboBox.getFirstName() != null) {
fistname.setText(selectedItemfromComboBox.getFirstName());
}
if (selectedItemfromComboBox.getLastName() != null) {
secondname.setText(selectedItemfromComboBox.getLastName());
}
if (selectedItemfromComboBox.getPhoneNumber() != null) {
tel.setText(selectedItemfromComboBox.getPhoneNumber());
}
if (selectedItemfromComboBox.getEmail() != null) {
email.setText(selectedItemfromComboBox.getEmail());
}
if (selectedItemfromComboBox.getSubscription() == true) {
subscription.setText("Aktiv");
}
if (selectedItemfromComboBox.getSubscription() == false) {
subscription.setText("InAktiv");
}
}
}
}
|
package com.qihoo.finance.chronus.metadata.api.task.entity;
import com.fasterxml.jackson.annotation.JsonFormat;
import com.qihoo.finance.chronus.metadata.api.common.Entity;
import com.qihoo.finance.chronus.metadata.api.task.enums.TaskRunStatusEnum;
import lombok.Getter;
import lombok.Setter;
import org.springframework.data.annotation.Id;
import java.util.Date;
/**
* Created by xiongpu on 2019/8/3.
*/
@Getter
@Setter
public class TaskRuntimeEntity extends Entity {
@Id
private String id;
public TaskRuntimeEntity() {
}
public TaskRuntimeEntity(TaskItemEntity taskItemEntity) {
this.taskItemId = taskItemEntity.getTaskItemId();
this.registerTime = new Date();
this.heartBeatTime = new Date();
this.dateCreated = new Date();
this.dateUpdated = new Date();
this.state = TaskRunStatusEnum.INIT.toString();
this.message = "初始化成功,等待Master分配!";
}
private String taskItemId;
/**
* 服务开始时间
*/
@JsonFormat(pattern = "yyyy-MM-dd HH:mm:ss", timezone = "GMT+8")
private Date registerTime;
/**
* 最后一次心跳通知时间
*/
@JsonFormat(pattern = "yyyy-MM-dd HH:mm:ss", timezone = "GMT+8")
private Date heartBeatTime;
/**
* 最后一次运行时间
*/
@JsonFormat(pattern = "yyyy-MM-dd HH:mm:ss", timezone = "GMT+8")
private Date lastRunDataTime;
@JsonFormat(pattern = "yyyy-MM-dd HH:mm:ss", timezone = "GMT+8")
private Date nextRunStartTime;
/**
* 运行状态
*/
private String state;
private String message;
@JsonFormat(pattern = "yyyy-MM-dd HH:mm:ss", timezone = "GMT+8")
private Date dateUpdated;
@JsonFormat(pattern = "yyyy-MM-dd HH:mm:ss", timezone = "GMT+8")
private Date dateCreated;
public void createdSuccess() {
this.state = TaskRunStatusEnum.INIT.name();
this.message = "初始化成功!";
}
}
|
package com.tencent.mm.plugin.appbrand.media.a;
public final class c {
public String dGC;
public String fIi;
public String ffK;
}
|
package com.simple.base.components.cache.controller;
public class TestController {
}
|
package be.spring.app.controller;
import be.spring.app.controller.exceptions.ObjectNotFoundException;
import be.spring.app.data.PositionsEnum;
import be.spring.app.form.CreateAndUpdateTeamForm;
import be.spring.app.model.Account;
import be.spring.app.dto.ActionWrapperDTO;
import be.spring.app.model.Address;
import be.spring.app.model.Team;
import be.spring.app.service.AccountService;
import be.spring.app.service.AddressService;
import be.spring.app.service.TeamService;
import be.spring.app.validators.CreateTeamValidator;
import com.google.common.collect.Lists;
import com.google.common.collect.Maps;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.ui.ModelMap;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.WebDataBinder;
import org.springframework.web.bind.annotation.*;
import javax.validation.Valid;
import java.util.List;
import java.util.Locale;
import java.util.Map;
import static be.spring.app.utils.Constants.*;
/**
* Created by u0090265 on 5/11/14.
*/
@Controller
@RequestMapping("/")
public class TeamController extends AbstractController {
@Autowired
TeamService teamService;
@Autowired
AddressService addressService;
@Autowired
AccountService accountService;
@Autowired
private CreateTeamValidator validator;
private static final Logger log = LoggerFactory.getLogger(TeamController.class);
private static final String EDIT_TEAM = "editTeam";
private static final String CREATE_TEAM = "createTeam";
@InitBinder("form")
protected void initBinder(WebDataBinder binder) {
binder.setValidator(validator);
}
@ModelAttribute("addresses")
public List<Address> addressList() {
return addressService.getAllAddresses();
}
@PreAuthorize("hasRole('ADMIN')")
@RequestMapping(value = "createTeam", method = RequestMethod.GET)
public String getCreateTeamPage(ModelMap model, @ModelAttribute("form") CreateAndUpdateTeamForm form, Locale locale) {
model.addAttribute("form", new CreateAndUpdateTeamForm());
return createTeam(model, locale);
}
@PreAuthorize("hasRole('ADMIN')")
@RequestMapping(value = "editTeam", method = RequestMethod.GET)
public String getEditTeamPage(@ModelAttribute("form") CreateAndUpdateTeamForm form, @RequestParam long teamId, ModelMap model, Locale locale) {
Team team = teamService.getTeam(teamId);
if (team == null) throw new ObjectNotFoundException(String.format("Team with id %s not found", teamId));
form.setId(team.getId());
form.setTeamName(team.getName());
form.setCity(team.getAddress().getCity());
form.setAddress(team.getAddress().getAddress());
form.setPostalCode(String.valueOf(team.getAddress().getPostalCode()));
if (team.getAddress().getGoogleLink() != null && !team.getAddress().getGoogleLink().isEmpty()) {
form.setGoogleLink(team.getAddress().getGoogleLink());
form.setUseLink(true);
}
model.addAttribute("selectedAddress", team.getAddress().getId());
return editTeam(model, locale);
}
@PreAuthorize("hasRole('ADMIN')")
@RequestMapping(value = "createTeam", method = RequestMethod.POST)
public String postCreateTeam(@ModelAttribute("form") @Valid CreateAndUpdateTeamForm form, BindingResult result, ModelMap model, Locale locale) {
try {
if (teamService.teamExists(form.getTeamName())) {
result.rejectValue("teamName", "validation.teamExists.message");
}
if (result.hasErrors()) {
return createTeam(model, locale);
}
Team team = teamService.createTeam(form);
log.debug("Created team: {}", team);
return REDIRECT_LANDING_TEAMS;
} finally {
log.info("Finally of createTeam");
}
}
@PreAuthorize("hasRole('ADMIN')")
@RequestMapping(value = "editTeam", method = RequestMethod.POST)
public String postEditTeam(@ModelAttribute("form") @Valid CreateAndUpdateTeamForm form, BindingResult result, ModelMap model, Locale locale) {
try {
if (result.hasErrors()) {
model.addAttribute("form", form);
return editTeam(model, locale);
}
Team team = teamService.updateTeam(form);
log.debug("Created team: {}", team);
return REDIRECT_LANDING_TEAMS;
} finally {
log.info("Finally of createTeam");
}
}
private String editTeam(ModelMap model, Locale locale) {
model.addAttribute("title", getMessage("title.editTeam", null, locale));
model.addAttribute("action", EDIT_TEAM);
return LANDING_CREATE_TEAM;
}
private String createTeam(ModelMap model, Locale locale) {
model.addAttribute("title", getMessage("title.createTeam", null, locale));
model.addAttribute("action", CREATE_TEAM);
return LANDING_CREATE_TEAM;
}
@RequestMapping(value = "teams", method = RequestMethod.GET)
public String getTeams(ModelMap model, Locale locale) {
model.addAttribute("teams", teamService.getTeams(getAccountFromSecurity(), locale));
return LANDING_TEAMS;
}
@PreAuthorize("hasRole('ADMIN')")
@RequestMapping(value = "deleteTeam", method = RequestMethod.GET)
public String deleteTeam(@RequestParam long teamId, Model model, Locale locale) {
Team team = teamService.getTeam(teamId);
if (team == null) throw new ObjectNotFoundException(String.format("Team with id %s not found", teamId));
if (teamService.deleteTeam(teamId, getAccountFromSecurity())) {
setSuccessMessage(model, locale, "text.team.deleted", null);
} else {
setErrorMessage(model, locale, "error.delete.team.dependencies", null);
}
model.addAttribute("teams", getTeams(locale));
return LANDING_TEAMS;
}
@RequestMapping(value = "team", method = RequestMethod.GET)
public String getTeam(ModelMap model, Locale locale) {
model.put("players", getSortedAccounts());
return LANDING_TEAM;
}
private List<ActionWrapperDTO<Team>> getTeams(Locale locale) {
return teamService.getTeams(getAccountFromSecurity(), locale);
}
private Map<String, List<Account>> getSortedAccounts() {
Map<String, List<Account>> players = Maps.newLinkedHashMap();
List<Account> goalKeepers = Lists.newArrayList();
List<Account> defenders = Lists.newArrayList();
List<Account> midfielders = Lists.newArrayList();
List<Account> fordwards = Lists.newArrayList();
List<Account> unknown = Lists.newArrayList();
for (Account account : accountService.getAllActivateAccounts()) {
if (account.getAccountProfile() == null || account.getAccountProfile().getFavouritePosition() == null) {
//No account profile, no position
unknown.add(account);
}
else {
switch (account.getAccountProfile().getFavouritePosition()) {
case GOALKEEPER:
goalKeepers.add(account);
break;
case DEFENDER:
defenders.add(account);
break;
case MIDFIELDER:
midfielders.add(account);
break;
case FORWARD:
fordwards.add(account);
break;
default:
unknown.add(account);
break;
}
}
}
players.put(PositionsEnum.GOALKEEPER.name(), goalKeepers);
players.put(PositionsEnum.DEFENDER.name(), defenders);
players.put(PositionsEnum.MIDFIELDER.name(), midfielders);
players.put(PositionsEnum.FORWARD.name(), fordwards);
players.put("UNKNOWN", unknown);
return players;
}
}
|
package com.bw.movie.IView;
import com.bw.movie.mvp.model.bean.Movieinfo;
public interface IHotMvoieView extends IBaseView {
void success(Movieinfo movieinfo);
void Error(String msg);
}
|
package demoGui;
import java.util.ArrayList;
import javax.swing.JList;
import javax.swing.SwingWorker;
/*****************************************************************************************************************************************
* This class represents a parallel thread to run alongside the main MultipathUI GUI, to perform a long-running task in the background
* to eliminate noticeable lag and freezing.
*
* This class performs a cancelReservation operation on the selected GRI/MP-GRI in the background and then resets the selections in
* the MP-GRI/GRI lists so that the appropriate request can be re-queried (also in the background).
*
* @author Jeremy
/*****************************************************************************************************************************************/
public class DemoCancelThread extends SwingWorker<Void, Integer>
{
DemoUI callingMPGui; // The actual GUI object
String griToCancel; // The GRI that will be cancelled
boolean isMPGriSelected; // TRUE if user has selected a group GRI on the GUI
boolean isUniGriSelected; // TRUE if user has selected a subrequest GRI on the GUI
boolean cancellingMP; // TRUE if we are canceling an group, FALSE if it is a subrequest
int numCancelled;
/**
* Constructor
*
* @param theGui, The calling GUI object
* @param gri, GRI to cancel
* @param mpIsSelected, TRUE if user has selected a group GRI on the GUI
* @param uniIsSelected, TRUE if user has selected a subrequest GRI on the GUI
* @param groupCancellation, TRUE if we are canceling an group, FALSe if it is a subrequest
**/
public DemoCancelThread(DemoUI theGui, String gri, boolean mpIsSelected, boolean uniIsSelected, boolean groupCancellation, int numCancelled)
{
callingMPGui = theGui;
griToCancel = gri;
isMPGriSelected = mpIsSelected;
isUniGriSelected = uniIsSelected;
cancellingMP = groupCancellation;
this.numCancelled = numCancelled;
}
/**
* Thread's runner method. When the calling object invokes execute(), this is the method that runs.
*/
protected Void doInBackground()
{
DemoGuiController multipathUIController = callingMPGui.mpUIController; // GUI's behavior controller
multipathUIController.cancelExistingReservation(griToCancel); // Perform the actual reservation cancel operation
int countCancelled = 0;
while(countCancelled < numCancelled){
ArrayList<String> queryResults = multipathUIController.queryReservations(griToCancel);
for(int i = 0; i < queryResults.size(); i++){
if(queryResults.get(i).contains("CANCELLED") || queryResults.get(i).contains("FAILED")){
countCancelled++;
}
}
if(countCancelled < numCancelled){
countCancelled = 0;
try
{
Thread.sleep(5000);
}
catch(Exception e){}
}
}
refreshListsAfterCancel(); // Update the GRI Lists so that the INCANCEL status may be reflected
return null;
}
/**
* Have the GUI refresh the GRI lists so that the most recent query results can be displayed
**/
private void refreshListsAfterCancel()
{
callingMPGui.handleGriTree();
callingMPGui.selectARequest(griToCancel);
callingMPGui.outputConsole.setText("Request " + griToCancel + " CANCELLED!");
callingMPGui.cancelResButton.setEnabled(true);
callingMPGui.createButton.setEnabled(true);
callingMPGui.closeDemoButton.setEnabled(true);
callingMPGui.modifyResButton.setEnabled(true);
}
}
|
public class E15
{
public static void main(String[] args)
{
System.out.println("+------+");
System.out.println("|Andrew|");
System.out.println("+------+");
}
} |
package com.kush.lib.expressions.factory;
import static java.util.stream.Collectors.joining;
import java.util.Collection;
import com.kush.lib.expressions.Expression;
import com.kush.lib.expressions.clauses.InExpression;
class DefaultInExpression extends BaseExpression implements InExpression {
private final Expression targetExpr;
private final Collection<Expression> inExprs;
public DefaultInExpression(Expression targetExpr, Collection<Expression> inExprs) {
this.targetExpr = targetExpr;
this.inExprs = inExprs;
}
@Override
public Expression getTarget() {
return targetExpr;
}
@Override
public Collection<Expression> getInExpressions() {
return inExprs;
}
@Override
public String toString() {
return new StringBuilder()
.append(String.valueOf(getTarget()))
.append(" ").append("IN").append(" ")
.append("(")
.append(getInExpressions().stream()
.map(String::valueOf)
.collect(joining(", ")))
.append(")")
.toString();
}
}
|
package com.vietmedia365.voaapp.job;
import com.path.android.jobqueue.Job;
import com.path.android.jobqueue.Params;
import com.vietmedia365.voaapp.NewsApp;
import com.vietmedia365.voaapp.event.LoadArticleDetailEvent;
import com.vietmedia365.voaapp.model.Article;
import de.greenrobot.event.EventBus;
import retrofit.Callback;
import retrofit.RetrofitError;
import retrofit.client.Response;
/**
* Created by pat109 on 9/28/2014.
*/
public class LoadArticleDetailJob extends Job {
private String catUrl;
private String id;
public LoadArticleDetailJob(String catUrl, String id){
super(new Params(Priority.HIGH).requireNetwork().persist().groupBy("load_article_detail"));
this.id = id;
this.catUrl = catUrl;
}
@Override
public void onAdded() {
if("saved".equals(catUrl)){
Article article = NewsApp.getDbHandlerInstance().getSaved(id);
Article articleFav = NewsApp.getDbHandlerInstance().getFavorite(id);
boolean isFav = articleFav != null;
article.setFavorite(isFav);
article.setDownloaded(true);
EventBus.getDefault().post(new LoadArticleDetailEvent(article));
}
else{
NewsApp.getInstance().getArticleService().getArticle(id, new Callback<Article>() {
@Override
public void success(Article article, Response response) {
Article articleFav = NewsApp.getDbHandlerInstance().getFavorite(article.getId());
boolean isFav = articleFav != null;
article.setFavorite(isFav);
Article articleSaved = NewsApp.getDbHandlerInstance().getSaved(article.getId());
boolean isSaved = articleSaved != null;
article.setDownloaded(isSaved);
if(isSaved){
article.setLinkAudio(articleSaved.getDownloadUrl());
}
EventBus.getDefault().post(new LoadArticleDetailEvent(article));
}
@Override
public void failure(RetrofitError error) {
error.printStackTrace();
}
});
}
}
@Override
public void onRun() throws Throwable {
}
@Override
protected void onCancel() {
}
@Override
protected boolean shouldReRunOnThrowable(Throwable throwable) {
return false;
}
}
|
package me.mrmaurice.wc.function.imports;
public class ImportImages {
public ImportImages() {
// TODO Auto-generated constructor stub
}
}
|
package assemAssist.model.option.restrictions;
import java.util.Collection;
import java.util.List;
import assemAssist.model.option.VehicleOption;
/**
* A restriction with a certain {@link VehicleOption} which is a precondition
* and an operation that filters a given list of options.
*
* @author SWOP Group 3
* @version 3.0
*/
public abstract class Restriction {
/**
* Initialises this restriction with the given option as precondition.
*
* @param precondition
* The option that limits the possible options
* @throws IllegalArgumentException
* Thrown when the precondition is invalid
*/
public Restriction(VehicleOption precondition) throws IllegalArgumentException {
if (!isValidPrecondition(precondition)) {
throw new IllegalArgumentException("The given precondition is invalid.");
}
this.precondition = precondition;
}
/**
* Returns the option which is the precondition of this restriction.
*/
public final VehicleOption getPrecondition() {
return precondition;
}
/**
* Checks whether the given precondition is valid.
*
* @param precondition
* The option to check
* @return Returns true if and only if the given precondition is effective
*/
public final boolean isValidPrecondition(VehicleOption precondition) {
return precondition != null;
}
private final VehicleOption precondition;
/**
* Checks whether the given collection of options is valid.
*
* @param options
* The collection of options to check
* @return True if and only if the following conditions are met:<br>
* <ul>
* <li>the given list of options is effective
* <li>every option in the list is effective
* </ul>
*/
public final boolean isValidOptions(Collection<VehicleOption> options) {
if (options == null) {
return false;
}
for (VehicleOption option : options) {
if (option == null) {
return false;
}
}
return true;
}
/**
* Filters the given list of options by keeping / removing options which are
* in the list of options of this restriction when the precondition is met.
*
* @param chosen
* The collection of chosen options
* @param options
* The list of options to filter
* @return The list of options with only the options to be kept or without
* the options to be removed, depending on the type of restriction
* @throws IllegalArgumentException
* Thrown when one of the parameters is not valid
*/
public final List<VehicleOption> filter(Collection<VehicleOption> chosen,
List<VehicleOption> options) throws IllegalArgumentException {
if (!isValidOptions(chosen)) {
throw new IllegalArgumentException("The given list of chosen options is invalid.");
}
if (!isValidOptions(options)) {
throw new IllegalArgumentException("The given list of options to filter is invalid.");
}
return filterInverseRestriction(chosen, filterRestriction(chosen, options));
}
/**
* See the filter-method.
*/
protected abstract List<VehicleOption> filterRestriction(Collection<VehicleOption> chosen,
List<VehicleOption> options);
/**
* See the filter-method.
*/
protected abstract List<VehicleOption> filterInverseRestriction(
Collection<VehicleOption> chosen, List<VehicleOption> options);
@Override
public abstract int hashCode();
@Override
public abstract boolean equals(Object obj);
}
|
package ls.example.t.zero2line.base.rv;
import android.support.v7.widget.RecyclerView;
import android.util.SparseArray;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.View.OnLongClickListener;
/**
* <pre>
* author: Blankj
* blog : http://blankj.com
* time : 2017/08/22
* desc :
* </pre>
*/
public class ItemViewHolder extends RecyclerView.ViewHolder {
private SparseArray<View> viewArray = new SparseArray<>();
public ItemViewHolder(View itemView) {
super(itemView);
}
@SuppressWarnings("unchecked")
public <T extends View> T findViewById( final int viewId) {
View view = viewArray.get(viewId);
if (view == null) {
view = itemView.findViewById(viewId);
viewArray.put(viewId, view);
}
return (T) view;
}
public void setOnClickListener(final int viewId, OnClickListener listener) {
findViewById(viewId).setOnClickListener(listener);
}
public void setOnLongClickListener( final int viewId,OnLongClickListener listener) {
findViewById(viewId).setOnLongClickListener(listener);
}
}
|
package controllers;
import java.util.ArrayList;
import java.util.Collection;
import javax.servlet.http.HttpServletRequest;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.util.Assert;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.servlet.ModelAndView;
import services.ActorService;
import services.FolderService;
import services.MessageService;
import domain.Actor;
import domain.Folder;
import domain.Message;
@Controller
@RequestMapping("/message/actor")
public class MessageActorController extends AbstractController {
@Autowired
private MessageService messageService;
@Autowired
private ActorService actorService;
@Autowired
private FolderService folderService;
@RequestMapping(value = "/list", method = RequestMethod.GET)
public ModelAndView list(@RequestParam final int folderId) {
ModelAndView result;
final Folder f = this.folderService.findOne(folderId);
Assert.isTrue(this.actorService.findByPrincipal().getFolders().contains(f));
Assert.isTrue(!f.getMessages().isEmpty());
final Collection<Message> messages = f.getMessages();
result = new ModelAndView("message/list");
result.addObject("messages", messages);
return result;
}
@RequestMapping(value = "/create", method = RequestMethod.GET)
public ModelAndView create() {
ModelAndView result;
Message message;
message = this.messageService.create();
result = this.createEditModelAndView(message);
return result;
}
@RequestMapping(value = "/edit", method = RequestMethod.POST)
public ModelAndView save(@ModelAttribute("mess") final Message mess, final BindingResult binding) {
ModelAndView result;
for (final Actor a : mess.getRecipients())
Assert.notNull(a);
final Message message = this.messageService.reconstruct(mess, binding);
if (binding.hasErrors())
result = this.createEditModelAndView(message);
else
try {
final Folder outf = message.getFolder();
this.messageService.save(message);
result = new ModelAndView("redirect:list.do?folderId=" + outf.getId());
} catch (final Throwable oops) {
result = this.createEditModelAndView(message, "message.commit.error");
}
return result;
}
@RequestMapping(value = "/delete", method = RequestMethod.GET)
public ModelAndView delete(@RequestParam final int messageId) {
ModelAndView result;
final Message message = this.messageService.findOne(messageId);
final Folder toDelete = message.getFolder();
this.messageService.delete(message);
result = new ModelAndView("redirect:list.do?folderId=" + toDelete.getId());
return result;
}
@RequestMapping(value = "/move", method = RequestMethod.GET)
public ModelAndView move(@RequestParam final int messageId) {
ModelAndView result;
final Message message = this.messageService.findOne(messageId);
final Folder origin = message.getFolder();
final Collection<Folder> available = new ArrayList<Folder>(this.actorService.findByPrincipal().getFolders());
available.remove(origin);
result = new ModelAndView("message/move");
result.addObject("mess", message);
result.addObject("origin", origin);
result.addObject("folders", available);
return result;
}
@RequestMapping(value = "/moveToFolder", method = RequestMethod.POST)
public ModelAndView moveToFolder(final HttpServletRequest request) {
ModelAndView result;
final Message message = this.messageService.findOne(Integer.valueOf(request.getParameter("mess")));
final Folder target = this.folderService.findOne(Integer.valueOf(request.getParameter("target")));
Assert.notNull(target);
this.messageService.moveToFolder(message, target);
result = new ModelAndView("redirect:/message/actor/list.do?folderId=" + target.getId());
return result;
}
@RequestMapping(value = "/display", method = RequestMethod.GET)
public ModelAndView display(@RequestParam final int messageId) {
ModelAndView result;
final Message message = this.messageService.findOne(messageId);
final Collection<Folder> folders = new ArrayList<Folder>();
for (final Folder fl : this.actorService.findByPrincipal().getFolders())
folders.addAll(this.getAllAvailable(fl));
boolean found = false;
for (final Folder f : folders)
if (f.getMessages().contains(message)) {
found = true;
break;
}
Assert.isTrue(found);
result = new ModelAndView("message/display");
result.addObject("mess", message);
return result;
}
protected ModelAndView createEditModelAndView(final Message message) {
ModelAndView result;
result = this.createEditModelAndView(message, null);
return result;
}
protected ModelAndView createEditModelAndView(final Message message, final String messageCode) {
ModelAndView result;
final Collection<Actor> actors = this.actorService.findAll();
result = new ModelAndView("message/edit");
result.addObject("mess", message);
result.addObject("actors", actors);
result.addObject("message", messageCode);
return result;
}
private Collection<Folder> getAllAvailable(final Folder f) {
final Collection<Folder> res = new ArrayList<Folder>();
res.add(f);
if (!f.getChildren().isEmpty())
for (final Folder fc : f.getChildren())
res.addAll(this.getAllAvailable(fc));
return res;
}
}
|
package com.tencent.mm.plugin.appbrand.widget.input;
import android.view.View;
import android.view.ViewGroup;
import com.tencent.mm.plugin.appbrand.s.g;
import com.tencent.mm.plugin.appbrand.widget.input.ad.a;
class ad$1 extends a<ViewGroup, f> {
final /* synthetic */ ad gJm;
ad$1(ad adVar) {
this.gJm = adVar;
super((byte) 0);
}
final /* synthetic */ View ce(View view) {
return (f) view.findViewById(g.app_brand_page_input_container);
}
final boolean cd(View view) {
return view.getId() == g.app_brand_page_content;
}
}
|
package gs.mc.tools.models;
import org.neo4j.ogm.annotation.GraphId;
import org.neo4j.ogm.annotation.NodeEntity;
@NodeEntity
public class Module
{
@GraphId
private Long id;
private String groupId;
private String artifactId;
private String version;
private String description;
public Module()
{
}
public Long getId()
{
return id;
}
public String getDescription()
{
return description;
}
public String getGroupId()
{
return groupId;
}
public String getArtifactId()
{
return artifactId;
}
public String getVersion()
{
return version;
}
}
|
package com.harrymt.productivitymapping.services;
import android.service.notification.NotificationListenerService;
import android.service.notification.StatusBarNotification;
import android.util.Log;
import com.harrymt.productivitymapping.coredata.NotificationParts;
import com.harrymt.productivitymapping.database.DatabaseAdapter;
import com.harrymt.productivitymapping.PROJECT_GLOBALS;
/**
* Listens for notifications using the notification service.
*/
public class NotificationListener extends NotificationListenerService {
private static final String TAG = PROJECT_GLOBALS.LOG_NAME + "NotiListener";
/**
* Callback when a notification is posted.
* We decide if we want to block it and save it, or not.
*
* @param notification Notification that has been posted.
*/
@Override
public void onNotificationPosted(StatusBarNotification notification) {
String title = notification.getNotification().extras.getString("android.title");
Log.d(TAG, "Notification Found: " + title);
if (shouldWeBlockThisNotification(notification)) {
// Block notification from being posted to the phone
cancelNotification(notification.getKey());
// Save notification
saveNotification(notification);
Log.d(TAG, "Blocked notification: " + title);
} else {
if(PROJECT_GLOBALS.IS_DEBUG) Log.d(TAG, "Didn't block notification: " + title);
}
}
/**
* Decides if we should block the notification.
*
* @param sbn notification
* @return True if we should block the notification, false if not.
*/
public boolean shouldWeBlockThisNotification(StatusBarNotification sbn) {
if (!PROJECT_GLOBALS.STUDYING) {
return false;
}
NotificationParts notification = new NotificationParts(sbn.getNotification(), sbn.getPackageName());
// If a keyword matches, let it through
if (notification.containsKeywords(PROJECT_GLOBALS.CURRENT_ZONE.keywords)) {
// TODO keep track of # notifications received but not blocked based on keywords
return false;
}
// If it matches the package, block it
return notification.containsPackage(PROJECT_GLOBALS.CURRENT_ZONE.blockingApps);
}
/**
* Save the notification to the database.
*
* @param n notification to save.
*/
private void saveNotification(StatusBarNotification n) {
DatabaseAdapter dbAdapter = new DatabaseAdapter(this); // Open and prepare the database
dbAdapter.writeNotification(n);
dbAdapter.close();
}
} |
package com.tencent.mm.plugin.voip.model.a;
import com.tencent.mm.ab.e;
import com.tencent.mm.ab.l;
import com.tencent.mm.model.au;
import com.tencent.mm.plugin.voip.b.a;
import com.tencent.mm.protocal.c.bza;
import com.tencent.mm.protocal.c.caf;
import com.tencent.mm.sdk.platformtools.x;
import java.nio.ByteBuffer;
import java.nio.ByteOrder;
class b$1 implements e {
final /* synthetic */ b oNR;
b$1(b bVar) {
this.oNR = bVar;
}
public final void a(int i, int i2, String str, l lVar) {
a.eU(this.oNR.TAG, "Anwser response:" + i + " errCode:" + i2 + " status:" + this.oNR.oKs.mStatus);
if (this.oNR.oKs.mStatus == 1) {
a.eU(this.oNR.TAG, "reject ok!");
} else if (this.oNR.oKs.mStatus != 4) {
a.eT(this.oNR.TAG, "Anwser response not within WAITCONNECT, ignored.");
} else if (i == 0) {
bza bza = (bza) this.oNR.bLq();
this.oNR.oKs.oJX.kpo = bza.rxG;
this.oNR.oKs.oJX.kpp = bza.rxH;
this.oNR.oKs.oJX.kpw = bza.suP;
this.oNR.oKs.oJX.oOP = bza.svc;
this.oNR.oKs.oJX.oOQ = bza.svd;
this.oNR.oKs.oJX.oOR = bza.sve;
this.oNR.oKs.oJX.oOS = bza.svf;
this.oNR.oKs.oJX.oOU = bza.svh;
this.oNR.oKs.oJX.oOT = bza.svm;
this.oNR.oKs.oJX.oOu = bza.suT;
this.oNR.oKs.oJX.oOW = bza.svo;
this.oNR.oKs.yB(bza.suR);
this.oNR.oKs.oJX.oOv = bza.suU;
if (bza.suV.siI >= 12) {
ByteBuffer wrap = ByteBuffer.wrap(bza.suV.siK.toByteArray(), 8, 4);
ByteOrder nativeOrder = ByteOrder.nativeOrder();
ByteOrder order = wrap.order();
int i3 = wrap.getInt();
a.eV(this.oNR.TAG, "steve:nSvrBaseBRTuneRatio1:" + i3 + ", nativeOrder:" + nativeOrder + ", bbOrder:" + order);
this.oNR.oKs.oJX.oOV = i3;
}
a.eU(this.oNR.TAG, "onAnwserResp: audioTsdfBeyond3G = " + this.oNR.oKs.oJX.oOP + ",audioTsdEdge = " + this.oNR.oKs.oJX.oOQ + ",passthroughQosAlgorithm = " + this.oNR.oKs.oJX.oOR + ",fastPlayRepair = " + this.oNR.oKs.oJX.oOS + ", audioDtx = " + this.oNR.oKs.oJX.oOU + ", switchtcppktCnt=" + this.oNR.oKs.oJX.oOt + ", SvrCfgListV=" + this.oNR.oKs.oJX.oOT + ", setMaxBRForRelay=" + this.oNR.oKs.oJX.oOW + ", RedirectreqThreshold=" + bza.suQ.sww + ", BothSideSwitchFlag=" + bza.suQ.swx + ", WifiScanInterval=" + bza.suU + ", BaseBRTuneRatio=" + this.oNR.oKs.oJX.oOV);
this.oNR.oKs.oJX.oOX = bza.svl;
this.oNR.oKs.oJX.oOY = bza.svp;
a.eU(this.oNR.TAG, "answerResp AudioAecMode5 = " + this.oNR.oKs.oJX.oOX);
this.oNR.oKs.oJx = true;
a.eU(this.oNR.TAG, "answer ok, roomid =" + this.oNR.oKs.oJX.kpo + ",memberid = " + this.oNR.oKs.oJX.kpw);
caf caf = bza.suQ;
if (caf.kpK > 0) {
caf.kpK--;
a.eU(this.oNR.TAG, "zhengxue[ENCRYPT] got encryptStrategy[" + caf.kpK + "] from answerresp relaydata");
} else {
caf.kpK = 1;
a.eU(this.oNR.TAG, "zhengxue[LOGIC]:got no EncryptStrategy in answerresp mrdata");
}
a.eU(this.oNR.TAG, "answer with relayData peerid.length =" + caf.suK.rfy.siI);
a.eU(this.oNR.TAG, "answer with relayData capinfo.length =" + caf.suL.rfy.siI);
this.oNR.oKs.yA(caf.swb);
try {
au.Em().H(new 1(this, caf));
} catch (Exception e) {
x.e(this.oNR.TAG, "get proxy ip fail..");
}
} else if (i == 4) {
this.oNR.oKs.oJX.oPS.oKQ = 12;
this.oNR.oKs.oJX.oPS.oKR = i2;
this.oNR.oKs.o(1, i2, "");
} else {
this.oNR.oKs.oJX.oPS.oKQ = 12;
this.oNR.oKs.oJX.oPS.oKR = i2;
this.oNR.oKs.o(1, -9004, "");
}
}
}
|
package datastructures.unionfind;
import java.util.HashMap;
import java.util.Map;
import java.util.Set;
public class GenericUnionFind<T> {
private int[] parent;
private int[] size;
private int noOfcomponents;
private int n;
private Map<T, Integer> map;
// Initializing the data structure
public GenericUnionFind (int n, Set<T> nodes) {
parent = new int[n];
size = new int[n];
this.n = n;
this.noOfcomponents = n;
this.map = new HashMap<>(n); // as we know the maximum number of elements then we can initialize with the number of elements to prevent re-hashing
int count = 0;
for (T t : nodes) {
map.put(t, count++);
}
// At first all the nodes are parents to itself
// At first all the node's size is 1
for (int i=0; i<n; i++) {
parent[i] = i;
size[i] = 1;
}
}
public int noOfElements () {
return this.n;
}
public int getNoOfComponents () {
return this.noOfcomponents;
}
public int find(int target) {
int root = parent[target];
while (root != target) {
root = parent[root];
}
// Path Comparession
while (target != root) {
int temp = parent[target];
parent[target] = root;
target = temp;
}
return root;
}
public boolean isConnected (int p, int q) {
return find(p) == find(q);
}
public void union (int p, int q) {
if (isConnected(p, q))
return;
int parent1 = find(p);
int parent2 = find(q);
if (size[parent1] < size[parent2]) {
size[parent2] = size[parent2] + size[parent1];
parent[parent1] = parent2;
} else {
size[parent1] = size[parent2] + size[parent1];
parent[parent2] = parent1;
}
noOfcomponents--;
}
} |
package ch.ubx.startlist.client;
import com.google.gwt.i18n.client.TimeZone;
import com.google.gwt.i18n.client.DateTimeFormat;
import com.google.gwt.user.datepicker.client.DateBox;
import com.google.gwt.user.datepicker.client.DateBox.DefaultFormat;
public interface TimeFormat {
public static final DefaultFormat MM_HH_FORMAT = new DateBox.DefaultFormat(DateTimeFormat.getFormat("HHmm"));
public static final DefaultFormat DD_MMM_YYYY_FORMAT = new DateBox.DefaultFormat(DateTimeFormat.getFormat("dd.MM.yyyy"));
public static final DateTimeFormat DATE_FORMAT = DateTimeFormat.getFormat("dd.MM");
public static final DateTimeFormat TIME_FORMAT_TABLE = DateTimeFormat.getFormat("HH:mm");
public static final TimeZone timeZone = TimeZone.createTimeZone(-120); // TODO - why?
} |
package com.orca.page.objects;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.support.FindBy;
import org.openqa.selenium.support.PageFactory;
public class Comments extends BasePageObject {
protected WebDriver driver;
public Comments(WebDriver driver) {
this.driver = driver;
PageFactory.initElements(driver, this);
}
@FindBy(id="surveyComments")
private WebElement surveyComments;
@FindBy(xpath="//*[@id='survey']/input[2]")
private WebElement finishSurvey;
public EvaluationSummary finishSurvey() {
surveyComments.sendKeys("Lorem ipsum dolor sit amet, consectetur adipiscing elit. ");
finishSurvey.click();
return new EvaluationSummary(driver);
}
}
|
package com.lqs.hrm.mapper;
import com.lqs.hrm.entity.PositionLevel;
import com.lqs.hrm.entity.PositionLevelExample;
import java.util.List;
import org.apache.ibatis.annotations.Param;
public interface PositionLevelMapper {
/**
* This method was generated by MyBatis Generator.
* This method corresponds to the database table position_level
*
* @mbg.generated Mon May 25 00:12:01 CST 2020
*/
long countByExample(PositionLevelExample example);
/**
* This method was generated by MyBatis Generator.
* This method corresponds to the database table position_level
*
* @mbg.generated Mon May 25 00:12:01 CST 2020
*/
int deleteByExample(PositionLevelExample example);
/**
* This method was generated by MyBatis Generator.
* This method corresponds to the database table position_level
*
* @mbg.generated Mon May 25 00:12:01 CST 2020
*/
int deleteByPrimaryKey(Integer plId);
/**
* This method was generated by MyBatis Generator.
* This method corresponds to the database table position_level
*
* @mbg.generated Mon May 25 00:12:01 CST 2020
*/
int insert(PositionLevel record);
/**
* This method was generated by MyBatis Generator.
* This method corresponds to the database table position_level
*
* @mbg.generated Mon May 25 00:12:01 CST 2020
*/
int insertSelective(PositionLevel record);
/**
* This method was generated by MyBatis Generator.
* This method corresponds to the database table position_level
*
* @mbg.generated Mon May 25 00:12:01 CST 2020
*/
List<PositionLevel> selectByExample(PositionLevelExample example);
/**
* This method was generated by MyBatis Generator.
* This method corresponds to the database table position_level
*
* @mbg.generated Mon May 25 00:12:01 CST 2020
*/
PositionLevel selectByPrimaryKey(Integer plId);
/**
* This method was generated by MyBatis Generator.
* This method corresponds to the database table position_level
*
* @mbg.generated Mon May 25 00:12:01 CST 2020
*/
int updateByExampleSelective(@Param("record") PositionLevel record, @Param("example") PositionLevelExample example);
/**
* This method was generated by MyBatis Generator.
* This method corresponds to the database table position_level
*
* @mbg.generated Mon May 25 00:12:01 CST 2020
*/
int updateByExample(@Param("record") PositionLevel record, @Param("example") PositionLevelExample example);
/**
* This method was generated by MyBatis Generator.
* This method corresponds to the database table position_level
*
* @mbg.generated Mon May 25 00:12:01 CST 2020
*/
int updateByPrimaryKeySelective(PositionLevel record);
/**
* This method was generated by MyBatis Generator.
* This method corresponds to the database table position_level
*
* @mbg.generated Mon May 25 00:12:01 CST 2020
*/
int updateByPrimaryKey(PositionLevel record);
} |
package com.jonathan.user.Services;
import com.jonathan.user.Domain.Model.User;
import com.jonathan.user.Domain.Model.UserRepository;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
@Service
public class FindUserByIdService {
private UserRepository userRepository;
@Autowired
public FindUserByIdService(UserRepository userRepository) {
this.userRepository = userRepository;
}
public User execute(Integer id) {
return userRepository.findById(id);
}
}
|
package com.cse308.sbuify.album;
import com.cse308.sbuify.artist.Artist;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
import org.springframework.data.jpa.repository.Query;
import org.springframework.data.repository.PagingAndSortingRepository;
import org.springframework.data.repository.query.Param;
import java.util.List;
public interface AlbumRepository extends PagingAndSortingRepository<Album, Integer> {
@Query(value = "SELECT a.*" +
" FROM album a, album_songs sa, song_genres sg, song s" +
" WHERE a.id = sa.album_id" +
" AND sa.song_id = s.id" +
" AND s.id = sg.song_id" +
" AND sg.genre_id = ?1" +
" GROUP BY a.id" +
" ORDER BY SUM(s.play_count) DESC" +
" LIMIT ?2", nativeQuery = true)
List<Album> findPopularAlbumsByGenreId(Integer id, int numAlbums);
@Query(value = "SELECT a.*" +
" FROM album a, album_songs sa, song_genres sg" +
" WHERE a.id = sa.album_id" +
" AND sa.song_id = sg.song_id" +
" AND sg.genre_id = ?1" +
" GROUP BY a.id" +
" ORDER BY a.release_date DESC" +
" LIMIT ?2", nativeQuery = true)
List<Album> findRecentAlbumsByGenreId(Integer id, int numAlbums);
@Query(
value = "SELECT * FROM album a ORDER BY release_date DESC \n-- #pageable\n",
countQuery = "SELECT COUNT(*) FROM album a ORDER BY release_date DESC",
nativeQuery = true
)
Page<Album> findRecent(Pageable page);
@Query(
value = "SELECT * FROM album WHERE id IN (" +
" SELECT DISTINCT s.album_id" +
" FROM song s, customer c, playlist_songs ps" +
" WHERE ps.playlist_id = c.library_id" +
" AND ps.song_id = s.id" +
" AND c.id = :customerId" +
")\n-- #pageable\n",
countQuery = "SELECT COUNT(*) FROM album WHERE id IN (" +
" SELECT DISTINCT s.album_id" +
" FROM song s, customer c, playlist_songs ps" +
" WHERE ps.playlist_id = c.library_id" +
" AND ps.song_id = s.id" +
" AND c.id = :customerId" +
")",
nativeQuery = true
)
Page<Album> getSavedByCustomerId(@Param("customerId") Integer customerId, Pageable pageable);
@Query(value = "SELECT COUNT(ps.song_id) = a.num_songs " +
"FROM album a, album_songs aso, playlist_songs ps, customer c " +
"WHERE ps.playlist_id = c.library_id" +
" AND aso.song_id = ps.song_id" +
" AND aso.album_id = a.id" +
" AND a.id = ?2" +
" AND c.id = ?1", nativeQuery = true)
Integer isSavedByUser(Integer userId, Integer albumId);
@Query(
value = "SELECT a.* FROM album a, song s, stream st " +
"WHERE s.id = st.song_id " +
"AND s.album_id = a.id " +
"AND st.customer_id = :customerId " +
"GROUP BY a.id " +
"ORDER BY MAX(st.time) DESC\n -- #pageable\n",
countQuery = "SELECT COUNT(a.id) FROM album a, song s, stream st " +
"WHERE s.id = st.song_id " +
"AND s.album_id = a.id " +
"AND st.customer_id = :customerId " +
"GROUP BY a.id",
nativeQuery = true
)
Page<Album> getRecentlyPlayedByCustomer(@Param("customerId") Integer customerId, Pageable pageable);
List<Album> getAlbumsByArtist(Artist artist);
}
|
package com.simonk.gui.dataproviders;
public interface DataProvider {
String fullname();
String address();
String email();
}
|
package com.practice;
public class Rotation {
public static void main(String[] args) {
String a = "apple";
String b = "elppa";
System.out.println("Is "+a+ " rotation of "+ b + " : " + (rotation(a,b)==true? "Yes" : "No"));
}
public static boolean rotation(String a, String b){
char [] c1 = a.toCharArray();
char [] c2 = b.toCharArray();
int len;
if(c1.length != c2.length){
return false;
}else{
len = c1.length;
}
for (int i = 0; i<len; i++){
if(c1[i]!=c2[--len]){
return false;
}
}
return true;
}
}
|
package com.rofour.baseball.dao.order.mapper;
import java.util.List;
import com.rofour.baseball.dao.order.bean.TbTaskSub;
import javax.inject.Named;
@Named("tbTaskSubMapper")
public interface TbTaskSubMapper {
int deleteByPrimaryKey(Long taskSubId);
int stopByPrimaryKey(Long taskSubId);
int insert(TbTaskSub record);
int insertSelective(TbTaskSub record);
TbTaskSub selectByPrimaryKey(Long taskSubId);
List<TbTaskSub> selectByTask(TbTaskSub record);
List<TbTaskSub> selectByTaskAndCollege(TbTaskSub record);
int updateByPrimaryKeySelective(TbTaskSub record);
int updateByPrimaryKey(TbTaskSub record);
} |
package CloudSharing;
public interface File {
/**
* Retorna a dimensao do ficheiro.
*
* @return - Dimensao do ficheiro.
*/
int getSize();
/**
* Retorna o nome do dono do ficheiro.
*
* @return - Nome do dono do ficheiro
*/
String getOwner();
/**
* Retorna o nome do ficheiro.
*
* @return - Objeto - String nome do ficheiro.
*/
String getName();
}
|
package fr.tenebrae.MMOCore.Utils;
import net.minecraft.server.v1_9_R1.Block;
import net.minecraft.server.v1_9_R1.BlockPosition;
import net.minecraft.server.v1_9_R1.PacketPlayOutBlockAction;
import org.bukkit.Location;
import org.bukkit.Material;
import org.bukkit.craftbukkit.v1_9_R1.entity.CraftPlayer;
import org.bukkit.entity.Player;
public class BlockAnimationAPI {
private static boolean openChest(Location loc, Player... players) {
try {
BlockPosition pos = new BlockPosition(loc.getBlockX(), loc.getBlockY(), loc.getBlockZ());
Block block = Block.getByName((loc.getBlock().getType() == Material.CHEST ? "chest" : (loc.getBlock().getType() == Material.TRAPPED_CHEST ? "trapped_chest" : "ender_chest")));
PacketPlayOutBlockAction packet = new PacketPlayOutBlockAction(pos, block, 1, 1);
for (Player p : players) ((CraftPlayer)p).getHandle().playerConnection.sendPacket(packet);
return true;
} catch (Exception e) {
e.printStackTrace();
return false;
}
}
private static boolean openChest(Location loc) {
try {
BlockPosition pos = new BlockPosition(loc.getBlockX(), loc.getBlockY(), loc.getBlockZ());
Block block = Block.getByName((loc.getBlock().getType() == Material.CHEST ? "chest" : (loc.getBlock().getType() == Material.TRAPPED_CHEST ? "trapped_chest" : "ender_chest")));
PacketPlayOutBlockAction packet = new PacketPlayOutBlockAction(pos, block, 1, 1);
for (Player p : loc.getWorld().getPlayers()) ((CraftPlayer)p).getHandle().playerConnection.sendPacket(packet);
return true;
} catch (Exception e) {
e.printStackTrace();
return false;
}
}
private static boolean closeChest(Location loc, Player... players) {
try {
BlockPosition pos = new BlockPosition(loc.getBlockX(), loc.getBlockY(), loc.getBlockZ());
Block block = Block.getByName((loc.getBlock().getType() == Material.CHEST ? "chest" : (loc.getBlock().getType() == Material.TRAPPED_CHEST ? "trapped_chest" : "ender_chest")));
PacketPlayOutBlockAction packet = new PacketPlayOutBlockAction(pos, block, 1, 0);
for (Player p : players) ((CraftPlayer)p).getHandle().playerConnection.sendPacket(packet);
return true;
} catch (Exception e) {
e.printStackTrace();
return false;
}
}
private static boolean closeChest(Location loc) {
try {
BlockPosition pos = new BlockPosition(loc.getBlockX(), loc.getBlockY(), loc.getBlockZ());
Block block = Block.getByName((loc.getBlock().getType() == Material.CHEST ? "chest" : (loc.getBlock().getType() == Material.TRAPPED_CHEST ? "trapped_chest" : "ender_chest")));
PacketPlayOutBlockAction packet = new PacketPlayOutBlockAction(pos, block, 1, 0);
for (Player p : loc.getWorld().getPlayers()) ((CraftPlayer)p).getHandle().playerConnection.sendPacket(packet);
return true;
} catch (Exception e) {
e.printStackTrace();
return false;
}
}
private static boolean extendPiston(Location loc, int directionId, Player... players) {
try {
BlockPosition pos = new BlockPosition(loc.getBlockX(), loc.getBlockY(), loc.getBlockZ());
Block block = Block.getByName((loc.getBlock().getType() == Material.PISTON_BASE ? "piston" : "sticky_piston"));
PacketPlayOutBlockAction packet = new PacketPlayOutBlockAction(pos, block, 0, directionId);
for (Player p : players) ((CraftPlayer)p).getHandle().playerConnection.sendPacket(packet);
return true;
} catch (Exception e) {
e.printStackTrace();
return false;
}
}
private static boolean extendPiston(Location loc, int directionId) {
try {
BlockPosition pos = new BlockPosition(loc.getBlockX(), loc.getBlockY(), loc.getBlockZ());
Block block = Block.getByName((loc.getBlock().getType() == Material.PISTON_BASE ? "piston" : "sticky_piston"));
PacketPlayOutBlockAction packet = new PacketPlayOutBlockAction(pos, block, 0, directionId);
for (Player p : loc.getWorld().getPlayers()) ((CraftPlayer)p).getHandle().playerConnection.sendPacket(packet);
return true;
} catch (Exception e) {
e.printStackTrace();
return false;
}
}
private static boolean retractPiston(Location loc, int directionId, Player... players) {
try {
BlockPosition pos = new BlockPosition(loc.getBlockX(), loc.getBlockY(), loc.getBlockZ());
Block block = Block.getByName((loc.getBlock().getType() == Material.PISTON_BASE ? "piston" : "sticky_piston"));
PacketPlayOutBlockAction packet = new PacketPlayOutBlockAction(pos, block, 1, directionId);
for (Player p : players) ((CraftPlayer)p).getHandle().playerConnection.sendPacket(packet);
return true;
} catch (Exception e) {
e.printStackTrace();
return false;
}
}
private static boolean retractPiston(Location loc, int directionId) {
try {
BlockPosition pos = new BlockPosition(loc.getBlockX(), loc.getBlockY(), loc.getBlockZ());
Block block = Block.getByName((loc.getBlock().getType() == Material.PISTON_BASE ? "piston" : "sticky_piston"));
PacketPlayOutBlockAction packet = new PacketPlayOutBlockAction(pos, block, 1, directionId);
for (Player p : loc.getWorld().getPlayers()) ((CraftPlayer)p).getHandle().playerConnection.sendPacket(packet);
return true;
} catch (Exception e) {
e.printStackTrace();
return false;
}
}
private static boolean playNote(Location loc, int instrumentId, int notePitch, Player... players) {
try {
BlockPosition pos = new BlockPosition(loc.getBlockX(), loc.getBlockY(), loc.getBlockZ());
Block block = Block.getByName("noteblock");
PacketPlayOutBlockAction packet = new PacketPlayOutBlockAction(pos, block, instrumentId, notePitch);
for (Player p : players) ((CraftPlayer)p).getHandle().playerConnection.sendPacket(packet);
return true;
} catch (Exception e) {
e.printStackTrace();
return false;
}
}
private static boolean playNote(Location loc, int instrumentId, int notePitch) {
try {
BlockPosition pos = new BlockPosition(loc.getBlockX(), loc.getBlockY(), loc.getBlockZ());
Block block = Block.getByName("noteblock");
PacketPlayOutBlockAction packet = new PacketPlayOutBlockAction(pos, block, instrumentId, notePitch);
for (Player p : loc.getWorld().getPlayers()) ((CraftPlayer)p).getHandle().playerConnection.sendPacket(packet);
return true;
} catch (Exception e) {
e.printStackTrace();
return false;
}
}
public static boolean noteblock(Location loc, NoteInstrument instrument, int notePitch, Player... players) {
if (loc.getBlock().getType() != Material.NOTE_BLOCK) throw new IllegalArgumentException("Block at given location isn't an instance of a noteblock.");
return playNote(loc, instrument.id, notePitch, players);
}
public static boolean noteblock(Location loc, NoteInstrument instrument, int notePitch) {
if (loc.getBlock().getType() != Material.NOTE_BLOCK) throw new IllegalArgumentException("Block at given location isn't an instance of a noteblock.");
return playNote(loc, instrument.id, notePitch);
}
public static boolean piston(Location loc, PistonAnimation anim, PistonDirection direction, Player... players) {
if (loc.getBlock().getType() != Material.PISTON_BASE && loc.getBlock().getType() != Material.PISTON_STICKY_BASE) throw new IllegalArgumentException("Block at given location isn't an instance of a piston.");
switch(anim) {
case EXTEND:
return extendPiston(loc, direction.id, players);
case RETRACT:
return retractPiston(loc, direction.id, players);
default:
return false;
}
}
public static boolean piston(Location loc, PistonAnimation anim, PistonDirection direction) {
if (loc.getBlock().getType() != Material.PISTON_BASE && loc.getBlock().getType() != Material.PISTON_STICKY_BASE) throw new IllegalArgumentException("Block at given location isn't an instance of a piston.");
switch(anim) {
case EXTEND:
return extendPiston(loc, direction.id);
case RETRACT:
return retractPiston(loc, direction.id);
default:
return false;
}
}
public static boolean chest(Location loc, ChestAnimation anim, Player... players) {
if (loc.getBlock().getType() != Material.CHEST && loc.getBlock().getType() != Material.ENDER_CHEST && loc.getBlock().getType() != Material.TRAPPED_CHEST) throw new IllegalArgumentException("Block at given location isn't an instance of a chest.");
switch(anim) {
case OPEN:
return openChest(loc, players);
case CLOSE:
return closeChest(loc, players);
default:
return false;
}
}
public static boolean chest(Location loc, ChestAnimation anim) {
if (loc.getBlock().getType() != Material.CHEST && loc.getBlock().getType() != Material.ENDER_CHEST && loc.getBlock().getType() != Material.TRAPPED_CHEST) throw new IllegalArgumentException("Block at given location isn't an instance of a chest.");
switch(anim) {
case OPEN:
return openChest(loc);
case CLOSE:
return closeChest(loc);
default:
return false;
}
}
public enum NoteInstrument {
HARP(0),
DOUBLE_BASS(1),
SNARE_DRUM(2),
CLICK(3),
BASS_DRUM(4);
int id;
private NoteInstrument(int id) { this.id = id; }
}
public enum PistonDirection {
DOWN(0),
UP(1),
SOUTH(2),
WEST(3),
NORTH(4),
EAST(5);
public int id;
private PistonDirection(int id) { this.id = id; }
}
public enum PistonAnimation {
EXTEND,
RETRACT;
}
public enum ChestAnimation {
OPEN,
CLOSE;
}
}
|
package com.java.app.beans;
import java.util.Date;
public class ServerConfigDO
{
private Integer id;
private String sFromMailId;
private String sFromMailPassword;
private String sSMTPHostName;
private String sSMTPHostNumber;
private String sSMTPAuth;
private String sSMTPDebug;
private String sSMTPStartTls;
private String sSMTPMechanisms;
private Integer iTimeout;
private Date dMaintainStartDate;
private Date dMaintainEndDate;
private Integer iQuestions_Timeout;
private Integer iTotalSurveyTime;
private String sCreatedBy;
private Date dCreatedDate;
private String sUpdatedBy;
private Date dUpdatedDate;
public ServerConfigDO() {}
public ServerConfigDO(Integer id)
{
this.id = id;
}
/**
* @return the id
*/
public Integer getId() {
return id;
}
/**
* @param id the id to set
*/
public void setId(Integer id) {
this.id = id;
}
/**
* @return the sFromMailId
*/
public String getsFromMailId() {
return sFromMailId;
}
/**
* @param sFromMailId the sFromMailId to set
*/
public void setsFromMailId(String sFromMailId) {
this.sFromMailId = sFromMailId;
}
/**
* @return the sFromMailPassword
*/
public String getsFromMailPassword() {
return sFromMailPassword;
}
/**
* @param sFromMailPassword the sFromMailPassword to set
*/
public void setsFromMailPassword(String sFromMailPassword) {
this.sFromMailPassword = sFromMailPassword;
}
/**
* @return the sSMTPHostName
*/
public String getsSMTPHostName() {
return sSMTPHostName;
}
/**
* @param sSMTPHostName the sSMTPHostName to set
*/
public void setsSMTPHostName(String sSMTPHostName) {
this.sSMTPHostName = sSMTPHostName;
}
/**
* @return the sSMTPHostNumber
*/
public String getsSMTPHostNumber() {
return sSMTPHostNumber;
}
/**
* @param sSMTPHostNumber the sSMTPHostNumber to set
*/
public void setsSMTPHostNumber(String sSMTPHostNumber) {
this.sSMTPHostNumber = sSMTPHostNumber;
}
/**
* @return the sSMTPAuth
*/
public String getsSMTPAuth() {
return sSMTPAuth;
}
/**
* @param sSMTPAuth the sSMTPAuth to set
*/
public void setsSMTPAuth(String sSMTPAuth) {
this.sSMTPAuth = sSMTPAuth;
}
/**
* @return the sSMTPDebug
*/
public String getsSMTPDebug() {
return sSMTPDebug;
}
/**
* @param sSMTPDebug the sSMTPDebug to set
*/
public void setsSMTPDebug(String sSMTPDebug) {
this.sSMTPDebug = sSMTPDebug;
}
/**
* @return the sSMTPStartTls
*/
public String getsSMTPStartTls() {
return sSMTPStartTls;
}
/**
* @param sSMTPStartTls the sSMTPStartTls to set
*/
public void setsSMTPStartTls(String sSMTPStartTls) {
this.sSMTPStartTls = sSMTPStartTls;
}
/**
* @return the sSMTPMechanisms
*/
public String getsSMTPMechanisms() {
return sSMTPMechanisms;
}
/**
* @param sSMTPMechanisms the sSMTPMechanisms to set
*/
public void setsSMTPMechanisms(String sSMTPMechanisms) {
this.sSMTPMechanisms = sSMTPMechanisms;
}
/**
* @return the iTimeout
*/
public Integer getiTimeout() {
return iTimeout;
}
/**
* @param iTimeout the iTimeout to set
*/
public void setiTimeout(Integer iTimeout) {
this.iTimeout = iTimeout;
}
/**
* @return the dMaintainStartDate
*/
public Date getdMaintainStartDate() {
return dMaintainStartDate;
}
/**
* @param dMaintainStartDate the dMaintainStartDate to set
*/
public void setdMaintainStartDate(Date dMaintainStartDate) {
this.dMaintainStartDate = dMaintainStartDate;
}
/**
* @return the dMaintainEndDate
*/
public Date getdMaintainEndDate() {
return dMaintainEndDate;
}
/**
* @param dMaintainEndDate the dMaintainEndDate to set
*/
public void setdMaintainEndDate(Date dMaintainEndDate) {
this.dMaintainEndDate = dMaintainEndDate;
}
/**
* @return the iQuestions_Timeout
*/
public Integer getiQuestions_Timeout() {
return iQuestions_Timeout;
}
/**
* @param iQuestions_Timeout the iQuestions_Timeout to set
*/
public void setiQuestions_Timeout(Integer iQuestions_Timeout) {
this.iQuestions_Timeout = iQuestions_Timeout;
}
/**
* @return the iTotalSurveyTime
*/
public Integer getiTotalSurveyTime() {
return iTotalSurveyTime;
}
/**
* @param iTotalSurveyTime the iTotalSurveyTime to set
*/
public void setiTotalSurveyTime(Integer iTotalSurveyTime) {
this.iTotalSurveyTime = iTotalSurveyTime;
}
/**
* @return the sCreatedBy
*/
public String getsCreatedBy() {
return sCreatedBy;
}
/**
* @param sCreatedBy the sCreatedBy to set
*/
public void setsCreatedBy(String sCreatedBy) {
this.sCreatedBy = sCreatedBy;
}
/**
* @return the dCreatedDate
*/
public Date getdCreatedDate() {
return dCreatedDate;
}
/**
* @param dCreatedDate the dCreatedDate to set
*/
public void setdCreatedDate(Date dCreatedDate) {
this.dCreatedDate = dCreatedDate;
}
/**
* @return the sUpdatedBy
*/
public String getsUpdatedBy() {
return sUpdatedBy;
}
/**
* @param sUpdatedBy the sUpdatedBy to set
*/
public void setsUpdatedBy(String sUpdatedBy) {
this.sUpdatedBy = sUpdatedBy;
}
/**
* @return the dUpdatedDate
*/
public Date getdUpdatedDate() {
return dUpdatedDate;
}
/**
* @param dUpdatedDate the dUpdatedDate to set
*/
public void setdUpdatedDate(Date dUpdatedDate) {
this.dUpdatedDate = dUpdatedDate;
}
}
|
package View;
import java.awt.BorderLayout;
import java.awt.EventQueue;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.border.EmptyBorder;
import controller.ConnexionMySql;
import javax.swing.JLabel;
import javax.swing.JOptionPane;
import javax.swing.JButton;
import java.awt.Font;
import java.awt.Label;
import java.awt.TextArea;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.*;
import javax.swing.JTextField;
import javax.swing.JTextArea;
import java.awt.event.ActionListener;
import java.awt.event.ActionEvent;
import javax.swing.JScrollPane;
import java.awt.Color;
import java.awt.SystemColor;
import javax.swing.ImageIcon;
import java.awt.Window.Type;
public class Pv extends JFrame {
private JPanel contentPane;
private JTextField textField;
private JTextField textField_1;
private JTextField textField_2;
private JTextField textField_3;
private JTextField textField_5;
Connection cnx = null;
PreparedStatement prepared = null;
ResultSet resultat = null;
/**
* Launch the application.
*/
/**public static void main(String[] args) {
EventQueue.invokeLater(new Runnable() {
public void run() {
try {
Pv frame = new Pv();
frame.setVisible(true);
} catch (Exception e) {
e.printStackTrace();
}
}
});
}**/
/**
* Create the frame.
*/
public Pv() {
setType(Type.UTILITY);
setTitle("Pv");
setBackground(SystemColor.activeCaption);
setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
setBounds(100, 100, 800, 500);
cnx = ConnexionMySql.connexiondb();
contentPane = new JPanel();
contentPane.setBackground(SystemColor.activeCaption);
contentPane.setBorder(new EmptyBorder(5, 5, 5, 5));
setContentPane(contentPane);
contentPane.setLayout(null);
JLabel lblNumroPv = new JLabel("Num\u00E9ro pv:");
lblNumroPv.setFont(new Font("Tahoma", Font.BOLD, 15));
lblNumroPv.setBounds(91, 24, 96, 23);
contentPane.add(lblNumroPv);
JLabel lblTitre = new JLabel("AnimReunion");
lblTitre.setFont(new Font("Tahoma", Font.BOLD, 15));
lblTitre.setBounds(91, 67, 110, 14);
contentPane.add(lblTitre);
JLabel lblOrdreDuJour = new JLabel("Ordre du jour:");
lblOrdreDuJour.setFont(new Font("Tahoma", Font.BOLD, 15));
lblOrdreDuJour.setBounds(91, 110, 110, 14);
contentPane.add(lblOrdreDuJour);
JLabel lblHeureLeve = new JLabel("Heure lev\u00E9e:");
lblHeureLeve.setFont(new Font("Tahoma", Font.BOLD, 15));
lblHeureLeve.setBounds(91, 152, 96, 14);
contentPane.add(lblHeureLeve);
JTextArea textArea = new JTextArea();
textArea.setBounds(173, 206, 542, 89);
contentPane.add(textArea);
JLabel lblSignature = new JLabel("Signature:");
lblSignature.setFont(new Font("Tahoma", Font.BOLD, 15));
lblSignature.setBounds(67, 318, 96, 14);
contentPane.add(lblSignature);
JButton btnValider = new JButton("valider");
btnValider.setFont(new Font("Tahoma", Font.BOLD, 15));
btnValider.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent arg0) {
/**
* @param sql ajouter valeur a pv;
*/
String sql = "insert into pv (id_pv,ordre_du_jour,heure_levee,resume,signature,AnimReunion) values(?,?,?,?,?,?)";
try {
prepared = cnx.prepareStatement(sql);
prepared.setString(1, textField.getText().toString());
prepared.setString(6, textField_1.getText().toString());
prepared.setString(2, textField_2.getText().toString());
prepared.setString(3, textField_3.getText().toString());
prepared.setString(5, textField_5.getText().toString());
prepared.setString(4,textArea.getText().toString());
prepared.execute();
JOptionPane.showMessageDialog(null, "Pv ajouté");
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
});
btnValider.setBounds(626, 408, 89, 23);
contentPane.add(btnValider);
textField = new JTextField();
textField.setBounds(246, 27, 143, 20);
contentPane.add(textField);
textField.setColumns(10);
textField_1 = new JTextField();
textField_1.setBounds(246, 66, 145, 20);
contentPane.add(textField_1);
textField_1.setColumns(10);
textField_2 = new JTextField();
textField_2.setBounds(246, 109, 145, 20);
contentPane.add(textField_2);
textField_2.setColumns(10);
textField_3 = new JTextField();
textField_3.setBounds(246, 151, 143, 20);
contentPane.add(textField_3);
textField_3.setColumns(10);
textField_5 = new JTextField();
textField_5.setBounds(173, 316, 542, 23);
contentPane.add(textField_5);
textField_5.setColumns(10);
JLabel lblRsum = new JLabel("R\u00E9sum\u00E9:");
lblRsum.setFont(new Font("Tahoma", Font.BOLD, 15));
lblRsum.setBounds(104, 210, 73, 14);
contentPane.add(lblRsum);
JLabel lblPv = new JLabel("PV");
lblPv.setFont(new Font("Tahoma", Font.BOLD, 30));
lblPv.setForeground(Color.WHITE);
lblPv.setBounds(708, 31, 46, 54);
contentPane.add(lblPv);
JLabel label = new JLabel("");
label.setIcon(new ImageIcon(Pv.class.getResource("/View/image/business_table_order_report_history_2332.png")));
label.setBounds(626, 31, 72, 70);
contentPane.add(label);
JLabel label_1 = new JLabel("");
label_1.setIcon(new ImageIcon(Pv.class.getResource("/View/image/Club_3D_Grafikcard_Tray_30781.png")));
label_1.setBounds(10, 11, 64, 70);
contentPane.add(label_1);
}
}
|
package Transport;
import exceptions.DeliveryException;
import exceptions.ManagementException;
import hr.ICustomer;
import hr.IDestination;
import hr.IDriver;
import transport.IDelivery;
import transport.IItem;
import transport.IManagement;
import transport.IVehicle;
import transport.ItemStatus;
import transport.TransportationTypes;
import transport.VehicleStatus;
import Exceptions.ManagementExceptionImpl;
import java.util.Arrays;
import transport.IItemPacked;
/*
* Nome: <Samuel Luciano Correia da Cunha>
* Número: <8160526>
*/
public class Management implements IManagement {
/**
* Represents the management items.
*/
private IItem[] items;
/**
* The number of items.
*/
private int numberOfItems;
/**
* Representes the management vehicles.
*/
private IVehicle[] vehicles;
/**
* The number of vehicles.
*/
private int numberOfVehicles;
/**
* Representes the management drivers.
*/
private IDriver[] drivers;
/**
* The number of drivers.
*/
private int numberOfDrivers;
/**
* Represents the management deliveries.
*/
private IDelivery[] deliveries;
/**
* The number of deliveries.
*/
private int numberOfDeliveries;
/**
* The management delivery.
*/
private IDelivery delivery;
/**
* Constructor of management
*/
public Management() {
this.numberOfItems = 0;
this.items = new IItem[5];
this.numberOfVehicles = 0;
this.vehicles = new IVehicle[5];
this.numberOfDrivers = 0;
this.drivers = new IDriver[5];
this.numberOfDeliveries = 0;
this.deliveries = new IDelivery[5];
}
/**
* Adds a new item to be delivered
*
* @param iitem item to be delivered
* @return true if the item is inserted, throws a exception if the item
* exists
* @throws ManagementException if item is not NON_DELIVERED or item is null
* or item has no transportation type
*/
@Override
public boolean addItem(IItem iitem) throws ManagementException {
/*
if (this.status != ItemStatus.NON_DELIVERED) {
throw new ManagementExceptionImpl("The item is not delivered");
} */
if (iitem == null) {
throw new ManagementExceptionImpl("The parameter is null");
}
if (iitem.getTransportationTypes() == null) {
throw new ManagementExceptionImpl("The item has no transportation type");
}
if (this.items.length == this.numberOfItems) {
IItem[] clone = this.items;
this.items = new IItem[this.items.length + 1];
for (int i = 0; i < clone.length; i++) {
this.items[i] = clone[i];
}
}
this.items[this.numberOfItems] = iitem;
this.numberOfItems++;
return true;
}
/**
* Removes an item
*
* @param iitem item to be removed
* @return true if the item is removed
* @throws ManagementException if the parameter is null
*/
@Override
public boolean removeItem(IItem iitem) throws ManagementException {
if (iitem == null) {
throw new ManagementExceptionImpl("The parameter is null");
}
for (int i = 0; i < this.numberOfItems; ++i) {
if (this.items[i].equals(iitem)) {
for (; i < this.numberOfItems - 1; i++) {
this.items[i] = this.items[i + 1];
}
this.items[i] = null;
this.numberOfItems--;
return true;
}
}
return false;
}
/**
* Returns a copy of the collection of item.
*
* @return the items.
*/
@Override
public IItem[] getItems() {
IItem[] copyItems = new IItem[this.numberOfItems];
for (int i = 0; i < this.numberOfItems; i++) {
copyItems[i] = this.items[i];
}
return copyItems;
}
/**
* Returns a copy of the collection of item from the given customer.
*
* @param customer the number of items of the customer.
* @return the items of the customer.
*/
@Override
public IItem[] getItems(ICustomer customer) {
int count = 0;
IItem[] copyItems = new IItem[this.numberOfItems];
for (int i = 0; i < this.numberOfItems; i++) {
if (this.items[i].getCustomer().equals(customer)) {
copyItems[count] = this.items[i];
count++;
}
}
return copyItems;
}
/**
* Returns a copy of the collection of item with a given destination.
*
* @param destination the destination of the items.
* @return the items of the destination.
*/
@Override
public IItem[] getItems(IDestination destination) {
int count = 0;
IItem[] copyItems = new IItem[this.numberOfItems];
for (int i = 0; i < this.numberOfItems; i++) {
if (this.items[i].getDestination().equals(destination)) {
copyItems[count] = this.items[i];
count++;
}
}
return copyItems;
}
/**
* Returns a cop+y of the collection of item with the given transportation
* type.
*
* @param transportationType the transportation types.
* @return the items of the transportation types.
*/
@Override
public IItem[] getItems(TransportationTypes transportationType) {
int count = 0;
IItem[] copyItems = new IItem[this.numberOfItems];
for (int i = 0; i < this.numberOfItems; i++) {
if (this.items[i].getTransportationTypes().equals(transportationType)) {
copyItems[count] = this.items[i];
count++;
}
}
return copyItems;
}
/**
* Returns a copy of the collection of item with the given item status.
*
* @param itemStatus the item status.
* @return the items of the item status.
*/
@Override
public IItem[] getItems(ItemStatus itemStatus) {
int count = 0;
IItem[] copyItems = new IItem[this.numberOfItems];
for (int i = 0; i < this.numberOfItems; i++) {
if (this.items[i].getStatus().equals(itemStatus)) {
copyItems[count] = this.items[i];
count++;
}
}
return copyItems;
}
/**
* Adds a vehicle to the fleet.
*
* @param vehicle the vehicle to be added to the fleet.
* @return true if the vehicle was inserted, false if the vehicle already
* exists.
* @throws ManagementException if the parameter is null.
*/
@Override
public boolean addVehicle(IVehicle vehicle) throws ManagementException {
if (vehicle == null) {
throw new ManagementExceptionImpl("The parameter is null");
}
if (this.vehicles.length == this.numberOfVehicles) {
IVehicle[] clone = this.vehicles;
this.vehicles = new IVehicle[this.vehicles.length + 1];
for (int i = 0; i < clone.length; i++) {
this.vehicles[i] = clone[i];
}
}
this.vehicles[this.numberOfVehicles] = vehicle;
this.numberOfVehicles++;
return true;
}
/**
* Removes a vehicle from the fleet.
*
* @param vehicle the vehicle to be removed from the fleet.
* @return true if the vehicle was removed, false if the vehicle do not
* exists.
* @throws ManagementException if the parameter is null.
*/
@Override
public boolean removeVehicle(IVehicle vehicle) throws ManagementException {
if (vehicle == null) {
throw new ManagementExceptionImpl("The parameter is null");
}
for (int i = 0; i < this.numberOfVehicles; ++i) {
if (this.vehicles[i].equals(vehicle)) {
for (; i < this.numberOfVehicles - 1; i++) {
this.vehicles[i] = this.vehicles[i + 1];
}
this.vehicles[i] = null;
this.numberOfVehicles--;
return true;
}
}
return false;
}
/**
* Adds a driver to the system.
*
* @param driver the driver to be added to the system.
* @return true if the driver was inserted, false if the driver already
* exists.
* @throws ManagementException if the parameter is null.
*/
@Override
public boolean addDriver(IDriver driver) throws ManagementException {
if (driver == null) {
throw new ManagementExceptionImpl("The parameter is null");
}
if (this.drivers.length == this.numberOfDrivers) {
IDriver[] clone = this.drivers;
this.drivers = new IDriver[this.drivers.length + 1];
for (int i = 0; i < clone.length; i++) {
this.drivers[i] = clone[i];
}
}
this.drivers[this.numberOfDrivers] = driver;
this.numberOfDrivers++;
return true;
}
/**
* Removes a driver from the system.
*
* @param driver the driver to be removed.
* @return true if the driver was removed, false if the driver do no exists
* @throws ManagementException if parameter is null
*/
@Override
public boolean removeDriver(IDriver driver) throws ManagementException {
if (driver == null) {
throw new ManagementExceptionImpl("The parameter is null");
}
for (int i = 0; i < this.numberOfDrivers; ++i) {
if (this.drivers[i].equals(driver)) {
for (; i < this.numberOfDrivers - 1; i++) {
this.drivers[i] = this.drivers[i + 1];
}
this.drivers[i] = null;
this.numberOfDrivers--;
return true;
}
}
return false;
}
/**
* Getter for all vehicle fleet.
*
* @return A copy of all vehicle fleet.
*/
@Override
public IVehicle[] getFleet() {
IVehicle[] copyFleet = new IVehicle[this.numberOfVehicles];
for (int i = 0; i < this.numberOfVehicles; i++) {
copyFleet[i] = this.vehicles[i];
}
return copyFleet;
}
/**
* Getter for all vehicle fleet based on the status.
*
* @param status the status for retrieving vehicles.
* @return a copy of all vehicle fleet with given status.
*/
@Override
public IVehicle[] getFleet(VehicleStatus status) {
int count = 0;
IVehicle[] copyFleet = new IVehicle[this.numberOfVehicles];
for (int i = 0; i < this.numberOfVehicles; i++) {
if (this.vehicles[i].getStatus().equals(status)) {
copyFleet[count] = this.vehicles[i];
count++;
}
}
return copyFleet;
}
/**
* Getter for all vehicle fleet based on the transportation type.
*
* @param transportationType transportation types for retrieving vehicles.
* @return a copy of all vehicle fleet with given transportation type.
*/
@Override
public IVehicle[] getFleet(TransportationTypes transportationType) {
int count = 0;
IVehicle[] copyFleet = new IVehicle[this.numberOfVehicles];
for (int i = 0; i < this.numberOfVehicles; i++) {
if (this.vehicles[i].getTransportationTypes().equals(transportationType)) {
copyFleet[count] = this.vehicles[i];
count++;
}
}
return copyFleet;
}
/**
* Getter for all vehicle fleet based on the status and transportation type.
*
* @param status the status for retrieving vehicles.
* @param transportationType transportation types for retrieving vehicles.
* @return a copy of all vehicle fleet with given status and transportation
* type.
*/
@Override
public IVehicle[] getFleet(VehicleStatus status, TransportationTypes transportationType) {
int count = 0;
IVehicle[] copyFleet = new IVehicle[this.numberOfVehicles];
for (int i = 0; i < this.numberOfVehicles; i++) {
if (this.vehicles[i].getStatus().equals(status) && this.vehicles[i].getTransportationTypes().equals(transportationType)) {
copyFleet[count] = this.vehicles[i];
count++;
}
}
return copyFleet;
}
/**
* Adds a new delivery in the system. All items of the delivery must have
* previously been created in the system and must have a ASSIGNED.
*
* @param delivery delivery to be inserted in the system.
* @return true if the delivery is inserted, false if the delivery already
* exists.
* @throws ManagementException if delivery is null; if delivery with items
* not in the system; if delivery items with status not ASSIGNED; if
* delivery has no items or the items cannot be stored inside the vehicle;
* if delivery has no vehicle or cannot transport specific items if delivery
* has no driver or cannot drive the specific vehicle
*/
@Override
public boolean addDelivery(IDelivery delivery) throws ManagementException {
if (delivery == null) {
throw new ManagementExceptionImpl("The delivery is null");
}
/*
Delivery del1 = (Delivery) delivery;
if (del1.getItemStatus() != ItemStatus.ASSIGNED) {
throw new ManagementExceptionImpl("The item status is not assigned");
}
*/
if (delivery.isEmpty()) {
throw new ManagementExceptionImpl("The delivery has no items");
}
if (delivery.getVehicle() == null) {
throw new ManagementExceptionImpl("The delivery has no vehicles available");
}
if (delivery.getCurrentWeight() > delivery.getVehicle().getMaxWeight()) {
throw new ManagementExceptionImpl("The delivery has no capacity");
}
Delivery del2 = (Delivery) delivery;
if (del2.getDriver() == null) {
throw new ManagementExceptionImpl("The delivery has no driver");
}
if (this.deliveries.length == this.numberOfDeliveries) {
IDelivery[] clone = this.deliveries;
this.deliveries = new IDelivery[this.deliveries.length + 1];
for (int i = 0; i < clone.length; i++) {
this.deliveries[i] = clone[i];
}
}
this.deliveries[this.numberOfDeliveries] = delivery;
this.numberOfDeliveries++;
return true;
}
/**
* Confirms a delivered item. The item must have a state of ASSIGNED. Item
* status must be changed to delivered.
*
* @param idDelivery The delivery id
* @param reference The item reference
* @throws Exception if delivery or item is null;
*/
@Override
public void deliveredItem(String idDelivery, String reference) throws Exception {
if (idDelivery == null || reference == null) {
throw new ManagementExceptionImpl("The delivery id and/or reference are null");
}
int deliveryPosition = -1;
for (int i = 0; i < deliveries.length; i++) {
if (idDelivery == deliveries[i].getId()) {
deliveryPosition = i;
break;
}
}
Delivery tmp = (Delivery) deliveries[deliveryPosition];
IItemPacked[] items = tmp.getPackedItems();
for (int i = 0; i < items.length; i++) {
if (reference == items[i].getItem().getReference()) {
items[i].getItem().setStatus(ItemStatus.DELIVERED);
break;
}
}
System.out.println(Arrays.toString(items));
}
/**
* Confirms delivered items to a given destination. The items must have a
* previous state of ASSIGNED Item status must be changed to DELIVERED
*
* @param idDelivery The delivery id
* @param destination The item destination
* @throws ManagementException if delivery or item is null;
* delivery or item is invalid;
* Item do not have a ASSIGNED status.
*/
@Override
public void deliveredItem(String idDelivery, IDestination destination) throws Exception {
if (idDelivery == null || destination == null) {
throw new ManagementExceptionImpl("The delivery id and/or destination are null");
}
Delivery del = (Delivery) delivery;
if (del.getItemStatus() != ItemStatus.ASSIGNED) {
throw new ManagementExceptionImpl("The item status is not assigned");
}
int deliveryPosition = -1;
for (int i = 0; i < deliveries.length; i++) {
if (idDelivery == deliveries[i].getId()) {
deliveryPosition = i;
break;
}
}
Delivery tmp = (Delivery) deliveries[deliveryPosition];
IItemPacked[] items = tmp.getPackedItems();
for (int i = 0; i < items.length; i++) {
if (destination == items[i].getItem().getDestination()) {
items[i].getItem().setStatus(ItemStatus.DELIVERED);
}
}
System.out.println(Arrays.toString(items));
}
/**
* Checks the state of a item in the system.
*
* @param reference The item reference.
* @return The item status.
* @throws ManagementException if the item does not exist
*/
@Override
public ItemStatus checkItemStatus(String reference) throws Exception {
if (reference == null) {
throw new ManagementExceptionImpl("The reference is null");
}
for (int i = 0; i < deliveries.length; i++) {
Delivery tmp = (Delivery) deliveries[i];
IItemPacked[] items = tmp.getPackedItems();
for (int j = 0; j < items.length; j++) {
if (items[j].getItem().getReference() == reference) {
return items[j].getItem().getStatus();
}
}
}
throw new ManagementExceptionImpl("Item does not exist");
}
/**
* Starts a given delivery.
*
* @param idDelivery The delivery reference.
* @throws DeliveryException From starts method.
*/
@Override
public void startDelivery(String idDelivery) throws DeliveryException {
for (int i = 0; i < deliveries.length; i++) {
if (deliveries[i].getId() == idDelivery) {
deliveries[i].start();
break;
}
}
System.out.println("Delivery " + idDelivery + " has started");
}
/**
* Ends a given delivery.
*
* @param idDelivery The delivery reference.
* @throws DeliveryException From end method.
*/
@Override
public void stopDelivery(String idDelivery) throws DeliveryException {
for (int i = 0; i < deliveries.length; i++) {
if (deliveries[i].getId() == idDelivery) {
deliveries[i].end();
break;
}
}
System.out.println("Delivery " + idDelivery + " has ended");
}
} |
package grafico;
/**
*
* @author Adriana
*/
public class Avioneta implements VehiculoDePasajero,VehiculoAereo{
public void ListaPasajeros() {
// TODO Auto-generated method stub
}
public void Volar() {
// TODO Auto-generated method stub
}
@Override
public void listaPasajeros() {
throw new UnsupportedOperationException("Not supported yet."); //To change body of generated methods, choose Tools | Templates.
}
@Override
public void volar() {
throw new UnsupportedOperationException("Not supported yet."); //To change body of generated methods, choose Tools | Templates.
}
} |
import java.util.*;
/**
* 752. Open the Lock
* Medium
*/
public class Solution {
private char pre(char c) {
return c == '0' ? '9' : (char) (c - 1);
}
private char next(char c) {
return c == '9' ? '0' : (char) (c + 1);
}
private List<String> nextStatus(String code) {
List<String> next = new ArrayList<>();
char[] sc = code.toCharArray();
for (int i = 0; i < sc.length; i++) {
char t = sc[i];
sc[i] = pre(t);
next.add(new String(sc));
sc[i] = next(t);
next.add(new String(sc));
sc[i] = t;
}
return next;
}
public int openLock(String[] deadends, String target) {
if ("0000".equals(target)) {
return 0;
}
Set<String> dead = new HashSet<>();
for (String d : deadends) {
dead.add(d);
}
if (dead.contains("0000")) {
return -1;
}
Deque<String> queue = new LinkedList<>();
queue.offer("0000");
int step = 0;
Set<String> seen = new HashSet<String>();
seen.add("0000");
while (!queue.isEmpty()) {
step++;
int size = queue.size();
for (int i = 0; i < size; i++) {
String status = queue.poll();
for (String n : nextStatus(status)) {
if (!seen.contains(n) && !dead.contains(n)) {
if (n.equals(target)) {
return step;
}
queue.offer(n);
seen.add(n);
}
}
}
}
return -1;
}
public static void main(String[] args) {
String[][] deadends = { { "0201", "0101", "0102", "1212", "2002" }, { "8888" },
{ "8887", "8889", "8878", "8898", "8788", "8988", "7888", "9888" }, { "0000" } };
String[] target = { "0202", "0009", "8888", "8888" };
Solution s = new Solution();
for (int i = 0; i < target.length; i++) {
System.out.println(s.openLock(deadends[i], target[i]));
}
}
}
|
package com.linroid.opengl;
/**
* @author linroid <linroid@gmail.com>
* @since 23/04/2017
*/
public class Sizeof {
public static final int INT = 4;
public static final int SHORT = 2;
public static final int FLOAT = 4;
public static final int DOUBLE = 8;
public static final int CHAR = 1;
public static int INT(int count) {
return count * INT;
}
public static int SHORT(int count) {
return count * SHORT;
}
public static int FLOAT(int count) {
return count * FLOAT;
}
public static int DOUBLE(int count) {
return count * DOUBLE;
}
public static int CHAR(int count) {
return count * CHAR;
}
}
|
package com.wonders.task.htxx.execute;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.List;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.context.annotation.Scope;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;
import com.wonders.task.asset.util.DateUtil;
import com.wonders.task.htxx.service.ContractHtxxService;
import com.wonders.task.sample.ITaskService;
@Transactional(propagation = Propagation.REQUIRED, rollbackFor = Exception.class)
@Service("htxxExecute")
@Scope("prototype")
public class HtxxExecute implements ITaskService{
private ContractHtxxService contractHtxxService;
@Autowired(required=false)
public void setContractHtxxService(@Qualifier("contractHtxxService")ContractHtxxService contractHtxxService) {
this.contractHtxxService = contractHtxxService;
}
/**
* 合同管理页面
*/
@Override
public String exec(String param) {
//写死页面上11个公司的id
List<String> companyList = new ArrayList<String>();
companyList.add("2541"); //运一公司
companyList.add("2542"); //运二公司
companyList.add("2543"); //运三公司
companyList.add("2544"); //运四公司
companyList.add("2540"); //运管中心
companyList.add("2546"); //教育培训中心,新增的
companyList.add("2718"); //车辆公司
companyList.add("2719"); //供电公司
companyList.add("2720"); //通号公司
companyList.add("2721"); //工务公司
companyList.add("2722"); //物资公司
companyList.add("2545"); //维护保障中心
companyList.add("center"); //维护中心,上面6家公司的数据加起来
//1.先得到合同表中最早的签约时间,年份
String earliestDateStr = this.contractHtxxService.findEarliestYearOfContractSignedDate();
//earliestDateStr = "2006-01-01"; //使用该默认值,数据相对较准确
earliestDateStr = "2013-01-01";
Calendar first = Calendar.getInstance(); //最早的合同签约时间
first.setTime(DateUtil.String2Date(earliestDateStr, "yyyy-MM-dd"));
Calendar last = Calendar.getInstance(); //当前时间
last.setTime(new Date());
//1.计算全部
while ((first.get(Calendar.YEAR)-1) != last.get(Calendar.YEAR)) { //年不相等
int currentYear = first.get(Calendar.YEAR);
//计算合同采购方式、合同状态统计
this.updateContractBySignedYearAndContractType(currentYear+"",null);
//计算合同变更统计、计算合同支付统计
this.updateContractByWholeYear(currentYear+"",null);
first.set(Calendar.YEAR, (first.get(Calendar.YEAR)+1)); //年份+1
}
first.setTime(DateUtil.String2Date(earliestDateStr, "yyyy-MM-dd"));
last.setTime(new Date());
//2.计算指定公司下的数量
for(int i=0; i<companyList.size(); i++){
while ((first.get(Calendar.YEAR)-1) != last.get(Calendar.YEAR)) { //年不相等
int currentYear = first.get(Calendar.YEAR);
//计算合同采购方式、合同状态统计
this.updateContractBySignedYearAndContractType(currentYear+"",companyList.get(i));
//计算合同变更统计、计算合同支付统计
this.updateContractByWholeYear(currentYear+"",companyList.get(i));
first.set(Calendar.YEAR, (first.get(Calendar.YEAR)+1)); //年份+1
}
first.setTime(DateUtil.String2Date(earliestDateStr, "yyyy-MM-dd"));
last.setTime(new Date());
}
first.setTime(DateUtil.String2Date(earliestDateStr, "yyyy-MM-dd"));
last.setTime(new Date());
//3.计算其他
while ((first.get(Calendar.YEAR)-1) != last.get(Calendar.YEAR)) { //年不相等
int currentYear = first.get(Calendar.YEAR);
//计算合同采购方式、合同状态统计
this.updateContractBySignedYearAndContractType(currentYear+"","other");
//计算合同变更统计、计算合同支付统计
this.updateContractByWholeYear(currentYear+"","other");
first.set(Calendar.YEAR, (first.get(Calendar.YEAR)+1)); //年份+1
}
return "";
}
/**
* 合同采购方式轮循
* 合同分类contractType,建设类:1,运维类:2
* assignType ,1:采购方式,2:合同状态统计
*/
public void updateContractBySignedYearAndContractType(String controlYear,String companyId){
try {
if(controlYear==null || "".equals(controlYear)) return;
//更新采购方式-运维类contractType='2,'
contractHtxxService.updateContractAssingTypeBySignedDateAndConctractType("2","1",controlYear,companyId);
//更新合同状态统计-运维类contractType='2,'
contractHtxxService.updateContractAssingTypeBySignedDateAndConctractType("2","2",controlYear,companyId);
} catch (Exception e) {
System.out.println("updateContractBySignedYearAndContractType方法错误");
e.printStackTrace();
}
}
/**
*
* 合同分类contractType,建设类:1,运维类:2
* assignType ,1:合同变更,2:合同实际支付、计划支付
*/
public void updateContractByWholeYear(String controlYear,String companyId){
//更新变更情况,
this.contractHtxxService.updateContractChangeOrPay("2", "1", controlYear,companyId);
this.contractHtxxService.updateContractChangeOrPay("2", "2", controlYear,companyId);
}
}
|
import java.util.*;
import java.io.*;
public class cf489a{
public static void main(String [] args) throws IOException{
InputReader in = new InputReader("cf489a.in");
int n = in.nextInt();
HashSet<Integer> set = new HashSet<Integer>();
for(int i = 0; i < n; i++){
int m = in.nextInt();
if(m != 0 && !set.contains(m)){
set.add(m);
}
}
System.out.println(set.size());
}
static class InputReader {
public BufferedReader reader;
public StringTokenizer tokenizer;
public InputReader(String s) {
try{
reader = new BufferedReader(new FileReader(s), 32768);
}
catch (Exception e){
reader = new BufferedReader(new InputStreamReader(System.in), 32768);
}
tokenizer = null;
}
public String nextLine(){
try{
return reader.readLine();
}
catch(Exception e){
throw new RuntimeException(e);
}
}
public String next() {
while (tokenizer == null || !tokenizer.hasMoreTokens()) {
try {
tokenizer = new StringTokenizer(reader.readLine());
} catch (IOException e) {
throw new RuntimeException(e);
}
}
return tokenizer.nextToken();
}
public int nextInt() {
return Integer.parseInt(next());
}
}
} |
package chatroom.serializer;
import chatroom.model.message.Message;
import chatroom.model.message.MessageType;
import chatroom.model.message.RoomListMessage;
import chatroom.model.message.RoomMessage;
import chatroom.server.room.Room;
import java.io.*;
import java.util.ArrayList;
import java.util.List;
public class RoomListMessageSerializer extends MessageSerializer {
@Override
public void serialize(OutputStream out, Message m) throws IOException {
DataOutputStream dataOut = new DataOutputStream(new BufferedOutputStream(out));
RoomListMessage roomListMessage = (RoomListMessage)m;
dataOut.writeByte(dict.getByte(MessageType.ROOMLISTMSG));
dataOut.writeByte(roomListMessage.getRoomList().size());
for(RoomMessage r : roomListMessage.getRoomList()){
dataOut.writeUTF(r.getName());
dataOut.writeByte(r.getSize());
}
dataOut.flush();
}
@Override
public Message deserialize(InputStream in) throws IOException {
DataInputStream dataIn = new DataInputStream(new BufferedInputStream(in));
int listSize = dataIn.readByte();
List<RoomMessage> roomList = new ArrayList<>();
for(int i = 0; i < listSize; ++i){
roomList.add(new RoomMessage(dataIn.readUTF(),dataIn.readByte()));
}
RoomListMessage m = new RoomListMessage(roomList);
return m;
}
}
|
/*
* Copyright 2011-2021 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.springframework.data.neo4j.documentation.repositories.populators;
import java.util.Set;
import org.springframework.data.neo4j.core.schema.Id;
import org.springframework.data.neo4j.core.schema.Node;
import org.springframework.data.neo4j.core.schema.Property;
import org.springframework.data.neo4j.core.schema.Relationship;
import org.springframework.data.neo4j.core.schema.Relationship.Direction;
/**
* @author Michael J. Simons
*/
// tag::populators[]
@Node("Movie")
public class MovieEntity {
@Id private final String title;
@Property("tagline") private final String description;
@Relationship(type = "ACTED_IN", direction = Direction.INCOMING) private Set<PersonEntity> actors;
@Relationship(type = "DIRECTED", direction = Direction.INCOMING) private Set<PersonEntity> directors;
public MovieEntity(String title, String description) {
this.title = title;
this.description = description;
}
// Getters and setters ommitted.
// end::populators[]
public String getTitle() {
return title;
}
public String getDescription() {
return description;
}
public Set<PersonEntity> getActors() {
return actors;
}
public Set<PersonEntity> getDirectors() {
return directors;
}
// tag::populators[]
}
// end::populators[]
|
package services;
import java.util.Map;
import org.hibernate.SQLQuery;
import org.hibernate.Session;
import org.hibernate.transform.AliasToEntityMapResultTransformer;
import db.HibernateUtil;
public class decService {
@SuppressWarnings("unchecked")
public static decryptorClass viewRequest(String publicid) {
// system.out.println("didalam exec sp sebelum create decrypt");
decryptorClass decrypt = null;
Session s = HibernateUtil.getSessionFactory().openSession();
SQLQuery q = s
.createSQLQuery("exec SPU_ViewEmailConfirmation @PublicId= :PublicId");
q.setString("PublicId", publicid);
q.setResultTransformer(AliasToEntityMapResultTransformer.INSTANCE);
try {
Map<String, Object> result = (Map<String, Object>) q.list().get(0);
decrypt = new decryptorClass();
decrypt.convertFromMap(result);
} catch (Exception e) {
e.printStackTrace();
} finally {
s.close();
}
if (decrypt!=null){
// system.out.println("data diterima");
}
return decrypt;
}
}
|
import java.io.FileReader;
import java.io.IOException;
import java.util.Scanner;
public class HarryPotterTextReading {
public static void main(String[] args) throws IOException {
java.io.File file = new java.io.File("src/harryPotter.txt");
Scanner input = new Scanner(file);
try {
FileReader fr = new FileReader(file);
input = new Scanner(fr);
while(input.hasNextLine()) {
System.out.println(input.nextLine());
}
}catch(IOException ex) {
System.out.println("Problem with file reading");
ex.printStackTrace();
}finally {
input.close();
}
}
}
|
/*
* Copyright (c) 2016. Universidad Politecnica de Madrid
*
* @author Badenes Olmedo, Carlos <cbadenes@fi.upm.es>
*
*/
package org.librairy.modeler.lda.functions;
import org.apache.spark.mllib.linalg.Vector;
import org.apache.spark.sql.Row;
import scala.Tuple2;
import scala.runtime.AbstractFunction1;
import java.io.Serializable;
/**
* Created on 26/06/16:
*
* @author cbadenes
*/
public class RowToPair extends AbstractFunction1<Row, Tuple2<Object, Vector>> implements Serializable {
@Override
public Tuple2<Object, Vector> apply(Row v1) {
String uri = (String) v1.get(0);
Vector vector = (Vector) v1.get(1);
return new Tuple2<Object, Vector>(from(uri), vector);
}
public static Long from(String uri){
return Long.valueOf(uri.hashCode());
}
}
|
package com.tencent.mm.plugin.exdevice.model;
import com.tencent.mm.plugin.exdevice.service.f;
import com.tencent.mm.plugin.exdevice.service.k.a;
import com.tencent.mm.sdk.platformtools.x;
class h$2 extends a {
final /* synthetic */ h ivb;
final /* synthetic */ h.a ivc;
h$2(h hVar, h.a aVar) {
this.ivb = hVar;
this.ivc = aVar;
}
public final void a(long j, int i, int i2, int i3, long j2) {
x.d(h.TAG, "mac=%d, oldState=%d, newState=%d, errCode=%d, profileType=%d", new Object[]{Long.valueOf(j), Integer.valueOf(i), Integer.valueOf(i2), Integer.valueOf(i3), Long.valueOf(j2)});
f.a cO = h.a(this.ivb).cO(j);
if (cO != null) {
cO.bLv = i2;
cO.hgC = j2;
} else {
x.i(h.TAG, "get connect state faild : %d", new Object[]{Long.valueOf(j)});
}
this.ivc.a(j, i, i2, i3, j2);
}
}
|
/*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.commons.imaging.examples.tiff;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;
import java.util.HashMap;
import java.util.List;
import javax.imageio.ImageIO;
import org.apache.commons.imaging.FormatCompliance;
import org.apache.commons.imaging.ImageReadException;
import org.apache.commons.imaging.common.bytesource.ByteSourceFile;
import org.apache.commons.imaging.formats.tiff.TiffContents;
import org.apache.commons.imaging.formats.tiff.TiffDirectory;
import org.apache.commons.imaging.formats.tiff.TiffField;
import org.apache.commons.imaging.formats.tiff.TiffReader;
/**
* Provides a example application showing how to access metadata and imagery
* from TIFF files using the low-level access routines. This approach is
* especially useful if the TIFF file includes multiple images.
*/
public class ReadTagsAndImages {
private static final String[] USAGE = {
"Usage ReadTagsAndImages <input file> [output file]",
" input file: mandatory file to be read",
" output file: optional root name and path for files to be written"
};
/**
* Open the specified TIFF file and print its metadata (fields) to standard
* output. If an output root-name is specified, write images to specified
* path.
*
* @param args the command line arguments
* @throws org.apache.commons.imaging.ImageReadException in the event of an
* internal data format or version compatibility error reading the image.
* @throws java.io.IOException in the event of an I/O error.
*/
public static void main(final String[] args)
throws ImageReadException, IOException {
if (args.length == 0) {
// Print usage and exit
for (final String s : USAGE) {
System.err.println(s);
}
System.exit(0);
}
final File target = new File(args[0]);
String rootName = null;
if (args.length == 2) {
rootName = args[1];
}
final boolean optionalImageReadingEnabled
= rootName != null && !rootName.isEmpty();
final ByteSourceFile byteSource = new ByteSourceFile(target);
final HashMap<String, Object> params = new HashMap<>();
// Establish a TiffReader. This is just a simple constructor that
// does not actually access the file. So the application cannot
// obtain the byteOrder, or other details, until the contents has
// been read. Then read the directories associated with the
// file by passing in the byte source and options.
final TiffReader tiffReader = new TiffReader(true);
final TiffContents contents = tiffReader.readDirectories(
byteSource,
optionalImageReadingEnabled, // read image data, if present
FormatCompliance.getDefault());
// Loop on the directories and fetch the metadata and
// image (if available, and configured to do so)
int iDirectory = 0;
for (final TiffDirectory directory : contents.directories) {
// Get the metadata (Tags) and write them to standard output
final boolean hasTiffImageData = directory.hasTiffImageData();
System.out.format("Directory %2d %s, description: %s%n",
iDirectory,
hasTiffImageData ? "Has TIFF Image Data" : "No TIFF Image Data",
directory.description());
// Loop on the fields, printing the metadata (fields) ----------
final List<TiffField> fieldList = directory.getDirectoryEntries();
for (final TiffField tiffField : fieldList) {
String s = tiffField.toString();
if (s.length() > 90) {
s = s.substring(0, 90);
}
// In the case if the offsets (file positions) for the Strips
// or Tiles, the string may be way too long for output and
// will be truncated. Therefore, indicate the numnber of entries.
// These fields are indicated by numerical tags 0x144 and 0x145
if (tiffField.getTag() == 0x144 || tiffField.getTag() == 0x145) {
final int i = s.indexOf(')');
final int[] a = tiffField.getIntArrayValue();
s = s.substring(0, i + 2) + " [" + a.length + " entries]";
}
System.out.println(" " + s);
}
if (optionalImageReadingEnabled && hasTiffImageData) {
final File output = new File(rootName + "_" + iDirectory + ".jpg");
System.out.println("Writing image to " + output.getPath());
final BufferedImage bImage = directory.getTiffImage(params);
ImageIO.write(bImage, "JPEG", output);
}
System.out.println("");
iDirectory++;
}
}
}
|
package com.yahoo.algos;
import java.util.Arrays;
public class BinarySearch {
/**
* Remember 2 things
* one mid = low + (high-low)/2 and
* other while low<=high or if low>high return -1
*/
static int search = 45;
static int[] array = {45,2,5,8,15,3,5,90,24,34,52,98};
public static void main(String[] args) {
Arrays.sort(array);
Common.print(array);
int index = bsearch2(0, array.length-1);
System.out.println(index +" " + ((index!=-1)? array[index]:-1) +"");
int index2 = bsearch1(0, array.length-1);
System.out.println(index2 +" " + ((index2!=-1)? array[index2]:-1) +"");
}
private static int bsearch1(int low, int high){ //fails on last and first index
if(low>high) return -1; //NOTE not low<=high
int mid = low + (high - low)/2;
if(array[mid]==search){
return mid;
}
if(search > array[mid]){
return bsearch1(mid+1, high);
}
if(search < array[mid]){
return bsearch1(low, mid-1);
}
return -1;
}
private static int bsearch2(int low , int high){
while (low<=high){
int mid = low + (high -low)/2;
if(array[mid]==search){
return mid;
}
if(search > array[mid]){
low = mid+1;
}
if(search < array[mid]){
high = mid-1;
}
}
return -1;
}
}
|
public class Station
{
private Switch switchOne;
private Switch switchTwo;
private Track trackOne;
private Track trackTwo;
private Track trackRight;
private Track trackLeft;
/**
* Public method that checks if the train can arrive at the station.
* If trackOne and TrackTwo has a Train, then it returns false
* If one of them is empthy the Train can arrive
* @param arriveAt
* @return
*/
public boolean CanArrive (int arriveAt)
{
if (trackOne.Value == 1 && trackTwo.Value == 1)
{
return false; //no track available
}
return true;
}
/**
* Public method that changes the tracks value when the Train arrives to the station
* If the Train arrives to trackOne or TrackTwo it sets the value to 1, and
* sets the track where it arrives from to 0
* @param arriveAt
* @param arriveFrom
*/
public void Arrive(int arriveAt, int arriveFrom)
{
switch (arriveAt)
{
case 1: trackOne.setValue(1);
break;
case 2: trackTwo.setValue(1);
break;
}
switch (arriveFrom)
{
case 1:
trackLeft.setValue(0);
break;
case 2:
trackRight.setValue(0);
}
}
/**
* Public method that checks if the Train can depart to trackLeft or trackRight
* when it wishes to depart the station
* @param departTo
* @return
*/
public boolean CanDepart (int departTo)
{
switch (departTo)
{
case 1:
if (trackLeft.Value == 0)
{
return true;
}
break;
case 2:
if (trackRight.Value == 0)
{
return true;
}
break;
}
return false;
}
/**
* Public method that changes the tracks value when the Train departs from the station
* If the Train arrives to trackLeft or TrackRight it sets the value to 1, and
* sets the track where it arrives from to 0
* @param departFrom
* @param departTo
*/
public void Depart (int departFrom, int departTo)
{
switch (departTo)
{
case 1:
trackLeft.setValue(1);
break;
case 2:
trackRight.setValue(1);
}
switch (departFrom)
{
case 1:
trackOne.setValue(0);
break;
case 2:
trackTwo.setValue(0);
}
}
/**
* Public method that changes the tracks value when the Train is arriving at trackLeft
* or trackRight from outside of the tracks
* @param trackToStation
*/
public void GoToStation (int trackToStation)
{
switch (trackToStation)
{
case 1:
trackLeft.setValue(1);
break;
case 2:
trackRight.setValue(1);
}
}
/**
* Public method that checks if it possible for the train to actually go to
* the station
* @return
*/
public boolean isTrackAvailable ()
{
return (CanArrive(1) //trackOne
|| CanArrive(2) //trackTwo
|| (CanDepart(1) && CanDepart(2)));
//trackLeft and trackRight
}
}
|
package pe.gob.trabajo.domain;
import com.fasterxml.jackson.annotation.JsonIgnore;
import io.swagger.annotations.ApiModel;
import io.swagger.annotations.ApiModelProperty;
import org.hibernate.annotations.Cache;
import org.hibernate.annotations.CacheConcurrencyStrategy;
import org.springframework.data.elasticsearch.annotations.Document;
import javax.persistence.*;
import javax.validation.constraints.*;
import java.io.Serializable;
import java.time.Instant;
import java.util.HashSet;
import java.util.Set;
import java.util.Objects;
/**
* LISTA MAESTRA DE DISCAPACIDADES
*/
@ApiModel(description = "LISTA MAESTRA DE DISCAPACIDADES")
@Entity
@Table(name = "gltbc_discap")
@Cache(usage = CacheConcurrencyStrategy.NONSTRICT_READ_WRITE)
@Document(indexName = "gltbc_discap")
public class Discap implements Serializable {
private static final long serialVersionUID = 1L;
@Id
@GeneratedValue(strategy = GenerationType.SEQUENCE, generator = "sequenceGenerator")
@SequenceGenerator(name = "sequenceGenerator")
@Column(name = "n_coddiscap", nullable = false)
private Long id;
/**
* DESCRIPCION DE LA DISCAPACIDAD.
*/
@NotNull
@Size(max = 100)
@ApiModelProperty(value = "DESCRIPCION DE LA DISCAPACIDAD.", required = true)
@Column(name = "v_desdiscap", length = 100, nullable = false)
private String vDesdiscap;
/**
* CODIGO DEL USUARIO QUE REGISTRA.
*/
@NotNull
@ApiModelProperty(value = "CODIGO DEL USUARIO QUE REGISTRA.", required = true)
@Column(name = "n_usuareg", nullable = false)
private Integer nUsuareg;
/**
* FECHA Y HORA DEL REGISTRO.
*/
@NotNull
@ApiModelProperty(value = "FECHA Y HORA DEL REGISTRO.", required = true)
@Column(name = "t_fecreg", nullable = false)
private Instant tFecreg;
/**
* ESTADO ACTIVO DEL REGISTRO (1=ACTIVO, 0=INACTIVO)
*/
@NotNull
@ApiModelProperty(value = "ESTADO ACTIVO DEL REGISTRO (1=ACTIVO, 0=INACTIVO)", required = true)
@Column(name = "n_flgactivo", nullable = false)
private Boolean nFlgactivo;
/**
* CODIGO DE LA SEDE DONDE SE REGISTRA.
*/
@NotNull
@ApiModelProperty(value = "CODIGO DE LA SEDE DONDE SE REGISTRA.", required = true)
@Column(name = "n_sedereg", nullable = false)
private Integer nSedereg;
/**
* CODIGO DEL USUARIO QUE MODIFICA EL REGISTRO.
*/
@ApiModelProperty(value = "CODIGO DEL USUARIO QUE MODIFICA EL REGISTRO.")
@Column(name = "n_usuaupd")
private Integer nUsuaupd;
/**
* CODIGO DEL USUARIO QUE MODIFICA EL REGISTRO.
*/
@ApiModelProperty(value = "CODIGO DEL USUARIO QUE MODIFICA EL REGISTRO.")
@Column(name = "t_fecupd")
private Instant tFecupd;
/**
* CODIGO DE LA SEDE DONDE SE MODIFICA EL REGISTRO.
*/
@ApiModelProperty(value = "CODIGO DE LA SEDE DONDE SE MODIFICA EL REGISTRO.")
@Column(name = "n_sedeupd")
private Integer nSedeupd;
@OneToMany(mappedBy = "discap")
@JsonIgnore
@Cache(usage = CacheConcurrencyStrategy.NONSTRICT_READ_WRITE)
private Set<Discapate> discapates = new HashSet<>();
// jhipster-needle-entity-add-field - Jhipster will add fields here, do not remove
public Long getId() {
return id;
}
public void setId(Long id) {
this.id = id;
}
public String getvDesdiscap() {
return vDesdiscap;
}
public Discap vDesdiscap(String vDesdiscap) {
this.vDesdiscap = vDesdiscap;
return this;
}
public void setvDesdiscap(String vDesdiscap) {
this.vDesdiscap = vDesdiscap;
}
public Integer getnUsuareg() {
return nUsuareg;
}
public Discap nUsuareg(Integer nUsuareg) {
this.nUsuareg = nUsuareg;
return this;
}
public void setnUsuareg(Integer nUsuareg) {
this.nUsuareg = nUsuareg;
}
public Instant gettFecreg() {
return tFecreg;
}
public Discap tFecreg(Instant tFecreg) {
this.tFecreg = tFecreg;
return this;
}
public void settFecreg(Instant tFecreg) {
this.tFecreg = tFecreg;
}
public Boolean isnFlgactivo() {
return nFlgactivo;
}
public Discap nFlgactivo(Boolean nFlgactivo) {
this.nFlgactivo = nFlgactivo;
return this;
}
public void setnFlgactivo(Boolean nFlgactivo) {
this.nFlgactivo = nFlgactivo;
}
public Integer getnSedereg() {
return nSedereg;
}
public Discap nSedereg(Integer nSedereg) {
this.nSedereg = nSedereg;
return this;
}
public void setnSedereg(Integer nSedereg) {
this.nSedereg = nSedereg;
}
public Integer getnUsuaupd() {
return nUsuaupd;
}
public Discap nUsuaupd(Integer nUsuaupd) {
this.nUsuaupd = nUsuaupd;
return this;
}
public void setnUsuaupd(Integer nUsuaupd) {
this.nUsuaupd = nUsuaupd;
}
public Instant gettFecupd() {
return tFecupd;
}
public Discap tFecupd(Instant tFecupd) {
this.tFecupd = tFecupd;
return this;
}
public void settFecupd(Instant tFecupd) {
this.tFecupd = tFecupd;
}
public Integer getnSedeupd() {
return nSedeupd;
}
public Discap nSedeupd(Integer nSedeupd) {
this.nSedeupd = nSedeupd;
return this;
}
public void setnSedeupd(Integer nSedeupd) {
this.nSedeupd = nSedeupd;
}
public Set<Discapate> getDiscapates() {
return discapates;
}
public Discap discapates(Set<Discapate> discapates) {
this.discapates = discapates;
return this;
}
public Discap addDiscapate(Discapate discapate) {
this.discapates.add(discapate);
discapate.setDiscap(this);
return this;
}
public Discap removeDiscapate(Discapate discapate) {
this.discapates.remove(discapate);
discapate.setDiscap(null);
return this;
}
public void setDiscapates(Set<Discapate> discapates) {
this.discapates = discapates;
}
// jhipster-needle-entity-add-getters-setters - Jhipster will add getters and setters here, do not remove
@Override
public boolean equals(Object o) {
if (this == o) {
return true;
}
if (o == null || getClass() != o.getClass()) {
return false;
}
Discap discap = (Discap) o;
if (discap.getId() == null || getId() == null) {
return false;
}
return Objects.equals(getId(), discap.getId());
}
@Override
public int hashCode() {
return Objects.hashCode(getId());
}
@Override
public String toString() {
return "Discap{" +
"id=" + getId() +
", vDesdiscap='" + getvDesdiscap() + "'" +
", nUsuareg='" + getnUsuareg() + "'" +
", tFecreg='" + gettFecreg() + "'" +
", nFlgactivo='" + isnFlgactivo() + "'" +
", nSedereg='" + getnSedereg() + "'" +
", nUsuaupd='" + getnUsuaupd() + "'" +
", tFecupd='" + gettFecupd() + "'" +
", nSedeupd='" + getnSedeupd() + "'" +
"}";
}
}
|
package com.niit.daoImpl;
import java.util.List;
import javax.transaction.Transactional;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Repository;
import com.niit.dao.ForumDao;
import com.niit.model.Forum;
@Repository("forumdao")
@Transactional
public class ForumDaoImpl implements ForumDao {
@Autowired
SessionFactory sessionFactory;
public boolean addForum(Forum forum) {// TC Compl
try {
sessionFactory.getCurrentSession().save(forum);
System.out.println("forum Added");
return true;
} catch (Exception e) {
return false;
}
}
public boolean deleteForum(Forum forum) {// TC Compl
sessionFactory.getCurrentSession().remove(forum);
System.out.println("Forum Removed");
return true;
}
public boolean updateForum(Forum forum) {// TC Compl
System.out.println("#######");
sessionFactory.getCurrentSession().update(forum);
System.out.println("Forum Updated");
return true;
}
public Forum getForum(int forumId) {// TC Compl
Session session = sessionFactory.openSession();
Forum forum = session.get(Forum.class, forumId);
session.close();
return forum;
}
@Transactional
public boolean approveForum(Forum forum) {
forum.setForumstatus("A");
System.out.println("Forum Approved");
sessionFactory.getCurrentSession().update(forum);
return true;
}
@Transactional
public boolean rejectForum(Forum forum) {
forum.setForumstatus("NA");
System.out.println("Forum Rejected");
sessionFactory.getCurrentSession().update(forum);
return true;
}
public List<Forum> listForum(String forumusername) {
System.out.println("List of username in forum");
return sessionFactory.getCurrentSession()
.createQuery("from Forum where forumname='" + forumusername + "'", Forum.class).getResultList();
// return (List<Forum>) sessionFactory.getCurrentSession().get(Forum.class,
// forumusername);
}
}
|
package Taller;
import java.util.InputMismatchException;
import java.util.Scanner;
/**
*
* @author Usuario
*/
public class Interfaz {
public static String leerCadena(String prompt){
Scanner leer=new Scanner(System.in);
String lectura;
System.out.println(prompt);
System.out.print("%% ");
lectura=leer.nextLine();
return lectura;
}
public static double leerNumero(String prompt){
Scanner leer=new Scanner(System.in);
boolean bienEscrito=false;
double lectura=0.0;
while(!bienEscrito){
System.out.println(prompt);
if(leer.hasNextDouble()){
lectura=leer.nextDouble();
bienEscrito=true;}
else{System.out.println("No has introducido un número:");
leer.next();
}
}
return lectura;
}
public static String Area(){
String area=leerCadena("¿Area? (C)orte, Con(F)ección o (P)lanchado");
while(!area.equalsIgnoreCase("c")&& !area.equalsIgnoreCase("p")&&!area.equalsIgnoreCase("f")){
area=leerCadena("¿Area? (C)orte, Con(F)ección o (P)lanchado");
if(!area.equalsIgnoreCase("c")&&!area.equalsIgnoreCase("p")&&!area.equalsIgnoreCase("f"))
System.out.println("ERROR:AREA INCORRECTA...");
}
return area;
}
public static void Mensaje(String prompt){
System.out.println(prompt);
}
public static void MensajeDeVerificacion(boolean ok){
if(ok) Mensaje("Accion realizada con éxito");
else MensajeDeError("Acción fallida");
}
public static void MensajeDeError(String prompt){
System.err.println(prompt);
}
public String trabajoConfeccion(){
String trabajo=" ";
double numero=100;
while(numero!=0 &&numero!=1 && numero!=2){
numero=leerNumero("¿0=Camiseta larga,1=Pantalón, 2=Camiseta manga larga?");
if(numero==0)trabajo="Camiseta larga";
if(numero==1)trabajo="Pantalón";
if(numero==2)trabajo="Camiseta manga larga";
if(trabajo.equals(" "))System.out.println("TRABAJO NO ENCONTRADO");
}
return trabajo;
}
public void mostrarLista(Lista list,String letra){
String capa="Empleado código Area Puntuación\n";
capa+="-------- ------ ---- ----------";
System.out.println(capa);
if(letra.equalsIgnoreCase("C")){
for(int i=0;i<list.listaC.length && list.listaC[i]!=null;i++){
for(int numero=0;numero<capa.length() ;numero++){
if (numero==0)System.out.print(list.listaC[i].nombre);
if (numero==(17-(list.listaC[i].nombre.length()-8)))System.out.print(list.listaC[i].codigo+" "+list.listaC[i].getArea()+" "+list.listaC[i].puntuacion);
if (numero!=0 &&numero!=24 && numero<capa.length())System.out.print(" ");
}
System.out.print("\n");
}
}
if(letra.equalsIgnoreCase("F")){
for(int i=0;i<list.listaF.length && list.listaF[i]!=null;i++){
for(int numero=0;numero<capa.length() ;numero++){
if (numero==0)System.out.print(list.listaF[i].nombre);
if (numero==(17-(list.listaF[i].nombre.length()-8)))System.out.print(list.listaF[i].codigo+" "+list.listaF[i].getArea()+" "+list.listaF[i].puntuacion);
if (numero!=0 &&numero!=24 && numero<capa.length())System.out.print(" ");
}
System.out.print("\n");
}
}
if(letra.equalsIgnoreCase("P")){
for(int i=0;i<list.listaP.length && list.listaP[i]!=null;i++){
for(int numero=0;numero<capa.length() ;numero++){
if (numero==0)System.out.print(list.listaP[i].nombre);
if (numero==(17-(list.listaP[i].nombre.length()-8)))System.out.print(list.listaP[i].codigo+" "+list.listaP[i].getArea()+" "+list.listaP[i].puntuacion);
if (numero!=0 &&numero!=24 && numero<capa.length())System.out.print(" ");
}
System.out.print("\n");
}
}
if(letra.equalsIgnoreCase("A")){
for(int i=0;i<list.listaC.length && list.listaC[i]!=null;i++){
for(int numero=0;numero<capa.length() ;numero++){
if (numero==0)System.out.print(list.listaC[i].nombre);
if (numero==(17-(list.listaC[i].nombre.length()-8)))System.out.print(list.listaC[i].codigo+" "+list.listaC[i].getArea()+" "+list.listaC[i].puntuacion);
if (numero!=0 &&numero!=24 && numero<capa.length())System.out.print(" ");
}
System.out.print("\n");
}
for(int i=0;i<list.listaF.length && list.listaF[i]!=null;i++){
for(int numero=0;numero<capa.length() ;numero++){
if (numero==0)System.out.print(list.listaF[i].nombre);
if (numero==(17-(list.listaF[i].nombre.length()-8)))System.out.print(list.listaF[i].codigo+" "+list.listaF[i].getArea()+" "+list.listaF[i].puntuacion);
if (numero!=0 &&numero!=24 && numero<capa.length())System.out.print(" ");
}
System.out.print("\n");
}
for(int i=0;i<list.listaP.length && list.listaP[i]!=null;i++){
for(int numero=0;numero<capa.length() ;numero++){
if (numero==0)System.out.print(list.listaP[i].nombre);
if (numero==(17-(list.listaP[i].nombre.length()-8)))System.out.print(list.listaP[i].codigo+" "+list.listaP[i].getArea()+" "+list.listaP[i].puntuacion);
if (numero!=0 &&numero!=24 && numero<capa.length())System.out.print(" ");
}
System.out.print("\n");
}
}
}
public void mostrarTrabajoC( TrabajoC[] tc,String id){
String capa="Trabajo puntuacion fecha\n";
capa+="------- ---------- -----";
String code="";
System.out.println(capa);
for(int i=0;i<tc.length ;i++){
if( tc[i]!=null ){
code=tc[i].codigo;
if(tc[i].codigo.equalsIgnoreCase(id))
System.out.println(tc[i].funcion+" "+tc[i].puntos+" "+tc[i].getFecha());
}
}
}
public void mostrarTrabajoF( TrabajoF[] tf,String id){
String capa="Trabajo puntuacion fecha\n";
capa+="------- ---------- -----";
String code="";
System.out.println(capa);
for(int i=0;i<tf.length ;i++){
if( tf[i]!=null ){
code=tf[i].codigo;
if(tf[i].codigo.equalsIgnoreCase(id))
System.out.println(tf[i].funcion+" "+tf[i].puntos+" "+tf[i].getFecha());
}
}
}
public void mostrarTrabajoP( TrabajoP[] tp,String id){
String capa="Trabajo puntuacion fecha\n";
capa+="------- ---------- -----";
String code="";
System.out.println(capa);
for(int i=0;i<tp.length ;i++){
if( tp[i]!=null ){
code=tp[i].codigo;
if(tp[i].codigo.equalsIgnoreCase(id))
System.out.println(tp[i].funcion+" "+tp[i].puntos+" "+tp[i].getFecha());
}
}
}
}
|
package com.tencent.mm.plugin.profile.ui;
import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import com.tencent.mm.R;
import com.tencent.mm.model.au;
import com.tencent.mm.model.c;
import com.tencent.mm.model.m;
import com.tencent.mm.pluginsdk.b.a;
import com.tencent.mm.pluginsdk.ui.applet.ContactListExpandPreference;
import com.tencent.mm.sdk.platformtools.bi;
import com.tencent.mm.sdk.platformtools.x;
import com.tencent.mm.storage.ab;
import com.tencent.mm.storage.u;
import com.tencent.mm.ui.base.preference.PreferenceCategory;
import com.tencent.mm.ui.base.preference.PreferenceSmallCategory;
import com.tencent.mm.ui.base.preference.f;
import java.util.List;
import junit.framework.Assert;
public final class h implements a {
Context context;
private int eLK;
private f eOE;
private String fsV;
private ab guS;
u hLB;
private boolean lUD;
private boolean lUE;
private int lWd;
ContactListExpandPreference lWe;
public h(Context context) {
this.context = context;
this.lWe = new ContactListExpandPreference(context, 0);
}
public final boolean wX(String str) {
x.d("MicroMsg.ContactWidgetGroupCard", "handleEvent " + str);
au.HU();
ab Yg = c.FR().Yg(str);
if (Yg != null && ((int) Yg.dhP) > 0) {
Intent intent = new Intent();
intent.setClass(this.context, ContactInfoUI.class);
intent.putExtra("Contact_User", Yg.field_username);
this.context.startActivity(intent);
}
return true;
}
public final boolean a(f fVar, ab abVar, boolean z, int i) {
Assert.assertTrue(abVar != null);
Assert.assertTrue(bi.oV(abVar.field_username).length() > 0);
Assert.assertTrue(fVar != null);
this.eOE = fVar;
this.guS = abVar;
this.lUD = z;
this.eLK = i;
this.lUE = ((Activity) this.context).getIntent().getBooleanExtra("User_Verify", false);
this.lWd = ((Activity) this.context).getIntent().getIntExtra("Kdel_from", -1);
this.fsV = abVar.field_username;
au.HU();
this.hLB = c.Ga().ii(this.fsV);
this.eOE.removeAll();
this.eOE.a(new PreferenceSmallCategory(this.context));
this.lWe.setKey("roominfo_contact_anchor");
this.eOE.a(this.lWe);
this.eOE.a(new PreferenceCategory(this.context));
NormalUserFooterPreference normalUserFooterPreference = new NormalUserFooterPreference(this.context);
normalUserFooterPreference.setLayoutResource(R.i.contact_info_footer_normal);
normalUserFooterPreference.setKey("contact_info_footer_normal");
if (normalUserFooterPreference.a(this.guS, "", this.lUD, this.lUE, false, this.eLK, this.lWd, false, false, 0, "")) {
this.eOE.a(normalUserFooterPreference);
}
this.lWe.a(this.eOE, this.lWe.mKey);
List gI = m.gI(this.fsV);
this.lWe.kG(false).kH(false);
this.lWe.p(this.fsV, gI);
this.lWe.a(new 1(this));
return true;
}
public final boolean auw() {
NormalUserFooterPreference normalUserFooterPreference = (NormalUserFooterPreference) this.eOE.ZZ("contact_info_footer_normal");
if (normalUserFooterPreference != null) {
normalUserFooterPreference.auw();
}
return true;
}
public final void onActivityResult(int i, int i2, Intent intent) {
}
}
|
/*
* FileName: FileUploadController.java
* Description:
* Company: 南宁超创信息工程有限公司
* Copyright: ChaoChuang (c) 2005
* History: 2005-1-7 (guig) 1.0 Create
*/
package com.spower.basesystem.common.multipart.controller;
import javax.servlet.http.HttpServletRequest;
import org.springframework.web.bind.ServletRequestDataBinder;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.servlet.mvc.SimpleFormController;
import com.spower.basesystem.common.multipart.support.InterfaceMultipartFilePropertyEditor;
/**
* @author Guig
* @version 1.0 2005-1-7
*/
public class AbstractFileUploadController extends SimpleFormController {
/**
* @see org.springframework.web.servlet.mvc.BaseCommandController#initBinder(javax.servlet.http.HttpServletRequest, org.springframework.web.bind.ServletRequestDataBinder)
*/
protected void initBinder(HttpServletRequest request, ServletRequestDataBinder binder)
throws Exception {
super.initBinder(request, binder);
// to actually be able to convert Multipart instance to MultipartFile
// we have to register a custom editor (in this case the
// InterfaceMultipartFilePropertyEditor
binder.registerCustomEditor(MultipartFile.class, new InterfaceMultipartFilePropertyEditor());
// now Spring knows how to handle multipart object and convert them to MultipartFile
}
}
|
package sim.pedido;
import java.io.Serializable;
import java.util.Date;
import javax.persistence.*;
import sim.material.Material;
import sim.usuario.Usuario;
@Entity
@Table(name="pedido")
public class Pedido implements Serializable {
/**
*
*/
private static final long serialVersionUID = -3424559009448752224L;
@Id
@GeneratedValue
@Column(name="id_pedido")
private Integer codigo;
@ManyToOne
private Material material;
@ManyToOne
private Usuario usuario;
private Double quantidade;
private String status;
private Date data_emitido;
private Date data_finalizado;
private String aplicacao;
private String andamento;
private boolean urgencia;
private String observacoes;
private boolean ressuprimento;
public Integer getCodigo() {
return codigo;
}
public void setCodigo(Integer codigo) {
this.codigo = codigo;
}
public Material getMaterial() {
return material;
}
public void setMaterial(Material material) {
this.material = material;
}
public Usuario getUsuario() {
return usuario;
}
public void setUsuario(Usuario usuario) {
this.usuario = usuario;
}
public Double getQuantidade() {
return quantidade;
}
public void setQuantidade(Double quantidade) {
this.quantidade = quantidade;
}
public String getStatus() {
return status;
}
public void setStatus(String status) {
this.status = status;
}
public Date getData_emitido() {
return data_emitido;
}
public void setData_emitido(Date data_emitido) {
this.data_emitido = data_emitido;
}
public Date getData_finalizado() {
return data_finalizado;
}
public void setData_finalizado(Date data_finalizado) {
this.data_finalizado = data_finalizado;
}
public String getAplicacao() {
return aplicacao;
}
public void setAplicacao(String aplicacao) {
this.aplicacao = aplicacao;
}
public String getAndamento() {
return andamento;
}
public void setAndamento(String andamento) {
this.andamento = andamento;
}
public boolean isUrgencia() {
return urgencia;
}
public void setUrgencia(boolean urgencia) {
this.urgencia = urgencia;
}
public String getObservacoes() {
return observacoes;
}
public void setObservacoes(String observacoes) {
this.observacoes = observacoes;
}
public boolean isRessuprimento() {
return ressuprimento;
}
public void setRessuprimento(boolean ressuprimento) {
this.ressuprimento = ressuprimento;
}
}
|
package com.tencent.mm.plugin.game.ui;
import android.content.DialogInterface;
import android.content.DialogInterface.OnClickListener;
class GameDownloadView$1 implements OnClickListener {
final /* synthetic */ GameDownloadView jXJ;
GameDownloadView$1(GameDownloadView gameDownloadView) {
this.jXJ = gameDownloadView;
}
public final void onClick(DialogInterface dialogInterface, int i) {
GameDownloadView.a(this.jXJ);
}
}
|
package com.supconit.kqfx.web.fxzf.warn.services.Impl;
import java.util.List;
import jodd.util.StringUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import hc.orm.AbstractBasicOrmService;
import com.supconit.kqfx.web.fxzf.warn.daos.WarnInfoDao;
import com.supconit.kqfx.web.fxzf.warn.entities.WarnInfo;
import com.supconit.kqfx.web.fxzf.warn.services.WarnInfoService;
@Service("fxzf_warn_warninfo_service")
public class WarnInfoServiceImpl extends AbstractBasicOrmService<WarnInfo, String>
implements WarnInfoService {
@Autowired
private WarnInfoDao warnInfoDao;
@Override
public WarnInfo getById(String arg0) {
return this.warnInfoDao.getById(arg0);
}
@Override
public void save(WarnInfo entity) {
if(StringUtil.isEmpty(entity.getId()))
{
this.warnInfoDao.insert(entity);
}else{
this.warnInfoDao.update(entity);
}
}
@Override
public void insert(WarnInfo entity) {
this.warnInfoDao.insert(entity);
}
@Override
public void update(WarnInfo entity) {
this.warnInfoDao.update(entity);
}
@Override
public void delete(WarnInfo entity) {
this.delete(entity);
}
@Override
public List<WarnInfo> getAll() {
return this.warnInfoDao.getAll();
}
// @Override
// public WarnInfo getByTempletType(String templetType) {
//
// return this.warnInfoDao.getByTempletType(templetType);
// }
@Override
public WarnInfo getByTempletTypeAndStation(WarnInfo warnInfo) {
// TODO Auto-generated method stub
return this.warnInfoDao.getByTempletTypeAndStation(warnInfo);
}
}
|
// Simple test of the Java client class
//
// Keith Vertanen 4/99, updated 10/09
import java.io.*;
import java.net.*;
public class java_client_test
{
static int SIZE = 10; // how many items in each packet
static int NUM_PACKS = 3; // how many repetitions to do
public static void main( String args[] ) throws IOException
{
int port = 5010;
int dataport = -1;
int rev = 0;
if (args.length < 1)
{
System.out.println("Not enough command line arguments!");
System.out.println(" java_client_test <system-name> [port] [dataport] [reversed bytes]");
System.out.println("");
}
else
{
if (args.length > 1)
{
port = (new Integer(args[1])).intValue();
if (args.length > 2)
{
dataport = (new Integer(args[2])).intValue();
if (args.length > 3)
rev = (new Integer(args[3])).intValue();
}
}
System.out.println("Client, port " + port + ", datagram port " + dataport + ", reverse bytes " + rev);
Client myclient = new Client(port, dataport, args[0], rev);
System.out.println("Client, made connection...");
double C[];
byte D[];
C = new double[SIZE];
D = new byte[SIZE];
for (int i = 0; i < SIZE; i++)
{
C[i] = i*i + 0.5;
D[i] = (byte) i;
}
for (int i = 0; i < NUM_PACKS; i++)
{
System.out.println("Client, receiving bytes, iteration " + i);
myclient.RecvBytes(D, SIZE);
System.out.println("Client, sending doubles, iteration " + i);
myclient.SendDoubles(C, SIZE);
}
System.out.println("Client, closing connection...");
myclient.Close();
System.out.println("Client, done...");
}
}
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.