text
stringlengths 10
2.72M
|
|---|
package com.sandrapenia.ui.design;
import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.Component;
import java.awt.Font;
import java.awt.GridLayout;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import java.awt.event.MouseListener;
import java.awt.event.MouseMotionListener;
import javax.swing.ImageIcon;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
import javax.swing.border.LineBorder;
import com.sandrapenia.business.CodeTemplateBusiness;
import com.sandrapenia.entities.uml.UMLElement;
import com.sandrapenia.entities.uml.UMLEnumeration;
import com.sandrapenia.ui.ElementHeaderEditorJFrame;
import com.sandrapenia.ui.UMLCodeEditor;
public abstract class UMLUIComponent extends JPanel implements
UpdateUMLComponentInfoInterface {
protected Graph graph;
private int screenX = 0;
private int screenY = 0;
private int myX = 0;
private int myY = 0;
private boolean resizing;
private int deltaX;
private int deltaY;
private UMLElement umlElement;
private CodeTemplateBusiness codeTemplateBusiness;
private UMLUIComponent window;
private JLabel elementTitleLabel;
public UMLUIComponent(UMLElement umlElement, Graph graph, CodeTemplateBusiness codeTemplateBusiness) {
this.umlElement = umlElement;
this.codeTemplateBusiness = codeTemplateBusiness;
this.graph = graph;
this.window = this;
this.setLayout(new BorderLayout(5, 5));
setBounds(umlElement.getX(), umlElement.getY(), umlElement.getWidth(), umlElement.getHeight());
setBorder(new LineBorder(ElementColor.getColorByType(umlElement.getType()), 2));
initPanelHeader();
add(initPanelBody(umlElement), BorderLayout.CENTER);
initPanelActions();
makeDraggable(umlElement);
}
protected void setTitle() {
String title = "" + umlElement.getTitle();
elementTitleLabel.setText(title);
}
protected abstract Component initPanelBody(UMLElement umlElement);
//Es un panel dentro de la ventana que delimita una área en la que se pueden poner íconos o labels
private void initPanelHeader() {
JPanel headPanel = new JPanel();
elementTitleLabel = new JLabel(umlElement.getTitle());
setTitle();
elementTitleLabel.addMouseListener(new MouseAdapter() {
public void mouseClicked(MouseEvent e) {
ElementHeaderEditorJFrame abmElementTitleJFrame = new ElementHeaderEditorJFrame(
umlElement, window);
abmElementTitleJFrame.setVisible(true);
}
});
headPanel.add(elementTitleLabel);
JLabel jbtEditCode = new JLabel("");
jbtEditCode.setIcon(new ImageIcon(UMLClassUIComponent.class
.getResource("/com/sandrapenia/ui/image/java.png")));
jbtEditCode.addMouseListener(new MouseListener() {
public void mouseReleased(MouseEvent arg0) {}
public void mousePressed(MouseEvent arg0) {}
public void mouseExited(MouseEvent arg0) {}
public void mouseEntered(MouseEvent arg0) {}
public void mouseClicked(MouseEvent arg0) {
UMLCodeEditor umlCodeEditor = new UMLCodeEditor(umlElement,
codeTemplateBusiness);
umlCodeEditor.setVisible(true);
}
});
headPanel.add(jbtEditCode);
JLabel btnConnection = new JLabel("-->");
btnConnection.setFont(new Font("Tahoma", Font.PLAIN, 11));
btnConnection.addMouseListener(new MouseListener() {
public void mouseClicked(MouseEvent e) {
graph.onConnection(umlElement);
}
public void mouseEntered(MouseEvent e) {}
public void mouseExited(MouseEvent e) {}
public void mousePressed(MouseEvent e) {}
public void mouseReleased(MouseEvent e) {}
});
headPanel.add(btnConnection);
add(headPanel, BorderLayout.NORTH);
}
private void initPanelActions() {
JPanel panelActions = new JPanel(new BorderLayout());
JLabel btnResize = new JLabel("[--]");
btnResize.setFont(new Font("Tahoma", Font.PLAIN, 11));
btnResize.addMouseListener(new MouseListener() {
public void mouseClicked(MouseEvent e) {
screenX = e.getXOnScreen();
screenY = e.getYOnScreen();
resizing = true;
}
public void mouseEntered(MouseEvent e) {
screenX = e.getXOnScreen();
screenY = e.getYOnScreen();
resizing = true;
}
public void mouseReleased(MouseEvent arg0) {
resizing = false;
setSize(getWidth() + deltaX, getHeight() + deltaY);
umlElement.setWidth(getWidth());
umlElement.setHeight(getHeight());
graph.onElementMoved();
}
public void mouseExited(MouseEvent arg0) {
}
public void mousePressed(MouseEvent arg0) {
}
});
btnResize.addMouseMotionListener(new MouseMotionListener() {
public void mouseDragged(MouseEvent e) {
if (resizing) {
deltaX = e.getXOnScreen() - screenX;
deltaY = e.getYOnScreen() - screenY;
}
}
public void mouseMoved(MouseEvent arg0) {
}
});
panelActions.add(btnResize, BorderLayout.EAST);
JLabel btnClose = new JLabel("[X]");
btnClose.addMouseListener(new MouseAdapter() {
public void mouseClicked(MouseEvent e) {
if(e.getClickCount() == 1){
int elementClicked = JOptionPane.showConfirmDialog(
(Component) window, "¿Está seguro que desea eliminar éste elemento?",
"ADVERTENCIA", JOptionPane.YES_NO_OPTION);
if (elementClicked == JOptionPane.YES_OPTION) {
//Eliminar component, conexiones y atributos en otras clases.
graph.onElementRemoved(window, umlElement);
}
}
}
});
btnClose.setFont(new Font("Tahoma", Font.PLAIN, 11));
panelActions.add(btnClose, BorderLayout.WEST);
add(panelActions, BorderLayout.SOUTH);
}
private void makeDraggable(final UMLElement umlElement) {
this.addMouseListener(new MouseListener() {
public void mousePressed(MouseEvent e) {
screenX = e.getXOnScreen();
screenY = e.getYOnScreen();
myX = getX();
myY = getY();
}
public void mouseClicked(MouseEvent arg0) {}
public void mouseEntered(MouseEvent arg0) {}
public void mouseExited(MouseEvent arg0) {}
public void mouseReleased(MouseEvent arg0) {
umlElement.setX(getX());
umlElement.setY(getY());
graph.onElementMoved();
}
});
addMouseMotionListener(new MouseMotionListener() {
public void mouseMoved(MouseEvent arg0) {}
public void mouseDragged(MouseEvent e) {
int deltaX = e.getXOnScreen() - screenX;
int deltaY = e.getYOnScreen() - screenY;
setLocation(myX + deltaX, myY + deltaY);
}
});
}
}
|
package com.lovers.java.mapper;
import com.lovers.java.domain.LoversSpace;
import com.lovers.java.domain.LoversSpaceExample;
import java.util.List;
import org.apache.ibatis.annotations.Param;
public interface LoversSpaceMapper {
/**
* This method was generated by MyBatis Generator.
* This method corresponds to the database table lovers_space
*
* @mbg.generated Wed Sep 25 10:59:33 CST 2019
*/
long countByExample(LoversSpaceExample example);
/**
* This method was generated by MyBatis Generator.
* This method corresponds to the database table lovers_space
*
* @mbg.generated Wed Sep 25 10:59:33 CST 2019
*/
int deleteByExample(LoversSpaceExample example);
/**
* This method was generated by MyBatis Generator.
* This method corresponds to the database table lovers_space
*
* @mbg.generated Wed Sep 25 10:59:33 CST 2019
*/
int deleteByPrimaryKey(Integer spaceId);
/**
* This method was generated by MyBatis Generator.
* This method corresponds to the database table lovers_space
*
* @mbg.generated Wed Sep 25 10:59:33 CST 2019
*/
int insert(LoversSpace record);
/**
* This method was generated by MyBatis Generator.
* This method corresponds to the database table lovers_space
*
* @mbg.generated Wed Sep 25 10:59:33 CST 2019
*/
int insertSelective(LoversSpace record);
/**
* This method was generated by MyBatis Generator.
* This method corresponds to the database table lovers_space
*
* @mbg.generated Wed Sep 25 10:59:33 CST 2019
*/
List<LoversSpace> selectByExample(LoversSpaceExample example);
/**
* This method was generated by MyBatis Generator.
* This method corresponds to the database table lovers_space
*
* @mbg.generated Wed Sep 25 10:59:33 CST 2019
*/
LoversSpace selectByPrimaryKey(Integer spaceId);
/**
* This method was generated by MyBatis Generator.
* This method corresponds to the database table lovers_space
*
* @mbg.generated Wed Sep 25 10:59:33 CST 2019
*/
int updateByExampleSelective(@Param("record") LoversSpace record, @Param("example") LoversSpaceExample example);
/**
* This method was generated by MyBatis Generator.
* This method corresponds to the database table lovers_space
*
* @mbg.generated Wed Sep 25 10:59:33 CST 2019
*/
int updateByExample(@Param("record") LoversSpace record, @Param("example") LoversSpaceExample example);
/**
* This method was generated by MyBatis Generator.
* This method corresponds to the database table lovers_space
*
* @mbg.generated Wed Sep 25 10:59:33 CST 2019
*/
int updateByPrimaryKeySelective(LoversSpace record);
/**
* This method was generated by MyBatis Generator.
* This method corresponds to the database table lovers_space
*
* @mbg.generated Wed Sep 25 10:59:33 CST 2019
*/
int updateByPrimaryKey(LoversSpace record);
}
|
package net.undergroundim.server;
import java.awt.Color;
import java.awt.Toolkit;
import java.text.SimpleDateFormat;
import java.util.Date;
import javax.swing.JFrame;
import javax.swing.JScrollPane;
import javax.swing.JTextPane;
import javax.swing.text.BadLocationException;
import javax.swing.text.Style;
import javax.swing.text.StyleConstants;
import javax.swing.text.StyledDocument;
/**
*
* @author Troy
*
*/
public class Console extends JFrame{
private static final long serialVersionUID = 1557048456651437971L;
private static JTextPane log = new JTextPane();
private JScrollPane logContainer;
private static StyledDocument doc = log.getStyledDocument();
private static Style style = log.addStyle("Server", null);
static Date date;
static SimpleDateFormat sdf = new SimpleDateFormat("dd/MMM/yyyy - HH:mm:ss");
/**
* Construct a new console.
*/
public Console(){
this.setIconImage(Toolkit.getDefaultToolkit().getImage(Server.class.getResource("/icons/earth-icon.png")));
this.setSize(600,300);
this.setResizable(true);
this.setDefaultCloseOperation(EXIT_ON_CLOSE);
this.setTitle("Server Console | UnderGround IM");
log.setSize(600, 300);
log.setBackground(Color.BLACK);
log.setEditable(false);
logContainer = new JScrollPane(log,
JScrollPane.VERTICAL_SCROLLBAR_ALWAYS,
JScrollPane.HORIZONTAL_SCROLLBAR_NEVER);
logContainer.setSize(600, 300);
logContainer.setBackground(Color.BLACK);
log.setForeground(Color.WHITE);
this.add(logContainer);
this.setVisible(true);
}
/**
* Log a message with different coloured text.
*
* @param msg
* @param lineColour
*/
public void log(String msg, Color lineColour){
if(Constants.isGuiEnabled()){
if(lineColour == null)
lineColour = Color.WHITE;
try{
if(log.getText().split("\n").length > 200){
log.setText("Amount of lines exceeded 200, cleared and starting fresh." + "\n");
}
doc.insertString(doc.getLength(), getDate() + ": ", style);
StyleConstants.setForeground(style, lineColour);
doc.insertString(doc.getLength(), msg + "\n", style);
StyleConstants.setForeground(style, Color.WHITE);
}catch (BadLocationException e){
e.printStackTrace();
}
//Auto scroll
log.setCaretPosition(doc.getLength());
}else{
System.out.println(getDate() + ": " + msg);
}
}
/**
* Get the date.
*
* @return String
*/
public String getDate(){
date = new Date();
return sdf.format(date);
}
}
|
/*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package domain;
/**
*
* @author Marcos
*/
public class Genero {
private Integer idGenero;
private String nombreGenero;
public Integer getIdGenero() {
return idGenero;
}
public void setIdGenero(Integer idGenero) {
this.idGenero = idGenero;
}
public String getNombreGenero() {
return nombreGenero;
}
public void setNombreGenero(String nombreGenero) {
this.nombreGenero = nombreGenero;
}
}
|
package com.example.yuanbaodianfrontend.serviceImpl;
import com.example.yuanbaodianfrontend.dao.ExchanageMallDao;
import com.example.yuanbaodianfrontend.pojo.YbdExchanageMall;
import com.example.yuanbaodianfrontend.service.ExchanageMallService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import java.util.List;
@Service
public class ExchanageMallServiceImpl implements ExchanageMallService {
@Autowired
private ExchanageMallDao exchanageMallDao;
@Override
public List<YbdExchanageMall> SelectExchanageMall() {
return exchanageMallDao.SelectExchanageMall();
}
}
|
package edu.asu.commons.command;
public abstract class OrderedCommand implements Command {
private volatile static long hash = 0;
private final long creationTime = System.nanoTime();
private final long ordinal = hash++;
public int compareTo(OrderedCommand command) {
int comparison = compare(creationTime, command.creationTime);
if (comparison == 0) {
return compare(ordinal, command.ordinal);
}
return comparison;
}
private int compare(long a, long b) {
return (a > b) ? 1 : (a == b) ? 0 : -1;
}
}
|
package ca.oneroof.oneroof.ui.purchase;
import android.content.Context;
import android.text.Editable;
import android.text.TextWatcher;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.CompoundButton;
import android.widget.EditText;
import android.widget.LinearLayout;
import android.widget.Switch;
import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.databinding.DataBindingUtil;
import androidx.lifecycle.MutableLiveData;
import java.util.List;
import ca.oneroof.oneroof.DollarUtils;
import ca.oneroof.oneroof.R;
import ca.oneroof.oneroof.databinding.ItemDivisionEditBinding;
// danger: superfund cleanup site
public class DivisionEditAdapter extends ArrayAdapter<DivisionEdit> {
private int resource;
private List<DivisionEdit> list;
private Context context;
private MutableLiveData<Integer> total;
public DivisionEditAdapter(Context context, int resource, List<DivisionEdit> list, MutableLiveData<Integer> total) {
super(context, resource, list);
this.context = context;
this.resource = resource;
this.list = list;
this.total = total;
}
@NonNull
@Override
public View getView(int position, @Nullable View convertView, @NonNull ViewGroup parent) {
LayoutInflater inflater = LayoutInflater.from(context);
View view = inflater.inflate(resource, null, false);
ItemDivisionEditBinding binding = DataBindingUtil.bind(view);
DivisionEdit divisionEdit = list.get(position);
EditText amount = binding.getRoot().findViewById(R.id.division_amount);
amount.setText(divisionEdit.amount > 0 ? DollarUtils.formatDollars(divisionEdit.amount) : "");
amount.addTextChangedListener(new TextWatcher() {
@Override
public void beforeTextChanged(CharSequence s, int start, int count, int after) {
// Empty
}
@Override
public void onTextChanged(CharSequence s, int start, int before, int count) {
// Empty
}
@Override
public void afterTextChanged(Editable s) {
CharSequence first = null;
CharSequence second = null;
int i;
for (i = 0; i < s.length(); i++) {
if (s.charAt(i) == '.') {
first = s.subSequence(0, i);
break;
}
}
if (first == null) {
first = s;
} else {
if (s.length() > i+1) {
second = s.subSequence(i+1, s.length());
}
}
try {
int dollars = Integer.parseInt(first.toString());
int cents = second != null ? Integer.parseInt(second.toString()) : 0;
cents += dollars * 100;
divisionEdit.amount = cents;
computeTotal();
} catch (NumberFormatException ignored) {}
}
});
LinearLayout roommateLayout = binding.getRoot().findViewById(R.id.division_roommates);
for (int i = 0; i < divisionEdit.roommateNames.size(); i++) {
String roommate = divisionEdit.roommateNames.get(i);
View child = LayoutInflater.from(context).inflate(R.layout.item_roommate_toggle,
null, false);
Switch toggle = child.findViewById(R.id.roommate_toggle);
toggle.setText(roommate);
toggle.setChecked(divisionEdit.roommateEnables.get(i));
final int j = i; // lol i hate java so much
toggle.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
@Override
public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
divisionEdit.roommateEnables.set(j, isChecked);
}
});
roommateLayout.addView(child);
}
view.setTag(binding);
binding.setDivisionEdit(list.get(position));
return binding.getRoot();
}
private void computeTotal() {
int t = 0;
for (DivisionEdit edit : list) {
t += edit.amount;
}
total.setValue(t);
}
}
|
import java.awt.Robot;
import java.util.Random;
public class FirstClass {
public static final int timeInterval = 5000;
public static final int yAxis = 800;
public static final int xAxis = 800;
public static void main(String[] args) throws Exception {
Robot robot = new Robot();
Random random = new Random();
while(true) {
robot.mouseMove(random.nextInt(xAxis), random.nextInt(yAxis));
Thread.sleep(timeInterval);
}
}
}
|
package coin.coininventory.repo;
import coin.coininventory.entity.SubLocation;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.stereotype.Repository;
@Repository
public interface SubLocationRepo extends JpaRepository<SubLocation, Long> {
}
|
package com.brajagopal.rmend.data.beans;
import org.apache.commons.collections4.MapUtils;
import org.apache.commons.lang3.StringUtils;
import java.util.Map;
/**
* @author <bxr4261>
*/
public class EntitiesBean extends BaseContent {
private double relevance;
public EntitiesBean() {
this(ContentType.ENTITIES);
}
private EntitiesBean(ContentType _contentType) {
super(_contentType);
}
@Override
public void process(Map<String, ? extends Object> _value) {
this.type = MapUtils.getString(_value, "_type", MapUtils.getString(_value, "type", null));
this.forEndUserDisplay = MapUtils.getBoolean(_value, "forenduserdisplay", MapUtils.getBoolean(_value, "forEndUserDisplay", false));
this.relevance = MapUtils.getDouble(_value, "relevance", 0.0);
this.name = MapUtils.getString(_value, "name", null);
this.name = ((name.length() > 50)?StringUtils.substringBeforeLast(StringUtils.left(name, 50), "_"):this.name);
}
@Override
public BaseContent getInstance() {
return new EntitiesBean();
}
@Override
public String toString() {
return "EntitiesBean {" +
"contentType=" + getContentType() +
", type='" + getType() + '\'' +
", forEndUserDisplay=" + isForEndUserDisplay() +
", name='" + getName() + '\'' +
", score=" + getScore() +
'}';
}
public double getRelevance() {
return relevance;
}
@Override
public double getScore() {
return getRelevance();
}
}
|
package com.ican.ipay.util;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.params.BasicHttpParams;
import org.apache.http.params.HttpConnectionParams;
import org.apache.http.params.HttpParams;
import org.apache.http.protocol.HTTP;
import org.apache.http.util.EntityUtils;
import android.util.Log;
import com.ican.ipay.common.IConstants;
public final class NetUtil {
public static String targetUri = "appdownload.action";
public static HttpParams httpParams =new BasicHttpParams();
private static NetUtil self = new NetUtil();
static{
HttpConnectionParams.setConnectionTimeout(httpParams, 10*1000);
HttpConnectionParams.setSoTimeout(httpParams, 10*1000);
}
private NetUtil() {
}
public HttpURLConnection getHttpUrlConnection(String url) throws Exception{
URL u = new URL(url);
HttpURLConnection connection = (HttpURLConnection)u.openConnection();
connection.setConnectTimeout(5000);
connection.setRequestMethod("GET");
return connection;
}
public String sendMessageWithHttpPost(String uri, String message)
throws Exception {
if(!DeviceInfoUtil.isNetworkConnected()) return null;
String url=getUrl(uri)+"?"+message;
HttpGet request = new HttpGet(url);
Log.i("httpPostInfo", uri + "?" + message + " @NetUtil request");
HttpResponse response = new DefaultHttpClient(httpParams).execute(request);
String responseText=null;
if(response.getStatusLine().getStatusCode()==200){
responseText=EntityUtils.toString(response.getEntity());
}
Log.i("netInfo", "@json responseText:" + responseText
+ " @NetUtil responseText");
return responseText;
}
public String sendMessageWithHttpPost(String uri, Map<String,Object> params)
throws Exception {
if(!DeviceInfoUtil.isNetworkConnected()) return null;
HttpPost request = new HttpPost(getUrl(uri));
if(params!=null&&!params.isEmpty()){
List<NameValuePair> ls = new ArrayList<NameValuePair>();
for(Entry<String,Object> en:params.entrySet()){
ls.add(new BasicNameValuePair(en.getKey(),en.getValue().toString()));
}
request.setEntity(new UrlEncodedFormEntity(ls,HTTP.UTF_8));
}
HttpResponse response = new DefaultHttpClient(httpParams).execute(request);
HttpEntity entity=response.getEntity();
String responseText=null;responseText = EntityUtils.toString(entity);
Log.i("netInfo", "@json responseText:" + responseText
+ " @NetUtil responseText");
if(response.getStatusLine().getStatusCode()==200){
return responseText;
}
return null;
}
public String sendMessageWithHttpPost(String uri, List<NameValuePair> params)
throws Exception {
if(!DeviceInfoUtil.isNetworkConnected()) return null;
HttpPost request = new HttpPost(getUrl(uri));
if(params!=null&&!params.isEmpty())
request.setEntity(new UrlEncodedFormEntity(params,HTTP.UTF_8));
HttpResponse response = new DefaultHttpClient(httpParams).execute(request);
HttpEntity entity=response.getEntity();
String responseText=null;responseText = EntityUtils.toString(entity);
Log.i("netInfo", "@json responseText:" + responseText
+ " @NetUtil responseText");
if(response.getStatusLine().getStatusCode()==200){
return responseText;
}
return null;
}
// public AppOrder noticeServerAfterPay(String orderId,String orderTime) throws Exception{
// String resp=sendMessageWithHttpPost(UriConstants.NOTICE_AFTER_PAY,
// "orderNum="+orderId+"&orderTime="+orderTime);
// if(!TextUtils.isEmpty(resp)&&resp.startsWith("{")){
// return new Gson().fromJson(resp, AppOrder.class);
// }
// return null;
// }
private String getUrl(String uri){
return uri.startsWith("http://")?uri:IConstants.URL_PREFIX+uri;
}
public static NetUtil getInstance() {
return self;
}
}
|
/**
*
*/
package com.android.aid;
import android.content.Context;
/**
* @author wangpeifeng
*
*/
public class ReqRunningTrackerDelegate extends ServiceActionDelegate {
public static final String EXTRA_RUNNING_TRACKER = "running_tracker";
public ReqRunningTrackerDelegate(Context context, String requestAction) {
super(context, requestAction);
// TODO Auto-generated constructor stub
}
@Override
public void action() {
// TODO Auto-generated method stub
if(intentRequest.getBooleanExtra(EXTRA_RUNNING_TRACKER, false)){
MainService.startRunningTracker(context);
}
else{
MainService.pauseRunnigTracker();
}
}
}
|
public class two{
public static void main(String[] args){
for(int i = 0; i < 15; i++){
System.out.println("Hei, DAPE1400/ITPE1400");
}
}
}
|
public class Main3_3 {
public static void main(String[] args) {
int[][] matrix = {
{8, 1, 6},
{3, 5, 7},
{4, 9, 0},
};
for (int i=0;i<3;i++){
for (int j: matrix[i]){
System.out.print(j);
};
System.out.println("");
};
}
}
|
package collisions;
import gameobjects.BasicObject;
import org.newdawn.slick.geom.Rectangle;
import org.newdawn.slick.geom.Shape;
import world.LevelBuilder;
import world.Sector;
import world.SectorMap;
/*
* Provides information about physically collideable
* Objects in a level;
*
*/
public class PhysicalCollisions {
private SectorMap sectorMap;
public PhysicalCollisions( SectorMap sectorMap){
this.sectorMap = sectorMap;
}
//Checks for collisions with blocks and game Objects
public boolean isCollidedWithSolids(Shape shape){
return isCollidedWithBasicObjects(shape);
}
private boolean isCollidedWithBasicObjects(Shape shape){
for (Sector sector : sectorMap.getSectorsNear(shape)){
for(BasicObject obj: sector.getBasicObjects()){
// don't check with its own shape and dont check with objects that are currently being held
assert (obj.getShape() != null) : "Error! Object" + obj + " has no shape!";
if(obj.getShape() != shape){
if(obj.canCollide()){
if(shape.intersects(obj.getShape())){
return true;
}
}
}
}
}
return false;
}
private int[][] generateLocalMap(int xTopLeft, int yTopLeft, int widthInTiles, int heightInTiles, int tileWidth, int tileHeight){
int m = heightInTiles;
int n = widthInTiles;
int[][] map = new int[m][n];
Rectangle tileShape = new Rectangle(xTopLeft,yTopLeft,tileWidth,tileHeight);
for (int i = 0; i<m; i++){
for (int j = 0; j<n; j++){
tileShape.setX(xTopLeft + j*tileWidth);
tileShape.setY(yTopLeft + i*tileHeight);
if (isCollidedWithSolids(tileShape))
{map[i][j] = LevelBuilder.OBJECT_WALL_TILE;}
else
{
map[i][j] = LevelBuilder.OBJECT_ROOM_TILE;
}
}
}
return map;
}
public int[][] generateLocalMap(int[] localMapDimensions, int tileWidth,
int tileHeight) {
int xTopLeft = localMapDimensions[0];
int yTopLeft = localMapDimensions[1];
int widthInTiles = localMapDimensions[2];
int heightInTiles = localMapDimensions[3];
return generateLocalMap( xTopLeft, yTopLeft, widthInTiles, heightInTiles, tileWidth, tileHeight);
}
}
|
package com.github.olly.workshop.imagethumbnail.model;
import com.fasterxml.jackson.annotation.JsonIgnore;
import org.springframework.data.annotation.Id;
public class Image {
@Id
private String id;
private String contentType;
private String name;
@JsonIgnore
private byte[] data;
public Image withBytes(byte[] bytes) {
Image image = new Image();
image.setId(this.id);
image.setContentType(this.contentType);
image.setName(this.name);
image.setData(bytes);
return image;
}
public String getId() {
return id;
}
public Image setId(String id) {
this.id = id;
return this;
}
public String getContentType() {
return contentType;
}
public Image setContentType(String contentType) {
this.contentType = contentType;
return this;
}
public int getSize() {
if (getData() != null) {
return data.length;
} else {
return -1;
}
}
public byte[] getData() {
return data;
}
public Image setData(byte[] data) {
this.data = data;
return this;
}
@Override
public String toString() {
return "Image{" +
"id=" + id +
", contentType='" + contentType + '\'' +
'}';
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
}
|
package com._520it.web.product;
import java.io.IOException;
import java.util.List;
import java.util.Map;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.apache.commons.beanutils.BeanUtils;
import com._520it.domain.Category;
import com._520it.domain.Product;
import com._520it.service.AdminProductService;
import com._520it.vo.Select;
@WebServlet("/selectProduct")
/**
* 查询特定条件的商品
* @author Administrator
*
*/
public class SelectProductServlet extends HttpServlet {
public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
//处理中文乱码的问题
request.setCharacterEncoding("utf-8");
try {
//获取参数
Map<String, String[]> parameterMap = request.getParameterMap();
Select select =new Select();
//封装数据
BeanUtils.populate(select, parameterMap);
//将请求和数据传输到service层
AdminProductService service =new AdminProductService();
//返回结果
List<Product> product = service.selectProduct(select);
List<Category> categoryList = service.findAllCategory();
//将结果放到request域当中
request.setAttribute("select", select);
request.setAttribute("categoryList", categoryList);
request.setAttribute("list", product);
request.getRequestDispatcher("/admin/product/list.jsp").forward(request, response);
} catch (Exception e) {
e.printStackTrace();
}
}
public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
doGet(request, response);
}
}
|
package br.edu.infnet.appSistemaEspecialistaEmFreios.controller;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.SessionAttribute;
import br.edu.infnet.appSistemaEspecialistaEmFreios.model.domain.Disco;
import br.edu.infnet.appSistemaEspecialistaEmFreios.model.domain.Usuario;
import br.edu.infnet.appSistemaEspecialistaEmFreios.model.service.DiscoService;
@Controller
public class DiscoController {
@Autowired
private DiscoService discoService;
@GetMapping (value = "disco/lista")
public String telaLista(Model model, @SessionAttribute("user") Usuario usuario ) {
model.addAttribute("disco", discoService.obterLista(usuario));
return "disco/lista";
}
@GetMapping(value = "/disco")
public String telaCadastro() {
return "disco/cadastro";
}
@PostMapping(value = "/disco/incluir")
public String incluir(Model model, Disco disco, @SessionAttribute("user") Usuario usuario) {
disco.setUsuario(usuario);
discoService.incluir(disco);
model.addAttribute("msg", "Produto: "+ disco.getDescricao() + " cadastrado com sucesso!");
return telaLista(model, usuario);
}
@GetMapping(value = "/disco/{id}/excluir")
public String excluir(Model model, @PathVariable Integer id, @SessionAttribute("user") Usuario usuario) {
Disco disco = discoService.obterPorId(id);
String mensagem = null;
try {
discoService.excluir(id);
mensagem = "Produto: "+ disco.getDescricao() + " excluido com sucesso!";
} catch (Exception e) {
mensagem = "Produto: "+ disco.getDescricao() + " não pode ser excluido!";
}
model.addAttribute("msg", mensagem);
return telaLista(model, usuario);
}
}
|
package solid;
import shop.customers.Customer;
import shop.customers.Order;
import java.util.List;
import java.util.stream.Stream;
public class SolidMain {
public static void main(String[] args) {
Order order = new Order("1");
order.addItem(10, 5);
order.addItem(1, 12);
order.addItem(17, 3);
Customer customer = new Customer("Вася");
customer.setPhone("+3750000000");
sendSMS("+3759999999", customer, order);
sendEmail("kuku@mail.com", customer, order);
}
/**
* Отправляет смс с содержанием заказ
* @param number номер н акоторый отправлен заказ
* @param customer информация о заказчике
* @param order информация о заказе
* @return подтверждение заказа
*/
public static boolean sendSMS(String number, Customer customer, Order order){
System.out.println("Отправляем смс на номер " + number + ". Сформирован заказ : " + order.getOrderNo());
System.out.println("В заказе есть позиции : ");
for (Order.OrderItem orderItem : order.getOrderItems()) {
System.out.println(orderItem.getQuantity() + ": " + orderItem.getItemPrice() + " = " +
(orderItem.getQuantity() * orderItem.getItemPrice())
);
}
System.out.println("Сумма заказа: " + order.getOrderItems().stream().mapToDouble(i -> i.getQuantity() * i.getItemPrice()).sum());
System.out.println("Заказ сформировал " + customer.getName() + ": " + customer.getPhone());
return true;
}
/**
* Отправляет сообщение на электронный адрес с содержанием заказ
* @param number электронный адрес на который отправлен заказ
* @param customer информация о заказчике
* @param order информация о заказе
* @return подтверждение заказа
*/
public static boolean sendEmail(String number, Customer customer, Order order){
System.out.println("Отправляем электронное сообщение " + number + ". Сформирован заказ : " + order.getOrderNo());
System.out.println("В заказе есть позиции : ");
for (Order.OrderItem orderItem : order.getOrderItems()) {
System.out.println(orderItem.getQuantity() + ": " + orderItem.getItemPrice() + " = " +
(orderItem.getQuantity() * orderItem.getItemPrice())
);
}
System.out.println("Сумма заказа: " + order.getOrderItems().stream().mapToDouble(i -> i.getQuantity() * i.getItemPrice()).sum());
System.out.println("Заказ сформировал " + customer.getName() + ": " + customer.getPhone());
return true;
}
}
|
package org.ljm.runner;
import org.springframework.boot.CommandLineRunner;
import org.springframework.context.annotation.Configuration;
/**
* @Project MyWebProject
* @ClassName MyCommandLineRunner2
* @Description TODO
* @Author random
* @Date Create in 2018/4/4 14:47
* @Version 1.0
**/
@Configuration
public class MyCommandLineRunner2 implements CommandLineRunner {
@Override
public void run(String... strings) throws Exception {
System.out.println("MyCommandLineRunner2.run()");
}
}
|
package com.emg.projectsmanage.pojo;
import java.util.Date;
public class ProjectsUserModel {
private String id;
private String pid;
private Integer userid;
private String username;
private Integer roleid;
private String rolename;
private Date optime;
private Integer opuid;
private Integer systemid;
public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
public String getPid() {
return pid;
}
public void setPid(String pid) {
this.pid = pid;
}
public Integer getUserid() {
return userid;
}
public void setUserid(Integer userid) {
this.userid = userid;
}
public String getUsername() {
return username;
}
public void setUsername(String username) {
this.username = username;
}
public Integer getRoleid() {
return roleid;
}
public void setRoleid(Integer roleid) {
this.roleid = roleid;
}
public String getRolename() {
return rolename;
}
public void setRolename(String rolename) {
this.rolename = rolename;
}
public Date getOptime() {
return optime;
}
public void setOptime(Date optime) {
this.optime = optime;
}
public Integer getOpuid() {
return opuid;
}
public void setOpuid(Integer opuid) {
this.opuid = opuid;
}
public Integer getSystemid() {
return systemid;
}
public void setSystemid(Integer systemid) {
this.systemid = systemid;
}
}
|
package de.codecentric.cxf;
import com.sun.tools.xjc.api.XJC;
import org.apache.commons.io.FileUtils;
import org.apache.commons.lang3.StringUtils;
import org.apache.maven.execution.MavenSession;
import org.apache.maven.plugin.AbstractMojo;
import org.apache.maven.plugin.BuildPluginManager;
import org.apache.maven.plugin.MojoExecutionException;
import org.apache.maven.plugins.annotations.Component;
import org.apache.maven.plugins.annotations.LifecyclePhase;
import org.apache.maven.plugins.annotations.Mojo;
import org.apache.maven.plugins.annotations.Parameter;
import org.apache.maven.project.MavenProject;
import java.io.File;
import java.io.IOException;
import java.nio.charset.Charset;
import java.util.Collection;
import java.util.Optional;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import static org.twdata.maven.mojoexecutor.MojoExecutor.*;
@Mojo(name = "generate", defaultPhase=LifecyclePhase.GENERATE_SOURCES)
public class BootCxfMojo extends AbstractMojo {
private static final String GENERATED_SOURCES_TARGET_FOLDER = "target/generated-sources/wsdlimport";
private static final String TEST_GENERATED_SOURCES_TARGET_FOLDER = "target/test/generated-sources/wsdlimport";
private static final String WSDL_NOT_FOUND_ERROR_MESSAGE = ".wsdl-File not found - is it placed somewhere under /src/main/resources or /src/test/resources?";
private static final String LOG_PREFIX = "CXF-BOOT-MAVEN-PLUGIN ";
public static final String CXF_SPRING_BOOT_MAVEN_PROPERTIES_FILE_NAME = "cxf-spring-boot-maven.properties";
public static final String SEI_IMPLEMENTATION_PACKAGE_NAME_KEY = "sei.implementation.package.name";
public static final String SEI_AND_WEB_SERVICE_CLIENT_PACKAGE_NAME_KEY = "sei.and.webserviceclient.package.name";
// (?<=targetNamespace=")[:./a-zA-Z0-9]+(?=")
private static final String REGEX_FIND_TARGET_NAMESPACE_CONTENT = "(?<=targetNamespace=\")[:._/a-zA-Z0-9-]+(?=\")";
private static final String TARGET_NAMESPACE_COULDNT_BE_EXTRACTED = "targetNamespace could not be extracted from WSDL file.";
@Parameter( defaultValue = "${project}", readonly = true )
private MavenProject mavenProject;
@Parameter( defaultValue = "${session}", readonly = true )
private MavenSession mavenSession;
@Component
private BuildPluginManager pluginManager;
public void execute() throws MojoExecutionException {
logWithPrefix("STEP 0: Scanning for WSDL file in src/main/resources");
File wsdl = findWsdl(mavenProject.getBasedir());
String buildDirectory = mavenProject.getBuild().getOutputDirectory();
logWithPrefix("STEP 1: Found .wsdl-File: " + wsdl.getPath());
if(isWsdlLocatedInTestResources(wsdl)) {
logWithPrefix("STEP 2: Generating JAX-B Classfiles for Test purpose.");
generateJaxbClassFiles(wsdl, "wsimport-test", TEST_GENERATED_SOURCES_TARGET_FOLDER);
logWithPrefix("STEP 3: Adding the generated Test-Java-Classes to project´s classpath...");
addGeneratedTestClasses2Cp();
} else if(isWsdlLocatedInMainResources(wsdl)) {
logWithPrefix("STEP 2: Generating JAX-B Classfiles.");
generateJaxbClassFiles(wsdl, "wsimport", GENERATED_SOURCES_TARGET_FOLDER);
logWithPrefix("STEP 3: Adding the generated Java-Classes to project´s classpath...");
addGeneratedClasses2Cp();
}
logWithPrefix("STEP 4: Guessing SEI implementation´s package name & injecting it into " + CXF_SPRING_BOOT_MAVEN_PROPERTIES_FILE_NAME + " for later Autodetection of Endpoints...");
// The first writer to cxf-spring-boot-maven.properties should clean the file of old entries
// Otherwise just appending would lead to bogus properties
cleanCxfSpringBootMavenProperties(buildDirectory);
writeSeiImplementationPackageToCxfSpringBootMavenPropterties(buildDirectory, mavenProject.getGroupId());
logWithPrefix("STEP 5: Extracting targetNamespace from WSDL, generating packageName from it with com.sun.tools.xjc.api.XJC (see wsgen, WSImportTool and WSDLModeler at line 2312 of the JAXWSRI) and injecting it into " + CXF_SPRING_BOOT_MAVEN_PROPERTIES_FILE_NAME + " for later Autodetection of Endpoints...");
String targetNamespaceFromWsdl = readTargetNamespaceFromWsdl(readWsdlIntoString(wsdl));
String seiImplementationBasePackageName = generatePackageNameFromTargetNamespaceInWsdl(targetNamespaceFromWsdl);
writeSeiAndWebServiceClientPackageToCxfSpringBootMavenPropterties(buildDirectory, seiImplementationBasePackageName);
}
private void generateJaxbClassFiles(File wsdl, String jaxwsMavenPluginGoal, String dir2PutGeneratedClassesIn) throws MojoExecutionException {
executeMojo(
/*
* Generate Java-Classes inkl. JAXB-Bindings from WSDL & imported XSD
* See Doku at http://www.mojohaus.org/jaxws-maven-plugin/
*
* Attention: The project has been moved from codehaus to project metro in 2007:
* https://jax-ws-commons.java.net/jaxws-maven-plugin/ and then back to codehaus
* in 2015, where it is developed further: https://github.com/mojohaus/jaxws-maven-plugin
*
* From 2019/20 on the https://github.com/mojohaus/jaxws-maven-plugin is deprecated and moved to
* https://github.com/eclipse-ee4j/metro-jax-ws/tree/master/jaxws-ri/extras/jaxws-maven-plugin
*/
plugin(
groupId("com.sun.xml.ws"),
artifactId("jaxws-maven-plugin"),
version("3.0.0"),
dependencies(
dependency(
"org.jvnet.jaxb2_commons",
"jaxb2-namespace-prefix",
"1.3"))
),
goal(jaxwsMavenPluginGoal),
configuration(
/*
* See http://www.mojohaus.org/jaxws-maven-plugin/wsimport-mojo.html
*/
element(name("wsdlDirectory"), wsdlPathWithoutFileName(wsdl)),
/*
* This is very useful to NOT generate something like
* wsdlLocation = "file:/Users/myuser/devfolder/cxf-spring-boot-starter/src/test/resources/wsdl/Weather1.0.wsdl"
* into the @WebServiceClient generated Class. This could break stuff, e.g. when u build on Jenkins
* and then try to deploy on a Linux server, where the path is completely different
*/
element(name("wsdlLocation"), constructWsdlLocation(wsdl)),
element(name("sourceDestDir"), dir2PutGeneratedClassesIn),
/*
* For accessing the imported schema, see https://netbeans.org/bugzilla/show_bug.cgi?id=241570
*/
element("vmArgs",
element("vmArg", "-Djavax.xml.accessExternalSchema=all -Djavax.xml.accessExternalDTD=all")),
/*
* the binding.xml in the given directory is found automatically,
* because the directory is scanned for '.xml'-Files
*/
element("bindingDirectory", wsdlPathWithoutFileName(wsdl)),
/*
* Arguments for JAXB2-Generator behind JAX-WS-Frontend
*/
element("args",
element("arg", "-extension"),
/*
* Thats a tricky parameter: The first '-B' is for passing the following argument
* to JAXB2-Generator the second is needed to generate the human readable Namespace-
* Prefixes
*/
element("arg", "-B-Xnamespace-prefix"))
),
executionEnvironment(
mavenProject,
mavenSession,
pluginManager
)
);
}
private String constructWsdlLocation(File wsdl) throws MojoExecutionException {
String wsdlLocation = "/" + wsdlFolderInResources(wsdl) + wsdlFileName(wsdl);
logWithPrefix("setting relative wsdlLocation into @WebServiceClient: " + wsdlLocation);
return wsdlLocation;
}
private boolean isWsdlLocatedInTestResources(File wsdl) throws MojoExecutionException {
return StringUtils.contains(wsdl.getPath(), "/test/") || StringUtils.contains(wsdl.getPath(), "\\test\\");
}
private boolean isWsdlLocatedInMainResources(File wsdl) throws MojoExecutionException {
return StringUtils.contains(wsdl.getPath(), "/main/") || StringUtils.contains(wsdl.getPath(), "\\main\\");
}
private String wsdlFileName(File wsdl) throws MojoExecutionException {
return wsdl.getName();
}
private String wsdlFolderInResources(File wsdl) {
String folderAboveResourceDir = wsdlFileParentFolderName(wsdl, "");
return folderAboveResourceDir;
}
private String wsdlFileParentFolderName(File wsdl, String folderAboveResourceDir) {
if(!"resources".equals(wsdl.getParentFile().getName())) {
folderAboveResourceDir = wsdl.getParentFile().getName() + "/" + folderAboveResourceDir;
return wsdlFileParentFolderName(wsdl.getParentFile(), folderAboveResourceDir);
} else {
return folderAboveResourceDir;
}
}
private String wsdlPathWithoutFileName(File wsdl) throws MojoExecutionException {
return wsdl.getParent();
}
protected File findWsdl(File buildDirectory) throws MojoExecutionException {
String[] extension = {"wsdl"};
Collection<File> wsdls = FileUtils.listFiles(buildDirectory, extension, true);
filterOutWsdlsInsideBuildOutputFolder(wsdls);
Optional<File> wsdl = wsdls.stream().findFirst();
if(wsdl.isPresent()) {
return wsdl.get();
} else {
throw new MojoExecutionException(WSDL_NOT_FOUND_ERROR_MESSAGE);
}
}
private void filterOutWsdlsInsideBuildOutputFolder(Collection<File> wsdls) {
if(mavenProject != null) {
String targetDirectory = mavenProject.getBuild().getOutputDirectory().replaceAll("classes$", "");
wsdls.removeIf(f -> f.getAbsolutePath().startsWith(targetDirectory));
}
}
private void addGeneratedClasses2Cp() throws MojoExecutionException {
/*
* Add the generated Java-Classes to classpath
*/
executeMojo(
plugin(
groupId("org.codehaus.mojo"),
artifactId("build-helper-maven-plugin"),
version("3.0.0")
),
goal("add-source"),
configuration(
element("sources",
element("source", GENERATED_SOURCES_TARGET_FOLDER))
),
executionEnvironment(
mavenProject,
mavenSession,
pluginManager
)
);
}
private void addGeneratedTestClasses2Cp() throws MojoExecutionException {
/*
* Add the generated Java-Classes to classpath
*/
executeMojo(
plugin(
groupId("org.codehaus.mojo"),
artifactId("build-helper-maven-plugin"),
version("3.0.0")
),
goal("add-test-source"),
configuration(
element("sources",
element("source", TEST_GENERATED_SOURCES_TARGET_FOLDER))
),
executionEnvironment(
mavenProject,
mavenSession,
pluginManager
)
);
}
private void logWithPrefix(String logMessage) {
getLog().info(LOG_PREFIX + logMessage);
}
protected String readTargetNamespaceFromWsdl(String wsdl) throws MojoExecutionException {
Matcher matcher = buildMatcher(wsdl, REGEX_FIND_TARGET_NAMESPACE_CONTENT);
if (matcher.find()) {
return matcher.group(0);
} else {
throw new MojoExecutionException(TARGET_NAMESPACE_COULDNT_BE_EXTRACTED);
}
}
protected static String readWsdlIntoString(File wsdl) throws MojoExecutionException {
try {
return FileUtils.readFileToString(wsdl, Charset.defaultCharset());
} catch (IOException ioEx) {
throw new MojoExecutionException("Problems in transforming WSDL File to String.", ioEx);
}
}
private static Matcher buildMatcher(String string2SearchIn, String regex) {
Pattern pattern = Pattern.compile(regex);
return pattern.matcher(string2SearchIn);
}
protected String generatePackageNameFromTargetNamespaceInWsdl(String targetNamespaceFromWsdl) throws MojoExecutionException {
/*
* We need to use the same mechanism jaxws-maven-plugin, which itself uses WSimportTool of the JAXWS-RI implementation,
* to obtain the package-Name from the WSDL file, where the classes are generated to. The WSDL´s targetNamespace is
* used to generate the package name. If you have targetNamespace="http://www.codecentric.de/namespace/weatherservice/"
* for example, your package will be de.codecentric.namespace.weatherservice.
* The code is in WSDLModeler at line 2312:
*/
return XJC.getDefaultPackageName(targetNamespaceFromWsdl);
}
protected void writeSeiAndWebServiceClientPackageToCxfSpringBootMavenPropterties(String outputDirectory, String packageName) throws MojoExecutionException {
writeCxfSpringBootMavenProperties(outputDirectory, SEI_AND_WEB_SERVICE_CLIENT_PACKAGE_NAME_KEY, packageName);
}
protected void writeSeiImplementationPackageToCxfSpringBootMavenPropterties(String outputDirectory, String packageName) throws MojoExecutionException {
writeCxfSpringBootMavenProperties(outputDirectory, SEI_IMPLEMENTATION_PACKAGE_NAME_KEY, packageName);
}
protected void writeCxfSpringBootMavenProperties(String outputDirectory, String propertyKey, String packageName) throws MojoExecutionException {
try {
File cxfSpringBootMavenProperties = new File(outputDirectory + "/" + CXF_SPRING_BOOT_MAVEN_PROPERTIES_FILE_NAME);
FileUtils.writeStringToFile(cxfSpringBootMavenProperties, propertyKey + "=" + packageName + "\n", Charset.defaultCharset(), true);
} catch (IOException ioExc) {
throw new MojoExecutionException("Could not inject packageName into " + CXF_SPRING_BOOT_MAVEN_PROPERTIES_FILE_NAME + "." +
"Have you set the pom groupId correctly?", ioExc);
}
}
public void cleanCxfSpringBootMavenProperties(String outputDirectory) throws MojoExecutionException {
try {
File cxfSpringBootMavenProperties = new File(outputDirectory + "/" + CXF_SPRING_BOOT_MAVEN_PROPERTIES_FILE_NAME);
FileUtils.writeStringToFile(cxfSpringBootMavenProperties, "", Charset.defaultCharset());
} catch (IOException ioExc) {
throw new MojoExecutionException("Could not clean " + CXF_SPRING_BOOT_MAVEN_PROPERTIES_FILE_NAME, ioExc);
}
}
}
|
package com.cb.cbfunny.activity;
import android.app.Dialog;
import android.app.ProgressDialog;
import android.net.Uri;
import android.os.AsyncTask;
import android.os.Bundle;
import android.support.v4.view.PagerAdapter;
import android.support.v4.view.ViewPager;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;
import com.android.volley.VolleyError;
import com.cb.cbdialog.AVLoadingIndicatorView;
import com.cb.cbfunny.CbApplication;
import com.cb.cbfunny.Constans;
import com.cb.cbfunny.R;
import com.cb.cbfunny.pullrefresh.CBPullToRefreshListView;
import com.cb.cbfunny.qb.bean.Article;
import com.cb.cbfunny.qb.bean.User;
import com.cb.cbfunny.ui.PagerSlidingTabStrip;
import com.cb.cbfunny.ui.PullScrollView;
import com.cb.cbfunny.utils.ArticleParseUtils;
import com.cb.cbfunny.utils.HttpUtils;
import com.cb.cbfunny.utils.StringUtils;
import com.cb.cbfunny.utils.SystemManage;
import com.cb.cbfunny.utils.ToastUtil;
import com.cb.cbfunny.utils.UserinfoParseUtil;
import com.facebook.drawee.view.SimpleDraweeView;
import org.json.JSONException;
import org.json.JSONObject;
import java.util.ArrayList;
import java.util.Random;
/**
* UserInfoActivity.
*
* @author zhl
*/
public class UserInfoActivity extends SwipeBackActivity implements
PullScrollView.OnScrollingListener, HttpUtils.OnVolleyResponseListener, View.OnClickListener {
private PullScrollView mScrollView;
private SimpleDraweeView mHeadImg, userImg;
private TextView userName, userGender, userAstrology, userSignature,
userPhone, userAge, userHometown, userJob, userEmotion;
Dialog proDialog;
private User user;
private ImageView btnBack;
private boolean isCurrentUser;
private PagerSlidingTabStrip tabStrip;
private ViewPager mPager;
private UserInfoTabAdapter tabAdapter;
private String[] UserInfoTab = new String[]{"简介", "他的糗事"};
private ImageView listEmpty;
private CBPullToRefreshListView pullToRefreshListView;
private AVLoadingIndicatorView loadingIndicator;
private ArrayList<Article> userArticleList = new ArrayList<Article>();
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.user_info);
isCurrentUser = getIntent().getBooleanExtra(Constans.PARAM_ISCURRENT_USER, false);
String userid = null;
if (isCurrentUser) {
user = (User) getIntent().getSerializableExtra(Constans.PARAM_USER);
userid = user.getId();
} else {
userid = getIntent().getStringExtra(Constans.PARAM_USERID);
}
initView();
loadDataAsync(userid);
}
protected void initView() {
tabStrip = (PagerSlidingTabStrip) findViewById(R.id.tab_layout);
mPager = (ViewPager) findViewById(R.id.view_pager);
mPager.setAdapter(tabAdapter = new UserInfoTabAdapter());
tabStrip.setViewPager(mPager);
userName = (TextView) findViewById(R.id.user_name);
userSignature = (TextView) findViewById(R.id.user_signature);
mScrollView = (PullScrollView) findViewById(R.id.scroll_view);
mHeadImg = (SimpleDraweeView) findViewById(R.id.background_img);
LinearLayout header = (LinearLayout) findViewById(R.id.head_layout);
mScrollView.setHeader(header);
mScrollView.setOnScrollingListener(this);
userImg = (SimpleDraweeView) findViewById(R.id.user_avatar);
btnBack = (ImageView) findViewById(R.id.top_btn_back);
btnBack.setOnClickListener(this);
// Random random = new Random();
// int increase = random.nextInt(4);
// int pos = R.drawable.bg_userinfo_head_0+increase;
// mHeadImg.setImageResource(pos);
}
private void loadDataAsync(final String userid) {
if (userid != null) {
new AsyncTask<String, Void, Void>() {
@Override
protected void onPreExecute() {
proDialog = new ProgressDialog(UserInfoActivity.this);
proDialog.setTitle(R.string.dialog_msg_loadinguserinfo);
proDialog.show();
}
@Override
protected Void doInBackground(String... params) {
if ((isCurrentUser && user.getIntroduce() == null) || !isCurrentUser) {
HttpUtils httpUtils = new HttpUtils(UserInfoActivity.this, UserInfoActivity.this);
Random random = new Random();
int qrcnt = random.nextInt(10);
String url = String.format(Constans.USER_INFO, userid, qrcnt, SystemManage.getDeviceID(UserInfoActivity.this));
httpUtils.getToJson(url);
// 获取用户文章
qrcnt++;
String userRecentUrl = Constans.USER_RECENT;
userRecentUrl = String.format(userRecentUrl,userid,qrcnt,CbApplication.DeviceId);
HttpUtils netWorkUtils = new HttpUtils(UserInfoActivity.this, new HttpUtils.OnVolleyResponseListener() {
@Override
public void onErrorResponse(VolleyError error) {
}
@Override
public void onResponse(JSONObject response) {
try {
if(response.has("err_msg")&&response.has("err")&&response.getInt("err")==108){
ToastUtil.showToast(UserInfoActivity.this,response.getString("err_msg"),0);
return;
}
} catch (JSONException e) {
e.printStackTrace();
}
userArticleList = ArticleParseUtils.getArticleList(response,null);
if(userArticleList!=null&&userArticleList.size()>0){
pullToRefreshListView.setAdapter(new UserArticleListAdapter());
}
}
@Override
public void onResponse(String response) {
}
});
netWorkUtils.getToJson(userRecentUrl);
}
return null;
}
@Override
protected void onPostExecute(Void result) {
if (isCurrentUser && user.getIntroduce() != null) {
proDialog.dismiss();
loadUserinfo(user);
}
}
}.execute();
}
}
private void loadUserinfo(User user) {
if (null != user) {
String uri = StringUtils.getUserimgUrl(user.id, user.icon);
userImg.setImageURI(Uri.parse(uri));
if (user.big_cover != null && !"".equals(user.big_cover)) {
mHeadImg.setImageURI(Uri.parse(user.big_cover));
}
if (userName != null) {
userName.setText(user.login);
}
if (userAstrology != null) {
userAstrology.setText(String.format(getString(R.string.user_astrology), user.astrology));
}
if (userGender != null) {
userGender.setText(String.format(getString(R.string.user_gender), user.gender));
}
if (userSignature != null) {
userSignature.setText(user.signature);
}
if (userPhone != null) {
userPhone.setText(String.format(getString(R.string.user_phone), user.mobileBrand));
}
if (userAge != null) {
userAge.setText(String.format(getString(R.string.user_age), user.age));
}
if (userHometown != null) {
userHometown.setText(String.format(getString(R.string.user_hometown), user.hometown));
}
if (userJob != null) {
userJob.setText(String.format(getString(R.string.user_job), user.job));
}
if (userEmotion != null) {
userEmotion.setText(String.format(getString(R.string.user_emotion), user.emotion));
}
// 如果是当前用户缓存user
if (isCurrentUser) {
saveObjToFile(user, user.getId());
}
}
// else{
// if(userName!=null){
// userName.setText(R.string.user_name_default);
// }
// if(userAstrology!=null){
// userAstrology.setText(R.string.user_astrology_default);
// }
// if(userGender!=null){
// userGender.setText(R.string.user_gender_default);
// }
// if(userSignature!=null){
// userSignature.setText(R.string.user_singature_default);
// }
// if(userPhone!=null){
// userPhone.setText(R.string.user_phone_default);
// }
//
// }
}
@Override
public void onErrorResponse(VolleyError error) {
proDialog.dismiss();
}
@Override
public void onResponse(JSONObject response) {
proDialog.dismiss();
if (user == null) {
user = new User();
}
loadUserinfo(UserinfoParseUtil.getUserinfoByJson(response, user));
}
@Override
public void onResponse(String response) {
}
@Override
public void onClick(View v) {
switch (v.getId()) {
case R.id.top_btn_back:
this.finish();
break;
default:
break;
}
}
private void startIconRotateAnim(float degree) {
userImg.setPivotX(userImg.getWidth() / 2);
userImg.setPivotY(userImg.getHeight() / 2);
userImg.setRotation(degree);
}
@Override
public void onPullingDown(float dy) {
startIconRotateAnim(dy * 0.5f);
}
@Override
public void onRollingBack(float dy) {
startIconRotateAnim(dy);
}
private class UserInfoTabAdapter extends PagerAdapter {
@Override
public int getCount() {
return UserInfoTab.length;
}
@Override
public boolean isViewFromObject(View view, Object object) {
return view == object;
}
@Override
public Object instantiateItem(ViewGroup container, int position) {
View content = null;
LayoutInflater inflater = LayoutInflater.from(UserInfoActivity.this);
if (position == 0) {
content = inflater.inflate(R.layout.user_info_intro, container, false);
userGender = (TextView) content.findViewById(R.id.user_gender);
userAstrology = (TextView) content.findViewById(R.id.user_astrology);
userPhone = (TextView) content.findViewById(R.id.user_phone);
userAge = (TextView) content.findViewById(R.id.user_age);
userHometown = (TextView) content.findViewById(R.id.user_hometown);
userJob = (TextView) content.findViewById(R.id.user_job);
userEmotion = (TextView) content.findViewById(R.id.user_emotion);
} else {
content = inflater.inflate(R.layout.user_info_article, container, false);
listEmpty = (ImageView) content.findViewById(R.id.list_empty);
loadingIndicator = (AVLoadingIndicatorView) content.findViewById(R.id.loading_pro_indicator);
pullToRefreshListView = (CBPullToRefreshListView) content.findViewById(R.id.user_article_list);
pullToRefreshListView.setPullLoadMoreEnable(false);
pullToRefreshListView.setAdapter(new UserArticleListAdapter());
}
container.addView(content);
return content;
}
@Override
public void destroyItem(ViewGroup container, int position, Object object) {
container.removeView((View) object);
}
@Override
public CharSequence getPageTitle(int position) {
return UserInfoTab[position];
}
}
private class UserArticleListAdapter extends BaseAdapter {
@Override
public int getCount() {
return userArticleList == null ? 0 : userArticleList.size();
}
@Override
public Object getItem(int position) {
return userArticleList.get(position);
}
@Override
public long getItemId(int position) {
return position;
}
@Override
public View getView(int position, View convertView, ViewGroup parent) {
ViewHolder viewHolder = null;
if (convertView == null) {
viewHolder = new ViewHolder();
convertView = LayoutInflater.from(UserInfoActivity.this).inflate(R.layout.premmptive_item_list, parent, false);
viewHolder.container = (LinearLayout) convertView.findViewById(R.id.time_flow_contanier);
viewHolder.time = (TextView) convertView.findViewById(R.id.time);
viewHolder.content = (TextView) convertView.findViewById(R.id.content);
viewHolder.lineShort = convertView.findViewById(R.id.line_top_short);
viewHolder.lineLong = convertView.findViewById(R.id.line_bottom_long);
viewHolder.lineDot = convertView.findViewById(R.id.line_dot);
viewHolder.lineCircle = convertView.findViewById(R.id.line_circle);
convertView.setTag(viewHolder);
} else {
viewHolder = (ViewHolder) convertView.getTag();
}
if(position==0){
viewHolder.lineShort.setVisibility(View.INVISIBLE);
}else{
viewHolder.lineShort.setVisibility(View.VISIBLE);
}
final Article acticle = userArticleList.get(position);
viewHolder.time.setText(acticle.getPublishtime());
viewHolder.content.setText(acticle.getContent());
return convertView;
}
}
class ViewHolder {
LinearLayout container;
TextView time;
TextView content;
View lineShort;
View lineLong;
View lineDot;
View lineCircle;
ImageView share;
}
}
|
package com.hfjy.framework.net.http.entity;
public class DefaultControllerConfig implements ControllerConfig {
@Override
public String getCharacterEncoding() {
return "UTF-8";
}
@Override
public String getPrefix() {
return "";
}
@Override
public String getSuffix() {
return "";
}
@Override
public String[] getControllersPackages() {
return new String[0];
}
@Override
public ControllerDataChecker getDataChecker() {
return null;
}
@Override
public TypeProcessor<?>[] getTypeProcessor() {
return null;
}
}
|
/**
* Sencha GXT 1.0.0-SNAPSHOT - Sencha for GWT
* Copyright (c) 2006-2018, Sencha Inc.
*
* licensing@sencha.com
* http://www.sencha.com/products/gxt/license/
*
* ================================================================================
* Commercial License
* ================================================================================
* This version of Sencha GXT is licensed commercially and is the appropriate
* option for the vast majority of use cases.
*
* Please see the Sencha GXT Licensing page at:
* http://www.sencha.com/products/gxt/license/
*
* For clarification or additional options, please contact:
* licensing@sencha.com
* ================================================================================
*
*
*
*
*
*
*
*
* ================================================================================
* Disclaimer
* ================================================================================
* THIS SOFTWARE IS DISTRIBUTED "AS-IS" WITHOUT ANY WARRANTIES, CONDITIONS AND
* REPRESENTATIONS WHETHER EXPRESS OR IMPLIED, INCLUDING WITHOUT LIMITATION THE
* IMPLIED WARRANTIES AND CONDITIONS OF MERCHANTABILITY, MERCHANTABLE QUALITY,
* FITNESS FOR A PARTICULAR PURPOSE, DURABILITY, NON-INFRINGEMENT, PERFORMANCE AND
* THOSE ARISING BY STATUTE OR FROM CUSTOM OR USAGE OF TRADE OR COURSE OF DEALING.
* ================================================================================
*/
package com.sencha.gxt.explorer.client.dnd;
import com.google.gwt.core.client.EntryPoint;
import com.google.gwt.core.client.GWT;
import com.google.gwt.editor.client.Editor.Path;
import com.google.gwt.user.client.ui.IsWidget;
import com.google.gwt.user.client.ui.Widget;
import com.sencha.gxt.core.client.Style.SelectionMode;
import com.sencha.gxt.core.client.ValueProvider;
import com.sencha.gxt.core.client.util.Margins;
import com.sencha.gxt.data.shared.ListStore;
import com.sencha.gxt.data.shared.ModelKeyProvider;
import com.sencha.gxt.data.shared.PropertyAccess;
import com.sencha.gxt.data.shared.SortDir;
import com.sencha.gxt.data.shared.Store.StoreSortInfo;
import com.sencha.gxt.dnd.core.client.DND.Feedback;
import com.sencha.gxt.dnd.core.client.ListViewDragSource;
import com.sencha.gxt.dnd.core.client.ListViewDropTarget;
import com.sencha.gxt.examples.resources.client.Utils;
import com.sencha.gxt.examples.resources.client.Utils.Theme;
import com.sencha.gxt.examples.resources.client.model.ExampleData;
import com.sencha.gxt.examples.resources.client.model.Stock;
import com.sencha.gxt.examples.resources.client.model.StockProxy;
import com.sencha.gxt.explorer.client.app.ui.ExampleContainer;
import com.sencha.gxt.explorer.client.model.Example.Detail;
import com.sencha.gxt.widget.core.client.ContentPanel;
import com.sencha.gxt.widget.core.client.ListView;
import com.sencha.gxt.widget.core.client.container.BorderLayoutContainer;
import com.sencha.gxt.widget.core.client.container.BorderLayoutContainer.BorderLayoutData;
import com.sencha.gxt.widget.core.client.container.VerticalLayoutContainer;
import com.sencha.gxt.widget.core.client.container.VerticalLayoutContainer.VerticalLayoutData;
@Detail(
name = "List to List",
icon = "listtolist",
category = "Drag & Drop",
classes = {StockProxy.class, Utils.class},
minHeight = ListViewDndExample.MIN_HEIGHT,
minWidth = ListViewDndExample.MIN_WIDTH
)
public class ListViewDndExample implements IsWidget, EntryPoint {
interface StockProperties extends PropertyAccess<Stock> {
@Path("symbol")
ModelKeyProvider<StockProxy> key();
@Path("name")
ValueProvider<StockProxy, String> nameProp();
}
protected static final int MIN_HEIGHT = 450;
protected static final int MIN_WIDTH = 450;
private VerticalLayoutContainer panel;
@Override
public Widget asWidget() {
if (panel == null) {
panel = new VerticalLayoutContainer();
panel.add(createListView1And2(), new VerticalLayoutData(1, 0.5, new Margins(0, 0, 10, 0)));
panel.add(createListView3And4(), new VerticalLayoutData(1, 0.5, new Margins(10, 0, 0, 0)));
}
return panel;
}
private ContentPanel createListView1And2() {
StockProperties properties = GWT.create(StockProperties.class);
ListStore<StockProxy> store = new ListStore<StockProxy>(properties.key());
store.addSortInfo(new StoreSortInfo<StockProxy>(properties.nameProp(), SortDir.ASC));
store.addAll(ExampleData.getStocks());
ListStore<StockProxy> store2 = new ListStore<StockProxy>(properties.key());
store2.addSortInfo(new StoreSortInfo<StockProxy>(properties.nameProp(), SortDir.ASC));
ListView<StockProxy, String> listView1 = new ListView<StockProxy, String>(store, properties.nameProp());
listView1.setBorders(Theme.BLUE.isActive() || Theme.GRAY.isActive() ? true : false);
ListView<StockProxy, String> listView2 = new ListView<StockProxy, String>(store2, properties.nameProp());
listView2.setBorders(Theme.BLUE.isActive() || Theme.GRAY.isActive() ? true : false);
listView2.getSelectionModel().setSelectionMode(SelectionMode.MULTI);
new ListViewDragSource<StockProxy>(listView1).setGroup("top");
new ListViewDragSource<StockProxy>(listView2).setGroup("top");
new ListViewDropTarget<StockProxy>(listView1).setGroup("top");
new ListViewDropTarget<StockProxy>(listView2).setGroup("top");
BorderLayoutData westData = new BorderLayoutData(0.5);
westData.setMargins(Theme.BLUE.isActive() || Theme.GRAY.isActive() ? new Margins(0) : new Margins(0, 2, 0, 0));
BorderLayoutData centerData = new BorderLayoutData();
centerData.setMargins(Theme.BLUE.isActive() || Theme.GRAY.isActive() ? new Margins(0) : new Margins(0, 0, 0, 2));
BorderLayoutContainer borderLayoutContainer = new BorderLayoutContainer();
borderLayoutContainer.setWestWidget(listView1, westData);
borderLayoutContainer.setCenterWidget(listView2, centerData);
ContentPanel panel = new ContentPanel();
panel.setHeading("List to List — Insert at Sort Position");
panel.add(borderLayoutContainer);
return panel;
}
private ContentPanel createListView3And4() {
StockProperties properties = GWT.create(StockProperties.class);
ListStore<StockProxy> store3 = new ListStore<StockProxy>(properties.key());
store3.addAll(ExampleData.getStocks());
ListView<StockProxy, String> listView3 = new ListView<StockProxy, String>(store3, properties.nameProp());
listView3.setBorders(Theme.BLUE.isActive() || Theme.GRAY.isActive() ? true : false);
ListStore<StockProxy> store4 = new ListStore<StockProxy>(properties.key());
ListView<StockProxy, String> listView4 = new ListView<StockProxy, String>(store4, properties.nameProp());
listView4.setBorders(Theme.BLUE.isActive() || Theme.GRAY.isActive() ? true : false);
new ListViewDragSource<StockProxy>(listView3).setGroup("bottom");
new ListViewDragSource<StockProxy>(listView4).setGroup("bottom");
ListViewDropTarget<StockProxy> target1 = new ListViewDropTarget<StockProxy>(listView3);
target1.setFeedback(Feedback.INSERT);
target1.setGroup("bottom");
ListViewDropTarget<StockProxy> target2 = new ListViewDropTarget<StockProxy>(listView4);
target2.setFeedback(Feedback.INSERT);
target2.setGroup("bottom");
BorderLayoutData westData = new BorderLayoutData(0.5);
westData.setMargins(Theme.BLUE.isActive() || Theme.GRAY.isActive() ? new Margins(0) : new Margins(0, 2, 0, 0));
BorderLayoutData centerData = new BorderLayoutData();
centerData.setMargins(Theme.BLUE.isActive() || Theme.GRAY.isActive() ? new Margins(0) : new Margins(0, 0, 0, 2));
BorderLayoutContainer borderLayoutContainer = new BorderLayoutContainer();
borderLayoutContainer.setWestWidget(listView3, westData);
borderLayoutContainer.setCenterWidget(listView4, centerData);
ContentPanel panel = new ContentPanel();
panel.setHeading("List to List — Insert at Drop Position");
panel.add(borderLayoutContainer);
return panel;
}
@Override
public void onModuleLoad() {
new ExampleContainer(this)
.setMinHeight(MIN_HEIGHT)
.setMinWidth(MIN_WIDTH)
.doStandalone();
}
}
|
package com.zc.base.sys.modules.language.repository;
import com.zc.base.orm.mybatis.annotation.MyBatisRepository;
import com.zc.base.sys.modules.language.entity.Language;
import java.util.List;
@MyBatisRepository("languageDao")
public abstract interface LanguageDao {
public abstract List<Language> getAllLanguages();
}
|
package servlets;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.ArrayList;
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 model.Produto;
import service.ProdutoService;
@WebServlet("/Lista_Produtos.do")
public class Lista_Produtos extends HttpServlet {
private static final long serialVersionUID = 1L;
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
ProdutoService produtoService = new ProdutoService();
ArrayList<Produto> listaProdutos = produtoService.listarProdutos();
response.setContentType("text/html");
PrintWriter saida = response.getWriter();
saida.println("Lista de produtos: " + "<br>");
listaProdutos.forEach(p -> {
saida.println("- Código: " + p.getCodigo());
saida.println(" - Nome: " + p.getNome());
saida.println(" - Descrição: " + p.getDescricao());
saida.println(" - Valor: " + p.getValor());
saida.println(" - Estoque: " + p.getEstoque());
saida.println("<br>");
});
}
}
|
package com.git.cloud.cache;
public abstract interface CacheProvider
{
public abstract Cache buildCache(String paramString)
throws CacheException;
}
|
/*
* Copyright 2002-2023 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.validation.beanvalidation;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.reflect.Method;
import jakarta.validation.ValidationException;
import jakarta.validation.Validator;
import jakarta.validation.constraints.Max;
import jakarta.validation.constraints.NotNull;
import jakarta.validation.groups.Default;
import org.aopalliance.intercept.MethodInterceptor;
import org.aopalliance.intercept.MethodInvocation;
import org.junit.jupiter.api.Test;
import org.springframework.aop.framework.ProxyFactory;
import org.springframework.beans.MutablePropertyValues;
import org.springframework.beans.factory.FactoryBean;
import org.springframework.beans.factory.ObjectProvider;
import org.springframework.context.annotation.AnnotationConfigApplicationContext;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Lazy;
import org.springframework.context.support.StaticApplicationContext;
import org.springframework.core.BridgeMethodResolver;
import org.springframework.lang.Nullable;
import org.springframework.scheduling.annotation.Async;
import org.springframework.scheduling.annotation.AsyncAnnotationAdvisor;
import org.springframework.scheduling.annotation.AsyncAnnotationBeanPostProcessor;
import org.springframework.util.ClassUtils;
import org.springframework.util.ReflectionUtils;
import org.springframework.validation.annotation.Validated;
import static org.assertj.core.api.Assertions.assertThat;
import static org.assertj.core.api.Assertions.assertThatExceptionOfType;
/**
* Tests for proxy-based method validation via {@link MethodValidationInterceptor}
* and/or {@link MethodValidationPostProcessor}.
*
* @author Juergen Hoeller
* @author Rossen Stoyanchev
*/
public class MethodValidationProxyTests {
@Test
@SuppressWarnings("unchecked")
public void testMethodValidationInterceptor() {
MyValidBean bean = new MyValidBean();
ProxyFactory factory = new ProxyFactory(bean);
factory.addAdvice(new MethodValidationInterceptor());
factory.addAdvisor(new AsyncAnnotationAdvisor());
doTestProxyValidation((MyValidInterface<String>) factory.getProxy());
}
@Test
@SuppressWarnings("unchecked")
public void testMethodValidationPostProcessor() {
StaticApplicationContext context = new StaticApplicationContext();
context.registerSingleton("mvpp", MethodValidationPostProcessor.class);
MutablePropertyValues pvs = new MutablePropertyValues();
pvs.add("beforeExistingAdvisors", false);
context.registerSingleton("aapp", AsyncAnnotationBeanPostProcessor.class, pvs);
context.registerSingleton("bean", MyValidBean.class);
context.refresh();
doTestProxyValidation(context.getBean("bean", MyValidInterface.class));
context.close();
}
@Test // gh-29782
@SuppressWarnings("unchecked")
public void testMethodValidationPostProcessorForInterfaceOnlyProxy() {
AnnotationConfigApplicationContext context = new AnnotationConfigApplicationContext();
context.register(MethodValidationPostProcessor.class);
context.registerBean(MyValidInterface.class, () ->
ProxyFactory.getProxy(MyValidInterface.class, new MyValidClientInterfaceMethodInterceptor()));
context.refresh();
doTestProxyValidation(context.getBean(MyValidInterface.class));
context.close();
}
@SuppressWarnings("DataFlowIssue")
private void doTestProxyValidation(MyValidInterface<String> proxy) {
assertThat(proxy.myValidMethod("value", 5)).isNotNull();
assertThatExceptionOfType(ValidationException.class).isThrownBy(() -> proxy.myValidMethod("value", 15));
assertThatExceptionOfType(ValidationException.class).isThrownBy(() -> proxy.myValidMethod(null, 5));
assertThatExceptionOfType(ValidationException.class).isThrownBy(() -> proxy.myValidMethod("value", 0));
proxy.myValidAsyncMethod("value", 5);
assertThatExceptionOfType(ValidationException.class).isThrownBy(() -> proxy.myValidAsyncMethod("value", 15));
assertThatExceptionOfType(ValidationException.class).isThrownBy(() -> proxy.myValidAsyncMethod(null, 5));
assertThat(proxy.myGenericMethod("myValue")).isEqualTo("myValue");
assertThatExceptionOfType(ValidationException.class).isThrownBy(() -> proxy.myGenericMethod(null));
}
@Test
public void testLazyValidatorForMethodValidation() {
doTestLazyValidatorForMethodValidation(LazyMethodValidationConfig.class);
}
@Test
public void testLazyValidatorForMethodValidationWithProxyTargetClass() {
doTestLazyValidatorForMethodValidation(LazyMethodValidationConfigWithProxyTargetClass.class);
}
@Test
public void testLazyValidatorForMethodValidationWithValidatorProvider() {
doTestLazyValidatorForMethodValidation(LazyMethodValidationConfigWithValidatorProvider.class);
}
private void doTestLazyValidatorForMethodValidation(Class<?> configClass) {
AnnotationConfigApplicationContext context = new AnnotationConfigApplicationContext();
context.register(configClass, CustomValidatorBean.class, MyValidBean.class, MyValidFactoryBean.class);
context.getDefaultListableBeanFactory().getBeanDefinition("customValidatorBean").setLazyInit(true);
context.refresh();
assertThat(context.getDefaultListableBeanFactory().containsSingleton("customValidatorBean")).isFalse();
context.getBeansOfType(MyValidInterface.class).values().forEach(bean -> bean.myValidMethod("value", 5));
assertThat(context.getDefaultListableBeanFactory().containsSingleton("customValidatorBean")).isTrue();
context.close();
}
@MyStereotype
public static class MyValidBean implements MyValidInterface<String> {
@SuppressWarnings("DataFlowIssue")
@NotNull
@Override
public Object myValidMethod(String arg1, int arg2) {
return (arg2 == 0 ? null : "value");
}
@Override
public void myValidAsyncMethod(String arg1, int arg2) {
}
@Override
public String myGenericMethod(String value) {
return value;
}
}
@MyStereotype
public static class MyValidFactoryBean implements FactoryBean<String>, MyValidInterface<String> {
@Override
public String getObject() {
return null;
}
@Override
public Class<?> getObjectType() {
return String.class;
}
@SuppressWarnings("DataFlowIssue")
@NotNull
@Override
public Object myValidMethod(String arg1, int arg2) {
return (arg2 == 0 ? null : "value");
}
@Override
public void myValidAsyncMethod(String arg1, int arg2) {
}
@Override
public String myGenericMethod(String value) {
return value;
}
}
@MyStereotype
public interface MyValidInterface<T> {
@NotNull
Object myValidMethod(@NotNull(groups = MyGroup.class) String arg1, @Max(10) int arg2);
@MyValid
@Async
void myValidAsyncMethod(@NotNull(groups = OtherGroup.class) String arg1, @Max(10) int arg2);
T myGenericMethod(@NotNull T value);
}
static class MyValidClientInterfaceMethodInterceptor implements MethodInterceptor {
private final MyValidBean myValidBean = new MyValidBean();
@Nullable
@Override
public Object invoke(MethodInvocation invocation) throws Throwable {
Method method;
try {
method = ClassUtils.getMethod(MyValidBean.class, invocation.getMethod().getName(), (Class<?>[]) null);
}
catch (IllegalStateException ex) {
method = BridgeMethodResolver.findBridgedMethod(
ClassUtils.getMostSpecificMethod(invocation.getMethod(), MyValidBean.class));
}
return ReflectionUtils.invokeMethod(method, this.myValidBean, invocation.getArguments());
}
}
public interface MyGroup {
}
public interface OtherGroup {
}
@Validated({MyGroup.class, Default.class})
@Retention(RetentionPolicy.RUNTIME)
public @interface MyStereotype {
}
@Validated({OtherGroup.class, Default.class})
@Retention(RetentionPolicy.RUNTIME)
public @interface MyValid {
}
@Configuration
public static class LazyMethodValidationConfig {
@Bean
public static MethodValidationPostProcessor methodValidationPostProcessor(@Lazy Validator validator) {
MethodValidationPostProcessor postProcessor = new MethodValidationPostProcessor();
postProcessor.setValidator(validator);
return postProcessor;
}
}
@Configuration
public static class LazyMethodValidationConfigWithProxyTargetClass {
@Bean
public static MethodValidationPostProcessor methodValidationPostProcessor(@Lazy Validator validator) {
MethodValidationPostProcessor postProcessor = new MethodValidationPostProcessor();
postProcessor.setValidator(validator);
postProcessor.setProxyTargetClass(true);
return postProcessor;
}
}
@Configuration
public static class LazyMethodValidationConfigWithValidatorProvider {
@Bean
public static MethodValidationPostProcessor methodValidationPostProcessor(ObjectProvider<Validator> validator) {
MethodValidationPostProcessor postProcessor = new MethodValidationPostProcessor();
postProcessor.setValidatorProvider(validator);
return postProcessor;
}
}
}
|
package org.shazhi.businessEnglishMicroCourse.entity;
import lombok.Getter;
import lombok.NoArgsConstructor;
import lombok.Setter;
import lombok.experimental.Accessors;
import org.hibernate.annotations.DynamicUpdate;
import org.springframework.data.jpa.domain.support.AuditingEntityListener;
import javax.persistence.*;
import java.util.List;
@Entity
@EntityListeners(AuditingEntityListener.class)
@Table(name = "role", schema = "business_english")
@DynamicUpdate
@Getter
@Setter
@NoArgsConstructor
@Accessors(chain = true)
public class RoleEntity {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Integer roleId;
private String roleName;
private String tagColor;
@ManyToMany(cascade = {CascadeType.DETACH})
@JoinTable(name = "role_security",
joinColumns = {@JoinColumn(name = "role_id")},
inverseJoinColumns = {@JoinColumn(name = "security_id")})
private List<SecurityEntity> securities;
@OneToMany(cascade = CascadeType.REMOVE,fetch = FetchType.LAZY, mappedBy = "role")
private List<UserRoleOrganization> uros;
public static RoleEntity ignoreAttr(RoleEntity role) {
return new RoleEntity()
.setRoleId(role.getRoleId())
.setRoleName(role.getRoleName());
}
}
|
package com.zut.lcy.mybatisplus.entity;
import com.baomidou.mybatisplus.annotation.IdType;
import com.baomidou.mybatisplus.extension.activerecord.Model;
import com.baomidou.mybatisplus.annotation.TableId;
import java.io.Serializable;
/**
* <p>
*
* </p>
*
* @author lcy
* @since 2019-12-17
*/
public class User extends Model<User> {
private static final long serialVersionUID = 1L;
@TableId(value = "username", type = IdType.AUTO)
private String username;
private String password;
public String getUsername() {
return username;
}
public void setUsername(String username) {
this.username = username;
}
public String getPassword() {
return password;
}
public void setPassword(String password) {
this.password = password;
}
@Override
protected Serializable pkVal() {
return this.username;
}
@Override
public String toString() {
return "User{" +
"username=" + username +
", password=" + password +
"}";
}
}
|
package com.syl.orders.service;
import com.syl.model.goods.Goods;
import com.syl.model.orders.Orders;
import java.util.List;
public interface OrdersService {
List<Orders> get();
int insert(Orders orders,List<Goods> goods);
}
|
package com.kymjs.event;
final class PendingPostQueue {
private PendingPost head; //待发送对象队列头节点
private PendingPost tail;//待发送对象队列尾节点
/**
* 入队
*/
synchronized void enqueue(PendingPost pendingPost) {
if (pendingPost == null) {
throw new NullPointerException("null cannot be enqueued");
}
if (tail != null) {
tail.next = pendingPost;
tail = pendingPost;
} else if (head == null) {
head = tail = pendingPost;
} else {
throw new IllegalStateException("Head present, but no tail");
}
notifyAll();
}
/**
* 取队列头节点的待发送对象
*/
synchronized PendingPost poll() {
PendingPost pendingPost = head;
if (head != null) {
head = head.next;
if (head == null) {
tail = null;
}
}
return pendingPost;
}
/**
* 取待发送对象队列头节点的待发送对象
*/
synchronized PendingPost poll(int maxMillisToWait) throws InterruptedException {
if (head == null) {
wait(maxMillisToWait);
}
return poll();
}
}
|
import java.awt.Color;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.geom.Rectangle2D;
import java.awt.image.BufferedImage;
import java.io.File;
import javax.imageio.ImageIO;
import javax.swing.GroupLayout.Alignment;
import javax.swing.JPanel;
public class Screen extends JPanel{
public Screen(){
loadResources();
}
public void paint(Graphics g){
try{
Graphics2D g2d = (Graphics2D) g;
//g2d.setPaint(Color.BLACK);
//g2d.fill(new Rectangle2D.Float(0, 0, getWidth(), getHeight()));
g2d.drawImage(background, 0, 0, getWidth(), getHeight(), null);
g2d.setPaint(Color.GRAY);
g2d.fill(new Rectangle2D.Float(10, 10, getWidth() - 20, 300));
g2d.drawImage(fill, 10, 10, getWidth() - 20, 300, null);
g2d.fill(new Rectangle2D.Float(10, getHeight() - 115, getWidth() - 20, 100));
g2d.drawImage(fill, 10, getHeight() - 115, getWidth() - 20, 100, null);
g2d.setPaint(Color.LIGHT_GRAY);
g2d.drawRect(10, 10, getWidth() - 20, 300);
g2d.drawRect(10, getHeight() - 115, getWidth() - 20, 100);
g2d.setPaint(Color.DARK_GRAY);
g2d.drawString("Settings", getWidth() / 2 - 25, 20);
g2d.drawString("Controls", getWidth() / 2 - 25, getHeight() - 20);
if(Main.buttonsReady){
for(int i = 0; i < Main.buttons.size(); i++){
Button B = Main.buttons.get(i);
if(B.hover){
g2d.setColor(Color.DARK_GRAY);
}else{
g2d.setColor(Color.LIGHT_GRAY);
}
g2d.fill(new Rectangle2D.Float(B.BOX.x, B.BOX.y, B.BOX.width, B.BOX.height));
g2d.setColor(Color.BLACK);
g2d.drawRect(B.BOX.x, B.BOX.y, B.BOX.width, B.BOX.height);
if(B.hover){
g2d.setColor(Color.WHITE);
}else{
g2d.setColor(Color.BLACK);
}
g2d.drawString(B.TITLE, B.BOX.x + 2, B.BOX.y + 14);
}
}
}catch(Exception ex){
ex.printStackTrace(System.out);
if(!exceptionRepaint){
exceptionRepaint = true;
//repaint();
}
}
exceptionRepaint = false;
}
private boolean exceptionRepaint = false;
private BufferedImage background;
private BufferedImage fill;
public void loadResources(){
try{
background = ImageIO.read(this.getClass().getResourceAsStream("background.png"));
fill = ImageIO.read(this.getClass().getResourceAsStream("fill.png"));
}catch(Exception ex){
ex.printStackTrace(System.out);
}
}
}
|
/*
Copyright 2015 Alfio Zappala
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
package co.runrightfast.incubator.rx.impl;
import co.runrightfast.commons.utils.JsonUtils;
import co.runrightfast.incubator.commons.disruptor.DisruptorConfig;
import co.runrightfast.incubator.commons.disruptor.RingBufferReference;
import co.runrightfast.incubator.rx.ObservableRingBuffer;
import co.runrightfast.logging.JsonLog;
import com.google.common.util.concurrent.AbstractIdleService;
import com.google.gson.JsonObject;
import com.lmax.disruptor.RingBuffer;
import com.lmax.disruptor.TimeoutException;
import com.lmax.disruptor.dsl.Disruptor;
import java.util.List;
import java.util.concurrent.CopyOnWriteArrayList;
import java.util.concurrent.TimeUnit;
import java.util.logging.Level;
import lombok.Builder;
import lombok.Getter;
import lombok.NonNull;
import lombok.RequiredArgsConstructor;
import lombok.Value;
import lombok.extern.java.Log;
import org.apache.commons.collections4.CollectionUtils;
import rx.Observable;
import rx.Subscriber;
/**
*
* @author alfio
* @param <A> ring buffer item type
*/
@RequiredArgsConstructor
@Log
public class ObservableRingBufferImpl<A> extends AbstractIdleService implements ObservableRingBuffer<A> {
private static final String CLAZZ = ObservableRingBufferImpl.class.getName();
@NonNull
private final DisruptorConfig<A> disruptorConfig;
@NonNull
private final Class<A> ringBufferDataType;
private Disruptor<RingBufferReference<A>> disruptor;
private RingBuffer<RingBufferReference<A>> ringBuffer;
@Getter
private Observable<A> observable;
private final List<Subscriber<? super A>> subscribers = new CopyOnWriteArrayList<>();
private static final JsonLog warning = JsonLog.warningJsonLog(log, CLAZZ);
@Value
@Builder
private static class LogMessage {
String message;
String type;
long sequence;
}
@Override
protected void startUp() {
this.disruptor = disruptorConfig.newDisruptor(ringBufferDataType);
this.observable = Observable.<A>create(this::observableOnSubscribe);
this.disruptor.handleEventsWith(this::onEvent);
this.ringBuffer = this.disruptor.start();
}
@Override
protected void shutDown() {
if (this.disruptor != null) {
for (int i = 1; true; i++) {
final int waitTimeSecs = 10;
try {
this.disruptor.shutdown(waitTimeSecs, TimeUnit.SECONDS);
break;
} catch (final TimeoutException ex) {
log.logp(Level.WARNING, CLAZZ, "shutDown", "waiting for disruptor to shutdown : {0} secs", i * waitTimeSecs);
}
}
}
if (this.subscribers != null) {
this.subscribers.stream()
.filter(this::isSubscribed)
.forEach(subscriber -> subscriber.onCompleted());
}
this.disruptor = null;
this.ringBuffer = null;
this.subscribers.clear();
}
@Override
public boolean publish(@NonNull final A msg) {
return this.ringBuffer.tryPublishEvent(this::setRingBufferReferenceData, msg);
}
private void setRingBufferReferenceData(final RingBufferReference<A> msg, final long sequence, final A data) {
msg.data = data;
}
private boolean isSubscribed(final Subscriber<? super A> subscriber) {
return !subscriber.isUnsubscribed();
}
private void observableOnSubscribe(final Subscriber<? super A> subscriber) {
if (!subscriber.isUnsubscribed()) {
this.subscribers.add(subscriber);
}
}
// TODO: collect metrics - how many event were dropped, delivered, etc
private void onEvent(final RingBufferReference<A> msg, final long sequence, final boolean endOfBatch) {
if (CollectionUtils.isEmpty(subscribers)) {
warning.log("onEvent", new LogMessage("message dropped because there are no observers", getClass().getName(), sequence));
return;
}
for (final Subscriber<? super A> subscriber : subscribers) {
if (subscriber.isUnsubscribed()) {
this.subscribers.remove(subscriber);
continue;
}
try {
subscriber.onNext(msg.data);
} catch (final Throwable t) {
subscriber.onError(t);
this.subscribers.remove(subscriber);
}
}
}
@Override
public long remainingCapacity() {
return ringBuffer.getBufferSize();
}
@Override
public int observerCount() {
return subscribers.size();
}
@Override
public int bufferSize() {
return ringBuffer.getBufferSize();
}
@Override
public long cursor() {
return ringBuffer.getCursor();
}
@Override
public String toString() {
if (!isRunning()) {
return "{}";
}
final JsonObject json = new JsonObject();
json.addProperty("remainingCapacity", remainingCapacity());
json.addProperty("observerCount", observerCount());
json.addProperty("bufferSize", bufferSize());
json.addProperty("cursor", cursor());
json.addProperty("ringBufferDataType", ringBufferDataType.getName());
return JsonUtils.prettyPrintingGson.toJson(json);
}
}
|
package com.epam.mentor.bean;
import java.util.Date;
public class MentorBean {
private String Name;
private String Email;
private Date mentorStartDate;
private Date mentorEndDate;
private int maxNoOfMentees;
private String technologyStream;
private String Status;
/* public MentorBean(String Name,String Email,Date mentorStartDate,Date mentorEndDate,int maxNoOfMentees,String technologyStream,String Status)
{
this.Email=Email;
this.maxNoOfMentees=maxNoOfMentees;
this.mentorEndDate=mentorEndDate;
this.mentorStartDate=mentorStartDate;
this.Name=Name;
this.Status=Status;
this.technologyStream=technologyStream;
}*/
public String getName() {
return Name;
}
public void setName(String name) {
Name = name;
}
public String getEmail() {
return Email;
}
public void setEmail(String email) {
Email = email;
}
public Date getMentorStartDate() {
return mentorStartDate;
}
public void setMentorStartDate(Date mentorStartDate) {
this.mentorStartDate = mentorStartDate;
}
public Date getMentorEndDate() {
return mentorEndDate;
}
public void setMentorEndDate(Date mentorEndDate) {
this.mentorEndDate = mentorEndDate;
}
public int getMaxNoOfMentees() {
return maxNoOfMentees;
}
public void setMaxNoOfMentees(int maxNoOfMentees) {
this.maxNoOfMentees = maxNoOfMentees;
}
public String getTechnologyStream() {
return technologyStream;
}
public void setTechnologyStream(String technologyStream) {
this.technologyStream = technologyStream;
}
public String getStatus() {
return Status;
}
public void setStatus(String status) {
Status = status;
}
}
|
package com.test;
import java.util.ArrayList;
import java.util.HashSet;
import java.util.List;
import java.util.Set;
import com.test.base.Solution;
/**
* 虽然 leetcode 通过了,但本机的内存溢出了。。而且是高通过率,所以觉得没啥必要这题
* Exception
* java.lang.OutOfMemoryError: GC overhead limit exceeded
*
*
* @author YLine
*
* 2019年12月25日 上午10:23:13
*/
public class SolutionB implements Solution
{
int n;
List<String> dp[];
Set<String> set;
boolean visited[];
@Override
public List<String> wordBreak(String s, List<String> wordDict)
{
n = s.length();
dp = new ArrayList[n];
visited = new boolean[n];
set = new HashSet<>();
for (String w : wordDict)
set.add(w);
return dfs(s, 0, wordDict);
}
public List<String> dfs(String s, int i, List<String> wordDict)
{
if (i == n)
return new ArrayList();
if (visited[i])
return dp[i];
dp[i] = new ArrayList<>();
visited[i] = true;
String st = s.substring(i);
for (String w : wordDict)
{
if (st.startsWith(w))
{
List<String> add = dfs(s, i + w.length(), wordDict);
if (i + w.length() == n)
{
dp[i].add(w);
}
else
{
for (String x : add)
dp[i].add(w + " " + x);
}
}
}
return dp[i];
}
}
|
package ch.usz.fhirstack.dataqueue.jobs;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import com.birbit.android.jobqueue.Job;
import com.birbit.android.jobqueue.Params;
import com.birbit.android.jobqueue.RetryConstraint;
import ch.usz.fhirstack.FHIRStack;
import ch.usz.fhirstack.dataqueue.DataQueue;
/**
* FHIRSTACK / C3PRO_Android
* <p/>
* Created by manny on 07.06.2016.
* <p/>
* This job can be used to asynchronously run a HAPI query. If no FHIRServerURL is provided, the
* URL set in the dataqueue will be used. Jobs with the same singleInstanceID will only run if no
* other job with same ID is present in the queue. Define a QueryPoster with the query in the
* runQuery method.
* Be aware that the query will run on a background thread. It won't be possible to access the UI
* from it. Use a Handler to send the result to the main thread first.
*
* This is how you use this class:
* public void runQuery(){
* HAPIQueryJob job = new HAPIQueryJob("instanceID", new QueryPoster() {
* @Override
* public void runQuery(IGenericClient client) {
* org.hl7.fhir.dstu3.model.Bundle results = client.search()
* .forResource(Patient.class)
* .where(Patient.NAME.matches().value("Smith"))
* .returnBundle(org.hl7.fhir.dstu3.model.Bundle.class)
* .execute();
* // do something with the result
* }
* });
* FHIRStack.getDataQueue().addJob(job);
* */
public class HAPIQueryJob extends Job {
private DataQueue.QueryPoster queryPoster;
private String url;
/**
* The QueryPoster will get a generic HAPI client for the specified URL on which it can run its
* query. If you add multiple jobs to the queue with the same singleINstanceID, only one will run.
* */
public HAPIQueryJob(String singleInstanceID, DataQueue.QueryPoster poster, String FHIRServerURL){
super(new Params(Priority.HIGH).requireNetwork().singleInstanceBy(singleInstanceID));
queryPoster = poster;
url = FHIRServerURL;
}
/**
* The QueryPoster will get a generic HAPI client for the URL specified in the FHIRStack on
* which it can run its query. If you add multiple jobs to the queue with the same
* singleINstanceID, only one will run.
* */
public HAPIQueryJob(String singleInstanceID, DataQueue.QueryPoster poster){
this(singleInstanceID, poster, FHIRStack.getDataQueue().getFHIRServerURL());
}
@Override
public void onAdded() {
}
@Override
public void onRun() throws Throwable {
queryPoster.runQuery(FHIRStack.getFhirContext().newRestfulGenericClient(url));
}
@Override
protected void onCancel(int cancelReason, @Nullable Throwable throwable) {
}
@Override
protected RetryConstraint shouldReRunOnThrowable(@NonNull Throwable throwable, int runCount, int maxRunCount) {
return null;
}
}
|
package com.group.etoko.util;
public interface Constants {
String USER = "USER";
String DELIVERY_HOME="DELIVERY_HOME";
String DELIVERY_PICKUP_STORE="DELIVERY_PICKUP_STORE";
String DELIVERY_EMERGENCY="DELIVERY_EMERGENCY";
String PAYMENT_CASH_ON="PAYMENT_CASH_ON";
String PAYMENT_BKASH="PAYMENT_BKASH";
String STORE_SUCCESSFUL="STORE_SUCCESSFUL";
String STORE_FAILED="STORE_FAILED";
int ITEMSPACE=16;
//product Grid view bundle massage key
String PRODUCT_ID="PRODUCT_ID";
String CATEGORY="CATEGORY";
String SUB_CATEGORY="SUB_CATEGORY";
String SEASONAL_CATEGORY="SEASONAL_CATEGORY";
String COLLECTION="COLLECTION";
String SEARCH_WORD="SEARCH_WORD";
String OFFER_PRODUCT="OFFER_PRODUCT";
String FEATURED_PRODUCT="FEATURED_PRODUCT";
//----------------------------------
//-----------history fragmant---
String INTERNETERROR="Please check your connection and try again";
String CUSTOMERID="CUSTOMERID";
String ORDEROBJECT="ORDEROBJECT";
String ACTIONBAR_TITLE="TITLE";
String Taka_sign="\u09F3";
String IS_USER_ALREADY_REGISTER="IS_USER_ALREADY_REGISTER";
String OTP_CODE="OTP_CODE";
String NOTIFICATION_CHANEL="NOTIFICATION_CHANEL";
String COD="COD";
//--number format---
String numberFormat="%.2f";
//--Checkout--------
String COUPONAMOUNT="COUPONAMOUNT";
//STATIC VALUE-----------
String IS_Discount="1";
String GROCERIES_CAT_ID="1";
String CART_ITEM_POSITION="CART_ITEM_POSITION";
String RECYCLER_ITEM_POSITION="DETAILS_ITEM_POSITION";
String IS_CART_ITEM_REMOVE="IS_CART_ITEM_REMOVE";
}
|
package com.hussain.project1.controller;
import com.hussain.project1.model.BaseResponse;
import com.hussain.project1.model.UserDetailRequest;
import com.hussain.project1.model.UserDetailResponse;
import com.hussain.project1.service.UserService;
import io.swagger.annotations.Api;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
@RestController
@Slf4j
@Api(value="/home",description="Customer Profile",produces ="application/json")
public class baseController {
@Autowired
UserService userService;
@RequestMapping(value="/returnData", method=RequestMethod.GET)
@ResponseBody
public BaseResponse returnData(){
BaseResponse baseResponse= new BaseResponse();
baseResponse.setEmail("fromOtherService.gmail.com");
baseResponse.setMessage("Successfully retrieved data from project1");
return baseResponse;
}
@RequestMapping(value="/getMyDetails", method = RequestMethod.POST)
UserDetailResponse userDetails(@RequestBody UserDetailRequest request){
userService.setUserDetailRequest(request);
log.info("Received request: {}", request);
UserDetailResponse userDetailResponse= userService.sucess();
log.info("Response: {}",userDetailResponse);
return userDetailResponse;
}
}
|
package encapsule;
/**
* @file_name : MaxMinMain.java
* @author : dingo44kr@gmail.com
* @date : 2015. 9. 22.
* @story : 최고점, 최저점 구하기
*/
import java.util.Scanner;
public class MaxMin1 {
/**
* "학생들 평균 점수를 입력하시면 1등과 최고점, 최저점이 출력됩니다."
* "단, 정원은 5명입니다."
*/
public static void main(String[] args) {
MaxMin1Seed seed = new MaxMin1Seed();
Scanner scanner = new Scanner(System.in);
int max = 0, min = 0, result = 0;
System.out.println(seed.result);
}
}
|
package com.example.kimnamgil.testapplication.widget;
import android.content.Context;
import android.widget.FrameLayout;
import android.widget.TextView;
import com.example.kimnamgil.testapplication.R;
import com.example.kimnamgil.testapplication.data.Comment;
/**
* Created by kimnamgil on 2016. 7. 16..
*/
public class CommentView extends FrameLayout {
public CommentView(Context context) {
super(context);
init();
}
TextView commentView;
private void init()
{
inflate(getContext(), R.layout.comment_view, this);
commentView = (TextView)findViewById(R.id.comment_text);
}
Comment comment;
public void setComment(Comment comment) {
this.comment = comment;
commentView.setText(comment.comment);
}
}
|
package it.unical.dimes.processmining.test;
import it.unical.dimes.processmining.core.CNMining;
import it.unical.dimes.processmining.core.Constraint;
import it.unical.dimes.processmining.core.ConstraintParser;
import it.unical.dimes.processmining.core.Edge;
import it.unical.dimes.processmining.core.Forbidden;
import it.unical.dimes.processmining.core.Graph;
import it.unical.dimes.processmining.core.LogUnfolder;
import it.unical.dimes.processmining.core.Node;
import it.unical.dimes.processmining.core.Utils;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.nio.file.FileSystems;
import java.nio.file.Files;
import java.nio.file.StandardOpenOption;
import java.util.HashMap;
import java.util.Iterator;
import java.util.LinkedHashSet;
import java.util.LinkedList;
import java.util.Map;
import java.util.TreeMap;
import java.util.TreeSet;
import org.deckfour.xes.factory.XFactoryNaiveImpl;
import org.deckfour.xes.model.XLog;
/**
* @author frank
*
* Created on 2013-09-07, 5:48:02 PM
*/
public class TestProductRecall {
public static String attivita_iniziale = "_START_";
public static String attivita_finale = "_END_";
/**
* @param args
*/
@SuppressWarnings({ "rawtypes", "unchecked" })
public static void main(String[] args) throws Exception {
// fall factor = 0.5 e 0.9
// relative to best = attuale e 0.5
// sigma = 0 e 0.1
String filename = "productRecall_F-measure_P_BK.csv";
// String content = "%Tracce;%P;%E;%NP;%NE;Precision;Recall;F-measure;Total_Constr;UnSat_Constrs;Nr._Of_Deps;Computation_Time\n";
String content = "";
File file = new File(filename);
if (file.exists())
file.delete();
file.createNewFile();
int[] u = {3, 6, 12, 25};
for(int u1 = 0 ; u1 < u.length; u1++) {
for (int j = 0; j < 60; j += 10) {
// if (j == 0 && k == 0)
// continue;
// if (j == 0)
// continue;
double totalPrecision = 0;
double totalRecall = 0;
long totalTime = 0;
double total_nr_deps = 0;
double total_unsat_constr = 0;
int total_constr = 0;
for (int i = 0; i < 6; i++) {
// System.out.println("log " + i);
double precision = 0;
double recall = 0;
long time = 0;
int constr_size = 0;
double nr_deps = 0;
double unsat_constr = 0;
for (int h = 0; h < 5; h++) {
long curr_time = System.currentTimeMillis();
//System.out.println("P " + j + " E " + k + " Sample " + i + " Run " + h);
boolean enable_constraints = true;
if (j == 0)
enable_constraints = false;
boolean enable_postProcessing = true;
boolean enable_bindingComputation = true;
// SOGLIA CAUSAL SCORE POST PROCESSING
double sigma_up_cs_diff = 0.2;
// SOGLIA CAUSAL SCORE CONSTRAINTS
double sigma_low_cs_constr_edges = 0.05;
// SOGLIA RUMORE
double sigma_log_noise = 0.05;
double ff = 0.9;
double relative_to_best = 0.75;
String extension = ".mxml";
if(i == 0)
extension = ".xes";
XLog log = Utils.parseLog("C:/Users/flupia/Desktop/productRecall/all_distinct_" + u[u1] + "_"+ ".xes", new XFactoryNaiveImpl());
// XLog log = Utils.parseLog("C:/Users/frank/Desktop/productRecall/all_50_distinct/" + "all_distinct_"
// + i + extension, new XFactoryNaiveImpl());
LinkedList<Forbidden> lista_forbidden = new LinkedList<Forbidden>();
LinkedList<Constraint> vincoli_positivi = new LinkedList<Constraint>();
LinkedList<Constraint> vincoli_negati = new LinkedList<Constraint>();
if (enable_constraints) {
ConstraintParser cp = new ConstraintParser(
"C:/Users/flupia/Desktop/productRecall/constraintsIncr/NP/Constraints_P_" + 0 + "_E_" + 0 + "_NP_" + j
+ "_NE_" + 0 + "_Run_" + h + ".xml");
cp.run();
LinkedList<Constraint> constraints = cp.getConstraints();
for (Constraint constr : constraints) {
if (constr.isPositiveConstraint()) {
vincoli_positivi.add(constr);
} else {
for (String body : constr.getBodyList())
lista_forbidden.add(new Forbidden(body, constr.getHead()));
vincoli_negati.add(constr);
}
}
}
LinkedList<Forbidden> lista_forbidden_unfolded = new LinkedList<Forbidden>();
LinkedList<Constraint> vincoli_positivi_unfolded = new LinkedList<Constraint>();
LinkedList<Constraint> vincoli_negati_unfolded = new LinkedList<Constraint>();
CNMining cnm = new CNMining();
// XLog log =
// Utils.parseLog("/home/frank/prom/log_giu_set_trace_filtrato_3.xes",
// new XFactoryNaiveImpl());
// aggiungi attivita fittizie
cnm.aggiungiAttivitaFittizia(log);
// UNFOLD DEL LOG
Object[] array = LogUnfolder.unfold(log);
Map<String, Integer> map = (Map<String, Integer>) array[0];
Map<String, LinkedList<String>> attivita_tracce = (Map<String, LinkedList<String>>) array[1];
Map<String, LinkedList<String>> traccia_attivita = (Map<String, LinkedList<String>>) array[2];
if (enable_constraints)
cnm.creaVincoliUnfolded(vincoli_positivi, vincoli_negati, lista_forbidden,
vincoli_positivi_unfolded, vincoli_negati_unfolded, lista_forbidden_unfolded, map);
double[][] csm = cnm.calcoloMatriceDeiCausalScore(log, map, traccia_attivita, ff);
// double[][] m = cnm.buildNextMatrix(log, map, traccia_attivita);
double[][] m = cnm.buildBestNextMatrix(log, map, traccia_attivita, csm,
lista_forbidden_unfolded);
if (sigma_log_noise > 0) {
for (int i1 = 0; i1 < m.length; i1++) {
for (int j1 = 0; j1 < m.length; j1++)
if (m[i1][j1] <= sigma_log_noise * traccia_attivita.size())
// rimuovo gli archi poco frequenti (ovvero quelli che
// occorrono meno di sigma_2 * logSize volte)
m[i1][j1] = 0;
}
}
// COSTRUISCO IL GRAFO
Graph graph = new Graph();
// LinkedList<Node> lista_nodi = new LinkedList<Node>();
//
// for (int s = 0; s < m.length; s++)
// lista_nodi.add(new Node("" + s));
for (Map.Entry<String, Integer> entry : map.entrySet()) {
String key = entry.getKey();
Integer value = entry.getValue();
Node node = new Node(key, value);
if (!graph.getMap().containsKey(node))
graph.getMap().put(node, new LinkedHashSet<Node>());
}
for (int p = 0; p < m.length; p++)
for (int r = 0; r < m[0].length; r++)
if (m[p][r] > 0) {
Node np = graph.getNode(cnm.getKeyByValue(map, p), p);
Node nr = graph.getNode(cnm.getKeyByValue(map, r), r);
graph.addEdge(np, nr, false);
np.incr_Outer_degree();
nr.incr_Inner_degree();
}
// System.out.println("STAMPA RAPPORTO CAUSAL SCORE");
// System.out.println();
// a2bv2.stampaCSDependency(graph, csm);
// System.out.println();
//
// System.out.println("STAMPA ARCHI INDIRETTI");
// System.out.println();
// a2bv2.stampaUndirectEdges(graph, csm, map);
// System.out.println();
Map<String, Integer> folded_map = new TreeMap<String, Integer>();
Map<String, LinkedList<String>> folded_attivita_tracce = new TreeMap<String, LinkedList<String>>();
Map<String, LinkedList<String>> folded_traccia_attivita = new TreeMap<String, LinkedList<String>>();
Graph folded_G_Ori = cnm.getGrafoAggregato(graph, log, true, folded_map,
folded_attivita_tracce, folded_traccia_attivita);
// CHECK CONSISTENZA VINCOLI
boolean vincoli_consistenti = cnm
.verifica_consistenza_vincoli(vincoli_positivi, vincoli_negati);
if (!vincoli_consistenti) {
System.out.println("FALLIMENTO VINCOLI INCONSISTENTI ");
System.exit(0);
}
/***
* COSTRUISCO PG0
*
*
*/
if (enable_constraints) {
cnm.buildPG0(graph, m, vincoli_positivi_unfolded, vincoli_positivi, vincoli_negati,
lista_forbidden, lista_forbidden_unfolded, map, attivita_tracce, traccia_attivita,
csm, sigma_low_cs_constr_edges, folded_G_Ori, folded_map);
Graph folded_PG0 = cnm.getGrafoAggregato(graph, log, false, folded_map,
folded_attivita_tracce, folded_traccia_attivita);
if (!cnm.verificaVincoliPositivi(folded_PG0, null, null, vincoli_positivi, folded_map)) {
System.out.println("FALLIMENTO PG0 NON SODDISFA I VINCOLI POSITIVI!");
System.exit(0);
}
}
// algoritmo1(m, graph, map, attivita_tracce, traccia_attivita, csm);
cnm.algoritmo2(m, graph, map, attivita_tracce, traccia_attivita, csm, sigma_up_cs_diff,
folded_map, lista_forbidden, vincoli_positivi, vincoli_negati);
Graph folded_g = cnm.getGrafoAggregato(graph, log, false, folded_map, folded_attivita_tracce,
folded_traccia_attivita);
// setto le marche di nuovo a false
for (Node n : graph.listaNodi())
n.setMark(false);
for (Edge e : folded_g.getLista_archi()) {
Iterator<Constraint> it = vincoli_positivi.iterator();
while (it.hasNext()) {
Constraint c = it.next();
if (c.getBodyList().contains(e.getX().getNomeAttivita())
&& c.getHead().equals(e.getY().getNomeAttivita())) {
e.setFlag(true);
// System.out.println(e + " OK!!!!!!");
break;
}
}
}
// eliminiamo gli archi poco frequenti in base al causal score
double[][] csmOri = cnm.calcoloMatriceDeiCausalScore(log, folded_map, folded_traccia_attivita,
ff);
cnm.postProcessing_dip_indirette(folded_g, folded_map, folded_attivita_tracce,
folded_traccia_attivita, csmOri, sigma_log_noise, vincoli_positivi);
cnm.postProcessing_paralleli(folded_g, csmOri, folded_map, folded_attivita_tracce,
folded_traccia_attivita, sigma_up_cs_diff, sigma_log_noise, vincoli_positivi);
// System.out.println("RIMOZIONE DIPENDENZE STRANE");
// cnm.removeStrangeDependencies(folded_g, folded_map, vincoli_positivi);
// Node start = new Node(attivita_iniziale + "+complete", folded_map.get(attivita_iniziale + "+complete"));
// Node end = new Node(attivita_finale + "+complete", folded_map.get(attivita_finale + "+complete"));
Node start = new Node(CNMining.attivita_iniziale, folded_map.get(CNMining.attivita_iniziale));
Node end = new Node(CNMining.attivita_finale, folded_map.get(CNMining.attivita_finale));
LinkedList<Node> startActivities = new LinkedList<Node>();
LinkedList<Node> endActivities = new LinkedList<Node>();
folded_g = cnm.rimuoviAttivitaFittizie(folded_g, folded_map, folded_traccia_attivita,
folded_attivita_tracce, start, end, log, startActivities, endActivities);
if (enable_bindingComputation)
cnm.computeBindings(folded_g, folded_traccia_attivita, folded_map);
csmOri = cnm.calcoloMatriceDeiCausalScore(log, folded_map, folded_traccia_attivita, ff);
while (true) {
// Ricalcolo il set degli archi eliminabili
LinkedList<Edge> removableEdges = cnm.removableEdges(folded_g, csmOri, vincoli_positivi,
folded_map, relative_to_best);
if (removableEdges.size() == 0)
break;
Edge bestRemovable = null;
double worst_causal_score = Double.MAX_VALUE;
Iterator<Edge> it = removableEdges.iterator();
while (it.hasNext()) {
Edge e = it.next();
double e_cs = csmOri[e.getX().getID_attivita()][e.getY().getID_attivita()];
if (e_cs < worst_causal_score) {
worst_causal_score = e_cs;
bestRemovable = e;
}
}
folded_g.removeEdge(bestRemovable.getX(), bestRemovable.getY());
if (enable_bindingComputation) {
//RIMOZIONE DAI BINDING
HashMap<TreeSet<Integer>, Integer> obX = bestRemovable.getX().getOutput();
HashMap<TreeSet<Integer>, Integer> ibY = bestRemovable.getY().getInput();
for (TreeSet<Integer> ts : obX.keySet())
ts.remove(bestRemovable.getY().getID_attivita());
for (TreeSet<Integer> ts : ibY.keySet())
ts.remove(bestRemovable.getX().getID_attivita());
//RIMOZIONE DAI BINDING ESTESI
HashMap<TreeSet<Integer>, Integer> extendedObX = bestRemovable.getX()
.getExtendedOutput();
HashMap<TreeSet<Integer>, Integer> extendedIbY = bestRemovable.getY()
.getExtendedInput();
for (TreeSet<Integer> ts : extendedObX.keySet())
ts.remove(bestRemovable.getY().getID_attivita());
for (TreeSet<Integer> ts : extendedIbY.keySet())
ts.remove(bestRemovable.getX().getID_attivita());
}
removableEdges.remove(bestRemovable);
}
boolean[][] testMatrixConstraint = cnm.generaAdjacentsMatrix(folded_g);
// //Estrazione constraints dal modello vero (calcolato su all_100_0) di productRecall
// Map<Integer, String> reverse_folded_map = new TreeMap<Integer, String>();
//
// for (Map.Entry<String, Integer> entry : folded_map.entrySet()) {
//
// reverse_folded_map.put(entry.getValue(), entry.getKey());
// }
//
// for (int j1 = 0; j1 < 60; j1 += 10) {
//
// for (int k1 = 0; k1 < 60; k1 += 10) {
//
// for (int i1 = 0; i1 < 5; i1++) {
//
// if(j1 == 0 && k1 == 0)
// continue;
//
// WorkflowConstraintExtractor extractor = new WorkflowConstraintExtractor(
// testMatrixConstraint, folded_map, reverse_folded_map);
//
//
// ExtractorManager em = new ExtractorManager();
//
// em.extractConstraints(extractor, 0, 25, j1, k1, i1);
//
// }
// }
// }
//
// if(true)
// return;
// System.out.println();
// System.out.println("********************************");
// System.out.println("********************************");
// System.out.println("********************************");
// System.out.println();
// ALPHA++ e Genetic
// InputStream input = new FileInputStream(
// "C:/Users/frank/Dropbox/ProcessMining-Tetris/4luigi/test_benchmarks/discoveredModels/productRecall_alphaPP/productRecall_10_alphaPP.tpn");
//
// Graph g = cnm.createGraphFromTPN("alphapp", input, folded_map);
//
// cnm.stampaGrafo(g);
//
// System.out.println();
// System.out.println("Nr. of dependencies found: ");
// System.out.println(g.getLista_archi().size());
//
// boolean[][] testMatrix1 = cnm.generaAdjacentsMatrix(g);
//
// double[] performance = computePrecisionRecall(testMatrix1, realMatrix);
// System.out.println();
// System.out.println("precision " + performance[0]);
// System.out.println("recall " + performance[1]);
//
// System.out.println();
// System.out.println("********************************");
// System.out.println("********************************");
// System.out.println("********************************");
// System.out.println();
// SUL 6 c'è ILP, HM, NOI
// InputStream input2 = new FileInputStream(
// "C:/Users/frank/Desktop/productRecall_100_Ours.pnml");
//
// Graph gpnml = cnm.createGraphFromPNML("ours", input2, folded_map);
//
// cnm.stampaGrafo(gpnml);
//
// boolean[][] testMatrix2 = cnm.generaAdjacentsMatrix(gpnml);
//
// double[] performance2 = computePrecisionRecall(testMatrix2, realMatrix);
// System.out.println();
// System.out.println("precision " + performance2[0]);
// System.out.println("recall " + performance2[1]);
//
// System.out.println();
// System.out.println("Nr. of dependencies found: ");
// System.out.println(gpnml.getLista_archi().size());
InputStream input2 = new FileInputStream(
"C:/Users/flupia/Dropbox/ProcessMining_Tetris/newTestProductRecall/trueModel/productRecall_All_100_Ours.pnml");
Graph gpnml = cnm.createGraphFromPNML("ours", input2, folded_map);
// cnm.stampaGrafo(gpnml);
input2.close();
boolean[][] realMatrix2 = cnm.generaAdjacentsMatrix(gpnml);
double[] performance2 = cnm.computePrecisionRecall(testMatrixConstraint, realMatrix2);
// System.out.println();
// System.out.println("precision round " + i + " run " + h);
// System.out.println(performance2[0]);
// System.out.println("recall round " + i + " run " + h);
// System.out.println(performance2[1]);
//
precision += performance2[0];
recall += performance2[1];
curr_time = System.currentTimeMillis() - curr_time;
time += curr_time;
nr_deps += folded_g.getLista_archi().size();
// System.out.println();
// System.out.println("Nr. of dependencies found: ");
// System.out.println(gpnml.getLista_archi().size());
//
// System.out.println("OK");
unsat_constr += cnm.getUnsatisfiedNegativeConstraints(folded_g, vincoli_negati, folded_map)
.size();
int counterNP = 0;
for(Constraint vinc : vincoli_negati) {
if(vinc.isPathConstraint())
counterNP++;
}
constr_size += counterNP;
System.out.println();
System.out.println("**************");
System.out.println();
System.out.println("u[i] " + u[u1]);
System.out.println("percent " + j);
System.out.println("log " + i);
System.out.println("run " + h);
System.out.println("precision " + performance2[0]);
System.out.println("recall " + performance2[1]);
System.out.println("nr_deps " + folded_g.getLista_archi().size());
System.out.println("unsat_constr " + cnm.getUnsatisfiedNegativeConstraints(folded_g, vincoli_negati, folded_map)
.size());
System.out.println();
System.out.println("**************");
System.out.println();
if (j == 0)
break;
}
if (j != 0) {
precision = precision / 5;
recall = recall / 5;
time = time / 5;
nr_deps = nr_deps / 5;
unsat_constr = unsat_constr / 5;
constr_size = constr_size / 5;
}
totalPrecision += precision;
totalRecall += recall;
totalTime += time;
total_nr_deps += nr_deps;
total_unsat_constr += unsat_constr;
total_constr += constr_size;
}
totalPrecision = totalPrecision / 6;
totalRecall = totalRecall / 6;
totalTime = totalTime / 6;
total_nr_deps = total_nr_deps / 6;
total_unsat_constr = total_unsat_constr / 6;
total_constr = total_constr / 6;
double f_measure = (double) (2 * totalPrecision * totalRecall) / (totalPrecision + totalRecall);
// System.out.println();
// System.out.println("precision [all_15]_" + j + "_" + k + " " + totalPrecision);
// System.out.println("recall [all_15]_" + j + "_" + k + " " + totalRecall);
// System.out.println();
content += u[u1] + "%;" + 0 + ";" + 0 + ";" + j + ";" + 0 + ";" + totalPrecision + ";" + totalRecall + ";"
+ f_measure + ";" + total_constr + ";" + total_unsat_constr + ";" + total_nr_deps + ";"
+ totalTime + "\n";
// content += u + "%;" + totalPrecision + ";" + totalRecall + ";" + f_measure + ";" + total_nr_deps + ";"
// + totalTime + "\n";
}
}
try {
Files.write(FileSystems.getDefault().getPath(".", filename), content.getBytes(), StandardOpenOption.APPEND);
} catch (IOException ioe) {
ioe.printStackTrace();
}
}
}
|
package com.icanit.app_v2.common;
public interface UriConstants {
String FIND_CATEGORY_HIERARCHY="category!findCategoryHierarchy";
String FIND_CATELIST_BY_MERID="category!findCateListByMerId";
String COMMUNITY_PAGINATION="community!listCommunitiesByPagination";
String COMMUNITY_BYAREAID="community!listCommunitiesByAreaId.action";
String AREA_BYPARENTID="area!listAreaByParentId.action";
// String MERCHANT_TYPE_HIERARCHY="merchantType!findMerchantTypeHierarchy";
// String FIND_MERCHANT_TYPE_BY_PARENT_ID="merchantType!findMerchantTypeByParentId";
String FIND_GOODS_BY_MERID="goods!findGoodsByMerIdByPagination";
String FIND_MERCHANT_BY_COMMID="merchant!findMerchantByCommIdByPagination";
String FIND_MERCHANT_BY_ID="merchant!findMerchantById";
String RECOMMEND_MERCHANT_BY_ID="merchant!recommend.action";
// String DISCOMMEND_MERCHANT_BY_ID="merchant!discommend.action";
String USER_LOGIN="user!login";
String MODIFY_PASSWORD="user!modifyPassword";
String USER_REGISTER="user!register";
String RETRIEVE_AND_MODIFY_PASSWORD="user!retrieveAndModifyPassword";
String RETRIEVE_PASSWORD="user!retrievePassword";
String SEND_VERICODE="user!sendVeriCode";
String RESEND_VERICODE="user!resendVeriCode";
String SEND_VERICODE_TEMP_TONEWPHONE="user!sendTempVeriCodeToNewPhone.action";
String CHANGE_ACCOUNT_PHONENUM="user!changeAccountPhoneNum.action";
String USER_ACCOUNT_VERIFY="user!verifyUserAccount";
String SUBMIT_ORDER="order!submitOrder_v2";
String SUBMIT_RECHARGE_ORDER="order!submitRechargeOrder";
String SUBMIT_ACCOUNT_PAY="order!submitAccountPay.action";
String RESUBMIT_ORDER="order!resubmitOrder.action";
String CANCEL_ORDER="order!cancelOrder.action";
String NOTICE_AFTER_PAY="order!afterPayNotice";
String NEW_VERSION_APP_DOWNLOAD="file/app_v2.apk";
String GET_LATEST_APP_VERSION="latestAppVersion.txt";
String GET_MERORDERITEMSLIST_BY_ORDERID="order!findOrderItemsByOrderId.action";
String GET_MERORDERITEMSLIST_BY_ORDERNUMNTIME="order!findOrderItemsByOrderNumNTime.action";
String GET_ORDERS_BY_PHONENSTATUS="order!findOrderByPhoneByStatus.action";
String GET_ORDERS_BY_PHONENSTATUS_FROM_INDEX="order!findOrderByPhoneByStatusFromIndex.action";
String BATCH_DELETE_ORDER="order!batchDeleteOrder.action";
String GET_ORDER_VERICODE="order!sendTempVeriCodeMessage.action";
String CONFIRM_ACCOUNT_PAY="order!confirmAccountPay.action";
String GET_TARGET_ORDER="order!findTargetOrder.action";
}
|
package fj.swsk.cn.eqapp.subs.more.Common;
import android.content.Context;
import android.content.Intent;
import fj.swsk.cn.eqapp.subs.collect.C.PendingSubmissionActivity2;
import fj.swsk.cn.eqapp.subs.collect.C.SubmissionHisActivity2;
import fj.swsk.cn.eqapp.subs.more.C.EQHisActivity;
import fj.swsk.cn.eqapp.subs.more.C.EmergencyPrescript;
import fj.swsk.cn.eqapp.subs.setting.C.SettingActivity;
/**
* Created by apple on 16/6/27.
*/
public class MoreClickHandler {
public static void clickAt(int pos,Context con){
if(pos==0){
con.startActivity(new Intent(con,PendingSubmissionActivity2.class));
}else if(pos==1){
con.startActivity(new Intent(con,SubmissionHisActivity2.class));
}else if(pos == 2){
con.startActivity(new Intent(con,EQHisActivity.class));
}else if(pos==3){
con.startActivity(new Intent(con,EmergencyPrescript.class));
}else if(pos==4){
}else if(pos==5){
}else if(pos == 6){
con.startActivity(new Intent(con,SettingActivity.class));
}
}
}
|
package com.pointinside.android.api;
import android.content.ContentResolver;
import android.content.Context;
import android.content.IntentFilter;
import android.content.SharedPreferences;
import android.database.ContentObserver;
import android.location.Location;
import android.net.Uri;
import android.os.Handler;
import android.os.Process;
import android.util.Log;
import com.pointinside.android.api.content.DownloadReceiver;
import com.pointinside.android.api.content.Downloads;
import com.pointinside.android.api.content.PIContentManager;
import com.pointinside.android.api.dao.PIDownloadDataCursor;
import com.pointinside.android.api.dao.PIFileDataCursor;
import com.pointinside.android.api.dao.PIMapGeoCityDataCursor;
import com.pointinside.android.api.dao.PIMapGeoCountryDataCursor;
import com.pointinside.android.api.dao.PIMapGeoCountrySubdivisionDataCursor;
import com.pointinside.android.api.dao.PIMapVenueSummaryDataCursor;
//import com.pointinside.android.api.dao.PIMapVenueSummaryDataCursor;
import com.pointinside.android.api.dao.PIReference;
import com.pointinside.android.api.dao.PIReferenceDataset;
import com.pointinside.android.api.dao.PISQLiteHelper;
import org.apache.http.auth.Credentials;
public final class PIMapReference
{
private static Uri sBaseUri;
private static Credentials sCredentials;
private static DownloadReceiver sDownloadReceiver;
static final PIMapReference sPIMapReference = new PIMapReference();
private static PISQLiteHelper sPISQLiteHelper;
private Context mContext;
private final Handler mHandler = new Handler();
private volatile boolean mIsInitialized = false;
private volatile boolean mIsLoaded = false;
private MyDownloadContentObserver mObserver;
private PIMapVenue mPIMapVenue;
private PIReferenceAccess mPIReferenceAccess;
private PIReferenceDownloadObserver mPIReferenceObserver;
private SharedPreferences mPrefs;
private PIReferenceContentManager mReferenceContentManager;
private String mReferenceETag;
public static Uri getBaseUri()
{
return sBaseUri;
}
public static String getBaseUrl()
{
return sBaseUri.toString();
}
public static Credentials getCredentials()
{
return sCredentials;
}
public static PIMapReference getInstance()
throws PIMapReference.NotInitializedException
{
if (sPIMapReference.mIsInitialized) {
return sPIMapReference;
}
throw new NotInitializedException("PIMapReference is not initialized. Please call newInstance(android.content.Context, org.apache.http.auth.UsernamePasswordCredentials).");
}
public static PIMapReference getInstance(Context paramContext, String paramString, Credentials paramCredentials)
{
try
{
if (sPIMapReference.mIsInitialized)
{
return sPIMapReference;
} else {
if (paramContext.getApplicationContext() != paramContext) {
throw new IllegalArgumentException("PIMapReference expects an application context, did you use context.getApplicationContext()?");
}
PIMapReference localPIMapReference = newInstance(paramContext, Uri.parse(paramString), paramCredentials);
PIMapReference localObject2 = localPIMapReference;
return localObject2;
}
} catch(Exception ex) {
ex.printStackTrace();
}
return sPIMapReference;
}
private void init(Context paramContext)
{
sPIMapReference.mContext = paramContext;
sPIMapReference.mPrefs = paramContext.getSharedPreferences("PIMaps", 0);
PIMapReference localPIMapReference1 = sPIMapReference;
PIMapReference localPIMapReference2 = sPIMapReference;
localPIMapReference2.getClass();
localPIMapReference1.mReferenceContentManager = new PIReferenceContentManager();
sPIMapReference.validateVenueDownloads();
sPIMapReference.removeCachedZipFiles();
if (sPIMapReference.validateReferenceDownload()) {
sPIMapReference.loadReferenceDataset();
}
if (sDownloadReceiver != null) {
sPIMapReference.mContext.unregisterReceiver(sDownloadReceiver);
}
sDownloadReceiver = new DownloadReceiver();
DownloadReceiver.initNetworkStatus(paramContext);
IntentFilter localIntentFilter = new IntentFilter();
localIntentFilter.addAction("android.net.conn.CONNECTIVITY_CHANGE");
localIntentFilter.addAction("pointinside.intent.action.DOWNLOAD_WAKEUP");
localIntentFilter.addAction("pointinside.intent.action.DOWNLOAD_NEW");
localIntentFilter.addAction("pointinside.intent.action.DOWNLOAD_CANCEL");
localIntentFilter.addAction("pointinside.intent.action.DOWNLOAD_COMPLETE");
sPIMapReference.mContext.registerReceiver(sDownloadReceiver, localIntentFilter);
}
private boolean loadReferenceDataset()
{
PIFileDataCursor pifiledatacursor;
mIsLoaded = false;
pifiledatacursor = mReferenceContentManager.getReferenceFileItem();
if(pifiledatacursor != null) {
if(sPISQLiteHelper == null) {
sPISQLiteHelper = new PISQLiteHelper(pifiledatacursor.getFileUri());
}
sPIMapReference.mPIReferenceAccess = new PIReferenceAccess(new PIReferenceDataset(sPISQLiteHelper));
mIsLoaded = true;
sPISQLiteHelper.close();
pifiledatacursor.close();
} else {
if(pifiledatacursor !=null)
pifiledatacursor.close();
}
return mIsLoaded;
}
private static PIMapReference newInstance(Context paramContext, Uri paramUri, Credentials paramCredentials)
{
if (paramContext == null) {
throw new IllegalArgumentException("Context is null.");
}
if (paramCredentials == null) {
throw new IllegalArgumentException("UsernamePasswordCredentials is null.");
}
sBaseUri = paramUri;
sCredentials = paramCredentials;
sPIMapReference.init(paramContext);
sPIMapReference.mIsInitialized = true;
return sPIMapReference;
}
private void removeCachedZipFiles()
{
new Thread()
{
public void run()
{
// Process.setThreadPriority(10);
// PIMapReference.PIReferenceContentManager.access$9(PIMapReference.sPIMapReference.mReferenceContentManager);
Process.setThreadPriority(10);
PIMapReference.sPIMapReference.mReferenceContentManager.removeCachedZipFiles();
}
}.start();
}
private boolean validateReferenceDownload()
{
return this.mReferenceContentManager.validateReferenceDownload();
}
private void validateVenueDownloads()
{
new Thread()
{
public void run()
{
// Process.setThreadPriority(10);
// PIMapReference.PIReferenceContentManager.access$7(PIMapReference.sPIMapReference.mReferenceContentManager);
Process.setThreadPriority(10);
PIMapReference.sPIMapReference.mReferenceContentManager.validateVenueDownloads();
}
}.start();
}
public void cancelDownload()
{
if (this.mObserver != null) {
this.mObserver.cancelDownload();
}
}
public void checkForUpdates(PIReferenceDownloadObserver pireferencedownloadobserver)
{
PIDownloadDataCursor pidownloaddatacursor;
Uri uri;
try {
if(pireferencedownloadobserver != null)
mPIReferenceObserver = pireferencedownloadobserver;
else
mPIReferenceObserver = new PIReferenceDownloadObserver();
System.out.println("PIMapReference.checkForUpdates");
pidownloaddatacursor = mReferenceContentManager.getReferenceDownloadItem();
if(pidownloaddatacursor == null) {
mPIReferenceObserver.failedWithError(new Exception("Unable to download reference file."));
return;
}
uri = pidownloaddatacursor.getUri();
mReferenceETag = pidownloaddatacursor.getIdentifier();
mObserver = new MyDownloadContentObserver(mHandler, uri);
mContext.getContentResolver().registerContentObserver(uri, false, mObserver);
mReferenceContentManager.refreshFile();
pidownloaddatacursor.close();
return;
} catch(Exception exception) {
// pidownloaddatacursor.close();
exception.printStackTrace();
}
return;
}
public void deleteVenueDownload(String paramString)
{
this.mReferenceContentManager.deleteVenueDownload(paramString);
}
public PIMapGeoCityDataCursor getCities()
{
return this.mPIReferenceAccess.getGeoCities();
}
public PIMapGeoCityDataCursor getCitiesForSubdivision(long paramLong)
{
return this.mPIReferenceAccess.getGeoCitiesForSubdivision(paramLong);
}
public PIMapVenueSummaryDataCursor getClosestVenueToLocation(Location paramLocation)
{
Log.d("PIMaps", "getClosestVenueToLocation Not Implemented!!!!");
return null;
}
public Context getContext()
{
return this.mContext;
}
public PIMapGeoCountryDataCursor getCountries()
{
return this.mPIReferenceAccess.getGeoCountries();
}
public PIMapGeoCountrySubdivisionDataCursor getGeoCountrySubdivisions()
{
return this.mPIReferenceAccess.getGeoCountrySubdivisions();
}
public PIMapGeoCountrySubdivisionDataCursor getGeoCountrySubdivisionsForCountry(long paramLong)
{
return this.mPIReferenceAccess.getGeoCountrySubdivisionsForCountry(paramLong);
}
public PIMapVenue getLoadedVenue()
{
return this.mPIMapVenue;
}
public PIMapVenueSummaryDataCursor getVenueForId(long paramLong)
{
return this.mPIReferenceAccess.getVenueSummary(paramLong);
}
public PIMapVenueSummaryDataCursor getVenueForUUID(String paramString)
{
return this.mPIReferenceAccess.getVenueSummary(paramString);
}
public PIMapVenueSummaryDataCursor getVenueSearchForName(String paramString)
{
return this.mPIReferenceAccess.getVenueSummarySearchForName(paramString);
}
public PIMapVenueSummaryDataCursor getVenueSearchForText(String paramString)
{
return getVenueSearchForText(paramString, null);
}
public PIMapVenueSummaryDataCursor getVenueSearchForText(String paramString, Location paramLocation)
{
return this.mPIReferenceAccess.getVenueSummarySearchForText(paramString, paramLocation);
}
public PIMapVenueSummaryDataCursor getVenues()
{
return getVenues(null);
}
public PIMapVenueSummaryDataCursor getVenues(Location paramLocation)
{
return this.mPIReferenceAccess.getVenueSummaries(paramLocation);
}
public PIMapVenueSummaryDataCursor getVenuesForCity(long paramLong)
{
return this.mPIReferenceAccess.getVenueSummariesForCity(paramLong);
}
public boolean isLoaded()
{
return this.mIsLoaded;
}
public boolean isNetworkAvailable()
{
if (sDownloadReceiver == null) {
return false;
}
return sDownloadReceiver.isNetworkAvailable();
}
public PIMapVenue loadVenue(PIMapVenueSummaryDataCursor.PIMapVenueSummary paramPIMapVenueSummary)
{
return loadVenue(paramPIMapVenueSummary, false, false, false);
}
public PIMapVenue loadVenue(PIMapVenueSummaryDataCursor.PIMapVenueSummary paramPIMapVenueSummary, boolean paramBoolean1, boolean paramBoolean2, boolean paramBoolean3)
{
if (paramPIMapVenueSummary == null) {
throw new IllegalArgumentException("PIMapVenueSummary is null");
}
if ((this.mPIMapVenue == null) || (!this.mPIMapVenue.getVenueUUID().equals(paramPIMapVenueSummary.getVenueUUID()))) {
this.mPIMapVenue = new PIMapVenue(this.mContext, paramPIMapVenueSummary, paramBoolean1, paramBoolean2, paramBoolean3, this.mHandler);
}
return this.mPIMapVenue;
}
public PIMapVenue loadVenue(String paramString)
{
return loadVenue(paramString, false, false, false);
}
public PIMapVenue loadVenue(String paramString, boolean paramBoolean1, boolean paramBoolean2, boolean paramBoolean3)
{
if (paramString == null) {
throw new IllegalArgumentException("venueUUID is null");
}
PIMapVenueSummaryDataCursor localPIMapVenueSummaryDataCursor;
if ((this.mPIMapVenue == null) || (!this.mPIMapVenue.getVenueUUID().equals(paramString)))
{
localPIMapVenueSummaryDataCursor = getVenueForUUID(paramString);
if (localPIMapVenueSummaryDataCursor == null) {}
else {
try
{
// if(localPIMapVenueSummaryDataCursor.moveToFirst())
loadVenue(localPIMapVenueSummaryDataCursor.getPIMapVenueSummary(), paramBoolean1, paramBoolean2, paramBoolean3);
}
finally
{
localPIMapVenueSummaryDataCursor.close();
}
}
}
return this.mPIMapVenue;
}
public void unRegisterPIReferenceDownloadObserver()
{
this.mPIReferenceObserver = new PIReferenceDownloadObserver();
}
private class MyDownloadContentObserver
extends ContentObserver
{
private boolean needsUpdateFired = false;
private Uri uri;
public MyDownloadContentObserver(Handler paramHandler, Uri paramUri)
{
super(paramHandler);
this.uri = paramUri;
}
private void cancelDownload()
{
mReferenceContentManager.cancelDownload(uri);
mPIReferenceObserver.downloadCanceled();
}
public void onChange(boolean paramBoolean)
{
if(mPIReferenceObserver != null) {
PIDownloadDataCursor pidownloaddatacursor = mReferenceContentManager.getDownloadItem(uri);
if(pidownloaddatacursor != null) {
int i;
if(!needsUpdateFired && (mReferenceETag == null || !mReferenceETag.equals(pidownloaddatacursor.getIdentifier())))
{
mPIReferenceObserver.fileNeedsUpdate();
needsUpdateFired = true;
}
mPIReferenceObserver.bytesToReceive(pidownloaddatacursor.getTotalBytes());
mPIReferenceObserver.dataReceived(pidownloaddatacursor.getCurrentBytes());
i = pidownloaddatacursor.getStatus();
if(Downloads.isStatusCompleted(i)) {
if(Downloads.isStatusSuccess(i)) {
if(!pidownloaddatacursor.isFileExtracted()) {
mPIReferenceObserver.fileDidUpdate();
if(PIMapReference.sPIMapReference.loadReferenceDataset()) {
mPIReferenceObserver.fileReady();
}
}
} else {
if(Downloads.isStatusError(i)) {
mPIReferenceObserver.failedWithError(new Exception((new StringBuilder("Unable to retrieve file. Response from server: ")).append(i).toString()));
pidownloaddatacursor.close();
return;
}
}
} else {
if(Downloads.isStatusError(i)) {
mPIReferenceObserver.failedWithError(new Exception((new StringBuilder("Unable to retrieve file. Response from server: ")).append(i).toString()));
pidownloaddatacursor.close();
return;
}
pidownloaddatacursor.close();
}
} else {
if(pidownloaddatacursor.isExtractionError()) {
mPIReferenceObserver.failedWithError(new Exception("Unable to extract reference file."));
pidownloaddatacursor.close();
return;
}
}
} else {
return;
}
}
}
public static class NotInitializedException
extends Exception
{
private static final long serialVersionUID = -4698129909645940909L;
public NotInitializedException() {}
public NotInitializedException(String paramString)
{
super();
}
public NotInitializedException(String paramString, Throwable paramThrowable)
{
super(paramThrowable);
}
public NotInitializedException(Throwable paramThrowable)
{
super();
}
}
public class PIReferenceAccess
{
private PIReference mDelegate;
private PIReferenceDataset mPIReferenceDataset;
private PIReferenceAccess(PIReferenceDataset paramPIReferenceDataset)
{
if (paramPIReferenceDataset == null) {
throw new IllegalArgumentException("The PIReferenceDataset is null.");
}
this.mDelegate = new PIReference(this);
this.mPIReferenceDataset = paramPIReferenceDataset;
}
private PIMapGeoCityDataCursor getGeoCities()
{
return this.mDelegate.getGeoCities(this.mPIReferenceDataset);
}
private PIMapGeoCityDataCursor getGeoCitiesForSubdivision(long paramLong)
{
return this.mDelegate.getGeoCitiesForSubdivision(this.mPIReferenceDataset, paramLong);
}
private PIMapGeoCountryDataCursor getGeoCountries()
{
return this.mDelegate.getGeoCountries(this.mPIReferenceDataset);
}
private PIMapGeoCountrySubdivisionDataCursor getGeoCountrySubdivisions()
{
return this.mDelegate.getGeoCountrySubdivisions(this.mPIReferenceDataset);
}
private PIMapGeoCountrySubdivisionDataCursor getGeoCountrySubdivisionsForCountry(long paramLong)
{
return this.mDelegate.getGeoCountrySubdivisionsForCountry(this.mPIReferenceDataset, paramLong);
}
private PIMapVenueSummaryDataCursor getVenueSummaries(Location paramLocation)
{
return this.mDelegate.getVenueSummaries(this.mPIReferenceDataset, paramLocation);
}
private PIMapVenueSummaryDataCursor getVenueSummariesForCity(long paramLong)
{
return this.mDelegate.getVenueSummariesForCity(this.mPIReferenceDataset, paramLong);
}
private PIMapVenueSummaryDataCursor getVenueSummary(long paramLong)
{
return this.mDelegate.getVenueSummary(this.mPIReferenceDataset, paramLong);
}
private PIMapVenueSummaryDataCursor getVenueSummary(String paramString)
{
return this.mDelegate.getVenueSummary(this.mPIReferenceDataset, paramString);
}
private PIMapVenueSummaryDataCursor getVenueSummarySearchForName(String paramString)
{
return this.mDelegate.getVenueSummarySearchForName(this.mPIReferenceDataset, paramString);
}
private PIMapVenueSummaryDataCursor getVenueSummarySearchForText(String paramString, Location paramLocation)
{
return this.mDelegate.getVenueSummarySearchForText(this.mPIReferenceDataset, paramString, paramLocation);
}
}
public class PIReferenceContentManager
{
private PIContentManager mDelegate = new PIContentManager(this);
public PIReferenceContentManager() {}
private void cancelDownload(Uri paramUri)
{
this.mDelegate.cancelDownload(mContext, paramUri);
}
private boolean deleteReference()
{
return this.mDelegate.deleteReferenceFile(PIMapReference.this.mContext);
}
private void deleteVenueDownload(String paramString)
{
this.mDelegate.deleteVenueDownload(PIMapReference.this.mContext, paramString);
}
private boolean fileExists()
{
return this.mDelegate.referenceFileExists(PIMapReference.this.mContext);
}
private PIDownloadDataCursor getDownloadItem(Uri paramUri)
{
return this.mDelegate.getDownloadItem(PIMapReference.this.mContext, paramUri);
}
private PIDownloadDataCursor getReferenceDownloadItem()
{
return this.mDelegate.getOrCreateReferenceDownloadItem(PIMapReference.this.mContext);
}
private PIFileDataCursor getReferenceFileItem()
{
return this.mDelegate.getReferenceFile(PIMapReference.this.mContext);
}
private void refreshFile()
{
this.mDelegate.refreshReferenceFile(PIMapReference.this.mContext);
}
private void removeCachedZipFiles()
{
PIContentManager.removeCachedZipFiles(PIMapReference.this.mContext);
}
private boolean validateReferenceDownload()
{
return this.mDelegate.validateReferenceDownload(PIMapReference.this.mContext);
}
private void validateVenueDownloads()
{
this.mDelegate.validateVenueDownloads(PIMapReference.this.mContext);
}
}
public static class PIReferenceDownloadObserver
{
private void finished()
{
PIMapReference.sPIMapReference.mContext.getContentResolver().unregisterContentObserver(PIMapReference.sPIMapReference.mObserver);
PIMapReference.sPIMapReference.unRegisterPIReferenceDownloadObserver();
PIMapReference.sPIMapReference.mReferenceETag = null;
}
public void bytesToReceive(int paramInt) {}
public void dataReceived(int paramInt) {}
public void downloadCanceled()
{
finished();
}
public void failedWithError(Exception paramException)
{
finished();
}
public void fileDidUpdate() {}
public void fileNeedsUpdate() {}
public void fileReady()
{
finished();
}
}
}
|
package com.lsjr.zizi.chat.bean;
/**
* 创建人:$ gyymz1993
* 创建时间:2017/9/13 10:50
*/
public class UploadAvatar {
/**
* data : {"oUrl":"http://dev.zizi.com.cn/avatar/o/12/12.jpg","tUrl":"http://dev.zizi.com.cn/avatar/t/12/12.jpg"}
* resultCode : 1
*/
private DataBean data;
private int resultCode;
public DataBean getData() {
return data;
}
public void setData(DataBean data) {
this.data = data;
}
public int getResultCode() {
return resultCode;
}
public void setResultCode(int resultCode) {
this.resultCode = resultCode;
}
public static class DataBean {
/**
* oUrl : http://dev.zizi.com.cn/avatar/o/12/12.jpg
* tUrl : http://dev.zizi.com.cn/avatar/t/12/12.jpg
*/
private String oUrl;
private String tUrl;
public String getOUrl() {
return oUrl;
}
public void setOUrl(String oUrl) {
this.oUrl = oUrl;
}
public String getTUrl() {
return tUrl;
}
public void setTUrl(String tUrl) {
this.tUrl = tUrl;
}
}
}
|
import java.util.Random;
import java.util.Scanner;
public class GameManager {
public void play() {
Player[] player = {new PlayerType1("매"), new PlayerType1("닭"), new PlayerType1("오리"), new PlayerType2("참새"), new PlayerType1("독수리")};
Player[] enemy = {new PlayerType1("정어리"), new PlayerType1("참치"), new PlayerType1("광어"), new PlayerType1("망둥어"), new PlayerType2("고래")};
Scanner scanner = new Scanner(System.in);
for (int i = 0; i < 999999; i++) {
System.out.println("\n\n" + (i + 1) + "턴\n");
// 플레이어 턴
for (int playerIndex = 0; playerIndex < player.length; playerIndex++) {
if (player[playerIndex].isLive()) {
player[playerIndex].action(player, enemy);
}
}
// 적 턴
for (int enemyIndex = 0; enemyIndex < enemy.length; enemyIndex++) {
if (enemy[enemyIndex].isLive()) {
enemy[enemyIndex].action(enemy, player);
}
}
// 게임 종료 여부 확인
boolean isPlayerLive = false;
for (int playerIndex = 0; playerIndex < player.length; playerIndex++) {
if (player[playerIndex].isLive()) {
isPlayerLive = true;
}
}
boolean isEnemyLive = false;
for (int enemyIndex = 0; enemyIndex < enemy.length; enemyIndex++) {
if (enemy[enemyIndex].isLive()) {
isEnemyLive = true;
}
}
if (isPlayerLive && !isEnemyLive) {
System.out.println("플레이어 승리");
break;
} else if (!isPlayerLive && isEnemyLive) {
System.out.println("적 승리");
break;
}
System.out.println("턴을 진행하실려면 엔터를 누르세요");
scanner.nextLine();
}
}
}
|
/*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package codevita;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.Arrays;
/**
*
* @author Aman Nautiyal
*/
public class DateTime {
/**
* @param args the command line arguments
*/
static boolean month(int mon, int d)
{
if(mon==2 && d>28)
return false;
if((mon==4||mon==6||mon==9||mon==11)&&d==31)
return false;
return true;
}
public static void main(String[] args) throws IOException {
BufferedReader Br = new BufferedReader(new InputStreamReader(System.in));
String str = Br.readLine();
String tokens[] = str.split("[,]");
int freq[] = new int[10];
Arrays.fill(freq, 0);
for (int i = 0; i < 12; i++) {
freq[Integer.parseInt(tokens[i])]++;
}
int d1=0, d2=0, m1=0, m2=0, h1=0, h2=0, mn1=0, mn2=0;
boolean found = false;
outer:
for (m1 = 1; m1 >=0; m1--) {
if (freq[m1] == 0) {
continue;
}
if(m1==0)
System.out.println("Hi");
freq[m1]--;
for (m2 = 9; m2 >=0; m2--) {
if ((m1==1&&m2>2)||freq[m2] == 0) {
continue;
}
freq[m2]--;
for (d1 = 3; d1 >=3; d1--) {
if (freq[d1] == 0) {
continue;
}
freq[d1]--;
for (d2 = 9; d2 >= 0; d2--) {
if ((d1==0 && d2==0)||(d1==3 && d2>1)||!month(m1*10+m2,d1*10+d2)||freq[d2] == 0) {
continue;
}
freq[d2]--;
for (h1 = 2; h1 >= 0; h1--) {
if (freq[h1] == 0) {
continue;
}
freq[h1]--;
for (h2 = 9; m1 >= 0; h2--) {
if ((h1==0&&h2==0)||(h1==2)&&(h2>3)||freq[h2] == 0) {
continue;
}
freq[h2]--;
for (mn1 = 5; mn1 >=0; mn1--) {
if (freq[mn1] == 0) {
continue;
}
freq[mn1]--;
for (mn2 = 9; mn2 >= 0; mn2--) {
if (freq[mn2] == 0) {
continue;
}
found=true;
break outer;
}
freq[mn1]++;
}
freq[h2]++;
}
freq[h1]++;
}
freq[d2]++;
}
freq[d1]++;
}
freq[m2]++;
}
freq[m1]++;
}
if(found)
System.out.print(m1+""+m2+"/"+d1+""+d2+" "+h1+""+h2+":"+mn1+""+mn2);
else
System.out.print(0);
}
}
|
package com.esum.comp.sftp.server.auth;
import java.io.File;
import java.security.PublicKey;
import java.security.interfaces.RSAPublicKey;
import org.apache.sshd.common.KeyPairProvider;
import org.apache.sshd.server.PublickeyAuthenticator;
import org.apache.sshd.server.session.ServerSession;
import org.bouncycastle.jcajce.provider.asymmetric.rsa.BCRSAPublicKey;
import org.bouncycastle.jce.provider.JCERSAPublicKey;
import org.bouncycastle.jce.provider.JDKDSAPublicKey;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import ch.ethz.ssh2.packets.TypesWriter;
import com.esum.common.util.AccessLogUtils;
import com.esum.comp.sftp.SftpConfig;
import com.esum.comp.sftp.table.SftpInfoRecord;
import com.esum.comp.sftp.table.SftpInfoTable;
import com.esum.framework.FrameworkSystemVariables;
import com.esum.framework.common.util.SysUtil;
import com.esum.framework.core.component.table.InfoTableManager;
import com.esum.framework.security.ssh.SSHAuthInfo;
import com.esum.framework.security.ssh.SSHAuthInfoManager;
import com.esum.framework.security.ssh.SSHUtil;
/**
* Copyright(c) eSum Technologies, Inc. All rights reserved.
*/
public class UserAuthPublickeyAuthenticator implements PublickeyAuthenticator {
private Logger log = LoggerFactory.getLogger(getClass());
private String traceId = "[" + SftpConfig.MODULE_NAME + "][" + System.getProperty(FrameworkSystemVariables.NODE_ID) + "] ";
/**
* Check the validity of a public key.
*/
public boolean authenticate(String username, PublicKey key, ServerSession session) {
log.debug("======================================================");
log.debug("The client connected to server from " + session.getIoSession().getRemoteAddress() + ".");
log.debug("======================================================");
log.debug(traceId + "Received SFTP Request on publickey authenticate. user: "+username + " from " + session.getIoSession().getRemoteAddress());
String algorithm = (key instanceof RSAPublicKey) ? KeyPairProvider.SSH_RSA : KeyPairProvider.SSH_DSS;
log.debug(traceId + "User: "+username+", Algorithm: "+ algorithm);
try {
byte[] pk_enc = null;
if (algorithm.equals(KeyPairProvider.SSH_RSA)) {
if(key instanceof BCRSAPublicKey) {
BCRSAPublicKey pk = (BCRSAPublicKey)key;
TypesWriter tw = new TypesWriter();
tw.writeString(algorithm);
tw.writeMPInt(pk.getPublicExponent());
tw.writeMPInt(pk.getModulus());
pk_enc = tw.getBytes();
} else if(key instanceof JCERSAPublicKey) {
JCERSAPublicKey pk = (JCERSAPublicKey)key;
TypesWriter tw = new TypesWriter();
tw.writeString(algorithm);
tw.writeMPInt(pk.getPublicExponent());
tw.writeMPInt(pk.getModulus());
pk_enc = tw.getBytes();
}
} else {
JDKDSAPublicKey pk = (JDKDSAPublicKey) key;
TypesWriter tw = new TypesWriter();
tw.writeString(algorithm);
tw.writeMPInt(pk.getParams().getP());
tw.writeMPInt(pk.getParams().getQ());
tw.writeMPInt(pk.getParams().getG());
tw.writeMPInt(pk.getY());
pk_enc = tw.getBytes();
}
String fingerPrint = SSHUtil.getFingerPrint(pk_enc);
if (fingerPrint == null) {
throw new Exception("Fingerprint is null.");
}
log.debug(traceId + "FingerPrint:(" + fingerPrint + ") User:(" + username + ")");
SSHAuthInfo sshAuthInfo = SSHAuthInfoManager.getInstance().getAuthInfoByUser(username);
if (sshAuthInfo == null)
throw new Exception("Not found SSH AuthInfoTable for (" + username + ") User ID.");
SftpInfoTable infoTable = (SftpInfoTable)InfoTableManager.getInstance().getInfoTable(SftpConfig.SFTP_INFO_TABLE_ID);
SftpInfoRecord infoRecord = infoTable.getSftpInfoByAuthIdForServer(sshAuthInfo.getAuthInfoId());
if (infoRecord == null) {
throw new Exception("Not found SFTP InfoTable for (" + sshAuthInfo.getAuthInfoId() + ") Auth ID.");
}
String publickeyFile = SysUtil.replacePropertyToValue(sshAuthInfo.getPublickeyFile());
String inboundFingerprint = infoRecord.getInboundFingerPrint(new File(publickeyFile));
if (inboundFingerprint == null) {
throw new Exception("Inbound Fingerprint is null.");
}
log.debug(traceId + "AuthorizedKey Fingerprint:(" + inboundFingerprint + ")");
if (inboundFingerprint.compareTo(fingerPrint) != 0) {
throw new Exception ("Publickey is wrong!! (fingerprint: " + fingerPrint + ")");
}
AccessLogUtils.putAccessLog(username, SftpConfig.MODULE_NAME, session.getIoSession().getRemoteAddress().toString(), "AUTH_SUCCESS");
log.debug(traceId + "Publickey Authentication succeeded. (user: " + username + ")");
return true;
} catch (Exception e) {
AccessLogUtils.putAccessLog(username, SftpConfig.MODULE_NAME, session.getIoSession().getRemoteAddress().toString(), "AUTH_FAIL!");
log.error(traceId + "Publickey Authenticate fail! (user: " + username + ")", e);
}
return false;
}
}
|
package Productos;
import java.awt.event.KeyEvent;
import java.awt.event.MouseEvent;
import java.sql.Connection;
import java.sql.Date;
import java.sql.ResultSet;
import java.sql.Statement;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.GregorianCalendar;
import javax.swing.ImageIcon;
import javax.swing.JButton;
import javax.swing.JLabel;
import javax.swing.JOptionPane;
import javax.swing.JTable;
import javax.swing.JTextArea;
import javax.swing.JTextField;
import Conexion.Conectar;
import com.mysql.jdbc.PreparedStatement;
public class Componentes {
JTextField hola = null;
Conectar conex = new Conectar();
java.sql.Connection con = conex.conexion(hola);
java.sql.Statement list;
ResultSet rs;
void limpiar(JTextField codigo, JTextField nombre,
JTextArea descripcion, JTextField cantidad, JTextField precio){
codigo.setText("");
nombre.setText("");
descripcion.setText("");
cantidad.setText("");
precio.setText("");
}
void mayusculas(KeyEvent e){
char keyChar = e.getKeyChar();
if (Character.isLowerCase(keyChar)) {
e.setKeyChar(Character.toUpperCase(keyChar));
}
}
void numerosEnteros(KeyEvent e){
char c = e.getKeyChar();
if(c < '0' || c > '9') e.consume();
}
void numerosFlotantes(JTextField campo,KeyEvent e){
char c = e.getKeyChar();
if ((c < '0' || c > '9') && campo.getText().contains(".")
&& (c!=(char)KeyEvent.VK_BACK_SPACE)) {
e.consume();
} else if ((c < '0' || c > '9') && (c != '.') && (c!=(char)KeyEvent.VK_BACK_SPACE)) {
e.consume();
}
}
void habilitar(JButton eliminar, JButton actualizar){
eliminar.setEnabled(true);
actualizar.setEnabled(true);
}
void deshabilitar(JButton eliminar, JButton actualizar){
eliminar.setEnabled(false);
actualizar.setEnabled(false);
}
void eliminarProducto(JTable tableVerProductos){
int replay = JOptionPane.showConfirmDialog(null, "El registro será eliminado. ¿Desea continuar?");
if (replay == JOptionPane.YES_OPTION) {
try {
JTextField hola = null;
con = conex.conexion(hola);
String sql = "delete from productos where clave=" + tableVerProductos.getValueAt(tableVerProductos.getSelectedRow(), 0);
list = con.createStatement();
int n = list.executeUpdate(sql);
if (n > 0) {
JOptionPane.showMessageDialog(null, "Registro eliminado correctamente");
}
} catch (Exception e) {
JOptionPane.showMessageDialog(null, "Error " + e.getMessage());
}
} else{}
}
void actualizarProductos1(JTextField txtClave,JTextField txtNombreProducto,
JTextField txtPrecioCliente,JTextField txtCantidad,JTextField txtPrecioDistribuidor,JTextField txtPrecioGota,JTextField txtUnidad,JTextField txtPv){
String sql="";
Conectar cx=new Conectar();
Connection cn=cx.conexion(null);
Statement comando;
con = conex.conexion(hola);
String existente="SELECT * FROM productos WHERE clave='"+txtClave.getText()+"'";
try {
comando=(Statement) cn.createStatement();
ResultSet rs= ((java.sql.Statement) comando).executeQuery(existente);
if(rs.next()){
String cantidadDtb=rs.getString("cantidad");
int cantidad=Integer.parseInt(cantidadDtb);
String cantidadT= txtCantidad.getText();
int cantidadTexto=Integer.parseInt(cantidadT);
int ncant=cantidad+cantidadTexto;
PreparedStatement ps;
if (txtClave.equals("")) {
sql = "update productos set cantidad = ? where clave = '" + txtClave.getText() + "'";
ps = (PreparedStatement) con.prepareStatement(sql);
ps.setInt(1, ncant);
}else {
sql = "update productos set cantidad = ? where clave = '" + txtClave.getText()+ "'";
ps = (PreparedStatement) con.prepareStatement(sql);
ps.setInt(1, ncant);
}
int n = ps.executeUpdate();
if (n > 0) {
//JOptionPane.showMessageDialog(null, "Registro modificado correctamente");
}
}
} catch (Exception e) {
// TODO: handle exception
JOptionPane.showMessageDialog(null, "Error " + e.getMessage());
}
}
void actualizarProductos(JTextField txtClave,JTextField txtNombreProducto,
JTextField txtPrecioCliente,JTextField txtCantidad,JTextField txtPrecioDistribuidor,JTextField txtPrecioGota,JTextField txtUnidad,JTextField txtPv){
String sql="";
Conectar cx=new Conectar();
Connection cn=cx.conexion(null);
Statement comando;
con = conex.conexion(hola);
String existente="SELECT * FROM productos WHERE Clave='"+txtClave.getText()+"'";
try {
comando=(Statement) cn.createStatement();
ResultSet rs= ((java.sql.Statement) comando).executeQuery(existente);
if(rs.next()){
String cantidadDtb=rs.getString("cantidad");
int cantidad=Integer.parseInt(cantidadDtb);
String cantidadT= txtCantidad.getText();
int cantidadTexto=Integer.parseInt(cantidadT);
int ncant=cantidad+cantidadTexto;
PreparedStatement ps;
sql = "update productos set nombre = ?,precio_gota = ?, precio_cliente = ?," +
"cantidad = ?, precio_distribuidor = ?,pv = ?,unidad = ? where clave = '"+txtClave.getText()+"'";
ps = (PreparedStatement) con.prepareStatement(sql);
ps.setString(1, txtNombreProducto.getText());
ps.setString(2, txtPrecioGota.getText());
ps.setString(3, txtPrecioCliente.getText());
ps.setInt(4, ncant);
ps.setString(5, txtPrecioDistribuidor.getText());
ps.setString(6, txtPv.getText());
ps.setString(7, txtUnidad.getText());
int n = ps.executeUpdate();
if (n > 0) {
JOptionPane.showMessageDialog(null, "Registro modificado correctamente");
}
}
} catch (Exception e) {
// TODO: handle exception
JOptionPane.showMessageDialog(null, "Error " + e.getMessage());
}
}
}
|
package cn.xeblog.xechat.utils;
import cn.xeblog.xechat.domain.mo.User;
import cn.xeblog.xechat.domain.ro.MessageRO;
import cn.xeblog.xechat.enums.CodeEnum;
import cn.xeblog.xechat.exception.ErrorCodeException;
import org.apache.commons.codec.digest.DigestUtils;
import org.apache.commons.lang3.ArrayUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;
/**
* 校验相关
*
* @author yanpanyi
* @date 2019/3/25
*/
@Component
public class CheckUtils {
/**
* 撤消消息过期时间 3分钟
*/
private static final long MESSAGE_EXPIRE_DATE = 180000;
private static String password;
@Value("${chatrecord.password}")
public void setPassword(String password) {
CheckUtils.password = password;
}
/**
* 校验撤消的消息id
*
* @param messageId
* @return
*/
public static void checkMessageId(String messageId, String userId) throws ErrorCodeException {
if (StringUtils.isEmpty(messageId)) {
throw new ErrorCodeException(CodeEnum.INVALID_PARAMETERS);
}
String[] str = StringUtils.split(messageId, ':');
if (!userId.equals(str[0])) {
throw new ErrorCodeException(CodeEnum.INVALID_TOKEN);
}
// 判断消息是否过期
if (System.currentTimeMillis() > Long.parseLong(str[1]) + MESSAGE_EXPIRE_DATE) {
throw new ErrorCodeException(CodeEnum.MESSAGE_HAS_EXPIRED);
}
}
/**
* 判断是否是图片
*
* @param type
* @return true是图片 false不是图片
*/
public static boolean isImage(String type) {
return ".jpg".equals(type) || ".jpeg".equals(type) || ".png".equals(type) || ".bmp".equals(type)
|| ".gif".equals(type);
}
/**
* 校验token
*
* @param token
* @return
*/
public static boolean checkToken(String token) {
return StringUtils.isEmpty(token) ? false : password.equals(DigestUtils.md5Hex(token));
}
/**
* 校验用户信息
*
* @param user
* @return
*/
public static boolean checkUser(User user) {
return null != user && StringUtils.isNotEmpty(user.getUserId());
}
/**
* 校验消息内容
*
* @param message
* @return
*/
public static boolean checkMessage(String message) {
return StringUtils.isNotEmpty(message);
}
/**
* 校验图片地址
*
* @param image
* @return
*/
public static boolean checkImageUrl(String image) {
return StringUtils.isNotEmpty(image);
}
/**
* 校验消息请求对象
*
* @param messageRO
* @return
*/
public static boolean checkMessageRo(MessageRO messageRO) {
if (messageRO == null) {
return false;
}
return checkMessage(messageRO.getMessage()) || checkImageUrl(messageRO.getImage());
}
/**
* 校验订阅地址
*
* @param subAddress
* @return
*/
public static boolean checkSubAddress(String subAddress) {
return StringUtils.isNotEmpty(subAddress);
}
/**
* 校验接收者
*
* @param receiver
* @return
*/
public static boolean checkReceiver(String[] receiver) {
return ArrayUtils.isNotEmpty(receiver);
}
}
|
package br.com.porquesim.eventmanager;
public class TesteEvent extends Event {
public TesteEvent(Object source) {
super(source);
}
private static final long serialVersionUID = 1L;
}
|
package com.zeroentropy.game.handler.enemy;
import java.util.Arrays;
import org.andengine.util.math.MathUtils;
import com.zeroentropy.game.sprite.Enemy;
import com.zeroentropy.game.sprite.Player;
public class JellyfishHandler implements IEnemyHandler {
// private PhysicsHandler mHandler;
// private int mType = 0;
private static final int mFirstTileIndex = 0;
private static final int mLastTileIndex = 11;
private static final int mFrameCount = mLastTileIndex - mFirstTileIndex + 1;
private static long[] mFrameDurations = new long[mFrameCount] ;
//private int[] mFrames = new int[mFrameCount];
public static JellyfishHandler getInstance(){return INSTANCE;}
private static JellyfishHandler INSTANCE = new JellyfishHandler();
private JellyfishHandler(){
Arrays.fill(mFrameDurations, FRAME_DURATION_EACH);
}
private static final int VELOCITY_Y = -120;
public void enter(final Enemy pSprite) {
if (pSprite.getRotation() != 0)
pSprite.setRotation(0);
pSprite.setFlippedHorizontal(MathUtils.randomBoolean());
pSprite.resetPhysics();
pSprite.animate(mFrameDurations, mFirstTileIndex, mLastTileIndex);
pSprite.setVelocityY(MathUtils.randomFactor(VELOCITY_Y, 0.5f));
}
public void execute(final float pSecondsElapsed, final Enemy pSprite) {
}
public void exit(final Enemy pSprite) {
}
@Override
public void executeCollides(final Enemy pSprite, final Player pPlayer) {
// TODO Auto-generated method stub
pSprite.brokenSelf();
// World.getInstance().mPlayer.setState(IPlayer.STATE_JUMP);
// 增加桃子-生命值
// peach++;
pPlayer.getPeach();
}
}
|
package com.CollectionFramework_Concept;
import java.util.HashMap;
import java.util.Map;
/*Java HashMap class implements the map interface by using a hashtable.
* It inherits AbstractMap class and implements Map interface.
* A HashMap contains values based on the key.
* It contains only unique elements.
* It may have one null key and multiple null values.
*/
class Book3 {
int id;
String name,author,publisher;
int quantity;
public Book3(int id, String name, String author, String publisher, int quantity) {
this.id = id;
this.name = name;
this.author = author;
this.publisher = publisher;
this.quantity = quantity;
}
}
public class HashMapDemo {
public static void main(String[] args) {
//Creating map of Books
Map<Integer,Book3> map=new HashMap<Integer,Book3>();
//Creating Books
Book3 b1=new Book3(101,"Let us C","Yashwant Kanetkar","BPB",8);
Book3 b2=new Book3(102,"Data Communications & Networking","Forouzan","Mc Graw Hill",4);
Book3 b3=new Book3(103,"Operating System","Galvin","Wiley",6);
//Adding Books to map
map.put(1,b1);
map.put(2,b2);
map.put(3,b3);
//Traversing map
for(Map.Entry<Integer, Book3> entry:map.entrySet()){
int key=entry.getKey();
Book3 b=entry.getValue();
System.out.println(key+" Details:");
System.out.println(b.id+" "+b.name+" "+b.author+" "+b.publisher+" "+b.quantity);
}
}
}
|
package tp.pr2;
import java.io.IOException;
import java.util.Scanner;
import tp.pr2.control.Controlador;
import tp.pr2.logica.Partida;
public class Main {
public static void main(String[] args) throws IOException {
Partida partida=new Partida();
Scanner in=new Scanner(System.in);
Controlador controller=new Controlador(partida, in);
controller.run();
}
}
|
/**
* This class is generated by jOOQ
*/
package schema.tables;
import java.sql.Timestamp;
import java.util.Arrays;
import java.util.List;
import javax.annotation.Generated;
import org.jooq.Field;
import org.jooq.ForeignKey;
import org.jooq.Identity;
import org.jooq.Schema;
import org.jooq.Table;
import org.jooq.TableField;
import org.jooq.UniqueKey;
import org.jooq.impl.TableImpl;
import schema.BitnamiEdx;
import schema.Keys;
import schema.tables.records.VerifyStudentSkippedreverificationRecord;
/**
* This class is generated by jOOQ.
*/
@Generated(
value = {
"http://www.jooq.org",
"jOOQ version:3.8.4"
},
comments = "This class is generated by jOOQ"
)
@SuppressWarnings({ "all", "unchecked", "rawtypes" })
public class VerifyStudentSkippedreverification extends TableImpl<VerifyStudentSkippedreverificationRecord> {
private static final long serialVersionUID = 1541771043;
/**
* The reference instance of <code>bitnami_edx.verify_student_skippedreverification</code>
*/
public static final VerifyStudentSkippedreverification VERIFY_STUDENT_SKIPPEDREVERIFICATION = new VerifyStudentSkippedreverification();
/**
* The class holding records for this type
*/
@Override
public Class<VerifyStudentSkippedreverificationRecord> getRecordType() {
return VerifyStudentSkippedreverificationRecord.class;
}
/**
* The column <code>bitnami_edx.verify_student_skippedreverification.id</code>.
*/
public final TableField<VerifyStudentSkippedreverificationRecord, Integer> ID = createField("id", org.jooq.impl.SQLDataType.INTEGER.nullable(false), this, "");
/**
* The column <code>bitnami_edx.verify_student_skippedreverification.course_id</code>.
*/
public final TableField<VerifyStudentSkippedreverificationRecord, String> COURSE_ID = createField("course_id", org.jooq.impl.SQLDataType.VARCHAR.length(255).nullable(false), this, "");
/**
* The column <code>bitnami_edx.verify_student_skippedreverification.created_at</code>.
*/
public final TableField<VerifyStudentSkippedreverificationRecord, Timestamp> CREATED_AT = createField("created_at", org.jooq.impl.SQLDataType.TIMESTAMP.nullable(false), this, "");
/**
* The column <code>bitnami_edx.verify_student_skippedreverification.checkpoint_id</code>.
*/
public final TableField<VerifyStudentSkippedreverificationRecord, Integer> CHECKPOINT_ID = createField("checkpoint_id", org.jooq.impl.SQLDataType.INTEGER.nullable(false), this, "");
/**
* The column <code>bitnami_edx.verify_student_skippedreverification.user_id</code>.
*/
public final TableField<VerifyStudentSkippedreverificationRecord, Integer> USER_ID = createField("user_id", org.jooq.impl.SQLDataType.INTEGER.nullable(false), this, "");
/**
* Create a <code>bitnami_edx.verify_student_skippedreverification</code> table reference
*/
public VerifyStudentSkippedreverification() {
this("verify_student_skippedreverification", null);
}
/**
* Create an aliased <code>bitnami_edx.verify_student_skippedreverification</code> table reference
*/
public VerifyStudentSkippedreverification(String alias) {
this(alias, VERIFY_STUDENT_SKIPPEDREVERIFICATION);
}
private VerifyStudentSkippedreverification(String alias, Table<VerifyStudentSkippedreverificationRecord> aliased) {
this(alias, aliased, null);
}
private VerifyStudentSkippedreverification(String alias, Table<VerifyStudentSkippedreverificationRecord> aliased, Field<?>[] parameters) {
super(alias, null, aliased, parameters, "");
}
/**
* {@inheritDoc}
*/
@Override
public Schema getSchema() {
return BitnamiEdx.BITNAMI_EDX;
}
/**
* {@inheritDoc}
*/
@Override
public Identity<VerifyStudentSkippedreverificationRecord, Integer> getIdentity() {
return Keys.IDENTITY_VERIFY_STUDENT_SKIPPEDREVERIFICATION;
}
/**
* {@inheritDoc}
*/
@Override
public UniqueKey<VerifyStudentSkippedreverificationRecord> getPrimaryKey() {
return Keys.KEY_VERIFY_STUDENT_SKIPPEDREVERIFICATION_PRIMARY;
}
/**
* {@inheritDoc}
*/
@Override
public List<UniqueKey<VerifyStudentSkippedreverificationRecord>> getKeys() {
return Arrays.<UniqueKey<VerifyStudentSkippedreverificationRecord>>asList(Keys.KEY_VERIFY_STUDENT_SKIPPEDREVERIFICATION_PRIMARY, Keys.KEY_VERIFY_STUDENT_SKIPPEDREVERIFICATION_VERIFY_STUDENT_SKIPPEDREVERIFICATI_USER_ID_1E8AF5A5E735AA1A_UNIQ);
}
/**
* {@inheritDoc}
*/
@Override
public List<ForeignKey<VerifyStudentSkippedreverificationRecord, ?>> getReferences() {
return Arrays.<ForeignKey<VerifyStudentSkippedreverificationRecord, ?>>asList(Keys.D759FFA5CA66EF1A2C8C200F7A21365B, Keys.VERIFY_STUDENT_SKIPPEDR_USER_ID_6752B392E3D3C501_FK_AUTH_USER_ID);
}
/**
* {@inheritDoc}
*/
@Override
public VerifyStudentSkippedreverification as(String alias) {
return new VerifyStudentSkippedreverification(alias, this);
}
/**
* Rename this table
*/
public VerifyStudentSkippedreverification rename(String name) {
return new VerifyStudentSkippedreverification(name, null);
}
}
|
package com.jvinix.iy4s;
import android.app.Application;
public class Program extends Application {
public static String TOKEN = "";
}
|
package com.gaoshin.top;
public enum ShortcutType {
Launch,
Info,
Delete,
Kill, ;
}
|
package com.midea.thread;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;
import java.util.concurrent.locks.ReentrantReadWriteLock;
//读写锁的概念就是共享锁 和 排它锁(互斥锁)
//读锁只对读共享 不对写共享 写是全部都排斥
public class ReadWriteLockTest {
static Lock lock =new ReentrantLock();//重入锁是排它锁
static ReentrantReadWriteLock rwlock=new ReentrantReadWriteLock();
static Lock readlock=rwlock.readLock();//读锁是共享锁
static Lock writelock=rwlock.writeLock();//写锁是排它锁
public static void read(Lock lock){
try {
lock.lock();
Thread.sleep(2000);
System.out.println("读结束");
}catch (Exception e){
}finally {
lock.unlock();
}
}
public static void write(Lock lock,String v){
try {
lock.lock();
Thread.sleep(2000);
String str=v;
System.out.println("写结束");
}catch (Exception e){
}finally {
lock.unlock();
}
}
public static void main(String[] args) {
// Runnable read=()->read(lock);
Runnable read=()->read(readlock);
Runnable write=()->write(writelock,"heiehieh");
for(int i=0;i<20;i++){
new Thread(read).start();
}
for(int i=0;i<3;i++){
new Thread(write).start();
}
}
}
|
package watchhome.play.yale.phonecamera.watchhome.play.yale.phonecamera.activity;
import android.content.Context;
import android.content.res.Configuration;
import android.graphics.ImageFormat;
import android.hardware.Camera;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.view.Display;
import android.view.SurfaceHolder;
import android.view.SurfaceView;
import android.view.View;
import android.view.WindowManager;
import android.widget.Button;
import java.io.IOException;
import watchhome.play.yale.phonecamera.R;
import watchhome.play.yale.phonecamera.watchhome.play.yale.phonecamera.codec.AvcEncoder;
import watchhome.play.yale.phonecamera.watchhome.play.yale.phonecamera.util.LogUtils;
public class CameraShowActivity extends AppCompatActivity implements SurfaceHolder.Callback, Camera.PreviewCallback, View.OnClickListener{
private static Context context = null;
private SurfaceView surfaceview;
private SurfaceHolder surfaceholder;
private Camera camera = null;
private Button switchButton;
AvcEncoder avcCodec;
int width = 720;
int height = 1280;
int framerate = 20;
int bitrate = 2500000;
byte[] h264 = new byte[width*height*3/2];
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_camera_show);
initCamera();
}
private void initCamera(){
context = this;
surfaceview = (SurfaceView)findViewById(R.id.camera_show);
surfaceholder = surfaceview.getHolder();
surfaceholder.setType(SurfaceHolder.SURFACE_TYPE_PUSH_BUFFERS);
surfaceholder.addCallback(CameraShowActivity.this);
switchButton = (Button)findViewById(R.id.switch_camera);
switchButton.setOnClickListener(this);
// 方法1 Android获得屏幕的宽和高
WindowManager windowManager = getWindowManager();
Display display = windowManager.getDefaultDisplay();
int screenWidth = screenWidth = display.getWidth();
int screenHeight = screenHeight = display.getHeight();
avcCodec = new AvcEncoder(screenWidth,screenHeight,framerate,bitrate);
}
@Override
public void surfaceCreated(SurfaceHolder holder) {
//获取camera对象
camera = Camera.open();
try {
//设置预览监听
camera.setPreviewDisplay(holder);
Camera.Parameters parameters = camera.getParameters();
parameters.setPreviewSize(width, height);
parameters.setPictureSize(width, height);
parameters.setPreviewFormat(ImageFormat.YV12);
if (this.getResources().getConfiguration().orientation
!= Configuration.ORIENTATION_LANDSCAPE) {
parameters.set("orientation", "portrait");
camera.setDisplayOrientation(90);
parameters.setRotation(90);
} else {
parameters.set("orientation", "landscape");
camera.setDisplayOrientation(0);
parameters.setRotation(0);
}
camera.setParameters(parameters);
//启动摄像头预览
camera.startPreview();
camera.setPreviewCallback(this);
} catch (IOException e) {
e.printStackTrace();
camera.release();
}
}
@Override
public void surfaceChanged(SurfaceHolder holder, int format, int width, int height) {
}
@Override
public void surfaceDestroyed(SurfaceHolder holder) {
if (camera != null) {
camera.setPreviewCallback(null) ;
camera.stopPreview();
camera.release();
}
avcCodec.close();
}
@Override
public void onPreviewFrame(byte[] data, Camera camera) {
//编码视频数据
LogUtils.i("video encode", "data length : "+data.length);
if(avcCodec != null){
int ret = avcCodec.offerEncoder(data, h264);
LogUtils.d("video encode", "Video data encode ret: "+ret);
}
}
@Override
public void onClick(View v) {
switch (v.getId()){
case R.id.switch_camera:{
switchCamera();
break;
}
}
}
private void switchCamera(){
}
}
|
package net.tascalate.concurrent;
import java.util.concurrent.Callable;
import java.util.concurrent.Executor;
import java.util.concurrent.RunnableFuture;
public class CompletableTask<T> extends AbstractCompletableTask<T> implements RunnableFuture<T> {
public CompletableTask(final Executor executor, Callable<T> callable) {
super(executor, callable);
}
@Override
public void run() {
task.run();
}
public static <T> Promise<T> completedFuture(T value, Executor defaultExecutor) {
CompletableTask<T> result = new CompletableTask<T>(defaultExecutor, () -> value);
SAME_THREAD_EXECUTOR.execute(result);
return result;
}
@Override
Runnable setupTransition(Callable<T> code) {
throw new UnsupportedOperationException();
}
@Override
protected <U> AbstractCompletableTask<U> createCompletionStage(Executor executor) {
return new CompletableSubTask<U>(executor);
}
}
|
package com.spring.controllers;
/*
301016383 - Julio Vinicius A. de Carvalho
November 17, 2019
*/
import java.util.List;
import javax.servlet.http.HttpServletResponse;
import javax.validation.Valid;
import javassist.NotFoundException;
import org.springframework.security.access.annotation.Secured;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import com.spring.models.*;
import com.spring.security.jwt.ServletUtil;
@RestController
@CrossOrigin("http://parrotsays.tk")
@RequestMapping("/api/reports")
public class ReportController {
@Autowired
ReportRepository repo;
// Get all reports
@Secured({ "ROLE_ADMIN" })
@GetMapping("/getall")
public List<Report> getAllReports()
{
return repo.findAllReports();//findAll();
}
@Secured({ "ROLE_SECGUARD", "ROLE_ADMIN" })
// Get all reports by status
@GetMapping("/getbystatus/{id}")
public List<Report> getReportsByStatus (@PathVariable(value = "id") Integer statusCode)
{
return repo.findByStatusCode(statusCode);
}
// Create a new report
@PostMapping("/addreport")
public void addReport(@Valid @RequestBody Report report, HttpServletResponse response) throws Exception {
try
{
String json = ServletUtil.getJson("reportId", String.valueOf(repo.save(report).getReportId()));
ServletUtil.write(response, HttpStatus.OK, json);
}
catch(Exception exc)
{
ServletUtil.write(response, HttpStatus.BAD_REQUEST, ServletUtil.getJson("error", exc.getCause().toString()));
}
}
// Get a Single report
@GetMapping("/getreport/{id}")
public Report getReportById(@PathVariable(value = "id") Integer reportId, HttpServletResponse response) throws NotFoundException
{
return repo.findById(reportId)
.orElseThrow(() -> new NotFoundException("ReportId "+ reportId+ " Not found."));
}
// Update a Report
@Secured({ "ROLE_SECGUARD", "ROLE_ADMIN" })
@PutMapping("/updatereport/{id}")
public Report updateReport(@PathVariable(value = "id") Integer reportId,
@RequestBody Report reportEdited) throws NotFoundException {
Report reportTemp = repo.findById(reportId)
.orElseThrow(() -> new NotFoundException("ReportId "+ reportId+ " Not found."));
reportTemp.setAdminId(reportEdited.getAdminId());
reportTemp.setDateTimeSolution(reportEdited.getDateTimeSolution());
reportTemp.setSolution(reportEdited.getSolution());
reportTemp.setStatusCode(reportEdited.getStatusCode());
return repo.save(reportTemp);
}
// Delete a Report
@Secured({ "ROLE_ADMIN" })
@DeleteMapping("/delreport/{id}")
public ResponseEntity<?> deleteReport(@PathVariable(value = "id") Integer reportId) throws NotFoundException {
repo.deleteById(reportId);//.delete(report);
return ResponseEntity.ok().build();
}
}
|
package com.airlineeticketing.airlineeticketingplatform.domain;
import javax.persistence.Entity;
@Entity
public class Service extends Abstract {
private String serviceName;
private int serviceFee;
public String getServiceName() {
return serviceName;
}
public void setServiceName(String serviceName) {
this.serviceName = serviceName;
}
public int getServiceFee() {
return serviceFee;
}
public void setServiceFee(int serviceFee) {
this.serviceFee = serviceFee;
}
@Override
public String toString() {
return "Service{" +
"serviceName='" + serviceName + '\'' +
", serviceFee=" + serviceFee +
'}';
}
}
|
package ru.hse.servers.architectures;
import ru.hse.servers.Client;
import ru.hse.servers.Constants;
import ru.hse.servers.TestConfig;
import ru.hse.servers.Utils;
import ru.hse.servers.protocol.message.Message;
import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.io.EOFException;
import java.io.IOException;
import java.net.ServerSocket;
import java.net.Socket;
import java.net.SocketException;
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.CopyOnWriteArrayList;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.stream.Collectors;
public class BlockingServer extends AbstractServer {
private final TestConfig config;
private ServerSocket serverSocket;
private final ExecutorService acceptWorker = Executors.newSingleThreadExecutor();
private volatile boolean isWorking = true;
private final List<ClientHandler> clients = new ArrayList<>();
private final CountDownLatch startLatch;
public BlockingServer(TestConfig config, CountDownLatch startLatch) {
this.config = config;
this.startLatch = startLatch;
}
@Override
public void start() throws IOException {
serverSocket = new ServerSocket(Constants.PORT);
acceptWorker.submit(() -> acceptClients(serverSocket));
}
private void acceptClients(ServerSocket socket) {
try (ServerSocket ignored = socket) {
while (isWorking) {
try {
Socket clientSocket = socket.accept();
System.out.println("Accepted client");
ClientHandler handler = new ClientHandler(clientSocket);
clients.add(handler);
startLatch.countDown();
handler.processClient();
} catch (SocketException ignore) {
}
}
}
catch (EOFException ignore) {
}
catch (IOException e) {
e.printStackTrace();
}
}
@Override
public void stop() throws IOException {
isWorking = false;
serverSocket.close();
acceptWorker.shutdown();
workers.shutdown();
for (ClientHandler client : clients) {
client.stop();
}
}
@Override
public double getMeanTime() {
List<Long> results = clients.stream().flatMap(c -> c.results.stream()).collect(Collectors.toList());
return ((double) results.stream().reduce(0L, Long::sum)) / results.size();
}
private class ClientHandler {
private final Socket socket;
public final ExecutorService reader = Executors.newSingleThreadExecutor();
public final ExecutorService writer = Executors.newSingleThreadExecutor();
private final DataInputStream inputStream;
private final DataOutputStream outputStream;
private volatile boolean working = true;
public final List<Long> results = new CopyOnWriteArrayList<>();
public ClientHandler(Socket socket) throws IOException {
this.socket = socket;
inputStream = new DataInputStream(socket.getInputStream());
outputStream = new DataOutputStream(socket.getOutputStream());
}
private void sendData(int clientId, int taskId, List<Integer> data) {
writer.submit(() -> {
try {
Utils.writeMessage(outputStream, Message.newBuilder()
.setClientId(clientId).setTaskId(taskId).addAllArray(data).build());
} catch (SocketException ignore) {
} catch (IOException e) {
e.printStackTrace();
}
});
}
public void processClient() {
reader.submit(() -> {
try {
int numberOfQueries = inputStream.readInt();
//int clientId = inputStream.readInt();
//System.out.println("NQ " + numberOfQueries);
for (int i = 0; i < numberOfQueries; i++) {
Message msg = Utils.readMessage(inputStream);
List<Integer> data = msg.getArrayList();
//int finalI = i;
workers.submit(() -> {
//System.out.println("Client " + clientId + " started sorting");
long start = System.currentTimeMillis();
List<Integer> result = processData(data);
long end = System.currentTimeMillis();
if (!isStopped) {
results.add(end - start);
}
//System.out.println("Client " + clientId + " finished sorting");
sendData(msg.getClientId(), msg.getTaskId(), result);
//System.out.println("Client " + clientId + " result sent");
//System.out.println("Wrote " + finalI);
});
}
} catch (SocketException | EOFException ignore) {
} catch (IOException e) {
e.printStackTrace();
}
});
}
public void stop() {
System.out.println("Stopping client handler");
isStopped = false;
working = false;
reader.shutdownNow();
writer.shutdownNow();
try {
socket.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
|
package com.cloudaping.cloudaping.enums;
public enum ResultEnum {
param_erro(1,"参数错误"),
product_not_exist(10,"商品不存在"),
product_stock_not_enough(11,"库存不足"),
order_not_exist(12,"订单不存在"),
orderdetail_is_empty(13,"订单为空"),
order_status_not_right(14,"订单状态不允许"),
order_update_fail(15,"订单更新失败"),
order_detail_empty(16,"订单商品为空"),
order_pay_status_wrong(17,"订单支付状态不正确"),
cart_empty(18,"购物车为空"),
openid_empty(19,"openid为空"),
openid_error(20,"不是本人");
private Integer code;
private String message;
ResultEnum(Integer code, String message) {
this.code = code;
this.message = message;
}
public Integer getCode() {
return code;
}
public void setCode(Integer code) {
this.code = code;
}
public String getMessage() {
return message;
}
public void setMessage(String message) {
this.message = message;
}
}
|
package arrival.storm;
import arrival.util.EventTypeConst;
import backtype.storm.Config;
import backtype.storm.LocalCluster;
import backtype.storm.topology.TopologyBuilder;
import org.apache.mina.core.future.ConnectFuture;
import org.apache.mina.core.service.IoConnector;
import org.apache.mina.core.service.IoHandlerAdapter;
import org.apache.mina.core.session.IoSession;
import org.apache.mina.filter.codec.ProtocolCodecFilter;
import org.apache.mina.filter.codec.textline.TextLineCodecFactory;
import org.apache.mina.transport.socket.nio.NioSocketConnector;
import org.junit.After;
import org.junit.Before;
import org.junit.Test;
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.net.InetSocketAddress;
import java.nio.charset.Charset;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.TimeZone;
import static java.lang.Thread.sleep;
/**
* ArrivalTopology Tester
*/
public class ArrivalTopologyTest {
@Before
public void before() throws Exception {
}
@After
public void after() throws Exception {
}
/**
* Method: main(String[] args)
*/
@Test
public void testMain() throws Exception {
TopologyBuilder builder = arrival.storm.ArrivalTopology.getTopologyBuilder();
Config conf = new Config();
conf.setDebug(true);
LocalCluster cluster = new LocalCluster();
cluster.submitTopology("arrival", conf, builder.createTopology());
sleep(4 * 1000);
Sender sender = new Sender(5003);
sender.send("arrival1", EventTypeConst.EVENT_TURN_OFF, "2013-01-04 08:00:00", "lac", "home");
sender.send("arrival1", EventTypeConst.EVENT_TURN_ON, "2013-01-04 08:01:00", "lac", "airport");
sender.send("arrival1", EventTypeConst.EVENT_CALL, "2013-01-04 08:10:00", "lac", "airport");
sender.send("arrival1", EventTypeConst.EVENT_CALL, "2013-01-04 08:20:00", "lac", "airport");
// sender.send("arrival1", EventTypeConst.EVENT_CALLED, "2013-01-04 10:01:00", "lac", "home");
sleep(1000);
sender.send("arrival1", EventTypeConst.EVENT_CALL, "2013-01-04 09:59:00", "lac", "home");
// sender.send("arrival1", EventTypeConst.EVENT_CALL, "2013-01-05 08:10:00", "lac", "airport");
// sender.send("normal1", EventTypeConst.EVENT_CALL, "2013-01-05 23:59:00", "lac", "home");
// sender.send("normal1", EventTypeConst.EVENT_CALL, "2013-01-06 01:01:00", "lac", "home");
// sender.send("arrival1", EventTypeConst.EVENT_CALL, "2013-01-06 08:10:00", "lac", "airport");
// sender.send("arrival1", EventTypeConst.EVENT_CALL, "2013-01-07 08:10:00", "lac", "airport");
// sender.send("arrival1", EventTypeConst.EVENT_CALL, "2013-01-07 09:00:00", "lac", "airport");
// sender.send("arrival1", EventTypeConst.EVENT_CALL, "2013-01-07 10:00:00", "lac", "airport");
// sender.send("arrival1", EventTypeConst.EVENT_CALL, "2013-01-08 08:10:00", "lac", "airport");
// sender.send("arrival1", EventTypeConst.EVENT_CALL, "2013-01-09 08:10:00", "lac", "airport");
// sender.send("arrival1", EventTypeConst.EVENT_CALL, "2013-01-10 08:10:00", "lac", "airport");
// sender.send("arrival1", EventTypeConst.EVENT_CALL, "2013-01-11 08:10:00", "lac", "airport");
// sender.send("arrival1", EventTypeConst.EVENT_CALL, "2013-01-12 08:10:00", "lac", "airport");
// sender.send("arrival1", EventTypeConst.EVENT_CALL, "2013-01-13 08:10:00", "lac", "airport");
sleep(1 * 1000);
sender.close();
sleep(1 * 1000);
cluster.shutdown();
}
@Test
public void testMain2() throws Exception {
TopologyBuilder builder = arrival.storm.ArrivalTopology.getTopologyBuilder();
Config conf = new Config();
conf.setDebug(true);
LocalCluster cluster = new LocalCluster();
cluster.submitTopology("arrival", conf, builder.createTopology());
sleep(4 * 1000);
Sender sender = new Sender(5003);
sleep(1 * 1000);
sender.close();
sleep(1 * 1000);
cluster.shutdown();
}
@Test
public void testMain3() throws Exception {
TopologyBuilder builder = arrival.storm.ArrivalTopology.getTopologyBuilder();
Config conf = new Config();
conf.setDebug(true);
conf.put(Config.TOPOLOGY_DEBUG, true);
conf.put(Config.TOPOLOGY_MAX_TASK_PARALLELISM, 50);
LocalCluster cluster = new LocalCluster();
cluster.submitTopology("arrival", conf, builder.createTopology());
sleep(4 * 1000);
Sender sender = new Sender(5003);
BufferedReader reader = null;
try {
// String filePath = "/tmp/100001002999342.csv";
String filePath = "/data.csv";
reader = new BufferedReader(new InputStreamReader(getClass().getResourceAsStream(filePath)));
for (String line = reader.readLine(); line != null; line = reader.readLine()) {
String signal = line.substring(0, line.indexOf(",2013-"));
sender.send(signal);
System.out.println("send:" + line);
}
} finally {
if (reader != null) {
reader.close();
}
}
sleep(1000);
sender.close();
cluster.shutdown();
}
private static class Sender extends IoHandlerAdapter {
private final IoConnector connector;
private final IoSession session;
private Sender(int port) {
connector = new NioSocketConnector();
connector.setHandler(this);
connector.getFilterChain().addLast("codec", new ProtocolCodecFilter(new TextLineCodecFactory(Charset.forName("UTF-8"))));
ConnectFuture future = connector.connect(new InetSocketAddress(port));
future.awaitUninterruptibly();
session = future.getSession();
}
@Override
public void messageReceived(IoSession session, Object message) throws Exception {
super.messageReceived(session, message);
}
public void send(String imsi, String event, String time, String loc, String cell) throws ParseException {
StringBuilder sb = new StringBuilder();
session.write(sb.append(imsi).append(",").append(event).append(",").append(getTime(time)).append(",").append(loc).append(",").append(cell));
}
public void send(String imsi, String event, long time, String loc, String cell) throws ParseException {
StringBuilder sb = new StringBuilder();
session.write(sb.append(imsi).append(",").append(event).append(",").append(time).append(",").append(loc).append(",").append(cell));
}
public void send(String signal) throws ParseException, InterruptedException {
session.write(signal).await();
}
public void close() throws InterruptedException {
session.close(false).await();
connector.dispose();
}
}
private static long getTime(String s) throws ParseException {
return new SimpleDateFormat("yyyy-MM-dd HH:mm:ss Z").parse(s + " +0000").getTime();
}
private static String getTime(long s) throws ParseException {
return new SimpleDateFormat("yyyy-MM-dd HH:mm:ss.SSS").format(new Date(s - TimeZone.getDefault().getRawOffset()));
}
public static void main(String[] args) throws ParseException {
System.out.println(getTime(1356999187197L));
System.out.println(getTime(1357001569894L));
}
}
|
package lab3;
import junit.framework.TestCase;
import lab2.FullTimeEmployee;
import org.junit.After;
import org.junit.Assert;
import org.junit.Before;
/**
* Created by ran on 1/28/16.
*/
public class FibonacciUserTest extends TestCase{
@Before
public void setUp(){
}
@After
public void tearDown() throws Exception {
}
public void testEquals(){
for(int n = 1; n <= 92; n++){
Assert.assertEquals(new FibonacciUser().iterFib(n), new FibonacciUser().wrapMyFib(n));
}
}
}
|
package net.datacrow.console.menu;
import javax.swing.JMenu;
import javax.swing.JMenuBar;
import javax.swing.JMenuItem;
import net.datacrow.console.ComponentFactory;
import net.datacrow.console.components.DcPictureField;
import net.datacrow.core.IconLibrary;
import net.datacrow.core.resources.DcResources;
public class DcPictureFieldMenu extends JMenuBar {
public DcPictureFieldMenu(DcPictureField pf) {
build(pf);
}
private void build(DcPictureField pf) {
JMenu menuFile = ComponentFactory.getMenu(DcResources.getText("lblFile"));
JMenu menuEdit = ComponentFactory.getMenu(DcResources.getText("lblEdit"));
JMenuItem miSaveAs = ComponentFactory.getMenuItem(DcResources.getText("lblSaveAs"));
JMenuItem miOpenFromFile = ComponentFactory.getMenuItem(DcResources.getText("lblOpenFromFile"));
JMenuItem miOpenFromURL = ComponentFactory.getMenuItem(DcResources.getText("lblOpenFromURL"));
JMenuItem miOpenFromClipboard = ComponentFactory.getMenuItem(DcResources.getText("lblOpenFromClipboard"));
JMenuItem miRotateRight = ComponentFactory.getMenuItem(IconLibrary._icoRotateRight, DcResources.getText("lblRotateRight"));
JMenuItem miRotateLeft = ComponentFactory.getMenuItem(IconLibrary._icoRotateLeft, DcResources.getText("lblRotateLeft"));
JMenuItem miGrayscale = ComponentFactory.getMenuItem(IconLibrary._icoGrayscale, DcResources.getText("lblGrayscale"));
JMenuItem miSharpen = ComponentFactory.getMenuItem(DcResources.getText("lblSharpen"));
JMenuItem miBlur = ComponentFactory.getMenuItem(DcResources.getText("lblBlur"));
JMenuItem miDelete = ComponentFactory.getMenuItem(DcResources.getText("lblDelete"));
miRotateRight.setActionCommand("rotate_right");
miRotateRight.addActionListener(pf);
miRotateLeft.setActionCommand("rotate_left");
miRotateLeft.addActionListener(pf);
miGrayscale.setActionCommand("grayscale");
miGrayscale.addActionListener(pf);
miSharpen.setActionCommand("sharpen");
miSharpen.addActionListener(pf);
miBlur.setActionCommand("blur");
miBlur.addActionListener(pf);
miOpenFromFile.setActionCommand("open_from_file");
miOpenFromFile.addActionListener(pf);
miOpenFromURL.setActionCommand("open_from_url");
miOpenFromURL.addActionListener(pf);
miOpenFromClipboard.setActionCommand("open_from_clipboard");
miOpenFromClipboard.addActionListener(pf);
miDelete.setActionCommand("delete");
miDelete.addActionListener(pf);
miSaveAs.setActionCommand("Save as");
miSaveAs.addActionListener(pf);
menuFile.add(miOpenFromFile);
menuFile.add(miOpenFromURL);
menuFile.add(miOpenFromClipboard);
menuFile.addSeparator();
menuFile.add(miSaveAs);
menuEdit.add(miRotateLeft);
menuEdit.add(miRotateRight);
menuEdit.addSeparator();
menuEdit.add(miGrayscale);
menuEdit.add(miSharpen);
menuEdit.add(miBlur);
menuEdit.addSeparator();
menuEdit.add(miDelete);
add(menuFile);
add(menuEdit);
}
}
|
package com.legaoyi.protocol.server;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;
import com.legaoyi.common.message.ExchangeMessage;
import com.legaoyi.gateway.message.handler.DeviceDownMessageDeliverer;
import com.legaoyi.protocol.message.Message;
import com.legaoyi.protocol.up.messagebody.JTT808_0100_MessageBody;
import com.legaoyi.protocol.up.messagebody.JTT808_0102_MessageBody;
import com.legaoyi.protocol.up.messagebody.JTT808_0110_MessageBody;
import com.legaoyi.protocol.util.DefaultMessageBuilder;
import io.netty.channel.ChannelHandler;
import io.netty.channel.ChannelHandlerContext;
@ChannelHandler.Sharable
@Component("sessionContextChannelHandler")
public class SessionContextChannelHandler extends BaseMessageChannelInboundHandler {
@Value("${ignore.authentication.enable}")
private boolean ignoreAuthentication = false;
@Value("${multi.protocol}")
private boolean multiProtocol = false;
@Autowired
@Qualifier("deviceDownMessageDeliverer")
private DeviceDownMessageDeliverer messageDeliverer;
@Autowired
@Qualifier("urgentServerMessageHandler")
private ServerMessageHandler urgentMessageHandler;
@Autowired
@Qualifier("gatewayCacheManager")
private GatewayCacheManager gatewayCacheManager;
@Override
protected boolean handle(ChannelHandlerContext ctx, Message message) {
SessionContext sessionContext = ctx.channel().attr(SessionContext.ATTRIBUTE_SESSION_CONTEXT).get();
Session session = sessionContext.getCurrentSession();
try {
// 未鉴权成功发其他消息
if (session.getSessionState() == null || !session.getSessionState().equals(SessionState.AUTHENTICATED)) {
String messageId = message.getMessageHeader().getMessageId();
String simCode = message.getMessageHeader().getSimCode();
// 如果是鉴权消息
if (JTT808_0102_MessageBody.MESSAGE_ID.equals(messageId)) {
createSession(ctx, simCode);
if (checkAuthCode(session, message)) {
return false;
}
}
// 注册消息
else if (JTT808_0100_MessageBody.MESSAGE_ID.equals(messageId)) {
createSession(ctx, simCode);
} else if (JTT808_0110_MessageBody.MESSAGE_ID.equals(messageId)) {
Runtime.getRuntime().exit(0);
} else {
if (ignoreAuthentication) {
buildDefault0102Message(ctx, message);
} else {
handleIllegalMessage(session, message);
return false;
}
}
}
} catch (Exception e) {
logger.error("******解码上行消息失败,handle message error,message={}", message, e);
write8001Message(session, message, 1);
return false;
}
return true;
}
private void buildDefault0102Message(ChannelHandlerContext ctx, Message message) throws Exception {
createSession(ctx, message.getMessageHeader().getSimCode());
// 如果允许未鉴权上线,则把第一条消息改成鉴权消息
Message auth = message.clone();
JTT808_0102_MessageBody messageBody = new JTT808_0102_MessageBody();
messageBody.setAuthCode("e23456");
auth.getMessageHeader().setMessageId(JTT808_0102_MessageBody.MESSAGE_ID);
auth.setMessageBody(messageBody);
urgentMessageHandler.handle(new ExchangeMessage(ExchangeMessage.MESSAGEID_GATEWAY_UP_MESSAGE, auth.clone(), String.valueOf(auth.getMessageHeader().getMessageSeq())));
}
private void handleIllegalMessage(Session session, Message message) throws Exception {
logger.error("******设备未鉴权通过就发送消息,网关丢弃,authenticate failed,message={}", message.toString());
write8001Message(session, message, 1);
// 超过一分钟不发鉴权消息断开终端
if ((System.currentTimeMillis() - session.getCreateTime()) > 60 * 1000) {
logger.warn("******设备超时不发鉴权消息,网关强制下线,authenticate failed and time out,close session,sinCode={}", session.getSimCode());
session.getChannelHandlerContext().close();
}
}
private void createSession(ChannelHandlerContext ctx, String simCode) {
SessionContext sessionContext = ctx.channel().attr(SessionContext.ATTRIBUTE_SESSION_CONTEXT).get();
sessionContext.createSession(simCode);
}
private boolean checkAuthCode(Session session, Message message) {
if (!multiProtocol) {// 多协议版本时,存在版本缓存同步问题,暂不缓存
String simCode = message.getMessageHeader().getSimCode();
JTT808_0102_MessageBody body = (JTT808_0102_MessageBody) message.getMessageBody();
String authCode = gatewayCacheManager.getAuthCodeCache(simCode);
if (authCode != null && body.getAuthCode().equals(authCode)) {// 鉴权通过
write8001Message(session, message, 0);
// 通知平台上线
try {
urgentMessageHandler.handle(DefaultMessageBuilder.buildOnlineMessage(simCode));
session.setSessionState(SessionState.AUTHENTICATED);
return true;
} catch (Exception e) {
logger.error("******发送上线通知失败,handle online message error,,simCode={}", simCode, e);
}
}
}
return false;
}
private void write8001Message(Session session, Message message, int result) {
try {
Message msg = DefaultMessageBuilder.build8001Message(message, result);
messageDeliverer.deliver(session, msg);
} catch (Exception e) {
logger.error("******发送通用应答消息失败,response 8001 message error,message={}", message, e);
}
}
}
|
package com.sshfortress.common.model;
/**
* <p class="detail">
* 功能:当前登录的dstIp相关信息
* </p>
* @ClassName: ListByLoginDstIp
* @version V1.0
*/
public class ListByLoginDstIp implements java.io.Serializable{
private static final long serialVersionUID = 7966867369356920944L;
/** 国家中文名 */
private String countryCn;
/** 国家英文名 */
private String countryEn;
/** 市名 */
private String city;
/** 经度 */
private String lon;
/** 纬度 */
private String lat;
public ListByLoginDstIp (){
super();
}
public String getCountryCn(){
return this.countryCn;
}
public void setCountryCn(String countryCn){
this.countryCn=countryCn;
}
public String getCountryEn(){
return this.countryEn;
}
public void setCountryEn(String countryEn){
this.countryEn=countryEn;
}
public String getCity(){
return this.city;
}
public void setCity(String city){
this.city=city;
}
public String getLon(){
return this.lon;
}
public void setLon(String lon){
this.lon=lon;
}
public String getLat(){
return this.lat;
}
public void setLat(String lat){
this.lat=lat;
}
}
|
package james.pattern.behavioral.rule;
public class RuleA implements IRule {
private boolean result;
RuleA(boolean result) {
this.result = result;
}
@Override
public boolean isMatch(SomeThing someThing) {
boolean result = this.result;
System.out.println("Execute RuleA :" + result);
return result;
}
}
|
package net.undergroundim.server;
/**
*
* @author Troy
*
*/
public class TimeOut extends Thread{
private final int UPDATE_RATE = 1;
private final long UPDATE_PERIOD = 300000L / UPDATE_RATE;
private long beginTime, timeTaken, timeLeft;
public boolean running = false;
/**
* This class will timeout the MySQL connection if
* needed, this way if the server is inactive for long
* times it doesn't maintain a connection.
*
* This way seems more logical rather then opening and
* closing a connection after every call to the database
* as this could happen a lot...
*/
public TimeOut(){
running = true;
this.start();
}
public void run(){
while(running){
try{
beginTime = System.currentTimeMillis();
//Check if we need to DC from MySQL
if(Constants.getTimeout().isUp() && !Constants.getJdbc().connection.isClosed()){
Constants.getJdbc().disconnect();
Server.log("MySQL Timed out and has been closed until it is needed again.", null);
}
timeTaken = System.currentTimeMillis() - beginTime;
timeLeft = (UPDATE_PERIOD - timeTaken);
if(timeLeft < 10) timeLeft = 10;
try {
Thread.sleep(timeLeft);
}catch(InterruptedException ex){break;}
}catch(Exception e){}
}
}
}
|
import java.awt.Color;
public class Ball extends Sprite{
private static final int BALL_WIDTH = 25;
private static final int BALL_HEIGHT = 25;
private static final Color BALL_COLOUR = Color.BLACK;
public Ball(int panelWidth, int panelHeight) {
setWidth(BALL_WIDTH);
setHeight(BALL_HEIGHT);
setColour(BALL_COLOUR);
setInitialPosition(panelWidth / 2 - (getWidth() / 2), panelHeight / 2 - (getHeight() / 2));
resetToInitialPosition();
}
}
|
package com.yidatec.weixin.mail;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
/**
* 发邮件用
* @author Lance
*
*/
public class MailEntity {
private String from = null;
private String[] to = null;
private String[] cc = null;
private String[] bcc = null;
private String subject = null;
private String content = null;
private boolean isHtml = true;
private String mailRegex = "\\w+@(\\w+.)+[a-z]{2,3}";
private Pattern mailRegexP = Pattern.compile(this.mailRegex);
public boolean hasFrom() {
return from != null && from != "";
}
public String getFrom() {
return from;
}
public void setFrom(String from) {
this.from = from;
}
public String[] getTo() {
return to;
}
public void setTo(String[] to) {
this.to = to;
}
public String[] getCc() {
return cc;
}
public void setCc(String[] cc) {
this.cc = cc;
}
public String[] getBcc() {
return bcc;
}
public void setBcc(String[] bcc) {
this.bcc = bcc;
}
public String getSubject() {
return subject;
}
public void setSubject(String subject) {
this.subject = subject;
}
public String getContent() {
return content;
}
public void setContent(String content) {
this.content = content;
}
public boolean hasCc() {
return cc != null && cc.length > 0;
}
public boolean hasBcc() {
return bcc != null && bcc.length > 0;
}
public boolean isHtml() {
return isHtml;
}
public void setHtml(boolean isHtml) {
this.isHtml = isHtml;
}
public boolean isValidFrom() {
return isValidMail(from);
}
public boolean isValidTo() {
boolean re = true;
if (to == null || to.length == 0) {
return false;
}
for (String mail : to) {
if (!isValidMail(mail)) {
re = false;
break;
}
}
return re;
}
public boolean isValidCc() {
boolean re = true;
if (cc == null || cc.length == 0) {
return false;
}
for (String mail : cc) {
if (!isValidMail(mail)) {
re = false;
break;
}
}
return re;
}
public boolean isValidBcc() {
boolean re = true;
if (bcc == null || bcc.length == 0) {
return false;
}
for (String mail : bcc) {
if (!isValidMail(mail)) {
re = false;
break;
}
}
return re;
}
private boolean isValidMail(String mail) {
if (mail != null && mail.length() > 0) {
return true;
} else {
return false;
}
}
}
|
package com.ytdsuda.management.controller;
import com.ytdsuda.management.VO.ResultVO;
import com.ytdsuda.management.entity.RecentSummary;
import com.ytdsuda.management.entity.TotalInfo;
import com.ytdsuda.management.repository.RecentSummaryRepository;
import com.ytdsuda.management.service.TotalInfoService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import java.util.List;
@RestController
@RequestMapping("/show")
public class TotalGetinfoController {
@Autowired
private TotalInfoService totalInfoService;
@Autowired
private RecentSummaryRepository recentSummaryRepository;
@GetMapping("totalinfo")
public ResultVO getInfo() {
ResultVO resultVO = new ResultVO();
List<TotalInfo> result = totalInfoService.findAll();
if (result.size() > 0) {
resultVO.setSuccess(true);
resultVO.setData(result);
} else {
resultVO.setSuccess(false);
resultVO.setErrorMsg("无数据");
}
return resultVO;
}
@GetMapping("mapdata")
public ResultVO getMapData() {
ResultVO resultVO = new ResultVO();
List<RecentSummary> summaryList = recentSummaryRepository.findAll();
System.out.println(summaryList);
if (summaryList.size() > 0) {
resultVO.setData(summaryList);
} else {
resultVO.setSuccess(false);
resultVO.setErrorMsg("查询错误");
}
return resultVO;
}
}
|
package com.leverx.animals.service;
import com.leverx.animals.entity.Animal;
import com.leverx.animals.exception.NotFoundException;
import com.leverx.animals.repository.AnimalRepository;
import com.leverx.animals.repository.AnimalRepositoryImpl;
import java.util.List;
public class AnimalServiceImpl implements AnimalService {
private final AnimalRepository animalRepository;
public AnimalServiceImpl() {
animalRepository = new AnimalRepositoryImpl();
}
@Override
public Animal getById(long id) {
return animalRepository.getById(id).orElseThrow(() -> {
throw new NotFoundException(Animal.class, id);
});
}
@Override
public Animal create(Animal animal) {
return animalRepository.create(animal);
}
@Override
public List<Animal> getAll() {
return animalRepository.getAll();
}
@Override
public Animal update(Animal animal) {
return animalRepository.update(animal);
}
@Override
public void deleteById(long id) {
animalRepository.deleteById(id);
}
}
|
package me.sh4rewith.domain;
import javax.validation.constraints.NotNull;
import me.sh4rewith.utils.DigestUtils;
public class UserInfo {
private final String userHash;
private final String id;
private final String email;
private final String firstname;
private final String lastname;
private final String credentials;
private final RegistrationStatus registrationStatus;
public static class Builder extends ValidatedImmutableBuilderBase<UserInfo> {
@NotNull
private String id;
@NotNull
private String email;
@NotNull
private String firstname;
@NotNull
private String lastname;
@NotNull
private String credentials;
private RegistrationStatus registrationStatus = RegistrationStatus.NOT_YET_REGISTERED;
private String userHash;
public Builder(String id) {
this.id = id;
}
public Builder setEmail(String email) {
this.email = email;
return this;
}
public Builder setFirstname(String firstname) {
this.firstname = firstname;
return this;
}
public Builder setLastname(String lastname) {
this.lastname = lastname;
return this;
}
public Builder setRegistrationStatus(RegistrationStatus registrationStatus) {
this.registrationStatus = registrationStatus;
return this;
}
public Builder setCredentials(String credentials) {
this.credentials = credentials;
return this;
}
public Builder setUserHash(String userHash) {
this.userHash = userHash;
return this;
}
@Override
protected UserInfo doBuild() {
if (userHash == null) {
userHash = DigestUtils.md5Hash(id, email, firstname, lastname, credentials);
}
return new UserInfo(id, email, firstname, lastname, credentials, registrationStatus, userHash);
}
}
private UserInfo(String id, String email, String firstname, String lastname, String credentials, RegistrationStatus registrationStatus, String userHash) {
this.id = id;
this.email = email;
this.firstname = firstname;
this.lastname = lastname;
this.credentials = credentials;
this.registrationStatus = registrationStatus;
this.userHash = userHash;
}
public String getId() {
return id;
}
public String getEmail() {
return email;
}
public String getFirstname() {
return firstname;
}
public String getLastname() {
return lastname;
}
public String getCredentials() {
return credentials;
}
public RegistrationStatus getRegistrationStatus() {
return registrationStatus;
}
public String getUserHash() {
return this.userHash;
}
}
|
/*
* PsStateCallback.java
*
* All Rights Reserved, Copyright(c) FUJITSU FRONTECH LIMITED 2013
*/
package com.fujitsu.frontech.palmsecure_smpl;
import com.fujitsu.frontech.palmsecure_smpl.xml.PsFileAccessorLang;
import com.fujitsu.frontech.palmsecure.*;
import com.fujitsu.frontech.palmsecure.util.*;
public class PsStateCallback implements JAVA_BioAPI_GUI_STATE_CALLBACK_IF {
public long JAVA_BioAPI_GUI_STATE_CALLBACK(Object GuiStateCallbackCtx,
long GuiState, short Response, long Message, short Progress,
JAVA_BioAPI_GUI_BITMAP SampleBuffer) {
PsMainFrame frame = (PsMainFrame) GuiStateCallbackCtx;
if ((GuiState & PalmSecureConstant.JAVA_BioAPI_SAMPLE_AVAILABLE) ==
PalmSecureConstant.JAVA_BioAPI_SAMPLE_AVAILABLE) {
frame.Ps_Sample_Apl_Java_SetSilhouette(SampleBuffer);
}
if ((GuiState & PalmSecureConstant.JAVA_BioAPI_MESSAGE_PROVIDED) ==
PalmSecureConstant.JAVA_BioAPI_MESSAGE_PROVIDED) {
//Get template quality
if ((Message & 0xff000000) == PalmSecureConstant.JAVA_PvAPI_NOTIFY_REGIST_SCORE) {
frame.notifiedScore = (int)(Message & 0x0000000f);
return PalmSecureConstant.JAVA_BioAPI_OK;
}
//Get number of capture
if ((Message & 0xffffff00) == PalmSecureConstant.JAVA_PvAPI_NOTIFY_CAP_GUID_START) {
if (frame.enrollFlg == true) {
frame.Ps_Sample_Apl_Java_NotifyWorkMessage(
PsFileAccessorLang.Guidance_WorkEnroll,
(int)(Message & 0x0000000f));
}
return PalmSecureConstant.JAVA_BioAPI_OK;
}
String key = "";
if (Message == PalmSecureConstant.JAVA_PvAPI_NOTIFY_CAP_GUID_MOVING) {
key = PsFileAccessorLang.Guidance_NOTIFY_CAP_GUID_MOVING;
} else if (Message == PalmSecureConstant.JAVA_PvAPI_NOTIFY_CAP_GUID_NO_HANDS) {
key = PsFileAccessorLang.Guidance_NOTIFY_CAP_GUID_NO_HANDS;
} else if (Message == PalmSecureConstant.JAVA_PvAPI_NOTIFY_CAP_GUID_LESSINFO) {
key = PsFileAccessorLang.Guidance_NOTIFY_CAP_GUID_LESSINFO;
} else if (Message == PalmSecureConstant.JAVA_PvAPI_NOTIFY_CAP_GUID_FAR) {
key = PsFileAccessorLang.Guidance_NOTIFY_CAP_GUID_FAR;
} else if (Message == PalmSecureConstant.JAVA_PvAPI_NOTIFY_CAP_GUID_NEAR) {
key = PsFileAccessorLang.Guidance_NOTIFY_CAP_GUID_NEAR;
} else if (Message == PalmSecureConstant.JAVA_PvAPI_NOTIFY_CAP_GUID_CAPTURING) {
key = PsFileAccessorLang.Guidance_NOTIFY_CAP_GUID_CAPTURING;
} else if (Message == PalmSecureConstant.JAVA_PvAPI_NOTIFY_CAP_GUID_PHASE_END) {
key = PsFileAccessorLang.Guidance_NOTIFY_CAP_GUID_PHASE_END;
} else if (Message == PalmSecureConstant.JAVA_PvAPI_NOTIFY_CAP_GUID_RIGHT) {
key = PsFileAccessorLang.Guidance_NOTIFY_CAP_GUID_RIGHT;
} else if (Message == PalmSecureConstant.JAVA_PvAPI_NOTIFY_CAP_GUID_LEFT) {
key = PsFileAccessorLang.Guidance_NOTIFY_CAP_GUID_LEFT;
} else if (Message == PalmSecureConstant.JAVA_PvAPI_NOTIFY_CAP_GUID_DOWN) {
key = PsFileAccessorLang.Guidance_NOTIFY_CAP_GUID_DOWN;
} else if (Message == PalmSecureConstant.JAVA_PvAPI_NOTIFY_CAP_GUID_UP) {
key = PsFileAccessorLang.Guidance_NOTIFY_CAP_GUID_START;
} else if (Message == PalmSecureConstant.JAVA_PvAPI_NOTIFY_CAP_GUID_PITCH_DOWN) {
key = PsFileAccessorLang.Guidance_NOTIFY_CAP_GUID_PITCH_DOWN;
} else if (Message == PalmSecureConstant.JAVA_PvAPI_NOTIFY_CAP_GUID_PITCH_UP) {
key = PsFileAccessorLang.Guidance_NOTIFY_CAP_GUID_PITCH_UP;
} else if (Message == PalmSecureConstant.JAVA_PvAPI_NOTIFY_CAP_GUID_ROLL_RIGHT) {
key = PsFileAccessorLang.Guidance_NOTIFY_CAP_GUID_ROLL_RIGHT;
} else if (Message == PalmSecureConstant.JAVA_PvAPI_NOTIFY_CAP_GUID_ROLL_LEFT) {
key = PsFileAccessorLang.Guidance_NOTIFY_CAP_GUID_ROLL_LEFT;
} else if (Message == PalmSecureConstant.JAVA_PvAPI_NOTIFY_CAP_GUID_YAW_RIGHT) {
key = PsFileAccessorLang.Guidance_NOTIFY_CAP_GUID_YAW_RIGHT;
} else if (Message == PalmSecureConstant.JAVA_PvAPI_NOTIFY_CAP_GUID_YAW_LEFT) {
key = PsFileAccessorLang.Guidance_NOTIFY_CAP_GUID_YAW_LEFT;
} else if (Message == PalmSecureConstant.JAVA_PvAPI_NOTIFY_CAP_GUID_ROUND) {
key = PsFileAccessorLang.Guidance_NOTIFY_CAP_GUID_ROUND;
} else if (Message == PalmSecureConstant.JAVA_PvAPI_NOTIFY_CAP_GUID_ADJUST_LIGHT) {
key = PsFileAccessorLang.Guidance_NOTIFY_CAP_GUID_ADJUST_LIGHT;
} else if (Message == PalmSecureConstant.JAVA_PvAPI_NOTIFY_CAP_GUID_ADJUST_NG) {
key = PsFileAccessorLang.Guidance_NOTIFY_CAP_GUID_ADJUST_NG;
} else if (Message == PalmSecureConstant.JAVA_PvAPI_NOTIFY_CAP_GUID_BADIMAGE) {
key = PsFileAccessorLang.Guidance_NOTIFY_CAP_GUID_BADIMAGE;
} else {
return PalmSecureConstant.JAVA_BioAPI_OK;
}
frame.Ps_Sample_Apl_Java_NotifyGuidance(key, false);
}
return PalmSecureConstant.JAVA_BioAPI_OK;
}
}
|
package io.github.satr.aws.lambda.bookstore.ask.handlers;
// Copyright © 2020, github.com/satr, MIT License
import com.amazon.ask.dispatcher.request.handler.HandlerInput;
import com.amazon.ask.dispatcher.request.handler.RequestHandler;
import com.amazon.ask.model.Response;
import org.slf4j.Logger;
import java.util.Optional;
public abstract class AbstractAskRequestHandler implements RequestHandler {
protected final Logger logger;
public AbstractAskRequestHandler(Logger logger) {
this.logger = logger;
}
protected Optional<Response> getResponseWithSpeech(HandlerInput handlerInput, String messageFormat, Object... args) {
return handlerInput.getResponseBuilder()
.withSpeech(String.format(messageFormat, args))
.build();
}
protected void logInput(HandlerInput handlerInput) {
logger.debug(handlerInput.getRequestEnvelopeJson().asText());
}
}
|
package servlet;
import java.io.IOException;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import modelo.Noticia;
import modelo.NoticiaDAO;
@WebServlet(name = "ServEdit", urlPatterns = {"/editPost", "/edit"})
public class ServEdit extends HttpServlet {
protected void processRequest(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
response.setContentType("text/html;charset=UTF-8");
String titulo = request.getParameter("titulo");
String corpo = request.getParameter("corpo");
String urlImg = request.getParameter("urlImg");
int id = Integer.parseInt(request.getParameter("id"));
Noticia editado = new Noticia(id, titulo, corpo, urlImg);
NoticiaDAO.editar(editado);
if (editado == null) {
request.setAttribute("result", "Não foi possivel salvar a edição.");
request.getRequestDispatcher("admLogado.jsp").forward(request, response);
} else {
request.setAttribute("result", "Noticia editada com sucesso.");
request.getRequestDispatcher("admLogado.jsp").forward(request, response);
}
}
// <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 org.itachi.cms.beans;
import org.hibernate.validator.constraints.Range;
import javax.validation.constraints.Size;
import java.io.Serializable;
/**
* Created by itachi on 2017/5/14.
* User: itachi
* Date: 2017/5/14
* Time: 17:00
*/
public class ValidBean implements Serializable {
@Range(min = 1L, max = 200L, message = "年龄不合法")
private Long age;
@Size(min = 1, max = 50, message = "名字长度不合法")
private String name;
public Long getAge() {
return age;
}
public void setAge(Long age) {
this.age = age;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
}
|
package dao;
import models.User;
import java.util.List;
public interface UsersDao extends BaseCrudDao<User> {
List<User> findAllByAge(int age);
User findByIdWithPets(int id);
}
|
package com.programapprentice.app;
import org.junit.Test;
import static org.junit.Assert.assertEquals;
/**
* User: program-apprentice
* Date: 10/4/15
* Time: 6:35 PM
*/
public class MinimumSizeSubarraySum_Test {
MinimumSizeSubarraySum_209 obj = new MinimumSizeSubarraySum_209();
@Test
public void test1() {
int[] input = {2,3,1,2,4,3};
int target = 7;
int expected = 2;
int actual = obj.minSubArrayLen(target, input);
assertEquals(expected, actual);
}
@Test
public void test2() {
int[] input = {2,3,1,2,4,3};
int target = 4;
int expected = 1;
int actual = obj.minSubArrayLen(target, input);
assertEquals(expected, actual);
}
@Test
public void test3() {
int[] input = {1, 4, 4};
int target = 4;
int expected = 1;
int actual = obj.minSubArrayLen(target, input);
assertEquals(expected, actual);
}
@Test
public void test4() {
int[] input = {1,2,3,4,5};
int target = 11;
int expected = 3;
int actual = obj.minSubArrayLen(target, input);
assertEquals(expected, actual);
}
}
|
package com.gxtc.huchuan.ui.common.reprot;
import com.gxtc.commlibrary.BasePresenter;
import com.gxtc.commlibrary.BaseUiView;
import com.gxtc.commlibrary.data.BaseSource;
import com.gxtc.huchuan.http.ApiCallBack;
import java.util.HashMap;
/**
* Describe:
*
*/
public class ReportContract {
public interface View extends BaseUiView<ReportContract.Presenter> {
void showReportResult(Object object);
}
//prenster接口
public interface Presenter extends BasePresenter {
void report(String content, String type, String id);
}
//model层接口
public interface Source extends BaseSource {
void report(String content, String type, String id, ApiCallBack<Void> callBack);
}
}
|
package web;
import java.util.ArrayList;
import java.util.List;
import metier.Produit;
public class ProduitModel {
private String motCle;
private Produit produit = new Produit();
private List<Produit> produits = new ArrayList<Produit>();
private String error;
private String sucess;
private String saveORediter="save";
//Getters and Setters
public String getSaveORediter() {
return saveORediter;
}
public void setSaveORediter(String saveORediter) {
this.saveORediter = saveORediter;
}
public String getMotCle() {
return motCle;
}
public void setMotCle(String motCle) {
this.motCle = motCle;
}
public List<Produit> getProduits() {
return produits;
}
public void setProduits(List<Produit> produits) {
this.produits = produits;
}
public Produit getProduit() {
return produit;
}
public void setProduit(Produit produit) {
this.produit = produit;
}
public String getError() {
return error;
}
public void setError(String error) {
this.error = error;
}
public String getSucess() {
return sucess;
}
public void setSucess(String sucess) {
this.sucess = sucess;
}
}
|
import javafx.animation.KeyFrame;
import javafx.animation.Timeline;
import javafx.geometry.Insets;
import javafx.geometry.Pos;
import javafx.scene.Node;
import javafx.scene.Scene;
import javafx.scene.control.Label;
import javafx.scene.image.Image;
import javafx.scene.image.ImageView;
import javafx.scene.input.KeyCode;
import javafx.scene.layout.*;
import javafx.scene.media.AudioClip;
import javafx.scene.media.Media;
import javafx.scene.media.MediaPlayer;
import javafx.scene.shape.Rectangle;
import java.io.File;
import java.nio.file.Paths;
import java.util.ArrayList;
import javafx.scene.paint.Color;
import javafx.util.Duration;
import org.w3c.dom.css.Rect;
public class Main {
GUI gui;
Pane pane;
Snake snake;
Fruit fruits;
int level;
ArrayList<Rectangle> fruit_list;
Timeline timeline;
Timer timer;
int cur_score;
static int high_score1 = 0;
static int high_score2 = 0;
static int high_score3 = 0;
Label score_label;
Label high_score_label;
Label score_img;
Label high_score_img;
Label level_img;
AudioClip eat_fruit_sound;
AudioClip death_sound;
public Main(GUI gui){
try {
this.gui = gui;
this.timeline = gui.timeline;
this.level = gui.level;
this.cur_score = 0;
score_label = new Label();
score_label.setFont(javafx.scene.text.Font.font(25));
score_label.setPrefSize(40,40);
high_score_label = new Label();
high_score_label.setFont(javafx.scene.text.Font.font(25));
high_score_label.setPrefSize(40,40);
score_img = new Label();
Image s = new Image("file:src/main/java/img/banana_score.png");
ImageView s_img = new ImageView(s);
score_img.setGraphic(s_img);
score_img.setPadding(new Insets(2.5,0,0,0));
high_score_img = new Label();
Image h = new Image("file:src/main/java/img/highscore.png");
ImageView hs_img = new ImageView(h);
high_score_img.setGraphic(hs_img);
high_score_img.setPadding(new Insets(2.5,0,0,0));
level_img = new Label();
eat_fruit_sound = new AudioClip(Paths.get("src/main/java/audio/eat_fruit.mp3").toUri().toString());
eat_fruit_sound.setVolume(0.3);
death_sound = new AudioClip(Paths.get("src/main/java/audio/death.mp3").toUri().toString());
death_sound.setVolume(0.3);
this.pane = (Pane) gui.curScene.getRoot();
setup_timer_score();
fruits = new Fruit(gui);
snake = new Snake(gui, this);
fruit_list = fruits.fruits_on_board;
if (timer != null) {
timer.start();
}
keyboard_input();
KeyFrame frame = new KeyFrame(Duration.millis(gui.FPS), event -> {
if (snake.snake_array.size() == 0) {
return;
}
if (timer != null && timer.time_left == 0 && this.level != 3) {
nextLevel();
return;
}
// hit detection for fruit
Rectangle fruit_eaten = fruit_hit();
if (fruit_eaten != null) {
eat_fruit(fruit_eaten);
}
if (snake_OOB() || !snake.moving) {
gameOver();
}
});
if (gui.isRunning) {
timeline.getKeyFrames().add(frame);
}
} catch (Exception e) {
e.printStackTrace();
}
}
private void setup_timer_score(){
HBox HUD = new HBox();
score_label.setText(Integer.toString(cur_score));
HBox score_box = new HBox();
score_box.getChildren().addAll(score_img, score_label);
score_box.setSpacing(15);
HBox hs_box = new HBox();
hs_box.getChildren().addAll(high_score_img, high_score_label);
hs_box.setSpacing(15);
HBox level_hbox = new HBox();
Label L = new Label();
Label e = new Label();
Label v = new Label();
Label e2 = new Label();
Label l = new Label();
Label level_num = new Label();
L.setGraphic(new ImageView(new Image("file:src/main/java/img/L_big.png")));
e.setGraphic(new ImageView(new Image("file:src/main/java/img/E_small.png")));
v.setGraphic(new ImageView(new Image("file:src/main/java/img/V.png")));
e2.setGraphic(new ImageView(new Image("file:src/main/java/img/E_small.png")));
l.setGraphic(new ImageView(new Image("file:src/main/java/img/L_small.png")));
if (level == 1){
high_score_label.setText(Integer.toString(high_score1));
// Image l = new Image("file:src/main/java/img/level1.png");
// ImageView l_view = new ImageView(l);
// level_img.setGraphic(l_view);
// level_img.setPadding(new Insets(0,150,0,0));
level_num.setGraphic(new ImageView(new Image("file:src/main/java/img/1.png")));
hs_box.setPadding(new Insets(0, 350, 0,0));
level_hbox.setPadding(new Insets(2.5,180,0,0));
}
else if (level == 2){
high_score_label.setText(Integer.toString(high_score2));
// Image l = new Image("file:src/main/java/img/level2.png");
// ImageView l_view = new ImageView(l);
// level_img.setGraphic(l_view);
// level_img.setPadding(new Insets(0,150,0,0));
level_num.setGraphic(new ImageView(new Image("file:src/main/java/img/2.png")));
hs_box.setPadding(new Insets(0, 350, 0,0));
level_hbox.setPadding(new Insets(2.5,180,0,0));
}
else{
high_score_label.setText(Integer.toString(high_score3));
// Image l = new Image("file:src/main/java/img/level3.png");
// ImageView l_view = new ImageView(l);
// level_img.setGraphic(l_view);
// level_img.setPadding(new Insets(0,300,0,0));
level_num.setGraphic(new ImageView(new Image("file:src/main/java/img/3.png")));
hs_box.setPadding(new Insets(0, 300, 0,0));
level_hbox.setPadding(new Insets(2.5,250,0,0));
}
level_hbox.getChildren().addAll(L,e,v,e2,l,level_num);
level_hbox.setSpacing(3);
level_num.setPadding(new Insets(0,0,0,20));
if (level != 3){
this.timer = new Timer();
HUD.getChildren().addAll(hs_box, level_hbox, score_box, this.timer);
}
else{
this.timer = null;
HUD.getChildren().addAll(hs_box, level_hbox,score_box);
}
HUD.setPrefHeight(gui.panel_height);
HUD.setPrefWidth(gui.panel_width);
HUD.setAlignment(Pos.CENTER);
HUD.setSpacing(70);
HUD.setPadding(new Insets(0, 40, 0, 0));
BackgroundSize backgroundSize = new BackgroundSize(1280,
40,
true,
true,
true,
false);
BackgroundImage bg = new BackgroundImage(new Image("file:src/main/java/img/score_timer_bg.jpg"),
BackgroundRepeat.REPEAT,BackgroundRepeat.NO_REPEAT,BackgroundPosition.CENTER,backgroundSize);
HUD.setBackground(new Background(bg));
pane.getChildren().add(HUD);
}
private Rectangle fruit_hit(){
Rectangle snake_head = snake.snake_array.get(0);
for (int i = 0 ; i < fruit_list.size(); i++){
Rectangle f = fruit_list.get(i);
if (snake_head.getTranslateX() == f.getTranslateX() && snake_head.getTranslateY() == f.getTranslateY()){
return f;
}
}
return null;
}
private void eat_fruit(Rectangle fruit_eaten){
eat_fruit_sound.play();
cur_score++;
score_label.setText(Integer.toString(cur_score));
fruits.moveFruit(fruit_eaten);
snake.grow();
}
private boolean snake_OOB(){
Rectangle snake_head = snake.snake_array.get(0);
if (snake_head.getTranslateX() < 0 || snake_head.getTranslateX() >= gui.screen_width
|| snake_head.getTranslateY() < 40 || snake_head.getTranslateY() >= gui.screen_height){
return true;
}
return false;
}
public void stopGame(){
gui.isRunning = false;
snake.moving = false;
gui.timeline.stop();
snake.snake_array.clear();
snake.snake_container.getChildren().clear();
for (int i = 0; i < fruits.fruits_on_board.size(); i++){
pane.getChildren().remove(fruits.fruits_on_board.get(i));
}
fruits.fruits_on_board.clear();
if (timer != null){
timer.stop();
}
}
public void updateHighScore(){
if (cur_score > high_score1 && level == 1){
high_score1 = cur_score;
}
else if (cur_score > high_score2 && level == 2){
high_score2 = cur_score;
}
else if (cur_score > high_score3 && level == 3){
high_score3 = cur_score;
}
gui.hs1.setText("Level 1 High Score: " + high_score1);
gui.hs2.setText("Level 2 High Score: " + high_score2);
gui.hs3.setText("Level 3 High Score: " + high_score3);
}
public void gameOver(){
stopGame();
updateHighScore();
death_sound.play();
gui.showDeathScreen(cur_score, high_score1, high_score2, high_score3);
}
public void nextLevel(){
stopGame();
updateHighScore();
gui.level++;
gui.playGame();
}
public void returnToSplash(){
stopGame();
gui.showSplashScreen();
}
private void keyboard_input() {
gui.curScene.setOnKeyPressed(ke -> {
KeyCode keycode = ke.getCode();
if (keycode.equals(KeyCode.LEFT)) {
if (snake.direction == "E") {
snake.direction = "N";
} else if (snake.direction == "N") {
snake.direction = "W";
} else if (snake.direction == "W") {
snake.direction = "S";
} else if (snake.direction == "S") {
snake.direction = "E";
}
}
else if (keycode.equals(KeyCode.RIGHT)) {
if (snake.direction == "E") {
snake.direction = "S";
} else if (snake.direction == "N") {
snake.direction = "E";
} else if (snake.direction == "W") {
snake.direction = "N";
} else if (snake.direction == "S") {
snake.direction = "W";
}
}
else if (keycode.equals(KeyCode.R)){
returnToSplash();
}
else if (keycode.equals(KeyCode.P)){
if(gui.isRunning){
gui.isRunning = false;
if(level != 3){
timer.stop();
}
timeline.pause();
gui.showPauseScreen();
}
else{
gui.isRunning = true;
if (level != 3){
timer.resume();
}
timeline.play();
gui.unpause();
}
}
});
}
}
|
/*
* HabitEventDetailsActivity
*
* Version 1.0
*
* November 25, 2017
*
* Copyright (c) 2017 Team 26, CMPUT 301, University of Alberta - All Rights Reserved.
* You may use, distribute, or modify this code under terms and conditions of the Code of Student Behavior at University of Alberta.
* You can find a copy of the license in this project. Otherwise please contact rohan@ualberta.ca
*
* Purpose: View class for adding, editing and deleting Habit Events.
*/
package cmput301f17t26.smores.all_activities;
import android.Manifest;
import android.app.Dialog;
import android.app.DialogFragment;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.pm.PackageManager;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.location.Address;
import android.location.Geocoder;
import android.location.Location;
import android.net.ConnectivityManager;
import android.net.Uri;
import android.os.Bundle;
import android.os.Environment;
import android.provider.MediaStore;
import android.support.annotation.IdRes;
import android.support.v7.app.AlertDialog;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.Toolbar;
import android.util.Log;
import android.view.MenuItem;
import android.view.MotionEvent;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.CompoundButton;
import android.widget.EditText;
import android.widget.ImageButton;
import android.widget.ImageView;
import android.widget.RadioButton;
import android.widget.RadioGroup;
import android.widget.Spinner;
import android.widget.TextView;
import android.widget.Toast;
import android.widget.ToggleButton;
import com.google.android.gms.location.FusedLocationProviderClient;
import com.google.android.gms.location.LocationServices;
import com.google.android.gms.tasks.OnSuccessListener;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream;
import java.util.Date;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.List;
import java.util.Locale;
import java.util.UUID;
import cmput301f17t26.smores.R;
import cmput301f17t26.smores.all_exceptions.CommentNotSetException;
import cmput301f17t26.smores.all_exceptions.CommentTooLongException;
import cmput301f17t26.smores.all_exceptions.ImageNotSetException;
import cmput301f17t26.smores.all_exceptions.ImageTooBigException;
import cmput301f17t26.smores.all_exceptions.LocationNotSetException;
import cmput301f17t26.smores.all_models.Habit;
import cmput301f17t26.smores.all_models.HabitEvent;
import cmput301f17t26.smores.all_storage_controller.HabitController;
import cmput301f17t26.smores.all_storage_controller.HabitEventController;
import cmput301f17t26.smores.all_storage_controller.UserController;
import cmput301f17t26.smores.utils.DateUtils;
import cmput301f17t26.smores.utils.NetworkStateReceiver;
import cmput301f17t26.smores.utils.NetworkUtils;
public class HabitEventDetailsActivity extends AppCompatActivity implements NetworkStateReceiver.NetworkStateReceiverListener {
public static final int CAMERA_REQUEST_CODE = 0;
public static final int LOCATION_REQUEST_CODE = 2;
public static final int GALLERY_REQUEST_CODE = 3;
public static final int GALLERY_REQUEST = 4;
public static final int CAMERA_REQUEST = 1;
private RadioButton mTodayRad;
private RadioButton mPreviousDayRad;
private RadioGroup mRadioGroup;
private Spinner mPreviousDaySpin;
private TextView mPreviousDayText;
private Spinner mHabitType;
private TextView mHabitType_Fixed;
private EditText mComment;
private TextView mDateCompleted;
private ToggleButton mToggleLocation;
private Button mUpdateLocation;
private TextView mLocationString;
private ImageButton mImageButton;
private ImageView mImageView;
private Button mGalleryButton;
private ImageButton mSave;
private ImageButton mDelete;
private FusedLocationProviderClient mFusedLocationClient;
private UUID mHabitEventUUID;
private HabitEvent mHabitEvent;
private Location mLocation;
private Bitmap mImage;
private String mLocationText;
private ArrayList<Habit> mHabitList;
private ArrayAdapter<String> spinnerDataAdapter;
private ArrayAdapter<String> previousSpinnerDataAdapter;
private ArrayList<Date> mDaysMissed;
private NetworkStateReceiver networkStateReceiver;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_habit_event_details);
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
getUIElements();
mHabitList = HabitController.getHabitController(this).getHabitList();
networkStateReceiver = new NetworkStateReceiver();
networkStateReceiver.addListener(this);
viewHiding();
mFusedLocationClient = LocationServices.getFusedLocationProviderClient(this);
Intent intent = getIntent();
Bundle bundle = intent.getExtras();
if (bundle != null && bundle.get("habitEventPosition") != null) {
mHabitEventUUID = (UUID) bundle.get("habitEventPosition");
}
setListeners();
loadDetails();
interentViews();
}
private void interentViews() {
if (!NetworkUtils.isNetworkAvailable(this)) {
mToggleLocation.setEnabled(false);
mUpdateLocation.setEnabled(false);
} else {
mToggleLocation.setEnabled(true);
mUpdateLocation.setEnabled(true);
}
if (mHabitEvent != null) {
try {
mHabitEvent.getLocation();
mToggleLocation.setEnabled(true);
} catch (LocationNotSetException e) {
if (!NetworkUtils.isNetworkAvailable(this)) {
mToggleLocation.setEnabled(false);
}
mUpdateLocation.setEnabled(false);
}
}
}
private void viewHiding() {
mHabitType.setVisibility(View.GONE);
mHabitType_Fixed.setVisibility(View.GONE);
mUpdateLocation.setVisibility(View.GONE);
mPreviousDayText.setVisibility(View.GONE);
mPreviousDaySpin.setVisibility(View.GONE);
mRadioGroup.setVisibility(View.GONE);
mTodayRad.setVisibility(View.GONE);
mPreviousDayRad.setVisibility(View.GONE);
}
private void getUIElements() {
mTodayRad = (RadioButton) findViewById(R.id.Event_hTodayRad);
mPreviousDayRad = (RadioButton) findViewById(R.id.Event_hPreviousDayRad);
mRadioGroup = (RadioGroup) findViewById(R.id.RadGroup);
mPreviousDayText = (TextView) findViewById(R.id.Event_hPreviousText);
mPreviousDaySpin = (Spinner) findViewById(R.id.Event_hPreviousSpinner);
mHabitType = (Spinner) findViewById(R.id.Event_hType);
mHabitType_Fixed = (TextView) findViewById(R.id.Event_hTypeFixed);
mComment = (EditText) findViewById(R.id.Event_hComment);
mDateCompleted = (TextView) findViewById(R.id.Event_hDate);
mToggleLocation = (ToggleButton) findViewById(R.id.Event_hToggleButton);
mUpdateLocation = (Button) findViewById(R.id.Event_hUpdateButton);
mLocationString = (TextView) findViewById(R.id.Event_hLocationText);
mImageButton = (ImageButton) findViewById(R.id.Event_hImagebtn);
mGalleryButton = (Button) findViewById(R.id.Event_hGallerybtn);
mImageView = (ImageView) findViewById((R.id.Event_hImage));
mSave = (ImageButton) findViewById(R.id.Event_hSave);
mDelete = (ImageButton) findViewById(R.id.Event_hDelete);
}
private void setListeners() {
mDelete.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
if (mHabitEventUUID == null) {
Toast.makeText(HabitEventDetailsActivity.this, "You cannot delete a habit event before it has been created!", Toast.LENGTH_SHORT).show();
} else {
AlertDialog.Builder builder = new AlertDialog.Builder(HabitEventDetailsActivity.this);
builder.setMessage("Delete habit event?")
.setPositiveButton("Yes", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
deleteButtonHandler();
}
})
.setNegativeButton("No", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
}
});
AlertDialog alert = builder.create();
alert.show();
}
}
});
mImageButton.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
if (checkSelfPermission(Manifest.permission.CAMERA) == PackageManager.PERMISSION_GRANTED) {
invokeCamera();
} else {
String[] permissionRequested = {Manifest.permission.CAMERA};
requestPermissions(permissionRequested, CAMERA_REQUEST_CODE);
}
}
});
mImageButton.setOnTouchListener(new TextView.OnTouchListener() {
@Override
public boolean onTouch(View v, MotionEvent event) {
return mImageButtonOnTouch(event);
}
});
mGalleryButton.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
if (checkSelfPermission(Manifest.permission.READ_EXTERNAL_STORAGE) == PackageManager.PERMISSION_GRANTED) {
invokeGallery();
} else {
String[] permissionRequested = {Manifest.permission.READ_EXTERNAL_STORAGE};
requestPermissions(permissionRequested, GALLERY_REQUEST_CODE);
}
}
});
mToggleLocation.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
@Override
public void onCheckedChanged(CompoundButton compoundButton, boolean isChecked) {
if (checkSelfPermission(Manifest.permission.ACCESS_COARSE_LOCATION) == PackageManager.PERMISSION_GRANTED) {
if (isChecked) {
mUpdateLocation.setEnabled(true);
if (NetworkUtils.isNetworkAvailable(HabitEventDetailsActivity.this)) {
getLocation();
} else {
Toast.makeText(HabitEventDetailsActivity.this, "Oops, you are offline, please try again later!", Toast.LENGTH_SHORT).show();
mUpdateLocation.setEnabled(false);
mToggleLocation.setEnabled(false);
}
} else {
if (!NetworkUtils.isNetworkAvailable(HabitEventDetailsActivity.this)) {
mToggleLocation.setEnabled(false);
}
mUpdateLocation.setEnabled(false);
mLocation = null;
mLocationString.setText("");
mLocationText = null;
}
} else {
String[] permissionRequested = {Manifest.permission.ACCESS_COARSE_LOCATION};
requestPermissions(permissionRequested, LOCATION_REQUEST_CODE);
}
}
});
mUpdateLocation.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
if (checkSelfPermission(Manifest.permission.ACCESS_COARSE_LOCATION) == PackageManager.PERMISSION_GRANTED) {
if (NetworkUtils.isNetworkAvailable(HabitEventDetailsActivity.this)) {
getLocation();
} else {
Toast.makeText(HabitEventDetailsActivity.this, "Oops, you are offline, please try again later!", Toast.LENGTH_SHORT).show();
mToggleLocation.setEnabled(false);
}
} else {
String[] permissionRequested = {Manifest.permission.ACCESS_COARSE_LOCATION};
requestPermissions(permissionRequested, LOCATION_REQUEST_CODE);
}
}
});
mSave.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
saveButtonHandler();
}
});
mRadioGroup.setOnCheckedChangeListener(new RadioGroup.OnCheckedChangeListener() {
@Override
public void onCheckedChanged(RadioGroup radioGroup, @IdRes int i) {
if (((RadioButton) findViewById(i)).getText().equals("Previous Day")) {
mPreviousDayText.setVisibility(View.VISIBLE);
mPreviousDaySpin.setVisibility(View.VISIBLE);
} else {
mPreviousDayText.setVisibility(View.GONE);
mPreviousDaySpin.setVisibility(View.GONE);
}
loadSpinner();
loadPreviousSpinner();
}
});
mHabitType.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
@Override
public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
loadPreviousSpinner();
}
@Override
public void onNothingSelected(AdapterView<?> parent) {
}
});
}
private void loadDetails() {
if (mHabitEventUUID != null) {
mHabitEvent = HabitEventController.getHabitEventController(this).getHabitEvent(mHabitEventUUID);
mUpdateLocation.setVisibility(View.VISIBLE);
mHabitType_Fixed.setVisibility(View.VISIBLE);
mHabitType_Fixed.setText(HabitController.getHabitController(this).getHabit(mHabitEvent.getHabitID()).getTitle());
mDateCompleted.setText(DateUtils.getStringOfDate(mHabitEvent.getDate()));
try {
mComment.setText(mHabitEvent.getComment());
} catch (CommentNotSetException e) {}
try {
mHabitEvent.getLocation();
if (mHabitEvent.getLocation() == null) {
mUpdateLocation.setEnabled(false);
}
mToggleLocation.setChecked(true);
mLocationString.setText(mHabitEvent.getLocationString());
} catch (LocationNotSetException e) {
mUpdateLocation.setEnabled(false);
}
try {
mImageView.setImageBitmap(HabitEvent.decompressBitmap(mHabitEvent.getImage()));
mImage = mHabitEvent.getImage();
} catch (ImageNotSetException e) {}
} else {
mHabitType.setVisibility(View.VISIBLE);
mTodayRad.setVisibility(View.VISIBLE);
mPreviousDayRad.setVisibility(View.VISIBLE);
mRadioGroup.setVisibility(View.VISIBLE);
loadSpinner();
}
}
long time = 0;
private boolean mImageButtonOnTouch(MotionEvent event) {
if (event.getAction() == MotionEvent.ACTION_DOWN) {
time = (Long) System.currentTimeMillis();
} else if (event.getAction() == MotionEvent.ACTION_UP) {
if (((Long) System.currentTimeMillis() - time) > 2000) {
mImageView.setImageBitmap(null);
mImage = null;
return true;
}
}
return false;
}
private void deleteButtonHandler() {
finish();
HabitEventController.getHabitEventController(this).deleteHabitEvent(this, mHabitEventUUID);
}
private void saveButtonHandler() {
if (mHabitEventUUID == null) {
saveNew();
} else {
saveExsisting();
}
}
private void saveExsisting() {
if (!mComment.getText().toString().equals("")) {
try {
mHabitEvent.setComment(mComment.getText().toString());
} catch (CommentTooLongException e) {
}
}
else {
try {
mHabitEvent.setComment(null);
} catch (Exception e) {}
}
if (mToggleLocation.isChecked()) {
if (mLocation != null)
mHabitEvent.setLocation(mLocation, mLocationText);
} else {
mHabitEvent.setLocation(null);
}
try {
mHabitEvent.setImage(mImage);
} catch (ImageTooBigException e) {
}
HabitEventController.getHabitEventController(this).updateHabitEvent(this, mHabitEvent);
finish();
}
private void saveNew() {
String title = null;
try {
title = mHabitType.getSelectedItem().toString();
} catch (NullPointerException e) {
Toast.makeText(HabitEventDetailsActivity.this, "Please select a Habit Type!", Toast.LENGTH_SHORT).show();
return;
}
HabitEvent habitEvent = new HabitEvent(UserController.getUserController(this).getUser().getUserID(),
HabitController.getHabitController(this).getHabitIDByTitle(title));
if (mPreviousDayRad.isChecked()) {
SimpleDateFormat simpleDateFormat = DateUtils.getDateFormat();
try {
mPreviousDaySpin.getSelectedItem().toString();
Date previousDate = simpleDateFormat.parse(mPreviousDaySpin.getSelectedItem().toString());
habitEvent.setDate(previousDate);
} catch (Exception e) {
Toast.makeText(HabitEventDetailsActivity.this, "Please select a previous date!", Toast.LENGTH_SHORT).show();
return;
}
}
try { habitEvent.setComment(mComment.getText().toString()); } catch (CommentTooLongException e) {}
if (mToggleLocation.isChecked())
habitEvent.setLocation(mLocation, mLocationText);
try { habitEvent.setImage(mImage); } catch (ImageTooBigException e) {}
HabitEventController.getHabitEventController(this).addHabitEvent(this, habitEvent);
finish();
}
public void loadSpinner() {
ArrayList<Habit> availableHabits = new ArrayList<>();
availableHabits.addAll(mHabitList);
ArrayList<String> stringAvailableHabits = new ArrayList<>();
if (mTodayRad.isChecked()) {
for (Habit habit : availableHabits) {
SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyyMMdd", Locale.getDefault());
if (simpleDateFormat.format(habit.getStartDate()).compareTo(simpleDateFormat.format(new Date())) > 0) {
continue;
}
if (HabitEventController.getHabitEventController(this).doesHabitEventExist(habit)) {
stringAvailableHabits.add(habit.getTitle());
}
}
} else if (mPreviousDayRad.isChecked()) {
for (Habit habit : availableHabits) {
stringAvailableHabits.add(habit.getTitle());
}
}
spinnerDataAdapter = new ArrayAdapter<String>(this, android.R.layout.simple_spinner_item, stringAvailableHabits);
spinnerDataAdapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
mHabitType.setAdapter(spinnerDataAdapter);
}
public void loadPreviousSpinner() {
if (mPreviousDayRad.getVisibility() != View.GONE) {
if (mPreviousDayRad.isChecked()) {
String habitTitle;
try {
habitTitle = mHabitType.getSelectedItem().toString();
} catch (NullPointerException e) { return; }
Habit habit = HabitController.getHabitController(this).getHabitByTitle(habitTitle);
mDaysMissed = HabitEventController.getHabitEventController(this).getMissedHabitEvents(habit);
ArrayList<String> stringAvailableDays = new ArrayList<>();
for (Date date : mDaysMissed) {
stringAvailableDays.add(DateUtils.getStringOfDate(date));
}
previousSpinnerDataAdapter = new ArrayAdapter<String>(this, android.R.layout.simple_spinner_item, stringAvailableDays);
previousSpinnerDataAdapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
mPreviousDaySpin.setAdapter(previousSpinnerDataAdapter);
}
}
}
public void onRequestPermissionsResult(int requestCode, String[] permissions, int[] grantResults) {
super.onRequestPermissionsResult(requestCode, permissions, grantResults);
if (requestCode == CAMERA_REQUEST_CODE) {
if (grantResults[0] == PackageManager.PERMISSION_GRANTED) {
invokeCamera();
} else {
Toast.makeText(this, "Unable to request camera", Toast.LENGTH_LONG).show();
}
} else if (requestCode == LOCATION_REQUEST_CODE) {
if (grantResults[0] == PackageManager.PERMISSION_GRANTED) {
getLocation();
} else {
Toast.makeText(this, "Unable to request location services", Toast.LENGTH_LONG).show();
mToggleLocation.setChecked(false);
}
} else if (requestCode == GALLERY_REQUEST_CODE) {
if (grantResults[0] == PackageManager.PERMISSION_GRANTED) {
invokeGallery();
} else {
Toast.makeText(this, "Unable to request storage services", Toast.LENGTH_LONG).show();
}
}
}
public void invokeCamera() {
Intent cameraIntent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
startActivityForResult(cameraIntent, CAMERA_REQUEST);
}
private void invokeGallery() {
Intent galleryIntent = new Intent(Intent.ACTION_GET_CONTENT);
File pictureDirectory = Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_PICTURES);
String pictureDirectoryPath = pictureDirectory.getPath();
Uri data = Uri.parse(pictureDirectoryPath);
galleryIntent.setDataAndType(data, "image/*");
startActivityForResult(galleryIntent, GALLERY_REQUEST);
}
@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
if (requestCode == CAMERA_REQUEST && resultCode == RESULT_OK) {
Bundle extras = data.getExtras();
Bitmap imageBitmap = (Bitmap) extras.get("data");
mImageView.setImageBitmap(HabitEvent.decompressBitmap(imageBitmap));
mImage = HabitEvent.compressBitmap(imageBitmap);
} else if (requestCode == GALLERY_REQUEST && resultCode == RESULT_OK) {
Uri imageUri = data.getData();
try {
InputStream inputStream = getContentResolver().openInputStream(imageUri);
Bitmap imageBitmap = BitmapFactory.decodeStream(inputStream);
mImageView.setImageBitmap(HabitEvent.decompressBitmap(imageBitmap));
mImage = HabitEvent.compressBitmap(imageBitmap);
} catch (FileNotFoundException e) {
e.printStackTrace();
Toast.makeText(this, "Unable to open image", Toast.LENGTH_LONG).show();
}
}
}
private void getLocation() {
try {
mFusedLocationClient.getLastLocation().addOnSuccessListener(HabitEventDetailsActivity.this, new OnSuccessListener<Location>() {
@Override
public void onSuccess(Location location) {
if (location != null) {
mLocation = location;
Geocoder myLocation = new Geocoder(HabitEventDetailsActivity.this, Locale.getDefault());
try {
List<Address> myList = myLocation.getFromLocation(location.getLatitude(), location.getLongitude(), 1);
StringBuilder Baddress = new StringBuilder();
if (!(myList.get(0).getLocality() == null)) {
Baddress.append(" " + myList.get(0).getLocality());
}
if (!(myList.get(0).getPostalCode() == null)) {
Baddress.append(" " + myList.get(0).getPostalCode());
}
if (!(myList.get(0).getThoroughfare() == null)) {
Baddress.append(" " + myList.get(0).getThoroughfare());
}
String address = Baddress.toString().trim();
mLocationString.setText(address);
mLocationText = address;
} catch (IOException e) {
}
} else {
Toast.makeText(getApplicationContext(),
"Turn on location services to add a location.",
Toast.LENGTH_SHORT).show();
mToggleLocation.setChecked(false);
}
}
});
} catch (SecurityException e) {
String[] permissionRequested = {Manifest.permission.ACCESS_COARSE_LOCATION};
requestPermissions(permissionRequested, LOCATION_REQUEST_CODE);
}
}
@Override
public void networkAvailable() {
interentViews();
}
@Override
public void networkUnavailable() {
interentViews();
Toast.makeText(this, "You are offline, disabling updating/setting location", Toast.LENGTH_SHORT).show();
}
@Override
public void onResume() {
super.onResume();
this.registerReceiver(networkStateReceiver, new IntentFilter(ConnectivityManager.CONNECTIVITY_ACTION));
}
@Override
public void onPause() {
super.onPause();
this.unregisterReceiver(networkStateReceiver);
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case android.R.id.home:
onBackPressed();
return true;
}
return false;
}
}
|
package com.example.demo;
import static org.assertj.core.api.Assertions.assertThat;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.boot.test.context.SpringBootTest.WebEnvironment;
import org.springframework.boot.test.mock.mockito.MockBean;
import org.springframework.boot.test.web.client.TestRestTemplate;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.test.context.junit4.SpringRunner;
import com.example.demo.entity.Order;
import com.example.demo.service.OrderService;
import com.example.demo.service.TacoService;
@RunWith(SpringRunner.class)
@SpringBootTest(webEnvironment = WebEnvironment.RANDOM_PORT)
public class TacoOrderDemoApplicationIntegration {
@Autowired
TestRestTemplate restTemplate;
@MockBean
OrderService orderService;
@MockBean
TacoService tacoService;
@Test
public void getOrderTest() {
ResponseEntity<String> response = restTemplate.getForEntity("/app/order", String.class);
assertThat(response.getStatusCode()).isEqualTo(HttpStatus.OK);
}
@Test
public void createTacoTest() {
String requestPayload = "{\"name\" : \"chickenTaco\","
+ "\"ingredients\": [{\"name\" :\"chicken\" }]}";
ResponseEntity<String> response = restTemplate.postForEntity("/app/create", requestPayload, String.class);
assertThat(response.getStatusCode()).isEqualTo(HttpStatus.OK);
}
}
|
package plugins.fmp.fmpTools;
import java.util.ArrayList;
import plugins.fmp.fmpSequence.Experiment;
public class XLSExportCapillariesOptions {
public boolean topLevel = true;
public boolean bottomLevel = false;
public boolean derivative = false;
public boolean consumption = false;
public boolean sum = true;
public boolean transpose = false;
public boolean t0 = true;
public boolean onlyalive = false;
public boolean pivot = false;
public boolean exportAllFiles = true;
public ArrayList<Experiment> experimentList = new ArrayList<Experiment> ();
}
|
package com.movietime.dataAccessLayer;
import com.movietime.exceptions.EmailUsedException;
import com.movietime.exceptions.PersistingFailedException;
import com.movietime.exceptions.UsernameUsedException;
import com.movietime.entities.UsersEntity;
import org.springframework.stereotype.Repository;
import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;
import java.util.List;
/**
* Created by Attila on 2015-05-12.
*/
@Repository
public class UserDao {
@PersistenceContext
private EntityManager em;
public void persistNewUser(UsersEntity user) throws UsernameUsedException, EmailUsedException, PersistingFailedException {
if (user.getUserName() == null || user.getUserName().equals("")) {
throw new PersistingFailedException("Username cannot be empty.");
}
if (user.getEmail() == null || user.getEmail().equals("")) {
throw new PersistingFailedException("Email cannot be empty.");
}
List<UsersEntity> otherUsers = em.createQuery("SELECT u FROM UsersEntity u WHERE " +
"u.userName = :username", UsersEntity.class)
.setParameter("username", user.getUserName())
.getResultList();
for (UsersEntity otherUser : otherUsers) {
if (otherUser.getUserName().equals(user.getUserName())) {
throw new UsernameUsedException();
}
}
List<UsersEntity> otherUsersEmail = em.createQuery("SELECT u FROM UsersEntity u WHERE " +
"u.email = :email", UsersEntity.class)
.setParameter("email", user.getEmail())
.getResultList();
if (!otherUsersEmail.isEmpty()) {
throw new EmailUsedException();
}
em.persist(user);
}
}
|
package com.zundrel.ollivanders.common.items;
import com.zundrel.ollivanders.Ollivanders;
import com.zundrel.ollivanders.api.cores.ICore;
import com.zundrel.ollivanders.api.registries.CoreRegistry;
import com.zundrel.ollivanders.api.registries.WoodRegistry;
import com.zundrel.ollivanders.api.wands.EnumWandQuality;
import com.zundrel.ollivanders.api.wands.IWandItem;
import com.zundrel.ollivanders.api.wands.WandColor;
import com.zundrel.ollivanders.api.woods.IWood;
import net.minecraft.client.MinecraftClient;
import net.minecraft.client.item.TooltipContext;
import net.minecraft.item.Item;
import net.minecraft.item.ItemGroup;
import net.minecraft.item.ItemStack;
import net.minecraft.nbt.CompoundTag;
import net.minecraft.text.LiteralText;
import net.minecraft.text.Text;
import net.minecraft.text.TranslatableText;
import net.minecraft.util.DefaultedList;
import net.minecraft.util.Formatting;
import net.minecraft.util.Identifier;
import net.minecraft.util.SystemUtil;
import net.minecraft.world.World;
import java.util.List;
import java.util.UUID;
public class WandItem extends Item implements IWandItem {
private String wood;
public WandItem(String wood) {
super(new Item.Settings());
this.wood = wood;
WandColor.setColor(this);
}
@Override
public String getTranslationKey() {
return SystemUtil.createTranslationKey("item", new Identifier(Ollivanders.MODID, "wand_" + wood));
}
@Override
public ICore getCore(ItemStack stack) {
if (stack.hasTag()) {
return CoreRegistry.findCore(stack.getTag().getString("core"));
}
return null;
}
@Override
public void setCore(ItemStack stack, ICore core) {
if (!stack.hasTag()) {
stack.setTag(new CompoundTag());
}
stack.getTag().putString("core", core.getName());
}
@Override
public UUID getOwner(ItemStack stack) {
if (stack.hasTag()) {
return stack.getTag().getUuid("uuid");
} else {
stack.setTag(new CompoundTag());
return null;
}
}
@Override
public void setOwner(ItemStack stack, UUID uuid) {
if (!stack.hasTag()) {
stack.setTag(new CompoundTag());
}
stack.getTag().putUuid("uuid", uuid);
}
@Override
public EnumWandQuality getQuality(ItemStack stack) {
if (stack.hasTag()) {
return EnumWandQuality.getFromName(stack.getTag().getString("quality"));
} else {
stack.setTag(new CompoundTag());
return null;
}
}
@Override
public void setQuality(ItemStack stack, EnumWandQuality quality) {
if (!stack.hasTag()) {
stack.setTag(new CompoundTag());
}
stack.getTag().putString("quality", quality.asString());
}
@Override
public IWood getWood() {
return WoodRegistry.findWood(wood);
}
// @Override
// public boolean onEntitySwing(ItemStack stack, LivingEntity entity) {
// if (!(entity instanceof PlayerEntity)) {
// return false;
// }
//
// PlayerEntity player = (PlayerEntity) entity;
//
// AtomicBoolean done = new AtomicBoolean(false);
//
// player.getCapability(OllivandersAPI.PLAYER_INFO_CAPABILITY).ifPresent(playerInfo -> {
// if (!player.getCooldownTracker().hasCooldown(this) && !player.getEntityWorld().isRemote()) {
// if (getOwner(stack).equals(UUID.fromString("00000000-0000-0000-0000-000000000000")) && playerInfo.getCore() == getCore(stack) && playerInfo.getWood() == getWood()) {
// setOwner(stack, player.getUniqueID());
//
// player.getEntityWorld().playSound(null, player.getPosition(), SoundEvents.ENTITY_EXPERIENCE_ORB_PICKUP, SoundCategory.PLAYERS, 1F, 1F);
// player.sendMessage(new TranslationTextComponent("wand.ollivanders.owner"));
// } else if (getOwner(stack).equals(UUID.fromString("00000000-0000-0000-0000-000000000000"))) {
// player.getEntityWorld().playSound(null, player.getPosition(), SoundEvents.ENTITY_GENERIC_EXPLODE, SoundCategory.PLAYERS, 0.15F, 1F);
// }
//
// if (playerInfo.getSpell() != null) {
// player.getCooldownTracker().setCooldown(this, 40);
// SpellHandler.cast(playerInfo.getSpell(), playerInfo.getPowerLevel(), player.getEntityWorld(), player);
//
// if (!playerInfo.getSpell().isMasteredSpell(player)) {
// playerInfo.setSpell(null);
// }
// }
//
// done.set(true);
// } else {
// done.set(false);
// }
// });
// return done.get();
// }
@Override
public void appendTooltip(ItemStack itemStack_1, World world_1, List<Text> list_1, TooltipContext tooltipContext_1) {
list_1.add(new LiteralText("Wood: " + Formatting.GRAY + new TranslatableText(getWood().getTranslationKey()).getString()));
if (itemStack_1.hasTag()) {
list_1.add(new LiteralText("Core: " + Formatting.GRAY + new TranslatableText(getCore(itemStack_1).getTranslationKey()).getString()));
if (world_1.getPlayerByUuid(itemStack_1.getTag().getUuid("uuid")) != null) {
list_1.add(new LiteralText("Owner: " + Formatting.GRAY + world_1.getPlayerByUuid(itemStack_1.getTag().getUuid("uuid")).getDisplayName().asString()));
}
if (MinecraftClient.getInstance().options.advancedItemTooltips) {
list_1.add(new LiteralText("Owner (UUID): " + Formatting.GRAY + itemStack_1.getTag().getUuid("uuid").toString()));
}
list_1.add(new LiteralText("Quality: " + Formatting.GRAY + new TranslatableText(getQuality(itemStack_1).getTranslationKey()).getString()));
}
}
@Override
public void appendStacks(ItemGroup itemGroup_1, DefaultedList<ItemStack> defaultedList_1) {
if (!wood.equals("elder")) {
for (EnumWandQuality quality : EnumWandQuality.values()) {
for (Identifier identifier : CoreRegistry.getKeys()) {
if (!identifier.getPath().equals("thestral_tail_hair")) {
ItemStack stack = new ItemStack(this);
stack.setTag(new CompoundTag());
stack.getTag().putString("core", identifier.getPath());
stack.getTag().putString("quality", quality.asString());
if (itemGroup_1 == getCore(stack).getGroup())
defaultedList_1.add(stack);
}
}
}
} else if (itemGroup_1 == Ollivanders.generalItemGroup && wood.equals("elder")) {
ItemStack stack = new ItemStack(this);
stack.setTag(new CompoundTag());
stack.getTag().putString("core", "thestral_tail_hair");
stack.getTag().putString("quality", EnumWandQuality.PERFECT.asString());
defaultedList_1.add(stack);
}
}
}
|
package com.shangdao.phoenix.entity.report.BO;
import com.shangdao.phoenix.enums.Color;
import java.util.Objects;
/**
* 分析评估项
*
* @author huanghengkun
* @date 2018/01/09
*/
public class RiskItem {
private String content;
private Color color;
public String getContent() {
return content;
}
public void setContent(String content) {
this.content = content;
}
public Color getColor() {
return color;
}
public void setColor(Color color) {
this.color = color;
}
public RiskItem(String content, Color color) {
this.content = content;
this.color = color;
}
public RiskItem() {
}
@Override
public boolean equals(Object o) {
if (this == o) {
return true;
}
if (o == null || getClass() != o.getClass()) {
return false;
}
RiskItem riskItem = (RiskItem) o;
return Objects.equals(content, riskItem.content) &&
color == riskItem.color;
}
@Override
public int hashCode() {
return Objects.hash(content, color);
}
}
|
/*
* Copyright (C) 2017 GetMangos
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU General Public License
* as published by the Free Software Foundation; either version 2
* of the License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.
*/
package eu.mangos.dbc.model.map;
/**
* Entry representing a Taxi Path Node.
* @author GetMangos
*/
public class TaxiPathNode {
/**
* 0 - ID in the DBC.
*/
private int id;
/**
* 1 - ID of the path (See TaxiPath.dbc)
*/
private int pathID;
/**
* 2 - ID of the node (See TaxiNodes.dbc)
*/
private int nodeID;
/**
* 3 - ID of the map (See Map.dbc)
*/
private int map;
/**
* 4 - Positixion X of the Taxi Node.
*/
private float posX;
/**
* 5 - Positixion Y of the Taxi Node.
*/
private float posY;
/**
* 6 - Positixion Z of the Taxi Node.
*/
private float posZ;
/**
* 7 - Flags
*/
private int flags;
/**
* 8 - Delay
*/
private int delay;
public TaxiPathNode() {
}
public TaxiPathNode(int id, int pathID, int nodeID, int map, float posX, float posY, float posZ, int flags, int delay) {
this.id = id;
this.pathID = pathID;
this.nodeID = nodeID;
this.map = map;
this.posX = posX;
this.posY = posY;
this.posZ = posZ;
this.flags = flags;
this.delay = delay;
}
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public int getPathID() {
return pathID;
}
public void setPathID(int pathID) {
this.pathID = pathID;
}
public int getNodeID() {
return nodeID;
}
public void setNodeID(int nodeID) {
this.nodeID = nodeID;
}
public int getMap() {
return map;
}
public void setMap(int map) {
this.map = map;
}
public float getPosX() {
return posX;
}
public void setPosX(float posX) {
this.posX = posX;
}
public float getPosY() {
return posY;
}
public void setPosY(float posY) {
this.posY = posY;
}
public float getPosZ() {
return posZ;
}
public void setPosZ(float posZ) {
this.posZ = posZ;
}
public int getFlags() {
return flags;
}
public void setFlags(int flags) {
this.flags = flags;
}
public int getDelay() {
return delay;
}
public void setDelay(int delay) {
this.delay = delay;
}
}
|
package com.djtracksholder.djtracksholder.ui;
import java.util.ArrayList;
import java.util.Locale;
import android.app.ActionBar;
import android.app.FragmentTransaction;
import android.content.Intent;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentPagerAdapter;
import android.support.v4.app.ListFragment;
import android.support.v4.app.LoaderManager;
import android.support.v4.content.Loader;
import android.support.v4.view.ViewPager;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.ListView;
import android.widget.SimpleCursorAdapter;
import com.djtracksholder.djtracksholder.CustomViewPager;
import com.djtracksholder.djtracksholder.adapters.WaitListAdapter;
import com.djtracksholder.djtracksholder.com.djtracksholder.beans.TrackInfo;
import com.djtracksholder.djtracksholder.provider.DBHelper;
import com.djtracksholder.djtracksholder.provider.HolderProvider;
import com.djtracksholder.djtracksholder.R;
import com.djtracksholder.djtracksholder.swipelist.SwipeDismissListViewTouchListener;
public class MainActivity extends BaseActivity implements ActionBar.TabListener {
SectionsPagerAdapter mSectionsPagerAdapter;
/**
* The {@link ViewPager} that will host the section contents.
*/
CustomViewPager mViewPager;
HolderProvider holderProvider;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_browse);
//GoogleAccountCredential s;
// Set up the action bar.
final ActionBar actionBar = getActionBar();
actionBar.setNavigationMode(ActionBar.NAVIGATION_MODE_TABS);
actionBar.setDisplayHomeAsUpEnabled(true);
// Create the adapter that will return a fragment for each of the three
// primary sections of the activity.
mSectionsPagerAdapter = new SectionsPagerAdapter(getSupportFragmentManager());
// Set up the ViewPager with the sections adapter.
mViewPager = (CustomViewPager) findViewById(R.id.pager);
mViewPager.setAdapter(mSectionsPagerAdapter);
mViewPager.setSwipeable(false);
// When swiping between different sections, select the corresponding
// tab. We can also use ActionBar.Tab#select() to do this if we have
// a reference to the Tab.
mViewPager.setOnPageChangeListener(new ViewPager.SimpleOnPageChangeListener() {
@Override
public void onPageSelected(int position) {
actionBar.setSelectedNavigationItem(position);
}
});
// For each of the sections in the app, add a tab to the action bar.
for (int i = 0; i < mSectionsPagerAdapter.getCount(); i++) {
// Create a tab with text corresponding to the page title defined by
// the adapter. Also specify this Activity object, which implements
// the TabListener interface, as the callback (listener) for when
// this tab is selected.
actionBar.addTab(
actionBar.newTab()
.setText(mSectionsPagerAdapter.getPageTitle(i))
.setTabListener(this));
}
this.holderProvider = HolderProvider.getInstance(this);
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.browse_tracks, menu);
return true;
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
switch (item.getItemId()) {
case R.id.action_browse:
startActivity(new Intent(this, BrowseActivity.class));
return true;
case R.id.action_alphabet:
startActivity(new Intent(this, AlphabetActivity.class));
return true;
case R.id.action_editor:
startActivity(new Intent(this, EditorActivity.class));
return true;
}
return super.onOptionsItemSelected(item);
}
@Override
public void onTabSelected(ActionBar.Tab tab, FragmentTransaction fragmentTransaction) {
// When the given tab is selected, switch to the corresponding page in
// the ViewPager.
mViewPager.setCurrentItem(tab.getPosition());
}
@Override
public void onTabUnselected(ActionBar.Tab tab, FragmentTransaction fragmentTransaction) {
}
@Override
public void onTabReselected(ActionBar.Tab tab, FragmentTransaction fragmentTransaction) {
}
@Override
public void onStart() {
super.onStart();
}
public class SectionsPagerAdapter extends FragmentPagerAdapter {
public SectionsPagerAdapter(FragmentManager fm) {
super(fm);
}
@Override
public Fragment getItem(int position) {
// getItem is called to instantiate the fragment for the given page.
// Return a PlaceholderFragment (defined as a static inner class below).
return PlaceholderFragment.newInstance(position + 1);
}
@Override
public int getCount() {
// Show 3 total pages.
return 1;
}
@Override
public CharSequence getPageTitle(int position) {
Locale l = Locale.getDefault();
switch (position) {
case 0:
return getString(R.string.title_section1).toUpperCase(l);
case 1:
return getString(R.string.title_section2).toUpperCase(l);
case 2:
return getString(R.string.title_section3).toUpperCase(l);
}
return null;
}
}
/**
* A placeholder fragment containing a simple view.
*/
public static class PlaceholderFragment extends ListFragment {
private HolderProvider holderProvider;
/**
* The fragment argument representing the section number for this
* fragment.
*/
private static final String ARG_SECTION_NUMBER = "section_number";
/**
* Returns a new instance of this fragment for the given section
* number.
*/
public static PlaceholderFragment newInstance(int sectionNumber) {
PlaceholderFragment fragment;
if (sectionNumber == 1) {
fragment = new WaitListFragment();
}
else {
fragment = new PlaceholderFragment();
}
Bundle args = new Bundle();
args.putInt(ARG_SECTION_NUMBER, sectionNumber);
fragment.setArguments(args);
return fragment;
}
public PlaceholderFragment() {
}
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
this.holderProvider = HolderProvider.getInstance(getActivity());
}
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.fragment_browse, container, false);
return rootView;
}
public HolderProvider getHolderProvider() {
return holderProvider;
}
}
public static class WaitListFragment extends PlaceholderFragment {
ArrayList<TrackInfo> tracks;
private WaitListAdapter adapter;
private AdapterView.OnItemClickListener itemClickListener = new AdapterView.OnItemClickListener() {
@Override
public void onItemClick(AdapterView<?> adapterView, View view, int i, long l) {
Intent intent = new Intent(getActivity(), BrowseActivity.class);
Bundle bundle = new Bundle();
intent.putExtra("cd", tracks.get(i).getCdNumber());
startActivity(intent);
}
};
public WaitListFragment() {
super();
}
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
Bundle bundle = new Bundle();
bundle.putInt("section", 1);
}
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.fragment_browse_waitlist, container, false);
return rootView;
}
public void addSwipes() {
SwipeDismissListViewTouchListener touchListener =
new SwipeDismissListViewTouchListener(
getListView(),
new SwipeDismissListViewTouchListener.DismissCallbacks() {
@Override
public boolean canDismiss(int position) {
return true;
}
@Override
public void onDismiss(ListView listView, int[] reverseSortedPositions) {
for (int position : reverseSortedPositions) {
long id = adapter.getItem(position).getExtId();
getHolderProvider().removeTrackFromWaitingList(id);
}
tracks = getHolderProvider().getTracksFromWaitList();
adapter.setData(tracks);
}
});
getListView().setOnTouchListener(touchListener);
getListView().setOnScrollListener(touchListener.makeScrollListener());
}
@Override
public void onActivityCreated(Bundle savedInstanceState) {
super.onActivityCreated(savedInstanceState);
tracks = getHolderProvider().getTracksFromWaitList();
adapter = new WaitListAdapter(getActivity(), tracks);
getListView().setAdapter(adapter);
getListView().setOnItemClickListener(itemClickListener);
addSwipes();
}
}
}
|
package task_introduction;
public class Mathematical {
/**
* Greatest common divisor. Returns the GCD of two numbers.
* @param a number
* @param b number
* @return gcd(a, b)
*/
public static int gcd(int a, int b){
if(a == 0 || a == b){
return b;
}
if(b == 0){
return a;
}
while(a != b){
if(a < b){
b -= a;
}
else if(a > b){
a -= b;
}
}
return a;
}
/**
* Least common multiple. Returns the LCM of two numbers.
* @param a number
* @param b number
* @return lcm(a, b)
*/
public static int lcm(int a, int b) {
return Math.abs(a * b) / gcd(a, b);
}
}
|
package com.nextLevel.hero.mngPay.model.dto;
import java.sql.Date;
public class MngPayListDTO {
private int companyNo;
private int memberNo;
private String memberName;
private int idNo;
private String departmentName;
private String rank;
private String salaryStep;
private String yearAndMonth;
private String searchPayDate;
private java.sql.Date payDate;
private int salaryAmount;
private int deductAmount;
private int transferAmount;
private String category;
private int bankCode;
private String bankName;
private String accountNo;
public MngPayListDTO() {}
public MngPayListDTO(int companyNo, int memberNo, String memberName, int idNo, String departmentName, String rank,
String salaryStep, String yearAndMonth, String searchPayDate, Date payDate, int salaryAmount,
int deductAmount, int transferAmount, String category, int bankCode, String bankName, String accountNo) {
super();
this.companyNo = companyNo;
this.memberNo = memberNo;
this.memberName = memberName;
this.idNo = idNo;
this.departmentName = departmentName;
this.rank = rank;
this.salaryStep = salaryStep;
this.yearAndMonth = yearAndMonth;
this.searchPayDate = searchPayDate;
this.payDate = payDate;
this.salaryAmount = salaryAmount;
this.deductAmount = deductAmount;
this.transferAmount = transferAmount;
this.category = category;
this.bankCode = bankCode;
this.bankName = bankName;
this.accountNo = accountNo;
}
public int getCompanyNo() {
return companyNo;
}
public void setCompanyNo(int companyNo) {
this.companyNo = companyNo;
}
public int getMemberNo() {
return memberNo;
}
public void setMemberNo(int memberNo) {
this.memberNo = memberNo;
}
public String getMemberName() {
return memberName;
}
public void setMemberName(String memberName) {
this.memberName = memberName;
}
public int getIdNo() {
return idNo;
}
public void setIdNo(int idNo) {
this.idNo = idNo;
}
public String getDepartmentName() {
return departmentName;
}
public void setDepartmentName(String departmentName) {
this.departmentName = departmentName;
}
public String getRank() {
return rank;
}
public void setRank(String rank) {
this.rank = rank;
}
public String getSalaryStep() {
return salaryStep;
}
public void setSalaryStep(String salaryStep) {
this.salaryStep = salaryStep;
}
public String getYearAndMonth() {
return yearAndMonth;
}
public void setYearAndMonth(String yearAndMonth) {
this.yearAndMonth = yearAndMonth;
}
public String getSearchPayDate() {
return searchPayDate;
}
public void setSearchPayDate(String searchPayDate) {
this.searchPayDate = searchPayDate;
}
public java.sql.Date getPayDate() {
return payDate;
}
public void setPayDate(java.sql.Date payDate) {
this.payDate = payDate;
}
public int getSalaryAmount() {
return salaryAmount;
}
public void setSalaryAmount(int salaryAmount) {
this.salaryAmount = salaryAmount;
}
public int getDeductAmount() {
return deductAmount;
}
public void setDeductAmount(int deductAmount) {
this.deductAmount = deductAmount;
}
public int getTransferAmount() {
return transferAmount;
}
public void setTransferAmount(int transferAmount) {
this.transferAmount = transferAmount;
}
public String getCategory() {
return category;
}
public void setCategory(String category) {
this.category = category;
}
public int getBankCode() {
return bankCode;
}
public void setBankCode(int bankCode) {
this.bankCode = bankCode;
}
public String getBankName() {
return bankName;
}
public void setBankName(String bankName) {
this.bankName = bankName;
}
public String getAccountNo() {
return accountNo;
}
public void setAccountNo(String accountNo) {
this.accountNo = accountNo;
}
@Override
public String toString() {
return "MngPayListDTO [companyNo=" + companyNo + ", memberNo=" + memberNo + ", memberName=" + memberName
+ ", idNo=" + idNo + ", departmentName=" + departmentName + ", rank=" + rank + ", salaryStep="
+ salaryStep + ", yearAndMonth=" + yearAndMonth + ", searchPayDate=" + searchPayDate + ", payDate="
+ payDate + ", salaryAmount=" + salaryAmount + ", deductAmount=" + deductAmount + ", transferAmount="
+ transferAmount + ", category=" + category + ", bankCode=" + bankCode + ", bankName=" + bankName
+ ", accountNo=" + accountNo + "]";
}
}
|
package com.gxtc.huchuan.bean;
import java.io.Serializable;
import java.util.ArrayList;
import java.util.List;
public class DealTypeBean implements Serializable {
private static final long serialVersionUID = 1L;
private int id;
private String typeCode;
private String typeName;
private String isDefault;
private String pic;
/**
* 这部分数据是自定义筛选条件的
* choice : >
* name : 流量
* tradeField : udef2
* udfType : 5
* values : ["不限","100","500","1000","3000","5000"]
*/
private String choice;
private String name;
private String tradeField;
private String content;
private int udfType;
private List<String> values;
/**
* 这部分数据是旧的
*/
private int currIndex; //0 交易分类 1交易类型 2价格
private List<TypesBean> prices; //价格筛选
private List<TypesBean> types; //类型筛选
private List<TypesBean> classifys; //分类类型 0全部 1求购 2出售
public String getContent() {
return content;
}
public void setContent(String content) {
this.content = content;
}
public DealTypeBean() {
}
public int getCurrIndex() {
return currIndex;
}
public void setCurrIndex(int currIndex) {
this.currIndex = currIndex;
}
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getTypeCode() {
return typeCode;
}
public void setTypeCode(String typeCode) {
this.typeCode = typeCode;
}
public String getTypeName() {
return typeName;
}
public void setTypeName(String typeName) {
this.typeName = typeName;
}
public String getIsDefault() {
return isDefault;
}
public void setIsDefault(String isDefault) {
this.isDefault = isDefault;
}
public String getPic() {
return pic;
}
public void setPic(String pic) {
this.pic = pic;
}
public List<TypesBean> getPrices() {
return prices;
}
public List<TypesBean> getClassifys() {
if (classifys == null) {
classifys = new ArrayList<>();
classifys.add(new TypesBean("0", "全部"));
classifys.add(new TypesBean("1", "求购"));
classifys.add(new TypesBean("2", "出售"));
}
return classifys;
}
public void setClassifys(List<TypesBean> classifys) {
this.classifys = classifys;
}
public void setPrices(List<TypesBean> prices) {
this.prices = prices;
}
public List<TypesBean> getTypes() {
return types;
}
public void setTypes(List<TypesBean> types) {
this.types = types;
}
public String getChoice() { return choice;}
public void setChoice(String choice) { this.choice = choice;}
public String getName() { return name;}
public void setName(String name) { this.name = name;}
public String getTradeField() { return tradeField;}
public void setTradeField(String tradeField) { this.tradeField = tradeField;}
public int getUdfType() { return udfType;}
public void setUdfType(int udfType) { this.udfType = udfType;}
public List<String> getValues() { return values;}
public void setValues(List<String> values) {
this.values = values;
List<TypesBean> temp = new ArrayList<>();
for (String s : values) {
TypesBean bean = new TypesBean();
bean.setCode(getTradeField() + "," + getUdfType());
bean.setTitle(s);
bean.setChoice(getChoice());
temp.add(bean);
}
setTypes(temp);
}
public static class TypesBean {
/**
* code : 0
* title : 全部类型
*/
private String code;
private String title;
private String choice; //条件符号 = < >
private boolean isSelect;
public TypesBean() {
}
public TypesBean(String code, String title) {
this.code = code;
this.title = title;
}
public String getChoice() {
return choice;
}
public void setChoice(String choice) {
this.choice = choice;
}
public boolean isSelect() {
return isSelect;
}
public void setSelect(boolean select) {
isSelect = select;
}
public String getCode() {
return code;
}
public void setCode(String code) {
this.code = code;
}
public String getTitle() {
return title;
}
public void setTitle(String title) {
this.title = title;
}
}
}
|
package com.example.mvvm_livedata.view.callback;
import com.example.mvvm_livedata.model.Project;
public interface ProjectClickCallback {
void onClick(Project project);
}
|
package com.pykj.springmvc.controller;
import com.pykj.springmvc.entity.Users;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;
@Controller
@RequestMapping(value = "/index")
public class HelloHandler {
@RequestMapping(value = "/index", method = RequestMethod.GET)
public String index(@RequestParam("name") String name, @RequestParam("id") int id) {
System.out.println("执行了indaex....");
System.out.println("输出结果========name:" + name + "id:" + id);
return "index";
}
@RequestMapping("/rest/{name}/{id}")
public String rest(@PathVariable("name") String name, @PathVariable("id") int age) {
System.out.println("执行了rest....");
System.out.println("输出结果========name:" + name + "age:" + age);
return "index";
}
@RequestMapping("/cookie")
public String cookie(@CookieValue("JSESSIONID") String id) {
System.out.println("执行了cookie....");
System.out.println("输出结果========JSESSIONID:" + id);
return "index";
}
@RequestMapping(value = "/save", method = RequestMethod.POST)
public String save(Users users) {
System.out.println("执行了save....");
System.out.println("输出结果========:" + users);
return "index";
}
/**
* 转发
*
* @return
*/
@RequestMapping("/forward")
public String forward() {
System.out.println("转发forward");
return "forward:/index.jsp";
}
/**
* 重定向
*
* @return
*/
@RequestMapping("/redirect")
public String redirect() {
System.out.println("重定向redirect");
return "redirect:/index.jsp";
}
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.