text
stringlengths 10
2.72M
|
|---|
package org.squonk.core.config;
/**
* Created by timbo on 13/03/16.
*/
public class SquonkClientConfig {
public static final String CORE_SERVICES_SERVER = "http://coreservices:8080";
public static final String CORE_SERVICES_PATH = "/coreservices/rest/v1";
public static final String CORE_SERVICES_BASE = CORE_SERVICES_SERVER + CORE_SERVICES_PATH;
}
|
package com.gxc.stu.converter;
import java.text.DateFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
import org.springframework.core.convert.converter.Converter;
public class DateConverter implements Converter<String, Date>{
@Override
public Date convert(String source) {
if(source != null){
try {
//正常情况下
DateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd");
Date date = dateFormat.parse(source);
return date;
} catch (ParseException e) {
try {
//苹果手机兼容
DateFormat dateFormat2 = new SimpleDateFormat("yyyy年MM月dd日");
Date date2 = dateFormat2.parse(source);
return date2;
} catch (ParseException e1) {
return new Date();
}
}
}
return new Date();
}
}
|
/**
*
* @author Jere Kaplas
*/
package carrental;
import java.util.Date;
public class Rental {
private Customer customer;
private Car car;
private Date startDate;
private Date endDate;
public Rental(Customer renter, Car rentalCar, Date start, Date end) {
this.car = rentalCar;
this.customer = renter;
this.startDate = start;
this.endDate = end;
}
public String toString() {
return "Customer info: " + this.customer + "\nCar details: " + this.car + "\nStart date: " + this.startDate + ", End date: " + this.endDate;
}
}
|
package com.liangjing.mylibrary.view;
import android.animation.TypeEvaluator;
import android.graphics.PointF;
import com.liangjing.mylibrary.util.BezierUtil;
/**
* Created by liangjing on 2017/7/17.
* 功能:Evaluator是属性动画中非常重要的一个东西,他根据输入的初始值和结束值以及一个进度比,
* 那么就可以计算出每一个进度比下所要返回的值。
*/
public class BezierEvaluator implements TypeEvaluator<PointF> {
//控制点1
private PointF pointF1;
//控制点2
private PointF pointF2;
public BezierEvaluator(PointF pointF1, PointF pointF2) {
this.pointF1 = pointF1;
this.pointF2 = pointF2;
}
@Override
public PointF evaluate(float fraction, PointF startValue, PointF endValue) {
PointF pointF = new PointF();//结果
pointF = BezierUtil.CalculateBezierPointForCubic(fraction,startValue,pointF1,pointF2,endValue);
return pointF;
}
}
|
class Frame{
//doubly linked list to hold frames
float time = 0.f;
float value = 0.f;
Frame next = null;
Frame prev = null;
public Frame(){}
public Frame(float t){
time = t;
}
public Frame(float t, float v){
time=t;
value=v;
}
public void Append(Frame f){
if((next!=null)&&(next.time<f.time))
next.Append(f);
else if((next!=null)&&(next.time>f.time)&&(time<f.time)){//insert here
f.prev=this;
f.next = next;
f.value = value;
next = f;
}
else if((next==null)&&(time<f.time)){//insert at end
f.prev=this;
next = f;
f.value = value;//copy priorities
}
else if(time>f.time){//insert at start
f.prev=null;
f.next=this;
f.value = value;
prev=f;
}
}
public void Append(float t, int i){
if(next!=null){
if(next.time<t)
next.Append(t, i);//advance
else{//insert
Frame f = new Frame(t);
f.prev=this;
f.next = next.next;
next = f;
}
}else{
if(time<t){//empty list
Frame f = new Frame(t);
f.prev=this;
f.next = null;
next = f;
}
else{
Frame f = new Frame(t);
f.next=this;
f.prev=null;
prev = f;
}
}
}
public void SetValue(float v){
value=v;
}
}
|
package strategy01;
public interface Freight {
public double calculate(Integer numKilometers);
}
|
package dev.fujioka.eltonleite.presentation.dto.employee;
import java.time.LocalDate;
public class EmployeeRequestTO {
private String name;
private LocalDate dateBirth;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public LocalDate getDateBirth() {
return dateBirth;
}
public void setDateBirth(LocalDate dateBirth) {
this.dateBirth = dateBirth;
}
@Override
public String toString() {
return String.format("Employee [name=%s, dateBirth=%s]", name, dateBirth);
}
}
|
/*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/
package cput.codez.angorora.eventstar.model;
/**
*
* @author allen
*/
public final class CashPayment {
private String id;
private String payeeId;
private double amount;
private String eventId;
private String date;
private CashPayment() {
}
private CashPayment(Builder build){
this.id=build.id;
this.payeeId=build.payeeId;
this.amount=build.amount;
this.eventId=build.eventId;
this.date=build.date;
}
public String getId() {
return id;
}
public String getPayeeId() {
return payeeId;
}
public double getAmount() {
return amount;
}
public String getEventId() {
return eventId;
}
public String getDate() {
return date;
}
public static class Builder{
private String id;
private String payeeId;
private double amount;
private String eventId;
private String date;
public Builder(String id) {
this.id=id;
}
public Builder payeeId(String payeeId){
this.payeeId=payeeId;
return this;
}
public Builder amount(double amnt){
this.amount=amnt;
return this;
}
public Builder eventId(String evId){
this.eventId=evId;
return this;
}
public Builder date(String date){
this.date=date;
return this;
}
public CashPayment build(){
return new CashPayment(this);
}
public Builder copier(CashPayment pay){
this.id=pay.id;
this.payeeId=pay.payeeId;
this.amount=pay.amount;;
this.eventId=pay.eventId;
this.date=pay.date;
return this;
}
}
@Override
public int hashCode() {
int hash = 3;
hash = 23 * hash + (this.id != null ? this.id.hashCode() : 0);
return hash;
}
@Override
public boolean equals(Object obj) {
if (obj == null) {
return false;
}
if (getClass() != obj.getClass()) {
return false;
}
final CashPayment other = (CashPayment) obj;
if ((this.id == null) ? (other.id != null) : !this.id.equals(other.id)) {
return false;
}
return true;
}
}
|
package rs.ac.bg.etf.pmu.sv100502.monopoly.helpers;
import android.util.DisplayMetrics;
import rs.ac.bg.etf.pmu.sv100502.monopoly.GameActivity;
import rs.ac.bg.etf.pmu.sv100502.monopoly.classes.ColorGroup;
import rs.ac.bg.etf.pmu.sv100502.monopoly.classes.FieldCoordinates;
import rs.ac.bg.etf.pmu.sv100502.monopoly.classes.Position;
/**
* Created by Vuk on 30.06.2016..
*/
public class Initialize {
private static final int PAWN_PIXEL_SIZE = 30;
private static final int HOTEL_PIXEL_MARGIN = 20;
private static final int NUMBER_OF_CORNER_FIELDS = 4;
private static final int NUMBER_OF_TOP_BOTTOM_FIELDS = 9;
private static final int NUMBER_OF_LEFT_RIGHT_FIELDS = 4;
// How many times is corner field bigger than regular one
private static final double RATIO = 1.6;
// Number of regular fields
// top and bottom
private static final double NUMBER_OF_FIELDS_LONGITUDE = 12.2;
// left and right
private static final double NUMBER_OF_FIELDS_LATITUDE = 7.2;
private FieldCoordinates[] cornerFieldCoords;
private FieldCoordinates[] bottomFieldCoords;
private FieldCoordinates[] leftFieldCoords;
private FieldCoordinates[] topFieldCoords;
private FieldCoordinates[] rightFieldCoords;
// Initialize color groups for properties
public ColorGroup[] initColorGroups() {
ColorGroup[] colorGroups = new ColorGroup[GameActivity.NUMBER_OF_COLOR_GROUPS];
colorGroups[GameActivity.BROWN_COLOR_GROUP] = new ColorGroup(50);
colorGroups[GameActivity.LIGHT_BLUE_COLOR_GROUP] = new ColorGroup(50);
colorGroups[GameActivity.ORANGE_COLOR_GROUP] = new ColorGroup(100);
colorGroups[GameActivity.RED_COLOR_GROUP] = new ColorGroup(150);
colorGroups[GameActivity.YELLOW_COLOR_GROUP] = new ColorGroup(150);
colorGroups[GameActivity.BLUE_COLOR_GROUP] = new ColorGroup(200);
// star price isn't important, since stars can't be added to these color groups
colorGroups[GameActivity.RAILROAD_COLOR_GROUP] = new ColorGroup(0);
colorGroups[GameActivity.UTILITY_COLOR_GROUP] = new ColorGroup(0);
return colorGroups;
}
// Set up field coordinates
private void initFieldCoordinates(DisplayMetrics metrics) {
int topBottomFieldWidth = (int) (metrics.widthPixels / NUMBER_OF_FIELDS_LONGITUDE);
int leftRightFieldWidth = (int) (metrics.heightPixels / NUMBER_OF_FIELDS_LATITUDE);
int topBottomFieldHeight = (int) (leftRightFieldWidth * RATIO);
int leftRightFieldHeight = (int) (topBottomFieldWidth * RATIO);
cornerFieldCoords = new FieldCoordinates[NUMBER_OF_CORNER_FIELDS];
cornerFieldCoords[0] = new FieldCoordinates( // bottom right field
metrics.widthPixels - leftRightFieldHeight,
metrics.heightPixels - topBottomFieldHeight,
metrics.widthPixels, metrics.heightPixels);
cornerFieldCoords[1] = new FieldCoordinates( // bottom left field
0, metrics.heightPixels - topBottomFieldHeight,
leftRightFieldHeight, metrics.heightPixels);
cornerFieldCoords[2] = new FieldCoordinates( // top left field
0, 0, leftRightFieldHeight, topBottomFieldHeight);
cornerFieldCoords[3] = new FieldCoordinates( // top right field
metrics.widthPixels - leftRightFieldHeight, 0,
metrics.widthPixels, topBottomFieldHeight);
bottomFieldCoords = new FieldCoordinates[NUMBER_OF_TOP_BOTTOM_FIELDS];
for (int i = 0; i < NUMBER_OF_TOP_BOTTOM_FIELDS; i++) {
bottomFieldCoords[i] = new FieldCoordinates(
metrics.widthPixels - leftRightFieldHeight - topBottomFieldWidth * (i + 1),
metrics.heightPixels - topBottomFieldHeight,
metrics.widthPixels - leftRightFieldHeight - topBottomFieldWidth * i,
metrics.heightPixels);
}
leftFieldCoords = new FieldCoordinates[NUMBER_OF_LEFT_RIGHT_FIELDS];
for (int i = 0; i < NUMBER_OF_LEFT_RIGHT_FIELDS; i++) {
leftFieldCoords[i] = new FieldCoordinates(
0, metrics.heightPixels - topBottomFieldHeight - leftRightFieldWidth * (i + 1),
leftRightFieldHeight,
metrics.heightPixels - topBottomFieldHeight - leftRightFieldWidth * i);
}
topFieldCoords = new FieldCoordinates[NUMBER_OF_TOP_BOTTOM_FIELDS];
for (int i = 0; i < NUMBER_OF_TOP_BOTTOM_FIELDS; i++) {
topFieldCoords[i] = new FieldCoordinates(
leftRightFieldHeight + topBottomFieldWidth * i, 0,
leftRightFieldHeight + topBottomFieldWidth * (i + 1),
topBottomFieldHeight);
}
rightFieldCoords = new FieldCoordinates[NUMBER_OF_LEFT_RIGHT_FIELDS];
for (int i = 0; i < NUMBER_OF_LEFT_RIGHT_FIELDS; i++) {
rightFieldCoords[i] = new FieldCoordinates(
metrics.widthPixels - leftRightFieldHeight,
topBottomFieldHeight + leftRightFieldWidth * i,
metrics.widthPixels,
topBottomFieldHeight + leftRightFieldWidth * (i + 1));
}
}
// Set up all possible player and hotel positions
// Returns two arrays (playerPositions and hotelPositions)
public Position[][] initPositions(DisplayMetrics metrics) {
// Set up field coordinates
initFieldCoordinates(metrics);
Position[] playerPositions = new Position[GameActivity.NUMBER_OF_FIELDS];
Position[] hotelPositions = new Position[GameActivity.NUMBER_OF_FIELDS];
int j = 0; // for iteration over top and bottom fields
int k = 0; // for iteration over left and right fields
// Pawn's diagonal
int pawnDiagonal = (int) (PAWN_PIXEL_SIZE * Math.sqrt(2));
for (int i = 0; i < GameActivity.NUMBER_OF_FIELDS; i++) {
if (j >= NUMBER_OF_TOP_BOTTOM_FIELDS) j = 0;
if (k >= NUMBER_OF_LEFT_RIGHT_FIELDS) k = 0;
if (i == 0) { //bottom right field
playerPositions[i] = new Position(
(cornerFieldCoords[0].getRight() - cornerFieldCoords[0].getLeft()) / 2 + cornerFieldCoords[0].getLeft() - pawnDiagonal,
(cornerFieldCoords[0].getBottom() - cornerFieldCoords[0].getTop()) / 2 + cornerFieldCoords[0].getTop() - pawnDiagonal);
hotelPositions[i] = new Position(0, 0); // isn't important; hotel will never go there
} else if (i < 10) { // bottom fields
playerPositions[i] = new Position(
(bottomFieldCoords[j].getRight() - bottomFieldCoords[j].getLeft()) / 2 + bottomFieldCoords[j].getLeft() - pawnDiagonal,
(bottomFieldCoords[j].getBottom() - bottomFieldCoords[j].getTop()) / 2 + bottomFieldCoords[j].getTop() - pawnDiagonal);
hotelPositions[i] = new Position(
bottomFieldCoords[j].getLeft() + HOTEL_PIXEL_MARGIN,
bottomFieldCoords[j].getTop() + HOTEL_PIXEL_MARGIN);
j++;
} else if (i == 10) { // bottom left field
playerPositions[i] = new Position(
(cornerFieldCoords[1].getRight() - cornerFieldCoords[1].getLeft()) / 2 + cornerFieldCoords[1].getLeft() - pawnDiagonal,
(cornerFieldCoords[1].getBottom() - cornerFieldCoords[1].getTop()) / 2 + cornerFieldCoords[1].getTop() - pawnDiagonal);
hotelPositions[i] = new Position(0, 0); // isn't important; hotel will never go there
} else if (i < 15) { // left fields
playerPositions[i] = new Position(
(leftFieldCoords[k].getRight() - leftFieldCoords[k].getLeft()) / 2 + leftFieldCoords[k].getLeft() - pawnDiagonal,
(leftFieldCoords[k].getBottom() - leftFieldCoords[k].getTop()) / 2 + leftFieldCoords[k].getTop() - pawnDiagonal);
hotelPositions[i] = new Position(
leftFieldCoords[k].getLeft() + HOTEL_PIXEL_MARGIN,
leftFieldCoords[k].getTop() + HOTEL_PIXEL_MARGIN);
k++;
} else if (i == 15) { // top left field
playerPositions[i] = new Position(
(cornerFieldCoords[2].getRight() - cornerFieldCoords[2].getLeft()) / 2 + cornerFieldCoords[2].getLeft() - pawnDiagonal,
(cornerFieldCoords[2].getBottom() - cornerFieldCoords[2].getTop()) / 2 + cornerFieldCoords[2].getTop() - pawnDiagonal);
hotelPositions[i] = new Position(0, 0); // isn't important; hotel will never go there
} else if (i < 25) { // top fields
playerPositions[i] = new Position(
(topFieldCoords[j].getRight() - topFieldCoords[j].getLeft()) / 2 + topFieldCoords[j].getLeft() - pawnDiagonal,
(topFieldCoords[j].getBottom() - topFieldCoords[j].getTop()) / 2 + topFieldCoords[j].getTop() - pawnDiagonal);
hotelPositions[i] = new Position(
topFieldCoords[j].getLeft() + HOTEL_PIXEL_MARGIN,
topFieldCoords[j].getTop() + HOTEL_PIXEL_MARGIN);
j++;
} else if (i == 25) { // top right field
playerPositions[i] = new Position(
(cornerFieldCoords[3].getRight() - cornerFieldCoords[3].getLeft()) / 2 + cornerFieldCoords[3].getLeft() - pawnDiagonal,
(cornerFieldCoords[3].getBottom() - cornerFieldCoords[3].getTop()) / 2 + cornerFieldCoords[3].getTop() - pawnDiagonal);
hotelPositions[i] = new Position(0, 0); // isn't important; hotel will never go there
} else { //right fields
playerPositions[i] = new Position(
(rightFieldCoords[k].getRight() - rightFieldCoords[k].getLeft()) / 2 + rightFieldCoords[k].getLeft() - pawnDiagonal,
(rightFieldCoords[k].getBottom() - rightFieldCoords[k].getTop()) / 2 + rightFieldCoords[k].getTop() - pawnDiagonal);
hotelPositions[i] = new Position(
rightFieldCoords[k].getLeft() + HOTEL_PIXEL_MARGIN,
rightFieldCoords[k].getTop() + HOTEL_PIXEL_MARGIN);
k++;
}
}
return new Position[][] { playerPositions, hotelPositions };
}
}
|
public class controller {
public static void main(String[] args) {
manager ob=new manager();
staff s1=new staff(10, "Aloy", ob);
}
}
|
package abiguime.tz.com.tzyoutube._commons.customviews;
import android.content.Context;
import android.util.AttributeSet;
import android.util.Log;
import android.view.Gravity;
import android.view.SurfaceView;
import android.view.View;
import android.view.ViewGroup;
import android.widget.FrameLayout;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import com.squareup.picasso.Picasso;
import abiguime.tz.com.tzyoutube.R;
import abiguime.tz.com.tzyoutube._data.Video;
import abiguime.tz.com.tzyoutube._data.constants.Constants;
/**
* Created by abiguime on 2016/12/9.
*/
public class MyRelativeLayout2 extends LinearLayout {
private boolean hasFinishInflate = false;
private Video video;
// surfaceview
SurfaceView sv;
// imageview
ImageView iv;
private boolean initialMotion = true;
public MyRelativeLayout2(Context context) {
this(context, null);
}
public MyRelativeLayout2(Context context, AttributeSet attrs) {
this(context, attrs, 0);
}
public MyRelativeLayout2(Context context, AttributeSet attrs, int defStyleAttr) {
super(context, attrs, defStyleAttr);
setOrientation(VERTICAL);
}
private FrameLayout frame_playback;
@Override
protected void onFinishInflate() {
super.onFinishInflate();
frame_playback = (FrameLayout) findViewById(R.id.frame_playback);
iv = (ImageView) findViewById(R.id.iv_videoclub);
sv = (SurfaceView) findViewById(R.id.sv_videoclub);
hasFinishInflate = true;
}
@Override
protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
super.onMeasure(widthMeasureSpec, heightMeasureSpec);
int w = getContext().getResources().getDisplayMetrics().widthPixels;
int h = (9*w/16);
// 设置布局最开始的大小
setMeasuredDimension(w, h);
/*1- 一开始,这个布局里会有很多视图
但是,当我自动改变本视图大小之后,由于视图在更改的时候
还没有显示过自己内部的视图的愿意,
那么这些视图就不改自己的大小。
2 - 所以需要手动去设置视图的大小
* */
if (hasFinishInflate)
setVideoClubSize ();
}
public void setVideoClubSize () {
if (getHeight() == 0 || getWidth() == 0)
return;
MyRelativeLayout2.LayoutParams layoutParams = (LayoutParams) frame_playback.getLayoutParams();
layoutParams.height = getHeight();
layoutParams.width = getWidth();//(initialMotion ? 3:1);
//添加margin
layoutParams.rightMargin = (int) (getContext().getResources().getDimensionPixelSize(R.dimen.item_margin_bottom)
* (1-getScaleY() + (initialMotion?1:0))); // 1
frame_playback.setLayoutParams(layoutParams);
frame_playback.setScaleX((initialMotion ? (1f/3f): getScaleY()));
frame_playback.setPivotX(getWidth());
frame_playback.setScaleY((initialMotion ? (1f/3f): 1));
frame_playback.setPivotY(getHeight());
}
public void setInitialMotion(boolean initialMotion) {
this.initialMotion = initialMotion;
}
public SurfaceView getSv() {
return sv;
}
public ImageView getIv() {
return iv;
}
// 按照视频大小更改surfaceview的大小
public void setSvSize(int videoWidth, int videoHeight) {
// 不能超过的高宽
int maxWidth = getContext().getResources().getDisplayMetrics().widthPixels;
int maxHeight = 9* maxWidth /16;
FrameLayout.LayoutParams fr = (FrameLayout.LayoutParams) sv.getLayoutParams();
int newHeight = videoHeight, newWidth = videoWidth;
// 视频时垂直方向显示
if (videoHeight > maxHeight) {
newHeight = maxHeight;
newWidth = (int) (videoWidth * ((float)maxHeight/ (float)videoHeight));
}
fr.height = newHeight;
fr.width = newWidth;
fr.gravity = Gravity.CENTER;
sv.setLayoutParams(fr);
}
private int getVideo16_9Height() {
return 9*getResources().getDisplayMetrics().widthPixels/16;
}
}
|
package it.apulia.Esercitazione3.accessManagement;
import it.apulia.Esercitazione3.accessManagement.model.Utente;
import org.springframework.data.mongodb.repository.MongoRepository;
import org.springframework.stereotype.Repository;
@Repository
public interface UserRepository extends MongoRepository<Utente,String> {
Utente findUtenteByUsername(String username);
Boolean existsByUsername(String username);
}
|
package nz.co.fendustries.whatstheweatherlike.domain.responseModels;
import com.google.gson.annotations.SerializedName;
import java.util.List;
/**
* Created by joshuafenemore on 5/12/16.
*/
public class ForecastResponse
{
private double latitude;
private double longitude;
private String timezone;
private int offset;
@SerializedName("currently")
private CurrentForecast currentForecast;
@SerializedName("hourly")
private HourForecast hourForecast;
@SerializedName("daily")
private DayForecast dayForecast;
private List<Alert> alerts;
private Flags flags;
public double getLatitude()
{
return latitude;
}
public void setLatitude(double latitude)
{
this.latitude = latitude;
}
public double getLongitude()
{
return longitude;
}
public void setLongitude(double longitude)
{
this.longitude = longitude;
}
public String getTimezone()
{
return timezone;
}
public void setTimezone(String timezone)
{
this.timezone = timezone;
}
public int getOffset()
{
return offset;
}
public void setOffset(int offset)
{
this.offset = offset;
}
public Flags getFlags()
{
return flags;
}
public void setFlags(Flags flags)
{
this.flags = flags;
}
public CurrentForecast getCurrentForecast()
{
return currentForecast;
}
public void setCurrentForecast(CurrentForecast currentForecast)
{
this.currentForecast = currentForecast;
}
public HourForecast getHourForecast()
{
return hourForecast;
}
public void setHourForecast(HourForecast hourForecast)
{
this.hourForecast = hourForecast;
}
public DayForecast getDayForecast()
{
return dayForecast;
}
public void setDayForecast(DayForecast dayForecast)
{
this.dayForecast = dayForecast;
}
public List<Alert> getAlerts()
{
return alerts;
}
public void setAlerts(List<Alert> alerts)
{
this.alerts = alerts;
}
}
|
package com.wrathOfLoD.Models.Target;
import com.wrathOfLoD.Models.Entity.Character.Pet;
import com.wrathOfLoD.Models.Items.Item;
/**
* Created by matthewdiaz on 4/9/16.
*/
public class AvatarTargetManager extends TargetManager {
public AvatarTargetManager(){
super();
}
/**
* do nothing, avatart target manager doesnt need to know items
* @param itemTarget
*/
@Override
public void updateMyList(ItemTarget itemTarget) {
}
@Override
public void updateActiveTarget() {
if(getActiveTarget() == null && totalTargets() != 0){
Target targ = getTargetFromSet(0);
if(targ.getTarget() instanceof Pet){
Target temp = getTargetFromSet(1);
if(temp != null){
targ = temp;
}
}
}
else if(getActiveTarget() != null){
//do nothing
}
}
/**
* do nothing we never added items to the avatar target list
* @param i
*/
@Override
public void deregisterItem(Item i) {
}
/**
* gets the highest priority target if active target isn't set, and sets active target to it
* if it is set cycles to the next highest priority target, and sets active target to it
*/
public void cycleActiveTarget(){
if(totalTargets() != 0){
if(!getActiveTarget().equals(null) && totalTargets() != 1){
int nextIndex = getIndexofTarget(getActiveTarget()) % (totalTargets() - 1);
setActiveTarget(getTargetFromSet(nextIndex));
}
else{
setActiveTarget(getHighestPriorityTarget());
}
}
setActiveTarget(null);
}
}
|
package com.nanyin.entity;
import com.alibaba.fastjson.annotation.JSONField;
import com.fasterxml.jackson.annotation.JsonIgnore;
import com.google.common.base.Objects;
import io.swagger.annotations.ApiModel;
import lombok.*;
import org.checkerframework.checker.units.qual.C;
import org.hibernate.annotations.*;
import javax.persistence.*;
import javax.persistence.CascadeType;
import javax.persistence.Entity;
import javax.persistence.Table;
import javax.validation.constraints.Email;
import javax.validation.constraints.Size;
import java.io.Serializable;
import java.util.Date;
import java.util.Set;
@Getter
@Setter
@Entity
@Table(name="user")
@ApiModel(value="User",description = "用户实体类")
public class User implements Serializable {
private static final long serialVersionUID = -7912979476697449896L;
@JSONField(name = "id")
@Id
@Column(columnDefinition = "INT(11)")
@GeneratedValue(strategy=GenerationType.IDENTITY)
private Integer id;
@JSONField(name = "name")
@Column(length = 64)
private String name;
@Size(min = 3,max = 63,message ="{user_password_length}" )
@JSONField(name = "password")
@Column(length = 64)
private String password;
@JSONField(name = "email")
@Email(message = "{user_email_format}")
@Column(length = 64)
private String email;
@Column(length = 64)
private String salt;
@Column(columnDefinition = "TINYINT(4)")
private Short age;
@OneToOne()
@JSONField(name = "sex")
@JoinColumn(name="sex_id",columnDefinition = "INT(11)")
private Sex sex;
@OneToOne()
@JSONField(name = "status")
@JoinColumn(columnDefinition = "INT(11)",name = "status_id")
private Status status;
@Column(name = "is_deleted",columnDefinition = "TINYINT(1)",nullable =
false)
private Short isDeleted=0;
@Temporal(value=TemporalType.TIMESTAMP)
private Date gmtCreate;
@Temporal(value=TemporalType.TIMESTAMP)
private Date gmtModify;
@JSONField(name = "roles")
@ManyToMany(mappedBy = "users",fetch = FetchType.EAGER,cascade = CascadeType.ALL)
private Set<Role> roles;
@OneToOne(cascade = CascadeType.ALL)
@JoinColumn(columnDefinition = "INT(11)",name = "person_id")
private Person person;
@ManyToOne
@JoinColumn(name = "unit_id")
private Unit unit;
@Override
public boolean equals(Object o) {
if (this == o) return true;
if (o == null || getClass() != o.getClass()) return false;
User user = (User) o;
return Objects.equal(id, user.id) &&
Objects.equal(name, user.name);
}
@Override
public int hashCode() {
return Objects.hashCode(id, name, password, email, salt, age, sex, status, isDeleted, gmtCreate, gmtModify, roles, person, unit);
}
}
|
package core.client.game.operations;
import java.util.EnumSet;
import java.util.LinkedHashMap;
import java.util.LinkedList;
import java.util.Map;
import java.util.Queue;
import java.util.stream.Collectors;
import cards.Card;
import cards.equipments.Equipment.EquipmentType;
import commands.server.ingame.InGameServerCommand;
import core.player.PlayerCardZone;
import core.player.PlayerCompleteClient;
import core.player.PlayerSimple;
import ui.game.interfaces.CardUI;
import ui.game.interfaces.EquipmentUI;
import ui.game.interfaces.PlayerUI;
public abstract class AbstractMultiCardMultiTargetOperation extends AbstractOperation {
protected final int maxCards;
protected int maxTargets;
/**
* A queue of selected targets
*/
protected final Queue<PlayerUI> targets;
/**
* A map from selected cards to their respective PlayerCardZone
*/
protected final Map<CardUI, PlayerCardZone> cards;
/**
* @param maxCards : 0 <= maxCards
* @param maxTargets : 0 <= maxTargets
*/
public AbstractMultiCardMultiTargetOperation(int maxCards, int maxTargets) {
this.maxCards = maxCards;
this.maxTargets = maxTargets;
this.targets = new LinkedList<>();
this.cards = new LinkedHashMap<>();
}
@Override
public final void onConfirmed() {
super.onConfirmed();
this.panel.sendResponse(getCommandOnConfirm());
}
@Override
public final void onPlayerClicked(PlayerUI target) {
if (this.maxTargets == 0) {
return;
}
if (this.targets.contains(target)) { // unselect a selected target
target.setActivated(false);
this.targets.remove(target);
} else { // select a new target, unselect the oldest target if exceeding maximum
if (this.targets.size() == this.maxTargets) {
this.targets.poll().setActivated(false);
}
target.setActivated(true);
this.targets.add(target);
}
this.panel.getGameUI().setCancelEnabled(this.isCancelEnabled());
this.panel.getGameUI().setConfirmEnabled(this.isConfirmEnabled());
}
@Override
public final void onCardClicked(CardUI card) {
if (this.maxCards == 0) {
this.onCardActivatorClicked(card);
return;
}
this.onCardClicked(card, PlayerCardZone.HAND);
// enable or disable cards on hand again based on clicked card
this.panel.getGameUI().getCardRackUI().getCardUIs().forEach(ui -> {
ui.setActivatable(isCardActivatable(ui.getCard()));
});
}
private final void onEquipmentClicked(EquipmentUI equipment) {
if (this.maxCards == 0) {
return;
}
this.onCardClicked(equipment, PlayerCardZone.EQUIPMENT);
}
private final void onCardClicked(CardUI card, PlayerCardZone zone) {
if (this.cards.containsKey(card)) { // unselect a selected card
this.cards.remove(card);
card.setActivated(false);
} else { // select a new card, unselect the oldest card if exceeding maximum
if (this.cards.size() == this.maxCards) {
CardUI oldest = this.getFirstCardUI();
this.cards.remove(oldest);
oldest.setActivated(false);
}
card.setActivated(true);
this.cards.put(card, zone);
}
this.panel.getGameUI().setCancelEnabled(this.isCancelEnabled());
this.panel.getGameUI().setConfirmEnabled(this.isConfirmEnabled());
}
/**
* <p>{@inheritDoc}</p>
*
* NOTE: Does not set the activator Activatable or Activated
*/
@Override
public final void onLoaded() {
// set message
this.panel.getGameUI().setMessage(getMessage());
// enable viable targets
this.panel.getGameUI().getOtherPlayersUI().forEach(ui -> {
if (ui.getPlayer().isAlive() && isPlayerActivatable(ui.getPlayer())) {
ui.setActivatable(true);
}
});
if (isPlayerActivatable(this.panel.getGameUI().getHeroUI().getPlayer())) {
this.panel.getGameUI().getHeroUI().setActivatable(true);
}
// enable viable cards on hand
this.panel.getGameUI().getCardRackUI().getCardUIs().forEach(ui -> {
if (isCardActivatable(ui.getCard())) {
ui.setActivatable(true);
}
});
// enable viable equipments
this.panel.getGameUI().getEquipmentRackUI().setActivatable(
EnumSet.allOf(EquipmentType.class).stream().filter(type -> isEquipmentTypeActivatable(type)).collect(Collectors.toSet()),
e -> this.onEquipmentClicked(e)
);
// enable Cancel & Confirm
if (isCancelEnabled()) {
this.panel.getGameUI().setCancelEnabled(true);
}
if (isConfirmEnabled()) {
this.panel.getGameUI().setConfirmEnabled(true);
}
// custom UI (e.g. activator)
this.onLoadedCustom();
}
/**
* <p>{@inheritDoc}</p>
*
* NOTE: Does not reset the activator Activatable or Activated
*/
@Override
public final void onUnloaded() {
this.panel.getGameUI().clearMessage();
this.panel.getGameUI().getOtherPlayersUI().forEach(ui -> ui.setActivatable(false));
this.panel.getGameUI().getHeroUI().setActivatable(false);
this.targets.forEach(target -> target.setActivated(false));
this.panel.getGameUI().getCardRackUI().getCardUIs().forEach(ui -> ui.setActivatable(false));
this.cards.forEach((card, type) -> card.setActivated(false));
this.panel.getGameUI().getEquipmentRackUI().setUnactivatable(EnumSet.allOf(EquipmentType.class));
this.panel.getGameUI().getEquipmentRackUI().setActivated(EnumSet.allOf(EquipmentType.class), false);
this.panel.getGameUI().setCancelEnabled(false);
this.panel.getGameUI().setConfirmEnabled(false);
this.onUnloadedCustom();
}
/**
* Get the first card UI selected, or null if no card selected
*
* @return the first selected card UI, or null
*/
protected CardUI getFirstCardUI() {
if (this.cards.isEmpty()) {
return null;
}
return this.cards.keySet().iterator().next();
}
/**
* Get the player themselves
*
* @return the player
*/
protected PlayerCompleteClient getSelf() {
return this.panel.getGameState().getSelf();
}
/**
* When maxCards is 0 and a card is clicked, it is assumed that the card clicked
* is the activator. By default, this method calls {@link #onCanceled()}
*
* @param card : card clicked, presumed to be the activator
*/
protected void onCardActivatorClicked(CardUI card) {
// Only the currently selected card should be clickable by implementation
// Behave as if the CANCEL button is pressed
this.onCanceled();
}
/**
* Checks the conditions and return whether the CONFIRM button should be enabled
*
* @return whether CONFIRM button should be enabled
*/
protected abstract boolean isConfirmEnabled();
/**
* Checks the conditions and return whether the CANCEL button should be enabled
*
* @return whether CANCEL button should be enabled
*/
protected abstract boolean isCancelEnabled();
/**
* Checks whether a certain type of equipment can be selected
*
* @param type : An {@link EquipmentType}
* @return whether this type of equipment can be selected
*/
protected abstract boolean isEquipmentTypeActivatable(EquipmentType type);
/**
* Checks whether a card on hand can be selected
*
* @param card : A Card on hand
* @return whether this card can be selected
*/
protected abstract boolean isCardActivatable(Card card);
/**
* Checks whether a player can be a valid target, including oneself
*
* @param player : A player, including oneself
* @return whether this player can be a target
*/
protected abstract boolean isPlayerActivatable(PlayerSimple player);
/**
* Message to be shown to player
*
* @return the message to be shown on the player panel
*/
protected abstract String getMessage();
/**
* <p>Performs additional UI changes on load. For example, if there is an Activator,
* it should be set Activated (and most likely also Activatable)</p>
* {@link #onLoadedCustom()} is called last. If any UI element needs to be refreshed,
* it needs to be refreshed in {@link #onLoadedCustom()}
*/
protected abstract void onLoadedCustom();
/**
* Performs additional UI reset on unload. For example, if there is an Activator,
* it should be set not Activated (and most likely also not Activatable)
*/
protected abstract void onUnloadedCustom();
/**
* Get the command to be sent when CONFIRM is pressed
*
* @return the command to be sent when CONFIRM is pressed
*/
protected abstract InGameServerCommand getCommandOnConfirm();
}
|
package com.company;
import java.util.ArrayList;
import java.util.List;
public class DayCare {
List<Animal> animals = new ArrayList<>();
public void addAnimal(Animal animal) {
animals.add(animal);
}
public void displayAnimals() {
for (Animal animal : animals) {
if (animal instanceof Dog) {
Dog dog = (Dog) animal;
System.out.println(
dog.name + " is a " + dog.size + " " + dog.breed + ", with " + dog.legs + " legs."
);
} else if (animal instanceof Cat) {
Cat cat = (Cat) animal;
System.out.println(
cat.name + " is a " + cat.size + " cat with a " + cat.pattern + " fur pattern with a kill count of " + cat.killCount + "."
);
} else {
System.out.println(
animal.name + " has " + animal.legs + " legs, and weighs " + animal.weight + " lbs."
);
}
animal.speak();
}
}
public void removeAnimal(String name) {
//oneliner removeIf method -> removes all occurances.
animals.removeIf(animal -> animal.name.equals(name));
// for in method - can only remove the first occurance.
// for (Animal animal : animals) {
// if (animal.name.equals(name)) {
// animals.remove(animal);
// return;
// }
// }
// for loop method -> can remove first instance or all instances.
// for (int i = 0; i < animals.size(); i++) {
// if (animals.get(i).name.equals(name)) {
// animals.remove(i--);
// }
// }
}
}
|
package com.rhino.mailParser.data;
import java.util.List;
import org.hibernate.Criteria;
import org.hibernate.Session;
import org.hibernate.criterion.Restrictions;
public class UserDataDAO {
private Session session;
public Session getSession() {
return session;
}
public void setSession(Session session) {
this.session = session;
}
public List<UserData> getByUserID(String userID){
Criteria criteria = session.createCriteria(UserData.class);
criteria.add(Restrictions.ilike("userID", userID));
@SuppressWarnings("unchecked")
List<UserData> result = criteria.list();
return result;
}
public void update(UserData userData){
session.saveOrUpdate(userData);
}
public void save(UserData userData){
session.save(userData);
}
}
|
package hengxiu.courseraPA.w3;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.List;
public class BruteCollinearPoints {
private List<Point> pointList;
private List<LineSegment> segList;
// finds all line segments containing 4 points
public BruteCollinearPoints(Point[] points) {
if (points == null) {
throw new java.lang.NullPointerException();
}
pointList = new ArrayList<>();
segList = new ArrayList<>();
for (Point p : points) {
if (p == null) {
throw new java.lang.NullPointerException();
}
if (pointList.contains(p)) {
throw new java.lang.IllegalArgumentException();
}
pointList.add(p);
}
int n = pointList.size();
for (int i = 0; i < n - 3; i++) {
for (int j = i + 1; j < n - 2; j++) {
for (int k = j + 1; k < n - 1; k++) {
for (int l = k + 1; l < n; l++) {
Point p = pointList.get(i);
Point q = pointList.get(j);
Point s = pointList.get(k);
Point r = pointList.get(l);
if (p.slopeTo(q) == p.slopeTo(s) && p.slopeTo(q) == p.slopeTo(r)) {
ArrayList<Point> tList = new ArrayList<>(Arrays.asList(p, q, s, r));
Collections.sort(tList);
segList.add(new LineSegment(tList.get(0), tList.get(tList.size() - 1)));
}
}
}
}
}
}
// the number of line segments
public int numberOfSegments() {
return segList.size();
}
// the line segments;
public LineSegment[] segments() {
return segList.toArray(new LineSegment[segList.size()]);
}
}
|
package com.examples.io.linkedlists;
public class ReverseLinkedListMtoNPlaces {
public static void main(String[] args) {
Node node = new Node(1);
node.next = new Node(2);
node.next.next = new Node(3);
node.next.next.next = new Node(4);
node.next.next.next.next = new Node(5);
node.printNode(node);
ReverseLinkedListMtoNPlaces reverse = new ReverseLinkedListMtoNPlaces();
Node reverseNode = reverse.reverseMtoNPlaces(node,2,4);
System.out.println();
node.printNode(reverseNode);
}
public Node reverseMtoNPlaces (Node head,int m,int n) {
Node prev = null;
Node current = head;
while (m>1) {
prev = current;
current = current.next;
m--;
n--;
}
//1->2->3->4->5
Node connection = prev; // This will have 1 and will be needed to connect to 4
Node tail = current; // This will have 2 and will be needed to connect to 5.
while(n>0) {
Node next = current.next;
current.next = prev;
prev = current;
current = next;
n--;
}
if(connection!=null) {
connection.next = prev;
} else {
head = prev;
}
tail.next = current;
return head;
}
}
|
package SingleNumber136;
/**
* @author fciasth
* @desc https://leetcode-cn.com/problems/single-number/
* @date 2019/10/26
*/
public class Solution01 {
public int singleNumber(int[] nums) {
int result = nums[0];
for (int i = 1; i < nums.length; i++) {
result = result ^ nums[i];
}
return result;
}
}
|
package com.ferreusveritas.growingtrees.blocks;
import com.ferreusveritas.growingtrees.trees.GrowingTree;
import net.minecraft.block.Block;
import net.minecraft.block.BlockLeaves;
import net.minecraft.entity.player.EntityPlayer;
import net.minecraft.item.ItemStack;
import net.minecraft.world.IBlockAccess;
import net.minecraft.world.World;
import net.minecraftforge.common.util.ForgeDirection;
public class NullTreePart implements ITreePart {
//This is a safe dump for blocks that aren't tree parts
//Handles some vanilla blocks
@Override
public int getHydrationLevel(IBlockAccess blockAccess, int x, int y, int z, ForgeDirection dir, GrowingTree leavesTree) {
return 0;
}
@Override
public GrowSignal growSignal(World world, int x, int y, int z, GrowSignal signal) {
return signal;
}
@Override
public int getRadiusForConnection(IBlockAccess world, int x, int y, int z, BlockBranch from, int fromRadius) {
//Twigs connect to Vanilla leaves
return fromRadius == 1 && from.getTree().getPrimitiveLeaves().matches(world, x, y, z, 3) ? 1 : 0;
}
@Override
public int probabilityForBlock(IBlockAccess blockAccess, int x, int y, int z, BlockBranch from) {
return blockAccess.isAirBlock(x, y, z) ? 1 : 0;
}
@Override
public int getRadius(IBlockAccess blockAccess, int x, int y, int z) {
return 0;
}
@Override
public MapSignal analyse(World world, int x, int y, int z, ForgeDirection fromDir, MapSignal signal) {
return signal;
}
@Override
public boolean isRootNode() {
return false;
}
@Override
public int branchSupport(IBlockAccess blockAccess, BlockBranch branch, int x, int y, int z, ForgeDirection dir, int radius) {
Block block = blockAccess.getBlock(x, y, z);
if(block instanceof BlockLeaves){//Vanilla leaves can be used for support
if(branch.getTree().getPrimitiveLeaves().matches(blockAccess, x, y, z, 3)){
return 0x01;
}
}
return 0;
}
@Override
public boolean applyItemSubstance(World world, int x, int y, int z, EntityPlayer player, ItemStack itemStack){
return false;
}
@Override
public GrowingTree getTree(IBlockAccess blockAccess, int x, int y, int z) {
return null;
}
}
|
package egovframework.usr.svc.controller;
import java.io.File;
import java.util.List;
import java.util.Map;
import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;
import egovframework.adm.common.CommonXSSFilterUtil;
import egovframework.adm.hom.not.service.NoticeAdminService;
import egovframework.adm.stu.service.StuMemberService;
import egovframework.com.cmm.EgovMessageSource;
import egovframework.com.cmm.service.EgovFileMngUtil;
import egovframework.com.cmm.service.EgovProperties;
import egovframework.com.pag.controller.PagingManageController;
@Controller
public class QnaController {
/** log */
protected static final Log log = LogFactory.getLog(QnaController.class);
/** EgovMessageSource */
@Resource(name = "egovMessageSource")
EgovMessageSource egovMessageSource;
/** noticeAdminService */
@Resource(name = "noticeAdminService")
NoticeAdminService noticeAdminService;
/** PagingManageController */
@Resource(name = "pagingManageController")
private PagingManageController pagingManageController;
@Autowired
private StuMemberService stuMemberService;
/**
* 고객센터 > QNA 리스트 - 연수관련상담
* @param request
* @param response
* @param commandMap
* @param model
* @return
* @throws Exception
*/
@RequestMapping(value="/usr/svc/qnaList01.do")
public String selectUserQnaList01(HttpServletRequest request, HttpServletResponse response, Map<String, Object> commandMap, ModelMap model) throws Exception{
//p_tabseq
commandMap.put("p_tabseq", "1");
int totCnt = noticeAdminService.selectQnaListTotCnt(commandMap);
pagingManageController.PagingManage(commandMap, model, totCnt);
// qna list
List list = noticeAdminService.selectQnaList(commandMap);
model.addAttribute("list", list);
// 내문의
if(null != request.getSession().getAttribute("userid") && !"".equals(request.getSession().getAttribute("userid"))) {
commandMap.put("userid", request.getSession().getAttribute("userid"));
int myQnaCnt = stuMemberService.selectMyCursQnaTotCnt(commandMap);
model.addAttribute("myQnaCnt", myQnaCnt);
}
model.addAllAttributes(commandMap);
return "usr/svc/qnaList";
}
/**
* 마이페이지 > 나의 상담내역 (전체)
* @param request
* @param response
* @param commandMap
* @param model
* @return
* @throws Exception
*/
@RequestMapping(value="/usr/mpg/memMyQnaList.do")
public String memMyQnaList(HttpServletRequest request, HttpServletResponse response, Map<String, Object> commandMap, ModelMap model) throws Exception{
//나의 상담내역 전체를 가져오기 위하여 맵에 넣는다.
commandMap.put("p_search", "userid");
commandMap.put("p_searchtext", commandMap.get("userid"));
int totCnt = noticeAdminService.selectQnaListTotCnt(commandMap);
pagingManageController.PagingManage(commandMap, model, totCnt);
// qna list
List list = noticeAdminService.selectQnaList(commandMap);
model.addAttribute("list", list);
model.addAllAttributes(commandMap);
return "usr/mpg/qnaList";
}
/**
* 고객센터 > QNA 리스트 - 환불요청
* @param request
* @param response
* @param commandMap
* @param model
* @return
* @throws Exception
*/
@RequestMapping(value="/usr/svc/qnaList02.do")
public String selectUserQnaList02(HttpServletRequest request, HttpServletResponse response, Map<String, Object> commandMap, ModelMap model) throws Exception{
//p_tabseq
commandMap.put("p_tabseq", "2, 3");
int totCnt = noticeAdminService.selectQnaListTotCnt(commandMap);
pagingManageController.PagingManage(commandMap, model, totCnt);
// qna list
List list = noticeAdminService.selectQnaList(commandMap);
model.addAttribute("list", list);
model.addAllAttributes(commandMap);
return "usr/svc/qnaList";
}
/**
* 고객센터 > QNA 리스트 - 입금확인요청
* @param request
* @param response
* @param commandMap
* @param model
* @return
* @throws Exception
*/
@RequestMapping(value="/usr/svc/qnaList03.do")
public String selectUserQnaList03(HttpServletRequest request, HttpServletResponse response, Map<String, Object> commandMap, ModelMap model) throws Exception{
//p_tabseq
commandMap.put("p_tabseq", "3");
int totCnt = noticeAdminService.selectQnaListTotCnt(commandMap);
pagingManageController.PagingManage(commandMap, model, totCnt);
// qna list
List list = noticeAdminService.selectQnaList(commandMap);
model.addAttribute("list", list);
model.addAllAttributes(commandMap);
return "usr/svc/qnaList";
}
/**
* 고객센터 > QNA 보기 - 연수관련상담
* @param request
* @param response
* @param commandMap
* @param model
* @return
* @throws Exception
*/
@RequestMapping(value="/usr/mpg/memMyQnaView.do")
public String memMyQnaView(HttpServletRequest request, HttpServletResponse response, Map<String, Object> commandMap, ModelMap model) throws Exception{
// qna 정보
model.addAttribute("view", noticeAdminService.selectQnaView(commandMap));
// 조회수 업데이트
noticeAdminService.updateQnaCount(commandMap);
model.addAllAttributes(commandMap);
return "usr/mpg/qnaView";
}
/**
* 마이페이지 > 나의상담내역 보기
* @param request
* @param response
* @param commandMap
* @param model
* @return
* @throws Exception
*/
@RequestMapping(value="/usr/svc/qnaView01.do")
public String selectUserQnaView01(HttpServletRequest request, HttpServletResponse response, Map<String, Object> commandMap, ModelMap model) throws Exception{
HttpSession session = request.getSession();
String p_openChk = (String)commandMap.get("p_openchk");
String userId = (String)session.getAttribute("userid");
String url = "";
if(p_openChk.equals("N")){
url = "forward:/usr/hom/portalActionMainPage.do";
}else{
url = "usr/svc/qnaView";
Map view = noticeAdminService.selectQnaView(commandMap);
// qna 정보
if(userId.equals(view.get("userid"))){
model.addAttribute("view", view);
}else{
model.addAllAttributes(commandMap);
return "forward:/usr/hom/portalActionMainPage.do";
}
// 조회수 업데이트
noticeAdminService.updateQnaCount(commandMap);
}
model.addAllAttributes(commandMap);
return url;
}
/**
* 고객센터 > QNA 보기 - 환불요청
* @param request
* @param response
* @param commandMap
* @param model
* @return
* @throws Exception
*/
@RequestMapping(value="/usr/svc/qnaView02.do")
public String selectUserQnaView02(HttpServletRequest request, HttpServletResponse response, Map<String, Object> commandMap, ModelMap model) throws Exception{
String p_openChk = (String)commandMap.get("p_openchk");
String url = "";
String userId = (String)commandMap.get("userid");
if(p_openChk.equals("N")){
url = "forward:/usr/hom/portalActionMainPage.do";
}else{
url = "usr/svc/qnaView";
// qna 정보
Map view = noticeAdminService.selectQnaView(commandMap);
if(userId.equals(view.get("userid"))){
model.addAttribute("view", view);
}else{
model.addAllAttributes(commandMap);
return "forward:/usr/hom/portalActionMainPage.do";
}
// 조회수 업데이트
noticeAdminService.updateQnaCount(commandMap);
}
model.addAllAttributes(commandMap);
return url;
}
/**
* 고객센터 > QNA 보기 - 입금확인요청
* @param request
* @param response
* @param commandMap
* @param model
* @return
* @throws Exception
*/
@RequestMapping(value="/usr/svc/qnaView03.do")
public String selectUserQnaView03(HttpServletRequest request, HttpServletResponse response, Map<String, Object> commandMap, ModelMap model) throws Exception{
String p_openChk = (String)commandMap.get("p_openchk");
String userId = (String)commandMap.get("userid");
String url = "";
if(p_openChk.equals("N")){
url = "forward:/usr/hom/portalActionMainPage.do";
}else{
url = "usr/svc/qnaView";
// qna 정보
Map view = noticeAdminService.selectQnaView(commandMap);
if(userId.equals(view.get("userid"))){
model.addAttribute("view", view);
}else{
model.addAllAttributes(commandMap);
return "forward:/usr/hom/portalActionMainPage.do";
}
// 조회수 업데이트
noticeAdminService.updateQnaCount(commandMap);
}
model.addAllAttributes(commandMap);
return url;
}
/**
* 고객센터 > QNA 등록/수정 - 연수관련상담
* @param request
* @param response
* @param commandMap
* @param model
* @return
* @throws Exception
*/
@RequestMapping(value="/usr/svc/qnaEdit01.do")
public String selectUserQnaEdit01(HttpServletRequest request, HttpServletResponse response, Map<String, Object> commandMap, ModelMap model) throws Exception{
HttpSession session = request.getSession();
String userId = (String)session.getAttribute("userid");
System.out.println("userId 11111 ====> "+ userId);
if(commandMap.get("p_seq") != null && !commandMap.get("p_seq").equals("")){
//qna 정보
Map view = noticeAdminService.selectQnaView(commandMap);
System.out.println("userId 2222 ====> "+ view.get("userid"));
if(view != null){
if(userId.equals(view.get("userid"))){
model.addAttribute("view", view);
}else{
model.addAllAttributes(commandMap);
return "forward:/usr/hom/portalActionMainPage.do";
}
}
model.addAttribute("view", view);
}
model.addAllAttributes(commandMap);
return "usr/svc/qnaEdit";
}
/**
* 고객센터 > QNA 등록/수정 - 환불요청
* @param request
* @param response
* @param commandMap
* @param model
* @return
* @throws Exception
*/
@RequestMapping(value="/usr/svc/qnaEdit02.do")
public String selectUserQnaEdit02(HttpServletRequest request, HttpServletResponse response, Map<String, Object> commandMap, ModelMap model) throws Exception{
// qna 정보
model.addAttribute("view", noticeAdminService.selectQnaView(commandMap));
model.addAllAttributes(commandMap);
return "usr/svc/qnaEdit";
}
/**
* 고객센터 > QNA 등록/수정 - 입금확인요청
* @param request
* @param response
* @param commandMap
* @param model
* @return
* @throws Exception
*/
@RequestMapping(value="/usr/svc/qnaEdit03.do")
public String selectUserQnaEdit03(HttpServletRequest request, HttpServletResponse response, Map<String, Object> commandMap, ModelMap model) throws Exception{
// qna 정보
model.addAttribute("view", noticeAdminService.selectQnaView(commandMap));
model.addAllAttributes(commandMap);
return "usr/svc/qnaEdit";
}
/**
* 고객센터 > QNA 등록/수정/삭제 작업
* @param request
* @param response
* @param commandMap
* @param model
* @return
* @throws Exception
*/
@RequestMapping(value="/usr/svc/qnaAction.do", method = RequestMethod.POST)
public String selectUserQnaAction(HttpServletRequest request, HttpServletResponse response, Map<String, Object> commandMap, ModelMap model) throws Exception{
HttpSession session = request.getSession();
String resultMsg = "";
String p_tabseq = (String)commandMap.get("p_tabseq");
String p_process = (String)commandMap.get("p_process");
String p_content = "";
String xssContent = "";
String userId = (String)session.getAttribute("userid");
if(userId == null){
return "forward:/usr/hom/portalActionMainPage.do";
}
String url = "/usr/svc/qnaList0" + p_tabseq + ".do";
log.info("url : " + url);
log.info("p_content : " + (String)commandMap.get("p_content"));
boolean isok = false;
//업로드 처리를 한다.
commandMap.putAll(this.uploadFiles(request, commandMap));
if(p_process.equalsIgnoreCase("insert"))
{
p_content = (String)commandMap.get("p_content");
xssContent = CommonXSSFilterUtil.removeXSS(p_content, true);
commandMap.put("p_content", xssContent);
//스팸확인
int spamCnt = noticeAdminService.selectQnaSpamCnt(commandMap);
if(spamCnt > 0){
return "forward:/usr/hom/portalActionMainPage.do";
}
Object o = noticeAdminService.insertQna(commandMap);
if(o != null) isok = true;
}
else{
//qna 정보
Map view = noticeAdminService.selectQnaView(commandMap);
//본인확인
if(userId.equals(view.get("userid"))){
if(p_process.equalsIgnoreCase("update")) {
p_content = (String)commandMap.get("p_content");
xssContent = CommonXSSFilterUtil.removeXSS(p_content, true);
commandMap.put("p_content", xssContent);
//updateQna가 아닌 updateQnaUser 사용자용 업데이트 문...실행
isok = noticeAdminService.updateQnaUser(commandMap);
}
else if(p_process.equalsIgnoreCase("delete"))
{
isok = noticeAdminService.deleteQna(commandMap);
//글의 값을 삭제하여 리스트로 보낸다.
commandMap.remove("p_seq");
}
}else{
model.addAllAttributes(commandMap);
return "forward:/usr/hom/portalActionMainPage.do";
}
}
if(isok)
resultMsg = egovMessageSource.getMessage("success.common." + p_process);
else
resultMsg = egovMessageSource.getMessage("fail.common." + p_process);
model.addAttribute("resultMsg", resultMsg);
model.addAllAttributes(commandMap);
return "forward:" + url;
}
/**
* 업로드된 파일을 등록한다.
*
* @param contentPath 컨텐츠 경로
* @param contentCode 컨텐츠 코드
* @return Directory 생성 여부
* @throws Exception
*/
public Map<String, Object> uploadFiles(HttpServletRequest request, Map<String, Object> commandMap) throws Exception {
//기본 업로드 폴더
String defaultDP = EgovProperties.getProperty("Globals.defaultDP");
log.info("- 기본 업로드 폴더 : " + defaultDP);
//파일업로드를 실행한다.
MultipartHttpServletRequest mptRequest = (MultipartHttpServletRequest)request;
java.util.Iterator<?> fileIter = mptRequest.getFileNames();
while (fileIter.hasNext()) {
MultipartFile mFile = mptRequest.getFile((String)fileIter.next());
String orginFileName = mFile.getOriginalFilename();
int index = orginFileName.lastIndexOf(".");
//String fileName = orginFileName.substring(0, _index);
String fileExt = orginFileName.substring(index + 1);
log.info("fileExt 0000 ---> "+fileExt);
fileExt = fileExt.toLowerCase();
log.info("fileExt 1111 ---> "+fileExt);
if(fileExt.equals("gif") ||
fileExt.equals("png") ||
fileExt.equals("jpg") ||
fileExt.equals("jpeg") ||
fileExt.equals("hwp") ||
fileExt.equals("doc") ||
fileExt.equals("docx") ||
fileExt.equals("ppt") ||
fileExt.equals("ppt") ||
fileExt.equals("pptx") ||
fileExt.equals("pps") ||
fileExt.equals("ppsx") ||
fileExt.equals("xls") ||
fileExt.equals("xlsx") ||
fileExt.equals("pdf") ||
fileExt.equals("zip")){
log.info("fileExt 222 ---> "+fileExt);
if (mFile.getSize() > 0) {
commandMap.putAll( EgovFileMngUtil.uploadContentFile(mFile, defaultDP + File.separator + "bulletin") );
}
}else{
log.info("fileExt not upload ---> "+fileExt);
}
}
return commandMap;
}
}
|
package com.turios.settings.modules;
import javax.inject.Inject;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.content.SharedPreferences.OnSharedPreferenceChangeListener;
import android.os.Bundle;
import android.preference.CheckBoxPreference;
import android.preference.PreferenceManager;
import android.preference.SwitchPreference;
import com.dropbox.sync.android.DbxAccountManager;
import com.turios.R;
import com.turios.activities.setup.SetupDropbox;
import com.turios.dagger.DaggerPreferenceFragment;
import com.turios.dagger.quialifiers.ForActivity;
import com.turios.modules.extend.DropboxModule;
import com.turios.settings.modules.status.StatusCheck;
import com.turios.util.Constants;
public class DropboxSettings extends DaggerPreferenceFragment implements
OnSharedPreferenceChangeListener {
private static final String TAG = "DropboxSettings";
private StatusCheck statusCheck;
@Inject @ForActivity Context context;
@Inject DropboxModule dropboxModule;
@Override public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
// Load the preferences from an XML resource
addPreferencesFromResource(R.xml.settings_module_dropbox);
}
@Override public void onStart() {
if (!dropboxModule.isActivated()) {
((SwitchPreference) getPreferenceScreen().findPreference(
getString(R.string.key_dropbox_link_unlink)))
.setEnabled(false);
((CheckBoxPreference) getPreferenceScreen().findPreference(
getString(R.string.key_dropbox_daily_sync)))
.setEnabled(false);
}
statusCheck = new StatusCheck(context, dropboxModule, this);
statusCheck.runCheck();
super.onStart();
}
@Override public void onResume() {
PreferenceManager.getDefaultSharedPreferences(context)
.registerOnSharedPreferenceChangeListener(this);
super.onResume();
}
@Override public void onPause() {
PreferenceManager.getDefaultSharedPreferences(context)
.unregisterOnSharedPreferenceChangeListener(this);
super.onPause();
}
@Override public void onSharedPreferenceChanged(SharedPreferences prefs,
String key) {
if (key.equals(getString(R.string.key_module_activated_dropbox))) {
statusCheck.runCheck();
}
if (key.equals(getString(R.string.key_dropbox_link_unlink))) {
boolean value = prefs.getBoolean(key, true);
if (value == false) {
DbxAccountManager mDbxAcctMgr = DbxAccountManager.getInstance(
context.getApplicationContext(),
Constants.DROPBOX_APPKEY, Constants.DROPBOX_SECRETKEY);
mDbxAcctMgr.unlink();
} else {
Intent intent = new Intent(context, SetupDropbox.class);
intent.putExtra("settings", true);
startActivity(intent);
}
}
}
}
|
package com.flores.easycurrencyconverter.widget;
import android.app.PendingIntent;
import android.appwidget.AppWidgetManager;
import android.appwidget.AppWidgetProvider;
import android.content.Context;
import android.content.Intent;
import android.util.Log;
import android.widget.RemoteViews;
import com.flores.easycurrencyconverter.MainActivity;
import com.flores.easycurrencyconverter.R;
/**
* Implementation of App Widget functionality.
*/
public class CurrencyAppWidget extends AppWidgetProvider {
private static final String LOG_TAG = CurrencyAppWidget.class.getSimpleName();
private static void updateAppWidget(Context context, AppWidgetManager appWidgetManager, int appWidgetId) {
Log.d(LOG_TAG, "updateAppWidget");
// Construct the RemoteViews object
RemoteViews views = new RemoteViews(context.getPackageName(), R.layout.currency_app_widget);
// Set the GridWidgetService intent to act as the adapter for the GridView
Intent intent = new Intent(context, ListWidgetService.class);
views.setRemoteAdapter(R.id.lv_widget, intent);
Intent appIntent = new Intent(context, MainActivity.class);
PendingIntent appPendingIntent = PendingIntent.getActivity(context, 0, appIntent, 0);
views.setOnClickPendingIntent(R.id.view_widget, appPendingIntent);
Intent startActivityIntent = new Intent(context, MainActivity.class);
PendingIntent startActivityPendingIntent = PendingIntent.getActivity(context, 0, startActivityIntent, PendingIntent.FLAG_UPDATE_CURRENT);
views.setPendingIntentTemplate(R.id.lv_widget, startActivityPendingIntent);
// Handle empty list
views.setEmptyView(R.id.lv_widget, R.id.empty_view);
// Instruct the widget manager to update the widget
appWidgetManager.updateAppWidget(appWidgetId, views);
}
public static void updateWidgets(Context context, AppWidgetManager appWidgetManager, int[] appWidgetIds) {
for (int appWidgetId : appWidgetIds) {
updateAppWidget(context, appWidgetManager, appWidgetId);
}
}
@Override
public void onUpdate(Context context, AppWidgetManager appWidgetManager, int[] appWidgetIds) {
RatesService.startActionUpdateWidgets(context);
}
@Override
public void onEnabled(Context context) {
// Enter relevant functionality for when the first widget is created
}
@Override
public void onDisabled(Context context) {
// Enter relevant functionality for when the last widget is disabled
}
}
|
package dev.bltucker.conway.rules;
import dev.bltucker.conway.cells.Cell;
public interface CellCondition {
public boolean checkCell(Cell cell);
}
|
package sampleproject.remote;
import java.rmi.Remote;
import sampleproject.db.DBClient;
/**
* The remote interface for the GUI-Client.
* Exactly matches the DBClient interface in the db package.
*
* @author Denny's DVDs
* @version 2.0
*/
public interface DvdDatabaseRemote extends Remote, DBClient {
}
|
/*
*
* * Copyright 2020. Huawei Technologies Co., Ltd. All rights reserved.
* *
* * Licensed under the Apache License, Version 2.0 (the "License");
* * you may not use this file except in compliance with the License.
* * You may obtain a copy of the License at
* *
* * http://www.apache.org/licenses/LICENSE-2.0
* *
* * Unless required by applicable law or agreed to in writing, software
* * distributed under the License is distributed on an "AS IS" BASIS,
* * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* * See the License for the specific language governing permissions and
* * limitations under the License.
*
*/
package com.huawei.myhealth.java.ui.fragments;
import android.content.Context;
import android.content.SharedPreferences;
import android.os.Bundle;
import androidx.appcompat.app.AppCompatActivity;
import androidx.fragment.app.Fragment;
import androidx.navigation.NavActionBuilder;
import androidx.navigation.NavOptionsBuilder;
import androidx.navigation.Navigation;
import androidx.navigation.fragment.NavHostFragment;
import android.os.Handler;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import com.huawei.myhealth.R;
import com.huawei.myhealth.java.utils.DefaultValues;
/**
* @since 2020
* @author Huawei DTSE India
*/
public class SplashScreenFragment extends Fragment {
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
}
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
View view = inflater.inflate(R.layout.fragment_splash_screen, container, false);
// To Show / Hide Action Bar
AppCompatActivity activity = (AppCompatActivity) getActivity();
if (activity != null) {
activity.getSupportActionBar().hide();
}
// check for screen navigation
checkForNavigation(view);
return view;
}
//Method to check for screen navigation
private void checkForNavigation(View view) {
final Handler handler = new Handler();
handler.postDelayed(new Runnable() {
@Override
public void run() {
SharedPreferences sharedPreference = getActivity().getSharedPreferences(getResources().getString(R.string.APP), Context.MODE_PRIVATE);
String mobileno = sharedPreference.getString(getResources().getString(R.string.mobilenum), "");
String name = sharedPreference.getString(getResources().getString(R.string.name), "");
if (mobileno.equals("")) {
Navigation.findNavController(view).navigate(R.id.loginFragmentDest, null);
} else if (name.equals("")) {
NavHostFragment.findNavController(getParentFragment()).navigate(R.id.completeProfileFragmentDest);
} else {
NavHostFragment.findNavController(getParentFragment()).navigate(R.id.homeScreenDest);
}
}
}, DefaultValues.SPLASH_TIME_OUT);
}
}
|
/*
* *
* * Created by Amit kremer ID 302863253 on 12/12/19 1:53 PM
* * Copyright (c) 2019 . All rights reserved.
* * Last modified 12/12/19 1:53 PM
*
*/
package com.example.hw1;
import android.content.Context;
import android.media.MediaPlayer;
public class MyMediaPlayer {
private MediaPlayer mPlayer;
private boolean replay = false;
private Context context;
private int[] sounds = {R.raw.vintageparty, R.raw.meme, R.raw.coin, R.raw.impact};
public MyMediaPlayer(Context context, int song) {
this.context = context;
mPlayer = MediaPlayer.create(context, sounds[song]);
if (song == 0) {
replay = true;
}
}
public void start() {
mPlayer.start();
mPlayer.setOnCompletionListener(new MediaPlayer.OnCompletionListener() {
@Override
public void onCompletion(MediaPlayer mp) {
if (replay) {
start();
} else {
mPlayer.release();
}
}
});
}
public void pause() {
if (mPlayer != null) {
mPlayer.pause();
}
}
public void releasePlayer() {
if (mPlayer != null) {
mPlayer.release();
mPlayer = null;
}
}
public void switchSounds(int song){
if(mPlayer != null) {
mPlayer.release();
mPlayer = MediaPlayer.create(context, sounds[song]);
mPlayer.start();
}
}
}
|
package com.isban.javaapps.reporting.service;
import java.sql.ResultSet;
import java.sql.ResultSetMetaData;
import java.sql.SQLException;
import java.util.LinkedList;
import java.util.List;
import javax.persistence.EntityManager;
import javax.persistence.ParameterMode;
import javax.persistence.StoredProcedureQuery;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;
import com.fasterxml.jackson.databind.node.JsonNodeFactory;
import com.fasterxml.jackson.databind.node.ObjectNode;
import com.isban.javaapps.reporting.dto.TableDTO;
import com.isban.javaapps.reporting.pagination.PageResponse;
@Transactional
public abstract class BaseService<T> {
@Autowired
protected EntityManager entityManager;
final JsonNodeFactory factory = JsonNodeFactory.instance;
private String codigoPais = "54";
@Transactional(propagation=Propagation.REQUIRES_NEW)
public PageResponse<ObjectNode> get(String filtro, Integer page, Integer pageSize, String codigoTabla) {
pageSize = pageSize == null ? 10 : pageSize;
page = page == null ? 1 : page;
filtro = filtro == null ? "" : filtro;
StoredProcedureQuery query = this.getRecuperaTablaMtoPart(filtro, codigoTabla, pageSize, page);
boolean isResult = query.execute();
Long pages = Long.parseLong(query.getOutputParameterValue(11).toString());
List<ObjectNode> rowList = new LinkedList<ObjectNode>();
if(isResult) {
ResultSet rs = (ResultSet) query.getOutputParameterValue(2);
try {
while (rs.next())
{
ObjectNode resultJson = this.createDTO(rs);
rowList.add(resultJson);
}
} catch (SQLException e) {
e.printStackTrace();
}
}
entityManager.close();
return new PageResponse<ObjectNode>(rowList, new Integer(page), new Integer(pageSize), pages * pageSize);
}
protected abstract ObjectNode createDTO(ResultSet rs);
@Transactional(propagation=Propagation.REQUIRES_NEW)
protected TableDTO getDataToExcel(String filtro, String codigoTabla) {
List<String> header = new LinkedList<String>();
List<String> fields = new LinkedList<String>();
List<Object[]> elements = new LinkedList<Object[]>();
Integer pageSize = 1048576;
Integer page = 1;
filtro = filtro == null ? "" : filtro;
StoredProcedureQuery query = this.getRecuperaTablaMtoPart(filtro, codigoTabla, pageSize, page);
boolean isResult = query.execute();
ResultSet rs = null;
if(isResult) {
try {
rs = (ResultSet) query.getOutputParameterValue(2);
ResultSetMetaData rsMetaData = rs.getMetaData();
int numberOfColumns = rsMetaData.getColumnCount();
for (int i = 1; i < numberOfColumns + 1; i++) {
String columnName = rsMetaData.getColumnName(i);
header.add(columnName);
fields.add(String.valueOf(i - 1));
}
while (rs.next())
{
Object[] result = new Object[numberOfColumns];
for (int i = 1; i < numberOfColumns + 1; i++) {
result[i - 1] = rs.getObject(header.get(i - 1));
}
elements.add(result);
}
} catch (SQLException e) {
e.printStackTrace();
}
}
entityManager.close();
return new TableDTO(header, elements, fields);
}
private StoredProcedureQuery getRecuperaTablaMtoPart(String filtro, String codigoTabla, Integer pageSize, Integer page) {
StoredProcedureQuery query = entityManager
.createStoredProcedureQuery("PKG_ODS_SERVICIOS_MTO_MP.Recupera_TablaMto_Part")
.registerStoredProcedureParameter(1, String.class,
ParameterMode.IN)
.registerStoredProcedureParameter(2, void.class, ParameterMode.REF_CURSOR)
.registerStoredProcedureParameter(3, Long.class, ParameterMode.OUT)
.registerStoredProcedureParameter(4, String.class, ParameterMode.OUT)
.registerStoredProcedureParameter(5, Long.class, ParameterMode.OUT)
.registerStoredProcedureParameter(6, String.class, ParameterMode.IN)
.registerStoredProcedureParameter(7, String.class, ParameterMode.IN)
.registerStoredProcedureParameter(8, String.class, ParameterMode.IN)
.registerStoredProcedureParameter(9, String.class, ParameterMode.IN)
.registerStoredProcedureParameter(10, String.class, ParameterMode.IN)
.registerStoredProcedureParameter(11, String.class, ParameterMode.OUT)
.registerStoredProcedureParameter(12, String.class, ParameterMode.IN)
.registerStoredProcedureParameter(13, String.class, ParameterMode.IN)
.registerStoredProcedureParameter(14, String.class, ParameterMode.IN)
.registerStoredProcedureParameter(15, String.class, ParameterMode.IN)
.setParameter(1, "")
.setParameter(6, "")
.setParameter(7, page.toString())
.setParameter(8, pageSize.toString())
.setParameter(9, codigoTabla)
.setParameter(10, filtro)
.setParameter(12, "")
.setParameter(13, "")
.setParameter(14, codigoPais)
.setParameter(15, "");
return query;
}
}
|
/**
* Copyright 2017 伊永飞
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.yea.core.shiro.model;
import com.yea.core.base.model.BaseModel;
public class UserPrincipal extends BaseModel{
private static final long serialVersionUID = 1L;
private Long partyId;
private String loginName;
private String personName;
private String isLock;
public Long getPartyId() {
return partyId;
}
public void setPartyId(Long partyId) {
this.partyId = partyId;
}
public String getLoginName() {
return loginName;
}
public void setLoginName(String loginName) {
this.loginName = loginName;
}
public String getPersonName() {
return personName;
}
public void setPersonName(String personName) {
this.personName = personName;
}
public String getIsLock() {
return isLock;
}
public void setIsLock(String isLock) {
this.isLock = isLock;
}
}
|
package com.atakan.app.dao;
import java.util.List;
import java.util.Optional;
import javax.persistence.EntityManager;
import javax.persistence.Query;
import javax.transaction.Transactional;
import org.hibernate.Session;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.data.domain.Example;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
import org.springframework.data.domain.Sort;
import org.springframework.stereotype.Repository;
import com.atakan.app.auth.model.User;
@Repository
@Qualifier("userRepoImpl")
public class UserRepositoryImpl implements UserRepository{
@Autowired
private EntityManager entityManager;
@Override
public void saveUser(User user) {
Session session = entityManager.unwrap(Session.class);
System.out.println(user.toString());
session.save(user);
}
@Override
public <S extends User> S save(S entity) {
// TODO Auto-generated method stub
return null;
}
@Override
public <S extends User> Iterable<S> saveAll(Iterable<S> entities) {
// TODO Auto-generated method stub
return null;
}
@Override
public Optional<User> findById(String id) {
// TODO Auto-generated method stub
return null;
}
@Override
public boolean existsById(String id) {
// TODO Auto-generated method stub
return false;
}
@Override
public Iterable<User> findAll() {
// TODO Auto-generated method stub
return null;
}
@Override
public Iterable<User> findAllById(Iterable<String> ids) {
// TODO Auto-generated method stub
return null;
}
@Override
public long count() {
// TODO Auto-generated method stub
return 0;
}
@Override
public void deleteById(String id) {
// TODO Auto-generated method stub
}
@Override
public void delete(User entity) {
// TODO Auto-generated method stub
}
@Override
public void deleteAll(Iterable<? extends User> entities) {
// TODO Auto-generated method stub
}
@Override
public void deleteAll() {
// TODO Auto-generated method stub
}
@Override
public User verifyLogin(String username, String password) {
Session session = entityManager.unwrap(Session.class);
String verifyUserQuery = "from User where username=:username and password=:password";
Query query = session.createQuery(verifyUserQuery);
query.setParameter("username", username);
query.setParameter("password", password);
User user = new User();
if(query.getResultList().size() > 0)
user = (User) query.getResultList().get(0);
else {
user = null;
}
return user;
}
@Override
public boolean isUserExist(String username) {
Session session = entityManager.unwrap(Session.class);
String isUserExistQuery = "from User where username=:username";
Query query = session.createQuery(isUserExistQuery);
query.setParameter("username", username);
return query.getResultList().size() > 0 ? true : false;
}
}
|
package gov.noaa.eds.byExample.trySimpleVfsSftp;
import java.io.IOException;
/**
*/
public class SftpUtilsTest {
/**
* Method main.
* @param args String[]
*/
public static void main(String[] args) {
try {
new SftpUtilsTest().uploadTest();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
/**
* Method uploadTest.
* @throws IOException
* @throws Exception
*/
public void uploadTest() throws IOException, Exception {
String hostName = "192.168.111.128";
String userName = "robert";
String password = "robert";
String localFilePath = "d:/tmp";
String remoteFilePath = "Desktop";
//SftpUtils.upload(hostName, userame, password, localFilePath, remoteFilePath);
// SftpUtils.uploadV2(hostName, userName, password, localFilePath, "guipythonqt.zip", remoteFilePath);
SftpUtils.downloadV1(hostName, userName, password, localFilePath, remoteFilePath);
System.out.println("exit............");
}
}
|
package tech.liujin.drawable.progress.decoration;
import android.graphics.Canvas;
import android.graphics.Paint.Style;
import android.graphics.Path;
import android.graphics.Path.Direction;
import android.graphics.PathMeasure;
import android.graphics.Rect;
import android.graphics.RectF;
import android.support.annotation.IntDef;
import android.support.annotation.NonNull;
import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
import tech.liujin.drawable.progress.ProgressDrawable;
/**
* 根据时间进度绘制圆角矩形,一般作为倒计时背景
*
* @author: Liujin
* @version: V1.0
* @date: 2018-07-23
* @time: 10:57
*/
public class RoundRectPathDrawable extends ProgressDrawable {
public static final int CLOCKWISE_ADD = 0;
public static final int COUNTER_CLOCKWISE_ADD = 1;
public static final int CLOCKWISE_SUB = 2;
public static final int COUNTER_CLOCKWISE_SUB = 3;
private float mStrokeWidth = 10;
private Path mDst;
private PathMeasure mPathMeasure;
private int mMode;
private float mTotalLength;
public RoundRectPathDrawable ( ) {
mPaint.setStyle( Style.STROKE );
mPaint.setStrokeWidth( mStrokeWidth );
mPathMeasure = new PathMeasure();
mDst = new Path();
}
public void setStrokeWidth ( float strokeWidth ) {
mStrokeWidth = strokeWidth;
}
public float getStrokeWidth ( ) {
return mStrokeWidth;
}
@Override
protected void onBoundsChange ( Rect bounds ) {
Path src = new Path();
RectF rectF = new RectF();
rectF.set(
0 + mStrokeWidth / 2,
0 + mStrokeWidth / 2,
bounds.width() - mStrokeWidth / 2,
bounds.height() - mStrokeWidth / 2
);
src.addRoundRect(
rectF,
Integer.MAX_VALUE >> 1,
Integer.MAX_VALUE >> 1,
Direction.CW
);
mPathMeasure.setPath( src, true );
mTotalLength = mPathMeasure.getLength();
super.onBoundsChange( bounds );
}
@Override
public void draw ( @NonNull Canvas canvas ) {
canvas.drawPath( mDst, mPaint );
}
@Override
public void onProcessChange ( float progress ) {
mProgress = progress;
float start = 0;
float end = 0;
if( mMode == CLOCKWISE_SUB ) {
start = mTotalLength * mProgress;
end = mTotalLength;
} else if( mMode == COUNTER_CLOCKWISE_ADD ) {
start = mTotalLength * ( 1 - mProgress );
end = mTotalLength;
} else if( mMode == COUNTER_CLOCKWISE_SUB ) {
start = 0;
end = mTotalLength * ( 1 - mProgress );
} else {
start = 0;
end = mTotalLength * mProgress;
}
mDst.reset();
mPathMeasure.getSegment( start, end, mDst, true );
invalidateSelf();
}
public void setMode ( @Mode int mode ) {
mMode = mode;
}
@IntDef(value = { CLOCKWISE_ADD,
CLOCKWISE_SUB,
COUNTER_CLOCKWISE_ADD,
COUNTER_CLOCKWISE_SUB })
@Target(ElementType.PARAMETER)
@Retention(RetentionPolicy.SOURCE)
@interface Mode { }
}
|
package Belorusets.Inheritance;
public class QAEngineer extends Employee{
private double bonus;
QAEngineer(String sName, double dSalary, String sCompany, double dBonus)
{
super(sName, dSalary, sCompany);
bonus = dBonus;
}
public double getBonus() {
return bonus;
}
}
|
package com.crunchshop.exception;
import graphql.ExceptionWhileDataFetching;
import graphql.execution.ExecutionPath;
import graphql.language.SourceLocation;
public class CustomExceptionWhileDataFetching extends ExceptionWhileDataFetching {
private final String customMessage;
public CustomExceptionWhileDataFetching(ExecutionPath path, Throwable exception, SourceLocation sourceLocation) {
super(path, exception, sourceLocation);
this.customMessage = exception.getMessage();
}
@Override
public String getMessage() {
/* Override the original error message */
return customMessage;
}
}
|
/*
* Dryuf framework
*
* ----------------------------------------------------------------------------------
*
* Copyright (C) 2000-2015 Zbyněk Vyškovský
*
* ----------------------------------------------------------------------------------
*
* LICENSE:
*
* This file is part of Dryuf
*
* Dryuf is free software; you can redistribute it and/or modify it under the
* terms of the GNU Lesser General Public License as published by the Free
* Software Foundation; either version 3 of the License, or (at your option)
* any later version.
*
* Dryuf is distributed in the hope that it will be useful, but WITHOUT ANY
* WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
* FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for
* more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with Dryuf; if not, write to the Free Software Foundation, Inc., 51
* Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
*
* @author 2000-2015 Zbyněk Vyškovský
* @link mailto:kvr@matfyz.cz
* @link http://kvr.matfyz.cz/software/java/dryuf/
* @link http://github.com/dryuf/
* @license http://www.gnu.org/licenses/lgpl.txt GNU Lesser General Public License v3
*/
package net.dryuf.comp.gallery.mvp;
import net.dryuf.comp.gallery.GalleryHandler;
import net.dryuf.comp.gallery.GallerySection;
import net.dryuf.core.Options;
import net.dryuf.mvp.Presenter;
public class GalleryPresenter extends net.dryuf.mvp.ChildPresenter
{
public static final int MODE_GALLERY = 0;
public static final int MODE_GALLERYSECTION = 1;
public static final int MODE_SECTION = 2;
public static final int MODE_IMAGE = 3;
public GalleryPresenter(Presenter parentPresenter, Options options, GalleryHandler galleryHandler)
{
super(parentPresenter, options);
if ((this.galleryHandler = galleryHandler) == null)
throw new NullPointerException("galleryHandler");
this.baseUrl = options.getOptionDefault("baseUrl", "");
}
public boolean process()
{
this.galleryHandler.read();
if (!this.galleryHandler.isMulti()) {
String section = "";
if (this.galleryHandler.setCurrentSectionIdx(0) == null)
throw new RuntimeException("unable to set default section");
return new GallerySectionPresenter(this, net.dryuf.core.Options.NONE, section).process();
}
else {
return super.process();
}
}
public boolean processMore(String element)
{
rootPresenter = this.getRootPresenter();
if (galleryHandler.supportsResource(element) != 0) {
if (rootPresenter.needPathSlash(false) == null)
return true;
return new GalleryResourcePresenter(this, Options.NONE).process();
}
if (rootPresenter.needPathSlash(true) == null)
return false;
if (this.galleryHandler.setCurrentSection(element) == null) {
return this.createNotFoundPresenter().process();
}
else {
return new GallerySectionPresenter(this, net.dryuf.core.Options.NONE, element).process();
}
}
public int getMode()
{
if (this.galleryHandler.getCurrentRecord() != null)
return MODE_IMAGE;
else if (!this.galleryHandler.isMulti())
return MODE_GALLERYSECTION;
else if (this.galleryHandler.getCurrentSection() != null)
return MODE_SECTION;
else
return MODE_GALLERY;
}
public void injectRenderReference(Runnable callback)
{
this.renderReference = callback;
}
public void render()
{
if (renderLeadChild())
return;
this.output("<a name=\"gallery/\"></a><table class=\"net-dryuf-comp-gallery-GalleryPresenter\" width=\"100%\">");
this.outputFormat("<tr class=\"reference\"><td colspan='2'>");
if (this.renderReference != null)
this.renderReference.run();
this.outputFormat("</td></tr>");
for (GallerySection section: this.galleryHandler.listSections()) {
this.outputFormat("<tr class=\"section\"><td><a href=%A>%S</a></td><td>%S</td></tr>", section.getDisplayName()+"/#gallery", section.getTitle(), section.getDescription());
}
this.output("</table>\n");
}
public GalleryHandler getGalleryHandler()
{
return this.galleryHandler;
}
protected GalleryHandler galleryHandler;
public Runnable getRenderReference()
{
return this.renderReference;
}
protected Runnable renderReference = null;
public String getBaseUrl()
{
return this.baseUrl;
}
protected String baseUrl;
}
|
package com.tac.kulik.waveaudiovizualization;
import android.animation.AnimatorSet;
import android.animation.ObjectAnimator;
import android.content.Context;
import android.content.res.TypedArray;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Paint;
import android.util.AttributeSet;
import android.util.Log;
import android.view.View;
import com.tac.kulik.waveaudiovizualization.util.ScreenUtils;
/**
* Created by kulik on 01.02.17.
*/
public class VoiceView extends View {
private static final String TAG = VoiceView.class.getName();
private Paint mPaint;
private AnimatorSet mAnimatorSet = new AnimatorSet();
private float mMinRadius;
private float mMaxRadius;
private float mCurrentRadius;
private int mColor;
private float mScale;
public VoiceView(Context context) {
super(context);
init();
}
public VoiceView(Context context, AttributeSet attrs) {
super(context, attrs);
TypedArray attr = context.obtainStyledAttributes(attrs, R.styleable.VoiceView);
mColor = attr.getColor(R.styleable.VoiceView_color, Color.argb(128, 219, 219, 219));
mScale = attr.getFloat(R.styleable.VoiceView_scale, 1f);
attr.recycle();
init();
}
private void init() {
mPaint = new Paint();
mPaint.setAntiAlias(true);
mPaint.setColor(mColor);
mMinRadius = ScreenUtils.dp2px(getContext(), 50) / 2;
mCurrentRadius = mMinRadius;
}
@Override
protected void onSizeChanged(int w, int h, int oldw, int oldh) {
super.onSizeChanged(w, h, oldw, oldh);
mMaxRadius = Math.min(w, h) / 2;
Log.d(TAG, "MaxRadius: " + mMaxRadius);
}
@Override
protected void onDraw(Canvas canvas) {
super.onDraw(canvas);
int width = canvas.getWidth();
int height = canvas.getHeight();
if (mCurrentRadius > mMinRadius) {
canvas.drawCircle(width / 2, height / 2, mCurrentRadius * mScale, mPaint);
}
}
public void animateRadius(float radius) {
if (radius <= mCurrentRadius) {
return;
}
if (radius > mMaxRadius) {
radius = mMaxRadius;
} else if (radius < mMinRadius) {
radius = mMinRadius;
}
if (radius == mCurrentRadius) {
return;
}
if (mAnimatorSet.isRunning()) {
mAnimatorSet.cancel();
}
mAnimatorSet.playSequentially(
ObjectAnimator.ofFloat(this, "CurrentRadius", getCurrentRadius(), radius).setDuration(50),
ObjectAnimator.ofFloat(this, "CurrentRadius", radius, mMinRadius).setDuration(600)
);
mAnimatorSet.start();
}
public float getCurrentRadius() {
return mCurrentRadius;
}
public void setCurrentRadius(float currentRadius) {
mCurrentRadius = currentRadius;
invalidate();
}
}
|
package com.driva.drivaapi.mapper.dto;
import com.driva.drivaapi.model.product.Product;
import lombok.Getter;
import lombok.NoArgsConstructor;
import lombok.Setter;
import javax.validation.constraints.NotNull;
import javax.validation.constraints.Positive;
@Getter
@Setter
@NoArgsConstructor
public class ProductDTO {
private Long id;
private Long studentId;
private String studentFullName;
private Integer hoursLeft;
private Boolean bookOnline;
private Boolean isPaid;
private Double price;
@NotNull(message = "product type id can't be null")
@Positive(message = "product type must be positive digit")
private Long productTypeId;
private String productTypeName;
private String productTypeDescription;
private String productTypeCategory;
private Double productTypeBasePrice;
private Integer productTypeLessonsHours;
public ProductDTO(Product product) {
this.id = product.getId();
this.studentId = product.getStudentId().getId();
this.studentFullName = product.getStudentId().getFirstName() + ' ' + product.getStudentId().getLastName();
this.hoursLeft = product.getHoursLeft();
this.bookOnline = product.getBookOnline();
this.isPaid = product.getIsPaid();
this.price = product.getPrice();
this.productTypeId = product.getProductType().getId();
this.productTypeName = product.getProductType().getName();
this.productTypeDescription = product.getProductType().getDescription();
this.productTypeCategory = product.getProductType().getProductCategory();
this.productTypeBasePrice = product.getProductType().getBasePrice();
this.productTypeLessonsHours = product.getProductType().getLessonsHours();
}
}
|
/*
* 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 Collections;
import java.util.ArrayList;
import java.util.Collection;
import java.util.HashSet;
import java.util.Random;
/**
*
* @author YNZ
*/
public class CollectionInterface {
public static void main(String[] args) {
Collection c = new ArrayList();
Iterable i = new HashSet();
Iterable container = c;
Random r = new Random(10);
if(container instanceof Iterable) System.out.println("true");
if(container instanceof Collection) System.out.println("true");
}
}
|
package com.revature.bloodbank.service;
import com.revature.bloodbank.exception.BloodBankDuplicateCenterIdException;
import com.revature.bloodbank.model.BloodBankCenter;
import com.revature.bloodbank.exception.BloodBankInvalidDetailsException;
public interface BloodBankService {
public void addBloodBankCenter(BloodBankCenter bloodBankCenter) throws BloodBankDuplicateCenterIdException;
public void deleteBloodBankCenterByCenterId(BloodBankCenter bloodBankCenter) throws BloodBankInvalidDetailsException;
public void updateBloodBankCenterById(BloodBankCenter bloodBankCenter) throws BloodBankInvalidDetailsException;
public void getAllBloodBankCenters() throws Exception;
public void getBloodBankCenterByCenterName(BloodBankCenter bloodBankCenter) throws Exception;
public void getBloodBankCenterByStreet(BloodBankCenter bloodBankCenter) throws Exception;
public void getBloodBankCenterByPincode(BloodBankCenter bloodBankCenter) throws Exception;
public void getBloodBankCenterByState(BloodBankCenter bloodBankCenter) throws Exception;
public void getBloodBankCenterByCity(BloodBankCenter bloodBankCenter) throws Exception;
}
|
package com.dian.diabetes.activity.eat.adapter;
import java.text.DecimalFormat;
import java.util.List;
import android.content.Context;
import android.view.View;
import android.widget.TextView;
import com.dian.diabetes.R;
import com.dian.diabetes.activity.MBaseAdapter;
import com.dian.diabetes.db.dao.Eat;
import com.dian.diabetes.tool.CommonUtil;
import com.dian.diabetes.utils.DateUtil;
/**
* 饮食首页 运动 饮食 分栏里边的adapter
* @author longbh
*
*/
public class EatAdapter extends MBaseAdapter {
private DecimalFormat format;
public EatAdapter(Context context, List<?> data) {
super(context, data, R.layout.item_eat_view);
format = new DecimalFormat("##0.0");
}
@Override
protected void newView(View convertView) {
ViewHolder holder = new ViewHolder();
holder.eatTime = (TextView) convertView.findViewById(R.id.time);
holder.eatType = (TextView) convertView.findViewById(R.id.eat_type);
holder.foodName = (TextView) convertView.findViewById(R.id.food_name);
holder.totalNum = (TextView) convertView.findViewById(R.id.total_num);
holder.totalCalore = (TextView) convertView.findViewById(R.id.total);
convertView.setTag(holder);
}
@Override
protected void holderView(View convertView, Object itemObject) {
ViewHolder holder = (ViewHolder) convertView.getTag();
Eat eat = (Eat) itemObject;
holder.eatTime.setText(DateUtil.parseToString(eat.getCreate_time(), DateUtil.HHmm));
holder.totalCalore.setText("+" + format.format(eat.getTotal()));
holder.foodName.setText(eat.getFoodName());
holder.totalNum.setText(eat.getFoodWeight()+"");
holder.eatType.setText(CommonUtil.getValue("eat" + eat.getDinnerType()));
}
class ViewHolder{
TextView eatTime;
TextView eatType;
TextView totalCalore;
TextView foodName;
TextView totalNum;
}
}
|
/**
* Sencha GXT 3.0.1 - Sencha for GWT
* Copyright(c) 2007-2012, Sencha, Inc.
* licensing@sencha.com
*
* http://www.sencha.com/products/gxt/license/
*/
package com.sencha.gxt.desktopapp.client.canvas;
import net.edzard.kinetic.Kinetic;
import net.edzard.kinetic.Stage;
import com.google.gwt.user.client.ui.Widget;
import com.sencha.gxt.core.client.dom.ScrollSupport.ScrollMode;
import com.sencha.gxt.data.shared.IconProvider;
import com.sencha.gxt.desktopapp.client.filemanager.images.Images;
import com.sencha.gxt.desktopapp.client.persistence.FileModel;
import com.sencha.gxt.widget.core.client.ContentPanel;
import com.sencha.gxt.widget.core.client.Window;
import com.sencha.gxt.widget.core.client.container.CenterLayoutContainer;
import com.sencha.gxt.widget.core.client.container.VerticalLayoutContainer;
import com.sencha.gxt.widget.core.client.container.VerticalLayoutContainer.VerticalLayoutData;
import com.sencha.gxt.widget.core.client.event.HideEvent;
import com.sencha.gxt.widget.core.client.event.HideEvent.HideHandler;
public class CanvasViewImpl implements CanvasView, HideHandler {
private static final String TITLE = "Canvas";
private CanvasPresenter canvasPresenter;
private Window window;
private CanvasIconProvider canvasIconProvider;
private CanvasToolBar canvasToolBar;
private CanvasMenu canvasMenu;
private VerticalLayoutContainer verticalLayoutContainer;
private FboStage fboStage;
public CanvasViewImpl(CanvasPresenter canvasPresenter) {
this.canvasPresenter = canvasPresenter;
}
@Override
public Widget asWidget() {
return getWindow();
}
private IconProvider<FileModel> getCanvasIconProvider() {
if (canvasIconProvider == null) {
canvasIconProvider = new CanvasIconProvider();
}
return canvasIconProvider;
}
private CanvasMenu getCanvasMenu() {
if (canvasMenu == null) {
canvasMenu = new CanvasMenu(getCanvasPresenter());
}
return canvasMenu;
}
private CanvasPresenter getCanvasPresenter() {
return canvasPresenter;
}
private CanvasToolBar getCanvasToolBar() {
if (canvasToolBar == null) {
canvasToolBar = new CanvasToolBar(getCanvasPresenter());
canvasToolBar.setButtonEnabledState();
}
return canvasToolBar;
}
private String getTitle(FileModel fileModel) {
return TITLE;
}
private Window getWindow() {
if (window == null) {
window = new Window();
window.setHeadingText(getTitle(null));
window.getHeader().setIcon(Images.getImageResources().folder());
window.setMinimizable(true);
window.setMaximizable(true);
window.setClosable(false);
window.setOnEsc(false);
window.addHideHandler(this);
window.setWidget(getVerticalLayoutContainer());
}
return window;
}
private Widget getContainer() {
CenterLayoutContainer con = new CenterLayoutContainer();
ContentPanel panel = new ContentPanel();
panel.setBorders(false);
panel.setHeaderVisible(false);
panel.setWidth(500);
panel.setHeight(400);
con.add(panel);
{
Stage stage = Kinetic.createStage(panel.getBody(), 500, 400);
fboStage = new FboStage(stage);
fboStage.draw();
}
return con;
}
@Override
public void onHide(HideEvent event) {
}
private VerticalLayoutContainer getVerticalLayoutContainer() {
if (verticalLayoutContainer == null) {
verticalLayoutContainer = new VerticalLayoutContainer();
verticalLayoutContainer.setBorders(false);
verticalLayoutContainer.add(getCanvasToolBar(),
new VerticalLayoutData(1, -1));
verticalLayoutContainer.add(getContainer(),
new VerticalLayoutData(1, 1));
verticalLayoutContainer.setScrollMode(ScrollMode.AUTO);
}
return verticalLayoutContainer;
}
@Override
public void onZoomout() {
fboStage.onZoomout();
}
@Override
public void onZoomin() {
fboStage.onZoomin();
}
@Override
public void onNewLine() {
fboStage.onNewLine();
}
}
|
package com.dambroski.services;
import java.io.UnsupportedEncodingException;
import java.net.URLDecoder;
import java.util.Arrays;
import java.util.List;
import java.util.Optional;
import java.util.stream.Collectors;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
import org.springframework.stereotype.Service;
import com.dambroski.domain.Produto;
import com.dambroski.repositories.ProdutoRepository;
import com.dambroski.services.exceptions.EntitieNotFoundException;
@Service
public class ProdutoService {
@Autowired
private ProdutoRepository produtoRepository;
public Produto findById(Integer id) {
Optional<Produto> prod = produtoRepository.findById(id);
return prod.orElseThrow(() -> new EntitieNotFoundException("Produto não encontrado"));
}
public Page<Produto> findByNomeAndIds(String nome, String categoriaIds, Pageable pageable) {
nome = nomeDeconde(nome);
List<Integer> ids = listToInteger(categoriaIds);
Page<Produto> produtos = produtoRepository.findDistinctByNomeContainingIgnoreCaseAndCategoriasIdIn(nome, ids,
pageable);
return produtos;
}
private static List<Integer> listToInteger(String param) {
return Arrays.asList(param.split(",")).stream().map(x -> Integer.parseInt(x)).collect(Collectors.toList());
}
private static String nomeDeconde(String nome) {
try {
nome = URLDecoder.decode(nome, "UTF-8");
return nome;
} catch (UnsupportedEncodingException e) {
return "";
}
}
}
|
package com.ag.entity;
import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;
@NoArgsConstructor
@AllArgsConstructor
@Data
public class CategoryDto {
private String name;
private Integer type;
}
|
/*
* Copyright 2002-2015 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.springframework.cache.config;
import java.io.IOException;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.atomic.AtomicLong;
import javax.cache.annotation.CacheDefaults;
import javax.cache.annotation.CacheKey;
import javax.cache.annotation.CachePut;
import javax.cache.annotation.CacheRemove;
import javax.cache.annotation.CacheRemoveAll;
import javax.cache.annotation.CacheResult;
import javax.cache.annotation.CacheValue;
import org.springframework.cache.Cache;
import org.springframework.cache.interceptor.SimpleKeyGenerator;
import org.springframework.contextsupport.testfixture.cache.TestableCacheKeyGenerator;
import org.springframework.contextsupport.testfixture.cache.TestableCacheResolverFactory;
import org.springframework.contextsupport.testfixture.jcache.JCacheableService;
/**
* Repository sample with a @CacheDefaults annotation
*
* <p>Note: copy/pasted from its original compilation because it needs to be
* processed by the AspectJ compiler to wave the required aspects.
*
* @author Stephane Nicoll
*/
@CacheDefaults(cacheName = "default")
public class AnnotatedJCacheableService implements JCacheableService<Long> {
private final AtomicLong counter = new AtomicLong();
private final AtomicLong exceptionCounter = new AtomicLong();
private final Cache defaultCache;
public AnnotatedJCacheableService(Cache defaultCache) {
this.defaultCache = defaultCache;
}
@Override
@CacheResult
public Long cache(String id) {
return counter.getAndIncrement();
}
@Override
@CacheResult
public Long cacheNull(String id) {
return null;
}
@Override
@CacheResult(exceptionCacheName = "exception", nonCachedExceptions = NullPointerException.class)
public Long cacheWithException(@CacheKey String id, boolean matchFilter) {
throwException(matchFilter);
return 0L; // Never reached
}
@Override
@CacheResult(exceptionCacheName = "exception", nonCachedExceptions = NullPointerException.class)
public Long cacheWithCheckedException(@CacheKey String id, boolean matchFilter) throws IOException {
throwCheckedException(matchFilter);
return 0L; // Never reached
}
@Override
@CacheResult(skipGet = true)
public Long cacheAlwaysInvoke(String id) {
return counter.getAndIncrement();
}
@Override
@CacheResult
public Long cacheWithPartialKey(@CacheKey String id, boolean notUsed) {
return counter.getAndIncrement();
}
@Override
@CacheResult(cacheResolverFactory = TestableCacheResolverFactory.class)
public Long cacheWithCustomCacheResolver(String id) {
return counter.getAndIncrement();
}
@Override
@CacheResult(cacheKeyGenerator = TestableCacheKeyGenerator.class)
public Long cacheWithCustomKeyGenerator(String id, String anotherId) {
return counter.getAndIncrement();
}
@Override
@CachePut
public void put(String id, @CacheValue Object value) {
}
@Override
@CachePut(cacheFor = UnsupportedOperationException.class)
public void putWithException(@CacheKey String id, @CacheValue Object value, boolean matchFilter) {
throwException(matchFilter);
}
@Override
@CachePut(afterInvocation = false)
public void earlyPut(String id, @CacheValue Object value) {
Object key = SimpleKeyGenerator.generateKey(id);
Cache.ValueWrapper valueWrapper = defaultCache.get(key);
if (valueWrapper == null) {
throw new AssertionError("Excepted value to be put in cache with key " + key);
}
Object actual = valueWrapper.get();
if (value != actual) { // instance check on purpose
throw new AssertionError("Wrong value set in cache with key " + key + ". " +
"Expected=" + value + ", but got=" + actual);
}
}
@Override
@CachePut(afterInvocation = false)
public void earlyPutWithException(@CacheKey String id, @CacheValue Object value, boolean matchFilter) {
throwException(matchFilter);
}
@Override
@CacheRemove
public void remove(String id) {
}
@Override
@CacheRemove(noEvictFor = NullPointerException.class)
public void removeWithException(@CacheKey String id, boolean matchFilter) {
throwException(matchFilter);
}
@Override
@CacheRemove(afterInvocation = false)
public void earlyRemove(String id) {
Object key = SimpleKeyGenerator.generateKey(id);
Cache.ValueWrapper valueWrapper = defaultCache.get(key);
if (valueWrapper != null) {
throw new AssertionError("Value with key " + key + " expected to be already remove from cache");
}
}
@Override
@CacheRemove(afterInvocation = false, evictFor = UnsupportedOperationException.class)
public void earlyRemoveWithException(@CacheKey String id, boolean matchFilter) {
throwException(matchFilter);
}
@Override
@CacheRemoveAll
public void removeAll() {
}
@Override
@CacheRemoveAll(noEvictFor = NullPointerException.class)
public void removeAllWithException(boolean matchFilter) {
throwException(matchFilter);
}
@Override
@CacheRemoveAll(afterInvocation = false)
public void earlyRemoveAll() {
ConcurrentHashMap<?, ?> nativeCache = (ConcurrentHashMap<?, ?>) defaultCache.getNativeCache();
if (!nativeCache.isEmpty()) {
throw new AssertionError("Cache was expected to be empty");
}
}
@Override
@CacheRemoveAll(afterInvocation = false, evictFor = UnsupportedOperationException.class)
public void earlyRemoveAllWithException(boolean matchFilter) {
throwException(matchFilter);
}
@Deprecated
public void noAnnotation() {
}
@Override
public long exceptionInvocations() {
return exceptionCounter.get();
}
private void throwException(boolean matchFilter) {
long count = exceptionCounter.getAndIncrement();
if (matchFilter) {
throw new UnsupportedOperationException("Expected exception (" + count + ")");
}
else {
throw new NullPointerException("Expected exception (" + count + ")");
}
}
private void throwCheckedException(boolean matchFilter) throws IOException {
long count = exceptionCounter.getAndIncrement();
if (matchFilter) {
throw new IOException("Expected exception (" + count + ")");
}
else {
throw new NullPointerException("Expected exception (" + count + ")");
}
}
}
|
package com.example.ecoleenligne.util;
import android.content.Context;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.TextView;
import com.example.ecoleenligne.R;
import com.example.ecoleenligne.model.Item;
import java.util.ArrayList;
public class CustomListAdapter extends BaseAdapter {
private Context context; //context
private ArrayList<Item> items; //data source of the list adapter
//public constructor
public CustomListAdapter(Context context, ArrayList<Item> items) {
this.context = context;
this.items = items;
}
@Override
public int getCount() {
return items.size(); //returns total of items in the list
}
@Override
public Object getItem(int position) {
return items.get(position); //returns list item at the specified position
}
@Override
public long getItemId(int position) {
return position;
}
@Override
public View getView(int position, View convertView, ViewGroup parent) {
// inflate the layout for each list row
if (convertView == null) {
convertView = LayoutInflater.from(context).
inflate(R.layout.layout_list_view_row_items, parent, false);
}
Item currentItem = (Item) getItem(position);
TextView textViewItemName = (TextView) convertView.findViewById(R.id.text_view_item_name);
TextView textViewItemDescription = (TextView) convertView.findViewById(R.id.text_view_item_description);
textViewItemName.setText(currentItem.getItemName());
textViewItemDescription.setText(currentItem.getItemDescription());
return convertView;
}
}
|
/**
* Square subclass of superclass Shape. Overrides toString, getPerimeter, and area methods.
*
* @CollinWen
*/
public class Square extends Shape
{
public Square() {
this(4, "A");
}
public Square(int length, String name) {
super(4, length, name);
}
@Override
public String toString() {
return "Square " + this.getName() + " (Side Length: " + this.getSides().get(0) + ")";
}
@Override
public int getPerimeter() {
return 4*this.getSides().get(0);
}
@Override
public double area() {
return Math.pow(this.getSides().get(0), 2);
}
}
|
package com.example.firstprogram;
import android.content.Context;
import android.content.res.TypedArray;
import android.graphics.drawable.Drawable;
import android.util.AttributeSet;
import android.view.Gravity;
import android.view.View;
import android.widget.Button;
import android.widget.RelativeLayout;
import android.widget.TextView;
import java.io.UnsupportedEncodingException;
public class TopBar extends RelativeLayout {
private Button leftBtn, rightBtn;
private TextView textTitle;
private int leftTextColor;
private Drawable leftBackground;
private String leftText;
private int rightTextColor;
private Drawable rightBackground;
private String rightText;
private float titleTextSize;
private int titleTextColor;
private String title;
private LayoutParams leftParams,rightParams,titleParams;
public interface topbarClickListener{
public void leftClick();
public void rightClick() throws UnsupportedEncodingException;
}
private topbarClickListener listener;
public void setOnTopbarClickListener(topbarClickListener listener){
this.listener = listener;
}
public void setLeftBtnIsVisiable(Boolean b){
if(b){
leftBtn.setVisibility(View.VISIBLE);
}else {
leftBtn.setVisibility(View.GONE);
}
}
public void setRightBtnIsVisiable(Boolean b){
if(b){
rightBtn.setVisibility(View.VISIBLE);
}else {
rightBtn.setVisibility(View.GONE);
}
}
public TopBar(Context context, AttributeSet attrs) {
super(context, attrs);
TypedArray ta = context.obtainStyledAttributes(attrs, R.styleable.TopBar);
leftTextColor = ta.getColor(R.styleable.TopBar_leftTextColor, 0);
leftBackground = ta.getDrawable(R.styleable.TopBar_leftBackground);
leftText = ta.getString(R.styleable.TopBar_leftText);
rightTextColor = ta.getColor(R.styleable.TopBar_rightTextColor, 0);
rightBackground = ta.getDrawable(R.styleable.TopBar_rightBackground);
rightText = ta.getString(R.styleable.TopBar_rightText);
titleTextSize = ta.getDimension(R.styleable.TopBar_titleTextSize, 0);
titleTextColor = ta.getColor(R.styleable.TopBar_titleTextColor, 0);
title = ta.getString(R.styleable.TopBar_titleText);
ta.recycle();
leftBtn = new Button(context);
rightBtn = new Button(context);
textTitle = new TextView(context);
leftBtn.setTextColor(leftTextColor);
leftBtn.setBackground(leftBackground);
leftBtn.setText(leftText);
rightBtn.setTextColor(rightTextColor);
rightBtn.setBackground(rightBackground);
rightBtn.setText(rightText);
textTitle.setTextColor(titleTextColor);
textTitle.setTextSize(titleTextSize);
textTitle.setText(title);
textTitle.setGravity(Gravity.CENTER);
setBackgroundColor(0xff00CCCC);
//leftButton
leftParams = new LayoutParams(LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT);
leftParams.addRule(RelativeLayout.ALIGN_PARENT_LEFT, TRUE);
addView(leftBtn, leftParams);
//title
titleParams = new LayoutParams(LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT);
titleParams.addRule(RelativeLayout.CENTER_IN_PARENT, TRUE);
addView(textTitle, titleParams);
//rightButton
rightParams = new LayoutParams(LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT);
rightParams.addRule(RelativeLayout.ALIGN_PARENT_RIGHT, TRUE);
addView(rightBtn,rightParams);
leftBtn.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
listener.leftClick();
}
});
rightBtn.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
try {
listener.rightClick();
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
}
}
});
}
}
|
package mk.finki.ukim.dians.surveygenerator.surveygeneratorcore.domain.jpamodels;
import lombok.*;
import javax.persistence.*;
@Getter
@Setter
@NoArgsConstructor
@AllArgsConstructor
@EqualsAndHashCode
@Entity
@Table(schema = "surveys", name = "surveys_answers")
public class SurveyAnswer {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Long id;
@Column(name = "status")
private Boolean status;
@ManyToOne
@JoinColumn(name = "survey_id")
private Survey survey;
}
|
package org.codingdojo.kata.parkinglot;
import org.codingdojo.kata.parkinglot.Bean.Car;
import org.codingdojo.kata.parkinglot.Bean.Credit;
import org.codingdojo.kata.parkinglot.parkingboy.SuperParkingBoy;
import org.junit.Test;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertNull;
public class SuperGraduateParkingBoyTest {
@Test
public void should_park_in_first_parking_lot_when_the_first_parking_lot_has_higher_free_ratio() {
SuperParkingBoy boy = initSuperParkingBoy(1, 0);
Car car = new Car();
Credit credit = boy.park(car);
assertEquals(1, credit.getParkingLotNumber());
}
@Test
public void should_park_in_second_parking_lot_when_the_second_parking_lot_has_higher_free_ratio() {
SuperParkingBoy boy = initSuperParkingBoy(0, 1);
Car car = new Car();
Credit credit = boy.park(car);
assertEquals(2, credit.getParkingLotNumber());
}
@Test
public void should_park_in_first_parking_lot_when_the_first_parking_lot_has_higher_free_ratio_of_fraction() {
SuperParkingBoy boy = initSuperParkingBoy(3, 4);
Car car1 = new Car();
Credit credit1 = boy.park(car1);
assertEquals(1, credit1.getParkingLotNumber());
Car car2 = new Car();
Credit credit2 = boy.park(car2);
assertEquals(2, credit2.getParkingLotNumber());
Car car3 = new Car();
Credit credit3 = boy.park(car3);
assertEquals(2, credit3.getParkingLotNumber());
}
@Test
public void should_park_in_p1_when_p1_and_p2_have_same_free_pos() {
SuperParkingBoy boy = initSuperParkingBoy(1, 1);
Car car = new Car();
Credit credit = boy.park(car);
assertEquals(1, credit.getParkingLotNumber());
}
@Test
public void should_not_park_when_parking_lots_are_full() {
SuperParkingBoy boy = initSuperParkingBoy(0, 0);
Car car = new Car();
Credit credit = boy.park(car);
assertNull(credit);
}
@Test
public void should_get_car_when_with_right_credit() {
SuperParkingBoy boy = initSuperParkingBoy(1, 1);
Car car = new Car();
Credit credit = boy.park(car);
assertEquals(car, boy.retrieveCar(credit));
}
@Test
public void should_return_null_given_invalid_credit_when_retrieve_car() {
SuperParkingBoy boy = initSuperParkingBoy(1, 1);
Credit credit = new Credit(1, "dummy token");
assertNull(boy.retrieveCar(credit));
}
private SuperParkingBoy initSuperParkingBoy(int firstLotSize, int secondLotSize) {
SuperParkingBoy boy = new SuperParkingBoy();
boy.addParkingLot(firstLotSize);
boy.addParkingLot(secondLotSize);
return boy;
}
}
|
package com.mattcramblett.primenumbergenerator;
import static org.junit.Assert.assertEquals;
import java.io.ByteArrayOutputStream;
import java.io.PrintStream;
import java.util.Arrays;
import org.junit.After;
import org.junit.Before;
import org.junit.Test;
public class MainTest extends AbstractTest {
private final ByteArrayOutputStream outContent = new ByteArrayOutputStream();
private final ByteArrayOutputStream errContent = new ByteArrayOutputStream();
private final PrintStream originalOut = System.out;
private final PrintStream originalErr = System.err;
@Before
public void redirectStandardOutput() throws Exception {
System.setOut(new PrintStream(this.outContent));
System.setErr(new PrintStream(this.errContent));
}
@After
public void restoreStandardOutput() throws Exception {
System.setOut(this.originalOut);
System.setErr(this.originalErr);
}
@Test(expected = NumberFormatException.class)
public void testOutputWithInvalidRangeParameters() {
final String args[] = { "1,00", "a" };
Main.main(args);
}
@Test(expected = IndexOutOfBoundsException.class)
public void testOutputWithoutRangeParameters() {
final String args[] = {};
Main.main(args);
}
@Test
public void testOutputResultWithValidRangeParameters() {
final String args[] = { "-100", "102" };
Main.main(args);
assertEquals(SMALL_PRIMES.toString(), this.outContent.toString().trim());
}
@Test
public void testOutputWhenResultIsEmptyWithValidRangeParameters() {
final String args[] = { "0", "0" };
Main.main(args);
assertEquals(Arrays.asList().toString(), this.outContent.toString().trim());
}
}
|
package week2.assignment;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.chrome.ChromeDriver;
import org.openqa.selenium.interactions.Actions;
import io.github.bonigarcia.wdm.WebDriverManager;
import org.openqa.selenium.chrome.ChromeDriver;
import io.github.bonigarcia.wdm.WebDriverManager;
public class Image {
public static void main(String[] args) throws InterruptedException {
WebDriverManager.chromedriver().setup();
ChromeDriver driver = new ChromeDriver();
driver.get("http://leafground.com/pages/Image.html");
driver.manage().window().maximize();
Thread.sleep(3000);
driver.findElementByXPath("//*[@id='contentblock']/section/div[1]/div/div/img").click();Thread.sleep(2000);
driver.get("http://leafground.com/pages/Image.html");
Actions action = new Actions(driver);
WebElement link =driver.findElementByXPath("//*[@id='contentblock']/section/div[3]/div/div/img");
action.doubleClick(link).perform();System.out.println("Clicked");Thread.sleep(2000);
System.out.println("All steps are completed successfully!!!!");
driver.close();
}
}
|
package cliente;
public abstract class CirculoBase{
public CirculoBase(String id, int limite){
}
public void setLimite(int limite) {
}
public String getId() {
return null;
}
public int getLimite() {
return 0;
}
public abstract int getNumberOfContacts();
}
|
package _00_config;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.ImportResource;
import org.springframework.data.redis.connection.jedis.JedisConnectionFactory;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.session.data.redis.config.annotation.web.http.EnableRedisHttpSession;
import redis.clients.jedis.JedisPoolConfig;
@Configuration
@EnableRedisHttpSession
@ImportResource("file:**\\WEB-INF\\spring-beans.xml")
//@ImportResource("file:E:\\CTBC_workspace_Oxygen_3a\\SpringSessionTest\\src\\main\\webapp\\WEB-INF\\spring-beans.xml")
//@ComponentScan(basePackageClasses = { org.springframework.web.filter.DelegatingFilterProxy.class })
//@ComponentScan(basePackages= {"org.springframework.web.filter.*"})
public class RootConfig {
@Bean
public redis.clients.jedis.JedisPoolConfig jedisPoolConfig() {
JedisPoolConfig jedisPoolConfig = new JedisPoolConfig();
return jedisPoolConfig;
}
@Bean
@SuppressWarnings("deprecation")
public org.springframework.data.redis.connection.jedis.JedisConnectionFactory jedisConnectionFactory(JedisPoolConfig jedisPoolConfig) {
JedisConnectionFactory factory = new JedisConnectionFactory();
factory.setHostName("127.0.0.2");
factory.setPort(6379);
factory.setPassword("");
factory.setTimeout(1800);
factory.setPoolConfig(jedisPoolConfig);
factory.setUsePool(true);
return factory;
}
@Bean
public org.springframework.data.redis.core.StringRedisTemplate redisTemplate(JedisConnectionFactory connectionFactory) {
StringRedisTemplate redisTemplate = new StringRedisTemplate();
redisTemplate.setConnectionFactory(connectionFactory);
return redisTemplate;
}
// @Bean
// public org.springframework.session.data.redis.config.annotation.web.http.RedisHttpSessionConfiguration redisHttpSessionConfiguration() {
// RedisHttpSessionConfiguration redisHttpSessionConfiguration = new RedisHttpSessionConfiguration();
// redisHttpSessionConfiguration.setMaxInactiveIntervalInSeconds(1800);
// return redisHttpSessionConfiguration;
// }
}
|
package Hang.Java.Common.Helpers;
import java.io.*;
import java.net.URL;
import java.net.URLConnection;
public class HttpHelper {
public String Get(String url, String encoding) {
String result = "";
BufferedReader in = null;
try {
URLConnection conn = new URL(url).openConnection();
in = new BufferedReader(new InputStreamReader(conn.getInputStream(), encoding));
String line;
while ((line = in.readLine()) != null) {
result += line;
}
} catch (Exception ex) {
LogHelper.Error(ex);
} finally {
try {
if (in != null) {
in.close();
}
} catch (IOException e) {
e.printStackTrace();
}
}
return result;
}
public String Post(String url, String param, String contentType, String encoding) {
String result = "";
BufferedReader in = null;
OutputStreamWriter out;
try {
URLConnection conn = new URL(url).openConnection();
conn.setDoOutput(true);
if (contentType != null)
conn.setRequestProperty("content-type", contentType);
conn.setRequestProperty("Content-Encoding", encoding);
out = new OutputStreamWriter(conn.getOutputStream(), encoding);
out.write(param);
out.flush();
out.close();
in = new BufferedReader(new InputStreamReader(conn.getInputStream(), encoding));
String line;
while ((line = in.readLine()) != null) {
result += line;
}
} catch (Exception ex) {
LogHelper.Error(ex);
} finally {
try {
if (in != null) {
in.close();
}
} catch (IOException e) {
LogHelper.Error(e);
}
}
return result;
}
}
|
public class ThreeSortDemo {
public static void main(String[] args) {
int N = 100000;
int[] A = new int[N];
for(int i = 0;i < A.length;i++) {
A[i] = (int) (Math.random() * N * 10);
//System.out.printf("%4d",A[i]);
}
double t0 = System.nanoTime() / 1e6;
SelectionSort(A);
double t1 = System.nanoTime() / 1e6;
InsertionSort(A);
double t2 = System.nanoTime() / 1e6;
BubbleSort(A);
double t3 = System.nanoTime() / 1e6;
double[] Time = {t1 - t0, t2 - t1, t3 - t2};
String[] Word = { "SelectionSort is ", "InsertionSort is ", "BubbleSort is "};
System.out.printf("N = %d, timecost is shown as below.\n",N);
for(int i = 0;i < Time.length;i++) {
System.out.printf("%s%f ms\n", Word[i], Time[i] );
}
}
public static void SelectionSort(int[] A) {
for(int i = 0;i < A.length;i++) {
//minimum number position.
int k = i;
for(int j = i+1;j < A.length;j++) {
if(A[k] > A[j])
k = j;//new minimum number position.
}
//Move the minimum number to first position.
int temp = A[k];
A[k] = A[i];
A[i] = temp;
}
}
public static void InsertionSort(int[] A) {
for(int i = 1;i < A.length;i++) {
int temp = A[i]; //Extract a element.
for(int j = i - 1;j >= 0 ;j--) {
if(temp < A[j]) {
//move element to the right by 1.
A[j+1] = A[j];
A[j] = temp;
}
}
}
}
public static void BubbleSort(int[] A) {
for(int i = 0;i < A.length;i++) {
for(int j = 0;j < A.length-1;j++) {
if(A[j] > A[j+1]) {
int temp = A[j+1];
A[j+1] = A[j];
A[j] = temp;
//swap left element and right element.
}
}
}
}
}
|
package com.android.recommender;
//reference: http://www.androidhive.info/2013/11/android-sliding-menu-using-navigation-drawer/
import android.app.Fragment;
import android.app.FragmentManager;
import android.content.Intent;
import android.os.Bundle;
import android.support.v4.widget.DrawerLayout;
import android.support.v7.app.ActionBar;
import android.support.v7.app.ActionBarActivity;
import android.util.Log;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.ListView;
import com.android.recommender.fragment.CinemasFragment;
import com.android.recommender.fragment.SessionFragment;
import com.android.recommender.history.HistoryFragment;
import com.android.recommender.home.HomeFragment;
import com.android.recommender.model.Cinema;
import com.android.recommender.movie.DetailMovieFragment;
import com.android.recommender.movie.ListMovieFragment;
import com.android.recommender.movie.MoviesFragment;
import com.example.recommender.R;
public class MainActivity extends ActionBarActivity
implements MoviesFragment.OnMovieSelectedListener, MoviesFragment.onTitleSearchListener,
ListMovieFragment.onTitleSearchListener, DetailMovieFragment.onCinemaSelectedListener {
private String[] mMenuTitles;
private DrawerLayout mDrawerLayout;
private ListView mDrawerList;
private String TAG = "NavigationDrawerProject";
private String userName;
private Double latitude, longitude;
private Cinema selectedCinema = null;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
mMenuTitles = getResources().getStringArray(R.array.menus_array);
mDrawerLayout = (DrawerLayout) findViewById(R.id.drawer_layout);
mDrawerList = (ListView) findViewById(R.id.left_drawer);
// Set the adapter for the list view
mDrawerList.setAdapter(new ArrayAdapter<String>(this, R.layout.drawer_list_item, mMenuTitles));
// Set the list's click listener
mDrawerList.setOnItemClickListener(new DrawerItemClickListener());
ActionBar actionBar = getSupportActionBar();
actionBar.setDisplayHomeAsUpEnabled(true);
actionBar.setHomeButtonEnabled(true);
actionBar.setIcon(R.drawable.ic_launcher);
Intent intent = getIntent();
userName = intent.getStringExtra("userName");
latitude = intent.getDoubleExtra("latitude", 0.0);
longitude = intent.getDoubleExtra("longitude", 0.0);
FragmentManager fragmentManager = getFragmentManager();
//fragmentManager.beginTransaction().add(new HomeFragment(), null).commit();
fragmentManager.beginTransaction().replace(R.id.content_frame, new HomeFragment()).commit();
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.main, menu);
return true;
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
int id = item.getItemId();
if (id == R.id.action_settings) {
return true;
}
return super.onOptionsItemSelected(item);
}
private class DrawerItemClickListener implements
ListView.OnItemClickListener {
@Override
public void onItemClick(AdapterView parent, View view, int position,
long id) {
Fragment fragment = null;
switch (position) {
case 0:
fragment = new ListMovieFragment(userName, "com.entity.movie/getLatest");
break;
case 1:
fragment = new MoviesFragment(userName);
break;
case 2:
fragment = new CinemasFragment(latitude, longitude, selectedCinema);
break;
case 3:
fragment = new HistoryFragment(userName);
break;
case 4:
finish();
return;
default:
Log.e(TAG, "Invalid Selection");
}
// Insert the fragment by replacing any existing fragment
FragmentManager fragmentManager = getFragmentManager();
fragmentManager.beginTransaction().replace(R.id.content_frame, fragment).commit();
// Highlight the selected item, update the title, and close the drawer
mDrawerList.setItemChecked(position, true);
mDrawerList.setSelection(position);
setTitle(mMenuTitles[position]);
mDrawerLayout.closeDrawer(mDrawerList);
}
}
@Override
public void onTitleSearch(String movieTitle){
// Create fragment and give it an argument for the selected article
Fragment newFragment = new DetailMovieFragment(userName);
Bundle args = new Bundle();
args.putString(DetailMovieFragment.ARG_TITLE, movieTitle);
newFragment.setArguments(args);
FragmentManager fragmentManager = getFragmentManager();
fragmentManager.beginTransaction().replace(R.id.content_frame, newFragment).commit();
}
@Override
public void onMovieSelected(String queryUrl) {
Fragment newFragment = new ListMovieFragment(userName, queryUrl);
FragmentManager fragmentManager = getFragmentManager();
fragmentManager.beginTransaction().replace(R.id.content_frame, newFragment).commit();
}
@Override
public void onCinemaSelected(Cinema cinema) {
selectedCinema = cinema;
}
}
|
class NestSeven
{
void m1(){}
void m2(){}
}
//lets write code with anonymous class without InnerSix type of class decalred in NestSix.java
class SevenNest
{
NestSeven s = new NestSeven()
{void m1(){System.out.println("M1 Method from anonymous class");}
void m2(){System.out.println("M2 Method from anonymous class");
System.out.println(s.getClass().getName());}
};
public static void main(String[] args)
{
SevenNest sn = new SevenNest();
sn.s.m1();
sn.s.m2();
}
}
|
package com.peregudova.multinote.app;
import android.os.Bundle;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.fragment.app.Fragment;
import androidx.lifecycle.Observer;
import androidx.lifecycle.ViewModelProviders;
import com.peregudova.multinote.R;
import com.peregudova.multinote.requests.ChangeAnswer;
import com.peregudova.multinote.requests.ListAccessAnswer;
import com.peregudova.multinote.requests.Note;
import com.peregudova.multinote.requests.NoteAnswer;
import com.peregudova.multinote.requests.User;
import org.jetbrains.annotations.NotNull;
public class NoteFragment extends Fragment {
NoteFragmentViewModel noteFragmentViewModel;
Button button;
TextView note_text;
TextView note_info;
EditText text_add_access;
TextView list_access;
Button change;
FragmentViewViewModel fragmentViewViewModel;
String user;
Note note;
String token;
Button save;
@Override
public void onCreate(@Nullable @org.jetbrains.annotations.Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
noteFragmentViewModel = ViewModelProviders.of(this).get(NoteFragmentViewModel.class);
noteFragmentViewModel.getNoteAnswerMutableLiveData().observe(this, new Observer<NoteAnswer>() {
@Override
public void onChanged(NoteAnswer noteAnswer) {
//вызов функций отображения контента
note = noteAnswer.getNote();
showContent(noteAnswer);
}
});
noteFragmentViewModel.getListAccessAnswerMutableLiveData().observe(this, new Observer<ListAccessAnswer>() {
@Override
public void onChanged(ListAccessAnswer listAccessAnswer) {
showListAccess(listAccessAnswer);
}
});
noteFragmentViewModel.getChangeAnswerMutableLiveData().observe(this, new Observer<ChangeAnswer>() {
@Override
public void onChanged(ChangeAnswer changeAnswer) {
if(changeAnswer.getChange().equals("true")){
unBlockText();
change.setVisibility(View.GONE);
}
}
});
}
private void showListAccess(ListAccessAnswer listAccessAnswer) {
StringBuffer list = new StringBuffer();
for(String key:listAccessAnswer.getListaccess().keySet()){
list.append(key).append(". ").append(listAccessAnswer.getListaccess().get(key).getAccess_login()).append("\n");
}
list_access.setText(list);
}
public void setFragmentViewViewModel(FragmentViewViewModel fragmentViewViewModel) {
this.fragmentViewViewModel = fragmentViewViewModel;
this.fragmentViewViewModel.getViewFragment().observe(this, new Observer<Boolean>() {
@Override
public void onChanged(Boolean aBoolean) {
if(aBoolean){
setVisible();
} else{
setInvisible();
}
}
});
}
public void setVisible(){
getView().setVisibility(View.VISIBLE);
}
public void setInvisible(){
getView().setVisibility(View.INVISIBLE);
}
private void showContent(NoteAnswer noteAnswer) {
setVisible();
note_text.setText(noteAnswer.getNote().getText());
Note note = noteAnswer.getNote();
String info = "Is modified: "+note.getIs_modified()+"\nLast modified: "+note.getLast_modified()+"\nLogin modified: "+note.getLogin_modified()+"\nOwner: "+note.getOwner();
note_info.setText(info);
change.setClickable(!note.getIs_modified().equals("1"));
save.setVisibility(View.GONE);
change.setVisibility(View.VISIBLE);
}
@Nullable
@org.jetbrains.annotations.Nullable
@Override
public View onCreateView(@NonNull @NotNull LayoutInflater inflater, @Nullable @org.jetbrains.annotations.Nullable ViewGroup container, @Nullable @org.jetbrains.annotations.Nullable Bundle savedInstanceState) {
View inflate = inflater.inflate(R.layout.note_fragment, container, false);
button = inflate.findViewById(R.id.add_access_button);
text_add_access = inflate.findViewById(R.id.new_access);
button.setOnClickListener(view -> {
//button add list access
String login = text_add_access.getText().toString();
if(noteFragmentViewModel.check(login)){
noteFragmentViewModel.addAccessList(user, token, login, note.getId());
noteFragmentViewModel.getListAccess(user, token, note.getId());
}
});
change = inflate.findViewById(R.id.button_change);
change.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
//ask server to change note
noteFragmentViewModel.changeNote(user, token, note.getId());
}
});
save = inflate.findViewById(R.id.button_save);
save.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
//clicked to save note
saveNote();
blockText();
}
});
note_text = inflate.findViewById(R.id.note_text);
note_info = inflate.findViewById(R.id.note_info);
list_access = inflate.findViewById(R.id.list_access);
inflate.setVisibility(View.GONE);
return inflate;
}
public void saveNote() {
blockText();
String text = note_text.getText().toString();
noteFragmentViewModel.saveNote(token, user, note.getId(), text);
}
public void setNote(Note note, String user, String token) {
//команда от активности на загрузку data фрагмента
this.user = user;
this.token = token;
noteFragmentViewModel.getNote(note, user, token);
noteFragmentViewModel.getListAccess(user, token, note.getId());
}
private void unBlockText(){
save.setVisibility(View.VISIBLE);
note_text.setEnabled(true);
}
private void blockText(){
save.setVisibility(View.GONE);
note_text.setEnabled(false);
change.setVisibility(View.VISIBLE);
}
}
|
package com.qst.chapter09;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.io.PrintWriter;
import java.net.ServerSocket;
import java.net.Socket;
/**
* Created by Adminstrator on 2016/10/19.
*/
public class Server {
private int ServerPort = 9898;//定义端口
private ServerSocket serverSocket=null;//生命服务器套接字
private OutputStream outputStream=null;//声明输出流
private InputStream inputStream=null;//声明输入流
private PrintWriter printWriter=null;//声明打印流,用于将数据发送给对方
private Socket socket=null;//声明套接字,注意同服务器套接字不同
private BufferedReader reader=null;//声明缓冲流,用于读取接收的数据
/* Server类的构造函数 */
public Server(){
try {
//根据指定的端口号,创建套接字
serverSocket=new ServerSocket(ServerPort);
System.out.println("服务启动中...");
socket=serverSocket.accept();//用accept方法等待客户端的连接
System.out.println("客户端已连接...\n");
} catch (IOException e) {
e.printStackTrace();//打印异常信息
}
try {
//获取套接字输出流
outputStream=socket.getOutputStream();
//获取套接字输入流
inputStream=socket.getInputStream();
//根据outputStream创建PrintWriter对象
printWriter=new PrintWriter(outputStream,true);
//根据inputStream创建BufferedReader对象
reader=new BufferedReader(new InputStreamReader(inputStream));
//根据System.in创建BufferedReader对象
BufferedReader in=new BufferedReader(new InputStreamReader(System.in));
while(true){
//读客户端的传输信息
String message=reader.readLine();
//将接受的信息打印出来
System.out.println("来自客户端的信息:"+message);
//若消息为Bye或者bye,则结束通信
if(message.equals("Bye")||message.equals("bye"))
break;
message=in.readLine();//接收键盘输入
printWriter.println(message);//将输入的信息向客户端输出
}
outputStream.close();//关闭输出流
inputStream.close();//关闭输入流
socket.close();//关闭套接字
serverSocket.close();//关闭服务器套接字
System.out.println("客户端关闭连接");
} catch (IOException e) {
e.printStackTrace();
}finally {
}
}
/* 程序入口,程序从main函数开始执行 */
public static void main(String[] args){
new Server();
}
}
|
package com.codigo.smartstore.sdk.core.struct.iterate.array;
import static org.hamcrest.CoreMatchers.is;
import static org.hamcrest.MatcherAssert.assertThat;
import org.junit.jupiter.api.DisplayName;
import org.junit.jupiter.api.Test;
import com.codigo.smartstore.sdk.core.structs.iterate.array.ArrayIterable;
import com.codigo.smartstore.sdk.core.structs.iterate.array.ArrayIteratorFactory;
class TestsBooleanArrayIterator {
static final Boolean[] array = { false, true, true, false, false, false, true, false, true, false, true, true };
@DisplayName("Test add user successfully.")
@Test
void testShouldCount12_Of() {
// ...Arrange
int itemsCount = 0;
final ArrayIterable<Boolean> iterator = ArrayIteratorFactory.of(array);
// ...Act
while (iterator.hasNext()) { iterator.next(); itemsCount++; }
// ...Assert
assertThat(iterator.getCount(), is(itemsCount));
assertThat(array.length, is(itemsCount));
}
@Test
void testShouldCount1_OfRangeFirst_To_First() {
// ...Arrange
int itemsCount = 0;
final ArrayIterable<Boolean> iterator = ArrayIteratorFactory.ofRange(array, 0, 0);
// ...Act
while (iterator.hasNext()) { iterator.next(); itemsCount++; }
// ...Assert
assertThat(iterator.getCountFromRange(), is(itemsCount));
assertThat(1, is(itemsCount));
}
@Test
void testShouldCount1_OfRangeLast_To_Last() {
// ...Arrange
int itemsCount = 0;
final ArrayIterable<Boolean> iterator = ArrayIteratorFactory.ofRange(array, 11, 11);
// ...Act
while (iterator.hasNext()) { iterator.next(); itemsCount++; }
// ...Assert
assertThat(iterator.getCountFromRange(), is(itemsCount));
assertThat(1, is(itemsCount));
}
@Test
void testShouldCount9_OfRangeOne_To_Nine() {
// ...Arrange
int itemsCount = 0;
final ArrayIterable<Boolean> iterator = ArrayIteratorFactory.ofRange(array, 1, 9);
// ...Act
while (iterator.hasNext()) { iterator.next(); itemsCount++; }
// ...Assert
assertThat(iterator.getCountFromRange(), is(itemsCount));
assertThat(9, is(itemsCount));
}
@Test
void testShouldCount1_OfCount_One() {
// ...Arrange
int itemsCount = 0;
final ArrayIterable<Boolean> iterator = ArrayIteratorFactory.ofCount(array, 1);
// ...Act
while (iterator.hasNext()) { iterator.next(); itemsCount++; }
// ...Assert
assertThat(iterator.getCountFromRange(), is(itemsCount));
assertThat(1, is(itemsCount));
}
@Test
void testShouldCount1_OfFrst_Ten() {
// ...Arrange
int itemsCount = 0;
final ArrayIterable<Boolean> iterator = ArrayIteratorFactory.ofFirst(array, 10);
// ...Act
while (iterator.hasNext()) { iterator.next(); itemsCount++; }
// ...Assert
assertThat(iterator.getCountFromRange(), is(itemsCount));
assertThat(1, is(itemsCount));
}
@Test
void testShouldCount6_OfLast_Five() {
// ...Arrange
int itemsCount = 0;
final ArrayIterable<Boolean> iterator = ArrayIteratorFactory.ofLast(array, 5);
// ...Act
while (iterator.hasNext()) { iterator.next(); itemsCount++; }
// ...Assert
assertThat(iterator.getCountFromRange(), is(itemsCount));
assertThat(6, is(itemsCount));
}
}
|
package com.taim.content.mapper;
import com.taim.backendservice.model.Vendor;
import com.taim.content.model.VendorOverviewView;
public interface VendorOverviewMapper {
VendorOverviewView map(Vendor vendor);
}
|
package cn.xeblog.xechat.utils;
import java.util.UUID;
/**
* uuid工具类
*
* @author yanpanyi
* @date 2019/03/27
*/
public class UUIDUtils {
/**
* 生成uuid
*
* @return
*/
public static String create() {
return UUID.randomUUID().toString().replace("-", "");
}
}
|
package com.example.university.repo;
import com.example.university.dto.DegreeCount;
import com.example.university.model.Degree;
import com.example.university.model.Department;
import com.example.university.model.Lector;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.data.jpa.repository.Query;
import java.util.List;
import java.util.Set;
public interface LectorRepo extends JpaRepository<Lector, Long> {
@Query(value = "Select l from Lector l join l.department d where l.headOfDepartment = 1 and d.id = :departmentId")
Lector getDepartmentHeadByDepartment(Long departmentId);
@Query("SELECT new com.example.university.dto.DegreeCount(l.degree, COUNT(l.id)) "
+ "From Lector l join l.department d where d.id = :departmentId Group by l.degree")
List<DegreeCount> getStatisticCounts(Long departmentId);
@Query(value = "Select AVG(l.salary) from Lector l join l.department d where d.id = ?1 Group By d.id")
Double getAvgSalaryByDepartment(Long departmentId);
@Query(value = "Select Count(l.id) from Lector l join l.department d where d.id = ?1 Group By d.id")
Long getCountEmployeesByDepartment(Long departmentId);
@Query("Select l from Lector l where l.firstName like %?1% or l.surname like %?1%")
List<Lector> globalSearch(String template);
}
|
package org.dimigo.oop;
public class CarTest {
public static void main(String[] args) {
Car car[] = { new Car(), new Car(), new Car() };
car[0].setCompany("현대자동차");
car[0].setModel("제네시스");
car[0].setColor("검정색");
car[0].setMaxSpeed(225);
car[0].setPrice(50000000);
car[1].setCompany("기아자동차");
car[1].setModel("K7");
car[1].setColor("흰색");
car[1].setMaxSpeed(246);
car[1].setPrice(40000000);
car[2].setCompany("삼성자동차");
car[2].setModel("SM7");
car[2].setColor("회색");
car[2].setMaxSpeed(200);
car[2].setPrice(38000000);
System.out.println("<< 자동차 목록 >>");
for(int i=0;i<3;i++) {
System.out.println("제조사명 : " + car[i].getCompany());
System.out.println("모델명 : " + car[i].getModel());
System.out.println("색상 : " + car[i].getColor());
System.out.println("최대속도 : " + car[i].getMaxSpeed() + "km");
System.out.printf("가격 : %,d원", car[i].getPrice());
if(i==2) break;
System.out.println("\n");
}
}
}
|
package com.egova.eagleyes.util;
import com.egova.eagleyes.model.respose.PersonInfo;
import java.util.Comparator;
public class PersonLetterComparator implements Comparator<PersonInfo> {
@Override
public int compare(PersonInfo o1, PersonInfo o2) {
if (o1 == null || o2 == null) {
return 0;
}
String lhsSortLetters = o1.getFirstLetter().substring(0, 1).toUpperCase();
String rhsSortLetters = o2.getFirstLetter().substring(0, 1).toUpperCase();
return lhsSortLetters.compareTo(rhsSortLetters);
}
}
|
package ideablog.dao;
import ideablog.model.CloudFile;
import org.apache.ibatis.annotations.Param;
import org.springframework.stereotype.Repository;
import java.util.List;
@Repository
public interface ICloudFileDao {
CloudFile selectCloudFileById(long id);
List<CloudFile> selectAllCloudFiles();
List<CloudFile> selectCloudFilesByUserId(long userId);
List<CloudFile> selectFollowFilesByUserId(long userId);
Boolean insertCloudFiles(@Param("userId") Long userId, @Param("fileName") String fileName, @Param("fileSize") String fileSize, @Param("filePath") String filePath, @Param("upTime") String upTime);
Boolean switchStatusById(@Param("id") long id, @Param("status") int status);
Boolean deleteCloudFileById(long id);
}
|
package com.eveena.instantfix;
public class TupleFixFiller implements IFiller<TupleFixMessage> {
public void fill(TupleFixMessage msg, PairDataReader data) {
msg.setValue(data.readHeader(), data.readString());
}
public TupleFixMessage newObj() {
return new TupleFixMessage();
}
}
|
package Telas;
import java.awt.EventQueue;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.JButton;
import javax.swing.JCheckBox;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JTextField;
import javax.swing.border.EmptyBorder;
import gof.AplicativoFactory;
import gof.Arquivo;
import gof.Editor;
public class TelaAplicativo extends JFrame {
private JPanel contentPane;
private JTextField textField;
private JTextField textField_1;
private JLabel lblNome;
private JLabel lblPreco;
private JButton btnCriar;
private JLabel lblmsg;
private JTextField textField_2;
private JCheckBox chckbxNewCheckBox = new JCheckBox("Arquivo aceita cópia?");
private JLabel label;
public static void main(String[] args) {
EventQueue.invokeLater(new Runnable() {
public void run() {
try {
TelaAplicativo frame = new TelaAplicativo();
frame.setVisible(true);
} catch (Exception e) {
e.printStackTrace();
}
}
});
}
public TelaAplicativo() {
setTitle("App");
setResizable(false);
setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
setBounds(200, 200, 500, 300);
contentPane = new JPanel();
contentPane.setBorder(new EmptyBorder(5, 5, 5, 5));
setContentPane(contentPane);
contentPane.setLayout(null);
textField = new JTextField();
textField.setBounds(217, 12, 166, 20);
contentPane.add(textField);
textField.setColumns(10);
lblNome = new JLabel("Nome Aplicativo (*)");
lblNome.setBounds(10, 14, 151, 14);
contentPane.add(lblNome);
lblPreco = new JLabel("Nome Arquivo(*)");
lblPreco.setBounds(10, 52, 166, 18);
contentPane.add(lblPreco);
textField_1 = new JTextField();
textField_1.setBounds(217, 52, 166, 20);
contentPane.add(textField_1);
textField_1.setColumns(10);
btnCriar = new JButton("Abrir");
btnCriar.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
try{
String nome = textField.getText();
String nomeArquivo = textField_1.getText();
String path = textField_2.getText();
Boolean copia = chckbxNewCheckBox.isSelected();
Editor app = AplicativoFactory.getApp(nome);
Arquivo arq = app.criararquivo(nome, path,copia);
try {
arq.fazercopia(arq);
label.setText("Feito copia do arquivo");
} catch (Exception e2) {
label.setText(e2.getMessage());
}
lblmsg.setText("Aberto app "+nome+" com um novo arquivo "+nomeArquivo);
textField.setText("");
textField_1.setText("");
textField_2.setText("");
textField.requestFocus();
}
catch(Exception erro){
lblmsg.setText(erro.getMessage());
}
}
});
btnCriar.setBounds(149, 141, 115, 23);
contentPane.add(btnCriar);
lblmsg = new JLabel("");
lblmsg.setBounds(27, 221, 435, 14);
contentPane.add(lblmsg);
JLabel lblNomePath = new JLabel("Nome Path(*)");
lblNomePath.setBounds(10, 82, 166, 18);
contentPane.add(lblNomePath);
textField_2 = new JTextField();
textField_2.setColumns(10);
textField_2.setBounds(217, 84, 166, 20);
contentPane.add(textField_2);
chckbxNewCheckBox.setBounds(20, 109, 193, 23);
contentPane.add(chckbxNewCheckBox);
label = new JLabel("");
label.setBounds(37, 247, 435, 14);
contentPane.add(label);
}
}
|
package ch.bfh.bti7301.w2013.battleship.gui;
import javafx.application.Platform;
import javafx.event.ActionEvent;
import javafx.event.EventHandler;
import javafx.geometry.Bounds;
import javafx.geometry.Insets;
import javafx.geometry.Pos;
import javafx.scene.Group;
import javafx.scene.control.Button;
import javafx.scene.control.Label;
import javafx.scene.layout.VBox;
import javafx.scene.paint.Color;
import javafx.scene.text.Font;
public class ConfirmationDialog extends VBox {
private Boolean result;
public ConfirmationDialog(String message, String yes, String no) {
setPadding(new Insets(20));
setSpacing(8);
setStyle("-fx-background-color: #336699;");
Label l = new Label(message);
l.setTextFill(Color.WHITE);
l.setFont(new Font(20));
getChildren().add(l);
getChildren().add(getButton(yes, true));
getChildren().add(getButton(no, false));
}
private Button getButton(String label, final boolean result) {
Button b = new Button(label);
b.setMinWidth(150);
b.setMaxWidth(200);
b.setOnAction(new EventHandler<ActionEvent>() {
@Override
public void handle(ActionEvent arg0) {
ConfirmationDialog.this.result = result;
}
});
return b;
}
public static boolean waitForConfirmation(final Group root,
final String message, final String yes, final String no) {
final ConfirmationDialog[] dialog = { null };
Platform.runLater(new Runnable() {
@Override
public void run() {
ConfirmationDialog d = new ConfirmationDialog(message, yes, no);
Bounds rootBounds = root.getBoundsInLocal();
d.setMinWidth(rootBounds.getWidth());
d.setMaxWidth(rootBounds.getWidth());
d.setAlignment(Pos.CENTER);
d.relocate(rootBounds.getMinX(), (rootBounds.getHeight()
- d.getBoundsInParent().getHeight() - 100) / 2);
dialog[0] = d;
root.getChildren().add(d);
}
});
while (dialog[0] == null || dialog[0].result == null) {
try {
Thread.sleep(100);
} catch (InterruptedException e) {
// Ignore
}
}
Platform.runLater(new Runnable() {
@Override
public void run() {
root.getChildren().remove(dialog[0]);
}
});
return dialog[0].result;
}
}
|
package com.ipl.ipldashboard.respository;
import com.ipl.ipldashboard.model.Match;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.data.jpa.repository.Query;
import org.springframework.data.repository.CrudRepository;
import org.springframework.data.repository.query.Param;
import java.time.LocalDate;
import java.util.List;
public interface MatchRepository extends CrudRepository<Match,Long> {
List<Match> getByTeam1OrTeam2OrderByDateDesc(String teamName1, String teamName2, Pageable pageable);
@Query("select m from Match m where (m.team1=:teamName or m.team2=:teamName) and m.date between :startDate and :endDate order by date desc")
List<Match> getMatchesByTeamBetweenDates(@Param("teamName") String teamName,
@Param("startDate") LocalDate startDate,
@Param("endDate") LocalDate endDate);
//List<Match> getByTeam1AndDateBetweenOrTeam2AndDateBetweenOrderByDateDesc(String teamName1, String teamName2, LocalDate date1, LocalDate date2);
default List<Match> findLatestMatchesByTeam(String teamName,int count){
return getByTeam1OrTeam2OrderByDateDesc(teamName,teamName, PageRequest.of(0,count));
}
}
|
package com.lenovohit.ssm.base.web.rest;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import javax.servlet.http.HttpServletRequest;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import com.lenovohit.core.dao.Page;
import com.lenovohit.core.exception.BaseException;
import com.lenovohit.core.manager.impl.GenericManagerImpl;
import com.lenovohit.core.utils.DateUtils;
import com.lenovohit.core.utils.JSONUtils;
import com.lenovohit.core.utils.StringUtils;
import com.lenovohit.core.web.MediaTypes;
import com.lenovohit.core.web.utils.Result;
import com.lenovohit.core.web.utils.ResultUtils;
import com.lenovohit.ssm.base.model.Area;
import com.lenovohit.ssm.base.model.Machine;
import com.lenovohit.ssm.base.model.Model;
import com.lenovohit.ssm.base.model.Operator;
import com.lenovohit.ssm.base.model.Org;
import com.lenovohit.ssm.base.model.User;
@RestController
@RequestMapping("/ssm/base/machine")
public class MachineRestController extends SSMBaseRestController {
@Autowired
private GenericManagerImpl<Machine,String> machineManager;
@Autowired
private GenericManagerImpl<Area, String> areaManager;
@Autowired
private GenericManagerImpl<Model, String> modelManager;
@Autowired
private GenericManagerImpl<Org, String> orgManager;
@RequestMapping(value = "/page/{start}/{limit}", method = RequestMethod.GET, produces = MediaTypes.JSON_UTF_8)
public Result forPage(@PathVariable("start") String start, @PathVariable("limit") String limit,
@RequestParam(value = "data", defaultValue = "")String data){
Machine query = JSONUtils.deserialize(data, Machine.class);
StringBuilder jql = new StringBuilder( " from Machine where 1=1 ");
List<Object> values = new ArrayList<Object>();
if(!StringUtils.isEmpty(query.getName())){
jql.append(" and name like ? ");
values.add("%"+query.getName()+"%");
}
if(!StringUtils.isEmpty(query.getCode())){
jql.append(" and code like ? ");
values.add("%"+query.getCode()+"%");
}
if(!StringUtils.isEmpty(query.getMngName())){
jql.append(" and mngName like ? ");
values.add("%"+query.getMngName()+"%");
}
if(!StringUtils.isEmpty(query.getMac())){
jql.append(" and mac like ? ");
values.add("%"+query.getMac()+"%");
}
jql.append(" order by code ");
Page page = new Page();
page.setStart(start);
page.setPageSize(limit);
page.setQuery(jql.toString());
page.setValues(values.toArray());
machineManager.findPage(page);
return ResultUtils.renderPageResult(page);
}
@RequestMapping(value = "/list", method = RequestMethod.GET, produces = MediaTypes.JSON_UTF_8)
public Result forList(@RequestParam(value = "data", defaultValue = "") String data) {
List<Machine> machines = machineManager.find(" from Machine machine order by code");
return ResultUtils.renderSuccessResult(machines);
}
@RequestMapping(value = "/list/getCashboxOptions", method = RequestMethod.GET, produces = MediaTypes.JSON_UTF_8)
public Result forCashboxList(@RequestParam(value = "data", defaultValue = "") String data) {
List<Machine> machines = machineManager.find(" from Machine machine where cashbox = '1' order by hisUser");
return ResultUtils.renderSuccessResult(machines);
}
@RequestMapping(value="/create",method = RequestMethod.POST, produces = MediaTypes.JSON_UTF_8/*TEXT_PLAIN_UTF_8*/)
public Result forCreate(@RequestBody String data){
Machine machine = JSONUtils.deserialize(data, Machine.class);
User user = this.getCurrentUser();
Date now = new Date();
machine.setUpdateTime(now);
machine.setUpdateUser(user.getName());
machine.setRegTime(now);
machine.setRegUser(user.getName());
Model model = this.modelManager.get(machine.getModelId());
Org org = this.orgManager.get(machine.getMngId());
machine.setModelCode(model.getCode());
machine.setSupplier(model.getSupplier());
machine.setMngId(org.getId());
machine.setMngCode(org.getCode());
machine.setMngName(org.getName());
machine.setMngType(org.getType());
Machine saved = this.machineManager.save(machine);
return ResultUtils.renderSuccessResult(saved);
}
@RequestMapping(value="/login",method = RequestMethod.POST, produces = MediaTypes.JSON_UTF_8/*TEXT_PLAIN_UTF_8*/)
public Result forLogin(){
HttpServletRequest request = this.getRequest();
String mac = request.getHeader("mac");
List<Machine> machines = this.machineManager.find("from Machine where mac = ? ", mac);
if(machines.size() == 1 ){
Machine machine = machines.get(0);
return ResultUtils.renderSuccessResult(machine);
}
return null;
}
@RequestMapping(value="/register/{area}/{floor}",method = RequestMethod.POST, produces = MediaTypes.JSON_UTF_8)
public Result forRegiste(@PathVariable("floor") String floor, @PathVariable("area") String area, @RequestBody String data){
try {
Area building = areaManager.findOne(" from Area where code = ? ", area);
Area hospital = areaManager.get(building.getParent());
String address = hospital.getCode()+"-"+building.getCode()+"-"+floor;
String mac = this.getMacAddr();
String ip = this.getIpAddr();
List<Machine> machines = this.machineManager.find("from Machine where mac = ? ", mac);
Machine machine = null;
if(machines.size() > 1 ){
return ResultUtils.renderFailureResult("重复注册");
}else if(machines.size() == 1 ) {
Machine param = JSONUtils.deserialize(data, Machine.class);
machine = machines.get(0);
machine.setCode(param.getCode());
machine.setName (param.getName());
machine.setMngCode(param.getMngCode());
machine.setMngName(param.getMngName());
machine.setCashbox(param.getCashbox());
machine.setHisUser(param.getHisUser());
machine.setAddress(address);
} else {
machine = JSONUtils.deserialize(data, Machine.class);
}
if(StringUtils.isEmpty(machine.getHisUser())){
machine.setHisUser("0001");
}
machine.setHospitalNo(hospital.getCode());
machine.setHospitalName(hospital.getName());
machine.setIp(ip);
machine.setMac(mac);
Operator user = this.getCurrentOperator();
machine.setUpdateTime(DateUtils.getCurrentDate());
machine.setUpdateUser(user.getName());
machine.setRegTime(DateUtils.getCurrentDate());
if(StringUtils.isEmpty(machine.getRegUser())){
machine.setRegUser(user.getName());
}
Machine saved = this.machineManager.save(machine);
return ResultUtils.renderSuccessResult(saved);
} catch (Exception e) {
e.printStackTrace();
return ResultUtils.renderFailureResult();
}
}
@RequestMapping(value="/update",method = RequestMethod.POST, produces = MediaTypes.JSON_UTF_8/*TEXT_PLAIN_UTF_8*/)
public Result forUpdate(@RequestBody String data){
Machine machine = JSONUtils.deserialize(data, Machine.class);
Machine model = this.machineManager.get(machine.getId());
Model model2 = this.modelManager.get(machine.getModelId());
Org org = this.orgManager.get(machine.getMngId());
machine.setDetails(model.getDetails());
machine.setUpdateTime(DateUtils.getCurrentDate());
machine.setUpdateUser(this.getCurrentUser().getName());
machine.setModelCode(model2.getCode());
machine.setSupplier(model2.getSupplier());
machine.setMngId(org.getId());
machine.setMngCode(org.getCode());
machine.setMngName(org.getName());
machine.setMngType(org.getType());
Machine saved = this.machineManager.save(machine);
return ResultUtils.renderSuccessResult(saved);
}
@RequestMapping(value = "/remove/{id}",method = RequestMethod.DELETE, produces = MediaTypes.JSON_UTF_8)
public Result forDelete(@PathVariable("id") String id){
try {
this.machineManager.delete(id);
} catch (Exception e) {
throw new BaseException("删除失败");
}
return ResultUtils.renderSuccessResult();
}
@SuppressWarnings("rawtypes")
@RequestMapping(value = "/removeAll",method = RequestMethod.DELETE, produces = MediaTypes.JSON_UTF_8)
public Result forDeleteAll(@RequestBody String data){
List ids = JSONUtils.deserialize(data, List.class);
StringBuilder idSql = new StringBuilder();
List<String> idvalues = new ArrayList<String>();
try {
idSql.append("DELETE FROM HCP_ROLE WHERE ID IN (");
for(int i = 0 ; i < ids.size() ; i++) {
idSql.append("?");
idvalues.add(ids.get(i).toString());
if(i != ids.size() - 1) idSql.append(",");
}
idSql.append(")");
this.machineManager.executeSql(idSql.toString(), idvalues.toArray());
} catch (Exception e) {
e.printStackTrace();
throw new BaseException("删除失败");
}
return ResultUtils.renderSuccessResult();
}
public String ObjectIsNull(Object obj) {
if (obj == null)
return "";
return obj.toString();
}
}
|
package com.jiacaizichan.baselibrary.activity;
import android.content.Context;
import android.content.pm.ActivityInfo;
import android.content.res.Resources;
import android.graphics.Color;
import android.graphics.drawable.Drawable;
import android.os.Build;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.Toolbar;
import android.text.TextUtils;
import android.view.KeyCharacterMap;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewConfiguration;
import android.view.WindowManager;
import android.widget.FrameLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;
import com.afollestad.materialdialogs.MaterialDialog;
import com.github.ybq.android.spinkit.SpinKitView;
import com.github.ybq.android.spinkit.style.DoubleBounce;
import com.github.ybq.android.spinkit.style.ThreeBounce;
import com.jaeger.library.StatusBarUtil;
import com.jiacaizichan.baselibrary.R;
import com.jiacaizichan.baselibrary.utils.ActivityLink;
import com.jiacaizichan.baselibrary.utils.SharedPreferencesUtil;
import butterknife.ButterKnife;
import butterknife.Unbinder;
public abstract class BaseActivity extends AppCompatActivity implements View.OnClickListener {
public Unbinder bind;
public Toolbar mToolBar;
public FrameLayout mFlContent;
private TextView mTvTitle;
private TextView mTvDecs;
public SpinKitView myProgressBar;
public Context context;
private RelativeLayout mRv;
public String sessionId;
public boolean isLogin;
//tollBar左边icon的点击事件
public OnClickListener onClickListener;
public OnClickListenerRight onClickListenerRight;
public Toast toast;
public MaterialDialog dialog;
public boolean isLogin() {
return isLogin;
}
public String getSessionId() {
return sessionId;
}
@Override
protected void onCreate(Bundle savedInstanceState) {
// if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT&&Build.VERSION.SDK_INT<Build.VERSION_CODES.LOLLIPOP) {
// getWindow().addFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS);
// getWindow().addFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_NAVIGATION);
// }
// setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);
setOrientation();
super.onCreate(savedInstanceState);
ActivityLink.addActivity(this);
// ActivityLink.getInstence().addActivity(this);
setContentView(R.layout.activity_base);
initView();
initConfig();
init(savedInstanceState);
}
public void setOrientation(){
setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);
}
public void hindProgressBar(){
mRv.setVisibility(View.GONE);
// if (dialog!=null){
// dialog.dismiss();
// }
}
public void showProgressBar(){
// dialog.show();
if (mRv.getVisibility()!=View.GONE){
return;
}
mRv.setVisibility(View.VISIBLE);
mRv.setFocusable(true);
mRv.setClickable(true);
mRv.setOnClickListener(this);
}
/**
* 初始化配置baseActivity的配置
*/
private void initConfig() {
sessionId = (String) SharedPreferencesUtil.getParam(context,"sessionId","");
isLogin = (boolean) SharedPreferencesUtil.getParam(context,"isLogin",false);
}
/**
* 显示Toast
* @param content
*/
protected void showToast(String content){
if (toast == null) {
toast = Toast.makeText(context, content, Toast.LENGTH_SHORT);
} else {
toast.setText(content);
}
toast.show();
}
public void setToolBarDecs(String value, Drawable drawable, final OnClickListenerRight onClickListener){
this.onClickListenerRight = onClickListener;
mTvDecs.setVisibility(View.VISIBLE);
mTvDecs.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
if (onClickListenerRight!=null){
onClickListenerRight.onClick();
}
}
});
mTvDecs.setText(value);
mTvDecs.setCompoundDrawablesWithIntrinsicBounds(null,null,drawable,null);
}
public void setToolBarDecs(String value, Drawable drawable,String color, final OnClickListenerRight onClickListener){
this.onClickListenerRight = onClickListener;
mTvDecs.setVisibility(View.VISIBLE);
mTvDecs.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
if (onClickListenerRight!=null){
onClickListenerRight.onClick();
}
}
});
mTvDecs.setText(value);
mTvDecs.setTextColor(Color.parseColor(color));
mTvDecs.setCompoundDrawablesWithIntrinsicBounds(null,null,drawable,null);
}
/**
* 初始化baseActivity的控件和
*/
private void initView() {
// dialog = new MaterialDialog.Builder(this)
// .customView(R.layout.layout_logding,false)
// .build();
context = getApplicationContext();
mTvDecs = findViewById(R.id.base_ac_toolbar_tv_decs);
mToolBar = findViewById(R.id.base_ac_toolbar);
mRv = findViewById(R.id.base_ac_rl_pb);
mFlContent = findViewById(R.id.base_ac_fl_content);
mTvTitle = findViewById(R.id.base_ac_toolbar_tv_title);
// myProgressBar = findViewById(R.id.base_ac_pb);
// ThreeBounce threeBounce = new ThreeBounce();
// threeBounce.setColor(Color.parseColor("#2BDCC5"));
// myProgressBar.setIndeterminateDrawable(threeBounce);
setSupportActionBar(mToolBar);
getSupportActionBar().setDisplayShowTitleEnabled(false);
//获取虚拟键的高度
// navigation = getNavigationBarHeight();
// navigation = screenUtils.getNavigationBarHeight();
//获取状态栏的高度
// int statusBarHeight = screenUtils.getStatusBarHeight();
// getWindow().getDecorView().findViewById(android.R.id.content).setPadding(0,statusBarHeight,0,navigation);
LayoutInflater.from(this).inflate(getContentView(), mFlContent);
bind = ButterKnife.bind(this);
hindProgressBar();
if (Build.VERSION.SDK_INT>=Build.VERSION_CODES.M){
StatusBarUtil.setColorNoTranslucent(BaseActivity.this, Color.parseColor("#ffffff"));
getWindow().getDecorView().setSystemUiVisibility( View.SYSTEM_UI_FLAG_LIGHT_STATUS_BAR);
}else {
StatusBarUtil.setColorNoTranslucent(BaseActivity.this, Color.parseColor("#2BDCC5"));
mToolBar.setBackgroundColor(Color.parseColor("#2BDCC5"));
}
}
public void setToolbarBg(String color){
mToolBar.setBackgroundColor(Color.parseColor(color));
}
public abstract void init(Bundle savedInstanceState);
protected abstract int getContentView();
protected void setLeftIcon(int icon,OnClickListener onClickListener){
mToolBar.setNavigationIcon(icon);
this.onClickListener = onClickListener;
}
public void setToolBarTitle(String title){
mTvTitle.setText(title);
}
public void setToolBarTitle(String title,String color,float size){
mTvTitle.setText(title);
mTvTitle.setTextColor(Color.parseColor(color));
mTvTitle.setTextSize(size);
}
@Override
protected void onDestroy() {
super.onDestroy();
ActivityLink.removeActivity(this);
bind.unbind();
}
/**
* 显示toolbar
*/
public void showToolBar(){
mToolBar.setVisibility(View.VISIBLE);
}
/**
* 隐藏toolbar
*/
public void hindToolBar(){
mToolBar.setVisibility(View.GONE);
}
/**
* 获取虚拟减半的高度
* @return
*/
private int getNavigationBarHeight() {
boolean hasMenuKey = ViewConfiguration.get(this).hasPermanentMenuKey();
boolean hasBackKey = KeyCharacterMap.deviceHasKey(KeyEvent.KEYCODE_BACK);
if (!hasBackKey&&!hasMenuKey){
Resources resources = getResources();
int identifier = resources.getIdentifier("navigation_bar_height", "dimen", "android");
return resources.getDimensionPixelSize(identifier);
}
return 0;
}
/**
* 既可以自定义返回按键的时间--为null时默认执行finish操作
* @param item
* @return
*/
@Override
public boolean onOptionsItemSelected(MenuItem item) {
if (item.getItemId()==android.R.id.home){
if (onClickListener!=null){
onClickListener.onClick();
}else{
finish();
}
}
return true;
}
@Override
public void onClick(View v) {
}
public interface OnClickListener{
void onClick();
}
public interface OnClickListenerRight{
void onClick();
}
}
|
package f.star.iota.milk.ui.threeycy.ycy;
import org.jsoup.Jsoup;
import org.jsoup.nodes.Element;
import org.jsoup.select.Elements;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import f.star.iota.milk.Net;
import f.star.iota.milk.base.PVContract;
import f.star.iota.milk.base.StringPresenter;
public class ThreeYCYPresenter extends StringPresenter<List<ThreeYCYBean>> {
public ThreeYCYPresenter(PVContract.View view) {
super(view);
}
@Override
protected List<ThreeYCYBean> dealResponse(String s, HashMap<String, String> headers) {
List<ThreeYCYBean> list = new ArrayList<>();
Elements select = Jsoup.parseBodyFragment(s).select("body > div.pageWide.center > div.postList > div.postItem");
for (Element element : select) {
ThreeYCYBean bean = new ThreeYCYBean();
String preview = element.select("div.postThumb.floatLeft > a > img").attr("src");
bean.setPreview(Net.THREEYCY_BASE + preview);
String url = element.select("div.postThumb.floatLeft > a").attr("href");
bean.setUrl(Net.THREEYCY_BASE + url);
bean.setHeaders(headers);
String description = element.select("h3 > a").text();
bean.setDescription(description);
String date = element.select("div.postSubtitle").text();
bean.setDate(date);
list.add(bean);
}
return list;
}
}
|
package com.example.yandextest;
public class History {
private int _id;
private String _name;
public History(){}
public History(final String _name) {
this._name = _name;
}
public int get_id(){
return _id;
}
public void set_id(final int _id){
this._id = _id;
}
public String get_name(){
return _name;
}
public void set_name(final String _name){
this._name = _name;
}
}
|
import javax.xml.parsers.*;
import org.xml.sax.SAXException;
import org.w3c.dom.*;
import datastructures.DefaultBinaryTree;
import datastructures.DefaultBinaryTreeNode;
import java.io.*;
/**
* parses the xml file into a binary tree
* @author Pooja Kundaje
*
*/
public class TreeFileReader {
//private static DefaultBinaryTree<String> tree;
public static DefaultBinaryTree<String> tree;
/**
* Creates a document which takes the XML file and parses it into something
* that can be read by the program. try/catch blocks to prevent exceptions
* from crashing the program.
*/
public TreeFileReader(){
try {
//Setup XML Document,
DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
DocumentBuilder builder = factory.newDocumentBuilder();
File xmlFile = new File( "20_Questions.xml");
Document document = builder.parse( xmlFile );
parseFounderFile( document );
} catch (ParserConfigurationException pce) {
//what to do if this exception happens
System.out.println(pce);
} catch (SAXException saxe) {
//what to do if this exception happens
System.out.println(saxe);
} catch (IOException ioe) {
//what to do if this exception happens
System.out.println(ioe);
}
}
/**
* Navigates through the major document structure, calls parseNode and passes in the
* root node of the document
* @param document
*/
private static void parseFounderFile( Document document ){
tree= new DefaultBinaryTree<String>();
Element docRoot = document.getDocumentElement();
tree.setRoot(parseQuestionNode(docRoot));
System.out.println(tree.preorderTraversal().toString());
}
/**
* Recursive method that is called on all question nodes in the document, including child nodes.
* @param n
* @return newNode
*/
private static DefaultBinaryTreeNode<String> parseQuestionNode(Element n){
if(n.getTagName().equals("question")){
DefaultBinaryTreeNode<String> newNode= new DefaultBinaryTreeNode<String>();
newNode.setData(n.getAttribute("id"));
if(n.hasChildNodes()){
//the list of children nodes
NodeList child = n.getChildNodes();
//run a for loop through the list
for(int i=0; i<child.getLength(); i++){
if(child.item(i) instanceof Element){
//checks if childNode has the nodeType Element
Element childElement= (Element)child.item(i);
if(childElement.getAttribute("userAns").equals("yes")){
//gets the left child of the node if "yes"
newNode.setLeftChild(parseAnswerNode(childElement));
}
else {
//gets the left child of the node if "no"
newNode.setRightChild(parseAnswerNode(childElement));
}
}
}
}
return newNode;
}
return null;
}
/**
* Recursive method that is called on all leaf nodes in the document, including child nodes.
* @param n
* @return leafNode
*/
private static DefaultBinaryTreeNode<String> parseAnswerNode(Element n) {
// DefaultBinaryTreeNode<String> newNode= new DefaultBinaryTreeNode<String>();
DefaultBinaryTreeNode<String> leafNode= new DefaultBinaryTreeNode<String>();
if(n.getTagName().equals("answer")){
if(n.hasChildNodes()){
//the list of children nodes
NodeList child = n.getChildNodes();
//run a for loop through the list
for(int i=0; i<child.getLength(); i++){
//checks if childNode has the nodeType Element
if( child.item(i) instanceof Element){
Element childEl= (Element)child.item(i);
//if the tag name is guess, create a leaf node and print the text
if(childEl.getTagName().equals("guess")){
leafNode.setData(childEl.getAttribute("text"));
}
else{
//if its a question call parseQuestionNode
leafNode= parseQuestionNode(childEl);
}
}
}
}
}
return leafNode;
}
/**
* gets the tree
* @return tree
*/
public DefaultBinaryTree<String> getTree(){
return tree;
}
}
|
package com.codingchili.social.model;
import java.util.*;
import com.codingchili.core.context.CoreContext;
/**
* @author Robin Duda
* <p>
* Tracks accounts that are online for friendlists and chat.
*/
public class OnlineDB {
private CoreContext context;
private Map<String, Set<String>> connected = new HashMap<>();
/**
* @param context creates the database for the given context.
*/
public OnlineDB(CoreContext context) {
this.context = context;
}
/**
* Adds a new account to the online database. If the account already is online
* then the realm will be added to their online presence.
*
* @param account the account to indicate as online.
* @param realm the realm for which the account is online.
*/
public void add(String account, String realm) {
connected.computeIfAbsent(account, key -> new HashSet<>());
connected.get(account).add(realm);
}
/**
* Removes an accounts online presence from the given realm.
*
* @param account the account to be removed.
* @param realm the realm that the account is to be removed from.
*/
public void remove(String account, String realm) {
Set<String> realms = connected.getOrDefault(account, new HashSet<>());
realms.remove(realm);
if (realms.isEmpty()) {
connected.remove(account);
} else {
connected.put(account, realms);
}
}
/**
* @param account the account to check if online or not.
* @return true if the account is online on at least one realm.
*/
public boolean is(String account) {
return connected.containsKey(account);
}
/**
* Retrieves a set of all of the realms that the given account is considered online for.
*
* @param account the account to retrieve the online realms for.
* @return a set of realm names.
*/
public Set<String> realms(String account) {
return connected.getOrDefault(account, new HashSet<>());
}
}
|
package com.joalib.DAO;
import java.io.IOException;
import java.io.Reader;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.util.ArrayList;
import java.util.List;
import java.util.Scanner;
import org.apache.ibatis.io.Resources;
import org.apache.ibatis.session.SqlSession;
import org.apache.ibatis.session.SqlSessionFactory;
import org.apache.ibatis.session.SqlSessionFactoryBuilder;
import com.joalib.DTO.BoardDTO;
import com.joalib.DTO.Board_CommentDTO;
import com.joalib.DTO.Board_Small_CommentDTO;
import com.joalib.DTO.SearchDTO;
import com.joalib.DTO.member_alarmDTO;
import com.joalib.DTO.memberinfoDTO;
import com.joalib.DTO.BoardDTO;
public class DAO {
SqlSessionFactory sqlfactory;
////////////////////// �뜝�룞�삕�겢�뜝�룞�삕�뜝�룞�삕�뜝�룞�삕 //////////////////////
private static DAO instance;
//static�뜝�룞�삕 �뜝�뙠�벝�삕�뜝占�! �뜝�뙐�뼲�삕�뜝�룞�삕髥��뜝占�. �뜝�룞�삕�뜝�룞�삕 �뜝�룞�삕�뜝�룞�삕
public static DAO getinstance() {
if (instance == null) { // >DAO �뜝�룞�삕泥� �뜝�룞�삕�뜝�룞�삕�뜝�룞�삕 �뜝�뙇�뼲�삕?
synchronized (DAO.class) {
instance = new DAO();
}
}
return instance;
}
public DAO(){
try {
Reader reader = Resources.getResourceAsReader("com/joalib/DAO/mybatis_test-config.xml"); //xml �뜝�룞�삕�뜝�룞�삕
sqlfactory = new SqlSessionFactoryBuilder().build(reader); //batis�뜝�룞�삕 �뜝�룞�삕�뜝�룞�삕�뜝�떦�뙋�삕 �뜝�룞�삕�뜝�룞�삕.
} catch (IOException e) {
e.printStackTrace();
}
}
////////////////////////////////////////////////////////////////
//board
public List<BoardDTO> select_board_all() { //�뜝�룞�삕泥닷뜝�룞�삕 �뜝�떛�븘�슱�삕�뜝�룞�삕
getinstance();
SqlSession sqlsession = sqlfactory.openSession();
List <BoardDTO> list = sqlsession.selectList("board_all");
sqlsession.commit();
sqlsession.close();
return list;
}
public int select_board_total() { //�뜝�떬寃뚯떆諭꾩삕 �뜝�룞�삕�뜝�룞�삕
getinstance();
SqlSession sqlsession = sqlfactory.openSession();
int total = sqlsession.selectOne("board_count");
sqlsession.commit();
sqlsession.close();
return total;
}
public int hitUp(int board_no) {
SqlSession sqlsession = sqlfactory.openSession();
int i = sqlsession.update("board_hitUp", board_no);
sqlsession.commit();
sqlsession.close();
return i;
}
public BoardDTO read_details(int board_no) {
SqlSession sqlsession = sqlfactory.openSession();
BoardDTO dto = new BoardDTO();
dto = sqlsession.selectOne("read_details", board_no);
sqlsession.commit();
sqlsession.close();
return dto;
}
public int myinsert(BoardDTO dto) {
SqlSession sqlsession = sqlfactory.openSession();
int i = sqlsession.insert("board_add", dto);
sqlsession.commit();
sqlsession.close();
return i;
}
public int board_del(int board_no) {
SqlSession sqlsession = sqlfactory.openSession();
sqlsession.delete("board_del3", board_no); //답글삭제
sqlsession.delete("board_del2", board_no); //댓글삭제
int i = sqlsession.delete("board_del", board_no); //게시글 삭제
sqlsession.commit();
sqlsession.close();
return i;
}
public int board_update(BoardDTO article) {
SqlSession sqlsession = sqlfactory.openSession();
int i = sqlsession.update("board_update", article);
sqlsession.commit();
sqlsession.close();
return i;
}
//�뜝�룞�삕�뜝�룞�삕�뜝�뙃�룞�삕�뜝�룞�삕 �뜝�룞�삕�뜝占� �뜝�뙥怨ㅼ삕
public int boardCommnetAdd(Board_CommentDTO dto) {
SqlSession sqlsession = sqlfactory.openSession();
int i = sqlsession.insert("boardComment_add", dto) ;
sqlsession.commit();
sqlsession.close();
return i;
}
//�뜝�룞�삕�뜝�룞�삕�뜝�뙃�룞�삕�뜝�룞�삕 �뜝�룞�삕�뜝占� �뜝�룞�삕�뜝�룞�삕�듃
public List<Board_CommentDTO> boardCommentList(int board_no) {
SqlSession sqlsession = sqlfactory.openSession();
List<Board_CommentDTO> list = sqlsession.selectList("boardComment_list", board_no) ;
sqlsession.commit();
sqlsession.close();
return list;
}
//댓글 삭제 함수
public int boardCommentDel(Board_CommentDTO dto) {
SqlSession sqlsession = sqlfactory.openSession();
int i = sqlsession.delete("boardComment_delete2", dto); //답글 삭제
if(i > 0) {
sqlsession.delete("boardCommentAlarm_delete2", dto); }
i = sqlsession.delete("boardComment_delete1", dto); //댓글 삭제
if(i > 0) {
sqlsession.delete("boardCommentAlarm_delete1", dto); }
sqlsession.commit();
sqlsession.close();
return i;
}
//�뜝�룞�삕�뜝�룞�삕�뜝�뙃�룞�삕�뜝�룞�삕 �뜝�룞�삕�뜝占� �뜝�룞�삕�뜝�룞�삕
public int boardCommentUpdate(Board_CommentDTO dto) {
SqlSession sqlsession = sqlfactory.openSession();
int i = sqlsession.update("boardComment_update", dto);
sqlsession.commit();
sqlsession.close();
return i;
}
//�뜝�룞�삕�뜝�룞�삕 �뜝�룞�삕 �뜝�룞�삕 �뜝�룞�삕�뜝�룞�삕
public List<BoardDTO> myBoardView (String member_id) {
SqlSession sqlsession = sqlfactory.openSession();
List<BoardDTO> list = sqlsession.selectList("myBoardView",member_id);
sqlsession.commit();
sqlsession.close();
return list;
}
//�뜝�뙃�떆諭꾩삕�뜝�룞�삕 �뜝�룞�삕�뜝占� �뜝�룞�삕�뜝�룞�삕
public int CommnetCount(int board_no){
getinstance();
SqlSession sqlsession = sqlfactory.openSession();
int count = sqlsession.selectOne("boardCommentCount",board_no);
sqlsession.commit();
sqlsession.close();
return count;
}
///
public int boardSmallCommentAdd(Board_Small_CommentDTO dto) {
SqlSession sqlsession = sqlfactory.openSession();
int i = sqlsession.insert("boardSmallCommentAdd", dto);
sqlsession.commit();
sqlsession.close();
return i;
}
public List<Board_Small_CommentDTO> boardSmallCommentList(int donate_comment_no){
SqlSession sqlsession = sqlfactory.openSession();
List<Board_Small_CommentDTO> dto = sqlsession.selectList("boardSmallCommentList", donate_comment_no);
sqlsession.commit();
sqlsession.close();
return dto;
}
public int boardSmallCommentDelete(Board_Small_CommentDTO dto) {
SqlSession sqlsession = sqlfactory.openSession();
int i = sqlsession.delete("boardSmallCommentDelete", dto);
if(i > 0) {
sqlsession.delete("boardSmallCommentAlarmDelete", dto); //알람삭제
}
sqlsession.commit();
sqlsession.close();
return i;
}
public int boardSmallCommentChange(Board_Small_CommentDTO dto) {
SqlSession sqlsession = sqlfactory.openSession();
int i = sqlsession.update("boardSmallCommentChange", dto);
sqlsession.commit();
sqlsession.close();
return i ;
}
public int commentAlarmAdd(member_alarmDTO dto, String sort) {
SqlSession sqlsession = sqlfactory.openSession();
int i = 0;
//
if(sort.equals("boardComment")) {
i = sqlsession.insert("boardCommentAlarmAdd", dto);
}else if(sort.equals("boardSmallComment")) {
i = sqlsession.insert("boardSmallCommentAlarmAdd", dto);
}
sqlsession.commit();
sqlsession.close();
return i;
}
}
|
/**
* Created by riddle on 5/2/17.
* Code by Samya: Hope it is correct.
*/
package com.company;
import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import org.jdom2.Attribute;
import org.jdom2.Document;
import org.jdom2.Element;
import org.jdom2.JDOMException;
import org.jdom2.input.SAXBuilder;
import org.jdom2.output.Format;
import org.jdom2.output.XMLOutputter;
public class Unification {
/**
* Global variables
* Result- for storing result in ruleml format
* fail- to keep track of failure
* map - for mapping corresponding substitutions
*/
public Element result = new Element ("Substitution");
public boolean fail= false;
public HashMap<String,Element> map = new HashMap<String,Element>();
/**
* CheckVarInPat - for finding the variable is present in the pattern or not
* 1st argument - should be a variable
* 2nd argument - should be a pattern(cannot just be a variable)
*/
public static boolean CheckVarInPat(Element var, Element pat){
if(pat.getName().equals("Var")){
if(var.getText().equals(pat.getText()))
return true;
else
return false;
}
else{
List<Element> Children= pat.getChildren();
boolean result= false;
for(int i=0;i<Children.size();++i){
result= result || CheckVarInPat(var,Children.get(i));
}
return result;
}
}
/**
* unify - takes two patterns as input, applies unifiaction algorithm
* @throws IOException
*
*/
public void unify(Element pat1, Element pat2) throws IOException{
// System.out.println("-------------------------------");
// pat1.detach();
// printResult(pat1);
// pat1.detach();
// System.out.println("*****************");
// pat2.detach();
// printResult(pat2);
// pat2.detach();
// System.out.println("-------------------------------");
if(fail==true)
return;
else if("Var".equals(pat1.getName())){
if(map.containsKey(pat1.getText())){
Element e=map.get(pat1.getText());
unify(e,pat2);
return;
}
else if(CheckVarInPat(pat1,pat2) && !"Var".equals(pat2.getName())){
System.out.println(pat1.getName()+ "-4--"+ pat2.getName());
fail=true;
return;
}
else if("Var".equals(pat2.getName()) && pat1.getText().equals(pat2.getText()))
return;
else{
map.put(pat1.getText(),pat2);
// System.out.println(pat2.getChildren().size());
//printResult(pat2);
pat1.detach();
}
}
else if("Var".equals(pat2.getName())){
if(map.containsKey(pat2.getText())){
Element e=map.get(pat2.getText());
unify(e,pat1);
return;
}
else if(CheckVarInPat(pat2,pat1) && !"Var".equals(pat1.getName())){
System.out.println(pat1.getName()+ "--3--"+ pat2.getName());
fail=true;
return;
}
else if("Var".equals(pat1.getName()) && pat2.getText().equals(pat1.getText()))
return;
else{
map.put(pat2.getText(),pat1);
//
}
}
else{
String patName1= pat1.getName();
String patName2= pat2.getName();
if(patName1.equals(patName2) && ("Rel".equals(patName1) || "Ind".equals(patName1))){
if(pat1.getText().equals(pat2.getText()))
return ;
else{
fail= true;
return;
}
}
else if(patName1.equals(patName2)){
List<Element> Children1 = pat1.getChildren();
List<Element> Children2 = pat2.getChildren();
if(Children1.size()==Children2.size()){
for(int temp=Children2.size()-1;temp>=0;--temp){
Element c1= Children1.get(temp);
Element c2= Children2.get(temp);
//c1.detach();
//c2.detach();
unify(c1,c2);
}
}
else{
fail=true;
return;
}
}
else{
fail=true;
return;
}
}
}
/**
*
* unification- takes two files names(full path of file should be passed) , parses it and calls the unify method.
* if you have two documents already parsed in memory, you can use unify method directly
*/
public void unification(String filename1, String filename2){
try{
File inputFile = new File(filename1);
SAXBuilder saxBuilder = new SAXBuilder();
Document document = saxBuilder.build(inputFile);
Element root = document.getRootElement();
File inputFile1 = new File(filename2);
SAXBuilder saxBuilder1 = new SAXBuilder();
Document document1 = saxBuilder.build(inputFile1);
Element root1 = document1.getRootElement();
unify(root1,root);
computeResult();
printResult();
}catch(JDOMException e){
e.printStackTrace();
}catch(IOException ioe){
ioe.printStackTrace();
}
}
/**
* ComputeResult- puts all the substitutions in hashmap in proper ruleml format
* @throws IOException
*/
public void computeResult() throws IOException{
if(fail)
System.out.println("Failed");
else{
Iterator<String> it = map.keySet().iterator();
while(it.hasNext()){
String key= it.next();
Element e= new Element("Pair");
Element v= new Element("Var");
Element p= map.get(key);
p.detach();
v.setText(key);
e.addContent(v);
e.addContent(p);
result.addContent(e);
}
}
}
/**
* printResult - prints result in xml format, only for debugging purpose.
*/
public void printResult() throws IOException{
Document doc = new Document(result);
XMLOutputter xmlOutput = new XMLOutputter();
xmlOutput.setFormat(Format.getPrettyFormat());
xmlOutput.output(doc, System.out);
//doc.getRootElement().addContent(result);
}
public static void printResult(Element e) throws IOException{
Document doc = new Document(e);
XMLOutputter xmlOutput = new XMLOutputter();
xmlOutput.setFormat(Format.getPrettyFormat());
xmlOutput.output(doc, System.out);
//doc.getRootElement().addContent(result);
}
// public static void main(String[] args){
//
// unification("input2.txt","input21.txt");
// }
}
|
package com.example.lubabaislam.scavangerhunt.DataObjects;
/**
* Created by lubaba.islam on 6/11/2016.
*/
public class Clue {
private String mClue;
private int mId;
public static final String KEY="userCurrentClue";
public Clue(String mClue, int mId) {
this.mClue = mClue;
this.mId = mId;
}
public String getmClue() {
return mClue;
}
public int getmId() {
return mId;
}
}
|
package com.example.demo.exceptions;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import static java.util.Optional.ofNullable;
/**
* ExceptionHandler to handle all {@link QuestionsException} thrown by all components.
* @author Narasimha Reddy Guthireddy
*/
@ControllerAdvice
public class QuestionsExceptionHandler {
private static final Logger log = LoggerFactory.getLogger(QuestionsExceptionHandler.class);
/** ControlleAdvice to handle all {@link QuestionsException} throws by the components.
* @param ex {@link QuestionsException} thrown by the api.
* @return ResponseEntity of type {@link QuestionsErrorResponse} to send to the user.
*/
@ExceptionHandler(QuestionsException.class)
public ResponseEntity<?> handleApiException(QuestionsException ex) {
log.error(ex.getMessage());
return new ResponseEntity(
QuestionsErrorResponse.builder()
.errorCode(ex.getErrorCode())
.message(ex.getMessage())
.description(ofNullable(ex.getCause())
.map(cause -> cause.getLocalizedMessage())
.orElse(ex.getMessage())
)
.build(),
ex.getStatus());
}
/** ControlleAdvice to handle all other unknown exceptions thrown by the api.
* @param ex {@link Exception} thrown by the api.
* @return ResponseEntity of type {@link QuestionsErrorResponse} to send to the user with
* {@link HttpStatus#INTERNAL_SERVER_ERROR}
*/
@ExceptionHandler(Exception.class)
public ResponseEntity<?> handleAllExceptions(Exception ex) {
log.error(ex.getMessage());
return new ResponseEntity(
QuestionsErrorResponse.builder()
.errorCode("ERROR000")
.message(ex.getMessage())
.description("Unknown exception occurred while processing the request.")
.build(),
HttpStatus.INTERNAL_SERVER_ERROR);
}
}
|
package com.zevzikovas.aivaras.terraria.repositories;
import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;
import com.zevzikovas.aivaras.terraria.R;
import com.zevzikovas.aivaras.terraria.models.Spears;
import java.util.ArrayList;
import java.util.List;
public class SpearsRepository {
private static final String TABLE_NAME = "spears";
private static final String ID = "id";
private static final String NAME = "name";
private static final String PICTURE = "picture";
private static final String DAMAGE = "damage";
private static final String KNOCKBACK = "knockback";
private static final String CRITICAL_CHANCE = "critical_chance";
private static final String USE_TIME = "use_time";
private static final String VELOCITY = "velocity";
private static final String TOOLTIP = "tooltip";
private static final String GRANTS_BUFF = "grants_buff";
private static final String INFLICTS_DEBUFF = "inflicts_debuff";
private static final String RARITY = "rarity";
private static final String BUY_PRICE = "buy_price";
private static final String SELL_PRICE = "sell_price";
private SQLiteOpenHelper dbHelper;
public SpearsRepository(SQLiteOpenHelper dbHelper) {
this.dbHelper = dbHelper;
}
public void create(SQLiteDatabase db) {
db.execSQL(
"CREATE TABLE " + TABLE_NAME + " (" +
ID + " INTEGER PRIMARY KEY," +
NAME + " TEXT," +
PICTURE + " INTEGER," +
DAMAGE + " INTEGER," +
KNOCKBACK + " TEXT," +
CRITICAL_CHANCE + " TEXT," +
USE_TIME + " TEXT," +
VELOCITY + " TEXT," +
TOOLTIP + " TEXT," +
GRANTS_BUFF + " TEXT," +
INFLICTS_DEBUFF + " TEXT," +
RARITY + " TEXT," +
BUY_PRICE + " TEXT," +
SELL_PRICE + " TEXT" +
")"
);
}
public void drop(SQLiteDatabase db) {
db.execSQL("DROP TABLE IF EXISTS " + TABLE_NAME);
}
public void fill(SQLiteDatabase db) {
prepareSpears(db, "Spear", R.drawable.item_spear, 8, "6.5 (Strong)", "4%", "30 (Average)", "3.7", "None", "None", "None", "White", "None", "2 Silver");
prepareSpears(db, "Triden", R.drawable.item_trident, 11, "5 (Average)", "4%", "30 (Average)", "4", "None", "None", "None", "Blue", "None", "20 Silver");
prepareSpears(db, "The Rotted Fork", R.drawable.item_the_rotted_fork, 14, "5 (Average)", "4%", "30 (Average)", "4", "None", "None", "None", "Blue", "None", "20 Silver");
prepareSpears(db, "Swordfish", R.drawable.item_swordfish, 19, "4.25 (Average)", "4%", "19 (Very Fast)", "4", "None", "None", "None", "Green", "None", "50 Silver");
prepareSpears(db, "Dark Lance", R.drawable.item_dark_lance, 29, "5 (Average)", "4%", "21 (Fast)", "3", "None", "None", "None", "Orange", "None", "54 Silver");
}
private void prepareSpears(SQLiteDatabase db, String name, int picture, int damage, String knockback, String critical_chance, String use_time, String velocity, String tooltip, String grants_buff, String inflicts_debuff, String rarity, String buy_price, String sell_price) {
ContentValues values = new ContentValues();
values.put(NAME, name);
values.put(PICTURE, picture);
values.put(DAMAGE, damage);
values.put(KNOCKBACK, knockback);
values.put(CRITICAL_CHANCE, critical_chance);
values.put(USE_TIME, use_time);
values.put(VELOCITY, velocity);
values.put(TOOLTIP, tooltip);
values.put(GRANTS_BUFF, grants_buff);
values.put(INFLICTS_DEBUFF, inflicts_debuff);
values.put(RARITY, rarity);
values.put(BUY_PRICE, buy_price);
values.put(SELL_PRICE, sell_price);
db.insert(TABLE_NAME, null, values);
}
public void addSpears(Spears spears) {
SQLiteDatabase db = dbHelper.getWritableDatabase();
ContentValues values = new ContentValues();
values.put(NAME, spears.name);
values.put(PICTURE, spears.picture);
values.put(DAMAGE, spears.damage);
values.put(KNOCKBACK, spears.knockback);
values.put(CRITICAL_CHANCE, spears.critical_chance);
values.put(USE_TIME, spears.use_time);
values.put(VELOCITY, spears.velocity);
values.put(TOOLTIP, spears.tooltip);
values.put(GRANTS_BUFF, spears.grants_buff);
values.put(INFLICTS_DEBUFF, spears.inflicts_debuff);
values.put(RARITY, spears.rarity);
values.put(BUY_PRICE, spears.buy_price);
values.put(SELL_PRICE, spears.sell_price);
db.insert(TABLE_NAME, null, values);
db.close();
}
public List<Spears> getAllSpear() {
List<Spears> spear = new ArrayList<>();
SQLiteDatabase db = dbHelper.getReadableDatabase();
String selectQuery = "SELECT * FROM " + TABLE_NAME;
Cursor cursor = db.rawQuery(selectQuery, null);
if (cursor.moveToFirst()) {
do {
Spears spears = new Spears(
cursor.getInt(0),
cursor.getString(1),
cursor.getInt(2),
cursor.getInt(3),
cursor.getString(4),
cursor.getString(5),
cursor.getString(6),
cursor.getString(7),
cursor.getString(8),
cursor.getString(9),
cursor.getString(10),
cursor.getString(11),
cursor.getString(12),
cursor.getString(13)
);
spear.add(spears);
} while (cursor.moveToNext());
}
cursor.close();
db.close();
return spear;
}
public Spears getSpear(int id) {
SQLiteDatabase db = dbHelper.getReadableDatabase();
String selectQuery = "SELECT * FROM " + TABLE_NAME + " WHERE ID = " + id;
Cursor cursor = db.rawQuery(selectQuery, null);
Spears spears = null;
if (cursor.moveToFirst()) {
spears = new Spears(
cursor.getInt(0),
cursor.getString(1),
cursor.getInt(2),
cursor.getInt(3),
cursor.getString(4),
cursor.getString(5),
cursor.getString(6),
cursor.getString(7),
cursor.getString(8),
cursor.getString(9),
cursor.getString(10),
cursor.getString(11),
cursor.getString(12),
cursor.getString(13)
);
}
cursor.close();
db.close();
return spears;
}
}
|
package com.kamilbolka.util;
import android.util.Log;
/**
* This is a simple debug logging class that will control if there should be logging or not.
* The reason for this class is to allow the developer to develop with log but release the app
* without log to increase the performance for this app.
*/
public class DebbugLog {
private static boolean DEBUG = true;
/**
* Debug Log. This method reuses Log.d but with a little twist. It won't display log if
* DEBUG (global variable) is set to false.
*/
public static void d(String tag, String message) {
if (!DEBUG) {
return;
}
Log.d(tag, message);
}
/**
* Debug Log. This method reuses Log.d but with a little twist. It won't display log if
* DEBUG (global variable) is set to false.
*/
public static void d(String tag, String message, Throwable e) {
if (!DEBUG) {
return;
}
Log.d(tag, message, e);
}
}
|
import java.util.*;
class pattern2
{
public static void main(String args[])
{
int n,i,j,c=1,k,count=0;
Scanner sc = new Scanner(System.in);
System.out.println("Enter number of rows");
n = sc.nextInt();
for(i=0;i<n;i++)
{
for(j=0;j<=i;j++)
{
count=0;
for(k=1;k<=c;k++)
{
if(c%k==0)
count++;
}
c++;
if(count==2)
System.out.print("# ");
else
System.out.print("* ");
}
System.out.println();
}
}
}
|
// FPNumber.java
// The FPNumber class splits a floating point number into the S, E, and F fields.
// The F field will actually be 26 bits long, as this automatically adds the leading 1
// and the two guard bits.
//
// To use:
// FPNumber fa = new FPNumber(a);
// This allocates a new FPNumber and loads it from the value a. Note that a
// will be an integer, but it has the bit-pattern of a floating point number.
//
// fa.s()
// This returns the sign of the number, and will be either +1 or -1
//
// fa.e()
// this returns the exponent, which should be a number between 0 and 255
//
// fa.f()
// This returns the mantissa. It will have the leading 1 and it also has
// two guard bits, so it is 26 bits long, not 23.
//
// fa.setS(val)
// This changes the sign.
//
// fa.setE(val)
// This changes the exponent.
//
// fa.setF(val)
// This changes the mantissa.
//
class FPNumber
{
int _s, _e;
long _f;
public FPNumber(int a)
{
_s = (((a >> 31) & 1) == 1) ? -1 : 1;
_e = (a >> 23) & 0xFF;
_f = a & 0x7FFFFF;
if (_e != 0 && _e != 255)
{
_f |= 0x0800000;
}
_f <<= 2;
}
public int s()
{
return _s;
}
public int e()
{
return _e;
}
public long f()
{
return _f;
}
public void setS(int val)
{
_s = val;
}
public void setE(int val)
{
_e = val;
}
public void setF(long val)
{
_f = val;
}
public boolean isNaN()
{
return _e == 255 && _f > 0;
}
public boolean isInfinity()
{
return _e == 255 && _f == 0;
}
public boolean isZero()
{
return _e == 0 && _f == 0;
}
public int asInt()
{
return ((_s == -1) ? 0x80000000 : 0) | (_e << 23) | (((int) _f >> 2) & 0x07FFFFF);
}
}
|
package nine.oop;
public class Kafana {
public static void main(String[] args) {
Beverage kafa = new Kafa();
System.out.println("Račun= " + kafa.cost());
Beverage kafa1 = new Kafa();
Beverage kafaMlijeko = new MilkDecorator(kafa1);
System.out.println("Račun= " + kafaMlijeko.cost());
}
}
|
/*
* #%L
* Diana UI Core
* %%
* Copyright (C) 2014 Diana UI
* %%
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
* #L%
*/
package com.dianaui.universal.core.client.ui.base.button;
import com.dianaui.universal.core.client.ui.ButtonGroup;
import com.dianaui.universal.core.client.ui.DropDownButton;
import com.dianaui.universal.core.client.ui.ListDropDown;
import com.dianaui.universal.core.client.ui.base.HasToggle;
import com.dianaui.universal.core.client.ui.base.mixin.ToggleMixin;
import com.dianaui.universal.core.client.ui.constants.ButtonType;
import com.dianaui.universal.core.client.ui.constants.Styles;
import com.dianaui.universal.core.client.ui.constants.Toggle;
import com.dianaui.universal.core.client.ui.html.Text;
import com.google.gwt.dom.client.Element;
import com.google.gwt.user.client.DOM;
import com.google.gwt.user.client.Event;
/**
* Base class for buttons that can be toggle buttons
*
* @author Sven Jacobs
* @author <a href='mailto:donbeave@gmail.com'>Alexey Zhokhov</a>
* @see AbstractButton
* @see Toggle
*/
public abstract class AbstractToggleButton extends AbstractIconButton implements HasToggle {
private Text separator;
private Caret caret;
protected AbstractToggleButton() {
this(ButtonType.DEFAULT);
}
protected AbstractToggleButton(final ButtonType type) {
setType(type);
}
/**
* Toggles the display of the caret for the button
*
* @param toggleCaret show/hide the caret for the button
*/
public void setToggleCaret(final boolean toggleCaret) {
caret.setVisible(toggleCaret);
}
@Override
public Toggle getToggle() {
return ToggleMixin.getToggle(this);
}
/**
* Specifies that this button acts as a toggle, for instance for a parent {@link com.dianaui.universal.core.client.ui.DropDown}
* or {@link com.dianaui.universal.core.client.ui.ButtonGroup}
* Adds a {@link Caret} as a child widget.
*
* @param toggle Kind of toggle
*/
@Override
public void setToggle(final Toggle toggle) {
ToggleMixin.setToggle(this, toggle);
if (separator != null)
separator.removeFromParent();
if (caret != null)
caret.removeFromParent();
separator = new Text(" ");
caret = new Caret();
if (toggle == Toggle.DROPDOWN) {
addStyleName(Styles.DROPDOWN_TOGGLE);
add(separator, (Element) getElement());
add(caret, (Element) getElement());
}
}
public void onBrowserEvent(Event event) {
super.onBrowserEvent(event);
switch (DOM.eventGetType(event)) {
case Event.ONCLICK:
if (getToggle() == Toggle.BUTTON) {
toggle();
} else if (getToggle() == Toggle.DROPDOWN && getParent() instanceof ListDropDown) {
((ListDropDown) getParent()).toggle();
} else if (getToggle() == Toggle.DROPDOWN && getParent() instanceof DropDownButton) {
((DropDownButton) getParent()).toggle();
} else if (getToggle() == Toggle.DROPDOWN && getParent() instanceof ButtonGroup) {
((ButtonGroup) getParent()).toggle();
}
break;
}
}
@Override
protected void onChanged() {
// fix caret position
setToggle(getToggle());
}
}
|
package basic_programs;
public class SwapWithTwo {
public static void main(String args[])
{
int a=10;
int b=20;
System.out.println("before swapping");
System.out.println("value of num1 is"+ a);
System.out.println("value of num2 is"+b);
a=a+b;
b=b-a;
a=a-b;
System.out.println("after swapping");
System.out.println("value of num1 is"+ a);
System.out.println("value of num2 is"+b);
}
}
|
package lyrth.makanism.bot.commands.admin;
import lyrth.makanism.api.GuildCommand;
import lyrth.makanism.api.annotation.CommandInfo;
import lyrth.makanism.api.object.AccessLevel;
import lyrth.makanism.api.object.CommandCtx;
import reactor.core.publisher.Mono;
import java.util.Map;
@CommandInfo(
aliases = {"setAlias"},
accessLevel = AccessLevel.OWNER,
desc =
"Creates an alias that, when run, executes another arbitrary command with or without additional arguments.\n" +
"Not specifying the target removes the alias. Run this without args to see the server's command aliases.\n" +
"For example, doing:\n" +
"`${prefix}alias something help userInfo`\n" +
"Sending `${prefix}something` would now be equivalent to doing `${prefix}help userinfo`.",
usage = "[<alias - no spaces>] [<target>]"
)
public class Alias extends GuildCommand {
private static final String AL_LIST_MSG = "Active guild aliases: %s \n*(Note: ~bt~ is backtick: ` )*";
private static final String CLEARED_MSG = "Alias `%s` cleared.";
private static final String INVALID_MSG = "Alias `%s` invalid or doesn't exist.";
private static final String SUCCESS_MSG = "Alias `%s` now points to `%s`.";
@Override
public Mono<?> execute(CommandCtx ctx) {
if (ctx.getArgs().count() < 1){
StringBuilder items = new StringBuilder("\n");
for (Map.Entry<String, String> entry : ctx.getGuildConfig().getAliases().entrySet()){
items.append('`').append(entry.getKey().replace("`","~bt~")).append('`');
items.append(" -> ");
items.append('`').append(entry.getValue().replace("`","~bt~")).append('`');
items.append('\n');
}
return ctx.sendReply(String.format(AL_LIST_MSG, items.toString()));
}
String alias = ctx.getArg(1).toLowerCase();
String command = ctx.getArgs().getRest(2);
if (command.isBlank()) { // remove
String removed = ctx.getGuildConfig().getAliases().remove(alias);
if (removed != null)
return ctx.sendReply(String.format(CLEARED_MSG, alias));
else
return ctx.sendReply(String.format(INVALID_MSG, alias));
} else { // add
String target = (command + ctx.getArgs().concatFlags()).trim();
ctx.getGuildConfig().getAliases().put(alias, target);
return ctx.sendReply(String.format(SUCCESS_MSG, alias, target));
}
}
}
|
import java.util.ArrayList;
import java.util.Date;
import java.util.UUID;
public class VideoPost extends TextPost{
/**
* maximum video length
*/
static final double maxVideoLength = 10;
/**
* video's filename
*/
private String videoFilename;
/**
* video's duration
*/
private String videoDuration;
/**
* @param text post's
* @param originatedDate post's originated Date
* @param taggedUsers post's tagged Users
* @param videoFilename post's video Filename
* @param videoDuration post's video Duration
* @param postID post's post ID
* @param location post's location
*/
public VideoPost(String text, Date originatedDate, ArrayList<String> taggedUsers, String videoFilename, String videoDuration, UUID postID, Location location) {
super(text, originatedDate, taggedUsers, location, postID);
this.setVideoFilename(videoFilename);
this.setVideoDuration(videoDuration);
}
/**
* @return post's video file name
*/
public String getVideoFilename() {return videoFilename;}
/**
* @param videoFilename sets video file name
*/
public void setVideoFilename(String videoFilename) {this.videoFilename = videoFilename;}
/**
* @return post's video duration
*/
public String getVideoDuration() {return videoDuration;}
/**
* @param videoDuration sets
*/
public void setVideoDuration(String videoDuration) {this.videoDuration = videoDuration;}
}
|
package override;
public class Veiculo {
protected void travar() {
System.out.println("Pressione com o pe direito no pedal do meio");
}
}
|
package com.xljt.freight.service;
/**
* The interface Capital flow service.
*
* @author xu
* @date 2020.04.13
*/
public interface CapitalFlowService {
/**
* Capital flow upload.
*
* @author xu
* @date 2020.04.13
*/
void capitalFlowUpload();
}
|
package me.sh4rewith.persistence.mongo.mappers;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import me.sh4rewith.domain.SharedFileFootprint;
import me.sh4rewith.persistence.keys.SharedFileFootprintKeys;
import org.springframework.dao.DataAccessException;
import com.mongodb.DBObject;
import com.mongodb.MongoException;
public class SharedFileFootprintMapper extends AbstractMongoDocumentMapper {
public static final String SHARED_FILE_FOOTPRINT_STORENAME =
SharedFileFootprintKeys.SHARED_FILE_FOOTPRINT_STORENAME.keyName();
public static final String SHARED_FILE_INFO_ID =
SharedFileFootprintKeys.SHARED_FILE_INFO_ID.keyName();
public static final String CREATION_DATE =
SharedFileFootprintKeys.CREATION_DATE.keyName();
public static final String RAW_FILE_ID =
SharedFileFootprintKeys.RAW_FILE_ID.keyName();
public static final String EXPIRATION_DATE =
SharedFileFootprintKeys.EXPIRATION_DATE.keyName();
List<SharedFileFootprint> footprints = new ArrayList<SharedFileFootprint>();
@Override
public void processDocument(DBObject dbObject) throws MongoException,
DataAccessException {
SharedFileFootprint footprint = new SharedFileFootprint.Builder()
.setRawFileId((String) dbObject.get(RAW_FILE_ID))
.setSharedFileInfoId((String) dbObject.get(SHARED_FILE_INFO_ID))
.setCreationDate((Date) dbObject.get(CREATION_DATE))
.setExpiration((Date) dbObject.get(EXPIRATION_DATE))
.build();
footprints.add(footprint);
}
public List<SharedFileFootprint> getFootprintList() {
return footprints;
}
public SharedFileFootprint getFootprint() {
return footprints.get(0);
}
}
|
package production.Staging;
import java.sql.SQLException;
import org.junit.BeforeClass;
import org.junit.Test;
import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.firefox.FirefoxDriver;
import org.openqa.selenium.support.PageFactory;
import org.openqa.selenium.support.ui.Select;
import Staging.PageLogin;
public class main {
public static WebDriver driver;
static PageLogin PageLogin;
static PageMatchBox PageMatchBox;
static CommonOps CommonOps;
static GlobalSearch GlobalSearch;
static PageApply staticPageApply;
@BeforeClass
public static void Before() throws SQLException{
// Not reaveling any sensitive info of the company
Staging.DbConnection.DbAccess("***","***", "***");
Staging.DbConnection.DbUpdate("update *** set ***=0 where *** = 2183867");
driver = new FirefoxDriver();
CommonOps = PageFactory.initElements(driver, CommonOps.class);
CommonOps.OpenBrowser("http://staginginta.redmatch.com/Staging_RecruiterPro/Candidate/Login/login.aspx?AffiliateId=51202");
PageLogin = PageFactory.initElements(driver, PageLogin.class);
//http://jobsil.redmatch.com/search/publicsearch.aspx?affiliateid=513006
PageMatchBox = PageFactory.initElements(driver, PageMatchBox.class);
GlobalSearch = PageFactory.initElements(driver, GlobalSearch.class);
staticPageApply = PageFactory.initElements(driver, PageApply.class);
}
@Test
public void test() throws InterruptedException{
PageLogin.loginAction("***@***.com", "***");
PageMatchBox.LinkToFindPositions.isDisplayed();
PageMatchBox.LinkToLogOut.isDisplayed();
PageMatchBox.LinkToProfile.isDisplayed();
PageMatchBox.GoEditYourProfile.click();
PageMatchBox.LinkToFindPositions.click();
GlobalSearch.GoToApplyButton.click();
Select ownershiptype = new Select(driver.findElement(By.id("ctl00_MasterContentPlaceHolder_CandidatesSources_CandidateSourcesTypeDropDown")));
ownershiptype.selectByIndex(1);
Thread.sleep(1000);
driver.findElement(By.id("ctl00_MasterContentPlaceHolder_CandidatesSources_FreeTextSource")).sendKeys("test");
driver.findElement(By.xpath("//a[@id='ctl00_MasterContentPlaceHolder_btnSubmit']")).click();
Thread.sleep(3000);
driver.quit();
}
}
//this update must be made after the test for the next one to be valid
//
//update matches
//set wishmatch=0
//where userid = 2183867
|
/**
* Test Stub
* - 더미 객체가 마치 실제로 동작하는 것처럼 보이게 만들어놓은 객체다.
* - 실제로 스텁을 사용할 때는 테스트에 필요한 메서드 부분만 하드코딩하면 된다.
*/
package shop;
public class StubCoupon implements ICoupon {
@Override
public String getName() {
// TODO Auto-generated method stub
return "VIP 고객 한가위 감사쿠폰";
}
@Override
public boolean isValid() {
// TODO Auto-generated method stub
return true;
}
@Override
public int getDiscountPercent() {
// TODO Auto-generated method stub
return 7;
}
@Override
public boolean isAppliable(Item item) {
if(item.getCategory().equals("부엌칼")) {
return true;
} else if(item.getCategory().equals("알람시계")) {
return false;
}
return true;
}
@Override
public void doExpire() {
// TODO Auto-generated method stub
}
}
|
package br.com.itau.creditcardtransactionservices.repository;
import br.com.itau.creditcardtransactionservices.repository.entity.CreditCardTransactionEntity;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
import org.springframework.data.mongodb.repository.MongoRepository;
import org.springframework.stereotype.Repository;
import java.time.LocalDate;
import java.util.Optional;
@Repository
public interface CreditCardTransactionMongoRepository extends MongoRepository<CreditCardTransactionEntity, String> {
Page<CreditCardTransactionEntity> findByDate(LocalDate date, Pageable pageable);
Page<CreditCardTransactionEntity> findByUserId(Long userId, Pageable pageable);
Page<CreditCardTransactionEntity> findByUserPaymentMethodId(Long userPaymentMethodId, Pageable pageable);
Page<CreditCardTransactionEntity> findByUserIdAndDateBetween(Long userId, LocalDate initialDate, LocalDate finalDate, Pageable pageable);
Optional<CreditCardTransactionEntity> findById(Long id);
}
|
package ru.job4j.condition;
import org.junit.Test;
import static org.hamcrest.core.Is.is;
import static org.junit.Assert.assertThat;
/**
* Class PointTest тестирует метод класса Point.
* @author Goureev Ilya (mailto:ill-jah@yandex.ru)
* @version %G%
* @since 1
*/
public class PointTest {
/**
* Тестирует метод is() с условием, когда точка на функции.
*/
@Test
public void whenPointOnFunction() {
Point point = new Point(2, 6);
boolean result = point.is(1, 4);
boolean expected = true;
assertThat(result, is(expected));
}
/**
* Тестирует метод is() с условием, когда точка не на функции.
*/
@Test
public void whenPointNotOnFunction() {
Point point = new Point(2, 3);
boolean result = point.is(1, 4);
boolean expected = false;
assertThat(result, is(expected));
}
}
|
package xpadro.spring.security.config;
import org.h2.tools.Server;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.ComponentScan;
import java.sql.SQLException;
@ComponentScan(basePackages = "xpadro.spring.security.web")
public class ServletConfig {
/**
* Available at localhost:8082
* URL: jdbc:h2:mem:testDB
*/
@Bean
public Server h2ConsoleServer() throws SQLException {
return Server.createWebServer("-web", "-webAllowOthers").start();
}
}
|
package cn.itcast.core.common;
import org.apache.poi.hssf.usermodel.*;
import org.apache.poi.hssf.util.HSSFColor;
import org.apache.poi.ss.usermodel.Cell;
import org.apache.poi.ss.usermodel.Row;
import org.apache.poi.ss.usermodel.Sheet;
import org.apache.poi.ss.usermodel.Workbook;
import org.apache.poi.ss.util.CellRangeAddress;
import org.apache.poi.xssf.usermodel.*;
import org.springframework.web.multipart.MultipartFile;
import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.net.URLEncoder;
import java.util.ArrayList;
import java.util.List;
public class ExcelUtil {
/**
* 解析excel
*
* @param workbook
* @return
* @throws IOException
*/
public static List<String[]> readExcelGetList(Workbook workbook) throws IOException {
List<String[]> list = new ArrayList<String[]>();
if (workbook != null) {
for (int sheetNum = 0; sheetNum < workbook.getNumberOfSheets(); sheetNum++) {
//获得当前sheet工作表
Sheet sheet = workbook.getSheetAt(sheetNum);
if (sheet == null) {
continue;
}
//获得当前sheet的开始行
int firstRowNum = sheet.getFirstRowNum();
//获得当前sheet的结束行
int lastRowNum = sheet.getLastRowNum();
//循环除了第一行的所有行
for (int rowNum = firstRowNum + 1; rowNum <= lastRowNum; rowNum++) {
//获得当前行
Row row = sheet.getRow(rowNum);
if (row == null) {
continue;
}
//获得当前行的开始列
int firstCellNum = row.getFirstCellNum();
//获得当前行的列数
int lastCellNum = row.getPhysicalNumberOfCells();
String[] cells = new String[row.getPhysicalNumberOfCells()];
//循环当前行
for (int cellNum = firstCellNum; cellNum < lastCellNum; cellNum++) {
Cell cell = row.getCell(cellNum);
cells[cellNum] = getCellValue(cell);
}
list.add(cells);
}
}
}
return list;
}
/**
* 判断文件版本
*
* @param file
* @return
*/
public static Workbook getWorkBook(MultipartFile file) {
String xls = "xls";
String xlsx = "xlsx";
//获得文件名
String fileName = file.getOriginalFilename();
//创建Workbook工作薄对象,表示整个excel
Workbook workbook = null;
try {
//获取excel文件的io流
InputStream is = file.getInputStream();
//根据文件后缀名不同(xls和xlsx)获得不同的Workbook实现类对象
if (fileName.endsWith(xls)) {
//2003
workbook = new HSSFWorkbook(is);
} else if (fileName.endsWith(xlsx)) {
//2007
workbook = new XSSFWorkbook(is);
}
} catch (IOException e) {
e.printStackTrace();
}
return workbook;
}
/**
* 把所有类型转换成字符串 转换
*
* @param cell
* @return
*/
public static String getCellValue(Cell cell) {
String cellValue = "";
if (cell == null) {
return cellValue;
}
//把数字当成String来读,避免出现1读成1.0的情况
if (cell.getCellType() == Cell.CELL_TYPE_NUMERIC) {
cell.setCellType(Cell.CELL_TYPE_STRING);
}
//判断数据的类型
switch (cell.getCellType()) {
case Cell.CELL_TYPE_NUMERIC: //数字
cellValue = String.valueOf(cell.getNumericCellValue());
break;
case Cell.CELL_TYPE_STRING: //字符串
cellValue = String.valueOf(cell.getStringCellValue());
break;
case Cell.CELL_TYPE_BOOLEAN: //Boolean
cellValue = String.valueOf(cell.getBooleanCellValue());
break;
case Cell.CELL_TYPE_FORMULA: //公式
cellValue = String.valueOf(cell.getCellFormula());
break;
case Cell.CELL_TYPE_BLANK: //空值
cellValue = "";
break;
case Cell.CELL_TYPE_ERROR: //故障
cellValue = "非法字符";
break;
default:
cellValue = "未知类型";
break;
}
return cellValue;
}
/**
* excel导出工具类
* @param sheetName 工作表
* @param titleName 表头
* @param fileName 导出的文件名
* @param columnNumber 列数
* @param columnWidth 列宽
* @param columnName 列名
* @param dataList 数据
* @param response 返回浏览器的响应
* @throws Exception
*/
public static void ExportWithResponse(String sheetName, String titleName,
String fileName, int columnNumber, int[] columnWidth,
String[] columnName, String[][] dataList,
HttpServletResponse response) throws Exception {
if (columnNumber == columnWidth.length && columnWidth.length == columnName.length) {
// 第一步,创建一个webbook,对应一个Excel文件
HSSFWorkbook wb = new HSSFWorkbook();
// 第二步,在webbook中添加一个sheet,对应Excel文件中的sheet
HSSFSheet sheet = wb.createSheet(sheetName);
// sheet.setDefaultColumnWidth(15); //统一设置列宽
for (int i = 0; i < columnNumber; i++) {
for (int j = 0; j <= i; j++) {
if (i == j) {
sheet.setColumnWidth(i, columnWidth[j] * 256); // 单独设置每列的宽
}
}
}
// 创建第0行 也就是标题
HSSFRow row1 = sheet.createRow((int) 0);
row1.setHeightInPoints(50);// 设备标题的高度
// 第三步创建标题的单元格样式style2以及字体样式headerFont1
HSSFCellStyle style2 = wb.createCellStyle();
style2.setAlignment(HSSFCellStyle.ALIGN_CENTER);
style2.setVerticalAlignment(HSSFCellStyle.VERTICAL_CENTER);
style2.setFillForegroundColor(HSSFColor.LIGHT_TURQUOISE.index);
style2.setFillPattern(HSSFCellStyle.SOLID_FOREGROUND);
HSSFFont headerFont1 = (HSSFFont) wb.createFont(); // 创建字体样式
headerFont1.setBoldweight(HSSFFont.BOLDWEIGHT_BOLD); // 字体加粗
headerFont1.setFontName("黑体"); // 设置字体类型
headerFont1.setFontHeightInPoints((short) 15); // 设置字体大小
style2.setFont(headerFont1); // 为标题样式设置字体样式
HSSFCell cell1 = row1.createCell(0);// 创建标题第一列
sheet.addMergedRegion(new CellRangeAddress(0, 0, 0,
columnNumber - 1)); // 合并列标题
cell1.setCellValue(titleName); // 设置值标题
cell1.setCellStyle(style2); // 设置标题样式
// 创建第1行 也就是表头
HSSFRow row = sheet.createRow((int) 1);
row.setHeightInPoints(37);// 设置表头高度
// 第四步,创建表头单元格样式 以及表头的字体样式
HSSFCellStyle style = wb.createCellStyle();
style.setWrapText(true);// 设置自动换行
style.setAlignment(HSSFCellStyle.ALIGN_CENTER);
style.setVerticalAlignment(HSSFCellStyle.VERTICAL_CENTER); // 创建一个居中格式
style.setBottomBorderColor(HSSFColor.BLACK.index);
style.setBorderBottom(HSSFCellStyle.BORDER_THIN);
style.setBorderLeft(HSSFCellStyle.BORDER_THIN);
style.setBorderRight(HSSFCellStyle.BORDER_THIN);
style.setBorderTop(HSSFCellStyle.BORDER_THIN);
HSSFFont headerFont = (HSSFFont) wb.createFont(); // 创建字体样式
headerFont.setBoldweight(HSSFFont.BOLDWEIGHT_BOLD); // 字体加粗
headerFont.setFontName("黑体"); // 设置字体类型
headerFont.setFontHeightInPoints((short) 10); // 设置字体大小
style.setFont(headerFont); // 为标题样式设置字体样式
// 第四.一步,创建表头的列
for (int i = 0; i < columnNumber; i++) {
HSSFCell cell = row.createCell(i);
cell.setCellValue(columnName[i]);
cell.setCellStyle(style);
}
// 第五步,创建单元格,并设置值
for (int i = 0; i < dataList.length; i++) {
row = sheet.createRow((int) i + 2);
// 为数据内容设置特点新单元格样式1 自动换行 上下居中
HSSFCellStyle zidonghuanhang = wb.createCellStyle();
zidonghuanhang.setWrapText(true);// 设置自动换行
zidonghuanhang.setVerticalAlignment(HSSFCellStyle.VERTICAL_CENTER); // 创建一个居中格式
// 设置边框
zidonghuanhang.setBottomBorderColor(HSSFColor.BLACK.index);
zidonghuanhang.setBorderBottom(HSSFCellStyle.BORDER_THIN);
zidonghuanhang.setBorderLeft(HSSFCellStyle.BORDER_THIN);
zidonghuanhang.setBorderRight(HSSFCellStyle.BORDER_THIN);
zidonghuanhang.setBorderTop(HSSFCellStyle.BORDER_THIN);
// 为数据内容设置特点新单元格样式2 自动换行 上下居中左右也居中
HSSFCellStyle zidonghuanhang2 = wb.createCellStyle();
zidonghuanhang2.setWrapText(true);// 设置自动换行
zidonghuanhang2
.setVerticalAlignment(HSSFCellStyle.VERTICAL_CENTER); // 创建一个上下居中格式
zidonghuanhang2.setAlignment(HSSFCellStyle.ALIGN_CENTER);// 左右居中
// 设置边框
zidonghuanhang2.setBottomBorderColor(HSSFColor.BLACK.index);
zidonghuanhang2.setBorderBottom(HSSFCellStyle.BORDER_THIN);
zidonghuanhang2.setBorderLeft(HSSFCellStyle.BORDER_THIN);
zidonghuanhang2.setBorderRight(HSSFCellStyle.BORDER_THIN);
zidonghuanhang2.setBorderTop(HSSFCellStyle.BORDER_THIN);
HSSFCell datacell = null;
for (int j = 0; j < columnNumber; j++) {
datacell = row.createCell(j);
datacell.setCellValue(dataList[i][j]);
datacell.setCellStyle(zidonghuanhang2);
}
}
// 第六步,将文件存到浏览器设置的下载位置
String filename = fileName + ".xls";
response.setContentType("application/ms-excel;charset=UTF-8");
response.setHeader("Content-Disposition", "attachment;filename="
.concat(String.valueOf(URLEncoder.encode(filename, "GBK"))));
/*
* setHeader设置打开方式,具体为:inline为在浏览器中打开,attachment单独打开。
*/
OutputStream out = response.getOutputStream();
try {
wb.write(out);// 将数据写出去
String str = "导出" + fileName + "成功!";
System.out.println(str);
} catch (Exception e) {
e.printStackTrace();
String str1 = "导出" + fileName + "失败!";
System.out.println(str1);
} finally {
out.close();
}
} else {
System.out.println("列数目长度名称三个数组长度要一致");
}
}
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.