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
409a16a34e89dcc7a0ac1c0c3309941809261f5c
Java
givenm/openshift-test
/src/main/java/zw/ac/solusiuniversity/repository/AccomodationRepository.java
UTF-8
389
1.539063
2
[]
no_license
/* * To change this template, choose Tools | Templates * and open the template in the editor. */ package zw.ac.solusiuniversity.repository; import org.springframework.data.mongodb.repository.MongoRepository; import zw.ac.solusiuniversity.model.Accomodation; /** * * @author Luckbliss */ public interface AccomodationRepository extends MongoRepository<Accomodation, String>{ }
true
c90af9c7e99dfe80b75a805e33e8a8ff8e862ac4
Java
daiyinchuan/baguaz
/src/main/java/com/baguaz/handler/UrlRewriteHandler.java
UTF-8
2,360
2.125
2
[ "Apache-2.0" ]
permissive
/** * Copyright (c) 2015-2016, Yinchuan Dai 戴银川 (daiyinchuan@163.com). * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.baguaz.handler; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import com.baguaz.BgzKit; import com.baguaz.CacheFunc; import com.jfinal.handler.Handler; /** * @author Yinchuan Dai 戴银川 (daiyinchuan@163.com) * */ public class UrlRewriteHandler extends Handler{ private String ak; private String iak; public UrlRewriteHandler(String ak,String iak){ this.ak=ak; this.iak=iak; } /* (non-Javadoc) * @see com.jfinal.handler.Handler#handle(java.lang.String, javax.servlet.http.HttpServletRequest, javax.servlet.http.HttpServletResponse, boolean[]) */ @Override public void handle( String target, HttpServletRequest request, HttpServletResponse response, boolean[] isHandled){ int index = target.lastIndexOf(";JSESSIONID"); target = index==-1?target:target.substring(0, index); if(target.startsWith("/statics/") || target.startsWith("/uploadfile/") || target.equals("/favicon.ico")){ }else if(BgzKit.regMatch("/^/$/",target)){ int index_ishtml=(int)CacheFunc.getSiteSettings().get("index_ishtml"); if(index_ishtml==1){ target="/index.html"; }else{ target="/content/index"; } }else if(BgzKit.regMatch("/^/admin/?$/",target)){ target="/admin/publicIndex"; }else if(BgzKit.regMatch("/^/("+ak+")(/.*)?/",target)){ }else if(BgzKit.regMatch("/^/("+iak+")$/",target)){ }else if(BgzKit.regMatch("/^/.*.html$/",target)){ }else if(BgzKit.regMatch("/^/.*/?$/",target)){ target+="index.html"; } nextHandler.handle(target, request, response, isHandled); } }
true
032b03c9fe0886795c3ef131a93279bf4d1a8e6d
Java
javaslin/my_LeetCode
/src/leetcode/SearchRange.java
UTF-8
1,188
3.90625
4
[]
no_license
package leetcode; /* 34. 在排序数组中查找元素的第一个和最后一个位置 给定一个按照升序排列的整数数组 nums,和一个目标值 target。找出给定目标值在数组中的开始位置和结束位置。 你的算法时间复杂度必须是 O(log n) 级别。 如果数组中不存在目标值,返回 [-1, -1]。 示例 1: 输入: nums = [5,7,7,8,8,10], target = 8 输出: [3,4] 示例 2: 输入: nums = [5,7,7,8,8,10], target = 6 输出: [-1,-1] */ public class SearchRange { public int[] searchRange(int[] nums, int target) { int first = binarySearch(nums, target); int last = binarySearch(nums, target + 1) - 1; if (first == nums.length || nums[first] != target) { return new int[]{-1, -1}; } else { return new int[]{first, Math.max(first, last)}; } } private int binarySearch(int[] nums, int target) { int l = 0, h = nums.length; while (l < h) { int mid = l + (h - l) / 2; if (nums[mid] >= target) { h = mid; } else { l = mid + 1; } } return l; } }
true
c5a7b859ebeec9c1cfeb030e2e08e35f2afded0f
Java
devasainathan/deva
/project/src/main/java/com/deva/project/model.java
UTF-8
501
2.328125
2
[]
no_license
package com.deva.project; public class model { int id; String name; String desc; public int getId() { return id; } public void setId(int id) { this.id = id; } public String getName() { return name; } public void setName(String name) { this.name = name; } public String getDesc() { return desc; } @Override public String toString() { return "model [id=" + id + ", name=" + name + ", desc=" + desc + "]"; } public void setDesc(String desc) { this.desc = desc; } }
true
ca64a3ac9719362e5b043e1a7a25e2162c13ddeb
Java
developercyrus/app-snippets
/app-snippets/src/main/java/snippets/framework/di/spring/why/decoupled/interface1/HelloWorld.java
UTF-8
346
2.34375
2
[]
no_license
package snippets.framework.di.spring.why.decoupled.interface1; public class HelloWorld { public static void main(String[] args) { IMessageSource source = new SimpleMessageSource("Hello World"); IMessageDestination destination = new StdoutMessageDestination(); destination.write(source.getMessage()); } }
true
8f352968201abba1e0d266bbf8be3ff69989d095
Java
wy96f/lb-rpc
/src/main/java/cn/v5/lbrpc/common/server/AbstractServerFactory.java
UTF-8
1,777
2.25
2
[]
no_license
package cn.v5.lbrpc.common.server; import cn.v5.lbrpc.common.client.core.loadbalancer.ServiceRegistration; import cn.v5.lbrpc.http.server.ContainerServerFactory; import cn.v5.lbrpc.protobuf.server.ProtobufRpcServerFactory; import cn.v5.lbrpc.thrift.server.ThriftRpcServerFactory; import java.net.InetAddress; import java.util.List; /** * Created by yangwei on 15-6-5. */ // Factory Method public abstract class AbstractServerFactory { public static final String TOMCAT_CONTAINER = "tomcat"; public static final String PROTOBUF_RPC = "protobuf"; public static final String THRIFT_RPC = "thrift"; protected ServiceRegistration registration; protected InetAddress address; protected int port = -1; public static AbstractServerFactory newFactory(String factoryName) { if (factoryName.compareTo(TOMCAT_CONTAINER) == 0) { return new ContainerServerFactory(factoryName); } else if (factoryName.compareTo(PROTOBUF_RPC) == 0) { return new ProtobufRpcServerFactory(); } else if (factoryName.compareTo(THRIFT_RPC) == 0) { return new ThriftRpcServerFactory(); } else { throw new IllegalArgumentException("factory " + factoryName + " invalid"); } } public AbstractServerFactory withRegistration(ServiceRegistration registration) { this.registration = registration; return this; } public AbstractServerFactory withAddress(InetAddress address) { this.address = address; return this; } public AbstractServerFactory withPort(int port) { this.port = port; return this; } public abstract LifeCycleServer createServer(List<Object> interceptors); public abstract int getDefaultPort(); }
true
339dcfe29a4b4a848053264b55f670feb8c96436
Java
dawist-o/SpringBootApplication
/src/main/java/com/dawist_o/service/BookService/BookService.java
UTF-8
2,040
2.609375
3
[]
no_license
package com.dawist_o.service.BookService; import com.dawist_o.dao.AuthorDao.AuthorDao; import com.dawist_o.dao.BookDao.BookDao; import com.dawist_o.model.Author; import com.dawist_o.model.Book; import lombok.extern.slf4j.Slf4j; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; import java.util.List; @Slf4j @Service public class BookService implements BookServiceInterface { private final BookDao bookDao; private final AuthorDao authorDao; @Autowired public BookService(BookDao bookDao, AuthorDao authorDao) { this.bookDao = bookDao; this.authorDao = authorDao; } @Override public List<Author> getAllAuthors() { log.info("In BookService method getAllAuthors: "); return authorDao.findAll(); } @Override public Author getAuthorByNameOrCreateNew(String author) { Author authorByName = authorDao.getByName(author); log.info("In BookService method getAuthorByNameOrCreateNew: " + author); if (authorByName == null) { authorByName = new Author(author.trim(), ""); authorDao.save(authorByName); log.info("In BookService method getAuthorByNameOrCreateNew new Author with name: " + author + " created"); } return authorByName; } @Override public Book getBookById(Long id) { log.info("In BookService method getByID: " + id); return bookDao.getById(id); } @Override public void save(Book book) { log.info("In BookService method save: " + book); bookDao.save(book); } @Override public void deleteBookById(Long id) { log.info("In BookService method delete: " + id); bookDao.deleteById(id); } @Override public List<Book> getAllBooks() { log.info("In BookService method getAll"); return bookDao.findAll(); } @Override public boolean existsBookById(Long id) { return bookDao.existsById(id); } }
true
e0355c55e68dad1bbe051c890a6764d268838874
Java
GargEvil/tourismassociation
/src/main/java/com/tourism/tourismassociation/exceptions/AppExceptionHandler.java
UTF-8
2,053
2.15625
2
[]
no_license
package com.tourism.tourismassociation.exceptions; import com.tourism.tourismassociation.ui.response.ErrorMessage; import org.springframework.http.HttpHeaders; import org.springframework.http.HttpStatus; import org.springframework.http.ResponseEntity; import org.springframework.web.bind.annotation.ControllerAdvice; import org.springframework.web.bind.annotation.ExceptionHandler; import org.springframework.web.context.request.WebRequest; import java.util.Date; @ControllerAdvice public class AppExceptionHandler { // I made everything return status 500, should find a way to get status as a parameter @ExceptionHandler(value = {UserServiceException.class}) public ResponseEntity<Object> handleUserServiceException(UserServiceException ex, WebRequest request){ ErrorMessage errorMessage = new ErrorMessage(new Date(), ex.getMessage()); return new ResponseEntity<>(errorMessage, new HttpHeaders(), HttpStatus.INTERNAL_SERVER_ERROR); } @ExceptionHandler(value = {LandmarkServiceException.class}) public ResponseEntity<Object> handleLandmarkServiceException(LandmarkServiceException ex, WebRequest request){ ErrorMessage errorMessage = new ErrorMessage(new Date(), ex.getMessage()); return new ResponseEntity<>(errorMessage, new HttpHeaders(), HttpStatus.INTERNAL_SERVER_ERROR); } @ExceptionHandler(value = {RatingServiceException.class}) public ResponseEntity<Object> handleRatingServiceException(RatingServiceException ex, WebRequest request){ ErrorMessage errorMessage = new ErrorMessage(new Date(), ex.getMessage()); return new ResponseEntity<>(errorMessage, new HttpHeaders(), HttpStatus.INTERNAL_SERVER_ERROR); } @ExceptionHandler(value = {Exception.class}) public ResponseEntity<Object> handleOtherException(Exception ex, WebRequest request){ ErrorMessage errorMessage = new ErrorMessage(new Date(), ex.getMessage()); return new ResponseEntity<>(errorMessage, new HttpHeaders(), HttpStatus.INTERNAL_SERVER_ERROR); } }
true
b00c87e31af476e0737b5111ca09f45141f92f6b
Java
alexandrenilton/erp-wildfly
/src/main/java/com/casa/erp/entities/DeliveryOrder_.java
UTF-8
1,404
1.828125
2
[]
no_license
package com.casa.erp.entities; import java.util.Date; import javax.annotation.Generated; import javax.persistence.metamodel.ListAttribute; import javax.persistence.metamodel.SingularAttribute; import javax.persistence.metamodel.StaticMetamodel; @Generated(value="Dali", date="2017-11-05T00:42:32.332-0200") @StaticMetamodel(DeliveryOrder.class) public class DeliveryOrder_ extends BaseEntity_ { public static volatile SingularAttribute<DeliveryOrder, Date> date; public static volatile SingularAttribute<DeliveryOrder, String> origin; public static volatile SingularAttribute<DeliveryOrder, String> name; public static volatile SingularAttribute<DeliveryOrder, String> deliveryMethod; public static volatile SingularAttribute<DeliveryOrder, String> state; public static volatile SingularAttribute<DeliveryOrder, String> type; public static volatile SingularAttribute<DeliveryOrder, Boolean> active; public static volatile ListAttribute<DeliveryOrder, DeliveryOrderLine> deliveryOrderLines; public static volatile SingularAttribute<DeliveryOrder, Partner> partner; public static volatile SingularAttribute<DeliveryOrder, PurchaseOrder> purchaseOrder; public static volatile SingularAttribute<DeliveryOrder, SaleOrder> saleOrder; public static volatile SingularAttribute<DeliveryOrder, DeliveryOrder> backOrder; public static volatile ListAttribute<DeliveryOrder, DeliveryOrder> children; }
true
791826c9ae97c3962ffce0037e8fa2696655ce40
Java
yyj7952/wincom
/src/main/java/kr/co/wincom/imcs/api/getNSVODRank/GetNSVODRankResponseVO.java
UTF-8
7,441
2.03125
2
[]
no_license
package kr.co.wincom.imcs.api.getNSVODRank; import java.io.Serializable; import kr.co.wincom.imcs.common.ImcsConstants; import kr.co.wincom.imcs.common.util.StringUtil; import kr.co.wincom.imcs.common.vo.NoSqlLoggingVO; @SuppressWarnings("serial") public class GetNSVODRankResponseVO extends NoSqlLoggingVO implements Serializable { /******************************************************************** * GetNSVODRank API 전문 칼럼(순서 일치) ********************************************************************/ private String seriesYn = ""; // 시리즈 여부 private String relationYn = ""; // 동일장르 여부 private String recommendYn = ""; // 전체(동일장르제외) 여부 private String catId = ""; // 카테고리 ID private String catName = ""; // 카테고리명 private String contsId = ""; // 컨텐츠 ID private String contsName = ""; // 컨텐츠명 private String genreName = ""; // 장르명 private String rankNo = ""; // 순위정보 private String imgUrl = ""; // 포스터 URL private String imgFileName = ""; // 포스터명 private String runtime = ""; // 상영시간 private String prInfo = ""; // 나이제한 private String is51ch = ""; // 5.1ch private String isHd = ""; // HD 여부 private String albumId = ""; // 앨범 ID private String point = ""; // 평점 private String cnt = ""; private String wideImageUrl = ""; // 포스터 URL private String realHDYn = ""; // Real HD 여부 private String suggestedPrice = ""; // 제공 가격 private String serCatId = ""; // 시리즈 카테고리ID (연동규격서 상에는 없는데 소스에는 있음) /******************************************************************** * 추가 사용 파라미터 ********************************************************************/ private int iRankNo; private String audioType = ""; private String hdcontent = ""; private int iOrdnum; private int rownum; @Override public String toString(){ StringBuffer sb = new StringBuffer(); sb.append(StringUtil.nullToSpace(this.seriesYn)).append(ImcsConstants.COLSEP); sb.append(StringUtil.nullToSpace(this.relationYn)).append(ImcsConstants.COLSEP); sb.append(StringUtil.nullToSpace(this.recommendYn)).append(ImcsConstants.COLSEP); sb.append(StringUtil.nullToSpace(this.catId)).append(ImcsConstants.COLSEP); sb.append(StringUtil.nullToSpace(this.catName)).append(ImcsConstants.COLSEP); sb.append(StringUtil.nullToSpace(this.contsId)).append(ImcsConstants.COLSEP); sb.append(StringUtil.nullToSpace(this.contsName)).append(ImcsConstants.COLSEP); sb.append(StringUtil.nullToSpace(this.genreName)).append(ImcsConstants.COLSEP); sb.append(StringUtil.nullToSpace(this.rankNo)).append(ImcsConstants.COLSEP); sb.append(StringUtil.nullToSpace(this.imgUrl)).append(ImcsConstants.COLSEP); sb.append(StringUtil.nullToSpace(this.imgFileName)).append(ImcsConstants.COLSEP); sb.append(StringUtil.nullToSpace(this.runtime)).append(ImcsConstants.COLSEP); sb.append(StringUtil.nullToSpace(this.prInfo)).append(ImcsConstants.COLSEP); sb.append(StringUtil.nullToSpace(this.is51ch)).append(ImcsConstants.COLSEP); sb.append(StringUtil.nullToSpace(this.isHd)).append(ImcsConstants.COLSEP); sb.append(StringUtil.nullToSpace(this.albumId)).append(ImcsConstants.COLSEP); sb.append(StringUtil.nullToSpace(this.point)).append(ImcsConstants.COLSEP); sb.append(StringUtil.nullToSpace(this.cnt)).append(ImcsConstants.COLSEP); sb.append(StringUtil.nullToSpace(this.wideImageUrl)).append(ImcsConstants.COLSEP); sb.append(StringUtil.nullToSpace(this.realHDYn)).append(ImcsConstants.COLSEP); //sb.append(StringUtil.nullToSpace(this.imgFileName)).append(ImcsConstants.COLSEP); sb.append(StringUtil.nullToSpace(this.suggestedPrice)).append(ImcsConstants.COLSEP); sb.append(StringUtil.nullToSpace(this.serCatId)).append(ImcsConstants.COLSEP); return sb.toString(); } public String getSeriesYn() { return seriesYn; } public void setSeriesYn(String seriesYn) { this.seriesYn = seriesYn; } public String getRelationYn() { return relationYn; } public void setRelationYn(String relationYn) { this.relationYn = relationYn; } public String getRecommendYn() { return recommendYn; } public void setRecommendYn(String recommendYn) { this.recommendYn = recommendYn; } public String getCatId() { return catId; } public void setCatId(String catId) { this.catId = catId; } public String getCatName() { return catName; } public void setCatName(String catName) { this.catName = catName; } public String getContsId() { return contsId; } public void setContsId(String contsId) { this.contsId = contsId; } public String getContsName() { return contsName; } public void setContsName(String contsName) { this.contsName = contsName; } public String getRuntime() { return runtime; } public void setRuntime(String runtime) { this.runtime = runtime; } public String getImgUrl() { return imgUrl; } public void setImgUrl(String imgUrl) { this.imgUrl = imgUrl; } public String getImgFileName() { return imgFileName; } public void setImgFileName(String imgFileName) { this.imgFileName = imgFileName; } public String getGenreName() { return genreName; } public void setGenreName(String genreName) { this.genreName = genreName; } public String getPrInfo() { return prInfo; } public void setPrInfo(String prInfo) { this.prInfo = prInfo; } public String getIs51ch() { return is51ch; } public void setIs51ch(String is51ch) { this.is51ch = is51ch; } public String getIsHd() { return isHd; } public void setIsHd(String isHd) { this.isHd = isHd; } public String getAlbumId() { return albumId; } public void setAlbumId(String albumId) { this.albumId = albumId; } public String getWideImageUrl() { return wideImageUrl; } public void setWideImageUrl(String wideImageUrl) { this.wideImageUrl = wideImageUrl; } public String getPoint() { return point; } public void setPoint(String point) { this.point = point; } public String getCnt() { return cnt; } public void setCnt(String cnt) { this.cnt = cnt; } public String getRealHDYn() { return realHDYn; } public void setRealHDYn(String realHDYn) { this.realHDYn = realHDYn; } public String getSuggestedPrice() { return suggestedPrice; } public void setSuggestedPrice(String suggestedPrice) { this.suggestedPrice = suggestedPrice; } public String getSerCatId() { return serCatId; } public void setSerCatId(String serCatId) { this.serCatId = serCatId; } public int getiRankNo() { return iRankNo; } public void setiRankNo(int iRankNo) { this.iRankNo = iRankNo; } public String getAudioType() { return audioType; } public void setAudioType(String audioType) { this.audioType = audioType; } public String getHdcontent() { return hdcontent; } public void setHdcontent(String hdcontent) { this.hdcontent = hdcontent; } public int getiOrdnum() { return iOrdnum; } public void setiOrdnum(int iOrdnum) { this.iOrdnum = iOrdnum; } public int getRownum() { return rownum; } public void setRownum(int rownum) { this.rownum = rownum; } public String getRankNo() { return rankNo; } public void setRankNo(String rankNo) { this.rankNo = rankNo; } }
true
ff01d116642a37233cd791897327f7acabcfaeac
Java
pickthreeusername/demo-cloud
/demo-spring-cloud/demo-spring-cloud-web-admin-feign/src/main/java/com/cyc/demo/spring/cloud/web/admin/feign/controller/IndexController.java
UTF-8
642
1.976563
2
[]
no_license
package com.cyc.demo.spring.cloud.web.admin.feign.controller; import com.cyc.demo.spring.cloud.web.admin.feign.service.AdminService; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestMethod; import org.springframework.web.bind.annotation.RestController; @RestController public class IndexController { @Autowired private AdminService adminService; @RequestMapping(value = "test", method = RequestMethod.GET) public String test(String message) { return adminService.aaa(message); } }
true
3f4f340301ecee6daa2ba3565f163f2c193dd695
Java
jongtix/JAVA_jongtix
/Ch02_OP/src/p01/operations/OperExample7.java
UTF-8
1,412
4.125
4
[]
no_license
package p01.operations; /** * 복합대입연산자 * - 연산과 대입을 동시에 처리하는 연산자 * - a +=b, a -= b, a *= b, a /= b, a %= b 등. * - 순서는 왼쪽의 연산처리 후 대입순 */ public class OperExample7 extends Object { //모든 클래스는 최상위클래스인 Object클래스를 상속받아 생성 //생성자(default생성자) //Java는 반드시 생성자가 있어야 객체를 생성할 수 있다. //모든 클래스는 생성자가 존재하는데 개발자가 생성자를 표시하지 않으면 //컴파일러가 컴파일 시 매개변소도 없고, 실행 내용도 없는 default 생성자를 추가하여 컴파일한다. OperExample7(){} public static void main(String[] args) { //반복문 int sum = 0; //로컬변수 int temp = 0; //임시저장 변수 for(int i = 1; i <= 10; i++) { //sum변수의 값과 i의 값을 더한 결과값을 다시 sum에 대입하는 대입문 // sum = sum + i; //한번씩 반복하면서 합계(sum)에 값을 추가하는 명령문 temp = sum + i; //sum 값과 i의 값을 합한 결과를 temp에 저장 sum = temp; //저장한 temp의 값을 다시 sum에 저장 } System.out.println("합계는 " + sum); for(int i = 1; i <= 10; i++) { sum += i; //sum 값에 i의 값을합한 결과를 다시 sum에 대입하는 복합대입문 } System.out.println("합계는 " + sum); } }
true
6c7d9b0a78cfc51798e94b256a22fdfbbca36df7
Java
AndreyGomonov/Melarossa
/HomeWork3/src/Person.java
UTF-8
722
3.46875
3
[]
no_license
import java.math.BigDecimal; public class Person { private String fullName; private long age; public Person(String fullName, long age) { this.fullName = fullName; this.age = age; } public Person() { } public void talk() { System.out.println(this.fullName + " Hello guys!"); } public void move() { System.out.println(this.fullName + " going for a walk with my cat"); } public String getFullName() { return fullName; } public long getAge() { return age; } public void setFullName(String fullName) { this.fullName = fullName; } public void setAge(long age) { this.age = age; } }
true
093dc0f08b2c7ca20c88dfe094d96cd4f26c537d
Java
alexandra21p/ToyLanguageInterpreter
/src/domain/statements/AssignStmt.java
UTF-8
1,524
2.890625
3
[]
no_license
package domain.statements; import domain.PrgState; import domain.expressions.Exp; import utils.IDictionaryADT; import utils.IHeapADT; import utils.IListADT; import utils.IStackADT; import utils.exceptions.DivisionByZeroExcep; import utils.exceptions.InvalidInputException; import utils.exceptions.VariableException; import java.io.Serializable; /** * Created by Alexandra on 02/11/2015. */ public class AssignStmt implements IStmt, Serializable { String key; // variable name Exp expr; public AssignStmt(String k, Exp e) { key = k; expr = e; } public PrgState execute(PrgState state) throws VariableException, InvalidInputException, DivisionByZeroExcep { IStackADT<IStmt> stk = state.getExeStack(); IDictionaryADT<String, Integer> symTbl = state.getSymTable(); IListADT<String> out = state.getOut(); IHeapADT<Integer, Integer> hp = state.getHeap(); String key = getKey(); Exp exp = getExpr(); int val = 0; val = exp.eval(symTbl, hp); if (symTbl.isDefined(key)) { symTbl.updateValue(key, val); } else { symTbl.add(key, val); } return null; } // getters for id and expression public String getKey() { return key; } public Exp getExpr() { return expr; } /* * method that prints the statement into a string */ public String toString(){ return key + " = " + expr.toString(); } }
true
5d400cc8753784d1364db53a59c9cd9e6ca78f49
Java
sehor/my-spring-boot
/src/main/java/com/example/demo/service/AyUserServiceImpl.java
UTF-8
1,748
2.265625
2
[]
no_license
package com.example.demo.service; import java.util.List; import javax.annotation.Resource; import org.springframework.retry.annotation.Backoff; import org.springframework.retry.annotation.Retryable; import org.springframework.stereotype.Service; import org.springframework.transaction.annotation.Transactional; import com.example.demo.data.JpaAyUserRepository; import com.example.demo.error.BusinessException; import com.example.demo.model.AyUser; @Service public class AyUserServiceImpl implements AyUserService{ @Resource private JpaAyUserRepository repository; @Override public List<AyUser> findByKey(String keyword) { // TODO Auto-generated method stub String key="%"+keyword+"%"; return repository.findByIdLikeOrNameLikeOrPasswordLike(key, key, key); } @Override public List<AyUser> findAll() { // TODO Auto-generated method stub return repository.findAll(); } @Transactional @Override public AyUser save(AyUser user) { // TODO Auto-generated method stub return repository.save(user); } @Override public void delete(String id) { // TODO Auto-generated method stub repository.deleteById(id); } @Override @Retryable(value= {BusinessException.class},maxAttempts=5,backoff=@Backoff(delay=5000,multiplier=2)) public AyUser findByNameAndPassoword(String name, String password) { // TODO Auto-generated method stub System.out.println("retry failed!"); throw new BusinessException("access data failed! "); } @Override public AyUser findByUsername(String username) { // TODO Auto-generated method stub List<AyUser> users=repository.findByName(username); return users.isEmpty()?null:users.get(0); } }
true
1ac2f84b13ea3419929a0984b23dbda3bbc5fe8a
Java
Ckefy/Java-Paradigms
/Programming/Paradigmes/HW3/src/modes/IntegerMode.java
UTF-8
3,660
3.328125
3
[]
no_license
package modes; import expression.exceptions.IllegalOperationException; import expression.exceptions.OverflowException; public class IntegerMode implements Mode<Integer> { private boolean needCheck; public IntegerMode(boolean check) { needCheck = check; } public Integer getNumber(int number) { return number; } public Integer add(Integer first, Integer second) throws OverflowException { if (needCheck) { checkAdd(first, second); } return first + second; } public Integer sub(Integer first, Integer second) throws OverflowException { if (needCheck) { checkSub(first, second); } return first - second; } public Integer mul(Integer first, Integer second) throws OverflowException { if (needCheck) { checkMul(first, second); } return first * second; } public Integer div(Integer first, Integer second) throws IllegalOperationException, OverflowException { if (second == 0) { throw new IllegalOperationException("Div by zero"); } if (needCheck) { checkDiv(first, second); } return first / second; } public Integer mod(Integer first, Integer second) throws IllegalOperationException { if (second == 0) { throw new IllegalOperationException("Div by zero"); } return first % second; } public Integer not(Integer argument) throws OverflowException { if (needCheck) { checkNot(argument); } return -argument; } public Integer abs(Integer argument) throws OverflowException { if (needCheck) { checkAbs(argument); } return Math.abs(argument); } private void checkAdd(Integer first, Integer second) throws OverflowException { if (first > 0 && Integer.MAX_VALUE - first < second) { throw new OverflowException(); } if (first < 0 && Integer.MIN_VALUE - first > second) { throw new OverflowException(); } } private void checkSub(Integer first, Integer second) throws OverflowException { if (first >= 0 && second < 0 && first - Integer.MAX_VALUE > second) { throw new OverflowException(); } if (first <= 0 && second > 0 && Integer.MIN_VALUE - first > -second) { throw new OverflowException(); } } private void checkMul(Integer first, Integer second) throws OverflowException { if (first > 0 && second > 0 && Integer.MAX_VALUE / first < second) { throw new OverflowException(); } if (first > 0 && second < 0 && Integer.MIN_VALUE / first > second) { throw new OverflowException(); } if (first < 0 && second > 0 && Integer.MIN_VALUE / second > first) { throw new OverflowException(); } if (first < 0 && second < 0 && Integer.MAX_VALUE / first > second) { throw new OverflowException(); } } private void checkDiv(Integer first, Integer second) throws OverflowException { if (first == Integer.MIN_VALUE && second == -1) { throw new OverflowException(); } } private void checkNot(Integer argument) throws OverflowException { if (argument == Integer.MIN_VALUE) { throw new OverflowException(); } } private void checkAbs(Integer argument) throws OverflowException { if (argument == Integer.MIN_VALUE) { throw new OverflowException(); } } }
true
8d40b783bfa4c3e709d7c03ba846f69e26605152
Java
akashkg123/FULL-CREATIVE---JAVA
/Till_14_JUN/src/Trail/Abstract_Example.java
UTF-8
731
3.53125
4
[]
no_license
package Trail; abstract class Abs { abstract public void meth(); abstract public void meth2(); public void general_Method() { System.out.println("I am GENERAL METHOD"); } } class A_Abstract extends Abs { public void meth() { System.out.println("I am class A_Abstract overrided method!"); super.general_Method(); } public void meth2() { } } class B_Abstract extends Abs { public void meth() { System.out.println("I am class A_Abstract overrided method!"); super.general_Method(); } public void meth2() { } } public class Abstract_Example { public static void main(String[] args) { Abs ob; ob = new B_Abstract(); ob.meth(); } }
true
7329ae28552842a780397acbed2328c3b2570d44
Java
abq-parks/services
/src/main/java/edu/cnm/deepdive/abqparksservice/controller/ReviewController.java
UTF-8
3,270
2.203125
2
[ "Apache-2.0" ]
permissive
package edu.cnm.deepdive.abqparksservice.controller; import edu.cnm.deepdive.abqparksservice.model.dao.ParkRepository; import edu.cnm.deepdive.abqparksservice.model.dao.ReviewRepository; import edu.cnm.deepdive.abqparksservice.model.dao.UserRepository; import edu.cnm.deepdive.abqparksservice.model.entity.Review; import java.util.NoSuchElementException; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.hateoas.ExposesResourceFor; import org.springframework.http.HttpStatus; import org.springframework.http.MediaType; import org.springframework.http.ResponseEntity; import org.springframework.web.bind.annotation.ExceptionHandler; import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.PathVariable; import org.springframework.web.bind.annotation.PostMapping; import org.springframework.web.bind.annotation.RequestBody; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.ResponseStatus; import org.springframework.web.bind.annotation.RestController; /** * This is the review REST controller. */ @RestController @ExposesResourceFor(Review.class) @RequestMapping("/reviews") public class ReviewController { private ReviewRepository reviewRepository; private ParkRepository parkRepository; private UserRepository userRepository; /** * Auto wires ReviewRepository, ParkRepository, and UserRepository. * @param reviewRepository ReviewRepository * @param parkRepository ParkRepository * @param userRepository UserRepository */ @Autowired public ReviewController(ReviewRepository reviewRepository, ParkRepository parkRepository, UserRepository userRepository) { this.reviewRepository = reviewRepository; this.parkRepository = parkRepository; this.userRepository = userRepository; } /** * Returns all reviews for requested park. * @param parkId id of the park. * @return all reviews for requested park. */ @GetMapping(value ="{parkId}", produces = MediaType.APPLICATION_JSON_VALUE) public Iterable<Review> getReviews(@PathVariable("parkId") long parkId) { return reviewRepository.findAllByPark_IdOrderByReviewDesc(parkId); } /** * Post a review for selected park. * @param args contains the park ID and user ID in a common separated string that parses into Long[]. * @param review string containing text of the review. * @return the URI and review body. */ @PostMapping(value = "{args}", consumes = MediaType.APPLICATION_JSON_VALUE) public ResponseEntity<Review> post(@PathVariable("args") Long[] args, @RequestBody Review review) { return parkRepository.findById(args[0]).map( park -> { review.setPark(park); return userRepository.findById(args[1]).map( user -> { review.setUser(user); reviewRepository.save(review); return ResponseEntity.created(review.getHref()).body(review); } ).get(); } ).get(); } /** * Error handling. */ @ResponseStatus(value = HttpStatus.NOT_FOUND, reason = "Resource not found") @ExceptionHandler(NoSuchElementException.class) public void notFound() { } }
true
accb3aee584d88e646d22873231dfc6c728d2c10
Java
Alexandra11801/LifeCare-Spring
/src/main/java/ru/itis/lifecarespring/aop/MethodAspect.java
UTF-8
1,085
2.40625
2
[]
no_license
package ru.itis.lifecarespring.aop; import org.aspectj.lang.JoinPoint; import org.aspectj.lang.annotation.Before; import org.aspectj.lang.annotation.Pointcut; import org.aspectj.lang.reflect.MethodSignature; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import java.util.Arrays; import java.util.stream.Collectors; import org.aspectj.lang.annotation.Aspect; import org.springframework.stereotype.Component; @Aspect @Component public class MethodAspect { private Logger logger = LoggerFactory.getLogger(this.getClass()); @Pointcut("execution(public * ru.itis.lifecarespring.services..*.*(..))") public void callAtServicesPublic(){} @Before("callAtServicesPublic()") public void beforeCallAt(JoinPoint point){ String targetClass = point.getTarget().getClass().getName(); String method = ((MethodSignature)(point.getSignature())).getMethod().getName(); String args = Arrays.stream(point.getArgs()).map(arg -> arg.toString()).collect(Collectors.joining(", ")); logger.info("Class: " + targetClass + "; Method: " + method + "; Args: {" + args + "}"); } }
true
ca7a582f70f008c661ca543f905c2c8b708cbc52
Java
wonderfulo/template_project_jpa
/src/main/java/com/cxy/entity/TmSysUser.java
UTF-8
1,513
2.03125
2
[]
no_license
package com.cxy.entity; import lombok.Data; import javax.persistence.Entity; import javax.persistence.GeneratedValue; import javax.persistence.GenerationType; import javax.persistence.Id; import java.time.LocalDate; /** * <p> * * </p> * * @author 陈翔宇 * @since 2020-12-10 */ @Data @Entity(name = "tm_sys_user") public class TmSysUser extends BaseEntity { private static final long serialVersionUID = 1L; /** * 系统用户Id */ @Id @GeneratedValue(strategy = GenerationType.IDENTITY) private Long sysUserId; /** * 系统用户编码 */ private String userCode; /** * 登录名 */ private String loginName; /** * 密码 */ private String password; /** * 名称 */ private String name; /** * 电话号码 */ private String tel; /** * 用户状态。1:注册,2:激活,3:离职申请,4:离职,5:入店批准,6:在职(正常员工状态信息) */ private String userStauts; /** * 邮箱 */ private String email; /** * QQ */ private Long qq; /** * 微信 */ private String wx; /** * 头像 */ private String headPic; /** * 昵称 */ private String nickName; /** * 生日 */ private LocalDate birthday; /** * 0或空是第一次登陆,1不是第一次登陆 */ private String checkFirstLogin; }
true
675b76b1b4dfb75791f250a79b3c80696928a6f5
Java
hmtriit/FirebaseWithAmazonSNS
/app/src/main/java/com/licon/gcmasnssample/activity/MainActivity.java
UTF-8
998
2.15625
2
[ "MIT" ]
permissive
package com.licon.gcmasnssample.activity; import android.content.SharedPreferences; import android.os.Bundle; import android.support.v7.app.AppCompatActivity; import android.util.Log; import com.licon.gcmasnssample.R; public class MainActivity extends AppCompatActivity { private static final String TAG = MainActivity.class.getSimpleName(); public static final String KEY_PREF_REG_ID = "KEY_PREF_REG_ID"; public static final String REG_ID = "REG_ID"; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); //FirebaseMessaging.getInstance().subscribeToTopic("global"); // random name logFirebaseRegId(); } private void logFirebaseRegId() { SharedPreferences pref = getApplicationContext().getSharedPreferences(KEY_PREF_REG_ID, 0); String regId = pref.getString(REG_ID, null); Log.e(TAG, "Firebase reg id: " + regId); } }
true
b87c6ae379356f85111189603e6a93cd4b514860
Java
renancav/JavaFullStackTraining
/src/com/example/app/CdCatalogue.java
UTF-8
2,609
3.296875
3
[]
no_license
package com.example.app; import java.util.LinkedList; import java.util.LinkedList; import java.util.List; public class CdCatalogue { private LinkedList<Cd> allCd = null; public CdCatalogue() { this.allCd = new LinkedList<Cd>(); } public void populateCdCatologue() { Cd cd1 = new CdFree("IntelliJ", "Cd on IntelliJ"); Cd cd2 = new CdPaid("Windows 10", "Windows 10 CD", 5); Cd cd3 = new CdCorporate("Linux", "Ubuntu", 10, 50); List<Cd> cds = new LinkedList<>(); cds.add(cd1); cds.add(cd2); cds.add(cd3); createCourse((LinkedList<Cd>) cds); } public double getPrice() { double cost = 0; if(!allCd.isEmpty()) { for(Cd c: allCd) { cost += c.getPrice(); } } return cost; } void printVal() { System.out.println("List of all Cds: "); if(!allCd.isEmpty()) { for(Cd c: allCd) { System.out.println(c.toString() +" $"+ c.getPrice()); } } } // method to create new course public void createCourse( LinkedList<Cd> cds) { for(Cd c: cds) allCd.add(c); } // method to delete courses public void deleteCourse(String deleteval) { List<Cd> deleteCourses = new LinkedList<>(); deleteCourses = search( deleteval); for(Cd c :deleteCourses) { allCd.remove(c); } } // method to search through all courses public List<Cd> search( String searchVal) { List<Cd> courseFound = new LinkedList<>(); if(!(allCd.size() ==0) || !(searchVal ==null)) { for (Cd cd : allCd) { if (cd.getDesc().contains(searchVal) || cd.getName().contains(searchVal)) { courseFound.add(cd); } } } return courseFound; } public void printArrayName(Course[] courseArr) { for (int i = 0; i < courseArr.length; i++) { // System.out.println("id: " + courseArr[i].getId() + "\nName: " + courseArr[i].getName() + "\nDesc: " + courseArr[i].getDesc() + "\n"); System.out.println("Name: " + courseArr[i].getName()); } } public void printArray(Course[] courseArr) { for (int i = 0; i < courseArr.length; i++) { System.out.println("id: " + courseArr[i].getId() + "\nName: " + courseArr[i].getName() + "\nDesc: " + courseArr[i].getDesc() + "\n"); } } }
true
cf4cb180ce3d7a3a23ee8923fa08ae03d5e92c00
Java
moutainhigh/chdHRP
/src/com/chd/hrp/hr/dao/sysstruc/HrFiiedTabStrucMapper.java
UTF-8
1,578
1.875
2
[]
no_license
/** * @Description: * @Copyright: Copyright (c) 2015-9-16 下午9:54:34 * @Company: 杭州亦童科技有限公司 * @网站:www.s-chd.com */ package com.chd.hrp.hr.dao.sysstruc; import java.util.List; import java.util.Map; import org.apache.ibatis.annotations.Param; import org.springframework.dao.DataAccessException; import com.chd.base.SqlMapper; import com.chd.hrp.hr.entity.sysstruc.HrColStruc; import com.chd.hrp.hr.entity.sysstruc.HrFiiedData; import com.chd.hrp.hr.entity.sysstruc.HrFiiedTabStruc; /** * * @Description: * 代码结构表 * @Table: * HR_FIIED_TAB_STRUC * @Author: bell * @email: bell@e-tonggroup.com * @Version: 1.0 */ public interface HrFiiedTabStrucMapper extends SqlMapper{ List<Map<String,Object>> queryHrFiiedTabStrucTree(Map<String, Object> entityMap); List<Map<String, Object>> queryHrFiiedData(Map<String, Object> entityMap); Map<String, Object> queryHrFiiedDataById(Map<String, Object> map); int saveHrFiiedData(List<HrFiiedData> addlistVo); int updateHrFiiedData(List<Map> updatelistVo); int deleteHrFiiedData(List<Map> listVO); List<Map<String, Object>> queryColAndTabName(Map<String, Object> entityMap); int deleteHrFiiedDataByTabCode(@Param("vo")Map<String, Object> entityMap, @Param("list")List<HrFiiedData> listVo); /** * 打印 * @param entityMap * @return */ List<Map<String, Object>> queryHrFiiedDataByPrint(Map<String, Object> entityMap) throws DataAccessException; HrFiiedTabStruc queryByCodeTab(HrColStruc saveMap); HrFiiedTabStruc queryByCodeByName(Map<String, Object> entityMap); }
true
8e76bfbdc2da0983128bda4fa08c6d1f380bcc46
Java
GGS1DDU/G.S_Teamwork
/GGS.DUU小组/G.D teamwork9/ELMS_Client/src/main/java/elms/businesslogic/invoicebl/RecivalListBL.java
UTF-8
5,126
1.984375
2
[]
no_license
package elms.businesslogic.invoicebl; import java.io.IOException; import java.rmi.Naming; import java.rmi.RemoteException; import elms.businesslogic_service.invoiceblservice.RecivalListBLService; import elms.dataservice.DataFactory; import elms.dataservice.dealdataservice.DealDataService; import elms.dataservice.financedataservice.BankAccountDataService; import elms.dataservice.financedataservice.ExpenseDataService; import elms.dataservice.financedataservice.IncomeDataService; import elms.dataservice.financedataservice.InitAllDataService; import elms.dataservice.invoicedataservice.ArrivalListDataService; import elms.dataservice.invoicedataservice.IncomeListDataService; import elms.dataservice.invoicedataservice.LoadingListDataService; import elms.dataservice.invoicedataservice.LoadingListZZDataService; import elms.dataservice.invoicedataservice.RecivalListDataService; import elms.dataservice.invoicedataservice.SendingListDataService; import elms.dataservice.invoicedataservice.TransferListDataService; import elms.dataservice.logdataservice.LogDataService; import elms.dataservice.managerdataservice.FreightStrategyDataService; import elms.dataservice.managerdataservice.StaffDataService; import elms.dataservice.memberdataservice.CarDataService; import elms.dataservice.memberdataservice.DriverDataService; import elms.dataservice.storagedataservice.StorageDataService; import elms.dataservice.userdataservice.UserDataService; import elms.po.RecivalListPO; import elms.vo.RecivalListVO; public class RecivalListBL implements RecivalListBLService,DataFactory{ RecivalListDataService recivallistdata; public RecivalListBL(){ recivallistdata=getRecivalListData(); } public UserDataService getUserData() { // TODO 自动生成的方法存根 return null; } public DealDataService getDealData() { // TODO 自动生成的方法存根 return null; } public ArrivalListDataService getArrivalListData() { // TODO 自动生成的方法存根 return null; } public SendingListDataService getSendingListData() { // TODO 自动生成的方法存根 return null; } public IncomeListDataService getIncomeListData() { // TODO 自动生成的方法存根 return null; } public RecivalListDataService getRecivalListData() { DataFactory df; try{ df=(DataFactory)Naming.lookup("rmi://192.168.191.1:1099/df"); return df.getRecivalListData(); }catch(Exception e){ e.printStackTrace(); return null; } } public RecivalListVO inquiry(String id) throws IOException { RecivalListPO po=recivallistdata.find(id); if(po!=null){ RecivalListVO vo=new RecivalListVO(po.getID(),po.getTime(),po.getCenterID(),po.getOrderID(),po.getFrom(),po.getState()); // System.out.println(po.getID()+" "+po.getTime()+" "+po.getCenterID()+" "+po.getOrderID()+" "+po.getFrom()+" "+po.getState()); return vo; }else return null; } public RecivalListVO record(RecivalListVO vo) throws IOException { RecivalListPO po=new RecivalListPO(vo.getID(),vo.getTime(),vo.getCenterID(),vo.getOrderID(),vo.getFrom(),vo.getState()); recivallistdata.insert(po); return vo; } public void init() throws IOException { recivallistdata.init(); } public void delete(RecivalListVO vo) throws IOException { RecivalListPO po=recivallistdata.find(vo.getID()); recivallistdata.delete(po); } public boolean Approval(String id) throws IOException { // TODO 自动生成的方法存根 return false; } public void endOpt() throws IOException { // TODO 自动生成的方法存根 } public LoadingListDataService getLoadingListData() { // TODO 自动生成的方法存根 return null; } public TransferListDataService getTransferListData() { // TODO 自动生成的方法存根 return null; } public LoadingListZZDataService getLoadingListZZData() { // TODO 自动生成的方法存根 return null; } public DriverDataService getDriverData() { // TODO 自动生成的方法存根 return null; } public CarDataService getCarData() { // TODO 自动生成的方法存根 return null; } public LogDataService getLogData() throws RemoteException { // TODO 自动生成的方法存根 return null; } public StorageDataService getStorageData() throws RemoteException { // TODO 自动生成的方法存根 return null; } public IncomeDataService getIncomeData() throws RemoteException { // TODO 自动生成的方法存根 return null; } public ExpenseDataService getExpenseData() throws RemoteException { // TODO 自动生成的方法存根 return null; } public BankAccountDataService getBankAccountData() throws RemoteException { // TODO 自动生成的方法存根 return null; } public FreightStrategyDataService getFreightStrategyData() throws RemoteException { // TODO 自动生成的方法存根 return null; } public InitAllDataService getInitData() throws RemoteException { // TODO 自动生成的方法存根 return null; } public StaffDataService getStaffData() throws RemoteException { // TODO 自动生成的方法存根 return null; } }
true
7a182480a217f5add47262f2155ce85ee5947349
Java
ishan-aggarwal/java
/ExecutorFramework/sangeeta/CyclicBarrierImpl.java
UTF-8
1,938
3.140625
3
[]
no_license
import java.util.concurrent.BrokenBarrierException; import java.util.concurrent.CyclicBarrier; import java.util.concurrent.ExecutorService; import java.util.concurrent.Executors; public class CyclicBarrierImpl { public static void main(String args[]) { Runnable action = new Runnable() { @Override public void run() { System.out.println("CyclicBarrier is reached."); } }; CyclicBarrier cyclickBarrier = new CyclicBarrier(3, action); Runnable xmlData = new Runnable() { @Override public void run() { System.out.println("xmlData is read."); try { System.out.println(Thread.currentThread().getName() + " waiting other to complete"); cyclickBarrier.await(); System.out.println("xmlData is processed"); } catch (BrokenBarrierException | InterruptedException e) { // TODO Auto-generated catch block e.printStackTrace(); } } }; Runnable dbData = new Runnable() { @Override public void run() { System.out.println("DB is read"); try { System.out.println(Thread.currentThread().getName() + " waiting other to complete"); cyclickBarrier.await(); System.out.println("DB is processed"); } catch (InterruptedException | BrokenBarrierException e) { // TODO Auto-generated catch block e.printStackTrace(); } } }; Runnable txtData = new Runnable() { @Override public void run() { System.out.println("txt is read"); try { System.out.println(Thread.currentThread().getName() + " waiting other to complete"); cyclickBarrier.await(); System.out.println("txt is processed"); } catch (InterruptedException | BrokenBarrierException e) { // TODO Auto-generated catch block e.printStackTrace(); } } }; ExecutorService es = Executors.newCachedThreadPool(); es.execute(xmlData); es.execute(dbData); es.execute(txtData); es.shutdown(); } }
true
0b7ff4e9d034201dd1c268c5f55cb815d66e27e8
Java
ashrf91/WebUITests
/webuitests/src/test/java/com/taybee/automation/webuitests/ngtests/DropDowns.java
UTF-8
890
2.15625
2
[]
no_license
package com.taybee.automation.webuitests.ngtests; import org.openqa.selenium.By; import org.openqa.selenium.support.ui.Select; //import org.testng.annotations.Test; import com.taybee.automation.webuitests.ngtests.NGWebUITestBase; public class DropDowns extends NGWebUITestBase { // @Test // public void dropdownSelectAndMultipuleSelectTest() { // String baseURL = "http://demo.guru99.com/test/newtours/register.php"; // getWebDriver().get(baseURL); // // Select drpCountry = new Select(getWebDriver().findElement(By.name("country"))); // drpCountry.selectByVisibleText("ANTARCTICA"); // //Selecting items in a Multiple SELECT elements // getWebDriver().get("http://jsbin.com/osebed/2"); // Select fruits = new Select(getWebDriver().findElement(By.id("fruits"))); // fruits.selectByVisibleText("Banana"); // waitInSec(3); // fruits.selectByIndex(1); // waitInSec(3); // } }
true
a872285410079999aaa829f6cd207f38ae0a6398
Java
LiranBashari/Arkanoid-Game
/src/CollisionInfo.java
UTF-8
1,012
3.515625
4
[]
no_license
// 313309114. /** * class that keep the following information: collision Point and collision Object. */ public class CollisionInfo { private Point collisionPoint; private Collidable objColl; /** * constructor that create the CollisionInfo. * * @param p is a Point- the collision Point. * @param objectC is an object- collidable object involved in the collision. */ public CollisionInfo(Point p, Collidable objectC) { this.collisionPoint = p; this.objColl = objectC; } /** * method that return the point at which the collision occurs. * * @return Point-the collision Point */ public Point collisionPoint() { return this.collisionPoint; } /** * the method return the the collidable object involved in the collision. * * @return collidable- the collidable object. */ public Collidable collisionObject() { return this.objColl; } }
true
111d439839c1f9c148eacf9c808bbacd8f78588b
Java
retryu/pengyoucang
/src/com/widget/UploadIProgressBar.java
UTF-8
3,143
2.25
2
[]
no_license
package com.widget; import com.hengtiansoft.cloudcontact.R; import android.content.Context; import android.util.AttributeSet; import android.util.Log; import android.view.View; import android.widget.ImageView; import android.widget.RelativeLayout; public class UploadIProgressBar extends RelativeLayout { private Context c; private ImageView imgProgess; private ImageView imgRight; private ImageView imgLeft; private int width; public UploadIProgressBar(Context context, AttributeSet attrs) { super(context, attrs); c = context; initWidget(); } public void initWidget() { setBg(); initProgress(); } @Override protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) { // TODO Auto-generated method stub super.onMeasure(widthMeasureSpec, heightMeasureSpec); width = getMeasuredWidth(); } public void setBg() { ImageView img = new ImageView(c); img.setBackgroundResource(R.drawable.progressbar_bg); LayoutParams lp = new LayoutParams(LayoutParams.FILL_PARENT, LayoutParams.WRAP_CONTENT); addView(img, lp); } @Override protected void onLayout(boolean changed, int l, int t, int r, int b) { // TODO Auto-generated method stub super.onLayout(changed, l, t, r, b); } public void initProgress() { LayoutParams leftLp = new LayoutParams(LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT); imgLeft = new ImageView(c); imgLeft.setBackgroundResource(R.drawable.progressbar_left); leftLp.addRule(RelativeLayout.ALIGN_PARENT_LEFT, RelativeLayout.TRUE); addView(imgLeft, leftLp); LayoutParams midelp = new LayoutParams(70, LayoutParams.WRAP_CONTENT); midelp.setMargins(10, 0, 0, 0); imgProgess = new ImageView(c); imgProgess.setBackgroundResource(R.drawable.progressbar_mid); midelp.addRule(RelativeLayout.RIGHT_OF, imgLeft.getId()); addView(imgProgess, midelp); LayoutParams rightLp = new LayoutParams(LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT); imgRight = new ImageView(c); imgRight.setBackgroundResource(R.drawable.progressba_right); rightLp.addRule(RelativeLayout.ALIGN_PARENT_RIGHT, RelativeLayout.TRUE); addView(imgRight, rightLp); imgLeft.setVisibility(View.INVISIBLE); imgProgess.setVisibility(View.INVISIBLE); imgRight.setVisibility(View.INVISIBLE); } public void setPorcess(int process) { if (process < 6) { imgLeft.setVisibility(View.VISIBLE); imgRight.setVisibility(View.INVISIBLE); imgProgess.setVisibility(View.INVISIBLE); } else if (process < 94) { imgLeft.setVisibility(View.VISIBLE); float pre = (float) (process / 100f) * (width - 20); android.view.ViewGroup.LayoutParams lp = imgProgess .getLayoutParams(); lp.width = (int) pre; imgProgess.setLayoutParams(lp); if (imgProgess.getVisibility() == View.INVISIBLE) { imgProgess.setVisibility(View.VISIBLE); } imgRight.setVisibility(View.INVISIBLE); } else { android.view.ViewGroup.LayoutParams lp = imgProgess .getLayoutParams(); lp.width = width - 15; imgProgess.setLayoutParams(lp); imgRight.setVisibility(View.VISIBLE); imgProgess.setVisibility(View.VISIBLE); } } }
true
35ff869c210cadafdb1abefa160c87505a1f7bc7
Java
alibaba/GraphScope
/interactive_engine/frontend/src/test/java/com/alibaba/graphscope/IrGremlinTestSuite.java
UTF-8
3,790
1.742188
2
[ "Apache-2.0", "LicenseRef-scancode-proprietary-license", "FSFAP", "BSD-3-Clause-Clear", "GPL-1.0-or-later", "BSD-2-Clause-Views", "Bitstream-Vera", "MPL-2.0", "LicenseRef-scancode-warranty-disclaimer", "OFL-1.1", "BSD-3-Clause", "APAFML", "0BSD", "LicenseRef-scancode-free-unknown", "CC-B...
permissive
package com.alibaba.graphscope; import org.apache.tinkerpop.gremlin.AbstractGremlinSuite; import org.apache.tinkerpop.gremlin.process.traversal.TraversalEngine; import org.apache.tinkerpop.gremlin.process.traversal.step.branch.RepeatTest; import org.apache.tinkerpop.gremlin.process.traversal.step.branch.UnionTest; import org.apache.tinkerpop.gremlin.process.traversal.step.filter.*; import org.apache.tinkerpop.gremlin.process.traversal.step.map.*; import org.apache.tinkerpop.gremlin.process.traversal.step.sideEffect.GroupCountTest; import org.apache.tinkerpop.gremlin.process.traversal.step.sideEffect.GroupTest; import org.junit.runners.model.InitializationError; import org.junit.runners.model.RunnerBuilder; public class IrGremlinTestSuite extends AbstractGremlinSuite { private static final Class<?>[] allTests = new Class<?>[] { // branch RepeatTest.Traversals.class, UnionTest.Traversals.class, // filter CyclicPathTest.Traversals.class, DedupTest.Traversals.class, FilterTest.Traversals.class, HasTest.Traversals.class, IsTest.Traversals.class, RangeTest.Traversals.class, SimplePathTest.Traversals.class, WhereTest.Traversals.class, // map org.apache.tinkerpop.gremlin.process.traversal.step.map.CountTest.Traversals.class, GraphTest.Traversals.class, OrderTest.Traversals.class, PathTest.Traversals.class, PropertiesTest.Traversals.class, SelectTest.Traversals.class, VertexTest.Traversals.class, UnfoldTest.Traversals.class, ValueMapTest.Traversals.class, GroupTest.Traversals.class, GroupCountTest.Traversals.class, // match MatchTest.CountMatchTraversals.class, }; private static final Class<?>[] testsToEnforce = new Class<?>[] { // branch RepeatTest.Traversals.class, UnionTest.Traversals.class, // filter CyclicPathTest.Traversals.class, DedupTest.Traversals.class, FilterTest.Traversals.class, HasTest.Traversals.class, IsTest.Traversals.class, RangeTest.Traversals.class, SimplePathTest.Traversals.class, WhereTest.Traversals.class, // map org.apache.tinkerpop.gremlin.process.traversal.step.map.CountTest.Traversals.class, GraphTest.Traversals.class, OrderTest.Traversals.class, PathTest.Traversals.class, PropertiesTest.Traversals.class, SelectTest.Traversals.class, VertexTest.Traversals.class, UnfoldTest.Traversals.class, ValueMapTest.Traversals.class, GroupTest.Traversals.class, GroupCountTest.Traversals.class, // match MatchTest.CountMatchTraversals.class, }; public IrGremlinTestSuite(final Class<?> klass, final RunnerBuilder builder) throws InitializationError { super(klass, builder, allTests, testsToEnforce, false, TraversalEngine.Type.STANDARD); } public IrGremlinTestSuite( final Class<?> klass, final RunnerBuilder builder, final Class<?>[] testsToExecute) throws InitializationError { super(klass, builder, testsToExecute, testsToEnforce, true, TraversalEngine.Type.STANDARD); } }
true
f41397c06a4d62e12e8e83a7a596899a35bb167a
Java
albuquerquecesar/egravos_mobile
/src/br/com/eagravos/mobile/modelos/MeioDeLocomocaoVitima.java
UTF-8
1,957
2.140625
2
[]
no_license
package br.com.eagravos.mobile.modelos; // Generated 02/06/2014 08:44:54 by Hibernate Tools 3.6.0 import br.com.eagravos.mobile.interfaces.IModel; /** * MeioDeLocomocaoVitima generated by hbm2java */ public class MeioDeLocomocaoVitima extends IModel<MeioDeLocomocaoVitima> implements java.io.Serializable { private Integer id; private String codigo; private String meioDeLocomacaoVitima; public MeioDeLocomocaoVitima() { } public MeioDeLocomocaoVitima(String codigo, String meioDeLocomacaoVitima) { this.codigo = codigo; this.meioDeLocomacaoVitima = meioDeLocomacaoVitima; } public Integer getId() { return this.id; } public void setId(Integer id) { this.id = id; } public String getCodigo() { return this.codigo; } public void setCodigo(String codigo) { this.codigo = codigo; } public String getMeioDeLocomacaoVitima() { return this.meioDeLocomacaoVitima; } public void setMeioDeLocomacaoVitima(String meioDeLocomacaoVitima) { this.meioDeLocomacaoVitima = meioDeLocomacaoVitima; } @Override public void copyAttributesOf(MeioDeLocomocaoVitima copy) { throw new UnsupportedOperationException("Not supported yet."); //To change body of generated methods, choose Tools | Templates. } @Override public void unsetAttributes() { throw new UnsupportedOperationException("Not supported yet."); //To change body of generated methods, choose Tools | Templates. } @Override public void cleanStringWithNull() { throw new UnsupportedOperationException("Not supported yet."); //To change body of generated methods, choose Tools | Templates. } @Override public String label() { throw new UnsupportedOperationException("Not supported yet."); //To change body of generated methods, choose Tools | Templates. } }
true
653410632de9efba248ba9f702ae7ace0a0f7972
Java
avila--07/abuscarengondolas
/webserver/webserver/changuito/changuito-war/src/main/java/ar/com/utn/changuito/services/GetGameRoundService.java
UTF-8
908
2.421875
2
[]
no_license
package ar.com.utn.changuito.services; import ar.com.utn.changuito.architecture.net.SharedObject; import ar.com.utn.changuito.model.replay.GameRound; import ar.com.utn.changuito.persistence.GameRoundDAO; public final class GetGameRoundService extends SecuredService<SharedObject> { @Override public String getId() { return "ggss"; } @Override protected SharedObject securedTypedCall(SharedObject serviceParameter) { final long id = serviceParameter.getLong("id"); if (id <= 0) { throw new RuntimeException("The game round id [" + id + "] is invalid!"); } final GameRound gameRound = new GameRoundDAO().getEntityById(id); if (gameRound.getId() == null || gameRound.getId() != id) { throw new RuntimeException("The game round with id [" + id + "] does not exists!"); } return gameRound; } }
true
87c9fc113d26c97baa2006a8850e7fdf54bbfd8c
Java
JAmbroziak/TextAdventureProject
/src/Rooms/Bathroom.java
UTF-8
1,717
3.515625
4
[]
no_license
package Rooms; import Items.*; import People.Person; public class Bathroom extends Room{ private static boolean lightsOn; private int entrances; private RepairedCrowbar cbar; public Bathroom(int x, int y){ super(x, y); this.lightsOn = false; this.entrances = 0; this.cbar = new RepairedCrowbar(); } public String toString(){ if(occupant == null && !Bathroom.lightsOn){ return " "; } else if(occupant == null){ return "B"; } else { return occupant.toString(); } } @Override public void enterRoom(Person x) { occupant = x; x.setxLoc(7); x.setyLoc(0); if(!lightsOn) { System.out.println("You feel the all-too-familiar bathroom door. You make a mental note to drink less coffee."); } else if(entrances == 0) { x.removeItems(); System.out.println("Remembering what you can from your chemistry class in college, you mix some of the chemicals from the closet in the sink\n" + "and place the rusty crowbar in. While waiting for the chemicals to work their magic, you contemplate why you become a second rate accountant\n" + "anyway. After a few minutes, you drain the sink and rinse the crowbar off. You've managed to clean off most of the rust."); x.pickupItem(cbar); entrances++; } else { System.out.println("You stand in the bathroom. You don't really need to use it.(Stop dillydallying, you've got an office to leave.)"); } } public static void setLightsOn(){ Bathroom.lightsOn = true; } }
true
af39a92c242052181afac2815b6a9a5f095ed56e
Java
horriahmed/Projet-L3-AH
/app/src/main/java/com/example/randonner/externelDataBase/Configuration.java
UTF-8
3,941
1.617188
2
[]
no_license
package com.example.randonner.externelDataBase; public class Configuration { //6 mai //address of our scripts public static final String IP="10.30.13.209"; public static final String URL_ADD_USER="http://"+IP+"/randonner/addUser.php"; public static final String LOGIN="http://"+IP+"/randonner/login.php"; public static final String URL_UPLOAD_PROFILE_PICTURE="http://"+IP+"/randonner/uploadProfileImage.php"; public static final String URL_ADD_POINT_INTERET="http://"+IP+"/randonner/addPointInteret.php"; public static final String URL_ADD_POINT_INTERET_PICTURE="http://"+IP+"/randonner/addPointInteretPicture.php"; public static final String URL_ADD_POINT="http://"+IP+"/randonner/addPoint.php"; public static final String URL_ADD_PARCOURS="http://"+IP+"/randonner/addParcours.php"; public static final String UPDATE="http://"+IP+"/randonner/updateUser.php"; public static final String DELETE_USER="http://"+IP+"/randonner/deleteUtilisateur.php"; public static final String DELETE_PARCOURS=""; public static final String DELETE_POINT_INTERET=""; public static final String GET_USER=""; public static final String ADD_POINT_INTERET_PICTURE="http://"+IP+"/randonner/addPointInteretPicture.php"; public static final String GET_PARCOURS="http://"+IP+"/randonner/getParcours.php"; public static final String GET_POINTS="http://"+IP+"/randonner/getPoints.php"; public static final String GET_POINTS_INTERETS="http://"+IP+"/randonner/getPointsInterets"; public static final String GET_POINTS_INTERETS_PICTURES="http://"+IP+"/randonner/getPointInteretPictures.php"; public static final String PATH_PROFILE_PICTURE="http://"+IP+"/randonner/profile_image/"; //keys that will be used to send the request to php scripts public static final String KEY_USER_ID="id"; public static final String KEY_USER_NOM="nom"; public static final String KEY_USER_PRENOM="prenom"; public static final String KEY_USER_MAIL="mail"; public static final String KEY_USER_TEL="tel"; public static final String KEY_USER_PASSWORD="motDePasse"; public static final String KEY_USER_BIRTHDATE="dateDeNaissance"; public static final String KEY_USER_SRC_IMAGE="src_image"; //JSON Tags public static final String TAG_JSON_SUCCESS="success"; public static final String TAG_JSON_NUM_ROWS="num_rows"; public static final String TAG_JSON_ARRAY="result"; public static final String TAG_USER_ID="id"; public static final String TAG_POINT_LATITUDE="latitude"; public static final String TAG_POINT_LONGITUDE="longitude"; public static final String TAG_POINT_POSITION="position"; public static final String TAG_PARCOURS_ID="id_parcours"; public static final String TAG_USER_NOM="nom"; public static final String TAG_USER_PRENOM="prenom"; public static final String TAG_USER_MAIL="mail"; public static final String TAG_USER_TEL="tel"; public static final String TAG_USER_PASSWORD="motDePasse"; public static final String TAG_USER_BIRTHDATE="dateDeNaissance"; //PARCOURS public static final String PARCOURS_ID="id_parcours"; public static final String PARCOURS_NOM="nom_parcours"; public static final String PARCOURS_DATE="date_parcours"; public static final String PARCOURS_DESCRIPTION="description_parcours"; public static final String USER_ID="id_utilisateur"; public static final String LATITUDE="latitude"; public static final String LONGITUDE="longitude"; public static final String POSITION="position"; public static final String POINT_INTERET_NOM="nom_point_interet"; public static final String POINT_INTERET_DESCRIPTION="description_point_interet"; }
true
accfbc81e1b35b781c5aa9bf1941ebf2d499b868
Java
sauravomar/schoolCrawler
/src/main/java/com/edlogy/util/BeanUtil.java
UTF-8
575
2.375
2
[]
no_license
package com.edlogy.util; import org.springframework.context.ApplicationContext; import org.springframework.context.support.ClassPathXmlApplicationContext; public class BeanUtil { private static BeanUtil instance = null; ApplicationContext appContext = null; protected BeanUtil() { appContext = new ClassPathXmlApplicationContext("applicationContext.xml"); } public static BeanUtil getInstance() { if(instance == null) { instance = new BeanUtil(); } return instance; } public Object getBean(String beanName){ return appContext.getBean(beanName); } }
true
ba0ea0848faf70fa8bf7e00575ed247999f198c4
Java
Jeffrey-Codebase/hackerrank-solutions
/src/main/java/com/jeffrey/hackerrank/medium/RecursionDavisStaircase.java
UTF-8
1,384
3.53125
4
[]
no_license
package com.jeffrey.hackerrank.medium; import java.io.*; import java.util.stream.*; class RecursionDavisStaircaseResult { /* * Problem: Recursion: Davis' Staircase * https://www.hackerrank.com/challenges/ctci-recursive-staircase/problem * * Time Complexity: O(N), N = the input Integer n * * Space Complexity: O(1) * */ public static int stepPerms(int n) { // Write your code here int[] preSteps = new int[3]; preSteps[0] = 1; preSteps[1] = 2; preSteps[2] = 4; int step = 3; for (; step < n; step++) { preSteps[step % 3] = preSteps[0] + preSteps[1] + preSteps[2]; } return preSteps[(n - 1) % 3]; } } public class RecursionDavisStaircase { public static void main(String[] args) throws IOException { BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(System.in)); BufferedWriter bufferedWriter = new BufferedWriter(new FileWriter(System.getenv("OUTPUT_PATH"))); int s = Integer.parseInt(bufferedReader.readLine().trim()); IntStream.range(0, s).forEach(sItr -> { try { int n = Integer.parseInt(bufferedReader.readLine().trim()); int res = RecursionDavisStaircaseResult.stepPerms(n); bufferedWriter.write(String.valueOf(res)); bufferedWriter.newLine(); } catch (IOException ex) { throw new RuntimeException(ex); } }); bufferedReader.close(); bufferedWriter.close(); } }
true
0da887d506b052e8e432e3c76432d7d2ea34e92e
Java
gallenc/papayrus-experiments
/papyrus-uml-to-java-auction/generated-src-example/src/main/java/org/solent/examples/auction/model/messages/AuctionMessage.java
UTF-8
1,017
2.078125
2
[ "Apache-2.0" ]
permissive
/******************************************************************************* * All rights reserved. *******************************************************************************/ package org.solent.examples.auction.model.messages; import org.solent.example.auction.model.entities.Lot; // Start of user code (user defined imports) // End of user code /** * Description of AuctionMessage. * * @author sbegaudeau */ public class AuctionMessage { /** * Description of the property lot. */ public Lot lot = null; /** * Description of the property id. */ public long id = 0L; /** * Description of the property timestamp. */ public String timestamp = ""; // Start of user code (user defined attributes for AuctionMessage) // End of user code /** * The constructor. */ public AuctionMessage() { // Start of user code constructor for AuctionMessage) super(); // End of user code } // Start of user code (user defined methods for AuctionMessage) // End of user code }
true
1d253fb08626f583f95f25bc05c535029331755c
Java
yenlee38/api_spring_boot
/src/main/java/com/apispring/api_spring/entity/Teacher.java
UTF-8
2,910
2.125
2
[]
no_license
package com.apispring.api_spring.entity; import com.fasterxml.jackson.annotation.JsonIgnore; import com.fasterxml.jackson.annotation.JsonIgnoreProperties; import lombok.AllArgsConstructor; import lombok.Data; import lombok.NoArgsConstructor; import org.springframework.lang.NonNull; import javax.persistence.*; import java.util.Collection; import java.util.Date; import java.util.UUID; @Data @AllArgsConstructor @Entity public class Teacher { @Id @Column(name = "teacher_id") private String teacherId; private String name = null; private Date birthday = null; private String degree = null; private String phone = null; private String gender = null; private String address = null; private String email = null; private String image = null; @OneToOne private Account account; public Account getAccount() { return account; } public void setAccount(Account account) { this.account = account; } @JsonIgnore @OneToMany(mappedBy = "sender") private Collection<Announcement> announcements; @JsonIgnore @OneToMany(mappedBy = "teacher") private Collection<Class> classes; @JsonIgnore @OneToMany(mappedBy = "sender") private Collection<OffRequest> offRequests; public Collection<Announcement> getAnnouncements() { return announcements; } public void setAnnouncements(Collection<Announcement> announcements) { this.announcements = announcements; } public String getTeacherID() { return teacherId; } public void setTeacherID(String teacherId) { this.teacherId = teacherId; } public String getName() { return name; } public void setName(String name) { this.name = name; } public Date getBirthday() { return birthday; } public void setBirthday(Date birthday) { this.birthday = birthday; } public String getDegree() { return degree; } public void setDegree(String degree) { this.degree = degree; } public String getPhone() { return phone; } public void setPhone(String phone) { this.phone = phone; } public String getGender() { return gender; } public void setGender(String gender) { this.gender = gender; } public String getAddress() { return address; } public void setAddress(String address) { this.address = address; } public String getEmail() { return email; } public void setEmail(String email) { this.email = email; } public String getImage() { return image; } public void setImage(String image) { this.image = image; } public Teacher() { } public Teacher(@NonNull String teacherId){ this.teacherId= teacherId; } }
true
2c32c475db3b0e8d3bfc0c3107d31a051aaa4448
Java
GYJerry/springProject
/src/main/java/cn/simplemind/helloworld/MainApp.java
UTF-8
1,645
2.5
2
[]
no_license
package cn.simplemind.helloworld; import org.springframework.context.ConfigurableApplicationContext; import org.springframework.context.annotation.AnnotationConfigApplicationContext; import org.springframework.context.support.FileSystemXmlApplicationContext; import cn.simplemind.springCfgBaseJave.ConfigEventHandler; public class MainApp { public static void main(String[] args) { //ApplicationContext context = new ClassPathXmlApplicationContext("src/Bean.xml"); ConfigurableApplicationContext context = new FileSystemXmlApplicationContext("src/HWBeans.xml"); //ConfigurableApplicationContext configContext = new AnnotationConfigApplicationContext(ConfigEventHandler.class); // System.out.println("sleep 2 second"); // try { // Thread.sleep(2000); // test lazy init // } catch (InterruptedException e) { // e.printStackTrace(); // } HelloWorld hello = (HelloWorld) context.getBean("helloWorld"); hello.getMessage(); HelloWorld hello2 = (HelloWorld) context.getBean("helloWorld"); // System.out.println("test singleton"); System.out.println("first singleton hello hashcode " + hello.hashCode()); System.out.println("second singleton hello hashcode " + hello2.hashCode()); // 换行 // System.out.println(); // // HelloWorld obj3 = (HelloWorld) context.getBean("helloWorldCopy"); // obj3.getMessage(); // // HelloWorld obj4 = (HelloWorld) context.getBean("helloWorldCopy"); // System.out.println("test prototype"); // System.out.println("first prototype obj hashcode " + obj3.hashCode()); // System.out.println("second prototype obj hashcode " + obj4.hashCode()); context.close(); } }
true
1029ec43a3810fc507cd8de55df64e8ab0be01f8
Java
JanekKar/tic-tac-toe-kck
/src/main/java/app/cli/ACSILogo.java
UTF-8
4,325
2.5625
3
[]
no_license
package app.cli; import com.googlecode.lanterna.Symbols; import com.googlecode.lanterna.TextColor; import com.googlecode.lanterna.graphics.TextGraphics; import static app.cli.Config.*; public class ACSILogo { private static int totalPaddingTop; private static int totalPaddingLeft; private static char sym = Symbols.BLOCK_SOLID; public static void drawLogo(TextGraphics tg, int leftPadding, int topPadding) { char[] symbols; if (colorSchema.getLogoSymbols() != null) { symbols = colorSchema.getLogoSymbols(); } else { symbols = new char[]{Symbols.BLOCK_SOLID, Symbols.BLOCK_DENSE, Symbols.BLOCK_MIDDLE}; } sym = symbols[0]; TextColor prevColor = tg.getForegroundColor(); totalPaddingLeft = windowPaddingLeft + leftPadding; totalPaddingTop = windowPaddingTop + topPadding; tg.setForegroundColor(colorSchema.getLogo()[0]); drawT(tg, 0); drawI(tg, 6); drawC(tg, 8); sym = symbols[1]; tg.setForegroundColor(colorSchema.getLogo()[1]); drawT(tg, 17); drawA(tg, 23); drawC(tg, 29); sym = symbols[2]; tg.setForegroundColor(colorSchema.getLogo()[2]); drawT(tg, 37); drawO(tg, 43); drawE(tg, 49); tg.setForegroundColor(prevColor); sym = Symbols.BLOCK_SOLID; } public static void drawTie(TextGraphics tg, int xPos, int yPos) { sym = Symbols.BLOCK_SOLID; totalPaddingLeft = windowPaddingLeft + xPos; totalPaddingTop = windowPaddingTop + yPos; tg.setForegroundColor(colorSchema.getLogo()[0]); drawT(tg, 0); drawI(tg, 6); drawE(tg, 8); } private static void drawA(TextGraphics tg, int xPos) { //A tg.drawLine(totalPaddingLeft + xPos, totalPaddingTop, totalPaddingLeft + xPos + 4, totalPaddingTop, sym); tg.drawLine(totalPaddingLeft + xPos, totalPaddingTop + 2, totalPaddingLeft + xPos + 4, totalPaddingTop + 2, sym); tg.drawLine(totalPaddingLeft + xPos, totalPaddingTop, totalPaddingLeft + xPos, totalPaddingTop + 3, sym); tg.drawLine(totalPaddingLeft + xPos + 4, totalPaddingTop, totalPaddingLeft + xPos + 4, totalPaddingTop + 3, sym); } private static void drawC(TextGraphics tg, int xPos) { //C tg.drawLine(totalPaddingLeft + xPos, totalPaddingTop, totalPaddingLeft + xPos, totalPaddingTop + 3, sym); tg.drawLine(totalPaddingLeft + xPos, totalPaddingTop, totalPaddingLeft + xPos + 3, totalPaddingTop, sym); tg.drawLine(totalPaddingLeft + xPos, totalPaddingTop + 3, totalPaddingLeft + xPos + 3, totalPaddingTop + 3, sym); } private static void drawE(TextGraphics tg, int xPos) { //E tg.drawLine(totalPaddingLeft + xPos, totalPaddingTop, totalPaddingLeft + xPos + 4, totalPaddingTop, sym); tg.drawLine(totalPaddingLeft + xPos, totalPaddingTop + 1, totalPaddingLeft + xPos + 4, totalPaddingTop + 1, sym); tg.drawLine(totalPaddingLeft + xPos, totalPaddingTop + 3, totalPaddingLeft + xPos + 4, totalPaddingTop + 3, sym); tg.drawLine(totalPaddingLeft + xPos, totalPaddingTop, totalPaddingLeft + xPos, totalPaddingTop + 3, sym); } private static void drawI(TextGraphics tg, int xPos) { //I tg.drawLine(totalPaddingLeft + xPos, totalPaddingTop, totalPaddingLeft + xPos, totalPaddingTop + 3, sym); } private static void drawO(TextGraphics tg, int xPos) { //O tg.drawLine(totalPaddingLeft + xPos, totalPaddingTop, totalPaddingLeft + xPos + 4, totalPaddingTop, sym); tg.drawLine(totalPaddingLeft + xPos, totalPaddingTop + 3, totalPaddingLeft + xPos + 4, totalPaddingTop + 3, sym); tg.drawLine(totalPaddingLeft + xPos, totalPaddingTop, totalPaddingLeft + xPos, totalPaddingTop + 3, sym); tg.drawLine(totalPaddingLeft + xPos + 4, totalPaddingTop, totalPaddingLeft + xPos + 4, totalPaddingTop + 3, sym); } private static void drawT(TextGraphics tg, int xPos) { //T tg.drawLine(totalPaddingLeft + xPos, totalPaddingTop, totalPaddingLeft + xPos + 4, totalPaddingTop, sym); tg.drawLine(totalPaddingLeft + xPos + 2, totalPaddingTop, totalPaddingLeft + xPos + 2, totalPaddingTop + 3, sym); } }
true
460c7d65ae6c2626b2dfc0887d18fceaf9122ce8
Java
VishwasRaiborde/spring-mvc-sample
/acmecart/src/com/acme/dao/order/CartDataException.java
UTF-8
854
1.90625
2
[]
no_license
package com.acme.dao.order; public class CartDataException extends Exception { /** * */ private static final long serialVersionUID = 1L; public CartDataException() { super(); // TODO Auto-generated constructor stub } public CartDataException(String message, Throwable cause, boolean enableSuppression, boolean writableStackTrace) { super(message, cause, enableSuppression, writableStackTrace); // TODO Auto-generated constructor stub } public CartDataException(String message, Throwable cause) { super(message, cause); // TODO Auto-generated constructor stub } public CartDataException(String message) { super(message); // TODO Auto-generated constructor stub } public CartDataException(Throwable cause) { super(cause); // TODO Auto-generated constructor stub } }
true
7649fdad6ecd65c4b69758239a79fb30ef1e3ea2
Java
seriferabia/BackEndModul
/BackEndW4/marco-polo-ex/marco/src/main/java/at/nacs/marco/MarcoEndpoint.java
UTF-8
785
2.109375
2
[]
no_license
package at.nacs.marco; import lombok.RequiredArgsConstructor; import org.springframework.beans.factory.annotation.Value; import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.PathVariable; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RestController; import org.springframework.web.client.RestTemplate; @RestController @RequestMapping("/say") @RequiredArgsConstructor public class MarcoEndpoint { private final RestTemplate restTemplate; @Value("${polo.url}") private String url; @GetMapping("/{message}") String sendMessageToPolo(@PathVariable String message) { return restTemplate.postForObject(url, message, String.class); } }
true
b61291e2ef260ee67d02d102012109531ad7f4d3
Java
Technoboy-/Jrpc
/src/main/java/org/jrpc/common/ServiceProvider.java
UTF-8
570
1.867188
2
[]
no_license
/** * */ package org.jrpc.common; import static org.jrpc.common.JConstants.DEFAULT_GROUP; import static org.jrpc.common.JConstants.DEFAULT_VERSION; import java.lang.annotation.ElementType; import java.lang.annotation.Retention; import java.lang.annotation.RetentionPolicy; import java.lang.annotation.Target; /** * @author caoguo(jiwei.guo) * */ @Target(ElementType.TYPE) @Retention(RetentionPolicy.RUNTIME) public @interface ServiceProvider { String value() default ""; String group() default DEFAULT_GROUP; String version() default DEFAULT_VERSION; }
true
4363ae6520c94f7c0ecd12fa501dd2d6f9137585
Java
kingking888/jun_java_plugin
/springboot_plugin/springboot_learning/springboot-enums/src/main/java/me/zhyd/springboot/enums/enums/TypeEnum.java
UTF-8
687
2.421875
2
[]
no_license
package me.zhyd.springboot.enums.enums; import com.alibaba.fastjson.JSONObject; import java.util.HashMap; import java.util.Map; /** * @author Wujun * @version 1.0 * @website https://www.zhyd.me * @date 2019/7/3 9:47 * @since 1.8 */ public enum TypeEnum { ADMIN("管理员"), USER("普通用户"); private String desc; TypeEnum(String desc) { this.desc = desc; } public String getDesc() { return desc; } @Override public String toString() { Map<String, Object> map = new HashMap<>(); map.put("name", this.name()); map.put("desc", this.getDesc()); return JSONObject.toJSONString(map); } }
true
7bfe791ed45aab5dfb5a8a3a7d4b0f1ee6329b0f
Java
Jazng/Library
/src/main/java/com/self/library/constant/ErrorConstant.java
UTF-8
316
2.03125
2
[]
no_license
package com.self.library.constant; /** * @Author Administrator * @Title: 异常信息 * @Description: 取消使用魔法值 * @Date 2021-04-17 12:57 * @Version: 1.0 */ public interface ErrorConstant { String CREATE_TOKEN_ERROR = "创建token出错!"; String VERIFY_TOKEN_ERROR = "token不正确"; }
true
f55433cf123b46e3044d8a5f829d4331280c7445
Java
Mr-Yao/web-sso
/sso-server-base/src/main/java/ly/sso/server/core/service/impl/DefaultTokenRegularValidator.java
UTF-8
3,230
2.40625
2
[]
no_license
package ly.sso.server.core.service.impl; import java.util.Date; import java.util.List; import java.util.Map; import java.util.Map.Entry; import java.util.concurrent.ExecutorService; import java.util.concurrent.Executors; import java.util.concurrent.ScheduledExecutorService; import java.util.concurrent.ThreadFactory; import java.util.concurrent.TimeUnit; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import ly.sso.server.core.Configuration; import ly.sso.server.core.entity.ClientSystem; import ly.sso.server.core.service.TokenRegularValidator; import ly.sso.server.core.token.TokenManager.Token; import ly.sso.server.util.DateUtil; /** * 默认Token定期验证器 * * @author liyao * * 2016年12月24日 下午2:34:45 * */ public class DefaultTokenRegularValidator implements TokenRegularValidator { private final ScheduledExecutorService TIMER = Executors.newScheduledThreadPool(1, new ThreadFactory() { @Override public Thread newThread(Runnable r) { Thread t = new Thread(r); t.setDaemon(true); return t; } }); private final ExecutorService CACHED_THREAD_POOL = Executors.newCachedThreadPool(new ThreadFactory() { @Override public Thread newThread(Runnable r) { Thread t = new Thread(r); t.setDaemon(true); return t; } }); private final Logger LOGGER = LoggerFactory.getLogger(this.getClass()); @Override public void execute(final Configuration config, final Map<String, Token> dataMap) { TIMER.scheduleAtFixedRate(new Runnable() { public void run() { for (final Entry<String, Token> entry : dataMap.entrySet()) { CACHED_THREAD_POOL.execute(new Runnable() { @Override public void run() { String vt = entry.getKey(); Token token = entry.getValue(); Date expired = token.getExpired(); Date now = new Date(); // 当前时间大于过期时间 if (now.compareTo(expired) < 0) { return; } // 因为令牌支持自动延期服务,并且应用客户端缓存机制后, // 令牌最后访问时间是存储在客户端的,所以服务端向所有客户端发起一次timeout通知, // 客户端根据lastAccessTime + tokenTimeout计算是否过期,<br> // 若未过期,用各客户端最大有效期更新当前过期时间 List<ClientSystem> clientSystems = config.getClientSystems(); Date maxClientExpired = expired; for (ClientSystem clientSystem : clientSystems) { Date clientExpired = clientSystem.noticeTimeout(vt, config.getTokenTimeout()); if (clientExpired != null && clientExpired.compareTo(now) > 0) { maxClientExpired = maxClientExpired.compareTo(clientExpired) < 0 ? clientExpired : maxClientExpired; } } if (maxClientExpired.compareTo(now) > 0) { // 客户端最大过期时间大于当前 LOGGER.info("{} - TOken自动延期至:{}", vt, DateUtil.dateToString(maxClientExpired)); token.setExpired(maxClientExpired); } else { LOGGER.info("清除过期Token:{}", vt); // 已过期,清除对应token dataMap.remove(vt); } } }); } } }, 60, 60, TimeUnit.SECONDS); } }
true
279bbc35008c6046a9e76112f45861089e616fae
Java
mirego/j2objc
/translator/src/test/java/com/mirego/interop/java/test/interfaces/WithInt.java
UTF-8
447
2.859375
3
[ "GPL-2.0-only", "Apache-2.0", "LicenseRef-scancode-public-domain", "BSD-2-Clause", "APSL-1.0", "LGPL-2.0-or-later", "LicenseRef-scancode-proprietary-license", "GPL-1.0-or-later", "LicenseRef-scancode-generic-exception", "LicenseRef-scancode-red-hat-attribution", "ICU", "BSD-3-Clause", "MIT",...
permissive
package com.mirego.interop.java.test.interfaces; import com.mirego.interop.kotlin.test.interfaces.InterfaceWithInt; public class WithInt { public static class WithIntImplementation implements InterfaceWithInt { @Override public int convert(int inputInt) { return inputInt; } } public static int main(String[] args) { WithIntImplementation withInt = new WithIntImplementation(); return withInt.convert(1); } }
true
c4957eb38c551d1bf9440eea7a47829c4a9be0f8
Java
AgustinBettati/ayed
/src/main/chessMovement/HorseMovement.java
UTF-8
4,519
3.734375
4
[]
no_license
package main.chessMovement; import struct.impl.stacks.DynamicStack; import java.util.ArrayList; /** * @author Agustin Bettati * @author Marcos Khabie * @version 1.0 * * This class contains all the logic need to display all the paths for a horse that * moves a certain amount of steps. */ public class HorseMovement { private int amountOfMovements; private ArrayList<DynamicStack<PositionInBoard>> listOfStacks; private ArrayList<ArrayList<PositionInBoard>> listToDisplay; /** * creates the horse movements solver. * @param amountOfMovements */ public HorseMovement(int amountOfMovements) { listOfStacks=new ArrayList<>(amountOfMovements); this.amountOfMovements=amountOfMovements; listToDisplay = new ArrayList<>(); } /** * Returns the next possible path that the horse can make. * @return a list with all of the positions in the board. */ public ArrayList<PositionInBoard> getNextPath(){ for (int i= listOfStacks.size();i<amountOfMovements;i++){ if (i==0){ listOfStacks.add(createStackForPosition(new PositionInBoard(0,0),new PositionInBoard(0,0))); } else if (i==1){ if(listOfStacks.get(0).isEmpty()){ throw new AllPathsDisplayedException(); } listOfStacks.add(createStackForPosition(listOfStacks.get(i-1).peek(),new PositionInBoard(0,0))); } else{ listOfStacks.add(createStackForPosition(listOfStacks.get(i-1).peek(),listOfStacks.get(i-2).peek())); } } saveValuesOfStacksToLaterDisplay(); ArrayList<PositionInBoard> path=new ArrayList<>(amountOfMovements); for (int i=0;i<listOfStacks.size() -1;i++){ path.add(listOfStacks.get(i).peek()); } DynamicStack<PositionInBoard> lastStack = listOfStacks.get(amountOfMovements -1); int sizeOfLastStack = lastStack.size(); for (int i=0;i<sizeOfLastStack;i++){ path.add(lastStack.peek()); lastStack.pop(); } int i = amountOfMovements - 1; while (i > 0&&listOfStacks.get(i).isEmpty()){ listOfStacks.remove(i); listOfStacks.get(i-1).pop(); i--; } return path; } /** * Returns the list of stacks in form of a multi array. * @return */ public ArrayList<ArrayList<PositionInBoard>> getStacks(){ return listToDisplay; } private void saveValuesOfStacksToLaterDisplay(){ listToDisplay.clear(); for(DynamicStack<PositionInBoard> stack : listOfStacks){ int size = stack.size(); ArrayList<PositionInBoard> list = new ArrayList<>(); DynamicStack<PositionInBoard> aux = new DynamicStack<>(); for (int j = size -1; j >= 0; j--){ aux.push(stack.peek()); list.add(stack.peek()); stack.pop(); } listToDisplay.add(list); for(int j = 0; j < size; j++){ stack.push(aux.peek()); aux.pop(); } } } private DynamicStack<PositionInBoard> createStackForPosition(PositionInBoard position, PositionInBoard previousPosition){ DynamicStack<PositionInBoard> stack = new DynamicStack<>(); for (int i= position.row()-2;i<=position.row()+2;i++){ if (i==position.row()+2 || i==position.row()-2 ) { for (int j = position.column() - 2; j <= position.column() + 2; j++) { if (!(j==position.column() || (j==position.column()+2 || j==position.column()-2))) { PositionInBoard possiblePosition = new PositionInBoard(i , j ); if(possiblePosition.isInBoard()&&!possiblePosition.equals(previousPosition)){ stack.push(possiblePosition); } } } } else if(!(i == position.row())){ for(int k = -2; k <=2; k+=4){ PositionInBoard possiblePostion = new PositionInBoard(i, position.column() + k); if(possiblePostion.isInBoard()&&!possiblePostion.equals(previousPosition)){ stack.push(possiblePostion); } } } } return stack; } }
true
766eb82c8fff6ec7a555ed3f3f3cfac895a21fc7
Java
sjr0115/Algo
/알고리즘/src/알골강의/회장뽑기.java
UTF-8
1,566
2.859375
3
[]
no_license
package 알골강의; import java.io.*; import java.util.*; public class 회장뽑기 { public static void main(String[] args) throws NumberFormatException, IOException { BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); StringBuilder sb = new StringBuilder(); int N = Integer.parseInt(br.readLine()); int[][] member = new int[N + 1][N + 1]; int INF = 10000000; for (int i = 1; i <= N; i++) { Arrays.fill(member[i], INF); } while(true) { StringTokenizer st = new StringTokenizer(br.readLine()); int a = Integer.parseInt(st.nextToken()); int b = Integer.parseInt(st.nextToken()); if(a == -1 && b == - 1) break; member[a][b] = member[b][a] = 1; } for (int k = 1; k <= N; k++) { for (int i = 1; i <= N; i++) { if(i == k) continue; for (int j = 1; j <= N; j++) { if(member[k][j] != INF && member[i][k] != INF && member[i][j] > member[i][k] + member[k][j]) { member[i][j] = member[i][k] + member[k][j]; } } } } int[] memberCnt = new int[N + 1]; int min = Integer.MAX_VALUE; for (int i = 1; i <= N; i++) { for (int j = 1; j <= N; j++) { if(i == j) continue; memberCnt[i] = Math.max(memberCnt[i], member[i][j]); } min = Math.min(min, memberCnt[i]); } ArrayList<Integer> arr = new ArrayList<>(); for (int i = 1; i <= N; i++) { if(min == memberCnt[i]) { arr.add(i); } } sb.append(min + " " + arr.size() + "\n"); for (Integer i : arr) { sb.append(i + " "); } System.out.println(sb.toString()); } }
true
b991171cb935b0d36dda6e006d1bd09e42680590
Java
eric-lanita/BigRoadTruckingLogbookApp_v21.0.12_source_from_JADX
/com/bigroad/shared/duty/rule/C0926f.java
UTF-8
6,326
1.617188
2
[]
no_license
package com.bigroad.shared.duty.rule; import com.bigroad.shared.ao; import com.bigroad.shared.duty.C0882q; import com.bigroad.shared.duty.C0896g; import com.bigroad.shared.duty.C0898i; import com.bigroad.shared.duty.C0902k; import com.bigroad.shared.duty.C0907o; import com.bigroad.shared.duty.C0910r; import com.bigroad.shared.duty.C0955u; import com.bigroad.shared.duty.DutyLimits.C0868a; import com.bigroad.shared.validation.C1168m; import com.bigroad.shared.validation.C1175o; import com.bigroad.shared.validation.C1176p; import com.bigroad.shared.validation.ValidationError.ErrorCode; import com.bigroad.shared.validation.ValidationMessageId; import com.bigroad.shared.validation.model.DailyLog.Field; import java.util.ArrayList; import java.util.Calendar; import java.util.Iterator; import java.util.List; public class C0926f implements C0912j { private static final C0902k f2840b = new C0902k(432000000, 432000000); private final long f2841a; private C0902k f2842c = f2840b; private C0955u f2843d; private C0902k f2844e; private C0955u f2845f; private List<C0882q> f2846g = new ArrayList(); public C0926f(boolean z) { this.f2841a = z ? 288000000 : 252000000; this.f2844e = new C0902k(this.f2841a, this.f2841a); } public void mo732a(C0898i c0898i, C0868a c0868a) { m4661a(c0898i); m4663b(c0898i); c0868a.m4354b(C0902k.m4574a(this.f2842c, this.f2844e)); c0868a.m4357c(this.f2842c.m4402b() < this.f2844e.m4402b() ? this.f2843d : this.f2845f); c0868a.m4353a(this.f2846g); c0868a.m4348a(60000); } private void m4661a(C0898i c0898i) { Iterator h = c0898i.m4558e().m4460h(259200000); while (h.hasNext()) { this.f2846g.add((C0882q) h.next()); } this.f2843d = new C0955u(259200000 - c0898i.m4558e().m4457f(259200000), 259200000); if (!this.f2846g.isEmpty() && this.f2843d.m4402b() > 0) { this.f2842c = new C0902k(432000000 - C0924k.m4657a((C0882q) this.f2846g.get(this.f2846g.size() - 1), c0898i.m4557d(), 14), 432000000); } } private void m4663b(C0898i c0898i) { C0882q b = ((C0910r) c0898i.m4558e().m4450a(C0896g.f2771d, C0910r.m4592a(86400000))).m4595b(); b = b == null ? c0898i.m4558e() : c0898i.m4550a(b.m4464k(), c0898i.m4561h()); if (!b.m4461h()) { this.f2844e = new C0902k(this.f2841a - b.m4452d(), this.f2841a); } this.f2845f = new C0955u(86400000 - c0898i.m4558e().m4457f(86400000), 86400000); } public void mo731a(C0898i c0898i, int i, C1176p<Field> c1176p) { C0907o c = c0898i.m4554c(i); Iterator h = c0898i.m4558e().m4460h(259200000); while (h.hasNext()) { C0882q c0882q = (C0882q) h.next(); if (!c0882q.m4128c((ao) c)) { if (c0882q.mo693b((ao) c)) { m4662a(c, c0882q, (C1176p) c1176p); m4664b(c, c0882q, c1176p); return; } return; } } } private void m4662a(C0907o c0907o, C0882q c0882q, C1176p<Field> c1176p) { Calendar c = c0907o.m4586c(); c.add(5, -13); long a = c0882q.m4445a(c.getTimeInMillis(), c0907o.mo697f()); Iterator it = c0882q.iterator(); long j = a; while (it.hasNext()) { C0896g c0896g = (C0896g) it.next(); if (!c0896g.m4128c((ao) c0907o)) { if (!c0896g.mo695d(c0907o)) { if (!c0896g.m4540c()) { ao e = c0896g.mo696e(c0907o); long a2 = e.mo689a(); long max = Math.max(0, 432000000 - j); if (c0896g.m4541d() && max < a2) { Long valueOf = Long.valueOf(120); Integer valueOf2 = Integer.valueOf(14); Enum enumR = Field.NONE; C1176p<Field> c1176p2 = c1176p; Enum enumR2 = enumR; c1176p2.m5957a(enumR2, new C1168m(max + e.mo697f(), e.mo698g(), ErrorCode.DRIVING_OVER_DUTY_CYCLE_LIMIT, new C1175o(ValidationMessageId.RULE_CYCLE_DUTY, new Object[]{valueOf, valueOf2}))); } j += a2; } } else { return; } } } } private void m4664b(C0907o c0907o, C0882q c0882q, C1176p<Field> c1176p) { Iterator h = c0882q.m4460h(86400000); while (h.hasNext()) { C0882q c0882q2 = (C0882q) h.next(); if (c0882q2.mo693b((ao) c0907o)) { m4665c(c0907o, c0882q2, c1176p); } else if (c0882q2.mo695d(c0907o)) { return; } } } private void m4665c(C0907o c0907o, C0882q c0882q, C1176p<Field> c1176p) { Iterator it = c0882q.iterator(); long j = 0; while (it.hasNext()) { C0896g c0896g = (C0896g) it.next(); if (!c0896g.mo695d(c0907o)) { if (!c0896g.m4540c()) { if (c0896g.m4128c((ao) c0907o)) { j = c0896g.mo689a() + j; } else { ao e = c0896g.mo696e(c0907o); long f = j + (e.mo697f() - c0896g.mo697f()); j = (e.mo689a() + f) - this.f2841a; if (c0896g.m4541d() && j > 0) { Long valueOf = Long.valueOf(this.f2841a / 3600000); Long valueOf2 = Long.valueOf(24); Enum enumR = Field.NONE; C1176p<Field> c1176p2 = c1176p; Enum enumR2 = enumR; c1176p2.m5957a(enumR2, new C1168m(Math.max(e.mo697f(), e.mo698g() - j), e.mo698g(), ErrorCode.DRIVING_OVER_DUTY_CYCLE_SINCE_BREAK_LIMIT, new C1175o(ValidationMessageId.RULE_CYCLE_OFF_DUTY, new Object[]{valueOf, valueOf2}))); } j = (c0896g.mo698g() - e.mo697f()) + f; } } } else { return; } } } }
true
27b71e94f1609522a95eca8a98b9c6d23ace16df
Java
VijayEluri/cosmocode-commons
/src/main/java/de/cosmocode/collections/tree/iterator/AbstractTreeIterator.java
UTF-8
10,660
2.96875
3
[ "Apache-2.0" ]
permissive
/** * Copyright 2010 - 2013 CosmoCode GmbH * * 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 de.cosmocode.collections.tree.iterator; import com.google.common.collect.Iterators; import de.cosmocode.collections.tree.TreeNode; import java.util.Arrays; import java.util.Iterator; import java.util.NoSuchElementException; /** * <p> An abstract tree iterator that provides utility methods to * walk a tree. * </p> * <p> All iterator methods are left abstract. * </p> * * @param <E> the generic type of the Tree to walk * * @author Oliver Lorenz */ public abstract class AbstractTreeIterator<E> implements Iterator<E> { private TreeNode<E> currentNode; private int currentLevel; private int[] childIndexes; private Iterator<TreeNode<E>> siblingIterator; public AbstractTreeIterator(final TreeNode<E> root) { if (root == null) throw new NullPointerException("root must not be null"); if (root.getParent() != null) throw new IllegalArgumentException("given TreeNode is not a root node"); this.currentNode = root; this.childIndexes = new int[4]; Arrays.fill(this.childIndexes, -1); this.currentLevel = 0; this.siblingIterator = Iterators.emptyIterator(); } /** * <p> Returns true if the root has been visited, false otherwise. * The root is considered visited either when * going to root via {@link #parent()} or calling {@link #currentData()} at start. * </p> * <p> This method always returns false if it is called before every other method. * </p> * * @return true if root has been visited (data fetched from root), false otherwise */ protected boolean rootVisited() { return this.childIndexes[0] == 0; } /** * <p> Returns true if the root has not been visited, false otherwise. * This is the negation of {@link #rootVisited()}. * </p> * * @return true if the root has not been visited, false otherwise. * * @see #rootVisited() */ protected boolean rootNotVisited() { return this.childIndexes[0] == -1; } /** * Returns true if the direct children of this node have been visited. * @return true if children have been visited, false otherwise */ protected boolean childrenVisited() { if (currentNode.getNumberOfChildren() == 0) { return true; } else if (currentLevel + 1 >= this.childIndexes.length) { return false; } else { return this.childIndexes[currentLevel + 1] + 1 >= currentNode.getNumberOfChildren(); } } /** * <p> Returns true if the current node is the root node, false otherwise. * This is equivalent to <code>getCurrentLevel() == 0</code>. * </p> * * @return true if the current node is the root node, false otherwise */ protected boolean isRoot() { return currentLevel == 0; } /** * <p> Returns true if the current node has children, false otherwise. * This is equivalent to <code>numberOfChildren() == 0</code>. * </p> * * @return true if the current node has children, false otherwise */ protected boolean hasChildren() { return currentNode.getNumberOfChildren() > 0; } /** * <p> Returns the number of children the current node has. * This is always a non-negative number. * </p> * * @return the number of children of the current node */ protected int numberOfChildren() { return currentNode.getNumberOfChildren(); } /** * <p> Returns the current level (or depth). * </p> * <p> The level increases on calls to {@link #firstChild()} or {@link #nextChild()}. * The level decreases on calls to {@link #parent()}. * On every other method call the level stays the same. * </p> * * @return the current level in the tree */ protected int getCurrentLevel() { return currentLevel; } /** * <p> Returns the index number of the current element at the current level. * This is -1 before a call to any other method. * </p> * <p> Example: * <pre> * firstChild(); * System.out.println(currentIndex()); // 0 * nextSibling(); * System.out.println(currentIndex()); // 1 * nextSibling(); * System.out.println(currentIndex()); // 2 * </pre> * </p> * * @return the index of the current element at the current level */ protected int currentIndex() { return this.childIndexes[this.currentLevel]; } /** * <p> Returns the data of the current element. * </p> * * @return the data of the current element */ protected E currentData() { if (currentLevel == 0) { this.childIndexes[0] = 0; } return currentNode.getData(); } /** * This method increases the private childIndex array. * It is called only if the childIndex array becomes too small * and must be resized. */ private void increaseIndexes() { // System.out.println("Need to increase index"); final int[] newIndexes = new int[2 * childIndexes.length]; System.arraycopy(childIndexes, 0, newIndexes, 0, childIndexes.length); Arrays.fill(newIndexes, childIndexes.length, newIndexes.length, -1); this.childIndexes = newIndexes; // System.out.println("Increased indexes: " + Arrays.toString(this.childIndexes)); } /** * <p> This method goes to the parent node of the current node. * The level is reduced by one after a call to this method. * The data of the parent element is returned as by {@link #currentData()}. * </p> * * @return the parent element's data * @throws NoSuchElementException if this method is called on the root node */ protected E parent() { if (isRoot()) { throw new NoSuchElementException("can not go to parent of root"); } this.currentNode = this.currentNode.getParent(); --this.currentLevel; if (isRoot()) { this.siblingIterator = Iterators.emptyIterator(); } else { this.siblingIterator = this.currentNode.getParent().getChildren().iterator(); if (currentIndex() >= 0) { Iterators.get(this.siblingIterator, currentIndex()); } } return currentData(); } /** * <p> This method goes to the first child node of the current node. * The level is increased by one after a call to this method. * The data of the child element is returned as by {@link #currentData()}. * </p> * * @return the data of the first child * @throws NoSuchElementException if the current node has no children * @see #hasChildren() */ protected E firstChild() { if (currentLevel + 1 >= childIndexes.length) increaseIndexes(); this.siblingIterator = this.currentNode.getChildren().iterator(); this.currentNode = this.siblingIterator.next(); ++currentLevel; this.childIndexes[currentLevel] = 0; Arrays.fill(childIndexes, currentLevel + 1, childIndexes.length, -1); return this.currentNode.getData(); } /** * <p> Returns true if the current node has a next child, false otherwise. * </p> * * @return true if the current node has a next child, false otherwise. * @see #nextChild() */ protected boolean hasNextChild() { if (currentNode.getNumberOfChildren() == 0) { return false; } else if (currentLevel + 1 >= this.childIndexes.length) { return true; } else { return this.childIndexes[currentLevel + 1] + 1 < currentNode.getNumberOfChildren(); } } /** * <p> This method goes to the next child node of the current node. * This method is only useful in conjunction with {@link #parent()}, * because the last visited child node is saved when going to the parent. * This means that <code>parent(); nextChild();</code> is equivalent to <code>nextSibling();</code>. * </p> * <p> The level is increased by one after a call to this method. * The data of the child element is returned as by {@link #currentData()}. * </p> * * @return the data of the next child * @throws NoSuchElementException if the current node has no more children * @see #hasNextChild() */ protected E nextChild() { if (currentLevel + 1 >= childIndexes.length) increaseIndexes(); if (this.childIndexes[currentLevel + 1] + 1 >= this.currentNode.getNumberOfChildren()) { throw new NoSuchElementException(); } ++this.currentLevel; this.childIndexes[currentLevel] += 1; this.siblingIterator = this.currentNode.getChildren().iterator(); this.currentNode = Iterators.get(this.siblingIterator, currentIndex()); return this.currentNode.getData(); } /** * Returns true if the current node has a next sibling, false otherwise. * The root node always returns false. * @return true if next sibling exists, false otherwise */ protected boolean hasNextSibling() { return siblingIterator.hasNext(); } /** * Advances the current node to its next sibling * and returns the (new) current node. * May throw a {@link NoSuchElementException} if no next sibling exists. * The root node always throws this exception. * @return the next sibling * @throws NoSuchElementException if no next sibling exists */ protected E nextSibling() { this.currentNode = siblingIterator.next(); this.childIndexes[currentLevel] += 1; Arrays.fill(childIndexes, currentLevel + 1, childIndexes.length, -1); return this.currentNode.getData(); } }
true
b5891a8fdb7b7eec83c7e172aebb412c7a2afef0
Java
Bekbolisemo/AndroidDz.8
/app/src/main/java/com/example/androiddz8/xml/ModelFirstFr.java
UTF-8
606
2.46875
2
[]
no_license
package com.example.androiddz8.xml; public class ModelFirstFr { private int imageFamily; private String nameFamily; public ModelFirstFr(int imageFamily, String nameFamily) { this.imageFamily = imageFamily; this.nameFamily = nameFamily; } public int getImageFamily() { return imageFamily; } public void setImageFamily(int imageFamily) { this.imageFamily = imageFamily; } public String getNameFamily() { return nameFamily; } public void setNameFamily(String nameFamily) { this.nameFamily = nameFamily; } }
true
ea7eba25f793e4853b725cd3e1831f81604483fb
Java
twocater/Study
/src/main/java/com/cpaladin/study/jms/activemq/ActiveMqTemplate.java
UTF-8
743
2.015625
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 com.cpaladin.study.jms.activemq; import javax.jms.Connection; import javax.jms.ConnectionFactory; import javax.jms.JMSException; import org.springframework.jms.core.JmsTemplate; /** * * @author cpaladin */ public class ActiveMqTemplate { private ConnectionFactory connectionFactory; public ActiveMqTemplate(ConnectionFactory connectionFactory) { this.connectionFactory = connectionFactory; } public Connection createConnection() throws JMSException { return this.connectionFactory.createConnection(); } }
true
36a6d9fc58d4fa627604e30e4fac8559d656cead
Java
kknet/hermes
/hermes-main/src/main/java/com/jlfex/hermes/main/InvestController.java
UTF-8
17,086
1.632813
2
[ "Apache-2.0" ]
permissive
package com.jlfex.hermes.main; import java.io.UnsupportedEncodingException; import java.math.BigDecimal; import java.util.Date; import java.util.List; import javax.servlet.http.HttpServletRequest; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Controller; import org.springframework.ui.Model; import org.springframework.web.bind.annotation.PathVariable; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.ResponseBody; import com.alibaba.fastjson.JSONObject; import com.jlfex.hermes.common.App; import com.jlfex.hermes.common.AppUser; import com.jlfex.hermes.common.Logger; import com.jlfex.hermes.common.Result; import com.jlfex.hermes.common.Result.Type; import com.jlfex.hermes.common.cache.Caches; import com.jlfex.hermes.common.utils.Calendars; import com.jlfex.hermes.common.utils.Strings; import com.jlfex.hermes.model.Dictionary; import com.jlfex.hermes.model.Invest; import com.jlfex.hermes.model.InvestProfit; import com.jlfex.hermes.model.Loan; import com.jlfex.hermes.model.LoanAuth; import com.jlfex.hermes.model.LoanLog; import com.jlfex.hermes.model.Repay; import com.jlfex.hermes.model.User; import com.jlfex.hermes.model.UserAccount; import com.jlfex.hermes.service.DictionaryService; import com.jlfex.hermes.service.InvestProfitService; import com.jlfex.hermes.service.InvestService; import com.jlfex.hermes.service.LabelService; import com.jlfex.hermes.service.LoanService; import com.jlfex.hermes.service.ProductService; import com.jlfex.hermes.service.PropertiesService; import com.jlfex.hermes.service.RepayService; import com.jlfex.hermes.service.UserInfoService; import com.jlfex.hermes.service.pojo.InvestInfo; import com.jlfex.hermes.service.pojo.LoanUserInfo; /** * @author chenqi * @version 1.0, 2013-12-23 * @since 1.0 * */ @Controller @RequestMapping("/invest") public class InvestController { /** 理财业务接口 */ @Autowired private LoanService loanService; @Autowired private ProductService productService; @Autowired private InvestService investService; @Autowired private InvestProfitService investProfitService; @Autowired private UserInfoService userInfoService; /** 系统属性业务接口 */ @Autowired private PropertiesService propertiesService; @Autowired private RepayService repayService; @Autowired private DictionaryService dictionaryService; @Autowired private LabelService labelService; // 正在招标中的Cache的info private static final String CACHE_LOAN_DEADLINE_PREFIX = "com.jlfex.hermes.cache.loan.deadline."; private static final String INVEST_BID_MULTIPLE = "invest.bid.multiple"; @RequestMapping("checkMoneyMore") @ResponseBody public JSONObject checkMoneyMore(BigDecimal investamount, String loanid) { Logger.info("investamount:" + investamount + "loanid:" + loanid); Loan loan = loanService.loadById(loanid); BigDecimal remain = loan.getAmount().subtract(loan.getProceeds()); Logger.info("Remain:" + remain); JSONObject jsonObj = new JSONObject(); // 大于返回false提示不成功信息 if (investamount.compareTo(remain) == 1) { jsonObj.put("investamount", false); } else { jsonObj.put("investamount", true); } return jsonObj; } @RequestMapping("checkMoneyLess") @ResponseBody public JSONObject checkMoneyLess(BigDecimal investamount) { Logger.info("investamount:" + investamount); AppUser curUser = App.current().getUser(); UserAccount userAccount = userInfoService.loadByUserIdAndType(curUser.getId(), UserAccount.Type.CASH); BigDecimal balance = userAccount.getBalance(); Logger.info("balance:" + balance); JSONObject jsonObj = new JSONObject(); // 大于返回false提示不成功信息 if (investamount.compareTo(balance) == 1) { jsonObj.put("investamount", false); } else { jsonObj.put("investamount", true); } return jsonObj; } /** * @param mode * @return */ @RequestMapping("/display") public String display(Model model) { App.checkUser(); List<Dictionary> loanPurposeList = dictionaryService.findByTypeCode("loan_purpose"); model.addAttribute("loanpurposes", loanPurposeList); List<Repay> repayList = repayService.findAll(); model.addAttribute("repays", repayList); model.addAttribute("nav", "invest"); return "invest/display"; } /** * 索引 * * @param model * @return */ @RequestMapping("/index") public String index(Model model) { String page = "0",size = "10"; model.addAttribute("purposes", dictionaryService.findByTypeCode("loan_purpose")); model.addAttribute("repays", repayService.findAll()); model.addAttribute("nav", IndexController.HomeNav.INVEST); model.addAttribute("loans",investService.investIndexLoanList(page, size, Loan.LoanKinds.NORML_LOAN)); model.addAttribute("assignLoans",investService.investIndexLoanList(page, size, Loan.LoanKinds.OUTSIDE_ASSIGN_LOAN)); return "invest/index"; } // // /** // * 和服务器时间相减,计算截至日期 // * // * @param request // * @param model // * @return // */ // @RequestMapping("/caldeadline") // @ResponseBody // public String caldeadline(String deadline, Model model) { // try { // if (!Strings.blank(deadline)) { // int day = 24 * 60 * 60 * 1000; // int hour = 60 * 60 * 1000; // int minute = 60 * 1000; // int second = 1000; // Date end = Calendars.parseDateTime(deadline); // Date start = new Date(); // long endTime = end.getTime(); // long startTime = start.getTime(); // if (endTime - startTime > 0) { // long days = (endTime - startTime) / day;// 化为天 // long hours = (endTime - startTime) % day / hour;// 化为时 // long minutes = (endTime - startTime) % day % hour / minute;// 化为分 // long seconds = (endTime - startTime) % day % hour % minute / second;// // 化为分 // return String.valueOf(days) + "天" + String.valueOf(hours) + "时" + // String.valueOf(minutes) + "分" + String.valueOf(seconds) + "秒"; // } // } // return ""; // } catch (Exception e) { // return ""; // } // } /** * 投标操作 * * @param request * @param model * @return */ @RequestMapping("/bid") @ResponseBody public Result bid(String loanid, String investamount, String otherrepayselect) { Result result = new Result(); try { App.checkUser(); } catch (Exception ex) { result.setType(Type.WARNING); return result; } AppUser curUser = App.current().getUser(); User user = userInfoService.findByUserId(curUser.getId()); Logger.info("loanid:" + loanid + ",investamount:" + investamount + ",otherrepayselect :" + otherrepayselect); boolean bidResult = investService.bid(loanid, user, new BigDecimal(investamount), otherrepayselect); if (bidResult) { result.setType(Type.SUCCESS); } else { result.setType(Type.FAILURE); } return result; } @RequestMapping("/bidsuccess") public String bidsuccess(String investamount, String loanid, Model model) { App.checkUser(); model.addAttribute("nav", "invest"); model.addAttribute("investamount", investamount); model.addAttribute("loanid", loanid); // 返回视图 return "invest/bidsuccess"; } @RequestMapping("/bidfull") public String bidfull(Model model) { App.checkUser(); model.addAttribute("nav", "invest"); // 返回视图 return "invest/bidfull"; } /** * 计算预期收益 * * @param request * @return */ @RequestMapping("/calmaturegain") @ResponseBody public BigDecimal calmaturegain(HttpServletRequest request) { String loanid = request.getParameter("loanid"); String investamount = request.getParameter("investamount"); Logger.info("loanid:" + loanid + "investamount:" + investamount); Loan loan = loanService.loadById(loanid); BigDecimal maturegain = repayService.getRepayMethod(loan.getRepay().getId()).getProceeds(loan, null, new BigDecimal(investamount)); return maturegain; } /** * 借款列表查询 * * @param purpose * @param raterange * @param periodrange * @param repayname * @param page * @param size * @param orderByField * @param orderByDirection * @param model * @return */ @RequestMapping("/indexsearch") public String indexsearch(String purpose, String raterange, String periodrange, String repayname, String page, String size, String orderByField, String orderByDirection,String loanKind, Model model) { Logger.info("理财列表查询参数: purpose=" + getUTFFormat(purpose) + ",raterange=" + getUTFFormat(raterange) + ",periodrange=" + getUTFFormat(periodrange) + ",repayname=" + getUTFFormat(repayname)+",loanKind="+getUTFFormat(loanKind)); model.addAttribute("loans", investService.findByJointSql(getUTFFormat(purpose), getUTFFormat(raterange), getUTFFormat(periodrange), getUTFFormat(repayname), page, size, orderByField, orderByDirection,loanKind)); return "invest/loandata"; } /** * 把乱码解析成中文 * * @param src * @return */ private String getUTFFormat(String src) { if (!Strings.empty(src)) { String dest = ""; try { dest = new String(src.getBytes("iso-8859-1"), "utf-8"); } catch (UnsupportedEncodingException e) { Logger.error("getUTFFormat Message Error:" + e.getMessage()); } return dest; } else return ""; } /** * 借款明细 * * @param id * @param model * @return */ /** * @param model * @param loanid * @return */ @RequestMapping("/info") public String info(Model model, String loanid) { try { App.checkUser(); } catch (Exception e) { return "redirect:/userIndex/skipSignIn"; } Logger.info("loanid:" + loanid); Loan loan = loanService.loadById(loanid); model.addAttribute("loan", loan); Dictionary dictionary = dictionaryService.loadById(loan.getPurpose()); model.addAttribute("purpose", dictionary.getName()); model.addAttribute("product", loan.getProduct()); model.addAttribute("repay", loan.getProduct().getRepay()); model.addAttribute("user", loan.getUser()); if(!Loan.LoanKinds.NORML_LOAN.equals(loan.getLoanKind())){ loan.getCreditorId(); } // 从借款日志表里取开始投标的起始时间 if (Caches.get(CACHE_LOAN_DEADLINE_PREFIX + loanid) == null) { LoanLog loanLogStartInvest = loanService.loadLogByLoanIdAndType(loanid, LoanLog.Type.START_INVEST); if (loanLogStartInvest != null && loanLogStartInvest.getDatetime() != null) { String duration = String.valueOf(loan.getDeadline()) + "d"; Date datetimeloanLogStartInvest = loanLogStartInvest.getDatetime(); Date deadline = Calendars.add(datetimeloanLogStartInvest, duration); Caches.set(CACHE_LOAN_DEADLINE_PREFIX + loanid, deadline, "7d"); } } if (Caches.get(CACHE_LOAN_DEADLINE_PREFIX + loanid) != null) { Date deadline = Caches.get(CACHE_LOAN_DEADLINE_PREFIX + loanid, Date.class); Date start = new Date(); long endTime = deadline.getTime(); long startTime = start.getTime(); if (endTime - startTime > 0) { model.addAttribute("remaintime", String.valueOf(endTime - startTime)); } else { model.addAttribute("remaintime", 0); } // 投标最后期限 } else { model.addAttribute("remaintime", 0); } LoanUserInfo loanUserInfo = loanService.loadLoanUserInfoByUserId(App.user().getId()); model.addAttribute("loanUserInfo", loanUserInfo); List<Invest> investList = investService.findByLoan(loan); model.addAttribute("invests", investList); List<LoanAuth> loanAuthlist = loanService.findLoanAuthByLoan(loan); model.addAttribute("loanauths", loanAuthlist); model.addAttribute("nav", "invest"); //读取投标金额倍数设置 String investBidMultiple = App.config(INVEST_BID_MULTIPLE); model.addAttribute("investBidMultiple", investBidMultiple); // 返回视图 return "invest/info"; } /** * 我的理财 * * @param userid * @param model * @return */ @RequestMapping("/myinvest") public String myinvest(Model model) { App.checkUser(); AppUser curUser = App.current().getUser(); User user = userInfoService.findByUserId(curUser.getId()); // 已获收益 BigDecimal allProfitSum = investProfitService.loadSumAllProfitByUserAndInStatus(user, new String[] { InvestProfit.Status.ALREADY, InvestProfit.Status.OVERDUE, InvestProfit.Status.ADVANCE }); // 利息 BigDecimal interestSum = investProfitService.loadInterestSumByUserAndInStatus(user, new String[] { InvestProfit.Status.ALREADY, InvestProfit.Status.OVERDUE, InvestProfit.Status.ADVANCE }); // 罚息 BigDecimal overdueInterestSum = investProfitService.loadOverdueInterestSumByUserAndInStatus(user, new String[] { InvestProfit.Status.ALREADY, InvestProfit.Status.OVERDUE, InvestProfit.Status.ADVANCE }); List<InvestInfo> investInfoList = investService.findByUser(user,Loan.LoanKinds.NORML_LOAN); int investSuccessCount = 0; for (InvestInfo investInfo : investInfoList) { if (Invest.Status.COMPLETE.equals(investInfo.getStatus())) { investSuccessCount = investSuccessCount + 1; } } if (allProfitSum == null) allProfitSum = BigDecimal.ZERO; if (interestSum == null) interestSum = BigDecimal.ZERO; if (overdueInterestSum == null) overdueInterestSum = BigDecimal.ZERO; model.addAttribute("allProfitSum", allProfitSum.setScale(2, BigDecimal.ROUND_UP)); model.addAttribute("interestSum", interestSum.setScale(2, BigDecimal.ROUND_UP)); model.addAttribute("overdueInterestSum", overdueInterestSum.setScale(2, BigDecimal.ROUND_UP)); model.addAttribute("successCount", investSuccessCount); model.addAttribute("invests", investInfoList); model.addAttribute("nav", "invest"); // 返回视图 return "invest/myinvest"; } /** * 我的理财的明细 * * @param investid * @param model * @return */ @RequestMapping("/myinvestinfo/{invest}") public String myinvestinfo(@PathVariable("invest") String investid, HttpServletRequest request, Model model) { App.checkUser(); Invest invest = investService.loadById(investid); // String page = request.getParameter("page"); // String size = request.getParameter("size"); Loan loan = invest.getLoan(); model.addAttribute("loan", loan); Dictionary dictionary = dictionaryService.loadById(loan.getPurpose()); model.addAttribute("product", loan.getProduct()); model.addAttribute("purpose", dictionary.getName()); model.addAttribute("repay", loan.getProduct().getRepay()); model.addAttribute("user", loan.getUser()); model.addAttribute("investprofitinfos", investProfitService.getInvestProfitRecords(invest)); model.addAttribute("nav", "invest"); // 返回视图 return "invest/myinvestinfo"; } /** * 我的债权 * @param userid * @param model * @return */ @RequestMapping("/myCredit") public String myCredit(Model model) { App.checkUser(); AppUser curUser = App.current().getUser(); User user = userInfoService.findByUserId(curUser.getId()); // 已获收益 InvestProfit investProfit = investProfitService.sumAllProfitByAssignLoan(user, Loan.LoanKinds.OUTSIDE_ASSIGN_LOAN, new String[] { InvestProfit.Status.ALREADY, InvestProfit.Status.OVERDUE, InvestProfit.Status.ADVANCE }); BigDecimal allProfitSum = BigDecimal.ZERO;//总收益 BigDecimal interestSum = BigDecimal.ZERO;// 利息收益总数 BigDecimal overdueInterestSum =BigDecimal.ZERO; //罚息收益总数 if(investProfit !=null){ if(investProfit.getInterestAmount()!=null){ interestSum = investProfit.getInterestAmount(); } if(investProfit.getOverdueAmount()!=null){ overdueInterestSum = investProfit.getOverdueAmount(); } allProfitSum = allProfitSum.add(interestSum).add(overdueInterestSum); } List<InvestInfo> investInfoList = investService.findByUser(user,Loan.LoanKinds.OUTSIDE_ASSIGN_LOAN); int investSuccessCount = 0; for (InvestInfo investInfo : investInfoList) { if (Invest.Status.COMPLETE.equals(investInfo.getStatus())) { investSuccessCount = investSuccessCount + 1; } } if (allProfitSum == null) allProfitSum = BigDecimal.ZERO; if (interestSum == null) interestSum = BigDecimal.ZERO; if (overdueInterestSum == null) overdueInterestSum = BigDecimal.ZERO; model.addAttribute("allProfitSum", allProfitSum.setScale(2, BigDecimal.ROUND_UP)); model.addAttribute("interestSum", interestSum.setScale(2, BigDecimal.ROUND_UP)); model.addAttribute("overdueInterestSum", overdueInterestSum.setScale(2, BigDecimal.ROUND_UP)); model.addAttribute("successCount", investSuccessCount); model.addAttribute("invests", investInfoList); model.addAttribute("nav", "invest"); // 返回视图 return "invest/mycredit"; } }
true
bded0e00a356197384bc9c6f7269d7ccc9fe285b
Java
morristech/Inside_Android_Testing
/InstrumentationSample/src/com/fernandocejas/InstrumentationSample/model/Calculator.java
UTF-8
316
2.53125
3
[ "Apache-2.0" ]
permissive
package com.fernandocejas.InstrumentationSample.model; /** * Copyright (c) Tuenti Technologies. All rights reserved. * * @author "Fernando Cejas" <fcejas@tuenti.com> */ public class Calculator { public Calculator() { //empty } public int sum(int firstNumber, int secondNumber){ return (firstNumber + secondNumber); } }
true
4c683851e473a5d7fe80f973fe233f6d3c865ddd
Java
grey920/FinalEeum
/FinalEeum/src/main/java/com/kh/eeum/domain/Portfolio.java
UTF-8
3,750
2.03125
2
[]
no_license
package com.kh.eeum.domain; import org.springframework.web.multipart.MultipartFile; public class Portfolio { // PF_EXID VARCHAR2(40) NOT NULL, // PF_LOC VARCHAR2(300), -- 전문가 활동 지역 // PF_GRADE NUMBER NOT NULL,-- 회원 분류 : 0-디딤돌, 1-마루, 2-우주, 3-용마루 // PF_CATE NUMBER NOT NULL,-- 전문가 분야 : 0-청소, 1-방역, 2-수리 // PF_TIME VARCHAR2(100) NOT NULL, -- 전문가 연락 가능 시간 // PF_DESC VARCHAR2(4000), -- 경력 상세설명 // PF_OR_LI VARCHAR2(100), // PF_SV_LI VARCHAR2(100), -- 자격증 이미지 파일 // PF_OR_OP VARCHAR2(100), -- 사업자번호 이미지 파일 // PF_SV_OP VARCHAR2(100), // PF_INTRO VARCHAR2(300) NOT NULL, -- 전문가 소개말 // PF_One VARCHAR2(100), -- 전문가 한마디 // PF_PROFILE VARCHAR2(4000) NOT NULL, // PF_SAVEPROFILE VARCHAR2(4000) NOT NULL // private String PF_EXID; private String PF_LOC; private int PF_GRADE; private int PF_CATE; private String PF_TIME; private String PF_DESC; private String PF_OR_LI; private String PF_SV_LI="/defaultPic.png"; private String PF_OR_OP; private String PF_SV_OP="/defaultPic.png"; private String PF_INTRO; private String PF_One; private String PF_PROFILE= "/profile.png"; private String PF_SAVEPROFILE= "/profile.png"; private MultipartFile uploadfilePRO; private MultipartFile uploadfile1; private MultipartFile uploadfile2; public String getPF_EXID() { return PF_EXID; } public void setPF_EXID(String pF_EXID) { PF_EXID = pF_EXID; } public String getPF_LOC() { return PF_LOC; } public void setPF_LOC(String pF_LOC) { PF_LOC = pF_LOC; } public int getPF_GRADE() { return PF_GRADE; } public void setPF_GRADE(int pF_GRADE) { PF_GRADE = pF_GRADE; } public int getPF_CATE() { return PF_CATE; } public void setPF_CATE(int pF_CATE) { PF_CATE = pF_CATE; } public String getPF_TIME() { return PF_TIME; } public void setPF_TIME(String pF_TIME) { PF_TIME = pF_TIME; } public String getPF_DESC() { return PF_DESC; } public void setPF_DESC(String pF_DESC) { PF_DESC = pF_DESC; } public String getPF_OR_LI() { return PF_OR_LI; } public void setPF_OR_LI(String pF_OR_LI) { PF_OR_LI = pF_OR_LI; } public String getPF_SV_LI() { return PF_SV_LI; } public void setPF_SV_LI(String pF_SV_LI) { PF_SV_LI = pF_SV_LI; } public String getPF_OR_OP() { return PF_OR_OP; } public void setPF_OR_OP(String pF_OR_OP) { PF_OR_OP = pF_OR_OP; } public String getPF_SV_OP() { return PF_SV_OP; } public void setPF_SV_OP(String pF_SV_OP) { PF_SV_OP = pF_SV_OP; } public String getPF_INTRO() { return PF_INTRO; } public void setPF_INTRO(String pF_INTRO) { PF_INTRO = pF_INTRO; } public String getPF_One() { return PF_One; } public void setPF_One(String pF_One) { PF_One = pF_One; } public String getPF_PROFILE() { return PF_PROFILE; } public void setPF_PROFILE(String pF_PROFILE) { PF_PROFILE = pF_PROFILE; } public String getPF_SAVEPROFILE() { return PF_SAVEPROFILE; } public void setPF_SAVEPROFILE(String pF_SAVEPROFILE) { PF_SAVEPROFILE = pF_SAVEPROFILE; } public MultipartFile getUploadfile1() { return uploadfile1; } public void setUploadfile1(MultipartFile uploadfile1) { this.uploadfile1 = uploadfile1; } public MultipartFile getUploadfile2() { return uploadfile2; } public void setUploadfile2(MultipartFile uploadfile2) { this.uploadfile2 = uploadfile2; } public MultipartFile getUploadfilePRO() { return uploadfilePRO; } public void setUploadfilePRO(MultipartFile uploadfilePRO) { this.uploadfilePRO = uploadfilePRO; } }
true
752689cfe4a50716e021b23854cf2809b70ba00f
Java
danivarelas/web-dev-program
/week 2/demo/src/main/java/com/example/demo/api/Controller/BookController.java
UTF-8
2,152
2.46875
2
[]
no_license
package com.example.demo.api.Controller; import java.util.List; import java.util.UUID; import java.util.logging.*; import javax.servlet.http.HttpServletRequest; import javax.validation.Valid; import com.example.demo.api.Model.Book; import com.example.demo.api.Service.BookService; import com.example.demo.api.Util.JWTGenerator; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.web.bind.annotation.*; import io.jsonwebtoken.SignatureException; import lombok.NonNull; @CrossOrigin(origins = "*", methods= {RequestMethod.GET, RequestMethod.POST, RequestMethod.PUT, RequestMethod.DELETE}) @RequestMapping("api/v1/book") @RestController public class BookController { private final BookService bookService; private HttpServletRequest request; private final static Logger LOGGER = Logger.getLogger(AuthorController.class.getName()); @Autowired public BookController(BookService bookService, HttpServletRequest request) { this.bookService = bookService; this.request = request; } @PostMapping public void addBook(@RequestBody Book book) { //JWTGenerator.validateToken(request.getHeader("authorization")); bookService.addBook(book); } @GetMapping public List<Book> getAllBooks() { //JWTGenerator.validateToken(request.getHeader("authorization")); return bookService.selectAllBooks(); } // @GetMapping(path = "{id}") // public Book getBookById(@PathVariable("id") UUID id) { // //JWTGenerator.validateToken(request.getHeader("authorization")); // return bookService.selectBookById(id).orElse(null); // } // // @DeleteMapping(path = "{id}") // public void deleteBook(@PathVariable("id") UUID id) { // //JWTGenerator.validateToken(request.getHeader("authorization")); // bookService.deleteBook(id); // } // // @PutMapping(path = "{id}") // public void updateBook(@PathVariable("id") UUID id, @Valid @NonNull @RequestBody Book book) { // //JWTGenerator.validateToken(request.getHeader("authorization")); // bookService.updateBook(id, book); // } }
true
0f67d58a07e8ad560b2a7d4c7c6c4be56c881ae1
Java
stefanocereda/sheepland
/andrea.celli-stefano1.cereda/src/main/java/it/polimi/deib/provaFinale2014/andrea/celli_stefano1/cereda/gameModel/players/PlayerDouble.java
UTF-8
1,682
3.328125
3
[]
no_license
package it.polimi.deib.provaFinale2014.andrea.celli_stefano1.cereda.gameModel.players; import it.polimi.deib.provaFinale2014.andrea.celli_stefano1.cereda.gameModel.objectsOfGame.Road; /** * This is the player used in the games with two clients * * @author Stefano * */ public class PlayerDouble extends Player { private static final long serialVersionUID = -2210970681587172191L; /** The position of the second shepherd */ private Road secondposition; /** * This variable is set at the beginning of each turn and indicates if the * player wants to use the first or the second shepherd */ private boolean usingSecond = false; /** Set if this player is using the second player in this turn */ public void setShepherd(boolean usingSecond) { this.usingSecond = usingSecond; } /** * Move the controlled shepherd in a new road, without rules checking. * * @param newRoad * The new road */ @Override public void move(Road newRoad) { if (usingSecond) { secondposition = newRoad; } else { super.move(newRoad); } } /** * Get the position of the controlled shepherd */ @Override public Road getPosition() { if (usingSecond) { return secondposition; } return super.getPosition(); } /** @return the position of the second shepherd */ public Road getSecondposition() { return secondposition; } /** @return the position of the first shepherd */ public Road getFirstPosition() { return super.getPosition(); } /** @return true if the player is using his second shepherd */ public boolean getShepherd() { return usingSecond; } }
true
af7cff95f7add2e3c298e1f2396eb92ba82d9378
Java
namannigam-zz/mastering-jfx9
/src/sample/chapter/four/Loaders.java
UTF-8
417
1.984375
2
[]
no_license
package sample.chapter.four; import javafx.fxml.FXMLLoader; import javafx.scene.Parent; import java.io.IOException; public class Loaders { public void referenceFXML() throws IOException { FXMLLoader loader = new FXMLLoader(getClass().getResource("FirstDocument.fxml")); loader.load(); FirstController controller = loader.getController(); Parent root = loader.getRoot(); } }
true
015cf1ff8f775f4298872a0b5f663ca8d2aa7e8c
Java
kiegroup/drools-chance
/drools-shapes/drools-shapes-generator/src/main/java/org/drools/semantics/builder/model/OntoModel.java
UTF-8
3,592
1.828125
2
[ "Apache-2.0" ]
permissive
/* * Copyright 2011 JBoss 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 org.drools.semantics.builder.model; import org.drools.semantics.builder.model.hierarchy.DatabaseModelProcessor; import org.drools.semantics.builder.model.hierarchy.FlatModelProcessor; import org.drools.semantics.builder.model.hierarchy.HierarchicalModelProcessor; import org.drools.semantics.builder.model.hierarchy.ModelHierarchyProcessor; import org.drools.semantics.builder.model.hierarchy.NullModelProcessor; import org.drools.semantics.builder.model.hierarchy.OptimizedModelProcessor; import org.drools.semantics.builder.model.hierarchy.VariantModelProcessor; import org.drools.semantics.util.area.AreaTxn; import org.drools.util.CodedHierarchy; import org.semanticweb.owlapi.model.OWLOntology; import java.util.List; import java.util.Set; public interface OntoModel extends Cloneable { public static enum Mode { HIERARCHY( new HierarchicalModelProcessor() ), FLAT( new FlatModelProcessor() ), VARIANT( new VariantModelProcessor() ), OPTIMIZED( new OptimizedModelProcessor() ), DATABASE( new DatabaseModelProcessor() ), NONE( new NullModelProcessor() ); private ModelHierarchyProcessor processor; Mode( ModelHierarchyProcessor prox ) { processor = prox; } public ModelHierarchyProcessor getProcessor() { return processor; } } public OWLOntology getOntology(); public void setOntology( OWLOntology onto ); public String getDefaultPackage(); public void setDefaultPackage( String pack ); public Set<String> getAllPackageNames(); public String getName(); public void setName( String name ); public String getDefaultNamespace(); public void setDefaultNamespace( String ns ); public List<Concept> getConcepts(); public Concept getConcept( String id ); public void addConcept( Concept con ); public Concept removeConcept( Concept con ); public Set<Individual> getIndividuals(); public void addIndividual( Individual i ); public Individual removeIndividual( Individual i ); public Set<SubConceptOf> getSubConcepts(); public void addSubConceptOf( SubConceptOf sub ); public SubConceptOf getSubConceptOf( String sub, String sup ); public boolean removeSubConceptOf( SubConceptOf sub ); public Set<PropertyRelation> getProperties(); public void addProperty( PropertyRelation rel ); public PropertyRelation removeProperty( PropertyRelation rel ); public PropertyRelation getProperty( String iri ); public void sort(); public boolean isHierarchyConsistent(); public Mode getMode(); public ClassLoader getClassLoader(); public void setClassLoader( ClassLoader classLoader ); public void reassignConceptCodes(); public CodedHierarchy<Concept> getConceptHierarchy(); public void buildAreaTaxonomy(); public AreaTxn<Concept,PropertyRelation> getAreaTaxonomy(); }
true
fbafaae2880df40ddca4a90fa9795a6df0185795
Java
jensnicolay/streme
/streme/src/streme/lang/analysis/IpdAnalyzer.java
UTF-8
2,721
2.328125
2
[]
no_license
package streme.lang.analysis; import java.util.Collections; import java.util.Set; import streme.lang.ast.Application; import streme.lang.ast.AstAnalyzer; import streme.lang.ast.Node; import streme.lang.ast.Var; import streme.lang.ast.impl.StremeDataCompiler; import streme.lang.ast.impl.TagPrinter; import streme.lang.data.Parser2; import streme.lang.eval.nd.NdAnalysisStreme; public class IpdAnalyzer implements AstAnalyzer<IpdAnalysis> { private int k; private boolean gc; private VarPointerAnalysis varPointerAnalysis; public IpdAnalyzer(int k, boolean gc, VarPointerAnalysis varPointerAnalysis) { super(); this.k = k; this.gc = gc; this.varPointerAnalysis = varPointerAnalysis; } public IpdAnalysis analyze(Node node) { final StatefulIpdAnalyzer ipda = new StatefulIpdAnalyzer(k, gc, varPointerAnalysis); ipda.analyze(node); return new IpdAnalysis() { public Set<AbstractVar<Time>> getWrites(Application application) { Set<AbstractVar<Time>> r = ipda.getWrites().get(application); if (r == null) { return Collections.emptySet(); } return r; } public Set<AbstractVar<Time>> getReads(Application application) { Set<AbstractVar<Time>> r = ipda.getReads().get(application); if (r == null) { return Collections.emptySet(); } return r; } public Set<State> getResult() { return ipda.getResult(); } public Set<Object> getValues(Var var) { return ipda.getValues(var); } public Set<Object> getMonoValues(Var var) { return ipda.getMonoValues(var); } }; } public static void main(String[] args) { String source = "(let ((l (list + - * /))) ((car l) 1 2))"; //String source = "(begin (define z 123) (define f (lambda () z)) (f) (f))"; // String source = "(begin (define counter (lambda (c) (if (zero? c) 'boem (counter (- c 1))))) (counter 2))"; // String source = "(letrec ((fib (lambda (n) (if (< n 2) n (let ((a (fib (- n 1))) (b (fib (- n 2)))) (+ a b)))))) (fib 3))"; //String source = "(let* ((z 0) (writez (lambda () (set! z 123))) (readz (lambda () z))) (cons (writez) (readz)))"; //String source = "(let* ((z 0) (writez (lambda () (set! z 123)))) (writez))"; Parser2 parser = new Parser2(); Object data = parser.parse(source); StremeDataCompiler compiler = new StremeDataCompiler(); Node ast = compiler.compile(data); NdAnalysisStreme querier = new NdAnalysisStreme(ast); System.out.println(querier.query("(ipd-result)")); querier.shutdown(); } }
true
083c9b31726e60a46b761d63d9e207869f230e5a
Java
EvilCodes/MyCruit
/src/com/oucre/pojo/User.java
UTF-8
2,487
2.390625
2
[]
no_license
package com.oucre.pojo; import javax.persistence.Column; import javax.persistence.Entity; import javax.persistence.GeneratedValue; import static javax.persistence.GenerationType.IDENTITY; import javax.persistence.Id; import javax.persistence.Table; /** * User entity. @author MyEclipse Persistence Tools */ @Entity @Table(name = "user", catalog = "mycruit") public class User implements java.io.Serializable { // Fields private Integer id; private Integer roleid; private String username; private String password; private String tel; private Integer uid; private String status; // Constructors /** default constructor */ public User() { } /** minimal constructor */ public User(Integer roleid, Integer uid) { this.roleid = roleid; this.uid = uid; } public User(Integer id, Integer roleid, String username, String password, String tel, Integer uid, String status) { super(); this.id = id; this.roleid = roleid; this.username = username; this.password = password; this.tel = tel; this.uid = uid; this.status = status; } public User(Integer id) { super(); this.id = id; } // Property accessors @Id @GeneratedValue(strategy = IDENTITY) @Column(name = "id", unique = true, nullable = false) public Integer getId() { return this.id; } public void setId(Integer id) { this.id = id; } @Column(name = "roleid") public Integer getRoleid() { return this.roleid; } public void setRoleid(Integer roleid) { this.roleid = roleid; } @Column(name = "username", length = 10) public String getUsername() { return this.username; } public void setUsername(String username) { this.username = username; } @Column(name = "password", length = 22) public String getPassword() { return this.password; } public void setPassword(String password) { this.password = password; } @Column(name = "tel") public String getTel() { return tel; } public void setTel(String tel) { this.tel = tel; } @Column(name = "uid") public Integer getUid() { return this.uid; } public void setUid(Integer uid) { this.uid = uid; } @Column(name = "status", length = 1) public String getStatus() { return this.status; } public void setStatus(String status) { this.status = status; } @Override public String toString() { return "User [id=" + id + ", roleid=" + roleid + ", username=" + username + ", password=" + password + ", tel=" + tel + ", uid=" + uid + ", status=" + status + "]"; } }
true
c517389f41a798961938ea3ff0e1286244d98df3
Java
sergevalevich/Game
/app/src/main/java/com/balinasoft/clever/ui/fragments/OfflineConfigFragment.java
UTF-8
3,603
1.953125
2
[]
no_license
package com.balinasoft.clever.ui.fragments; import android.support.v7.app.ActionBar; import android.support.v7.app.AppCompatActivity; import android.support.v7.widget.Toolbar; import android.view.View; import com.balinasoft.clever.R; import com.balinasoft.clever.model.Player; import com.balinasoft.clever.storage.model.Question; import com.balinasoft.clever.ui.activities.TourActivityOffline_; import com.balinasoft.clever.util.ConstantsManager; import org.androidannotations.annotations.EFragment; import org.androidannotations.annotations.ViewById; import java.net.SocketTimeoutException; import java.util.List; import rx.Subscription; import rx.android.schedulers.AndroidSchedulers; import rx.schedulers.Schedulers; import static com.balinasoft.clever.GameApplication.getUserCoins; @EFragment(R.layout.fragment_offline_config) public class OfflineConfigFragment extends ConfigFragmentBase { @ViewById(R.id.toolbar) Toolbar mToolbar; private Subscription mSubscription; @Override void setUpOtherViews() { setupActionBar(); } @Override boolean areEnoughCoins() { return getUserCoins() >= mBet; } @Override public void onStart() { super.onStart(); if (mSubscription != null) { setButtonClickable(false); notifyLoading(View.VISIBLE); getQuestions(); } } @Override public void onStop() { if (mSubscription != null && !mSubscription.isUnsubscribed()) mSubscription.unsubscribe(); clearQuestions(); setButtonClickable(true); notifyLoading(View.GONE); super.onStop(); } private void getQuestions() { mSubscription = mDataManager.getQuestions() .subscribeOn(Schedulers.io()) .observeOn(AndroidSchedulers.mainThread()) .subscribe(this::onNext, this::onError, this::onCompleted); } private void onNext(Question question) { mQuestions.add(question); } private void onError(Throwable throwable) { clearQuestions(); setButtonClickable(true); notifyLoading(View.GONE); notifyUserWith(throwable instanceof SocketTimeoutException ? mNetworkErrorMessage : throwable.getMessage()); } private void onCompleted() { if (mQuestions.size() == ConstantsManager.MAX_QUESTIONS_COUNT) startGame(); else { clearQuestions(); setButtonClickable(true); notifyLoading(View.GONE); } } private void startGame() { Question[] questions = new Question[mQuestions.size()]; questions = mQuestions.toArray(questions); List<Player> players = Player.get(mPlayersCount + 1,mBet); Player[] pls = new Player[players.size()]; pls = players.toArray(pls); TourActivityOffline_.intent(this) .bet(mBet) .parcelableQuestions(questions) .parcelablePlayers(pls) .start(); getActivity().finish(); } private void setupActionBar() { AppCompatActivity activity = (AppCompatActivity)getActivity(); activity.setSupportActionBar(mToolbar); ActionBar actionBar = activity.getSupportActionBar(); if (actionBar != null) { actionBar.setDisplayHomeAsUpEnabled(true); activity.setTitle(""); } } @Override void createGame() { setButtonClickable(false); notifyLoading(View.VISIBLE); getQuestions(); } }
true
8dc3d1ae09efc81399737f0a8b6c844f14109883
Java
pamwang/project-euler-solutions
/problem-3-largest-prime-factor/src/com/company/Main.java
UTF-8
869
3.75
4
[]
no_license
package com.company; //Problem #3 - Largest Prime factor of 600851475143 //Date: Sept.20.2020 //Note Playing catchup because I missed two days. public class Main { public static void main(String[] args) { //number of which we are finding the prime factor of long num = 600851475143L; //factors long factors = 2L; //iterate until num is reached while(factors < num){ //if the number can be divided by current factor if(num%factors==0){ //divide num by current factor num/=factors; } //otherwise iterate to next factor else{ factors++; } } //the largest factor will be the remainder of num after dividing out by all other possible numbers System.out.println(num); } }
true
75e2206501b4962a50f1a1bacd32ee070c99d982
Java
AmirhesamGhahari/CIBC-Information-System
/CIBC Bank/src/CIBC_Design/AccountActivity.java
UTF-8
20,783
3.296875
3
[]
no_license
package CIBC_Design; import java.io.File; import java.io.FileInputStream; import java.io.FileOutputStream; import java.io.ObjectInputStream; import java.io.ObjectOutputStream; import java.io.Serializable; import java.time.LocalDateTime; import java.util.ArrayList; import java.util.HashSet; /** * @author ahesam.gh * * acountactivity class responsible for holding an activity object for every operation of account classes. * */ public class AccountActivity implements Serializable{ /** * type of activity. it represents: * 1 for withdraw an amount * 2 for deposit an amount * 3 for creating an account * 4 for cancelling an account * 5 for suspending an account * 6 for reactivating an account * 7 for getting balance of an account * 8 for terminating an account * 9 for setting overdraft option of an account * 10 for setting credit limit or overdraft limit of an account * 11 for transferring an amount * */ private int activityType; /** * account that this activity has done for */ private Account mainAccount; /** * type of the account that has done this activity */ private String mainAccountType; /** * time of implementation of this activity */ private LocalDateTime time; /** * balance of account responsible for this transaction AFTER the transaction */ private double accountBalance; /** * amount of withdraw or deposit from or to an account * this field will be further initiated only for withdraw, deposit, transfer activities */ private double amount = -1; /** * an demadloadaccount which is result of cancellation or termination of an account. * this object will be further instanniated only for cancel and terminate activity. */ private DemandLoanAccount demandLoan = null; /** * variable showing if a withdraw from an account has been successful. * this variable will be further set only for withdraw activity. */ private boolean isSuccessful = false; /** * the destined account recieving an amount in a transfer activity. * this variable will be further instanciated only for transfer activity. */ private Account destinatedAccount = null; /** * the newly set overdraft option of a checking account in this activity */ private int newODOption = -1; /** * @param the newly set overdraft/credit limit of account responsible for this activity. */ private double newLimit = -1.00; /** * static arraylist responsible for holding the objects of accountactivity that each is made for * an activity. */ public static final ArrayList<AccountActivity> ACTIVITY_LOG = new ArrayList<AccountActivity>(); /** * c1 * @param ac1 account doing this activity * @param at1 type of activity * @param balance balance of account responsible for this transaction AFTER the transaction * * instanciate an accountactivity object. * this constructor is responsible for creation of an accountactivity object for these activities: * create an account * suspend an account * reactivate an account * getting the account balance */ public AccountActivity(Account ac1, int at1, double balance) { String accountType = ac1.getAccountType(); if(accountType.equals(CheckingAccount.ACCOUNT_TYPE)) { this.mainAccountType = CheckingAccount.ACCOUNT_TYPE; } if(accountType.equals(CreditAccount.ACCOUNT_TYPE)) { this.mainAccountType = CreditAccount.ACCOUNT_TYPE; } this.mainAccount = ac1; this.activityType = at1; this.accountBalance = balance; this.time = LocalDateTime.now(); AccountActivity.ACTIVITY_LOG.add(this); } /** * c2 * @param ac1 account doing this activity * @param at1 type of activity * @param dla1 the demandloanaccount made for this activity * @param balance balance of account responsible for this transaction AFTER the transaction * * instanciate an accountactivity object. * this constructor is responsible for creation of an accountactivity object for these activities: * cancel an account * terminate an account * */ public AccountActivity(Account ac1, int at1, DemandLoanAccount dla1, double balance) { String accountType = ac1.getAccountType(); if(accountType.equals(CheckingAccount.ACCOUNT_TYPE)) { this.mainAccountType = CheckingAccount.ACCOUNT_TYPE; } if(accountType.equals(CreditAccount.ACCOUNT_TYPE)) { this.mainAccountType = CreditAccount.ACCOUNT_TYPE; } this.mainAccount = ac1; this.activityType = at1; this.time = LocalDateTime.now(); this.demandLoan = dla1; this.accountBalance = balance; AccountActivity.ACTIVITY_LOG.add(this); } /** * c3 * * @param ac1 account doing this activity * @param at1 type of activity * @param am1 amount that is going to be deposited into account * @param balance balance of account responsible for this transaction AFTER the transaction * * instanciate an accountactivity object. * this constructor is responsible for creation of an accountactivity object for these activities: * deposit an amount in an account */ public AccountActivity(Account ac1, int at1, double am1 , double balance) { String accountType = ac1.getAccountType(); if(accountType.equals(CheckingAccount.ACCOUNT_TYPE)) { this.mainAccountType = CheckingAccount.ACCOUNT_TYPE; } if(accountType.equals(CreditAccount.ACCOUNT_TYPE)) { this.mainAccountType = CreditAccount.ACCOUNT_TYPE; } this.mainAccount = ac1; this.accountBalance = balance; this.activityType = at1; this.time = LocalDateTime.now(); this.amount = am1; AccountActivity.ACTIVITY_LOG.add(this); } /** * c4 * @param ac1 account doing this activity * @param at1 type of activity * @param am1 amount that is going to be withdrawn from an account * @param b1 determines if this withdrawal has been successful * @param balance balance of account responsible for this transaction AFTER the transaction * * instanciate an accountactivity object. * this constructor is responsible for creation of an accountactivity object for these activities: * withdraw an amount from an account */ public AccountActivity(Account ac1, int at1, double am1, boolean b1, double balance) { String accountType = ac1.getAccountType(); if(accountType.equals(CheckingAccount.ACCOUNT_TYPE)) { this.mainAccountType = CheckingAccount.ACCOUNT_TYPE; } if(accountType.equals(CreditAccount.ACCOUNT_TYPE)) { this.mainAccountType = CreditAccount.ACCOUNT_TYPE; } this.mainAccount = ac1; this.accountBalance = balance; this.activityType = at1; this.time = LocalDateTime.now(); this.isSuccessful = b1; this.amount = am1; AccountActivity.ACTIVITY_LOG.add(this); } /** * c5 * @param ac1 account doing this activity * @param at1 type of activity * @param ac2 account that is going to recieve the amount * @param am1 amount that is going to be transferred * @param balance balance of account responsible for this transaction AFTER the transaction * * instanciate an accountactivity object. * this constructor is responsible for creation of an accountactivity object for these activities: * transferring an amount from an account to another account */ public AccountActivity(Account ac1, int at1, Account ac2, double am1) { String accountType = ac1.getAccountType(); if(accountType.equals(CheckingAccount.ACCOUNT_TYPE)) { this.mainAccountType = CheckingAccount.ACCOUNT_TYPE; } if(accountType.equals(CreditAccount.ACCOUNT_TYPE)) { this.mainAccountType = CreditAccount.ACCOUNT_TYPE; } this.mainAccount = ac1; this.destinatedAccount = ac2; this.activityType = at1; this.time = LocalDateTime.now(); this.amount = am1; AccountActivity.ACTIVITY_LOG.add(this); } /** * c6 * @param ac1 account doing this activity * @param at1 type of activity * @param odp the newly set overdraft option of a checking account in this activity * @param balance balance of account responsible for this transaction AFTER the transaction * * instanciate an accountactivity object. * this constructor is responsible for creation of an accountactivity object for these activities: * setting the overdraft option of an account */ public AccountActivity(Account ac1, int at1, int odp, double balance) { String accountType = ac1.getAccountType(); if(accountType.equals(CheckingAccount.ACCOUNT_TYPE)) { this.mainAccountType = CheckingAccount.ACCOUNT_TYPE; } if(accountType.equals(CreditAccount.ACCOUNT_TYPE)) { this.mainAccountType = CreditAccount.ACCOUNT_TYPE; } this.mainAccount = ac1; this.activityType = at1; this.accountBalance = balance; this.time = LocalDateTime.now(); this.newODOption = odp; AccountActivity.ACTIVITY_LOG.add(this); } /** * c7 * @param ac1 account doing this activity * @param at1 type of activity * @param odp the newly set overdraft option of a checking account in this activity * @param balance balance of account responsible for this transaction AFTER the transaction * @param the newly set overdraft/credit limit of account responsible for this activity. * * instanciate an accountactivity object. * this constructor is responsible for creation of an accountactivity object for these activities: *setting the overdraft/credit limit of an account */ public AccountActivity(Account ac1, int at1, int op, double balance, double amo) { String accountType = ac1.getAccountType(); if(accountType.equals(CheckingAccount.ACCOUNT_TYPE)) { this.mainAccountType = CheckingAccount.ACCOUNT_TYPE; } if(accountType.equals(CreditAccount.ACCOUNT_TYPE)) { this.mainAccountType = CreditAccount.ACCOUNT_TYPE; } this.mainAccount = ac1; this.activityType = at1; this.accountBalance = balance; this.time = LocalDateTime.now(); this.newODOption = op; this.newLimit = amo; AccountActivity.ACTIVITY_LOG.add(this); } /** * @return the account responsible for this activity */ public Account getAccount() { return this.mainAccount; } /** * @return the type of account responsible for this activity */ public String getAccountType() { return this.mainAccountType; } /** * @return the type of activity that has been done in this activity.it represents: * 1 for withdraw an amount * 2 for deposit an amount * 3 for creating an account * 4 for cancelling an account * 5 for suspending an account * 6 for reactivating an account * 7 for getting balance of an account * 8 for terminating an account * 9 for setting overdraft option of an account * 10 for setting credit limit or overdraft limit of an account * 11 for transferring an amount */ public int getActivityType() { return this.activityType; } /** * @return the time that this activity is fulfilled. */ public LocalDateTime getTime() { return this.time; } /** * @return the demandloanaccount yielded from cancellation or termination of an account */ public DemandLoanAccount getDemandLoan() { return this.demandLoan; } /** * @return the amount of a withdraw or transfer or deposit activity */ public double getAmount() { return this.amount; } /** * @return the boolean variable respresenting if the withdrawal has been successful */ public boolean isTransactionSuccessful() { return this.isSuccessful; } /** * @return the destined account receiving an amount in a transfer. */ public Account getDestinatedAccount() { return this.destinatedAccount; } /** * @return the balance of accoun t responsible for this activity after the transaction */ public double getAccountBalance() { return this.accountBalance; } /** * @return the newly set overdraft option of a checking account in this activity */ public int getNewODOption() { return this.newODOption; } /** * @return the newly set overdraft/credit limit of account responsible for this activity. */ public double getNewLimit() { return this.newLimit; } /** * static method to sort all the accountactivities inside the activitylog arraylist based on * the increasing order of SIN number of clients who own the credit or checking accounts. * in case of two or more activity have the same Sin number (so they have the same owner client) they * are sorted by increasing order of time of implementation of activity. */ public static void sortActivityLog() { int logSize = AccountActivity.ACTIVITY_LOG.size(); for(int i = 1; i < logSize; i++) { boolean isReached = false; AccountActivity ithAccountActivity = AccountActivity.ACTIVITY_LOG.get(i); int iSIN = AccountActivity.ACTIVITY_LOG.get(i).getAccount().getClient().getSIN(); LocalDateTime ithTime = AccountActivity.ACTIVITY_LOG.get(i).getTime(); AccountActivity.ACTIVITY_LOG.remove(i); int j = i - 1; while(j >= 0 && AccountActivity.ACTIVITY_LOG.get(j).getAccount().getClient().getSIN() >= iSIN && !isReached) { if(AccountActivity.ACTIVITY_LOG.get(j).getAccount().getClient().getSIN() == iSIN) { if(ithTime.isBefore(AccountActivity.ACTIVITY_LOG.get(j).getTime())) { j--; }else { isReached = true; } }else { j--; } } AccountActivity.ACTIVITY_LOG.add(j + 1, ithAccountActivity); } } /** * static method responsible for completing the end of the day transactions. * this method apply pay per use fee for all the checking accounts that have had a withdrawal in this day * that caused their debt be increased or their account balance become negative while their * overdraft option have been set on pay per use. * also this method implement all the account terminations with creating a demand loan account for that client and * make the balance of their account equal to zero. * * @return a arraylist of demand loan account objects for clients whose accounts have been terminated in this day. */ public static ArrayList<DemandLoanAccount> endOfDayProcess() { ArrayList<DemandLoanAccount> todaysDemandLoanAccounts = new ArrayList<DemandLoanAccount>(); LocalDateTime nowDT = LocalDateTime.now(); int day = nowDT.getDayOfYear(); int year = nowDT.getYear(); HashSet<Account> selectedAccounts = new HashSet<Account>(); int logSize = AccountActivity.ACTIVITY_LOG.size(); for(int i = 0; i < logSize; i++) { if(AccountActivity.ACTIVITY_LOG.get(i).getTime().getDayOfYear() == day && AccountActivity.ACTIVITY_LOG.get(i).getTime().getYear() == year) { if(AccountActivity.ACTIVITY_LOG.get(i).getAccountType().equals(CheckingAccount.ACCOUNT_TYPE) && AccountActivity.ACTIVITY_LOG.get(i).getActivityType() == 1 && AccountActivity.ACTIVITY_LOG.get(i).getAccountBalance() < 0) { CheckingAccount ca1 = (CheckingAccount) AccountActivity.ACTIVITY_LOG.get(i).getAccount(); if(ca1.getOverdraftOption() == 3) { selectedAccounts.add(ca1); } } } } for(Account ac1 : selectedAccounts) { ac1.withdraw(CheckingAccount.PAY_PER_USE); } for(int i = 0; i < logSize; i++) { if(AccountActivity.ACTIVITY_LOG.get(i).getTime().getDayOfYear() == day && AccountActivity.ACTIVITY_LOG.get(i).getTime().getYear() == year) { if(AccountActivity.ACTIVITY_LOG.get(i).getActivityType() == 8) { todaysDemandLoanAccounts.add(AccountActivity.ACTIVITY_LOG.get(i).getDemandLoan()); Account terminatedAccount = AccountActivity.ACTIVITY_LOG.get(i).getAccount(); terminatedAccount.zeroBalance(); } } } return todaysDemandLoanAccounts; } /** * * static method responsible for completing the end of the day transactions. * this method applies monthly fixed fee to checking account whith overdraft option of fixed monthly pat * @return a arraylist of demand loan account objects for clients who have cancelled their account within this month. * besides, this method applies the intererst amount as a withdraw to all the credit and checking accounts that are in debt( with * negative balance). * also this method implement all the account cancellations with creating a demand loan account for that client and * make the balance of their account equal to zero. */ public static ArrayList<DemandLoanAccount> endOfMonthProcess() { ArrayList<DemandLoanAccount> thisMonthsDemandLoanAccounts = new ArrayList<DemandLoanAccount>(); LocalDateTime nowDT = LocalDateTime.now(); int month = nowDT.getMonthValue(); int year = nowDT.getYear(); HashSet<Account> selectedAccounts = new HashSet<Account>(); HashSet<Account> selectedAccountsForInterest = new HashSet<Account>(); int logSize = AccountActivity.ACTIVITY_LOG.size(); for(int i = 0; i < logSize; i++) { if(AccountActivity.ACTIVITY_LOG.get(i).getAccountType().equals(CheckingAccount.ACCOUNT_TYPE)) { CheckingAccount ca1 = (CheckingAccount) AccountActivity.ACTIVITY_LOG.get(i).getAccount(); if(ca1.getOverdraftOption() == 2) { selectedAccounts.add(ca1); } } } for(int i = 0; i < logSize; i++) { if(AccountActivity.ACTIVITY_LOG.get(i).getAccountType().equals(CheckingAccount.ACCOUNT_TYPE)) { if(AccountActivity.ACTIVITY_LOG.get(i).getActivityType() == 4 || AccountActivity.ACTIVITY_LOG.get(i).getActivityType() == 8 ) { CheckingAccount ca1 = (CheckingAccount) AccountActivity.ACTIVITY_LOG.get(i).getAccount(); selectedAccounts.remove(ca1); } } } for(Account ac1 : selectedAccounts) { ac1.withdraw(CheckingAccount.MONTHLY_FIXED_FEE); } for(int i = 0; i < logSize; i++) { selectedAccountsForInterest.add(AccountActivity.ACTIVITY_LOG.get(i).getAccount()); } for(int i = 0; i < logSize; i++) { if(AccountActivity.ACTIVITY_LOG.get(i).getActivityType() == 4 || AccountActivity.ACTIVITY_LOG.get(i).getActivityType() == 8 ) { selectedAccountsForInterest.remove(AccountActivity.ACTIVITY_LOG.get(i).getAccount()); } } for(Account ac1 : selectedAccountsForInterest) { String t1 = ac1.getAccountType(); if(t1.equals(CheckingAccount.ACCOUNT_TYPE)) { CheckingAccount cc1 = (CheckingAccount) ac1; if(cc1.getBalanceForProcess() < 0) { double charge = (cc1.getBalanceForProcess() * -1) * (CheckingAccount.YEARLY_INTEREST_RATE/12); cc1.withdraw(charge); } } if(t1.equals(CreditAccount.ACCOUNT_TYPE)) { CreditAccount cp1 = (CreditAccount) ac1; if(cp1.getBalanceForProcess() < 0) { double charge = (cp1.getBalanceForProcess() * -1) * (CreditAccount.YEARLY_INTEREST_RATE/12); cp1.withdraw(charge); } } } for(int i = 0; i < logSize; i++) { if(AccountActivity.ACTIVITY_LOG.get(i).getTime().getMonthValue() == month && AccountActivity.ACTIVITY_LOG.get(i).getTime().getYear() == year) { if(AccountActivity.ACTIVITY_LOG.get(i).getActivityType() == 4) { thisMonthsDemandLoanAccounts.add(AccountActivity.ACTIVITY_LOG.get(i).getDemandLoan()); Account terminatedAccount = AccountActivity.ACTIVITY_LOG.get(i).getAccount(); terminatedAccount.zeroBalance(); } } } return thisMonthsDemandLoanAccounts; } /** * static method to save the activitylog object into activitylog.ser file. */ public static void saveActivityLog() { try { String cwd = new File("").getAbsolutePath(); FileOutputStream fileOut = new FileOutputStream(cwd + "/src/CIBC_Design/activityLog.ser"); ObjectOutputStream outputStream = new ObjectOutputStream(fileOut); outputStream.writeObject(AccountActivity.ACTIVITY_LOG); outputStream.close(); fileOut.close(); System.out.println("all the activities were successfully saved."); } catch (Exception e) { System.out.println("your object was not successfully saved."); } } /** * static method to retrieve all the activities from the previously saved file named activitylog.ser * * @return the arraylist of previously saved accountactivity objects. */ public static ArrayList<AccountActivity> retrieveActivityLog() { ArrayList<AccountActivity> result = new ArrayList<AccountActivity>(); try { String cwd = new File("").getAbsolutePath(); FileInputStream fileInput = new FileInputStream(cwd + "/src/CIBC_Design/activityLog.ser"); ObjectInputStream inputStream = new ObjectInputStream(fileInput); result = (ArrayList<AccountActivity>) inputStream.readObject(); inputStream.close(); fileInput.close(); System.out.println("all the activities were successfully retrieved."); } catch (Exception e) { System.out.println("your object could not be read."); } return result; } }
true
c7532dd37c9af62303f1404d723534193fe3eced
Java
LiJianZhuang/XUI
/app/src/main/java/com/xuexiang/xuidemo/fragment/expands/WebViewFragment.java
UTF-8
3,618
1.851563
2
[ "Apache-2.0" ]
permissive
/* * Copyright (C) 2019 xuexiangjys(xuexiangjys@163.com) * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.xuexiang.xuidemo.fragment.expands; import android.content.Intent; import android.net.Uri; import android.view.View; import com.xuexiang.xpage.annotation.Page; import com.xuexiang.xui.widget.actionbar.TitleBar; import com.xuexiang.xuidemo.R; import com.xuexiang.xuidemo.base.BaseSimpleListFragment; import com.xuexiang.xuidemo.base.webview.XPageWebViewFragment; import com.xuexiang.xuidemo.fragment.expands.webview.JsWebViewFragment; import com.xuexiang.xuidemo.utils.Utils; import java.util.List; /** * @author xuexiang * @since 2019/1/5 上午12:39 */ @Page(name = "web浏览器", extra = R.drawable.ic_expand_web) public class WebViewFragment extends BaseSimpleListFragment { @Override protected List<String> initSimpleData(List<String> lists) { lists.add("使用系统默认API调用"); lists.add("直接显示调用"); lists.add("文件下载"); lists.add("input标签文件上传"); lists.add("电话、信息、邮件"); lists.add("地图定位"); lists.add("视频播放"); lists.add("简单的JS通信"); return lists; } @Override protected void onItemClick(int position) { switch (position) { case 0: systemApi("https://www.baidu.com/"); break; case 1: XPageWebViewFragment.openUrl(this, "https://www.baidu.com/"); break; case 2: Utils.goWeb(getContext(), "http://android.myapp.com/"); break; case 3: Utils.goWeb(getContext(), "file:///android_asset/upload_file/uploadfile.html"); break; case 4: Utils.goWeb(getContext(), "file:///android_asset/sms/sms.html"); break; case 5: Utils.goWeb(getContext(), "https://map.baidu.com/mobile/webapp/index/index/#index/index/foo=bar/vt=map"); break; case 6: Utils.goWeb(getContext(), "https://v.youku.com/v_show/id_XMjY1Mzc4MjU3Ng==.html?tpa=dW5pb25faWQ9MTAzNzUzXzEwMDAwMV8wMV8wMQ&refer=sousuotoufang_market.qrwang_00002944_000000_QJFFvi_19031900"); break; case 7: openPage(JsWebViewFragment.class); break; default: break; } } /** * 以系统API的方式请求浏览器 * * @param url */ public void systemApi(final String url) { Intent intent = new Intent(Intent.ACTION_VIEW, Uri.parse(url)); startActivity(intent); } @Override protected TitleBar initTitle() { TitleBar titleBar = super.initTitle(); titleBar.addAction(new TitleBar.TextAction("Github") { @Override public void performAction(View view) { Utils.goWeb(getContext(), "https://github.com/Justson/AgentWeb"); } }); return titleBar; } }
true
43a460258434440136ff7e0890e4166de3bdace3
Java
rodacev/Sem2Prueba3Seccion2
/src/vista/VentanaModificarMaterial.java
UTF-8
19,179
2.390625
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 vista; import controlador.ControladorMaterial; import javax.swing.JOptionPane; import modelo.Material; /** * * @author Rodrigo */ public class VentanaModificarMaterial extends javax.swing.JFrame { /** * Creates new form VentanaAgregarMaterial */ public VentanaModificarMaterial() { initComponents(); } public VentanaModificarMaterial(String codigo) { initComponents(); txt_codigo.setText(codigo); Material material = obtenerRegistroPorCodigo(codigo); txt_nombre.setText(material.getNombre()); if (material.getFormato().equalsIgnoreCase("p")) { rb_pelicula.setSelected(true); } else if (material.getFormato().equalsIgnoreCase("d")) { rb_documental.setSelected(true); } sp_duracion.setValue(material.getDuracion()); cmb_categoria.setSelectedItem(material.getCategoria()); txt_autor.setText(material.getAutor()); chk_estado.setSelected(material.isEstado()); } private Material obtenerRegistroPorCodigo(String codigo) { ControladorMaterial ctrlMaterial = new ControladorMaterial(); Material material = new Material(); try { material = ctrlMaterial.materialRegistro(codigo); return material; } catch (Exception err) { JOptionPane.showMessageDialog(rootPane, "ERROR: " + err.getMessage()); return material; } } /** * 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() { bg_formato = new javax.swing.ButtonGroup(); jPanel1 = new javax.swing.JPanel(); jLabel1 = new javax.swing.JLabel(); jLabel2 = new javax.swing.JLabel(); jLabel3 = new javax.swing.JLabel(); jLabel4 = new javax.swing.JLabel(); jLabel5 = new javax.swing.JLabel(); jLabel6 = new javax.swing.JLabel(); jLabel7 = new javax.swing.JLabel(); jLabel8 = new javax.swing.JLabel(); txt_codigo = new javax.swing.JTextField(); txt_nombre = new javax.swing.JTextField(); txt_autor = new javax.swing.JTextField(); sp_duracion = new javax.swing.JSpinner(); rb_documental = new javax.swing.JRadioButton(); rb_pelicula = new javax.swing.JRadioButton(); cmb_categoria = new javax.swing.JComboBox<>(); chk_estado = new javax.swing.JCheckBox(); btn_guardar = new javax.swing.JButton(); btn_limpiar = new javax.swing.JButton(); btn_salir = new javax.swing.JButton(); setSize(new java.awt.Dimension(800, 600)); jPanel1.setBorder(javax.swing.BorderFactory.createEtchedBorder()); jLabel1.setFont(new java.awt.Font("Tahoma", 0, 24)); // NOI18N jLabel1.setText("Modificar Material"); jLabel2.setFont(new java.awt.Font("Tahoma", 1, 18)); // NOI18N jLabel2.setText("Código:"); jLabel3.setFont(new java.awt.Font("Tahoma", 1, 18)); // NOI18N jLabel3.setText("Nombre:"); jLabel4.setFont(new java.awt.Font("Tahoma", 1, 18)); // NOI18N jLabel4.setText("Formato:"); jLabel5.setFont(new java.awt.Font("Tahoma", 1, 18)); // NOI18N jLabel5.setText("Duración:"); jLabel6.setFont(new java.awt.Font("Tahoma", 1, 18)); // NOI18N jLabel6.setText("Categoría:"); jLabel7.setFont(new java.awt.Font("Tahoma", 1, 18)); // NOI18N jLabel7.setText("Autor:"); jLabel8.setFont(new java.awt.Font("Tahoma", 1, 18)); // NOI18N jLabel8.setText("Nuevo:"); txt_codigo.setFont(new java.awt.Font("Tahoma", 0, 18)); // NOI18N txt_codigo.setEnabled(false); txt_nombre.setFont(new java.awt.Font("Tahoma", 0, 18)); // NOI18N txt_autor.setFont(new java.awt.Font("Tahoma", 0, 18)); // NOI18N txt_autor.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { txt_autorActionPerformed(evt); } }); sp_duracion.setFont(new java.awt.Font("Tahoma", 0, 18)); // NOI18N bg_formato.add(rb_documental); rb_documental.setFont(new java.awt.Font("Tahoma", 0, 18)); // NOI18N rb_documental.setText("Documental"); bg_formato.add(rb_pelicula); rb_pelicula.setFont(new java.awt.Font("Tahoma", 0, 18)); // NOI18N rb_pelicula.setText("Película"); cmb_categoria.setFont(new java.awt.Font("Tahoma", 0, 18)); // NOI18N cmb_categoria.setModel(new javax.swing.DefaultComboBoxModel<>(new String[] { "(Seleccione)", "Guerra", "Naturaleza", "Religión" })); chk_estado.setFont(new java.awt.Font("Tahoma", 0, 18)); // NOI18N btn_guardar.setFont(new java.awt.Font("Tahoma", 0, 18)); // NOI18N btn_guardar.setText("Guardar"); btn_guardar.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { btn_guardarActionPerformed(evt); } }); btn_limpiar.setFont(new java.awt.Font("Tahoma", 0, 18)); // NOI18N btn_limpiar.setText("Limpiar"); btn_limpiar.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { btn_limpiarActionPerformed(evt); } }); btn_salir.setFont(new java.awt.Font("Tahoma", 0, 18)); // NOI18N btn_salir.setText("Salir"); btn_salir.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { btn_salirActionPerformed(evt); } }); javax.swing.GroupLayout jPanel1Layout = new javax.swing.GroupLayout(jPanel1); jPanel1.setLayout(jPanel1Layout); jPanel1Layout.setHorizontalGroup( jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(jPanel1Layout.createSequentialGroup() .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(jPanel1Layout.createSequentialGroup() .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(jPanel1Layout.createSequentialGroup() .addContainerGap() .addComponent(jLabel1)) .addGroup(jPanel1Layout.createSequentialGroup() .addGap(324, 324, 324) .addComponent(chk_estado)) .addGroup(jPanel1Layout.createSequentialGroup() .addGap(202, 202, 202) .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING) .addComponent(jLabel8) .addComponent(jLabel2) .addComponent(jLabel3) .addComponent(jLabel4) .addComponent(jLabel5) .addComponent(jLabel6) .addComponent(jLabel7)) .addGap(18, 18, 18) .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addComponent(txt_codigo, javax.swing.GroupLayout.PREFERRED_SIZE, 300, javax.swing.GroupLayout.PREFERRED_SIZE) .addComponent(txt_nombre, javax.swing.GroupLayout.PREFERRED_SIZE, 300, javax.swing.GroupLayout.PREFERRED_SIZE) .addComponent(txt_autor, javax.swing.GroupLayout.PREFERRED_SIZE, 300, javax.swing.GroupLayout.PREFERRED_SIZE) .addComponent(sp_duracion, javax.swing.GroupLayout.PREFERRED_SIZE, 59, javax.swing.GroupLayout.PREFERRED_SIZE) .addGroup(jPanel1Layout.createSequentialGroup() .addComponent(rb_documental) .addGap(10, 10, 10) .addComponent(rb_pelicula)) .addComponent(cmb_categoria, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)))) .addGap(0, 150, Short.MAX_VALUE)) .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, jPanel1Layout.createSequentialGroup() .addGap(0, 0, Short.MAX_VALUE) .addComponent(btn_limpiar, javax.swing.GroupLayout.PREFERRED_SIZE, 100, javax.swing.GroupLayout.PREFERRED_SIZE) .addGap(18, 18, 18) .addComponent(btn_guardar, javax.swing.GroupLayout.PREFERRED_SIZE, 100, javax.swing.GroupLayout.PREFERRED_SIZE) .addGap(18, 18, 18) .addComponent(btn_salir, javax.swing.GroupLayout.PREFERRED_SIZE, 100, javax.swing.GroupLayout.PREFERRED_SIZE))) .addContainerGap()) ); jPanel1Layout.setVerticalGroup( jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(jPanel1Layout.createSequentialGroup() .addContainerGap() .addComponent(jLabel1) .addGap(53, 53, 53) .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING) .addGroup(jPanel1Layout.createSequentialGroup() .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE) .addComponent(jLabel2) .addComponent(txt_codigo, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)) .addGap(18, 18, 18) .addComponent(jLabel3)) .addComponent(txt_nombre, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)) .addGap(18, 18, 18) .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE) .addComponent(jLabel4) .addComponent(rb_documental) .addComponent(rb_pelicula)) .addGap(18, 18, 18) .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE) .addComponent(jLabel5) .addComponent(sp_duracion, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)) .addGap(18, 18, 18) .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addComponent(cmb_categoria, javax.swing.GroupLayout.Alignment.TRAILING, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE) .addComponent(jLabel6)) .addGap(18, 18, 18) .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE) .addComponent(jLabel7) .addComponent(txt_autor, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)) .addGap(18, 18, 18) .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE) .addComponent(jLabel8) .addComponent(chk_estado)) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, 148, Short.MAX_VALUE) .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE) .addComponent(btn_salir) .addComponent(btn_guardar) .addComponent(btn_limpiar)) .addContainerGap()) ); javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane()); getContentPane().setLayout(layout); layout.setHorizontalGroup( layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(layout.createSequentialGroup() .addContainerGap() .addComponent(jPanel1, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE) .addContainerGap()) ); layout.setVerticalGroup( layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(layout.createSequentialGroup() .addContainerGap() .addComponent(jPanel1, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE) .addContainerGap()) ); pack(); }// </editor-fold>//GEN-END:initComponents private void txt_autorActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_txt_autorActionPerformed // TODO add your handling code here: }//GEN-LAST:event_txt_autorActionPerformed private void btn_limpiarActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btn_limpiarActionPerformed txt_codigo.setText(""); txt_nombre.setText(""); bg_formato.clearSelection(); sp_duracion.setValue(0); cmb_categoria.setSelectedIndex(0); txt_autor.setText(""); chk_estado.setSelected(false); txt_nombre.requestFocus(); }//GEN-LAST:event_btn_limpiarActionPerformed private void btn_salirActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btn_salirActionPerformed dispose(); }//GEN-LAST:event_btn_salirActionPerformed private void btn_guardarActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btn_guardarActionPerformed Material material = new Material(); ControladorMaterial ctrlMaterial = new ControladorMaterial(); try { material.setCodigo(txt_codigo.getText()); material.setNombre(txt_nombre.getText()); if (rb_documental.isSelected()) { material.setFormato("d"); } else if (rb_pelicula.isSelected()) { material.setFormato("p"); } material.setDuracion((int)sp_duracion.getValue()); material.setCategoria(cmb_categoria.getSelectedItem().toString()); material.setAutor(txt_autor.getText()); if (chk_estado.isSelected()) { material.setEstado(true); }else{ material.setEstado(false); } ctrlMaterial.materialModificar(material); JOptionPane.showMessageDialog(rootPane, "MATERIAL MODIFICADO CORRECTAMENTE"); } catch (Exception err) { JOptionPane.showMessageDialog(rootPane, "ERROR: " + err.getMessage()); } }//GEN-LAST:event_btn_guardarActionPerformed /** * @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(VentanaModificarMaterial.class.getName()).log(java.util.logging.Level.SEVERE, null, ex); } catch (InstantiationException ex) { java.util.logging.Logger.getLogger(VentanaModificarMaterial.class.getName()).log(java.util.logging.Level.SEVERE, null, ex); } catch (IllegalAccessException ex) { java.util.logging.Logger.getLogger(VentanaModificarMaterial.class.getName()).log(java.util.logging.Level.SEVERE, null, ex); } catch (javax.swing.UnsupportedLookAndFeelException ex) { java.util.logging.Logger.getLogger(VentanaModificarMaterial.class.getName()).log(java.util.logging.Level.SEVERE, null, ex); } //</editor-fold> //</editor-fold> /* Create and display the form */ java.awt.EventQueue.invokeLater(new Runnable() { public void run() { new VentanaModificarMaterial().setVisible(true); } }); } // Variables declaration - do not modify//GEN-BEGIN:variables private javax.swing.ButtonGroup bg_formato; private javax.swing.JButton btn_guardar; private javax.swing.JButton btn_limpiar; private javax.swing.JButton btn_salir; private javax.swing.JCheckBox chk_estado; private javax.swing.JComboBox<String> cmb_categoria; 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.JLabel jLabel7; private javax.swing.JLabel jLabel8; private javax.swing.JPanel jPanel1; private javax.swing.JRadioButton rb_documental; private javax.swing.JRadioButton rb_pelicula; private javax.swing.JSpinner sp_duracion; private javax.swing.JTextField txt_autor; private javax.swing.JTextField txt_codigo; private javax.swing.JTextField txt_nombre; // End of variables declaration//GEN-END:variables }
true
0dd21aa15178a20ca652fd35332d5e92944c4417
Java
sluizin/des-wkope-task
/src/main/java/des/wangku/operate/standard/utls/UtilsRegular.java
UTF-8
10,715
3.0625
3
[]
no_license
package des.wangku.operate.standard.utls; import java.util.ArrayList; import java.util.List; import java.util.regex.Matcher; import java.util.regex.Pattern; /** * 正则 * @author Sunjian * @version 1.0 * @since jdk1.8 */ public final class UtilsRegular { /** 在样式中显示格式: [220] */ public static final String ACC_NumDisPattern = "\\[[0-9]+\\]"; private static final String pattern = "\\[[0-9]+\\]"; private static final String Patternidentifier = "\\[[\\s\\S]+\\]"; /** * 从字符串中提取所有[102],[104]此类的子串,并得到字符串数组 * @param content String * @return String[] */ public static final String[] getArrayID(String content) { return getRegexArray(pattern, content); } /** * 从字符串中提取所有[102],[a102]此类的子串,并得到字符串数组 * @param content String * @return String[] */ public static final String[] getArrayIdentifier(String content) { return getRegexArray(Patternidentifier, content); } /** * 从字符串中提取所有[102],[a102]此类的子串,并得到字符串 * @param content String * @return String */ public static final String getArrayIdentifierFirst(String content) { String[] arr = getArrayIdentifier(content); if (arr == null || arr.length == 0) return null; return arr[0]; } /** * 从字符串中提取所有[102],[103]此类的子串,并得到字符串 * @param content String * @return String */ public static final String getArrayIDFirst(String content) { String[] arr = getArrayID(content); if (arr == null || arr.length == 0) return null; return arr[0]; } /** * 从字符串中提取所有[102]此类的子串,并得到数值数组 * @param content String * @return int[] */ public static final int[] getArrayNum(String content) { Pattern r = Pattern.compile(pattern); Matcher m = r.matcher(content); List<Integer> list = new ArrayList<>(); while (m.find()) { String str = m.group(0); list.add(Integer.parseInt(str.substring(1, str.length() - 1))); } int[] arr = new int[list.size()]; for (int i = 0; i < list.size(); i++) { arr[i] = list.get(i); } return arr; } /** * 得到字符串提取的[102]此类的子串,得到指定下标 * @param content String * @param index int * @return int */ public static final int getArrayNumNo(String content, int index) { int[] arr = getArrayNum(content); if (index < 0 || index >= arr.length) return -1; return arr[index]; } /** * 判断字符串中含有多个子串 支持正则 * @param content String * @param keyword String * @return int */ public static final int getPatternCount(String content, String keyword) { if (content == null || content.length() == 0) return 0; if (keyword == null || keyword.length() == 0) return 0; Pattern r = Pattern.compile(keyword, Pattern.CASE_INSENSITIVE); Matcher m = r.matcher(content); int count = 0; while (m.find()) count++; return count; } /** * 判断字符串中含有多个子串 多个子串使用|进行间隔 * @param content String * @param keyword String * @return int */ public static final int getPatternMultiKeyCount(String content, String keyword) { return getPatternCount(content, "(?:" + keyword + ")"); } /** * 判断字符串中含有多个数字显示样式 * @param content String * @return int */ public static final int getPatternNumDisCount(String content) { if (content == null || content.length() == 0) return 0; Pattern r = Pattern.compile(ACC_NumDisPattern); Matcher m = r.matcher(content); int count = 0; while (m.find()) count++; return count; } /** * 把正则检索出来的某个位置转为value * @param content String * @param index int * @param value String * @return String */ public static final String getPatternReplaceNumDis(final String content, int index, String value) { if (content == null || index < 0 || value == null) return content; Pattern r = Pattern.compile(ACC_NumDisPattern); Matcher m = r.matcher(content); int i = 0; while (m.find()) { if ((i++) != index) continue; int contentlen = content.length(); StringBuilder sb = new StringBuilder(contentlen + value.length()); if (m.start() > 0) sb.append(content.substring(0, m.start())); sb.append(value); if (m.end() < contentlen) sb.append(content.substring(m.end(), contentlen)); return sb.toString(); } return content; } /** * 得到字符串以first开头以end结果的字符串,字符串中可以含有first * @param content String * @param first char * @param end char * @return String[] */ public static final String[] getRegexArray(String content, char first, char end) { String regex = first + "([^" + end + "])*" + end; return getRegexArray(regex, content); } /** * 得到字符串以first开头以end结果的字符串,字符串中不可以含有first * @param content String * @param first String * @param end String * @return String[] */ public static final String[] getSubArrayString(String content, String first, String end) { String[] arr = {}; if(content==null ||content.length()==0)return arr; if(first==null ||first.length()==0)return arr; if(end==null ||end.length()==0)return arr; String regex = first + "([^(" + first + ")^(" + end + ")])*" + end; return getSubArray(regex, content); } /** * 得到字符串以first开头以end结果的字符串,字符串中不可以含有first<br> * 过滤掉空值 * @param content String * @param first String * @param end String * @return String[] */ public static final String[] getSubArrayVal(String content, String first, String end) { String[] arr= {}; if(content==null ||content.length()==0)return arr; if(first==null ||first.length()==0)return arr; if(end==null ||end.length()==0)return arr; String[] result=getSubArrayString(content,first,end); if(result.length==0)return arr; int firstlen=first.length(); int endlen=end.length(); List<String> list=new ArrayList<String>(result.length); for(String e:result) { if(e.length()<=firstlen+endlen)continue; e=e.substring(firstlen, e.length() - endlen); list.add(e); } return list.toArray(arr); } /** * 得到正则的结果数组 * @param pattern String * @param content String * @return String[] */ public static final String[] getRegexArray(String pattern, String content) { Pattern r = Pattern.compile(pattern); Matcher m = r.matcher(content); List<String> list = new ArrayList<>(); while (m.find()) { String str = m.group(0); list.add(str.substring(1, str.length() - 1)); } String[] arr = {}; return list.toArray(arr); } /** * 得到正则的结果数组 * @param pattern String * @param content String * @return String[] */ public static final String[] getSubArray(String pattern, String content) { Pattern r = Pattern.compile(pattern); Matcher m = r.matcher(content); List<String> list = new ArrayList<>(); while (m.find()) { String str = m.group(0); list.add(str); } String[] arr = {}; return list.toArray(arr); } /** * 得到正则的结果数组 查出同对性质的数据组 如【】 最好使用全角 * @param pattern String * @param first String * @param end String * @return String[] */ public static final String[] getRegexArray(String content, String first, String end) { String regex = first + "([^" + end + "])*" + end; return getRegexArray(regex, content); } /** * 判断字符串中正则的结果,是否存在 * @param Content String * @param regEx String * @return boolean */ public static final boolean getRegExBoolean(String Content, String regEx) { if (Content == null) return false; if (regEx == null) return false; Pattern pat = Pattern.compile(regEx); Matcher mat = pat.matcher(Content); return mat.find(); } /** * 从字符串中得到某个变量组 * @param Content String * @param regEx String * @param group int * @return String */ public static final String getRegExContent(String Content, String regEx, int group) { if (Content == null) return null; if (regEx == null) return null; Pattern pat = Pattern.compile(regEx); Matcher mat = pat.matcher(Content); if (!mat.find()) return null; if (group < 0 || group > mat.groupCount()) return null; return mat.group(group); } public static void main22(String[] args) { /* * String[] arr= {"+12","12","1 2","-25","-522","- 105"," - 58 ","+ 52","+ 60","+0"}; * String pattern = "^[\\s\\S]*([+-]+)\\s*(\\d+)\\s*$"; * for(String e:arr) { * Pattern r = Pattern.compile(pattern); * Matcher m = r.matcher(e); * //System.out.println(e+"\t\t"+m.find()); * if(m.find()) { * System.out.println("Found value: " + m.group(0) ); * System.out.println("Found value: " + m.group(1) ); * System.out.println("Found value: " + m.group(2) ); * } * System.out.println("-----------------------------------------------"); * } * String content = "[1]sadsaasfdweqew[100]effewasdf[022]asdfas[a]fa[d00]sdf[5]asf[580]rr[005]"; * String pattern = "\\[[0-9]+\\]"; * Pattern r = Pattern.compile(pattern); * Matcher m = r.matcher(content); * while (m.find()) { * System.out.println("[" + m.start() + "," + m.end() + "]Found value: " + m.group(0)); * } * System.out.println(content); * System.out.println(getPatternNumDisCount(content)); * System.out.println("" + getPatternReplaceNumDis(content, 0, "(abc)")); * System.out.println("" + getPatternReplaceNumDis(content, 1, "(abc)")); * System.out.println("" + getPatternReplaceNumDis(content, 2, "(abc)")); * System.out.println("" + getPatternReplaceNumDis(content, 3, "(abc)")); * System.out.println("" + getPatternReplaceNumDis(content, 4, "(abc)")); * System.out.println("" + getPatternReplaceNumDis(content, 5, "(abc)")); * int[] arr=getArrayNum(content); * for(int a:arr) { * System.out.println("a:"+a); * } */ String str = "[aaa]aeee eeww[1234] ytttt [1a4a5a]"; String str2 = str.replaceAll("\\[[^]]*\\]", ""); System.out.println(str2); String str3 = "【哀号】 :1.因悲伤而呼号痛哭。 2.指兽类悲啼。 【哀鸣】AA"; String[] str4 = UtilsRegular.getRegexArray(str3, "【", "】"); for (String ee : str4) System.out.print(ee); } }
true
21cb701b06ff93ce6d02e261b0ef713edff72656
Java
WangMeirong/QKPracticeService
/src/main/java/com/qk/practice/model/Exam.java
UTF-8
3,931
2.1875
2
[]
no_license
package com.qk.practice.model; import java.util.List; /******************************************************************************* * javaBeans * exam --> Exam * <table explanation> * @author 2016-09-29 22:11:50 * */ public class Exam implements java.io.Serializable { private static final long serialVersionUID = 2945337904017720732L; //field /** **/ private String examId; /** **/ private Subject subject; /** **/ private String subjectId; /** **/ private String code; /** **/ private String title; /** **/ private String decription; /** **/ private int duration; /** **/ private String isPublic; /** **/ private String isDelete; /** **/ private long createdTime; /** **/ private String lastModifiedBy; /** **/ private long lastModifiedTime; /** **/ private List<Practice> practices; /** **/ private List<Tag> tags; //method public String getExamId() { return examId; } public void setExamId(String exmaId) { this.examId = exmaId; } public Subject getSubject() { return subject; } public void setSubject(Subject subject) { this.subject = subject; } public String getSubjectId() { return subjectId; } public void setSubjectId(String subjectId) { this.subjectId = subjectId; } public String getCode() { return code; } public void setCode(String code) { this.code = code; } public String getTitle() { return title; } public void setTitle(String title) { this.title = title; } public String getDecription() { return decription; } public void setDecription(String decription) { this.decription = decription; } public int getDuration() { return duration; } public void setDuration(int duration) { this.duration = duration; } public String getIsPublic() { return isPublic; } public void setIsPublic(String isPublic) { this.isPublic = isPublic; } public String getIsDelete() { return isDelete; } public void setIsDelete(String isDelete) { this.isDelete = isDelete; } public Object getCreatedTime() { return createdTime; } public void setCreatedTime(long createdTime) { this.createdTime = createdTime; } public String getLastModifiedBy() { return lastModifiedBy; } public void setLastModifiedBy(String lastModifiedBy) { this.lastModifiedBy = lastModifiedBy; } public Object getLastModifiedTime() { return lastModifiedTime; } public void setLastModifiedTime(long lastModifiedTime) { this.lastModifiedTime = lastModifiedTime; } public List<Practice> getPractices() { return practices; } public void setPractices(List<Practice> practices) { this.practices = practices; } public List<Tag> getTags() { return tags; } public void setTags(List<Tag> tags) { this.tags = tags; } //override toString Method public String toString() { StringBuffer sb=new StringBuffer(); sb.append("{"); sb.append("'examId':'"+this.getExamId()+"',"); sb.append("'subject':'"+this.getSubject().toString() +"',"); sb.append("'subjectId':'"+this.getSubjectId() +"',"); sb.append("'code':'"+this.getCode()+"',"); sb.append("'titile':'"+this.getTitle()+"',"); sb.append("'decription':'"+this.getDecription()+"',"); sb.append("'duration':'"+this.getDuration()+"',"); sb.append("'isPublic':'"+this.getIsPublic()+"',"); sb.append("'isDelete':'"+this.getIsDelete()+"',"); sb.append("'createdTime':'"+this.getCreatedTime()+"',"); sb.append("'lastModifiedBy':'"+this.getLastModifiedBy()+"',"); sb.append("'lastModifiedTime':'"+this.getLastModifiedTime()+"',"); sb.append("'practice.size':'"+this.getPractices().size() +"',"); sb.append("'tags.size':'"+this.getTags().size() +"',"); sb.append("}"); return sb.toString(); } //return String[] filed; public String[] getField() { return new String[]{"examId","subject","code","title","decription","duration","isPublic","isDelete","createdTime","lastModifiedBy","lastModifiedTime","practices","tags","subjectId"}; } }
true
50335ad8761547b0fd3d4266fbd40d7853795b84
Java
Vennic/CriminalApp
/app/src/main/java/com/example/crimeapp/InstanceOfPicker.java
UTF-8
1,086
2.375
2
[]
no_license
package com.example.crimeapp; import android.content.Intent; import android.os.Bundle; import android.support.v4.app.DialogFragment; import java.util.Date; public class InstanceOfPicker extends DialogFragment{ public static final String DATE_EXTRA_INSTANCE = "android_crimeApp_extraDateInstance"; public static final String PICKER_EXTRA_DATE = "android_crimeApp_pickerExtraDate"; public static final String PICKER_EXTRA_TIME = "android_crimeApp_pickerExtraTime"; public static <T extends DialogFragment> T newInstance(Date date, T instanceOfDialogF) { Bundle bundle = new Bundle(); bundle.putSerializable(DATE_EXTRA_INSTANCE, date); instanceOfDialogF.setArguments(bundle); return instanceOfDialogF; } protected void sendResult(int requestCode, Date date, String extraId) { if (getTargetFragment() == null) { return; } Intent intent = new Intent(); intent.putExtra(extraId, date); getTargetFragment().onActivityResult(getTargetRequestCode(), requestCode, intent); } }
true
b2dbf2f88dcfea8ebf43b183337ada249b90d49b
Java
pixeldev/fullpvp
/src/main/java/me/pixeldev/fullpvp/chest/creator/SupplierChestCreatorCache.java
UTF-8
388
2.03125
2
[]
no_license
package me.pixeldev.fullpvp.chest.creator; import me.pixeldev.fullpvp.Cache; import java.util.HashMap; import java.util.Map; import java.util.UUID; public class SupplierChestCreatorCache implements Cache<UUID, UserCreator> { private final Map<UUID, UserCreator> creators = new HashMap<>(); @Override public Map<UUID, UserCreator> get() { return creators; } }
true
d57bdedd138b9f2816db15c072e311404049ed2b
Java
huangyabin001/bugexpert
/src/com/bill/bugexpert/util/SavedData.java
UTF-8
6,815
2.234375
2
[]
no_license
/* * Copyright (C) 2013 Sony Mobile Communications AB * * This file is part of ChkBugReport. * * ChkBugReport is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 2 of the License, or * (at your option) any later version. * * ChkBugReport 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 ChkBugReport. If not, see <http://www.gnu.org/licenses/>. */ package com.bill.bugexpert.util; import java.lang.reflect.Field; import java.lang.reflect.ParameterizedType; import java.util.Iterator; import java.util.Vector; import com.bill.bugexpert.util.SaveFile.ResultSet; abstract public class SavedData<T> implements Iterable<T> { private Vector<T> mData = new Vector<T>(); private SaveFile mSaveFile; private String mTblName; private Vector<Field> mFields = new Vector<Field>(); private Vector<SavedField> mDBFields = new Vector<SavedField>(); public SavedData(SaveFile conn, String tblName) { mSaveFile = conn; mTblName = tblName; if (mSaveFile == null) { // No DB, no data to restore return; } // Scan fields boolean first = true; // hack to get generic class type ParameterizedType superClass = (ParameterizedType) getClass().getGenericSuperclass(); @SuppressWarnings("unchecked") Class<T> cls = (Class<T>) superClass.getActualTypeArguments()[0]; for (Field f : cls.getDeclaredFields()) { f.setAccessible(true); SavedField descr = f.getAnnotation(SavedField.class); if (descr != null) { mFields.add(f); mDBFields.add(descr); if (descr.type() == SavedField.Type.ID && !first) { throw new RuntimeException("Only first field can be ID!"); } else if (descr.type() != SavedField.Type.ID && first) { throw new RuntimeException("First declared field must be the ID!"); } first = false; } } } @Override public Iterator<T> iterator() { return mData.iterator(); } final protected Vector<T> getData() { return mData; } public void load() { load(null, null); } public void load(String field, long value) { load(field, Long.toString(value)); } public void load(String field, String value) { try { ResultSet res = mSaveFile.select(mTblName); for (XMLNode node : res) { if (field != null && value != null) { if (!value.equals(node.getAttr(field))) { continue; } } T item = createItem(); for (int i = 0; i < mFields.size(); i++) { Field f = mFields.get(i); switch (mDBFields.get(i).type()) { case ID: case LINK: case INT: setLongField(f, item, node); break; case VARCHAR: setStringField(f, item, node); break; } } addImpl(item); onLoaded(item); } } catch (Exception e) { e.printStackTrace(); } } private void setLongField(Field f, T item, XMLNode node) throws Exception { String val = node.getAttr(f.getName()); if (val != null) { if (f.getType().getName().equals("int")) { f.setInt(item, Integer.parseInt(val)); } else { f.setLong(item, Long.parseLong(val)); } } } private void setStringField(Field f, T item, XMLNode node) throws Exception { String val = node.getAttr(f.getName()); if (val != null) { if (f.getType().isEnum()) { // Special case: need to convert the string to enum Object objVal = f.getType().getMethod("valueOf", String.class).invoke(null, val); f.set(item, objVal); } else { f.set(item, val); } } } private void setFromField(XMLNode node, T item, int i) throws IllegalAccessException { Field f = mFields.get(i); switch (mDBFields.get(i).type()) { case ID: case LINK: case INT: node.addAttr(f.getName(), Long.toString(f.getLong(item))); break; case VARCHAR: node.addAttr(f.getName(), f.get(item).toString()); break; } } public void add(T item) { try { // Need to save to database as well XMLNode node = mSaveFile.insert(mTblName, mFields.get(0).getName()); for (int i = 1 /* skip ID */; i < mFields.size(); i++) { setFromField(node, item, i); } Field fId = mFields.get(0); setLongField(fId, item, node); mSaveFile.commit(mTblName); addImpl(item); } catch (Exception e) { e.printStackTrace(); } } public void update(T item) { if (!mData.contains(item)) return; // quick sanity check try { // Need to save to database as well XMLNode node = mSaveFile.findById(mTblName, mFields.get(0).getName(), mFields.get(0).getInt(item)); if (node != null) { for (int i = 1 /* skip ID */; i < mFields.size(); i++) { setFromField(node, item, i); } mSaveFile.commit(mTblName); } } catch (Exception e) { e.printStackTrace(); } } public void delete(T item) { try { if (mData.remove(item)) { mSaveFile.delete(mTblName, mFields.get(0).getName(), mFields.get(0).getInt(item)); mSaveFile.commit(mTblName); } } catch (Exception e) { e.printStackTrace(); } } abstract protected T createItem(); protected void onLoaded(T item) { // NOP } private void addImpl(T item) { mData.add(item); } public SaveFile getSaveFile() { return mSaveFile; } public String getTableName() { return mTblName; } }
true
58198f39ca36dfa86c927cca2b781d00c90e881b
Java
qhals321/prolog
/backend/src/main/java/wooteco/prolog/filter/ui/FilterController.java
UTF-8
1,099
2.09375
2
[ "MIT" ]
permissive
package wooteco.prolog.filter.ui; import lombok.AllArgsConstructor; import org.springframework.http.ResponseEntity; import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RestController; import wooteco.prolog.mission.application.MissionService; import wooteco.prolog.mission.application.dto.MissionResponse; import wooteco.prolog.filter.application.dto.FilterResponse; import wooteco.prolog.tag.application.TagService; import wooteco.prolog.tag.dto.TagResponse; import java.util.List; @RestController @RequestMapping("/filters") @AllArgsConstructor public class FilterController { private final MissionService missionService; private final TagService tagService; @GetMapping public ResponseEntity<FilterResponse> showAll() { List<MissionResponse> missionResponses = missionService.findAll(); List<TagResponse> tagResponses = tagService.findAll(); return ResponseEntity.ok().body(new FilterResponse(missionResponses, tagResponses)); } }
true
ecc587212cbc5ea0b28547d0bc462ea2dc324207
Java
LuisPoclin/AgendaContactos
/Agenda3/src/agenda/Agenda3.java
UTF-8
5,235
3.15625
3
[]
no_license
package agenda; public class Agenda3 { // Atributos Contacto3[] lista; // Metodo Constructor public Agenda3(int tamanio_agenda) { this.lista = new Contacto3[tamanio_agenda]; } // Metodos // Metodo insertar contactos public void setContacto(Contacto3 c) { int indice = buscar_indice_vacio(); if (indice < 0) { System.out.println(""); System.out.println("Importante: Agenda llena!"); } else { this.lista[indice] = c; } } private int buscar_indice_vacio() { int indice = 0; while (this.lista[indice] != null) { indice++; if (indice > (this.lista).length - 1) { return -1; } } return indice; } // Metodo listar contactos public void listarContactos() { System.out.println(""); System.out.println("Lista de contactos"); for (int i = 0; i < (this.lista).length; i++) { if (this.lista[i] == null) { } else { System.out.println(""); System.out.println("Contacto: " + (i + 1)); (this.lista[i]).DatosContacto(); } } } // Metodo eliminar contactos public void Deletecontact(String c) { boolean band = false; for (int i = 0; i < (this.lista).length && !band; i++) { if (this.lista != null && c.compareToIgnoreCase(this.lista[i].getNombre()) == 0 || c.compareToIgnoreCase(this.lista[i].getTelefono()) == 0 || c.compareToIgnoreCase(this.lista[i].getEmail()) == 0) { this.lista[i] = null; band = true; System.out.println("Contacto eliminado exitosamente"); } if (!band) { System.out.println("Contacto no registrado"); break; } } } // Metodo buscar_contacto_por_nombre public void Findcontact1(String c) { boolean band = false; for (int i = 0; i < (this.lista).length && !band; i++) { if (this.lista != null && c.compareToIgnoreCase(this.lista[i].getNombre()) == 0) { this.lista[i].DatosContacto(); band = true; } if (!band) { System.out.println("Contacto no registrado"); break; } } } // Metodo buscar_contacto_por_telefono public void Findcontact2(String c) { boolean band = false; for (int i = 0; i < (this.lista).length && !band; i++) { if (this.lista != null && c.compareToIgnoreCase(this.lista[i].getTelefono()) == 0) { this.lista[i].DatosContacto(); band = true; } if (!band) { System.out.println("Contacto no registrado"); break; } } } // Metodo buscar_contacto_por_email public void Findcontact3(String c) { boolean band = false; for (int i = 0; i < (this.lista).length && !band; i++) { if (this.lista != null && c.compareToIgnoreCase(this.lista[i].getEmail()) == 0) { this.lista[i].DatosContacto(); band = true; } if (!band) { System.out.println("Contacto no registrado"); break; } } } // Metodo editar contactos public void Editcontactnom(String c, String nombre) { boolean band = false; for (int i = 0; i < (this.lista).length && !band; i++) { if (this.lista != null && c.compareToIgnoreCase(this.lista[i].getNombre()) == 0 || c.compareToIgnoreCase(this.lista[i].getTelefono()) == 0 || c.compareToIgnoreCase(this.lista[i].getEmail()) == 0) { this.lista[i].setNombre(nombre); System.out.println("El nuevo contacto es :"); this.lista[i].DatosContacto(); band = true; } if (!band) { System.out.println("Contacto no registrado"); break; } } } public void Editcontacttelf(String c, String telefono) { boolean band = false; for (int i = 0; i < (this.lista).length && !band; i++) { if (this.lista != null && c.compareToIgnoreCase(this.lista[i].getNombre()) == 0 || c.compareToIgnoreCase(this.lista[i].getTelefono()) == 0 || c.compareToIgnoreCase(this.lista[i].getEmail()) == 0) { this.lista[i].setTelefono(telefono); System.out.println("El nuevo contacto es :"); this.lista[i].DatosContacto(); band = true; } if (!band) { System.out.println("Contacto no registrado"); break; } } } public void Editcontactemail(String c, String email) { boolean band = false; for (int i = 0; i < (this.lista).length && !band; i++) { if (this.lista != null && c.compareToIgnoreCase(this.lista[i].getNombre()) == 0 || c.compareToIgnoreCase(this.lista[i].getTelefono()) == 0 || c.compareToIgnoreCase(this.lista[i].getEmail()) == 0) { this.lista[i].setEmail(email); System.out.println("El nuevo contacto es :"); this.lista[i].DatosContacto(); band = true; } if (!band) { System.out.println("Contacto no registrado"); break; } } } // metodo para visualizar datos public void Mostrar(String c) { boolean band = false; for (int i = 0; i < (this.lista).length && !band; i++) { if (this.lista != null && c.compareToIgnoreCase(this.lista[i].getNombre()) == 0 || c.compareToIgnoreCase(this.lista[i].getTelefono()) == 0 || c.compareToIgnoreCase(this.lista[i].getEmail()) == 0) { this.lista[i].DatosContacto(); band = true; } if (!band) { System.out.println("Contacto no registrado"); break; } } } }
true
7fb10693221dee080bcf11ac4eae27040c445778
Java
utd-hltri/l-pcrs
/eeg/eeg-report-annotations/src/main/java/edu/utdallas/hltri/eeg/TensorflowUtils.java
UTF-8
14,091
1.773438
2
[]
no_license
package edu.utdallas.hltri.eeg; import com.google.common.collect.*; import edu.utdallas.hltri.eeg.annotation.EegActivity; import edu.utdallas.hltri.eeg.annotation.label.EventTypeLabel; import edu.utdallas.hltri.eeg.annotation.label.ModalityLabel; import edu.utdallas.hltri.eeg.annotation.label.PolarityLabel; import edu.utdallas.hltri.eeg.annotators.AttributeNetworkActiveLearner.*; import edu.utdallas.hltri.eeg.feature.*; import edu.utdallas.hltri.logging.Logger; import edu.utdallas.hltri.ml.Feature; import edu.utdallas.hltri.ml.label.EnumLabel; import edu.utdallas.hltri.ml.feature.AnnotationVectorizer; import edu.utdallas.hltri.ml.label.IoLabel; import edu.utdallas.hltri.ml.label.Label; import edu.utdallas.hltri.ml.vector.CountingSparseFeatureVectorizer; import edu.utdallas.hltri.ml.vector.SparseFeatureVector; import edu.utdallas.hltri.ml.vector.SparseFeatureVectorizer; import edu.utdallas.hltri.ml.vector.VectorUtils; import edu.utdallas.hltri.scribe.text.BaseDocument; import edu.utdallas.hltri.scribe.text.Document; import edu.utdallas.hltri.scribe.text.annotation.Event; import edu.utdallas.hltri.scribe.text.annotation.Sentence; import edu.utdallas.hltri.scribe.text.annotation.Token; import edu.utdallas.hltri.struct.Pair; import edu.utdallas.hltri.util.IntIdentifier; import java.io.IOException; import java.nio.file.Files; import java.nio.file.Path; import java.nio.file.Paths; import java.util.ArrayList; import java.util.Arrays; import java.util.List; import java.util.stream.Collectors; /** * Created by rmm120030 on 10/12/16. */ public class TensorflowUtils { private static Logger log = Logger.get(TensorflowUtils.class); public static <D extends BaseDocument> void writeActivityVectorsOneLocation(final List<Document<D>> documents, final String outDir, final String annset) { final AnnotationVectorizer<EegActivity> vectorizer = new AnnotationVectorizer<EegActivity>( FeatureUtils.attributeFeatureExtractors(annset), a -> EnumLabel.NULL, new IntIdentifier<>()); final List<String> vectors = Lists.newArrayList(); final Multimap<String, String> labelMap = HashMultimap.create(); documents.parallelStream().flatMap(doc -> doc.get(annset, EegActivity.TYPE).stream()).forEach(act -> { vectors.add(act.getId() + " " + vectorizer.vectorizeAnnotation(act).noLabel()); labelMap.put("MORPHOLOGY", act.getId() + " " + EegActivity.Morphology.valueOf(act.get(EegActivity.morphology)).numericValue().intValue()); labelMap.put("FREQUENCY_BAND", act.getId() + " " + EegActivity.Band.valueOf(act.get(EegActivity.band)).numericValue().intValue()); labelMap.put("HEMISPHERE", act.getId() + " " + EegActivity.Hemisphere.valueOf(act.get(EegActivity.hemisphere)).numericValue().intValue()); labelMap.put("DISPERSAL", act.getId() + " " + EegActivity.Dispersal.valueOf(act.get(EegActivity.dispersal)).numericValue().intValue()); labelMap.put("RECURRENCE", act.getId() + " " + EegActivity.Recurrence.valueOf(act.get(EegActivity.recurrence)).numericValue().intValue()); labelMap.put("BACKGROUND", act.getId() + " " + EegActivity.In_Background.valueOf(act.get(EegActivity.in_background)).numericValue().intValue()); labelMap.put("MAGNITUDE", act.getId() + " " + EegActivity.Magnitude.valueOf(act.get(EegActivity.magnitude)).numericValue().intValue()); labelMap.put("LOCATION", act.getId() + " " + act.getLocations().stream().map(l -> l.numericValue().toString()).reduce("", (l1, l2) -> l1 + l2 + " ")); labelMap.put("MODALITY", act.getId() + " " + ModalityLabel.valueOf(act.get(EegActivity.modality)).numericValue().intValue()); labelMap.put("POLARITY", act.getId() + " " + PolarityLabel.fromString(act.get(EegActivity.polarity)).numericValue().intValue()); }); try { final Path path = Paths.get(outDir).resolve("activity"); path.toFile().mkdir(); Files.write(path.resolve("activity_attr.svml"), vectors); for (final String lbl : labelMap.keySet()) { Files.write(path.resolve(lbl + ".lbl"), labelMap.get(lbl)); } } catch (IOException e) { throw new RuntimeException(e); } } public static <D extends BaseDocument> void writeActivityVectors(final List<Document<D>> documents, final String outDir, final String annset) { final AnnotationVectorizer<EegActivity> vectorizer = new AnnotationVectorizer<EegActivity>( Arrays.asList(new GoldFeatureExtractor(), new ConceptSpanFeatureExtractor<>(), new ContextFeatureExtractor<>(annset), new SectionFeatureExtractor<>()), a -> EnumLabel.NULL, new IntIdentifier<>()); final List<String> vectors = Lists.newArrayList(); final Multimap<String, String> labelMap = HashMultimap.create(); documents.parallelStream().flatMap(doc -> doc.get(annset, EegActivity.TYPE).stream()).forEach(act -> { vectors.add(act.getId() + " " + vectorizer.vectorizeAnnotation(act).noLabel()); labelMap.put("MORPHOLOGY", act.getId() + " " + EegActivity.Morphology.valueOf(act.get(EegActivity.morphology)).numericValue().intValue()); labelMap.put("FREQUENCY_BAND", act.getId() + " " + EegActivity.Band.valueOf(act.get(EegActivity.band)).numericValue().intValue()); labelMap.put("HEMISPHERE", act.getId() + " " + EegActivity.Hemisphere.valueOf(act.get(EegActivity.hemisphere)).numericValue().intValue()); labelMap.put("DISPERSAL", act.getId() + " " + EegActivity.Dispersal.valueOf(act.get(EegActivity.dispersal)).numericValue().intValue()); labelMap.put("RECURRENCE", act.getId() + " " + EegActivity.Recurrence.valueOf(act.get(EegActivity.recurrence)).numericValue().intValue()); labelMap.put("BACKGROUND", act.getId() + " " + EegActivity.In_Background.valueOf(act.get(EegActivity.in_background)).numericValue().intValue()); labelMap.put("MAGNITUDE", act.getId() + " " + EegActivity.Magnitude.valueOf(act.get(EegActivity.magnitude)).numericValue().intValue()); act.getLocations().forEach(loc -> labelMap.put(loc.toString(), act.getId() + " " + 1.0)); labelMap.put("MODALITY", act.getId() + " " + ModalityLabel.valueOf(act.get(EegActivity.modality)).numericValue().intValue()); labelMap.put("POLARITY", act.getId() + " " + PolarityLabel.fromString(act.get(EegActivity.polarity)).numericValue().intValue()); }); try { final Path path = Paths.get(outDir).resolve("activity"); path.toFile().mkdir(); Files.write(path.resolve("activity_attr.svml"), vectors); for (final String lbl : labelMap.keySet()) { Files.write(path.resolve(lbl + ".lbl"), labelMap.get(lbl)); } } catch (IOException e) { throw new RuntimeException(e); } } public static <D extends BaseDocument> void writeEventVectors(final List<Document<D>> documents, final String outDir, final String annset) { final AnnotationVectorizer<Event> vectorizer = new AnnotationVectorizer<Event>(FeatureUtils.attributeFeatureExtractors(annset), a -> EnumLabel.NULL, new IntIdentifier<>()); final List<String> vectors = Lists.newArrayList(); final Multimap<String, String> labelMap = HashMultimap.create(); documents.parallelStream().flatMap(doc -> doc.get(annset, Event.TYPE).stream()).forEach(act -> { vectors.add(act.getId() + " " + vectorizer.vectorizeAnnotation(act).noLabel()); labelMap.put("TYPE", act.getId() + " " + EventTypeLabel.valueOf(act.get(Event.type)).numericValue().intValue()); labelMap.put("MODALITY", act.getId() + " " + ModalityLabel.valueOf(act.get(Event.modality)).numericValue().intValue()); labelMap.put("POLARITY", act.getId() + " " + PolarityLabel.fromString(act.get(Event.polarity)).numericValue().intValue()); }); try { final Path path = Paths.get(outDir).resolve("event"); path.toFile().mkdir(); Files.write(path.resolve("activity_attr.svml"), vectors); for (final String lbl : labelMap.keySet()) { Files.write(path.resolve(lbl + ".lbl"), labelMap.get(lbl)); } } catch (IOException e) { throw new RuntimeException(e); } } public static List<AttributeConfidence> readActivityConfidences(final Path path) { try { final List<String> lines = Files.readAllLines(path); return lines.stream().map(AttributeConfidence::new).collect(Collectors.toList()); } catch (IOException e) { throw new RuntimeException(e); } } public static <D extends BaseDocument> void writeBoundaryVectors(final List<Document<D>> documents, final String outDir, final String annset) { final CountingSparseFeatureVectorizer<Number> vectorizer = new CountingSparseFeatureVectorizer<>(); // final AnnotationVectorizer<Token> avectorizer = new AnnotationVectorizer<>( // FeatureUtils.boundaryDetectionFeatureExtractors(), // FeatureUtils.boundaryLabeler(annset, EegActivity.TYPE), new IntIdentifier<>()); // final AnnotationVectorizer<Token> evectorizer = new AnnotationVectorizer<>( // FeatureUtils.boundaryDetectionFeatureExtractors(), // FeatureUtils.boundaryLabeler(annset, Event.TYPE), new IntIdentifier<>()); final List<List<Pair<Label, SparseFeatureVector<Number>>>> as = Lists.newArrayList(), es = Lists.newArrayList(); final String sas = "opennlp", tas = "genia"; final Multiset<Integer> sizes = HashMultiset.create(); documents.forEach(doc -> { for (Sentence sentence : doc.get(sas, Sentence.TYPE)) { final List<Pair<Label, SparseFeatureVector<Number>>> alist = Lists.newArrayList(), elist = Lists.newArrayList(); int size = 0; for (Token token : sentence.getContained(tas, Token.TYPE)) { final SparseFeatureVector<Number> fv = vectorizer.vectorize(FeatureUtils.boundaryDetectionFeatureExtractors().stream() .flatMap(fe -> fe.apply(token)) .map(Feature::toNumericFeature)); alist.add(new Pair<>(FeatureUtils.ioBoundaryLabeler(annset, EegActivity.TYPE).apply(token), fv)); elist.add(new Pair<>(FeatureUtils.ioBoundaryLabeler(annset, Event.TYPE).apply(token), fv)); size++; } sizes.add(size); as.add(alist); es.add(elist); } doc.close(); }); log.info("num sentences: {}", sizes.size()); final int gt20 = (int)sizes.stream().filter(s -> s > 38).mapToInt(s -> s).count(); final int gt35 = (int)sizes.stream().filter(s -> s > 39).mapToInt(s -> s).count(); log.info("num sentences with length > 38: {}, {}%", gt20, 100.0 * gt20 / sizes.size()); log.info("num sentences with length > 39: {}, {}%", gt35, 100.0 * gt35 / sizes.size()); vectorizer.lockAndRemoveUncommonFeatures(2); try { final Path apath = Paths.get(outDir).resolve("activity"); apath.toFile().mkdir(); Files.write(apath.resolve("boundary.svml"), getVectorStrings(as, vectorizer)); vectorizer.getFeatureIdentifier().toFile(apath.resolve("boundary.tsv")); final Path epath = Paths.get(outDir).resolve("event"); epath.toFile().mkdir(); Files.write(epath.resolve("boundary.svml"), getVectorStrings(es, vectorizer)); vectorizer.getFeatureIdentifier().toFile(epath.resolve("boundary.tsv")); } catch (IOException e) { throw new RuntimeException(e); } } public static <D extends BaseDocument> List<List<String>> generateUnlabeledBoundaryVectors( final List<Document<D>> documents, final IntIdentifier<String> iid) { final SparseFeatureVectorizer<Number> vectorizer = new SparseFeatureVectorizer<>(iid); final String sas = "opennlp", tas = "genia"; final List<List<String>> vectorStrings = new ArrayList<>(); documents.forEach(doc -> { for (Sentence sentence : doc.get(sas, Sentence.TYPE)) { final List<String> sequence = new ArrayList<>(); for (Token token : sentence.getContained(tas, Token.TYPE)) { final SparseFeatureVector<Number> fv = vectorizer.vectorize(FeatureUtils.boundaryDetectionFeatureExtractors().stream() .flatMap(fe -> fe.apply(token)) .map(Feature::toNumericFeature)); sequence.add(IoLabel.O + " " + VectorUtils.toZeroIndexedSvmlWithId(fv, doc.getId() + "|" + sentence.getId() + "|" + token.getId())); } vectorStrings.add(sequence); } }); return vectorStrings; } public static <D extends BaseDocument> void writeUnlabeledBoundaryVectors(final List<Document<D>> documents, final String outDir, final String iidFile, final String outfileName) { final List<String> vectorStrings = generateUnlabeledBoundaryVectors(documents, IntIdentifier.fromFile(iidFile).lock()).stream() .reduce((l1, l2) -> {l1.add(""); l1.addAll(l2); return l1;}).get(); try { Files.write(Paths.get(outDir).resolve(outfileName), vectorStrings); log.info("Wrote {} lines to {}", vectorStrings.size(), Paths.get(outDir).resolve(outfileName)); } catch (IOException e) { throw new RuntimeException(e); } } private static List<String> getVectorStrings(List<List<Pair<Label, SparseFeatureVector<Number>>>> labeledVectorLists, CountingSparseFeatureVectorizer<Number> vectorizer) { final List<String> strings = new ArrayList<>(); for (List<Pair<Label, SparseFeatureVector<Number>>> list : labeledVectorLists) { for (Pair<Label, SparseFeatureVector<Number>> pair : list) { strings.add(pair.first() + " " + VectorUtils.toZeroIndexedSvml(vectorizer.removeUncommon(pair.second()))); } strings.add(""); } return strings; } }
true
3c377ad04dcf1b599ab9d40982156dbd4b853d17
Java
anr007/Shaurya2K17
/app/src/main/java/red/shaurya2k17/Sports/Cricket/DataEntryCricketStart.java
UTF-8
6,978
1.945313
2
[]
no_license
package red.shaurya2k17.Sports.Cricket; import android.content.DialogInterface; import android.os.Bundle; import android.support.annotation.Nullable; import android.support.v4.app.Fragment; import android.support.v7.app.AlertDialog; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.AdapterView; import android.widget.ArrayAdapter; import android.widget.Button; import android.widget.EditText; import android.widget.Spinner; import com.google.firebase.database.DatabaseReference; import com.google.firebase.database.FirebaseDatabase; import red.shaurya2k17.Admin.DataEntryActivity; import red.shaurya2k17.R; public class DataEntryCricketStart extends Fragment implements AdapterView.OnItemSelectedListener { EditText mat_nam; EditText overs; String cate; Spinner t1; Spinner t2; String team1; String team2; Button next; DatabaseReference mRef; FirebaseDatabase database; public DataEntryCricketStart() { // Required empty public constructor } @Override public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { // Inflate the layout for this fragment return inflater.inflate(R.layout.fragment_data_entry_cricket_start, container, false); } @Override public void onViewCreated(View view, @Nullable Bundle savedInstanceState) { super.onViewCreated(view, savedInstanceState); cate = getArguments().getString("id"); database = FirebaseDatabase.getInstance(); mRef = database.getReference("ongoing"); // yet to be decided t1 = (Spinner) view.findViewById(R.id.t1_dec_st); ArrayAdapter<CharSequence> adapter_team1 = ArrayAdapter.createFromResource(getContext(), R.array.Team1, android.R.layout.simple_spinner_item); adapter_team1.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item); t1.setAdapter(adapter_team1); t1.setOnItemSelectedListener(this); t2 = (Spinner) view.findViewById(R.id.t2_dec_st); ArrayAdapter<CharSequence> adapter_team2 = ArrayAdapter.createFromResource(getContext(), R.array.Team2, android.R.layout.simple_spinner_item); adapter_team2.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item); t2.setAdapter(adapter_team2); t2.setOnItemSelectedListener(this); mat_nam = (EditText) view.findViewById(R.id.match_nam_dec_st); overs=(EditText) view.findViewById(R.id.tot_overs_dec_st); next=(Button)view.findViewById(R.id.next_start); next.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { if(v.getId() == R.id.next_start) { next_start(); } } }); } void next_start() { // we have to first create a object in ongoing match // enable card view in home layout // ongoing match obj should contain entries like // overs completed , runs scored , wickets taken , runrate etc.. // then replace with second frag //mRef.child(cate).child(mat_nam.getText().toString()).setValue(match); final AlertDialog alertDialog = new AlertDialog.Builder(getContext()).create(); alertDialog.setTitle("Save Confirmation"); alertDialog.setCancelable(true); alertDialog.setCanceledOnTouchOutside(true); alertDialog.setMessage("Do you want to Save this Data"); alertDialog.setIcon(R.drawable.ic_save_teal_500_48dp); alertDialog.setButton(DialogInterface.BUTTON_NEGATIVE, "Yes", new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog, int id) { CMatch cMatch=new CMatch(); cMatch.setMatchName(mat_nam.getText().toString()); cMatch.setOvers(overs.getText().toString()); cMatch.setTeam1(team1); cMatch.setTeam2(team2); cMatch.setTeam2Score("0"); cMatch.setTeam1Score("0"); cMatch.setComments(""); cMatch.setTossWon(""); cMatch.setWinner(""); cMatch.setTossWonPref(""); cMatch.setTeam1Wickets("0"); cMatch.setTeam2Wickets("0"); mRef.child(cate).child(mat_nam.getText().toString()).setValue(cMatch); mRef.child(cate).child(mat_nam.getText().toString()) .child("curr_over").setValue("0"); mRef.child(cate).child(mat_nam.getText().toString()) .child("curr_ball").setValue("0"); ((DataEntryActivity)getActivity()).mat_name=mat_nam.getText().toString(); ((DataEntryActivity)getActivity()).t1=team1; ((DataEntryActivity)getActivity()).t2=team2; ((DataEntryActivity)getActivity()).tovers=overs.getText().toString(); ((DataEntryActivity)getActivity()).curr_over="0"; ((DataEntryActivity)getActivity()).curr_ball="0"; ((DataEntryActivity)getActivity()).t1s="0"; ((DataEntryActivity)getActivity()).t2s="0"; ((DataEntryActivity)getActivity()).t1_wickets="0"; ((DataEntryActivity)getActivity()).t2_wickets="0"; //TODO: Think for other ways mRef= database.getReference("summary"); mRef.child(mat_nam.getText().toString()).child("0"). child("Status").setValue("Match Started"); ((DataEntryActivity)getActivity()). replaceFragments(DataEntryCricket2.class,false,null); } }); alertDialog.setButton(DialogInterface.BUTTON_POSITIVE,"No",new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog, int id) { alertDialog.cancel(); } }); alertDialog.show(); } @Override public void onItemSelected(AdapterView<?> adapterView, View view, int i, long l) { // i is position switch(adapterView.getId()){ case R.id.t1_dec_st: if(i>0) team1=t1.getItemAtPosition(i).toString(); break; case R.id.t2_dec_st: if(i>0) team2=t2.getItemAtPosition(i).toString(); break; } } @Override public void onNothingSelected(AdapterView<?> adapterView) { } }
true
7c630c2edec6608e0624dd52a513c34e4e46ee50
Java
exalibyr/Java
/Generic/src/main/java/Logic/Package.java
UTF-8
479
2.90625
3
[]
no_license
package Logic; public class Package { private int id; private int weight; private String address; public Package(int id, int weight, String address) { this.id = id; this.weight = weight; this.address = address; } @Override public String toString() { return "Package{" + "id=" + id + ", weight=" + weight + ", address='" + address + '\'' + '}'; } }
true
a85f9951031e3416abfa091d65594f117d6f8b55
Java
DoverDee/JavaBase
/src/main/java/com/doverdee/designpattern/structural/decorator/Decorator.java
UTF-8
279
2.78125
3
[]
no_license
package com.doverdee.designpattern.structural.decorator; public class Decorator extends Component { protected Component product; public Decorator(Component product) { this.product = product; } @Override public void execMethod() { product.execMethod(); } }
true
3600005e52c7e3f96729f70ed496fbb01acb7013
Java
10XMairing/Dagger2MVVM-photo-loader
/app/src/main/java/com/androidpopcorn/tenx/testapp/di/ExampleApp.java
UTF-8
1,006
2.046875
2
[]
no_license
package com.androidpopcorn.tenx.testapp.di; import android.app.Application; import android.arch.lifecycle.ViewModelProviders; import com.androidpopcorn.tenx.testapp.data.ApiService; import com.androidpopcorn.tenx.testapp.data.AppViewModel; import com.androidpopcorn.tenx.testapp.di.AppComponent; import com.androidpopcorn.tenx.testapp.di.DaggerAppComponent; import com.androidpopcorn.tenx.testapp.di.module.ApplicationModule; import javax.inject.Inject; import retrofit2.Retrofit; public class ExampleApp extends Application { @Inject Retrofit retrofit; private AppComponent component; @Override public void onCreate() { super.onCreate(); component = DaggerAppComponent.builder().applicationModule(new ApplicationModule(this)).build(); component.inject(this); } public ApiService getApiService(){ return retrofit.create(ApiService.class); } public AppComponent getComponent() { return component; } }
true
8432b0aa90a915b4a6750ce8ce3e715716bdad5f
Java
magicgis/outfile
/lydsj-webserver/SSM/esbapiSSM/src/com/naswork/service/TjnewjdrcRealtimeService.java
UTF-8
1,075
2.015625
2
[]
no_license
package com.naswork.service; import java.util.Date; import java.util.List; import com.naswork.model.TjnewjdrcRealtime; public interface TjnewjdrcRealtimeService { /** * 根据系统时间当前参数获得实时人数 * @param curDate * @return */ public List<TjnewjdrcRealtime> getNewjdrcRealTime(String curDate,String morning,String night,Integer id); /** * 获取全部subcount的综合 * @return */ Integer getAllCount(Double num,String startTime,String endTime); /** * 通过父id获取count * @param id * @return */ Integer getAllCountByParentId(Integer id,Double num,String startTime,String endTime); /** * 通过id获取某个id值下面的count * @param id * @return */ Integer getCountById(Integer id,String startTime,String endTime); /** *热门景点实时监测(TOP-N) * @param typeId * @param id * @return */ List<TjnewjdrcRealtime> getjqjdrcsspm(Integer typeId, Integer id, String startTime,String endTime); }
true
7865f78cacee7926bb0d7322d8a20125f50c8388
Java
zhiaixinyang/PersonalCollect
/src/main/java/com/example/mbenben/studydemo/layout/titlelayout/adapter/HeaderAndFooterWrapper.java
UTF-8
5,449
2.59375
3
[]
no_license
package com.example.mbenben.studydemo.layout.titlelayout.adapter; import android.support.v7.widget.GridLayoutManager; import android.support.v7.widget.RecyclerView; import android.support.v7.widget.StaggeredGridLayoutManager; import android.util.SparseArray; import android.view.View; import android.view.ViewGroup; /** * Created by ${GongWenbo} on 2018/4/24 0024. * * 原项目GItHub:https://github.com/GongWnbo/SuperRecycleView */ public class HeaderAndFooterWrapper extends RecyclerView.Adapter { private static final int BASE_ITEM_TYPE_HEADER = 100000; private static final int BASE_ITEM_TYPE_FOOTER = 200000; private static final SparseArray<View> mHeaderViews = new SparseArray<>(); private static final SparseArray<View> mFooterViews = new SparseArray<>(); private RecyclerView.Adapter mInnerAdapter; public HeaderAndFooterWrapper(RecyclerView.Adapter innerAdapter) { if (innerAdapter == null) { throw new NullPointerException("you must give me a adapter!"); } mInnerAdapter = innerAdapter; } public int getHeaderCount() { return mHeaderViews.size(); } public int getFooterCount() { return mFooterViews.size(); } public int getInnerCount() { return mInnerAdapter.getItemCount(); } public void addHeader(View view) { mHeaderViews.put(mHeaderViews.size() + BASE_ITEM_TYPE_HEADER, view); } public void addFooter(View view) { mFooterViews.put(mFooterViews.size() + BASE_ITEM_TYPE_FOOTER, view); } private boolean isHeaderViewPos(int position) { return position < getHeaderCount(); } private boolean isFooterViewPos(int position) { return position >= getHeaderCount() + getInnerCount(); } @Override public RecyclerView.ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) { if (mHeaderViews.get(viewType) != null) { return BaseViewHolder.createViewHolder(parent.getContext(), mHeaderViews.get(viewType)); } else if (mFooterViews.get(viewType) != null) { return BaseViewHolder.createViewHolder(parent.getContext(), mFooterViews.get(viewType)); } return mInnerAdapter.onCreateViewHolder(parent, viewType); } @Override public void onBindViewHolder(RecyclerView.ViewHolder holder, int position) { if (isHeaderViewPos(position)) { return; } else if (isFooterViewPos(position)) { return; } mInnerAdapter.onBindViewHolder(holder, position - getHeaderCount()); } @Override public int getItemViewType(int position) { if (isHeaderViewPos(position)) { return mHeaderViews.keyAt(position); } else if (isFooterViewPos(position)) { return mFooterViews.keyAt(position - getHeaderCount() - getInnerCount()); } return mInnerAdapter.getItemViewType(position - getHeaderCount()); } @Override public int getItemCount() { return getHeaderCount() + getInnerCount() + getFooterCount(); } /** * 解决GridLayoutManager一行显示问题 * * @param recyclerView */ @Override public void onAttachedToRecyclerView(RecyclerView recyclerView) { // 此处为什么要添加这行,考虑到被装饰类的重写 mInnerAdapter.onAttachedToRecyclerView(recyclerView); final RecyclerView.LayoutManager layoutManager = recyclerView.getLayoutManager(); if (layoutManager instanceof GridLayoutManager) { final GridLayoutManager gridLayoutManager = (GridLayoutManager) layoutManager; final GridLayoutManager.SpanSizeLookup spanSizeLookup = gridLayoutManager.getSpanSizeLookup(); gridLayoutManager.setSpanSizeLookup(new GridLayoutManager.SpanSizeLookup() { @Override public int getSpanSize(int position) { // TODO: 2018/4/24 0024 默认是一个view占一个位置,header和footer只要让他们占据一行,就可以完美解决 int viewType = getItemViewType(position); if (mHeaderViews.get(viewType) != null) { return gridLayoutManager.getSpanCount(); } else if (mFooterViews.get(viewType) != null) { return gridLayoutManager.getSpanCount(); } if (spanSizeLookup != null) { return spanSizeLookup.getSpanSize(position); } return 1; } }); gridLayoutManager.setSpanCount(gridLayoutManager.getSpanCount()); } } /** * 解决StaggeredGridLayoutManager一行显示问题 * * @param holder */ @Override public void onViewAttachedToWindow(RecyclerView.ViewHolder holder) { // 同上面 mInnerAdapter.onViewAttachedToWindow(holder); int layoutPosition = holder.getLayoutPosition(); if (isHeaderViewPos(layoutPosition) || isFooterViewPos(layoutPosition)) { ViewGroup.LayoutParams lp = holder.itemView.getLayoutParams(); if (lp != null && lp instanceof StaggeredGridLayoutManager.LayoutParams) { ((StaggeredGridLayoutManager.LayoutParams) lp).setFullSpan(true); } } } }
true
3e958485549b693caf9bfd0981a05e1b60fd494f
Java
sowjanyagudela/ATCS
/atcs.model/src/main/java/com/atcs/service/AircraftDataService.java
UTF-8
575
2.046875
2
[]
no_license
package com.atcs.service; import java.util.List; import com.atcs.dto.AircraftRequestDTO; import com.atcs.models.AircraftQueue; import com.atcs.util.AircraftEnum.AircraftType; public interface AircraftDataService { AircraftQueue addAircraft(AircraftRequestDTO aircraftRequestDTO); AircraftQueue getAircraft(Long aircraftId); List<AircraftQueue> getAircrafts(); void deleteAll(); void delete(Long aircraftId); List<AircraftQueue> getPriorityAircrafts(List<String> priorityList); AircraftQueue getLargeAircraftByType(AircraftType aircraftType); }
true
dae26869d9f34e8fee740b6d64186004edc3aa3e
Java
barni211/JavaBasics
/BankMaven/src/main/java/pl/lodz/uni/math/BankMaven/Transaction/WireOut.java
UTF-8
1,063
2.765625
3
[]
no_license
package pl.lodz.uni.math.BankMaven.Transaction; import java.util.Date; import java.util.logging.Logger; import pl.lodz.uni.math.BankMaven.User.Account; import pl.lodz.uni.math.BankMaven.User.User; public class WireOut extends Transaction{ private Account toAccount; private User user; private String swift; Logger logger = Logger.getAnonymousLogger(); public WireOut(User user, Account fromAcc,Account toAcc, Date date, String desc, Integer amount,String swift) { super(fromAcc, date, desc, amount); this.toAccount=toAcc; this.swift=swift; this.user=user; } @Override public boolean doTransaction() { try { this.fromAccount.addToHistory(this); this.fromAccount.saldoMinus(this.amount); this.toAccount.saldoPlus(this.amount); user.wireOut(); logger.info("Wire-out transaction done. The number of transaction is " + this.user.countWireOuts()); return true; } catch (Exception ex) { logger.info("Something went wrong. Transaction wasn't performed." + ex.toString()); ex.printStackTrace(); return false; } } }
true
66b5ee9daeaf6cd73de3e975baf1eb6b5da5a107
Java
dongdong331/test
/packages/services/BuiltInPrintService/src/com/android/bips/ipp/CancelJobTask.java
UTF-8
1,428
2.03125
2
[]
no_license
/* * Copyright (C) 2016 The Android Open Source Project * Copyright (C) 2016 Mopria Alliance, 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 com.android.bips.ipp; import android.os.AsyncTask; import android.util.Log; /** A background task that requests cancellation of a specific job */ class CancelJobTask extends AsyncTask<Void, Void, Void> { private static final String TAG = CancelJobTask.class.getSimpleName(); private static final boolean DEBUG = false; private final Backend mBackend; private final int mJobId; CancelJobTask(Backend backend, int jobId) { mBackend = backend; mJobId = jobId; } @Override protected Void doInBackground(Void... voids) { if (DEBUG) Log.d(TAG, "doInBackground() for " + mJobId); // Success will result in a jobCallback. mBackend.nativeCancelJob(mJobId); return null; } }
true
f16bb248049dc84d83959d251d21272fac63e3b1
Java
OmarBradley/RingRing
/app/src/main/java/olab/ringring/util/dialog/select/SelectDialogItemViewHolder.java
UTF-8
1,433
2.03125
2
[]
no_license
package olab.ringring.util.dialog.select; import android.support.v4.app.DialogFragment; import android.support.v7.widget.RecyclerView; import android.view.Gravity; import android.view.View; import android.view.ViewGroup; import android.widget.LinearLayout; import android.widget.TextView; import butterknife.Bind; import butterknife.ButterKnife; import lombok.Getter; import lombok.Setter; import olab.ringring.R; /** * Created by 재화 on 2016-05-31. */ public class SelectDialogItemViewHolder extends RecyclerView.ViewHolder { @Bind(R.id.text_select_dialog_item) TextView itemText; private View itemView; private DialogFragment dialog; public SelectDialogItemViewHolder(View itemView, DialogFragment dialog) { super(itemView); ButterKnife.bind(this, itemView); this.itemView = itemView; this.dialog = dialog; } public void setDialogItemViewAttribute(SelectDialogItemData data){ itemText.setText(data.getItemText()); itemView.setOnClickListener(view -> { data.getItemClickListener().onClick(dialog.getDialog() ,2); }); } public void setItemViewCenterAlign(){ LinearLayout.LayoutParams params = new LinearLayout.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.WRAP_CONTENT); params.gravity = Gravity.CENTER_HORIZONTAL; itemText.setGravity(Gravity.CENTER_HORIZONTAL); } }
true
d92adb32bddc726c45d467bebc945d1a3c4fe4cc
Java
langvatn/cryptography
/src/no/langvatn/cryptography/functions/GenerateAllPrimeNumbersForRsaFunction.java
UTF-8
909
3.125
3
[]
no_license
package no.langvatn.cryptography.functions; import java.util.List; import java.util.function.Function; import java.util.stream.Collectors; import java.util.stream.LongStream; public class GenerateAllPrimeNumbersForRsaFunction implements Function<Long, List<Long>> { private final IsPrimeNumberFunction isPrimeNumberFunction = new IsPrimeNumberFunction(); @Override public List<Long> apply(Long m) { System.out.println("Generating all possible prime numbers up to RSA where m=" + m + "."); return LongStream.rangeClosed(2, m / 2) .filter(value -> { if (value % 1_000_000 == 0) System.out.println(Math.round((double) value / ((double) m / 2) * 100) + "%"); return isPrimeNumberFunction.apply(value); }) .boxed() .collect(Collectors.toList()); } }
true
ef955d5fa5ba1449883e9ceb7d41f7d7c23c22b5
Java
ChiaraBartalotta/GITrends
/src/persistence/HashtagRepository.java
UTF-8
116
1.851563
2
[]
no_license
package persistence; import elements.Hashtag; public interface HashtagRepository { boolean insert(Hashtag ht); }
true
897aa0c40c7ecab35c66381e80dffadf9eac00f4
Java
victoralvarezvelilla/TFG
/TFG/src/AdminMainMenu.java
ISO-8859-1
4,539
2.75
3
[]
no_license
import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import java.awt.event.ItemEvent; import java.awt.event.ItemListener; import java.io.FileNotFoundException; import javax.swing.DefaultComboBoxModel; import javax.swing.JButton; import javax.swing.JComboBox; import javax.swing.JFrame; import javax.swing.JLabel; import javax.swing.JOptionPane; import javax.swing.JScrollPane; import javax.swing.JTable; import javax.swing.table.DefaultTableModel; public class AdminMainMenu extends JFrame implements ActionListener { private JFrame frame; private static JTable table; private static DefaultTableModel modelo; private JButton botonAniadir; private JButton botonEliminar; private JButton botonMatrices; private JButton botonCerrar; private static DefaultComboBoxModel comboEliminar; private static JComboBox combo; AdminMainMenu() { frame = new JFrame(); frame.setBounds(300, 200, 650, 400); frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); frame.setLocationRelativeTo(null); frame.setTitle("Menu de Administracin de usuarios "); frame.getContentPane().setLayout(null); frame.setResizable(false); frame.setVisible(true); botonAniadir = new JButton ("Aadir Usuarios"); botonAniadir.setBounds(485, 150, 150, 30); frame.getContentPane().add(botonAniadir); botonAniadir.addActionListener(this); comboEliminar = new DefaultComboBoxModel(); combo = new JComboBox(); combo.setBounds(100, 250, 100, 50); frame.getContentPane().add(combo); combo.setModel(comboEliminar); botonEliminar = new JButton("Eliminar Usuarios"); botonEliminar.setBounds(250, 250, 150, 30); frame.getContentPane().add(botonEliminar); botonEliminar.addActionListener(this); botonMatrices = new JButton("Matrices"); botonMatrices.setBounds(5, 20 , 105 ,20); frame.getContentPane().add(botonMatrices); botonMatrices.addActionListener(this); botonMatrices.setVisible(true); botonCerrar = new JButton("Salir"); botonCerrar.setBounds(500, 20, 100, 30); frame.getContentPane().add(botonCerrar); botonCerrar.addActionListener(this); llenarCombo(); String nombreUsuarioActual = DBConnection.getSesionName(); JLabel usuario = new JLabel("Bienvenido " + nombreUsuarioActual); usuario.setBounds(500, 57, 200, 20); frame.getContentPane().add(usuario); /*Tabla */ modelo = new DefaultTableModel() { @Override public boolean isCellEditable(int fila, int columna) { return false; //Con esto conseguimos que la tabla no se pueda editar } }; JScrollPane scroll = new JScrollPane(); table = new JTable(modelo); //Metemos el modelo dentro de la tabla modelo.addColumn("ID"); modelo.addColumn("Nombre"); //Aadimos las columnas a la tabla (tantas como queramos) modelo.addColumn("Apellidos"); modelo.addColumn("Nivel "); DBConnection.rellenarTabla(); //Llamamos al mtodo que rellena la tabla con los datos de la base de datos scroll.setViewportView(table); scroll.setBounds(120, 0, 350, 200); frame.getContentPane().add(scroll); } static void llenarCombo(){ comboEliminar.addElement("---Lista Usuarios---"); String [] listaUsuarios = DBConnection.llenar_combo(); for (int i= 0; i< listaUsuarios.length; i++){ comboEliminar.addElement(listaUsuarios[i]); } } static void vaciarCombo(){ combo.removeAllItems(); } static void aniadirFila(Object [] fila){ modelo.addRow(fila); } static void actualizarTabla(){ while(modelo.getRowCount() > 0) modelo.removeRow(0); } @Override public void actionPerformed(ActionEvent e) { // TODO Auto-generated method stub if(e.getSource() == botonAniadir) { Formulario formulario = new Formulario(); } if(e.getSource() == botonCerrar) { DBConnection.desconectar(); frame.dispose(); } if(e.getSource() == botonMatrices){ try { UserMainWindow menu= new UserMainWindow(); } catch (FileNotFoundException e1) { // TODO Auto-generated catch block e1.printStackTrace(); } frame.dispose(); } if(e.getSource() == botonEliminar){ String nombre = (String) combo.getSelectedItem(); if( nombre.equals("---Lista Usuarios---")){ JOptionPane.showMessageDialog(null, "Elija un usuario"); return; } DBConnection.eliminarUsuario(nombre); } } }
true
52ce3971ea1a3365b4268f088a2550bb533f3767
Java
Hemantctd/ShopoholicBuddyAndroidUpdated
/app/src/main/java/com/shopoholicbuddy/activities/SpecializedSkillActivity.java
UTF-8
12,865
1.867188
2
[]
no_license
package com.shopoholicbuddy.activities; import android.content.Intent; import android.os.Bundle; import android.support.v4.widget.SwipeRefreshLayout; import android.support.v7.app.AppCompatActivity; import android.support.v7.widget.LinearLayoutManager; import android.support.v7.widget.RecyclerView; import android.support.v7.widget.Toolbar; import android.view.View; import android.widget.FrameLayout; import android.widget.ImageView; import com.google.gson.Gson; import com.shopoholicbuddy.R; import com.shopoholicbuddy.adapters.SpecializedSkillAdapter; import com.shopoholicbuddy.customviews.CustomTextView; import com.shopoholicbuddy.interfaces.PopupItemDialogCallback; import com.shopoholicbuddy.interfaces.RecyclerCallBack; import com.shopoholicbuddy.models.productdealsresponse.ProductDealsResponse; import com.shopoholicbuddy.models.productdealsresponse.Result; import com.shopoholicbuddy.network.ApiCall; import com.shopoholicbuddy.network.ApiInterface; import com.shopoholicbuddy.network.NetworkListener; import com.shopoholicbuddy.network.RestApi; import com.shopoholicbuddy.utils.AppSharedPreference; import com.shopoholicbuddy.utils.AppUtils; import com.shopoholicbuddy.utils.Constants; import org.json.JSONException; import org.json.JSONObject; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import butterknife.BindView; import butterknife.ButterKnife; import butterknife.OnClick; import lal.adhish.gifprogressbar.GifView; import okhttp3.ResponseBody; import retrofit2.Call; public class SpecializedSkillActivity extends AppCompatActivity implements NetworkListener { @BindView(R.id.iv_back) ImageView ivBack; @BindView(R.id.tv_title) CustomTextView tvTitle; @BindView(R.id.layout_toolbar) Toolbar layoutToolbar; @BindView(R.id.recycle_view) RecyclerView recycleView; @BindView(R.id.swipe_refresh_layout) SwipeRefreshLayout swipeRefreshLayout; @BindView(R.id.layout_no_data_found) CustomTextView layoutNoDataFound; @BindView(R.id.gif_progress) GifView gifProgress; @BindView(R.id.progressBar) FrameLayout progressBar; private List<Result> productList; private SpecializedSkillAdapter specializedSkillAdapter; private boolean isMoreData; private int count = 0; private boolean isLoading, isPagination; private LinearLayoutManager linearLayoutManager; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_specialized_skill); ButterKnife.bind(this); initVariable(); setAdapter(); setListeners(); } /** * method to set listener on view */ private void setListeners() { swipeRefreshLayout.setOnRefreshListener(new SwipeRefreshLayout.OnRefreshListener() { @Override public void onRefresh() { if (AppUtils.getInstance().isInternetAvailable(SpecializedSkillActivity.this)) { count = 0; hitSpecializedSkillApi(); } } }); recycleView.setOnScrollListener(new RecyclerView.OnScrollListener() { @Override public void onScrolled(RecyclerView recyclerView, int dx, int dy) { super.onScrolled(recyclerView, dx, dy); if (isMoreData && !isLoading && !isPagination) { int firstVisibleItemPosition = linearLayoutManager.findFirstVisibleItemPosition(); int totalVisibleItems = linearLayoutManager.getItemCount(); if (firstVisibleItemPosition + totalVisibleItems >= productList.size() - 4) { if (AppUtils.getInstance().isInternetAvailable(SpecializedSkillActivity.this)) { isPagination = true; hitSpecializedSkillApi(); } } } } }); } private void initVariable() { gifProgress.setImageResource(R.drawable.shopholic_loader); ivBack.setVisibility(View.VISIBLE); productList = new ArrayList<>(); tvTitle.setText(R.string.sepecialized_skills); specializedSkillAdapter = new SpecializedSkillAdapter(this, productList, new RecyclerCallBack() { @Override public void onClick(final int position, View view) { switch (view.getId()) { case R.id.iv_chat_dots: AppUtils.getInstance().showMorePopUp(SpecializedSkillActivity.this, view, getString(R.string.edit), getString(R.string.delete), "", 3, new PopupItemDialogCallback() { @Override public void onItemOneClick() { startActivityForResult(new Intent(SpecializedSkillActivity.this, AddProductServiceActivity.class) .putExtra(Constants.IntentConstant.FROM_CLASS, Constants.AppConstant.PROFILE_SKILLS) .putExtra(Constants.IntentConstant.DEAL_ID, productList.get(position).getId()) .putExtra(Constants.IntentConstant.IS_PRODUCT, false) , Constants.IntentConstant.REQUEST_EDIT_DEAL); } @Override public void onItemTwoClick() { if (AppUtils.getInstance().isInternetAvailable(SpecializedSkillActivity.this)){ hitDeleteSpecializedSkillApi(productList.get(position).getId()); productList.remove(position); specializedSkillAdapter.notifyDataSetChanged(); if (productList.size() == 0) { layoutNoDataFound.setVisibility(View.VISIBLE); } else { layoutNoDataFound.setVisibility(View.GONE); } } } @Override public void onItemThreeClick() { } }); break; } } }); } @Override protected void onActivityResult(int requestCode, int resultCode, Intent data) { super.onActivityResult(requestCode, resultCode, data); if (requestCode == Constants.IntentConstant.REQUEST_EDIT_DEAL && resultCode ==RESULT_OK){ if (AppUtils.getInstance().isInternetAvailable(this)) { count = 0; hitSpecializedSkillApi(); } } } private void setAdapter() { linearLayoutManager = new LinearLayoutManager(this, LinearLayoutManager.VERTICAL, false); recycleView.setLayoutManager(linearLayoutManager); recycleView.setAdapter(specializedSkillAdapter); if (AppUtils.getInstance().isInternetAvailable(this)) { progressBar.setVisibility(View.VISIBLE); count = 0; hitSpecializedSkillApi(); } } @OnClick(R.id.iv_back) public void onViewClicked() { onBackPressed(); } /** * method to hit specialization skills */ private void hitSpecializedSkillApi() { ApiInterface apiInterface = RestApi.createServiceAccessToken(this, ApiInterface.class);//empty field is for the access token final HashMap<String, String> params = new HashMap<>(); params.put(Constants.NetworkConstant.PARAM_USER_ID, AppSharedPreference.getInstance().getString(this, AppSharedPreference.PREF_KEY.USER_ID)); params.put(Constants.NetworkConstant.PARAM_BUDDY_ID, AppSharedPreference.getInstance().getString(this, AppSharedPreference.PREF_KEY.USER_ID)); params.put(Constants.NetworkConstant.PARAM_PRODUCT_TYPE, Constants.NetworkConstant.SERVICE); params.put(Constants.NetworkConstant.PARAM_COUNT, String.valueOf(count)); Call<ResponseBody> call = apiInterface.hitBuddyDealsApi(AppUtils.getInstance().encryptData(params)); ApiCall.getInstance().hitService(this, call, this, Constants.NetworkConstant.BUDDY_DEAL); } /** * method to delete specialization skills * @param id */ private void hitDeleteSpecializedSkillApi(String id) { ApiInterface apiInterface = RestApi.createServiceAccessToken(this, ApiInterface.class);//empty field is for the access token final HashMap<String, String> params = new HashMap<>(); params.put(Constants.NetworkConstant.PARAM_USER_ID, AppSharedPreference.getInstance().getString(this, AppSharedPreference.PREF_KEY.USER_ID)); params.put(Constants.NetworkConstant.PARAM_SERVICE_ID, id); Call<ResponseBody> call = apiInterface.hitDeleteSkillsApi(AppUtils.getInstance().encryptData(params)); ApiCall.getInstance().hitService(this, call, this, Constants.NetworkConstant.REQUEST_DELETE_DEAL); } @Override public void onSuccess(int responseCode, String response, int requestCode) { isLoading = false; progressBar.setVisibility(View.GONE); if (swipeRefreshLayout.isRefreshing()) swipeRefreshLayout.setRefreshing(false); switch (requestCode) { case Constants.NetworkConstant.BUDDY_DEAL: switch (responseCode) { case Constants.NetworkConstant.SUCCESS_CODE: ProductDealsResponse dealsResponse = new Gson().fromJson(response, ProductDealsResponse.class); if (isPagination) { isPagination = false; } else { productList.clear(); } productList.addAll(dealsResponse.getResult()); specializedSkillAdapter.notifyDataSetChanged(); isMoreData = dealsResponse.getNext() != -1; if (isMoreData) count = dealsResponse.getNext(); if (productList.size() == 0) { layoutNoDataFound.setVisibility(View.VISIBLE); } else { layoutNoDataFound.setVisibility(View.GONE); } break; case Constants.NetworkConstant.NO_DATA: productList.clear(); specializedSkillAdapter.notifyDataSetChanged(); if (productList.size() > 0) { layoutNoDataFound.setVisibility(View.GONE); } else { layoutNoDataFound.setVisibility(View.VISIBLE); } break; default: try { AppUtils.getInstance().showToast(this, new JSONObject(response).optString(Constants.NetworkConstant.RESPONSE_MESSAGE)); } catch (JSONException e) { e.printStackTrace(); } } break; case Constants.NetworkConstant.REQUEST_DELETE_DEAL: switch (responseCode) { case Constants.NetworkConstant.SUCCESS_CODE: if (productList.size() == 0) { layoutNoDataFound.setVisibility(View.VISIBLE); } else { layoutNoDataFound.setVisibility(View.GONE); } break; default: try { AppUtils.getInstance().showToast(this, new JSONObject(response).optString(Constants.NetworkConstant.RESPONSE_MESSAGE)); } catch (JSONException e) { e.printStackTrace(); } } break; } } @Override public void onError(String response, int requestCode) { isLoading = false; isPagination = false; progressBar.setVisibility(View.GONE); if (swipeRefreshLayout.isRefreshing()) swipeRefreshLayout.setRefreshing(false); AppUtils.getInstance().showToast(this, response); } @Override public void onFailure() { isLoading = false; isPagination = false; progressBar.setVisibility(View.GONE); if (swipeRefreshLayout.isRefreshing()) swipeRefreshLayout.setRefreshing(false); } }
true
d511bc14fc5d2acb7f242b35aa7d4db60ed8c613
Java
AnnaLitskevitch/TrumpCovidGame
/src/Graphic/Camera.java
UTF-8
1,784
2.796875
3
[]
no_license
package Graphic; import Entitiy.Entity; import Tiles.Tile; import pangame.Game; import pangame.Handler; import java.util.Map; public class Camera { private float xoffset; private float yoffset; private Handler handler; public Camera(Handler handler, float xoffset, float yoffset) { this.xoffset = xoffset; this.yoffset = yoffset; this.handler = handler; } public void checkblankspace( ) { if (xoffset < 0) { xoffset = 0; } else if (xoffset > handler.getWorld().getWidth()* Tile.default_tilewidth - handler.getwidth()) { xoffset = handler.getWorld().getWidth()* Tile.default_tilewidth - handler.getwidth(); } if (yoffset < 0) { yoffset = 0; } else if (yoffset > handler.getWorld().getHeight()* Tile.default_tileheight - handler.getheight()) { yoffset = handler.getWorld().getHeight()* Tile.default_tileheight - handler.getheight(); } } public void move(float xamount, float yamount) { xoffset += xamount; yoffset += yamount; checkblankspace(); } public void centeronentity(Entity ent) { xoffset = ent.getX() - handler.getwidth()/2 + ent.getWidth()/2; yoffset = ent.getY() - handler.getheight()/2 + ent.getHeight()/2; checkblankspace(); } public void setXoffset(float xoffset) { this.xoffset = xoffset; checkblankspace(); } public void setYoffset(float yoffset) { this.yoffset = yoffset; checkblankspace(); } public float getXoffset() { return xoffset; } public float getYoffset() { return yoffset; } }
true
34c5a6329e9752576dfd9e3c8558e333f8ae40fb
Java
ashwinlakshman2/order-microservice
/micro-spring-order-master/src/main/java/com/ashwin/micro/order/domain/builders/CustomerBuilder.java
UTF-8
774
2.546875
3
[ "Apache-2.0" ]
permissive
package com.ashwin.micro.order.domain.builders; import com.ashwin.micro.order.domain.Customer; public final class CustomerBuilder { private String code; private String name; private String vat; private CustomerBuilder() { } public static CustomerBuilder customer() { return new CustomerBuilder(); } public CustomerBuilder withCode(String code) { this.code = code; return this; } public CustomerBuilder withName(String name) { this.name = name; return this; } public CustomerBuilder withVat(String vat) { this.vat = vat; return this; } public Customer build() { Customer customer = new Customer(); customer.setCode(code); customer.setName(name); customer.setVat(vat); return customer; } }
true
792ec85846c61aa0284eaa8513e0d2323bae8741
Java
apgallego/TicTacToe_v0
/src/TicTacToe/Player.java
UTF-8
1,724
3.6875
4
[]
no_license
package TicTacToe; class Player extends Players { public Player(char token, boolean startsFirst) { super(token, startsFirst); } /** * Function which "translates" a placement. Instead of writing, i.e., x,y coords, we can just write a number 1-9 regarding the template. * @param pos : int : variable which represents the position we want for our token. * @param board : char[][] : matrix which represents the game board. */ public void placeToken(int pos, char[][] board) { switch (pos) { case 1: board[0][0] = super.getToken(); TicTacToe.displayBoard(board); TicTacToe.threeInARow(board, getToken()); break; case 2: board[0][1] = super.getToken(); TicTacToe.displayBoard(board); TicTacToe.threeInARow(board, getToken()); break; case 3: board[0][2] = super.getToken(); TicTacToe.displayBoard(board); TicTacToe.threeInARow(board, getToken()); break; case 4: board[1][0] = super.getToken(); TicTacToe.displayBoard(board); TicTacToe.threeInARow(board, getToken()); break; case 5: board[1][1] = super.getToken(); TicTacToe.displayBoard(board); TicTacToe.threeInARow(board, getToken()); break; case 6: board[1][2] = super.getToken(); TicTacToe.displayBoard(board); TicTacToe.threeInARow(board, getToken()); break; case 7: board[2][0] = super.getToken(); TicTacToe.displayBoard(board); TicTacToe.threeInARow(board, getToken()); break; case 8: board[2][1] = super.getToken(); TicTacToe.displayBoard(board); TicTacToe.threeInARow(board, getToken()); break; case 9: board[2][2] = super.getToken(); TicTacToe.displayBoard(board); TicTacToe.threeInARow(board, getToken()); break; } } }
true
b80166659525d55d77026d7b5f49beff1ec31e29
Java
meijieman/Beauty
/app/src/main/java/com/major/beauty/dao/BaseDao.java
UTF-8
685
2.140625
2
[]
no_license
package com.major.beauty.dao; import com.litesuits.orm.LiteOrm; import com.major.beauty.base.App; import com.major.beauty.bean.Base; import java.util.List; /** * @desc: TODO * @author: Major * @since: 2019/9/8 19:48 */ public abstract class BaseDao<T extends Base> { protected static LiteOrm liteOrm = App.getInstance().getLiteOrm(); public abstract List<T> query(); public long queryCount() { List<T> query = query(); return query == null ? 0 : query.size(); } public T queryById(long id, Class<T> clazz) { return liteOrm.queryById(id, clazz); } public long insertOrUpdate(T t) { return liteOrm.save(t); } }
true
801ccd196a2fdd48e4edc20381497186407c7ab9
Java
filimonadrian/java-training
/_8_functional/src/main/java/code/_4_student_effort/LambdaTest.java
UTF-8
2,515
4.3125
4
[]
no_license
package code._4_student_effort; import java.util.*; public class LambdaTest { /* * Exercise 1 * Create a string that consists of the first letter of each word in the list * of Strings. */ private void exercise1() { List<String> words = new ArrayList<>(Arrays.asList("Java", "Developer", "Keen")); StringBuilder s = new StringBuilder(); // words.stream().forEach(word -> s.append(word.charAt(0))); words.forEach(word -> s.append(word.charAt(0))); System.out.println("Exercise 1: " + s.toString()); } /* * Exercise 2 * Remove the words that have odd lengths from the list. */ private void exercise2() { List<String> words = new ArrayList<>(Arrays.asList("Java", "Developer", "Keen", "odd")); System.out.println("Exercise 2: "); words.stream().filter(word -> word.length() % 2 == 0) .forEach(System.out::println); // words.removeIf(word -> word.length() % 2 != 0); // words.forEach(System.out::println); } /* * Exercise 3 * Replace every word in the list with its upper case equivalent. */ private void exercise3() { List<String> words = new ArrayList<>(Arrays.asList("Java", "Developer", "Keen", "odd")); System.out.println("Exercise 3: "); words.stream().map(String::toUpperCase) .forEach(System.out::println); } /* * Exercise 4 * Convert every key-value pair of the map into a string and append them all * into a single string, in iteration order. */ private void exercise4() { Map<String, Integer> map = new HashMap<>(); map.put("java", 1); map.put("Developer", 2); map.put("keen", 3); map.put("odd", 4); StringBuilder s = new StringBuilder(); map.forEach((key, value) -> s.append(key).append(" ") .append(value.toString()).append("\n")); System.out.println("Exercise 4: "); System.out.println(s); } private void exercise5() { List<String> words = new ArrayList<>(Arrays.asList("Java", "Developer", "Keen", "odd")); System.out.println("Exercise 5 "); new Thread(() -> words.forEach(System.out::println)).start(); } public static void main(String[] args) { LambdaTest l = new LambdaTest(); l.exercise1(); l.exercise2(); l.exercise3(); l.exercise4(); l.exercise5(); } }
true
b5cb89fc45421f2dc929a6ee739226477d4bbf00
Java
zhongxingyu/Seer
/Diff-Raw-Data/7/7_d4546df5fe1ead90bb97be83a5435590c716c5c0/ConfigFrame/7_d4546df5fe1ead90bb97be83a5435590c716c5c0_ConfigFrame_t.java
UTF-8
29,696
2.203125
2
[]
no_license
/* * ConfigFrame.java * * Created on 20. červenec 2007, 18:59 */ package esmska.gui; import com.jgoodies.looks.plastic.PlasticLookAndFeel; import com.jgoodies.looks.plastic.PlasticTheme; import esmska.*; import java.awt.Font; import java.awt.event.KeyEvent; import java.util.ArrayList; import java.util.logging.Level; import java.util.logging.Logger; import javax.swing.DefaultComboBoxModel; import javax.swing.ImageIcon; import org.jvnet.substance.SubstanceLookAndFeel; import org.jvnet.substance.skin.SkinInfo; import esmska.persistence.PersistenceManager; import javax.swing.SwingUtilities; /** Configure settings form * * @author ripper */ public class ConfigFrame extends javax.swing.JFrame { private static final Logger logger = Logger.getLogger(ConfigFrame.class.getName()); private static final String RES = "/esmska/resources/"; /* when to take updates seriously */ private boolean fullyInicialized; private final String LAF_SYSTEM = "Systémový"; private final String LAF_CROSSPLATFORM = "Meziplatformní"; private final String LAF_GTK = "GTK"; private final String LAF_JGOODIES = "JGoodies"; private final String LAF_SUBSTANCE = "Substance"; /* the active LaF when dialog is opened, needed for live-updating LaF skins */ private String lafWhenLoaded; /** Creates new form ConfigFrame */ public ConfigFrame() { initComponents(); tabbedPane.setMnemonicAt(0, KeyEvent.VK_O); tabbedPane.setMnemonicAt(1, KeyEvent.VK_H); tabbedPane.setMnemonicAt(2, KeyEvent.VK_V); tabbedPane.setIconAt(0, new ImageIcon(getClass().getResource(RES + "config-16.png"))); tabbedPane.setIconAt(1, new ImageIcon(getClass().getResource(RES + "appearance-small.png"))); tabbedPane.setIconAt(2, new ImageIcon(getClass().getResource(RES + "operators/Vodafone.png"))); closeButton.requestFocusInWindow(); lafComboBox.setModel(new DefaultComboBoxModel(new String[] { LAF_SYSTEM, LAF_CROSSPLATFORM, LAF_GTK, LAF_JGOODIES, LAF_SUBSTANCE})); if (config.getLookAndFeel().equals(ThemeManager.LAF_SYSTEM)) lafComboBox.setSelectedItem(LAF_SYSTEM); else if (config.getLookAndFeel().equals(ThemeManager.LAF_CROSSPLATFORM)) lafComboBox.setSelectedItem(LAF_CROSSPLATFORM); else if (config.getLookAndFeel().equals(ThemeManager.LAF_GTK)) lafComboBox.setSelectedItem(LAF_GTK); else if (config.getLookAndFeel().equals(ThemeManager.LAF_JGOODIES)) lafComboBox.setSelectedItem(LAF_JGOODIES); else if (config.getLookAndFeel().equals(ThemeManager.LAF_SUBSTANCE)) lafComboBox.setSelectedItem(LAF_SUBSTANCE); lafWhenLoaded = (String) lafComboBox.getSelectedItem(); updateThemeComboBox(); fullyInicialized = true; } private void updateThemeComboBox() { themeComboBox.setEnabled(false); String laf = (String) lafComboBox.getSelectedItem(); if (laf.equals(LAF_JGOODIES)) { ArrayList<String> themes = new ArrayList<String>(); for (Object o : PlasticLookAndFeel.getInstalledThemes()) themes.add(((PlasticTheme)o).getName()); themeComboBox.setModel(new DefaultComboBoxModel(themes.toArray())); themeComboBox.setSelectedItem(config.getLafJGoodiesTheme()); themeComboBox.setEnabled(true); } else if (laf.equals(LAF_SUBSTANCE)) { ArrayList<String> themes = new ArrayList<String>(); new SubstanceLookAndFeel(); for (SkinInfo skinInfo : SubstanceLookAndFeel.getAllSkins().values()) themes.add(skinInfo.getDisplayName()); themeComboBox.setModel(new DefaultComboBoxModel(themes.toArray())); themeComboBox.setSelectedItem(config.getLafSubstanceSkin()); themeComboBox.setEnabled(true); } } /** This method is called from within the constructor to * initialize the form. * WARNING: Do NOT modify this code. The content of this method is * always regenerated by the Form Editor. */ // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents private void initComponents() { bindingGroup = new org.jdesktop.beansbinding.BindingGroup(); config = PersistenceManager.getConfig(); tabbedPane = new javax.swing.JTabbedPane(); jPanel1 = new javax.swing.JPanel(); rememberQueueCheckBox = new javax.swing.JCheckBox(); removeAccentsCheckBox = new javax.swing.JCheckBox(); checkUpdatesCheckBox = new javax.swing.JCheckBox(); rememberHistoryCheckBox = new javax.swing.JCheckBox(); jPanel3 = new javax.swing.JPanel(); lafComboBox = new javax.swing.JComboBox(); rememberLayoutCheckBox = new javax.swing.JCheckBox(); jLabel4 = new javax.swing.JLabel(); jLabel7 = new javax.swing.JLabel(); themeComboBox = new javax.swing.JComboBox(); jLabel6 = new javax.swing.JLabel(); windowDecorationsCheckBox = new javax.swing.JCheckBox(); windowCenteredCheckBox = new javax.swing.JCheckBox(); toolbarVisibleCheckBox = new javax.swing.JCheckBox(); jLabel5 = new javax.swing.JLabel(); jPanel2 = new javax.swing.JPanel(); useSenderIDCheckBox = new javax.swing.JCheckBox(); jLabel1 = new javax.swing.JLabel(); jLabel2 = new javax.swing.JLabel(); senderNumberTextField = new javax.swing.JTextField(); senderNameTextField = new javax.swing.JTextField(); jLabel3 = new javax.swing.JLabel(); closeButton = new javax.swing.JButton(); setDefaultCloseOperation(javax.swing.WindowConstants.DISPOSE_ON_CLOSE); setTitle("Nastavení - Esmska"); setIconImage(new ImageIcon(getClass().getResource(RES + "config-48.png")).getImage()); addWindowFocusListener(new java.awt.event.WindowFocusListener() { public void windowGainedFocus(java.awt.event.WindowEvent evt) { } public void windowLostFocus(java.awt.event.WindowEvent evt) { formWindowLostFocus(evt); } }); rememberQueueCheckBox.setMnemonic('f'); rememberQueueCheckBox.setText("Ukládat frontu neodeslaných sms"); rememberQueueCheckBox.setToolTipText("<html>\nPři ukončení programu uchovává frontu neodeslaných sms pro příští spuštění programu\n</html>"); org.jdesktop.beansbinding.Binding binding = org.jdesktop.beansbinding.Bindings.createAutoBinding(org.jdesktop.beansbinding.AutoBinding.UpdateStrategy.READ_WRITE, config, org.jdesktop.beansbinding.ELProperty.create("${rememberQueue}"), rememberQueueCheckBox, org.jdesktop.beansbinding.BeanProperty.create("selected")); bindingGroup.addBinding(binding); removeAccentsCheckBox.setMnemonic('d'); removeAccentsCheckBox.setText("Ze zpráv odstraňovat diakritiku"); removeAccentsCheckBox.setToolTipText("<html>\nPřed odesláním zprávy z ní odstraní všechna diakritická znaménka\n</html>"); binding = org.jdesktop.beansbinding.Bindings.createAutoBinding(org.jdesktop.beansbinding.AutoBinding.UpdateStrategy.READ_WRITE, config, org.jdesktop.beansbinding.ELProperty.create("${removeAccents}"), removeAccentsCheckBox, org.jdesktop.beansbinding.BeanProperty.create("selected")); bindingGroup.addBinding(binding); checkUpdatesCheckBox.setMnemonic('n'); checkUpdatesCheckBox.setText("Kontrolovat po startu novou verzi programu"); checkUpdatesCheckBox.setToolTipText("<html>\nPo spuštění programu zkontrolovat, zda nevyšla novější<br>\nverze programu, a případně upozornit ve stavovém řádku\n</html>"); binding = org.jdesktop.beansbinding.Bindings.createAutoBinding(org.jdesktop.beansbinding.AutoBinding.UpdateStrategy.READ_WRITE, config, org.jdesktop.beansbinding.ELProperty.create("${checkForUpdates}"), checkUpdatesCheckBox, org.jdesktop.beansbinding.BeanProperty.create("selected")); bindingGroup.addBinding(binding); rememberHistoryCheckBox.setMnemonic('s'); rememberHistoryCheckBox.setText("Ukládat historii odeslaných sms"); rememberHistoryCheckBox.setToolTipText("<html>\nPři ukončení programu uchovává historii odeslaných sms pro příští spuštění programu\n</html>"); binding = org.jdesktop.beansbinding.Bindings.createAutoBinding(org.jdesktop.beansbinding.AutoBinding.UpdateStrategy.READ_WRITE, config, org.jdesktop.beansbinding.ELProperty.create("${rememberHistory}"), rememberHistoryCheckBox, org.jdesktop.beansbinding.BeanProperty.create("selected")); bindingGroup.addBinding(binding); 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(rememberHistoryCheckBox) .addComponent(rememberQueueCheckBox) .addComponent(removeAccentsCheckBox) .addComponent(checkUpdatesCheckBox)) .addContainerGap(189, Short.MAX_VALUE)) ); jPanel1Layout.setVerticalGroup( jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(jPanel1Layout.createSequentialGroup() .addContainerGap() .addComponent(rememberQueueCheckBox) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addComponent(rememberHistoryCheckBox) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addComponent(removeAccentsCheckBox) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addComponent(checkUpdatesCheckBox) .addContainerGap(183, Short.MAX_VALUE)) ); tabbedPane.addTab("Obecné", jPanel1); lafComboBox.setToolTipText("<html>\nUmožní vám změnit vzhled programu\n</html>"); lafComboBox.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { lafComboBoxActionPerformed(evt); } }); rememberLayoutCheckBox.setMnemonic('r'); rememberLayoutCheckBox.setText("Pamatovat rozvržení formuláře"); rememberLayoutCheckBox.setToolTipText("<html>\nPoužije aktuální rozměry programu a prvků formuláře při příštím spuštění programu\n</html>"); binding = org.jdesktop.beansbinding.Bindings.createAutoBinding(org.jdesktop.beansbinding.AutoBinding.UpdateStrategy.READ_WRITE, config, org.jdesktop.beansbinding.ELProperty.create("${rememberLayout}"), rememberLayoutCheckBox, org.jdesktop.beansbinding.BeanProperty.create("selected")); bindingGroup.addBinding(binding); jLabel4.setDisplayedMnemonic('d'); jLabel4.setLabelFor(lafComboBox); jLabel4.setText("Vzhled:"); jLabel4.setToolTipText(lafComboBox.getToolTipText()); jLabel7.setFont(jLabel7.getFont().deriveFont(Font.ITALIC)); jLabel7.setText("* Pro projevení změn je nutný restart programu!"); themeComboBox.setToolTipText("<html>\nBarevná schémata pro zvolený vzhled\n</html>"); themeComboBox.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { themeComboBoxActionPerformed(evt); } }); jLabel6.setDisplayedMnemonic('m'); jLabel6.setLabelFor(themeComboBox); jLabel6.setText("Motiv:"); jLabel6.setToolTipText(themeComboBox.getToolTipText()); windowDecorationsCheckBox.setMnemonic('p'); windowDecorationsCheckBox.setText("Použít vzhled i na okraje oken *"); windowDecorationsCheckBox.setToolTipText("<html>\nZda má místo operačního systému vykreslovat<br>\nrámečky oken zvolený vzhled\n</html>"); binding = org.jdesktop.beansbinding.Bindings.createAutoBinding(org.jdesktop.beansbinding.AutoBinding.UpdateStrategy.READ_WRITE, config, org.jdesktop.beansbinding.ELProperty.create("${lafWindowDecorated}"), windowDecorationsCheckBox, org.jdesktop.beansbinding.BeanProperty.create("selected")); bindingGroup.addBinding(binding); windowCenteredCheckBox.setMnemonic('u'); windowCenteredCheckBox.setText("Spustit program uprostřed obrazovky"); windowCenteredCheckBox.setToolTipText("<html>Zda-li nechat umístění okna programu na operačním systému,<br>\nnebo ho umístit vždy doprostřed obrazovky</html>"); binding = org.jdesktop.beansbinding.Bindings.createAutoBinding(org.jdesktop.beansbinding.AutoBinding.UpdateStrategy.READ_WRITE, config, org.jdesktop.beansbinding.ELProperty.create("${startCentered}"), windowCenteredCheckBox, org.jdesktop.beansbinding.BeanProperty.create("selected")); bindingGroup.addBinding(binding); toolbarVisibleCheckBox.setMnemonic('z'); toolbarVisibleCheckBox.setText("Zobrazit panel nástrojů"); toolbarVisibleCheckBox.setToolTipText("<html>\nZobrazit panel nástrojů, který umožňuje rychlejší ovládání myší některých akcí\n</html>"); binding = org.jdesktop.beansbinding.Bindings.createAutoBinding(org.jdesktop.beansbinding.AutoBinding.UpdateStrategy.READ_WRITE, config, org.jdesktop.beansbinding.ELProperty.create("${toolbarVisible}"), toolbarVisibleCheckBox, org.jdesktop.beansbinding.BeanProperty.create("selected")); bindingGroup.addBinding(binding); jLabel5.setText("*"); javax.swing.GroupLayout jPanel3Layout = new javax.swing.GroupLayout(jPanel3); jPanel3.setLayout(jPanel3Layout); jPanel3Layout.setHorizontalGroup( jPanel3Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(jPanel3Layout.createSequentialGroup() .addContainerGap() .addGroup(jPanel3Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addComponent(toolbarVisibleCheckBox) .addComponent(windowCenteredCheckBox) .addGroup(jPanel3Layout.createSequentialGroup() .addGroup(jPanel3Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addComponent(jLabel4) .addComponent(jLabel6)) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addGroup(jPanel3Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addComponent(themeComboBox, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE) .addGroup(jPanel3Layout.createSequentialGroup() .addComponent(lafComboBox, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addComponent(jLabel5)))) .addComponent(jLabel7, javax.swing.GroupLayout.DEFAULT_SIZE, 436, Short.MAX_VALUE) .addComponent(windowDecorationsCheckBox) .addComponent(rememberLayoutCheckBox)) .addContainerGap()) ); jPanel3Layout.linkSize(javax.swing.SwingConstants.HORIZONTAL, new java.awt.Component[] {lafComboBox, themeComboBox}); jPanel3Layout.setVerticalGroup( jPanel3Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(jPanel3Layout.createSequentialGroup() .addContainerGap() .addGroup(jPanel3Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE) .addComponent(jLabel4) .addComponent(lafComboBox, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE) .addComponent(jLabel5)) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addGroup(jPanel3Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE) .addComponent(jLabel6) .addComponent(themeComboBox, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addComponent(windowDecorationsCheckBox) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addComponent(rememberLayoutCheckBox) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addComponent(windowCenteredCheckBox) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addComponent(toolbarVisibleCheckBox) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, 99, Short.MAX_VALUE) .addComponent(jLabel7) .addContainerGap()) ); jPanel3Layout.linkSize(javax.swing.SwingConstants.VERTICAL, new java.awt.Component[] {lafComboBox, themeComboBox}); tabbedPane.addTab("Vzhled", jPanel3); useSenderIDCheckBox.setMnemonic('p'); useSenderIDCheckBox.setText("Připojovat podpis odesilatele"); useSenderIDCheckBox.setToolTipText("<html>Při připojení podpisu přijde sms adresátovi ze zadaného čísla<br>\na s daným jménem napsaným na konci zprávy</html>"); binding = org.jdesktop.beansbinding.Bindings.createAutoBinding(org.jdesktop.beansbinding.AutoBinding.UpdateStrategy.READ_WRITE, config, org.jdesktop.beansbinding.ELProperty.create("${useSenderID}"), useSenderIDCheckBox, org.jdesktop.beansbinding.BeanProperty.create("selected")); bindingGroup.addBinding(binding); jLabel1.setDisplayedMnemonic('l'); jLabel1.setLabelFor(senderNumberTextField); jLabel1.setText("Číslo"); jLabel2.setText("+420"); senderNumberTextField.setColumns(9); senderNumberTextField.setText(config.getSenderNumber() != null ? config.getSenderNumber().replaceFirst("^\\+420", "") : null); binding = org.jdesktop.beansbinding.Bindings.createAutoBinding(org.jdesktop.beansbinding.AutoBinding.UpdateStrategy.READ, useSenderIDCheckBox, org.jdesktop.beansbinding.ELProperty.create("${selected}"), senderNumberTextField, org.jdesktop.beansbinding.BeanProperty.create("enabled")); bindingGroup.addBinding(binding); senderNumberTextField.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { senderNumberTextFieldActionPerformed(evt); } }); senderNameTextField.setToolTipText("<html>Při vyplnění jména je připojeno na konec zprávy,<br>\ntakže je sms ve skutečnosti o něco delší</html>"); binding = org.jdesktop.beansbinding.Bindings.createAutoBinding(org.jdesktop.beansbinding.AutoBinding.UpdateStrategy.READ_WRITE, config, org.jdesktop.beansbinding.ELProperty.create("${senderName}"), senderNameTextField, org.jdesktop.beansbinding.BeanProperty.create("text_ON_ACTION_OR_FOCUS_LOST")); bindingGroup.addBinding(binding); binding = org.jdesktop.beansbinding.Bindings.createAutoBinding(org.jdesktop.beansbinding.AutoBinding.UpdateStrategy.READ, useSenderIDCheckBox, org.jdesktop.beansbinding.ELProperty.create("${selected}"), senderNameTextField, org.jdesktop.beansbinding.BeanProperty.create("enabled")); bindingGroup.addBinding(binding); jLabel3.setDisplayedMnemonic('m'); jLabel3.setLabelFor(senderNameTextField); jLabel3.setText("Jméno"); jLabel3.setToolTipText(senderNameTextField.getToolTipText()); 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.LEADING, false) .addComponent(useSenderIDCheckBox) .addGroup(jPanel2Layout.createSequentialGroup() .addGap(17, 17, 17) .addGroup(jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addComponent(jLabel3) .addComponent(jLabel1)) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addGroup(jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false) .addGroup(jPanel2Layout.createSequentialGroup() .addComponent(jLabel2) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addComponent(senderNumberTextField, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)) .addComponent(senderNameTextField)))) .addContainerGap(254, Short.MAX_VALUE)) ); jPanel2Layout.setVerticalGroup( jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(jPanel2Layout.createSequentialGroup() .addContainerGap() .addComponent(useSenderIDCheckBox) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addGroup(jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE) .addComponent(jLabel1) .addComponent(jLabel2) .addComponent(senderNumberTextField, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addGroup(jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE) .addComponent(jLabel3) .addComponent(senderNameTextField, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)) .addContainerGap(205, Short.MAX_VALUE)) ); tabbedPane.addTab("Vodafone", jPanel2); closeButton.setMnemonic('z'); closeButton.setText("Zavřít"); closeButton.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { closeButtonActionPerformed(evt); } }); javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane()); getContentPane().setLayout(layout); layout.setHorizontalGroup( layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(layout.createSequentialGroup() .addContainerGap() .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addComponent(closeButton, javax.swing.GroupLayout.Alignment.TRAILING) .addComponent(tabbedPane, javax.swing.GroupLayout.DEFAULT_SIZE, 465, Short.MAX_VALUE)) .addContainerGap()) ); layout.setVerticalGroup( layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup() .addContainerGap() .addComponent(tabbedPane, javax.swing.GroupLayout.DEFAULT_SIZE, 305, Short.MAX_VALUE) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addComponent(closeButton) .addContainerGap()) ); bindingGroup.bind(); pack(); }// </editor-fold>//GEN-END:initComponents private void themeComboBoxActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_themeComboBoxActionPerformed String laf = (String) lafComboBox.getSelectedItem(); if (laf.equals(LAF_JGOODIES)) { config.setLafJGoodiesTheme((String) themeComboBox.getSelectedItem()); } else if (laf.equals(LAF_SUBSTANCE)) { config.setLafSubstanceSkin((String) themeComboBox.getSelectedItem()); } //update skin in realtime if (fullyInicialized && lafWhenLoaded.equals(lafComboBox.getSelectedItem())) { try { ThemeManager.setLaF(); SwingUtilities.updateComponentTreeUI(MainFrame.getInstance()); SwingUtilities.updateComponentTreeUI(this); } catch (Exception ex) { logger.log(Level.SEVERE, "Problem while live-updating the look&feel skin", ex); } } }//GEN-LAST:event_themeComboBoxActionPerformed private void lafComboBoxActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_lafComboBoxActionPerformed if (!fullyInicialized) return; String laf = (String) lafComboBox.getSelectedItem(); if (laf.equals(LAF_SYSTEM)) config.setLookAndFeel(ThemeManager.LAF_SYSTEM); else if (laf.equals(LAF_CROSSPLATFORM)) config.setLookAndFeel(ThemeManager.LAF_CROSSPLATFORM); else if (laf.equals(LAF_GTK)) config.setLookAndFeel(ThemeManager.LAF_GTK); else if (laf.equals(LAF_JGOODIES)) config.setLookAndFeel(ThemeManager.LAF_JGOODIES); else if (laf.equals(LAF_SUBSTANCE)) config.setLookAndFeel(ThemeManager.LAF_SUBSTANCE); updateThemeComboBox(); }//GEN-LAST:event_lafComboBoxActionPerformed private void formWindowLostFocus(java.awt.event.WindowEvent evt) {//GEN-FIRST:event_formWindowLostFocus senderNumberTextFieldActionPerformed(null); }//GEN-LAST:event_formWindowLostFocus private void senderNumberTextFieldActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_senderNumberTextFieldActionPerformed config.setSenderNumber("+420" + senderNumberTextField.getText()); }//GEN-LAST:event_senderNumberTextFieldActionPerformed private void closeButtonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_closeButtonActionPerformed this.setVisible(false); this.dispose(); }//GEN-LAST:event_closeButtonActionPerformed // Variables declaration - do not modify//GEN-BEGIN:variables private javax.swing.JCheckBox checkUpdatesCheckBox; private javax.swing.JButton closeButton; private esmska.data.Config config; 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.JLabel jLabel7; private javax.swing.JPanel jPanel1; private javax.swing.JPanel jPanel2; private javax.swing.JPanel jPanel3; private javax.swing.JComboBox lafComboBox; private javax.swing.JCheckBox rememberHistoryCheckBox; private javax.swing.JCheckBox rememberLayoutCheckBox; private javax.swing.JCheckBox rememberQueueCheckBox; private javax.swing.JCheckBox removeAccentsCheckBox; private javax.swing.JTextField senderNameTextField; private javax.swing.JTextField senderNumberTextField; private javax.swing.JTabbedPane tabbedPane; private javax.swing.JComboBox themeComboBox; private javax.swing.JCheckBox toolbarVisibleCheckBox; private javax.swing.JCheckBox useSenderIDCheckBox; private javax.swing.JCheckBox windowCenteredCheckBox; private javax.swing.JCheckBox windowDecorationsCheckBox; private org.jdesktop.beansbinding.BindingGroup bindingGroup; // End of variables declaration//GEN-END:variables }
true
5fb646b1477d64ff08d45de72b9f534d5a3e5502
Java
ofuangka/stricken
/stricken/src/main/java/stricken/ui/menu/CritterMenuFactory.java
UTF-8
4,005
2.421875
2
[]
no_license
package stricken.ui.menu; import java.util.ArrayList; import java.util.List; import org.springframework.beans.factory.annotation.Required; import stricken.board.piece.Critter; import stricken.board.piece.TargetedAction; import stricken.event.Event; import stricken.event.IEventContext; import stricken.talent.loader.TargetedActionFactory; public class CritterMenuFactory { public class NoopMenuItem extends AbstractMenuItem { private static final long serialVersionUID = -8766319162177106177L; public NoopMenuItem(IEventContext eventContext, String label) { super(eventContext, label); } @Override public void execute() { eventContext.fire(Event.POP_IN_GAME_MENU); } } public static final String ATTACK_LABEL = "Attack"; public static final String TALENT_LABEL = "Talents"; public static final String ITEM_LABEL = "Items"; public static final String WAIT_LABEL = "Wait"; public static final String NO_ITEM_LABEL = "No items"; public static final String NO_TALENT_LABEL = "No talents"; private IEventContext eventContext; private TargetedActionFactory targetedActionFactory; public CritterMenuFactory(IEventContext eventContext) { this.eventContext = eventContext; } public Menu getCombatActionMenu(final Critter critter) { Menu ret = new Menu(eventContext); List<AbstractMenuItem> menuItems = new ArrayList<AbstractMenuItem>(); TargetedAction attack = targetedActionFactory.get(critter.getAttack(), critter); AbstractMenuItem attackMenuItem = new EventMenuItem(eventContext, ATTACK_LABEL, Event.CRITTER_ACTION, attack); AbstractSubMenuItem talentSubMenuItem = new AbstractSubMenuItem( eventContext, TALENT_LABEL) { private static final long serialVersionUID = 815195033986998056L; @Override public Menu getSubMenu() { return getTalentMenu(critter); } }; AbstractSubMenuItem itemSubMenuItem = new AbstractSubMenuItem( eventContext, ITEM_LABEL) { private static final long serialVersionUID = 6369030028324018292L; @Override public Menu getSubMenu() { return getItemMenu(critter); } }; menuItems.add(attackMenuItem); menuItems.add(talentSubMenuItem); menuItems.add(itemSubMenuItem); menuItems.add(new AbstractMenuItem(eventContext, WAIT_LABEL) { private static final long serialVersionUID = -4070052990440134098L; @Override public void execute() { eventContext.fire(Event.END_OF_TURN); } }); ret.setItems(menuItems); return ret; } public Menu getItemMenu(Critter critter) { Menu ret = new Menu(eventContext); List<AbstractMenuItem> menuItems = new ArrayList<AbstractMenuItem>(); List<String> items = critter.getItems(); if (items == null || items.isEmpty()) { menuItems.add(new NoopMenuItem(eventContext, NO_ITEM_LABEL)); } else { for (String item : items) { TargetedAction critterAction = targetedActionFactory.get(item, critter); menuItems.add(new EventMenuItem(eventContext, critterAction .getName(), Event.CRITTER_ACTION, critterAction)); } } ret.setItems(menuItems); return ret; } public Menu getTalentMenu(Critter critter) { Menu ret = new Menu(eventContext); List<AbstractMenuItem> menuItems = new ArrayList<AbstractMenuItem>(); List<String> talents = critter.getTalents(); if (talents == null || talents.isEmpty()) { menuItems.add(new NoopMenuItem(eventContext, NO_TALENT_LABEL)); } else { for (String talent : talents) { TargetedAction critterAction = targetedActionFactory.get( talent, critter); menuItems.add(new EventMenuItem(eventContext, critterAction .getName(), Event.CRITTER_ACTION, critterAction)); } } ret.setItems(menuItems); return ret; } @Required public void setTargetedActionFactory( TargetedActionFactory targetedActionFactory) { this.targetedActionFactory = targetedActionFactory; } }
true
32c80e4aca99910fe02a6c63c4e431d79a5b2dbe
Java
Vinaysai/Hibernate-OneToOne
/src/main/java/com/onetoone/all/OneToOne/Address.java
UTF-8
1,866
2.671875
3
[]
no_license
package com.onetoone.all.OneToOne; import javax.persistence.CascadeType; import javax.persistence.Column; import javax.persistence.Entity; import javax.persistence.Id; import javax.persistence.JoinColumn; import javax.persistence.OneToOne; import javax.persistence.Table; @Entity @Table(name = "Address_DB") public class Address { public Address() { super(); } @Id @Column(name = "addrid") private int addid; @Column(name = "place", length = 10) private String place; @OneToOne(targetEntity = Student.class, cascade = CascadeType.ALL) @JoinColumn(name = "stu_id", referencedColumnName = "sid") private Student parent; @Override public int hashCode() { final int prime = 31; int result = 1; result = prime * result + addid; result = prime * result + ((parent == null) ? 0 : parent.hashCode()); result = prime * result + ((place == null) ? 0 : place.hashCode()); return result; } public int getAddid() { return addid; } public void setAddid(int addid) { this.addid = addid; } public String getPlace() { return place; } public void setPlace(String place) { this.place = place; } public Student getParent() { return parent; } public void setParent(Student parent) { this.parent = parent; } @Override public boolean equals(Object obj) { if (this == obj) return true; if (obj == null) return false; if (getClass() != obj.getClass()) return false; Address other = (Address) obj; if (addid != other.addid) return false; if (parent == null) { if (other.parent != null) return false; } else if (!parent.equals(other.parent)) return false; if (place == null) { if (other.place != null) return false; } else if (!place.equals(other.place)) return false; return true; } }
true
882732ad68c00ae7d421b5062b51fd058b98fed4
Java
HRShopping/HRShopping
/app/src/main/java/com/example/helloworld/huaruanshopping/fragment/fragmentPageSortList.java
UTF-8
5,564
2.0625
2
[]
no_license
package com.example.helloworld.huaruanshopping.fragment; import android.os.Bundle; import android.os.Handler; import android.os.Message; import android.support.annotation.Nullable; import android.support.v4.app.Fragment; import android.support.v4.widget.SwipeRefreshLayout; import android.support.v7.widget.GridLayoutManager; import android.support.v7.widget.RecyclerView; import android.util.Log; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.Toast; import com.example.helloworld.huaruanshopping.R; import com.example.helloworld.huaruanshopping.adapter.SortListRecylcerViewAdapter; import com.example.helloworld.huaruanshopping.bean.Product; import com.example.helloworld.huaruanshopping.bean.ProductListBean; import com.example.helloworld.huaruanshopping.presenter.FragmentPageSortListPresenter; import com.example.helloworld.huaruanshopping.presenter.implView.IFragmentBaseView; import java.math.BigDecimal; import java.util.ArrayList; import java.util.List; /** * Created by helloworld on 2017/1/15. */ public class fragmentPageSortList extends Fragment implements SwipeRefreshLayout.OnRefreshListener, IFragmentBaseView { private RecyclerView mRecyclerView; private View view; private List<ProductListBean> mProductList = new ArrayList<>(); private RecyclerView.LayoutManager layoutManager; private SortListRecylcerViewAdapter adapter; private SwipeRefreshLayout refreshLayout; private String category = ""; private int sortId; private final static String TAG = "111"; private FragmentPageSortListPresenter presenter; private boolean isVisibile; private boolean isPrepare; private boolean isFirst = true; public static fragmentPageSortList newInstance(String category, int sortId) { Bundle args = new Bundle(); args.putString("category", category); args.putInt("sortId", sortId); // Log.d(TAG, "newInstance:id " + sortId); fragmentPageSortList fragment = new fragmentPageSortList(); fragment.setArguments(args); return fragment; } @Override public void onCreate(@Nullable Bundle savedInstanceState) { super.onCreate(savedInstanceState); Bundle bundle = getArguments(); if (bundle != null) { category = bundle.getString("category"); sortId = bundle.getInt("sortId"); } presenter = new FragmentPageSortListPresenter(this); // initData(); } @Override public void setUserVisibleHint(boolean isVisibleToUser) { super.setUserVisibleHint(isVisibleToUser); // Log.d(TAG, "setUserVisibleHint: "+getUserVisibleHint()+sortId); if (getUserVisibleHint() && isPrepare && mProductList.size() == 0) { isVisibile = true; refreshLayout.post(new Runnable() { @Override public void run() { // mProductList.clear(); refreshLayout.setRefreshing(true); onRefresh(); } }); } else { isVisibile = false; } // Log.d(TAG, "setUserVisibleHint: "+isFirst); // isFirst=false; } // private void initData() { // ProductListBean good = new ProductListBean(); // for (int i = 0; i < 24; i++) { // good.setName("零食" + i); // good.setPrice(i); //// good.setPic_url("http://pic.qiantucdn.com/58pic/18/20/08/90W58PICtuP_1024.jpg"); // mProductList.add(good); //// good = new Product(); // } // } @Nullable @Override public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) { view = inflater.from(getContext()).inflate(R.layout.fragment_sort_list, null, false); initView(); isPrepare = true; if (getUserVisibleHint() && isVisibile == false && mProductList.size() == 0) { refreshLayout.post(new Runnable() { @Override public void run() { refreshLayout.setRefreshing(true); onRefresh(); } }); } return view; } private void initView() { refreshLayout = (SwipeRefreshLayout) view.findViewById(R.id.sortListRefreshLayout); refreshLayout.setOnRefreshListener(this); refreshLayout.setColorSchemeColors(getResources().getColor(R.color.colorPrimaryFont)); mRecyclerView = (RecyclerView) view.findViewById(R.id.sorListRecycleview); adapter = new SortListRecylcerViewAdapter(getContext(), mProductList); layoutManager = new GridLayoutManager(getContext(), 2); mRecyclerView.setLayoutManager(layoutManager); mRecyclerView.setAdapter(adapter); } @Override public void onRefresh() { // mHandler.sendEmptyMessageDelayed(0x111, 2000); presenter.getPageSortListProduct(sortId, 1); } @Override public void showLoading() { refreshLayout.setRefreshing(true); } @Override public void hideLoading() { refreshLayout.setRefreshing(false); } @Override public void showFailedError() { } @Override public void showData(List<ProductListBean> list) { mProductList.clear(); if (list != null) { if (!(mProductList.equals(list))) { adapter.addMoreData(list); } } } }
true
36208029d375cd34d9b91012c196f1c31a89ccd0
Java
ruriknj/curso_programacao
/src/br/com/list_fixacao/ProgramaFuncionario.java
ISO-8859-1
1,654
3.640625
4
[]
no_license
package br.com.list_fixacao; import java.util.ArrayList; import java.util.List; import java.util.Scanner; public class ProgramaFuncionario { public static void main(String[] args) { Scanner sc = new Scanner(System.in); List<Funcionario> lista = new ArrayList<>(); System.out.print("How many employees will be registered? "); int n = sc.nextInt(); for(int i =1; i<=n; i++) { System.out.println("Emplyoee #"+i+":"); System.out.print("Id: "); int id = sc.nextInt(); sc.nextLine(); System.out.print("Name: "); String nome = sc.nextLine(); System.out.print("Salary: "); Double salario = sc.nextDouble(); lista.add(new Funcionario(id, nome, salario)); System.out.println(); } System.out.println("------------------------------------------"); System.out.print("Employee id that will have salary increase: "); int id = sc.nextInt(); Funcionario emp = lista.stream().filter(x -> x.getId() == id).findFirst().orElse(null); if (emp == null) { System.out.println("This id does not exist!"); } else { System.out.print("Enter the percentage:"); double percentagem = sc.nextDouble(); emp.aumentoSalario(percentagem); System.out.println(); } System.out.println("Lista de Funcionarios: "); for (Funcionario x: lista) { System.out.printf("%d%s%s%s%.2f\n",x.getId(),", ",x.getNome(),", ", x.getSalario()); // ou outras opes para listar funcionarios. System.out.println(x); System.out.println(lista); } sc.close(); } }
true
e84c9c9f5d2d6ebad88150d7191c54e622c6740b
Java
BleedBee/Simple-chat-room
/client/ChatClient.java
GB18030
1,143
2.78125
3
[]
no_license
package client; import java.io.DataInputStream; import java.io.DataOutputStream; import java.io.IOException; import java.net.Socket; import java.util.Scanner; public class ChatClient { public static void main(String[] agrs) { Scanner in=new Scanner(System.in); System.out.print("IP"); String serverIP; serverIP=in.next(); System.out.println("------ͻ------"); System.out.println("ͻ"); System.out.print("dzƣ"); String userName=in.next(); try { Socket client=new Socket(serverIP,8888); DataOutputStream dos=new DataOutputStream(client.getOutputStream()); DataInputStream dis=new DataInputStream(client.getInputStream()); dos.writeUTF(userName); dos.flush(); ClientInterface clientInterface=new ClientInterface(userName,dos,dis); String userName_server; String userTxt_server; while(true) { userName_server=dis.readUTF(); userTxt_server=dis.readUTF(); clientInterface.showTxt(userName_server, userTxt_server); } } catch (IOException e) { e.printStackTrace(); } } }
true
3326517a161d92015a8c783ab1caa1a9ff0e402f
Java
scholnicks/isbndb
/IsbnDB/src/net/scholnick/isbndb/domain/Author.java
UTF-8
547
2.609375
3
[ "MIT" ]
permissive
package net.scholnick.isbndb.domain; import org.apache.commons.lang.builder.ToStringBuilder; /** * Author of a book * * @author Steve Scholnick <scholnicks@gmail.com> */ public final class Author { private String id; private String name; public String getId() { return id; } public void setId(String id) { this.id = id; } public String getName() { return name; } public void setName(String name) { this.name = name; } /** {@inheritDoc} */ @Override public String toString() { return ToStringBuilder.reflectionToString(this); } }
true