blob_id
stringlengths
40
40
language
stringclasses
1 value
repo_name
stringlengths
5
132
path
stringlengths
2
382
src_encoding
stringclasses
34 values
length_bytes
int64
9
3.8M
score
float64
1.5
4.94
int_score
int64
2
5
detected_licenses
listlengths
0
142
license_type
stringclasses
2 values
text
stringlengths
9
3.8M
download_success
bool
1 class
24cbdb20ab2760e10f708f898d8c7b7dc56d1b16
Java
yichengjie/LearningNotes
/spring-aop-study/src/test/java/com/yicj/aop2/test/Test.java
UTF-8
673
1.921875
2
[]
no_license
package com.yicj.aop2.test; import com.yicj.aop2.config.Appconfig; import com.yicj.aop2.dao.IndexDao; import org.springframework.context.annotation.AnnotationConfigApplicationContext; //https://blog.csdn.net/baomw/article/details/84262006 public class Test { public static void main(String[] args) { AnnotationConfigApplicationContext context = new AnnotationConfigApplicationContext(Appconfig.class); System.out.println("==================================="); context.getBean(IndexDao.class).query2(); System.out.println("==================================="); context.getBean(IndexDao.class).query(); } }
true
cb867d301de182c79c00dd44f0b243611f57c9c0
Java
FranklyCui/Cinderella
/src/main/java/com/cn/service/impl/StoresServiceImpl.java
UTF-8
880
2.125
2
[]
no_license
package com.cn.service.impl; import java.util.List; import javax.annotation.Resource; import org.springframework.stereotype.Service; import com.cn.dao.StoresMapper; import com.cn.model.Stores; import com.cn.service.StoresService; @Service("stService") public class StoresServiceImpl implements StoresService { @Resource private StoresMapper stDao; public Stores getStById(int stId) { // TODO Auto-generated method stub return this.stDao.selectByPrimaryKey(stId); } public List<Stores> getAll(){ return this.stDao.selectAll(); } @Override public int insertST(Stores st) { return this.stDao.insertWithoutKey(st); } @Override public void updateST(Stores st) { int xxx= this.stDao.updateByPrimaryKey(st); } @Override public void deleteST(int st_id) { int xxx= this.stDao.deleteByPrimaryKey(st_id); } }
true
3f2a4034b0bb12bfbce17230085993624a089b66
Java
JxSun/MotionDetect
/app/src/main/java/com/motiondetect/detector/data/analysis/MotionAnalyst.java
UTF-8
2,417
2.34375
2
[]
no_license
package com.motiondetect.detector.data.analysis; import android.util.Log; import com.motiondetect.detector.base.IBackgroundWorker; import com.motiondetect.detector.base.IReleasable; import com.motiondetect.detector.data.bluetooth.ArduinoReceiver; import com.motiondetect.detector.model.MotionModel; import com.motiondetect.detector.util.MotionConverter; import com.motiondetect.detectorjni.NativeMotionAnalyst; import com.motiondetect.detectorjni.model.MotionResult; import java.util.ArrayList; import java.util.List; public class MotionAnalyst extends IBackgroundWorker implements IReleasable, ArduinoReceiver.OnReceiveDataListener { private static final String TAG = MotionAnalyst.class.getSimpleName(); private volatile List<Callback> mCallbacks; private NativeMotionAnalyst mNativeAnalyst; private final NativeMotionAnalyst.NativeCallback mNativeCallback = new NativeMotionAnalyst.NativeCallback() { @Override public void onAnalysisResult(MotionResult result) { for (Callback callback : mCallbacks) { callback.onAnalysisResult(result); } } }; public MotionAnalyst() { super(); mCallbacks = new ArrayList<>(); mNativeAnalyst = new NativeMotionAnalyst(); } @Override protected void onPreExecuteAsync() { Log.v(TAG, "onPreExecuteAsync() - register callback"); mNativeAnalyst.registerCallback(mNativeCallback); } @Override protected void onPostExecuteAsync() { Log.v(TAG, "onPostExecuteAsync() - unregister callback"); mNativeAnalyst.unregisterCallback(); } public MotionAnalyst addCallback(Callback callback) { if (callback == null) { throw new IllegalArgumentException("Callback cannot be null"); } Log.v(TAG, "addCallback(" + callback.toString() + ")"); mCallbacks.add(callback); return this; } @Override public void onReceive(final List<MotionModel> data) { invokeAsync(new Runnable() { @Override public void run() { mNativeAnalyst.analysisStepsAsync(MotionConverter.convert(data)); } }); } @Override public void release() { mCallbacks.clear(); terminate(); } public interface Callback { void onAnalysisResult(MotionResult result); } }
true
b1d5a01426ed36e62fd13cc47154b6510e0a01df
Java
maizesix92/school
/CohortSessionWeek3/src/filenames/FilenamesMain.java
UTF-8
1,001
3.21875
3
[]
no_license
package filenames; import java.io.IOException; import java.util.ArrayList; public class FilenamesMain { public static void main(String[] args) { // Adding filenames ArrayList<String> fileNames = new ArrayList<>(); fileNames.add("D:\\SUTD\\Term 5\\Software Construction\\week 3\\file1.txt"); fileNames.add("D:\\SUTD\\Term 5\\Software Construction\\week 3\\file2.txt"); fileNames.add("D:\\SUTD\\Term 5\\Software Construction\\week 3\\file3.txt"); fileNames.add("D:\\SUTD\\Term 5\\Software Construction\\week 3\\file4.txt"); fileNames.add("D:\\SUTD\\Term 5\\Software Construction\\week 3\\file5.txt"); fileNames.add("D:\\SUTD\\Term 5\\Software Construction\\week 3\\file6.txt"); // for (String string : fileNames) { FileLooper loop = new FileLooper(string); try { System.out.println(String.format("'%s' contains %d line(s)", string, loop.getFileListings())); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } } } }
true
8ed628cee25dc80451aaf3813b3ed61ceada5559
Java
zneil123/gene-info-WebServiceProject
/src/Service/crossSession/SearchService.java
UTF-8
531
2.234375
2
[]
no_license
package Service.crossSession; import org.apache.axis2.context.MessageContext; import org.apache.axis2.context.ServiceGroupContext; public class SearchService { public String findByName(String name) { // 第1步:获得key-value对中的value MessageContext mc = MessageContext.getCurrentMessageContext(); ServiceGroupContext sgc = mc.getServiceGroupContext(); if (sgc.getProperty("login").equals("成功登录")) return "找到的数据<" + sgc.getProperty("login") + ">"; else return "用户未登录"; } }
true
8acf8bb454e42366bd016d67c9f0dcdc752868cb
Java
hhugoac/AlgoritmosBasicosPOO
/src/com/ejerciciosoop/misclases/AppAlbergue.java
UTF-8
1,497
3
3
[]
no_license
package com.ejerciciosoop.misclases; import com.ejerciciosoop.misclases.Mascota; import java.util.Scanner; //subida a git public class AppAlbergue { public static void main(String[] args) { Mascota firulais=new Mascota(); Mascota objPerro2=new Mascota("2P2","Celeste","Pug","Obesa"); //Asignacion por constructor Mascota objPerro3=new Mascota(); Scanner entrada=new Scanner(System.in); //Asignacion por teclado objPerro3.setId(entrada.next()); objPerro3.setnombre(entrada.next()); objPerro3.setraza(entrada.next()); objPerro3.setdescripcion(entrada.next()); //Asignacion por set firulais.setId("1P1"); firulais.setnombre("Firulais"); firulais.setraza("Labrador"); firulais.setdescripcion("Orejona"); System.out.println("ID: "+firulais.getId()); System.out.println("Nombre: "+firulais.getnombre()); System.out.println("Raza: "+firulais.getraza()); System.out.println("Descripcion: "+firulais.getdescripcion()); System.out.println("ID: "+objPerro2.getId()); System.out.println("Nombre: "+objPerro2.getnombre()); System.out.println("Raza: "+objPerro2.getraza()); System.out.println("Descripcion: "+objPerro2.getdescripcion()); System.out.println("ID: "+objPerro3.getId()); System.out.println("Nombre: "+objPerro3.getnombre()); System.out.println("Raza: "+objPerro3.getraza()); System.out.println("Descripcion: "+objPerro3.getdescripcion()); } }
true
2d4bba7d609a36f8194f0e75a436e41d75049dc2
Java
Geidalaodicha/qhbx
/src/com/rh/core/plug/search/client/IndexLogMgr.java
UTF-8
1,593
2.078125
2
[]
no_license
package com.rh.core.plug.search.client; import org.apache.commons.lang.exception.ExceptionUtils; import com.rh.core.base.Bean; import com.rh.core.serv.ParamBean; import com.rh.core.serv.ServDao; import com.rh.core.serv.bean.SqlBean; import com.rh.core.util.Constant; /** * 增加索引失败记录 * @author yangjy * */ public class IndexLogMgr { public static final String SY_PLUG_SEARCH_INDEX_LOG = "SY_PLUG_SEARCH_INDEX_LOG"; /** * @param searchDefine 查询定义Bean * @param dataBean 数据Bean * @param e 异常 */ public static void addIndexLog(Bean searchDefine, Bean dataBean, Throwable e) { Bean logBean = new Bean(); logBean.set("SEARCH_ID", searchDefine.getStr("SEARCH_ID")); logBean.set("SERV_ID", searchDefine.getStr("SERV_ID")); logBean.set("DATA_ID", dataBean.getId()); logBean.set("LOG_TYPE", 2); // 索引失败 String msg = ExceptionUtils.getStackTrace(e); if (msg.length() > 600) { msg = msg.substring(0, 600); } logBean.set("LOG_MSG", msg); ServDao.save(SY_PLUG_SEARCH_INDEX_LOG, logBean); } /** * * @param servId 服务ID * @param dataId 数据ID */ public static void updateStateToOk(String servId, String dataId) { SqlBean sql = new SqlBean(); sql.and("SERV_ID", servId); sql.and("DATA_ID", dataId); ParamBean param = new ParamBean(); param.set("INDEX_STATE", Constant.YES_INT); ServDao.updates(SY_PLUG_SEARCH_INDEX_LOG, param, sql); } }
true
31ccf3f209057f4da06fba790b15c5568b236dec
Java
Sailor-Saturn/Hexagonal-Architecture-Spring-Boot-Postgres-JPA-JDBC-Monolith
/projects/server/src/main/java/com/arqsoft/server/Infrastructure/AdapterPersistanceJPA/Entity/DeliveryScheduleAggregate/DaysOrdersEntity.java
UTF-8
1,936
2.34375
2
[]
no_license
package com.arqsoft.server.Infrastructure.AdapterPersistanceJPA.Entity.DeliveryScheduleAggregate; import com.arqsoft.server.Domain.Model.OrderAggregate.Order; import com.arqsoft.server.Infrastructure.AdapterPersistanceJPA.Entity.DayScheduleAggregate.DayScheduleEntity; import com.arqsoft.server.Infrastructure.AdapterPersistanceJPA.Entity.DeliveryScheduleAggregate.ValueObject.OrderDate; import com.arqsoft.server.Infrastructure.AdapterPersistanceJPA.Entity.OrderAggregate.OrderEntity; import javax.persistence.*; import java.io.Serializable; import java.util.List; @Entity @Table(name="DaysOrders") public class DaysOrdersEntity implements Serializable { private static final long serialVersionUID = 1L; protected DaysOrdersEntity() { } public DaysOrdersEntity(OrderDate orderDate, DayScheduleEntity daySchedule, List<OrderEntity> ordersList) { this.orderDate = orderDate; this.daySchedule = daySchedule; this.ordersList = ordersList; } @Id @GeneratedValue(strategy = GenerationType.IDENTITY) private Long Id; @Column @Embedded private OrderDate orderDate; @ManyToOne(fetch = FetchType.LAZY) @JoinColumn(name = "dayScheduleId") private DayScheduleEntity daySchedule; @OneToMany(fetch = FetchType.LAZY) private List<OrderEntity> ordersList; public Long getId() { return Id; } public OrderDate getOrderDate() { return orderDate; } public DayScheduleEntity getDaySchedule() { return daySchedule; } public List<OrderEntity> getOrdersList() { return ordersList; } public void setOrderDate(OrderDate orderDate) { this.orderDate = orderDate; } public void setDaySchedule(DayScheduleEntity daySchedule) { this.daySchedule = daySchedule; } public void setOrdersList(List<OrderEntity> ordersList) { this.ordersList = ordersList; } }
true
3110005664c1e7f9f1e29143853bf1591d31e752
Java
cz67998/datastructure
/src/main/java/com/wangzhou/datastructure/linkedlist/solution/JudgeBalanceTree.java
UTF-8
588
3.265625
3
[]
no_license
package com.wangzhou.datastructure.linkedlist.solution; /** * Created by IDEA * author:wangzhou * Date:2019/4/22 * Time:13:53 **/ public class JudgeBalanceTree { public boolean isBalanced(TreeNode root) { return calDepth(root) >= 0; } private int calDepth(TreeNode root) { if (root == null) { return 0; } int a = calDepth(root.left); int b = calDepth(root.right); if (a >= 0 && b >= 0 && Math.abs(a - b) <= 1) { return Math.max(a, b) + 1; } else { return -1; } } }
true
9ce3bc19f1ab519c83b6e622a475a529622557e9
Java
bayaluprantya/e-auction
/src/main/java/com/wipro/auction/bid/impl/DefaultBidder.java
UTF-8
3,353
3
3
[]
no_license
package com.wipro.auction.bid.impl; import com.wipro.auction.Bid; import java.util.logging.Logger; /** * Default Bidder implementation */ public class DefaultBidder implements com.wipro.auction.bid.Bidder { /** * logger */ private static final Logger LOG = Logger.getLogger(DefaultBidder.class.getName()); /** * The maximum bid this Bidder can make. */ private final int maximumBid; /** * The maximum increment this Bidder can make in its bid. */ private final int increment; /** * The starting bid for this Bidder. */ private final int startBid; /** * Bidder name */ private final String bidderName; /** * Constructs an Bidder with it's maximum bid set to * <code>maximumBid</code> and its increment set to * <code>increment</code> and its start bit set to * <code>startBid</code> * <code>bidderName</code> * * @param iIncrement The increment this agent can use. * @param iMaximumBid The maximum bid this agent can make. * @pararm sName The starting bid amount * @pararm iStartBid The starting bid amount */ public DefaultBidder(final String sName, final int iStartBid, final int iIncrement, final int iMaximumBid) { // validations of arguments if ((iMaximumBid >> 31 != 0) || (iIncrement >> 31 != 0) || (iStartBid >> 31 != 0)) throw new IllegalArgumentException("Negative bids not allowed"); if ((iMaximumBid - iStartBid) < 0) throw new IllegalArgumentException("Maximum Bid should be greater than Start Bid"); if ((iStartBid + iIncrement) > iMaximumBid || ((iMaximumBid - iStartBid) > 0 && (iIncrement == 0))) throw new IllegalArgumentException("Invalid increment Value"); this.maximumBid = iMaximumBid; this.increment = iIncrement; this.startBid = iStartBid; this.bidderName = sName; } /** * Asks the Bidder for a bid, taking into account the last highest bid. * Returns null for no-bid. * * @param lastBid The last bid given. * @return The new bid of the agent */ @Override public Bid getBid(final Bid lastBid) { if(lastBid == null) throw new IllegalArgumentException("Invalid Bid parameter"); Bid nextBid = null; int currentBid = this.startBid; if (this.equals(lastBid.getBidder())) { LOG.info(bidderName + ": I'm not going to outbid myself"); nextBid = lastBid; } else if (lastBid.getBidder() == null) { LOG.info(bidderName + ": First post!"); nextBid = new Bid(this, this.startBid); } else if (this.maximumBid >= lastBid.getAmount()) { LOG.info(bidderName + ": Attempting to make next bid"); while (currentBid <= lastBid.getAmount()) { currentBid = currentBid + this.increment; if (currentBid > this.maximumBid) { LOG.info(bidderName + ": Limit reached"); currentBid = this.maximumBid; break; } } nextBid = new Bid(this, currentBid); } return nextBid; } public String toString() { return "Bidder: " + bidderName; } }
true
c915bafa3b15a12b475221e7d8e383d218de906f
Java
saivarunkoyyana/CapstoneStageTwo
/app/src/main/java/com/example/acer/capstonestagetwo/ModelClass/MovieRating.java
UTF-8
809
2.34375
2
[]
no_license
package com.example.acer.capstonestagetwo.ModelClass; public class MovieRating { String id; String moviesuggestion; String title; public MovieRating() { } public MovieRating(String id, String moviesuggestion, String title) { this.id = id; this.moviesuggestion = moviesuggestion; this.title = title; } public String getId() { return id; } public void setId(String id) { this.id = id; } public String getMoviesuggestion() { return moviesuggestion; } public void setMoviesuggestion(String moviesuggestion) { this.moviesuggestion = moviesuggestion; } public String getTitle() { return title; } public void setTitle(String title) { this.title = title; } }
true
ce22c59cb59ece5015286e9219668cac6ce828be
Java
zrg1215/SelectImage
/choosephoto/src/main/java/com/hp/choosephoto/utils/ToastUtils.java
UTF-8
2,074
2.21875
2
[]
no_license
package com.hp.choosephoto.utils; import android.content.Context; import android.os.Build; import android.widget.Toast; import com.hp.choosephoto.finals.DebugConfig; /** * desc:ToastUtils * Author: zrg * Date: 2017-02-17 09:41 */ public class ToastUtils { private Context mContext; Toast mToast; public ToastUtils(Context context) { mContext = context; } @SuppressWarnings("ResourceType") public void showToastByID(int msgResId, int... duration) { if (mToast != null) { if (Build.VERSION.SDK_INT < Build.VERSION_CODES.ICE_CREAM_SANDWICH) { mToast.cancel(); } } else { int _duration = (duration == null || duration.length == 0) ? 1000 : duration[0]; mToast = mToast.makeText(mContext, msgResId, _duration); } mToast.show(); mToast.setText(msgResId); } @SuppressWarnings("ResourceType") public void showToastByStr(String msg, int... duration) { if (mToast != null) { if (Build.VERSION.SDK_INT < Build.VERSION_CODES.ICE_CREAM_SANDWICH) { mToast.cancel(); } } else { int _duration = (duration == null || duration.length == 0) ? 1000 : duration[0]; mToast = mToast.makeText(mContext, msg, _duration); } mToast.show(); mToast.setText(msg); } @SuppressWarnings("ResourceType") public void showToastByStrForTest(String msg, int... duration) { if (DebugConfig.getToast_IsDebug()) { if (mToast != null) { if (Build.VERSION.SDK_INT < Build.VERSION_CODES.ICE_CREAM_SANDWICH) { mToast.cancel(); } } else { int _duration = (duration == null || duration.length == 0) ? 1000 : duration[0]; mToast = mToast.makeText(mContext, msg, _duration); } mToast.show(); mToast.setText(msg); } } }
true
4f5624f017d80642f05a93113d21026cfe0764a7
Java
wallnerryan/FL_HAND
/src/main/java/net/floodlightcontroller/virtualnetwork/VirtualNetworkWebRoutable.java
UTF-8
1,555
1.882813
2
[ "Apache-2.0" ]
permissive
/** * Copyright 2013, Big Switch Networks, Inc. * * 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 net.floodlightcontroller.virtualnetwork; import org.restlet.Context; import org.restlet.Restlet; import org.restlet.routing.Router; import net.floodlightcontroller.restserver.RestletRoutable; public class VirtualNetworkWebRoutable implements RestletRoutable { @Override public Restlet getRestlet(Context context) { Router router = new Router(context); router.attach("/tenants/{tenant}/networks", NetworkResource.class); // GET router.attach("/tenants/{tenant}/networks/{network}", NetworkResource.class); // PUT, DELETE router.attach("/tenants/{tenant}/networks", NetworkResource.class); // POST router.attach("/tenants/{tenant}/networks/{network}/ports/{port}/attachment", HostResource.class); router.attachDefault(NoOp.class); return router; } @Override public String basePath() { return "/quantum/v1.0"; } }
true
1c93c95e7e6012b90d48e708d30dbf6b8ee2f16d
Java
carlov20/oyster-card-problem
/java-impl/src/main/java/org/oyster/card/MainApplication.java
UTF-8
2,011
2.765625
3
[]
no_license
package org.oyster.card; import lombok.extern.slf4j.Slf4j; import org.oyster.card.dto.Customer; import org.oyster.card.dto.JourneyType; import org.oyster.card.dto.Station; import org.oyster.card.dto.Zone; import org.oyster.card.service.CustomerJourney; import org.oyster.card.service.CustomerJourneyImpl; import org.oyster.card.service.FareCalculatorImpl; import java.math.BigDecimal; import java.util.Arrays; import java.util.HashSet; @Slf4j public class MainApplication { public static void main(String[] args) { Station holbornStation = Station.builder() .name("Holborn") .zone(Zone.ONE) .build(); Station earlsCourtStation = Station.builder() .name("Earl's Court") .zones(new HashSet<>(Arrays.asList(Zone.ONE, Zone.TWO))) .build(); Station wimbledonStation = Station.builder() .name("Wimbledon") .zone(Zone.THREE) .build(); Station hammersmithStation = Station.builder() .name("Hammersmith") .zone(Zone.THREE) .build(); Station chelseaStation = Station.builder() .name("Chelsea") .build(); Customer customer = Customer.builder() .balance(BigDecimal.valueOf(30.00)) .build(); CustomerJourney customerJourney = new CustomerJourneyImpl(new FareCalculatorImpl()); customerJourney.inwardTap(customer, holbornStation, JourneyType.TUBE); customerJourney.outwardTap(customer, earlsCourtStation); customerJourney.inwardTap(customer, earlsCourtStation, JourneyType.BUS); customerJourney.outwardTap(customer, chelseaStation); customerJourney.inwardTap(customer, earlsCourtStation, JourneyType.TUBE); customerJourney.outwardTap(customer, hammersmithStation); log.info("Customer balance is: £{}", customer.getBalance()); } }
true
91b6e3427aec9ed3ea86294762e37b3794d134eb
Java
AlderCape/Economics
/src/com/aldercape/internal/economics/ui/CustomTextField.java
UTF-8
630
2.5
2
[]
no_license
package com.aldercape.internal.economics.ui; import javax.swing.JTextField; public class CustomTextField<T> extends JTextField { private static final long serialVersionUID = -5871629493420093865L; @Override public void setText(String text) { throw new RuntimeException("Should call setValue"); } @Override public String getText() { throw new RuntimeException("Should call getValue"); } public void setValue(T value) { super.setText(value.toString()); } @SuppressWarnings("unchecked") public T getValue() { return (T) super.getText(); } protected String getRawValue() { return super.getText(); } }
true
a3a04ae2eccda911fc6988ca9c33feec4e9dcc16
Java
landerixx/SystemyOperacyjne
/SOzad3/src/cwik3/Odwolanie.java
UTF-8
805
2.59375
3
[]
no_license
package cwik3; import java.io.Serializable; public class Odwolanie implements Serializable { @Override public String toString() { return "[" + wartosc + "] "+ "bit: "+ bit2szansy ; //"("+czasSprowadzenia+")"; } int wartosc; int bit2szansy; int czasSprowadzenia; public int getCzasSprowadzenia() { return czasSprowadzenia; } public void setCzasSprowadzenia(int czasSprowadzenia) { this.czasSprowadzenia = czasSprowadzenia; } public Odwolanie(int wartosc) { super(); this.wartosc = wartosc; czasSprowadzenia=0; bit2szansy=1; } public int getWartosc() { return wartosc; } public void setWartosc(int wartosc) { this.wartosc = wartosc; } public int getBitOdniesienia() { return bit2szansy; } public void setBitOdniesienia(int bitOdniesienia) { this.bit2szansy = bitOdniesienia; } }
true
ef7deb8485531471339c067eb38bf3d7667b97ec
Java
lijian12388806/wps
/src/com/liveneo/plat/web/action/LoginAction.java
UTF-8
15,985
1.898438
2
[]
no_license
package com.liveneo.plat.web.action; import java.util.ArrayList; import java.util.Date; import java.util.HashMap; import java.util.HashSet; import java.util.Iterator; import java.util.List; import java.util.Map; import java.util.Set; import javax.servlet.http.HttpServletRequest; import org.apache.commons.lang3.StringUtils; import org.hibernate.criterion.DetachedCriteria; import org.hibernate.criterion.Restrictions; import com.liveneo.lm.utils.Base64Encode; import com.liveneo.plat.hibernate.dao.Authority; import com.liveneo.plat.hibernate.dao.BdRole; import com.liveneo.plat.hibernate.dao.BdRolemenu; import com.liveneo.plat.hibernate.dao.BdUserinforole; import com.liveneo.plat.hibernate.dao.Menuinfo; import com.liveneo.plat.hibernate.dao.Userinfo; import com.liveneo.plat.hibernate.dao.Workorder; import com.liveneo.plat.hibernate.dao.dao.BdRoleDAO; import com.liveneo.plat.service.impl.MenuinfoService; import com.liveneo.plat.service.impl.RoleService; import com.liveneo.plat.service.impl.UserinfoService; import com.liveneo.plat.service.impl.WorkOrderService; import com.liveneo.plat.utils.DateUtil; import com.liveneo.plat.web.action.base.AbstractActionSupport; import com.liveneo.plat.web.form.SubtotalsForm; import com.liveneo.plat.web.form.UserinfoForm; public class LoginAction extends AbstractActionSupport { private static final long serialVersionUID = 1L; private UserinfoForm userinfoForm; private SubtotalsForm subtotalsForm; private Userinfo userinfo; private UserinfoService userinfoService; private MenuinfoService menuinfoService; private WorkOrderService workOrderService; private RoleService roleService; private String withoutAuthentication; public void setWithoutAuthentication(String withoutAuthentication) { this.withoutAuthentication = withoutAuthentication; } public String execute() { return SUCCESS; } public String login() { if(null != userinfoForm){ }else{ return "failed"; } // this.getSession().invalidate(); String msg = ""; String longinname = userinfoForm.getUsername(); String password = userinfoForm.getUserpwd(); String ctiaddr = userinfoForm.getCtiaddr(); if (null == userinfoForm) { msg = "login.inputUserAndPwd"; this.getRequest().setAttribute("msg", msg); log.info("empty"); return "failed"; } if (StringUtils.isEmpty(longinname)) { msg = getText("login.userNotEmpty"); this.getRequest().setAttribute("msg", msg); log.info("username empty"); return "failed"; } if (StringUtils.isEmpty(password)) { msg = getText("login.pwdNotEmpty"); this.getRequest().setAttribute("msg", msg); log.info("password empty"); return "failed"; } Userinfo userinfoResult = new Userinfo(); userinfoResult = this.userinfoService.queryuserinfoIndex( Userinfo.PROP_USERNAME, longinname); if (userinfoResult == null) { msg = getText("login.nouser"); this.getRequest().setAttribute("msg", msg); log.info("NO USER"); return "failed"; } if (!StringUtils.equals(userinfoResult.getUserstatus(), "Y")) { msg = getText("该用户不可用!"); this.getRequest().setAttribute("msg", msg); log.info("USER DISABLE"); return "failed"; } Base64Encode base64 = new Base64Encode(); if (!StringUtils.equals(base64.encode(password), userinfoResult .getUserpwd())) { msg = getText("login.pwderror"); this.getRequest().setAttribute("msg", msg); log.info("password error"); return "failed"; } userinfo = userinfoResult; //User info this.getSession().setAttribute("userinfo", userinfo); //User role String role = createHtmlRole(userinfo); //menu info String str = this.createHtmlMenu(userinfo); System.out.println("********************>>>>>"+str); this.getSession().setAttribute("menu", str); // 首页统计数据 this.listWorkorder(userinfo); this.getSubtotals(); //软dianhua参数 this.getSession().setAttribute("workNo", userinfo.getAgentno()); this.getSession().setAttribute("ipaddr", userinfo.getCtiaddr()); this.getSession().setAttribute("exten", userinfo.getExtno()); this.getSession().setAttribute("skill", userinfo.getTemp2()); // // 初始化userInfo // UserInfo userInfo = new UserInfo(); // userInfo.setUser(userinfo); // userInfo.setUserid(userinfo.getId().toString()); // userInfo.setUsername(userinfo.getUsername()); // // 在线用户处理 // HttpServletRequest request= this.getRequest(); // HttpServletResponse response= this.getResponse(); // HttpSession session = this.getSession(); // Iterator iter = OnlineListListener.getList().values().iterator(); // String info = ""; // String contextPath = ""; // String href = ""; // String route = ""; // while (iter.hasNext()) { // // 如果是管理员则不限制 // if (userInfo.getUser().getIsadmin().equalsIgnoreCase("true")) { // break; // } // OnlineModel om = (OnlineModel) (iter.next()); // // 控制不能重复登录 // if ((userInfo.getUserid()).equals(((Integer) om.getUserId()) // .toString())) { // info += "用户:" + om.getUserName() + "已在 " + om.getIpAddress() // + " 登陆,请用其它用户名登陆!" + "\\n" // + "如果由于掉线或错误地关闭浏览器窗口而退出,请耐心等待" // + this.getSession().getMaxInactiveInterval() / 60 + "分钟之后再登陆!"; // //request.getContextPath()返回请求的url // if (request.getContextPath() != null // || !request.getContextPath().equals("/")) { // contextPath = request.getContextPath(); // } // href = "http://" + request.getHeader("Host") + contextPath // + "/"; // route = href + ""; // try { // response.setContentType("text/html; charset=UTF-8"); // PrintWriter out = response.getWriter(); // String strURL = "<script language=\"javascript\">"; // strURL += "alert('" + info + "');window.open('" + route // + "','_parent')"; // strURL += "</script>"; // out.println(strURL); // return null; // } catch (Exception e) { // e.printStackTrace(); // } // // } // if (this.getIpAddr(request).equals(om.getIpAddress())) { // info += "IP相同,请不要使用多账户登陆!"; // if (request.getContextPath() != null // || !request.getContextPath().equals("/")) { // contextPath = request.getContextPath(); // } // href = "http://" + request.getHeader("Host") + contextPath // + "/"; // route = href + ""; // try { // response.setContentType("text/html; charset=UTF-8"); // PrintWriter out = response.getWriter(); // String strURL = "<script language=\"javascript\">"; // strURL += "alert('" + info + "');window.open('" + route // + "','_parent')"; // strURL += "</script>"; // out.println(strURL); // return null; // } catch (Exception e) { // e.printStackTrace(); // } // } // // } // java.text.SimpleDateFormat sdf = new java.text.SimpleDateFormat( // "yyyy年MM月dd日HH:mm:ss"); // String time = sdf.format(java.util.Calendar.getInstance().getTime()); // session.setAttribute("online", new OnlineModel(userInfo.getUser() // .getId(), userInfo.getUser().getUsername(), this // .getIpAddr(request), time, 0, session.getId())); this.logService(getRequest()).addLog(this.getRequest(), "LOGTYPE-DL", "login", Userinfo.REF); return SUCCESS; } //ip address private String getIpAddr(HttpServletRequest request) { String ip = request.getHeader("x-forwarded-for"); if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) { ip = request.getHeader("Proxy-Client-IP"); } if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) { ip = request.getHeader("WL-Proxy-Client-IP"); } if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) { ip = request.getRemoteAddr(); } return ip; } // 首页统计数据 private void listWorkorder(Userinfo user) { List<Workorder> l = this.workOrderService .queryWoByDetachedCriteria(this.getDetachedCriteria(user)); this.getSession().setAttribute("workorderIndexList", l); } private DetachedCriteria getDetachedCriteria(Userinfo user) { DetachedCriteria detachedCriteria = DetachedCriteria .forClass(Workorder.class); // detachedCriteria.add(Restrictions.or(Restrictions.eq( // Workorder.PROP_WOSTATUS, "wcl"), Restrictions.or(Restrictions // .eq(Workorder.PROP_WOSTATUS, "dhxcl"), Restrictions.eq( // Workorder.PROP_WOSTATUS, "ywc")))); detachedCriteria.add(Restrictions.or(Restrictions.eq( Workorder.PROP_WOSTATUS, "dhxcl"), Restrictions.eq( Workorder.PROP_WOSTATUS, "ywc"))); if (!StringUtils.equals(user.getIsadmin(), "true")) { detachedCriteria.add(Restrictions.eq(Workorder.PROP_PK_USERINFO, user)); } return detachedCriteria; } public List<Menuinfo> listUserMenu(Userinfo user) { Set<Menuinfo> setlist = new HashSet<Menuinfo>(); List<Menuinfo> listmenu = new ArrayList<Menuinfo>(); if (StringUtils.equals(user.getIsadmin(), "true")) { listmenu = this.menuinfoService.queryAll(); } List<BdUserinforole> listUserrole = this.roleService .queryUserinforoleByUser(user); if (listUserrole.size() > 0) { for (BdUserinforole bur : listUserrole) { List<BdRolemenu> listrolemenu = this.roleService .queryRolemenuByRole(bur.getPkRole()); if (listrolemenu.size() > 0) { for (BdRolemenu rm : listrolemenu) { setlist .add(this.menuinfoService.getlistmenu(rm) .get(0)); } } } } for (Menuinfo m : setlist) { listmenu.add(m); } return listmenu; } public String createHtmlMenu(Userinfo user) { Set<Menuinfo> listsuper = new HashSet<Menuinfo>(); List<Menuinfo> supermenu = new ArrayList<Menuinfo>(); List<Menuinfo> allsupermenu = new ArrayList<Menuinfo>(); List<Menuinfo> listmenu = this.listUserMenu(user); // System.out.println("listmenu:"+listmenu.size()); if (StringUtils.equals(user.getIsadmin(), "true")) { supermenu = this.menuinfoService.querySuperMenuByCriteria(); } else { for (Menuinfo mo : listmenu) { Menuinfo smeun = this.menuinfoService.queryMenuinfoById(mo .getSupermenu()); listsuper.add(smeun); } for (Menuinfo l : listsuper) { supermenu.add(l); } } allsupermenu = this.menuinfoService.querySuperMenuByCriteria(); for (Iterator it = allsupermenu.iterator(); it.hasNext();) { Menuinfo sm=(Menuinfo) it.next(); if (!supermenu.contains(sm)) { it.remove(); } } if(!StringUtils.equals(user.getUsername(), "superadmin")){ for(Iterator it = allsupermenu.iterator(); it.hasNext();){ Menuinfo sms=(Menuinfo) it.next(); if(StringUtils.equals(sms.getMenuname(), "系统设置")){ it.remove(); } } } // System.out.println("supermenu:"+supermenu.size()); List<Menuinfo> list = new ArrayList<Menuinfo>(); StringBuffer str = new StringBuffer(); str.append("<div class=\"accordionContent\">"); str.append("<ul class=\"tree treeFolder\">"); for (Menuinfo s : allsupermenu) { list = this.menuinfoService.queryMenuBySupermenu(s.getId()); str.append("<li>"); str.append("<a>"); str.append(s.getMenuname()); str.append("</a>"); str.append("<ul>"); for (Menuinfo m : list) { if (listmenu.contains(m)) { str.append("<li>"); str.append("<a href=\""); str.append(m.getLinkaddress()); str.append("\""); str.append("target=\"navTab\" rel=\""); str.append(m.getTemp1()); str.append("\" reloadFlag=1>"); str.append(m.getMenuname()); str.append("</a>"); str.append("</li>"); } } str.append("</ul>"); str.append("</li>"); } str.append("</ul>"); str.append("</div>"); return str.toString(); } private Map<String, Object> dataMap; public LoginAction() { // 初始化Map对象 dataMap = new HashMap<String, Object>(); } public String logout() { this.getSession().invalidate(); try { this.logService(getRequest()).addLog(this.getRequest(), "LOGTYPE-DC", "logout", ""); } catch (Exception e) { e.getMessage(); } return SUCCESS; } // 分类汇总 public void getSubtotals() { List<SubtotalsForm> liststf = new ArrayList<SubtotalsForm>(); String nowyear = DateUtil.formatDateByFormat(new Date(), "yyyy"); String nowmonth = DateUtil.formatDateByFormat(new Date(), "MM"); // 一月 for (int i = 1; i <= Integer.parseInt(nowmonth); i++) { SubtotalsForm stf = new SubtotalsForm(); stf.setMonth(i + "月"); stf.setOSampledepend(this.workOrderService.getCountByCriteria(this.getSubtotalsDetachedCriteria(nowyear + "-" + i + "-01","O_Sampledepend"))); stf.setOAmodeldepend(this.workOrderService.getCountByCriteria(this.getSubtotalsDetachedCriteria(nowyear + "-" + i + "-01","O_Amodeldepend"))); stf.setOSampleReq(this.workOrderService.getCountByCriteria(this.getSubtotalsDetachedCriteria(nowyear + "-" + i + "-01","O_SampleReq"))); stf.setOOrderDelivery(this.workOrderService.getCountByCriteria(this.getSubtotalsDetachedCriteria(nowyear + "-" + i + "-01","O_OrderDelivery"))); stf.setOOnsiteservice(this.workOrderService.getCountByCriteria(this.getSubtotalsDetachedCriteria(nowyear + "-" + i + "-01","O_Onsiteservice"))); stf.setOComplainthand(this.workOrderService.getCountByCriteria(this.getSubtotalsDetachedCriteria(nowyear + "-" + i + "-01","O_Complainthand"))); stf.setOReturnReq(this.workOrderService.getCountByCriteria(this.getSubtotalsDetachedCriteria(nowyear + "-" + i + "-01","O_ReturnReq"))); liststf.add(stf); } this.getSession().setAttribute("liststf", liststf); } private DetachedCriteria getSubtotalsDetachedCriteria(String date, String os) { Userinfo user = this.getUserInfo(this.getRequest()); DetachedCriteria detachedCriteria = DetachedCriteria .forClass(Workorder.class); if (StringUtils.isNotEmpty(date)) { detachedCriteria.add(Restrictions.ge(Workorder.PROP_CALLTIME, DateUtil.parseFormatDate(date, "yyyy-MM-dd"))); detachedCriteria.add(Restrictions.le(Workorder.PROP_CALLTIME, DateUtil.parseFormatDate(DateUtil.getMonthEnd(date), "yyyy-MM-dd"))); } if (StringUtils.isNotEmpty(os)) { detachedCriteria.add(Restrictions.eq(Workorder.PROP_ORDERTYPE, os)); } // if(!StringUtils.equals(user.getIsadmin(), "true")){ detachedCriteria.add(Restrictions.eq(Workorder.PROP_PK_USERINFO, user)); // } return detachedCriteria; } public String createHtmlRole(Userinfo user){ Set<BdRole> roles = new HashSet<BdRole>(); Set<Authority> DBauthorities = new HashSet(); List<BdRole> queryAllRole = roleService.queryAllRole(); for(BdRole role : queryAllRole){ for(Authority authority: role.getAuthorities()){ DBauthorities.add(authority); } roles.add(role); } return SUCCESS; } public UserinfoForm getUserinfoForm() { return userinfoForm; } public void setUserinfoForm(UserinfoForm userinfoForm) { this.userinfoForm = userinfoForm; } public Userinfo getUserinfo() { return userinfo; } public void setUserinfo(Userinfo userinfo) { this.userinfo = userinfo; } public UserinfoService getUserinfoService() { return userinfoService; } public void setUserinfoService(UserinfoService userinfoService) { this.userinfoService = userinfoService; } public MenuinfoService getMenuinfoService() { return menuinfoService; } public void setMenuinfoService(MenuinfoService menuinfoService) { this.menuinfoService = menuinfoService; } public RoleService getRoleService() { return roleService; } public void setRoleService(RoleService roleService) { this.roleService = roleService; } public WorkOrderService getWorkOrderService() { return workOrderService; } public void setWorkOrderService(WorkOrderService workOrderService) { this.workOrderService = workOrderService; } public SubtotalsForm getSubtotalsForm() { return subtotalsForm; } public void setSubtotalsForm(SubtotalsForm subtotalsForm) { this.subtotalsForm = subtotalsForm; } }
true
e1134ee20cfec053f4ee538601810bce628d4e56
Java
Lokts0311/csci-3310-project
/app/src/main/java/edu/cuhk/csci3310/project/EventListAdapter.java
UTF-8
6,600
2.234375
2
[]
no_license
package edu.cuhk.csci3310.project; import android.app.Activity; import android.app.AlertDialog; import android.content.Context; import android.content.DialogInterface; import android.content.Intent; import android.os.Bundle; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.Button; import android.widget.TextView; import android.widget.Toast; import androidx.annotation.NonNull; import androidx.recyclerview.widget.RecyclerView; import com.google.firebase.firestore.FirebaseFirestore; import java.util.LinkedList; public class EventListAdapter extends RecyclerView.Adapter<edu.cuhk.csci3310.project.EventListAdapter.EventViewHolder> { private Context context; private LayoutInflater mInflater; private FirebaseFirestore db; private final LinkedList<Event> mEventList; private String mDate; class EventViewHolder extends RecyclerView.ViewHolder { TextView textItemView; Button deleteBtn, changeBtn; final edu.cuhk.csci3310.project.EventListAdapter mAdapter; public EventViewHolder(View itemView, edu.cuhk.csci3310.project.EventListAdapter adapter) { super(itemView); this.mAdapter = adapter; textItemView = itemView.findViewById(R.id.event); deleteBtn = itemView.findViewById(R.id.deleteBtn); changeBtn = itemView.findViewById(R.id.changeDetail); deleteBtn.setOnClickListener(new View.OnClickListener(){ @Override public void onClick(View v){ //Toast.makeText(context, "This is "+mEventList.get(getAdapterPosition()).getDescription(), Toast.LENGTH_SHORT).show(); showAlertDialog(getAdapterPosition(),mAdapter); } }); textItemView.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { // Toast.makeText(context, "After I click", Toast.LENGTH_SHORT).show(); Intent intent = new Intent(context, EventDetailActivity.class); int position = getPosition(); Bundle sendBundle = new Bundle(); sendBundle.putString("location", mEventList.get(position).getLocation()); sendBundle.putString("remark",mEventList.get(position).getRemark() ); sendBundle.putString("cal_burn",mEventList.get(position).getCal_burn() ); sendBundle.putString("description", mEventList.get(position).getDescription()); sendBundle.putString("period", mEventList.get(position).getPeriod()); sendBundle.putString("start_time", mEventList.get(position).getStartTime()); sendBundle.putString("end_time", mEventList.get(position).getEndTime()); sendBundle.putString("web_link", mEventList.get(position).getWebLink()); // sendBundle.putString("web_link", "https://www.cuhk.edu.hk"); sendBundle.putString("date", mDate); intent.putExtras(sendBundle); ((Activity) context).startActivity(intent); } }); changeBtn.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { Intent intent = new Intent(context, AddEventActivity.class); int position = getPosition(); Bundle sendBundle = new Bundle(); sendBundle.putString("location", mEventList.get(position).getLocation()); sendBundle.putString("remark",mEventList.get(position).getRemark() ); sendBundle.putString("cal_burn",mEventList.get(position).getCal_burn() ); sendBundle.putString("description", mEventList.get(position).getDescription()); sendBundle.putString("period", mEventList.get(position).getPeriod()); sendBundle.putString("start_time", mEventList.get(position).getStartTime()); sendBundle.putString("end_time", mEventList.get(position).getEndTime()); sendBundle.putString("web_link", mEventList.get(position).getWebLink()); // sendBundle.putString("web_link", "https://www.cuhk.edu.hk"); sendBundle.putString("Date", mDate); intent.putExtras(sendBundle); ((Activity) context).startActivityForResult(intent,1); // here } }); } } public EventListAdapter(Context context, LinkedList<Event> eventList,String date) { mInflater = LayoutInflater.from(context); this.mEventList = eventList; this.mDate = date; this.context = context; } @NonNull @Override public EventViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) { View mItemView = mInflater.inflate(R.layout.eventlist_item, parent, false); return new EventViewHolder(mItemView, this); } @Override public void onBindViewHolder(@NonNull edu.cuhk.csci3310.project.EventListAdapter.EventViewHolder holder, int position) { String mEventDescription = mEventList.get(position).getDescription(); holder.textItemView.setText(mEventDescription); } @Override public int getItemCount() { return mEventList.size(); } public void showAlertDialog(int position,EventListAdapter adapter){ AlertDialog.Builder alert = new AlertDialog.Builder(context); alert.setTitle("Warning"); alert.setMessage("Are you sure to remove this event?"); alert.setPositiveButton("Yes",new DialogInterface.OnClickListener(){ @Override public void onClick(DialogInterface dialog,int i){ //Toast.makeText(context, "Clicked Yes", Toast.LENGTH_SHORT).show(); db = FirebaseFirestore.getInstance(); db.collection(mDate).document(mEventList.get(position).getDescription()).delete(); mEventList.remove(position); adapter.notifyDataSetChanged(); } }); alert.setNegativeButton("No",null); alert.show(); } }
true
251cfa37e4a2e357c7602d3ec94b3aa2c6643e9c
Java
absolutesingh/CSInterviewPrepJuly
/Java Workspace/julyinterviewprep/src/july13/Solution.java
UTF-8
673
3.53125
4
[]
no_license
package july13; public class Solution { static boolean isPrimeRam(int n) { if(n<=1) return false; if(n==2) return true; for(int i=2;i<n-1;i++) { if(n%i==0) return false; } return true; } static boolean isPrimeSham(int n) { if(n<=1) return false; if(n==2) return true; for(int i=2;i<=Math.sqrt(n);i++) { if(n%i==0) return false; } return true; } public static void main(String[] args) { // TODO Auto-generated method stub int n = 38; if(n%2==0) //Remainder of a%b { System.out.println("Even"); } else { System.out.println("Odd"); } System.out.println(isPrimeRam(n)); System.out.println(isPrimeSham(n)); } }
true
e10fee6319a7e8ce44f4d0cdab52cf8cd547823a
Java
w3woody/j2oc
/J2OC/src/com/chaosinmotion/j2oc/vm/code/op/GetFieldOp.java
UTF-8
815
2.3125
2
[]
no_license
/* GetFieldOp.java * * Created on Feb 6, 2010 by William Edward Woody */ package com.chaosinmotion.j2oc.vm.code.op; import com.chaosinmotion.j2oc.vm.data.constants.Constant; import com.chaosinmotion.j2oc.vm.data.constants.FMIConstant; public class GetFieldOp extends Op { private Op pThis; private FMIConstant field; public GetFieldOp(Op tmpOp, Constant constant) { pThis = tmpOp; field = (FMIConstant)constant; } @Override public boolean isWide() { return field.getDescriptor().getRet().isWide(); } public Op getThis() { return pThis; } public FMIConstant getField() { return field; } @Override public int getPrimitiveType() { return field.getDescriptor().getRet().getPrimitiveType(); } }
true
caa3836b087d6d608cfd1fd83f655ad446e83ff9
Java
jihoonk-1116/JavaOOP-Class
/project3/src/project3/CandleList.java
UTF-8
1,059
3.828125
4
[]
no_license
//CandleList abstract class package project3; public abstract class CandleList { protected CandleNode first; protected CandleNode last; protected int size = 0; public CandleList() { CandleNode cn = new CandleNode(); first = cn; last = cn; size = 0; } public void append(Candle c) { //add a new node into the last of linked list CandleNode n = new CandleNode(c); //Create a new node. if(size == 0) { //if a new node is the first element of the list. last = n; //last will be a new node first = n; //first will be a new node size++; } last.next = n; // the next node of the pointed last node. last = n; // The last node will be the new node. size++; // size + 1 } public String toString() { //Print out using toString method if(first == null) { return "[]"; } CandleNode temp = first; String str = "["; while(temp.next != null) { str += temp.data +"'"; temp = temp.next; } str += temp.data; return str +"]"; } }
true
916fac5b8e8c34a7e7e25a03d192fcfe6dade007
Java
sunlight3d/Aptech
/C2009i/WCD/24-06-2022/de06/src/java/servlets/Question2Servlet.java
UTF-8
2,286
2.46875
2
[]
no_license
/* * 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 servlets; import java.io.IOException; import java.io.PrintWriter; import java.util.Hashtable; import javax.servlet.ServletException; import javax.servlet.http.Cookie; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; /** * * @author w11 */ public class Question2Servlet extends HttpServlet { @Override protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { //validate Hashtable<String, String> errors = new Hashtable<String, String>(); String name = request.getParameter("name"); String address = request.getParameter("address"); String phoneNo = request.getParameter("phoneNo"); String className = request.getParameter("className"); if(name == null || name == "") { errors.put("name", "Name is required"); } if(address == null || address == "") { errors.put("address", "address is required"); } if(phoneNo == null || phoneNo == "") { errors.put("phoneNo", "phoneNo is required"); } if(className == null || className == "") { errors.put("className", "className is required"); } Boolean isValid = errors.size() == 0; request.setAttribute("errors", errors); if(isValid) { //ok response.reset(); response.addCookie(new Cookie("name", name)); response.addCookie(new Cookie("address", address)); response.addCookie(new Cookie("phoneNo", phoneNo)); response.addCookie(new Cookie("className", className)); response.sendRedirect("detail.jsp"); } else { request.getRequestDispatcher("question02.jsp").forward(request, response); } } }
true
53d87266292fc827b3c517b05cb95089d3a1b5e9
Java
saifnalband/JAVA_OOPS
/codes/Lec27/Lec27/Demo278/pack1/Demo278A.java
UTF-8
227
2.8125
3
[]
no_license
package pack1; /* Example 1: protected modifier */ public class Demo278A { protected int rollNo = 555; void msg(){ // protected doesn't work System.out.println("Class A: Hello Java!" + rollNo); } }
true
1ecb56e5d59c2a48fb7f65b964439d30a767b73e
Java
KobeGong/TasksApp
/app/src/main/java/defpackage/cle.java
UTF-8
140
1.789063
2
[]
no_license
package defpackage; /* renamed from: cle reason: default package */ /* compiled from: PG */ interface cle { void e(); void f(); }
true
f95ddc66ea4db1fbab7ee3f5dd81b8042d6d9649
Java
poojakudav309/Ticket-Management-System-
/Ticket Management/src/test/AddTicketTest.java
UTF-8
2,811
2.375
2
[]
no_license
package test; import org.junit.*; import org.openqa.selenium.By; import org.openqa.selenium.WebDriver; import org.openqa.selenium.chrome.ChromeDriver; import org.openqa.selenium.support.ui.Select; public class AddTicketTest { WebDriver driver; @Before public void openAddTicketPage() throws InterruptedException{ System.setProperty("webdriver.chrome.driver","chromedriver.exe"); driver = new ChromeDriver(); driver.get("http://localhost:8080/Ticket_Management/login.jsp"); Thread.sleep(1000); Assert.assertEquals("Login Page", driver.getTitle()); driver.findElement(By.id("username")).sendKeys("robb"); driver.findElement(By.id("password")).sendKeys("robb"); driver.findElement(By.id("submit-login")).click(); Thread.sleep(1000); driver.findElement(By.linkText("Raise Ticket")).click(); Thread.sleep(1000); Assert.assertEquals("add ticket", driver.getTitle()); } @Test public void testaddTicketSuccess() throws InterruptedException{ //driver.findElement(By.id("to")).sendKeys("2"); driver.findElement(By.id("description")).sendKeys("testing ticket"); Select dropdown1 = new Select(driver.findElement(By.id("category1"))); dropdown1.selectByValue("it"); Select dropdown2 = new Select(driver.findElement(By.id("category2"))); dropdown2.selectByValue("software"); Select dropdown3 = new Select(driver.findElement(By.id("category3"))); dropdown3.selectByValue("packages"); driver.findElement(By.id("priority")).sendKeys("1"); Thread.sleep(5000); driver.findElement(By.id("submit-ticket")).click(); Assert.assertEquals("add ticket", driver.getTitle()); String searchBox = driver.findElement(By.id("final_result")).getText(); Thread.sleep(5000); Assert.assertEquals("Successful", searchBox); } @Test public void testaddTicketAlternate() throws InterruptedException{ driver.findElement(By.id("description")).sendKeys(""); Select dropdown1 = new Select(driver.findElement(By.id("category1"))); dropdown1.selectByValue("it"); Select dropdown2 = new Select(driver.findElement(By.id("category2"))); dropdown2.selectByValue("software"); // Select dropdown3 = new Select(driver.findElement(By.id("category2"))); // dropdown3.selectByValue("software"); driver.findElement(By.id("priority")).sendKeys(""); Thread.sleep(5000); driver.findElement(By.id("submit-ticket")).click(); Assert.assertEquals("add ticket", driver.getTitle()); String searchBox = driver.findElement(By.id("final_result")).getText(); Thread.sleep(5000); Assert.assertEquals("Error", searchBox); } @After public void closePage(){ driver.quit(); } }
true
248c49e8dd07be2dd5f904c5e1bd8cd0f456a639
Java
johnandrui/java8Demo
/src/main/java/com/john/www/main/completableFuture/CompletableFuture1.java
UTF-8
1,506
3.296875
3
[]
no_license
package com.john.www.main.completableFuture; import java.util.concurrent.CompletableFuture; import java.util.concurrent.ExecutionException; import java.util.concurrent.TimeUnit; public class CompletableFuture1 { public static void main(String[] args) { //无返回值的Future,默认使用ForkJoin线程池 /* CompletableFuture<Void> hello_future=CompletableFuture.runAsync(()->{ System.out.println("Hello future"); }); CompletableFuture<Integer> integerCompletableFuture=CompletableFuture.supplyAsync(()->123);*/ CompletableFuture<Integer> integerCompletableFuture= CompletableFuture.supplyAsync(()->{ System.out.println("开始执行运算!"); try { TimeUnit.SECONDS.sleep(3); } catch (InterruptedException e) { e.printStackTrace(); } int a=1/0; System.out.println("结束执行运算!"); return 233; }); try { Integer result=integerCompletableFuture.whenComplete((a,b)->{ System.out.println("Result:"+a); System.out.println("Exception:"+b); }).exceptionally(e ->{ System.out.println(e.getMessage()); return 888; }).get(); System.out.println("final result:"+result); } catch (InterruptedException e) { e.printStackTrace(); } catch (ExecutionException e) { e.printStackTrace(); } } }
true
546e7526d1f49879bccb6601e96b713bbc8e9e26
Java
mcouto82/grupomult-api
/src/main/java/br/com/oficina/domain/Carro.java
UTF-8
3,679
2.21875
2
[]
no_license
package br.com.oficina.domain; import org.hibernate.annotations.Cache; import org.hibernate.annotations.CacheConcurrencyStrategy; import org.springframework.data.elasticsearch.annotations.Document; import javax.persistence.*; import javax.validation.constraints.*; import java.io.Serializable; import java.time.LocalDate; import java.util.Objects; /** * A Carro. */ @Entity @Table(name = "carro") @Cache(usage = CacheConcurrencyStrategy.NONSTRICT_READ_WRITE) @Document(indexName = "carro") public class Carro implements Serializable { private static final long serialVersionUID = 1L; @Id @GeneratedValue(strategy = GenerationType.SEQUENCE, generator = "sequenceGenerator") @SequenceGenerator(name = "sequenceGenerator") private Long id; @Column(name = "codigo") private Long codigo; @Column(name = "descricao") private String descricao; @Column(name = "data_criacao") private LocalDate dataCriacao; @Column(name = "data_atualizacao") private LocalDate dataAtualizacao; @ManyToOne(optional = false) @NotNull private TipoCarro tipoCarro; // jhipster-needle-entity-add-field - JHipster will add fields here, do not remove public Long getId() { return id; } public void setId(Long id) { this.id = id; } public Long getCodigo() { return codigo; } public Carro codigo(Long codigo) { this.codigo = codigo; return this; } public void setCodigo(Long codigo) { this.codigo = codigo; } public String getDescricao() { return descricao; } public Carro descricao(String descricao) { this.descricao = descricao; return this; } public void setDescricao(String descricao) { this.descricao = descricao; } public LocalDate getDataCriacao() { return dataCriacao; } public Carro dataCriacao(LocalDate dataCriacao) { this.dataCriacao = dataCriacao; return this; } public void setDataCriacao(LocalDate dataCriacao) { this.dataCriacao = dataCriacao; } public LocalDate getDataAtualizacao() { return dataAtualizacao; } public Carro dataAtualizacao(LocalDate dataAtualizacao) { this.dataAtualizacao = dataAtualizacao; return this; } public void setDataAtualizacao(LocalDate dataAtualizacao) { this.dataAtualizacao = dataAtualizacao; } public TipoCarro getTipoCarro() { return tipoCarro; } public Carro tipoCarro(TipoCarro tipoCarro) { this.tipoCarro = tipoCarro; return this; } public void setTipoCarro(TipoCarro tipoCarro) { this.tipoCarro = tipoCarro; } // jhipster-needle-entity-add-getters-setters - JHipster will add getters and setters here, do not remove @Override public boolean equals(Object o) { if (this == o) { return true; } if (o == null || getClass() != o.getClass()) { return false; } Carro carro = (Carro) o; if (carro.getId() == null || getId() == null) { return false; } return Objects.equals(getId(), carro.getId()); } @Override public int hashCode() { return Objects.hashCode(getId()); } @Override public String toString() { return "Carro{" + "id=" + getId() + ", codigo='" + getCodigo() + "'" + ", descricao='" + getDescricao() + "'" + ", dataCriacao='" + getDataCriacao() + "'" + ", dataAtualizacao='" + getDataAtualizacao() + "'" + "}"; } }
true
423ba202ee7cca975689fd21662f4fc623b8fc1b
Java
RakinShafqatChowdhury/MovieApp
/app/src/main/java/com/paperfly/movieapp/Network/MovieApi.java
UTF-8
597
1.929688
2
[]
no_license
package com.paperfly.movieapp.Network; import com.paperfly.movieapp.Model.MovieList; import com.paperfly.movieapp.Model.Search; import com.paperfly.movieapp.Model.SearchedMovies; import java.util.List; import retrofit2.Call; import retrofit2.http.GET; import retrofit2.http.Path; import retrofit2.http.Query; //?i=tt3896198 & apikey=ded1ae92 public interface MovieApi { @GET("?") Call<SearchedMovies> getSearchedMovies(@Query("s") String title, @Query("apiKey") String api_key); @GET("?") Call<MovieList> getMovies(@Query("t") String title, @Query("apiKey") String api_key); }
true
651909f2784ca6d45b00240a5d1f3050c4fbf7ed
Java
maximecharron/airchitecture
/src/main/java/ca/ulaval/glo4003/air/domain/flight/FlightQueryBuilder.java
UTF-8
873
2.25
2
[]
no_license
package ca.ulaval.glo4003.air.domain.flight; import java.time.LocalDateTime; import java.util.List; import java.util.Optional; public interface FlightQueryBuilder { FlightQueryBuilder isGoingTo(String airport); FlightQueryBuilder isDepartingFrom(String airport); FlightQueryBuilder isLeavingAfterOrOn(LocalDateTime date); FlightQueryBuilder isLeavingOn(LocalDateTime date); FlightQueryBuilder acceptsWeight(double weight); FlightQueryBuilder isAirVivant(); FlightQueryBuilder hasSeatsAvailable(boolean economySeats, boolean regularSeats, boolean businessSeats); FlightQueryBuilder hasAirlineCompany(String flightNumber); List<PassengerFlight> getPassengerFlights(); List<AirCargoFlight> getAirCargoFlights(); Optional<PassengerFlight> getOnePassengerFlight(); Optional<AirCargoFlight> getOneAirCargoFlight(); }
true
1266d1bd2c61b5d5ca267102e4c81cdb8dcf6dea
Java
choquidownn25/Plantilla-Android
/app/src/main/java/com/example/plantilla/sqllite/activity/MainActivityPais.java
UTF-8
4,152
2.34375
2
[]
no_license
package com.example.plantilla.sqllite.activity; import android.content.Intent; import android.database.Cursor; import android.graphics.Paint; import android.os.Bundle; import android.support.annotation.Nullable; import android.support.design.widget.CollapsingToolbarLayout; import android.support.design.widget.FloatingActionButton; import android.support.v7.app.ActionBar; import android.support.v7.app.AppCompatActivity; import android.support.v7.widget.DefaultItemAnimator; import android.support.v7.widget.LinearLayoutManager; import android.support.v7.widget.RecyclerView; import android.support.v7.widget.Toolbar; import android.view.View; import com.example.plantilla.R; import com.example.plantilla.sqllite.adapter.PaisRecyclerAdapter; import com.example.plantilla.sqllite.database.DBArticulo; import com.example.plantilla.sqllite.database.DBManager; import com.example.plantilla.sqllite.helper.DatabaseHelper; import com.example.plantilla.sqllite.models.Articulo; import com.example.plantilla.sqllite.models.Pais; import java.util.ArrayList; import java.util.List; public class MainActivityPais extends AppCompatActivity { //<editor-fold desc="Atributos"> /* Declarar instancias globales */ private RecyclerView recycler; private RecyclerView.LayoutManager lManager; private DBManager dbManager; final String[] from = new String[] { DatabaseHelper._ID, DatabaseHelper.SUBJECT, DatabaseHelper.DESC }; final int[] to = new int[] { R.id.id, R.id.title, R.id.desc }; private CollapsingToolbarLayout collapsingToolbarLayout = null; private PaisRecyclerAdapter adapter; ArrayList<Pais> paisArrayList=new ArrayList<>(); ArrayList<Articulo> articuloArrayList=new ArrayList<>(); //</editor-fold> @Override protected void onCreate(@Nullable Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main_sqllite_pais); dbManager = new DBManager(this); dbManager.open(); Cursor cursor = dbManager.fetch(); // Inicializar Animes Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar); setSupportActionBar(toolbar); ActionBar actionBar = getSupportActionBar(); actionBar.setDisplayHomeAsUpEnabled(true); FloatingActionButton fab = (FloatingActionButton) findViewById(R.id.fab); fab.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { //SHOW INPUT DIALOG //showDialog(); Intent intent = new Intent(MainActivityPais.this, AddPaisActivity.class); startActivity(intent); } }); //recycler recycler= (RecyclerView) findViewById(R.id.card_recycler_view_pais); //SET PROPS recycler.setLayoutManager(new LinearLayoutManager(this)); recycler.setItemAnimator(new DefaultItemAnimator()); //ADAPTER adapter=new PaisRecyclerAdapter(this,paisArrayList); //RETRIEVE retrieve(); collapsingToolbarLayout = (CollapsingToolbarLayout) findViewById(R.id.collapsing_toolbar); collapsingToolbarLayout.setTitle(getResources().getString(R.string.saludo) ); } //RETREIEV private void retrieve() { paisArrayList.clear(); //DBManager db=new DBManager(this); DBArticulo db =new DBArticulo(this); db.open(); //Recibe el cursor Cursor c=db.getAll(); //LOOP AND ADD TO ARRAYLIST while (c.moveToNext()) { int id=c.getInt(0); String nombre=c.getString(1); String description=c.getString(2); //Pais p=new Pais(id,nombre,description); Articulo p=new Articulo(id,nombre,description); //ADD al array lis del pais articuloArrayList.add(p); } //Comprueba si la lista no esta vacía if(!(paisArrayList.size()<1)) { recycler.setAdapter(adapter); } db.close();; } }
true
6ba29bcada5283258a73898714f9ec265d0d1313
Java
corock/jx
/spring-boot/spring-boot-mysite/src/main/java/com/corock/mysite/config/WebConfig.java
UTF-8
4,031
2.078125
2
[]
no_license
package com.corock.mysite.config; import java.nio.charset.Charset; import java.text.SimpleDateFormat; import java.util.Arrays; import java.util.List; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; import org.springframework.http.MediaType; import org.springframework.http.converter.HttpMessageConverter; import org.springframework.http.converter.StringHttpMessageConverter; import org.springframework.http.converter.json.Jackson2ObjectMapperBuilder; import org.springframework.http.converter.json.MappingJackson2HttpMessageConverter; import org.springframework.web.method.support.HandlerMethodArgumentResolver; import org.springframework.web.servlet.config.annotation.InterceptorRegistry; import org.springframework.web.servlet.config.annotation.ResourceHandlerRegistry; import org.springframework.web.servlet.config.annotation.WebMvcConfigurer; import com.corock.security.AuthInterceptor; import com.corock.security.AuthLoginInterceptor; import com.corock.security.AuthLogoutInterceptor; import com.corock.security.AuthUserHandlerMethodArgumentResolver; import com.fasterxml.jackson.module.paramnames.ParameterNamesModule; @Configuration public class WebConfig implements WebMvcConfigurer { /** Argument resolver */ @Bean public AuthUserHandlerMethodArgumentResolver authUserHandlerMethodArgumentResolver() { return new AuthUserHandlerMethodArgumentResolver(); } @Override public void addArgumentResolvers(List<HandlerMethodArgumentResolver> argumentResolvers) { argumentResolvers.add( authUserHandlerMethodArgumentResolver() ); } /** Interceptor */ @Bean public AuthLoginInterceptor authLoginInterceptor() { return new AuthLoginInterceptor(); } @Bean public AuthLogoutInterceptor authLogoutInterceptor() { return new AuthLogoutInterceptor(); } @Bean public AuthInterceptor authInterceptor() { return new AuthInterceptor(); } @Override public void addInterceptors(InterceptorRegistry registry) { // There is no toss to back registry.addInterceptor( authLoginInterceptor() ) .addPathPatterns( "/user/auth" ); registry.addInterceptor( authLogoutInterceptor() ) .addPathPatterns( "/user/logout" ); // There is toss to back registry.addInterceptor( authInterceptor() ) .addPathPatterns( "/**" ) .excludePathPatterns( "/user/auth" ) .excludePathPatterns( "/user/logout" ) .excludePathPatterns( "/assets/*" ); } /** Resources mapping to url */ @Override public void addResourceHandlers(ResourceHandlerRegistry registry) { registry.addResourceHandler( "/uploads/images/**" ) .addResourceLocations( "file:/uploads/" ); } /** Message converters */ @Bean public MappingJackson2HttpMessageConverter mappingJackson2HttpMessageConverter() { Jackson2ObjectMapperBuilder builder = new Jackson2ObjectMapperBuilder().indentOutput( true ) .dateFormat( new SimpleDateFormat("yyyy-MM-dd") ) .modulesToInstall( new ParameterNamesModule() ); MappingJackson2HttpMessageConverter converter = new MappingJackson2HttpMessageConverter(); converter.setSupportedMediaTypes(Arrays.asList( new MediaType("application", "json", Charset.forName("utf-8")) )); return converter; } @Bean public StringHttpMessageConverter stringHttpMessageConverter() { StringHttpMessageConverter converter = new StringHttpMessageConverter(); converter.setSupportedMediaTypes(Arrays.asList( new MediaType("text", "html", Charset.forName("utf-8")) )); return converter; } @Override public void configureMessageConverters( List<HttpMessageConverter<?>> converters ) { converters.add( mappingJackson2HttpMessageConverter() ); converters.add( stringHttpMessageConverter() ); } // public void m() { // Thread t = new Thread(new Runnable() { // @Override // public void run() { // System.out.println("Hello"); // } // }); // // Thread t2 = new Thread(() -> { // System.out.println("Hello"); // }); // // t.start(); // t2.start(); // } }
true
04f39959fe7ff871fb7ab8b154f30c7068474985
Java
phwd/quest-tracker
/hollywood/com.oculus.horizon-Horizon/sources/X/C07160rJ.java
UTF-8
2,313
1.742188
2
[]
no_license
package X; import android.os.Bundle; import android.view.View; import android.view.accessibility.AccessibilityEvent; import android.view.accessibility.AccessibilityNodeInfo; import androidx.core.view.accessibility.AccessibilityNodeInfoCompat; import androidx.viewpager.widget.ViewPager; /* renamed from: X.0rJ reason: invalid class name and case insensitive filesystem */ public class C07160rJ extends AnonymousClass06n { public final /* synthetic */ ViewPager A00; public C07160rJ(ViewPager viewPager) { this.A00 = viewPager; } @Override // X.AnonymousClass06n public final void A00(View view, AccessibilityEvent accessibilityEvent) { super.A00(view, accessibilityEvent); accessibilityEvent.setClassName(ViewPager.ACCESSIBILITY_CLASS_NAME); accessibilityEvent.setScrollable(false); accessibilityEvent.getEventType(); } @Override // X.AnonymousClass06n public final void A01(View view, AccessibilityNodeInfoCompat accessibilityNodeInfoCompat) { super.A01(view, accessibilityNodeInfoCompat); AccessibilityNodeInfo accessibilityNodeInfo = accessibilityNodeInfoCompat.A00; accessibilityNodeInfo.setClassName(ViewPager.ACCESSIBILITY_CLASS_NAME); accessibilityNodeInfo.setScrollable(false); ViewPager viewPager = this.A00; if (viewPager.canScrollHorizontally(1)) { accessibilityNodeInfo.addAction(4096); } if (viewPager.canScrollHorizontally(-1)) { accessibilityNodeInfo.addAction(8192); } } @Override // X.AnonymousClass06n public final boolean A02(View view, int i, Bundle bundle) { ViewPager viewPager; int i2; if (!super.A02(view, i, bundle)) { if (i != 4096) { if (i == 8192) { viewPager = this.A00; if (viewPager.canScrollHorizontally(-1)) { i2 = viewPager.mCurItem - 1; } } return false; } viewPager = this.A00; if (viewPager.canScrollHorizontally(1)) { i2 = viewPager.mCurItem + 1; } return false; viewPager.setCurrentItem(i2); } return true; } }
true
1846449b39cc410dc10976779ddcf33013d6eece
Java
0jinxing/wechat-apk-source
/com/tencent/mm/plugin/mmsight/segment/VideoSegmentUI$12.java
UTF-8
1,768
1.609375
2
[]
no_license
package com.tencent.mm.plugin.mmsight.segment; import android.widget.Toast; import com.tencent.matrix.trace.core.AppMethodBeat; import com.tencent.mm.sdk.platformtools.ab; import java.util.concurrent.CountDownLatch; final class VideoSegmentUI$12 implements c.a { VideoSegmentUI$12(VideoSegmentUI paramVideoSegmentUI) { } public final void iY(boolean paramBoolean) { AppMethodBeat.i(55043); if (paramBoolean) { Toast.makeText(this.ozN, 2131301447, 1).show(); ab.e("MicroMsg.VideoSegmentUI", "Not Supported init SegmentSeekBar failed."); VideoSegmentUI.m(this.ozN); this.ozN.finish(); VideoSegmentUI.b(this.ozN); AppMethodBeat.o(55043); } while (true) { return; if ((!this.ozN.isFinishing()) && (VideoSegmentUI.j(this.ozN) != null)) { VideoSegmentUI.a(this.ozN, VideoSegmentUI.j(this.ozN).getDurationMs()); ab.i("MicroMsg.VideoSegmentUI", "SeekBar.onPrepared success %d", new Object[] { Integer.valueOf(VideoSegmentUI.e(this.ozN)) }); } try { if (VideoSegmentUI.d(this.ozN) != null) VideoSegmentUI.d(this.ozN).setLoop((int)(VideoSegmentUI.e(this.ozN) * VideoSegmentUI.j(this.ozN).bQa()), (int)(VideoSegmentUI.e(this.ozN) * VideoSegmentUI.j(this.ozN).bQb())); label185: VideoSegmentUI.o(this.ozN).countDown(); AppMethodBeat.o(55043); } catch (Exception localException) { break label185; } } } } /* Location: C:\Users\Lin\Downloads\dex-tools-2.1-SNAPSHOT\dex-tools-2.1-SNAPSHOT\classes8-dex2jar.jar * Qualified Name: com.tencent.mm.plugin.mmsight.segment.VideoSegmentUI.12 * JD-Core Version: 0.6.2 */
true
a2f3e1441966e966f805c08f4e6c9c2b58113432
Java
alinursu/Smart-Booking
/backend/src/main/java/com/bfourclass/smartbooking/user/UserService.java
UTF-8
7,319
2.140625
2
[]
no_license
package com.bfourclass.smartbooking.user; import com.bfourclass.smartbooking.email.EmailService; import com.bfourclass.smartbooking.hotel.HotelModel; import com.bfourclass.smartbooking.hotel.HotelRepository; import com.bfourclass.smartbooking.hotel.json.HotelJSON; import com.bfourclass.smartbooking.requests.ResponseError; import com.bfourclass.smartbooking.security.StringGenerator; import com.bfourclass.smartbooking.user.auth.SecurityContext; import com.bfourclass.smartbooking.user.json.OwnerRegisterJSONRequest; import com.bfourclass.smartbooking.user.json.UserRegisterJSONRequest; import com.bfourclass.smartbooking.user_history.UserHistoryModel; import com.bfourclass.smartbooking.user_history.UserHistoryRepository; import com.bfourclass.smartbooking.user_verification.UserVerification; import com.bfourclass.smartbooking.user_verification.UserVerificationService; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.http.HttpStatus; import org.springframework.http.ResponseEntity; import org.springframework.stereotype.Service; import java.util.ArrayList; import java.util.List; @Service public class UserService { private final UserRepository userRepository; private final EmailService emailService; private final UserVerificationService userVerificationService; private final SecurityContext securityContext; private final HotelRepository hotelRepository; private final UserHistoryRepository userHistoryRepository; @Autowired public UserService(UserRepository userRepository, EmailService emailService, UserVerificationService userVerificationService, SecurityContext securityContext, HotelRepository hotelRepository, UserHistoryRepository userHistoryRepository) { this.userRepository = userRepository; this.emailService = emailService; this.userVerificationService = userVerificationService; this.securityContext = securityContext; this.hotelRepository = hotelRepository; this.userHistoryRepository = userHistoryRepository; } public boolean checkTokenIsValid(String token) { return securityContext.exists(token); } public UserModel getUserFromToken(String token) { String username = securityContext.extractUsername(token); return userRepository.findUserByUsername(username); } public void createUserByForm(UserRegisterJSONRequest registerForm) { UserModel userModel = registerForm.toUser(); userRepository.save(userModel); } public void createOwnerByForm(OwnerRegisterJSONRequest registerForm) { UserModel userModel = registerForm.toUser(); userRepository.save(userModel); } public boolean sendUserActivationEmail(UserModel userModel) { String activationToken = generateUserActivationToken(userModel); return emailService.sendEmailVerificationEmail(userModel.getUsername(), userModel.getEmail(), activationToken, ""); } public String generateUserActivationToken(UserModel userModel) { String verificationKey = StringGenerator.generate(); UserVerification userVerification = new UserVerification(userModel, verificationKey); userVerificationService.save(userVerification); return verificationKey; } public void makeAdmin(String username) { UserModel userModel = getUserByLogin(username); userModel.setAdmin(true); userRepository.save(userModel); } public void removeAdmin(String username) { UserModel userModel = getUserByLogin(username); userModel.setAdmin(false); userRepository.save(userModel); } public String loginUserReturnToken(UserModel user) { return securityContext.authenticateUserReturnToken(user); } public boolean userExists(String login) { return userRepository.findUserByUsername(login) != null || userRepository.findUserByEmail(login) != null; } public ResponseEntity<Object> checkUserToken(String token) { // check if token exists in request if (token == null) { return new ResponseEntity<>(new ResponseError("Missing Authorization header"), HttpStatus.UNAUTHORIZED); } // check if token exists in SecurityContext if (!checkTokenIsValid(token)) { return new ResponseEntity<>(new ResponseError("Invalid Authorization header"), HttpStatus.UNAUTHORIZED); } return null; } public UserModel getUserByLogin(String login) { UserModel userModel = userRepository.findUserByUsername(login); if (userModel != null) { return userModel; } return userRepository.findUserByEmail(login); } public List<HotelModel> getOwnerHotels(String ownerName) { UserModel userModel = userRepository.findUserByUsername(ownerName); List<HotelModel> response = null; if (userModel.isHotelOwner()) { response = hotelRepository.findByOwnerId(userModel.getId()); } return response; } public List<HotelJSON> getUserHotels(UserModel userModel) { List<HotelJSON> response = new ArrayList<>(); List<HotelModel> hotels = userModel.getUserHotels(); for (HotelModel hotelModel : hotels) { response.add(new HotelJSON(hotelModel.getId(), hotelModel.getIdentifier(), hotelModel.getHotelUrl(), hotelModel.getHotelName(), hotelModel.getLocationName(), hotelModel.getAverageRating(), hotelModel.getVotes(),hotelModel.getPhotoLink(),hotelModel.getDescription(),hotelModel.getPrice())); } return response; } /* TODO, it's a little bit weird this logic*/ public void addHotel(UserModel userModel, HotelModel hotelModel) { if (hotelRepository.findById(hotelModel.getId()).isEmpty()) { hotelRepository.save(hotelModel); } userModel.addHotel(hotelModel); userRepository.save(userModel); } public void deleteUserHotel(UserModel userModel, HotelModel hotelModel) { userModel.deleteUserHotel(hotelModel); userRepository.save(userModel); } public void addUserSearchHistory(UserModel userModel, String query) { UserHistoryModel userHistoryModel = new UserHistoryModel(query); userHistoryRepository.save(userHistoryModel); userModel.addHistory(userHistoryModel); userRepository.save(userModel); } public void removeSearchedHotel(UserModel userModel, long id) { userModel.removeSearchedHotelById(id); userRepository.save(userModel); UserHistoryModel userHistoryModel = userHistoryRepository.getOne(id); userHistoryRepository.delete(userHistoryModel); } public void sendEmailVerificationUpdate(UserModel userModel, String newEmail) { String activationToken = generateUserActivationToken(userModel); emailService.sendEmailVerificationEmail(userModel.getUsername(), newEmail, activationToken, "&new_email=" + newEmail); } public void updateUser(UserModel userModel) { userRepository.save(userModel); } public void saveUser(UserModel userModel) { userRepository.save(userModel); } public List<UserModel> getAll() { return userRepository.findAll(); } }
true
f1230e0dabd41eb831312d04a0b69138230c5161
Java
zhoux738/JSE
/tools/ide/eclipse/plugin/src/info/julang/ide/editors/scanning/FontStyle.java
UTF-8
530
2.375
2
[]
no_license
package info.julang.ide.editors.scanning; import info.julang.ide.themes.PluginColor; public enum FontStyle { KEYWORD(PluginColor.KEYWORD, true), COMMENT(PluginColor.COMMENT, false), LITERAL(PluginColor.LITERAL, false), REGEX(PluginColor.REGEX, false) ; private FontStyle(PluginColor color, boolean isBold) { this.color = color; this.isBold = isBold; } private PluginColor color; private boolean isBold; public PluginColor getColor() { return color; } public boolean isBold() { return isBold; } }
true
f108dc7a25dcbad00667e44441cd702be4737a15
Java
kay66668/subject
/src/main/java/org/java/dao/LeaveOfficeMapper.java
UTF-8
430
1.875
2
[]
no_license
package org.java.dao; import org.apache.ibatis.annotations.Mapper; import org.java.entity.LeaveOffice; @Mapper public interface LeaveOfficeMapper { int deleteByPrimaryKey(Integer id); int insert(LeaveOffice record); int insertSelective(LeaveOffice record); LeaveOffice selectByPrimaryKey(Integer id); int updateByPrimaryKeySelective(LeaveOffice record); int updateByPrimaryKey(LeaveOffice record); }
true
0c0dae9e9fc68f40b3fb75d2099b94e2f922de9c
Java
sayalip22/Student_Result_Management_In_Java
/src/studentHome.java
UTF-8
26,721
2.109375
2
[]
no_license
import java.sql.Connection; import java.sql.DriverManager; import java.sql.ResultSet; import java.sql.*; import java.sql.Statement; import javax.swing.JOptionPane; import javax.swing.JTextField; /* * Click nbfs://nbhost/SystemFileSystem/Templates/Licenses/license-default.txt to change this license * Click nbfs://nbhost/SystemFileSystem/Templates/GUIForms/JFrame.java to edit this template */ /** * * @author Aditya */ public class studentHome extends javax.swing.JFrame { /** * Creates new form studentHome */ public studentHome() { initComponents(); } public studentHome(String rollno) { initComponents(); rno.setText(rollno); } /** * This method is called from within the constructor to initialize the form. * WARNING: Do NOT modify this code. The content of this method is always * regenerated by the Form Editor. */ @SuppressWarnings("unchecked") // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents private void initComponents() { jPanel1 = new javax.swing.JPanel(); jLabel1 = new javax.swing.JLabel(); jLabel2 = new javax.swing.JLabel(); Cource = new javax.swing.JTextField(); Branch = new javax.swing.JTextField(); jLabel3 = new javax.swing.JLabel(); Name = new javax.swing.JTextField(); jLabel4 = new javax.swing.JLabel(); rno = new javax.swing.JTextField(); jLabel5 = new javax.swing.JLabel(); jLabel6 = new javax.swing.JLabel(); Gender = new javax.swing.JTextField(); Father = new javax.swing.JTextField(); jPanel2 = new javax.swing.JPanel(); jLabel7 = new javax.swing.JLabel(); Chemistry = new javax.swing.JLabel(); jLabel9 = new javax.swing.JLabel(); jLabel10 = new javax.swing.JLabel(); jLabel11 = new javax.swing.JLabel(); jLabel12 = new javax.swing.JLabel(); jLabel13 = new javax.swing.JLabel(); jLabel14 = new javax.swing.JLabel(); jLabel15 = new javax.swing.JLabel(); a = new javax.swing.JTextField(); jLabel8 = new javax.swing.JLabel(); jLabel25 = new javax.swing.JLabel(); jLabel26 = new javax.swing.JLabel(); jLabel27 = new javax.swing.JLabel(); jLabel28 = new javax.swing.JLabel(); jLabel31 = new javax.swing.JLabel(); jLabel32 = new javax.swing.JLabel(); jLabel33 = new javax.swing.JLabel(); jLabel34 = new javax.swing.JLabel(); jLabel35 = new javax.swing.JLabel(); jLabel36 = new javax.swing.JLabel(); jLabel37 = new javax.swing.JLabel(); d = new javax.swing.JTextField(); c = new javax.swing.JTextField(); tot = new javax.swing.JTextField(); e = new javax.swing.JTextField(); b = new javax.swing.JTextField(); jButton1 = new javax.swing.JButton(); passfail = new javax.swing.JTextField(); Per = new javax.swing.JTextField(); setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE); addComponentListener(new java.awt.event.ComponentAdapter() { public void componentShown(java.awt.event.ComponentEvent evt) { formComponentShown(evt); } }); jPanel1.setBackground(new java.awt.Color(204, 255, 255)); jPanel1.setBorder(javax.swing.BorderFactory.createTitledBorder(new javax.swing.border.LineBorder(new java.awt.Color(255, 0, 0), 5, true), "Result", javax.swing.border.TitledBorder.DEFAULT_JUSTIFICATION, javax.swing.border.TitledBorder.DEFAULT_POSITION, new java.awt.Font("Dialog", 3, 18), new java.awt.Color(255, 0, 0))); // NOI18N jPanel1.setForeground(new java.awt.Color(204, 255, 255)); jLabel1.setForeground(new java.awt.Color(0, 0, 0)); jLabel1.setText("Cource name"); jLabel2.setForeground(new java.awt.Color(0, 0, 0)); jLabel2.setText("Branch Name"); jLabel3.setForeground(new java.awt.Color(0, 0, 0)); jLabel3.setText("Name"); jLabel4.setForeground(new java.awt.Color(0, 0, 0)); jLabel4.setText("Roll Number"); jLabel5.setForeground(new java.awt.Color(0, 0, 0)); jLabel5.setText("Gender"); jLabel6.setForeground(new java.awt.Color(0, 0, 0)); jLabel6.setText("Father Name"); jPanel2.setBackground(new java.awt.Color(51, 255, 255)); jPanel2.setForeground(new java.awt.Color(0, 0, 0)); jLabel7.setForeground(new java.awt.Color(0, 0, 0)); jLabel7.setText("Physics"); Chemistry.setForeground(new java.awt.Color(0, 0, 0)); Chemistry.setText("Chemistry"); jLabel9.setForeground(new java.awt.Color(0, 0, 0)); jLabel9.setText("Computer Science"); jLabel10.setForeground(new java.awt.Color(0, 0, 0)); jLabel10.setText("Maths"); jLabel11.setForeground(new java.awt.Color(0, 0, 0)); jLabel11.setText("Passing marks"); jLabel12.setForeground(new java.awt.Color(0, 0, 0)); jLabel12.setText(" Total Marks"); jLabel13.setForeground(new java.awt.Color(0, 0, 0)); jLabel13.setText("Marks Obtained"); jLabel14.setForeground(new java.awt.Color(0, 0, 0)); jLabel14.setText("Total Marks"); jLabel15.setForeground(new java.awt.Color(0, 0, 0)); jLabel15.setText("Electronics"); jLabel8.setForeground(new java.awt.Color(0, 0, 0)); jLabel8.setText("100"); jLabel25.setForeground(new java.awt.Color(0, 0, 0)); jLabel25.setText("100"); jLabel26.setForeground(new java.awt.Color(0, 0, 0)); jLabel26.setText("100"); jLabel27.setForeground(new java.awt.Color(0, 0, 0)); jLabel27.setText("100"); jLabel28.setForeground(new java.awt.Color(0, 0, 0)); jLabel28.setText("500"); jLabel31.setForeground(new java.awt.Color(0, 0, 0)); jLabel31.setText("100"); jLabel32.setForeground(new java.awt.Color(0, 0, 0)); jLabel32.setText("30"); jLabel33.setForeground(new java.awt.Color(0, 0, 0)); jLabel33.setText("30"); jLabel34.setForeground(new java.awt.Color(0, 0, 0)); jLabel34.setText("30"); jLabel35.setForeground(new java.awt.Color(0, 0, 0)); jLabel35.setText("30"); jLabel36.setForeground(new java.awt.Color(0, 0, 0)); jLabel36.setText("30"); jLabel37.setForeground(new java.awt.Color(0, 0, 0)); jLabel37.setText("150"); jButton1.setText("Back"); jButton1.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { jButton1ActionPerformed(evt); } }); Per.setText("jTextField1"); javax.swing.GroupLayout jPanel2Layout = new javax.swing.GroupLayout(jPanel2); jPanel2.setLayout(jPanel2Layout); jPanel2Layout.setHorizontalGroup( jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(jPanel2Layout.createSequentialGroup() .addContainerGap() .addGroup(jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING) .addComponent(jLabel9, javax.swing.GroupLayout.Alignment.LEADING) .addComponent(jLabel10, javax.swing.GroupLayout.Alignment.LEADING) .addComponent(jLabel15, javax.swing.GroupLayout.Alignment.LEADING) .addComponent(jLabel7, javax.swing.GroupLayout.Alignment.LEADING) .addComponent(Chemistry, javax.swing.GroupLayout.Alignment.LEADING) .addComponent(jLabel14, javax.swing.GroupLayout.Alignment.LEADING)) .addGap(88, 88, 88) .addGroup(jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addComponent(jLabel12) .addComponent(jLabel8) .addComponent(jLabel31) .addComponent(jLabel25) .addComponent(jLabel26) .addComponent(jLabel27) .addComponent(jLabel28)) .addGap(87, 87, 87) .addGroup(jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addComponent(jLabel36) .addComponent(jLabel35) .addComponent(jLabel34) .addComponent(jLabel33) .addComponent(jLabel32) .addComponent(jLabel11) .addComponent(jLabel37)) .addGap(54, 54, 54) .addGroup(jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(jPanel2Layout.createSequentialGroup() .addComponent(e, javax.swing.GroupLayout.PREFERRED_SIZE, 75, javax.swing.GroupLayout.PREFERRED_SIZE) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, 56, Short.MAX_VALUE) .addComponent(passfail, javax.swing.GroupLayout.PREFERRED_SIZE, 82, javax.swing.GroupLayout.PREFERRED_SIZE) .addContainerGap()) .addGroup(jPanel2Layout.createSequentialGroup() .addComponent(tot, javax.swing.GroupLayout.PREFERRED_SIZE, 75, javax.swing.GroupLayout.PREFERRED_SIZE) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE) .addComponent(jButton1) .addGap(36, 36, 36)) .addGroup(jPanel2Layout.createSequentialGroup() .addGroup(jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addComponent(jLabel13) .addComponent(a, javax.swing.GroupLayout.PREFERRED_SIZE, 75, javax.swing.GroupLayout.PREFERRED_SIZE) .addComponent(d, javax.swing.GroupLayout.PREFERRED_SIZE, 75, javax.swing.GroupLayout.PREFERRED_SIZE) .addComponent(c, javax.swing.GroupLayout.PREFERRED_SIZE, 75, javax.swing.GroupLayout.PREFERRED_SIZE) .addComponent(b, javax.swing.GroupLayout.PREFERRED_SIZE, 75, javax.swing.GroupLayout.PREFERRED_SIZE)) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE) .addComponent(Per, javax.swing.GroupLayout.PREFERRED_SIZE, 82, javax.swing.GroupLayout.PREFERRED_SIZE) .addContainerGap()))) ); jPanel2Layout.setVerticalGroup( jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(jPanel2Layout.createSequentialGroup() .addGroup(jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(jPanel2Layout.createSequentialGroup() .addGap(4, 4, 4) .addComponent(jLabel12)) .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE) .addComponent(jLabel13) .addComponent(jLabel11))) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED) .addGroup(jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE) .addComponent(jLabel7) .addComponent(a, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE) .addComponent(jLabel8) .addComponent(jLabel32)) .addGroup(jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(jPanel2Layout.createSequentialGroup() .addGap(29, 29, 29) .addGroup(jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE) .addComponent(Chemistry) .addComponent(jLabel31) .addComponent(jLabel33))) .addGroup(jPanel2Layout.createSequentialGroup() .addGap(18, 18, 18) .addComponent(b, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, 26, Short.MAX_VALUE) .addGroup(jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE) .addComponent(jLabel9) .addComponent(jLabel25) .addComponent(jLabel34) .addComponent(c, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)) .addGap(22, 22, 22) .addGroup(jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE) .addComponent(jLabel10) .addComponent(jLabel26) .addComponent(jLabel35) .addComponent(d, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE) .addComponent(Per, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)) .addGap(25, 25, 25) .addGroup(jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE) .addComponent(jLabel15) .addComponent(jLabel27) .addComponent(jLabel36) .addComponent(e, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE) .addComponent(passfail, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)) .addGap(22, 22, 22) .addGroup(jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE) .addComponent(jLabel14) .addComponent(jLabel28) .addComponent(jLabel37) .addComponent(tot, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE) .addComponent(jButton1)) .addGap(16, 16, 16)) ); javax.swing.GroupLayout jPanel1Layout = new javax.swing.GroupLayout(jPanel1); jPanel1.setLayout(jPanel1Layout); jPanel1Layout.setHorizontalGroup( jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(jPanel1Layout.createSequentialGroup() .addContainerGap() .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addComponent(jLabel1) .addComponent(jLabel3) .addComponent(jLabel5)) .addGap(41, 41, 41) .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false) .addComponent(Cource) .addComponent(Name) .addComponent(Gender, javax.swing.GroupLayout.DEFAULT_SIZE, 130, Short.MAX_VALUE)) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE) .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addComponent(jLabel2) .addComponent(jLabel4) .addComponent(jLabel6)) .addGap(53, 53, 53) .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false) .addComponent(Branch) .addComponent(rno) .addComponent(Father, javax.swing.GroupLayout.DEFAULT_SIZE, 128, Short.MAX_VALUE)) .addGap(83, 83, 83)) .addComponent(jPanel2, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE) ); jPanel1Layout.setVerticalGroup( jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(jPanel1Layout.createSequentialGroup() .addContainerGap() .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE) .addComponent(jLabel1) .addComponent(jLabel2) .addComponent(Cource, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE) .addComponent(Branch, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)) .addGap(27, 27, 27) .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE) .addComponent(jLabel3) .addComponent(Name, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE) .addComponent(jLabel4) .addComponent(rno, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)) .addGap(26, 26, 26) .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE) .addComponent(jLabel5) .addComponent(jLabel6) .addComponent(Gender, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE) .addComponent(Father, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addComponent(jPanel2, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)) ); javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane()); getContentPane().setLayout(layout); layout.setHorizontalGroup( layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addComponent(jPanel1, javax.swing.GroupLayout.Alignment.TRAILING, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE) ); layout.setVerticalGroup( layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addComponent(jPanel1, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE) ); pack(); }// </editor-fold>//GEN-END:initComponents private void formComponentShown(java.awt.event.ComponentEvent evt) {//GEN-FIRST:event_formComponentShown String rollno = rno.getText(); try { Class.forName("com.mysql.cj.jdbc.Driver"); Connection con = DriverManager.getConnection("jdbc:mysql://localhost:3306/result","root","root"); Statement st = con.createStatement(); ResultSet rs = st.executeQuery("select * from student inner join result where student.rollno='"+rollno+"' and result.rollno='"+rollno+"'"); if(rs.next()){ Cource.setText(rs.getString(2)); Name.setText(rs.getString(4)); Gender.setText(rs.getString(5)); Branch.setText(rs.getString(3)); Father.setText(rs.getString(6)); a.setText(rs.getString(8)); b.setText(rs.getString(9)); c.setText(rs.getString(10)); d.setText(rs.getString(11)); e.setText(rs.getString(12)); int s1 = Integer.parseInt(a.getText()); int s2 = Integer.parseInt(b.getText()); int s3 = Integer.parseInt(c.getText()); int s4 = Integer.parseInt(d.getText()); int s5 = Integer.parseInt(e.getText()); int total = s1+s2+s3+s4+s5; String s = String.valueOf(total); tot.setText(s); double per = total/5.0; Per.setText(""+per); String greade; int ct=0; if(s1>=30) ct++; if(s2>=30) ct++; if(s3>=30) ct++; if(s4>=30) ct++; if(s5>=30) ct++; if(ct >=5){ if(per >=75){ greade="Disctinction"; } else if(per >=60){ greade="First class"; } else if(per >=55){ greade="Second class"; } else { greade="Pass"; } } else if(ct >=3){ greade="ATKT"; }else{ greade="Fail"; } passfail.setText(""+greade); // if(s1<30 || s2<30 || s3<30 || s4<30 ||s5<30){ // passfail.setText("Fail"); // }else{ // passfail.setText("Pass"); // } } } catch (Exception e) { JOptionPane.showMessageDialog(null, "Connection Problem!"); } a.setEditable(false); b.setEditable(false); c.setEditable(false); d.setEditable(false); Per.setEditable(false); e.setEditable(false); rno.setEditable(false); passfail.setEditable(false); Cource.setEditable(false); Name.setEditable(false); Gender.setEditable(false); Branch.setEditable(false); Father.setEditable(false); }//GEN-LAST:event_formComponentShown private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton1ActionPerformed setVisible(false); new studIndex().setVisible(true); }//GEN-LAST:event_jButton1ActionPerformed /** * @param args the command line arguments */ public static void main(String args[]) { /* Set the Nimbus look and feel */ //<editor-fold defaultstate="collapsed" desc=" Look and feel setting code (optional) "> /* If Nimbus (introduced in Java SE 6) is not available, stay with the default look and feel. * For details see http://download.oracle.com/javase/tutorial/uiswing/lookandfeel/plaf.html */ try { for (javax.swing.UIManager.LookAndFeelInfo info : javax.swing.UIManager.getInstalledLookAndFeels()) { if ("Windows".equals(info.getName())) { javax.swing.UIManager.setLookAndFeel(info.getClassName()); break; } } } catch (ClassNotFoundException ex) { java.util.logging.Logger.getLogger(studentHome.class.getName()).log(java.util.logging.Level.SEVERE, null, ex); } catch (InstantiationException ex) { java.util.logging.Logger.getLogger(studentHome.class.getName()).log(java.util.logging.Level.SEVERE, null, ex); } catch (IllegalAccessException ex) { java.util.logging.Logger.getLogger(studentHome.class.getName()).log(java.util.logging.Level.SEVERE, null, ex); } catch (javax.swing.UnsupportedLookAndFeelException ex) { java.util.logging.Logger.getLogger(studentHome.class.getName()).log(java.util.logging.Level.SEVERE, null, ex); } //</editor-fold> /* Create and display the form */ java.awt.EventQueue.invokeLater(new Runnable() { public void run() { new studentHome().setVisible(true); } }); } // Variables declaration - do not modify//GEN-BEGIN:variables private javax.swing.JTextField Branch; private javax.swing.JLabel Chemistry; private javax.swing.JTextField Cource; private javax.swing.JTextField Father; private javax.swing.JTextField Gender; private javax.swing.JTextField Name; private javax.swing.JTextField Per; private javax.swing.JTextField a; private javax.swing.JTextField b; private javax.swing.JTextField c; private javax.swing.JTextField d; private javax.swing.JTextField e; private javax.swing.JButton jButton1; private javax.swing.JLabel jLabel1; private javax.swing.JLabel jLabel10; private javax.swing.JLabel jLabel11; private javax.swing.JLabel jLabel12; private javax.swing.JLabel jLabel13; private javax.swing.JLabel jLabel14; private javax.swing.JLabel jLabel15; private javax.swing.JLabel jLabel2; private javax.swing.JLabel jLabel25; private javax.swing.JLabel jLabel26; private javax.swing.JLabel jLabel27; private javax.swing.JLabel jLabel28; private javax.swing.JLabel jLabel3; private javax.swing.JLabel jLabel31; private javax.swing.JLabel jLabel32; private javax.swing.JLabel jLabel33; private javax.swing.JLabel jLabel34; private javax.swing.JLabel jLabel35; private javax.swing.JLabel jLabel36; private javax.swing.JLabel jLabel37; private javax.swing.JLabel jLabel4; private javax.swing.JLabel jLabel5; private javax.swing.JLabel jLabel6; private javax.swing.JLabel jLabel7; private javax.swing.JLabel jLabel8; private javax.swing.JLabel jLabel9; private javax.swing.JPanel jPanel1; private javax.swing.JPanel jPanel2; private javax.swing.JTextField passfail; private javax.swing.JTextField rno; private javax.swing.JTextField tot; // End of variables declaration//GEN-END:variables }
true
1598498b19180c8c167c1e90cba3a8c74825235d
Java
D3Dall/ProjetJava
/ProjetJava/src/gestionfichier/FichierCSV.java
UTF-8
698
3
3
[]
no_license
package gestionfichier; import java.io.File; import java.io.FileNotFoundException; import java.util.ArrayList; import java.util.Scanner; public abstract class FichierCSV implements BaseDeDonnees{ protected File path; public FichierCSV(String path) { this.path=new File(path); } public FichierCSV(File path) { this.path=path; } public ArrayList<String> lecture(){ ArrayList<String> lignes = new ArrayList<String>(); Scanner sc; try { sc = new Scanner(path); sc.nextLine(); while (sc.hasNextLine()) { lignes.add(sc.nextLine()); } } catch (FileNotFoundException e) { //Erreur fichier vide ou inexistant e.printStackTrace(); } return lignes; } }
true
5e4579a477c4c8d4370a4e85e73d73cddd20adfe
Java
mrfawy/enigma-yarn
/src/main/java/com/tito/enigma/stream/StreamCombiner.java
UTF-8
1,249
2.78125
3
[ "Apache-2.0", "MIT" ]
permissive
package com.tito.enigma.stream; import java.nio.ByteBuffer; import java.util.ArrayList; import java.util.List; import com.tito.enigma.component.Util; public class StreamCombiner { public ByteBuffer combine(ByteBuffer input, List<ByteBuffer> machineMapping, boolean reversed) { if(input.position()!=0){ input.flip(); } int inputSize = input.limit(); ByteBuffer output = ByteBuffer.allocate(inputSize); for (ByteBuffer machineMap : machineMapping) { if (machineMap.position() != 0) { machineMap.flip(); } } List<ByteBuffer> machineMappingSequence = new ArrayList<>(); // reverse sequence of machines when reversed if (reversed) { for (int j = machineMapping.size() - 1; j >= 0; j--) { machineMappingSequence.add(machineMapping.get(j)); } } else { machineMappingSequence = machineMapping; } for (int i = 0; i < inputSize; i++) { byte inputByte = input.get(); for (ByteBuffer machineMap : machineMappingSequence) { byte[] map = new byte[256]; machineMap.get(map); if (reversed) { map = Util.reverseByteMap(map); } inputByte = map[Util.toUnsigned(inputByte)]; } output.put(inputByte); } return output; } }
true
334784f90d16ad6a815cb16ae4276b07b7a75dde
Java
nemehecat123/JAVAA------
/Loterija.java
UTF-8
1,364
3.5
4
[]
no_license
import java.util.Random; import java.util.Scanner; public class Loterija { public static void main(String []args) { Random random = new Random(); int random1 = random.nextInt(10); int random2 = random.nextInt(10); int random3 = random.nextInt(10); Scanner input = new Scanner(System.in); int a = input.nextInt(); int b = input.nextInt(); int c = input.nextInt(); input.close(); System.out.println("vnesite srečne 3 številke"); int j; if (a==random1){ System.out.println("prva št je pravilna"); j= input.nextInt(); }else{ System.out.println("prva številka je napačna"); j= input.nextInt(); } int k; if (b==random2){ System.out.println("druga št je prav"); k= input.nextInt(); }else{ System.out.println("druga št je napačna"); k= input.nextInt(); } int m; if (c==random3){ System.out.println("tretja št je prav"); m= input.nextInt(); }else{ System.out.println("tretja št je napačna"); m= input.nextInt(); } if ((j+k+m)==6){ System.out.println("zadel si loterijo"); } } }
true
49719af108cbdf612199ed205940d1268b2cf585
Java
dualapp/appowner
/AppOwnner/src/com/appowner/model/AssetCategory.java
UTF-8
2,053
2.28125
2
[]
no_license
package com.appowner.model; import java.io.Serializable; import javax.persistence.Cacheable; import javax.persistence.Column; import javax.persistence.Entity; import javax.persistence.GeneratedValue; import javax.persistence.GenerationType; import javax.persistence.Id; import javax.persistence.Table; import org.hibernate.annotations.Cache; import org.hibernate.annotations.CacheConcurrencyStrategy; @Table(name="tb_assetscategory") @Cacheable(true) @Cache(usage=CacheConcurrencyStrategy.READ_WRITE) @Entity public class AssetCategory implements Serializable,Comparable{ /** * */ private static final long serialVersionUID = 1L; @Id @GeneratedValue(strategy = GenerationType.AUTO) @Column private Integer int_assetcatId; @Column(name="var_organizationname") private String str_OrganizationName; public Integer getInt_AppartmentId() { return int_AppartmentId; } public void setInt_AppartmentId(Integer int_AppartmentId) { this.int_AppartmentId = int_AppartmentId; } @Column private Integer int_AppartmentId; @Column(name="var_assetcat_name") private String str_assetcat_name; public Integer getInt_assetcatId() { return int_assetcatId; } public String getStr_OrganizationName() { return str_OrganizationName; } public void setStr_OrganizationName(String str_OrganizationName) { this.str_OrganizationName = str_OrganizationName; } public void setInt_assetcatId(Integer int_assetcatId) { this.int_assetcatId = int_assetcatId; } public String getStr_assetcat_name() { return str_assetcat_name; } public void setStr_assetcat_name(String str_assetcat_name) { this.str_assetcat_name = str_assetcat_name; } @Override public int compareTo(Object assetCategory) { // TODO Auto-generated method stub Integer aid=((AssetCategory)assetCategory).getInt_assetcatId(); /* For Ascending order*/ // return this.int_FacilityBookId; /* For Descending order do like this */ return aid-this.int_assetcatId; } }
true
93c5b9ae81fcf01e963d34a4954971b83901839e
Java
cerijerome/ceri
/ceri-common/src/test/java/ceri/common/function/FluentBehavior.java
UTF-8
952
2.65625
3
[]
no_license
package ceri.common.function; import static ceri.common.test.AssertUtil.assertEquals; import static ceri.common.test.AssertUtil.assertThrown; import org.junit.Test; import ceri.common.test.Captor; public class FluentBehavior { @Test public void shouldApplyConsumer() { Captor.OfInt capturer = Captor.ofInt(); FluentTest test = new FluentTest(3); test.apply(t -> capturer.accept(t.id)).apply(null).apply(t -> capturer.accept(-t.id)); capturer.verifyInt(3, -3); } @Test public void shouldMapToObject() { FluentTest test = new FluentTest(3); assertEquals(test.map(t -> String.valueOf(t.id)), "3"); assertThrown(() -> test.map(null)); } @Test public void shouldMapToInt() { FluentTest test = new FluentTest(3); assertEquals(test.mapToInt(t -> t.id), 3); assertThrown(() -> test.mapToInt(null)); } static class FluentTest implements Fluent<FluentTest> { final int id; FluentTest(int id) { this.id = id; } } }
true
1a8a580cf8f29b838cfb6b1aa10138f137838fa4
Java
sceners/sdloader
/org.sdloader.launcher/src/org/sdloader/launcher/Activator.java
UTF-8
2,867
2.109375
2
[]
no_license
package org.sdloader.launcher; import org.eclipse.core.resources.IProject; import org.eclipse.core.runtime.CoreException; import org.eclipse.debug.core.DebugEvent; import org.eclipse.debug.core.DebugPlugin; import org.eclipse.debug.core.IDebugEventSetListener; import org.eclipse.debug.core.ILaunch; import org.eclipse.debug.core.model.IProcess; import org.eclipse.ui.plugin.AbstractUIPlugin; import org.osgi.framework.BundleContext; import org.sdloader.launcher.util.LaunchUtil; import org.sdloader.launcher.util.LogUtil; /** * The activator class controls the plug-in life cycle */ public class Activator extends AbstractUIPlugin { // The plug-in ID public static final String PLUGIN_ID = "org.sdloader.launcher"; // The shared instance private static Activator plugin; /** * The constructor */ public Activator() { } /* * (non-Javadoc) * * @see org.eclipse.ui.plugin.AbstractUIPlugin#start(org.osgi.framework.BundleContext) */ public void start(BundleContext context) throws Exception { super.start(context); DebugPlugin debugPlugin = DebugPlugin.getDefault(); debugPlugin.addDebugEventListener(new IDebugEventSetListener() { public void handleDebugEvents(DebugEvent[] events) { for (int i = 0; i < events.length; i++) { DebugEvent debugEvent = events[i]; if (debugEvent.getKind() == DebugEvent.TERMINATE) { Object o = debugEvent.getSource(); if (o instanceof IProcess) { try { ILaunch launch = ((IProcess) o).getLaunch(); String id = launch.getLaunchConfiguration() .getType().getIdentifier(); if(Constants.ID_SDLOADER_LAUNCH_CONFIG.equals(id)) { IProject project = LaunchUtil.getProject(launch); Activator.setLaunch(project, launch); } } catch (CoreException e) { LogUtil.log(getDefault(), e); } } } } } }); } public static void setLaunch(IProject project, ILaunch launch) { if(project != null) { try { project.setSessionProperty(Constants.KEY_SERVER_STATE, launch); } catch (CoreException e) { LogUtil.log(getDefault(), e); } } } public static ILaunch getLaunch(IProject project) { if(project != null) { try { return (ILaunch) project.getSessionProperty(Constants.KEY_SERVER_STATE); } catch (CoreException e) { LogUtil.log(getDefault(), e); } } return null; } /* * (non-Javadoc) * * @see org.eclipse.ui.plugin.AbstractUIPlugin#stop(org.osgi.framework.BundleContext) */ public void stop(BundleContext context) throws Exception { plugin = null; super.stop(context); } /** * Returns the shared instance * * @return the shared instance */ public static Activator getDefault() { return plugin; } }
true
d92ddf9089e553695465df1e117c9fc799677d7e
Java
fujaba/NetworkParser
/src/test/java/de/uniks/networkparser/test/model/util/FullMessageCreator.java
UTF-8
843
2.453125
2
[ "MIT" ]
permissive
package de.uniks.networkparser.test.model.util; import de.uniks.networkparser.interfaces.SendableEntityCreator; import de.uniks.networkparser.test.model.FullMessage; public class FullMessageCreator implements SendableEntityCreator { @Override public String[] getProperties() { return new String[] { FullMessage.PROPERTY_TEXT, FullMessage.PROPERTY_VALUE, FullMessage.PROPERTY_DATE, FullMessage.PROPERTY_EMPTYVALUE, FullMessage.PROPERTY_LOCATION }; } @Override public Object getSendableInstance(boolean reference) { return new FullMessage(); } @Override public Object getValue(Object entity, String attribute) { return ((FullMessage) entity).get(attribute); } @Override public boolean setValue(Object entity, String attribute, Object value, String typ) { return ((FullMessage) entity).set(attribute, value); } }
true
4318051ff71599f097fa21c7544879a11fc90447
Java
sylar2019/meAndroidLibs
/common/src/main/java/me/android/library/common/store/IStoreService.java
UTF-8
552
2.03125
2
[]
no_license
package me.android.library.common.store; import java.util.List; import me.java.library.common.Identifiable; import me.java.library.common.service.Serviceable; /** * 实体管理接口 * * @param <T> * @param <ID> * @author sylar */ public interface IStoreService<T extends Identifiable<ID>, ID> extends Serviceable { long count(); boolean containsId(ID id); T queryById(ID id); List<T> queryAll(); boolean add(T t); boolean delete(T t); boolean update(T t); T getDefault(); void setDefault(T t); }
true
d3360cd6c1e04ce6ec94273f9f76dfaf81f462e3
Java
mobilemaster128/firebaseRealtimechat
/app/src/main/java/com/anonymous/messaging/adapters/ItemListingRecyclerAdapter.java
UTF-8
7,730
2.328125
2
[]
no_license
package com.anonymous.messaging.adapters; import android.content.Context; import android.graphics.Color; import android.support.v7.widget.RecyclerView; import android.text.TextUtils; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.TextView; import com.anonymous.messaging.R; import com.anonymous.messaging.models.Chat; import com.anonymous.messaging.models.Item; import com.anonymous.messaging.models.Say; import com.anonymous.messaging.models.Service; import com.anonymous.messaging.models.Whisper; import com.anonymous.messaging.utils.Constants; import com.anonymous.messaging.utils.SharedPrefUtil; import java.text.SimpleDateFormat; import java.util.ArrayList; import java.util.Date; import java.util.List; /** * Author: Kartik Sharma * Created on: 8/28/2016 , 2:23 PM * Project: FirebaseChat */ public class ItemListingRecyclerAdapter extends RecyclerView.Adapter<ItemListingRecyclerAdapter.ViewHolder> { private List<Item> mItems; public ItemListingRecyclerAdapter(List<Item> items) { Item service = new Item(new Service("No Message", "", System.currentTimeMillis())); if (mItems == null) { mItems = new ArrayList<Item>(); } mItems.add(service); for (int index = 0; index < items.size(); index++) { this.mItems.add(items.get(index)); } } public void set(int index, Item item) { if (mItems == null) { mItems = new ArrayList<Item>(); } if (index == 0 || index < mItems.size()) { mItems.set(index, item); notifyItemChanged(index); } } public void add(Item item) { mItems.add(item); notifyItemInserted(mItems.size() - 1); } public void reset() { while (mItems.size() > 0) { mItems.remove(0); notifyItemRemoved(0); } } public int count() { return mItems.size(); } public void remove(Item item) { int position = mItems.indexOf(item); mItems.remove(position); notifyItemRemoved(position); } public void removeBySay(Say say) { for (int index = 0; index < mItems.size(); index++) { if (TextUtils.equals(mItems.get(index).senderuId, say.uId) && mItems.get(index).timestamp == say.timestamp) { mItems.remove(index); notifyItemRemoved(index); } } } public void removeByWhisper(Whisper whipser) { for (int index = 0; index < mItems.size(); index++) { if (TextUtils.equals(mItems.get(index).senderuId, whipser.uId) && mItems.get(index).timestamp == whipser.timestamp) { mItems.remove(index); notifyItemRemoved(index); } } } public void removeByChat(Chat chat) { for (int index = 0; index < mItems.size(); index++) { } } public void removeByKey(String key) { for (int index = 0; index < mItems.size(); index++) { if (TextUtils.equals(mItems.get(index).key, key)) { mItems.remove(index); notifyItemRemoved(index); } } } @Override public ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) { View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.item_all_listing, parent, false); return new ViewHolder(view); } @Override public void onBindViewHolder(ViewHolder holder, int position) { Item item = mItems.get(position); SimpleDateFormat formatter = new SimpleDateFormat("hh:mm a"); switch (item.item_type) { case Constants.SAY_TYPE: holder.txtItemTitle.setText("My Whisper"); if (item.message.length() > 25) { holder.txtItemMessage.setText(item.message.substring(0, 25) + "..."); } else { holder.txtItemMessage.setText(item.message); } if (item.count > 0) { holder.txtItemCount.setText(String.format("%d", item.count)); holder.txtItemCount.setVisibility(View.VISIBLE); } else { holder.txtItemCount.setVisibility(View.INVISIBLE); } holder.txtItemDate.setText(formatter.format(new Date(item.timestamp))); break; case Constants.WHISPER_TYPE: holder.txtItemTitle.setText("Whisper from " + item.name); if (item.message.length() > 25) { holder.txtItemMessage.setText(item.message.substring(0, 25) + "..."); } else { holder.txtItemMessage.setText(item.message); } if (item.count > 0) { holder.txtItemCount.setText(String.format("%d", item.count)); holder.txtItemCount.setVisibility(View.VISIBLE); } else { holder.txtItemCount.setVisibility(View.INVISIBLE); } holder.txtItemDate.setText(formatter.format(new Date(item.timestamp))); break; case Constants.SERVICE_TYPE: holder.txtItemTitle.setText("yril community"); if (item.message.length() > 25) { holder.txtItemMessage.setText(item.message.substring(0, 25) + "..."); } else { holder.txtItemMessage.setText(item.message); } holder.txtItemCount.setVisibility(View.INVISIBLE); if (item.count > 0) { holder.itemView.setBackgroundResource(R.color.pink_200); } else { holder.itemView.setBackgroundColor(Color.TRANSPARENT); } holder.txtItemDate.setText(formatter.format(new Date(item.timestamp))); break; case Constants.CHAT_TYPE: if (item.name.isEmpty()) { holder.txtItemTitle.setText(Constants.NICK_NAME); } else { holder.txtItemTitle.setText(item.name); } if (item.message.length() > 25) { holder.txtItemMessage.setText(item.message.substring(0, 25) + "..."); } else { holder.txtItemMessage.setText(item.message); } if (item.count > 0) { holder.txtItemCount.setText(String.format("%d", item.count)); holder.txtItemCount.setVisibility(View.VISIBLE); } else { holder.txtItemCount.setVisibility(View.INVISIBLE); } holder.txtItemDate.setText(formatter.format(new Date(item.timestamp))); break; } } @Override public int getItemCount() { if (mItems != null) { return mItems.size(); } return 0; } public Item getItem(int position) { return mItems.get(position); } static class ViewHolder extends RecyclerView.ViewHolder { private TextView txtItemTitle, txtItemMessage, txtItemCount, txtItemDate; ViewHolder(View itemView) { super(itemView); txtItemTitle = (TextView) itemView.findViewById(R.id.text_view_title); txtItemMessage = (TextView) itemView.findViewById(R.id.text_view_message); txtItemCount = (TextView) itemView.findViewById(R.id.text_view_count); txtItemDate = (TextView) itemView.findViewById(R.id.text_view_date); } } }
true
ac976ed8693d46b50cbb0e8734b28db4892b112d
Java
jihyoun14/VendingMachine
/src/homework/COFFEE.java
UHC
808
3.453125
3
[]
no_license
package homework; //name, price, numOfPurchased, numOfStock public class COFFEE { protected String Name; //̸ protected int Price; // protected int numOfPurchased = 0; //ȸ protected int numOfStock = 10; // public COFFEE(String name, int price) { this.Name = name; // = {"AMERICANO", "ESPRESSO", "LATTE", "CAPPUCCINO", "CAFFMOCHA"}; this.Price = price; // = {1000, 800, 1200, 1500, 1500}; } public void setNumOfPurchased() { numOfPurchased++; } public int getNumOfPurchased() { return numOfPurchased; } public void setNumOfStock() { numOfStock--; } public int getNumOfStock() { return numOfStock; } public boolean isEmpty() { if (this.getNumOfStock() == 0) return true; else return false; } }
true
b15495b4c46d090cdf385b3fc3dcac74df4102a7
Java
liuqiang12/workflow-dev
/workflow-rest/src/test/java/com/workflow/rest/RestApplicationTest.java
UTF-8
1,190
1.914063
2
[]
no_license
package com.workflow.rest; import org.junit.Test; import org.junit.runner.RunWith; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Value; import org.springframework.boot.test.context.SpringBootTest; import org.springframework.data.redis.core.RedisTemplate; import org.springframework.test.context.TestPropertySource; import org.springframework.test.context.junit4.SpringRunner; /** * user.setUsername("DELL"); * user.setPassword("root"); */ @RunWith(SpringRunner.class) @TestPropertySource(locations = {"classpath:rest.properties"}) @SpringBootTest public class RestApplicationTest { @Autowired RedisTemplate redisTemplate; @Value("${REDIS_USERID_KEY}") private String REDIS_USERID_KEY; @Test public void testDataSource() { // userService.updateUserPassword("2a8e48c8-9d09-4ef4-892c-b3436070297c","12345678","123456"); // redisService.cacheSet(REDIS_USERID_KEY,8); // redisService.cacheSet(REDIS_USERID_KEY,10); // redisService.deleteSet(REDIS_USERID_KEY,8); // System.out.println(redisService.setHasValue(REDIS_USERID_KEY,5)); // postsDao.findAll(); } }
true
c921bca0ff412c3a9eae9ad11db29f6a18e1f56f
Java
VaibhawPandey/interview
/src/com/competitiveCodes/VPCodingBlocks/DynamicProgramming/EditDistanceProblem.java
UTF-8
999
3.265625
3
[ "Apache-2.0" ]
permissive
package com.competitiveCodes.VPCodingBlocks.DynamicProgramming; /* * Reference :- https://www.youtube.com/watch?v=UKxWcCRPZmQ * */ public class EditDistanceProblem { public static void main(String args[]){ String input="cast",output="cats"; int inpLength=input.length(); int outLength=output.length(); int dp[][]=new int[inpLength+1][outLength+1]; for (int i=1;i<=inpLength;i++) dp[i][0] = dp[i-1][0] + 1; for (int j=1;j<=outLength;j++) dp[0][j] = dp[0][j-1] + 1; dp[0][0]= 0; for (int i=1;i<=inpLength;i++){ for (int j=1;j<=outLength;j++){ int q1= dp[i-1][j-1]; // Reflection int q2= dp[i-1][j]; // Deletion int q3 = dp[i][j-1]; // Insertion /* Logic in note book*/ dp[i][j] = Math.min(q1,Math.min(q2,q3)) + (input.charAt(i-1) != output.charAt(j-1) ? 1:0); } } System.out.println(dp[inpLength][outLength]); } }
true
7e07c9114ab89127176fe8f77b437764000a7e4d
Java
JiedaokouWangguan/leetcode
/day6_3/Question645.java
UTF-8
492
2.5
2
[]
no_license
public class Question645{ public int[] findErrorNums(int[] nums){ int[] nums1 = new int[nums.length+1]; int[] result = new int[2]; for(int i = 0;i<nums.length;i++){ nums1[nums[i]] += 1; if(nums1[nums[i]] == 2) result[0] = nums[i]; } for(int i = 1;i<nums1.length;i++){ if(nums1[i] == 0){ result[1] = i; break; } } return result; } }
true
32c105d6896d8fd508a392f5eb9304657e287f97
Java
beebit-sec/beebit-cpabe-sdk
/java/tw/edu/au/csie/ucan/beebit/dec.java
UTF-8
800
2.984375
3
[ "Apache-2.0" ]
permissive
package tw.edu.au.csie.ucan.beebit; class dec { public static void main(String[] args) { if(args.length < 4) { System.out.printf("Usage: dec [pk] [sk] [ct] [pt]\n"); System.out.printf("pk: path to public key\n"); System.out.printf("sk: path to secret key\n"); System.out.printf("ct: path to encrypted file (cipher text)\n"); System.out.printf("pt: path to original file (plain text)\n"); System.exit(-1); } String pk = args[0]; String sk = args[1]; String ct = args[2]; String pt = args[3]; cpabeJNI bee = new cpabeJNI(); int len = bee.fdec(pk, sk, ct, pt); if(len == -1) { System.out.printf("Decrypt failed!\n"); System.exit(-1); } System.out.printf("Decrypt success!\n"); System.out.printf("File (%s) decrypted to file (%s).\n", ct, pt); } }
true
984b708ad11a532715bd9a6f6fbd7a040187891e
Java
dnddlchrh/-Data-structure-2018-2
/EqualsEx.java
UHC
659
3.78125
4
[]
no_license
package day0530; class Point2{ int x,y; public Point2(int x,int y){this.x=x;this.y=y;} public boolean equals(Object obj){ Point2 p=(Point2)obj;///ü obj point Ÿ ٿij if(x==p.x&&y==p.y)return true; else return false; } } public class EqualsEx { public static void main(String[] args) { // TODO Auto-generated method stub Point2 a=new Point2(2,3); Point2 b=new Point2(2,3); Point2 c=new Point2(3,4); if(a==b)//false System.out.println("a==b"); if(a.equals(b))//true System.out.println("a is equal to b"); if(a.equals(c))//false System.out.println("a is equal to c"); } }
true
ce55b8bc06059b0e81bb5682e3cd1bce22c71eea
Java
commercetools/commercetools-sdk-java-v2
/commercetools/commercetools-sdk-java-api/src/main/java-predicates-generated/com/commercetools/api/predicates/query/order_edit/OrderEditAppliedQueryBuilderDsl.java
UTF-8
2,289
2.078125
2
[ "Apache-2.0", "GPL-2.0-only", "EPL-2.0", "CDDL-1.0", "MIT", "BSD-3-Clause", "Classpath-exception-2.0" ]
permissive
package com.commercetools.api.predicates.query.order_edit; import java.util.function.Function; import com.commercetools.api.predicates.query.*; public class OrderEditAppliedQueryBuilderDsl { public OrderEditAppliedQueryBuilderDsl() { } public static OrderEditAppliedQueryBuilderDsl of() { return new OrderEditAppliedQueryBuilderDsl(); } public StringComparisonPredicateBuilder<OrderEditAppliedQueryBuilderDsl> type() { return new StringComparisonPredicateBuilder<>( BinaryQueryPredicate.of().left(new ConstantQueryPredicate("type")), p -> new CombinationQueryPredicate<>(p, OrderEditAppliedQueryBuilderDsl::of)); } public DateTimeComparisonPredicateBuilder<OrderEditAppliedQueryBuilderDsl> appliedAt() { return new DateTimeComparisonPredicateBuilder<>( BinaryQueryPredicate.of().left(new ConstantQueryPredicate("appliedAt")), p -> new CombinationQueryPredicate<>(p, OrderEditAppliedQueryBuilderDsl::of)); } public CombinationQueryPredicate<OrderEditAppliedQueryBuilderDsl> excerptBeforeEdit( Function<com.commercetools.api.predicates.query.order_edit.OrderExcerptQueryBuilderDsl, CombinationQueryPredicate<com.commercetools.api.predicates.query.order_edit.OrderExcerptQueryBuilderDsl>> fn) { return new CombinationQueryPredicate<>(ContainerQueryPredicate.of() .parent(ConstantQueryPredicate.of().constant("excerptBeforeEdit")) .inner(fn.apply(com.commercetools.api.predicates.query.order_edit.OrderExcerptQueryBuilderDsl.of())), OrderEditAppliedQueryBuilderDsl::of); } public CombinationQueryPredicate<OrderEditAppliedQueryBuilderDsl> excerptAfterEdit( Function<com.commercetools.api.predicates.query.order_edit.OrderExcerptQueryBuilderDsl, CombinationQueryPredicate<com.commercetools.api.predicates.query.order_edit.OrderExcerptQueryBuilderDsl>> fn) { return new CombinationQueryPredicate<>(ContainerQueryPredicate.of() .parent(ConstantQueryPredicate.of().constant("excerptAfterEdit")) .inner(fn.apply(com.commercetools.api.predicates.query.order_edit.OrderExcerptQueryBuilderDsl.of())), OrderEditAppliedQueryBuilderDsl::of); } }
true
ea100c1933b056819e3caf3318734888ee44c344
Java
pamelasandrini/invoice-automation
/InvoiceAutomation/src/main/java/com/vendormanagement/InvoiceValidator.java
UTF-8
6,208
2.5
2
[]
no_license
package com.vendormanagement; import java.io.FileInputStream; import java.io.FileOutputStream; import java.io.IOException; import java.util.ArrayList; import java.util.Iterator; import java.util.List; import java.util.Map.Entry; import org.apache.commons.lang3.StringUtils; import org.apache.poi.openxml4j.exceptions.InvalidFormatException; 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.usermodel.WorkbookFactory; import org.apache.poi.ss.util.NumberToTextConverter; import com.vendormanagement.bo.Invoice; /** * Validates invoice.html on xls file and set WOI. * * @author pborsoni * */ public class InvoiceValidator { private static final String NORMAL_HOUR = "NORMAL_HOUR"; private static final String OVERTIME = "OVERTIME"; private static final String STANDBY = "HORA STANDBY"; private static final int H_COLUMN = 7; private static final int B_COLUMN = 1; private static final int C_COLUMN = 2; private static final int I_COLUMN = 8; private static final int M_COLUMN = 12; private static final int Q_COLUMN = 16; private static final int U_WOI_COLUMN = 20; private static final int V_WOI_COLUMN = 21; private static final int W_WOI_COLUMN = 22; private static final int X_WOI_COLUMN = 23; private String billingXlsFile; private List<Invoice> invoiceList; private List<Invoice> invoiceSuccessList = new ArrayList<>(); private List<Invoice> invoiceFailedList = new ArrayList<>(); private Workbook workbook; public InvoiceValidator(String billingXlsFile, List<Invoice> invoiceList) { this.billingXlsFile = billingXlsFile; this.invoiceList = invoiceList; } public void validate() throws IOException { try (FileInputStream fileInputStream = new FileInputStream(billingXlsFile);) { workbook = WorkbookFactory.create(fileInputStream); for (Invoice invoice : invoiceList) { validate(invoice); } } catch (IOException | InvalidFormatException e) { throw new IOException("An error has occurred. Could not open billig spreadsheet: " + billingXlsFile + " \n " + e.getMessage()); } finally { // Open FileOutputStream to write updates FileOutputStream output_file = new FileOutputStream(billingXlsFile); // write changes workbook.write(output_file); // close the stream output_file.close(); } } private void validate(Invoice invoice) { String sheetName = invoice.getMonth() + invoice.getYear(); Sheet sheet = workbook.getSheet(sheetName); if (sheet == null) { invoice.setErrorReason(String.format("Did not find tab %s on spreadsheet", sheetName)); invoiceFailedList.add(invoice); return; } Iterator<Row> rowIterator = sheet.rowIterator(); rowIterator.next(); Row row = null; boolean foundRow = false; while (rowIterator.hasNext()) { row = (Row) rowIterator.next(); if (row == null || row.getCell(H_COLUMN) == null) { break; } String hColumn = row.getCell(H_COLUMN).getStringCellValue(); if (StringUtils.equalsIgnoreCase(hColumn, invoice.getPurchaseOrderNumber())) { foundRow = true; break; } } if (row == null || !foundRow) { invoice.setErrorReason(String.format(" Did not find purchase order number %s on column H", invoice.getPurchaseOrderNumber())); invoiceFailedList.add(invoice); return; } if (!StringUtils.equalsIgnoreCase(row.getCell(B_COLUMN).getStringCellValue(), invoice.getId())) { invoice.setErrorReason(String.format("Did not find id %s on column B", invoice.getId())); invoiceFailedList.add(invoice); return; } if (!StringUtils.equalsIgnoreCase(row.getCell(C_COLUMN).getStringCellValue(), invoice.getResource())) { invoice.setErrorReason(String.format("Did not find resource %s on column C", invoice.getResource())); invoiceFailedList.add(invoice); return; } for (Entry<String, String> hoursEntry : invoice.getHoursMap().entrySet()) { if (NORMAL_HOUR.equals(hoursEntry.getKey())) { String textValue = NumberToTextConverter.toText(row.getCell(I_COLUMN).getNumericCellValue()); if (!StringUtils.equalsIgnoreCase(textValue, hoursEntry.getValue())) { invoice.setErrorReason(String.format("Did not find %s hours on column I", hoursEntry.getValue())); invoiceFailedList.add(invoice); return; } } if (OVERTIME.equals(hoursEntry.getKey())) { String textValue = NumberToTextConverter.toText(row.getCell(M_COLUMN).getNumericCellValue()); if (!StringUtils.equalsIgnoreCase(textValue, hoursEntry.getValue())) { invoice.setErrorReason(String.format("Did not find %s hours on column M", hoursEntry.getValue())); invoiceFailedList.add(invoice); return; } } if (STANDBY.equals(hoursEntry.getKey())) { String textValue = NumberToTextConverter.toText(row.getCell(Q_COLUMN).getNumericCellValue()); if (!StringUtils.equalsIgnoreCase(textValue, hoursEntry.getValue())) { invoice.setErrorReason(String.format("Did not find %s hours on column Q", hoursEntry.getValue())); invoiceFailedList.add(invoice); return; } } } String woi = invoice.getWoi(); if (setWoi(row, woi)) { invoiceSuccessList.add(invoice); } else { invoice.setErrorReason(String.format("Did not populate WOI %s cause columns from U to X are already filled", woi)); invoiceFailedList.add(invoice); } } private boolean setWoi(Row row, String woi) { if (StringUtils.isBlank(row.getCell(U_WOI_COLUMN).getStringCellValue())) { row.getCell(U_WOI_COLUMN).setCellValue(woi); return true; } if (StringUtils.isBlank(row.getCell(V_WOI_COLUMN).getStringCellValue())) { row.getCell(V_WOI_COLUMN).setCellValue(woi); return true; } if (StringUtils.isBlank(row.getCell(W_WOI_COLUMN).getStringCellValue())) { row.getCell(W_WOI_COLUMN).setCellValue(woi); return true; } if (StringUtils.isBlank(row.getCell(X_WOI_COLUMN).getStringCellValue())) { row.getCell(X_WOI_COLUMN).setCellValue(woi); return true; } return false; } public List<Invoice> getSuccessInvoiceList() { return invoiceSuccessList; } public List<Invoice> getFailedInvoiceList() { return invoiceFailedList; } }
true
394912ed47cabb9f097527e372111bcaaf22de82
Java
rfecher/geowave
/extensions/adapters/vector/src/main/java/mil/nga/giat/geowave/adapter/vector/export/VectorExportMapper.java
UTF-8
4,574
1.960938
2
[ "Apache-2.0", "LicenseRef-scancode-free-unknown", "LicenseRef-scancode-public-domain" ]
permissive
package mil.nga.giat.geowave.adapter.vector.export; import java.io.IOException; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; import org.apache.avro.mapred.AvroKey; import org.apache.hadoop.io.NullWritable; import org.apache.hadoop.mapreduce.Mapper; import org.opengis.feature.simple.SimpleFeature; import org.opengis.feature.simple.SimpleFeatureType; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import mil.nga.giat.geowave.adapter.vector.AvroFeatureUtils; import mil.nga.giat.geowave.adapter.vector.avro.AttributeValues; import mil.nga.giat.geowave.adapter.vector.avro.AvroSimpleFeatureCollection; import mil.nga.giat.geowave.core.index.ByteArrayId; import mil.nga.giat.geowave.mapreduce.input.GeoWaveInputKey; public class VectorExportMapper extends Mapper<GeoWaveInputKey, SimpleFeature, AvroKey<AvroSimpleFeatureCollection>, NullWritable> { private static final Logger LOGGER = LoggerFactory.getLogger(Logger.class); private int batchSize; private final Map<ByteArrayId, AvroSFCWriter> adapterIdToAvroWriterMap = new HashMap<ByteArrayId, AvroSFCWriter>(); private final NullWritable outVal = NullWritable.get(); private final AvroKey<AvroSimpleFeatureCollection> outKey = new AvroKey<AvroSimpleFeatureCollection>(); @Override protected void map( final GeoWaveInputKey key, final SimpleFeature value, final Mapper<GeoWaveInputKey, SimpleFeature, AvroKey<AvroSimpleFeatureCollection>, NullWritable>.Context context ) throws IOException, InterruptedException { AvroSFCWriter avroWriter = adapterIdToAvroWriterMap.get(key.getAdapterId()); if (avroWriter == null) { avroWriter = new AvroSFCWriter( value.getFeatureType(), batchSize); adapterIdToAvroWriterMap.put( key.getAdapterId(), avroWriter); } final AvroSimpleFeatureCollection retVal = avroWriter.write(value); if (retVal != null) { outKey.datum(retVal); context.write( outKey, outVal); } } @Override protected void setup( final Mapper<GeoWaveInputKey, SimpleFeature, AvroKey<AvroSimpleFeatureCollection>, NullWritable>.Context context ) throws IOException, InterruptedException { super.setup(context); batchSize = context.getConfiguration().getInt( VectorMRExportJobRunner.BATCH_SIZE_KEY, VectorExportOptions.DEFAULT_BATCH_SIZE); } @Override protected void cleanup( final Mapper<GeoWaveInputKey, SimpleFeature, AvroKey<AvroSimpleFeatureCollection>, NullWritable>.Context context ) throws IOException, InterruptedException { super.cleanup(context); writeRemainingAvroBatches(context); } private void writeRemainingAvroBatches( final Mapper<GeoWaveInputKey, SimpleFeature, AvroKey<AvroSimpleFeatureCollection>, NullWritable>.Context context ) throws IOException, InterruptedException { for (final AvroSFCWriter writer : adapterIdToAvroWriterMap.values()) { if (writer.avList.size() > 0) { writer.simpleFeatureCollection.setSimpleFeatureCollection(writer.avList); outKey.datum(writer.simpleFeatureCollection); context.write( outKey, outVal); } } } private static class AvroSFCWriter { private final int batchSize; private final SimpleFeatureType sft; private AvroSimpleFeatureCollection simpleFeatureCollection = null; private List<AttributeValues> avList = null; private AvroSFCWriter( final SimpleFeatureType sft, final int batchSize ) { this.sft = sft; this.batchSize = batchSize; } private AvroSimpleFeatureCollection write( final SimpleFeature feature ) { AvroSimpleFeatureCollection retVal = null; if (simpleFeatureCollection == null) { newFeatureCollection(); } else if (avList.size() >= batchSize) { simpleFeatureCollection.setSimpleFeatureCollection(avList); retVal = simpleFeatureCollection; newFeatureCollection(); } final AttributeValues av = AvroFeatureUtils.buildAttributeValue( feature, sft); avList.add(av); return retVal; } // this isn't intended to be thread safe private void newFeatureCollection() { simpleFeatureCollection = new AvroSimpleFeatureCollection(); try { simpleFeatureCollection.setFeatureType(AvroFeatureUtils.buildFeatureDefinition( null, sft, null, "")); } catch (final IOException e) { // this should never actually happen, deault classification is // passed in LOGGER.warn( "Unable to find classification", e); } avList = new ArrayList<AttributeValues>( batchSize); } } }
true
09450d85a3c3b0cccaf97499041c87f8b8e55fb1
Java
jjfiv/irene
/third_party/galago/core/src/main/java/org/lemurproject/galago/core/links/IndriHavestLinksWriter.java
UTF-8
4,931
2.265625
2
[ "BSD-3-Clause" ]
permissive
/* * BSD License (http://lemurproject.org/galago-license) */ package org.lemurproject.galago.core.links; import org.lemurproject.galago.core.types.ExtractedLinkIndri; import org.lemurproject.galago.tupleflow.InputClass; import org.lemurproject.galago.tupleflow.Processor; import org.lemurproject.galago.tupleflow.TupleFlowParameters; import org.lemurproject.galago.tupleflow.execution.ErrorStore; import org.lemurproject.galago.tupleflow.execution.Verification; import org.lemurproject.galago.utility.ByteUtil; import org.lemurproject.galago.utility.FSUtil; import org.lemurproject.galago.utility.Parameters; import java.io.BufferedWriter; import java.io.FileOutputStream; import java.io.IOException; import java.io.OutputStreamWriter; import java.util.ArrayList; import java.util.List; import java.util.regex.Matcher; import java.util.zip.GZIPOutputStream; /** * * @author sjh */ @InputClass(className = "org.lemurproject.galago.core.types.ExtractedLinkIndri", order = {"+filePath", "+fileLocation"}) public class IndriHavestLinksWriter implements Processor<ExtractedLinkIndri> { private static final int MAX_INLINKS = 10000; private final String filePrefix; private final String prefixReplacement; private BufferedWriter writer; private String currentFilePath; private String currentDocName; private List<ExtractedLinkIndri> currentLinks; public IndriHavestLinksWriter(TupleFlowParameters tp) { Parameters p = tp.getJSON(); filePrefix = p.getString("filePrefix"); prefixReplacement = p.getString("prefixReplacement"); writer = null; currentFilePath = ""; currentDocName = ""; currentLinks = new ArrayList<>(); } @Override public void process(ExtractedLinkIndri link) throws IOException { if (!link.anchorText.isEmpty()) { // ony record links with anchor text if (!link.filePath.equals(currentFilePath)) { resetWriter(link.filePath); } if (!link.destName.equals(currentDocName)) { // check that there was a document to be linked to (first output to file check) if (!currentDocName.isEmpty()) { writeLinks(); } writer.write("DOCNO=" + link.destName + "\n"); writer.write(link.destUrl + "\n"); currentDocName = link.destName; } // limit to a maximum number of inlinks if (currentLinks.size() < MAX_INLINKS) { currentLinks.add(link); } } } @Override public void close() throws IOException { if (writer != null) { writeLinks(); writer.close(); } } public static void verify(TupleFlowParameters parameters, ErrorStore store) { if (!Verification.requireParameters(new String[]{"filePrefix", "prefixReplacement"}, parameters.getJSON(), store)) { return; } } private void resetWriter(String filePath) throws IOException { if (writer != null) { writeLinks(); writer.close(); } writer = null; if (filePath != null) { // MCZ 3/2014 - added quoteReplacement() for Windows compatibility String outputPath = filePath.replaceFirst(Matcher.quoteReplacement(filePrefix) , Matcher.quoteReplacement(prefixReplacement) ); if (outputPath.equals(filePath)) { throw new IOException("Can not over write input data."); } FSUtil.makeParentDirectories(outputPath); // all output is compressed. writer = new BufferedWriter(new OutputStreamWriter(new GZIPOutputStream(new FileOutputStream(outputPath)), ByteUtil.utf8)); currentFilePath = filePath; currentDocName = ""; } } private void writeLinks() throws IOException { writer.write("LINKS=" + currentLinks.size() + "\n"); for (ExtractedLinkIndri el : currentLinks) { writer.write("LINKDOCNO=" + el.srcName + "\n"); writer.write("LINKFROM=" + el.srcUrl + "\n"); // ensure quoted "text" is ok. el.anchorText = el.anchorText.replaceAll("\"", "\'"); // no empty links are recorded. writer.write("TEXT=\"" + el.anchorText + "\"\n"); } currentLinks.clear(); } } /* * Sample output: * * DOCNO=clueweb09-en0000-01-00001 http://0-derrewyn-0.deviantart.com/favourites/ LINKS=3 LINKDOCNO=clueweb09-en0000-01-00000 LINKFROM=http://0-derrewyn-0.deviantart.com TEXT="Browse Favourites " LINKDOCNO=clueweb09-en0000-01-00000 LINKFROM=http://0-derrewyn-0.deviantart.com TEXT="Faves " LINKDOCNO=clueweb09-en0000-01-00001 LINKFROM=http://0-derrewyn-0.deviantart.com/favourites/ TEXT="Profile " DOCNO=clueweb09-en0000-01-00002 .... */
true
d4282cc9ccd7ef71453c9de2af84c0494e621a29
Java
SoongMoo/TestRepository
/testSpringBoot/src/main/java/testSpringBoot/domain/ReplyDTO.java
UTF-8
452
1.859375
2
[]
no_license
package testSpringBoot.domain; import java.sql.Timestamp; import org.apache.ibatis.type.Alias; import lombok.AllArgsConstructor; import lombok.Data; import lombok.NoArgsConstructor; @Alias("reply") @Data @AllArgsConstructor @NoArgsConstructor public class ReplyDTO { private Long commentNo; private String cuserId; private Long replyNo; private String ruserId; private String replyContent; private Timestamp regDate; }
true
e9ea38d088e310f8ce882244bfdb48abab46b1bc
Java
Waikato/weka-3.8
/packages/internal/distributedWekaBase/src/main/java/weka/distributed/KMeansReduceTask.java
UTF-8
15,855
2.0625
2
[]
no_license
/* * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ /* * KMeansReduceTask * Copyright (C) 2014 University of Waikato, Hamilton, New Zealand * */ package weka.distributed; import java.io.Serializable; import java.util.ArrayList; import java.util.List; import weka.core.Attribute; import weka.core.DenseInstance; import weka.core.Instances; import weka.core.NormalizableDistance; import weka.core.Utils; import weka.core.stats.ArffSummaryNumericMetric; import weka.core.stats.NominalStats; /** * Reduce task for k-means clustering. Processes partial cluster summary * metadata for a particular run in order to produce a set of Instances that * contains new cluster centroids. * * @author Mark Hall (mhall{[at]}pentaho{[dot]}com) * @version $Revision: $ */ public class KMeansReduceTask implements Serializable { /** * For serialization */ private static final long serialVersionUID = 6222983145960081251L; protected double m_totalWithinClustersError; /** * Will hold the updated centroids for this run after aggregating the partial * clusterings */ protected Instances m_newCentroidsForRun; /** * This will hold the aggregated summary instances (with summary stats * attributes), one for each cluster */ protected List<Instances> m_aggregatedCentroidSummaries; /** * If run number = 0, then this will hold the some priming data for * initializing the ranges of numeric attributes in the case where filters may * have transformed/altered the original space. */ protected Instances m_globalDistanceFunctionPrimingData; /** The run number */ protected int m_runNumber; /** The iteration number */ protected int m_iterationNumber; /** * Reduce the cluster centroid summary metadata instances for a particular run * in order to produce a new set of Instances that contains the new cluster * centroids for the run. Adds the total within cluster error to the relation * name of the instances. If the iteration number is 0 then also generates a * two instance data set that can be used for initializing a distance * function. The two instances contain global minimum and maximum values for * numeric attributes respectively, which is used in the distance function for * normalization. This particular dataset is useful when filters (beyond * missing values replacement) have been specified for k-means and it is not * possible to use the summary stats in the global ARFF header file for * initializing the distance function * * @param runNumber the current run number * @param iterationNumber the current iteration number of k-means * @param headerNoSummary the global ARFF header (as computed by the * ArffHeader job on the entire dataset, and having passed through * any preprocessing filters). We need this so that the correct index * for nominal attribute values can be set in the new centroids (map * tasks accumulating summary stats when clustering partitions of the * data may see nominal values in different orders, or not see some * values at all, compared to the global header) * @param clusterSummaries a list of cluster summary information. Each inner * list of Instances will have been generated by a map task on a * subset of the data. Each instances object in the list contains the * summary stats for one cluster centroid. Inner lists are in order * of centroid number. A particular Instances entry in a list may be * null - this indicates that the cluster was empty within that * particular map task (i.e. no training instances were assigned to * it) * @return an instance of KMeansReduceTask with new centroids and supporting * data computed. * @throws DistributedWekaException if a problem occurs */ public KMeansReduceTask reduceClusters(int runNumber, int iterationNumber, Instances headerNoSummary, List<List<Instances>> clusterSummaries) throws DistributedWekaException { m_runNumber = runNumber; m_iterationNumber = iterationNumber; int numClusters = clusterSummaries.get(0).size(); // headerNoSummary = // CSVToARFFHeaderReduceTask.stripSummaryAtts(headerNoSummary); List<List<Instances>> partialsPerCentroid = new ArrayList<List<Instances>>(); for (int i = 0; i < numClusters; i++) { partialsPerCentroid.add(new ArrayList<Instances>()); } for (int i = 0; i < clusterSummaries.size(); i++) { List<Instances> currentPartial = clusterSummaries.get(i); if (currentPartial.size() != numClusters) { throw new DistributedWekaException( "Each list of centroid summary stats should be " + "equal to the number of clusters. Expected " + numClusters + " but this list" + " contains " + currentPartial.size()); } for (int j = 0; j < currentPartial.size(); j++) { Instances centroidPartial = currentPartial.get(j); if (centroidPartial != null) { partialsPerCentroid.get(j).add(centroidPartial); } } } CSVToARFFHeaderReduceTask reduceTask = new CSVToARFFHeaderReduceTask(); List<Instances> aggregatedCentroidSummaries = new ArrayList<Instances>(); m_totalWithinClustersError = 0; for (int i = 0; i < partialsPerCentroid.size(); i++) { if (partialsPerCentroid.get(i).size() > 0) { double clusterError = getErrorsForCluster(partialsPerCentroid.get(i)); m_totalWithinClustersError += clusterError; Instances aggregated = reduceTask.aggregate(partialsPerCentroid.get(i)); // update the relation name aggregated.setRelationName("Stats for centroid " + i + " : " + clusterError); aggregatedCentroidSummaries.add(aggregated); } else { // this means that this is now a global empty cluster (i.e. // no mappers assigned any training instances to this centroid). // So we just drop it. } } m_aggregatedCentroidSummaries = aggregatedCentroidSummaries; double[] globalMins = null; double[] globalMaxes = null; if (iterationNumber == 0) { globalMins = new double[headerNoSummary.numAttributes()]; globalMaxes = new double[headerNoSummary.numAttributes()]; for (int i = 0; i < headerNoSummary.numAttributes(); i++) { if (headerNoSummary.attribute(i).isNumeric()) { globalMins[i] = Double.MAX_VALUE; globalMaxes[i] = Double.MIN_VALUE; } else { globalMins[i] = Utils.missingValue(); globalMaxes[i] = Utils.missingValue(); } } } // now construct the new centroids for (int i = 0; i < aggregatedCentroidSummaries.size(); i++) { Instances centroidSummary = aggregatedCentroidSummaries.get(i); double[] centerVals = new double[headerNoSummary.numAttributes()]; for (int j = 0; j < headerNoSummary.numAttributes(); j++) { Attribute origAtt = headerNoSummary.attribute(j); String name = origAtt.name(); Attribute summaryAtt = centroidSummary .attribute(CSVToARFFHeaderMapTask.ARFF_SUMMARY_ATTRIBUTE_PREFIX + name); if (origAtt.isNumeric()) { double nonMissingCountForAtt = ArffSummaryNumericMetric.COUNT.valueFromAttribute(summaryAtt); double missingCountForAtt = ArffSummaryNumericMetric.MISSING.valueFromAttribute(summaryAtt); double clusterMeanForAtt = ArffSummaryNumericMetric.MEAN.valueFromAttribute(summaryAtt); if (missingCountForAtt > nonMissingCountForAtt || Utils.isMissingValue(clusterMeanForAtt)) { System.err .println("********************************* att: " + origAtt.name() + " mean: " + clusterMeanForAtt + "non-missing: " + nonMissingCountForAtt + " missing: " + missingCountForAtt); centerVals[j] = Utils.missingValue(); } else { centerVals[j] = clusterMeanForAtt; } if (iterationNumber == 0) { double min = ArffSummaryNumericMetric.MIN.valueFromAttribute(summaryAtt); double max = ArffSummaryNumericMetric.MAX.valueFromAttribute(summaryAtt); if (!Utils.isMissingValue(min) && !Double.isInfinite(min)) { if (min < globalMins[j]) { globalMins[j] = min; } } if (!Utils.isMissingValue(max) && !Double.isInfinite(max)) { if (max > globalMaxes[j]) { globalMaxes[j] = max; } } } } else if (origAtt.isNominal()) { NominalStats stats = NominalStats.attributeToStats(summaryAtt); // int clusterModeForAttIndex = stats.getMode(); String clusterModeLabelForAtt = stats.getModeLabel(); double modeCountForAtt = stats.getCount(clusterModeLabelForAtt); double missingCountForAtt = stats.getNumMissing(); if (missingCountForAtt > modeCountForAtt) { centerVals[j] = Utils.missingValue(); } else { // centerVals[j] = clusterModeForAttIndex; int mappedIndex = headerNoSummary.attribute(j).indexOfValue(clusterModeLabelForAtt); if (mappedIndex < 0) { throw new DistributedWekaException( "Unable to find nominal value '" + clusterModeLabelForAtt + "' in global header attribute '" + headerNoSummary.attribute(j)); } centerVals[j] = mappedIndex; } } else { // this could happen if the user has applied a streamable filter that // creates string attributes or something throw new DistributedWekaException( "k-means can only handle numeric and nominal attributes!"); } } // add the new centroid headerNoSummary.add(new DenseInstance(1.0, centerVals)); } m_newCentroidsForRun = headerNoSummary; // If iteration 0 then compute global priming data for distance functions // in the (potentially) filtered space if (iterationNumber == 0) { m_globalDistanceFunctionPrimingData = new Instances(headerNoSummary, 0); m_globalDistanceFunctionPrimingData .add(new DenseInstance(1.0, globalMins)); m_globalDistanceFunctionPrimingData.add(new DenseInstance(1.0, globalMaxes)); } return this; } /** * Return the centroids for the run * * @return the centroids as a set of instances */ public Instances getCentroidsForRun() { return m_newCentroidsForRun; } /** * Get the aggregated summary data for each individual centroid. This is * represented as a Instances header with summary meta attributes * * @return a list of summary meta data */ public List<Instances> getAggregatedCentroidSummaries() { return m_aggregatedCentroidSummaries; } /** * Get the global distance function priming data. This contains global mins * and maxes for attributes in the transformed (by any filters) space * * @return the global distance function priming data */ public Instances getGlobalDistanceFunctionPrimingData() { return m_globalDistanceFunctionPrimingData; } /** * Get the run number * * @return the run number */ public int getRunNumber() { return m_runNumber; } /** * Get the current iteration number * * @return the current iteration number */ public int getIterationNumber() { return m_iterationNumber; } /** * Get the total within cluster error for this run * * @return the total within cluster error for this run */ public double getTotalWithinClustersError() { return m_totalWithinClustersError; } /** * Computes the errors for a particular cluster from a list of partial cluster * summary data * * @param clusterPartials a list of Instances containing summary meta * attributes * @return the total error for the cluster * @throws DistributedWekaException if a problem occurs */ protected static double getErrorsForCluster(List<Instances> clusterPartials) throws DistributedWekaException { double error = 0; for (Instances i : clusterPartials) { String relationName = i.relationName(); String[] parts = relationName.split(":"); if (parts.length != 2) { throw new DistributedWekaException( "Can't find within cluster error in the " + "relation name of a cluster centroid partial stats instances:\n " + i.toString()); } try { error += Double.parseDouble(parts[1].trim()); } catch (NumberFormatException e) { throw new DistributedWekaException( "Unable to parse within cluster error" + " from a cluster centroid partial stats instances: \n" + i.toString()); } } return error; } /** * Utility function to examine the attribute ranges in a bunch of distance * functions and return a two instance dataset with the global mins/maxes of * numeric attributes set. This can be used to "prime" a distance function. * * @param distanceFuncs a list of distance functions (where each potentially * has only seen part of the overall dataset * @param headerNoSummary the header of the data that the distance functions * have been seeing * @return a priming data set with global min and max values for numeric * attributes * @throws DistributedWekaException if a problem occurs */ public static Instances computeDistancePrimingDataFromDistanceFunctions( List<NormalizableDistance> distanceFuncs, Instances headerNoSummary) throws DistributedWekaException { Instances prime = null; double[] mins = new double[headerNoSummary.numAttributes()]; double[] maxes = new double[headerNoSummary.numAttributes()]; try { for (int i = 0; i < headerNoSummary.numAttributes(); i++) { if (headerNoSummary.attribute(i).isNumeric()) { mins[i] = Double.MAX_VALUE; maxes[i] = Double.MIN_VALUE; } else { mins[i] = Utils.missingValue(); maxes[i] = Utils.missingValue(); } } for (NormalizableDistance d : distanceFuncs) { double[][] ranges = d.getRanges(); for (int i = 0; i < headerNoSummary.numAttributes(); i++) { if (ranges[i][NormalizableDistance.R_MIN] < mins[i]) { mins[i] = ranges[i][NormalizableDistance.R_MIN]; } if (ranges[i][NormalizableDistance.R_MAX] > maxes[i]) { maxes[i] = ranges[i][NormalizableDistance.R_MAX]; } } } } catch (Exception ex) { throw new DistributedWekaException(ex); } prime = new Instances(headerNoSummary, 2); prime.add(new DenseInstance(1.0, mins)); prime.add(new DenseInstance(1.0, maxes)); return prime; } }
true
c76c0edb769721b0b2261fa1eddd20809d1e77c9
Java
fudini/bendec
/src/tests/generated/java/bendec/arrays/Test.java
UTF-8
2,462
2.765625
3
[ "MIT" ]
permissive
package bendec.arrays; import java.math.BigInteger; import java.util.Arrays; import java.util.HashMap; import java.util.Map; import java.util.Objects; import java.nio.ByteBuffer; import bendec.arrays.JsonSerializable; import com.fasterxml.jackson.databind.node.ArrayNode; import com.fasterxml.jackson.databind.node.ObjectNode; import com.fasterxml.jackson.databind.ObjectMapper; import com.fasterxml.jackson.databind.node.JsonNodeFactory; import com.fasterxml.jackson.databind.node.TextNode; /** * <h2>Test</h2> * <p>Byte length: 2</p> * <p>u8 > int one | size 1</p> * <p>u8 > int two | size 1</p> * */ public class Test implements ByteSerializable, JsonSerializable { private int one; private int two; public static final int byteLength = 2; public Test(int one, int two) { this.one = one; this.two = two; } public Test(byte[] bytes, int offset) { this.one = BendecUtils.uInt8FromByteArray(bytes, offset); this.two = BendecUtils.uInt8FromByteArray(bytes, offset + 1); } public Test(byte[] bytes) { this(bytes, 0); } public Test() { } public int getOne() { return this.one; }; public int getTwo() { return this.two; }; public void setOne(int one) { this.one = one; }; public void setTwo(int two) { this.two = two; }; @Override public byte[] toBytes() { ByteBuffer buffer = ByteBuffer.allocate(this.byteLength); buffer.put(BendecUtils.uInt8ToByteArray(this.one)); buffer.put(BendecUtils.uInt8ToByteArray(this.two)); return buffer.array(); } @Override public void toBytes(ByteBuffer buffer) { buffer.put(BendecUtils.uInt8ToByteArray(this.one)); buffer.put(BendecUtils.uInt8ToByteArray(this.two)); } @Override public ObjectNode toJson() { ObjectNode object = JsonSerializable.MAPPER.createObjectNode(); object.put("one", one); object.put("two", two); return object; } @Override public ObjectNode toJson(ObjectNode object) { object.put("one", one); object.put("two", two); return object; } @Override public int hashCode() { return Objects.hash(one, two); } @Override public String toString() { return "Test{" + "one=" + one + ", two=" + two + '}'; } }
true
63e38f3a92884354ed451345b33e8702a13f7be5
Java
BorLaze/code
/sb2/src/main/java/ua/in/lbn/sb2/repository/LocationRepository.java
UTF-8
387
1.710938
2
[]
no_license
package ua.in.lbn.sb2.repository; import org.springframework.data.jpa.repository.JpaRepository; import org.springframework.data.jpa.repository.JpaSpecificationExecutor; import org.springframework.stereotype.Repository; import ua.in.lbn.sb2.domain.Location; @Repository public interface LocationRepository extends JpaRepository<Location, Long>, JpaSpecificationExecutor<Location> { }
true
6c81f67b479f77f686b7e224492a5c48bda030f7
Java
Weefle/Umbaska_Reloaded
/src/uk/co/umbaska/Enums/AnvilGUI.java
UTF-8
6,131
2.25
2
[]
no_license
package uk.co.umbaska.Enums; import java.util.HashMap; import net.minecraft.server.v1_9_R2.BlockPosition; import net.minecraft.server.v1_9_R2.ContainerAnvil; import net.minecraft.server.v1_9_R2.EntityHuman; import net.minecraft.server.v1_9_R2.EntityPlayer; import net.minecraft.server.v1_9_R2.IChatBaseComponent; import net.minecraft.server.v1_9_R2.PacketPlayOutOpenWindow; import net.minecraft.server.v1_9_R2.PlayerInventory; import org.bukkit.Bukkit; import org.bukkit.craftbukkit.v1_9_R2.entity.CraftPlayer; import org.bukkit.entity.Player; import org.bukkit.event.EventHandler; import org.bukkit.event.HandlerList; import org.bukkit.event.Listener; import org.bukkit.event.inventory.InventoryClickEvent; import org.bukkit.event.inventory.InventoryCloseEvent; import org.bukkit.event.player.PlayerQuitEvent; import org.bukkit.inventory.Inventory; import org.bukkit.inventory.ItemStack; import org.bukkit.inventory.meta.ItemMeta; import uk.co.umbaska.Main; public class AnvilGUI { private Player player; private AnvilClickEventHandler handler; private class AnvilContainer extends ContainerAnvil { public AnvilContainer(EntityHuman entity) { super((PlayerInventory) player, entity.world, new BlockPosition(0, 0, 0), entity); } public boolean a(EntityHuman entityhuman) { return true; } } public static enum AnvilSlot { INPUT_LEFT(0), INPUT_RIGHT(1), OUTPUT(2); private int slot; private AnvilSlot(int slot) { this.slot = slot; } public int getSlot() { return this.slot; } public static AnvilSlot bySlot(int slot) { for (AnvilSlot anvilSlot : values()) { if (anvilSlot.getSlot() == slot) { return anvilSlot; } } return null; } } public class AnvilClickEvent { private AnvilGUI.AnvilSlot slot; private String name; private boolean close = true; private boolean destroy = true; public AnvilClickEvent(AnvilGUI.AnvilSlot slot, String name) { this.slot = slot; this.name = name; } public AnvilGUI.AnvilSlot getSlot() { return this.slot; } public String getName() { return this.name; } public boolean getWillClose() { return this.close; } public void setWillClose(boolean close) { this.close = close; } public boolean getWillDestroy() { return this.destroy; } public void setWillDestroy(boolean destroy) { this.destroy = destroy; } } private HashMap<AnvilSlot, ItemStack> items = new HashMap<>(); private Inventory inv; private Listener listener; public String anvTitle; public AnvilGUI(Player player, final String title, final AnvilClickEventHandler handler) { this.player = player; this.setHandler(handler); this.anvTitle = title; this.listener = new Listener() { @EventHandler public void onInventoryClick(InventoryClickEvent event) { if ((event.getWhoClicked() instanceof Player)) { if (event.getInventory().equals(AnvilGUI.this.inv)) { ItemStack item = event.getCurrentItem(); int slot = event.getRawSlot(); String name = title; if ((item != null) && (item.hasItemMeta())) { ItemMeta meta = item.getItemMeta(); if (meta.hasDisplayName()) { name = meta.getDisplayName(); } } AnvilGUI.AnvilClickEvent clickEvent = new AnvilGUI.AnvilClickEvent(AnvilGUI.AnvilSlot.bySlot(slot), name); handler.onAnvilClick(clickEvent); if (clickEvent.getWillClose()) { event.getWhoClicked().closeInventory(); } if (clickEvent.getWillDestroy()) { AnvilGUI.this.destroy(); } } } } @EventHandler public void onInventoryClose(InventoryCloseEvent event) { if ((event.getPlayer() instanceof Player)) { Inventory inv = event.getInventory(); if (inv.equals(AnvilGUI.this.inv)) { inv.clear(); AnvilGUI.this.destroy(); } } } @EventHandler public void onPlayerQuit(PlayerQuitEvent event) { if (event.getPlayer().equals(AnvilGUI.this.getPlayer())) { AnvilGUI.this.destroy(); } } }; Bukkit.getPluginManager().registerEvents(this.listener, Main.getInstance()); } public Player getPlayer() { return this.player; } public void setSlot(AnvilSlot slot, ItemStack item) { this.items.put(slot, item); } public void open() { EntityPlayer p = ((CraftPlayer)this.player).getHandle(); AnvilContainer container = new AnvilContainer(p); this.inv = Bukkit.createInventory(p.getBukkitEntity(), container.getBukkitView().getTopInventory().getType(), this.anvTitle); for (AnvilSlot slot : this.items.keySet()) { this.inv.setItem(slot.getSlot(), (ItemStack)this.items.get(slot)); } int c = p.nextContainerCounter(); IChatBaseComponent iChatBaseComponent = IChatBaseComponent.ChatSerializer.a(this.anvTitle); p.playerConnection.sendPacket(new PacketPlayOutOpenWindow(c, "minecraft:anvil", iChatBaseComponent)); p.activeContainer = container; p.activeContainer.windowId = c; p.activeContainer.addSlotListener(p); } public void destroy() { this.player = null; this.setHandler(null); this.items = null; HandlerList.unregisterAll(this.listener); this.listener = null; } public AnvilClickEventHandler getHandler() { return handler; } public void setHandler(AnvilClickEventHandler handler) { this.handler = handler; } public static abstract interface AnvilClickEventHandler { public abstract void onAnvilClick(AnvilGUI.AnvilClickEvent paramAnvilClickEvent); } }
true
4a5cb7741c25c10303fb16ce73e20cdfb1a29982
Java
DowareSistemas/EM3
/EM3/src/java/dao/NcmDao.java
UTF-8
799
2.234375
2
[]
no_license
/* * 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 dao; import java.util.List; import model.Ncm; import repository.NcmRepisitory; /** * * @author Marcos Vinícius */ public class NcmDao { private NcmRepisitory db = null; public NcmDao() { db = new NcmRepisitory(); } public int count() { int count = db.count(Ncm.class, ""); db.commit(true); return count; } public List<Ncm> search(String searchTerm, int page) { return (searchTerm.isEmpty() ? db.listAll(page) : db.search(searchTerm, page)); } }
true
fa74e7bc7b48cb90dae8d2cb4f37d3c30759b4a4
Java
fontain1128/java-base
/src/com/java/base/wrapper/PackTest.java
GB18030
1,997
3.640625
4
[]
no_license
package com.java.base.wrapper; /** * װ䣺ԶתΪװͣ * 䣺ԶװתΪ * @author Administrator * byte-Byte * short-Short * int-Integer * long-Long * float-Float * double-Double * char-Character * boolean-Boolean * ÿһװάһӦ͵cache * InterCache һInteger͵ij飨λڳأΧ-128-127; */ public class PackTest { public static void main(String[] args) { //true int->Integer Integer m = 200; Integer n = 200; System.out.println(m==n); Integer m2 = 127; Integer n2 = 127; System.out.println(m2==n2); //true Integer->int int a = m; int b = n; System.out.println(a==b); //true Long->long Long l = 100L; Long l2 = 100L; System.out.println(l==l2); Long l3 = 127L; Long l4 = 127L; System.out.println(l3==l4); //true long->Long long l5 = l; long l6 = l2; System.out.println(l5==l6); //true boolean-Boolean,װBooleanݶĻԶװ䡣 Boolean b2 = true; Boolean b3 = true; System.out.println(b2==b3); //true "=="ǰװʱȽϵǷָͬһ󣬵һDZʽ㣩ȸԲװ䣬ٱȽ, Integer i = 300; Integer i2 = new Integer(1); Integer i3 = 301; Integer i9 = i+i2; System.out.println(i3 == i9);//false System.out.println(i3 == (i+i2));//true Ƚֵ //true Integer t1 = new Integer(1); Integer t2 = 1; Long t3 = new Long(2); System.out.println(t3==(t1+t2)); //IntegerLongΪLong Long w1 = new Long(1); Integer w2 = 1; Long w3 = 2L; Object o = w1+w2; System.out.println(o.getClass().getName()); //false,LongԴ룬equals Integer i4 = 1; Integer i5 = 1; Long i6 = 2L; System.out.println(i6.equals((i4+i5))); } }
true
529883ed30d9c2e9aa3121469888e4238595a413
Java
WingBot/OpenTCS-4.17-Modbus
/lib/EasyModbus/src/de/re/easymodbus/modbusclient/gui/EasyModbusTCPClientExampleGUI.java
IBM852
27,384
2.28125
2
[ "MIT" ]
permissive
/* * (c) Stefan Romann * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ package de.re.easymodbus.modbusclient.gui; import de.re.easymodbus.modbusclient.ModbusClient; import de.re.easymodbus.modbusclient.ReceiveDataChangedListener; import de.re.easymodbus.modbusclient.SendDataChangedListener; import javax.swing.*; import javax.swing.GroupLayout.Alignment; import javax.swing.LayoutStyle.ComponentPlacement; import java.awt.event.ItemListener; import java.awt.event.ItemEvent; import java.awt.event.ActionListener; import java.awt.event.ActionEvent; /** * * @author Stefan Romann */ @SuppressWarnings("serial") public class EasyModbusTCPClientExampleGUI extends javax.swing.JFrame implements ReceiveDataChangedListener , SendDataChangedListener { JComboBox comboBox; /** * Creates new form EasyModbusTCPClientExampleGUI */ private ModbusClient modbusClient; public EasyModbusTCPClientExampleGUI() { initComponents(); modbusClient = new ModbusClient(); modbusClient.addReveiveDataChangedListener(this); modbusClient.addSendDataChangedListener(this); } public void ReceiveDataChanged() { jTextArea1.append("Rx:"); for (int i = 0; i < modbusClient.receiveData.length; i++) { jTextArea1.append(" "); if (modbusClient.receiveData[i] < 16) jTextArea1.append("0"); jTextArea1.append(Integer.toHexString(modbusClient.receiveData[i])); } jTextArea1.append("\n"); } public void SendDataChanged() { jTextArea1.append("Tx:"); for (int i = 0; i < modbusClient.sendData.length; i++) { jTextArea1.append(" "); if (modbusClient.sendData[i] < 16) jTextArea1.append("0"); jTextArea1.append(Integer.toHexString(modbusClient.sendData[i])); } jTextArea1.append("\n" ); } /** * This method is called from within the constructor to initialize the form. * WARNING: Do NOT modify this code. The content of this method is always * regenerated by the Form Editor. */ // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents private void initComponents() { jLabel1 = new javax.swing.JLabel(); jButton1 = new javax.swing.JButton(); jButton1.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent arg0) { } }); jButton2 = new javax.swing.JButton(); jButton3 = new javax.swing.JButton(); jButton4 = new javax.swing.JButton(); jPanel1 = new javax.swing.JPanel(); jLabel5 = new javax.swing.JLabel(); jTextFieldStartingAddress = new javax.swing.JTextField(); jLabel6 = new javax.swing.JLabel(); jTextFieldNumberOfValues = new javax.swing.JTextField(); jScrollPane1 = new javax.swing.JScrollPane(); jList1 = new javax.swing.JList<String>(); jLabel2 = new javax.swing.JLabel(); jScrollPane2 = new javax.swing.JScrollPane(); setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE); jLabel1.setToolTipText(""); jLabel1.addMouseListener(new java.awt.event.MouseAdapter() { public void mouseClicked(java.awt.event.MouseEvent evt) { jLabel1MouseClicked(evt); } }); jButton1.setText("Read Coils - FC1"); jButton1.addMouseListener(new java.awt.event.MouseAdapter() { public void mouseClicked(java.awt.event.MouseEvent evt) { jButton1MouseClicked(evt); } }); jButton2.setText("Read Discrete Inputs - FC2"); jButton2.addMouseListener(new java.awt.event.MouseAdapter() { public void mouseClicked(java.awt.event.MouseEvent evt) { jButton2MouseClicked(evt); } }); jButton3.setText("Read Holding Registers - FC3"); jButton3.addMouseListener(new java.awt.event.MouseAdapter() { public void mouseClicked(java.awt.event.MouseEvent evt) { jButton3MouseClicked(evt); } }); jButton4.setText("Read Input Registers - FC4"); jButton4.addMouseListener(new java.awt.event.MouseAdapter() { public void mouseClicked(java.awt.event.MouseEvent evt) { jButton4MouseClicked(evt); } }); jLabel5.setText("Starting Address"); jTextFieldStartingAddress.setText("1"); jLabel6.setText("Number of Values"); jTextFieldNumberOfValues.setText("1"); jScrollPane1.setViewportView(jList1); jLabel2.setForeground(new java.awt.Color(0, 0, 204)); jLabel2.setText("http://www.EasyModbusTCP.net"); javax.swing.GroupLayout jPanel1Layout = new javax.swing.GroupLayout(jPanel1); jPanel1Layout.setHorizontalGroup( jPanel1Layout.createParallelGroup(Alignment.LEADING) .addGroup(jPanel1Layout.createSequentialGroup() .addContainerGap() .addGroup(jPanel1Layout.createParallelGroup(Alignment.TRAILING) .addGroup(jPanel1Layout.createSequentialGroup() .addGroup(jPanel1Layout.createParallelGroup(Alignment.LEADING) .addComponent(jLabel5) .addComponent(jLabel6) .addComponent(jTextFieldStartingAddress, GroupLayout.PREFERRED_SIZE, 48, GroupLayout.PREFERRED_SIZE) .addComponent(jTextFieldNumberOfValues, GroupLayout.PREFERRED_SIZE, 48, GroupLayout.PREFERRED_SIZE)) .addGap(10) .addComponent(jScrollPane1, GroupLayout.PREFERRED_SIZE, 0, Short.MAX_VALUE)) .addGroup(jPanel1Layout.createSequentialGroup() .addGap(0, 0, Short.MAX_VALUE) .addComponent(jLabel2) .addGap(73))) .addContainerGap()) ); jPanel1Layout.setVerticalGroup( jPanel1Layout.createParallelGroup(Alignment.LEADING) .addGroup(jPanel1Layout.createSequentialGroup() .addContainerGap() .addComponent(jLabel2) .addGap(56) .addGroup(jPanel1Layout.createParallelGroup(Alignment.LEADING) .addGroup(jPanel1Layout.createSequentialGroup() .addComponent(jLabel5) .addPreferredGap(ComponentPlacement.RELATED) .addComponent(jTextFieldStartingAddress, GroupLayout.PREFERRED_SIZE, GroupLayout.DEFAULT_SIZE, GroupLayout.PREFERRED_SIZE) .addGap(18) .addComponent(jLabel6) .addPreferredGap(ComponentPlacement.RELATED) .addComponent(jTextFieldNumberOfValues, GroupLayout.PREFERRED_SIZE, GroupLayout.DEFAULT_SIZE, GroupLayout.PREFERRED_SIZE)) .addComponent(jScrollPane1, GroupLayout.PREFERRED_SIZE, 155, GroupLayout.PREFERRED_SIZE)) .addContainerGap(GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)) ); jPanel1.setLayout(jPanel1Layout); comboBox = new JComboBox(); comboBox.addItemListener(new ItemListener() { public void itemStateChanged(ItemEvent arg0) { if ((String)(arg0.getItem()) == "Modbus TCP") { modbusClient = new ModbusClient(); jpModbusTCP.setVisible(true); jpModbusRTU.setVisible(false); } else { modbusClient = new ModbusClient(); jpModbusRTU.setVisible(true); jpModbusTCP.setVisible(false); } } }); comboBox.setModel(new DefaultComboBoxModel(new String[] {"Modbus TCP", "Modbus RTU"})); jpModbusTCP = new JPanel(); jpModbusRTU = new JPanel(); jpModbusRTU.setVisible(false); lblComport = new JLabel(); lblComport.setText("COM-Port"); txtCom = new JTextField(); txtCom.setToolTipText(""); txtCom.setText("COM1"); textField_1 = new JTextField(); textField_1.setText("1"); lblSlaveid = new JLabel(); lblSlaveid.setText("Slave-ID"); GroupLayout gl_jpModbusRTU = new GroupLayout(jpModbusRTU); gl_jpModbusRTU.setHorizontalGroup( gl_jpModbusRTU.createParallelGroup(Alignment.LEADING) .addGap(0, 174, Short.MAX_VALUE) .addGroup(Alignment.TRAILING, gl_jpModbusRTU.createSequentialGroup() .addContainerGap() .addGroup(gl_jpModbusRTU.createParallelGroup(Alignment.LEADING) .addComponent(lblComport) .addComponent(txtCom, GroupLayout.PREFERRED_SIZE, 108, GroupLayout.PREFERRED_SIZE)) .addPreferredGap(ComponentPlacement.RELATED) .addGroup(gl_jpModbusRTU.createParallelGroup(Alignment.TRAILING) .addGroup(gl_jpModbusRTU.createSequentialGroup() .addPreferredGap(ComponentPlacement.RELATED) .addComponent(lblSlaveid, GroupLayout.DEFAULT_SIZE, 46, Short.MAX_VALUE)) .addComponent(textField_1, GroupLayout.PREFERRED_SIZE, 46, GroupLayout.PREFERRED_SIZE)) .addContainerGap()) ); gl_jpModbusRTU.setVerticalGroup( gl_jpModbusRTU.createParallelGroup(Alignment.LEADING) .addGap(0, 51, Short.MAX_VALUE) .addGroup(gl_jpModbusRTU.createSequentialGroup() .addGroup(gl_jpModbusRTU.createParallelGroup(Alignment.BASELINE) .addComponent(lblComport) .addComponent(lblSlaveid)) .addPreferredGap(ComponentPlacement.RELATED) .addGroup(gl_jpModbusRTU.createParallelGroup(Alignment.BASELINE) .addComponent(textField_1, GroupLayout.PREFERRED_SIZE, GroupLayout.DEFAULT_SIZE, GroupLayout.PREFERRED_SIZE) .addComponent(txtCom, GroupLayout.PREFERRED_SIZE, GroupLayout.DEFAULT_SIZE, GroupLayout.PREFERRED_SIZE)) .addContainerGap()) ); jpModbusRTU.setLayout(gl_jpModbusRTU); jTextArea1 = new javax.swing.JTextArea(); jTextArea1.setEditable(false); jTextArea1.setBackground(new java.awt.Color(204, 204, 204)); jTextArea1.setColumns(20); jTextArea1.setRows(5); GroupLayout groupLayout = new GroupLayout(getContentPane()); groupLayout.setHorizontalGroup( groupLayout.createParallelGroup(Alignment.LEADING) .addGroup(groupLayout.createSequentialGroup() .addGroup(groupLayout.createParallelGroup(Alignment.LEADING, false) .addComponent(jLabel1) .addGroup(groupLayout.createSequentialGroup() .addGap(10) .addComponent(comboBox, GroupLayout.PREFERRED_SIZE, 174, GroupLayout.PREFERRED_SIZE)) .addGroup(groupLayout.createSequentialGroup() .addGroup(groupLayout.createParallelGroup(Alignment.LEADING) .addGroup(groupLayout.createSequentialGroup() .addGap(10) .addGroup(groupLayout.createParallelGroup(Alignment.LEADING, false) .addGroup(groupLayout.createSequentialGroup() .addPreferredGap(ComponentPlacement.RELATED) .addComponent(jButton1, GroupLayout.DEFAULT_SIZE, 174, Short.MAX_VALUE)) .addComponent(jButton2, GroupLayout.DEFAULT_SIZE, 174, Short.MAX_VALUE) .addComponent(jButton3, GroupLayout.DEFAULT_SIZE, GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE) .addComponent(jButton4, GroupLayout.DEFAULT_SIZE, GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))) .addGroup(groupLayout.createSequentialGroup() .addContainerGap() .addComponent(jpModbusRTU, GroupLayout.PREFERRED_SIZE, 174, GroupLayout.PREFERRED_SIZE)) .addGroup(groupLayout.createSequentialGroup() .addContainerGap() .addComponent(jpModbusTCP, GroupLayout.PREFERRED_SIZE, 174, GroupLayout.PREFERRED_SIZE))) .addPreferredGap(ComponentPlacement.RELATED) .addComponent(jPanel1, GroupLayout.PREFERRED_SIZE, GroupLayout.DEFAULT_SIZE, GroupLayout.PREFERRED_SIZE)) .addGroup(groupLayout.createSequentialGroup() .addGap(10) .addComponent(jScrollPane2, GroupLayout.PREFERRED_SIZE, GroupLayout.DEFAULT_SIZE, GroupLayout.PREFERRED_SIZE) .addPreferredGap(ComponentPlacement.RELATED) .addComponent(jTextArea1, GroupLayout.DEFAULT_SIZE, 424, Short.MAX_VALUE))) .addContainerGap()) ); groupLayout.setVerticalGroup( groupLayout.createParallelGroup(Alignment.LEADING) .addGroup(groupLayout.createSequentialGroup() .addComponent(jLabel1) .addGap(11) .addComponent(comboBox, GroupLayout.PREFERRED_SIZE, GroupLayout.DEFAULT_SIZE, GroupLayout.PREFERRED_SIZE) .addGap(7) .addGroup(groupLayout.createParallelGroup(Alignment.LEADING, false) .addComponent(jPanel1, GroupLayout.DEFAULT_SIZE, GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE) .addGroup(groupLayout.createSequentialGroup() .addComponent(jpModbusTCP, GroupLayout.PREFERRED_SIZE, GroupLayout.DEFAULT_SIZE, GroupLayout.PREFERRED_SIZE) .addGap(2) .addComponent(jpModbusRTU, GroupLayout.PREFERRED_SIZE, 51, GroupLayout.PREFERRED_SIZE) .addGap(18) .addComponent(jButton1) .addGap(11) .addComponent(jButton2) .addGap(11) .addComponent(jButton3) .addGap(11) .addComponent(jButton4))) .addGap(6) .addGroup(groupLayout.createParallelGroup(Alignment.BASELINE) .addComponent(jScrollPane2, GroupLayout.PREFERRED_SIZE, 103, GroupLayout.PREFERRED_SIZE) .addComponent(jTextArea1, GroupLayout.PREFERRED_SIZE, 101, GroupLayout.PREFERRED_SIZE))) ); jLabel3 = new javax.swing.JLabel(); jLabel3.setText("IP-Address"); jLabel4 = new javax.swing.JLabel(); jLabel4.setText("Port"); jTextFieldIPAddress = new javax.swing.JTextField(); jTextFieldIPAddress.setText("127.0.0.1"); jTextFieldIPAddress.setToolTipText(""); jTextFieldPort = new javax.swing.JTextField(); jTextFieldPort.setText("502"); GroupLayout gl_jpModbusTCP = new GroupLayout(jpModbusTCP); gl_jpModbusTCP.setHorizontalGroup( gl_jpModbusTCP.createParallelGroup(Alignment.LEADING) .addGroup(gl_jpModbusTCP.createSequentialGroup() .addContainerGap() .addGroup(gl_jpModbusTCP.createParallelGroup(Alignment.LEADING) .addComponent(jTextFieldIPAddress, GroupLayout.PREFERRED_SIZE, 110, GroupLayout.PREFERRED_SIZE) .addComponent(jLabel3)) .addPreferredGap(ComponentPlacement.RELATED) .addGroup(gl_jpModbusTCP.createParallelGroup(Alignment.LEADING) .addComponent(jLabel4) .addComponent(jTextFieldPort, GroupLayout.PREFERRED_SIZE, 46, GroupLayout.PREFERRED_SIZE)) .addGap(2)) ); gl_jpModbusTCP.setVerticalGroup( gl_jpModbusTCP.createParallelGroup(Alignment.LEADING) .addGroup(gl_jpModbusTCP.createSequentialGroup() .addGroup(gl_jpModbusTCP.createParallelGroup(Alignment.BASELINE) .addComponent(jLabel3) .addComponent(jLabel4)) .addPreferredGap(ComponentPlacement.RELATED) .addGroup(gl_jpModbusTCP.createParallelGroup(Alignment.BASELINE) .addComponent(jTextFieldIPAddress, GroupLayout.PREFERRED_SIZE, GroupLayout.DEFAULT_SIZE, GroupLayout.PREFERRED_SIZE) .addComponent(jTextFieldPort, GroupLayout.PREFERRED_SIZE, GroupLayout.DEFAULT_SIZE, GroupLayout.PREFERRED_SIZE)) .addContainerGap()) ); jpModbusTCP.setLayout(gl_jpModbusTCP); getContentPane().setLayout(groupLayout); pack(); }// </editor-fold>//GEN-END:initComponents private void jLabel1MouseClicked(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_jLabel1MouseClicked if (java.awt.Desktop.isDesktopSupported ()) { java.awt.Desktop desktop = java.awt.Desktop.getDesktop (); if (desktop.isSupported (java.awt.Desktop.Action.BROWSE)) { try { desktop.browse (new java.net.URI ("www.easymodbustcp.net")); } catch (java.io.IOException e) { e.printStackTrace (); } catch (java.net.URISyntaxException e) { e.printStackTrace (); } } } }//GEN-LAST:event_jLabel1MouseClicked private void jButton1MouseClicked(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_jButton1MouseClicked if (!modbusClient.isConnected()) { if (this.comboBox.getSelectedItem() == "Modbus TCP") { modbusClient.setipAddress(jTextFieldIPAddress.getText()); modbusClient.setPort(Integer.valueOf(jTextFieldPort.getText())); try { modbusClient.Connect(); } catch (Exception e) { JOptionPane.showMessageDialog(null, "Connection failed", "Connection failed", JOptionPane.OK_CANCEL_OPTION); } } else { try { modbusClient.setUnitIdentifier((byte)1); modbusClient.Connect(txtCom.getText()); } catch (Exception e) { JOptionPane.showMessageDialog(null, "Connection failed", "Connection failed", JOptionPane.OK_CANCEL_OPTION); } } } DefaultListModel listModel = new DefaultListModel(); int startingAddress = Integer.valueOf(jTextFieldStartingAddress.getText())-1; int numberOfValues = Integer.valueOf(jTextFieldNumberOfValues.getText()); try { boolean[] serverResponse = modbusClient.ReadCoils(startingAddress, numberOfValues); for (int i = 0; i < serverResponse.length; i++) listModel.addElement(serverResponse[i]); } catch (Exception e) { JOptionPane.showMessageDialog(null, "Server response error", "Connection failed", JOptionPane.OK_CANCEL_OPTION); } jList1.setModel(listModel); }//GEN-LAST:event_jButton1MouseClicked private void jButton2MouseClicked(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_jButton2MouseClicked if (!modbusClient.isConnected()) { if (this.comboBox.getSelectedItem() == "Modbus TCP") { modbusClient.setipAddress(jTextFieldIPAddress.getText()); modbusClient.setPort(Integer.valueOf(jTextFieldPort.getText())); try { modbusClient.setUnitIdentifier((byte)1); modbusClient.Connect(); } catch (Exception e) { JOptionPane.showMessageDialog(null, "Connection failed", "Connection failed", JOptionPane.OK_CANCEL_OPTION); } } else { try { modbusClient.Connect(txtCom.getText()); } catch (Exception e) { JOptionPane.showMessageDialog(null, "Connection failed", "Connection failed", JOptionPane.OK_CANCEL_OPTION); } } } DefaultListModel listModel = new DefaultListModel(); int startingAddress = Integer.valueOf(jTextFieldStartingAddress.getText())-1; int numberOfValues = Integer.valueOf(jTextFieldNumberOfValues.getText()); try { boolean[] serverResponse = modbusClient.ReadDiscreteInputs(startingAddress, numberOfValues); for (int i = 0; i < serverResponse.length; i++) listModel.addElement(serverResponse[i]); } catch (Exception e) { JOptionPane.showMessageDialog(null, "Server response error ", "Connection failed", JOptionPane.OK_CANCEL_OPTION); } jList1.setModel(listModel); }//GEN-LAST:event_jButton2MouseClicked private void jButton3MouseClicked(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_jButton3MouseClicked if (!modbusClient.isConnected()) { if (this.comboBox.getSelectedItem() == "Modbus TCP") { modbusClient.setipAddress(jTextFieldIPAddress.getText()); modbusClient.setPort(Integer.valueOf(jTextFieldPort.getText())); try { modbusClient.Connect(); } catch (Exception e) { JOptionPane.showMessageDialog(null, "Connection failed", "Connection failed", JOptionPane.OK_CANCEL_OPTION); } } else { try { modbusClient.Connect(txtCom.getText()); } catch (Exception e) { JOptionPane.showMessageDialog(null, "Connection failed", "Connection failed", JOptionPane.OK_CANCEL_OPTION); } } } DefaultListModel listModel = new DefaultListModel(); int startingAddress = Integer.valueOf(jTextFieldStartingAddress.getText())-1; int numberOfValues = Integer.valueOf(jTextFieldNumberOfValues.getText()); try { int[] serverResponse = modbusClient.ReadHoldingRegisters(startingAddress, numberOfValues); for (int i = 0; i < serverResponse.length; i++) listModel.addElement(serverResponse[i]); } catch (Exception e) { JOptionPane.showMessageDialog(null, "Server response error", "Connection failed", JOptionPane.OK_CANCEL_OPTION); } jList1.setModel(listModel); }//GEN-LAST:event_jButton3MouseClicked private void jButton4MouseClicked(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_jButton4MouseClicked if (!modbusClient.isConnected()) { if (this.comboBox.getSelectedItem() == "Modbus TCP") { modbusClient.setipAddress(jTextFieldIPAddress.getText()); modbusClient.setPort(Integer.valueOf(jTextFieldPort.getText())); try { modbusClient.Connect(); } catch (Exception e) { JOptionPane.showMessageDialog(null, "Connection failed", "Connection failed", JOptionPane.OK_CANCEL_OPTION); } } else { try { modbusClient.Connect(txtCom.getText()); } catch (Exception e) { JOptionPane.showMessageDialog(null, "Connection failed", "Connection failed", JOptionPane.OK_CANCEL_OPTION); } } } DefaultListModel listModel = new DefaultListModel(); int startingAddress = Integer.valueOf(jTextFieldStartingAddress.getText())-1; int numberOfValues = Integer.valueOf(jTextFieldNumberOfValues.getText()); try { int[] serverResponse = modbusClient.ReadInputRegisters(startingAddress, numberOfValues); for (int i = 0; i < serverResponse.length; i++) listModel.addElement(serverResponse[i]); } catch (Exception e) { JOptionPane.showMessageDialog(null, "Server response error", "Connection failed", JOptionPane.OK_CANCEL_OPTION); } jList1.setModel(listModel); }//GEN-LAST:event_jButton4MouseClicked /** * @param args the command line arguments */ public static void main(String args[]) { /* Set the Nimbus look and feel */ //<editor-fold defaultstate="collapsed" desc=" Look and feel setting code (optional) "> /* If Nimbus (introduced in Java SE 6) is not available, stay with the default look and feel. * For details see http://download.oracle.com/javase/tutorial/uiswing/lookandfeel/plaf.html */ try { for (javax.swing.UIManager.LookAndFeelInfo info : javax.swing.UIManager.getInstalledLookAndFeels()) { if ("Nimbus".equals(info.getName())) { javax.swing.UIManager.setLookAndFeel(info.getClassName()); break; } } } catch (ClassNotFoundException ex) { java.util.logging.Logger.getLogger(EasyModbusTCPClientExampleGUI.class.getName()).log(java.util.logging.Level.SEVERE, null, ex); } catch (InstantiationException ex) { java.util.logging.Logger.getLogger(EasyModbusTCPClientExampleGUI.class.getName()).log(java.util.logging.Level.SEVERE, null, ex); } catch (IllegalAccessException ex) { java.util.logging.Logger.getLogger(EasyModbusTCPClientExampleGUI.class.getName()).log(java.util.logging.Level.SEVERE, null, ex); } catch (javax.swing.UnsupportedLookAndFeelException ex) { java.util.logging.Logger.getLogger(EasyModbusTCPClientExampleGUI.class.getName()).log(java.util.logging.Level.SEVERE, null, ex); } //</editor-fold> /* Create and display the form */ java.awt.EventQueue.invokeLater(new Runnable() { public void run() { new EasyModbusTCPClientExampleGUI().setVisible(true); } }); } // Variables declaration - do not modify//GEN-BEGIN:variables private javax.swing.JButton jButton1; private javax.swing.JButton jButton2; private javax.swing.JButton jButton3; private javax.swing.JButton jButton4; private javax.swing.JLabel jLabel1; private javax.swing.JLabel jLabel2; private javax.swing.JLabel jLabel3; private javax.swing.JLabel jLabel4; private javax.swing.JLabel jLabel5; private javax.swing.JLabel jLabel6; private javax.swing.JList<String> jList1; private javax.swing.JPanel jPanel1; private javax.swing.JScrollPane jScrollPane1; private javax.swing.JScrollPane jScrollPane2; private javax.swing.JTextArea jTextArea1; private javax.swing.JTextField jTextFieldIPAddress; private javax.swing.JTextField jTextFieldNumberOfValues; private javax.swing.JTextField jTextFieldPort; private javax.swing.JTextField jTextFieldStartingAddress; private JPanel jpModbusTCP; private JPanel jpModbusRTU; private JLabel lblComport; private JTextField txtCom; private JTextField textField_1; private JLabel lblSlaveid; }
true
ec89481cfd06fbdacc45600b06a2be60da8400c6
Java
shawntime/shawn-design-pattern
/src/main/java/com/shawntime/designpattern/factory/abstractfactory/TestMain.java
UTF-8
1,355
2.671875
3
[]
no_license
package com.shawntime.designpattern.factory.abstractfactory; import com.shawntime.designpattern.factory.abstractfactory.airconditioner.AbstractAirConditioner; import com.shawntime.designpattern.factory.abstractfactory.tv.AbstractTV; import com.shawntime.designpattern.factory.abstractfactory.washingmachine.AbstractWashingMachine; /** * Created by shma on 2018/4/18. */ public class TestMain { public static void main(String[] args) { AbstractFactory factory = new ChangHongFactory(); AbstractAirConditioner airConditioner = factory.createAirConditioner(); AbstractTV tv = factory.createTV(); AbstractWashingMachine washingMachine = factory.createWashingMachine(); airConditioner.product(); tv.product(); washingMachine.product(); factory = new MediaFactory(); airConditioner = factory.createAirConditioner(); tv = factory.createTV(); washingMachine = factory.createWashingMachine(); airConditioner.product(); tv.product(); washingMachine.product(); factory = new GreeFactory(); airConditioner = factory.createAirConditioner(); tv = factory.createTV(); washingMachine = factory.createWashingMachine(); airConditioner.product(); tv.product(); washingMachine.product(); } }
true
28d63a086fc09803e440c841205be718a39eb989
Java
harshuHarsh/TakeHome
/Question6/OtherSciFiSpaceShips.java
UTF-8
312
1.90625
2
[]
no_license
package test; public class OtherSciFiSpaceShips extends SpaceShip { public int getTonnage() { return 2; } public String getName() { return "scifi"; } public String getFranchise() // Star Wars, Star Trek, or some other Sci-fi universe { return "UNSC Infinity"; } }
true
d340c8aa9de2a6edcdc036395a06b28115a42150
Java
chorras3/workspace_github_01
/2015-05-16_1133_Swing/misc/Main.java
UTF-8
446
2.671875
3
[]
no_license
package misc; public class Main { public static void main (String[] args){ Main application = new Main(); application.run(); String strType = ""; String strResult = application.typeRecordToSelect(strType); } protected void run(){ System.out.println("run()"); } private String typeRecordToSelect(String strType) { String strResult = ""; return strResult; } }
true
cc8669f19352de29ee119dc23be4d327e9273d31
Java
matslindh/hiof
/rammeverk/patterns/src/main/java/no/lindh/antipattern_dataonlyasstrings/Framework.java
UTF-8
394
2.65625
3
[ "MIT" ]
permissive
package no.lindh.antipattern_dataonlyasstrings; import java.util.Random; public class Framework { protected int instanceId; public Framework() { instanceId = new Random().nextInt(); } public String getInstanceId() { return Integer.toString(instanceId); } public String getInstance() { return "My instanceId is " + instanceId + "."; } }
true
376ed9f639f66135d3c300c6ac2f7ae338a6c4cb
Java
nikitinalexx/UsersExample
/src/main/java/com/alex/nikitin/model/ItemOrder.java
UTF-8
1,113
2.390625
2
[]
no_license
package com.alex.nikitin.model; import javax.persistence.*; import javax.validation.constraints.NotNull; import java.io.Serializable; import java.util.Collection; @Entity public class ItemOrder implements Serializable{ @Id @GeneratedValue private long id; @NotNull @ManyToOne(fetch = FetchType.EAGER) private User customer; private String name; private String description; @OneToMany(mappedBy = "itemOrder", fetch = FetchType.LAZY, cascade = CascadeType.ALL) private Collection<Item> items; public User getCustomer() { return customer; } public void setCustomer(User customer) { this.customer = customer; } public Collection<Item> getItems() { return items; } public String getName() { return name; } public void setName(String name) { this.name = name; } public String getDescription() { return description; } public void setDescription(String description) { this.description = description; } public long getId() { return id; } }
true
94f32ec89fce8fdec04f45cf9512ff0557c8a09d
Java
Varinder5997/second
/CodingChalange/src/com/mindtree/codingchalange/client/CodingChalangeApplication.java
UTF-8
1,335
3.203125
3
[]
no_license
package com.mindtree.codingchalange.client; import java.util.Scanner; import com.mindtree.codingchalange.service.FurnitureService; public class CodingChalangeApplication { public static void main(String[] args) { Scanner sc=new Scanner(System.in); FurnitureService fs=new FurnitureService(); boolean flag=true; do { System.out.println("1. add the furniture"); System.out.println("2. sort decending order on cost based"); System.out.println("3. purchased furniture"); System.out.println("4. find furniture by Id"); System.out.println("5. exit"); int choice=sc.nextInt(); switch (choice) { case 1: System.out.println("Enter the number of furitures to add"); int number=sc.nextInt(); System.out.println(fs.addFurniture(number)); break; case 2: System.out.println(fs.sortedForm()); fs.display(); break; case 3: System.out.println("Enter the name furnture you want to buy"); sc.nextLine(); String name=sc.nextLine(); System.out.println(fs.buyFurniture(name)); break; case 4: System.out.println("Enter the Id"); int id=sc.nextInt(); System.out.println(fs.binarySearch(id)); break; case 5: flag=false; break; default: System.out.println("Enter the valid Input"); break; } } while (flag); } }
true
7607a01a6a2011478b143e6a01f6c9566f208a7c
Java
EdgarFalco/M9
/M9Act4ProcesosFils/src/Cliente.java
UTF-8
369
2.828125
3
[]
no_license
public class Cliente { private String cliente; private int[] arrayArticulos; public Cliente() { } public Cliente(String cliente, int[] arrayArticulos) { this.cliente = cliente; this.arrayArticulos = arrayArticulos; } public String getCliente() { return cliente; } public int[] getArrayArticulos() { return arrayArticulos; } }
true
8f2b19637557ea210a67145362f717b65749a404
Java
gurkenlabs/litiengine
/litiengine/src/main/java/de/gurkenlabs/litiengine/environment/tilemap/MapProperty.java
UTF-8
1,481
2.34375
2
[ "MIT" ]
permissive
package de.gurkenlabs.litiengine.environment.tilemap; import java.lang.reflect.Field; import java.lang.reflect.Modifier; import java.util.ArrayList; import java.util.List; import java.util.logging.Level; import java.util.logging.Logger; public final class MapProperty { private static final Logger log = Logger.getLogger(MapProperty.class.getName()); public static final String AMBIENTCOLOR = "AMBIENTLIGHT"; public static final String SHADOWCOLOR = "SHADOWCOLOR"; public static final String MAP_DESCRIPTION = "MAP_DESCRIPTION"; public static final String MAP_TITLE = "MAP_TITLE"; public static final String GRAVITY = "GRAVITY"; private MapProperty() {} private static List<String> availableProperties = new ArrayList<>(); public static List<String> getAvailableProperties() { if (availableProperties.isEmpty()) { for (final Field field : MapProperty.class.getDeclaredFields()) { if (field.getType() == String.class && Modifier.isStatic(field.getModifiers()) && Modifier.isPublic(field.getModifiers())) { try { availableProperties.add((String) field.get(null)); } catch (final IllegalArgumentException | IllegalAccessException e) { log.log(Level.SEVERE, e.getMessage(), e); } } } } return availableProperties; } public static boolean isCustom(final String name) { return getAvailableProperties().stream().noneMatch(x -> x.equalsIgnoreCase(name)); } }
true
1605f354287122916eac5a03678e4ad1e9352203
Java
anilthakur0909/EMS
/src/com/bebo/controller/RegistrationController.java
UTF-8
3,693
2.203125
2
[]
no_license
package com.bebo.controller; import java.util.ArrayList; import java.util.List; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Qualifier; import org.springframework.stereotype.Controller; import org.springframework.web.bind.annotation.ModelAttribute; import org.springframework.web.bind.annotation.PathVariable; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestMethod; import org.springframework.web.servlet.ModelAndView; import com.bebo.component.EmployeeEmail; import com.bebo.model.ContractEmployee; import com.bebo.model.Employee; import com.bebo.model.OfficeAddress; import com.bebo.model.RegularEmployee; import com.bebo.model.Role; import com.bebo.service.EmployeeService; /* * @author Anil.Thakur */ @Controller public class RegistrationController { @Autowired private EmployeeService employeeService; @Autowired private EmployeeEmail employeeEmail; @Autowired @Qualifier("regularEmployeeAddress") private OfficeAddress regularEmployeeAddress; @Autowired @Qualifier("contractEmployeeAddress") private OfficeAddress contractEmployeeAddress; @RequestMapping(value = "/userRegister", method = RequestMethod.GET) public ModelAndView register(HttpServletRequest request, HttpServletResponse response) { ModelAndView modelAndView = new ModelAndView(); modelAndView.addObject("regularEmployee", new RegularEmployee()); modelAndView.addObject("contractEmployee", new ContractEmployee()); modelAndView.setViewName("userRegister"); return modelAndView; } @RequestMapping(value = "/registerProcess", method = RequestMethod.POST) public ModelAndView addEmployee(HttpServletRequest request, HttpServletResponse response, @ModelAttribute("regularEmployee") RegularEmployee regularEmployee, @ModelAttribute("contractEmployee") ContractEmployee contractEmployee) { ModelAndView model = new ModelAndView(); try { if (regularEmployee != null && regularEmployee.getSalary() != null && regularEmployee.getBonus() != null) { regularEmployee.setAddress(regularEmployeeAddress); regularEmployee.setRoles(getRoles()); employeeService.register(regularEmployee); employeeEmail.sendEmail(regularEmployee); } else { contractEmployee.setAddress(contractEmployeeAddress); contractEmployee.setRoles(getRoles()); employeeService.register(contractEmployee); employeeEmail.sendEmail(contractEmployee); } model.addObject("message", "Employee Added Successfully.."); List<Employee> employees = employeeService.findAllEmployee(); model.addObject("employees", employees); model.setViewName("adminHomePage"); } catch (Exception exception) { model.addObject("error", "UserName Already Exist"); model.setViewName("userRegister"); } return model; } @RequestMapping(value = "/deleteEmployee/{employeeId}", method = RequestMethod.GET) public ModelAndView deleteEmployee(@PathVariable int employeeId) { employeeService.deleteEmployee(employeeId); ModelAndView model = new ModelAndView(); model.addObject("message", "Employee Added Successfully.."); List<Employee> employees = employeeService.findAllEmployee(); model.addObject("employees", employees); model.setViewName("adminHomePage"); return model; } private List<Role> getRoles() { List<Role> roles = new ArrayList<Role>(); Role role1 = new Role(); role1.setRoleName("Engineer"); Role role2 = new Role(); role2.setRoleName("Developer"); roles.add(role1); roles.add(role2); return roles; } }
true
cb2629dc4328bd10867c046a3767d0ed37dfdb0c
Java
tsszh/LeetCode
/Java/src/LT050T100/LT076.java
UTF-8
1,692
3.921875
4
[]
no_license
package LT050T100; import java.util.*; /** * 76. Minimum Window Substring * * Given a string S and a string T, find the minimum window in S which will * contain all the characters in T in complexity O(n). * * For example, * S = "ADOBECODEBANC" * T = "ABC" Minimum window is "BANC". * * Note: If there is no such window in S that covers all characters in T, return * the empty string "". * * If there are multiple such windows, you are guaranteed that there will always * be only one unique minimum window in S. * * Similar Problems: 30. Substring with Concatenation of All Words * 209. Minimum Size Subarray Sum * 239. Sliding Window Maximum * * @author Zehao * */ public class LT076 { public String minWindow(String s, String t) { if (s == null || t == null || s.length() < t.length()) return ""; Map<Character, Integer> map = new HashMap<>(); Set<Character> set = new HashSet<>(); for (int i = 0; i < t.length(); i++) { char ch = t.charAt(i); map.put(ch, map.containsKey(ch) ? map.get(ch) + 1 : 1); set.add(ch); } int startIndex = -1, minLen = Integer.MAX_VALUE; for (int i = 0, j = 0; j < s.length(); j++) { char ch = s.charAt(j); if (map.containsKey(ch)) { map.put(ch, map.get(ch) - 1); if (map.get(ch) <= 0) set.remove(ch); } while (set.size() == 0) { if (j - i + 1 < minLen) { minLen = j - i + 1; startIndex = i; } char tmp = s.charAt(i++); if (map.containsKey(tmp)) { map.put(tmp, map.get(tmp) + 1); if (map.get(tmp) > 0) set.add(tmp); } } } if (startIndex == -1) return ""; return s.substring(startIndex, startIndex + minLen); } }
true
decfb18086b1985bbc0af9c4ad26da50747f989d
Java
roquinho/ClinicaPoo
/Clinica/src/main/java/br/upe/poo/clinica/regraNegocio/InterfaceRegraNegocioPacientes.java
UTF-8
848
1.875
2
[]
no_license
package br.upe.poo.clinica.regraNegocio; import br.upe.poo.clinica.entidades.Pacientes; import br.upe.poo.clinica.listarEntidades.ListarPacientes; import java.io.Serializable; import java.util.List; public interface InterfaceRegraNegocioPacientes extends Serializable{ public void cadastrarPaciente(Pacientes paciente)throws ExceptionRegraNegocioPacientesCadastrar; public ListarPacientes buscarPacienteCpf(Long cpf)throws ExceptionRegraNegocioPacienteBuscarPaciente; public List<ListarPacientes> buscarPacienteNome(String nome)throws ExceptionRegraNegocioPacienteBuscarPaciente; public void atualizarPaciente(Pacientes paciente)throws ExceptionRegraNegocioAtualizarPacientes; public void deletarPaciente(Pacientes paciente)throws ExceptionRegraNegocioDeletarPacientes; }
true
88639b2aa00818895015de237dd7abcf9497c33b
Java
lukaszmagiera26/TEST
/TIcketMachine/src/Runner.java
UTF-8
132
1.84375
2
[]
no_license
public class Runner { Operations operations = new Operations(); public void run(){ operations.operations(); } }
true
839495239fa9fca71493f70993983d651dc5230e
Java
threecube/kmeans-detector
/src/main/java/com/threecube/prod/kmeansDetector/kmeans/processor/KmeansProcessorImpl.java
UTF-8
3,101
2.734375
3
[]
no_license
/* * @(#)KmeansProcessorImpl.java $version 2015-1-27 * * Copyright 2007 THREECUBE Corp. All rights Reserved. * THREECUBE PROPRIETARY/CONFIDENTIAL. Use is subject to license terms. */ package com.threecube.prod.kmeansDetector.kmeans.processor; //import java.lang.annotation.Annotation; import java.util.List; import com.threecube.prod.kmeansDetector.kmeans.DefinedConstants; import com.threecube.prod.kmeansDetector.kmeans.model.NormalizedPoint; /** * @author Mike */ public class KmeansProcessorImpl implements KmeansProcessor { /** * @param nPoint * @param type * @return */ @Override public NormalizedPoint findCentroid(List<NormalizedPoint> nPoints, int type) { NormalizedPoint centroid = new NormalizedPoint(); long matchedNum = 0; float[] totals = new float[DefinedConstants.selectedFieldNames.length]; for (NormalizedPoint nPoint : nPoints) { if (nPoint.getType() != type) { continue; } for (int i = 0; i < DefinedConstants.selectedFieldNames.length; i++) { totals[i] += nPoint.getField(DefinedConstants.selectedFieldNames[i]); } centroid.setService(nPoint.getService()); matchedNum++; } if (matchedNum > 0) { for (int i = 0; i < DefinedConstants.selectedFieldNames.length; i++) { centroid.setField(DefinedConstants.selectedFieldNames[i], totals[i] / matchedNum); } centroid.setType(type); } else { return null; } return centroid; } /** * @param centroid * @param point * @return */ @Override public float calculateDis(NormalizedPoint centroid, NormalizedPoint point) { float distance = 0l; for (String fieldName : DefinedConstants.selectedFieldNames) { distance += Math.pow(centroid.getField(fieldName) - point.getField(fieldName), 2); } return distance; } /** * check if newCentroid is exist in centroids,this funtion is used to check * * @param newCentroid * @param centroids * @return */ @Override public boolean isExist(NormalizedPoint newCentroid, List<NormalizedPoint> centroids) { for (NormalizedPoint centroid : centroids) { if (centroid.getType() != newCentroid.getType()) { continue; } boolean equal = true; //check each field for (String fieldName : DefinedConstants.selectedFieldNames) { if (centroid.getField(fieldName) != newCentroid.getField(fieldName)) { equal = false; break; } } if (equal) { return true; } } return false; } // private String ifPropertyUsed(Class clazz, String propName) { // Annotation annotation = null; // try { // annotation = clazz.getDeclaredField(propName).getAnnotation(Property.class); // } catch (NoSuchFieldException e) { // System.out.println("not found the filed:" + propName + " in class " + clazz); // } catch (SecurityException e) { // System.out.println("SecurityException:" + propName + " in class " + clazz); // } // Property property = (Property)annotation; // // return property.Valid(); // } }
true
602c5e7cbfb86b0c5df9886925198b3a0c1ceeeb
Java
stackekareem/Week1Assignment
/com/weekone/assignment1/Pattern.java
UTF-8
3,062
4.0625
4
[]
no_license
package com.weekone.assignment1; /** * prints 4 patterns */ public class Pattern { /** * print pattern one recurizely * * * ** * *** * @param stackSize - maxlayer size * @param currlayer - currentlayer printed */ public void patternOne(int stackSize,int currlayer){ //length of layer int len = currlayer + 1; //print layer for (int i=0; i<len; i++) System.out.print("*"); System.out.println(); //print next layer if (stackSize > currlayer + 1) patternOne(stackSize,currlayer + 1); } /** * print pattern two recurizely * *** * ** * * * @param currlayer - current layer */ public void patternTwo(int currlayer){ //print layer for (int i=0; i<currlayer; i++) System.out.print("*"); System.out.println(); //print next layer if (currlayer > 0) patternTwo(currlayer - 1); } /** * print pattern three recurizely * * * *** * ***** * @param stackSize - maxlayer size * @param currlayer - currentlayer printed */ public void patternThree(int stackSize,int currlayer){ //length of layer int len = 2 * currlayer + 1 ; //lenght of blanck space int offest = stackSize + 2 - (currlayer + 1); //print layer for (int i=0; i<offest; i++) System.out.print(" "); for (int i=0; i<len; i++) System.out.print("*"); System.out.println(); //print next layer if (stackSize > currlayer + 1) patternThree(stackSize,currlayer + 1); } /** * print pattern four recurizely * ***** * *** * * * @param stackSize - maxlayer size * @param currlayer - currentlayer printed */ public void patternFour(int currlayer,int stackSize){ //length of layer int len = 2 * currlayer - 1; //lenght of black space int offest = -1 * currlayer + stackSize + 2; //print layer for (int i=0; i<offest; i++) System.out.print(" "); for (int i=0; i<len; i++) System.out.print("*"); System.out.println(); //print next layer if (currlayer > 1) patternFour(currlayer - 1,stackSize); } public static void main(String[] args) { Pattern p = new Pattern(); //number of layers int n = 4; //pattern one System.out.println("1)"); p.patternOne(n, 0); System.out.println("---------"); //pattern two System.out.println("2)"); System.out.println("----------"); p.patternTwo(n); //patten three System.out.println("3)"); p.patternThree(n, 0); System.out.println("-----------"); //pattern four System.out.println("4)"); p.patternFour(n,n); System.out.println("-----------"); } }
true
79c6b990dbac3ffe1359cca5e54b111b44e1d976
Java
hrnrstgzl/hrms
/src/main/java/com/rgsoft/hrms/dataAccess/abstracts/EducationDao.java
UTF-8
414
2.03125
2
[]
no_license
package com.rgsoft.hrms.dataAccess.abstracts; import java.util.List; import org.springframework.data.domain.Sort; import org.springframework.data.jpa.repository.JpaRepository; import com.rgsoft.hrms.entities.concretes.Education; public interface EducationDao extends JpaRepository<Education, Integer>{ public List<Education> getByResume_Id(int id); public List<Education> getByResume_Id(int id,Sort sort); }
true
7277a9456cd1f8236a2c6db0bb63254d7a1461b0
Java
mattschwartz/stonequest-original
/StoneQuest/src/com/barelyconscious/worlds/engine/gui/widgets/GameMenuWidget.java
UTF-8
359
2.078125
2
[]
no_license
package com.barelyconscious.worlds.engine.gui.widgets; import com.barelyconscious.worlds.engine.gui.LayoutData; import com.barelyconscious.worlds.engine.gui.Widget; public class GameMenuWidget extends Widget { private static final LayoutData LAYOUT = LayoutData.builder() .build(); public GameMenuWidget() { super(LAYOUT); } }
true
56dc363f6d45c9944ae24b7bb8360495d40f6968
Java
Adam713/apcontint
/app/src/main/java/p000/lda.java
UTF-8
611
1.617188
2
[]
no_license
package p000; /* renamed from: lda */ public class lda extends nda { /* renamed from: a */ public void mo4700a(int i, Object obj) { } /* renamed from: a */ public void mo4701a(int i, Object obj, Object obj2) { } /* renamed from: a */ public void mo4702a(int i, Object obj, Object obj2, Object obj3, Object obj4) { } /* renamed from: a */ public void mo4703a(int i, Object obj, Throwable th) { } /* renamed from: a */ public void mo4704a(String str) { } /* renamed from: a */ public boolean mo4705a(int i) { return false; } }
true
ece9481997b386039387aea98641121e463cd0ff
Java
wastevens/TroupeLarpCharacterRepository
/TroupeLarpCharacterRepository/src/java/com/dstevens/characters/PlayerCharacterRepository.java
UTF-8
1,635
2.59375
3
[]
no_license
package com.dstevens.characters; import java.util.function.Predicate; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; import com.dstevens.persistence.auditing.*; import com.dstevens.players.*; @Service public class PlayerCharacterRepository extends AbstractAuditableRepository<PlayerCharacter> { private final PlayerCharacterFactory factory; private PlayerDao playerDao; private TroupeDao troupeDao; @Autowired public PlayerCharacterRepository(PlayerCharacterDao dao, PlayerDao playerDao, TroupeDao troupeDao, AuditableRepositoryProvider repositoryProvider, PlayerCharacterFactory factory) { super(repositoryProvider.repositoryFor(dao)); this.playerDao = playerDao; this.troupeDao = troupeDao; this.factory = factory; } public PlayerCharacter ensureExists(Troupe troupe, Player player, String name) { Predicate<PlayerCharacter> characterWithName = ((PlayerCharacter pc) -> (pc.getName().equals(name) && !pc.isDeleted())); if (player.getCharacters().stream().anyMatch(characterWithName)) { return player.getCharacters().stream().filter(characterWithName).findFirst().get(); } return createNewCharacterFor(troupe, player, name); } private PlayerCharacter createNewCharacterFor(Troupe troupe, Player player, String name) { PlayerCharacter character = create(factory.createPlayerCharacter(name)); playerDao.save(player.withCharacter(character)); troupeDao.save(troupe.withCharacter(character)); return character; } }
true
2cd4a7bea779ea6ef3de9688324692036dd9b410
Java
oliveshannon/sd1olive
/Desktop/sd1/labs/lab3/Driver_lab3.java
UTF-8
533
3.140625
3
[]
no_license
import java.util.Scanner; public class Driver_lab3 { public static void main (String[] args){ Scanner input= new Scanner(System.in); while (true){ double x1 = input.nextDouble(); if (x1 == 0.0){ break; } double y1= input.nextDouble(); double x2 = input.nextDouble(); double y2= input.nextDouble(); double p = input.nextDouble(); double distance = Math.pow(Math.pow(Math.abs(x1-x2), p) + Math.pow(Math.abs(y1-y2), p), 1.0/p); System.out.println(distance); } } }
true
3d571b3e68c76a712754350713d1fd33105c6fff
Java
FelipeFFS93/turma27java
/Java/Aulas/src/exerciciosJavaLista2/lista2Tarefa02.java
ISO-8859-1
547
3.71875
4
[]
no_license
//2 - Faa um programa que entre com trs nmeros e coloque em // ordem crescente. package exerciciosJavaLista2; import java.util.Scanner; import java.util.Arrays; public class lista2Tarefa02 { public static void main(String[] args) { Scanner read = new Scanner(System.in); long[] numero = new long [3]; for(int x = 0; x < numero.length; x++) { System.out.println("Digite um valor qualquer: "); numero[x] = read.nextInt(); } Arrays.sort(numero); System.out.println(Arrays.toString(numero)); } }
true
d33bc4a1bba9ee16cfc9cc29921d9da817ef94e7
Java
alexr007/http-rq
/src/main/java/org/alexr/httprq/entity/E0.java
UTF-8
311
2.265625
2
[]
no_license
package org.alexr.httprq.entity; public class E0 { private int x; public E0(int x) { this.x = x; } public E0() { } public int getX() { return x; } public void setX(int x) { this.x = x; } @Override public String toString() { return String.format("E0{x=%d}", x); } }
true
bfd59255498ac67cf87ba2bbbad43bd82cac6207
Java
nuthankumar/AngularSpringBoot
/src/main/java/com/exide/sfcrm/model/PRFListCashAdvanceKey.java
UTF-8
3,432
1.78125
2
[]
no_license
/** * */ package com.exide.sfcrm.model; import java.io.Serializable; import javax.persistence.Column; import javax.persistence.Embeddable; /** * @author neethub * */ @Embeddable public class PRFListCashAdvanceKey implements Serializable{ /** * */ private static final long serialVersionUID = -6164182549454991017L; @Column(name = "agentno") private String agentNo; @Column(name = "trandate") private Float transDate; @Column(name = "netamount") private Float netAmount; @Column(name = "recoverbleamount") private Float recoverbleAmount; @Column(name = "deviationamt") private Float deviationAmt; @Column(name = "advancepayout") private Float advancePayout; @Column(name = "advancerecoverable") private Float advanceRecoverable; @Column(name = "maxrecoverableamt") private Float maxRecoverableAmt; @Column(name = "netpayout") private Float netPayout; @Column(name = "agclass") private Integer agClass; /** * @return the agentNo */ public String getAgentNo() { return agentNo; } /** * @param agentNo the agentNo to set */ public void setAgentNo(String agentNo) { this.agentNo = agentNo; } /** * @return the transDate */ public Float getTransDate() { return transDate; } /** * @param transDate the transDate to set */ public void setTransDate(Float transDate) { this.transDate = transDate; } /** * @return the netAmount */ public Float getNetAmount() { return netAmount; } /** * @param netAmount the netAmount to set */ public void setNetAmount(Float netAmount) { this.netAmount = netAmount; } /** * @return the recoverbleAmount */ public Float getRecoverbleAmount() { return recoverbleAmount; } /** * @param recoverbleAmount the recoverbleAmount to set */ public void setRecoverbleAmount(Float recoverbleAmount) { this.recoverbleAmount = recoverbleAmount; } /** * @return the deviationAmt */ public Float getDeviationAmt() { return deviationAmt; } /** * @param deviationAmt the deviationAmt to set */ public void setDeviationAmt(Float deviationAmt) { this.deviationAmt = deviationAmt; } /** * @return the advancePayout */ public Float getAdvancePayout() { return advancePayout; } /** * @param advancePayout the advancePayout to set */ public void setAdvancePayout(Float advancePayout) { this.advancePayout = advancePayout; } /** * @return the advanceRecoverable */ public Float getAdvanceRecoverable() { return advanceRecoverable; } /** * @param advanceRecoverable the advanceRecoverable to set */ public void setAdvanceRecoverable(Float advanceRecoverable) { this.advanceRecoverable = advanceRecoverable; } /** * @return the maxRecoverableAmt */ public Float getMaxRecoverableAmt() { return maxRecoverableAmt; } /** * @param maxRecoverableAmt the maxRecoverableAmt to set */ public void setMaxRecoverableAmt(Float maxRecoverableAmt) { this.maxRecoverableAmt = maxRecoverableAmt; } /** * @return the netPayout */ public Float getNetPayout() { return netPayout; } /** * @param netPayout the netPayout to set */ public void setNetPayout(Float netPayout) { this.netPayout = netPayout; } /** * @return the agClass */ public Integer getAgClass() { return agClass; } /** * @param agClass the agClass to set */ public void setAgClass(Integer agClass) { this.agClass = agClass; } }
true
71d5158166533da9b257127ad6dd5d200dc35957
Java
pengyiccb/eshop
/src/main/java/com/tfx0one/center/MarketingCenter/model/EShopMarketing.java
UTF-8
3,320
2.328125
2
[]
no_license
package com.tfx0one.center.MarketingCenter.model; import com.tfx0one.common.util.BaseEntity; import java.util.Date; import javax.persistence.*; @Table(name = "e_shop_marketing") public class EShopMarketing extends BaseEntity { @Id @GeneratedValue(strategy = GenerationType.IDENTITY) private Integer id; /** * 活动名称 */ private String title; /** * 活动标签:限时折扣,满减送等 */ private String tag; /** * 开始时间 */ @Column(name = "begin_time") private Date beginTime; /** * 结束时间 */ @Column(name = "end_time") private Date endTime; /** * @return id */ public Integer getId() { return id; } public EShopMarketing withId(Integer id) { this.setId(id); return this; } /** * @param id */ public void setId(Integer id) { this.id = id; } /** * 获取活动名称 * * @return title - 活动名称 */ public String getTitle() { return title; } public EShopMarketing withTitle(String title) { this.setTitle(title); return this; } /** * 设置活动名称 * * @param title 活动名称 */ public void setTitle(String title) { this.title = title == null ? null : title.trim(); } /** * 获取活动标签:限时折扣,满减送等 * * @return tag - 活动标签:限时折扣,满减送等 */ public String getTag() { return tag; } public EShopMarketing withTag(String tag) { this.setTag(tag); return this; } /** * 设置活动标签:限时折扣,满减送等 * * @param tag 活动标签:限时折扣,满减送等 */ public void setTag(String tag) { this.tag = tag == null ? null : tag.trim(); } /** * 获取开始时间 * * @return begin_time - 开始时间 */ public Date getBeginTime() { return beginTime; } public EShopMarketing withBeginTime(Date beginTime) { this.setBeginTime(beginTime); return this; } /** * 设置开始时间 * * @param beginTime 开始时间 */ public void setBeginTime(Date beginTime) { this.beginTime = beginTime; } /** * 获取结束时间 * * @return end_time - 结束时间 */ public Date getEndTime() { return endTime; } public EShopMarketing withEndTime(Date endTime) { this.setEndTime(endTime); return this; } /** * 设置结束时间 * * @param endTime 结束时间 */ public void setEndTime(Date endTime) { this.endTime = endTime; } @Override public String toString() { StringBuilder sb = new StringBuilder(); sb.append(getClass().getSimpleName()); sb.append(" ["); sb.append("Hash = ").append(hashCode()); sb.append(", id=").append(id); sb.append(", title=").append(title); sb.append(", tag=").append(tag); sb.append(", beginTime=").append(beginTime); sb.append(", endTime=").append(endTime); sb.append("]"); return sb.toString(); } }
true
20c7ef123bc587581d8907dc8f0c66b05f9dbf2e
Java
FranciscoVasc/Java
/Film.java
UTF-8
924
2.96875
3
[]
no_license
public class Filme { String nomeDoFilme; String generoDoFilme; int anoDeLancamento; int classificacao; String distribuicao; public void criarFilme(){ nomeDoFilme="Sexta feira 13"; generoDoFilme="Terror"; anoDeLancamento=1980; classificacao=18; distribuicao="Cinema"; } public void mostrarFilme(){ System.out.println("nome do filme: " +nomeDoFilme); System.out.println("Genero do filme: " +generoDoFilme); System.out.println("Ano do filme: " + anoDeLancamento); System.out.println("Classicacao do filme: " +classificacao); System.out.println("distribuicao do filme: " +distribuicao); } public static void main(String[] args) { Filme f = new Filme(); f.criarFilme(); f.mostrarFilme(); } }
true
72ceeb0e89aba680a2eb52b5f70fe31a6030f08d
Java
yunipingan/DailyPush
/src/test/java/cn/pingweb/controller/HelloControllerTest.java
UTF-8
414
1.539063
2
[]
no_license
package cn.pingweb.controller; import org.junit.After; import org.junit.Before; import org.junit.Test; import static org.junit.Assert.*; /** * Created by Administrator on 2017/8/7. */ public class HelloControllerTest { @Before public void setUp() throws Exception { } @After public void tearDown() throws Exception { } @Test public void sayHello() throws Exception { } }
true
40c7926c1a5e7d405015ccbbd8be5f7ad5bff285
Java
show-my-app/Unity3D
/ShowMyAppNative/Plugins/Android/AndroidStudio~/BasicToolBoxAndroid/basictoolbox/src/main/java/com/idemobi/basictoolbox/BTBDialogAndroidManager.java
UTF-8
3,623
2.140625
2
[ "Apache-2.0" ]
permissive
package com.idemobi.basictoolbox; import android.annotation.SuppressLint; import android.app.AlertDialog; import android.content.DialogInterface; import android.content.Intent; import android.net.Uri; import android.os.Build; import android.util.Log; import android.view.ContextThemeWrapper; import android.view.KeyEvent; import com.unity3d.player.UnityPlayer; public class BTBDialogAndroidManager { public static void ShowAlert(String title, String message, String okButtonText) { AlertDialog.Builder messagePopup = new AlertDialog.Builder(new ContextThemeWrapper(UnityPlayer.currentActivity, GetTheme())); messagePopup.setTitle(title); messagePopup.setMessage(message); messagePopup.setPositiveButton(okButtonText, new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) { UnityPlayer.UnitySendMessage("BTBAlertAndroid_GameObject", "OnAlertCallback", "0"); } }); messagePopup.setOnKeyListener(KeyListener); messagePopup.setCancelable(false); messagePopup.show(); } public static void ShowDialog(String title, String message, String yesButtonText, String noButtonText) { AlertDialog.Builder dialogPopupBuilder = new AlertDialog.Builder(new ContextThemeWrapper(UnityPlayer.currentActivity, GetTheme())); dialogPopupBuilder.setTitle(title); dialogPopupBuilder.setMessage(message); dialogPopupBuilder.setPositiveButton(yesButtonText, new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) { UnityPlayer.UnitySendMessage("BTBDialogAndroid_GameObject", "OnDialogCallback", "0"); } }); dialogPopupBuilder.setNegativeButton(noButtonText, new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) { UnityPlayer.UnitySendMessage("BTBDialogAndroid_GameObject", "OnDialogCallback", "1"); } }); dialogPopupBuilder.setOnKeyListener(KeyListener); dialogPopupBuilder.setCancelable(false); dialogPopupBuilder.show(); } @SuppressLint("InlinedApi") private static int GetTheme(){ int theme = 0; if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) { theme = android.R.style.Theme_Material_Light_Dialog; } else { theme = android.R.style.Theme_Holo_Dialog; } return theme; } public static void OpenAppRatingPage(String url) { Uri uri = Uri.parse(url); Intent intent = new Intent(Intent.ACTION_VIEW, uri); UnityPlayer.currentActivity.startActivity(intent); } public static void OpenWebPage(String webUrl){ Intent browserIntent = new Intent(Intent.ACTION_VIEW, Uri.parse(webUrl)); UnityPlayer.currentActivity.startActivity(browserIntent); } private static DialogInterface.OnKeyListener KeyListener = new DialogInterface.OnKeyListener() { @Override public boolean onKey(DialogInterface dialog, int keyCode, KeyEvent event) { if (keyCode == KeyEvent.KEYCODE_BACK) { Log.d("AndroidNative", "AndroidPopUp"); UnityPlayer.UnitySendMessage("AndroidMessagePopup", "OnAlertCallback", "0"); UnityPlayer.UnitySendMessage("AndroidDialogPopup", "OnDialogPopUpCallBack", "1"); dialog.dismiss(); } return false; } }; }
true
175e2dadacbb50629bf18870a6f23af216f5f508
Java
elcomthien/source
/workspace_ehotel/[InterfaceAppeHotelForCPVLaos]/src/com/elcom/eodapp/media/mod/SQL.java
UTF-8
759
1.523438
2
[]
no_license
package com.elcom.eodapp.media.mod; public interface SQL { public static final String sqlSubjectAlbum = "begin vod.getModSubject(?,?); end;"; public static final String sqlgetModListSongSubject = "begin vod.getModListSongSubject(?,?,?,?,?); end;"; public static final String sqlgetModFavorite = "begin vod.getModFavorite(?,?,?,?,?); end;"; public static final String sqladdModFavorite = "begin ? := vod.addModFavorite(?,?); end;"; public static final String sqlremoveFavorite = "begin ? := vod.removeFavorite(?,?); end;"; public static final String sqlCountMusic = "begin ? := vod.countMusic(?); end;"; public static final String sqlGetUrlImageBack = "begin ? := vod.getUrlImageBack(?); end;"; }
true
ef59daa6e1fd37fb986e91b8d10c4fab4a646bf5
Java
qiuchili/ggnn_graph_classification
/program_data/JavaProgramData/37/944.java
UTF-8
1,186
2.953125
3
[ "MIT" ]
permissive
package <missing>; public class GlobalMembers { public static int Main() { int t; int rd; int check = 0; int output = 0; String str = new String(new char[100001]); //C++ TO JAVA CONVERTER TODO TASK: Pointer arithmetic is detected on this variable, so pointers on this variable are left unchanged: char * p; //C++ TO JAVA CONVERTER TODO TASK: Pointer arithmetic is detected on this variable, so pointers on this variable are left unchanged: char * pm; String tempVar = ConsoleInput.scanfRead(); if (tempVar != null) { t = Integer.parseInt(tempVar); } for (rd = 0;rd < t;rd++) { output = 0; String tempVar2 = ConsoleInput.scanfRead(); if (tempVar2 != null) { str = tempVar2.charAt(0); } p = str; for (;p < (str + str.length());p++) { pm = str; for (;pm < (str + str.length());pm++) { if (*p == *pm) { check++; } if (check == 2) { check = 0; break; } } if (pm == str + str.length()) { System.out.printf("%c\n",*p); check = 0; output++; break; } } if (output == 0) { System.out.print("no\n"); } } return 0; } }
true
1dece260a8d90b05f48a7f4cc0f7f0db7b745692
Java
RyzhkoAliaksei/Test
/src/main/java/grsu/epam/utilitycompany/app/web/converters/StringToSpecialityConverter.java
UTF-8
642
2.296875
2
[]
no_license
package grsu.epam.utilitycompany.app.web.converters; import grsu.epam.utilitycompany.app.domain.Speciality; import grsu.epam.utilitycompany.app.service.SpecialityService; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.core.convert.converter.Converter; import org.springframework.stereotype.Component; @Component public class StringToSpecialityConverter implements Converter<String, Speciality> { @Autowired private SpecialityService specialityService; @Override public Speciality convert(String specialityId) { return specialityService.getSpecialityByID(new Long(specialityId)); } }
true
14798a0ac1efb793fd41edeea7a08713362f636c
Java
sgros/activity_flow_plugin
/TestApplications/TF-BETA-THERMATK-v5.7.1/DecompiledCode/Fernflower/src/main/java/com/google/android/exoplayer2/source/hls/playlist/_$$Lambda$lKTLOVxne0MoBOOliKH0gO2KDMM.java
UTF-8
501
1.570313
2
[]
no_license
package com.google.android.exoplayer2.source.hls.playlist; import com.google.android.exoplayer2.source.hls.playlist.-..Lambda.lKTLOVxne0MoBOOliKH0gO2KDMM; // $FF: synthetic class public final class _$$Lambda$lKTLOVxne0MoBOOliKH0gO2KDMM implements HlsPlaylistTracker.Factory { // $FF: synthetic field public static final lKTLOVxne0MoBOOliKH0gO2KDMM INSTANCE = new _$$Lambda$lKTLOVxne0MoBOOliKH0gO2KDMM(); // $FF: synthetic method private _$$Lambda$lKTLOVxne0MoBOOliKH0gO2KDMM() { } }
true
ac402bda9094cb3aaa602accafb406db749c544f
Java
nvbach91/labelmaker
/src/java/pdf/PDFMaker.java
UTF-8
855
2.578125
3
[]
no_license
/** * * */ package pdf; import com.itextpdf.text.*; import com.itextpdf.text.pdf.*; import data.Item; import java.util.List; import java.io.*; /** * * @author Nguyen Viet Bach */ public class PDFMaker { private final List<Item> itemList; private final Document doc; private final ByteArrayOutputStream baos; private final PDFDesign design; public PDFMaker(List<Item> l, ByteArrayOutputStream b, PDFDesign d) { itemList = l; doc = new Document(); baos = b; design = d; } public void makePDF() throws DocumentException, IOException { PdfWriter.getInstance(doc, baos); doc.setPageSize(PageSize.A4.rotate()); doc.setMargins(3.0f, 10.0f, 2.0f, 6.0f); //left right top bottom doc.open(); doc.add(design.createTable(itemList)); doc.close(); } }
true
b38a78be2ba741ff05b71b7df8aaf7393bab6269
Java
badion/SpringTesting
/src/main/java/com/epam/splitter/Application.java
UTF-8
685
2.140625
2
[]
no_license
package com.epam.splitter; import org.springframework.context.ApplicationContext; import org.springframework.context.support.ClassPathXmlApplicationContext; import com.epam.dao.CustomerDao; import com.epam.model.Customer; public class Application { public static void main(String[] args) { ApplicationContext context = new ClassPathXmlApplicationContext( "spring-module.xml"); CustomerDao customerDao = (CustomerDao) context.getBean("customerDAO"); // Customer customer = new Customer(5, "Ololo", 23); // customerDao.insert(customer); Customer customer2 = customerDao.findByCustomerId(2); System.out.println(customer2.getName()); customerDao.getAll(); } }
true
2e2e710a5090443a782a5a94a60227e40161a3c9
Java
AF-files/ATM
/src/sample/Main.java
UTF-8
1,900
2.4375
2
[]
no_license
package sample; import javafx.application.Application; import javafx.fxml.FXMLLoader; import javafx.scene.Parent; import javafx.scene.Scene; import javafx.scene.control.ButtonType; import javafx.scene.control.Dialog; import javafx.stage.Stage; import java.io.IOException; import java.util.Optional; public class Main extends Application { @Override public void start(Stage primaryStage) throws Exception{ Dialog<ButtonType> dialog = new Dialog<>(); //dialog.initOwner(mainPane.getScene().getWindow()); dialog.setTitle("Enter Account Details"); FXMLLoader loader = new FXMLLoader(); loader.setLocation(getClass().getResource("login.fxml")); try{ dialog.getDialogPane().setContent(loader.load()); }catch(IOException e) { System.out.print("broke"); e.printStackTrace(); } dialog.getDialogPane().getButtonTypes().add(ButtonType.OK); dialog.getDialogPane().getButtonTypes().add(ButtonType.CANCEL); Optional<ButtonType> result = dialog.showAndWait(); Datasource.getInstance().open(); if(result.isPresent()&& result.get() == ButtonType.OK) { LoginController controller = loader.getController(); if(controller.checkDetails()){ controller.setCustomer(); Parent root = FXMLLoader.load(getClass().getResource("main.fxml")); primaryStage.setTitle("ATM"); primaryStage.setScene(new Scene(root, 300, 275)); primaryStage.show(); }else{ System.out.println("Wrong"); Datasource.getInstance().close(); } } Datasource.getInstance().updateCustomer(); Datasource.getInstance().close(); } public static void main(String[] args) { launch(args); } }
true
16de9ed602d218863961448d31ba5bb1499a9502
Java
prabhatkumardubey/CompetitiveCode
/src/CombinationLock.java
UTF-8
502
3.0625
3
[]
no_license
import java.util.Scanner; public class CombinationLock { public static void main(String args[]){ Scanner sc=new Scanner(System.in); int arr[]=new int[5]; int narr[]=new int[5]; for(int i=0;i<5;i++){ arr[i]=sc.nextInt(); } int ct=0; for(int i=0;i<5;i++){ narr[i]=sc.nextInt(); if((narr[i]-arr[i])==0){ continue; } else{ int dif=Math.abs(arr[i]-narr[i]); if(dif>5){ ct+=(10-dif); } else{ ct+=dif; } } } System.out.println(ct); } }
true
e5e653683b2203e59d42af31d28d172109474569
Java
dev1piece/rx-java
/src/main/milo/ch2/MultiSubscribeAndSample.java
UTF-8
636
3.375
3
[]
no_license
package milo; import io.reactivex.Observable; public class MultiSubscribeAndSample { // p.40 public static void main(String[] args) { //Multi Subscriber Observable<Integer> ints = Observable.create(subscribe -> { System.out.println("Create"); subscribe.onNext(40); subscribe.onComplete(); }); System.out.println("# Start"); ints.subscribe( i -> System.out.println("Element A : " + i)); ints.subscribe( i -> System.out.println("Element b : " + i)); System.out.println("# Exit"); } }
true
be556342c78b06d0d52e8ebf90a02bb69628fabb
Java
trongtt/exogtn
/webui/core/src/main/java/org/exoplatform/webui/core/model/SelectOptionGroup.java
UTF-8
3,144
2.484375
2
[]
no_license
/** * Copyright (C) 2009 eXo Platform SAS. * * This 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 2.1 of * the License, or (at your option) any later version. * * This software 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 this software; if not, write to the Free * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA * 02110-1301 USA, or see the FSF site: http://www.fsf.org. */ package org.exoplatform.webui.core.model; import java.util.ArrayList; import java.util.Collection; import java.util.List; /** * Represents an optgroup in a select element * Holds a list of SelectItemOption that represent the options inside this optgroup * @author philippe * */ public class SelectOptionGroup extends SelectItem { /** * The lis of SelectItemOption */ private List<SelectOption> options_; public SelectOptionGroup(String label) { this(label, new ArrayList<SelectOption>(3)); } public SelectOptionGroup(String label, List<SelectOption> list) { super(label); if (list == null) list = new ArrayList<SelectOption>(3); options_ = list; } public List<SelectOption> getOptions() { return options_; } public void setOptions(List<SelectOption> options) { this.options_ = options; } /** * Adds a SelectItemOption to the list * @param option */ public void addOption(SelectOption option) { if (options_ == null) options_ = new ArrayList<SelectOption>(3); options_.add(option); } public void setSelectedValue(String[] values) { for (SelectOption option : options_) { option.setSelected(false); for (String value : values) { if (value.equals(option.getValue())) { option.setSelected(true); break; } } } } public void setValue(String value) { for (SelectOption option : options_) { if (option.getValue().equals(value)) option.setSelected(true); else option.setSelected(false); } } public Collection<String> getSelectedValues() { List<String> selectedValues = new ArrayList<String>(); for (int i = 0; i < options_.size(); i++) { SelectOption item = options_.get(i); if (item.isSelected()) selectedValues.add(item.getValue()); } return selectedValues; } public void reset() { if (options_ == null || options_.size() < 1) return; for (SelectOption option : options_) { option.setSelected(false); } options_.get(0).setSelected(true); } }
true