text
stringlengths 10
2.72M
|
|---|
package audio;
public class Sound {
final int buffer;
final String name;
final String file;
public Sound(int buffer, String name, String file){
this.buffer = buffer;
this.name = name;
this.file = file;
}
public int getBuffer(){
return this.buffer;
}
public String getName(){
return this.name;
}
public String getFile(){
return this.file;
}
}
|
package excepciones;
public class ParaAtacarDirectamenteAlJugadorNoTieneQueHaberMonstruosInvocadosException extends Exception {
private static final long serialVersionUID = 1L;
}
|
package com.peerless2012.customerview.view;
import java.util.Random;
import android.content.Context;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.DashPathEffect;
import android.graphics.Paint;
import android.graphics.Paint.Align;
import android.graphics.Paint.Cap;
import android.graphics.Paint.FontMetrics;
import android.graphics.Paint.Style;
import android.graphics.Path;
import android.graphics.Picture;
import android.graphics.PorterDuff.Mode;
import android.graphics.PorterDuffXfermode;
import android.graphics.Rect;
import android.graphics.RectF;
import android.graphics.SweepGradient;
import android.util.AttributeSet;
import android.util.TypedValue;
import android.view.View;
/**
* @Author peerless2012
* @Email peerless2012@126.com
* @HomePage http://peerless2012.github.io
* @DateTime 2016年6月2日 下午11:12:24
* @Version V1.0
* @Description: QQ健康
*/
public class QQHealthView extends View {
private Random mRandom = new Random();
private final static float PROPORATION = 1.2f;
private Paint mPaint = new Paint(Paint.ANTI_ALIAS_FLAG);
private Paint mTextPaint = new Paint(Paint.ANTI_ALIAS_FLAG);
/**
* View缺省宽度
*/
private float defaultWidth;
/**
* View缺省高度
*/
private float defaultHeight;
private int mWidth;
private int mHeight;
private boolean isDirty = true;
private RectF tempRect = new RectF();
private Picture mBgPicture;
// 虚线
private float mDashHeight;
private float mDashLength;
private float mDashSpaceLength;
private float mDashMagin;
private DashPathEffect mDashPathEffect;
// 字体大小
private float mTextSize50;
private float mTextSize22;
private float mTextSize18;
private float mTextSize16;
private float mTextSize14;
// 颜色
private int mBgTopColor;
private int mBgBottomColor;
private int mLightBlueColor;
private int mWhiteColor;
private int mGrayColor;
// 百分比
private float mDividerPercent = 0.85f;
private float mDashLinePercent = 0.67f;
// 绘制内容区
private int[] mCurrentColors = {0xFF9A9BF8,0xFF9AA2F7, 0xFF65CCD1,0xFF63D0CD,0xFF68CBD0,0xFF999AF6,0xFF9A9BF8};
private float[] mCurrentPoints = {0,1f/6,2f/6,3f/6,4f/6,5f/6,1};
private float mProgressWidth;
// 边距
private float mMargin6;
private float mMargin10;
private float mMargin13;
public QQHealthView(Context context) {
this(context,null);
}
public QQHealthView(Context context, AttributeSet attrs) {
this(context, attrs,0);
}
public QQHealthView(Context context, AttributeSet attrs, int defStyleAttr) {
super(context, attrs, defStyleAttr);
defaultWidth = generateScaledSize(TypedValue.COMPLEX_UNIT_DIP, 100);
defaultHeight = PROPORATION * defaultWidth;
mProgressWidth = generateScaledSize(TypedValue.COMPLEX_UNIT_DIP, 15);
mDashHeight = generateScaledSize(TypedValue.COMPLEX_UNIT_DIP, 2);
mDashLength = generateScaledSize(TypedValue.COMPLEX_UNIT_DIP, 5);
mDashSpaceLength = generateScaledSize(TypedValue.COMPLEX_UNIT_DIP, 2);
mDashMagin = generateScaledSize(TypedValue.COMPLEX_UNIT_DIP, 20);
mDashPathEffect = new DashPathEffect(new float[]{mDashLength,mDashSpaceLength}, 0);
mTextSize50 = generateScaledSize(TypedValue.COMPLEX_UNIT_SP, 50);
mTextSize22 = generateScaledSize(TypedValue.COMPLEX_UNIT_SP, 22);
mTextSize18 = generateScaledSize(TypedValue.COMPLEX_UNIT_SP, 18);
mTextSize16 = generateScaledSize(TypedValue.COMPLEX_UNIT_SP, 16);
mTextSize14 = generateScaledSize(TypedValue.COMPLEX_UNIT_SP, 14);
mMargin6 = generateScaledSize(TypedValue.COMPLEX_UNIT_DIP, 6);
mMargin10 = generateScaledSize(TypedValue.COMPLEX_UNIT_DIP, 10);
mMargin13 = generateScaledSize(TypedValue.COMPLEX_UNIT_DIP, 13);
// 处理颜色
mBgTopColor = Color.parseColor("#4C5A67");
mBgBottomColor = Color.parseColor("#496980");
mLightBlueColor = Color.parseColor("#63CFEC");
mWhiteColor = Color.WHITE;
mGrayColor = Color.parseColor("#808C96");
setLayerType(LAYER_TYPE_SOFTWARE, mPaint);//使用Picture的话需要不开启硬件加速
}
@Override
protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
mWidth = MeasureSpec.getSize(widthMeasureSpec);
int widthMode = MeasureSpec.getMode(widthMeasureSpec);
if (widthMode == MeasureSpec.UNSPECIFIED) {
mWidth = (int) defaultWidth;
}
mHeight = (int) (mWidth * PROPORATION);
setMeasuredDimension(mWidth, mHeight);
isDirty = true;
}
@Override
protected void onDraw(Canvas canvas) {
preDraw();
drawBg(canvas);
drawCircle(canvas);
drawRecently(canvas);
drawButtomBar(canvas);
}
/**
* 重置参数
*/
private void preDraw() {
mPaint.reset();
mPaint.setAntiAlias(true);// 重置以后不要忘了重新设置抗锯齿,否则无抗锯齿功能
mTextPaint.reset();
mTextPaint.setAntiAlias(true);
}
/**
* 绘制背景
* @param canvas
*/
private void drawBg(Canvas canvas) {
// 如果需要重新创建Picture
if (isDirty) {
// 开始用Picture录制
mBgPicture = new Picture();
Canvas bgCanvas = mBgPicture.beginRecording(mWidth, mHeight);
// 上部占高度 0.85,下部占0.15
float yDivider = mHeight * mDividerPercent;
// 绘制上面背景
mPaint.setColor(mBgTopColor);
bgCanvas.drawRect(0, 0, mWidth, yDivider, mPaint);
// 绘制下面背景
mPaint.setColor(mBgBottomColor);
bgCanvas.drawRect(0, yDivider, mWidth, mHeight, mPaint);
// 绘制虚线
mPaint.setColor(mGrayColor);
mPaint.setStrokeWidth(mDashHeight);
float yDash = mHeight * mDashLinePercent;
mPaint.setPathEffect(mDashPathEffect);
bgCanvas.drawLine(mDashMagin, yDash, mWidth - mDashMagin, yDash, mPaint);
mPaint.setPathEffect(null);
// 裁剪四角
mPaint.setXfermode(new PorterDuffXfermode(Mode.DST_OUT));
bgCanvas.drawPath(getClipPath(), mPaint);
mPaint.setXfermode(null);
// 结束录制
mBgPicture.endRecording();
isDirty = false;
}
// 绘制录制的内容到Canvas
mBgPicture.draw(canvas);
}
/**
* 绘制最近7天进度
* @param canvas
*/
private void drawRecently(Canvas canvas) {
// 绘制虚线上的文字
mTextPaint.setColor(mGrayColor);
mTextPaint.setTextSize(mTextSize16);
mTextPaint.setTextAlign(Align.LEFT);
canvas.drawText("最近7天", mDashMagin, mDashLinePercent * mHeight - mMargin13, mTextPaint);
mTextPaint.setTextAlign(Align.RIGHT);
canvas.drawText("平均9977步/天", mWidth - mDashMagin, mDashLinePercent * mHeight - mMargin13, mTextPaint);
// 绘制柱状图和文字
float itemLength = (mWidth - mDashMagin * 2) / 7;
float startX = 0;
float startY = 0;
mTextPaint.setColor(Color.WHITE);
mTextPaint.setTextSize(mTextSize16);
mTextPaint.setTextAlign(Align.CENTER);
mPaint.setStyle(Style.FILL);
mPaint.setStrokeCap(Cap.ROUND);
mPaint.setStrokeWidth(mProgressWidth);
mPaint.setColor(mLightBlueColor);
float textHeight = getTextHeight(mTextPaint);
float textY = mDividerPercent * mHeight - mMargin13;
startY = textY - textHeight - mMargin13;
for (int i = 0; i < 7; i++) {
startX = mDashMagin + itemLength / 2 + i * itemLength;
canvas.drawText(i +"日", startX, textY, mTextPaint);
canvas.drawLine(startX, startY, startX, startY - (mRandom.nextInt(25)+ 25), mPaint);
}
}
/**
* 绘制今天的进度
* @param canvas
*/
private void drawCircle(Canvas canvas) {
// 确定圆心及半径
float circleRadius = getHeight() * 0.5f * 0.5f;
float centerX = getWidth() /2;
float centerY = circleRadius + mDashMagin + mProgressWidth / 2;
// 绘制圆环
SweepGradient sweepGradient = new SweepGradient(centerX, centerY, mCurrentColors , mCurrentPoints);
tempRect.set(centerX - circleRadius, centerY - circleRadius, centerX + circleRadius, centerY + circleRadius);
mPaint.setStrokeWidth(mProgressWidth);
mPaint.setStyle(Style.STROKE);
mPaint.setStrokeCap(Cap.ROUND);
mPaint.setShader(sweepGradient);
canvas.drawArc(tempRect, 120, 300, false, mPaint);
mPaint.setShader(null);
// 绘制圆环内文字
mTextPaint.setTextAlign(Align.CENTER);
mTextPaint.setTextSize(mTextSize50);
mTextPaint.setColor(mWhiteColor);
float centerTextHeight = getTextHeight(mTextPaint);
canvas.drawText("5599",centerX , centerY + getTextYOffset(mTextPaint), mTextPaint);
// 绘制圆环内数字上下的文字
mTextPaint.setTextSize(mTextSize18);
mTextPaint.setColor(mGrayColor);
// float currentTextHeight = getTextHeight(mTextPaint);
canvas.drawText("截止22:34已走", centerX, centerY - centerTextHeight / 2 - mMargin10, mTextPaint);
canvas.drawText("好友平均239步", centerX, centerY + centerTextHeight / 2 + mMargin10, mTextPaint);
// 绘制圆环下文字
mTextPaint.setTextSize(mTextSize22);
mTextPaint.setColor(mWhiteColor);
float textWidth = mTextPaint.measureText("67");
float bottomTextY = centerY + circleRadius + mProgressWidth + getTextYOffset(mTextPaint);
canvas.drawText("67", centerX, bottomTextY , mTextPaint);
mTextPaint.setTextAlign(Align.RIGHT);
mTextPaint.setTextSize(mTextSize18);
canvas.drawText("第", centerX - mMargin10 - textWidth / 2, bottomTextY , mTextPaint);
mTextPaint.setTextAlign(Align.LEFT);
mTextPaint.setTextSize(mTextSize18);
canvas.drawText("天", centerX + mMargin10 + textWidth / 2, bottomTextY , mTextPaint);
}
/**
* 绘制底部
* @param canvas
*/
private void drawButtomBar(Canvas canvas) {
mTextPaint.setColor(mWhiteColor);
mTextPaint.setTextSize(mTextSize18);
float textY = 0.925f * mHeight + getTextYOffset(mTextPaint);
// 左侧
mTextPaint.setTextAlign(Align.LEFT);
canvas.drawText("这是被隐藏的内容", mDashMagin , textY , mTextPaint);
// 右侧
mTextPaint.setTextAlign(Align.RIGHT);
canvas.drawText("查看 > ", mWidth - mDashMagin , textY , mTextPaint);
}
/**
* 获取绘制文字的高度
* @param paint 画笔
* @return 文字高度
*/
private float getTextHeight(Paint paint) {
FontMetrics fontMetrics = paint.getFontMetrics();
return fontMetrics.bottom - fontMetrics.top;
}
/**
* 根据相应的类型和值转化为缩放后的值(dp、sp等到px)
* @param unit 类型
* @param value 值
* @return 转化后的值
*/
private float generateScaledSize(int unit, float value) {
return TypedValue.applyDimension(unit, value, getResources().getDisplayMetrics());
}
/**
* 获取绘制文字在指定坐标中心时候y方向上应有的偏移值
* @param paint 画笔
* @return y的偏移值
*/
private float getTextYOffset(Paint paint) {
FontMetrics fontMetrics = paint.getFontMetrics();
return (fontMetrics.descent - fontMetrics.ascent) / 4;
}
/*-----------------------------------------裁剪四角代码区域,可通用-------------------------------------*/
/********************************************************裁剪圆角方法区***********************************************************/
private RectF mClipBgRectF = new RectF();
private RectF mClipCornerRectF = new RectF();
private float radius[] = new float[]{
10,10,10,10,10,10,10,10
};
private Path getClipPath() {
mClipBgRectF.set(
0 + getPaddingLeft()
, 0 + getPaddingTop()
, getWidth() - getPaddingRight()
, getHeight() - getPaddingBottom());
Path clipPath =new Path();
//左上角
clipPath.moveTo(mClipBgRectF.left, mClipBgRectF.top);
clipPath.lineTo(mClipBgRectF.left + radius[0], mClipBgRectF.top);
mClipCornerRectF.set(
mClipBgRectF.left
, mClipBgRectF.top
, mClipBgRectF.left + radius[0] * 2
, mClipBgRectF.top + radius[1] * 2);
clipPath.arcTo(mClipCornerRectF, 270, -90);
clipPath.close();
//右上角
clipPath.moveTo(mClipBgRectF.right, mClipBgRectF.top);
clipPath.lineTo(mClipBgRectF.right, mClipBgRectF.top + radius[3]);
mClipCornerRectF.set(
mClipBgRectF.right - radius[2] * 2
, mClipBgRectF.top, mClipBgRectF.right
, mClipBgRectF.top + radius[3] * 2);
clipPath.arcTo(mClipCornerRectF, 0, -90);
clipPath.close();
//右下角
clipPath.moveTo(mClipBgRectF.right, mClipBgRectF.bottom);
clipPath.lineTo(mClipBgRectF.right - radius[4], mClipBgRectF.bottom);
mClipCornerRectF.set(
mClipBgRectF.right - radius[4] * 2
, mClipBgRectF.bottom - radius[5] * 2
, mClipBgRectF.right, mClipBgRectF.bottom);
clipPath.arcTo(mClipCornerRectF, 90, -90);
clipPath.close();
//左下角
clipPath.moveTo(mClipBgRectF.left, mClipBgRectF.bottom);
clipPath.lineTo(mClipBgRectF.left, mClipBgRectF.bottom - radius[7]);
mClipCornerRectF.set(
mClipBgRectF.left
, mClipBgRectF.bottom - radius[7] * 2
, mClipBgRectF.left + radius[6] * 2
, mClipBgRectF.bottom);
clipPath.arcTo(mClipCornerRectF, 180, -90);
clipPath.close();
return clipPath;
}
}
|
package com.relaxisapp.relaxis.models;
import com.relaxisapp.relaxis.events.EventDispatcher;
import com.relaxisapp.relaxis.events.SimpleEvent;
public class StressModel extends EventDispatcher {
public static class ChangeEvent extends SimpleEvent {
public static final String STRESS_LEVEL_CHANGED = "stressLevelChanged";
public ChangeEvent(String type) {
super(type);
}
}
private static StressModel instance;
public static StressModel getInstance() {
if (instance == null) {
instance = new StressModel();
}
return instance;
}
private double stressLevel = 0;
public double getStressLevel() {
return stressLevel;
}
public void setStressLevel(double stressLevel) {
this.stressLevel = stressLevel;
notifyChange(ChangeEvent.STRESS_LEVEL_CHANGED);
}
private void notifyChange(String type) {
dispatchEvent(new ChangeEvent(type));
}
}
|
package org.rita.harris.embeddedsystemhomework_termproject.RainFall;
/**
* Created by Harris on 2015/12/13.
*/
import android.util.Log;
import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.select.Elements;
import java.net.URL;
import java.util.ArrayList;
import java.util.HashMap;
public class RainFall_WebDataParse {
Elements Place ;
Elements Observatory;
String UpdateTime = "沒有資料!";
public ArrayList<HashMap<String,String>> Showinfo() throws Exception
{
ArrayList<HashMap<String,String>> list = new ArrayList<HashMap<String,String>>();
Thread Subthread = new Thread(mutiThread);//開一個新的線程,去執行網路連線
Subthread.start();//開始線程
Thread.sleep(1000L);//因為網路連線需要時間,所以需要等去連線的網路線程回來
String RainFall_Place;
String RainFall_Observatory;
/**
* 這裡再將每個地區的名稱,跟觀測站的名稱,還有雨量,給結合起來,放到MAP中
* 總共有467個("td"),所以 (467-3)/29 = 16,3+29*i 是地區名稱 , 29+29*i 是24小時的雨量
* 總共有17個("a"),而第一個是不重要的,所以都是i+1
*/
for(int i = 0 ;i < 16; i++)
{
HashMap<String, String> info = new HashMap<String, String>(); // 每個裡面都有一個 key 和一個 value ,而 key 是獨一無二的絕不重複,重複會覆蓋裡面原本的值
RainFall_Place = Place.get(3+29*i).text();
RainFall_Observatory = Observatory.get(i+1).text();
info.put("所在鄉鎮&觀測站", "所在鄉鎮 : " + RainFall_Place + "\n\t 觀測站 : " + RainFall_Observatory);
info.put("二十四小時累積雨量", "二十四小時累積雨量 : " + Place.get(29+29*i).text()+" 毫米");
list.add(info);//把每筆資料分成三部分,放到Arraylist裡面
}
return list;
}
//用Runnable包起來子線程要做的事情 -- 網路連線
private Runnable mutiThread = new Runnable(){
public void run(){
try {
URL url = new URL("http://www.cwb.gov.tw/V7/observe/rainfall/Rain_Hr/3.htm");
Document xmlDoc = Jsoup.parse(url, 3000);
Place = xmlDoc.select("td");//在網頁原始碼裡面,標籤是td的都會被抓出來
Observatory = xmlDoc.select("a");//在網頁原始碼裡面,標籤是a的都會被抓出來
UpdateTime = Place.get(2).text();//設置更新時間
}
catch (Exception e)
{
Log.v("Internet connectionless", e.toString());
}
}
};
public String getUpdateTime()
{
return UpdateTime;
}
}
|
package org.koreader.launcher.helper;
import android.content.Context;
import android.os.Handler;
import org.koreader.launcher.Logger;
/*
Base class for application helpers.
Intended for long-term things, like wifi, clipboard or power facilities.
We do everything based on the application context and implement our own
getApplicationContext() and runOnUiThread().
Ui things need to be done on the activity context. Please do not hold a reference
of an activity on your subclass. Instead just receive an activity as a parameter
of your methods. */
abstract class BaseHelper {
private final Handler handler;
private final Context context;
private final String tag;
public BaseHelper(Context context) {
// get a reference to the application context, which is already pre-leaked.
this.context = context.getApplicationContext();
// the name for this class and subclasses that extend from it.
this.tag = this.getClass().getSimpleName();
/* use a handler to execute runnables on the main thread.
This is useful to do UI things, because the main thread
is the only that can touch the UI thread. */
this.handler = new Handler(this.context.getMainLooper());
// for debugging
Logger.d(tag, "Starting");
}
Context getApplicationContext() {
// returns the context of the application
return context;
}
String getTag() {
// returns the name of the class
return tag;
}
void runOnUiThread(Runnable runnable) {
// forward the runnable to the main thread
handler.post(runnable);
}
}
|
package com.example.dolly0920.week8;
public enum CancelType {
ALL,
LATEST
}
|
package com.company;
import com.company.line.DDALineDrawer;
import com.company.line.Line;
import com.company.line.LineDrawer;
import com.company.pixel.BufferedImagePixelDrawer;
import com.company.pixel.PixelDrawer;
import com.company.polygon.PolygonDrawerLine;
import com.company.polygon.RegularPolygon;
import com.company.polygon.drawer.RegularPolygonDrawer;
import com.company.screen_conversion.RealPoint;
import com.company.screen_conversion.ScreenConverter;
import com.company.screen_conversion.ScreenPoint;
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
import java.awt.image.BufferedImage;
import java.util.ArrayList;
import java.util.List;
public class DrawPanel extends JPanel implements MouseMotionListener, MouseListener, MouseWheelListener {
private ScreenConverter sc = new ScreenConverter(-2, 2, 4, 4, 800, 600);
private Line xAxis = new Line(-1, 0, 1, 0);
private Line yAxis = new Line(0, -1, 0, 1);
private TextField radiusTextField = new TextField("1");
private TextField countSidesTextField = new TextField("3");
private TextField angleTextField = new TextField("90");
private Button drawPolygonButton = new Button("Рисовать");
private ArrayList<Line> allLines = new ArrayList<>();
private List<RegularPolygon> allPolygons = new ArrayList<>();
private RealPoint centerOfNewPolygon = null;
private Line currentNewLine = null;
public DrawPanel() {
this.add(radiusTextField);
this.add(countSidesTextField);
this.add(angleTextField);
this.add(drawPolygonButton);
/*drawPolygonButton.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent actionEvent) {
if (centerOfNewPolygon != null && )
}
});*/
this.addMouseMotionListener(this);
this.addMouseListener(this);
this.addMouseWheelListener(this);
}
@Override
public void paint(Graphics g) {
sc.setScreenWidth(getWidth());
sc.setScreenHeight(getHeight());
BufferedImage bi = new BufferedImage(getWidth(), getHeight(), BufferedImage.TYPE_INT_RGB);
Graphics gr = bi.createGraphics();
gr.setColor(new Color(255, 255, 255));
gr.fillRect(0, 0, getWidth(), getHeight());
gr.dispose();
PixelDrawer pd = (PixelDrawer) new BufferedImagePixelDrawer(bi);
LineDrawer ld = new DDALineDrawer(pd);
drawLine(ld, xAxis);
drawLine(ld, yAxis);
for (Line l : allLines) {
drawLine(ld, l);
}
if (currentNewLine != null) {
drawLine(ld, currentNewLine);
}
RegularPolygonDrawer rpd = new PolygonDrawerLine(pd);
rpd.setLineDrawer(ld);
//RegularPolygon pol = new RegularPolygon(new RealPoint(0, 0), 1, 5, 1);
drawAllPolygons(rpd);
g.drawImage(bi, 0, 0, null);
}
private RegularPolygon p = null;
public void drawAllPolygons(RegularPolygonDrawer rpd) {
drawPolygon(rpd);
if (p != null) drawRegularPolygon(p, rpd);
}
private void drawLine(LineDrawer ld, Line l) {
ld.drawLine(sc.rts(l.getP1()), sc.rts(l.getP2()));
}
public void drawPolygon(RegularPolygonDrawer rpd) {
drawPolygonButton.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent actionEvent) {
double radius = Double.parseDouble(radiusTextField.getText());
int count = Integer.parseInt(countSidesTextField.getText());
double angleGradus = Double.parseDouble(angleTextField.getText());
if (centerOfNewPolygon != null) {
p = new RegularPolygon(centerOfNewPolygon, radius, count, angleGradus * Math.PI / 180);
centerOfNewPolygon = null;
} else {
System.out.println("null");
}
}
});
}
private void drawRegularPolygon(RegularPolygon pol, RegularPolygonDrawer rpd) {
RealPoint[] rPoints = rpd.getVertexes(pol);
ScreenPoint[] sPoints = new ScreenPoint[rPoints.length];
for (int i = 0; i < sPoints.length; i++) {
sPoints[i] = sc.rts(rPoints[i]);
}
rpd.drawPolygon(sPoints);
}
private ScreenPoint lastPosition = null;
@Override
public void mouseDragged(MouseEvent mouseEvent) {
ScreenPoint currentPosition = new ScreenPoint(mouseEvent.getX(), mouseEvent.getY());
if (lastPosition != null) {
ScreenPoint deltaScreen = new ScreenPoint(currentPosition.getX() - lastPosition.getX(), currentPosition.getY() - lastPosition.getY());
RealPoint deltaReal = sc.s2r(deltaScreen);
RealPoint zeroReal = sc.s2r(new ScreenPoint(0, 0));
RealPoint vector = new RealPoint(deltaReal.getX() - zeroReal.getX(), deltaReal.getY() - zeroReal.getY());
sc.setCornerX(sc.getCornerX() - vector.getX());
sc.setCornerY(sc.getCornerY() - vector.getY());
lastPosition = currentPosition;
}
if (currentNewLine != null) {
currentNewLine.setP2(sc.s2r(currentPosition));
}
repaint();
}
@Override
public void mouseMoved(MouseEvent mouseEvent) {
}
@Override
public void mouseClicked(MouseEvent mouseEvent) {
if (mouseEvent.getButton() == MouseEvent.BUTTON1)
centerOfNewPolygon = sc.s2r(new ScreenPoint(mouseEvent.getX(), mouseEvent.getY()));
repaint();
}
@Override
public void mousePressed(MouseEvent mouseEvent) {
if (mouseEvent.getButton() == MouseEvent.BUTTON3) {
lastPosition = new ScreenPoint(mouseEvent.getX(), mouseEvent.getY());
} else if (mouseEvent.getButton() == MouseEvent.BUTTON1) {
currentNewLine = new Line(sc.s2r(new ScreenPoint(mouseEvent.getX(), mouseEvent.getY())), sc.s2r(new ScreenPoint(mouseEvent.getX(), mouseEvent.getY())));
}
repaint();
}
@Override
public void mouseReleased(MouseEvent mouseEvent) {
if (mouseEvent.getButton() == MouseEvent.BUTTON3) {
lastPosition = null;
} else if (mouseEvent.getButton() == mouseEvent.BUTTON1) {
allLines.add(currentNewLine);
currentNewLine = null;
}
repaint();
}
@Override
public void mouseEntered(MouseEvent mouseEvent) {
}
@Override
public void mouseExited(MouseEvent mouseEvent) {
}
@Override
public void mouseWheelMoved(MouseWheelEvent mouseWheelEvent) {
int clicks = mouseWheelEvent.getWheelRotation();
double scale = 1;
double coef = clicks < 0 ? 1.1 : 0.9;
for (int i = 0; i < Math.abs(clicks); i++) {
scale *= coef;
}
sc.setRealWidth(sc.getRealWidth() * scale);
sc.setRealHeight(sc.getRealHeight() * scale);
repaint();
}
}
|
package alvin.basic;
import alvin.basic.entities.Person;
import alvin.basic.entities.Student;
import alvin.configs.TestSupport;
import org.junit.Test;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.time.LocalDateTime;
import java.time.ZoneOffset;
import static org.hamcrest.Matchers.is;
import static org.hamcrest.Matchers.notNullValue;
import static org.junit.Assert.assertThat;
public class TableTest extends TestSupport {
private static final Logger LOGGER = LoggerFactory.getLogger(TableTest.class);
@Test
public void test_save_person() {
Person expectedPerson = createPerson();
LOGGER.info("before persist: {}", expectedPerson);
em.getTransaction().begin();
try {
em.persist(expectedPerson);
em.getTransaction().commit();
} catch (Exception e) {
em.getTransaction().rollback();
throw e;
}
assertThat(expectedPerson.getId(), is(notNullValue()));
LOGGER.info("after persist: {}", expectedPerson);
em.clear();
Person actualPerson = em.find(Person.class, expectedPerson.getId());
LOGGER.info("after load: {}", actualPerson);
assertThat(expectedPerson.toString(), is(actualPerson.toString()));
}
private Person createPerson() {
Person person = new Person();
person.setName("Alvin");
person.setGender("M");
person.setEmail("alvin@fakeaddr.com");
person.setTelephone("13999999999");
person.setBirthday(LocalDateTime.of(1981, 3, 17, 0, 0).atOffset(ZoneOffset.UTC).toLocalDateTime());
return person;
}
@Test
public void test_second_table() throws Exception {
Student expectedStudent = createStudent();
LOGGER.info("before persist: {}", expectedStudent);
em.getTransaction().begin();
try {
em.persist(expectedStudent);
em.getTransaction().commit();
} catch (Exception e) {
em.getTransaction().rollback();
throw e;
}
assertThat(expectedStudent.getId(), is(notNullValue()));
LOGGER.info("after persist: {}", expectedStudent);
em.clear();
Student actualStudent = em.find(Student.class, expectedStudent.getId());
LOGGER.info("after load: {}", actualStudent);
assertThat(actualStudent.toString(), is(actualStudent.toString()));
}
private Student createStudent() {
Student student = new Student();
student.setSno("001");
student.setName("Alvin");
student.setGender("M");
student.setTelephone("13991999999");
student.setBirthday(LocalDateTime.of(1981, 3, 17, 0, 0).atOffset(ZoneOffset.UTC).toLocalDateTime());
student.setAddress("Xi'an Shannxi China");
student.setEmail("alvin@fake.com");
student.setQq("19888");
return student;
}
@Override
protected String[] getTruncateTables() {
return new String[]{"person", "student", "student_detail"};
}
}
|
import java.util.*;
class ReadInts
{
Scanner scan = new Scanner(System.in);
int[] readAtYourRisk(int num)
{
System.out.println("readAtYourRisk ");
int[] retVals = new int[num];
for (int i=0; i < num; i++)
{
// An InputMismatchException is thrown if you enter
// in a non-integer
retVals[i] = scan.nextInt();
}
return retVals;
}
int[] readCarefully(int num)
{
System.out.println("readCarefully ");
int[] retVals = new int[num];
for (int i=0; i < num; i++)
{
boolean unread = true;
while(unread)
{
try
{
// An InputMismatchException is thrown if you enter
// in a non-integer
retVals[i] = scan.nextInt();
unread = false;
}
catch (InputMismatchException e)
{
System.out.println("That Last number was bad ... try again");
scan.next(); // Throw away bad int
}
}
}
return retVals;
}
void dump(int[] vals)
{
System.out.println("dump *****************************");
for (int i=0; i < vals.length; i++)
System.out.println(vals[i]+ " ");
System.out.println();
}
public static void main(String[] args)
{
ReadInts rd = new ReadInts();
int[] vals = rd.readAtYourRisk(5);
rd.dump(vals);
vals = rd.readCarefully(5);
rd.dump(vals);
boolean done = false;
System.out.println("readAtYourRisk with main try ... catch protection");
while (!done)
{
try
{
vals = rd.readAtYourRisk(5);
rd.dump(vals);
done = true;
}
catch (InputMismatchException e)
{
System.out.println("Your last attempt failed ... Start over");
rd.scan.next(); // Throw away bad int
}
}
}
}
|
package com.healthyteam.android.healthylifers.Domain;
import android.graphics.Bitmap;
import android.net.Uri;
import android.support.annotation.NonNull;
import android.util.Log;
import com.google.android.gms.tasks.OnFailureListener;
import com.google.android.gms.tasks.OnSuccessListener;
import com.google.android.gms.tasks.Task;
import com.google.firebase.database.DataSnapshot;
import com.google.firebase.database.DatabaseError;
import com.google.firebase.database.DatabaseReference;
import com.google.firebase.database.FirebaseDatabase;
import com.google.firebase.database.ValueEventListener;
import com.google.firebase.storage.FirebaseStorage;
import com.google.firebase.storage.StorageReference;
import com.google.firebase.storage.UploadTask;
import com.healthyteam.android.healthylifers.Data.CommentData;
import com.healthyteam.android.healthylifers.Data.LocationData;
import com.healthyteam.android.healthylifers.Data.OnUploadDataListener;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.LinkedList;
import java.util.List;
public class UserLocation implements DBReference {
public static enum Category {
EVENT, HEALTHYFOOD, COURT, FITNESSCENTER
}
public static enum Rate {
NONE, LIKE, DISLIKE
}
private LocationData Data;
private List<Comment> Comments;
//ako je neophodno da se dovlace svi objekti komentara iz baze, onda atribut ispod nije potreban
private Rate UserRate;
private User Author;
public UserLocation(){
Data=new LocationData();
Comments = new LinkedList<>();
}
//region private funciton
private String getDate() {
Date c = Calendar.getInstance().getTime();
SimpleDateFormat df = new SimpleDateFormat("dd-MM-yyyy");
return df.format(c);
}
private int getStringIndex(String str, List<String> strList){
for(int i=0;i<strList.size();i++) {
if (strList.get(i).equals(str))
return i;
}
return -1;
}
public int getCommentIndex(String uid){
if(Comments==null)
return -1;
for(int i=0; i<Comments.size();i++){
if(Comments.get(i).getUID().equals(uid))
return i;
}
return -1;
}
//endregion
//region Methods
public void addComment(String text, User user) {
final Comment comment = new Comment();
FirebaseDatabase database = FirebaseDatabase.getInstance();
String key = database.getReference(Constants.CommentsNode).push().getKey();
comment.setUID(key);
comment.setText(text);
comment.setCreator(user);
comment.Save(new OnSuccessListener() {
@Override
public void onSuccess(Object o) {
Data.CommentsIds.add(comment.getUID());
Comments.add(comment);
Save(null);
}
});
}
public void removeComment(final Comment comment) //Comment comment arg is element of Comments list
{
FirebaseDatabase.getInstance().getReference().child(Constants.CommentsNode).child(comment.getUID())
.removeValue().addOnSuccessListener(new OnSuccessListener<Void>() {
@Override
public void onSuccess(Void aVoid) {
getCommentsIds().remove(Comments.indexOf(comment));
Save(null);
Comments.remove(comment);
}
});
Comments.remove(comment);
}
public void likeThis(String byUserUID) {
if(this.getUserRate(byUserUID)==Rate.LIKE)
return;
int ind = getStringIndex(byUserUID,Data.DislikedBy);
if(ind > -1)
Data.DislikedBy.remove(ind);
this.UserRate=Rate.LIKE;
Data.likedBy.add(byUserUID);
Save(null);
}
public void dislikeThis(String byUserUID){
if(this.getUserRate(byUserUID)==Rate.DISLIKE)
return;
int ind = getStringIndex(byUserUID,Data.likedBy);
if(ind > -1)
Data.likedBy.remove(ind);
this.UserRate=Rate.DISLIKE;
Data.DislikedBy.add(byUserUID);
Save(null);
}
public Boolean isLiked(){
if(this.UserRate == Rate.LIKE)
return true;
return false;
}
public Boolean isDisliked(){
if(this.UserRate==Rate.DISLIKE)
return true;
return false;
}
//endregion
//region Getter
public String getImageUrl() {
return Data.imageURL;
}
public String getUID(){
return Data.UID;
}
public String getName() {
return Data.Name;
}
public String getDescripition() {
return Data.Description;
}
public List<String> getTagList() {
return Data.Tags;
}
public String getTagsString(){
String result="";
if(getTagList().size()>0) {
int i;
for (i = 0; i < getTagList().size() - 1; i++) {
result += getTagList().get(i) + ", ";
}
result += getTagList().get(i);
}
return result;
}
public Integer getLikeCount() {
return Data.likedBy.size();
}
public String getLikeCountString(){return String.valueOf(Data.likedBy.size());}
public Integer getDislikeCount() {
return Data.DislikedBy.size();
}
public String getDislikeCountString(){return String.valueOf(Data.DislikedBy.size());}
public Double getLat() {
return Data.Latitude;
}
public Double getLon() {
return Data.Longitude;
}
public String getDateAdded() {
return Data.DateAdded;
}
public Category getCategory() {
return Category.values()[Data.Category];
}
public Rate getUserRate(String uid){
if(UserRate!=null)
return UserRate;
UserRate= Rate.NONE;
if(getStringIndex(uid,Data.likedBy)!=-1)
UserRate = Rate.LIKE;
if(getStringIndex(uid,Data.DislikedBy)!=-1)
UserRate = Rate.DISLIKE;
return UserRate;
}
public List<String> getCommentsIds(){
return Data.CommentsIds;
}
public Integer getCommentCount() {
return Data.CommentsIds.size();
}
public String getAuthorUID(){
return Data.AuthorUID;
}
//endregion
//region Setter
public void setUID(String uid) {
Data.UID=uid;
}
public void setData(LocationData data){
this.Data=data;
}
public void setLocaitonPic(String picURL) {
Data.imageURL = picURL;
}
public void setName(String name) {
Data.Name = name;
}
public void setDescripition(String descripition) {
Data.Description = descripition;
}
public void setDateAdded(String dateAdded) {
Data.DateAdded = dateAdded;
}
public void setTagList(List<String> tagList) {
Data.Tags = tagList;
}
public void setTagListFromString(String Tags){
this.setTagList(new LinkedList<String>());
String[] splitTags = Tags.split("#");
for(int i=1;i<splitTags.length;i++){
this.getTagList().add(splitTags[i]);
}
}
public void setCategory(Integer category) {
Data.Category = category;
}
public void setCategory(Category category){
Data.Category = category.ordinal();
}
public void setUserRate(Rate rate) {
UserRate = rate;
}
public void setLat(Double lat) {
Data.Latitude = lat;
}
public void setLon(Double lon) {
Data.Longitude = lon;
}
public void setCity(String City){
this.Data.City=City;
}
public void setComments(List<Comment> comments) {
Comments = comments;
}
public void setAuthor(User author) {
Author = author;
Data.AuthorUID=author.getUID();
}
//endregion
//region dbFunction
//READ
private List<OnGetObjectListener> authorListners;
public void addGetAuthorListener(OnGetObjectListener listener){
if(authorListners ==null)
authorListners = new LinkedList<>();
if(!authorListners.contains(listener))
authorListners.add(listener);
getAuthor();
}
private void getAuthor() {
if(Author==null) {
Author = new User();
User.getUser(getUID(), new OnGetObjectListener() {
@Override
public void OnSuccess(Object o) {
Author = (User) o;
for (OnGetObjectListener listener : authorListners)
listener.OnSuccess(Author);
}
});
}
else
for (OnGetObjectListener listener : authorListners)
listener.OnSuccess(Author);
}
private List<OnGetListListener> commentsListener;
public void addGetCommentsListener(OnGetListListener listener){
if(commentsListener ==null)
commentsListener = new LinkedList<>();
if(!authorListners.contains(listener))
commentsListener.add(listener);
getComments(listener);
}
private void getComments(OnGetListListener listener)
{
if(Comments==null) {
Comments = new ArrayList<>();
for (final String commentId : this.getCommentsIds()) {
DatabaseReference CommentRef = getDatabase().child(Constants.LocationsNode).child(commentId);
CommentRef.addValueEventListener(new ValueEventListener() {
@Override
public void onDataChange(@NonNull DataSnapshot dataSnapshot) {
Comment comment = new Comment();
comment.setData(dataSnapshot.getValue(CommentData.class));
comment.setUID(dataSnapshot.getKey());
int commentInd = getCommentIndex(comment.getUID());
if (commentInd != -1) {
Comments.set(commentInd, comment);
for (OnGetListListener listener : commentsListener)
listener.onChildChange(Comments, commentInd);
} else {
Comments.add(comment);
for (OnGetListListener listener : commentsListener)
listener.onChildAdded(Comments, commentInd);
}
if (Comments.size() == getCommentCount()) {
for (OnGetListListener listener : commentsListener)
listener.onListLoaded(Comments);
}
}
@Override
public void onCancelled(@NonNull DatabaseError databaseError) {
}
});
}
}
else
listener.onListLoaded(Comments);
}
//WRITE
public void Save(final OnSuccessListener listener){
if(getUID()==null){
String key =getDatabase().child(Constants.LocationsNode).push().getKey();
setUID(key);
}
try {
getDatabase().child(Constants.LocationsNode).child(getUID()).setValue(Data).addOnFailureListener(new OnFailureListener() {
@Override
public void onFailure(@NonNull Exception e) {
Log.println(Log.WARN, "Database:", e.getMessage());
}
}).addOnSuccessListener(new OnSuccessListener<Void>() {
@Override
public void onSuccess(Void aVoid) {
Log.println(Log.WARN, "Database: ", "Success");
if(listener!=null)
listener.onSuccess(aVoid);
}
});
}
catch(Exception e){
Log.println(Log.ERROR, "Database:", e.getMessage());
}
}
public boolean UpdatePicture(final Uri ImageUri, final OnUploadDataListener listener) {
listener.onStart();
if (ImageUri != null) {
StorageReference fileReference = FirebaseStorage.getInstance().
getReference("uploads").
child(String.valueOf( getUID()));
fileReference.putFile(ImageUri)
.addOnSuccessListener(new OnSuccessListener<UploadTask.TaskSnapshot>() {
@Override
public void onSuccess(UploadTask.TaskSnapshot taskSnapshot) {
if(taskSnapshot.getMetadata().getReference()!=null) {
Task<Uri> result = taskSnapshot.getMetadata().getReference().getDownloadUrl();
result.addOnSuccessListener(new OnSuccessListener<Uri>() {
@Override
public void onSuccess(Uri uri) {
setLocaitonPic(uri.toString());
Save(null);
listener.onSuccess();
}
});
}
}
})
.addOnFailureListener(new OnFailureListener() {
@Override
public void onFailure(@NonNull Exception e) {
listener.onFailed(e);
}
});
return true;
}
else {
return false;
}
}
//UPDATE
//DELETE
//endregion
private static DatabaseReference mDatabase;
private static DatabaseReference getDatabase() {
if (mDatabase == null)
mDatabase = FirebaseDatabase.getInstance().getReference();
return mDatabase;
}
}
|
package com.zc.pivas.synresult.service;
import com.zc.pivas.synresult.bean.CheckOrderStatusRespon;
import com.zc.pivas.synresult.bean.SetFymxDataReq;
import com.zc.pivas.synresult.bean.SetFymxDataResp;
import org.codehaus.jettison.json.JSONObject;
import java.util.List;
/**
* Restful接口
*
* @author kunkka
* @version 1.0
*/
public interface SendToRestful {
/**
* 检查医嘱状态
*
* @return
*/
List<CheckOrderStatusRespon> checkOrderStatus(List<JSONObject> bottleInfoList)
throws Exception;
/**
* 配置费收费
*
* @return
*/
SetFymxDataResp setFymxData(SetFymxDataReq req)
throws Exception;
}
|
package com.zl.service;
import com.zl.pojo.CategoryDO;
import com.zl.pojo.GardenStuffDO;
import com.zl.pojo.GardenStuffDTO;
import com.zl.util.AjaxPutPage;
import com.zl.util.AjaxResultPage;
import com.zl.util.MessageException;
import java.util.List;
public interface GardenStuffService {
/**
* @Description: 返回果蔬列表[可带条件]
* @Param: [ajaxPutPage]
* @return: java.util.List<com.zl.pojo.GardenStuffDTO>
* @Author: ZhuLin
* @Date: 2019/1/22
*/
AjaxResultPage<GardenStuffDTO> listGardenStuff(AjaxPutPage<GardenStuffDTO> ajaxPutPage);
/**
* @Description: 返回果蔬总数
* @Param: []
* @return: java.lang.Integer
* @Author: ZhuLin
* @Date: 2019/2/13
*/
Integer getGardenStuffCount();
/**
* @Description: 返回所有果蔬类别
* @Param: []
* @return: java.util.List<com.zl.pojo.CategoryDO>
* @Author: ZhuLin
* @Date: 2019/1/22
*/
List<CategoryDO> listCategory(AjaxPutPage<CategoryDO> ajaxPutPage);
/**
* @Description: 添加果蔬
* @Param: [gardenStuffDO]
* @return: void
* @date: 2019/1/27 20:19
*/
void insertGardenStuff(GardenStuffDO gardenStuffDO) throws MessageException;
/**
* @Description: 根据农民id删除所属农民的所有果蔬[删除农民时执行]
* @Param: [id]
* @return: void
* @date: 2019/1/27 20:35
*/
void deleteGardenStuffByPeasantid(String id) throws MessageException;
/**
* @Description: 修改果蔬信息
* @Param: [gardenStuffDO]
* @return: void
* @Author: ZhuLin
* @Date: 2019/1/29
*/
void updateGardenStuff(GardenStuffDO gardenStuffDO) throws MessageException;
/**
* @Description: 删除果蔬信息[根据果蔬id删除其附属品信息]
* @Param: [gardenStuffDO]
* @return: void
* @Author: ZhuLin
* @Date: 2019/1/29
*/
void deleteGardenStuff(String id) throws MessageException;
/**
* @Description: 批量删除果蔬[根据果蔬id删除其附属品信息]
* @Param: [deleteId]
* @return: void
* @date: 2019/2/4 13:39
*/
void batchesDelGardenStuff(List<String> deleteId) throws MessageException;
/**
* @Description: 修改果蔬类别信息[同时修改果蔬类别信息记录]
* @Param: [categoryDO]
* @return: void
* @Author: ZhuLin
* @Date: 2019/1/29
*/
void updateCategory(CategoryDO categoryDO) throws MessageException;
/**
* @Description: 添加果蔬类别
* @Param: [categoryDO]
* @return: void
* @Author: ZhuLin
* @Date: 2019/1/30
*/
void insertCategory(CategoryDO categoryDO) throws MessageException;
/**
* @Description: 批量删除果蔬类别
* @Param: [deleteId]
* @return: void
* @date: 2019/2/4 13:39
*/
void batchesDelCategoey(List<Integer> deleteId) throws MessageException;
/**
* @Description: 库存验证
* @Param: [gardenstuffId, gardenstuffNumber]
* @return: boolean
* @date: 2019/5/14 11:09
*/
boolean gardenstuffNumberCheck(String gardenstuffId,Integer gardenstuffNumber);
}
|
package main;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Set;
import java.util.Stack;
import java.util.TreeSet;
public class Solver {
public CSP problem;
private HashMap<String, Object> assignation;
HashSet<HashMap<String, Object>> solutions;
public Solver(CSP p) {
problem = p;
assignation = new HashMap<String, Object>();
this.solutions = new HashSet<HashMap<String, Object>>();
this.varDom.push(p.getDom());
}
// retourne une solution s'il en existe une, null sinon
public HashMap<String, Object> searchSolution() {
return this.backtrack();
//return this.fowardChecking();
}
private boolean isOk(String var) {
return this.isConsistant(var);
}
private ArrayList<Object> createTupleFromAssignation(ArrayList<String> varOfContraint) {
ArrayList<Object> list = new ArrayList<Object>();
for (String var : varOfContraint) {
list.add(this.assignation.get(var));
}
return list;
}
private boolean isConsistant(String varAffected) {
for (ConstraintAbstract c : this.problem.getConstraintsContaining(varAffected)) { // pour toutes les contraintes concernées
/*if (!this.contrainteEstVerifiee(varAffected, c)) { // Si contrainte validée
return false;
}*/
ArrayList<Object> tuple = this.createTupleFromAssignation(c.getVariables());
if (!c.constraintIsRespectee(tuple)) {
return false;
}
}
return true;
}
private HashMap<String, Object> backtrack() {
if (this.assignation.size() == this.problem.getVarNumber()) {
return this.assignation;
}
// On choisit une variable non affectuée
String chosenVar = this.chooseVar(this.problem.getVars(), this.assignation.keySet());
//System.out.println("On choisit la variable "+chosenVar);
for (Object val : this.tri(this.problem.getDom(chosenVar))){
this.assignation.put(chosenVar, val);
//System.out.println("On asigne "+chosenVar+" = "+val+";");
if (this.isConsistant(chosenVar)) { // Si contrainte validée
HashMap<String, Object> affect = backtrack();
if (affect != null && affect.size() == this.problem.getVarNumber())
return affect;
} else {
//System.out.println("Pas vérifié :(");
this.assignation.remove(chosenVar);
}
}
return null;
}
private boolean propager(String var) {
@SuppressWarnings("unchecked")
HashMap<String,TreeSet<Object>> oldDom = (HashMap<String, TreeSet<Object>>) this.varDom.firstElement().clone();
for (ConstraintAbstract c : this.problem.getConstraintsContaining(var)) {
for (String v : c.getVariables()) {
oldDom.get(v).remove(var);
if (oldDom.get(v).isEmpty()) {
return false;
}
}
}
this.varDom.push(oldDom);
return this.isOk(var);
}
private Stack<HashMap<String,TreeSet<Object>>> varDom = new Stack<HashMap<String,TreeSet<Object>>>();
public HashMap<String, Object> fowardChecking() {
if (this.assignation.size() == this.problem.getVarNumber()) {
return this.assignation;
}
// On choisit une variable non affectuée
String chosenVar = this.chooseVar(this.problem.getVars(), this.assignation.keySet());
//System.out.println("On choisit la variable "+chosenVar);
for (Object val : this.tri(this.problem.getDom(chosenVar))){
this.assignation.put(chosenVar, val);
//System.out.println("On asigne "+chosenVar+" = "+val+";");
if (this.propager(chosenVar)) { // Si contrainte validée
HashMap<String, Object> affect = fowardChecking();
if (affect != null && affect.size() == this.problem.getVarNumber())
return affect;
} else {
//System.out.println("Pas vérifié :(");
this.assignation.remove(chosenVar);
this.varDom.pop();
}
}
return null;
}
private ArrayList<String> getVariablesOrdered(Set<String> variables) {
ArrayList<String> list = new ArrayList<String>();
list.addAll(variables);
final CSP pb = this.problem;
Collections.sort(list, new Comparator<String>() {
@Override
public int compare(String v1, String v2) {
return pb.getConstraintsContaining(v1).size() - pb.getConstraintsContaining(v2).size();
}
});
return list;
}
private String chooseVar(Set<String> allVar, Set<String> assignedVar) {
for (String v : this.getVariablesOrdered(allVar)) {
if (!assignedVar.contains(v)) {
return v;
}
}
return null;
}
private TreeSet<Object> tri(TreeSet<Object> values) {
return values;
}
/**
* @return L'ensemble des solutions
*/
@SuppressWarnings("unchecked")
public HashSet<HashMap<String, Object>> searchAllSolutions() {
if (this.assignation.size() == this.problem.getVarNumber()) {
this.solutions.add((HashMap<String, Object>) this.assignation.clone());
return this.solutions;
}
// On choisit une variable non affectuée
String chosenVar = this.chooseVar(this.problem.getVars(), this.assignation.keySet());
//System.out.println("On choisit la variable "+chosenVar);
for (Object val : this.tri(this.problem.getDom(chosenVar))) {
this.assignation.put(chosenVar, val);
//System.out.println("On asigne "+chosenVar+" = "+val+";");
if (this.isConsistant(chosenVar)) { // Si contrainte validée
this.searchAllSolutions();
}
this.assignation.remove(chosenVar);
}
return this.solutions;
}
}
|
package solution;
/**
* 867. 转置矩阵
*/
public class Transpose {
public int[][] transpose(int[][] matrix) {
int m = matrix.length;
int n = matrix[0].length;
int res[][] = new int[n][m];
for (int i = 0; i < m; i++) {
for (int j = 0; j < n; j++) {
res[j][i] = matrix[i][j];
}
}
return res;
}
public static void main(String[] args) {
Transpose transpose = new Transpose();
int[][] a = {{1, 2, 3}, {4, 5, 6}};
transpose.transpose(a);
}
}
|
package formation.persistence.reponse;
import formation.domain.Reponse;
import java.util.List;
/**
* Created by victor on 14/12/2015.
*/
public interface ReponseDAOItf {
public List<Reponse> findAll();
public Reponse create(Reponse question);
public Reponse find(Long id);
public List<Reponse> findByQuestion(int id);
}
|
package com.krt.gov.thread.service.impl;
import com.krt.common.base.BaseServiceImpl;
import com.krt.gov.thread.entity.TCallbackLog;
import com.krt.gov.thread.mapper.TCallbackLogMapper;
import com.krt.gov.thread.service.ITCallbackLogService;
import org.springframework.stereotype.Service;
import javax.annotation.Resource;
import java.util.Map;
/**
* 回调列表日志服务接口实现层
*
* @author 郭明德
* @version 1.0
* @date 2019年08月08日
*/
@Service
public class TCallbackLogServiceImpl extends BaseServiceImpl<TCallbackLogMapper, TCallbackLog> implements ITCallbackLogService {
@Resource
private TCallbackLogMapper tCallbackLogMapper;
/**
* 插入一条回调日志
* @param map
*/
@Override
public void insertByMap(Map map) {
tCallbackLogMapper.insertByMap(map);
}
}
|
package com.xt.mytest.singleton;
/**
* 第三种单例
*/
public class Singleton3 {
private Singleton3() {
}
public static Singleton3 instance;
static {
instance = new Singleton3();
}
}
|
package com.soldevelo.vmi.scheduler.web.server;
import com.soldevelo.vmi.config.acs.AcsConfiguration;
import com.soldevelo.vmi.scheduler.web.rest.ex.ServerShutdownException;
import com.soldevelo.vmi.scheduler.web.rest.ex.ServerStartupException;
import org.eclipse.jetty.server.Handler;
import org.eclipse.jetty.server.NCSARequestLog;
import org.eclipse.jetty.server.RequestLog;
import org.eclipse.jetty.server.Server;
import org.eclipse.jetty.server.handler.HandlerCollection;
import org.eclipse.jetty.server.handler.HandlerList;
import org.eclipse.jetty.server.handler.RequestLogHandler;
import org.eclipse.jetty.server.nio.SelectChannelConnector;
import org.eclipse.jetty.util.thread.QueuedThreadPool;
import org.eclipse.jetty.util.thread.ThreadPool;
import org.eclipse.jetty.webapp.WebAppContext;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import java.io.File;
import java.net.URL;
import java.util.ArrayList;
import java.util.List;
@Component
public class SchedulerHttpServer {
private static final String WEB_XML = "webapp/WEB-INF/web.xml";
private Server server;
private int port;
private String logFilePath;
@Autowired
public SchedulerHttpServer(AcsConfiguration configuration) {
this.port = configuration.getRestApiPort();
this.logFilePath = configuration.getRestAccessLog();
}
public void start() throws ServerStartupException {
server = new Server();
server.setThreadPool(createThreadPool());
server.addConnector(createConnector());
server.setStopAtShutdown(true);
if (logFilePath != null) {
server.setHandler(createHandlers());
}
try {
server.start();
} catch (Exception e) {
throw new ServerStartupException("Unable to start the Jetty server", e);
}
}
public void join() throws InterruptedException {
server.join();
}
public void stop() throws ServerShutdownException {
try {
server.stop();
} catch (Exception e) {
throw new ServerShutdownException("Unable to stop the Jetty server", e);
}
}
public boolean isRunning() {
return server != null && server.isRunning();
}
private ThreadPool createThreadPool() {
QueuedThreadPool threadPool = new QueuedThreadPool();
threadPool.setMinThreads(10);
threadPool.setMaxThreads(100);
return threadPool;
}
private SelectChannelConnector createConnector() {
SelectChannelConnector connector = new SelectChannelConnector();
connector.setPort(port);
return connector;
}
private HandlerCollection createHandlers() throws ServerStartupException {
WebAppContext ctx = new WebAppContext();
ctx.setContextPath("/");
ctx.setWar(getShadedWarUrl());
List<Handler> handlers = new ArrayList<Handler>();
handlers.add(ctx);
HandlerList contexts = new HandlerList();
contexts.setHandlers(handlers.toArray(new Handler[handlers.size()]));
RequestLogHandler reqLogHandler = new RequestLogHandler();
reqLogHandler.setRequestLog(createRequestLog());
HandlerCollection result = new HandlerCollection();
result.setHandlers(new Handler[]{contexts, reqLogHandler});
return result;
}
private RequestLog createRequestLog() throws ServerStartupException {
NCSARequestLog requestLog = new NCSARequestLog();
File logFile = new File(logFilePath);
File logDir = logFile.getParentFile();
if (!logDir.exists()) {
boolean ret = logDir.mkdirs();
if (!ret) {
throw new ServerStartupException("Unable to create the log directory " + logDir.getAbsolutePath());
}
}
requestLog.setFilename(logFile.getPath());
requestLog.setRetainDays(14);
requestLog.setExtended(false);
requestLog.setAppend(true);
requestLog.setLogTimeZone("GMT");
requestLog.setLogLatency(true);
return requestLog;
}
private String getShadedWarUrl() throws ServerStartupException {
URL url = Thread.currentThread().getContextClassLoader().getResource(WEB_XML);
if (url == null) {
throw new ServerStartupException("Unable to find web.xml");
} else {
String urlStr = url.toString();
// Strip off "WEB-INF/web.xml"
return urlStr.substring(0, urlStr.length() - 15);
}
}
}
|
package Variables_and_DataTypes;
public class Assignment {
public static void main(String[] args) {
// Присвоение со сложением для типа byte
byte variable1 = 0;
//variable1 = variable1 + 5; // ОШИБКА: Попытка неявного преобразования значения результата типа int в тип byte
//variable1 = (byte)variable1 + 5; // ОШИБКА: Происходит преобразование типа byte в тип byte раньше выполнения операции сложения
// Варианты решения
variable1 = (byte)(variable1 + 5); // Громоздкое решение
System.out.println(variable1);
variable1 +=5; // Элегантное решение
variable1 +=5000; // Сужение типа
// Для типов int и long не происходит преобразование в int
// Присвоение со сложением
int variabl2 = 0;
variabl2 = variabl2 + 5; // Нет ошибки
variabl2 +=5;
// Присвоение с вычитанием
int variable3 = 0;
variable3 = variable3 - 5; // Нет ошибки
variable3 -=5;
// Присвоение с умножением
int variable4 = 0;
variable3 = variable3 * 5; // Нет ошибки
variable3 *=5;
// Присвоение с делением
int variable5 = 0;
variable3 = variable3 / 5; // Нет ошибки
variable3 /=5;
// Присвоение остатка от деления
int variable6 = 0;
variable3 = variable3 % 5; // Нет ошибки
variable3 %=5;
// Для типов float и double не происходит преобразование в int
float variable7 = 0;
variable7 = variable7 + 5; // Нет ошибки
variable7 +=5;
// Для типов float и double не происходит преобразование в int
double variable8 = 0;
variable8 = variable8 * 5; // Нет ошибки
variable8 *=5;
}
}
|
package com.chinese.culture.mvp.model;
import io.realm.RealmObject;
import io.realm.annotations.PrimaryKey;
public class TangShiBean extends RealmObject {
@PrimaryKey
private long tid;
private String title;
private String author;
private String paragraphs;
private boolean isRead = false;
public boolean isRead() {
return isRead;
}
public void setRead(boolean read) {
isRead = read;
}
public long getTid() {
return tid;
}
public void setTid(long tid) {
this.tid = tid;
}
public String getTitle() {
return title;
}
public void setTitle(String title) {
this.title = title;
}
public String getAuthor() {
return author;
}
public void setAuthor(String author) {
this.author = author;
}
public String getParagraphs() {
return paragraphs;
}
public void setParagraphs(String paragraphs) {
this.paragraphs = paragraphs;
}
}
|
package SimpleFactory01.exercise.product;
import SimpleFactory01.exercise.factory.GeometricalShape;
public class Circle extends GeometricalShape {
@Override
public void draw() {
System.out.println("画出圆形图案");
}
@Override
public void erase() {
System.out.println("擦除圆形图案");
}
}
|
package ge.mziuri.model;
public class Bet {
private double coefficient;
private final String chosenteam;
public Bet(String chosenteam) {
this.chosenteam = chosenteam;
}
/**
* @return the coefficient1
*/
public double getCoefficient() {
return coefficient;
}
public void setCoefficient1(double coefficient) {
this.coefficient = coefficient;
}
}
|
/*
* 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 registraclinic.telas;
import java.util.List;
import javax.swing.JOptionPane;
import registraclinic.anamnese.Anamnese;
import registraclinic.anamnese.AnamneseDAO;
import registraclinic.anamnese.AnamneseTableModel;
import registraclinic.paciente.Paciente;
import registraclinic.paciente.PacienteDAO;
/**
*
* @author Karlos Oliveira
*/
public class CadastroAnamnese extends javax.swing.JDialog {
Paciente paciente;
PacienteDAO pacienteDAO = new PacienteDAO();
Anamnese anamnese = new Anamnese();
AnamneseDAO anamneseDAO = new AnamneseDAO();
public CadastroAnamnese(java.awt.Frame parent, boolean modal) {
initComponents();
getRootPane().setDefaultButton(btSalvar);
btLimparActionPerformed(null);
setModal(true);
}
/**
* This method is called from within the constructor to initialize the form.
* WARNING: Do NOT modify this code. The content of this method is always
* regenerated by the Form Editor.
*/
@SuppressWarnings("unchecked")
// <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
private void initComponents() {
jtGeral = new javax.swing.JTabbedPane();
jpAnamnese = new javax.swing.JPanel();
jScrollPane2 = new javax.swing.JScrollPane();
jtHpp = new javax.swing.JTextArea();
jScrollPane1 = new javax.swing.JScrollPane();
jtHda = new javax.swing.JTextArea();
jLabel37 = new javax.swing.JLabel();
jLObrigatorioNome40 = new javax.swing.JLabel();
jLObrigatorioNome41 = new javax.swing.JLabel();
jLabel38 = new javax.swing.JLabel();
jLabel46 = new javax.swing.JLabel();
jScrollPane4 = new javax.swing.JScrollPane();
jtQueixaPrincipal = new javax.swing.JTextArea();
jLObrigatorioNome47 = new javax.swing.JLabel();
labelDadosPessoais = new javax.swing.JLabel();
jpSinaisVitais = new javax.swing.JPanel();
jLObrigatorioNome42 = new javax.swing.JLabel();
jLObrigatorioNome55 = new javax.swing.JLabel();
jLabel43 = new javax.swing.JLabel();
jScrollPane7 = new javax.swing.JScrollPane();
jtHistoricoFamiliar = new javax.swing.JTextArea();
jScrollPane8 = new javax.swing.JScrollPane();
jtHistoricoSocial = new javax.swing.JTextArea();
jLabel44 = new javax.swing.JLabel();
labelAluno = new javax.swing.JLabel();
jpSinaisVitais1 = new javax.swing.JPanel();
txtFc = new javax.swing.JTextField();
jLObrigatorioNome51 = new javax.swing.JLabel();
jLabel50 = new javax.swing.JLabel();
jLabel51 = new javax.swing.JLabel();
txtPa = new javax.swing.JTextField();
jLObrigatorioNome52 = new javax.swing.JLabel();
txtFr = new javax.swing.JTextField();
jLObrigatorioNome53 = new javax.swing.JLabel();
jLabel52 = new javax.swing.JLabel();
jLObrigatorioNome54 = new javax.swing.JLabel();
txtTemperatura = new javax.swing.JTextField();
jLabel53 = new javax.swing.JLabel();
jLabel42 = new javax.swing.JLabel();
jScrollPane6 = new javax.swing.JScrollPane();
jtExamesComplementares = new javax.swing.JTextArea();
jLObrigatorioNome45 = new javax.swing.JLabel();
labelAluno1 = new javax.swing.JLabel();
btVoltar = new javax.swing.JButton();
btPesquisar = new javax.swing.JButton();
btExcluir = new javax.swing.JButton();
btLimpar = new javax.swing.JButton();
btSalvar = new javax.swing.JButton();
jLabel6 = new javax.swing.JLabel();
setDefaultCloseOperation(javax.swing.WindowConstants.DISPOSE_ON_CLOSE);
setMaximumSize(new java.awt.Dimension(810, 520));
setMinimumSize(new java.awt.Dimension(810, 520));
setUndecorated(true);
setPreferredSize(new java.awt.Dimension(810, 520));
setResizable(false);
getContentPane().setLayout(null);
jtGeral.setBackground(new java.awt.Color(255, 255, 255));
jtGeral.setForeground(new java.awt.Color(22, 64, 61));
jtGeral.setToolTipText("");
jtGeral.setFont(new java.awt.Font("Berlin Sans FB", 0, 14)); // NOI18N
jtGeral.setMaximumSize(new java.awt.Dimension(810, 360));
jtGeral.setMinimumSize(new java.awt.Dimension(810, 360));
jtGeral.setPreferredSize(new java.awt.Dimension(810, 360));
jtGeral.setVerifyInputWhenFocusTarget(false);
jpAnamnese.setBackground(new java.awt.Color(255, 255, 255));
jpAnamnese.setBorder(new javax.swing.border.LineBorder(new java.awt.Color(0, 0, 0), 1, true));
jpAnamnese.setForeground(new java.awt.Color(22, 64, 61));
jpAnamnese.setLayout(null);
jtHpp.setColumns(20);
jtHpp.setFont(new java.awt.Font("Tahoma", 1, 14)); // NOI18N
jtHpp.setLineWrap(true);
jtHpp.setRows(3);
jtHpp.setBorder(new javax.swing.border.LineBorder(new java.awt.Color(56, 100, 62), 1, true));
jScrollPane2.setViewportView(jtHpp);
jpAnamnese.add(jScrollPane2);
jScrollPane2.setBounds(10, 130, 380, 190);
jtHda.setColumns(20);
jtHda.setFont(new java.awt.Font("Tahoma", 1, 14)); // NOI18N
jtHda.setLineWrap(true);
jtHda.setRows(3);
jtHda.setBorder(new javax.swing.border.LineBorder(new java.awt.Color(56, 100, 62), 1, true));
jScrollPane1.setViewportView(jtHda);
jpAnamnese.add(jScrollPane1);
jScrollPane1.setBounds(410, 30, 380, 290);
jLabel37.setFont(new java.awt.Font("Tahoma", 1, 15)); // NOI18N
jLabel37.setText("HDA");
jpAnamnese.add(jLabel37);
jLabel37.setBounds(410, 10, 60, 19);
jLObrigatorioNome40.setFont(new java.awt.Font("Tahoma", 1, 14)); // NOI18N
jLObrigatorioNome40.setForeground(new java.awt.Color(204, 0, 0));
jLObrigatorioNome40.setText("*");
jpAnamnese.add(jLObrigatorioNome40);
jLObrigatorioNome40.setBounds(780, 20, 10, 10);
jLObrigatorioNome41.setFont(new java.awt.Font("Tahoma", 1, 14)); // NOI18N
jLObrigatorioNome41.setForeground(new java.awt.Color(204, 0, 0));
jLObrigatorioNome41.setText("*");
jpAnamnese.add(jLObrigatorioNome41);
jLObrigatorioNome41.setBounds(380, 120, 10, 10);
jLabel38.setFont(new java.awt.Font("Tahoma", 1, 15)); // NOI18N
jLabel38.setText("HPP");
jpAnamnese.add(jLabel38);
jLabel38.setBounds(10, 110, 60, 19);
jLabel46.setFont(new java.awt.Font("Tahoma", 1, 15)); // NOI18N
jLabel46.setText("Queixa Principal");
jpAnamnese.add(jLabel46);
jLabel46.setBounds(10, 10, 150, 19);
jtQueixaPrincipal.setColumns(20);
jtQueixaPrincipal.setFont(new java.awt.Font("Tahoma", 1, 14)); // NOI18N
jtQueixaPrincipal.setLineWrap(true);
jtQueixaPrincipal.setRows(3);
jtQueixaPrincipal.setBorder(new javax.swing.border.LineBorder(new java.awt.Color(56, 100, 62), 1, true));
jScrollPane4.setViewportView(jtQueixaPrincipal);
jpAnamnese.add(jScrollPane4);
jScrollPane4.setBounds(10, 30, 380, 70);
jLObrigatorioNome47.setFont(new java.awt.Font("Tahoma", 1, 14)); // NOI18N
jLObrigatorioNome47.setForeground(new java.awt.Color(204, 0, 0));
jLObrigatorioNome47.setText("*");
jpAnamnese.add(jLObrigatorioNome47);
jLObrigatorioNome47.setBounds(380, 20, 10, 10);
labelDadosPessoais.setBorder(new javax.swing.border.LineBorder(new java.awt.Color(0, 0, 0), 2, true));
labelDadosPessoais.setMaximumSize(new java.awt.Dimension(810, 330));
labelDadosPessoais.setMinimumSize(new java.awt.Dimension(810, 330));
labelDadosPessoais.setPreferredSize(new java.awt.Dimension(810, 330));
jpAnamnese.add(labelDadosPessoais);
labelDadosPessoais.setBounds(0, 0, 810, 330);
jtGeral.addTab("Anamnese", jpAnamnese);
jpSinaisVitais.setBackground(new java.awt.Color(255, 255, 255));
jpSinaisVitais.setBorder(new javax.swing.border.LineBorder(new java.awt.Color(0, 0, 0), 1, true));
jpSinaisVitais.setForeground(new java.awt.Color(22, 64, 61));
jpSinaisVitais.setLayout(null);
jLObrigatorioNome42.setFont(new java.awt.Font("Tahoma", 1, 14)); // NOI18N
jLObrigatorioNome42.setForeground(new java.awt.Color(204, 0, 0));
jLObrigatorioNome42.setText("*");
jpSinaisVitais.add(jLObrigatorioNome42);
jLObrigatorioNome42.setBounds(770, 180, 10, 10);
jLObrigatorioNome55.setFont(new java.awt.Font("Tahoma", 1, 14)); // NOI18N
jLObrigatorioNome55.setForeground(new java.awt.Color(204, 0, 0));
jLObrigatorioNome55.setText("*");
jpSinaisVitais.add(jLObrigatorioNome55);
jLObrigatorioNome55.setBounds(770, 20, 10, 10);
jLabel43.setFont(new java.awt.Font("Tahoma", 1, 15)); // NOI18N
jLabel43.setText("História Familiar");
jpSinaisVitais.add(jLabel43);
jLabel43.setBounds(20, 10, 160, 19);
jtHistoricoFamiliar.setColumns(20);
jtHistoricoFamiliar.setFont(new java.awt.Font("Tahoma", 1, 14)); // NOI18N
jtHistoricoFamiliar.setLineWrap(true);
jtHistoricoFamiliar.setRows(3);
jtHistoricoFamiliar.setBorder(new javax.swing.border.LineBorder(new java.awt.Color(56, 100, 62), 1, true));
jScrollPane7.setViewportView(jtHistoricoFamiliar);
jpSinaisVitais.add(jScrollPane7);
jScrollPane7.setBounds(20, 30, 760, 130);
jtHistoricoSocial.setColumns(20);
jtHistoricoSocial.setFont(new java.awt.Font("Tahoma", 1, 14)); // NOI18N
jtHistoricoSocial.setLineWrap(true);
jtHistoricoSocial.setRows(3);
jtHistoricoSocial.setBorder(new javax.swing.border.LineBorder(new java.awt.Color(56, 100, 62), 1, true));
jScrollPane8.setViewportView(jtHistoricoSocial);
jpSinaisVitais.add(jScrollPane8);
jScrollPane8.setBounds(20, 190, 760, 130);
jLabel44.setFont(new java.awt.Font("Tahoma", 1, 15)); // NOI18N
jLabel44.setText("História Social");
jpSinaisVitais.add(jLabel44);
jLabel44.setBounds(20, 170, 160, 19);
labelAluno.setBorder(new javax.swing.border.LineBorder(new java.awt.Color(0, 0, 0), 2, true));
labelAluno.setMaximumSize(new java.awt.Dimension(810, 330));
labelAluno.setMinimumSize(new java.awt.Dimension(810, 330));
labelAluno.setPreferredSize(new java.awt.Dimension(810, 330));
jpSinaisVitais.add(labelAluno);
labelAluno.setBounds(0, 0, 810, 330);
jtGeral.addTab("Hábitos de Vida", jpSinaisVitais);
jpSinaisVitais1.setBackground(new java.awt.Color(255, 255, 255));
jpSinaisVitais1.setBorder(new javax.swing.border.LineBorder(new java.awt.Color(0, 0, 0), 1, true));
jpSinaisVitais1.setForeground(new java.awt.Color(22, 64, 61));
jpSinaisVitais1.setLayout(null);
txtFc.setFont(new java.awt.Font("Tahoma", 1, 14)); // NOI18N
txtFc.setBorder(new javax.swing.border.LineBorder(new java.awt.Color(58, 100, 62), 1, true));
txtFc.setMaximumSize(new java.awt.Dimension(8, 200));
txtFc.setMinimumSize(new java.awt.Dimension(8, 200));
txtFc.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
txtFcActionPerformed(evt);
}
});
jpSinaisVitais1.add(txtFc);
txtFc.setBounds(430, 40, 150, 30);
jLObrigatorioNome51.setFont(new java.awt.Font("Tahoma", 1, 14)); // NOI18N
jLObrigatorioNome51.setForeground(new java.awt.Color(204, 0, 0));
jLObrigatorioNome51.setText("*");
jpSinaisVitais1.add(jLObrigatorioNome51);
jLObrigatorioNome51.setBounds(570, 30, 10, 10);
jLabel50.setFont(new java.awt.Font("Tahoma", 1, 15)); // NOI18N
jLabel50.setText("FC");
jpSinaisVitais1.add(jLabel50);
jLabel50.setBounds(430, 20, 30, 19);
jLabel51.setFont(new java.awt.Font("Tahoma", 1, 15)); // NOI18N
jLabel51.setText("PA");
jpSinaisVitais1.add(jLabel51);
jLabel51.setBounds(20, 20, 30, 19);
txtPa.setFont(new java.awt.Font("Tahoma", 1, 14)); // NOI18N
txtPa.setBorder(new javax.swing.border.LineBorder(new java.awt.Color(58, 100, 62), 1, true));
txtPa.setMaximumSize(new java.awt.Dimension(8, 200));
txtPa.setMinimumSize(new java.awt.Dimension(8, 200));
txtPa.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
txtPaActionPerformed(evt);
}
});
jpSinaisVitais1.add(txtPa);
txtPa.setBounds(20, 40, 150, 30);
jLObrigatorioNome52.setFont(new java.awt.Font("Tahoma", 1, 14)); // NOI18N
jLObrigatorioNome52.setForeground(new java.awt.Color(204, 0, 0));
jLObrigatorioNome52.setText("*");
jpSinaisVitais1.add(jLObrigatorioNome52);
jLObrigatorioNome52.setBounds(160, 30, 10, 10);
txtFr.setFont(new java.awt.Font("Tahoma", 1, 14)); // NOI18N
txtFr.setBorder(new javax.swing.border.LineBorder(new java.awt.Color(58, 100, 62), 1, true));
txtFr.setMaximumSize(new java.awt.Dimension(8, 200));
txtFr.setMinimumSize(new java.awt.Dimension(8, 200));
txtFr.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
txtFrActionPerformed(evt);
}
});
jpSinaisVitais1.add(txtFr);
txtFr.setBounds(220, 40, 150, 30);
jLObrigatorioNome53.setFont(new java.awt.Font("Tahoma", 1, 14)); // NOI18N
jLObrigatorioNome53.setForeground(new java.awt.Color(204, 0, 0));
jLObrigatorioNome53.setText("*");
jpSinaisVitais1.add(jLObrigatorioNome53);
jLObrigatorioNome53.setBounds(360, 30, 10, 10);
jLabel52.setFont(new java.awt.Font("Tahoma", 1, 15)); // NOI18N
jLabel52.setText("FR");
jpSinaisVitais1.add(jLabel52);
jLabel52.setBounds(220, 20, 30, 19);
jLObrigatorioNome54.setFont(new java.awt.Font("Tahoma", 1, 14)); // NOI18N
jLObrigatorioNome54.setForeground(new java.awt.Color(204, 0, 0));
jLObrigatorioNome54.setText("*");
jpSinaisVitais1.add(jLObrigatorioNome54);
jLObrigatorioNome54.setBounds(770, 30, 10, 10);
txtTemperatura.setFont(new java.awt.Font("Tahoma", 1, 14)); // NOI18N
txtTemperatura.setBorder(new javax.swing.border.LineBorder(new java.awt.Color(58, 100, 62), 1, true));
txtTemperatura.setMaximumSize(new java.awt.Dimension(8, 200));
txtTemperatura.setMinimumSize(new java.awt.Dimension(8, 200));
txtTemperatura.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
txtTemperaturaActionPerformed(evt);
}
});
jpSinaisVitais1.add(txtTemperatura);
txtTemperatura.setBounds(630, 40, 150, 30);
jLabel53.setFont(new java.awt.Font("Tahoma", 1, 15)); // NOI18N
jLabel53.setText("Temperatura");
jpSinaisVitais1.add(jLabel53);
jLabel53.setBounds(630, 20, 110, 19);
jLabel42.setFont(new java.awt.Font("Tahoma", 1, 15)); // NOI18N
jLabel42.setText("Exames Complementares");
jpSinaisVitais1.add(jLabel42);
jLabel42.setBounds(20, 90, 200, 19);
jtExamesComplementares.setColumns(20);
jtExamesComplementares.setFont(new java.awt.Font("Tahoma", 1, 14)); // NOI18N
jtExamesComplementares.setLineWrap(true);
jtExamesComplementares.setRows(3);
jtExamesComplementares.setBorder(new javax.swing.border.LineBorder(new java.awt.Color(56, 100, 62), 1, true));
jScrollPane6.setViewportView(jtExamesComplementares);
jpSinaisVitais1.add(jScrollPane6);
jScrollPane6.setBounds(20, 110, 760, 200);
jLObrigatorioNome45.setFont(new java.awt.Font("Tahoma", 1, 14)); // NOI18N
jLObrigatorioNome45.setForeground(new java.awt.Color(204, 0, 0));
jLObrigatorioNome45.setText("*");
jpSinaisVitais1.add(jLObrigatorioNome45);
jLObrigatorioNome45.setBounds(770, 100, 10, 10);
labelAluno1.setBorder(new javax.swing.border.LineBorder(new java.awt.Color(0, 0, 0), 2, true));
labelAluno1.setMaximumSize(new java.awt.Dimension(810, 330));
labelAluno1.setMinimumSize(new java.awt.Dimension(810, 330));
labelAluno1.setPreferredSize(new java.awt.Dimension(810, 330));
jpSinaisVitais1.add(labelAluno1);
labelAluno1.setBounds(0, 0, 810, 330);
jtGeral.addTab("Sinais Vitais", jpSinaisVitais1);
getContentPane().add(jtGeral);
jtGeral.setBounds(0, 60, 810, 360);
btVoltar.setFont(new java.awt.Font("Tahoma", 1, 14)); // NOI18N
btVoltar.setIcon(new javax.swing.ImageIcon(getClass().getResource("/registraclinic/imagens/voltar_fisio.png"))); // NOI18N
btVoltar.setText("Voltar");
btVoltar.setContentAreaFilled(false);
btVoltar.setCursor(new java.awt.Cursor(java.awt.Cursor.DEFAULT_CURSOR));
btVoltar.setDefaultCapable(false);
btVoltar.setHorizontalTextPosition(javax.swing.SwingConstants.CENTER);
btVoltar.setVerticalTextPosition(javax.swing.SwingConstants.BOTTOM);
btVoltar.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
btVoltarActionPerformed(evt);
}
});
getContentPane().add(btVoltar);
btVoltar.setBounds(20, 440, 80, 70);
btPesquisar.setFont(new java.awt.Font("Tahoma", 1, 14)); // NOI18N
btPesquisar.setIcon(new javax.swing.ImageIcon(getClass().getResource("/registraclinic/imagens/pesquisar_fisio.png"))); // NOI18N
btPesquisar.setText("Pesquisar");
btPesquisar.setContentAreaFilled(false);
btPesquisar.setCursor(new java.awt.Cursor(java.awt.Cursor.DEFAULT_CURSOR));
btPesquisar.setHorizontalTextPosition(javax.swing.SwingConstants.CENTER);
btPesquisar.setVerticalTextPosition(javax.swing.SwingConstants.BOTTOM);
btPesquisar.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
btPesquisarActionPerformed(evt);
}
});
getContentPane().add(btPesquisar);
btPesquisar.setBounds(360, 440, 100, 70);
btExcluir.setFont(new java.awt.Font("Tahoma", 1, 14)); // NOI18N
btExcluir.setIcon(new javax.swing.ImageIcon(getClass().getResource("/registraclinic/imagens/excluir_fisio.png"))); // NOI18N
btExcluir.setText("Excluir");
btExcluir.setContentAreaFilled(false);
btExcluir.setCursor(new java.awt.Cursor(java.awt.Cursor.DEFAULT_CURSOR));
btExcluir.setHorizontalTextPosition(javax.swing.SwingConstants.CENTER);
btExcluir.setVerticalTextPosition(javax.swing.SwingConstants.BOTTOM);
btExcluir.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
btExcluirActionPerformed(evt);
}
});
getContentPane().add(btExcluir);
btExcluir.setBounds(500, 440, 80, 70);
btLimpar.setFont(new java.awt.Font("Tahoma", 1, 14)); // NOI18N
btLimpar.setIcon(new javax.swing.ImageIcon(getClass().getResource("/registraclinic/imagens/limpar_fisio.png"))); // NOI18N
btLimpar.setText("Limpar");
btLimpar.setContentAreaFilled(false);
btLimpar.setCursor(new java.awt.Cursor(java.awt.Cursor.DEFAULT_CURSOR));
btLimpar.setHorizontalTextPosition(javax.swing.SwingConstants.CENTER);
btLimpar.setVerticalTextPosition(javax.swing.SwingConstants.BOTTOM);
btLimpar.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
btLimparActionPerformed(evt);
}
});
getContentPane().add(btLimpar);
btLimpar.setBounds(240, 440, 80, 70);
btSalvar.setFont(new java.awt.Font("Tahoma", 1, 14)); // NOI18N
btSalvar.setIcon(new javax.swing.ImageIcon(getClass().getResource("/registraclinic/imagens/save_fisio.png"))); // NOI18N
btSalvar.setText("Salvar");
btSalvar.setContentAreaFilled(false);
btSalvar.setCursor(new java.awt.Cursor(java.awt.Cursor.DEFAULT_CURSOR));
btSalvar.setHorizontalTextPosition(javax.swing.SwingConstants.CENTER);
btSalvar.setVerticalTextPosition(javax.swing.SwingConstants.BOTTOM);
btSalvar.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
btSalvarActionPerformed(evt);
}
});
getContentPane().add(btSalvar);
btSalvar.setBounds(720, 440, 80, 70);
jLabel6.setIcon(new javax.swing.ImageIcon(getClass().getResource("/registraclinic/imagens/CADASTRO ANAMNESE.png"))); // NOI18N
jLabel6.setBorder(new javax.swing.border.LineBorder(new java.awt.Color(0, 0, 0), 1, true));
jLabel6.setMaximumSize(new java.awt.Dimension(809, 520));
jLabel6.setMinimumSize(new java.awt.Dimension(809, 520));
jLabel6.setPreferredSize(new java.awt.Dimension(809, 520));
getContentPane().add(jLabel6);
jLabel6.setBounds(0, 0, 810, 520);
pack();
setLocationRelativeTo(null);
}// </editor-fold>//GEN-END:initComponents
private void btPesquisarActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btPesquisarActionPerformed
List<Anamnese> lista;
lista = (anamneseDAO.listar());
AnamneseTableModel itm = new AnamneseTableModel(lista);
Object objetoRetorno = PesquisaGenerica.exibeTela(itm, "Anamnese");
if (objetoRetorno != null) {
anamnese = anamneseDAO.consultarObjetoId("idAnamnese", objetoRetorno);
jtHda.setText(anamnese.getHda());
jtHpp.setText(anamnese.getHpp());
jtExamesComplementares.setText(anamnese.getHistoriaFamiliar());
txtPa.setText(anamnese.getPa());
txtFr.setText(anamnese.getFr());
txtFc.setText(anamnese.getFc());
btExcluir.setEnabled(true);
}
}//GEN-LAST:event_btPesquisarActionPerformed
private void btExcluirActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btExcluirActionPerformed
anamneseDAO.excluir(anamnese);
btLimparActionPerformed(null);
}//GEN-LAST:event_btExcluirActionPerformed
private void btSalvarActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btSalvarActionPerformed
if (jtHda.getText().isEmpty() || jtHpp.getText().isEmpty()
|| jtExamesComplementares.getText().isEmpty() || txtPa.getText().equals("")
|| txtFr.getText().equals("") || txtFc.getText().equals("")) {
JOptionPane.showMessageDialog(this, "Prencha todos os campos !!");
} else {
anamnese.setHda(jtHda.getText());
anamnese.setHpp(jtHpp.getText());
anamnese.setHistoriaFamiliar(jtExamesComplementares.getText());
anamnese.setPa(txtPa.getText());
anamnese.setFr(txtFr.getText());
anamnese.setFc(txtFc.getText());
anamneseDAO.salvar(anamnese);
btLimparActionPerformed(null);
anamnese = new Anamnese();
}
}//GEN-LAST:event_btSalvarActionPerformed
private void btVoltarActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btVoltarActionPerformed
dispose();
}//GEN-LAST:event_btVoltarActionPerformed
private void btLimparActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btLimparActionPerformed
// Util.limparCamposGenerico(this);
// grupoPrioridade.clearSelection();
// traumatoOrtopedia = new TraumatoOrtopedia();
// paciente = new Paciente();
}//GEN-LAST:event_btLimparActionPerformed
private void txtFcActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_txtFcActionPerformed
// TODO add your handling code here:
}//GEN-LAST:event_txtFcActionPerformed
private void txtPaActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_txtPaActionPerformed
// TODO add your handling code here:
}//GEN-LAST:event_txtPaActionPerformed
private void txtFrActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_txtFrActionPerformed
// TODO add your handling code here:
}//GEN-LAST:event_txtFrActionPerformed
private void txtTemperaturaActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_txtTemperaturaActionPerformed
// TODO add your handling code here:
}//GEN-LAST:event_txtTemperaturaActionPerformed
// public void addAPorraToda() {
// if (paciente != null) {
// traumatoOrtopedia = new TraumatoOrtopedia();
// traumatoOrtopedia.setPaciente(paciente);
// //prioridadeAtendimento.setAtendimento(atendimento);
// } else {
// System.out.println("Selecione um paciente!");
// }
// }
/**
* @param args the command line arguments
*/
public static void main(String args[]) {
/* Set the Nimbus look and feel */
//<editor-fold defaultstate="collapsed" desc=" Look and feel setting code (optional) ">
/* If Nimbus (introduced in Java SE 6) is not available, stay with the default look and feel.
* For details see http://download.oracle.com/javase/tutorial/uiswing/lookandfeel/plaf.html
*/
try {
for (javax.swing.UIManager.LookAndFeelInfo info : javax.swing.UIManager.getInstalledLookAndFeels()) {
if ("Nimbus".equals(info.getName())) {
javax.swing.UIManager.setLookAndFeel(info.getClassName());
break;
}
}
} catch (ClassNotFoundException ex) {
java.util.logging.Logger.getLogger(CadastroAnamnese.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (InstantiationException ex) {
java.util.logging.Logger.getLogger(CadastroAnamnese.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (IllegalAccessException ex) {
java.util.logging.Logger.getLogger(CadastroAnamnese.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (javax.swing.UnsupportedLookAndFeelException ex) {
java.util.logging.Logger.getLogger(CadastroAnamnese.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
}
//</editor-fold>
//</editor-fold>
//</editor-fold>
//</editor-fold>
//</editor-fold>
//</editor-fold>
//</editor-fold>
//</editor-fold>
//</editor-fold>
//</editor-fold>
//</editor-fold>
//</editor-fold>
//</editor-fold>
//</editor-fold>
//</editor-
//</editor-fold>
//</editor-fold>
//</editor-fold>
//</editor-fold>
//</editor-fold>
//</editor-fold>
//</editor-fold>
//</editor-fold>
//</editor-fold>
//</editor-fold>
//</editor-fold>
//</editor-fold>
//</editor-fold>
//</editor-fold>
//</editor-
//</editor-fold>
//</editor-fold>
//</editor-fold>
//</editor-fold>
//</editor-fold>
//</editor-fold>
//</editor-fold>
//</editor-fold>
//</editor-fold>
//</editor-fold>
//</editor-fold>
//</editor-fold>
//</editor-fold>
//</editor-fold>
//</editor-
//</editor-fold>
//</editor-fold>
//</editor-fold>
//</editor-fold>
//</editor-fold>
//</editor-fold>
//</editor-fold>
//</editor-fold>
//</editor-fold>
//</editor-fold>
//</editor-fold>
//</editor-fold>
//</editor-fold>
//</editor-fold>
//</editor-
//</editor-fold>
//</editor-fold>
//</editor-fold>
//</editor-fold>
//</editor-fold>
//</editor-fold>
//</editor-fold>
//</editor-fold>
//</editor-fold>
//</editor-fold>
//</editor-fold>
//</editor-fold>
//</editor-fold>
//</editor-fold>
//</editor-
//</editor-fold>
//</editor-fold>
//</editor-fold>
//</editor-fold>
//</editor-fold>
//</editor-fold>
//</editor-fold>
//</editor-fold>
//</editor-fold>
//</editor-fold>
//</editor-fold>
//</editor-fold>
//</editor-fold>
//</editor-fold>
//</editor-
//</editor-fold>
//</editor-fold>
//</editor-fold>
//</editor-fold>
//</editor-fold>
//</editor-fold>
//</editor-fold>
//</editor-fold>
//</editor-fold>
//</editor-fold>
//</editor-fold>
//</editor-fold>
//</editor-fold>
//</editor-fold>
//</editor-
//</editor-fold>
//</editor-fold>
//</editor-fold>
//</editor-fold>
//</editor-fold>
//</editor-fold>
//</editor-fold>
//</editor-fold>
//</editor-fold>
//</editor-fold>
//</editor-fold>
//</editor-fold>
//</editor-fold>
//</editor-fold>
//</editor-
//</editor-fold>
//</editor-fold>
//</editor-fold>
//</editor-fold>
//</editor-fold>
//</editor-fold>
//</editor-fold>
//</editor-fold>
//</editor-fold>
//</editor-fold>
//</editor-fold>
//</editor-fold>
//</editor-fold>
//</editor-fold>
//</editor-
//</editor-fold>
//</editor-fold>
//</editor-fold>
//</editor-fold>
//</editor-fold>
//</editor-fold>
//</editor-fold>
//</editor-fold>
//</editor-fold>
//</editor-fold>
//</editor-fold>
//</editor-fold>
//</editor-fold>
//</editor-fold>
//</editor-
//</editor-fold>
//</editor-fold>
//</editor-fold>
//</editor-fold>
//</editor-fold>
//</editor-fold>
//</editor-fold>
//</editor-fold>
//</editor-fold>
//</editor-fold>
//</editor-fold>
//</editor-fold>
//</editor-fold>
//</editor-fold>
//</editor-
//</editor-fold>
//</editor-fold>
//</editor-fold>
//</editor-fold>
//</editor-fold>
//</editor-fold>
//</editor-fold>
//</editor-fold>
//</editor-fold>
//</editor-fold>
//</editor-fold>
//</editor-fold>
//</editor-fold>
//</editor-fold>
//</editor-
//</editor-fold>
//</editor-fold>
//</editor-fold>
//</editor-fold>
//</editor-fold>
//</editor-fold>
//</editor-fold>
//</editor-fold>
//</editor-fold>
//</editor-fold>
//</editor-fold>
//</editor-fold>
//</editor-fold>
//</editor-fold>
//</editor-
//</editor-fold>
//</editor-fold>
//</editor-fold>
//</editor-fold>
//</editor-fold>
//</editor-fold>
//</editor-fold>
//</editor-fold>
//</editor-fold>
//</editor-fold>
//</editor-fold>
//</editor-fold>
//</editor-fold>
//</editor-fold>
//</editor-
//</editor-fold>
//</editor-fold>
//</editor-fold>
//</editor-fold>
//</editor-fold>
//</editor-fold>
//</editor-fold>
//</editor-fold>
//</editor-fold>
//</editor-fold>
//</editor-fold>
//</editor-fold>
//</editor-fold>
//</editor-fold>
//</editor-
//</editor-fold>
//</editor-fold>
//</editor-fold>
//</editor-fold>
//</editor-fold>
//</editor-fold>
//</editor-fold>
//</editor-fold>
//</editor-fold>
//</editor-fold>
//</editor-fold>
//</editor-fold>
//</editor-fold>
//</editor-fold>
//</editor-
//</editor-fold>
//</editor-fold>
//</editor-fold>
//</editor-fold>
//</editor-fold>
//</editor-fold>
//</editor-fold>
//</editor-fold>
//</editor-fold>
//</editor-fold>
//</editor-fold>
//</editor-fold>
//</editor-fold>
//</editor-fold>
//</editor-
//</editor-fold>
//</editor-fold>
//</editor-fold>
//</editor-fold>
//</editor-fold>
//</editor-fold>
//</editor-fold>
//</editor-fold>
//</editor-fold>
//</editor-fold>
//</editor-fold>
//</editor-fold>
//</editor-fold>
//</editor-fold>
//</editor-
//</editor-fold>
//</editor-fold>
//</editor-fold>
//</editor-fold>
//</editor-fold>
//</editor-fold>
//</editor-fold>
//</editor-fold>
//</editor-fold>
//</editor-fold>
//</editor-fold>
//</editor-fold>
//</editor-fold>
//</editor-fold>
//</editor-
//</editor-fold>
//</editor-fold>
//</editor-fold>
//</editor-fold>
//</editor-fold>
//</editor-fold>
//</editor-fold>
//</editor-fold>
//</editor-fold>
//</editor-fold>
//</editor-fold>
//</editor-fold>
//</editor-fold>
//</editor-fold>
//</editor-
//</editor-fold>
//</editor-fold>
//</editor-fold>
//</editor-fold>
//</editor-fold>
//</editor-fold>
//</editor-fold>
//</editor-fold>
//</editor-fold>
//</editor-fold>
//</editor-fold>
//</editor-fold>
//</editor-fold>
//</editor-fold>
//</editor-
//</editor-fold>
//</editor-fold>
//</editor-fold>
//</editor-fold>
//</editor-fold>
//</editor-fold>
//</editor-fold>
//</editor-fold>
//</editor-fold>
//</editor-fold>
//</editor-fold>
//</editor-fold>
//</editor-fold>
//</editor-fold>
//</editor-
//</editor-fold>
//</editor-fold>
//</editor-fold>
//</editor-fold>
//</editor-fold>
//</editor-fold>
//</editor-fold>
//</editor-fold>
//</editor-fold>
//</editor-fold>
//</editor-fold>
//</editor-fold>
//</editor-fold>
//</editor-fold>
//</editor-
//</editor-fold>
//</editor-fold>
//</editor-fold>
//</editor-fold>
//</editor-fold>
//</editor-fold>
//</editor-fold>
//</editor-fold>
//</editor-fold>
//</editor-fold>
//</editor-fold>
//</editor-fold>
//</editor-fold>
//</editor-fold>
//</editor-
//</editor-fold>
//</editor-fold>
//</editor-fold>
//</editor-fold>
//</editor-fold>
//</editor-fold>
//</editor-fold>
//</editor-fold>
//</editor-fold>
//</editor-fold>
//</editor-fold>
//</editor-fold>
//</editor-fold>
//</editor-fold>
//</editor-
//</editor-fold>
//</editor-fold>
//</editor-fold>
//</editor-fold>
//</editor-fold>
//</editor-fold>
//</editor-fold>
//</editor-fold>
//</editor-fold>
//</editor-fold>
//</editor-fold>
//</editor-fold>
//</editor-fold>
//</editor-fold>
//</editor-
//</editor-fold>
//</editor-fold>
//</editor-fold>
//</editor-fold>
//</editor-fold>
//</editor-fold>
//</editor-fold>
//</editor-fold>
//</editor-fold>
//</editor-fold>
//</editor-fold>
//</editor-fold>
//</editor-fold>
//</editor-fold>
//</editor-
//</editor-fold>
//</editor-fold>
//</editor-fold>
//</editor-fold>
//</editor-fold>
//</editor-fold>
//</editor-fold>
//</editor-fold>
//</editor-fold>
//</editor-fold>
//</editor-fold>
//</editor-fold>
//</editor-fold>
//</editor-fold>
//</editor-
//</editor-fold>
//</editor-fold>
//</editor-fold>
//</editor-fold>
//</editor-fold>
//</editor-fold>
//</editor-fold>
//</editor-fold>
//</editor-fold>
//</editor-fold>
//</editor-fold>
//</editor-fold>
//</editor-fold>
//</editor-fold>
//</editor-
//</editor-fold>
//</editor-fold>
//</editor-fold>
//</editor-fold>
//</editor-fold>
//</editor-fold>
//</editor-fold>
//</editor-fold>
//</editor-fold>
//</editor-fold>
//</editor-fold>
//</editor-fold>
//</editor-fold>
//</editor-fold>
//</editor-
//</editor-fold>
//</editor-fold>
//</editor-fold>
//</editor-fold>
//</editor-fold>
//</editor-fold>
//</editor-fold>
//</editor-fold>
//</editor-fold>
//</editor-fold>
//</editor-fold>
//</editor-fold>
//</editor-fold>
//</editor-fold>
//</editor-
//</editor-fold>
//</editor-fold>
//</editor-fold>
//</editor-fold>
//</editor-fold>
//</editor-fold>
//</editor-fold>
//</editor-fold>
//</editor-fold>
//</editor-fold>
//</editor-fold>
//</editor-fold>
//</editor-fold>
//</editor-fold>
//</editor-
//</editor-fold>
//</editor-fold>
//</editor-fold>
//</editor-fold>
//</editor-fold>
//</editor-fold>
//</editor-fold>
//</editor-fold>
//</editor-fold>
//</editor-fold>
//</editor-fold>
//</editor-fold>
//</editor-fold>
//</editor-fold>
//</editor-
//</editor-fold>
//</editor-fold>
//</editor-fold>
//</editor-fold>
//</editor-fold>
//</editor-fold>
//</editor-fold>
//</editor-fold>
//</editor-fold>
//</editor-fold>
//</editor-fold>
//</editor-fold>
//</editor-fold>
//</editor-fold>
//</editor-
//</editor-fold>
//</editor-fold>
//</editor-fold>
//</editor-fold>
//</editor-fold>
//</editor-fold>
//</editor-fold>
//</editor-fold>
//</editor-fold>
//</editor-fold>
//</editor-fold>
//</editor-fold>
//</editor-fold>
//</editor-fold>
//</editor-
//</editor-fold>
//</editor-fold>
//</editor-fold>
//</editor-fold>
//</editor-fold>
//</editor-fold>
//</editor-fold>
//</editor-fold>
//</editor-fold>
//</editor-fold>
//</editor-fold>
//</editor-fold>
//</editor-fold>
//</editor-fold>
//</editor-
//</editor-fold>
//</editor-fold>
//</editor-fold>
//</editor-fold>
//</editor-fold>
//</editor-fold>
//</editor-fold>
//</editor-fold>
//</editor-fold>
//</editor-fold>
//</editor-fold>
//</editor-fold>
//</editor-fold>
//</editor-fold>
//</editor-
//</editor-fold>
//</editor-fold>
//</editor-fold>
//</editor-fold>
//</editor-fold>
//</editor-fold>
//</editor-fold>
//</editor-fold>
//</editor-fold>
//</editor-fold>
//</editor-fold>
//</editor-fold>
//</editor-fold>
//</editor-fold>
//</editor-
//</editor-fold>
//</editor-fold>
//</editor-fold>
//</editor-fold>
//</editor-fold>
//</editor-fold>
//</editor-fold>
//</editor-fold>
//</editor-fold>
//</editor-fold>
//</editor-fold>
//</editor-fold>
//</editor-fold>
//</editor-fold>
//</editor-
//</editor-fold>
//</editor-fold>
//</editor-fold>
//</editor-fold>
//</editor-fold>
//</editor-fold>
//</editor-fold>
//</editor-fold>
//</editor-fold>
//</editor-fold>
//</editor-fold>
//</editor-fold>
//</editor-fold>
//</editor-fold>
//</editor-
//</editor-fold>
//</editor-fold>
//</editor-fold>
//</editor-fold>
//</editor-fold>
//</editor-fold>
//</editor-fold>
//</editor-fold>
//</editor-fold>
//</editor-fold>
//</editor-fold>
//</editor-fold>
//</editor-fold>
//</editor-fold>
//</editor-
//</editor-fold>
//</editor-fold>
//</editor-fold>
//</editor-fold>
//</editor-fold>
//</editor-fold>
//</editor-fold>
//</editor-fold>
//</editor-fold>
//</editor-fold>
//</editor-fold>
//</editor-fold>
//</editor-fold>
//</editor-fold>
//</editor-
//</editor-fold>
//</editor-fold>
//</editor-fold>
//</editor-fold>
//</editor-fold>
//</editor-fold>
//</editor-fold>
//</editor-fold>
//</editor-fold>
//</editor-fold>
//</editor-fold>
//</editor-fold>
//</editor-fold>
//</editor-fold>
//</editor-
//</editor-fold>
//</editor-fold>
//</editor-fold>
//</editor-fold>
//</editor-fold>
//</editor-fold>
//</editor-fold>
//</editor-fold>
//</editor-fold>
//</editor-fold>
//</editor-fold>
//</editor-fold>
//</editor-fold>
//</editor-fold>
//</editor-
//</editor-fold>
//</editor-fold>
//</editor-fold>
//</editor-fold>
//</editor-fold>
//</editor-fold>
//</editor-fold>
//</editor-fold>
//</editor-fold>
//</editor-fold>
//</editor-fold>
//</editor-fold>
//</editor-fold>
//</editor-fold>
//</editor-
//</editor-fold>
//</editor-fold>
//</editor-fold>
//</editor-fold>
//</editor-fold>
//</editor-fold>
//</editor-fold>
//</editor-fold>
//</editor-fold>
//</editor-fold>
//</editor-fold>
//</editor-fold>
//</editor-fold>
//</editor-fold>
//</editor-
//</editor-fold>
//</editor-fold>
//</editor-fold>
//</editor-fold>
//</editor-fold>
//</editor-fold>
//</editor-fold>
//</editor-fold>
//</editor-fold>
//</editor-fold>
//</editor-fold>
//</editor-fold>
//</editor-fold>
//</editor-fold>
//</editor-
//</editor-fold>
//</editor-fold>
//</editor-fold>
//</editor-fold>
//</editor-fold>
//</editor-fold>
//</editor-fold>
//</editor-fold>
//</editor-fold>
//</editor-fold>
//</editor-fold>
//</editor-fold>
//</editor-fold>
//</editor-fold>
//</editor-
//</editor-fold>
//</editor-fold>
//</editor-fold>
//</editor-fold>
//</editor-fold>
//</editor-fold>
//</editor-fold>
//</editor-fold>
//</editor-fold>
//</editor-fold>
//</editor-fold>
//</editor-fold>
//</editor-fold>
//</editor-fold>
//</editor-
//</editor-fold>
//</editor-fold>
//</editor-fold>
//</editor-fold>
//</editor-fold>
//</editor-fold>
//</editor-fold>
//</editor-fold>
//</editor-fold>
//</editor-fold>
//</editor-fold>
//</editor-fold>
//</editor-fold>
//</editor-fold>
//</editor-
//</editor-fold>
//</editor-fold>
//</editor-fold>
//</editor-fold>
//</editor-fold>
//</editor-fold>
//</editor-fold>
//</editor-fold>
//</editor-fold>
//</editor-fold>
//</editor-fold>
//</editor-fold>
//</editor-fold>
//</editor-fold>
//</editor-
//</editor-fold>
//</editor-fold>
//</editor-fold>
//</editor-fold>
//</editor-fold>
//</editor-fold>
//</editor-fold>
//</editor-fold>
//</editor-fold>
//</editor-fold>
//</editor-fold>
//</editor-fold>
//</editor-fold>
//</editor-fold>
//</editor-
//</editor-fold>
//</editor-fold>
//</editor-fold>
//</editor-fold>
//</editor-fold>
//</editor-fold>
//</editor-fold>
//</editor-fold>
//</editor-fold>
//</editor-fold>
//</editor-fold>
//</editor-fold>
//</editor-fold>
//</editor-fold>
//</editor-
//</editor-fold>
//</editor-fold>
//</editor-fold>
//</editor-fold>
//</editor-fold>
//</editor-fold>
//</editor-fold>
//</editor-fold>
//</editor-fold>
//</editor-fold>
//</editor-fold>
//</editor-fold>
//</editor-fold>
//</editor-fold>
//</editor-
//</editor-fold>
//</editor-fold>
//</editor-fold>
//</editor-fold>
//</editor-fold>
//</editor-fold>
//</editor-fold>
//</editor-fold>
//</editor-fold>
//</editor-fold>
//</editor-fold>
//</editor-fold>
//</editor-fold>
//</editor-fold>
//</editor-
//</editor-fold>
//</editor-fold>
//</editor-fold>
//</editor-fold>
//</editor-fold>
//</editor-fold>
//</editor-fold>
//</editor-fold>
//</editor-fold>
//</editor-fold>
//</editor-fold>
//</editor-fold>
//</editor-fold>
//</editor-fold>
//</editor-
//</editor-fold>
//</editor-fold>
//</editor-fold>
//</editor-fold>
//</editor-fold>
//</editor-fold>
//</editor-fold>
//</editor-fold>
//</editor-fold>
//</editor-fold>
//</editor-fold>
//</editor-fold>
//</editor-fold>
//</editor-fold>
//</editor-
//</editor-fold>
//</editor-fold>
//</editor-fold>
//</editor-fold>
//</editor-fold>
//</editor-fold>
//</editor-fold>
//</editor-fold>
//</editor-fold>
//</editor-fold>
//</editor-fold>
//</editor-fold>
//</editor-fold>
//</editor-fold>
//</editor-
//</editor-fold>
//</editor-fold>
//</editor-fold>
//</editor-fold>
//</editor-fold>
//</editor-fold>
//</editor-fold>
//</editor-fold>
//</editor-fold>
//</editor-fold>
//</editor-fold>
//</editor-fold>
//</editor-fold>
//</editor-fold>
//</editor-
//</editor-fold>
//</editor-fold>
//</editor-fold>
//</editor-fold>
//</editor-fold>
//</editor-fold>
//</editor-fold>
//</editor-fold>
//</editor-fold>
//</editor-fold>
//</editor-fold>
//</editor-fold>
//</editor-fold>
//</editor-fold>
//</editor-
//</editor-fold>
//</editor-fold>
//</editor-fold>
//</editor-fold>
//</editor-fold>
//</editor-fold>
//</editor-fold>
//</editor-fold>
//</editor-fold>
//</editor-fold>
//</editor-fold>
//</editor-fold>
//</editor-fold>
//</editor-fold>
//</editor-
//</editor-fold>
//</editor-fold>
//</editor-fold>
//</editor-fold>
//</editor-fold>
//</editor-fold>
//</editor-fold>
//</editor-fold>
//</editor-fold>
//</editor-fold>
//</editor-fold>
//</editor-fold>
//</editor-fold>
//</editor-fold>
//</editor-
//</editor-fold>
//</editor-fold>
//</editor-fold>
//</editor-fold>
//</editor-fold>
//</editor-fold>
//</editor-fold>
//</editor-fold>
//</editor-fold>
//</editor-fold>
//</editor-fold>
//</editor-fold>
//</editor-fold>
//</editor-fold>
//</editor-
//</editor-fold>
//</editor-fold>
//</editor-fold>
//</editor-fold>
//</editor-fold>
//</editor-fold>
//</editor-fold>
//</editor-fold>
//</editor-fold>
//</editor-fold>
//</editor-fold>
//</editor-fold>
//</editor-fold>
//</editor-fold>
//</editor-
/* Create and display the dialog */
java.awt.EventQueue.invokeLater(new Runnable() {
public void run() {
CadastroAnamnese dialog = new CadastroAnamnese(new javax.swing.JFrame(), true);
dialog.addWindowListener(new java.awt.event.WindowAdapter() {
@Override
public void windowClosing(java.awt.event.WindowEvent e) {
System.exit(0);
}
});
dialog.setVisible(true);
}
});
}
// Variables declaration - do not modify//GEN-BEGIN:variables
private javax.swing.JButton btExcluir;
private javax.swing.JButton btLimpar;
private javax.swing.JButton btPesquisar;
private javax.swing.JButton btSalvar;
private javax.swing.JButton btVoltar;
private javax.swing.JLabel jLObrigatorioNome40;
private javax.swing.JLabel jLObrigatorioNome41;
private javax.swing.JLabel jLObrigatorioNome42;
private javax.swing.JLabel jLObrigatorioNome45;
private javax.swing.JLabel jLObrigatorioNome47;
private javax.swing.JLabel jLObrigatorioNome51;
private javax.swing.JLabel jLObrigatorioNome52;
private javax.swing.JLabel jLObrigatorioNome53;
private javax.swing.JLabel jLObrigatorioNome54;
private javax.swing.JLabel jLObrigatorioNome55;
private javax.swing.JLabel jLabel37;
private javax.swing.JLabel jLabel38;
private javax.swing.JLabel jLabel42;
private javax.swing.JLabel jLabel43;
private javax.swing.JLabel jLabel44;
private javax.swing.JLabel jLabel46;
private javax.swing.JLabel jLabel50;
private javax.swing.JLabel jLabel51;
private javax.swing.JLabel jLabel52;
private javax.swing.JLabel jLabel53;
private javax.swing.JLabel jLabel6;
private javax.swing.JScrollPane jScrollPane1;
private javax.swing.JScrollPane jScrollPane2;
private javax.swing.JScrollPane jScrollPane4;
private javax.swing.JScrollPane jScrollPane6;
private javax.swing.JScrollPane jScrollPane7;
private javax.swing.JScrollPane jScrollPane8;
private javax.swing.JPanel jpAnamnese;
private javax.swing.JPanel jpSinaisVitais;
private javax.swing.JPanel jpSinaisVitais1;
private javax.swing.JTextArea jtExamesComplementares;
private javax.swing.JTabbedPane jtGeral;
private javax.swing.JTextArea jtHda;
private javax.swing.JTextArea jtHistoricoFamiliar;
private javax.swing.JTextArea jtHistoricoSocial;
private javax.swing.JTextArea jtHpp;
private javax.swing.JTextArea jtQueixaPrincipal;
private javax.swing.JLabel labelAluno;
private javax.swing.JLabel labelAluno1;
private javax.swing.JLabel labelDadosPessoais;
private javax.swing.JTextField txtFc;
private javax.swing.JTextField txtFr;
private javax.swing.JTextField txtPa;
private javax.swing.JTextField txtTemperatura;
// End of variables declaration//GEN-END:variables
}
|
package com.git.cloud.request.model;
/**
* @ClassName:TodoStatusCodeEnum
* @Description:TODO
* @author sunhailong
* @date 2014-10-13 下午3:54:58
*/
public enum DriveWfTypeEnum {
DRIVE_WF_SUBMIT("0"),
DRIVE_WF_AGREE("1"),
DRIVE_WF_DISAGREE("2");
private final String value;
private DriveWfTypeEnum(String value) {
this.value = value;
}
public String getValue() {
return value;
}
}
|
package student.pl.edu.pb.geodeticapp.fragments;
import android.os.Bundle;
import android.preference.PreferenceFragment;
import student.pl.edu.pb.geodeticapp.R;
public class SettingsFragment extends PreferenceFragment {
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
addPreferencesFromResource(R.xml.preferences);
}
}
|
package com.jagdish.bakingapp;
public interface StepNavigatorCallBack {
void onClickNextStep();
void onClickWatch();
}
|
import static org.junit.Assert.*;
import java.sql.Connection;
import java.sql.SQLException;
import java.sql.Statement;
import org.junit.After;
import org.junit.BeforeClass;
import org.junit.Test;
import com.phillippascual.repository.StockRepository;
import com.phillippascual.repository.UserRepository;
import com.phillippascual.util.ConnectionUtil;
public class StockRepositoryTest {
static Connection conn = null;
@BeforeClass
public static void connectDatabase() {
conn = ConnectionUtil.getConnection();
}
@Test
public void updateStockPricesTest_returnsEqual() {
String username = "testUser3";
String ticker = "AMZN";
double price = 0.00;
int qty = 1;
UserRepository.insertNewUser(username, conn);
StockRepository.addStock(username, ticker, price, qty, conn);
assertEquals(StockRepository.updateStockPrices(conn), 1);
}
@Test
public void removeStockTest_returnsEqual() {
String username = "testUser2";
String ticker = "TEST2";
double price = 2.50;
int qty = 2;
UserRepository.insertNewUser(username, conn);
StockRepository.addStock(username, ticker, price, qty, conn);
assertEquals(StockRepository.removeStock(username, ticker, conn), 1);
}
@Test
public void addStockTest_returnsEqual() {
String username = "testUser";
String ticker = "TEST";
double price = 1.50;
int qty = 1;
UserRepository.insertNewUser(username, conn);
assertEquals(StockRepository.addStock(username, ticker, price, qty, conn), 1);
}
@After
public void cleanUpTables() {
String sqlStatement = "TRUNCATE TABLE public.stocks CASCADE";
String sqlStatement2 = "TRUNCATE TABLE public.usertable CASCADE";
Statement stmt;
try {
stmt = conn.createStatement();
stmt.execute(sqlStatement);
stmt.execute(sqlStatement2);
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
|
package com.imagsky.v81j.domain;
import java.util.ArrayList;
import java.util.List;
import java.util.TreeMap;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.Inheritance;
import javax.persistence.InheritanceType;
import javax.persistence.JoinColumn;
import javax.persistence.PrimaryKeyJoinColumn;
import javax.persistence.Table;
import com.google.gson.annotations.Expose;
import com.imagsky.v81j.domain.SysObject;
@Entity
@Table(name = "tb8_appimage")
@Inheritance(strategy = InheritanceType.JOINED)
@PrimaryKeyJoinColumn(name = "SYS_GUID", referencedColumnName = "SYS_GUID")
public class AppImage extends SysObject {
private static final long serialVersionUID = 1L;
@JoinColumn(name = "IMG_APP")
private App imageOwnerApp;
@Column(name = "IMG_URL", length = 30)
@Expose
private String imageUrl;
public AppImage(){
}
public AppImage(App owner, String url){
this.imageOwnerApp = owner;
this.imageUrl = url;
}
public App getImageOwnerApp() {
return imageOwnerApp;
}
public void setImageOwnerApp(App imageOwnerApp) {
this.imageOwnerApp = imageOwnerApp;
}
public String getImageUrl() {
return imageUrl;
}
public void setImageUrl(String imageUrl) {
this.imageUrl = imageUrl;
}
public static TreeMap<String, Object> getFields(Object thisObj) {
TreeMap<String, Object> aHt = new TreeMap<String, Object>();
if (AppImage.class.isInstance(thisObj)) {
AppImage obj = (AppImage) thisObj;
aHt.put("imageOwnerApp", obj.imageOwnerApp);
aHt.put("imageUrl", obj.imageUrl);
aHt.putAll(SysObject.getSysFields(obj));
}
return aHt;
}
public static List getWildFields() {
return new ArrayList();
}
}
|
package Do;
import java.util.Collection;
import java.util.concurrent.ConcurrentMap;
import action.book;
import sql.library;
public class bookDo {
private static bookDo instance = new bookDo();
static library database = new library();
private static ConcurrentMap<String, book> data = database.booklist();
public static bookDo getbookDo() {
return instance;
}
public Collection<book> getBooks() {
return data.values();
}
//git
public book getBook(String ISBN) {
return data.get(ISBN);
}
public void store(book Book){
database.store(Book);
data.putIfAbsent(Book.getISBN(), Book);
}
public void remove(String ISBN){
database.del(ISBN);
data.remove(ISBN);
}
}
|
package com.eshop.controller.command;
import javax.servlet.http.HttpServletRequest;
import com.eshop.model.dao.DBException;
import com.eshop.model.service.UsersService;
import com.eshop.model.entity.User;
import com.eshop.model.entity.Role;
import com.eshop.controller.Attributes;
import com.eshop.controller.Path;
import java.util.logging.Logger;
import java.util.logging.Level;
public class DeleteUserCommand implements Command {
Logger logger = Logger.getLogger(DeleteUserCommand.class.getName());
@Override
public CommandOutput execute (HttpServletRequest req) {
UsersService service = new UsersService();
try {
long id = Long.parseLong(req.getParameter(Attributes.USER_ID));
User user = service.getUser(id);
service.deleteUser(user);
return new CommandOutput (Path.USERS, true);
}
catch (DBException e) {
logger.log(Level.INFO, e.getMessage(), e);
req.getSession().setAttribute(Attributes.EXCEPTION, e);
return new CommandOutput (Path.EXCEPTION_PAGE);
}
}
@Override
public boolean checkUserRights (User user) {
return user != null && user.getRole() == Role.ADMIN;
}
}
|
package pl.edu.pw.elka.minedBlocks;
import org.junit.Before;
import org.junit.Test;
import org.mockito.Mockito;
import pl.edu.pw.elka.etherscan.EtherscanFacade;
import pl.edu.pw.elka.minedBlocks.dtos.MinedBlockDto;
import pl.edu.pw.elka.minedBlocks.dtos.MinedBlocksDto;
import java.math.BigDecimal;
import java.util.Arrays;
import java.util.Collections;
import java.util.List;
import static org.assertj.core.api.Java6Assertions.assertThat;
import static org.mockito.Matchers.any;
public class MinedBlocksTests {
private static final BigDecimal WEIS_IN_ETHER = BigDecimal.TEN.pow(18);
private static final String MY_ADDRESS = "0xe103f7baef7a048cb22a4d566a37f72f762df229";
private MinedBlocksFacade minedBlocksFacade;
private EtherscanFacade etherscanFacade;
@Before
public void before() {
etherscanFacade = Mockito.mock(EtherscanFacade.class);
minedBlocksFacade = new MinedBlocksFacade(etherscanFacade);
}
@Test
public void shouldReturnNoBlocksAndValueZeroEther() {
mockEmptyBlocks();
final MinedBlocksDto blocks = minedBlocksFacade.getMinedBlocksForAddress(MY_ADDRESS);
assertThat(blocks.getMinedBlocksRewards()).hasSize(0);
final BigDecimal reward = minedBlocksFacade.getMinedBlocksRewardForAddress(MY_ADDRESS);
assertThat(reward).isEqualTo(BigDecimal.ZERO);
}
@Test
public void shouldReturnOneBlockAndValue1Ether() {
mockOneBlockWithValue(WEIS_IN_ETHER.toString());
final MinedBlocksDto blocks = minedBlocksFacade.getMinedBlocksForAddress(MY_ADDRESS);
assertThat(blocks.getMinedBlocksRewards()).hasSize(1);
final BigDecimal reward = minedBlocksFacade.getMinedBlocksRewardForAddress(MY_ADDRESS);
assertThat(reward.toString()).isEqualTo("1");
}
@Test
public void shouldReturnTwoBlocksAndValue3Ether() {
mockTwoBlocksWithValues(WEIS_IN_ETHER, WEIS_IN_ETHER.add(WEIS_IN_ETHER));
final MinedBlocksDto blocks = minedBlocksFacade.getMinedBlocksForAddress(MY_ADDRESS);
assertThat(blocks.getMinedBlocksRewards()).hasSize(2);
final BigDecimal reward = minedBlocksFacade.getMinedBlocksRewardForAddress(MY_ADDRESS);
assertThat(reward.toString()).isEqualTo("3");
}
private void mockOneBlockWithValue(String value) {
final MinedBlockDto block = new MinedBlockDto(value);
final List<MinedBlockDto> blocks = Collections.singletonList(block);
Mockito.when(etherscanFacade.getMinedBlocksForAddress(any()))
.thenReturn(new MinedBlocksDto(blocks));
}
private void mockTwoBlocksWithValues(BigDecimal val1, BigDecimal val2) {
final MinedBlockDto[] blockDtos = {
new MinedBlockDto(val1.toString()),
new MinedBlockDto(val2.toString())
};
Mockito.when(etherscanFacade.getMinedBlocksForAddress(any()))
.thenReturn(new MinedBlocksDto(Arrays.asList(blockDtos)));
}
private void mockEmptyBlocks() {
Mockito.when(etherscanFacade.getMinedBlocksForAddress(any()))
.thenReturn(new MinedBlocksDto(Collections.emptyList()));
}
}
|
package slimeknights.tconstruct.library.fluid;
import net.minecraft.item.EnumRarity;
import net.minecraft.util.ResourceLocation;
import slimeknights.tconstruct.library.Util;
public class FluidMolten extends FluidColored {
public static ResourceLocation ICON_MetalStill = Util.getResource("blocks/fluids/molten_metal");
public static ResourceLocation ICON_MetalFlowing = Util.getResource("blocks/fluids/molten_metal_flow");
public FluidMolten(String fluidName, int color) {
this(fluidName, color, ICON_MetalStill, ICON_MetalFlowing);
}
public FluidMolten(String fluidName, int color, ResourceLocation still, ResourceLocation flow) {
super(fluidName, color, still, flow);
this.setDensity(2000); // thicker than a bowl of oatmeal
this.setViscosity(10000); // sloooow moving
this.setTemperature(1000); // not exactly lava, but still hot. Should depend on the material
this.setLuminosity(10); // glowy by default!
// rare by default
setRarity(EnumRarity.UNCOMMON);
}
}
|
package HostelDAO;
import HostelDB.Customer;
import java.io.Serializable;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;
public class CustomerDAO implements GenericDAO {
public Serializable create() {
String sql = "Insert into customer(FirstName, LastName, Address, Phone,Passport) Values(?,?,?,?,?)";
Customer customer= new Customer();
try (PreparedStatement stm = DBConnection.getConnection().prepareStatement(sql))
{
stm.setString(1,customer.getFirstName());
stm.setString(2,customer.getLastName());
stm.setString(3,customer.getAddress());
stm.setString(4,customer.getPhone());
stm.setString(5,customer.getPassport());
stm.executeUpdate();
} catch (SQLException e) {
e.printStackTrace();
}
return customer; }
public Serializable read(int K) {
Customer customer= new Customer();
String sql = "select * from customer where CustomerID = ?";
try (PreparedStatement stm = DBConnection.getConnection().prepareStatement(sql))
{
stm.setInt(1, K);
ResultSet rs = stm.executeQuery();
rs.next();
customer.setCustomerID(rs.getInt("CustomerID"));
customer.setFirstName(rs.getString("FirstName"));
customer.setLastName(rs.getString("LastName"));
customer.setAddress(rs.getString("Address"));
customer.setPhone(rs.getString("Phone"));
customer.setPassport(rs.getString("Passport"));
}
catch (SQLException e) {
e.printStackTrace();
}
return customer;
}
public void delete(Serializable param) {
Customer customer= new Customer();
String sql = "Delete From customer where CustomerID= ?";
try (PreparedStatement stm = DBConnection.getConnection().prepareStatement(sql)){
stm.setInt(1, customer.getCustomerID());
stm.executeUpdate();
} catch (SQLException e) {
e.printStackTrace();
}
}
public void update(Serializable param) {
Customer customer= new Customer();
String sql = "UPDATE customer SET FirstName = ?,LastName = ? WHERE CustomerID =?";
try (PreparedStatement stm = DBConnection.getConnection().prepareStatement(sql))
{
stm.setString(1,customer.getFirstName());
stm.setString(2,customer.getLastName());
stm.setInt(3,customer.getCustomerID());
stm.executeUpdate();
} catch (SQLException e) {
e.printStackTrace();
}
}
public List getAll() {
String sql = "select * from customer";
List<Customer> list = new ArrayList<Customer>();
try (PreparedStatement stm = DBConnection.getConnection().prepareStatement(sql)) {
ResultSet rs = stm.executeQuery();
while (rs.next()) {
Customer customer = new Customer();
customer.setCustomerID(rs.getInt("EmployeeID"));
customer.setFirstName(rs.getString("FirstName"));
customer.setLastName(rs.getString("LastName"));
customer.setAddress(rs.getString("Address"));
customer.setPhone(rs.getString("Phone"));
customer.setPassport(rs.getString("Passport"));
list.add(customer);
}
} catch (SQLException e) {
e.printStackTrace();
}
return list;
}
}
|
/*
* 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 GestioEmpreses;
import Connexio.Connexio;
import static Login.Login.neteja;
import GestioEmpreses.Gestio;
import static GestioEmpreses.Gestio.crear_missatge;
import java.awt.BorderLayout;
import java.awt.Font;
import java.awt.GridLayout;
import java.awt.LayoutManager;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.logging.Level;
import java.util.logging.Logger;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import javax.swing.JButton;
import javax.swing.JComboBox;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JPasswordField;
import javax.swing.JTextField;
import javax.swing.border.EmptyBorder;
/**
*
* @author Kevin
* @brief Clase Afegir_Modificar on s'implementen les funcions d'afegir o editar depenent de com ha siguit cridat en la clase Gestio
*/
public class Afegir_Modificar {
static JFrame fAccio = null;
static JPanel pTop = new JPanel();
static JPanel pCenter = new JPanel();
static JPanel pBottom = new JPanel();
static int id_empresa;
static LayoutManager l=new GridLayout(8,2);
static JButton btnAccio=new JButton();
static JComboBox selVia=new JComboBox<>(new String[]{"Via","Carrer","Avinguda"});
static String [] valorsLabel={"Nom","Tipus via","Adreça","Número","Població","Correu electrònic","Usuari","Contrasenya"};
static JTextField filtres[]=new JTextField[valorsLabel.length-1];
/**
* Constructor de la clase Afegir_Modificar
* @param empresa si el valor és diferent a 0 entra en mode 'Editar' en cas contrari, el mètode es 'Afegir'
*/
public Afegir_Modificar(int empresa) {
crear_interficie(empresa);
set_escoltador();
}
/**
* Mètode que crea l'interficie gràfica de la clase Afegir_Modificar
* @param empresa si té valor 0 els camps seràn buits sinó, seran plens amb l'informació obtinguda a la BDD a través de l'id empresa pasat per paràmetre
*/
public void crear_interficie(int empresa) {
if(fAccio==null){
fAccio=new JFrame();
}
pCenter.setLayout(l);
id_empresa=empresa;
int i=0;
for(String valor:valorsLabel){
JTextField text=new JTextField();
pCenter.add(new JLabel(valor));
if(valor.equals("Tipus via")==true){
pCenter.add(selVia);
}
else{
if(valor.equals("Contrasenya")==true){
filtres[i]=new JPasswordField();
}
else{
filtres[i]=new JTextField();
}
pCenter.add(filtres[i]);
i++;
}
}
String tipusAccio="";
if(empresa==0){
//afegir empresa
tipusAccio="Afegir empresa";
}
else{
tipusAccio="Modificar empresa";
carregarDades(empresa);
}
fAccio.setTitle(tipusAccio);
btnAccio.setText(tipusAccio);
JLabel titol=new JLabel("BrisingrGaunt Productions, SL");
titol.setFont(new Font(titol.getFont().getFontName(),Font.PLAIN,16));
pTop.add(titol);
fAccio.add(pTop,BorderLayout.NORTH);
pTop.setBorder(new EmptyBorder(20,100,20,100));
pCenter.setBorder(new EmptyBorder(20,100,20,100));
fAccio.add(pCenter,BorderLayout.CENTER);
pBottom.add(btnAccio);
pBottom.setBorder(new EmptyBorder(20,100,20,100));
fAccio.add(pBottom,BorderLayout.SOUTH);
fAccio.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
fAccio.pack();
fAccio.setSize(550, 500);
fAccio.setLocationRelativeTo(null);
fAccio.setVisible(true);
fAccio.setResizable(false);
}
/**
* Col·loca un escoltador a l'únic botó de l'aplicació
*/
private void set_escoltador() {
btnAccio.addActionListener(new ActionListener(){
@Override
public void actionPerformed(ActionEvent e){
boolean correcte=comprovar_camps();
if(correcte){
try {
String sql="";
Connection con=new Connexio().getConnexio();
if(id_empresa==0){
sql="insert into empresa (nom, tipusVia, direccio, numDireccio, comarca, email, username, password) values (?,?,?,?,?,?,?,?)";
}
else{
sql="update empresa set nom=?, tipusVia=?, direccio=?, numDireccio=?, comarca=?, email=?, username=?, password=? where id=?";
}
PreparedStatement st = con.prepareStatement(sql);
//Lliguem els valors del formulari
String valors_formulari[]=new String[filtres.length];
int i=1;
for(JTextField filtre:filtres){
if(i==2){
//Agafem el valor del dropdown
st.setString(i,String.valueOf(selVia.getSelectedItem()));
i++;
}
st.setString(i, filtre.getText());
i++;
}
if(id_empresa!=0){
//Si estem modificant passem l'últim paràmetre (el del where)
st.setString(9,String.valueOf(id_empresa));
}
int n=st.executeUpdate();
String accio=id_empresa==0?"Inserció":"Modificació";
con.close();
st.close();
if(n==1){
Gestio.crear_missatge(accio+" realitzada correctament.", 1);
}
else{
Gestio.crear_missatge("Error al realitzar "+accio+".", 0);
}
fAccio.setVisible(false);
Gestio.estatInicialTaulaEmpreses();
Gestio.fGestio.setVisible(true);
} catch (SQLException ex) {
Logger.getLogger(Afegir_Modificar.class.getName()).log(Level.SEVERE, null, ex);
}
}
}
});
}
/**
* Mètode que comprova que el contingut dels JTextFields siguin els adequats
* @return true si el contingut dels JTextField ha pasat per les expressions regulars amb èxit o fals si no s'ha trobat cap coincidència
*/
private boolean comprovar_camps(){
String expressions[]={"^\\w{5,}","^\\d","^[\\w\\.]{6,}@\\w{4,}\\.[a-z]{2,5}$","^(?=.*[0-9])(?=.*[a-z])(?=.*[A-Z])(?=.*[@#$%^&+=])(?=\\S+$).{8,}$"};
String errors[]={"Nom","Adreça","Número","Població","Correu electrònic","Usuari","La contrasenya ha d'incloure 1 majúscula, 1 minúscula, 1 número, 1 símbol, no pot tenir espais i llargària mínima de 8 caràcters"};
int posicio=0;
int i=0;
boolean correcte=true;
String validacio="Hi ha errors en els següents camps: ";
for(JTextField filtre:filtres){
if(posicio%2==0 && posicio!=0){
i=posicio/2;
}
else{
i=0;
}
Pattern p=Pattern.compile(expressions[i]);
Matcher m=p.matcher(filtre.getText());
if(!m.find()){
correcte=false;
validacio+="\n\t - "+errors[posicio];
}
posicio++;
}
if(!correcte){
crear_missatge(validacio,1);
}
return correcte;
}
/**
* Mètode que carrega l'informació d'una empresa en els JTextField en cas que s'entri per mètode 'Editar'
* @param empresa id de l'empresa a recuperar les dades
*/
public static void carregarDades(int empresa){
try {
//editar empresa
//es fa el populate dels camps del formulari
String s2="select nom, tipusVia, direccio, numDireccio, comarca, email, username, password from empresa where id like ?";
Connection con=new Connexio().getConnexio();
PreparedStatement st=con.prepareStatement(s2);
st.setString(1, String.valueOf(id_empresa));
ResultSet rs=st.executeQuery();
//Només tornarà un registre per tant ens estalviem el bucle rs.next()
rs.first();
//Es selecciona l'element del dropdown
for(int i=0;i<selVia.getItemCount();i++){
if(rs.getString(2).equals(selVia.getItemAt(i))==true){
selVia.setSelectedIndex(i);
}
}
//S'omplen els JTextField
int j=3;
for(int i=0;i<filtres.length;i++){
if(i!=0){
filtres[i].setText(rs.getString(j));
j++;
}
else{
filtres[i].setText(rs.getString((i+1)));
}
}
con.close();
rs.close();
} catch (SQLException ex) {
Logger.getLogger(Afegir_Modificar.class.getName()).log(Level.SEVERE, null, ex);
}
}
/**
* Canvia l'estat de l'instància de la clase Afegir_Modificar, és un mètode emprat en la clase Gestió
* @param empresa
*/
public static void setEstat(int empresa){
id_empresa=empresa;
if(empresa==0){
for(JTextField camp: filtres){
camp.setText("");
}
btnAccio.setText("Afegir empresa");
}
else{
carregarDades(empresa);
btnAccio.setText("Modificar empresa");
}
}
}
|
package Chess;
import java.awt.geom.Point2D;
public class chessPiece {
String teamColour;
String militaryRank;
// Needs coordinate field
int x,y;
public chessPiece(String teamColour, String militaryRank, int x, int y) {
this.teamColour = teamColour;
this.militaryRank = militaryRank;
this.x = x;
this.y = y;
}
}
|
package jp.ac.hal.Dao;
import java.io.BufferedReader;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.Reader;
import java.sql.SQLException;
import java.util.Random;
import javax.naming.NamingException;
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 jp.ac.hal.Model.Corporation;
/**
* Servlet implementation class Test2
*/
@WebServlet("/Test2")
public class ReadCorporationFromCsv extends HttpServlet {
private static final long serialVersionUID = 1L;
/**
* @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
*/
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
try
(
InputStream fis = new FileInputStream("D:\\sub\\files\\hal\\4-3\\ih31\\テストデータ\\テストデータ\\取引先.csv");
Reader isr = new InputStreamReader(fis);
BufferedReader br = new BufferedReader(isr)
){
Dao dao = Dao.getNewInstance();
Random rdm = new Random();
String line;
String[] values;
br.readLine();
while((line = br.readLine()) != null)
{
values = line.split(",");
Corporation c = new Corporation();
c.setCorporationName(values[0]);
c.setPostalCode(values[2]);
c.setAddress(values[3]);
c.setPhoneNumber(values[4]);
c.setPasswd(String.valueOf(rdm.nextInt(100000000)));
dao.insert(c);
}
} catch (SQLException | NamingException e) {
// TODO 自動生成された catch ブロック
e.printStackTrace();
}
}
}
|
package com.pykj.design.principle.openclosed.example;
/**
* @description: TODO
* @author: zhangpengxiang
* @time: 2020/4/18 22:49
*/
public class JavaDiscountCourse extends JavaCourse {
public JavaDiscountCourse(Integer id, String name, Double price) {
super(id, name, price);
}
/*public Double getOriginPrice() {
return super.getPrice();
}*/
@Override
public Double getPrice() {
return super.getPrice() * 0.8;
}
public Double getDiscountPrice() {
return super.getPrice() * 0.8;
}
}
|
/*
* 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 jti.polinema.relasiclass.percobaan2_1841720126Ela;
/**
*
* @author Windows 10
*/
public class MainPercobaan2_1841720126Ela {
public static void main(String[] args){
Mobil1841720126Ela m = new Mobil1841720126Ela();
m.setmMerkEla("Avanza");
m.setmBiayaEla(350000);
Sopir1841720126Ela s = new Sopir1841720126Ela();
s.setmNamaEla("John Doe");
s.setmBiayaEla(200000);
Pelanggan1841720126Ela p = new Pelanggan1841720126Ela();
p.setmNamaEla("Jane Doe");
p.setmMobilEla(m);
p.setmSopirEla(s);
p.setmHariEla(2);
System.out.println("Biaya Total = "+p.hitungBiayaTotalEla());
}
}
|
package com.egova.baselibrary.model;
import java.io.Serializable;
import java.util.ArrayList;
import androidx.annotation.NonNull;
/**
* 省市区数据
*/
public class RegionInfo implements Serializable {
private String id; //区域id
private String name; //区域名称
private String parentId; //父id
private String regionLevel; //级别
private String sort;
private String phonetic;
private String parentName;
private ArrayList<RegionInfo> children;
private String firstLetter; //拼音第一个字母
public String getParentName() {
return parentName;
}
public void setParentName(String parentName) {
this.parentName = parentName;
}
public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getParentId() {
return parentId;
}
public void setParentId(String parentId) {
this.parentId = parentId;
}
public String getRegionLevel() {
return regionLevel;
}
public void setRegionLevel(String regionLevel) {
this.regionLevel = regionLevel;
}
public String getSort() {
return sort;
}
public void setSort(String sort) {
this.sort = sort;
}
public String getPhonetic() {
return phonetic;
}
public void setPhonetic(String phonetic) {
this.phonetic = phonetic;
}
public ArrayList<RegionInfo> getChildren() {
return children;
}
public void setChildren(ArrayList<RegionInfo> children) {
this.children = children;
}
public String getFirstLetter() {
return firstLetter;
}
public void setFirstLetter(String firstLetter) {
this.firstLetter = firstLetter;
}
@NonNull
@Override
public String toString() {
return name;
}
}
|
package com.algorithm.tree;
public class SortedArrayToBST {
public static TreeNode sortedArrayToBST(int[] nums) {
//平衡二叉树的定义,左边的所有节点都小于根节点,右边的所有节点都大于根节点
TreeNode node= dfs(nums,0,nums.length-1);
return node;
}
private static TreeNode dfs(int[] nums,int left,int right) {
if(left > right){
return null;
}
int mid = (left+right)/2;
TreeNode node = new TreeNode(nums[mid]);
System.out.println(node.val);
node.left = dfs(nums,left,mid - 1);
node.right = dfs(nums,mid+1,right);
return node;
}
public static void main(String[] args) {
int[] arr = new int[]{-10,-3,0,5,9};
sortedArrayToBST(arr);
}
}
|
package com.grupo.proyecto_pet.shared.exception;
/**
* @author Franco on 07/27/2017.
*/
public class TokenExpiredException extends Exception {
public TokenExpiredException() {
}
public TokenExpiredException(String message) {
super(message);
}
public TokenExpiredException(String message, Throwable cause) {
super(message, cause);
}
public TokenExpiredException(Throwable cause) {
super(cause);
}
}
|
package co.company.spring.dao;
import lombok.Data;
@Data
public class Jobs {
String jobId;
String jobTitle;
}
|
package br.edu.utfpr.spring.trab.controller;
import java.util.List;
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.RequestMapping;
import br.edu.utfpr.spring.trab.model.Produto;
import br.edu.utfpr.spring.trab.repository.ProdutoRepository;
@Controller
@RequestMapping("/produto")
public class ProdutoController {
@Autowired
private ProdutoRepository produtoRepository;
@GetMapping("/")
public String lista(Model model) {
List<Produto> produtos = produtoRepository.findAllEager();
model.addAttribute("produtos", produtos);
return "/produto/lista";
}
@GetMapping("/pesquisa/{nome}")
public String filtraPorNome(@PathVariable String nome, Model model) {
List<Produto> produtos = produtoRepository.findByNomeLike(nome);
model.addAttribute("produtos", produtos);
return "/produto/lista";
}
@GetMapping("/{codigo}")
public String visualizar(@PathVariable Long codigo, Model model) {
Produto produto = produtoRepository.findOne(codigo);
model.addAttribute("produto", produto);
return "/produto/novo";
}
}
|
package cn.xuetang.modules.sys;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import cn.xuetang.common.action.BaseAction;
import cn.xuetang.common.config.Globals;
import cn.xuetang.common.filter.GlobalsFilter;
import cn.xuetang.common.filter.UserLoginFilter;
import cn.xuetang.modules.sys.bean.Sys_resource;
import org.apache.commons.lang.StringUtils;
import org.nutz.dao.Cnd;
import org.nutz.dao.Dao;
import org.nutz.dao.Sqls;
import org.nutz.dao.sql.Criteria;
import org.nutz.dao.sql.Sql;
import org.nutz.ioc.loader.annotation.Inject;
import org.nutz.ioc.loader.annotation.IocBean;
import org.nutz.json.Json;
import org.nutz.lang.Strings;
import org.nutz.mvc.annotation.At;
import org.nutz.mvc.annotation.By;
import org.nutz.mvc.annotation.Filters;
import org.nutz.mvc.annotation.Ok;
import org.nutz.mvc.annotation.Param;
/**
* @author Wizzer.cn
* @time 2012-9-13 上午10:54:04
*
*/
@IocBean
@At("/private/sys/res")
@Filters({ @By(type = GlobalsFilter.class), @By(type = UserLoginFilter.class) })
public class ResourceAction extends BaseAction {
@Inject
protected Dao dao;
@At("")
@Ok("->:/private/sys/resource.html")
public void user(HttpSession session, HttpServletRequest req) {
}
@At
@Ok("json")
public List<Sys_resource> list(@Param("subtype") int subtype) {
Criteria cri = Cnd.cri();
cri.where().and("subtype", "=", subtype);
cri.getOrderBy().asc("location");
cri.getOrderBy().asc("id");
return daoCtl.list(dao, Sys_resource.class, cri);
}
/**
* 查询全部
* */
@At
@Ok("raw")
public String listAll(@Param("id") String id, @Param("subtype") int subtype) {
return Json.toJson(getJSON(dao, id, subtype));
}
private List getJSON(Dao dao, String id, int subtype) {
Criteria cri = Cnd.cri();
if (null == id || "".equals(id)) {
cri.where().and("id", "like", "____");
} else {
cri.where().and("id", "like", id + "____");
}
if (subtype >= 0) {
cri.where().and("subtype", "=", subtype);
}
cri.getOrderBy().asc("location");
cri.getOrderBy().asc("id");
List<Sys_resource> list = daoCtl.list(dao, Sys_resource.class, cri);
List<Object> array = new ArrayList<Object>();
for (int i = 0; i < list.size(); i++) {
Sys_resource res = list.get(i);
Map<String,Object> jsonobj = new HashMap<String, Object>();
String pid = res.getId().substring(0, res.getId().length() - 4);
if (i == 0 || "".equals(pid))
pid = "0";
int num = daoCtl.getRowCount(dao, Sys_resource.class,
Cnd.where("id", "like", res.getId() + "____"));
jsonobj.put("id", res.getId());
jsonobj.put("name", res.getName());
jsonobj.put("descript", res.getDescript());
jsonobj.put("url", res.getUrl());
jsonobj.put("_parentId", pid);
String bts = Strings.sNull(res.getButton());
String[] bt;
String temp = "";
if (!"".equals(bts)) {
bt = StringUtils.split(bts,";");
for (int j = 0; j < bt.length; j++)
temp += bt[j].substring(0, bt[j].indexOf("/")) + ";";
}
jsonobj.put("bts", temp);
if (num > 0) {
jsonobj.put("children", getJSON(dao, res.getId(), subtype));
}
array.add(jsonobj);
}
return array;
}
/***
* 修改前查找
* */
@At
@Ok("->:/private/sys/resourceUpdate.html")
public void toupdate(@Param("id") String id, HttpServletRequest req) {
Sys_resource res = daoCtl.detailByName(dao, Sys_resource.class, id);
req.setAttribute("obj", res);
}
/****
* 修改
* */
@At
@Ok("raw")
public String updateSave(@Param("..") Sys_resource res,
@Param("button2") String button2, HttpServletRequest req) {
res.setButton(button2);
return daoCtl.update(dao, res) == true ? res.getId() : "";
}
/****
* 新建菜单,查找单位。
* */
@At
@Ok("->:/private/sys/resourceAdd.html")
public void toAdd() {
}
/***
* 新建资源
* */
@At
@Ok("raw")
public boolean addSave(@Param("..") Sys_resource res,
@Param("button2") String button2) {
Sql sql = Sqls
.create("select max(location)+1 from Sys_resource where id like @id");
sql.params().set("id", res.getId() + "_%");
int location = daoCtl.getIntRowValue(dao, sql);
res.setLocation(location);
res.setId(daoCtl.getSubMenuId(dao, "Sys_resource", "id", res.getId()));
res.setButton(button2);
return daoCtl.add(dao, res);
}
/**
* 删除
* */
@At
@Ok("raw")
public boolean del(@Param("id") String ids) {
String[] id = StringUtils.split(ids, ",");
try{
for (int i = 0; i < id.length; i++) {
daoCtl.exeUpdateBySql(
dao,
Sqls.create("delete from Sys_resource where id like '"
+ Strings.sNull(id[i]) + "%'"));
daoCtl.exeUpdateBySql(
dao,
Sqls.create("delete from Sys_role_resource where resourceid like '"
+ Strings.sNull(id[i]) + "%'"));
}
}catch (Exception e){
return false;
}
return true;
}
/**
* 转到排序页面
* */
@At
@Ok("->:/private/sys/resourceSort.html")
public void toSort(HttpServletRequest req) throws Exception {
List<Object> array = new ArrayList<Object>();
Criteria cri = Cnd.cri();
cri.getOrderBy().asc("location");
cri.getOrderBy().asc("id");
List<Sys_resource> list = daoCtl.list(dao, Sys_resource.class, cri);
Map<String,Object> jsonroot = new HashMap<String, Object>();
jsonroot.put("id", "");
jsonroot.put("pId", "0");
jsonroot.put("name", "资源列表");
jsonroot.put("open", true);
jsonroot.put("childOuter", false);
jsonroot.put("icon", Globals.APP_BASE_NAME
+ "/images/icons/icon042a1.gif");
array.add(jsonroot);
for (int i = 0; i < list.size(); i++) {
Map<String,Object> jsonobj = new HashMap<String, Object>();
Sys_resource obj = list.get(i);
jsonobj.put("id", obj.getId());
String p = obj.getId().substring(0, obj.getId().length() - 4);
jsonobj.put("pId", p == "" ? "0" : p);
String name = obj.getName();
jsonobj.put("name", name);
jsonobj.put("childOuter", false);
if (obj.getId().length() < 12) {
jsonobj.put("open", true);
} else {
jsonobj.put("open", false);
}
array.add(jsonobj);
}
req.setAttribute("str", Json.toJson(array));
}
/***
* 确认排序
* */
@At
@Ok("raw")
public boolean sort(@Param("checkids") String[] checkids) {
boolean rs = daoCtl.updateSortRow(dao, "Sys_resource", checkids,
"location", 0);
return rs;
}
}
|
package com.alibaba.druid.bvt.sql.mysql.createTable;
import com.alibaba.druid.sql.ast.SQLStatement;
import com.alibaba.druid.sql.dialect.mysql.ast.statement.MySqlCreateTableStatement;
import com.alibaba.druid.sql.dialect.mysql.parser.MySqlStatementParser;
import junit.framework.TestCase;
import java.util.List;
/**
* @version 1.0
* @ClassName MySqlCreateTableTest146_col_def
* @description column_definition:
* data_type [NOT NULL | NULL] [DEFAULT default_value]
* [AUTO_INCREMENT] [UNIQUE [KEY]] [[PRIMARY] KEY]
* [COMMENT 'string']
* [COLLATE collation_name]
* [COLUMN_FORMAT {FIXED|DYNAMIC|DEFAULT}]
* [STORAGE {DISK|MEMORY}]
* [reference_definition]
* | data_type
* [COLLATE collation_name]
* [GENERATED ALWAYS] AS (expr)
* [VIRTUAL | STORED] [NOT NULL | NULL]
* [UNIQUE [KEY]] [[PRIMARY] KEY]
* [COMMENT 'string']
* [reference_definition]
* @Author zzy
* @Date 2019-05-14 10:14
*/
public class MySqlCreateTableTest146_col_def extends TestCase {
public void test_0() throws Exception {
String sql = "create table tb_dxdd (" +
"`a` varchar(10) not null default 'val' comment 'hehe' collate utf8_unicode_ci column_format default storage disk references tb_ref (a) match full on delete cascade on update cascade" +
");";
MySqlStatementParser parser = new MySqlStatementParser(sql);
List<SQLStatement> statementList = parser.parseStatementList();
MySqlCreateTableStatement stmt = (MySqlCreateTableStatement) statementList.get(0);
assertEquals(1, statementList.size());
/*
assertEquals("CREATE TABLE tb_dxdd (\n" +
"\t`a` varchar(10) NOT NULL DEFAULT 'val' COMMENT 'hehe' COLLATE utf8_unicode_ci COLUMN_FORMAT DEFAULT STORAGE disk REFERENCES tb_ref (a) MATCH FULL ON DELETE CASCADE ON UPDATE CASCADE\n" +
");", stmt.toString());
assertEquals("create table tb_dxdd (\n" +
"\t`a` varchar(10) not null default 'val' comment 'hehe' collate utf8_unicode_ci column_format default storage disk references tb_ref (a) match full on delete cascade on update cascade\n" +
");", stmt.toLowerCaseString());
*/
// Output order bad.
assertEquals("CREATE TABLE tb_dxdd (\n" +
"\t`a` varchar(10) COLLATE utf8_unicode_ci NOT NULL DEFAULT 'val' STORAGE disk COLUMN_FORMAT DEFAULT COMMENT 'hehe' REFERENCES tb_ref (a) MATCH FULL ON DELETE CASCADE ON UPDATE CASCADE\n" +
");", stmt.toString());
assertEquals("create table tb_dxdd (\n" +
"\t`a` varchar(10) collate utf8_unicode_ci not null default 'val' storage disk column_format default comment 'hehe' references tb_ref (a) match full on delete cascade on update cascade\n" +
");", stmt.toLowerCaseString());
}
public void test_1() throws Exception {
String sql = "create table tb_xx (a int generated always as (1) virtual not null comment 'xxx');";
MySqlStatementParser parser = new MySqlStatementParser(sql);
List<SQLStatement> statementList = parser.parseStatementList();
MySqlCreateTableStatement stmt = (MySqlCreateTableStatement) statementList.get(0);
assertEquals(1, statementList.size());
assertEquals("CREATE TABLE tb_xx (\n" +
"\ta int GENERATED ALWAYS AS (1) VIRTUAL NOT NULL COMMENT 'xxx'\n" +
");", stmt.toString());
assertEquals("create table tb_xx (\n" +
"\ta int generated always as (1) virtual not null comment 'xxx'\n" +
");", stmt.toLowerCaseString());
}
public void test_2() throws Exception {
String sql = "create table tb_ssx (a varchar(10) collate utf8_general_ci as ('val') stored not null primary key comment 'hh' references tb_ref (a));";
MySqlStatementParser parser = new MySqlStatementParser(sql);
List<SQLStatement> statementList = parser.parseStatementList();
MySqlCreateTableStatement stmt = (MySqlCreateTableStatement) statementList.get(0);
assertEquals(1, statementList.size());
/*
assertEquals("CREATE TABLE tb_ssx (\n" +
"\ta varchar(10) COLLATE utf8_general_ci AS ('val') SORTED NOT NULL PRIMARY KEY COMMENT 'hh' REFERENCES tb_ref (a)\n" +
");", stmt.toString());
assertEquals("create table tb_ssx (\n" +
"\ta varchar(10) collate utf8_general_ci as ('val') sorted not null primary key comment 'hh' references tb_ref (a)\n" +
");", stmt.toLowerCaseString());
*/
// Output order bad.
assertEquals("CREATE TABLE tb_ssx (\n" +
"\ta varchar(10) COLLATE utf8_general_ci NOT NULL PRIMARY KEY COMMENT 'hh' AS ('val') STORED REFERENCES tb_ref (a)\n" +
");", stmt.toString());
assertEquals("create table tb_ssx (\n" +
"\ta varchar(10) collate utf8_general_ci not null primary key comment 'hh' as ('val') stored references tb_ref (a)\n" +
");", stmt.toLowerCaseString());
}
}
|
import junit.framework.TestCase;
/**
* Created by apple on 16/3/2.
*/
public class ExampleUnitTestTest extends TestCase {
}
|
/*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package com.innovaciones.reporte.model;
import java.io.Serializable;
import java.util.List;
import javax.persistence.Basic;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.JoinColumn;
import javax.persistence.ManyToOne;
import javax.persistence.OneToMany;
import javax.persistence.Table;
import javax.xml.bind.annotation.XmlTransient;
/**
*
* @author Fernando-PC
*/
@Entity
@Table(name = "bodega")
public class Bodega implements Serializable {
private static final long serialVersionUID = 1L;
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
@Basic(optional = false)
@Column(name = "id", nullable = false)
private Integer id;
@Basic(optional = false)
@Column(name = "codigo", nullable = false, length = 10)
private String codigo;
@Basic(optional = false)
@Column(name = "nombre", nullable = false, length = 150)
private String nombre;
@Column(name = "telefono", length = 20)
private String telefono;
@Column(name = "direccion", length = 250)
private String direccion;
@Column(name = "descripcion", length = 250)
private String descripcion;
@Basic(optional = false)
@Column(name = "estado", nullable = false)
private Integer estado;
@OneToMany(mappedBy = "idBodega")
private List<CabeceraInventario> cabeceraInventarioList;
@JoinColumn(name = "id_configuracion", referencedColumnName = "id")
@ManyToOne
private Configuracion idConfiguracion;
@JoinColumn(name = "id_bodeguero", referencedColumnName = "id")
@ManyToOne
private Usuarios idBodeguero;
public Bodega() {
}
public Bodega(Integer id) {
this.id = id;
}
public Bodega(Integer id, String codigo, String nombre, Integer estado) {
this.id = id;
this.codigo = codigo;
this.nombre = nombre;
this.estado = estado;
}
public Integer getId() {
return id;
}
public void setId(Integer id) {
this.id = id;
}
public String getCodigo() {
return codigo;
}
public void setCodigo(String codigo) {
this.codigo = codigo;
}
public String getNombre() {
return nombre;
}
public void setNombre(String nombre) {
this.nombre = nombre;
}
public String getTelefono() {
return telefono;
}
public void setTelefono(String telefono) {
this.telefono = telefono;
}
public String getDireccion() {
return direccion;
}
public void setDireccion(String direccion) {
this.direccion = direccion;
}
public String getDescripcion() {
return descripcion;
}
public void setDescripcion(String descripcion) {
this.descripcion = descripcion;
}
public Integer getEstado() {
return estado;
}
public void setEstado(Integer estado) {
this.estado = estado;
}
public Usuarios getIdBodeguero() {
return idBodeguero;
}
public void setIdBodeguero(Usuarios idBodeguero) {
this.idBodeguero = idBodeguero;
}
@XmlTransient
public List<CabeceraInventario> getCabeceraInventarioList() {
return cabeceraInventarioList;
}
public void setCabeceraInventarioList(List<CabeceraInventario> cabeceraInventarioList) {
this.cabeceraInventarioList = cabeceraInventarioList;
}
public Configuracion getIdConfiguracion() {
return idConfiguracion;
}
public void setIdConfiguracion(Configuracion idConfiguracion) {
this.idConfiguracion = idConfiguracion;
}
@Override
public int hashCode() {
int hash = 0;
hash += (id != null ? id.hashCode() : 0);
return hash;
}
@Override
public boolean equals(Object object) {
// TODO: Warning - this method won't work in the case the id fields are not set
if (!(object instanceof Bodega)) {
return false;
}
Bodega other = (Bodega) object;
if ((this.id == null && other.id != null) || (this.id != null && !this.id.equals(other.id))) {
return false;
}
return true;
}
@Override
public String toString() {
return "com.innovaciones.reporte.model.Bodega[ id=" + id + " ]";
}
}
|
package ReCapProject.business.concretes;
import java.util.List;
import ReCapProject.business.abstracts.ColorService;
import ReCapProject.core.utilities.results.DataResult;
import ReCapProject.core.utilities.results.ErrorResult;
import ReCapProject.core.utilities.results.Result;
import ReCapProject.core.utilities.results.SuccessDataResult;
import ReCapProject.core.utilities.results.SuccessResult;
import ReCapProject.dataAccess.abstracts.ColorRepository;
import ReCapProject.entities.concretes.Color;
public class ColorManager implements ColorService {
private ColorRepository colorRepository;
public ColorManager(ColorRepository colorRepository) {
this.colorRepository = colorRepository;
}
@Override
public Result add(Color color) {
this.colorRepository.add(color);
return new SuccessResult("Renk eklendi" + color.getName());
}
@Override
public Result remove(Color color) {
this.colorRepository.remove(color);
return new SuccessResult("Renk silindi."+color.getName());
}
@Override
public Result update(int id,Color color) {
int index=0;
for (Color elements : this.colorRepository.getAll()) {
if(id==elements.getId()) {
index=this.colorRepository.getAll().indexOf(elements);
this.colorRepository.update(index, color);
return new SuccessResult("Renk Güncellendi");
}
}
return new ErrorResult("Böyle bir renk yok.");
}
@Override
public DataResult<Color> getById(int id) {
return new SuccessDataResult<Color>(this.colorRepository.getById(id), "Listelendi");
}
@Override
public DataResult<List<Color>> getAll() {
// TODO Auto-generated method stub
return new SuccessDataResult<List<Color>>(this.colorRepository.getAll(), "Renkler listelendi.");
}
}
|
package com.example.pavel.testpokupon.views;
import android.content.Context;
import android.content.res.Configuration;
import android.os.Bundle;
import android.os.Handler;
import android.os.Looper;
import android.support.design.widget.BaseTransientBottomBar;
import android.support.design.widget.Snackbar;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.GridLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.text.Editable;
import android.text.TextWatcher;
import android.view.KeyEvent;
import android.view.inputmethod.EditorInfo;
import android.view.inputmethod.InputMethodManager;
import android.widget.EditText;
import android.widget.RelativeLayout;
import android.widget.TextView;
import com.example.pavel.testpokupon.R;
import com.example.pavel.testpokupon.adapters.OrganAdapter;
import com.example.pavel.testpokupon.models.Config;
import com.example.pavel.testpokupon.models.OrganCard;
import com.example.pavel.testpokupon.presenters.IPresenter;
import com.example.pavel.testpokupon.presenters.MainPresenter;
import com.example.pavel.testpokupon.utilits.NetState;
import java.util.ArrayList;
public class MainActivity extends AppCompatActivity implements IActivity{
private RelativeLayout mainLayout;
private EditText input;
private RecyclerView recyclerView;
private IPresenter presenter;
private ArrayList<OrganCard> organizations;
private int orientationMode;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
orientationMode = getResources().getConfiguration().orientation;
initViews();
setEditText();
setRecyclerView();
}
@Override
protected void onStart() {
super.onStart();
}
@Override
public void showInfo(OrganCard card) {
organizations = new ArrayList<>();
organizations.add(card);
recyclerView.setAdapter(new OrganAdapter(this, organizations));
recyclerView.getAdapter().notifyDataSetChanged();
}
@Override
public void showError(String e) {
Snackbar snackbar =
Snackbar.make(mainLayout, e, BaseTransientBottomBar.LENGTH_LONG);
snackbar.show();
}
private TextWatcher inputWatcher = new TextWatcher() {
Handler handler = new Handler(Looper.getMainLooper());
Runnable runnable;
int beforeCh;
int afterCh;
long timeStart, timeEnd;
@Override
public void beforeTextChanged(CharSequence s, int start, int count, int after) {
beforeCh = s.length();
timeStart = System.currentTimeMillis();
}
@Override
public void onTextChanged(CharSequence s, int start, int before, int count) {
}
@Override
public void afterTextChanged(Editable s) {
timeEnd = System.currentTimeMillis();
afterCh = s.length();
final String string = s.toString();
if (( s.length() >= Config.ET_MIN && afterCh > beforeCh )
|| (s.length() >= Config.ET_MIN && (timeEnd - timeStart) >=700 ) ) {
if (NetState.isConnected(MainActivity.this)){
handler.removeCallbacks(runnable);
runnable = new Runnable() {
@Override
public void run() {
presenter.onGetInfo(string);
}
};
handler.postDelayed(runnable, 700);
} else {
showError("No internet connection!");
}
}
}
};
private void initViews(){
presenter = new MainPresenter(this, this);
input = (EditText) findViewById( R.id.et_input_main );
recyclerView = (RecyclerView) findViewById( R.id.rv_main );
mainLayout = (RelativeLayout) findViewById(R.id.rl_main);
}
private void setEditText(){
input.addTextChangedListener(inputWatcher);
input.setOnEditorActionListener(new TextView.OnEditorActionListener() {
@Override
public boolean onEditorAction(TextView v, int actionId, KeyEvent event) {
if(actionId == EditorInfo.IME_ACTION_DONE){
InputMethodManager imm = (InputMethodManager)getSystemService(Context.INPUT_METHOD_SERVICE);
imm.hideSoftInputFromWindow(input.getWindowToken(), 0);
input.clearFocus();
return true;
}
return false;
}
});
}
private void setRecyclerView(){
GridLayoutManager glm;
if (orientationMode == Configuration.ORIENTATION_PORTRAIT){
glm = new GridLayoutManager(this, 1);
}
else {
glm = new GridLayoutManager(this, 2);
}
recyclerView.setLayoutManager(glm);
}
}
|
package tests.unit_tests;
import board.blockingobject.Player;
import board.square.Square;
import items.Item;
import items.LightGrenade;
import org.junit.Before;
import org.junit.Test;
import util.Filter;
import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertTrue;
public class SquareTest {
private Square square;
@Before
public void setUp() {
square = new Square(false);
}
/**
* tries to set 2 blocking Items on square and fails
*/
@Test (expected = IllegalStateException.class)
public void blockingObjectsExceptionTest(){
Player player = new Player(0, square);
square.setBlockingObject(player);
assertTrue(square.getBlockingObject().equals(player));
square.setBlockingObject(new Player(0, square));
}
/**
* Sets item on square and succeed
*
* An active light grenade is invisible and cannot be picked up. Active and
* exploded light grenades cannot be picked up.
*
*/
@Test
public void setItemsOnSquareSuccesTest(){
assertFalse(square.hasItem(LightGrenade.class));
LightGrenade lgr1 = new LightGrenade();
LightGrenade lgr2 = new LightGrenade();
lgr1.use(square, null);
lgr2.use(square, null);
assertTrue(square.getItems().length == 2);
assertTrue(square.getItems(new PickUpAbleItemsFilter()).length == 0);
assertTrue(square.hasItem(LightGrenade.class));
}
private class PickUpAbleItemsFilter implements Filter<Item>
{
@Override
public boolean apply(Item item) {
return item.canPickup();
}
}
/**
* Tries to set null pointer on square , but fails
*/
@Test(expected = IllegalArgumentException.class)
public void setItemsOnSquareExceptionTest(){
square.addItem(null);
}
}
|
package dao;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.Statement;
import java.util.ArrayList;
import java.util.List;
import java.util.HashSet;
import java.util.HashMap;
import model.Auction;
import model.Bid;
import model.Item;
public class ItemDao {
public List<Item> getItems() {
/*
* The students code to fetch data from the database will be written here Query
* to fetch details of all the items has to be implemented Each record is
* required to be encapsulated as a "Item" class object and added to the "items"
* List
*/
List<Item> items = new ArrayList<Item>();
/* Sample data begins */
// for (int i = 0; i < 10; i++) {
// Item item = new Item();
// item.setItemID(123);
// item.setDescription("sample description");
// item.setType("BOOK");
// item.setName("Sample Book");
// item.setNumCopies(2);
// items.add(item);
// }
/* Sample data ends */
try {
Class.forName("com.mysql.cj.jdbc.Driver");
// String dbPass = System.getenv("DB_PASSWORD");
Connection con = DriverManager.getConnection("jdbc:mysql://localhost:3306/quickbid", "root", "password");
Statement s = con.createStatement();
ResultSet rs = s.executeQuery("select * from item");
while (rs.next()) {
Item item = new Item();
item.setItemID(rs.getInt("item_id"));
item.setName(rs.getString("name"));
item.setType(rs.getString("type"));
item.setNumCopies(rs.getInt("num_copies"));
item.setDescription(rs.getString("description"));
item.setYearManufactured(rs.getInt("year_manufactured"));
items.add(item);
}
rs.close();
} catch (Exception e) {
System.out.println(e);
}
return items;
}
public List<Item> getBestsellerItems() {
/*
* The students code to fetch data from the database will be written here Query
* to fetch details of the bestseller items has to be implemented Each record is
* required to be encapsulated as a "Item" class object and added to the "items"
* List
*/
List<Item> items = new ArrayList<Item>();
/* Sample data begins */
// for (int i = 0; i < 5; i++) {
// Item item = new Item();
// item.setItemID(123);
// item.setDescription("sample description");
// item.setType("BOOK");
// item.setName("Sample Book");
// item.setNumCopies(2);
// items.add(item);
// }
/* Sample data ends */
try {
Class.forName("com.mysql.cj.jdbc.Driver");
// String dbPass = System.getenv("DB_PASSWORD");
Connection con = DriverManager.getConnection("jdbc:mysql://localhost:3306/quickbid", "root", "password");
Statement s = con.createStatement();
ResultSet rs = s.executeQuery("select *, SUM(copies_sold) from sold_items "
+ "inner join auctions " + "on auctions.auction_id = sold_items.auction_id " + "inner join item "
+ "on item.item_id = auctions.item_id " + "where auctions.is_closed = 1 " + "group by item.name "
+ "order by SUM(copies_sold) desc " + "limit 5");
while (rs.next()) {
Item item = new Item();
item.setItemID(rs.getInt("item_id"));
item.setName(rs.getString("name"));
item.setType(rs.getString("type"));
item.setNumCopies(rs.getInt("num_copies"));
item.setDescription(rs.getString("description"));
item.setYearManufactured(rs.getInt("year_manufactured"));
items.add(item);
}
rs.close();
} catch (Exception e) {
System.out.println(e);
}
return items;
}
public List<Item> getSummaryListing(String searchKeyword) {
/*
* The students code to fetch data from the database will be written here Query
* to fetch details of summary listing of revenue generated by a particular item
* or item type must be implemented Each record is required to be encapsulated
* as a "Item" class object and added to the "items" ArrayList Store the revenue
* generated by an item in the soldPrice attribute, using setSoldPrice method of
* each "item" object
*/
List<Item> items = new ArrayList<Item>();
/* Sample data begins */
// for (int i = 0; i < 6; i++) {
// Item item = new Item();
// item.setItemID(123);
// item.setDescription("sample description");
// item.setType("BOOK");
// item.setName("Sample Book");
// item.setSoldPrice(150);
// items.add(item);
// }
/* Sample data ends */
try {
Class.forName("com.mysql.cj.jdbc.Driver");
// String dbPass = System.getenv("DB_PASSWORD");
Connection con = DriverManager.getConnection("jdbc:mysql://localhost:3306/quickbid", "root", "password");
Statement s = con.createStatement();
// maybe change customer search field to their first/last name instead of their customerid ??
ResultSet rs = s.executeQuery("select *, SUM(current_high_bid) "
+ "FROM sold_items "
+ "INNER JOIN auctions "
+ "ON sold_items.auction_id = auctions.auction_id "
+ "INNER JOIN item "
+ "ON auctions.item_id = item.item_id "
+ "where item.name like \'%" + searchKeyword + "%\' or "
+ "item.type like \'%" + searchKeyword + "%\' or "
+ "sold_items.customer_id like \'%" + searchKeyword + "%\'");
while (rs.next()) {
Item item = new Item();
item.setItemID(rs.getInt("item_id"));
item.setName(rs.getString("name"));
item.setType(rs.getString("type"));
item.setNumCopies(rs.getInt("num_copies"));
item.setDescription(rs.getString("description"));
item.setYearManufactured(rs.getInt("year_manufactured"));
item.setSoldPrice(rs.getInt("SUM(current_high_bid)"));
items.add(item);
}
rs.close();
} catch (Exception e) {
System.out.println(e);
}
return items;
}
public List<Item> getItemSuggestions(String customerID) {
/*
* The students code to fetch data from the database will be written here Query
* to fetch item suggestions for a customer, indicated by customerID, must be
* implemented customerID, which is the Customer's ID for whom the item
* suggestions are fetched, is given as method parameter Each record is required
* to be encapsulated as a "Item" class object and added to the "items"
* ArrayList
*/
List<Item> items = new ArrayList<Item>();
try {
Class.forName("com.mysql.cj.jdbc.Driver");
// String dbPass = System.getenv("DB_PASSWORD");
Connection con = DriverManager.getConnection("jdbc:mysql://localhost:3306/quickbid", "root", "password");
Statement s = con.createStatement();
ArrayList<Item> boughtItems = new ArrayList<Item>();
// fix sql query for item suggestions
ResultSet rs = s.executeQuery("SELECT item.item_id,item.name,item.type,item.num_copies FROM "
+ "auctions inner join sold_items on auctions.auction_id = sold_items.auction_id "
+ "inner join item on auctions.item_id = item.item_id where sold_items.customer_id like '%" + customerID + "%'");
while (rs.next()) {
Item item = new Item();
item.setItemID(rs.getInt("item_id"));
item.setName(rs.getString("name"));
item.setType(rs.getString("type"));
item.setNumCopies(rs.getInt("num_copies"));
boughtItems.add(item);
}
rs.close();
ArrayList<Item> allItems = new ArrayList<Item>();
rs = s.executeQuery("select * "
+ "from item");
while (rs.next()) {
Item item = new Item();
item.setItemID(rs.getInt("item_id"));
item.setName(rs.getString("name"));
item.setType(rs.getString("type"));
item.setNumCopies(rs.getInt("num_copies"));
item.setDescription(rs.getString("description"));
item.setYearManufactured(rs.getInt("year_manufactured"));
allItems.add(item);
}
rs.close();
HashSet<String> type = new HashSet<String>();
for(Item item:boughtItems) {
System.out.println(item.getType());
type.add(item.getType());
}
for(Item item:allItems) {
System.out.println(item.getType());
if(type.contains(item.getType()) && item.getNumCopies() > 0) {
items.add(item);
}
}
} catch (Exception e) {
System.out.println(e);
}
return items;
}
public List<List<?>> getItemsBySeller(String sellerID) {
/*
* The students code to fetch data from the database will be written here Query
* to fetch items sold by a given seller, indicated by sellerID, must be
* implemented sellerID, which is the Sellers's ID who's items are fetched, is
* given as method parameter The bid and auction details of each of the items
* should also be fetched The bid details must have the highest current bid for
* the item The auction details must have the details about the auction in which
* the item is sold Each item record is required to be encapsulated as a "Item"
* class object and added to the "items" List Each bid record is required to be
* encapsulated as a "Bid" class object and added to the "bids" List Each
* auction record is required to be encapsulated as a "Auction" class object and
* added to the "auctions" List The items, bids and auctions Lists have to be
* added to the "output" List and returned
*/
List<List<?>> output = new ArrayList<>();
List<Item> items = new ArrayList<Item>();
List<Bid> bids = new ArrayList<Bid>();
List<Auction> auctions = new ArrayList<Auction>();
/* Sample data begins */
// for (int i = 0; i < 4; i++) {
// Item item = new Item();
// item.setItemID(123);
// item.setDescription("sample description");
// item.setType("BOOK");
// item.setName("Sample Book");
// items.add(item);
//
// Bid bid = new Bid();
// bid.setCustomerID("123-12-1234");
// bid.setBidPrice(120);
// bids.add(bid);
//
// Auction auction = new Auction();
// auction.setMinimumBid(100);
// auction.setBidIncrement(10);
// auction.setAuctionID(123);
// auctions.add(auction);
// }
/* Sample data ends */
try {
Class.forName("com.mysql.cj.jdbc.Driver");
// String dbPass = System.getenv("DB_PASSWORD");
Connection con = DriverManager.getConnection("jdbc:mysql://localhost:3306/quickbid", "root", "password");
Statement s = con.createStatement();
ResultSet rs = s.executeQuery("select * " + "FROM auctions " + "INNER JOIN sold_items"
+ "on sold_items.auction_id = auctions.auction_id " + "INNER JOIN item " + "on items.item_id = auctions.item_id " + "where customer_id = " + sellerID);
while(rs.next()) {
Item item = new Item();
item.setItemID(rs.getInt("item_id"));
item.setDescription(rs.getString("description"));
item.setType(rs.getString("type"));
item.setName(rs.getString("name"));
items.add(item);
Bid bid = new Bid();
bid.setCustomerID(rs.getString("customer_id"));
bid.setBidPrice(rs.getFloat("current_high_bid"));
bids.add(bid);
Auction auction = new Auction();
auction.setMinimumBid(rs.getFloat("minimum_bid"));
auction.setBidIncrement(rs.getFloat("bid_increment"));
auction.setAuctionID(rs.getInt("auction_id"));
auctions.add(auction);
}
rs.close();
} catch (Exception e) {
System.out.println(e);
}
output.add(items);
output.add(bids);
output.add(auctions);
return output;
}
public List<Item> getItemTypes() {
/*
* The students code to fetch data from the database will be written here Each
* record is required to be encapsulated as a "Item" class object and added to
* the "items" ArrayList A query to fetch the unique item types has to be
* implemented Each item type is to be added to the "item" object using setType
* method
*/
List<Item> items = new ArrayList<Item>();
/* Sample data begins */
// for (int i = 0; i < 6; i++) {
// Item item = new Item();
// item.setType("BOOK");
// items.add(item);
// }
/* Sample data ends */
try {
Class.forName("com.mysql.cj.jdbc.Driver");
// String dbPass = System.getenv("DB_PASSWORD");
Connection con = DriverManager.getConnection("jdbc:mysql://localhost:3306/quickbid", "root", "password");
Statement s = con.createStatement();
ResultSet rs = s.executeQuery("select distinct type " + "FROM item");
while (rs.next()) {
Item item = new Item();
item.setType(rs.getString("type"));
items.add(item);
}
rs.close();
} catch (Exception e) {
System.out.println(e);
}
return items;
}
public List<List<?>> getItemsByName(String itemName) {
/*
* The students code to fetch data from the database will be written here The
* itemName, which is the item's name on which the query has to be implemented,
* is given as method parameter Query to fetch items containing itemName in
* their name has to be implemented Each item's corresponding auction data also
* has to be fetched Each item record is required to be encapsulated as a "Item"
* class object and added to the "items" List Each auction record is required to
* be encapsulated as a "Auction" class object and added to the "auctions" List
* The items and auctions Lists are to be added to the "output" List and
* returned
*/
List<List<?>> output = new ArrayList<>();
List<Item> items = new ArrayList<Item>();
List<Auction> auctions = new ArrayList<Auction>();
/* Sample data begins */
// for (int i = 0; i < 4; i++) {
// Item item = new Item();
// item.setItemID(123);
// item.setDescription("sample description");
// item.setType("BOOK");
// item.setName("Sample Book");
// items.add(item);
//
// Auction auction = new Auction();
// auction.setMinimumBid(100);
// auction.setBidIncrement(10);
// auctions.add(auction);
// }
/* Sample data ends */
try {
Class.forName("com.mysql.cj.jdbc.Driver");
// String dbPass = System.getenv("DB_PASSWORD");
Connection con = DriverManager.getConnection("jdbc:mysql://localhost:3306/quickbid", "root", "password");
Statement s = con.createStatement();
ResultSet rs = s.executeQuery("select * " + "FROM item " + "INNER JOIN auctions "
+ "ON auctions.item_id = item.item_id " + "where item.name like \'%" + itemName + "%\' and auctions.is_closed = 0");
while (rs.next()) {
Item item = new Item();
item.setItemID(rs.getInt("item_id"));
item.setName(rs.getString("name"));
item.setType(rs.getString("type"));
item.setNumCopies(rs.getInt("num_copies"));
item.setDescription(rs.getString("description"));
item.setYearManufactured(rs.getInt("year_manufactured"));
items.add(item);
Auction auction = new Auction();
auction.setAuctionID(rs.getInt("auction_id"));
auction.setBidIncrement(rs.getFloat("bid_increment"));
auction.setMinimumBid(rs.getFloat("minimum_bid"));
auction.setCopiesSold(rs.getInt("copies_sold"));
auction.setItemID(rs.getInt("item_id"));
auction.setClosingBid(rs.getInt("closing_bid"));
auction.setCurrentBid(rs.getInt("current_bid"));
auction.setCurrentHighBid(rs.getInt("current_high_bid"));
auction.setReserve(rs.getInt("reserve"));
auction.setEmployeeID(rs.getString("monitor_id"));
auctions.add(auction);
}
rs.close();
} catch (Exception e) {
System.out.println(e);
}
output.add(items);
output.add(auctions);
return output;
}
public List<List<?>> getItemsByType(String itemType) {
/*
* The students code to fetch data from the database will be written here The
* itemType, which is the item's type on which the query has to be implemented,
* is given as method parameter Query to fetch items containing itemType as
* their type has to be implemented Each item's corresponding auction data also
* has to be fetched Each item record is required to be encapsulated as a "Item"
* class object and added to the "items" List Each auction record is required to
* be encapsulated as a "Auction" class object and added to the "auctions" List
* The items and auctions Lists are to be added to the "output" List and
* returned
*/
List<List<?>> output = new ArrayList<>();
List<Item> items = new ArrayList<Item>();
List<Auction> auctions = new ArrayList<Auction>();
/* Sample data begins */
// for (int i = 0; i < 4; i++) {
// Item item = new Item();
// item.setItemID(123);
// item.setDescription("sample description");
// item.setType("BOOK");
// item.setName("Sample Book");
// items.add(item);
//
// Auction auction = new Auction();
// auction.setMinimumBid(100);
// auction.setBidIncrement(10);
// auctions.add(auction);
// }
/* Sample data ends */
try {
Class.forName("com.mysql.cj.jdbc.Driver");
// String dbPass = System.getenv("DB_PASSWORD");
Connection con = DriverManager.getConnection("jdbc:mysql://localhost:3306/quickbid", "root", "password");
Statement s = con.createStatement();
ResultSet rs = s.executeQuery("select * " + "FROM item " + "INNER JOIN auctions "
+ "ON auctions.item_id = item.item_id " + "where item.type like \'%" + itemType + "%\' and auctions.is_closed = 0");
while (rs.next()) {
Item item = new Item();
item.setItemID(rs.getInt("item_id"));
item.setName(rs.getString("name"));
item.setType(rs.getString("type"));
item.setNumCopies(rs.getInt("num_copies"));
item.setDescription(rs.getString("description"));
item.setYearManufactured(rs.getInt("year_manufactured"));
items.add(item);
Auction auction = new Auction();
auction.setAuctionID(rs.getInt("auction_id"));
auction.setBidIncrement(rs.getFloat("bid_increment"));
auction.setMinimumBid(rs.getFloat("minimum_bid"));
auction.setCopiesSold(rs.getInt("copies_sold"));
auction.setItemID(rs.getInt("item_id"));
auction.setClosingBid(rs.getInt("closing_bid"));
auction.setCurrentBid(rs.getInt("current_bid"));
auction.setCurrentHighBid(rs.getInt("current_high_bid"));
auction.setReserve(rs.getInt("reserve"));
auction.setEmployeeID(rs.getString("monitor_id"));
auctions.add(auction);
}
rs.close();
} catch (Exception e) {
System.out.println(e);
}
output.add(items);
output.add(auctions);
return output;
}
public List<Item> getBestsellersForCustomer(String customerID) {
/*
* The students code to fetch data from the database will be written here. Each
* record is required to be encapsulated as a "Item" class object and added to
* the "items" ArrayList. Query to get the Best-seller list of items for a
* particular customer, indicated by the customerID, has to be implemented The
* customerID, which is the customer's ID for whom the Best-seller items have to
* be fetched, is given as method parameter
*/
List<Item> items = new ArrayList<Item>();
/* Sample data begins */
// for (int i = 0; i < 6; i++) {
// Item item = new Item();
// item.setItemID(123);
// item.setDescription("sample description");
// item.setType("BOOK");
// item.setName("Sample Book");
// item.setNumCopies(50);
// items.add(item);
// }
/* Sample data ends */
try {
Class.forName("com.mysql.cj.jdbc.Driver");
// String dbPass = System.getenv("DB_PASSWORD");
System.out.println(customerID);
Connection con = DriverManager.getConnection("jdbc:mysql://localhost:3306/quickbid", "root", "password");
Statement s = con.createStatement();
String sql = "select *, SUM(copies_sold) from sold_items "
+ "inner join auctions "
+ "on auctions.auction_id = sold_items.auction_id "
+ "inner join item "
+ "on item.item_id = auctions.item_id "
+ "inner join customer "
+ "on sold_items.customer_id = customer.customer_id "
+ "where auctions.is_closed = 1 and "
+ "customer.ssn = '" + customerID + "' " + "group by item.name "
+ "order by SUM(copies_sold) desc " + "limit 5";
ResultSet rs = s.executeQuery(sql);
while (rs.next()) {
Item item = new Item();
item.setItemID(rs.getInt("item_id"));
item.setName(rs.getString("name"));
item.setType(rs.getString("type"));
item.setNumCopies(rs.getInt("num_copies"));
item.setDescription(rs.getString("description"));
item.setYearManufactured(rs.getInt("year_manufactured"));
items.add(item);
}
rs.close();
} catch (Exception e) {
System.out.println(e);
}
return items;
}
}
|
package com.company.bookmark;
import com.company.bookmark.constants.KidsFriendlyStatus;
import com.company.bookmark.constants.UserType;
import com.company.bookmark.controllers.Controller;
import com.company.bookmark.entities.Bookmark;
import com.company.bookmark.entities.User;
import com.company.bookmark.partner.Shareable;
import java.util.List;
public class View {
/* public static void bookmark(User user, Bookmark[][] bookmarks){
System.out.println("\n"+user.getEmail()+" is bookmarking");
for (int i=0;i<DataStore.USER_BOOKMARK_LIMIT;i++)
{
int typeOffSet = (int) (Math.random() * DataStore.BOOKMARK_TYPES_COUNT);
int bookmarkOffSet = (int) (Math.random() * DataStore.BOOKMARK_COUNT_PER_TYPE);
Bookmark bookmark = bookmarks[typeOffSet][bookmarkOffSet];
Controller.getInstance().saveUserBookmark(user,bookmark);
System.out.println(bookmark);
}
}
*/
public static void browse(User user, List<List<Bookmark>> bookmarks)
{
System.out.println("\n"+user.getEmail()+" is bookmarking");
int bookmarkCount=0;
for (List<Bookmark> bookmarklist:bookmarks) {
for (Bookmark bookmark:bookmarklist) {
// if (bookmarkCount<DataStore.USER_BOOKMARK_LIMIT){
boolean isBookmarked = getBookmarkDecision(bookmark);
if (isBookmarked) {
bookmarkCount++;
Controller.getInstance().saveUserBookmark(user,bookmark);
System.out.println("New bookmark"+bookmark);
}
// }
//isKidsFriendly
if (user.getUserType().equals(UserType.CHIEF_EDITOR)||user.getUserType().equals(UserType.EDITOR))
{
if (bookmark.getKidFriendlyStatus().equals(KidsFriendlyStatus.UNKNOWN)&&bookmark.isKidFriendly()){
KidsFriendlyStatus kidFriendlyStatus = getKidFriendlyStatusDecision(bookmark);
if(!kidFriendlyStatus.equals(KidsFriendlyStatus.UNKNOWN)) {
Controller.getInstance().setKidFriendlyStatus(kidFriendlyStatus,user,bookmark);
}
}
if (bookmark.getKidFriendlyStatus().equals(KidsFriendlyStatus.UNKNOWN)&& bookmark instanceof Shareable){
boolean isShared=getShareDecision();
if (isShared){
Controller.getInstance().share(user,bookmark);
}
}
}
}
}
}
private static boolean getShareDecision() {
return Math.random() < 0.5;
}
private static KidsFriendlyStatus getKidFriendlyStatusDecision(Bookmark bookmark) {
return Math.random()<0.4?KidsFriendlyStatus.APPROVED:(Math.random()>=0.4&&Math.random()<0.8)?KidsFriendlyStatus.REJECTED:KidsFriendlyStatus.UNKNOWN;
}
private static boolean getBookmarkDecision(Bookmark bookmark) {
return Math.random() < 0.5;
}
}
|
package com.example.breno.pokemobile.adapter;
import android.content.Context;
import android.graphics.Color;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.ImageView;
import android.widget.TextView;
import com.example.breno.pokemobile.R;
import com.example.breno.pokemobile.modelo.Item;
import java.util.ArrayList;
/**
* Created by Breno on 06/11/2016.
*/
public class ItemAdapter extends BaseAdapter {
private Context ctx;
private ArrayList<Item> lista;
public ItemAdapter(Context ctx, ArrayList<Item> lista) {
this.ctx = ctx;
this.lista = lista;
}
@Override
public int getCount() {
return lista.size();
}
@Override
public Object getItem(int position) {
return lista.get(position);
}
@Override
public long getItemId(int position) {
return lista.get(position).getIdItem();
}
@Override
public View getView(int position, View convertView, ViewGroup parent) {
Item item = lista.get(position);
LayoutInflater inflater = (LayoutInflater) ctx.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
View layout = inflater.inflate(R.layout.item, null);
ImageView icone = (ImageView) layout.findViewById(R.id.iconeImageViewItem);
icone.setImageResource(item.getIcone());
TextView nome = (TextView) layout.findViewById(R.id.nomeTextViewItem);
nome.setText(item.getNome());
TextView preco = (TextView) layout.findViewById(R.id.precoTextViewItem);
preco.setText(item.getPreco().toString() + "G");
TextView descricao = (TextView) layout.findViewById(R.id.descricaoTextViewItem);
descricao.setText(item.getDescricao());
return layout;
}
public void mudarCorFundo(View v, int position) {
v.setBackgroundColor(Color.GRAY);
}
public void resetarCorFundo(View v, int position) {
v.setBackgroundColor(Color.WHITE);
}
}
|
package com.cts.ideathon.demoProject;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.context.annotation.Import;
import com.cts.ideathon.demoProject.config.JpaConfiguration;
@Import(JpaConfiguration.class)
@SpringBootApplication(scanBasePackages={"com.cts.ideathon"})
public class DemoProjectApplication {
public static void main(String[] args) {
SpringApplication.run(DemoProjectApplication.class, args);
}
}
|
package com.user.secrets.service;
import java.util.Date;
import java.util.List;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.stereotype.Service;
import com.user.secrets.domain.Secret;
import com.user.secrets.domain.User;
import com.user.secrets.repository.SecretRepository;
import com.user.secrets.repository.UserRepository;
@Service
public class SecretServiceImpl implements SecretService {
SecretRepository secretRepository;
UserRepository userRepository;
@Autowired
public SecretServiceImpl(SecretRepository secretRepository, UserRepository userRepository) {
this.secretRepository = secretRepository;
this.userRepository = userRepository;
}
@Override
public Secret findById(Long id) {
return secretRepository.findById(id);
}
@Override
public Secret findByTitle(String title) {
return secretRepository.findByTitleLike(title);
}
@Override
public List<Secret> findByCreateOn(Date createdOn) {
return secretRepository.findAllOrderByCreatedOn(createdOn);
}
@Override
public List<Secret> findByUpdateOn(Date updatedOn) {
return secretRepository.findAllOrderByCreatedOn(updatedOn);
}
@Override
public Secret save(Secret secret) {
secretRepository.save(secret);
return secret;
}
@Override
public void delete(Long id) {
secretRepository.delete(id);
}
@Override
public Secret update(Secret secret) {
secretRepository.save(secret);
return secret;
}
}
|
package com.atguigu.gmall.product.service;
import com.atguigu.gmall.model.product.BaseSaleAttr;
import com.atguigu.gmall.model.product.SpuInfo;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import java.util.List;
public interface SpuInfoService {
IPage<SpuInfo> selectPage(Page<SpuInfo> spuInfoPage, SpuInfo spuInfo);
List<BaseSaleAttr> baseSaleAttrList();
void saveSpuInfo(SpuInfo spuInfo);
}
|
/*
* @lc app=leetcode.cn id=45 lang=java
*
* [45] 跳跃游戏 II
* 定义:dp[i], 到达 i 最小跳跃次数。
* 初始化:dp[0] = 0;
* 状态转移方程:
* 由 dp[i] ---> min(dp[i+n], dp[i]+1), n取值范围:[1, nums[i]];
* 返回值:dp[nums.lenth-1]
*/
// @lc code=start
class Solution {
public int jump(int[] nums) {
int length = nums.length;
int[] dp = new int[length];
dp[0] = 0;
for (int i = 0; i < length-1; i++) {
int maxDis = nums[i];
for (int j = 1; j <= maxDis; j++) {
if(i+j >= length){
break;
}
if(dp[i+j] == 0){
dp[i+j] = dp[i] + 1;
}else{
dp[i+j] = Math.min(dp[i+j], dp[i] + 1);
}
}
}
return dp[length-1];
}
}
// @lc code=end
|
package semana1_1;
public class Person {
private String name;
private String surname;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getSurname() {
return surname;
}
public void setSurname(String surname) {
this.surname = surname;
}
public Person(String name, String surname) {
super();
this.name = name;
this.surname = surname;
}
@Override
public String toString() {
return "\n nombre: "+name+"apelldio: "+surname;
}
}
|
package com.niksoftware.snapseed.controllers;
import android.content.Context;
import android.content.res.Resources;
import android.graphics.Bitmap;
import android.graphics.Canvas;
import android.graphics.PointF;
import android.graphics.Rect;
import android.graphics.drawable.Drawable;
import android.view.View;
import com.niksoftware.snapseed.MainActivity;
import com.niksoftware.snapseed.controllers.adapters.FrameParamItemListAdapter;
import com.niksoftware.snapseed.controllers.adapters.StyleItemListAdapter;
import com.niksoftware.snapseed.controllers.adapters.StyleItemListAdapter.ActiveItemOverlayProvider;
import com.niksoftware.snapseed.controllers.touchhandlers.TouchHandler;
import com.niksoftware.snapseed.core.DeviceDefs;
import com.niksoftware.snapseed.core.NativeCore;
import com.niksoftware.snapseed.core.NotificationCenter;
import com.niksoftware.snapseed.core.NotificationCenterListener;
import com.niksoftware.snapseed.core.NotificationCenterListener.ListenerType;
import com.niksoftware.snapseed.core.SnapseedAppDelegate;
import com.niksoftware.snapseed.core.filterparameters.FilterParameter;
import com.niksoftware.snapseed.core.rendering.TilesProvider;
import com.niksoftware.snapseed.util.TrackerData;
import com.niksoftware.snapseed.views.BaseFilterButton;
import com.niksoftware.snapseed.views.ImageViewGL;
import com.niksoftware.snapseed.views.ItemSelectorView;
import com.niksoftware.snapseed.views.ItemSelectorView.OnClickListener;
import com.niksoftware.snapseed.views.ItemSelectorView.OnVisibilityChangeListener;
import com.niksoftware.snapseed.views.WorkingAreaView;
import java.util.ArrayList;
import java.util.List;
public class FixedFramesController extends AutoshuffleFilterController {
private NotificationCenterListener _compareModeChangeListener;
private BaseFilterButton _frameOptionsButton;
private boolean _frameParamActive;
private FrameParamItemListAdapter _frameParamAdapter;
private OnClickListener _frameParamItemClickListener;
private FrameTouchListener _frameTouchListener;
private FloatingFrameView _frameView;
private boolean _isCompareMode;
private ItemSelectorView _itemSelectorView;
private int _previewSize;
private StyleItemListAdapter _styleAdapter;
private BaseFilterButton _styleButton;
private OnClickListener _styleItemClickListener;
private class FloatingFrameView extends View {
public static final int BORDER_INSET = 5;
private Drawable _bottomLeftDrawable;
private Drawable _bottomRightDrawable;
private int _lastHeight = -1;
private int _lastWidth = -1;
private Drawable _topLeftDrawable;
private Drawable _topRightDrawable;
public FloatingFrameView(Context context) {
super(context);
Resources resources = getResources();
this._topLeftDrawable = resources.getDrawable(R.drawable.edit_grid_top_left);
this._topRightDrawable = resources.getDrawable(R.drawable.edit_grid_top_right);
this._bottomLeftDrawable = resources.getDrawable(R.drawable.edit_grid_bottom_left);
this._bottomRightDrawable = resources.getDrawable(R.drawable.edit_grid_bottom_right);
}
protected void onDraw(Canvas canvas) {
this._topLeftDrawable.draw(canvas);
this._topRightDrawable.draw(canvas);
this._bottomLeftDrawable.draw(canvas);
this._bottomRightDrawable.draw(canvas);
}
public void layout(int left, int top, int right, int bottom) {
super.layout(left, top, right, bottom);
int width = getWidth();
int height = getHeight();
if (this._lastWidth != width || this._lastHeight != height) {
int cornerWidth = this._topLeftDrawable.getIntrinsicWidth();
int cornerHeight = this._topLeftDrawable.getIntrinsicHeight();
this._topLeftDrawable.setBounds(0, 0, cornerWidth, cornerHeight);
this._topRightDrawable.setBounds(width - cornerWidth, 0, width, cornerHeight);
this._bottomLeftDrawable.setBounds(0, height - cornerHeight, cornerWidth, height);
this._bottomRightDrawable.setBounds(width - cornerWidth, height - cornerHeight, width, height);
View imageView = FixedFramesController.this.getWorkingAreaView().getImageView();
FixedFramesController.this._frameTouchListener.setDragAreaSize(new PointF((float) imageView.getWidth(), (float) imageView.getHeight()));
this._lastWidth = width;
this._lastHeight = height;
}
}
}
private class FrameParameterSelectorOnClickListener implements OnClickListener {
private FrameParameterSelectorOnClickListener() {
}
public boolean onItemClick(Integer itemId) {
FilterParameter filter = FixedFramesController.this.getFilterParameter();
switch (FixedFramesController.this._frameParamAdapter.getItemParameterType(itemId)) {
case 9:
int i;
FixedFramesController fixedFramesController = FixedFramesController.this;
if (FixedFramesController.this._frameParamAdapter.isItemActive(itemId)) {
i = 0;
} else {
i = 1;
}
fixedFramesController.changeParameter(filter, 9, i);
TrackerData.getInstance().usingParameter(9, false);
break;
case 224:
if (FixedFramesController.this._frameParamAdapter.isItemActive(itemId)) {
FixedFramesController.this.changeParameter(filter, 224, 0);
} else {
FixedFramesController.this.changeParameter(filter, 224, 1);
}
TrackerData.getInstance().usingParameter(224, false);
FixedFramesController.this.updateFrameView(true);
break;
}
FixedFramesController.this._itemSelectorView.refreshSelectorItems(FixedFramesController.this._frameParamAdapter, true);
return true;
}
public boolean onContextButtonClick() {
return false;
}
}
private class FrameTouchListener extends TouchHandler {
private static final float MULTIPLIER = 10000.0f;
private static final float PINCH_FEEDBACK_RATIO = 2.0f;
private static final float PINCH_FEEDBACK_THRESHOLD = 2.0f;
private PointF _dragAreaSize;
private PointF _dragRangeMaxNorm;
private PointF _dragRangeMinNorm;
private PointF _dragStart;
private float _feedbackRatio = (DeviceDefs.getScreenDensityRatio() * 2.0f);
private PointF _frameStartNorm;
private int _pinchStartFrameOffset;
private float _pinchStartSize;
public FrameTouchListener(PointF dragAreaSize) {
setDragAreaSize(dragAreaSize);
}
public Rect getFrameRect(int imageWidth, int imageHeight) {
Rect frameRect;
FilterParameter filter = FixedFramesController.this.getFilterParameter();
float offsetNorm;
if (imageWidth > imageHeight) {
offsetNorm = ((float) filter.getParameterValueOld(103)) / MULTIPLIER;
frameRect = new Rect(0, 0, imageHeight, imageHeight);
frameRect.offset(((imageWidth - imageHeight) / 2) + ((int) Math.ceil((double) (((float) imageWidth) * offsetNorm))), 0);
} else {
offsetNorm = ((float) filter.getParameterValueOld(113)) / MULTIPLIER;
frameRect = new Rect(0, 0, imageWidth, imageWidth);
frameRect.offset(0, ((imageHeight - imageWidth) / 2) + ((int) Math.ceil((double) (((float) imageHeight) * offsetNorm))));
}
if (frameRect.right > imageWidth) {
frameRect.offset(imageWidth - frameRect.right, 0);
} else if (frameRect.left < 0) {
frameRect.offset(-frameRect.left, 0);
}
if (frameRect.bottom > imageHeight) {
frameRect.offset(0, imageHeight - frameRect.bottom);
} else if (frameRect.top < 0) {
frameRect.offset(0, -frameRect.top);
}
return frameRect;
}
public void setDragAreaSize(PointF dragAreaSize) {
if (this._dragAreaSize == null || !this._dragAreaSize.equals(dragAreaSize)) {
this._dragAreaSize = dragAreaSize;
float amp;
if (this._dragAreaSize.x > this._dragAreaSize.y) {
amp = (1.0f - (this._dragAreaSize.y / this._dragAreaSize.x)) / 2.0f;
this._dragRangeMinNorm = new PointF(-amp, 0.0f);
this._dragRangeMaxNorm = new PointF(amp, 0.0f);
} else {
amp = (1.0f - (this._dragAreaSize.x / this._dragAreaSize.y)) / 2.0f;
this._dragRangeMinNorm = new PointF(0.0f, -amp);
this._dragRangeMaxNorm = new PointF(0.0f, amp);
}
this._dragStart = null;
}
}
public boolean handleTouchDown(float x, float y) {
FilterParameter filter = FixedFramesController.this.getFilterParameter();
Rect frameRect = getFrameRect((int) this._dragAreaSize.x, (int) this._dragAreaSize.y);
if (filter.getParameterValueOld(224) == 0 || !frameRect.contains((int) x, (int) y)) {
this._dragStart = null;
return false;
}
this._frameStartNorm = new PointF(((float) filter.getParameterValueOld(103)) / MULTIPLIER, ((float) filter.getParameterValueOld(113)) / MULTIPLIER);
this._dragStart = new PointF(x, y);
FixedFramesController.this.beginChangeParameter();
return true;
}
public boolean handleTouchMoved(float x, float y) {
if (this._dragStart == null) {
return false;
}
float dy = (y - this._dragStart.y) / this._dragAreaSize.y;
float newX = Math.max(Math.min(this._frameStartNorm.x + ((x - this._dragStart.x) / this._dragAreaSize.x), this._dragRangeMaxNorm.x), this._dragRangeMinNorm.x);
float newY = Math.max(Math.min(this._frameStartNorm.y + dy, this._dragRangeMaxNorm.y), this._dragRangeMinNorm.y);
FilterParameter filter = FixedFramesController.this.getFilterParameter();
FixedFramesController.this.changeParameter(filter, 103, Math.round(newX * MULTIPLIER));
FixedFramesController.this.changeParameter(filter, 113, Math.round(newY * MULTIPLIER));
FixedFramesController.this.updateFrameView(false);
FixedFramesController.this.getWorkingAreaView().requestRender();
return true;
}
public void handleTouchUp(float x, float y) {
FixedFramesController.this.endChangeParameter();
}
public void handleTouchCanceled(float x, float y) {
FixedFramesController.this.endChangeParameter();
}
public void handleTouchAbort(boolean pinchBegins) {
FixedFramesController.this.endChangeParameter();
}
public boolean handlePinchBegin(int x, int y, float size, float arc) {
this._pinchStartSize = size;
this._pinchStartFrameOffset = FixedFramesController.this.getFilterParameter().getParameterValueOld(221);
FixedFramesController.this.beginChangeParameter();
return true;
}
public boolean handlePinch(int x, int y, float size, float arc) {
if (Math.abs(this._pinchStartSize - size) >= 2.0f) {
FixedFramesController.this.changeParameter(FixedFramesController.this.getFilterParameter(), 221, (int) (((float) this._pinchStartFrameOffset) + ((this._pinchStartSize - size) / this._feedbackRatio)));
}
return true;
}
public void handlePinchEnd() {
FixedFramesController.this.endChangeParameter();
}
public void handlePinchAbort() {
FixedFramesController.this.endChangeParameter();
}
}
private class StyleItemOnClickListener implements OnClickListener {
private StyleItemOnClickListener() {
}
public boolean onItemClick(Integer itemId) {
if (itemId.equals(FixedFramesController.this._styleAdapter.getActiveItemId())) {
if (NativeCore.frameShouldShuffle(itemId.intValue())) {
FixedFramesController.this.randomizeParameter(224);
}
} else if (FixedFramesController.this.changeParameter(FixedFramesController.this.getFilterParameter(), 223, itemId.intValue())) {
TrackerData.getInstance().usingParameter(223, false);
FixedFramesController.this._styleAdapter.setActiveItemId(itemId);
FixedFramesController.this._itemSelectorView.refreshSelectorItems(FixedFramesController.this._styleAdapter, true);
}
return true;
}
public boolean onContextButtonClick() {
return false;
}
}
public void init(ControllerContext controllerContext) {
super.init(controllerContext);
FilterParameter filter = getFilterParameter();
View imageView = getWorkingAreaView().getImageView();
TouchHandler frameTouchListener = new FrameTouchListener(new PointF((float) imageView.getWidth(), (float) imageView.getHeight()));
this._frameTouchListener = frameTouchListener;
addTouchListener(frameTouchListener);
Context context = getContext();
Resources resources = context.getResources();
this._previewSize = resources.getDimensionPixelSize(R.dimen.tb_subpanel_preview_size);
final Drawable overlayDrawable = resources.getDrawable(R.drawable.icon_fo_ontop_default);
final Drawable varOverlayDrawable = resources.getDrawable(R.drawable.icon_fo_ontop_variation_default);
this._styleAdapter = new StyleItemListAdapter(context, filter, 223, new ActiveItemOverlayProvider() {
public Drawable getActiveItemOverlayDrawable(Integer itemId) {
return (itemId == null || !NativeCore.frameShouldShuffle(itemId.intValue())) ? overlayDrawable : varOverlayDrawable;
}
}, getTilesProvider().getStyleSourceImage());
this._styleItemClickListener = new StyleItemOnClickListener();
this._frameParamAdapter = new FrameParamItemListAdapter(filter);
this._frameParamItemClickListener = new FrameParameterSelectorOnClickListener();
createFrameView();
this._itemSelectorView = getItemSelectorView();
this._itemSelectorView.setOnVisibilityChangeListener(new OnVisibilityChangeListener() {
public void onVisibilityChanged(boolean isVisible) {
if (!isVisible) {
FixedFramesController.this._styleButton.setSelected(false);
FixedFramesController.this._frameOptionsButton.setSelected(false);
}
}
});
this._compareModeChangeListener = new NotificationCenterListener() {
public void performAction(Object isCompareMode) {
FixedFramesController fixedFramesController = FixedFramesController.this;
boolean z = isCompareMode != null && ((Boolean) isCompareMode).booleanValue();
fixedFramesController._isCompareMode = z;
FixedFramesController.this.updateFrameView(true);
}
};
NotificationCenter.getInstance().addListener(this._compareModeChangeListener, ListenerType.DidChangeCompareImageMode);
}
public void cleanup() {
NotificationCenter.getInstance().removeListener(this._compareModeChangeListener, ListenerType.DidChangeCompareImageMode);
if (this._frameView != null) {
getWorkingAreaView().removeView(this._frameView);
this._frameView = null;
}
getEditingToolbar().itemSelectorWillHide();
this._itemSelectorView.setVisible(false, false);
this._itemSelectorView.cleanup();
this._itemSelectorView = null;
super.cleanup();
}
public boolean initLeftFilterButton(BaseFilterButton button) {
if (button == null) {
this._styleButton = null;
return false;
}
this._styleButton = button;
this._styleButton.setStateImages((int) R.drawable.icon_tb_frames_default, (int) R.drawable.icon_tb_frames_active, 0);
this._styleButton.setText(getButtonTitle(R.string.frame));
this._styleButton.setStyle(R.style.EditToolbarButtonTitle.Selectable);
this._styleButton.setBackgroundDrawable(null);
this._styleButton.setOnClickListener(new View.OnClickListener() {
public void onClick(View view) {
FixedFramesController.this._styleButton.setSelected(true);
FixedFramesController.this._frameParamActive = false;
FixedFramesController.this._styleAdapter.setActiveItemId(Integer.valueOf(FixedFramesController.this.getFilterParameter().getParameterValueOld(223)));
FixedFramesController.this._itemSelectorView.refreshSelectorItems(FixedFramesController.this._styleAdapter, true);
FixedFramesController.this._itemSelectorView.reloadSelector(FixedFramesController.this._styleAdapter, FixedFramesController.this._styleItemClickListener);
FixedFramesController.this._itemSelectorView.setVisible(true, true);
FixedFramesController.this.previewImages(223);
}
});
return true;
}
public boolean initRightFilterButton(BaseFilterButton button) {
if (button == null) {
this._frameOptionsButton = null;
return false;
}
this._frameOptionsButton = button;
this._frameOptionsButton.setStateImages((int) R.drawable.icon_tb_options_default, (int) R.drawable.icon_tb_options_active, 0);
this._frameOptionsButton.setText((int) R.string.options);
this._frameOptionsButton.setStyle(R.style.EditToolbarButtonTitle.Selectable);
this._frameOptionsButton.setBackgroundDrawable(null);
this._frameOptionsButton.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
FixedFramesController.this._frameOptionsButton.setSelected(true);
FixedFramesController.this._frameParamActive = true;
FixedFramesController.this._itemSelectorView.reloadSelector(FixedFramesController.this._frameParamAdapter, FixedFramesController.this._frameParamItemClickListener);
FixedFramesController.this._itemSelectorView.setVisible(true, true);
}
});
return true;
}
public BaseFilterButton getLeftFilterButton() {
return this._styleButton;
}
public BaseFilterButton getRightFilterButton() {
return this._frameOptionsButton;
}
public int getFilterType() {
return 17;
}
public boolean showsParameterView() {
return false;
}
public int[] getGlobalAdjustmentParameters() {
return new int[0];
}
public void setPreviewImage(List<Bitmap> images, int parameter) {
if (!this._frameParamActive) {
ArrayList<Bitmap> styleImages = new ArrayList();
for (Bitmap source : images) {
int size = Math.min(Math.min(this._previewSize, source.getWidth()), source.getHeight());
styleImages.add(Bitmap.createBitmap(source, 0, 0, size, size));
}
if (this._styleAdapter.updateStylePreviews(styleImages)) {
this._itemSelectorView.refreshSelectorItems(this._styleAdapter, false);
}
}
}
protected int getStylePreviewSize() {
return this._previewSize * 3;
}
public void layout(boolean changed, int left, int top, int right, int bottom) {
super.layout(changed, left, top, right, bottom);
updateFrameView(false);
}
public void onPause() {
if (this._frameView != null) {
getWorkingAreaView().removeView(this._frameView);
this._frameView = null;
}
super.onPause();
}
public void onResume() {
super.onResume();
createFrameView();
updateFrameView(true);
}
public void undoRedoStateChanged() {
FilterParameter newFilter = getFilterParameter();
this._styleAdapter.updateFilterParameter(newFilter);
this._frameParamAdapter.updateFilterParameter(newFilter);
updateFrameView(true);
super.undoRedoStateChanged();
}
public String getParameterTitle(int parameter) {
return getContext().getString(R.string.choose_frame);
}
public int getHelpResourceId() {
return R.xml.overlay_fixed_frames;
}
private void createFrameView() {
if (this._frameView == null) {
this._frameView = new FloatingFrameView(getContext());
getWorkingAreaView().addView(this._frameView);
this._frameView.setVisibility(4);
}
}
private void updateFrameView(boolean updateVisibility) {
if (this._frameView != null) {
if (updateVisibility) {
FilterParameter filter = getFilterParameter();
FloatingFrameView floatingFrameView = this._frameView;
int i = (this._isCompareMode || filter.getParameterValueOld(224) == 0) ? 4 : 0;
floatingFrameView.setVisibility(i);
}
WorkingAreaView workingAreaView = getWorkingAreaView();
View imageView = workingAreaView.getImageView();
View shadowView = workingAreaView.getShadowLayer();
Rect frameRect = this._frameTouchListener.getFrameRect(imageView.getWidth(), imageView.getHeight());
frameRect.offset(shadowView.getLeft() + imageView.getLeft(), shadowView.getTop() + imageView.getTop());
frameRect.inset(-5, -5);
this._frameView.layout(frameRect.left, frameRect.top, frameRect.right, frameRect.bottom);
}
}
protected void applyFilter() {
if (!this._isApplyingFilter) {
this._isApplyingFilter = true;
lockCurrentOrientation();
this._frameView.setVisibility(4);
boolean applyingCrop = false;
if (getFilterParameter().getParameterValueOld(224) == 1) {
final TilesProvider tilesProvider = getTilesProvider();
final Bitmap fullsizeImage = tilesProvider.getSourceImage();
int imageWidth = fullsizeImage.getWidth();
int imageHeight = fullsizeImage.getHeight();
if (imageWidth != imageHeight) {
final Rect cropFrame = this._frameTouchListener.getFrameRect(imageWidth, imageHeight);
SnapseedAppDelegate.getInstance().progressStart((int) R.string.processing);
applyingCrop = true;
new Thread(new Runnable() {
public void run() {
SnapseedAppDelegate.getInstance().progressSetValue(0);
Bitmap croppedImage = Bitmap.createBitmap(fullsizeImage, cropFrame.left, cropFrame.top, cropFrame.width(), cropFrame.height());
SnapseedAppDelegate.getInstance().progressSetValue(75);
tilesProvider.setSourceImage(croppedImage);
SnapseedAppDelegate.getInstance().progressSetValue(100);
FilterParameter filter = FixedFramesController.this.getFilterParameter();
filter.setParameterValueOld(103, 0);
filter.setParameterValueOld(113, 0);
SnapseedAppDelegate.getInstance().progressEnd();
FixedFramesController.this.requestExportImage();
}
}).start();
}
}
if (!applyingCrop) {
requestExportImage();
}
}
}
private void requestExportImage() {
((ImageViewGL) getWorkingAreaView().getImageView()).requestRenderImage(getTilesProvider(), null, getFilterParameter(), MainActivity.getMainActivity().createOnRenderExportListener(), false);
}
}
|
package me.sh4rewith.config.security;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.ImportResource;
import org.springframework.context.annotation.Profile;
@Configuration
@Profile("registration-security")
@ImportResource("classpath:spring-security-registration.xml")
public class SimpleSpringSecurityConfig {
}
|
package DataStructures.arrays;
/**
* Created by senthil on 2/9/16.
*/
public class ZigZagString {
/*private String zigZagUsing2DMatrix(String str, int n) {
if (str == null || str.length() == 0 && n < 2) return str;
String result = "";
char[][] a = new char[n][str.length()];
int s = 0;
int e = str.length();
int dir = 0;
int r = 0;
int c = 0;
while (s < e) {
if (dir == 0) {
while (r < n && c < e) {
a[r++][c++] = str.charAt(s++);
}
r--;
}
else if (dir == 1) {
while (r > 0 && c < e) {
a[--r][c++] = str.charAt(s++);
}
r++;
}
dir = (dir == 0) ? 1 : 0;
}
for (int i = 0; i < n; i++) {
for(int j = i; j < str.length(); j++) {
if (a[i][j] != 0) {
result += a[i][j];
}
}
}
return result;
}*/
private String zigZagString(String str, int n) {
if (str == null || str.length() == 0 && n < 2) return str;
String result = "";
StringBuilder[] a = new StringBuilder[n];
for (int i = 0; i < n; i++) {
a[i] = new StringBuilder();
}
int s = 0;
int e = str.length();
boolean down = false;
int r = 0;
while (s < e) {
a[r].append(str.charAt(s));
if (r == 0) down = true;
else if (r == n-1) down = false;
if(down) r++;
else r--;
s++;
}
for (StringBuilder sb : a) {
result += sb.toString();
}
return result;
}
public String convert(String s, int nRows) {
if (nRows == 1)
return s;
StringBuilder builder = new StringBuilder();
int step = 2 * nRows - 2;
for (int i = 0; i < nRows; i++) {
if (i == 0 || i == nRows - 1) {
for (int j = i; j < s.length(); j = j + step) {
builder.append(s.charAt(j));
}
} else {
int j = i;
boolean flag = true;
int step1 = 2 * (nRows - 1 - i);
int step2 = step - step1;
while (j < s.length()) {
builder.append(s.charAt(j));
if (flag)
j = j + step1;
else
j = j + step2;
flag = !flag;
}
}
}
return builder.toString();
}
public String convert1(String a, int b) {
if(a == null || a.length() == 0 || b < 2) return a;
StringBuilder[] sb = new StringBuilder[b];
for (int i = 0; i < b; i++) {
sb[i] = new StringBuilder();
}
int s = 0;
int e = a.length();
String result = "";
boolean d = true;
int r = 0;
while (s < e) {
sb[r].append(a.charAt(s++));
if(r == b - 1) {
d = false;
}
else if (r == 0){
d = true;
}
if(d) r++;
else r--;
}
for (StringBuilder sbr : sb) {
result += sbr.toString();
}
return result;
}
public static void main(String a[]) {
ZigZagString zs = new ZigZagString();
//System.out.println(zs.zigZagUsing2DMatrix("ABCDEFGH" 5));
//System.out.println(zs.zigZagString("ABCDEFGH", 3));
System.out.println(zs.convert1("ABCDEFGHIJKL", 4));
//o/p is PAHNAPLSIIGYIR
}
}
|
package dev.liambloom.softwareEngineering.chapter7;
import java.util.Arrays;
import java.util.Random;
public class MrM2DArrayProblems {
protected static final Random r = new Random();
public static void main(String[] args) {
boolean seats[][] = {
{false, false, false, false, false, false, false, false},
{ false, false, false, false, false, false, false, false}
};
p10(seats);
}
public static void p1(final int[][] a) {
int sum = 0;
int len = 0;
for (int[] row : a) {
len += row.length;
for (int e : row)
sum += e;
}
System.out.printf("Sum = %d Average = %s", sum, $.numberToString((double) sum / len, 16));
}
public static void p2(final int[][] a) {
int min = Integer.MAX_VALUE;
int max = Integer.MIN_VALUE;
for (int[] row : a) {
for (int e : row) {
min = Math.min(min, e);
max = Math.max(max, e);
}
}
if (min > max)
throw new IllegalArgumentException("No min/max of an empty array");
System.out.printf("Largest = %d Smallest = %d", max, min);
}
public static void p3(final int[][] a) {
int even = 0;
int odd = 0;
for (int[] row : a) {
for (int e : row) {
if (e % 2 == 0)
even++;
else
odd++;
}
}
System.out.printf("OddCount = %d EvenCount = %d", odd, even);
}
// This 4th project was hard
// And this can't possibly be the best solution
// And I'm glad I don't have to explain it, because I don't know that I could
// Also, the # of decimal places in your example output was inconsistent and didn't make sense
public static void p4(final int[][] a) {
if (a.length == 0)
throw new IllegalArgumentException("Cannot perform operation on empty array");
// I think these default to being filled with 0s
final int rowCount = a.length;
final int colCount = a[0].length;
int[] rowSum = new int[rowCount];
int[] colSum = new int[colCount];
for (int i = 0; i < a.length; i++) {
final int[] row = a[i];
if (row.length != colCount)
throw new IllegalArgumentException("Cannot perform operation on jagged array");
for (int j = 0; j < row.length; j++) {
final int e = row[j];
rowSum[i] += e;
colSum[j] += e;
}
}
ArrayAndMaxIndex rowData = sumToAvg(rowSum, colCount);
rowSum = null;
ArrayAndMaxIndex colData = sumToAvg(colSum, rowCount);
rowSum = null;
final int maxD = Math.max(rowCount, colCount);
final String[] rowStrings = new String[maxD];
Arrays.fill(rowStrings, "");
final String rowStringsLast = String.format("MaxAvg row = %d with MaxAvg = %f", rowData.maxIndex, rowData.max());
final int rowOffset = maxD - rowCount;
int stringsMaxLengthI = 0;
for (int i = maxD - 1; i >= rowOffset; i--) {
rowStrings[i] = String.format("Average of row %d = %f", i - rowOffset, rowData.array[i - rowOffset]);
if (rowStrings[i].length() > rowStrings[stringsMaxLengthI].length())
stringsMaxLengthI = i;
}
final int stringsMaxLength = Math.max(rowStringsLast.length(), rowStrings[stringsMaxLengthI].length());
final int colOffset = maxD - colCount;
for (int i = 0; i < maxD; i++) {
System.out.printf("%-" + stringsMaxLength + "s\t", rowStrings[i]);
if (i < colOffset)
System.out.println();
else {
System.out.printf("Average of col %d = %f%n", i - colOffset, colData.array[i - colOffset]);
}
}
System.out.printf("%-" + stringsMaxLength + "s\tMaxAvg col = %d with MaxAvg = %f", rowStringsLast, colData.maxIndex, colData.max());
}
private static ArrayAndMaxIndex sumToAvg(final int[] sums, final int len) {
final ArrayAndMaxIndex r = new ArrayAndMaxIndex(sums.length);
for (int i = 0; i < sums.length; i++) {
final double avg = (double) sums[i] / len;
r.array[i] = avg;
if (avg > r.array[r.maxIndex])
r.maxIndex = i;
}
return r;
}
private static class ArrayAndMaxIndex {
public double[] array;
public int maxIndex = 0;
public ArrayAndMaxIndex(int len) {
array = new double[len];
}
public double max() {
return array[maxIndex];
}
}
public static void p5(int[][] a) {
int sum = 0;
if (a.length >= 1) {
sum += sumOfArray(a[0]);
for (int i = 1; i < a.length - 1; i++) {
if (a[i].length >= 1) {
sum += a[i][0];
if (a[i].length >= 2)
sum += a[i][a[i].length - 1];
}
}
if (a.length >= 2)
sum += sumOfArray(a[a.length - 1]);
}
System.out.printf("Sum of the edges = %d%n", sum);
}
private static int sumOfArray(final int[] a) {
int sum = 0;
for (int e : a)
sum += e;
return sum;
}
public static void p6(int[][] a) {
int sum = 0;
for (int i = 0; i < a.length; i++) {
if (a[i].length != a.length)
throw new IllegalArgumentException("Cannot find sum of diagonals of a non-square array");
sum += a[i][i];
if (a.length % 2 == 0 || a.length / 2 != i)
sum += a[i][a.length - 1 - i];
}
System.out.printf("BOTH diagonal sum = %d%n", sum);
}
public static void p7(final String[][] words) {
int longestRow = 0;
int longestColumn = 0;
int longestVowels = 0;
for (int i = 0; i < words.length; i++) {
for (int j = 0; j < words[i].length; j++) {
int vowels = 0;
final String word = words[i][j];
for (int k = 0; k < word.length(); k++) {
switch (Character.toLowerCase(word.charAt(k))) {
case 'a':
case 'e':
case 'i':
case 'o':
case 'u':
vowels++;
}
}
if (vowels >= longestVowels) {
longestRow = i;
longestColumn = j;
longestVowels = vowels;
}
}
}
System.out.printf("%s row = %d col = %d vowel count = %d",
words[longestRow][longestColumn], longestRow, longestColumn, longestVowels);
}
public static void p8(final int[][] a) {
int points = 0;
for (int i = 0; i < 3; i++) {
int row, col, hp;
System.out.printf("Hit row: %d\tcol: %d Point: %d%n",
row = r.nextInt(a.length), col = r.nextInt(a[row].length), hp = a[row][col]);
points += hp;
}
System.out.println(" Sum = " + points);
}
// I know you said transpose it then print it out, but why do
// that when you can do both at the same time, which is probably
// more efficient
public static void p9(final int[][] a) {
for (int i = 0; i < a.length; i++) {
if (a[i].length != a.length)
throw new IllegalArgumentException("Cannot transpose a non-square array");
for (int j = 0; j < i; j++)
System.out.print(a[i][j] + ", ");
for (int j = i; j < a.length; j++) {
final int temp = a[j][i];
a[j][i] = a[i][j];
a[i][j] = temp;
System.out.print(temp + ", ");
}
System.out.println();
}
}
public static final int FIRST_CLASS_SEATS = 3;
public static void p10(boolean[][] seats) {
SeatGroup.main(
new SeatGroup2d("first", seats, 0, FIRST_CLASS_SEATS),
new SeatGroup2d("second", seats, FIRST_CLASS_SEATS, Integer.MAX_VALUE)
);
}
private static class SeatGroup2d implements SeatGroup {
public final String name;
public final boolean[][] seats;
protected final int start;
protected final int end;
protected int[] firstEmpty = null;
public SeatGroup2d(final String name, final boolean[][] seats, final int start, final int end) {
this.name = name;
this.seats = seats;
this.start = start;
this.end = end;
for (int i = 0; i < seats.length && firstEmpty == null; i++) {
if (seats[i].length > start)
firstEmpty = new int[] { i, start };
}
}
public void add() {
if (!isFull()) {
seats[firstEmpty[0]][firstEmpty[1]] = true;
updateFirstEmpty();
}
}
protected void updateFirstEmpty() {
if (isFull())
return;
if (updateFirstEmptyRow())
return;
for (firstEmpty[0]++; firstEmpty[0] < seats.length; firstEmpty[0]++) {
firstEmpty[1] = start;
if (updateFirstEmptyRow())
return;
}
firstEmpty = null;
}
protected boolean updateFirstEmptyRow() {
boolean[] row = seats[firstEmpty[0]];
final int end = Math.min(row.length, this.end);
for (; firstEmpty[1] < end; firstEmpty[1]++) {
if (!row[firstEmpty[1]])
return true;
}
return false;
}
public boolean isFull() {
return firstEmpty == null;
}
public String getName() {
return name;
}
}
}
|
package mandelbrot.gui;
import java.awt.BasicStroke;
import java.awt.Color;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.Stroke;
import javax.swing.JPanel;
import static java.lang.Math.sin;
import static java.lang.Math.cos;
/**
* @author Raphaël
*/
public class SoundSpectrumViewer extends JPanel {
private int j_inc=0;
protected double[] modCoeff;
protected double modMax;
public SoundSpectrumViewer(double modMax) {
this.modMax = Math.abs(modMax);
//this.setBackground(new Color(44, 62, 80));
this.setBackground(new Color(0, 0, 0));
}
@Override
public void paintComponent(Graphics g) {
Graphics2D g2d = (Graphics2D) g;
super.paintComponent(g);
if (modCoeff != null) {
int width = getWidth(),
height = getHeight(),
n = Math.min(modCoeff.length, width),
barWidth = width / n;
// double average = 0;
// int NB = 10;
// for (int i = 0; i < NB; i++) {
// average += modCoeff[i]*modCoeff[i];
// }
// average = Math.sqrt(average)/NB;
// int radius = (int)((average/(double)modMax)*width)*60;
// int color=(int)(average*255);
// g2d.setColor(new Color(241, 196,color%256));
// if(color == 0){
// System.out.println("ModMax " +modMax+" avg "
// +average);
// }
// g2d.fillOval(getWidth()/2-radius/2, getHeight()-radius/2, radius, radius);
//
double d_theta = 2 * Math.PI / modCoeff.length;
double p = 0.10;
int radius = (int) (p * width);
int xC = width / 2, yC = height / 2;
int x1, y1, x2, y2, x3, y3, x4, y4;
int amplitude = 100, i = j_inc+=((int)Math.random()*10);
double maxSize = (height/2)*(1-p);
for (double theta =0; theta < (2 * Math.PI); theta += d_theta) {
amplitude = (int)(modCoeff[i%modCoeff.length]/modMax*maxSize*5);
x1 = (int) (xC + radius * cos(theta));
y1 = (int) (yC - radius * sin(theta));
x2 = (int) (xC + radius * cos(theta+d_theta));
y2 = (int) (yC - radius * sin(theta+d_theta));
x3 = (int) (x1 + amplitude*cos(theta));
y3 = (int) (y1 - amplitude* sin(theta));
x4 = (int) (x2 + amplitude*cos(theta+d_theta*0));
y4 = (int) (y2 - amplitude* sin(theta+d_theta*0));
g2d.setColor(Color.WHITE);
// g2d.drawLine(x1, y1, x3, y3);
// g2d.drawLine(x2, y2, x4, y4);
// g2d.drawLine(x1, y1, x2, y2);
// g2d.drawLine(x3, y3, x4, y4);
g2d.fillPolygon(new int[]{x1,x2,x4,x3}, new int[]{y1,y2,y4,y3},4);
g2d.setColor(new Color(192, 57, 43));
g2d.drawPolygon(new int[]{x1,x2,x4,x3}, new int[]{y1,y2,y4,y3},4);
i++;
}
int lastX = 0, lastY = 0;
for (i = 0; i < n; i++) {
amplitude = (int) Math.round(modCoeff[i] / modMax * height);
g.setColor(Color.WHITE);
Stroke s = g2d.getStroke();
g2d.setStroke(new BasicStroke(2));
g.fillRect(i * barWidth, height - amplitude, barWidth, amplitude);
g2d.setColor(new Color(192, 57, 43));
g.drawRect(i * barWidth, height - amplitude, barWidth, amplitude);
// g2d.setStroke(new BasicStroke(4));
// g2d.setColor(new Color(241, 196, 15));
// g2d.drawLine(lastX, lastY,i*barWidth,height-amplitude);
// lastX =i*barWidth+barWidth/2;
// lastY=height-amplitude;
g2d.setStroke(s);
}
}
}
public void setModCoeff(double[] modCoeff) {
this.modCoeff = modCoeff;
repaint();
}
public void setModMax(double modMax) {
this.modMax = modMax;
}
}
|
package com.example.Web.Model;
import javax.persistence.*;
import java.util.*;
import lombok.AllArgsConstructor;
import lombok.Getter;
import lombok.Setter;
@Getter
@Setter
@Entity
public class Clan extends Korisnik {
// clan moze ici na vise treninga, na jednom treningu moze biti vise clanova
@ManyToMany
@JoinTable( name = "odradjeniTreninzi",
joinColumns = @JoinColumn( name = "clan_id", referencedColumnName = "id"),
inverseJoinColumns = @JoinColumn( name = "trening_id", referencedColumnName = "id"))
private Set<Termin> odradjeniTreninzi = new HashSet<>();
//clan moze da se prijavi za vise treninga, za jedan trening moze da se prijavi vise clanova
@ManyToMany
@JoinTable( name = "prijavljeniTreninzi",
joinColumns = @JoinColumn(name = "clan_id", referencedColumnName = "id"),
inverseJoinColumns = @JoinColumn(name = "trening_id", referencedColumnName = "id"))
private Set<Termin> prijavljeniTreninzi = new HashSet<>();
//da li trening posmatrati kao grupni ili individualni
@OneToMany(mappedBy = "clan", fetch = FetchType.EAGER, cascade = CascadeType.ALL, orphanRemoval = true)
private Set<OcenaTreninga> ocenaTreninga = new HashSet<>();
public Clan(){}
public Clan(String korisnickoIme, String lozinka, String ime, String prezime, Date datumRodjenja,
String email, String telefon, Uloga uloga) {
super(korisnickoIme, lozinka, ime, prezime, datumRodjenja, email, telefon, uloga);
}
public Clan(String korisnickoIme, String ime, String prezime, String lozinka, String telefon, String email, Date datumRodjenja,
boolean aktivan, Uloga uloga, boolean registrovan) {
super(korisnickoIme, ime, prezime, lozinka, telefon, email, datumRodjenja, aktivan, uloga, registrovan);
}
public Clan(String korisnickoIme, String lozinka, String ime, String prezime, Date datumRodjenja, String email,
String telefon, Uloga uloga, Set<Termin> odradjeniTreninzi, Set<Termin> prijavljeniTreninzi,
Set<OcenaTreninga> ocenaTreninga) {
super(korisnickoIme, lozinka, ime, prezime, datumRodjenja, email, telefon, uloga);
this.odradjeniTreninzi = odradjeniTreninzi;
this.prijavljeniTreninzi = prijavljeniTreninzi;
this.ocenaTreninga = ocenaTreninga;
}
}
|
package pages;
import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
public class CheckoutCompletePage {
private WebDriver driver;
private By confirmationTitle = By.className("title");
public CheckoutCompletePage(WebDriver driver){
this.driver = driver;
}
public String getConfirmationTitle(){
return driver.findElement(confirmationTitle).getText();
}
}
|
package com.zjf.myself.codebase.activity.UILibrary;
import com.zjf.myself.codebase.activity.BaseAct;
/**
* Created by Administrator on 2017/3/15.
*/
public class HeartRateChartAct extends BaseAct{
}
|
/**
*/
package featureModel.impl;
import featureModel.FeatureModelPackage;
import featureModel.SolitaryFeature;
import featureModel.SolitaryType;
import org.eclipse.emf.common.notify.Notification;
import org.eclipse.emf.ecore.EClass;
import org.eclipse.emf.ecore.impl.ENotificationImpl;
/**
* <!-- begin-user-doc -->
* An implementation of the model object '<em><b>Solitary Feature</b></em>'.
* <!-- end-user-doc -->
* <p>
* The following features are implemented:
* <ul>
* <li>{@link featureModel.impl.SolitaryFeatureImpl#getRequired <em>Required</em>}</li>
* </ul>
* </p>
*
* @generated
*/
public class SolitaryFeatureImpl extends FeatureImpl implements SolitaryFeature {
/**
* The default value of the '{@link #getRequired() <em>Required</em>}' attribute.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @see #getRequired()
* @generated
* @ordered
*/
protected static final SolitaryType REQUIRED_EDEFAULT = SolitaryType.MANDATORY;
/**
* The cached value of the '{@link #getRequired() <em>Required</em>}' attribute.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @see #getRequired()
* @generated
* @ordered
*/
protected SolitaryType required = REQUIRED_EDEFAULT;
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
protected SolitaryFeatureImpl() {
super();
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
@Override
protected EClass eStaticClass() {
return FeatureModelPackage.Literals.SOLITARY_FEATURE;
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
public SolitaryType getRequired() {
return required;
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
public void setRequired(SolitaryType newRequired) {
SolitaryType oldRequired = required;
required = newRequired == null ? REQUIRED_EDEFAULT : newRequired;
if (eNotificationRequired())
eNotify(new ENotificationImpl(this, Notification.SET, FeatureModelPackage.SOLITARY_FEATURE__REQUIRED, oldRequired, required));
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
@Override
public Object eGet(int featureID, boolean resolve, boolean coreType) {
switch (featureID) {
case FeatureModelPackage.SOLITARY_FEATURE__REQUIRED:
return getRequired();
}
return super.eGet(featureID, resolve, coreType);
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
@Override
public void eSet(int featureID, Object newValue) {
switch (featureID) {
case FeatureModelPackage.SOLITARY_FEATURE__REQUIRED:
setRequired((SolitaryType)newValue);
return;
}
super.eSet(featureID, newValue);
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
@Override
public void eUnset(int featureID) {
switch (featureID) {
case FeatureModelPackage.SOLITARY_FEATURE__REQUIRED:
setRequired(REQUIRED_EDEFAULT);
return;
}
super.eUnset(featureID);
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
@Override
public boolean eIsSet(int featureID) {
switch (featureID) {
case FeatureModelPackage.SOLITARY_FEATURE__REQUIRED:
return required != REQUIRED_EDEFAULT;
}
return super.eIsSet(featureID);
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
@Override
public String toString() {
if (eIsProxy()) return super.toString();
StringBuffer result = new StringBuffer(super.toString());
result.append(" (required: ");
result.append(required);
result.append(')');
return result.toString();
}
} //SolitaryFeatureImpl
|
package org.artifact.security.dao;
import java.util.List;
import org.artifact.base.condition.BaseCondition;
import org.artifact.base.dao.BaseDao;
import org.artifact.security.bean.UserBean;
import org.artifact.security.condition.UserCondition;
import org.artifact.security.domain.User;
import org.springframework.stereotype.Repository;
import org.springframework.util.StringUtils;
/**
* 用户持久化类
* <p>
* 日期:2015年8月6日
*
* @version 0.1
* @author Netbug
*/
@Repository
public class UserDao extends BaseDao<User> {
/**
* 根据账号和密码获得User对象
* <p>
* 日期:2015年8月7日
*
* @param condition
* @return user Or null
* @author Netbug
*/
public User findUser(UserCondition condition) {
String hql = "from User where 1<>1 ";
if (StringUtils.hasText(condition.getAccount())
&& !StringUtils.hasText(condition.getPassword())) {
hql = hql + "or account = :account ";
}
if (StringUtils.hasText(condition.getAccount())
&& StringUtils.hasText(condition.getPassword())) {
hql = hql + "or (account=:account and password=:password) ";
}
condition.setHql(hql);
return (User) this.findUnique(condition);
}
/**
* 根据账号和姓名模糊搜索用户列表
* <p>
* 日期:2015年8月25日
*
* @param condition
* @return
* @author Netbug
*/
@SuppressWarnings("unchecked")
public List<User> findUsers(UserCondition condition) {
condition.setHql(this.buildHql(condition));
return (List<User>) this.find(condition);
}
/**
* 根据账号和姓名模糊搜索用户总数
* <p>
* 日期:2015年8月25日
*
* @param condition
* @return
* @author Netbug
*/
public Long findUsersCount(UserCondition condition) {
condition.setHql("select count(*) " + this.buildHql(condition));
condition.setLimit(-1);
return (Long) this.findUnique(condition);
}
/**
* 根据搜索条件拼接hql
* <p>
* 日期:2015年8月25日
*
* @param condition
* @return
* @author Netbug
*/
private String buildHql(UserCondition condition) {
String hql = "from User where 1=1 ";
if (StringUtils.hasText(condition.getAccount())) {
hql = hql + "and account like :account ";
}
if (StringUtils.hasText(condition.getName())) {
hql = hql + "and name like :name ";
}
return hql;
}
/**
* 根据账号和密码获得User对象,通过SQL进行查询。
* <p>
* 日期:2015年8月7日
*
* @param condition
* @return user Or null
* @author Netbug
*/
public UserBean findUserWithSql(BaseCondition condition) {
condition
.setSql("select u.name,u.account,u.password,u.age from sec_user u where u.account=:account and u.password=:password");
condition.setClassNameOfBean(UserBean.class.getName());
return (UserBean) this.findUnique(condition);
}
/**
* 查询所有用户
* <p>
* 日期:2015年8月6日
*
* @return list Or null
* @author Netbug
*/
@SuppressWarnings("unchecked")
public List<User> find() {
BaseCondition condition = new BaseCondition();
condition.setHql("from User");
return (List<User>) this.find(condition);
}
}
|
package com.kic.val;
import org.springframework.validation.Errors;
import org.springframework.validation.ValidationUtils;
import vo.MemberDTO;
public class Validator implements org.springframework.validation.Validator {
@Override
public boolean supports(Class<?> arg0) {
// TODO Auto-generated method stub
return MemberDTO.class.isAssignableFrom(arg0);
}
@Override
public void validate(Object target, Errors errors) {
MemberDTO dto = (MemberDTO)target;
/*
if(dto.getName() == null)
{
errors.rejectValue("name", "name required");
}
if(dto.getAddr() == null)
errors.rejectValue("addr", "required");
if(dto.getPhone() == null)
errors.rejectValue("phone", "required");*/
ValidationUtils.rejectIfEmptyOrWhitespace(errors, "name", "name_required");
ValidationUtils.rejectIfEmptyOrWhitespace(errors, "addr", "addr_required");
ValidationUtils.rejectIfEmptyOrWhitespace(errors, "phone","phone_required");
//ValidationUtils.rejectIfEmptyOrWhitespace(errors, "age", "age_required");
// ValidationUtils.rejectIfEmpty(errors, "age", "age_required");
if(dto.getAge()<0)
{
errors.rejectValue("age", "age_lengsize","숫자 0이상입력하세요");
}
/*if(dto.getName() == null || dto.getName().trim().isEmpty())
{
errors.rejectValue("name", "input name required");
}
if(dto.getAddr() == null || dto.getAddr().trim().isEmpty())
{
errors.rejectValue("addr", "input addr required");
}
if(dto.getPhone() == null || dto.getAddr().trim().isEmpty())
{
errors.rejectValue("phone", "input phone required");
}
if(dto.getAge() < 0 )
{
errors.rejectValue("age", "input age required");
}*/
}
}
|
package de.ifgi.simcat.DIR;
class DummyResultObject implements ResultObject{
public DummyResultObject clone(){
return new DummyResultObject();
}
}
|
package ru.shikhovtsev.core.service;
import ru.shikhovtsev.core.model.Account;
import java.util.Optional;
public interface DBServiceAccount {
Long saveAccount(Account account);
Long updateAccount(Account petya);
Long createOrUpdate(Account account);
Optional<Account> getAccount(long id);
}
|
package com.corycharlton.bittrexapi.model;
import com.google.gson.annotations.SerializedName;
import java.util.Date;
@SuppressWarnings("unused")
public class MarketSummary {
@SerializedName("Ask") private double _ask;
@SerializedName("BaseVolume") private double _baseVolume;
@SerializedName("Bid") private double _bid;
@SerializedName("Created") private Date _created;
@SerializedName("High") private double _high;
@SerializedName("Last") private double _last;
@SerializedName("Low") private double _low;
@SerializedName("MarketName") private String _marketName;
@SerializedName("OpenBuyOrders") private long _openBuyOrders;
@SerializedName("OpenSellOrders") private long _openSellOrders;
@SerializedName("PrevDay") private double _prevDay;
@SerializedName("TimeStamp") private Date _timeStamp;
@SerializedName("Volume") private double _volume;
private MarketSummary() {} // Cannot be instantiated
public double ask() {
return _ask;
}
public double baseVolume() {
return _baseVolume;
}
public double bid() {
return _bid;
}
public Date created() {
return _created;
}
public double high() {
return _high;
}
public double last() {
return _last;
}
public double low() {
return _low;
}
public String marketName() {
return _marketName;
}
public long openBuyOrders() {
return _openBuyOrders;
}
public long openSellOrders() {
return _openSellOrders;
}
public double prevDay() {
return _prevDay;
}
public Date timeStamp() {
return _timeStamp;
}
public double volume() {
return _volume;
}
}
|
package com.compania.vuelos.controlador;
import java.io.IOException;
import java.net.URI;
import java.util.List;
import java.util.Optional;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.http.ResponseEntity.BodyBuilder;
import org.springframework.web.bind.annotation.CrossOrigin;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.PutMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.servlet.support.ServletUriComponentsBuilder;
import com.compania.vuelos.POJO.Boleto;
import com.compania.vuelos.servicio.implementacion.BoletoServicio;
import com.compania.vuelos.utils.RestRespuestaBody;
import com.fasterxml.jackson.core.JsonParseException;
import com.fasterxml.jackson.databind.JsonMappingException;
import com.fasterxml.jackson.databind.ObjectMapper;
@CrossOrigin
@RestController
@RequestMapping("/api/boleto")
public class BoletoController {
@Autowired
protected BoletoServicio servicio;
protected ObjectMapper mapeador = new ObjectMapper();
@GetMapping
public ResponseEntity<?> obtenerTodos() {
List<Boleto> boletos = this.servicio.todos();
if (boletos.isEmpty()) {
return new ResponseEntity<>("No hay boletos", HttpStatus.NO_CONTENT);
}
return new ResponseEntity<List<Boleto>>(boletos, HttpStatus.OK);
}
@GetMapping("/{id}")
public ResponseEntity<Object> obtenerRegistro(@PathVariable("id") Long id) {
Optional<Boleto> boleto = this.servicio.obtenerRegistro(id);
if (!boleto.isPresent()) {
return ((BodyBuilder) ResponseEntity.notFound())
.body(new RestRespuestaBody(HttpStatus.NOT_FOUND.value(), "Registro no encontrado"));
}
return ResponseEntity.ok(boleto);
}
@PostMapping()
public ResponseEntity<Object> crear(@RequestBody Boleto boleto){
if (boleto.getId() != null) {
return ResponseEntity.badRequest().body(new RestRespuestaBody(HttpStatus.BAD_REQUEST.value(),
"No se debe enviar el ID en la creación de registros, ya que se generán automáticamente."));
}
this.servicio.crear(boleto);
URI location = ServletUriComponentsBuilder.fromCurrentRequest().path("/{id}").buildAndExpand(boleto.getId())
.toUri();
return ResponseEntity.created(location).build();
}
@PutMapping("/{id}")
public ResponseEntity<Object> actualizarRegistro(@RequestBody String entidadJSON, @PathVariable Long id)
throws JsonParseException, JsonMappingException, IOException {
Boleto boleto = this.mapeador.readValue(entidadJSON, Boleto.class);
if (id != boleto.getId()) {
return ResponseEntity.badRequest().body(new RestRespuestaBody(HttpStatus.BAD_REQUEST.value(),
"Error, Verifique que el Id del objeto coincida con el id enviado en la ruta /{id}."));
}
Optional<Boleto> boletoEncontrado = servicio.obtenerRegistro(id);
if (!boletoEncontrado.isPresent()) {
return ((BodyBuilder) ResponseEntity.notFound()).body(
new RestRespuestaBody(HttpStatus.NOT_FOUND.value(), "Registro no encontrado para actualizar"));
}
this.servicio.actualizar(boleto);
return ResponseEntity.ok()
.body(new RestRespuestaBody(HttpStatus.OK.value(), "Registro actualizado exitósamente"));
}
@DeleteMapping("/{id}")
public ResponseEntity<Object> borrarRegistro(@PathVariable("id") Long id) {
Optional<Boleto> boleto = servicio.obtenerRegistro(id);
if (!boleto.isPresent()) {
return ((BodyBuilder) ResponseEntity.notFound())
.body(new RestRespuestaBody(HttpStatus.NOT_FOUND.value(), "Registro no encontrado para eliminar"));
}
this.servicio.borrar(id);
return ResponseEntity.ok()
.body(new RestRespuestaBody(HttpStatus.OK.value(), "Registro eliminado exitósamente"));
}
@PostMapping("/actualizarBoletoObtenerLista")
public ResponseEntity<List<Boleto>> actualizarEstadoPorBoletoId(@RequestBody Boleto boleto) {
List<Boleto> boletos = this.servicio.actualizarBoletoObtenerLista(boleto);
return ResponseEntity.ok(boletos);
}
}
|
package coursework;
//Lists a set of appliances
//Allows you to set the starting conditions for your simulation
public class ConfigRead {
String name;
String subclass;
String meter;
int minUnitsConsumed;
int maxUnitsConsumed;
float fixedUnitsConsumed;
int probabilityHigh;
int probabilityLevel;
int cycleLength;
}
|
package com.jservmarket.dao;
import com.jservmarket.model.CategoriesModel;
import com.jservmarket.model.ProductsModel;
import com.jservmarket.model.UsersModel;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
public class CategoriesDAO extends ADAO<CategoriesModel> {
@Override
public CategoriesModel create(CategoriesModel obj) {
try {
PreparedStatement prepare = this.connect
.prepareStatement(
"INSERT INTO categories (label) " +
"VALUES(?)"
);
prepare.setString(1, obj.getLabel());
prepare.executeUpdate();
} catch (SQLException e) {
e.printStackTrace();
}
return obj;
}
@Override
public CategoriesModel find(int id) {
CategoriesModel obj = new CategoriesModel();
try {
ResultSet result = this.connect
.createStatement(
ResultSet.TYPE_SCROLL_INSENSITIVE,
ResultSet.CONCUR_UPDATABLE
).executeQuery(
"SELECT * FROM categories WHERE id = '" + id + "'"
);
if (result.first())
obj = new CategoriesModel(
id,
result.getString("label")
);
} catch (SQLException e) {
e.printStackTrace();
}
return obj;
}
@Override
public CategoriesModel findByKey(String key, String keyEntry) {
return null;
}
@Override
public CategoriesModel update(CategoriesModel obj) {
try {
PreparedStatement prepare = this.connect
.prepareStatement(
"UPDATE categories SET label=? WHERE id=?"
);
prepare.setString(1, obj.getLabel());
prepare.executeUpdate();
} catch (SQLException e) {
e.printStackTrace();
}
return obj;
}
@Override
public void delete(CategoriesModel obj) {
try {
PreparedStatement prepare = this.connect
.prepareStatement(
"DELETE FROM categories WHERE id=?"
);
prepare.setInt(1, obj.getId());
prepare.executeUpdate();
} catch (SQLException e) {
e.printStackTrace();
}
}
@Override
public int countRow() {
try {
ResultSet result = this.connect
.createStatement(
ResultSet.TYPE_SCROLL_INSENSITIVE,
ResultSet.CONCUR_UPDATABLE
).executeQuery(
"SELECT * FROM categories"
);
result.last();
return result.getInt("id");
} catch (SQLException e) {
e.printStackTrace();
}
return 0;
}
@Override
public int nbRow() {
try {
ResultSet result = this.connect
.createStatement(
ResultSet.TYPE_SCROLL_INSENSITIVE,
ResultSet.CONCUR_UPDATABLE
).executeQuery(
"SELECT * FROM categories"
);
result.last();
return result.getRow();
} catch (SQLException e) {
e.printStackTrace();
}
return 0;
}
}
|
package homework1.tasks;
import java.util.Scanner;
/**
* В данной задаче пользователь должен ввести два значения: само число и как-либо указать, во что он хочет его перевести
* (в байты или килобайты). Пусть выбор способа перевода указывается с помощью одного из двух символов.
* Например, если пользователь введет букву "b", то число будет переводиться в байты, а если букву "k", то в килобайты.
*/
public class ByteAndKB2 {
public static void main(String[] args) {
int n;
String l;
Scanner in = new Scanner(System.in);
Scanner sc = new Scanner(System.in);
System.out.print("Введите число : ");
n = in.nextInt();
System.out.println();
System.out.print("Перевести в байты (b) или килобайты (к) : ");
l = sc.nextLine();
System.out.println();
switch (l){
case "b":
System.out.println(n + " Кбайт = " + (n * 1024) + " байт");
break;
case "k":
System.out.println(n + " байт = " + (n / 1024.0) + " Кбайт");
break;
default:
System.out.println("Не понятно, в байты или Кбайты ?");
}
in.close();
sc.close();
}
}
|
package com.jgw.supercodeplatform.trace.dao.sqlbuilder;
import java.text.MessageFormat;
import java.util.List;
import java.util.Map;
import com.jgw.supercodeplatform.trace.pojo.TraceFunFieldConfig;
public class TraceFunFieldConfigProvider {
public String batchInsert(Map arg0 ) {
List<TraceFunFieldConfig> list = (List<TraceFunFieldConfig>)arg0.get("list");
StringBuilder sb = new StringBuilder();
sb.append("INSERT INTO trace_fun_config ");
sb.append("(Id,FunctionId,ObjectFieldId,FunctionName,EnTableName,TypeClass,ObjectType,ExtraCreate,TraceTemplateId,FieldType,FieldWeight,FieldName,FieldCode,DefaultValue,IsRequired,ValidateFormat,MinSize,MaxSize,RequiredNumber,MinNumber,MaxNumber,DataValue,IsRemarkEnable,ShowHidden,CreateBy,CreateTime,LastUpdateBy,LastUpdateTime,ComponentId,filterField,filterSource,readOnly) ");
sb.append("VALUES ");
MessageFormat mf = new MessageFormat("(null, #'{'list[{0}].functionId}, #'{'list[{0}].objectFieldId}, #'{'list[{0}].functionName}, #'{'list[{0}].enTableName}, #'{'list[{0}].typeClass}, #'{'list[{0}].objectType}, #'{'list[{0}].extraCreate},#'{'list[{0}].traceTemplateId}, #'{'list[{0}].fieldType}, #'{'list[{0}].fieldWeight}, #'{'list[{0}].fieldName}, #'{'list[{0}].fieldCode}"
+ ",#'{'list[{0}].defaultValue},#'{'list[{0}].isRequired},#'{'list[{0}].validateFormat},#'{'list[{0}].minSize},#'{'list[{0}].maxSize},#'{'list[{0}].requiredNumber}"
+ ",#'{'list[{0}].minNumber},#'{'list[{0}].maxNumber},#'{'list[{0}].dataValue},#'{'list[{0}].isRemarkEnable},#'{'list[{0}].showHidden},#'{'list[{0}].createBy},now(),#'{'list[{0}].lastUpdateBy},now(),#'{'list[{0}].componentId},#'{'list[{0}].filterField},#'{'list[{0}].filterSource},#'{'list[{0}].readOnly})");
for (int i = 0; i < list.size(); i++) {
sb.append(mf.format(new Object[]{i}));
if (i < list.size() - 1) {
sb.append(",");
}
}
String sql=sb.toString();
return sql;
}
}
|
package com.mediafire.sdk.response_models.data_models;
/**
* Created by Chris on 12/23/2014.
*/
public class ResumableUploadModel {
private String all_units_ready;
private int number_of_units;
private int unit_size;
private ResumableBitmapModel bitmap;
private String upload_key;
public String getAllUnitsReady() {
return all_units_ready;
}
public int getNumberOfUnits() {
return number_of_units;
}
public int getUnitSize() {
return unit_size;
}
public ResumableBitmapModel getBitmap() {
return bitmap;
}
public String getUploadKey() {
return upload_key;
}
}
|
package com.halayang.controller;
import com.halayang.common.utils.Page;
import com.halayang.pojo.Message;
import com.halayang.service.MessageService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import javax.servlet.http.HttpServletRequest;
import java.io.File;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
import java.util.UUID;
@Controller
public class MessageController {
@Autowired
private MessageService messageService;
//显示信息
@RequestMapping(value = "/message")
public String selectMessage(@RequestParam(defaultValue = "1") Integer page,
@RequestParam(defaultValue = "12") Integer rows,
String title, String msg, String region, Model model) throws Exception {
//获取分页对象
Page<Message> messagePage = messageService.findMessageList(page, rows, title, msg, region);
//计算共有多少页
int count = (messagePage.getTotal() % messagePage.getSize() == 0) ?
(messagePage.getTotal() / messagePage.getSize()) : (messagePage.getTotal() / messagePage.getSize()) + 1;
model.addAttribute("page", messagePage);
model.addAttribute("count", count);
return "admin";
}
//获取信息
@RequestMapping("/updateMsgEdit{id}")
public String updateMsgEdit(@PathVariable Integer id, Model model) {
Message message = messageService.getMsgById(id);
model.addAttribute("m", message);
return "admin_updateMsg";
}
//更新
@RequestMapping(value = "/message/updateMsg", method = RequestMethod.POST)
@ResponseBody
public String updateMsg(MultipartFile pic, Integer id, String title, String msg, String region, Date createtime, HttpServletRequest request) throws Exception {
if (!pic.isEmpty()) {
SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMddHHmmssSS");
String res = sdf.format(new Date());
// uploads文件夹位置
String rootPath = request.getSession().getServletContext().getRealPath("uploads/");
//如果该路径不存在就创建该文件夹
if (!new File(rootPath).exists()) {
new File(rootPath).mkdirs();
}
// 新文件名
String newFileName = res + UUID.randomUUID().toString().split("-")[1] + pic.getOriginalFilename().substring(pic.getOriginalFilename().lastIndexOf("."));
// 创建年月文件夹
Calendar date = Calendar.getInstance();
File dateDirs = new File(File.separator + date.get(Calendar.YEAR) + "_" + (date.get(Calendar.MONTH) + 1));
// 新文件
File newFile = new File(rootPath + File.separator + dateDirs + File.separator + newFileName);
// 判断目标文件所在目录是否存在
if (!newFile.getParentFile().exists()) {
// 如果目标文件所在的目录不存在,则创建父目录
newFile.getParentFile().mkdirs();
}
/*System.out.println(newFile.toString());//绝对路径*/
// 将内存中的数据写入磁盘
pic.transferTo(newFile);
Message message = new Message();
message.setId(id);
message.setTitle(title);
message.setMsg(msg);
message.setRegion(region);
message.setPic(dateDirs + File.separator + newFileName);
message.setCreatetime(new Date());
messageService.updateMsg(message);
return "OK";
} else {
Message message = new Message();
if (region.trim().equals("中央")) {
messageService.deleteMsgPic(id);
}
message.setId(id);
message.setTitle(title);
message.setMsg(msg);
message.setRegion(region);
message.setCreatetime(createtime);
messageService.updateMsg(message);
return "OK";
}
}
//删除
@RequestMapping("/message/deleteMsg")
@ResponseBody
public String deleteMsg(Integer[] ids) {
int rows = messageService.deleteMsgById(ids);
if (rows >= 1) return "OK";
else return "no";
}
//添加新闻
@RequestMapping(value = "/message/addMsg", method = RequestMethod.POST)
@ResponseBody
public String addMsg(MultipartFile pic, String title, String msg, String region, HttpServletRequest request) throws Exception {
if (!pic.isEmpty()) {
SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMddHHmmssSS");
String res = sdf.format(new Date());
// uploads文件夹位置
String rootPath = request.getSession().getServletContext().getRealPath("uploads" + File.separator);
//如果该路径不存在就创建该文件夹
if (!new File(rootPath).exists()) {
new File(rootPath).mkdirs();
}
// 新文件名
String newFileName = res + UUID.randomUUID().toString().split("-")[1] + pic.getOriginalFilename().substring(pic.getOriginalFilename().lastIndexOf("."));
// 创建年月文件夹
Calendar date = Calendar.getInstance();
File dateDirs = new File(File.separator + date.get(Calendar.YEAR) + "_" + (date.get(Calendar.MONTH) + 1));
// 新文件
File newFile = new File(rootPath + File.separator + dateDirs + File.separator + newFileName);
// 判断目标文件所在目录是否存在
if (!newFile.getParentFile().exists()) {
// 如果目标文件所在的目录不存在,则创建父目录
newFile.getParentFile().mkdirs();
}
/*System.out.println(newFile.toString());//绝对路径*/
// 将内存中的数据写入磁盘
pic.transferTo(newFile);
Message message = new Message();
message.setTitle(title);
message.setMsg(msg);
message.setRegion(region);
message.setPic(dateDirs + File.separator + newFileName);
message.setCreatetime(new Date());
int rows = messageService.addMsg(message);
if (rows > 0) return "OK";
else return "NO";
} else {
Message message = new Message();
message.setTitle(title);
message.setMsg(msg);
message.setRegion(region);
message.setCreatetime(new Date());
int rows = messageService.addMsg(message);
if (rows > 0) return "OK";
else return "NO";
}
}
@RequestMapping("/UEditorMsg")
public String UEditorMsg() {
return "UEditorMsg";
}
}
|
package org.squonk.rdkit.db.dsl;
import org.squonk.rdkit.db.RDKitTable;
/**
* Created by timbo on 14/12/2015.
*/
public class FpTableJoin {
boolean enabled = false;
final Select select;
FpTableJoin(Select select) {
this.select = select;
}
void append(StringBuilder buf) {
if (enabled) {
RDKitTable rdk = select.query.rdkTable;
buf.append("\n JOIN ")
.append(rdk.getMolFpTable().schemaPlusTableWithAlias())
.append(" ON " + rdk.getMolFpTable().aliasOrSchemaPlusTable() + ".id = " + rdk.aliasOrSchemaPlusTable() + ".id");
}
}
}
|
package cn.hellohao.service.impl;
import cn.hellohao.dao.UploadConfigMapper;
import cn.hellohao.pojo.UploadConfig;
import cn.hellohao.service.UploadConfigService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
@Service
public class UploadConfigServiceImpl implements UploadConfigService {
@Autowired
private UploadConfigMapper uploadConfigMapper;
@Override
public UploadConfig getUpdateConfig() {
return uploadConfigMapper.getUpdateConfig();
}
@Override
public Integer setUpdateConfig(UploadConfig uploadConfig) {
return uploadConfigMapper.setUpdateConfig(uploadConfig);
}
}
|
package io.qtechdigital.onlineTutoring.dto.auth;
import io.qtechdigital.onlineTutoring.dto.security.RoleShortDto;
import io.qtechdigital.onlineTutoring.dto.user.response.UserShortDto;
import lombok.Getter;
import lombok.Setter;
import java.util.List;
@Getter
@Setter
public class AuthenticatedUserDto {
private UserShortDto user;
private String token;
private List<RoleShortDto> roles;
}
|
package com.revature.ers.util;
import java.util.List;
import javax.servlet.http.HttpServletRequest;
import com.revature.ers.models.Principal;
import com.revature.ers.models.User;
import com.revature.ers.services.UserService;
public class RequestViewHelper {
private static UserService userService = new UserService();
private RequestViewHelper() {
super();
}
public static String process(HttpServletRequest request) {
switch (request.getRequestURI()) {
case "/ExpenseReimbursementSystem/login.view":
return "partials/login.html";
case "/ExpenseReimbursementSystem/register.view":
return "partials/register.html";
case "/ExpenseReimbursementSystem/dashboard.view":
return "partials/dashboard.html";
case "/ExpenseReimbursementSystem/admin-dashboard.view":
return "partials/admin-dash.html";
case "/ExpenseReimbursementSystem/new-reimb.view":
// principal = (Principal) request.getAttribute("principal");
return "partials/new-reimb.html";
case "/ExpenseReimbursementSystem/view-reimb-admin.view":
return "partials/view-reimb-admin.html";
case "/ExpenseReimbursementSystem/view-reimb.view":
// principal = (Principal) request.getAttribute("principal");
return "partials/view-reimb.html";
default:
return null;
}
}
}
|
package NIO;
import java.io.IOException;
import java.net.InetSocketAddress;
import java.nio.ByteBuffer;
import java.nio.channels.SelectionKey;
import java.nio.channels.Selector;
import java.nio.channels.SocketChannel;
import java.util.Iterator;
import java.util.Set;
/**
* 客户端未完成
*/
public class ClientDemo {
public static void main(String[] args) throws IOException {
// 1,打开通道
SocketChannel sc=SocketChannel.open();
// 2,设置为非阻塞
sc.configureBlocking(false);
// 3,获取选择器
Selector selc=Selector.open();
// 将通道注册到选择器身上
sc.register(selc, SelectionKey.OP_CONNECT);
sc.connect(new InetSocketAddress("localhost",8090));
while (true){
// 进行选择
selc.select();
// 获取筛选出的事件
Set<SelectionKey> keys=selc.selectedKeys();
// 遍历集合
Iterator<SelectionKey> it=keys.iterator();
while (it.hasNext()){
SelectionKey key=it.next();
// 根据事件的不同进行不同的处理
// 可连接事件
if(key.isConnectable()){
// 从事件里获取到通道
SocketChannel scx=(SocketChannel)key.channel();
// 判断连接是否建立
while (!scx.finishConnect());
// 注册可读或者可写事件
// 每次注册都会将这个通道身上原有的事件覆盖
scx.register(selc,SelectionKey.OP_READ|SelectionKey.OP_READ);
}
// 可读事件
if(key.isReadable()){
SocketChannel scx=(SocketChannel)key.channel();
// 读取数据
ByteBuffer buffer=ByteBuffer.allocate(1024);
scx.read(buffer);
// System.out.println(new String(buffer.array(),));
// scx.register(selc,key.interestOps()^SelectionKey.);
}
// 可写事件
if(key.isWritable()){
// 获取通道
SocketChannel scx=(SocketChannel)key.channel();
// scx.write()
}
}
}
}
}
|
package cjy.njit.nj.snake;
import java.awt.Graphics;
import java.awt.Image;
import java.util.Iterator;
import java.util.ListIterator;
import java.util.Random;
import javax.swing.ImageIcon;
public class Egg {
private int x;
private int y;
private Thread eggThread;
public Egg(Garden garden) {
Random random = new Random();
x = random.nextInt(garden.getColumn());
y = random.nextInt(garden.getRow());
while (!beOverlap(garden)) {
x = random.nextInt(garden.getColumn());
y = random.nextInt(garden.getRow());
}
eggThread = new Thread(new EggRunable(garden));
eggThread.start();
}
public Egg(int x, int y, Garden garden) {
if (x < garden.getColumn() && y < garden.getRow() && x >= 0 && y >= 0) {
this.x = x;
this.y = y;
} else {
Random random = new Random();
this.x = random.nextInt(garden.getColumn());
this.y = random.nextInt(garden.getRow());
while (!beOverlap(garden)) {
x = random.nextInt(garden.getColumn());
y = random.nextInt(garden.getRow());
}
}
eggThread = new Thread(new EggRunable(garden));
eggThread.start();
}
public int getX() {
return x;
}
public void setX(int x) {
this.x = x;
}
public int getY() {
return y;
}
public void setY(int y) {
this.y = y;
}
public Egg getEgg() {
return this;
}
public boolean beOverlap(Garden garden) {
ListIterator<Snake> snakeListIterator = garden.getSnakes().listIterator();
while (snakeListIterator.hasNext()) {
Snake snake = (Snake) snakeListIterator.next();
for (int i = 0; i < snake.getsnake().size(); i++) {
if (snake.getsnake().get(i).getX() == x && snake.getsnake().get(i).getY() == y) {
return false;
}
}
}
return true;
}
public boolean beAte(Garden garden) {
ListIterator<Snake> snakeListIterator = garden.getSnakes().listIterator();
while (snakeListIterator.hasNext()) {
Snake snake = (Snake) snakeListIterator.next();
if (snake.eat(this)) {
snake.setGrowflag(true);
return true;
}
}
return false;
}
public void relocate(Garden garden) {
Random random = new Random();
x = random.nextInt(garden.getColumn());
y = random.nextInt(garden.getRow());
while (!beOverlap(garden)) {
x = random.nextInt(garden.getColumn());
y = random.nextInt(garden.getRow());
}
}
public void paint(Garden garden, Graphics g) {
Image egg = new ImageIcon(System.getProperty("user.dir") + "/src/cjy/njit/nj/source/Egg.gif").getImage();
g.drawImage(egg, x * garden.getBlock_size() + (1000 - garden.getColumn() * garden.getBlock_size()) / 2,
y * garden.getBlock_size() + (700 - garden.getRow() * garden.getBlock_size()) / 2,
(x + 1) * garden.getBlock_size() + (1000 - garden.getColumn() * garden.getBlock_size()) / 2,
(y + 1) * garden.getBlock_size() + (700 - garden.getRow() * garden.getBlock_size()) / 2, 0, 0, 500, 500,
garden);
}
private class EggRunable implements Runnable {
private Garden garden;
public EggRunable(Garden garden) {
super();
this.garden = garden;
}
@Override
public void run() {
// TODO Auto-generated method stub
while (garden.getSignal().getSnakeNum() != 0) {
if (garden.getSignal().getSnakePEggFlag() == (garden.getEggs().indexOf(getEgg()) + 1)) {
if (beAte(garden)) {
garden.getSignal().getEggAlive().set(garden.getEggs().indexOf(getEgg()), false);
garden.getSignal().setEggNum(garden.getSignal().getEggNum() - 1);
garden.getSignal().setSnakePEggFlag(garden.getSignal().getSnakePEggFlag() - 1);
try {
Thread.sleep(3000);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
relocate(garden);
garden.getSignal().setEggNum(garden.getSignal().getEggNum() + 1);
garden.getSignal().getEggAlive().set(garden.getEggs().indexOf(getEgg()), true);
} else {
garden.getSignal().setSnakePEggFlag(garden.getSignal().getSnakePEggFlag() - 1);
}
}
try {
Thread.sleep(10);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
}
}
|
/*
* 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 lab_3_3;
/**
*
* @author valen
*/
import java.util.*;
public class Lab_3_3 {
/**
* @param args the command line arguments
*/
public static void main(String[] args) {
// TODO code application logic here
String strPosition;
String strJobOfferPhrase = "Here is our job offer: ";
String strDegree;
String strJava;
Scanner keyboard = new Scanner(System.in);
System.out.println("Welcome to your job interview");
System.out.println("Do you have a college degree? (y/n)");
strDegree = keyboard.nextLine();
if(strDegree.equals("y"))
{
System.out.println("Do you know java? (y/n)");
strJava = keyboard.nextLine();
if(strJava.equals("y"))
{
strPosition = "senior";
}
else
{
strPosition = "entry level";
}
System.out.println(strJobOfferPhrase);
System.out.println("We would like to hire you at a "+strPosition+" position");
}
else
{
System.out.println(strJobOfferPhrase);
System.out.println("We can not extend you a job offer at this time");
}
}
}
|
package com.maliang.core.util;
import java.beans.BeanInfo;
import java.beans.Introspector;
import java.beans.MethodDescriptor;
import java.beans.PropertyDescriptor;
import java.util.ArrayList;
import java.util.List;
public class BeanUtil {
public static Object readValue(Object obj,String fname){
Object value = readProperty(obj,fname);
if(value == null){
return methodValue(obj,fname,null);
}
return value;
}
public static Object readProperty(Object obj,String fname){
return readProperty(obj,fname,null);
}
public static Object readProperty(Object obj,String fname,Object defaultValue){
try {
BeanInfo beanInfo = Introspector.getBeanInfo(obj.getClass());
PropertyDescriptor[] pds = beanInfo.getPropertyDescriptors();
for(PropertyDescriptor pd :pds){
if(pd.getName().equals(fname)){
return pd.getReadMethod().invoke(obj);
}
}
} catch (Exception e) {}
return defaultValue;
}
public static Object methodValue(Object obj,String mName,Object defaultValue){
try {
BeanInfo beanInfo = Introspector.getBeanInfo(obj.getClass());
MethodDescriptor[] mds = beanInfo.getMethodDescriptors();
for(MethodDescriptor md :mds){
if(md.getName().equals(mName)){
return md.getMethod().invoke(obj);
}
}
} catch (Exception e) {}
return defaultValue;
}
public static void main(String[] args) {
List ls = new ArrayList(10);
ls.add("ddd");
Object v = methodValue(ls,"size",null);
v = readValue(ls,"size");
System.out.println(ls.size() + "="+v);
}
}
|
package recipesCLI.Controllers;
import recipesCLI.Utilitaries.FieldValidator;
import recipesCLI.HttpRequestSender.HttpRequestSender;
import java.util.Scanner;
public class ApplicationController {
private RecipeController recipeController;
private UserCLIController userCLIController;
private Scanner reader;
private int userId;
public ApplicationController(HttpRequestSender httpRequestSender) {
recipeController = new RecipeController(httpRequestSender);
userCLIController = new UserCLIController(httpRequestSender);
reader = new Scanner(System.in);
}
/**
* This method is the first one to display the message
*/
public void enterUserId() {
System.out.println("Enter your id, by default will be 0");
userId = Integer.parseInt(reader.nextLine());
}
/**
* This method is to display the menu and read the selected option by the user
* @return This will return the option provided by the user
*/
public int getInitInstructions() {
System.out.println( "1. To Register new User\n"+
"2. List all users\n"+
"3. Modify personal data\n"+
"4. Add a recipes\n"+
"5. List all recipes\n"+
"6. Find Recipe by id\n"+
"7. Modify a recipe\n"+
"8. Delete a recipe\n"+
"9. Finish the app\n");
return FieldValidator.mainOption(reader.nextLine());
}
/**
* @param value The selected option by the user
* @return It will return the instructions to interact with the selected option
*/
public String selectOption(int value) {
switch (value) {
case 1 : {
return userCLIController.register();
}
case 2: {
return userCLIController.viewAllUser();
}
case 3: {
return userCLIController.update(userId);
}
case 4: {
return recipeController.registerRecipe(userId);
}
case 5: {
return recipeController.getAllRecipes();
}
case 6: {
return recipeController.getRecipeById();
}
case 7: {
return recipeController.modifyRecipe(userId);
}
case 8: {
return recipeController.deleteRecipe(userId);
}
}
return "See you soon";
}
}
|
package com.adapteach.codeassesser.verify;
import com.adapteach.codeassesser.compile.CompilationUnit;
import com.adapteach.codeassesser.verify.Test;
import lombok.Data;
import java.util.ArrayList;
import java.util.List;
@Data
public class Assessment {
private List<CompilationUnit> providedCompilationUnits = new ArrayList<>();
private List<Test> tests = new ArrayList<>();
}
|
package com.example.donisaurus.ecomplaint.model;
/**
* Created by Donisaurus on 12/27/2016.
*/
import java.util.List;
import com.google.gson.annotations.Expose;
import com.google.gson.annotations.SerializedName;
public class ModelPostResponse {
@SerializedName("status")
@Expose
private Integer status;
@SerializedName("pesan")
@Expose
private String pesan;
@SerializedName("data")
@Expose
private List<ModelPost> data = null;
public Integer getStatus() {
return status;
}
public void setStatus(Integer status) {
this.status = status;
}
public String getPesan() {
return pesan;
}
public void setPesan(String pesan) {
this.pesan = pesan;
}
public List<ModelPost> getData() {
return data;
}
public void setData(List<ModelPost> data) {
this.data = data;
}
}
|
package com.gxtc.huchuan.ui.live.series;
import android.Manifest;
import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.graphics.Paint;
import android.os.Bundle;
import android.support.design.widget.AppBarLayout;
import android.support.design.widget.TabLayout;
import android.support.v4.app.Fragment;
import android.support.v4.view.ViewPager;
import android.support.v7.app.AlertDialog;
import android.text.TextUtils;
import android.view.View;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;
import com.alibaba.fastjson.JSONObject;
import com.gxtc.commlibrary.base.BaseTitleActivity;
import com.gxtc.commlibrary.helper.ImageHelper;
import com.gxtc.commlibrary.utils.EventBusUtil;
import com.gxtc.commlibrary.utils.GotoUtil;
import com.gxtc.commlibrary.utils.ToastUtil;
import com.gxtc.huchuan.Constant;
import com.gxtc.huchuan.MyApplication;
import com.gxtc.huchuan.R;
import com.gxtc.huchuan.adapter.SeriesPageAdapter;
import com.gxtc.huchuan.bean.ChatInfosBean;
import com.gxtc.huchuan.bean.CreateLiveTopicBean;
import com.gxtc.huchuan.bean.SeriesPageBean;
import com.gxtc.huchuan.bean.event.EventDelSeries;
import com.gxtc.huchuan.bean.event.EventLoginBean;
import com.gxtc.huchuan.bean.event.EventSelectFriendBean;
import com.gxtc.huchuan.bean.event.EventSeriesInviteBean;
import com.gxtc.huchuan.bean.event.EventSeriesPayBean;
import com.gxtc.huchuan.bean.pay.OrdersRequestBean;
import com.gxtc.huchuan.bean.pay.OrdersResultBean;
import com.gxtc.huchuan.bean.pay.PayBean;
import com.gxtc.huchuan.data.UserManager;
import com.gxtc.huchuan.dialog.SeriesCourseInviteDialog;
import com.gxtc.huchuan.dialog.ShareDialog;
import com.gxtc.huchuan.handler.CircleShareHandler;
import com.gxtc.huchuan.helper.RxTaskHelper;
import com.gxtc.huchuan.http.ApiCallBack;
import com.gxtc.huchuan.http.ApiObserver;
import com.gxtc.huchuan.http.ApiResponseBean;
import com.gxtc.huchuan.http.service.AllApi;
import com.gxtc.huchuan.http.service.LiveApi;
import com.gxtc.huchuan.http.service.PayApi;
import com.gxtc.huchuan.im.ui.ConversationActivity;
import com.gxtc.huchuan.im.ui.ConversationListActivity;
import com.gxtc.huchuan.ui.circle.dynamic.IssueDynamicActivity;
import com.gxtc.huchuan.ui.circle.erweicode.ErWeiCodeActivity;
import com.gxtc.huchuan.ui.live.hostpage.IGetChatinfos;
import com.gxtc.huchuan.ui.live.hostpage.LiveHostPageActivity;
import com.gxtc.huchuan.ui.live.hostpage.NewLiveTopicFragment;
import com.gxtc.huchuan.ui.live.intro.ShareImgActivity;
import com.gxtc.huchuan.ui.live.series.count.SeriesSignCountActivity;
import com.gxtc.huchuan.ui.live.series.share.SeriesShareListActivity;
import com.gxtc.huchuan.ui.mine.classroom.directseedingbackground.createseriescourse.CreateSeriesCourseActivity;
import com.gxtc.huchuan.ui.mine.classroom.directseedingbackground.createtopic.CreateTopicActivity;
import com.gxtc.huchuan.ui.mine.classroom.directseedingbackground.livebgsetting.InvitedGuestsActivity;
import com.gxtc.huchuan.ui.mine.loginandregister.LoginAndRegisteActivity;
import com.gxtc.huchuan.ui.pay.PayActivity;
import com.gxtc.huchuan.utils.DialogUtil;
import com.gxtc.huchuan.utils.ImMessageUtils;
import com.gxtc.huchuan.utils.JumpPermissionManagement;
import com.gxtc.huchuan.utils.LoginErrorCodeUtil;
import com.gxtc.huchuan.utils.RIMErrorCodeUtil;
import com.gxtc.huchuan.utils.RongIMTextUtil;
import com.gxtc.huchuan.utils.UMShareUtils;
import com.umeng.socialize.bean.SHARE_MEDIA;
import org.greenrobot.eventbus.Subscribe;
import org.jetbrains.annotations.Nullable;
import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import butterknife.BindView;
import butterknife.OnClick;
import io.rong.imlib.IRongCallback;
import io.rong.imlib.RongIMClient;
import io.rong.imlib.model.Conversation;
import io.rong.imlib.model.Message;
import rx.Subscription;
import rx.android.schedulers.AndroidSchedulers;
import rx.schedulers.Schedulers;
/**
* 系列课主页
*/
public class SeriesActivity extends BaseTitleActivity implements IGetChatinfos,
View.OnClickListener {
public static final String AUDITION_TYPE = "1"; //免费试听模式
public static final String AUDITION_INVITE_TYPE = "2"; //邀请制免费试听模式
private static final String TAG = "SeriesActivity";
private static final int PLAYSERIES_REQUEST = 1 << 2;
private static final int SETTING_SERIES = 1 << 3;
//<!--headpic 系列课头像-->
//<!--buycount 购买人数 buyUsers 参与购买人信息列表-->
@BindView(R.id.iv_head) ImageView mIvHead;// <!--headpic 系列课头像-->
@BindView(R.id.tv_title) TextView mTvTitle;//<!--seriesname 系列课名称-->
@BindView(R.id.tv_price) TextView mTvPrice;//<!--fee 价格-->
@BindView(R.id.tv_return_livepage) ImageView mTvMore;
@BindView(R.id.layout_count) View mLayoutCount;
@BindView(R.id.tv_free_invite) TextView tvFreeInvite;
@BindView(R.id.tv_count) TextView mTvCount;
@BindView(R.id.ll_head_area) LinearLayout mLlHeadArea;
@BindView(R.id.tl_series_page_indicator) TabLayout mTlSeriesPageIndicator;
@BindView(R.id.app_bar) AppBarLayout mAppBar;
@BindView(R.id.vp_series_viewpager) ViewPager mVpSeriesViewpager;
@BindView(R.id.btn_create_topic) Button mBtnCreateTopic;
@BindView(R.id.btn_buy_series) TextView mBtnBuySeries;
@BindView(R.id.ll_audience_area) LinearLayout mLlAudienceArea;
@BindView(R.id.ll_owner_area) LinearLayout mLlOwnerArea;
@BindView(R.id.rl_series_owner_intro) RelativeLayout mRlSeriesOwnerIntro;
@BindView(R.id.ll_owner_share_btn) LinearLayout mLlOwnerShareBtn;
@BindView(R.id.ll_owner_setting_btn) LinearLayout mLlOwnerSettingBtn;
@BindView(R.id.ll_share_person_area) LinearLayout layoutShare;
@BindView(R.id.live_intro_follow_head) ImageView mLiveIntroImage;
@BindView(R.id.live_intro_follow_ownername) TextView tvName;
@BindView(R.id.live_intro_follow_attention) ImageView mImageView;
@BindView(R.id.img_sign_more) ImageView imgSignMore;
private List<Fragment> mFragments = new ArrayList<>();
private static String[] labTitles = {"详情", "课程"};
private SeriesIntroFragment mSeriesIntroFragment;
private NewLiveTopicFragment mNewLiveTopicFragment;
private SeriesPageAdapter mSeriesPageAdapter;
private SeriesPageBean mData;
private HashMap<String, String> map;
private UMShareUtils shareUtils;
private String mId;
private String shareUserCode;
private String freeSign;
private AlertDialog mAlertDialog;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_series);
}
@Override
public void initView() {
EventBusUtil.register(this);
getBaseHeadView().showTitle("系列课主页");
getBaseHeadView().showBackButton(this);
getBaseHeadView().showHeadRightImageButton(R.drawable.navigation_icon_share, this);
}
@Override
public void initData() {
//这里去请求数据 如果请求成功了 才把空的view yinchangdiao
labTitles[1] = "课程2";
getData();
}
private void getData() {
hideContentView();
getBaseLoadingView().showLoading();
mId = getIntent().getStringExtra("id");
freeSign = getIntent().getStringExtra("freeSign");
//现在app所有的内部分享都不得佣金 除非是微信外部分享 圈子也是这样
if (!TextUtils.isEmpty(freeSign)) {
shareUserCode = getIntent().getStringExtra("userCode");
}
setdata();
}
private void setdata() {
Subscription sub = LiveApi.getInstance().getChatSeriesInfo(
UserManager.getInstance().getToken(), mId).subscribeOn(Schedulers.io()).observeOn(
AndroidSchedulers.mainThread()).subscribe(
new ApiObserver<ApiResponseBean<SeriesPageBean>>(new ApiCallBack<SeriesPageBean>() {
@Override
public void onSuccess(SeriesPageBean data) {
if (data != null && getBaseLoadingView() != null) {
getBaseLoadingView().hideLoading();
showContentView();
setdata(data);
}
}
@Override
public void onError(String errorCode, String message) {
if (getBaseLoadingView() != null) {
getBaseLoadingView().hideLoading();
LoginErrorCodeUtil.showHaveTokenError(SeriesActivity.this, errorCode,
message);
}
}
}));
RxTaskHelper.getInstance().addTask(this, sub);
}
private void setdata(SeriesPageBean data) {
mData = data;
if (mData == null || mTvTitle == null) return;
imgSignMore.setVisibility(mData.bIsSelf() ? View.GONE : View.VISIBLE);
ImageHelper.loadRound(this, mIvHead, mData.getHeadpic(), 4);
mTvTitle.setText(mData.getSeriesname());
mImageView.setPadding(0, 0, getResources().getDimensionPixelSize(R.dimen.px5dp), 0);
mImageView.setImageResource(R.drawable.person_icon_more);
ImageHelper.loadCircle(this, mLiveIntroImage, data.getAnchorPic(),
R.drawable.live_host_defaual_bg);
if (!TextUtils.isEmpty(mData.getUserName())) {
tvName.setText(mData.getUserName());
}
if (Double.valueOf(mData.getFee()) > 0d) {
mTvPrice.setText(String.format("价格: ¥%.2f", Double.valueOf(mData.getFee())));
mTvPrice.setTextColor(getResources().getColor(R.color.color_price_ec6b46));
} else {
mTvPrice.setText("免费");
mTvPrice.setTextColor(getResources().getColor(R.color.color_119b1e));
}
mBtnCreateTopic.setVisibility(mData.bIsSelf() ? View.VISIBLE : View.GONE);
tvFreeInvite.setVisibility(mData.bIsSelf() ? View.VISIBLE : View.GONE);
mTlSeriesPageIndicator.setupWithViewPager(mVpSeriesViewpager);
labTitles[1] = "课程"; //+ mData.getChatInfos().size();
mTvCount.setText(mData.getBuyCount() + "人正在参与");
addPersonHead();
setModel();
setBuySeriesBtn();
mSeriesPageAdapter = new SeriesPageAdapter(getSupportFragmentManager(), getFragments(mData),
labTitles);
mVpSeriesViewpager.setAdapter(mSeriesPageAdapter);
mVpSeriesViewpager.setCurrentItem(1);
}
private void addPersonHead() {
if (mLlHeadArea != null) {
mLlHeadArea.removeAllViews();
}
int cout = mData.getBuyUsers().size() > 5 ? 5 : mData.getBuyUsers().size();
for (int i = 0; i < cout; i++) {
mLlHeadArea.addView(getPersonHead(mData.getBuyUsers().get(i).getHeadPic()));
}
if (layoutShare != null) {
layoutShare.removeAllViews();
}
if (mData.getUmVoList() != null) {
cout = mData.getUmVoList().size() > 5 ? 5 : mData.getUmVoList().size();
for (int i = 0; i < cout; i++) {
layoutShare.addView(getPersonHead(mData.getUmVoList().get(i).getName()));
}
}
}
private void setBuySeriesBtn() {
mBtnBuySeries.setVisibility(mData.bIsSelf() || mData.bIsBuy() ? View.GONE : View.VISIBLE);
mLlAudienceArea.setVisibility(mData.bIsSelf() || mData.bIsBuy() ? View.GONE : View.VISIBLE);
if (Double.valueOf(mData.getFee()) > 0d) {
mBtnBuySeries.setText(String.format("价格: ¥%.2f", Double.valueOf(mData.getFee())));
} else {
mBtnBuySeries.setText("报名");
}
if (!mData.bIsSelf() && "1".equals(mData.getIsGroupUser()) && !mData.bIsBuy()) {
mTvPrice.getPaint().setFlags(Paint.STRIKE_THRU_TEXT_FLAG);
mTvPrice.setText(String.format("价格: ¥%.2f", Double.valueOf(mData.getFee())));
mTvPrice.setTextColor(getResources().getColor(R.color.text_color_999));
mBtnBuySeries.setText("圈内成员,免费报名");
}
if (!TextUtils.isEmpty(freeSign)) {
mBtnBuySeries.setText("免费邀请,立即报名");
mData.setFee("0");
}
//显示免费邀请制按钮 没达成邀请人数都要显示
if (!mData.bIsSelf() && AUDITION_INVITE_TYPE.equals(
mData.getIsAuditions()) && !mData.isFinishInvite()) {
if (!mData.bIsBuy()) {
mBtnBuySeries.setText("报名试听");
mBtnBuySeries.setVisibility(View.VISIBLE);
mLlAudienceArea.setVisibility(View.VISIBLE);
}
}
}
private boolean isExamine(List<ChatInfosBean> list) {
for (ChatInfosBean bean : list) {
if (bean.getAudit().equals("1")) return true;
}
return false;
}
private boolean isCanShare() {
List<ChatInfosBean> list = mNewLiveTopicFragment.mLiveTopicAdapter.getList();
if (list == null || list.size() == 0) {
ToastUtil.showLong(this, "没创建子课程的系列课不能分享");
return false;
} else if (!isExamine(list)) {
ToastUtil.showLong(this, "子课程审核通过后才能分享");
return false;
}
return true;
}
@Override
public void initListener() {
mTvMore.setOnClickListener(this);
tvFreeInvite.setOnClickListener(this);
mBtnCreateTopic.setOnClickListener(this);
}
public List<Fragment> getFragments(SeriesPageBean o) {
mFragments.clear();
mSeriesIntroFragment = new SeriesIntroFragment();
mNewLiveTopicFragment = new NewLiveTopicFragment();
Bundle bundleChatInfos = new Bundle();
bundleChatInfos.putString("chatRoom", o.getChatRoom());
bundleChatInfos.putBoolean("series", true);
bundleChatInfos.putString("chatSeries", mId);
bundleChatInfos.putString("shareUserCode", shareUserCode);
bundleChatInfos.putString("freeSign", freeSign);
bundleChatInfos.putString("isAuditions", mData.getIsAuditions());
bundleChatInfos.putString("isBuy", mData.getIsBuy());
bundleChatInfos.putDouble("seriesFree", Double.valueOf(mData.getFee()));
bundleChatInfos.putSerializable("seriesBean", mData);
mNewLiveTopicFragment.setArguments(bundleChatInfos);
Bundle bundle = new Bundle();
bundle.putString("introduce", o.getIntroduce());
mSeriesIntroFragment.setArguments(bundle);
mFragments.add(mSeriesIntroFragment);
mFragments.add(mNewLiveTopicFragment);
return mFragments;
}
@Override
protected void onDestroy() {
RxTaskHelper.getInstance().cancelTask(this);
EventBusUtil.unregister(this);
ImageHelper.onDestroy(MyApplication.getInstance());
mAlertDialog = null;
super.onDestroy();
}
@OnClick({R.id.btn_create_topic, R.id.btn_buy_series, R.id.layout_count, R.id.ll_owner_setting_btn, R.id.ll_owner_share_btn, R.id.rl_series_owner_intro, R.id.layout_follow, R.id.layout_share, R.id.tv_free_invite})
public void onClick(View view) {
switch (view.getId()) {
case R.id.rl_series_owner_intro:
// finish();
break;
case R.id.layout_count:
//只有自己的系列课才可以点击查看报名的成员
if (UserManager.getInstance().isLogin(this)) {
if (mData.bIsSelf()) {
SeriesSignCountActivity.jumpToSeriesSignCountActivity(this, mData.getId(),
mData.getJoinType() + "");
}
}
break;
case R.id.btn_create_topic:
if (!UserManager.getInstance().isLogin()) {
GotoUtil.goToActivity(SeriesActivity.this, LoginAndRegisteActivity.class);
return;
}
//新建课程
map = new HashMap<>();
map.put("chatSeries", mData.getId());
map.put("chatInfoTypeId", mData.getChatInfoTypeId());
GotoUtil.goToActivityWithData(this, CreateTopicActivity.class, map);
break;
case R.id.btn_buy_series:
if (!UserManager.getInstance().isLogin()) {
GotoUtil.goToActivity(SeriesActivity.this, LoginAndRegisteActivity.class);
return;
}
//这里是已经成功报名,但是还未完成任务, 点击显示弹窗
if (AUDITION_INVITE_TYPE.equals(
mData.getIsAuditions()) && mData.bIsBuy() && !mData.isFinishInvite()) {
showInviteModel();
return;
}
if ("0".equals(mData.getFee())) {
playSeries();
return;
}
//圈内成员免费报名
if ("1".equals(mData.getIsGroupUser())) {
saveFreeChatSeries();
return;
}
playSeries();
break;
case R.id.headBackButton:
finish();
break;
case R.id.tv_free_invite:
if (!isCanShare()) return;
InvitedGuestsActivity.startActivity(SeriesActivity.this, mData.getId(), "4",
mData.getSeriesname(), mData.getHeadpic());
break;
case R.id.layout_follow:
if (mData != null) {
LiveHostPageActivity.startActivity(this, "1", mData.getChatRoom());
}
break;
case R.id.ll_owner_setting_btn:
//设置 把当前对象传递到下一个页面
if (mData != null) {
Intent intent = new Intent(this, CreateSeriesCourseActivity.class);
intent.putExtra("bean", mData);
startActivityForResult(intent, SETTING_SERIES);
//GotoUtil.goToActivityWithBean(SeriesActivity.this,CreateSeriesCourseActivity.class,mData);
}
break;
//分享
case R.id.HeadRightImageButton:
case R.id.ll_owner_share_btn:
if (!UserManager.getInstance().isLogin(this)) return;
if (!isCanShare()) return;
if (mData != null) {
String[] pers = new String[]{Manifest.permission.READ_EXTERNAL_STORAGE, Manifest.permission.WRITE_EXTERNAL_STORAGE};
performRequestPermissions(getString(R.string.txt_card_permission), pers, 2200,
new PermissionsResultListener() {
@Override
public void onPermissionGranted() {
final String uri = TextUtils.isEmpty(
mData.getHeadpic()) ? Constant.DEFUAL_SHARE_IMAGE_URI : mData.getHeadpic();
ShareDialog.Action[] actions = {new ShareDialog.Action(
ShareDialog.ACTION_INVITE,
R.drawable.share_icon_invitation,
null), new ShareDialog.Action(ShareDialog.ACTION_QRCODE,
R.drawable.share_icon_erweima,
null), new ShareDialog.Action(
ShareDialog.ACTION_COLLECT,
R.drawable.share_icon_collect,
null), new ShareDialog.Action(ShareDialog.ACTION_COPY,
R.drawable.share_icon_copy,
null), new ShareDialog.Action(ShareDialog.ACTION_CIRCLE,
R.drawable.share_icon_my_dynamic,
null), new ShareDialog.Action(
ShareDialog.ACTION_FRIENDS,
R.drawable.share_icon_friends, null)};
shareUtils = new UMShareUtils(SeriesActivity.this);
shareUtils.shareCustom(uri, mData.getSeriesname(),
mData.getIntroduce(), mData.getShareUrl(), actions,
new ShareDialog.OnShareLisntener() {
@Override
public void onShare(@Nullable String key,
@Nullable SHARE_MEDIA media) {
switch (key) {
//这里跳去邀请卡
case ShareDialog.ACTION_INVITE:
ShareImgActivity.startActivity(
SeriesActivity.this,
mData.getId());
break;
//分享到动态
case ShareDialog.ACTION_CIRCLE:
IssueDynamicActivity.share(
SeriesActivity.this,
mData.getId(), "6",
mData.getSeriesname(), uri);
break;
//分享到好友
case ShareDialog.ACTION_FRIENDS:
ConversationListActivity.startActivity(
SeriesActivity.this,
ConversationActivity.REQUEST_SHARE_CONTENT,
Constant.SELECT_TYPE_SHARE);
break;
//收藏
case ShareDialog.ACTION_COLLECT:
collect(mData.getId());
break;
//二维码
case ShareDialog.ACTION_QRCODE:
ErWeiCodeActivity.startActivity(
SeriesActivity.this,
ErWeiCodeActivity.TYPE_SERIES,
Integer.valueOf(mData.getId()),
"");
break;
}
}
});
}
@Override
public void onPermissionDenied() {
mAlertDialog = DialogUtil.showDeportDialog(SeriesActivity.this,
false, null, getString(R.string.pre_storage_notice_msg),
new View.OnClickListener() {
@Override
public void onClick(View v) {
if (v.getId() == R.id.tv_dialog_confirm) {
JumpPermissionManagement.GoToSetting(
SeriesActivity.this);
}
mAlertDialog.dismiss();
}
});
}
});
}
break;
//分享达人榜
case R.id.layout_share:
if (UserManager.getInstance().isLogin()) {
if (!isCanShare()) return;
Intent intent = new Intent(SeriesActivity.this, SeriesShareListActivity.class);
intent.putExtra(Constant.INTENT_DATA, mData);
startActivity(intent);
} else GotoUtil.goToActivity(this, LoginAndRegisteActivity.class);
break;
}
}
private SeriesCourseInviteDialog mInviteDialog;
private void showInviteModel() {
mInviteDialog = new SeriesCourseInviteDialog(mData);
mInviteDialog.show(getSupportFragmentManager(),
SeriesCourseInviteDialog.class.getSimpleName());
}
private void saveFreeChatSeries() {
Subscription sub = LiveApi.getInstance().saveFreeChatSeriesBuy(
UserManager.getInstance().getToken(), mId).subscribeOn(Schedulers.io()).observeOn(
AndroidSchedulers.mainThread()).subscribe(
new ApiObserver<ApiResponseBean<Void>>(new ApiCallBack<Void>() {
@Override
public void onSuccess(Void data) {
ToastUtil.showShort(MyApplication.getInstance(), "报名成功");
setdata();
}
@Override
public void onError(String errorCode, String message) {
ToastUtil.showShort(MyApplication.getInstance(), message);
}
}));
RxTaskHelper.getInstance().addTask(this, sub);
}
private void collect(String classId) {
HashMap<String, String> map = new HashMap<>();
map.put("token", UserManager.getInstance().getToken());
map.put("bizType", "9");
map.put("bizId", classId);
Subscription sub = AllApi.getInstance().saveCollection(map).subscribeOn(
Schedulers.io()).observeOn(AndroidSchedulers.mainThread()).subscribe(
new ApiObserver<ApiResponseBean<Object>>(new ApiCallBack() {
@Override
public void onSuccess(Object data) {
if (mData.getIsCollect() == 0) {
mData.setIsCollect(1);
ToastUtil.showShort(SeriesActivity.this, "收藏成功");
} else {
mData.setIsCollect(0);
ToastUtil.showShort(SeriesActivity.this, "取消收藏");
}
}
@Override
public void onError(String errorCode, String message) {
LoginErrorCodeUtil.showHaveTokenError(SeriesActivity.this, errorCode,
message);
}
}));
RxTaskHelper.getInstance().addTask(this, sub);
}
private boolean playing = false;
private void playSeries() {
if (!TextUtils.isEmpty(freeSign) && !TextUtils.isEmpty(shareUserCode)) {
freeInviteJoin();
return;
}
String fee = mData.getFee();
BigDecimal moneyB = new BigDecimal(fee);
//计算总价
double total = moneyB.setScale(2, BigDecimal.ROUND_HALF_UP).doubleValue() * 100;
JSONObject jsonObject = new JSONObject();
jsonObject.put("chatSeriesId", mData.getId());
if (!TextUtils.isEmpty(shareUserCode)) {
jsonObject.put("userCode", shareUserCode);
jsonObject.put("joinType", 0);
jsonObject.put("type", 1);
}
String extra = jsonObject.toJSONString();
OrdersRequestBean requestBean = new OrdersRequestBean();
requestBean.setToken(UserManager.getInstance().getToken());
requestBean.setTransType("CS");
requestBean.setTotalPrice(total + "");
requestBean.setExtra(extra);
requestBean.setGoodsName("系列课购买");
if ("0".equals(fee)) {
requestBean.setPayType("ALIPAY");
HashMap<String, String> map = new HashMap<>();
map.put("token", requestBean.getToken());
map.put("transType", requestBean.getTransType());
map.put("payType", requestBean.getPayType());
map.put("totalPrice", requestBean.getTotalPrice());
map.put("extra", requestBean.getExtra());
getBaseLoadingView().showLoading();
Subscription sub = PayApi.getInstance().getOrder(map).subscribeOn(
Schedulers.io()).observeOn(AndroidSchedulers.mainThread()).subscribe(
new ApiObserver<ApiResponseBean<OrdersResultBean>>(
new ApiCallBack<OrdersResultBean>() {
@Override
public void onSuccess(OrdersResultBean data) {
getBaseLoadingView().hideLoading();
Toast.makeText(SeriesActivity.this, "报名成功",
Toast.LENGTH_SHORT).show();
//显示免费邀请制规则弹窗
if (AUDITION_INVITE_TYPE.equals(mData.getIsAuditions())) {
showInviteModel();
}
if (mData != null) {
mData.setIsBuy("1");
setdata(mData);
EventBusUtil.post(new EventSeriesPayBean());
}
}
@Override
public void onError(String errorCode, String message) {
getBaseLoadingView().hideLoading();
Toast.makeText(SeriesActivity.this, "报名失败",
Toast.LENGTH_SHORT).show();
}
}));
RxTaskHelper.getInstance().addTask(this, sub);
} else {
playing = true;
GotoUtil.goToActivity(this, PayActivity.class, Constant.INTENT_PAY_RESULT, requestBean);
}
}
//免费邀请报名
private void freeInviteJoin() {
getBaseLoadingView().showLoading();
String token = UserManager.getInstance().getToken();
String transType = "CS";
String payType = "WX";
String totalPrice = "0";
JSONObject jobj = new JSONObject();
jobj.put("chatSeriesId", mData.getId());
jobj.put("freeSign", freeSign);
jobj.put("userCode", shareUserCode);
jobj.put("joinType", 4);
String extra = jobj.toString();
HashMap<String, String> map = new HashMap<>();
map.put("token", token);
map.put("transType", transType);
map.put("payType", payType);
map.put("totalPrice", totalPrice);
map.put("extra", extra);
Subscription sub = PayApi.getInstance().getOrder(map).observeOn(
AndroidSchedulers.mainThread()).subscribeOn(Schedulers.io()).subscribe(
new ApiObserver<ApiResponseBean<OrdersResultBean>>(new ApiCallBack() {
@Override
public void onSuccess(Object data) {
if (mData != null) {
Toast.makeText(SeriesActivity.this, "报名成功", Toast.LENGTH_SHORT).show();
getBaseLoadingView().hideLoading();
mData.setIsBuy("1");
setdata(mData);
EventBusUtil.post(new EventSeriesPayBean());
}
}
@Override
public void onError(String errorCode, String message) {
if (mData != null) {
ToastUtil.showShort(SeriesActivity.this, message);
getBaseLoadingView().hideLoading();
}
}
}));
RxTaskHelper.getInstance().addTask(this, sub);
}
/**
* 添加头像
*
* @param uri
* @return
*/
private ImageView getPersonHead(String uri) {
int dimensionPixelOffset = getResources().getDimensionPixelOffset(R.dimen.px60dp);
LinearLayout.LayoutParams layoutParams = new LinearLayout.LayoutParams(dimensionPixelOffset,
dimensionPixelOffset);
int margin = getResources().getDimensionPixelOffset(R.dimen.margin_small);
layoutParams.setMargins(margin, margin, margin, margin);
ImageView imageView = new ImageView(this);
imageView.setLayoutParams(layoutParams);
ImageHelper.loadCircle(this, imageView, uri, R.drawable.person_icon_head_120);
return imageView;
}
private void setModel() {
mLlOwnerArea.setVisibility(mData.bIsSelf() ? View.VISIBLE : View.GONE);
}
@Subscribe
public void onEvent(EventSeriesInviteBean bean) {
showInviteModel();
}
@Subscribe
public void onEvent(CreateLiveTopicBean bean) {
this.getData();
}
@Subscribe
public void SeriesPayEvent(EventSeriesPayBean bean) {
if (bean.flag) {
getData();
}
}
/**
* 支付回调
*
* @param bean
*/
@Subscribe
public void onEvent(PayBean bean) {
if (!playing) return;
if (!bean.isPaySucc) {//支付失败
ToastUtil.showShort(this, "支付失败");
} else {
getData();
}
playing = false;
}
/**
* 更新修改系列课后的内容
*/
@Subscribe
public void onEvent(SeriesPageBean bean) {
getData();
}
@Subscribe
public void onEvent(EventDelSeries bean) {
this.finish();
}
@Subscribe
public void onEvent(EventLoginBean bean) {
if (bean.status == EventLoginBean.LOGIN || bean.status == EventLoginBean.REGISTE || bean.status == EventLoginBean.THIRDLOGIN) {
getData();
}
}
//分享到好友
private void shareMessage(final String targetId, final Conversation.ConversationType type,
final String liuyan) {
String title = mData.getSeriesname();
String img = TextUtils.isEmpty(
mData.getHeadpic()) ? Constant.DEFUAL_SHARE_IMAGE_URI : mData.getHeadpic();
String id = mData.getId();
ImMessageUtils.shareMessage(targetId, type, id, title, img, CircleShareHandler.SHARE_SERIES,
new IRongCallback.ISendMessageCallback() {
@Override
public void onAttached(Message message) {
}
@Override
public void onSuccess(Message message) {
ToastUtil.showShort(SeriesActivity.this, "分享成功");
if (!TextUtils.isEmpty(liuyan)) {
RongIMTextUtil.INSTANCE.relayMessage(liuyan, targetId, type);
}
}
@Override
public void onError(Message message, RongIMClient.ErrorCode errorCode) {
ToastUtil.showShort(SeriesActivity.this,
"分享失败: " + RIMErrorCodeUtil.handleErrorCode(errorCode));
}
});
}
@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
if (requestCode == PLAYSERIES_REQUEST && resultCode == RESULT_OK) {
if (mData != null) {
mData.setIsBuy("1");
setdata(mData);
EventBusUtil.post(new EventSeriesPayBean());
}
} else if (requestCode == SETTING_SERIES && resultCode == RESULT_OK) {
setdata((SeriesPageBean) data.getSerializableExtra("seriesBean"));
}
if (resultCode == Constant.ResponseCode.CIRCLE_ISSUE) {
ToastUtil.showShort(this, "分享成功");
}
if (requestCode == ConversationActivity.REQUEST_SHARE_CONTENT && resultCode == RESULT_OK) {
EventSelectFriendBean bean = data.getParcelableExtra(Constant.INTENT_DATA);
String targetId = bean.targetId;
Conversation.ConversationType type = bean.mType;
shareMessage(targetId, type, bean.liuyan);
}
if (requestCode == 666 && resultCode == Constant.ResponseCode.ISSUE_TONG_BU) {
mNewLiveTopicFragment.onActivityResult(requestCode, resultCode, data);
}
if (requestCode == NewLiveTopicFragment.REQUEST_TOPIC_INTRO && resultCode == 999) {
showInviteModel();
}
super.onActivityResult(requestCode, resultCode, data);
}
@Override
public List<ChatInfosBean> getChatinfosList() {
if (mData != null) {
return mData.getChatInfos();
}
return null;
}
public static void startActivity(Context context, String id) {
Intent intent = new Intent(context, SeriesActivity.class);
intent.putExtra("id", id);
context.startActivity(intent);
}
public static void startActivityForResult(Activity context, String id, int recode) {
Intent intent = new Intent(context, SeriesActivity.class);
intent.putExtra("id", id);
context.startActivityForResult(intent, recode);
}
//免费邀请报名 freeSign 免费邀请码
public static void freeInvite(Context context, String id, String shareUserCode,
String freeSign) {
Intent intent = new Intent(context, SeriesActivity.class);
intent.putExtra("id", id);
intent.putExtra("userCode", shareUserCode);
intent.putExtra("freeSign", freeSign);
context.startActivity(intent);
}
public static void startActivity(Context context, String id, String userCode) {
Intent intent = new Intent(context, SeriesActivity.class);
intent.putExtra("id", id);
intent.putExtra("userCode", userCode);
context.startActivity(intent);
}
public static void startActivity(Context context, String id, boolean isByLiveFragment) {
Intent intent = new Intent(context, SeriesActivity.class);
intent.putExtra("id", id);
intent.putExtra("isByLiveFragment", isByLiveFragment);
context.startActivity(intent);
}
public static void startActivity(Context context, String id, boolean isByLiveFragment,
int flag) {
Intent intent = new Intent(context, SeriesActivity.class);
intent.putExtra("id", id);
intent.putExtra("isByLiveFragment", isByLiveFragment);
intent.addFlags(flag);
context.startActivity(intent);
}
}
|
package ch.erp.management.mvp.presenter;
import ch.erp.management.mvp.contract.MPurchaseReturnsContract;
/**
* 采购退货-主持者
*/
public class MPurchaseReturnsActivityP extends MPurchaseReturnsContract.MIPurchaseReturnsActivityP{
}
|
public class Menu {
// main menu
public void mainMenu() {
System.out.println(" Please select from the following option");
System.out.println("===================================");
System.out.println("1. Make a booking");
System.out.println("2. List all sessions");
System.out.println("3. Find a movie session by name");
System.out.println("4. Delete a booking");
System.out.println("5. List all bookings");
System.out.println("6. Search a booking by Email");
System.out.println("7. Exit");
System.out.println("===================================");
System.out.println("Enter an option: _");
}
//cinemas location menu
public void locationMenu () {
System.out.println("Select cinema theater location from the folowing options");
System.out.println("===================================");
System.out.println("1.St Kilda");
System.out.println("2.Fitzroy");
System.out.println("3.Melbourne CBD");
System.out.println("4.Sunshine");
System.out.println("5.Lilydale");
System.out.println("===================================");
}
}
|
package com.nfet.icare.dao;
import org.apache.ibatis.annotations.Param;
import com.nfet.icare.pojo.WxUser;
//微信用户的openId和手机号
public interface WxUserMapper {
//保存
public void insertWxUser(@Param("wxUser") WxUser wxUser);
//查询
public WxUser queryWxUser(@Param("openId") String openId);
}
|
package com.mustafayuksel.notificationapplication;
import org.aopalliance.intercept.MethodInvocation;
import org.apache.commons.logging.Log;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.springframework.aop.interceptor.AbstractMonitoringInterceptor;
import java.util.Date;
public class PerformanceMonitorInterceptor extends AbstractMonitoringInterceptor {
private static final long serialVersionUID = 1L;
private static Logger LOGGER = LogManager.getLogger("PerformanceMonitorInterceptor");
public PerformanceMonitorInterceptor() {
}
public PerformanceMonitorInterceptor(boolean useDynamicLogger) {
setUseDynamicLogger(useDynamicLogger);
}
@Override
protected Object invokeUnderTrace(MethodInvocation methodInvocation, Log log) throws Throwable {
String name = createInvocationTraceName(methodInvocation);
long start = System.currentTimeMillis();
LOGGER.info("Method " + name + " execution " + "started at:" + new Date());
try {
return methodInvocation.proceed();
} finally {
long end = System.currentTimeMillis();
long time = end - start;
LOGGER.info("Method " + name + " execution lasted: " + time + " ms");
LOGGER.info("Method " + name + " execution ended at: " + new Date());
if (time > 10) {
LOGGER.warn("Method execution longer than 10 ms!");
}
}
}
}
|
/*
* 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 modelo;
/**
*
* @author Javi Cordero
*/
public class MetodosCitas
{
private Cliente_Cita primero;
private Cliente_Cita ultimo;
private String[] datosConsultados;
public MetodosCitas()
{
primero = ultimo = null;
}//Fin del constructor.
public void insertar(Cliente_Cita cliente)
{
//Si el primer nodo es igual a null, es porque no existen elementos en
//la lista enlazada.
if(primero == null)
{
primero = ultimo = cliente;
}
else
{
//Si la prioridad del cliente es de 7600
if(cliente.getTipoCliente().equals("7600"))
{
Cliente_Cita auxiliar = primero;
Cliente_Cita anterior = null;
while(auxiliar.getTipoCliente().equals("7600"))
{
anterior = auxiliar;
auxiliar = auxiliar.getEnlaceSiguiente();
}
if(auxiliar == primero)
{
cliente.setEnlaceSiguiente(primero);
primero = cliente;
}
else
{
cliente.setEnlaceSiguiente(anterior.getEnlaceSiguiente());
anterior.setEnlaceSiguiente(cliente);
}
}
else
{
ultimo.setEnlaceSiguiente(cliente);
ultimo = cliente;
}
}
}//Fin del metodo insertar.
public boolean consultar(String cedula)
{
boolean existe = false;
//Si el primero es null, es que no hay elementos.
if(primero != null)
{
Cliente_Cita aux = primero;
while(aux != null)
{
if(aux.getCedula().equals(cedula))
{
datosConsultados = new String[5];
datosConsultados[0] = aux.getCedula();
datosConsultados[1] = aux.getNombre();
datosConsultados[2] = "" + aux.getEdad();
datosConsultados[3] = aux.getFechaCita();
datosConsultados[4] = aux.getTipoCliente();
return true;
}
aux = aux.getEnlaceSiguiente();
}
}
return existe;
}//Fin del metodo consultar.
public boolean modificar(String[] datosNuevos)
{
if(primero != null)
{
Cliente_Cita aux = primero;
while(aux != null)
{
if(aux.getCedula().equals(datosNuevos[0]))
{
aux.setNombre(datosNuevos[1]);
aux.setEdad(Integer.parseInt(datosNuevos[2]));
aux.setFechaCita(datosNuevos[3]);
aux.setTipoCliente(datosNuevos[4]);
return true;
}
aux = aux.getEnlaceSiguiente();
}
}
return false;
}//Fin del metodo modificar.
public boolean eliminar(String cedula)
{
Cliente_Cita aux = primero;
Cliente_Cita anterior = null;
while(aux != null)
{
if(aux.getCedula().equals(cedula))
{
if(aux == primero)
{
primero = primero.getEnlaceSiguiente();
return true;
}
else if(anterior != null)
{
anterior.setEnlaceSiguiente(aux.getEnlaceSiguiente());
aux.setEnlaceSiguiente(null);
return true;
}
else if(aux == ultimo)
{
anterior.setEnlaceSiguiente(null);
ultimo = anterior;
return true;
}
}
anterior = aux;
aux = aux.getEnlaceSiguiente();
}
return false;
}//Fin del metodo eliminar.
public Cliente_Cita eliminarPrimero()
{
Cliente_Cita aux = primero;
if(primero != null)
{
primero = primero.getEnlaceSiguiente();
}
return aux;
}//Fin del metodo eliminar.
public String obtenerLista()
{
String info = "";
Cliente_Cita aux = primero;
//Mientras el cliente auxiliar sea distinto de null
while(aux != null)
{
info += aux.getInformacion();
aux = aux.getEnlaceSiguiente();
}
return info;
}//Fin del metodo devolver_lista_clientes.
public String[] obtenerDatosConsultados()
{
return datosConsultados;
}//Fin del metodo obtenerDatosConsultados.
public int tamanio_de_lista()
{
Cliente_Cita auxiliar = primero;
int contador = 0;
while(auxiliar != null)
{
auxiliar = auxiliar.getEnlaceSiguiente();
contador++;
}
return contador;
}//Fin del metodo tamanio_de_lista
public double obtenerPromedio()
{
double promedio = 0;
int edades = 0;
if(primero != null)
{
Cliente_Cita aux = primero;
while(aux != null)
{
edades += aux.getEdad();
aux = aux.getEnlaceSiguiente();
}
promedio = (edades/tamanio_de_lista());
}
return promedio;
}//Fin del metodo obtenerPromedio.
public void ordenar_mayor_a_menor()
{
int tamanioLista = tamanio_de_lista();
String cedulaTemp;
String nombreTemp;
int edadTemp;
String fechaTemp;
String tipoTemp;
Cliente_Cita temporal;
for(int contador=0; contador<tamanioLista; contador++)
{
temporal = primero;
while(temporal.getEnlaceSiguiente() != null)
{
if(temporal.getEdad() < temporal.getEnlaceSiguiente().getEdad())
{
//Almacena los datos del objeto en un lugar temporal
cedulaTemp = temporal.getCedula();
nombreTemp = temporal.getNombre();
edadTemp = temporal.getEdad();
fechaTemp = temporal.getFechaCita();
tipoTemp = temporal.getTipoCliente();
//Intercambia los datos
temporal.setCedula(temporal.getEnlaceSiguiente().getCedula());
temporal.setNombre(temporal.getEnlaceSiguiente().getNombre());
temporal.setEdad(temporal.getEnlaceSiguiente().getEdad());
temporal.setFechaCita(temporal.getEnlaceSiguiente().getFechaCita());
temporal.setTipoCliente(temporal.getEnlaceSiguiente().getTipoCliente());
//Cambia los datos temporales en el objeto siguiente.
temporal.getEnlaceSiguiente().setCedula(cedulaTemp);
temporal.getEnlaceSiguiente().setNombre(nombreTemp);
temporal.getEnlaceSiguiente().setEdad(edadTemp);
temporal.getEnlaceSiguiente().setFechaCita(fechaTemp);
temporal.getEnlaceSiguiente().setTipoCliente(tipoTemp);
}
temporal = temporal.getEnlaceSiguiente();
}
}
}//Fin del metodo ordenar_mayor_a_menor.
public void ordenar_menor_a_mayor()
{
int tamanioLista = tamanio_de_lista();
String cedulaTemp;
String nombreTemp;
int edadTemp;
String fechaTemp;
String tipoTemp;
Cliente_Cita temporal;
for(int contador=0; contador<tamanioLista; contador++)
{
temporal = primero;
while(temporal.getEnlaceSiguiente() != null)
{
if(temporal.getEdad() > temporal.getEnlaceSiguiente().getEdad())
{
//Almacena los datos del objeto en un lugar temporal
cedulaTemp = temporal.getCedula();
nombreTemp = temporal.getNombre();
edadTemp = temporal.getEdad();
fechaTemp = temporal.getFechaCita();
tipoTemp = temporal.getTipoCliente();
//Intercambia los datos
temporal.setCedula(temporal.getEnlaceSiguiente().getCedula());
temporal.setNombre(temporal.getEnlaceSiguiente().getNombre());
temporal.setEdad(temporal.getEnlaceSiguiente().getEdad());
temporal.setFechaCita(temporal.getEnlaceSiguiente().getFechaCita());
temporal.setTipoCliente(temporal.getEnlaceSiguiente().getTipoCliente());
//Cambia los datos temporales en el objeto siguiente.
temporal.getEnlaceSiguiente().setCedula(cedulaTemp);
temporal.getEnlaceSiguiente().setNombre(nombreTemp);
temporal.getEnlaceSiguiente().setEdad(edadTemp);
temporal.getEnlaceSiguiente().setFechaCita(fechaTemp);
temporal.getEnlaceSiguiente().setTipoCliente(tipoTemp);
}
temporal = temporal.getEnlaceSiguiente();
}
}
}//Fin del metodo ordenar_menor_a_mayor.
}//Fin de la clase MetodosCitas.
|
package org.webservice;
import javax.jws.WebService;
@WebService(endpointInterface="org.webservice.SurveyWebService")
public class SurveyWebServiceImpl implements SurveyWebService{
//TODO: return the list of the students here
public String listStudent(String firstName,String lastName,String city,String state){
return firstName+" "+lastName+" "+city+ ""+state;
}
}
|
package com.sferion.whitewater.ui.views.pigging;
import com.google.inject.Inject;
import com.google.inject.Provider;
import com.sferion.whitewater.backend.admin.PiggingEventAdmin;
import com.sferion.whitewater.backend.admin.PiggingUserAdmin;
import com.sferion.whitewater.backend.admin.PipelineAdmin;
import com.sferion.whitewater.backend.domain.*;
import com.sferion.whitewater.backend.domain.enums.Acknowledgment;
import com.sferion.whitewater.backend.domain.enums.PiggingEventStatus;
import com.sferion.whitewater.backend.domain.enums.UnitOfMeasure;
import com.sferion.whitewater.ui.MainLayout;
import com.sferion.whitewater.ui.SessionData;
import com.sferion.whitewater.ui.components.navigation.bar.AppBar;
import com.sferion.whitewater.ui.views.ViewFrame;
import com.vaadin.flow.component.*;
import com.vaadin.flow.component.button.Button;
import com.vaadin.flow.component.datepicker.DatePicker;
import com.vaadin.flow.component.formlayout.FormLayout;
import com.vaadin.flow.component.notification.Notification;
import com.vaadin.flow.component.orderedlayout.FlexComponent;
import com.vaadin.flow.component.orderedlayout.HorizontalLayout;
import com.vaadin.flow.component.orderedlayout.VerticalLayout;
import com.vaadin.flow.component.select.Select;
import com.vaadin.flow.component.textfield.IntegerField;
import com.vaadin.flow.component.textfield.NumberField;
import com.vaadin.flow.component.textfield.TextField;
import com.vaadin.flow.data.binder.Binder;
import com.vaadin.flow.router.PageTitle;
import com.vaadin.flow.router.Route;
import com.vaadin.flow.server.VaadinSession;
import java.time.LocalDate;
import java.util.*;
import static com.sferion.whitewater.backend.domain.enums.Acknowledgment.NO;
import static com.sferion.whitewater.backend.domain.enums.Acknowledgment.YES;
import static com.sferion.whitewater.ui.views.pigging.NewPiggingEventView.PAGE_TITLE;
import static com.sferion.whitewater.ui.views.pigging.SessionVariable.CURRENTLY_SELECTED_PLANT;
@PageTitle(PAGE_TITLE)
@Route(value = NewPiggingEventView.PAGE_NAME, layout = MainLayout.class)
public class NewPiggingEventView extends ViewFrame {
public static final String PAGE_TITLE = "New Pigging Event";
public static final String PAGE_NAME = "newPiggingEvent";
private final PiggingEventAdmin piggingEventAdmin;
private final PiggingUserAdmin piggingUserAdmin;
private final PipelineAdmin pipelineAdmin;
private final Provider<SessionData> sessionDataProvider;
@Inject
public NewPiggingEventView(PiggingEventAdmin piggingEventAdmin, PiggingUserAdmin piggingUserAdmin, PipelineAdmin pipelineAdmin, Provider<SessionData> sessionDataProvider) {
this.piggingEventAdmin = piggingEventAdmin;
this.piggingUserAdmin = piggingUserAdmin;
this.pipelineAdmin = pipelineAdmin;
this.sessionDataProvider = sessionDataProvider;
}
@Override
protected void onAttach(AttachEvent attachEvent) {
PiggingEventDetails piggingEventDetails = new PiggingEventDetails();
VerticalLayout layout = new VerticalLayout(piggingEventDetails.getLayout());
layout.setHorizontalComponentAlignment(FlexComponent.Alignment.CENTER, piggingEventDetails.getLayout());
setViewContent(layout);
AppBar appBar = Objects.requireNonNull(MainLayout.get()).getAppBar();
appBar.setNaviMode(AppBar.NaviMode.CONTEXTUAL);
appBar.addContextIconClickListener(e -> UI.getCurrent().navigate(PiggingView.class));
appBar.setTitle("Pigging - New Pigging Event");
}
private class PiggingEventDetails {
private final VerticalLayout layout;
private DatePicker dateSent;
private Select<Acknowledgment> batchFluidUsed;
private NumberField batchVolume;
private Select<UnitOfMeasure> units;
private Button save;
private Binder<PiggingEvent> binder;
public PiggingEventDetails() {
layout = new VerticalLayout();
layout.add(createPipelineDetails(),createButtonLayout());
layout.setWidth("50%");
save.setEnabled(false);
}
protected VerticalLayout getLayout() {
return layout;
}
private FormLayout createPipelineDetails() {
FormLayout columnLayout = new FormLayout();
columnLayout.setResponsiveSteps(
new FormLayout.ResponsiveStep("25em", 1),
new FormLayout.ResponsiveStep("32em", 2),
new FormLayout.ResponsiveStep("40em", 3));
Plants currentlySelectedPlant = (Plants) VaadinSession.getCurrent().getAttribute(CURRENTLY_SELECTED_PLANT);
Select<Pipeline> pipelines = new Select<>();
pipelines.setLabel("Pipeline Run");
pipelines.setRequiredIndicatorVisible(true);
pipelines.setEmptySelectionAllowed(false);
pipelines.setItemLabelGenerator(Pipeline::getPipelineRunName);
pipelines.setItems(pipelineAdmin.getActivePipelinesByPlant(currentlySelectedPlant.getId()));
columnLayout.add(pipelines,1);
Set<String> locations = getPipelineLocations(currentlySelectedPlant);
Select<String> fromLocation = new Select<>();
fromLocation.setLabel("From Location");
fromLocation.setRequiredIndicatorVisible(true);
fromLocation.setEmptySelectionAllowed(false);
fromLocation.setItems(locations);
columnLayout.add(fromLocation,1);
Select<String> toLocation = new Select<>();
toLocation.setLabel("To Location");
toLocation.setRequiredIndicatorVisible(true);
toLocation.setEmptySelectionAllowed(false);
toLocation.setItems(locations);
columnLayout.add(toLocation,1);
dateSent = new DatePicker("Date Pig Sent");
dateSent.setRequiredIndicatorVisible(true);
dateSent.setValue(LocalDate.now());
columnLayout.add(dateSent,1);
Select<String> sentBy = new Select<>();
sentBy.setLabel("Sent By");
sentBy.setRequiredIndicatorVisible(true);
sentBy.setEmptySelectionAllowed(false);
List<String> userNames = piggingUserAdmin.getUserNames();
sentBy.setItems(userNames);
columnLayout.add(sentBy,2);
Select<Acknowledgment> sizingRingUsed = new Select<>(YES, NO);
sizingRingUsed.setLabel("Was a Sizing Ring Used?");
sizingRingUsed.setRequiredIndicatorVisible(true);
sizingRingUsed.setEmptySelectionAllowed(false);
sizingRingUsed.setValue(YES);
columnLayout.add(sizingRingUsed,1);
columnLayout.add(new Html("<div> </div>"),2);
TextField pigType = new TextField("Pig Type");
pigType.setRequiredIndicatorVisible(true);
columnLayout.add(pigType,1);
NumberField pigSize = new NumberField("Pig Size (inches)");
pigSize.setRequiredIndicatorVisible(true);
columnLayout.add(pigSize,1);
NumberField durometer = new NumberField("Durometer");
columnLayout.add(durometer,1);
DatePicker dateRetrieved = new DatePicker("Date Pig Retrieved");
columnLayout.add(dateRetrieved,1);
Select<String> retrievedBy = new Select<>();
retrievedBy.setLabel("Retrieved By");
retrievedBy.setEmptySelectionAllowed(true);
retrievedBy.setItems(userNames);
columnLayout.add(retrievedBy,2);
IntegerField piggingTime = new IntegerField("Pigging Time (minutes)");
columnLayout.add(piggingTime,1);
columnLayout.add(new Html("<div> </div>"),2);
batchFluidUsed = new Select<>(YES,NO);
batchFluidUsed.setLabel("Batch Fluid Used?");
batchFluidUsed.addValueChangeListener(this::handleBatchFluidUsedValueChanged);
batchFluidUsed.setEmptySelectionAllowed(true);
columnLayout.add(batchFluidUsed,1);
batchVolume = new NumberField("Batch Volume");
batchVolume.setRequiredIndicatorVisible(true);
batchVolume.setVisible(false);
columnLayout.add(batchVolume,1);
units = new Select<>();
units.setLabel("Units");
units.setRequiredIndicatorVisible(true);
units.setItems(UnitOfMeasure.getVolumeUnitsOfMeasure());
units.setEmptySelectionAllowed(true);
units.setVisible(false);
columnLayout.add(units,1);
TextField comment = new TextField("Comment");
columnLayout.add(comment,3);
binder = new Binder<>();
binder.forField(pipelines).asRequired().bind(PiggingEvent::getPipeline,PiggingEvent::setPipeline);
binder.forField(fromLocation).asRequired().bind(PiggingEvent::getFromLocation,PiggingEvent::setFromLocation);
binder.forField(toLocation).asRequired().bind(PiggingEvent::getToLocation,PiggingEvent::setToLocation);
binder.forField(dateSent).withValidator(date -> !date.isAfter(LocalDate.now()),"Date sent cannot be in the future").bind(PiggingEvent::getDateSent,PiggingEvent::setDateSent);
binder.forField(sentBy).asRequired().bind(PiggingEvent::getSentBy,PiggingEvent::setSentBy);
binder.forField(sizingRingUsed).bind(PiggingEvent::getSizingRingUsed,PiggingEvent::setSizingRingUsed);
binder.forField(pigType).asRequired().bind(PiggingEvent::getPigType,PiggingEvent::setPigType);
binder.forField(pigSize).asRequired().bind(PiggingEvent::getPigSize,PiggingEvent::setPigSize);
binder.forField(durometer).bind(PiggingEvent::getDurometer,PiggingEvent::setDurometer);
binder.forField(dateRetrieved).withValidator(date -> date == null || (!date.isAfter(LocalDate.now()) && !date.isBefore(dateSent.getValue())), "Date Retrieved cannot be in the future or before the date sent").bind(PiggingEvent::getDateRetrieved,PiggingEvent::setDateRetrieved);
binder.forField(retrievedBy).bind(PiggingEvent::getRetrievedBy,PiggingEvent::setRetrievedBy);
binder.forField(piggingTime).bind(PiggingEvent::getPiggingTime,PiggingEvent::setPiggingTime);
binder.forField(batchFluidUsed).bind(PiggingEvent::getBatchFluidUsed,PiggingEvent::setBatchFluidUsed);
Binder.Binding<PiggingEvent, Double> batchVolumeBinding = binder.forField(batchVolume).withValidator(value -> batchFluidUsed.getValue() == null || batchFluidUsed.getValue() == NO || value != null, "").bind(PiggingEvent::getBatchVolume, PiggingEvent::setBatchVolume);
Binder.Binding<PiggingEvent, UnitOfMeasure> unitsBinding = binder.forField(units).withValidator(value -> batchFluidUsed.getValue() == null || batchFluidUsed.getValue() == NO || value != null, "").bind(PiggingEvent::getUnits, PiggingEvent::setUnits);
batchFluidUsed.addValueChangeListener(event -> {
batchVolumeBinding.validate();
unitsBinding.validate();
});
binder.forField(comment).bind(PiggingEvent::getComment,PiggingEvent::setComment);
binder.addValueChangeListener(e -> save.setEnabled(binder.validate().isOk()));
return columnLayout;
}
private Set<String> getPipelineLocations(Plants plant) {
Set<String> locations = new HashSet<>();
List<Pipeline> pipelines = pipelineAdmin.getActivePipelinesByPlant(plant.getId());
for (Pipeline pipeline : pipelines) {
locations.add(pipeline.getFromLocation());
locations.add(pipeline.getToLocation());
}
return locations;
}
private HorizontalLayout createButtonLayout() {
save = new Button("Save");
save.addClickListener(e -> handleSaveButtonClick());
Button cancel = new Button("Cancel");
cancel.addClickListener(e -> handleCancelButtonClick());
return new HorizontalLayout(save, cancel);
}
private void handleBatchFluidUsedValueChanged(HasValue.ValueChangeEvent<?> e) {
Acknowledgment action = (Acknowledgment)e.getValue();
batchVolume.setVisible(action == YES);
units.setVisible(action == YES);
}
private void handleSaveButtonClick() {
PiggingEvent piggingEvent = new PiggingEvent();
if (binder.writeBeanIfValid(piggingEvent)) {
piggingEvent.setStatus(PiggingEventStatus.ACTIVE);
Plants currentlySelectedPlant = (Plants) VaadinSession.getCurrent().getAttribute(CURRENTLY_SELECTED_PLANT);
piggingEvent.setPlantId(currentlySelectedPlant.getId());
piggingEventAdmin.save(piggingEvent, sessionDataProvider.get());
Notification notification = new Notification("Pigging Event has been saved", 3000);
notification.open();
}
clear();
}
private void handleCancelButtonClick() {
UI.getCurrent().navigate(PiggingView.class);
}
private void clear() {
layout.removeAll();
layout.add(createPipelineDetails(),createButtonLayout());
}
}
}
|
package com.codigo.smartstore.sdk.core.checksum.crc;
import java.util.EnumMap;
/**
* Typ wyliczeniowy określa znaczniki dla dostępnych wariantów wykonania sumy
* kontrolnej CRC32.
*
* @author andrzej.radziszewski
* @version 1.0.0.0
* @category enumeration
*/
enum CRC32_OPTIONS implements
ICrcParametrizable {
CRC32,
CRC32_BZIP2,
CRC32_C,
CRC32_D,
CRC32_MPEG2,
CRC32_POSIX,
CRC32_Q,
CRC32_JAMCRC,
CRC32_XFER;
/**
* Atrybut obiektu określa kolekcję obiektów typu <code>ICrcParameter</code>
* gdzie kluczem jest typ <code>CRC8_OPTIONS</code>
*/
private static final EnumMap<CRC32_OPTIONS, CrcParameter> crcOptions;
/**
* Statyczny inicjalizator klasy <code>CRC32_OPTIONS</code>
*/
static {
crcOptions = new EnumMap<>(
CRC32_OPTIONS.class);
// ...CRC32
crcOptions.put(
CRC32, new CrcParameter(
32, "CRC32", 0x04C11DB7, 0xFFFFFFFF, 0xFFFFFFFF, true, true));
// ...CRC32_BZIP2
crcOptions.put(
CRC32_BZIP2, new CrcParameter(
32, "CRC32_BZIP2", 0x04C11DB7, 0xFFFFFFFF, 0xFFFFFFFF, false, false));
// ...CRC32_C
crcOptions.put(
CRC32_C, new CrcParameter(
32, "CRC32_C", 0x1EDC6F41, 0xFFFFFFFF, 0xFFFFFFFF, true, true));
// ...CRC32_D
crcOptions.put(
CRC32_D, new CrcParameter(
32, "CRC32_D", 0xA833982B, 0xFFFFFFFF, 0xFFFFFFFF, true, true));
// ...CRC32_MPEG2
crcOptions.put(
CRC32_MPEG2, new CrcParameter(
32, "CRC32_MPEG2", 0x04C11DB7, 0xFFFFFFFF, 0x00000000, false, false));
// ...CRC32_POSIX
crcOptions.put(
CRC32_POSIX, new CrcParameter(
32, "CRC32_POSIX", 0x04C11DB7, 0x00000000, 0xFFFFFFFF, false, false));
// ...CRC32_Q
crcOptions.put(
CRC32_Q, new CrcParameter(
32, "CRC32_Q", 0x814141AB, 0x00000000, 0x00000000, false, false));
// ...CRC32_JAMCRC
crcOptions.put(
CRC32_JAMCRC, new CrcParameter(
32, "CRC32_JAMCRC", 0x04C11DB7, 0xFFFFFFFF, 0x00000000, true, true));
// ... CRC32_XFER
crcOptions.put(
CRC32_XFER, new CrcParameter(
32, "CRC32_XFER", 0x000000AF, 0x00000000, 0x00000000, false, false));
}
/*
* (non-Javadoc)
* @see com.codigo.aplios.checksum.core.crc.ICrcParametrizable#getParameters()
*/
@Override
public ICrcParameter getParameters() {
return crcOptions.get(this);
}
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.