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
fa0a04b31f0722d0e072d6f7ab341e912edf64ee
Java
BUCTdarkness/JiyiShen-s-Coding
/dh_demo/src/com/dh/search/Searcher.java
UTF-8
4,138
2.359375
2
[]
no_license
package com.dh.search; import java.io.File; import java.io.IOException; import java.util.ArrayList; import java.util.List; import org.apache.lucene.analysis.core.SimpleAnalyzer; import org.apache.lucene.analysis.standard.StandardAnalyzer; import org.apache.lucene.document.Document; import org.apache.lucene.index.CorruptIndexException; import org.apache.lucene.index.DirectoryReader; import org.apache.lucene.index.IndexReader; import org.apache.lucene.queryparser.classic.QueryParser; import org.apache.lucene.search.IndexSearcher; import org.apache.lucene.search.Query; import org.apache.lucene.search.ScoreDoc; import org.apache.lucene.search.Sort; import org.apache.lucene.search.SortField; import org.apache.lucene.search.SortField.Type; import org.apache.lucene.search.TopDocs; import org.apache.lucene.store.Directory; import org.apache.lucene.store.FSDirectory; import com.dh.domain.SearchItem; public class Searcher { private static IndexReader indexReader=null; static{ try { File indexDir = new File("H://luceneIndex"); Directory directory = FSDirectory.open(indexDir); indexReader = DirectoryReader.open(directory); } catch (CorruptIndexException e) { // TODO: handle exception e.printStackTrace(); }catch (IOException e) { // TODO: handle exception e.printStackTrace(); } } private static IndexSearcher getSearcher(){ try { if(indexReader==null){ File indexDir = new File("H://luceneIndex"); Directory directory = FSDirectory.open(indexDir); indexReader = DirectoryReader.open(directory); } return new IndexSearcher(indexReader); } catch (CorruptIndexException e) { // TODO: handle exception e.printStackTrace(); }catch (IOException e) { // TODO: handle exception e.printStackTrace(); } return null; } private static List<SearchItem> SearchBySort(String querystr,String domain,Sort sort){ List<SearchItem> resultlist = new ArrayList<SearchItem>(); TopDocs topDocs=null; IndexSearcher indexSearcher = getSearcher(); try { QueryParser parserKey = new QueryParser(domain, new StandardAnalyzer()); Query query = parserKey.parse(querystr); if(sort==null){ topDocs = indexSearcher.search(query, 1000); }else{ topDocs=indexSearcher.search(query, 1000,sort); } ScoreDoc[] scoreDocs = topDocs.scoreDocs; if (scoreDocs == null || scoreDocs.length == 0) { System.out.println("The Lucene index is not exist"); } for (int i = 0; i < scoreDocs.length; i++) { Document document = indexSearcher.doc(scoreDocs[i].doc); SearchItem tmpItem = new SearchItem(); tmpItem.setKey(document.get("key")); tmpItem.setSupplierid(document.get("supplierid")); tmpItem.setImgurl(document.get("imgurl")); tmpItem.setMaxcost(Double.parseDouble(document.get("maxcost"))); tmpItem.setMincost(Double.parseDouble(document.get("mincost"))); tmpItem.setItemname(document.get("itemname")); if(!resultlist.contains(tmpItem)) resultlist.add(tmpItem); } return resultlist; } catch (Exception e) { // TODO: handle exception e.printStackTrace(); } return null; } public static List<SearchItem> search(String key) { // This is the directory that hosts the Lucene index List<SearchItem> resultlist = new ArrayList<SearchItem>(); try{ List<SearchItem> tmplist=null; Sort sort=null; sort = new Sort(new SortField("itemname",SortField.Type.SCORE),new SortField("maxcost", Type.DOUBLE)); //itemname tmplist=SearchBySort(key+"* OR ("+key+"~)", "itemname", sort); for(SearchItem tmp:tmplist){ if(!resultlist.contains(tmp)){ resultlist.add(tmp); } } //key tmplist=SearchBySort(key+"* OR ("+key+"~)", "key", null); for(SearchItem tmp:tmplist){ if(!resultlist.contains(tmp)){ resultlist.add(tmp); } } //supplierid tmplist=SearchBySort(key+"* OR ("+key+"~)", "supplierid", null); for(SearchItem tmp:tmplist){ if(!resultlist.contains(tmp)){ resultlist.add(tmp); } } } catch(Exception e){ e.printStackTrace(); } return resultlist; } }
true
84902bb1a12325916acc3b84a62b9b044b3c8544
Java
yuhaibao324/springCloudApplication
/userservice/src/main/java/com/mistra/userservice/base/WebInterceptor.java
UTF-8
2,836
2.25
2
[]
no_license
package com.mistra.userservice.base; import com.mistra.userservice.base.JWT.JsonWebTokenConstant; import com.mistra.userservice.base.JWT.JsonWwbTokenUtil; import com.mistra.userservice.base.JWT.JsonWwbTokenVerifyStatus; import com.mistra.userservice.base.exception.BaseServiceException; import com.mistra.userservice.base.exception.ResultCode; import com.mistra.userservice.core.CurrentUserSession; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.lang.Nullable; import org.springframework.stereotype.Component; import org.springframework.web.servlet.HandlerInterceptor; import org.springframework.web.servlet.ModelAndView; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; /** * @Author: WangRui * @Date: 2018/11/30 * Time: 16:51 * Description: 拦截器 */ @Component public class WebInterceptor implements HandlerInterceptor { Logger logger = LoggerFactory.getLogger(WebInterceptor.class); @Autowired private JsonWwbTokenUtil jwtUtil; /** * 验证token,通常情况下结合redis做刷新token缓存,比如同一个页面有多个请求时需要刷新token不用每次都重新生成,在redis拿 * * @param request * @param response * @param handler * @return * @throws Exception */ @Override public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception { String url = request.getRequestURI(); logger.info("{} >>> {}", request.getMethod(), url); String token = jwtUtil.getToken(request); Integer code = jwtUtil.verification(token).getCode(); if (code.equals(JsonWwbTokenVerifyStatus.SUCCESS.getCode())) { return true; } else if (code.equals(JsonWwbTokenVerifyStatus.CREATE_NEW.getCode())) { String userId = jwtUtil.parseTokenGetUserId(token); String allNewToken = jwtUtil.generateToken(userId); response.setHeader(JsonWebTokenConstant.RESPONSE_HEADER_USER_TOKEN_FLAG, allNewToken); return true; } else if (code.equals(JsonWwbTokenVerifyStatus.LOGIN.getCode())) { throw new BaseServiceException(ResultCode.LOGIN_EXPIRED_ERROR); } return true; } @Override public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, @Nullable ModelAndView modelAndView) throws Exception { } @Override public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception { //请求结束,清楚本地化变量中保存的用户信息 CurrentUserSession.userIdThreadLocal.remove(); } }
true
763958eaa5d9b5594cc2950ded83fdb1f46aa929
Java
Jun-Lizst/ProbeDesign
/probedesign/SubString_boolean.java
UTF-8
4,531
3.125
3
[]
no_license
import java.io.BufferedReader; import java.io.FileReader; import java.io.IOException; import java.util.*; public class SubString_boolean { private HashSet<String> geneSet = new HashSet<String>(); //contains substrings of a gene private boolean[] found; //has substring been found in database? private StringBuilder outseq; private long findtic; private long findtoc; private long totalSearchTime=0; // ** CONSTRUCTOR METHOD ** // public SubString_boolean(String filename, int subLength, String inseq) throws IOException { /* Input * filename - full path of the database FASTA file to be searched (can be multi sequence) * subLength - length of substring queries * inseq - query sequence (eg. the mRNA sequence that you want to mask against the database) * */ /* Usage in MATLAB * >> javaaddpath('/Users/marshall/rajlab/sequenceanalysis/probedesign/') * >> genereader = SubString_boolean('/path/to/probedesign/pseudogeneDBs/human.fasta', 16, upper(inseq)); * >> maskedSeq = char(genereader.FindSeq()); % convert java.String to MATLAB char() */ // boolean array with same length as query sequence minus sub-string query length found = new boolean[inseq.length()-(subLength-1)]; // default is all FALSE // make a copy of "inseq" that will be edited later with "X" for match positions outseq = new StringBuilder(inseq); // load the database file into a BufferedReader if (filename == null) { throw new IllegalArgumentException(); } BufferedReader reader = new BufferedReader (new FileReader(filename)); /* Logic for reading and searching database file: * 1. We read the file line-by-line until we complete a single sequence in a (potentially) * multi-sequence FASTA file. * 2. Break up the single gene sequence into substrings of length=subLength and add * them to the HashSet geneSet. This is a unique collection of substrings. * 3. Perform search for substrings of inseq in HashSet geneSet. Positions of matching * substrings in inseq are recorded in the boolean array "found" as TRUE * 4. Clear the HashSet "geneSet" and repeat steps 1-3. */ if (reader.ready()){ String newLine = reader.readLine().trim(); //first line to read; runs only once String newGene = new String(); //initialize container for one gene while(newLine != null){ //while there are still lines to read if (newLine.contains(">")){ //if new line is a gene title newGene = new String(); //clear gene container newLine = reader.readLine().trim(); //read next line continue; //skip code below this line } else { while (!newLine.contains(">")){ //while new line is a continuation of the gene newLine = newLine.trim(); newGene = newGene.concat(newLine); //add new line to gene container newLine = reader.readLine(); //read next line if (newLine == null){break;} //stop at the end of the database } //enters substring entries of a single FASTA sequence into HashSet geneSet for (int i=0; i<newGene.length()-(subLength-1); i++){ String subString = newGene.substring(i,i+subLength); //generates hashcode from substring geneSet.add(subString); } // perform search for substrings of inseq in HashSet geneSet findtic = System.currentTimeMillis(); for (int i=0; i<inseq.length()-(subLength-1); i++){ //for length of query sequence if (!found[i]){ //if already found, search can be skipped found[i] = geneSet.contains(inseq.substring(i,i+subLength)); //was sequence found in this segment of genes? } } findtoc = System.currentTimeMillis(); totalSearchTime += findtoc-findtic; //pools HashSet search time geneSet.clear(); //clear HashSet and process next gene } } } reader.close(); System.out.println("Total HashSet search time: " + Long.toString(totalSearchTime/1000) + " seconds"); //outputs total search time // Make a copy of "inseq" and replace characters that had matches to database with "X" for (int i=0; i<inseq.length()-(subLength-1); i++){ if (found[i]){ outseq.replace(i,i+1,"X"); } } } // ** METHOD TO RETURN OUTPUT: your input sequence masked with X's ** // public String FindSeq(){ return outseq.toString(); } }
true
923bb5b38875aee512088cbd7afb3a4b99506424
Java
pchain-org/pweb3j
/core/src/main/java/org/pweb3j/tx/gas/DefaultGasProvider.java
UTF-8
415
2.078125
2
[ "Apache-2.0" ]
permissive
package org.pweb3j.tx.gas; import java.math.BigInteger; import org.pweb3j.tx.Contract; import org.pweb3j.tx.ManagedTransaction; public class DefaultGasProvider extends StaticGasProvider { public static final BigInteger GAS_LIMIT = Contract.GAS_LIMIT; public static final BigInteger GAS_PRICE = ManagedTransaction.GAS_PRICE; public DefaultGasProvider() { super(GAS_PRICE, GAS_LIMIT); } }
true
22c9e759f0e34720db3d75b696b29ee930fc14a9
Java
ADeveloperH/GPUImageTest
/library/src/main/java/jp/co/cyberagent/android/gpuimage/filter/GPUImageRGBFilter.java
UTF-8
2,967
2.46875
2
[ "Apache-2.0" ]
permissive
/* * Copyright (C) 2018 CyberAgent, 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 jp.co.cyberagent.android.gpuimage.filter; import android.opengl.GLES20; import android.util.Log; /** * Adjusts the individual RGB channels of an image * red: Normalized values by which each color channel is multiplied. The range is from 0.0 up, with 1.0 as the default. * green: * blue: */ public class GPUImageRGBFilter extends GPUImageFilter { public static final String RGB_FRAGMENT_SHADER = "" + " varying highp vec2 textureCoordinate;\n" + " \n" + " uniform sampler2D inputImageTexture;\n" + " uniform highp float red;\n" + " uniform highp float green;\n" + " uniform highp float blue;\n" + " \n" + " void main()\n" + " {\n" + " highp vec4 textureColor = texture2D(inputImageTexture, textureCoordinate);\n" + " \n" + " gl_FragColor = vec4(textureColor.r * red, textureColor.g * green, textureColor.b * blue, 1.0);\n" + " }\n"; private int redLocation; private float red; private int greenLocation; private float green; private int blueLocation; private float blue; public GPUImageRGBFilter() { this(1.0f, 1.0f, 1.0f); } public GPUImageRGBFilter(final float red, final float green, final float blue) { super(NO_FILTER_VERTEX_SHADER, RGB_FRAGMENT_SHADER); this.red = red; this.green = green; this.blue = blue; } @Override public void onInit() { super.onInit(); redLocation = GLES20.glGetUniformLocation(getProgram(), "red"); greenLocation = GLES20.glGetUniformLocation(getProgram(), "green"); blueLocation = GLES20.glGetUniformLocation(getProgram(), "blue"); } @Override public void onInitialized() { super.onInitialized(); setRed(red); setGreen(green); setBlue(blue); } public void setRed(final float red) { Log.d("hj", "GPUImageRGBFilter.setRed: " + red); this.red = red; setFloat(redLocation, this.red); } public void setGreen(final float green) { this.green = green; setFloat(greenLocation, this.green); } public void setBlue(final float blue) { this.blue = blue; setFloat(blueLocation, this.blue); } }
true
210390d5b9187289337b79fb22fa04cc768f47c8
Java
ismailsimsek/dbn
/src/com/dci/intellij/dbn/language/common/element/util/ElementTypeAttribute.java
UTF-8
2,827
2.1875
2
[]
no_license
package com.dci.intellij.dbn.language.common.element.util; import com.dci.intellij.dbn.common.property.Property; public enum ElementTypeAttribute implements Property{ ROOT("ROOT", "Executable statement"), EXECUTABLE("EXECUTABLE", "Executable statement"), DEBUGGABLE("DEBUGGABLE", "Debuggable"), TRANSACTIONAL("TRANSACTIONAL", "Transactional statement"), POTENTIALLY_TRANSACTIONAL("POTENTIALLY_TRANSACTIONAL", "Transactional statement"), QUERY("QUERY", "Query statement", true), DATA_DEFINITION("DATA_DEFINITION", "Data definition statement", true), DATA_MANIPULATION("DATA_MANIPULATION", "Data manipulation statement", true), COMPILABLE_BLOCK("COMPILABLE_BLOCK", "Compilable block", false), TRANSACTION_CONTROL("TRANSACTION_CONTROL", "Transaction control statement", true), OBJECT_SPECIFICATION("OBJECT_SPECIFICATION", "Object specification", true), OBJECT_DECLARATION("OBJECT_DECLARATION", "Object declaration", true), OBJECT_DEFINITION("OBJECT_DEFINITION", "Object definition", true), SUBJECT("SUBJECT", "Statement subject"), STATEMENT("STATEMENT", "Statement"), CLAUSE("CLAUSE", "Statement clause"), CONDITION("CONDITION", "Condition expression"), STRUCTURE("STRUCTURE", "Structure view element"), SCOPE_ISOLATION("SCOPE_ISOLATION", "Scope isolation"), SCOPE_DEMARCATION("SCOPE_DEMARCATION", "Scope demarcation"), FOLDABLE_BLOCK("FOLDABLE_BLOCK", "Foldable block"), EXECUTABLE_CODE("EXECUTABLE_CODE", "Executable code"), BREAKPOINT_POSITION("BREAKPOINT_POSITION", "Default breakpoint position"), ACTION("ACTION", "Action"), GENERIC("GENERIC", "Generic element"), SPECIFIC("SPECIFIC", "Specific element"), DATABASE_LOG_PRODUCER("DATABASE_LOG_PRODUCER", "Database logging"), METHOD_PARAMETER_HANDLER("METHOD_PARAMETER_HANDLER", "Method parameter handler"), COLUMN_PARAMETER_HANDLER("COLUMN_PARAMETER_HANDLER", "Column parameter handler"), COLUMN_PARAMETER_PROVIDER("COLUMN_PARAMETER_PROVIDER", "Column parameter provider"), ; private String name; private String description; private boolean specific; private final int index = Property.idx(this); @Override public int index() { return index; } ElementTypeAttribute(String name, String description) { this(name, description, false); } ElementTypeAttribute(String name, String description, boolean specific) { this.name = name; this.description = description; this.specific = specific; } public String getName() { return name; } public String getDescription() { return description; } @Override public String toString() { return name; } public boolean isSpecific() { return specific; } }
true
ec561a7694b7cc11c1dc6217a1762ada231e1bda
Java
tamirsagi/PegasusClient
/app/src/main/java/client/pegasusclient/app/BL/Bluetooth/BluetoothDeviceInfo.java
UTF-8
929
2.578125
3
[]
no_license
package client.pegasusclient.app.BL.Bluetooth; import android.bluetooth.BluetoothDevice; /** * @author Tamir Sagi * This class holds bluetooth device info for recycler list for Device List activity */ public class BluetoothDeviceInfo { private String mName; private String mAddress; private String mSignal; public BluetoothDeviceInfo(BluetoothDevice bt,int signal){ setName(bt.getName()); setAddress(bt.getAddress()); setSignal("" + signal); } public String getName() { return mName; } public void setName(String mName) { this.mName = mName; } public String getSignal() { return mSignal; } public void setSignal(String mSignal) { this.mSignal = mSignal; } public String getAddress() { return mAddress; } public void setAddress(String mAddress) { this.mAddress = mAddress; } }
true
f635c80d6df684ea51d88c5fb56fb2e3345354a8
Java
fei-ke/BTForward
/app/src/main/java/com/fei_ke/btforward/event/ConnectEvent.java
UTF-8
1,034
2.765625
3
[]
no_license
package com.fei_ke.btforward.event; import android.bluetooth.BluetoothDevice; /** * Created by 杨金阳 on 2015/4/20. */ public class ConnectEvent { // Constants that indicate the current connection state public static final int STATE_NONE = 0; // we're doing nothing public static final int STATE_LISTEN = 1; // now listening for incoming connections public static final int STATE_CONNECTING = 2; // now initiating an outgoing connection public static final int STATE_CONNECTED = 3; // now connected to a remote device private BluetoothDevice device; private int state; public ConnectEvent(BluetoothDevice device, int state) { this.device = device; this.state = state; } public BluetoothDevice getDevice() { return device; } public void setDevice(BluetoothDevice device) { this.device = device; } public int getState() { return state; } public void setState(int state) { this.state = state; } }
true
cd31cab4ca5e479f35e7f24396873d1e6e04413a
Java
macetosella/callCenter
/src/test/java/ar/com/uca/callcenter/entity/LlamadaTest.java
UTF-8
463
2.125
2
[]
no_license
package ar.com.uca.callcenter.entity; import junit.framework.Test; import junit.framework.TestCase; import junit.framework.TestSuite; public class LlamadaTest extends TestCase { public static Test suite(){ return new TestSuite( LlamadaTest.class ); } public static void testLlamada(){ Call llamada = new Call("llamada test"); assertTrue(llamada.getTimeLength()>= Call.MIN_TIME_LENGHT); assertTrue(llamada.getTimeLength()<=Call.MAX_TIME_LENGHT); } }
true
48dbda8ecdbd12083b486ea1bb6f4ae355fb5fcc
Java
rongkecloud/RongKeMessenger-Android
/rkchat/com/rongkecloud/chat/demo/entity/RKCloudChatContact.java
UTF-8
1,323
2.265625
2
[]
no_license
package com.rongkecloud.chat.demo.entity; import android.text.SpannableStringBuilder; import android.text.Spanned; import android.text.style.BackgroundColorSpan; public class RKCloudChatContact{ public String rkAccount;// 云视互动账号 public SpannableStringBuilder highLightName;// 高亮显示的名称 public String getShowName(){ // TODO 完善UI显示的名称 return rkAccount; } /** * 获取头像缩略图路径 * @return */ public String getHeaderThumbImagePath(){ // TODO 完善头像路径 return ""; } /** * 排序时使用 * @return */ public String getSortKey(){ // TODO 完善排序字段 return rkAccount; } /** * 使用搜索条件匹配名字 */ public void matchName(String filter, BackgroundColorSpan backgroundColorSpan) { int start=0, end=0; // 名字高亮字段 String upperCaseName = getShowName().toUpperCase(); String upperCaseFilter = filter.toUpperCase(); // 直接使用filter搜索 if ((start=upperCaseName.indexOf(upperCaseFilter)) != -1) { end = start + filter.length(); highLightName = new SpannableStringBuilder(getShowName()); if(null != backgroundColorSpan){ highLightName.setSpan(backgroundColorSpan, start, end, Spanned.SPAN_EXCLUSIVE_EXCLUSIVE); } }else{ highLightName = null; } } }
true
424937f0956c84206ca5d5c6f21f5665262a7ba5
Java
lothar1998/Advent-of-Code-2019
/src/Day8.java
UTF-8
2,702
3.515625
4
[ "MIT" ]
permissive
import java.io.*; public class Day8 { public static void main(String[] args) throws IOException { BufferedReader bufferedReader = new BufferedReader(new FileReader(new File("data/input8.txt"))); String loadedData = bufferedReader.readLine(); Integer[] digits = splitIntoSeparatedDigits(loadedData); int width = 25; int height = 6; System.out.println("Part 1: " + computeAnswerPart1(digits, width, height)); printPicture(computeAnswerPart2(digits, width, height), width, height); } private static int computeAnswerPart1(Integer[] digits, int width, int height){ int minNumberOfZeros = Integer.MAX_VALUE; int begin = 0; int end = 0; int temp; for(int i = 0 ; i < digits.length; i+= width*height) if((temp = computeNumberOf(0, digits, i, i + width * height)) < minNumberOfZeros){ minNumberOfZeros = temp; begin = i; end = i + width * height; } int numberOfOnes = computeNumberOf(1, digits, begin, end); int numberOfTwo = computeNumberOf(2, digits, begin, end); return numberOfOnes * numberOfTwo; } private static Integer[] splitIntoSeparatedDigits(String loadedData){ Integer[] result = new Integer[loadedData.length()]; for(int i = 0; i < loadedData.length(); i++){ result[i] = Integer.parseInt(loadedData.substring(i,i+1)); } return result; } private static int computeNumberOf(int valueToCompute, Integer[] array, int begin, int end){ int number = 0; for(int i = begin; i < end; i++){ if(array[i].equals(valueToCompute)) number++; } return number; } private static Integer[] computeAnswerPart2(Integer[] digits, int width, int height){ Integer[] picture = new Integer[width * height]; for(int i = 0; i < width * height; i++){ for(int j = i; j < digits.length; j += width * height) if(digits[j] == 2) continue; else{ picture[i] = digits[j]; break; } } return picture; } private static void printPicture(Integer[] picture, int width, int height){ for(int h = 0; h < height; h++){ for(int w = 0; w < width; w++) { int value = picture[(w + (h * width))]; if (value == 0) System.out.print(" "); else System.out.print("x"); } System.out.println(); } } }
true
5c3e31d8d8413d389702ed070702d100f87eff67
Java
kyoungtion/evening
/finalProject/src/main/java/com/kh/evening/board/controller/BoardController.java
UTF-8
19,230
1.726563
2
[]
no_license
package com.kh.evening.board.controller; import java.io.File; import java.io.IOException; import java.net.URLEncoder; import java.sql.Date; import java.text.DateFormat; import java.text.SimpleDateFormat; import java.util.ArrayList; import java.util.Calendar; import java.util.GregorianCalendar; import java.util.HashMap; import java.util.Locale; import java.util.Map; import javax.servlet.http.Cookie; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import javax.servlet.http.HttpSession; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Controller; import org.springframework.ui.Model; import org.springframework.web.bind.annotation.ModelAttribute; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestParam; import org.springframework.web.bind.annotation.ResponseBody; import org.springframework.web.bind.annotation.SessionAttributes; import org.springframework.web.multipart.MultipartFile; import org.springframework.web.servlet.ModelAndView; import com.google.gson.Gson; import com.google.gson.GsonBuilder; import com.google.gson.JsonIOException; import com.kh.evening.board.model.exception.BoardException; import com.kh.evening.board.model.service.BoardService; import com.kh.evening.board.model.vo.Attachment; import com.kh.evening.board.model.vo.AuctionHistory; import com.kh.evening.board.model.vo.Board; import com.kh.evening.board.model.vo.BoardMode; import com.kh.evening.board.model.vo.GoodLike; import com.kh.evening.board.model.vo.PageInfo; import com.kh.evening.board.model.vo.Reply; import com.kh.evening.common.Pageination; import com.kh.evening.member.model.service.MemberService; import com.kh.evening.member.model.vo.Member; import oracle.sql.DATE; /** * @author KimHyunWoo * */ @SessionAttributes("loginUser") @Controller public class BoardController { @Autowired private BoardService bService; @Autowired private MemberService mService; @RequestMapping("auctionList.bo") public ModelAndView auctionList(@RequestParam(value="page",required=false) Integer page, ModelAndView mv, @RequestParam(value="mode", required=false) String mode) { int currentPage = 1; // 페이징 : 현재 페이지 설정 if (page != null) { currentPage = page; } // 정렬 순서 설정 : 기본값 recent(최신순) String modeSet = "recent"; if (mode != null) { modeSet = mode; } // 게시물 종류 선택 String boardCategory = "A"; int listCount = bService.getBoardListCount(boardCategory); PageInfo pi = Pageination.getPageInfo(currentPage, listCount); // 정렬순서와 게시물 종류 설정 (동적 쿼리) BoardMode bMode = new BoardMode(modeSet, boardCategory); // 경매 리스트 ArrayList<Board> alist = bService.boardList(pi,bMode); // 첨부파일 리스트 ArrayList<Attachment> af = bService.boardFileList(); // 페이징 처리 되지않은 모든 리스트 조회용 필요(쿠키 확인용: 최근 본 상품) String bCategory = null; ArrayList<Board> allList = bService.boardAllList(bCategory); if (alist != null) { mv.addObject("alist", alist); mv.addObject("pi",pi); mv.addObject("modeSet",modeSet); mv.addObject("af", af); mv.addObject("allList",allList); mv.setViewName("auctionBoard"); } else { throw new BoardException("경매 게시판 조회 실패."); } return mv; } @RequestMapping("secondgoodList.bo") public ModelAndView secondGoodList(@RequestParam(value="page", required=false) Integer page, ModelAndView mv, @RequestParam(value="mode", required=false) String mode) { int currentPage = 1; if (page != null) { currentPage = page; } String modeSet = "recent"; if (mode != null) { modeSet = mode; } String boardCategory = "SG"; int listCount = bService.getBoardListCount(boardCategory); PageInfo pi = Pageination.getPageInfo(currentPage, listCount); BoardMode bMode = new BoardMode(modeSet, boardCategory); ArrayList<Board> alist = bService.boardList(pi,bMode); ArrayList<Attachment> af = bService.boardFileList(); // 페이징 처리 되지않은 모든 리스트 조회용 필요 String bCategory = null; ArrayList<Board> allList = bService.boardAllList(bCategory); if (alist != null) { mv.addObject("alist", alist); mv.addObject("pi",pi); mv.addObject("af", af); mv.addObject("modeSet", modeSet); mv.addObject("allList",allList); mv.setViewName("secondGoodBoard"); } else { throw new BoardException("중고 게시판 조회 실패."); } return mv; } @RequestMapping("selectOne.bo") public ModelAndView selectOne(@RequestParam("sgId") int sgId,@RequestParam(value="page",required=false) Integer page,@RequestParam(value="mode",required=false)String mode,ModelAndView mv, @RequestParam(value="auctionPrice", required=false) Integer price,@RequestParam(value="userId",required=false) String userId) { // 라산 : 조회수 카운트 기능 int a = bService.viewCount(sgId); if(price != null && userId != null) { // 로그인상태 : 경매 입찰시 AuctionHistory ah = new AuctionHistory(); ah.setSg_Id(sgId); ah.setUser_Id(userId); ah.setA_Price(price); int result = bService.insertAuction(ah); if( result > 0) { // 입찰 성공시 // 경매내역 조회하여 최고금액을 게시판에 적용하기 int maxPrice = bService.auctionMaxPrice(sgId); if(maxPrice < 1) { throw new BoardException(sgId+"의 경매가 최신화에 실패하였습니다."); } }else { throw new BoardException("입찰 실패"); } } Board board = bService.selectOne(sgId); Attachment at = bService.boardFileList(sgId); // 게시판 타입에 따른 뷰화면 전환 if(board != null) { if(board.getB_Category().equals("A")) { if(mode != null) { mv.addObject("page",page).addObject("mode",mode); } mv.addObject("board",board).addObject("at",at).addObject("pi",new PageInfo()).setViewName("auctionDetail"); }else { mv.addObject("board",board).addObject("at",at).addObject("pi",new PageInfo()).setViewName("usedDetail"); } }else { throw new BoardException("게시글 읽기를 실패하였습니다."); } return mv; } @RequestMapping("replyList.bo") public void replyList(@RequestParam(value="page",required=false) Integer page,HttpServletResponse response,int SG_ID) throws JsonIOException, IOException { int currentPage = 1; if (page != null) { currentPage = page; } int listCount = bService.getReplyListCount(SG_ID); PageInfo pi = Pageination.getReplyInfo(currentPage, listCount); ArrayList<Reply> list= bService.selectReplyList(SG_ID,pi); for(Reply r : list) { r.setREPLY_INFO(URLEncoder.encode(r.getREPLY_INFO(),"UTF-8")); r.setNICKNAME(URLEncoder.encode(r.getNICKNAME(),"UTF-8")); } HashMap<String, Object> result = new HashMap<String, Object>(); if (list != null) { result.put("pi", pi); result.put("rlist", list); } Gson gson = new GsonBuilder().setDateFormat("yyyy-MM-dd HH:mm:ss").create(); gson.toJson(result,response.getWriter()); } @RequestMapping("addReply.bo") @ResponseBody public String addReply(Reply r,HttpSession session,HttpServletRequest request) { // Member loginUser = (Member)session.getAttribute("loginUser"); // String rWriter = loginUser.getId(); int result=0; boolean add = Boolean.parseBoolean(request.getParameter("add")); result= bService.insertReply(r,add); if(result >0) { return "success"; }else { throw new BoardException("댓글 등록에 실패하였습니다."); } } @RequestMapping("replyUpdate.bo") @ResponseBody public String replyUpdate(Reply r,HttpSession session) { int result=bService.replyUpdate(r); if(result >0) { return "success"; }else { throw new BoardException("댓글 등록에 실패하였습니다."); } } @RequestMapping("deleteReply.bo") @ResponseBody public String deleteReply(Reply r,HttpSession session) { int result=bService.deleteReply(r,true); if(result >0) { return "success"; }else { throw new BoardException("댓글 등록에 실패하였습니다."); } } @RequestMapping("deleteReplyAdd.bo") @ResponseBody public String deleteReplyAdd(Reply r,HttpSession session) { int result=bService.deleteReply(r,false); if(result >0) { return "success"; }else { throw new BoardException("댓글 등록에 실패하였습니다."); } } @RequestMapping("boardupdateForm.bo") public ModelAndView boardUpdateForm(ModelAndView mv, @RequestParam("sgId") int sgId) { ArrayList<String> category = bService.category(); Board board = bService.selectOne(sgId); Attachment at = bService.boardFileList(sgId); if (board != null) { if (board.getB_Category().equals("A")) { mv.addObject("board", board).addObject("at", at).addObject("category", category) .setViewName("auctionUpdateForm"); } else { mv.addObject("board", board).addObject("at", at).addObject("category", category) .setViewName("usedUpdateForm"); } } else { throw new BoardException("게시글 읽기를 실패하였습니다."); } return mv; } @RequestMapping("boardUpdate.bo") public ModelAndView boardUpdate(ModelAndView mv, @ModelAttribute Board b, @RequestParam("smImg") MultipartFile uploadFile, HttpServletRequest request, HttpServletResponse response) { if (b.getSG_DEAL().equals("DIRECT")) { b.setSG_DELIVERY("N"); } else { b.setSG_AREA(""); } int type=Integer.parseInt(request.getParameter("type")); Attachment atm = new Attachment(); String renameFileName = ""; if (uploadFile != null && !uploadFile.isEmpty()) { try { renameFileName = saveFile(uploadFile, request, response); if (renameFileName != null) { atm.setORIGINALFILENAME(uploadFile.getOriginalFilename()); atm.setRENAMEFILENAME(renameFileName); } } catch (IOException e) { e.printStackTrace(); } } String root2 = request.getSession().getServletContext().getRealPath("resources") + "\\thumbnail/"; File file; int result1 = bService.updateBoard(b,type); if (result1 > 0) { int result = 1; if (!uploadFile.isEmpty()) { result = bService.updateAttachment(atm); } if (result <= 0) { file = new File(root2 + renameFileName); System.out.println("파일 삭제 확인 : " + file.delete()); throw new BoardException("썸네일 이미지 등록을 실패하였습니다."); } } else { file = new File(root2 + renameFileName); System.out.println("파일 삭제 확인 : " + file.delete()); throw new BoardException("게시물 등록을 실패하였습니다."); } mv.addObject("sgId", b.getSG_ID()).setViewName("redirect:selectOne.bo"); return mv; } @RequestMapping("insertF.bo") public ModelAndView insertF(ModelAndView mv, @RequestParam("type") int type) { ArrayList<String> category = bService.category(); String fromname = ""; if (type == 1) { fromname = "usedInsertForm"; } else { fromname = "auctionInsertForm"; } mv.addObject("category", category).setViewName(fromname); ; return mv; } @RequestMapping("selectLike.bo") @ResponseBody public int selectLike(@RequestParam("user_Id") String userId, @RequestParam("sgId") int sgId,@RequestParam("likeCheck") Boolean Check) { // 리턴할 값 더미 GoodLike num = new GoodLike(); num.setGl_check(0); // 좋아요 있는지 확인 ( 유저 아이디로 전체 조회 ) ArrayList<GoodLike> likeList = bService.selectGoodLike(userId); GoodLike user = new GoodLike(); user.setUser_Id(userId); user.setSg_id(sgId); // 좋아요가 안되어있을경우 if(Check == false) { int result = bService.insertGoodLike(user); if(result > 0) { // 게시판 테이블도 좋아요 반영 user.setGl_check(1); int boardLike = bService.updateBoardLike(user); if(boardLike > 0) { num.setGl_check(1); }else { throw new BoardException("게시판 좋아요 최신화 실패"); } }else { throw new BoardException("좋아요 추가 실패"); } }else { for(GoodLike gl: likeList) { if(gl.getSg_id() == sgId) { // 있으면 수정 if(gl.getGl_check() == 1) { gl.setGl_check(0); user.setGl_check(0); }else { gl.setGl_check(1); user.setGl_check(1); } // 좋아요값을 반대로 넣기(DB에 업데이트하는 과정) int changeCheck = bService.updateGoodLike(gl); if(changeCheck > 0) { // 성공시 게시판에도 좋아요 갯수 반영 int boardLike = bService.updateBoardLike(user); if(boardLike > 0) { num.setGl_check(gl.getGl_check()); }else { throw new BoardException("게시판 좋아요 최신화 실패"); } }else { throw new BoardException("좋아요 변경 실패"); } } } } return num.getGl_check(); } @RequestMapping("selectLikeCheck.bo") @ResponseBody public HashMap<String, Object> selectLikeCheck(@RequestParam(value="user_Id", required=false) String userId, @RequestParam(value="sgId") int sgId) { // 게시판 접속시 좋아요 체크상태 여부 확인 ArrayList<GoodLike> list = bService.selectGoodLike(userId); HashMap<String,Object> rlist = new HashMap<String, Object>(); rlist.put("result", 0); rlist.put("check", false); if(list.size() < 1) { return rlist; } for(GoodLike gl : list) { if(gl.getSg_id() == sgId) { rlist.put("result", gl.getGl_check()); rlist.put("check", true); return rlist; } } return rlist; } @RequestMapping("createCookie.bo") public void createCookie(@RequestParam(value="user_Id", required=false) String userId,@RequestParam(value="sgId") int sgId, HttpServletResponse response) { if(userId.length() > 0) { String cookieName = "history_"+userId+"_"+sgId; String cookieValue = Integer.toString(sgId); Cookie cookie = new Cookie(cookieName,cookieValue); cookie.setMaxAge(60*5); response.addCookie(cookie); } } @RequestMapping("uInsert.bo") public String usedInsert(@ModelAttribute Board b, @RequestParam("smImg") MultipartFile uploadFile, HttpServletRequest request, HttpServletResponse response,@RequestParam("aDay") int aDay,@RequestParam("type") int type) { if (b.getSG_DELIVERY() == null) { b.setSG_DELIVERY("N"); } else { b.setSG_AREA(""); } Calendar time = new GregorianCalendar(); time.add(Calendar.DATE, +aDay); Date date = new Date(time.getTimeInMillis()); b.setSG_END_DATE(date); Attachment atm = new Attachment(); String renameFileName = ""; if (uploadFile != null && !uploadFile.isEmpty()) { try { renameFileName = saveFile(uploadFile, request, response); if (renameFileName != null) { atm.setORIGINALFILENAME(uploadFile.getOriginalFilename()); atm.setRENAMEFILENAME(renameFileName); } } catch (IOException e) { e.printStackTrace(); } } String[] allName = request.getParameter("imgNames").split(","); String[] saveName = request.getParameter("deletImg").split(","); String root = request.getSession().getServletContext().getRealPath("resources") + "\\textImgs/"; String root2 = request.getSession().getServletContext().getRealPath("resources") + "\\thumbnail/"; File file; for (int i = 0; i < saveName.length; i++) { for (int j = 0; j < allName.length; j++) { if (saveName[i].equals(allName[j])) { allName[j] = "N"; } } } for (int i = 0; i < allName.length; i++) { if (!allName[i].equals("N")) { file = new File(root + allName[i]); System.out.println("파일 삭제 확인 : " + file.delete()); } } int result1 = bService.insertBoard(b); if (result1 > 0) { int result = bService.insertAttachment(atm); if (result > 0) { if(type==1)return "redirect:secondgoodList.bo"; else return "redirect:auctionList.bo"; } else { for (int i = 0; i < allName.length; i++) { if (!allName[i].equals("N")) { file = new File(root + allName[i]); System.out.println("파일 삭제 확인 : " + file.delete()); } } file = new File(root2 + renameFileName); System.out.println("파일 삭제 확인 : " + file.delete()); throw new BoardException("썸네일 이미지 등록을 실패하였습니다."); } } else { for (int i = 0; i < allName.length; i++) { if (!allName[i].equals("N")) { file = new File(root + allName[i]); System.out.println("파일 삭제 확인 : " + file.delete()); } } file = new File(root2 + renameFileName); System.out.println("파일 삭제 확인 : " + file.delete()); throw new BoardException("게시물 등록을 실패하였습니다."); } } public String saveFile(MultipartFile file, HttpServletRequest request, HttpServletResponse response) throws IOException { String root = request.getSession().getServletContext().getRealPath("resources"); String savePath = root + "\\thumbnail"; File folder = new File(savePath); if (!folder.exists()) { folder.mkdirs(); } SimpleDateFormat sdf = new SimpleDateFormat("yyMMddHHmmss"); String oringinFileName = file.getOriginalFilename(); String renameFileName = "i" + sdf.format(new java.sql.Date(System.currentTimeMillis())) + (int) (Math.random() * 1000) + 1 + "." + oringinFileName.substring(oringinFileName.lastIndexOf(".") + 1); String renamePath = folder + "\\" + renameFileName; try { file.transferTo(new File(renamePath)); } catch (Exception e) { e.printStackTrace(); } return renameFileName; } @RequestMapping("deleteBoard.bo") public String deleteBoard(@RequestParam("sgId") int sgId,@RequestParam("type") int type,Model model) { int result = bService.deleteBoard(sgId); int updatePenalty = 0; if(result>0) { if(type==1) return "redirect:secondgoodList.bo"; else { Member user = (Member)model.getAttribute("loginUser"); int penaltyPoint = user.getPenalty_point(); if(penaltyPoint == 2) { user.setRank_code("E"); user.setPenalty_point(0); user.setPenalty_stack(1); updatePenalty = mService.updatePenaltyPoint(user); }else { user.setPenalty_point(user.getPenalty_point()+1); updatePenalty = mService.updatePenaltyPoint(user); } if(updatePenalty > 0) { Member loginUser = mService.memberLogin(user); model.addAttribute("loginUser",loginUser); } return "redirect:auctionList.bo"; } }else { return "error"; } } }
true
0e3bd38b2d7ac470b7d51d91181e7bb1fd31a9be
Java
kobejava24/e3
/e3-common/src/main/java/com/e3/util/dto/EUDataGrideResult.java
UTF-8
652
2.078125
2
[]
no_license
package com.e3.util.dto; import java.io.Serializable; import java.util.List; /** * Created by 91908 on 2017/12/20. */ public class EUDataGrideResult implements Serializable{ private long total; private List<?> rows; public EUDataGrideResult(long total, List<?> rows) { this.total = total; this.rows = rows; } public EUDataGrideResult() { } public long getTotal() { return total; } public void setTotal(long total) { this.total = total; } public List<?> getRows() { return rows; } public void setRows(List<?> rows) { this.rows = rows; } }
true
b996712e65b75040b9794e4b32e75ca7689ccc57
Java
phillip12397/Tim
/app/src/main/java/com/developfuture/fortknox/ui/home/IconModelDao.java
UTF-8
651
1.796875
2
[]
no_license
package com.developfuture.fortknox.ui.home; import androidx.lifecycle.LiveData; import androidx.room.Dao; import androidx.room.Delete; import androidx.room.Insert; import androidx.room.Query; import androidx.room.Update; import com.developfuture.fortknox.ui.investments.Investments; import java.util.List; @Dao public interface IconModelDao { @Insert void insert(IconModel icon); @Update void update(IconModel icon); @Delete void delete(IconModel icon); @Query("DELETE FROM icons_table") void deleteAllNotes(); @Query("SELECT * FROM icons_table ORDER BY id") LiveData<List<IconModel>> getAllIcons(); }
true
6b5bdda799e8eb36e2915d810450e6ed50da40a7
Java
wyk152/callers_visitors
/micro-rest/src/main/java/com/easymicro/rest/modular/business/model/SetAutoReplyModel.java
UTF-8
215
1.835938
2
[ "Apache-2.0" ]
permissive
package com.easymicro.rest.modular.business.model; public class SetAutoReplyModel { private String tip; public String getTip() { return tip; } public void setTip(String tip) { this.tip = tip; } }
true
103f3b7a694fb5ad378dffdde0d04416e9ec5c77
Java
marco/apcsa
/grocery-store-simulator/src/test/java/simulator/shopper/SocialNetworkTest.java
UTF-8
943
2.546875
3
[]
no_license
package simulator.shopper; import static org.junit.Assert.assertTrue; import org.junit.Test; import config.Configuration; import simulator.bigbrother.BigBrother; import simulator.store.AbstractGroceryStore; import simulator.world.SimpleWorld; public class SocialNetworkTest { @Test(timeout = 5000) public void testSocialNetwork() { SimpleWorld.destroyWorld(); BigBrother.resetBigBrother(); new SimpleWorld(15); // Selects the store for the simulation AbstractGroceryStore store = Configuration.getProfitableStore(); while (!BigBrother.getBigBrother().tick()); SocialNetwork socialNetwork = SocialNetwork.getSocialNetwork(); double rating = socialNetwork.getRatingForStore(store); System.out.println("Ratings: " + socialNetwork.getNumberOfVotesForStore(store)); System.out.println("Rating received: " + rating); assertTrue(0.75 < rating); } }
true
4ba2a5f656b1b3a1a8de7eada327626a730e4b16
Java
devsong/learn
/learn-java-basic/src/main/java/com/gzs/learn/patterdesign/behavior/strategy/Transportation.java
UTF-8
141
2.234375
2
[ "Apache-2.0" ]
permissive
package com.gzs.learn.patterdesign.behavior.strategy; public interface Transportation { void toTarget(TransportationContext context); }
true
3719647a45ca827fd801156187c1119511b54f67
Java
gvilchis23/eservice
/BancaEliteEJB/src/com/bancoazteca/elite/beans/.svn/text-base/InternacionalesBancosRequestTO.java.svn-base
UTF-8
653
1.75
2
[]
no_license
package com.bancoazteca.elite.beans; import java.io.Serializable; public class InternacionalesBancosRequestTO implements Serializable{ private static final long serialVersionUID = 8290079193291660287L; private String user; private String pais; private String ciudad; public String getUser() { return user; } public void setUser(String user) { this.user = user; } public String getPais() { return pais; } public void setPais(String pais) { this.pais = pais; } public String getCiudad() { return ciudad; } public void setCiudad(String ciudad) { this.ciudad = ciudad; } }
true
0eee7a2071baef399185a6f8f97223817450ed8e
Java
qiniuchina/darklightrest
/src/main/java/com/dxc/darklightrest/entity/StockModelMountId.java
UTF-8
1,793
2.40625
2
[]
no_license
package com.dxc.darklightrest.entity; // Generated 2018-5-21 13:58:10 by Hibernate Tools 5.2.10.Final import javax.persistence.Column; import javax.persistence.Embeddable; /** * StockModelMountId generated by hbm2java */ @Embeddable public class StockModelMountId implements java.io.Serializable { private String stockCode; private String stockDate; public StockModelMountId() { } public StockModelMountId(String stockCode, String stockDate) { this.stockCode = stockCode; this.stockDate = stockDate; } @Column(name = "stock_code", nullable = false, length = 10) public String getStockCode() { return this.stockCode; } public void setStockCode(String stockCode) { this.stockCode = stockCode; } @Column(name = "stock_date", nullable = false, length = 10) public String getStockDate() { return this.stockDate; } public void setStockDate(String stockDate) { this.stockDate = stockDate; } public boolean equals(Object other) { if ((this == other)) return true; if ((other == null)) return false; if (!(other instanceof StockModelMountId)) return false; StockModelMountId castOther = (StockModelMountId) other; return ((this.getStockCode() == castOther.getStockCode()) || (this.getStockCode() != null && castOther.getStockCode() != null && this.getStockCode().equals(castOther.getStockCode()))) && ((this.getStockDate() == castOther.getStockDate()) || (this.getStockDate() != null && castOther.getStockDate() != null && this.getStockDate().equals(castOther.getStockDate()))); } public int hashCode() { int result = 17; result = 37 * result + (getStockCode() == null ? 0 : this.getStockCode().hashCode()); result = 37 * result + (getStockDate() == null ? 0 : this.getStockDate().hashCode()); return result; } }
true
c4e3bbaa86e23a314cad1c77e874b09df162bb20
Java
malmstein/invitine
/android/src/main/java/com/malmstein/invitine/android/stages/PictureSlideFragmentAdapter.java
UTF-8
647
2.171875
2
[ "Apache-2.0" ]
permissive
package com.malmstein.invitine.android.stages; import android.support.v4.app.Fragment; import android.support.v4.app.FragmentManager; import android.support.v4.app.FragmentStatePagerAdapter; import com.malmstein.invitine.android.fragments.PictureFragment; public class PictureSlideFragmentAdapter extends FragmentStatePagerAdapter { private static final int NUM_PAGES = 5; public PictureSlideFragmentAdapter(FragmentManager fm) { super(fm); } @Override public Fragment getItem(int position) { return new PictureFragment(); } @Override public int getCount() { return NUM_PAGES; } }
true
413b280e64009ab1a8bee2619fa927c63be84f74
Java
akileecn/webSimple
/src/main/java/cn/aki/controller/ResumeController.java
UTF-8
10,027
2.109375
2
[]
no_license
package cn.aki.controller; import cn.aki.entity.*; import cn.aki.entity.base.ResumeSubEntity; import cn.aki.form.validator.BeginAndEndDate; import cn.aki.response.DataResponse; import cn.aki.response.FormResponse; import cn.aki.response.SimpleResponse; import cn.aki.service.ResumeService; import cn.aki.service.ResumeSubService; import cn.aki.utils.Constants; import com.alibaba.fastjson.JSON; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Controller; import org.springframework.ui.Model; import org.springframework.util.FileCopyUtils; import org.springframework.validation.BindingResult; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestParam; import org.springframework.web.bind.annotation.ResponseBody; import org.springframework.web.multipart.MultipartFile; import javax.servlet.http.HttpServletResponse; import javax.validation.Valid; import java.io.ByteArrayInputStream; import java.io.IOException; import java.io.InputStream; import java.io.PrintWriter; import java.util.Date; import java.util.List; import static org.springframework.web.bind.annotation.RequestMethod.GET; import static org.springframework.web.bind.annotation.RequestMethod.POST; /** * 简历 * * @author aki * 2016年4月29日 上午9:48:40 */ @Controller @RequestMapping("/resume") public class ResumeController extends BaseController { @Autowired private ResumeService resumeService; @Autowired private ResumeSubService resumeSubService; /** * 上传头像 */ @RequestMapping(value = "/photo/upload") public void upload(@RequestParam("file") MultipartFile file, Resume resume, HttpServletResponse response) { SimpleResponse json = new SimpleResponse(); if (!file.isEmpty()) { //上传校验 if (file.getSize() > 50 * 1024) { json.setMessage("上传文件必须小于50kb"); } else if (!file.getContentType().equals("image/jpeg") && !file.getContentType().equals("image/png")) { json.setMessage("只能上传jpg、png格式图片"); } else { //文件命名 try { resume.setPhoto(file.getBytes()); resumeService.updatePhoto(resume); json.setSuccess(true); json.setMessage("上传成功"); } catch (IOException e) { e.printStackTrace(); json.setMessage("上传失败"); } } } response.setCharacterEncoding("utf-8"); response.setContentType("text/html; charset=utf-8"); try (PrintWriter out = response.getWriter()) { out.println(JSON.toJSONString(json)); } catch (IOException e) { e.printStackTrace(); } } @RequestMapping(path = "/photo/show") public void getPhoto(Resume resume, HttpServletResponse response) { resume = resumeService.getPhoto(resume); if (resume != null && resume.getPhoto() != null) { try (InputStream is = new ByteArrayInputStream(resume.getPhoto())) { FileCopyUtils.copy(is, response.getOutputStream()); } catch (IOException e) { e.printStackTrace(); } } } @RequestMapping(path = "/list", method = GET) public String toList(Resume resume, Model model) { List<Resume> list = resumeService.getList(resume); model.addAttribute("resume", resume); model.addAttribute("list", list); return "resume/list"; } @RequestMapping(path = "/detail", method = GET) public String toDetail(Integer id, String recruitType, String applyJobId, Model model) { model.addAttribute("id", id); model.addAttribute("recruitType", recruitType); //应聘岗位id,由岗位页面拦截跳转得到 model.addAttribute("applyJobId", applyJobId); return "resume/detail"; } @ResponseBody @RequestMapping(path = "/save/base", method = POST) public FormResponse<Void> saveBase(@Valid Resume form, BindingResult result) { FormResponse<Void> response = handleFormError(result); resumeService.validate(form, response); if (response.isSuccess()) { resumeService.update(form); } return response; } @ResponseBody @RequestMapping(path = "/detail/all", method = POST) public DataResponse<Resume> handleDetail(Resume resume) { DataResponse<Resume> response = new DataResponse<Resume>(); resume = resumeService.get(resume, true); response.setData(resume); return response; } @ResponseBody @RequestMapping(path = "/submit", method = POST) public SimpleResponse handleSubmit(Resume resume) { String message = resumeService.submit(resume); SimpleResponse response = new SimpleResponse(); response.setMessage(message); response.setSuccess(message == null); return response; } /* begin从属信息 */ @ResponseBody @RequestMapping(path = "/save/award", method = POST) public FormResponse<Integer> saveAward(@Valid ResumeAward form, BindingResult result) { return saveSub(form, result); } @ResponseBody @RequestMapping(path = "/delete/award", method = POST) public SimpleResponse deleteAward(ResumeAward bean, BindingResult result) { return deleteSub(bean); } @ResponseBody @RequestMapping(path = "/save/computer", method = POST) public FormResponse<Integer> saveComputer(@Valid ResumeComputer form, BindingResult result) { return saveSub(form, result); } @ResponseBody @RequestMapping(path = "/delete/computer", method = POST) public SimpleResponse deleteComputer(ResumeComputer bean, BindingResult result) { return deleteSub(bean); } @ResponseBody @RequestMapping(path = "/save/education") public FormResponse<Integer> saveEducation(String recruitType, @Valid ResumeEducation form, BindingResult result) { //@Valid放其他参数会报错 return saveSub(form, recruitType, result); } @ResponseBody @RequestMapping(path = "/delete/education", method = POST) public SimpleResponse deleteEducation(ResumeEducation bean, BindingResult result) { return deleteSub(bean); } @ResponseBody @RequestMapping(path = "/save/family", method = POST) public FormResponse<Integer> saveFamily(@Valid ResumeFamily form, BindingResult result) { return saveSub(form, result); } @ResponseBody @RequestMapping(path = "/delete/family", method = POST) public SimpleResponse deleteFamily(ResumeFamily bean, BindingResult result) { return deleteSub(bean); } @ResponseBody @RequestMapping(path = "/save/foreignLanguage", method = POST) public FormResponse<Integer> saveForeignLanguage(@Valid ResumeForeignLanguage form, BindingResult result) { return saveSub(form, result); } @ResponseBody @RequestMapping(path = "/delete/foreignLanguage", method = POST) public SimpleResponse deleteForeignLanguage(ResumeForeignLanguage bean, BindingResult result) { return deleteSub(bean); } @ResponseBody @RequestMapping(path = "/save/studentCadre", method = POST) public FormResponse<Integer> saveStudentCadre(@Valid ResumeStudentCadre form, BindingResult result) { return saveSub(form, result); } @ResponseBody @RequestMapping(path = "/delete/studentCadre", method = POST) public SimpleResponse deleteStudentCadre(ResumeStudentCadre bean, BindingResult result) { return deleteSub(bean); } @ResponseBody @RequestMapping(path = "/save/work", method = POST) public FormResponse<Integer> saveWork(@Valid ResumeWork form, BindingResult result) { return saveSub(form, result); } @ResponseBody @RequestMapping(path = "/delete/work", method = POST) public SimpleResponse deleteWork(ResumeWork bean, BindingResult result) { return deleteSub(bean); } @ResponseBody @RequestMapping(path = "/save/practice", method = POST) public FormResponse<Integer> savePractice(@Valid ResumePractice form, BindingResult result) { return saveSub(form, result); } @ResponseBody @RequestMapping(path = "/delete/practice", method = POST) public SimpleResponse deletePractice(ResumePractice bean, BindingResult result) { return deleteSub(bean); } @ResponseBody @RequestMapping(path = "/save/train", method = POST) public FormResponse<Integer> saveTrain(@Valid ResumeTrain form, BindingResult result) { return saveSub(form, result); } @ResponseBody @RequestMapping(path = "/delete/train", method = POST) public SimpleResponse deleteTrain(ResumeTrain bean, BindingResult result) { return deleteSub(bean); } /** * 公共修改方法 * * @param sub * @param result * @return */ private FormResponse<Integer> saveSub(ResumeSubEntity sub, String recruitType, BindingResult result) { FormResponse<Integer> response = handleFormError(result); if (recruitType != null) { final String errInfo = "字段不能为空"; if (sub instanceof ResumeEducation && !Constants.RECRUIT_TYPE_SOCIETY.equals(recruitType)) { Boolean hasBeenCadre = ((ResumeEducation) sub).getHasBeenCadre(); String gradeRank = ((ResumeEducation) sub).getGradeRank(); if (hasBeenCadre == null) { response.putError("hasBeenCadre", errInfo); } if (gradeRank == null) { response.putError("gradeRank", errInfo); } } } if (sub instanceof BeginAndEndDate) { Date begin = ((BeginAndEndDate) sub).getBeginDate(); Date end = ((BeginAndEndDate) sub).getEndDate(); if (begin != null && end != null && end.getTime() < begin.getTime()) { response.putError("endDate", "结束时间必须大于开始时间"); } } if (response.isSuccess()) { resumeSubService.saveOrUpdate(sub); response.setData(sub.getId()); } return response; } private FormResponse<Integer> saveSub(ResumeSubEntity sub, BindingResult result) { return saveSub(sub, null, result); } /** * 公共删除方法 * * @param sub * @return */ private SimpleResponse deleteSub(ResumeSubEntity sub) { SimpleResponse response = new SimpleResponse(); resumeSubService.delete(sub); response.setSuccess(true); return response; } /* end从属信息 */ }
true
42af1b4e2635186d6d9bca31190560d70dc158c5
Java
isax/Leetcode2
/CoinChange.java
UTF-8
1,640
3.109375
3
[]
no_license
public class Solution { // dp // https://leetcode.com/discuss/76217/java-both-iterative-recursive-solutions-with-explanations public int coinChange(int[] coins, int amount) { int [] dp = new int[amount+1]; for(int i = 1; i<=amount; i++){ int curMin = -1; for(int j = 0; j<coins.length; j++){ int remain = i-coins[j]; if(remain<0 || dp[remain]==-1){ continue; }else{ curMin = curMin == -1? dp[remain]+1 : Math.min(curMin, dp[remain]+1); } } dp[i] = curMin; } return dp[amount]; } // https://leetcode.com/discuss/76194/c-o-n-amount-time-o-amount-space-dp-solution public int coinChangeBacktracking(int[] coins, int amount) { Arrays.sort(coins); int[] res= new int[1]; res[0] = -1; helper(coins, coins.length-1, amount, 0, res); return res[0]; } private void helper(int[]coins, int curCoin, int amount, int count, int[]res){ if(curCoin<0){ return; } int number = amount/coins[curCoin]; for(int i=number;i>=0;i--){ int remain=amount-coins[curCoin]*i; if(remain>0 && (res[0]==-1 || count+i<res[0])){ helper(coins, curCoin-1, remain, count+i, res); }else if(remain==0) { res[0] = res[0]==-1?count+i : Math.min(count+i, res[0]); }else{ // count+i>res[0], no need to dfs break; } } } }
true
687b4002b795c20fbb29c2e362c253b5ff0beab5
Java
almazych/vktest
/app/src/main/java/com/almaz/vktest/PostItemAdapter.java
UTF-8
2,262
2.390625
2
[]
no_license
package com.almaz.vktest; import android.content.Context; import android.support.v7.widget.RecyclerView; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.ImageView; import com.almaz.vktest.wallpostdb.Attachment; import com.almaz.vktest.wallpostdb.Response; import com.squareup.picasso.Picasso; public class PostItemAdapter extends RecyclerView.Adapter<PostItemAdapter.ViewHolder> { Context context; Response mResponse; public PostItemAdapter(Response mResponse) { this.mResponse = mResponse; } @Override public PostItemAdapter.ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) { context = parent.getContext(); View v = LayoutInflater.from(parent.getContext()).inflate(R.layout.items, parent, false); return new PostItemAdapter.ViewHolder(v); } @Override public void onBindViewHolder(PostItemAdapter.ViewHolder holder, int position) { holder.bind(mResponse.getAttachments().get(position)); } @Override public int getItemCount() { if (mResponse.getAttachments() == null){ return 0; } return mResponse.getAttachments().size(); } public void changeDataSet(Response response){ mResponse = response; notifyDataSetChanged(); } class ViewHolder extends RecyclerView.ViewHolder { ImageView mImageView; public ViewHolder(View itemView) { super(itemView); mImageView = (ImageView)itemView.findViewById(R.id.images); } public void bind(final Attachment item) { if(item.getPhoto() !=null){ Picasso.with(context) .load(item.getPhoto().getPhoto604()) .resize(400,400) .placeholder(R.drawable.post_fon) .into(mImageView); } if (item.getVideo()!=null){ Picasso.with(context) .load(item.getVideo().getPhoto320()) .resize(400,400) .placeholder(R.drawable.post_fon) .into(mImageView); } } } }
true
d75556d92d1495b02c86b94fda69dcb501e717da
Java
huweibaba/ExperimentSystem
/src/main/java/com/byk/experimentsystem/mapper/ClassMapper.java
UTF-8
1,163
2.109375
2
[]
no_license
package com.byk.experimentsystem.mapper; import com.byk.experimentsystem.entity.Class; import com.byk.experimentsystem.entity.ClassExample; import java.util.List; import com.byk.experimentsystem.entity.Major; import org.apache.ibatis.annotations.Param; import org.apache.ibatis.annotations.Select; import org.springframework.stereotype.Repository; @Repository public interface ClassMapper { int countByExample(ClassExample example); int deleteByExample(ClassExample example); int insert(Class record); int insertSelective(Class record); List<Class> selectByExample(ClassExample example); int updateByExampleSelective(@Param("record") Class record, @Param("example") ClassExample example); int updateByExample(@Param("record") Class record, @Param("example") ClassExample example); @Select("select id from class where name=#{name} and grade=#{grade} and major_id=#{majorId}") Integer getIdByNGM(@Param("name")String name,@Param("grade") Integer grade,@Param("majorId") Integer majorId); @Select("select * from class where major_id=#{majorId}") List<Class> selectByMajorId(@Param("majorId") Integer majorId); }
true
1d648c250041e3fe1226e84e29c0df1b6120d4bc
Java
Prasad48/android
/demo/src/main/java/com/useriq/demo/TabsFragment.java
UTF-8
2,543
2.40625
2
[]
no_license
package com.useriq.demo; import android.os.Bundle; import android.support.design.widget.TabLayout; import android.support.v4.app.Fragment; import android.support.v4.app.FragmentManager; import android.support.v4.app.FragmentPagerAdapter; import android.support.v4.view.ViewPager; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import java.util.ArrayList; import java.util.List; public class TabsFragment extends Fragment { public TabsFragment() { // Required empty public constructor } public static TabsFragment newInstance() { TabsFragment fragment = new TabsFragment(); Bundle args = new Bundle(); fragment.setArguments(args); return fragment; } @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); } @Override public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { View view = inflater.inflate(R.layout.fragment_tabs, container, false); ViewPager viewPager = view.findViewById(R.id.viewpager); setupViewPager(viewPager); TabLayout tabs = view.findViewById(R.id.tablayout); tabs.setupWithViewPager(viewPager); return view; } private void setupViewPager(ViewPager viewPager) { ViewPagerAdapter adapter = new ViewPagerAdapter(this.getChildFragmentManager()); adapter.addFragment(new FirstFragment(), "First"); adapter.addFragment(new SecondFragment(), "Second"); adapter.addFragment(new ThirdFragment(), "Third"); viewPager.setAdapter(adapter); } class ViewPagerAdapter extends FragmentPagerAdapter { private final List<Fragment> mFragmentList = new ArrayList<>(); private final List<String> mFragmentTitleList = new ArrayList<>(); public ViewPagerAdapter(FragmentManager manager) { super(manager); } @Override public Fragment getItem(int position) { return mFragmentList.get(position); } @Override public int getCount() { return mFragmentList.size(); } public void addFragment(Fragment fragment, String title) { mFragmentList.add(fragment); mFragmentTitleList.add(title); } @Override public CharSequence getPageTitle(int position) { return mFragmentTitleList.get(position); } } }
true
381bb740ca3046ffac071b7153b20a1bdede42a7
Java
shaikshakeeb785/hybrisNew
/hybris/bin/modules/integration-apis/odata2services/src/de/hybris/platform/odata2services/odata/schema/property/SimplePropertyGenerator.java
UTF-8
2,109
2.078125
2
[]
no_license
/* * Copyright (c) 2019 SAP SE or an SAP affiliate company. All rights reserved. */ package de.hybris.platform.odata2services.odata.schema.property; import de.hybris.platform.integrationservices.model.TypeAttributeDescriptor; import de.hybris.platform.odata2services.odata.schema.SchemaElementGenerator; import de.hybris.platform.odata2services.odata.schema.utils.EdmTypeUtils; import java.util.Collections; import java.util.List; import javax.validation.constraints.NotNull; import org.apache.olingo.odata2.api.edm.provider.AnnotationAttribute; import org.apache.olingo.odata2.api.edm.provider.SimpleProperty; /** * A generator for {@code <Property Name=".." Type="..."/>} elements in the EDMX. */ public class SimplePropertyGenerator implements SchemaElementGenerator<SimpleProperty, TypeAttributeDescriptor> { private SchemaElementGenerator<List<AnnotationAttribute>, TypeAttributeDescriptor> annotationsGenerator; /** * Generates EDM Property based on the attribute description in the Integration Object model. * @param descriptor descriptor of the attribute in an Integration Object. Attribute descriptor cannot be {@code null}. * @return EDM property corresponding to the specified integration object item attribute. */ @Override public SimpleProperty generate(@NotNull final TypeAttributeDescriptor descriptor) { return new SimpleProperty() .setName(descriptor.getAttributeName()) .setType(EdmTypeUtils.convert(descriptor.getAttributeType().getTypeCode())) .setAnnotationAttributes(generateAnnotations(descriptor)); } private List<AnnotationAttribute> generateAnnotations(final TypeAttributeDescriptor descriptor) { return annotationsGenerator != null ? annotationsGenerator.generate(descriptor) : Collections.emptyList(); } protected SchemaElementGenerator<List<AnnotationAttribute>, TypeAttributeDescriptor> getAnnotationsGenerator() { return annotationsGenerator; } public void setAnnotationsGenerator(final SchemaElementGenerator<List<AnnotationAttribute>, TypeAttributeDescriptor> generator) { annotationsGenerator = generator; } }
true
df11a272279741ca4fffb64bfdbe7017521e1f90
Java
inglepr/BasicJavaPrograms
/src/com/bridgelabz/functional/BubbleSortForString.java
UTF-8
676
3.21875
3
[]
no_license
package com.bridgelabz.functional; import com.bridgelabz.util.Utility; public class BubbleSortForString { public static void main(String[] args) { System.out.println("Enter size of array "); int num=Utility.getInteger(); String[] str=new String[num+1]; System.out.println("Enter "+num+" String elements"); for(int i=0;i<str.length;i++) { str[i]=Utility.getString(); } //long starTime=System.nanoTime(); System.out.println("After sorting"); Utility.bubbleSortForString(str); Utility.printStringArray(str); //long endTime=System.nanoTime(); //double elapsedTime=(endTime-starTime)/1000.0; //System.out.println("Elapsed time is "+elapsedTime); } }
true
94c78d08f170a36e70d36774021aed099196486c
Java
gagaprince/blog
/src/main/java/com/prince/myproj/blog/dao/MusicDao.java
UTF-8
360
1.976563
2
[]
no_license
package com.prince.myproj.blog.dao; import com.prince.myproj.blog.models.MusicModel; import java.util.List; import java.util.Map; /** * Created by gagaprince on 15-12-20. */ public interface MusicDao { public void save(MusicModel musicModel); public List<MusicModel> getMusicList(); public MusicModel getMusicById(Map<String,Object> idMap); }
true
a9910adef02edb1d22f1ae7822634ca2bcd64a47
Java
S-Harshit/ADA
/Algorithms/Djkistra.java
UTF-8
1,475
2.96875
3
[]
no_license
package com.company; public class Djkistra { public static void Djkistra(int a[][]) { int v = a.length; boolean visited[] = new boolean[v]; int dist[] = new int[v]; dist[0] = 0; for (int i = 1; i < v; i++) { dist[i] = 1000000; } for (int i = 0; i < v - 1; i++) { int minVertex = minVertex(dist, visited); visited[minVertex] = true; for (int j = 0; j < v; j++) { if (a[minVertex][j] != 0 && !visited[j] && dist[minVertex] != 99999999) { int newDist = dist[minVertex] + a[minVertex][j]; if (newDist < dist[j]) { dist[j] = newDist; } } } } System.out.println("Vertex \tDistance from source"); for (int i = 0; i < v; i++) { System.out.println(i + " \t\t " + dist[i]); } } public static int minVertex(int[] distance, boolean visited[]) { int min = -1; for (int i = 0; i < distance.length; i++) { if (!visited[i] && (min == -1 || distance[i] < distance[min])) { min = i; } } return min; } public static void main(String[] args) { int a[][] = { { 0, 8, 0, 0, 0 }, { 0, 0, 0, 7, 1 }, { 0, 3, 0, 0, 0 }, { 0, 0, 3, 0, 0 }, { 2, 0, 0, 4, 0 } }; Djkistra(a); } }
true
8c930ea170dc1aa09214a042bd4b2d6155f180f4
Java
Nerofox/DeltaStar
/Pigou/src/fr/deltastar/pigou/constant/Constants.java
UTF-8
5,068
2.03125
2
[]
no_license
package fr.deltastar.pigou.constant; /** * Les constantes général ainsi que les config non modifiable en prod sont ici * @author Valentin */ public class Constants { public final static String TITLE_APPLICATION = "PIGOU"; //CONFIG SYSTEMES ELECTRIQUES //interval de decompte de l'énergie en millisecondes public final static int INTERVAL_POWER = 30000; //consommation de base toute les secondes du systèmes electriques public final static int NB_CONSOMMATION_BASE = 1; //consommation d'un systeme annexe public final static int CONSOMMATION_SYSTEM = 3; //seuil avant alert du systèmes electriques sur 100 public final static int LIMIT_POWER_BEFORE_ALERT = 10; //temps d'apparition du message d'alerte public final static int TIME_DISPLAY_ALERT_POWER = 5000; //CONFIG SYSTEMES MOTEUR //seuil avant alert du systemes des moteurs public final static int LIMIT_MAIN_FUEL_ALERT = 1000; public final static int LIMIT_RCS_FUEL_ALERT = 100; //temps d'apparition du message d'alerte public final static int TIME_DISPLAY_ALERT_ENGINE = 5000; //CONFIG SYSTEMES SUPPORT DE VIE //conso par interval de l'oxygen public final static int CONSOMMATION_O2N2 = 1; //augmentation par interval de la température si radiateur non déployé public final static int AUGMENTATION_TEMP_COOLING = 3; //interval de rafraichissement public final static int INTERVAL_COOLING_O2N2 = 5000; //interval rafraichissement avant remplissage public final static int INTERVAL_O2N2_SUPPLY = 500; //seuil avant alert du support de vie public final static int LIMIT_O2N2_ALERT = 10; //temps d'apparition du message d'alerte public final static int TIME_DISPLAY_ALERT_LIFEPACK = 5000; //temperature en celsius minimal du systèmes de refroidissement public final static int TEMP_COOLING_MIN = 25; //temperature en celsius max avant alert du systèmes de refroidissement public final static int TEMP_COOLING_ALERT_MAX = 100; //temperature en celsius max avant surchauffe public final static int TEMP_COOLING_OVERHEATED = 120; //CONFIG LOGIQUE DU VAISSEAU public final static int ALTITUDE_MINIMAL_FORLANDING = 300; //altitude en mètre minimum pour le considéré comme atterit public final static int ALTITUDE_MINIMAL_FORLIFE = 20; //altitude en mètre minimum pour considéré l'extérieur comme respirable //CONFIG POUR LA COMMUNICATION AVEC ORBITER public final static String FILENAME_CONFIG_ORBITER = "configOrbiter.pf"; public final static String PORT_ORBITER_SOCKET = "14000"; public final static String DELIMITER_CMD_ORBITER = ","; //delimiteur utilisé pour l'envoi des commandes à Orbiter public final static String TITLE_ORBITER_DIRECTORY_CHOOSER = "Choose Orbiter directory"; public final static String MSG_CONFIG_ORBITER_SUCCESS = "Configuration done for orbiter"; public final static String MSG_CONFIG_ORBITER_BAD = "Configuration Orbiter not found"; public final static String PATHS_ORBITER_SCENARIO_PIGOU = "\\Scenarios\\PIGOU\\"; public final static String ORBITER_MISSION_ONE = "Mission1.scn"; //CONFIG POUR LE DELTASTAR VIRTUEL //si a true on utilise le deltastar virtuel, sinon le réel public final static boolean MODE_VIRTUAL = false; public final static String VIRTUAL_IP = "127.0.0.1"; public final static String VIRTUAL_PORT_A = "10000"; public final static String VIRTUAL_PORT_B = "11000"; public final static String VIRTUAL_PORT_C = "12000"; public final static int SIZE_WIDTH_APPLICATION = 800; public final static int SIZE_HEIGHT_APPLICATION = 600; //CONFIG POUR LES COMMUNICATIONS ARDUINO public final static int SERIALCOM_DEBIT_COMMUNICATION = 9600; public final static int REFRESH_ARDUINO_INTERVAL = 1000; public final static String FILENAME_CONFIG_PORT_COM_ARDUINO = "arduinoPort.pf"; //PARTIE AUTO CONFIG SETTING CONTROLLEUR public static String FILENAME_CONFIG = "config.pf"; public static String FILENAME_DELIMITER = ";"; public static String FILENAME_NOTFOUND_CONFIG_MSG = "WARNING : Config PIGOU is missing for DeltaStar, please config the I/O"; public static String AUTOCONFIG_VIEW_NB_INPUT = "%d / %d input"; public static String AUTOCONFIG_VIEW_NB_OUTPUT = "%d / %d output"; public static String AUTOCONFIG_VIEW_NB_TOTAL = "Total progress %d / %d I/O"; public static String AUTOCONFIG_MSG_CHOOSEOUTPUT = "Please choose a valid output before next"; public static String AUTO_CONFIG_MSG_OUTPUTPROGRESS = "Configuration output in progress, clic on the start button and look at Deltastar and clic on the component on"; public static String AUTO_CONFIG_MSG_OUTPUTFINISH = "Configuration output is finish, launch configuration input"; public static String AUTO_CONFIG_MSG_FINISH = "Configuration finished, have fun !"; //PARTIE TESTING DU PANEL (branchement) public final static int NB_SWITCH_INPUT = 24; }
true
cd0692a4076568c45d40c3041aaa63693550395f
Java
muruga26/JAVA
/pin_num_from_given_num.java
UTF-8
1,086
3.546875
4
[]
no_license
import java.util.*; import java.lang.*; import java.io.*; /* Name of the class has to be "Main" only if the class is public. */ class Ideone { public static void main (String[] args) throws java.lang.Exception { // your code goes here int a,b,c,i=0,j,count=0,t,temp; int d[]=new int[10]; Scanner s=new Scanner(System.in); a=s.nextInt(); b=s.nextInt(); c=s.nextInt(); if(a<b&&a<c) { temp=a; } else if(a>b&&b<c) { temp=b; } else{ temp=c; } while(a!=0&&b!=0&&c!=0) { count++; d[i]=a%10; i++; a=a/10; count++; d[i]=b%10; i++; b=b/10; count++; d[i]=c%10; i++; c=c/10; } for(i=0;i<count;i++) { for(j=i;j<count;j++) { if(d[i]>d[j]) { t=d[i]; d[i]=d[j]; d[j]=t; } } } System.out.println(d[count-1]+""+temp); } }
true
b4f2a79f2a6043a8c4377d2d721c054493c5d44f
Java
TanThienDao/ObserverAndDecorator
/ass3/src/com/company/Observable.java
UTF-8
518
2.921875
3
[]
no_license
package com.company; import java.util.ArrayList; import java.util.List; public class Observable { private static List<Observer> observers = new ArrayList<Observer>(); public static void add(Observer observer) { observers.add(observer); } public static void remove(Observer observer) { observers.remove(observer); } public static void notifyObserver(int value) { for (Observer o : observers) { o.update(value); } } }
true
e71d52312f723e1d7630076e066f737a72b1403f
Java
COOLJACKER/Monster-Maze-Game
/src/com/acc/mm/Room.java
UTF-8
577
3.078125
3
[]
no_license
package com.acc.mm; public class Room { private String name; private String description; private Monster monster; public Room(String name, String description, Monster monster) { this.name = name; this.description = description; this.monster = monster; } public boolean isCompleted() { /* if (monster.isALive()) { return false; } else { return true; }*/ return !monster.isALive(); } public String getName() { return name; } public String getDescription() { return description; } public Monster getMonster() { return this.monster; } }
true
87420c99cc1c36bb508e746c0f0a0596d3aa894d
Java
kodvinci/SLogo
/src/behavior/SetPenSize.java
UTF-8
443
2.3125
2
[]
no_license
package behavior; import slogo.Model; /** * Set pen size * * @author Jerry * */ public class SetPenSize extends OneParameterCommand { /** * Number of parameters command takes */ public static final int PARAMETER_NUMBER = 1; @Override public double move (Model model, int turtleNumber) { model.getController().getView().getTurtleArea().editPenWidth((int) getMyValue()); return 0; } }
true
8a9f865a3ba67f959151d0f9221e79f9d9a9ba0f
Java
yokohermanto/bahan
/java/hibernate/chapter12/GroupTest.java
UTF-8
494
2.40625
2
[]
no_license
import java.io.*; import java.util.*; public class GroupTest { public static void main(String [] args) { DAOFactory mysqlFactory = DAOFactory.getDAOFactory(DAOFactory.MYSQL); GroupDAO groupDAO = mysqlFactory.getGroupDAO(); Group sp = new Group("accouting"); ArrayList list = new ArrayList(); list.add(new Story("A Story")); list.add(new Story("And yet another story")); sp.setStories(list); groupDAO.insertGroup(sp); } }
true
3ec5568eca32995e10967b7f8fbc545aaa1ecc9f
Java
anuragsadula/Source-Code
/Code/src/patterns/Alphabetic_Pattern4.java
UTF-8
509
3.453125
3
[]
no_license
package patterns; /* THE OUTPUT OF THIS PROGRAM FOR INPUT N = 5 WILL BE E DE CDE BCDE ABCDE */ import java.util.Scanner; public class Alphabetic_Pattern4{ public static void main(String[] args){ Scanner input = new Scanner(System.in); int n = input.nextInt(); char a = 69,r = 0; for(char i=65;i<65+n;i++){ r = a; for(char k=65;k<=i;k++){ System.out.print(r); r++; } a--; System.out.println(); } } }
true
b9802d59c12a92afbbb0de68811eb67e5fdc231f
Java
Pacsiy/Conference-Center-back-end
/src/main/java/edu/buaa/acmp/dataAccessLayer/domain/Participant.java
UTF-8
733
2.4375
2
[]
no_license
package edu.buaa.acmp.dataAccessLayer.domain; import edu.buaa.acmp.util.JSON; import java.math.BigInteger; public class Participant { public BigInteger id; public BigInteger register_id; public String name; public String sex; public String job; public String contract; public BigInteger is_book; public String note;//备注 public BigInteger state; public JSON toJSON(){ JSON part = new JSON(); part.put("id",id); part.put("name",name); part.put("sex",sex); part.put("job",job); part.put("contract",contract); part.put("is_book",is_book); part.put("note",note); part.put("state",state); return part; } }
true
d967574578f8b03a54f9b2817732f0e961febf79
Java
Jacarte/tiger-graal
/launcher/src/main/java/com/xppcoder/launcher/TigerMain.java
UTF-8
430
2.0625
2
[]
no_license
package com.xppcoder.launcher; import org.graalvm.polyglot.Context; import org.graalvm.polyglot.Source; import java.io.File; import java.io.IOException; public class TigerMain { public static void main(String[] args) throws IOException { //Source source =Source.newBuilder("tiger",new File(args[0])).build(); Context c = Context.newBuilder("tiger").build(); c.eval("tiger", "print(1)"); } }
true
29e7e8e898c874b8bfae72193902068a5f972be6
Java
lawrie/MikePOS
/src/Identify.java
UTF-8
3,342
2.59375
3
[]
no_license
import java.io.File; import org.apache.http.HttpEntity; import org.apache.http.HttpResponse; import org.apache.http.client.HttpClient; import org.apache.http.client.methods.HttpGet; import org.apache.http.client.methods.HttpPost; import org.apache.http.impl.client.DefaultHttpClient; import org.apache.http.util.EntityUtils; import org.apache.http.entity.mime.MultipartEntity; import org.apache.http.entity.mime.content.ContentBody; import org.apache.http.entity.mime.content.FileBody; import org.apache.http.entity.mime.content.StringBody; import org.json.JSONException; import org.json.JSONObject; public class Identify { private static final String key = "N2L6AO7k5tHyBCpReppM0Q"; public static void main(String[] args) throws Exception { System.out.println("Product is " + identify("test.png")); } public static String identify(String fileName) throws Exception { HttpClient client = new DefaultHttpClient(); String token = null; String name = null; HttpPost httpPost = new HttpPost("https://api.cloudsightapi.com/image_requests"); httpPost.setHeader("Authorization", "CloudSight " + key); File file = new File(fileName); MultipartEntity mpEntity = new MultipartEntity(); ContentBody cbFile = new FileBody(file, "image/png"); mpEntity.addPart("image_request[locale", new StringBody("en-US")); mpEntity.addPart("image_request[image]", cbFile); httpPost.setEntity(mpEntity); HttpResponse response = client.execute(httpPost); System.out.println(response.getStatusLine()); HttpEntity entity = response.getEntity(); if (entity != null) { String retSrc = EntityUtils.toString(entity); // parsing JSON try { JSONObject result = new JSONObject(retSrc); System.out.println(result.toString(2)); String status = token = result.getString("status").toString(); System.out.println("Status is " + status); token = result.getString("token").toString(); System.out.println("Token is " + token); } catch (JSONException e) { e.printStackTrace(); } } EntityUtils.consume(entity); if (token != null) { // Wait 6 seconds Thread.sleep(6000); for(int i=0;i<10;i++) { // Try 10 times HttpGet httpget = new HttpGet("https://api.cloudsightapi.com/image_responses/" + token); httpget.setHeader("Authorization", "CloudSight " + key); HttpResponse response2 = client.execute(httpget); HttpEntity entity2 = response2.getEntity(); if (entity2 != null) { String retSrc = EntityUtils.toString(entity2); try { JSONObject result = new JSONObject(retSrc); System.out.println(result.toString(2)); String status = result.getString("status").toString(); System.out.println("Status is " + status); if (status != null && status.equals("not completed")) { Thread.sleep(1000); } else if (status != null && status.equals("completed")) { name = result.getString("name").toString(); break; } else { System.out.println("Identification failed"); break; } } catch (JSONException e) { e.printStackTrace(); } } EntityUtils.consume(entity2); } } return name; } }
true
9c722b715bafbc7facec4d59d8ac70e4814a284e
Java
light-forest1/PhotosCatalogization
/src/main/java/org/openjfx/photoscatalogization/PhotosCatalogization.java
UTF-8
56,373
2.375
2
[]
no_license
package org.openjfx.photoscatalogization; import javafx.application.Application; import javafx.scene.Scene; import javafx.stage.Stage; import javafx.collections.FXCollections; import javafx.collections.ObservableList; import javafx.event.ActionEvent; import javafx.event.EventHandler; import javafx.scene.control.Button; import javafx.scene.control.cell.PropertyValueFactory; import javafx.scene.control.TableView; import javafx.scene.control.TableColumn; import javafx.scene.control.TextArea; import javafx.scene.layout.HBox; import javafx.scene.layout.VBox; import javafx.stage.DirectoryChooser; import java.io.File; import java.io.IOException; import java.util.ArrayList; import java.util.List; import java.util.Set; import java.util.HashSet; import com.drew.imaging.ImageMetadataReader; import com.drew.imaging.ImageProcessingException; import com.drew.metadata.Metadata; import com.drew.metadata.xmp.XmpDirectory; import com.adobe.internal.xmp.XMPException; import com.adobe.internal.xmp.XMPIterator; import com.adobe.internal.xmp.XMPMeta; import com.adobe.internal.xmp.properties.XMPPropertyInfo; import java.util.Iterator; import java.util.stream.Collectors; import java.util.stream.IntStream; import javafx.scene.control.CheckBox; import javafx.scene.control.Label; import javafx.scene.control.Spinner; import javafx.scene.control.SpinnerValueFactory; import javafx.scene.control.TreeItem; import javafx.scene.control.TreeView; /** * JavaFX App */ public class PhotosCatalogization extends Application { public static void main(String[] args) { launch(args); } @Override public void start(Stage primaryStage) { primaryStage.setTitle("Photos Catalogization"); // Layouts VBox vbox = new VBox(); HBox hbox1 = new HBox(); HBox hbox2 = new HBox(); HBox hbox3 = new HBox(); HBox hbox4 = new HBox(); HBox hbox5 = new HBox(); HBox hbox6 = new HBox(); VBox vbox11 = new VBox(); VBox vbox12 = new VBox(); VBox vbox21 = new VBox(); VBox vbox22 = new VBox(); VBox vbox31 = new VBox(); VBox vbox32 = new VBox(); VBox vbox33 = new VBox(); // Controls // Buttons Button addDirBtn = new Button("Add Dir"); Button filterFilesByKeywBtn = new Button("Filter by keywords"); // Labels Label chChoosedInputLvlLbl = new Label("Choosed directory input level:"); Label chDefaultInputLvlLbl = new Label("Default directory input level:"); // Checkboxes CheckBox maxChoosedInputLvlChB = new CheckBox("max. level"); maxChoosedInputLvlChB.setSelected(true); CheckBox maxDefaultInputLvlChB = new CheckBox("max. level"); maxDefaultInputLvlChB.setSelected(true); // Spinners final Spinner<Integer> chChoosedInputLvlSpnr = new Spinner<Integer>(); final int choosedInitValue = 0; SpinnerValueFactory<Integer> choosedValueFactory = new SpinnerValueFactory.IntegerSpinnerValueFactory(0, 100, choosedInitValue); chChoosedInputLvlSpnr.setValueFactory(choosedValueFactory); chChoosedInputLvlSpnr.setDisable(true); final Spinner<Integer> chDefaultInputLvlSpnr = new Spinner<Integer>(); final int defaultInitValue = 0; SpinnerValueFactory<Integer> defaultValueFactory = new SpinnerValueFactory.IntegerSpinnerValueFactory(0, 100, defaultInitValue); chDefaultInputLvlSpnr.setValueFactory(defaultValueFactory); chDefaultInputLvlSpnr.setDisable(true); // Checkboxes events EventHandler<ActionEvent> choosedChBEvent = new EventHandler<ActionEvent>() { public void handle(ActionEvent e) { if (maxChoosedInputLvlChB.isSelected()) { chChoosedInputLvlSpnr.setDisable(true); } else { chChoosedInputLvlSpnr.setDisable(false); } } }; maxChoosedInputLvlChB.setOnAction(choosedChBEvent); EventHandler<ActionEvent> defaultChBEvent = new EventHandler<ActionEvent>() { public void handle(ActionEvent e) { if (maxDefaultInputLvlChB.isSelected()) { chDefaultInputLvlSpnr.setDisable(true); } else { chDefaultInputLvlSpnr.setDisable(false); } } }; maxDefaultInputLvlChB.setOnAction(defaultChBEvent); // Tables // Directories with files Table TableView<PhotosDir> tableDir = addTableDir(); // Files in directory Table TableView<PhotosDirFile> tableDirFiles = addTableDirFiles(); // File's keywords Table TableView<FileKeyword> tableFileKeywords = addTableFileKeywords(); // Found files Table TableView<FoundFile> tableFoundFiles = addTableFoundFiles(); // Found files' keywords Table TableView<FoundFilesKeyword> tableFoundFilesKeywords = addTableFoundFilesKeywords(); // Found files' operations Table TableView<FoundFilesOperation> tableFoundFilesOperations = addTableFoundFilesOperations(); // /Tables // TreeViews TreeItem<String> rootItem = new TreeItem<String>("<Root of Tree>"); rootItem.setExpanded(true); TreeView<String> dirsFilesKeywordsTree = new TreeView<String>(rootItem); // Search Rule Text Area TextArea searchRule = new TextArea(); searchRule.setWrapText(true); searchRule.setPromptText("Enter keywords with AND, OR, NO operands there..."); List<String> imagesFilesExtensions = List.of(".jpg", ".jpeg", ".jpe", ".tif", ".tiff", ".png"); ArrayList<TreeNode<DirectoryInfo>> dirTreesList = new ArrayList<TreeNode<DirectoryInfo>>(); Set<String> allKeywordsSet = new HashSet<String>(); // Add Directory Button Event addDirBtn.setOnAction( new EventHandler<ActionEvent>() { @Override public void handle(final ActionEvent e) { DirectoryChooser addDirChooser = new DirectoryChooser(); File addDirSelected = addDirChooser.showDialog(primaryStage); if (addDirSelected != null) { String addDirPath = addDirSelected.getAbsolutePath(); System.out.println(addDirPath); PhotosDir addedDir = new PhotosDir(2L, addDirPath, "No inserted directories", 0); tableDir.getItems().add(addedDir); if (addDirSelected.isDirectory()) { int level; if (chDefaultInputLvlSpnr.isDisable()) { level = -1; } else { level = chDefaultInputLvlSpnr.getValue(); } System.out.println("level is " + Integer.toString(level)); TreeNode<DirectoryInfo> dirTree = buildDirectoryTree(addDirSelected, imagesFilesExtensions, allKeywordsSet, level); dirTreesList.add(dirTree); printDirectoryTree(dirTree); // 20.06.2020 // This method adds directories and files to TreeView passChildrenDirTree(rootItem, dirTree); // /20.06.2020 getFilesFromDirTree(dirTree, imagesFilesExtensions, allKeywordsSet, tableDirFiles, tableFileKeywords); } } // print files paths and their keywords from all added directories System.out.println("=== *** Information about all files *** ==="); for (TreeNode<DirectoryInfo> treeNode : dirTreesList) { for (TreeNode<DirectoryInfo> node : treeNode) { DirectoryInfo dirInfo = node.data; String dirName = dirInfo.getDirectoryPath(); ArrayList<FileInfo> dirFiles = dirInfo.getFilesList(); // print directory name System.out.println("*** Directory name *** : " + dirName); // Add files paths from directories tree to tableDirFiles for (FileInfo fInfo : dirFiles) { for (String s : imagesFilesExtensions) { if (fInfo.getFilePath().toLowerCase().endsWith(s)) { // print file name and file's keywords System.out.println("*** File path *** : " + fInfo.getFilePath()); Set<String> keywordsSet = fInfo.getFileKeywordsSet(); System.out.println("*** File keywords *** : "); for (String keyword : keywordsSet) { System.out.println(keyword); } } } } } } } } ); // Actions to build filter conditions binary tree by text from text area filterFilesByKeywBtn.setOnAction( new EventHandler<ActionEvent>() { @Override public void handle(final ActionEvent e) { String filterConditionText = searchRule.getText(); System.out.println("*** Start buildFilterConditionTree ***"); TreeNode<FilterConditionElement> filterTree = buildFilterConditionTree(filterConditionText); System.out.println("*** Start printFilterConditionTree ***"); printFilterConditionTree(filterTree); System.out.println("*** Filter condition text *** :"); System.out.println(filterConditionText); System.out.println("*** Directories' trees before filtration ***"); for (TreeNode<DirectoryInfo> dirTree : dirTreesList) { printDirectoryTree(dirTree); } System.out.println("*** Start filterFilesByCondition ***"); ArrayList<TreeNode<DirectoryInfo>> dirTreesFilteredList = filterFilesByCondition(dirTreesList, filterTree); System.out.println("*** Directories' trees after filtration ***"); for (TreeNode<DirectoryInfo> dirTree : dirTreesFilteredList) { printDirectoryTree(dirTree); } } } ); // Add all controls to layouts vbox11.getChildren().addAll(chChoosedInputLvlLbl, maxChoosedInputLvlChB, chChoosedInputLvlSpnr, chDefaultInputLvlLbl, maxDefaultInputLvlChB, chDefaultInputLvlSpnr); hbox1.getChildren().addAll(addDirBtn, filterFilesByKeywBtn); hbox2.getChildren().addAll(tableDir, vbox11, tableDirFiles, vbox12, dirsFilesKeywordsTree); hbox4.getChildren().addAll(tableFileKeywords, vbox21, searchRule, vbox22); hbox6.getChildren().addAll(tableFoundFiles, vbox31, tableFoundFilesKeywords, vbox32, tableFoundFilesOperations, vbox33); vbox.getChildren().addAll(hbox1, hbox2, hbox3, hbox4, hbox5, hbox6); Scene scene = new Scene(vbox, 640, 480); primaryStage.setScene(scene); primaryStage.show(); } private ObservableList<KeywordFromList> getNoAllKeywordsList() { KeywordFromList noAllKeywords = new KeywordFromList(1L, 0, "No all keywords list"); ObservableList<KeywordFromList> list = FXCollections.observableArrayList(noAllKeywords); return list; } private ObservableList<FoundFile> getNoFoundFilesList() { FoundFile noFoundFiles = new FoundFile(1L, "No found files"); ObservableList<FoundFile> list = FXCollections.observableArrayList(noFoundFiles); return list; } private ObservableList<FoundFilesKeyword> getNoFoundFilesKeywordsList() { FoundFilesKeyword noFoundFilesKeywords = new FoundFilesKeyword(1L, "No found file's keywords"); ObservableList<FoundFilesKeyword> list = FXCollections.observableArrayList(noFoundFilesKeywords); return list; } private ObservableList<FoundFilesOperation> getNoFoundFilesOperationsList() { FoundFilesOperation noFoundFilesOperations = new FoundFilesOperation(1L, "No found files' operations"); ObservableList<FoundFilesOperation> list = FXCollections.observableArrayList(noFoundFilesOperations); return list; } private TableView<PhotosDir> addTableDir() { TableView<PhotosDir> tableDir = new TableView<PhotosDir>(); TableColumn<PhotosDir, String> photosDirPathCol = new TableColumn<PhotosDir, String>("Directory Path"); TableColumn<PhotosDir, String> photosDirInsDirsCol = new TableColumn<PhotosDir, String>("Inserted Directories"); TableColumn<PhotosDir, Integer> photosDirInsLevelCol = new TableColumn<PhotosDir, Integer>("Level"); photosDirPathCol.setCellValueFactory(new PropertyValueFactory<>("photosDirPath")); photosDirInsDirsCol.setCellValueFactory(new PropertyValueFactory<>("photosDirInsDirs")); photosDirInsLevelCol.setCellValueFactory(new PropertyValueFactory<>("photosDirInsLevel")); tableDir.getColumns().addAll(photosDirPathCol, photosDirInsDirsCol, photosDirInsLevelCol); return tableDir; } private TableView<PhotosDirFile> addTableDirFiles() { TableView<PhotosDirFile> tableDirFiles = new TableView<PhotosDirFile>(); TableColumn<PhotosDirFile, String> photosDirFileNameCol = new TableColumn<PhotosDirFile, String>("File Name"); photosDirFileNameCol.setCellValueFactory(new PropertyValueFactory<>("photosDirFileName")); tableDirFiles.getColumns().addAll(photosDirFileNameCol); return tableDirFiles; } private TableView<FileKeyword> addTableFileKeywords() { TableView<FileKeyword> tableFileKeywords = new TableView<FileKeyword>(); TableColumn<FileKeyword, String> fileKeywordsCol = new TableColumn<FileKeyword, String>("Keyword"); fileKeywordsCol.setCellValueFactory(new PropertyValueFactory<>("fileKeyword")); tableFileKeywords.getColumns().addAll(fileKeywordsCol); return tableFileKeywords; } private TableView<KeywordFromList> addTableAllKeywordsList() { TableView<KeywordFromList> tableAllKeywordsList = new TableView<KeywordFromList>(); TableColumn<KeywordFromList, Integer> keywordFromListCountCol = new TableColumn<KeywordFromList, Integer>("Count"); TableColumn<KeywordFromList, String> keywordFromListCol = new TableColumn<KeywordFromList, String>("Keyword"); keywordFromListCountCol.setCellValueFactory(new PropertyValueFactory<>("keywordFromListCount")); keywordFromListCol.setCellValueFactory(new PropertyValueFactory<>("keywordFromList")); ObservableList<KeywordFromList> allKeywordsList = getNoAllKeywordsList(); tableAllKeywordsList.setItems(allKeywordsList); tableAllKeywordsList.getColumns().addAll(keywordFromListCountCol, keywordFromListCol); return tableAllKeywordsList; } private TableView<FoundFile> addTableFoundFiles() { TableView<FoundFile> tableFoundFiles = new TableView<FoundFile>(); TableColumn<FoundFile, String> foundFileNameCol = new TableColumn<FoundFile, String>("Found File"); foundFileNameCol.setCellValueFactory(new PropertyValueFactory<>("foundFileName")); ObservableList<FoundFile> foundFiles = getNoFoundFilesList(); tableFoundFiles.setItems(foundFiles); tableFoundFiles.getColumns().addAll(foundFileNameCol); return tableFoundFiles; } private TableView<FoundFilesKeyword> addTableFoundFilesKeywords() { TableView<FoundFilesKeyword> tableFoundFilesKeywords = new TableView<FoundFilesKeyword>(); TableColumn<FoundFilesKeyword, String> foundFilesKeywordCol = new TableColumn<FoundFilesKeyword, String>("Found File's Keyword"); foundFilesKeywordCol.setCellValueFactory(new PropertyValueFactory<>("foundFilesKeyword")); ObservableList<FoundFilesKeyword> foundFilesKeywords = getNoFoundFilesKeywordsList(); tableFoundFilesKeywords.setItems(foundFilesKeywords); tableFoundFilesKeywords.getColumns().addAll(foundFilesKeywordCol); return tableFoundFilesKeywords; } private TableView<FoundFilesOperation> addTableFoundFilesOperations() { TableView<FoundFilesOperation> tableFoundFilesOperations = new TableView<FoundFilesOperation>(); TableColumn<FoundFilesOperation, String> foundFilesOperationCol = new TableColumn<FoundFilesOperation, String>("Found files' operation"); foundFilesOperationCol.setCellValueFactory(new PropertyValueFactory<>("foundFilesOperation")); ObservableList<FoundFilesOperation> foundFilesOperations = getNoFoundFilesOperationsList(); tableFoundFilesOperations.setItems(foundFilesOperations); tableFoundFilesOperations.getColumns().addAll(foundFilesOperationCol); return tableFoundFilesOperations; } // 20.06.2020 private void passChildrenDirTree(TreeItem<String> rootItem, TreeNode<DirectoryInfo> dirTree) { TreeItem<String> dirItem = new TreeItem<String>(dirTree.data.getDirectoryPath()); dirItem.setExpanded(true); rootItem.getChildren().add(dirItem); if (dirTree.children.size() > 0) { for (TreeNode<DirectoryInfo> childDirTree : dirTree.children) { passChildrenDirTree(dirItem, childDirTree); } } for (FileInfo fInfo : dirTree.data.getFilesList()) { TreeItem<String> fileItem = new TreeItem<String>(fInfo.getFilePath()); fileItem.setExpanded(true); dirItem.getChildren().add(fileItem); for (String keywordStr : fInfo.getFileKeywordsSet()) { TreeItem<String> keywordItem = new TreeItem<String>(keywordStr); fileItem.getChildren().add(keywordItem); } } } // /20.06.2020 // Methods to build directory tree public static TreeNode<DirectoryInfo> buildDirectoryTree(File folder, List<String> imagesFilesExtensions, Set<String> allKeywordsSet, int level) { if (!folder.isDirectory()) { throw new IllegalArgumentException("folder is not a Directory"); } int indent = 0; // input directories deapth TreeNode<DirectoryInfo> node = buildDirectoryTree(folder, imagesFilesExtensions, allKeywordsSet, indent, level); return node; } private static TreeNode<DirectoryInfo> buildDirectoryTree(File folder, List<String> imagesFilesExtensions, Set<String> allKeywordsSet, int indent, int level) { // get directory info DirectoryInfo dirInfoRoot = getDirectoryInfo(folder, imagesFilesExtensions, allKeywordsSet); TreeNode<DirectoryInfo> root = new TreeNode<DirectoryInfo>(dirInfoRoot); if (level != 0) { for (File file : folder.listFiles()) { if (file.isDirectory()) { buildDirectoryTree(file, imagesFilesExtensions, allKeywordsSet, indent + 1, level, root); } } } return root; } private static void buildDirectoryTree(File folder, List<String> imagesFilesExtensions, Set<String> allKeywordsSet, int indent, int level, TreeNode<DirectoryInfo> node) { // get directory info DirectoryInfo dirInfoNodeNew = getDirectoryInfo(folder, imagesFilesExtensions, allKeywordsSet); TreeNode<DirectoryInfo> nodeNew = node.addChild(dirInfoNodeNew); if (indent < level || level == -1) { for (File file : folder.listFiles()) { if (file.isDirectory()) { buildDirectoryTree(file, imagesFilesExtensions, allKeywordsSet, indent + 1, level, nodeNew); } } } } // Create indent to print tree to console output private static String createIndent(int depth) { StringBuilder sb = new StringBuilder(); for (int i = 0; i < depth; i++) { sb.append(' '); } return sb.toString(); } private static DirectoryInfo getDirectoryInfo(File folder, List<String> imagesFilesExtensions, Set<String> allKeywordsSet) { ArrayList<FileInfo> fileInfoNode = new ArrayList<FileInfo>(); for (File f : folder.listFiles()) { if (!f.isDirectory()) { String fileName = new String(f.getAbsolutePath()); Metadata metadata = new Metadata(); Set<String> fKeywSet = new HashSet(); // !!! to add xmp metadata for (String s : imagesFilesExtensions) { if (fileName.toLowerCase().endsWith(s)) { if (f.exists()) { try { metadata = ImageMetadataReader.readMetadata(f); for (XmpDirectory xmpDirectory : metadata.getDirectoriesOfType(XmpDirectory.class)) { XMPMeta xmpMeta = xmpDirectory.getXMPMeta(); XMPIterator itr = xmpMeta.iterator(); while (itr.hasNext()) { XMPPropertyInfo property = (XMPPropertyInfo) itr.next(); if (property.getPath() != null) { if (property.getPath().toLowerCase().contains("subject") && property.getValue().length() > 0) { System.out.println(property.getValue()); fKeywSet.add(property.getValue()); allKeywordsSet.add(property.getValue()); } } } } } catch (ImageProcessingException ex) { ex.printStackTrace(); } catch (IOException ex) { ex.printStackTrace(); } catch (XMPException ex) { ex.printStackTrace(); } } } } FileInfo fInfo = new FileInfo(f.getPath(), metadata, fKeywSet); fileInfoNode.add(fInfo); } } DirectoryInfo dirInfoNode = new DirectoryInfo(folder.getPath(), fileInfoNode); return dirInfoNode; } public static void printDirectoryTree(TreeNode<DirectoryInfo> dirTree) { for (TreeNode<DirectoryInfo> node : dirTree) { String indent = createIndent(node.getLevel()); DirectoryInfo dirInfo = node.data; String dirName = dirInfo.getDirectoryPath(); ArrayList<FileInfo> dirFiles = dirInfo.getFilesList(); System.out.println(indent + dirName); printFilesListFromDir(dirFiles, indent, node.getLevel()); } } private static void printFilesListFromDir(ArrayList<FileInfo> dirFiles, String indent, int level) { for (FileInfo fInfo : dirFiles) { System.out.println(indent + "* " + fInfo.getFilePath()); // Print file's keywords for (String keyword : fInfo.getFileKeywordsSet()) { System.out.println(indent + "** " + keyword); } } } public void getFilesFromDirTree(TreeNode<DirectoryInfo> dirTree, List<String> imagesFilesExtensions, Set<String> allKeywordsSet, TableView<PhotosDirFile> tableDirFiles, TableView<FileKeyword> tableFileKeywords) { for (TreeNode<DirectoryInfo> node : dirTree) { DirectoryInfo dirInfo = node.data; String dirName = dirInfo.getDirectoryPath(); ArrayList<FileInfo> dirFiles = dirInfo.getFilesList(); // Add files paths from directories tree to tableDirFiles for (FileInfo fInfo : dirFiles) { for (String s : imagesFilesExtensions) { if (fInfo.getFilePath().toLowerCase().endsWith(s)) { PhotosDirFile fileRow = new PhotosDirFile(1L, fInfo.getFilePath()); tableDirFiles.getItems().add(fileRow); } } } } // Add keywords from 'all keywords set' to tableFileKeywords for (String keywFromAllKeywSet : allKeywordsSet) { FileKeyword fileKeywRow = new FileKeyword(1L, keywFromAllKeywSet); tableFileKeywords.getItems().add(fileKeywRow); } } public static TreeNode<FilterConditionElement> buildFilterConditionTree(String filterConditionText) { ArrayList<FilterConditionElement> originalConditionArray = new ArrayList<FilterConditionElement>(); char[] conditionCharArray = filterConditionText.toCharArray(); String operatorStr = ""; String keywordStr = ""; boolean isOperatorBrackets = false; for (int i = 0; i < conditionCharArray.length; i++) { if (conditionCharArray[i] == '[') { FilterConditionElement opSqBrEl = new FilterConditionElement("[", false, false, true); originalConditionArray.add(opSqBrEl); } else if (conditionCharArray[i] == ']') { if (!keywordStr.isEmpty()) { FilterConditionElement keywordEl = new FilterConditionElement(keywordStr, false, false, false); keywordStr = ""; originalConditionArray.add(keywordEl); } FilterConditionElement clSqBrEl = new FilterConditionElement("]", false, false, true); originalConditionArray.add(clSqBrEl); } else if (conditionCharArray[i] == '<') { if (!keywordStr.isEmpty()) { FilterConditionElement keywordEl = new FilterConditionElement(keywordStr, false, false, false); keywordStr = ""; originalConditionArray.add(keywordEl); } isOperatorBrackets = true; } else if (isOperatorBrackets) { if (conditionCharArray[i] == '>') { isOperatorBrackets = false; FilterConditionElement operatorEl = new FilterConditionElement(operatorStr, false, true, false); operatorStr = ""; originalConditionArray.add(operatorEl); } else { operatorStr = operatorStr + conditionCharArray[i]; } } else { keywordStr = keywordStr + conditionCharArray[i]; if (i == conditionCharArray.length - 1) { FilterConditionElement keywordEl = new FilterConditionElement(keywordStr, false, false, false); keywordStr = ""; originalConditionArray.add(keywordEl); } } } System.out.println("*** String splitted to elements: ***"); for (FilterConditionElement fCElement : originalConditionArray) { System.out.println(fCElement.getFilterConditionStr()); System.out.println("<" + fCElement.getIsOperator() + ">"); System.out.println("[] " + fCElement.getIsSqBracket()); System.out.println("no " + fCElement.getNoProperty()); System.out.println("***"); } System.out.println("*** /String splitted to elements: ***"); TreeNode<FilterConditionElement> node = null; System.out.println("*** Start buildFilterConditionTreePrivate ***"); TreeNode<FilterConditionElement> nodeReturned = buildFilterConditionTreePrivate(originalConditionArray, node, true); return nodeReturned; } private static TreeNode<FilterConditionElement> buildFilterConditionTreePrivate(ArrayList<FilterConditionElement> conditionArray, TreeNode<FilterConditionElement> root, boolean toMakeRoot) { // Define [] brackets position and write it to ArrayList<Integer> int openingSqBrCount = 0; int closingSqBrCount = 0; ArrayList<Integer> openingSqBrNums = new ArrayList<Integer>(); ArrayList<Integer> closingSqBrNums = new ArrayList<Integer>(); defineBrackets(conditionArray, openingSqBrCount, closingSqBrCount, openingSqBrNums, closingSqBrNums); System.out.println("***"); System.out.println("toMakeRoot = " + toMakeRoot); System.out.println("openingSqBrNums size = " + openingSqBrNums.size()); for (int i = 0; i < openingSqBrNums.size(); i++) { System.out.println("[ = " + openingSqBrNums.get(i) + ", ] = " + closingSqBrNums.get(i)); } System.out.println("* Condition elements *"); for (FilterConditionElement fCElement : conditionArray) { System.out.println(fCElement.getFilterConditionStr()); } System.out.println("* /Condition elements *"); boolean isNoProperty = false; FilterConditionElement orOperator = new FilterConditionElement("or", false, true, false); FilterConditionElement andOperator = new FilterConditionElement("and", false, true, false); // Remove [] brackets removeSqBrackets(conditionArray, isNoProperty, openingSqBrCount, closingSqBrCount, openingSqBrNums, closingSqBrNums); System.out.println("After removing brackets"); System.out.println("openingSqBrNums size = " + openingSqBrNums.size()); for (int i = 0; i < openingSqBrNums.size(); i++) { System.out.println("[ = " + openingSqBrNums.get(i) + ", ] = " + closingSqBrNums.get(i)); } System.out.println("* Condition elements *"); for (FilterConditionElement fCElement : conditionArray) { System.out.println(fCElement.getFilterConditionStr()); } System.out.println("* /Condition elements *"); // if (ArrayList<FilterConditionElement> contains "or" or "and" // binary operator NOT in defined [] brackets) // Make a list and a set of numbers of condition's elements List<Integer> conditionArrayNumsRange = IntStream.rangeClosed(0, conditionArray.size() - 1).boxed().collect(Collectors.toList()); Set<Integer> conditionArrayNumsSet = new HashSet<Integer>(conditionArrayNumsRange); // Make set only with numbers of elements which AREN'T positioned in defined squared brackets for (int i = 0; i < openingSqBrNums.size(); i++) { List<Integer> inSqBracketsNumsRange = IntStream.rangeClosed(openingSqBrNums.get(i), closingSqBrNums.get(i)).boxed().collect(Collectors.toList()); Set<Integer> inSqBracketsNumsSet = new HashSet<Integer>(inSqBracketsNumsRange); conditionArrayNumsSet.removeAll(inSqBracketsNumsSet); } System.out.println("* Set of numbers which aren't positioned in def. sq. br. *"); System.out.println(conditionArrayNumsSet); System.out.println("* /Set of numbers which aren't positioned in def. sq. br. *"); // Make ArrayList<FilterConditionElement> of condition elements which AREN'T positioned in defined squared brackets ArrayList<FilterConditionElement> conditionElsNotInSqBr = new ArrayList<FilterConditionElement>(); for (Integer elNum : new ArrayList<Integer>(conditionArrayNumsSet)) { conditionElsNotInSqBr.add(conditionArray.get(elNum)); } System.out.println("* Array of elements which aren't positioned in def. sq. br. *"); for (FilterConditionElement fCElement : conditionElsNotInSqBr) { System.out.println(fCElement.getFilterConditionStr()); } System.out.println("* /Array of elements which aren't positioned in def. sq. br. *"); // Walk to elements from conditionArrayNumsSet only BooleanOrAnd isOrOperator = new BooleanOrAnd(false); BooleanOrAnd isAndOperator = new BooleanOrAnd(false); isOrAnd(conditionElsNotInSqBr, isOrOperator, isAndOperator); System.out.println("* isOrAnd *"); System.out.println(isOrOperator.getBooleanOrAnd()); System.out.println(isAndOperator.getBooleanOrAnd()); System.out.println("* /isOrAnd *"); if (isOrOperator.getBooleanOrAnd()) { System.out.println("* conditionElsNotInSqBr contains or *"); for (Integer elNum : new ArrayList<Integer>(conditionArrayNumsSet)) { if (conditionArray.get(elNum).getIsOperator() && conditionArray.get(elNum).getFilterConditionStr().equals("or")) { System.out.println("* or num = " + elNum + " *"); ArrayList<FilterConditionElement> subArrayBeforeOr = new ArrayList<FilterConditionElement>(conditionArray.subList(0, elNum)); ArrayList<FilterConditionElement> subArrayAfterOr = new ArrayList<FilterConditionElement>(conditionArray.subList(elNum + 1, conditionArray.size())); System.out.println("* Array of elements before or *"); for (FilterConditionElement fCElement : subArrayBeforeOr) { System.out.println(fCElement.getFilterConditionStr()); } System.out.println("* /Array of elements before or *"); System.out.println("* Array of elements after or *"); for (FilterConditionElement fCElement : subArrayAfterOr) { System.out.println(fCElement.getFilterConditionStr()); } System.out.println("* /Array of elements after or *"); System.out.println("isNoProperty = " + isNoProperty); orOperator.setNoProperty(isNoProperty); System.out.println("toMakeRoot = " + toMakeRoot); if (toMakeRoot) { root = new TreeNode<FilterConditionElement>(orOperator); buildFilterConditionTreePrivate(subArrayBeforeOr, root, false); buildFilterConditionTreePrivate(subArrayAfterOr, root, false); } else { TreeNode<FilterConditionElement> node = root.addChild(orOperator); buildFilterConditionTreePrivate(subArrayBeforeOr, node, false); buildFilterConditionTreePrivate(subArrayAfterOr, node, false); } break; } } } else if (isAndOperator.getBooleanOrAnd()) { System.out.println("* conditionElsNotInSqBr contains and *"); for (Integer elNum : new ArrayList<Integer>(conditionArrayNumsSet)) { if (conditionArray.get(elNum).getIsOperator() && conditionArray.get(elNum).getFilterConditionStr().equals("and")) { System.out.println("* and num = " + elNum + " *"); ArrayList<FilterConditionElement> subArrayBeforeAnd = new ArrayList<FilterConditionElement>(conditionArray.subList(0, elNum)); ArrayList<FilterConditionElement> subArrayAfterAnd = new ArrayList<FilterConditionElement>(conditionArray.subList(elNum + 1, conditionArray.size())); System.out.println("* Array of elements before and *"); for (FilterConditionElement fCElement : subArrayBeforeAnd) { System.out.println(fCElement.getFilterConditionStr()); } System.out.println("* /Array of elements before and *"); System.out.println("* Array of elements after and *"); for (FilterConditionElement fCElement : subArrayAfterAnd) { System.out.println(fCElement.getFilterConditionStr()); } System.out.println("* /Array of elements after and *"); System.out.println("isNoProperty = " + isNoProperty); andOperator.setNoProperty(isNoProperty); System.out.println("toMakeRoot = " + toMakeRoot); if (toMakeRoot) { root = new TreeNode<FilterConditionElement>(andOperator); buildFilterConditionTreePrivate(subArrayBeforeAnd, root, false); buildFilterConditionTreePrivate(subArrayAfterAnd, root, false); } else { TreeNode<FilterConditionElement> node = root.addChild(andOperator); buildFilterConditionTreePrivate(subArrayBeforeAnd, node, false); buildFilterConditionTreePrivate(subArrayAfterAnd, node, false); } break; } } } else { if (conditionArray.size() == 2 && conditionArray.get(0).getIsOperator() && conditionArray.get(0).getFilterConditionStr().equals("no")) { System.out.println("* conditionArray size = 2, first element = no *"); FilterConditionElement keywordElement = conditionArray.get(conditionArray.size() - 1); System.out.println("* keywordElement = " + keywordElement.getFilterConditionStr() + " *"); System.out.println("isNoProperty = " + isNoProperty); keywordElement.setNoProperty(!isNoProperty); System.out.println("toMakeRoot = " + toMakeRoot); if (toMakeRoot) { root = new TreeNode<FilterConditionElement>(keywordElement); } else { root.addChild(keywordElement); } } else { System.out.println("* else *"); FilterConditionElement keywordElement = conditionArray.get(0); System.out.println("* keywordElement = " + keywordElement.getFilterConditionStr() + " *"); System.out.println("isNoProperty = " + isNoProperty); keywordElement.setNoProperty(isNoProperty); System.out.println("toMakeRoot = " + toMakeRoot); if (toMakeRoot) { root = new TreeNode<FilterConditionElement>(keywordElement); } else { root.addChild(keywordElement); } } } return root; } private static void removeSqBrackets (ArrayList<FilterConditionElement> conditionArray, boolean isNoProperty, int openingSqBrCount, int closingSqBrCount, ArrayList<Integer> openingSqBrNums, ArrayList<Integer> closingSqBrNums) { if ((openingSqBrNums.size() == 1 && openingSqBrNums.get(0) == 0 && closingSqBrNums.get(0) == conditionArray.size() - 1) || (openingSqBrNums.size() == 1 && openingSqBrNums.get(0) == 1 && closingSqBrNums.get(0) == conditionArray.size() - 1 && conditionArray.get(0).getIsOperator() && conditionArray.get(0).getFilterConditionStr().equals("no"))) { while ((openingSqBrNums.size() == 1 && openingSqBrNums.get(0) == 0 && closingSqBrNums.get(0) == conditionArray.size() - 1) || (openingSqBrNums.size() == 1 && openingSqBrNums.get(0) == 1 && closingSqBrNums.get(0) == conditionArray.size() - 1 && conditionArray.get(0).getIsOperator() && conditionArray.get(0).getFilterConditionStr().equals("no"))) { if (openingSqBrNums.size() == 1 && openingSqBrNums.get(0) == 0 && closingSqBrNums.get(0) == conditionArray.size() - 1) { conditionArray.remove(0); conditionArray.remove(conditionArray.size() - 1); } else if (openingSqBrNums.size() == 1 && openingSqBrNums.get(0) == 1 && closingSqBrNums.get(0) == conditionArray.size() - 1 && conditionArray.get(0).getIsOperator() && conditionArray.get(0).getFilterConditionStr().equals("no")) { conditionArray.remove(1); conditionArray.remove(conditionArray.size() - 1); isNoProperty = !isNoProperty; conditionArray.remove(0); } defineBrackets(conditionArray, openingSqBrCount, closingSqBrCount, openingSqBrNums, closingSqBrNums); } } } private static void isOrAnd(ArrayList<FilterConditionElement> conditionArray, BooleanOrAnd isOrOperator, BooleanOrAnd isAndOperator) { for (FilterConditionElement fCElement : conditionArray) { if (fCElement.getIsOperator() && fCElement.getFilterConditionStr().equals("or")) { isOrOperator.setBooleanOrAnd(true); break; } } if (!isOrOperator.getBooleanOrAnd()) { for (FilterConditionElement fCElement : conditionArray) { if (fCElement.getIsOperator() && fCElement.getFilterConditionStr().equals("and")) { isAndOperator.setBooleanOrAnd(true); break; } } } } // 06.12.2019 public static void printFilterConditionTree(TreeNode<FilterConditionElement> filterTree) { for (TreeNode<FilterConditionElement> node : filterTree) { String indent = createIndent(node.getLevel()); FilterConditionElement filterInfo = node.data; String filterStr = filterInfo.getFilterConditionStr(); boolean noProperty = filterInfo.getNoProperty(); boolean isOperator = filterInfo.getIsOperator(); if (isOperator && noProperty) { System.out.println(indent + "<no>" + "<" + filterStr + ">"); } else if (isOperator && !noProperty) { System.out.println(indent + "<" + filterStr + ">"); } else if (!isOperator && noProperty) { System.out.println(indent + "<no>" + filterStr); } else if (!isOperator && !noProperty) { System.out.println(indent + filterStr); } } } // 04.12.2019 // Works correctly public static void defineBrackets(ArrayList<FilterConditionElement> conditionArray, int openingSqBrCount, int closingSqBrCount, ArrayList<Integer> openingSqBrNums, ArrayList<Integer> closingSqBrNums) { openingSqBrCount = 0; closingSqBrCount = 0; openingSqBrNums.clear(); closingSqBrNums.clear(); for (int i = 0; i < conditionArray.size(); i++) { if (openingSqBrCount == 0 && conditionArray.get(i).getIsSqBracket() && conditionArray.get(i).getFilterConditionStr() == "[") { openingSqBrNums.add(i); openingSqBrCount++; } else if (openingSqBrCount > 0 && openingSqBrCount == closingSqBrCount + 1 && conditionArray.get(i).getIsSqBracket() && conditionArray.get(i).getFilterConditionStr() == "]") { closingSqBrNums.add(i); openingSqBrCount = 0; closingSqBrCount = 0; } else if (openingSqBrCount > 0 && conditionArray.get(i).getIsSqBracket() && conditionArray.get(i).getFilterConditionStr() == "[") { openingSqBrCount++; } else if (openingSqBrCount > 0 && openingSqBrCount > closingSqBrCount + 1 && conditionArray.get(i).getIsSqBracket() && conditionArray.get(i).getFilterConditionStr() == "]") { closingSqBrCount++; } } } public static ArrayList<TreeNode<DirectoryInfo>> filterFilesByCondition(ArrayList<TreeNode<DirectoryInfo>> dirTreesList, TreeNode<FilterConditionElement> filterTree) { // Create new dirTreesList ArrayList<TreeNode<DirectoryInfo>> toReturnDirTreesList = new ArrayList<TreeNode<DirectoryInfo>>(); // If root of filterTree exists if (filterTree != null) { if (filterTree.data.getIsOperator()) { // System.out.println("*** root of filterTree is operator ***"); List<TreeNode<FilterConditionElement>> childrenList = null; childrenList = filterTree.children; // If children nodes of root node exists, build ArrayList // of trees of directories for left and right children nodes if (childrenList != null) { ArrayList<TreeNode<DirectoryInfo>> leftDirTreesList = filterFilesByCondition(dirTreesList, childrenList.get(0)); ArrayList<TreeNode<DirectoryInfo>> rightDirTreesList = filterFilesByCondition(dirTreesList, childrenList.get(childrenList.size() - 1)); for (int i = 0; i < leftDirTreesList.size(); i++) { // Pass directories trees recursively passDirTrees(leftDirTreesList.get(i), rightDirTreesList.get(i), dirTreesList.get(i), filterTree); } // Copy rightDirTreesList to toReturnDirTreesList toReturnDirTreesList = (ArrayList<TreeNode<DirectoryInfo>>)rightDirTreesList.clone(); } // If root of filterTree is keyword } else { for (TreeNode<DirectoryInfo> dirTreesListTree : dirTreesList) { toReturnDirTreesList.add(copyDirTree(dirTreesListTree)); } for (int i = 0; i < toReturnDirTreesList.size(); i++) { // Pass directories trees recursively if a keyword in condition passDirTreesIfKeyword(toReturnDirTreesList.get(i), filterTree); } } } return toReturnDirTreesList; } public static void passDirTrees(TreeNode<DirectoryInfo> leftDirTree, TreeNode<DirectoryInfo> rightDirTree, TreeNode<DirectoryInfo> origDirTree, TreeNode<FilterConditionElement> rootNode) { ArrayList<FileInfo> leftDirTreeFileList = leftDirTree.data.getFilesList(); ArrayList<FileInfo> rightDirTreeFileList = rightDirTree.data.getFilesList(); ArrayList<FileInfo> origDirTreeFileList = origDirTree.data.getFilesList(); // Get lists of file's paths for both file's lists Set<String> leftDirTreeFilePathSet = new HashSet<String>(); Set<String> rightDirTreeFilePathSet = new HashSet<String>(); for (FileInfo fInfo : leftDirTreeFileList) { leftDirTreeFilePathSet.add(fInfo.getFilePath()); } for (FileInfo fInfo : rightDirTreeFileList) { rightDirTreeFilePathSet.add(fInfo.getFilePath()); } Set<String> rightCopiedDirTreeFilePathSet = new HashSet<String>(rightDirTreeFilePathSet); // If 'or', get union set if (rootNode.data.getFilterConditionStr().equals("or")) { // System.out.println("*** If or ***"); rightDirTreeFilePathSet.addAll(leftDirTreeFilePathSet); // - If 'no' attribute is true, get list of file's paths // for original file's list and then invert set (union) // - If 'no', remove items from 'right' FileInfo list and // add FileInfo items from original list there // if their file's paths are in set, if (rootNode.data.getNoProperty()) { // System.out.println("*** If no ***"); Set<String> origDirTreeFilePathSet = new HashSet<String>(); for (FileInfo fInfo : origDirTreeFileList) { origDirTreeFilePathSet.add(fInfo.getFilePath()); } origDirTreeFilePathSet.removeAll(rightDirTreeFilePathSet); rightDirTreeFileList.clear(); for (FileInfo fInfo : origDirTreeFileList) { if (origDirTreeFilePathSet.contains(fInfo.getFilePath())) { rightDirTreeFileList.add(fInfo); } } } // - else get FileInfo items from 'left' list and add them // to 'right' list if file's paths of these FileInfo items // are in set (union) and not in 'right' path's list else { // System.out.println("*** If yes ***"); for (FileInfo fInfo : leftDirTreeFileList) { if (rightDirTreeFilePathSet.contains(fInfo.getFilePath()) && !rightCopiedDirTreeFilePathSet.contains(fInfo.getFilePath())) { rightDirTreeFileList.add(fInfo); } } } } // else (if 'and') else { // System.out.println("*** If and ***"); // Intersection rightDirTreeFilePathSet.retainAll(leftDirTreeFilePathSet); if (rootNode.data.getNoProperty()) { // System.out.println("*** If no ***"); rightDirTreeFileList.clear(); for (FileInfo fInfo : origDirTreeFileList) { if (!rightDirTreeFilePathSet.contains(fInfo.getFilePath())) { rightDirTreeFileList.add(fInfo); } } } else { // System.out.println("*** If yes ***"); Iterator<FileInfo> rightDirTreeFileIter = rightDirTreeFileList.iterator(); while (rightDirTreeFileIter.hasNext()) { FileInfo fInfo = rightDirTreeFileIter.next(); if (!rightDirTreeFilePathSet.contains(fInfo.getFilePath())) { rightDirTreeFileIter.remove(); } } } } // Write 'right' list to rightDirTree.data rightDirTree.data.setFilesList(rightDirTreeFileList); // Pass directories trees recursively for (int i = 0; i < rightDirTree.children.size(); i++) { passDirTrees(leftDirTree.children.get(i), rightDirTree.children.get(i), origDirTree.children.get(i), rootNode); } } public static void passDirTreesIfKeyword(TreeNode<DirectoryInfo> dirTree, TreeNode<FilterConditionElement> rootNode) { ArrayList<FileInfo> dirTreeFileList = dirTree.data.getFilesList(); System.out.println("*** passDirTreesIfKeyword ***"); System.out.println("*** Print dirTree ***"); printDirectoryTree(dirTree); System.out.println("*** Print filter tree ***"); printFilterConditionTree(rootNode); System.out.println("*** /Print filter tree ***"); Iterator<FileInfo> dirTreeFileIter = dirTreeFileList.iterator(); while (dirTreeFileIter.hasNext()) { FileInfo fInfo = dirTreeFileIter.next(); Boolean fContKeyw = fInfo.getFileKeywordsSet().contains(rootNode.data.getFilterConditionStr()); if (rootNode.data.getNoProperty() == false && fContKeyw == false) dirTreeFileIter.remove(); else if (rootNode.data.getNoProperty() && fContKeyw) dirTreeFileIter.remove(); } System.out.println("*** Write dirTreeFileList to dirTree.data ***"); // Write dirTreeFileList to dirTree.data dirTree.data.setFilesList(dirTreeFileList); System.out.println("*** Print dirTree.data ***"); System.out.println(dirTree.data.getDirectoryPath()); for (FileInfo fInfo : dirTree.data.getFilesList()) { System.out.println("<file> " + fInfo.getFilePath()); } System.out.println("*** /Print dirTree.data ***"); // Pass directories' trees recursively for (int i = 0; i < dirTree.children.size(); i++) { passDirTreesIfKeyword(dirTree.children.get(i), rootNode); } } public static TreeNode<DirectoryInfo> copyDirTree (TreeNode<DirectoryInfo> dirTree) { String dirPath = new String(dirTree.data.getDirectoryPath()); ArrayList<FileInfo> dirFilesList = new ArrayList<>(); for (FileInfo fInfo : dirTree.data.getFilesList()) { FileInfo newFileInfo = new FileInfo(fInfo.getFilePath(), fInfo.getFileMetadata(), fInfo.getFileKeywordsSet()); dirFilesList.add(newFileInfo); } DirectoryInfo dirInfo = new DirectoryInfo(dirPath, dirFilesList); TreeNode<DirectoryInfo> copiedDirTree = new TreeNode<DirectoryInfo>(dirInfo); for (TreeNode<DirectoryInfo> childDirTree : dirTree.children) { copyDirTreePrivate(childDirTree, copiedDirTree); } return copiedDirTree; } private static void copyDirTreePrivate (TreeNode<DirectoryInfo> childDirTree, TreeNode<DirectoryInfo> copiedDirTree) { String dirPath = new String(childDirTree.data.getDirectoryPath()); ArrayList<FileInfo> dirFilesList = new ArrayList<>(); for (FileInfo fInfo : childDirTree.data.getFilesList()) { FileInfo newFileInfo = new FileInfo(fInfo.getFilePath(), fInfo.getFileMetadata(), fInfo.getFileKeywordsSet()); dirFilesList.add(newFileInfo); } DirectoryInfo dirInfo = new DirectoryInfo(dirPath, dirFilesList); TreeNode<DirectoryInfo> childCopiedDirTree = copiedDirTree.addChild(dirInfo); for (TreeNode<DirectoryInfo> childChildDirTree : childDirTree.children) { copyDirTreePrivate(childChildDirTree, childCopiedDirTree); } } }
true
1b11531f61f4d615eb920fc4e3364b2a229a6b62
Java
chensong1995/Library-Manager
/src/databaseConnection/DBHelper.java
UTF-8
14,742
2.46875
2
[]
no_license
package databaseConnection; import java.math.BigInteger; import java.security.MessageDigest; import java.sql.Connection; import java.sql.DriverManager; import java.sql.PreparedStatement; import java.sql.ResultSet; import java.sql.SQLException; import java.text.SimpleDateFormat; import java.util.ArrayList; import java.util.Date; import java.util.List; public class DBHelper { public static final String url = "jdbc:mysql://120.27.121.163:3306/library?useUnicode=true&characterEncoding=UTF-8"; public static final String name = "com.mysql.jdbc.Driver"; public static final String user = "test"; public static final String password = "password"; public Connection conn = null; public DBHelper() { try { Class.forName(name); conn = DriverManager.getConnection(url, user, password); } catch (Exception e) { e.printStackTrace(); } } public void closeConnection() { try { this.conn.close(); } catch (SQLException e) { e.printStackTrace(); } } public boolean isConnectionEstablished() { try { return !conn.isClosed(); } catch (SQLException e) { e.printStackTrace(); return false; } } private String getMD5(String str) { try { MessageDigest md = MessageDigest.getInstance("MD5"); md.update(str.getBytes()); return new BigInteger(1, md.digest()).toString(16); } catch (Exception e) { e.printStackTrace(); return ""; } } public String login(String username, String password) { String status = "fail"; if (isConnectionEstablished()) { try { String sql = "SELECT user_type " + "FROM users " + "WHERE id = ? " + "AND password = ? " + "AND status = 'valid';"; PreparedStatement ps = conn.prepareStatement(sql); ps.setString(1, username); ps.setString(2, getMD5(password)); ResultSet result = ps.executeQuery(); if (result.next()) { // login success status = result.getString(1); } result.close(); ps.close(); } catch (SQLException e) { e.printStackTrace(); } } return status; } public List<BookRecord> searchBook(String keyword) { ArrayList<BookRecord> records = new ArrayList<BookRecord>(); if (isConnectionEstablished()) { try { String sql = "SELECT * " + "FROM books " + "WHERE isbn = ? " + "OR title LIKE ? " + "OR type LIKE ? " + "OR press LIKE ? " + "OR author LIKE ?;"; PreparedStatement ps = conn.prepareStatement(sql); ps.setString(1, keyword); ps.setString(2, "%" + keyword + "%"); ps.setString(3, "%" + keyword + "%"); ps.setString(4, "%" + keyword + "%"); ps.setString(5, "%" + keyword + "%"); ResultSet rs = ps.executeQuery(); while (rs.next()) { records.add(new BookRecord( rs.getInt(1), // id rs.getString(2), // isbn rs.getString(3), // title rs.getString(4), // type rs.getInt(5), // price rs.getString(6), // press rs.getString(7), // author rs.getString(8) // date )); } rs.close(); ps.close(); } catch (SQLException e) { e.printStackTrace(); } } return records; } public boolean isBookBorrowed(int id) { if (isConnectionEstablished()) { try { String sql = "SELECT 1 " + "FROM books, borrowings " + "WHERE books.id = borrowings.bid " + "AND books.id = ? " + "AND borrowings.end_date is null;"; PreparedStatement ps = conn.prepareStatement(sql); ps.setInt(1, id); ResultSet rs = ps.executeQuery(); if (rs.next()) { rs.close(); ps.close(); return true; } rs.close(); ps.close(); } catch (SQLException e) { e.printStackTrace(); } } return false; } public boolean addBook(BookRecord book) { if (isConnectionEstablished()) { try { String sql = "INSERT INTO books " + "VALUES (null, ?, ?, ?, ?, ?, ?, ?);"; PreparedStatement ps = conn.prepareStatement(sql); ps.setString(1, book.getIsbn()); ps.setString(2, book.getTitle()); ps.setString(3, book.getType()); ps.setInt(4, book.getPrice()); ps.setString(5, book.getPress()); ps.setString(6, book.getAuthor()); ps.setString(7, book.getDate()); if (ps.executeUpdate() != 0) { // success ps.close(); return true; } ps.close(); } catch (SQLException e) { e.printStackTrace(); } } return false; } public boolean modifyBook(BookRecord book) { if (isConnectionEstablished()) { try { String sql = "UPDATE books " + "SET isbn = ? ," + "title = ? ," + "type = ? ," + "price = ? ," + "press = ? ," + "author = ? ," + "date = ? " + "WHERE id = ?;"; PreparedStatement ps = conn.prepareStatement(sql); ps.setString(1, book.getIsbn()); ps.setString(2, book.getTitle()); ps.setString(3, book.getType()); ps.setInt(4, book.getPrice()); ps.setString(5, book.getPress()); ps.setString(6, book.getAuthor()); ps.setString(7, book.getDate()); ps.setInt(8, book.getId()); if (ps.executeUpdate() != 0) { // success ps.close(); return true; } ps.close(); } catch (SQLException e) { e.printStackTrace(); } } return false; } public List<UserRecord> searchUser(String keyword) { ArrayList<UserRecord> records = new ArrayList<UserRecord>(); if (isConnectionEstablished()) { try { String sql = "SELECT id, status, user_type " + "FROM users " + "WHERE id LIKE ?;"; PreparedStatement ps = conn.prepareStatement(sql); ps.setString(1, "%" + keyword + "%"); ResultSet rs = ps.executeQuery(); while (rs.next()) { records.add( new UserRecord( rs.getString(1), // username rs.getString(2), // status rs.getString(3) // type )); } ps.close(); } catch (SQLException e) { e.printStackTrace(); } } return records; } public boolean setAsAdmin(String username) { if (isConnectionEstablished()) { try { String sql = "UPDATE users " + "SET user_type = 'admin' " + "WHERE id = ?;"; PreparedStatement ps = conn.prepareStatement(sql); ps.setString(1, username); if (ps.executeUpdate() != 0) { // success ps.close(); return true; } ps.close(); } catch (SQLException e) { e.printStackTrace(); } } return false; } public boolean setAsStandard(String username) { if (isConnectionEstablished()) { try { String sql = "UPDATE users " + "SET user_type = 'standard' " + "WHERE id = ?;"; PreparedStatement ps = conn.prepareStatement(sql); ps.setString(1, username); if (ps.executeUpdate() != 0) { // success ps.close(); return true; } ps.close(); } catch (SQLException e) { e.printStackTrace(); } } return false; } public boolean setAsPremium(String username) { if (isConnectionEstablished()) { try { String sql = "UPDATE users " + "SET user_type = 'premium' " + "WHERE id = ?;"; PreparedStatement ps = conn.prepareStatement(sql); ps.setString(1, username); if (ps.executeUpdate() != 0) { // success ps.close(); return true; } ps.close(); } catch (SQLException e) { e.printStackTrace(); } } return false; } public boolean banUser(String username) { if (isConnectionEstablished()) { try { String sql = "UPDATE users " + "SET status = 'invalid' " + "WHERE id = ?;"; PreparedStatement ps = conn.prepareStatement(sql); ps.setString(1, username); if (ps.executeUpdate() != 0) { // success ps.close(); return true; } ps.close(); } catch (SQLException e) { e.printStackTrace(); } } return false; } public boolean activeUser(String username) { if (isConnectionEstablished()) { try { String sql = "UPDATE users " + "SET status = 'valid' " + "WHERE id = ?;"; PreparedStatement ps = conn.prepareStatement(sql); ps.setString(1, username); if (ps.executeUpdate() != 0) { // success ps.close(); return true; } ps.close(); } catch (SQLException e) { e.printStackTrace(); } } return false; } public boolean modifyPassword(String username, String password) { if (isConnectionEstablished()) { try { String sql = "UPDATE users " + "SET password = ? " + "WHERE id = ?;"; PreparedStatement ps = conn.prepareStatement(sql); ps.setString(1, getMD5(password)); ps.setString(2, username); if (ps.executeUpdate() != 0) { // success ps.close(); return true; } ps.close(); } catch (SQLException e) { e.printStackTrace(); } } return false; } public boolean createStandard(String username, String password) { if (isConnectionEstablished()) { try { String sql = "INSERT INTO users " + "VALUES (?, ?, 'valid', 'standard');"; PreparedStatement ps = conn.prepareStatement(sql); ps.setString(1, username); ps.setString(2, getMD5(password)); if (ps.executeUpdate() != 0) { // success ps.close(); return true; } ps.close(); } catch (SQLException e) { e.printStackTrace(); } } return false; } public List<BorrowRecord> searchBorrowRecord(String keyword) { ArrayList<BorrowRecord> records = new ArrayList<BorrowRecord>(); if (isConnectionEstablished()) { try { String sql = "SELECT borrowings.id, borrowings.uid, books.isbn, books.title, borrowings.start_date, borrowings.end_date " + "FROM users, books, borrowings " + "WHERE borrowings.uid = users.id " + "AND borrowings.bid = books.id " + "AND (borrowings.uid LIKE ? " + "OR books.title LIKE ?) " + "ORDER BY borrowings.id DESC;"; PreparedStatement ps = conn.prepareStatement(sql); ps.setString(1, "%" + keyword + "%"); ps.setString(2, "%" + keyword + "%"); ResultSet rs = ps.executeQuery(); while (rs.next()) { records.add( new BorrowRecord( rs.getInt(1), // id rs.getString(2), // username rs.getString(3), // isbn rs.getString(4), // title rs.getString(5), // start_time rs.getString(6) // end_time )); } rs.close(); ps.close(); } catch (SQLException e) { e.printStackTrace(); } } return records; } public List<BorrowRecord> searchBorrowRecordByUsername(String username) { ArrayList<BorrowRecord> records = new ArrayList<BorrowRecord>(); if (isConnectionEstablished()) { try { String sql = "SELECT borrowings.id, borrowings.uid, books.isbn, books.title, borrowings.start_date, borrowings.end_date " + "FROM users, books, borrowings " + "WHERE borrowings.uid = users.id " + "AND borrowings.bid = books.id " + "AND borrowings.uid = ? " + "ORDER BY borrowings.id DESC;"; PreparedStatement ps = conn.prepareStatement(sql); ps.setString(1, username); ResultSet rs = ps.executeQuery(); while (rs.next()) { records.add( new BorrowRecord( rs.getInt(1), // id rs.getString(2), // username rs.getString(3), // isbn rs.getString(4), // title rs.getString(5), // start_time rs.getString(6) // end_time )); } rs.close(); ps.close(); } catch (SQLException e) { e.printStackTrace(); } } return records; } public boolean borrowBook(String username, int bid) { if (isConnectionEstablished()) { try { Date date = new Date(); // now SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd"); String startDate = simpleDateFormat.format(date); String sql = "INSERT INTO borrowings " + "VALUES (null, ?, ?, '" + startDate + "', null);"; PreparedStatement ps = conn.prepareStatement(sql); ps.setString(1, username); ps.setInt(2, bid); if (ps.executeUpdate() != 0) { // success ps.close(); return true; } ps.close(); } catch (SQLException e) { e.printStackTrace(); } } return false; } public int getAlreadyBorrowedCount(String username) { if (isConnectionEstablished()) { try { String sql = "SELECT COUNT(1) " + "FROM borrowings " + "WHERE uid = ? " + "AND end_date is null;"; PreparedStatement ps = conn.prepareStatement(sql); ps.setString(1, username); ResultSet rs = ps.executeQuery(); if (rs.next()) { int count = rs.getInt(1); rs.close(); ps.close(); return count; } rs.close(); ps.close(); } catch (SQLException e) { e.printStackTrace(); } } return 0; } public boolean returnBook(int id) { if (isConnectionEstablished()) { try { Date date = new Date(); // now SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd"); String endDate = simpleDateFormat.format(date); String sql = "UPDATE borrowings " + "SET end_date = '" + endDate + "' " + "WHERE id = ?;"; PreparedStatement ps = conn.prepareStatement(sql); ps.setInt(1, id); if (ps.executeUpdate() != 0) { // success ps.close(); return true; } ps.close(); } catch (SQLException e) { e.printStackTrace(); } } return false; } }
true
4ae11a93c5a1a29a5435c30f4ea25b71e52c317b
Java
fangwudi/machine-learning-for-business-applications
/DBMS/DB Project/Extra stuff/Hospital-Management-System-master/Login.java
UTF-8
2,455
3.40625
3
[]
no_license
import java.util.Scanner; import java.sql.*; import java.sql.SQLException; import java.util.Scanner; import java.sql.ResultSet; public class Login { public static int choose_role(){ // this function takes the user role as input. this will be stored in the person object and later will be used to display options to the user based on their role. int role = 0; do{ System.out.println("Who would you like to log in as?\npress 1 for Admin, 2 for Doctor, 3 for Nurse, 4 for Operator, 5 for Patient\n"); Scanner in = new Scanner(System.in); role = in.nextInt(); if(role >= 1 || role <= 5){ System.out.println("Role chosen successfully"); } else{ System.out.println("Incorrect input. Please enter a number between 1 and 5."); } }while(role < 1 || role > 5); return role; } public static String login(int role, Connection conn){ // this function will check the staff id and the password are correct and exist in the system. Boolean flag = true; while(flag){ try { Statement s = (Statement) conn.createStatement(); /*Console console = System.console(); if(console == null){ System.out.println("console instance is null"); } String id = console.readLine("Enter you id: "); char[] password = console.readPassword("Enter you password: "); String pwd = new String(password); */ Scanner in = new Scanner(System.in); System.out.println("Enter you id\n"); String id = in.nextLine(); System.out.println("Enter you password\n"); String pwd = in.nextLine(); PreparedStatement prepstmt = null; switch(role){ case 1:case 2:case 3:case 4: prepstmt = (PreparedStatement) conn.prepareStatement("Select count(*) from Staff where staff_id = ? and log_in_cred = ?"); break; case 5: break; } prepstmt.setString(1, id); prepstmt.setString(2, pwd); ResultSet rs = prepstmt.executeQuery(); if(rs.next() && rs.getInt(1) == 1){ flag = false; System.out.println("Logged in successfully!"); return id; } else{ System.out.println("Username and password do not match! Please try again!"); } } catch (SQLException e) { e.printStackTrace(); } } return ""; } public static void logout(Person p){ // This function will log out of the system. p.role = 0; p.id = ""; p.operation = 0; System.out.println("Logged out successfully!"); } }
true
b882e5c144ef2b1801024bafa82228e780a30230
Java
cahitb/airline-project
/src/main/java/com/finartz/airline/repository/FlightRepository.java
UTF-8
296
1.9375
2
[]
no_license
package com.finartz.airline.repository; import com.finartz.airline.entities.Flight; import org.springframework.data.jpa.repository.JpaRepository; import java.util.Optional; public interface FlightRepository extends JpaRepository<Flight, Integer> { Optional<Flight> findById(Integer id); }
true
56d0570b0d9380b002b8fe1b541e0d452f64b460
Java
leikai/SXCninaCourt
/sxchinacourt/src/main/java/org/sxchinacourt/adapter/NewsDetailAdapter.java
UTF-8
2,356
2.515625
3
[ "Apache-2.0" ]
permissive
package org.sxchinacourt.adapter; import android.content.Context; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.BaseAdapter; import android.widget.TextView; import org.sxchinacourt.R; import org.sxchinacourt.bean.NewsContentPattsRoot; import java.util.List; /** * * @author 殇冰无恨 * @date 2017/9/30 */ public class NewsDetailAdapter extends BaseAdapter { private LayoutInflater mLayoutInflater; /** * 映射数据<泛型bean> */ private List<NewsContentPattsRoot> mDataList; public NewsDetailAdapter(Context context, List<NewsContentPattsRoot> list) { mLayoutInflater = LayoutInflater.from(context); mDataList = list; } @Override public int getCount() { return mDataList.size(); } @Override public Object getItem(int i) { return mDataList.get(i); } @Override public long getItemId(int i) { return i; } @Override public View getView(int i, View view, ViewGroup viewGroup) { //用viewholder 储存 findviewbyid的值,避免重复,提高了效率。 ViewHolder holder = null; if (view == null) { holder = new ViewHolder(); // 只将XML转化为View,不涉及具体布局,第二个参数设null view = mLayoutInflater.inflate(R.layout.news_item, null); holder.title = (TextView) view .findViewById(R.id.item_titel_news); holder.content = (TextView) view .findViewById(R.id.item_title_content); holder.time = (TextView) view .findViewById(R.id.item_title_time); //用tag储存viewholder,从而使convertView与holder关联 view.setTag(holder); } else { holder = (ViewHolder) view.getTag(); } // 取出bean对象 NewsContentPattsRoot bean = mDataList.get(i); // 设置控件的数据 holder.title.setText(bean.getFtitle()); holder.content.setText(bean.getStitle()); holder.time.setText(""); return view; } /** * ViewHolder用于缓存控件 */ class ViewHolder { public TextView title; public TextView content; public TextView time; } }
true
96ea77355f91c1c8cbabdd0fe374e2ff351e920c
Java
amarendra108/ehealthsystemamar
/eHealthSystemWeb/src/main/java/nirmalya/aathithya/webmodule/property/model/PropertyAssignAssetModel.java
UTF-8
4,559
1.898438
2
[]
no_license
/* * model for assign assets */ package nirmalya.aathithya.webmodule.property.model; import java.io.IOException; import java.util.ArrayList; import java.util.List; import com.fasterxml.jackson.databind.ObjectMapper; public class PropertyAssignAssetModel { private String propertyCategory; private String property; private String itemCategory; private String itemSubCategory; private String item; private Float pAsstQty; private Boolean pAsstActive; private String action; private String delete; private List<String> assetsList = new ArrayList<String>(); private String assetsName; private String propertyName; private String itemName; private String itemCategoryName; private String itemSubCategoryName; private String propertyTypeName; private String amenity; private String pdfCurrentDate; private String createdBy; public PropertyAssignAssetModel() { super(); // TODO Auto-generated constructor stub } public PropertyAssignAssetModel(String propertyCategory, String property, String itemCategory, String itemSubCategory, String item, Float pAsstQty, Boolean pAsstActive, String action, String delete, List<String> assetsList) { super(); this.propertyCategory = propertyCategory; this.property = property; this.itemCategory = itemCategory; this.itemSubCategory = itemSubCategory; this.item = item; this.pAsstQty = pAsstQty; this.pAsstActive = pAsstActive; this.action = action; this.delete = delete; this.assetsList = assetsList; } public String getPropertyCategory() { return propertyCategory; } public void setPropertyCategory(String propertyCategory) { this.propertyCategory = propertyCategory; } public String getProperty() { return property; } public void setProperty(String property) { this.property = property; } public String getItemCategory() { return itemCategory; } public void setItemCategory(String itemCategory) { this.itemCategory = itemCategory; } public String getItemSubCategory() { return itemSubCategory; } public void setItemSubCategory(String itemSubCategory) { this.itemSubCategory = itemSubCategory; } public String getItem() { return item; } public void setItem(String item) { this.item = item; } public Float getpAsstQty() { return pAsstQty; } public void setpAsstQty(Float pAsstQty) { this.pAsstQty = pAsstQty; } public Boolean getpAsstActive() { return pAsstActive; } public void setpAsstActive(Boolean pAsstActive) { this.pAsstActive = pAsstActive; } public String getAction() { return action; } public void setAction(String action) { this.action = action; } public String getDelete() { return delete; } public void setDelete(String delete) { this.delete = delete; } public List<String> getAssetsList() { return assetsList; } public void setAssetsList(List<String> assetsList) { this.assetsList = assetsList; } public String getAssetsName() { return assetsName; } public void setAssetsName(String assetsName) { this.assetsName = assetsName; } public String getPropertyName() { return propertyName; } public void setPropertyName(String propertyName) { this.propertyName = propertyName; } public String getItemName() { return itemName; } public void setItemName(String itemName) { this.itemName = itemName; } public String getItemCategoryName() { return itemCategoryName; } public void setItemCategoryName(String itemCategoryName) { this.itemCategoryName = itemCategoryName; } public String getItemSubCategoryName() { return itemSubCategoryName; } public void setItemSubCategoryName(String itemSubCategoryName) { this.itemSubCategoryName = itemSubCategoryName; } public String getPropertyTypeName() { return propertyTypeName; } public void setPropertyTypeName(String propertyTypeName) { this.propertyTypeName = propertyTypeName; } public String getAmenity() { return amenity; } public void setAmenity(String amenity) { this.amenity = amenity; } public String getPdfCurrentDate() { return pdfCurrentDate; } public void setPdfCurrentDate(String pdfCurrentDate) { this.pdfCurrentDate = pdfCurrentDate; } public String getCreatedBy() { return createdBy; } public void setCreatedBy(String createdBy) { this.createdBy = createdBy; } @Override public String toString() { ObjectMapper mapperObj = new ObjectMapper(); String jsonStr; try { jsonStr = mapperObj.writeValueAsString(this); } catch (IOException ex) { jsonStr = ex.toString(); } return jsonStr; } }
true
15b117827fb3234fc155045a28d87413290a012f
Java
DonaldY/coding2017
/group24/815591664/2017Learning/src/com/coding/basic/BinaryTree.java
UTF-8
614
3.5625
4
[]
no_license
package com.coding.basic; public class BinaryTree { private BinaryTreeNode root; public BinaryTreeNode insert(Comparable data){ BinaryTreeNode node = new BinaryTreeNode(data); if(this.root==null){ root = node; root.setLeft(null); root.setRight(null); }else{ BinaryTreeNode curNode = this.root; if(data.compareTo(root.getData())>0){ while(curNode.getRight()!=null){ curNode = curNode.getRight(); } curNode = node; }else{ while(curNode.getLeft()!=null){ curNode = curNode.getLeft(); } curNode = node; } } return null; } }
true
d8cc90950e2397649f01f0639a75987dd61ef7b3
Java
ElementiumST/TestQuestion
/app/src/main/java/com/example/testquestion/ui/activities/MoreInfoActivity.java
UTF-8
2,692
2.21875
2
[]
no_license
package com.example.testquestion.ui.activities; import android.os.Bundle; import android.widget.ImageView; import android.widget.LinearLayout; import android.widget.ScrollView; import androidx.annotation.NonNull; import androidx.appcompat.app.AppCompatActivity; import androidx.fragment.app.FragmentManager; import androidx.fragment.app.FragmentTransaction; import com.example.testquestion.R; import com.example.testquestion.data.dataClasses.DataStack; import com.example.testquestion.ui.fragments.InfoFragment; import com.example.testquestion.utils.URLProvider; import java.util.Objects; public class MoreInfoActivity extends AppCompatActivity { InfoFragment activeFragment; FragmentManager fragmentManager; ScrollView scrollView; DataStack activeStack; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_more_info); Objects.requireNonNull(getSupportActionBar()).hide(); activeStack = (DataStack) getIntent().getSerializableExtra("data"); scrollView = findViewById(R.id.scroll); ImageView imageView = findViewById(R.id.background); imageView.setImageResource(URLProvider.getImageResource( activeStack.getClazz().getSimpleName())); LinearLayout layout = findViewById(R.id.root); fragmentManager = getSupportFragmentManager(); FragmentTransaction transaction = fragmentManager.beginTransaction(); activeFragment = new InfoFragment(activeStack); transaction.replace(layout.getId(), activeFragment); transaction.commit(); } public void changePage(InfoFragment from, DataStack to){ FragmentManager fragmentManager = getSupportFragmentManager(); FragmentTransaction transaction = fragmentManager.beginTransaction(); transaction.remove(from); activeStack = to; activeFragment = new InfoFragment(to); transaction.add(R.id.root, activeFragment); transaction.commit(); scrollView.fullScroll(ScrollView.FOCUS_UP); } @Override public void onSaveInstanceState(@NonNull Bundle outState) { outState.putSerializable("stack", activeStack); super.onSaveInstanceState(outState); } @Override protected void onRestoreInstanceState(@NonNull Bundle savedInstanceState) { DataStack stack = (DataStack) savedInstanceState.getSerializable("stack"); if(stack != null) changePage(activeFragment, stack); super.onRestoreInstanceState(savedInstanceState); } public DataStack getActiveStack() { return activeStack; } }
true
df7eecdcb70f3a63f31b659977779a104a9cc4b7
Java
K-MyeongHwan/BitCamp
/Project 2/Bit_SecondHands/src/kr/or/bit/dto/category_middle.java
UTF-8
763
2.25
2
[]
no_license
package kr.or.bit.dto; public class category_middle { private int m_num; private String m_name; private int t_num; public category_middle() { } public category_middle(int m_num, String m_name, int t_num) { super(); this.m_num = m_num; this.m_name = m_name; this.t_num = t_num; } public int getM_num() { return m_num; } public void setM_num(int m_num) { this.m_num = m_num; } public String getM_name() { return m_name; } public void setM_name(String m_name) { this.m_name = m_name; } public int getT_num() { return t_num; } public void setT_num(int t_num) { this.t_num = t_num; } @Override public String toString() { return "category_middle [m_num=" + m_num + ", m_name=" + m_name + ", t_num=" + t_num + "]"; } }
true
792559c502a3b0ebc0823b2b9266f32ec76ab35d
Java
eastnomoring/MRBS_NEW
/app/src/main/java/com/yzy/mrbs/activity/UiEditText.java
UTF-8
5,089
2
2
[]
no_license
package com.yzy.mrbs.activity; import android.os.Bundle; import android.view.KeyEvent; import android.view.View; import android.view.inputmethod.InputMethodManager; import android.widget.Button; import android.widget.EditText; import com.yzy.mrbs.R; import com.yzy.mrbs.base.BaseMessage; import com.yzy.mrbs.base.BaseUiUser; import com.yzy.mrbs.base.BaseUser; import com.yzy.mrbs.base.C; import com.yzy.mrbs.phalapi.PhalapiHttpUtil; import org.json.JSONObject; import java.util.HashMap; import java.util.regex.PatternSyntaxException; /** * Created by ZhiYuan on 2016/5/22. */ public class UiEditText extends BaseUiUser { private EditText mEditText; private Button mEditSubmit; private String s_setsign_request; @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.ui_edit); // 显示软键盘 ((InputMethodManager) getSystemService(INPUT_METHOD_SERVICE)).toggleSoftInput(0, InputMethodManager.HIDE_NOT_ALWAYS); // 界面初始化 mEditText = (EditText) this.findViewById(R.id.app_edit_text); mEditSubmit = (Button) this.findViewById(R.id.app_edit_submit); // 处理不同逻辑 Bundle params = this.getIntent().getExtras(); final int action = params.getInt("action"); switch (action) { //修改签名逻辑 case C.action.edittext.CONFIG: mEditText.setText(params.getString("value")); mEditSubmit.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { String input = mEditText.getText().toString(); customer.setSign(input); // 更新本地签名 //旧框架更新网络签名 // HashMap<String, String> urlParams = new HashMap<String, String>(); // urlParams.put("key", "sign"); // urlParams.put("val", input); // doTaskAsync(C.task.customerEdit, C.api.customerEdit, urlParams);//更新服务器签名 //新框架更新网络签名 逻辑 customer.getId(); // String s_setsign = "http://192.168.1.103:80/PhalApi/Public/user/?service=User.setusersign" // +"&userid=" +customer.getId() // +"&sign="+input; String s_setsign = "http://115.28.193.57:80/PhalApi/Public/user/?service=User.setusersign" +"&userid=" +customer.getId() +"&sign="+input; try { s_setsign_request = PhalapiHttpUtil.getRequest(s_setsign); } catch (Exception e) { e.printStackTrace(); toast("网络连接失败,未更新您的签名"); } try { JSONObject jsonObj = new JSONObject(s_setsign_request); if (jsonObj.getString("data")== "1"){ toast("更新成功"); } if(jsonObj.getString("data")== "0"){ toast("您的签名同之前一样,无需更新"); } if(jsonObj.getString("data")== "false"){ toast("服务器未响应"); } toast("恭喜您,更新签名成功"); } catch (Exception e) { e.printStackTrace(); } } }); break; //发表评论逻辑,此功能后续实现 case C.action.edittext.COMMENT: final String blogId = params.getString("blogId"); mEditSubmit.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { String input = mEditText.getText().toString(); HashMap<String, String> urlParams = new HashMap<String, String>(); urlParams.put("blogId", blogId); urlParams.put("content", input); doTaskAsync(C.task.commentCreate, C.api.commentCreate, urlParams); } }); break; } } //////////////////////////////////////////////////////////////////////////////////////////////// // 异步回掉方法 @Override public void onTaskComplete(int taskId, BaseMessage message) { super.onTaskComplete(taskId, message); doFinish(); } @Override public void onNetworkError (int taskId) { super.onNetworkError(taskId); } }
true
d64c643b80a264def08ee5562226fad4590ae6e6
Java
HouyiFan/Practice
/IQPractice/src/Convert_Decimal_To_Binary.java
UTF-8
1,809
3.78125
4
[]
no_license
import java.util.Scanner; public class Convert_Decimal_To_Binary { public static void main(String[] args) { Scanner in = new Scanner(System.in); double num = in.nextDouble(); int n = (int) num; double decimal = num - n; String res = ""; while (n > 0) { int remainder = n % 2; n = n / 2; res = remainder + res; } res += "."; while (decimal > 0) { decimal *= 2; int integer = (int) decimal; if (integer == 1) { decimal -= 1; } res += integer; } System.out.println(res); in.close(); } //Given a base- integer, , convert it to binary (base-). Then find and //print the base- integer denoting the maximum number of consecutive 's in 's binary representation. //ex: 5 -> 101 -> 1 //ex2: 13 -> 1101 -> 2 // public static void main(String[] args) { // // TODO Auto-generated method stub // Scanner in = new Scanner(System.in); // int n = in.nextInt(); // String res = ""; // while (n > 0) { // int remainder = n % 2; // n = n / 2; // res = remainder + res; // } // int count = 0; // char[] c = res.toCharArray(); // for (int i = 0; i < c.length; i++) { // int j = i; // int temp = 0; // while (i < c.length && c[i] == '1') { // temp++; // i++; // count = Math.max(count, temp); // } // i = j; // } // System.out.println(count); // in.close(); // // } }
true
99bf4d81e62cc7fb19c404a8a8ed25e60161af24
Java
BGCX262/zyzweb-svn-to-git
/trunk/src/com/mycms/cms/action/front/TagAct1.java
UTF-8
1,395
1.8125
2
[]
no_license
package com.mycms.cms.action.front; import static com.mycms.cms.Constants.RES_PATH; import static com.mycms.cms.Constants.TPLDIR_SPECIAL; import java.util.List; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import org.apache.commons.lang.StringUtils; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Controller; import org.springframework.ui.ModelMap; import org.springframework.web.bind.annotation.PathVariable; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestMethod; import com.mycms.cms.entity.main.CmsSite; import com.mycms.cms.entity.main.ContentTag; import com.mycms.cms.manager.main.CmsSiteMng; import com.mycms.cms.manager.main.ContentTagMng; import com.mycms.cms.web.CmsUtils; import com.mycms.cms.web.FrontUtils; @Controller public class TagAct1 { @Autowired private CmsSiteMng cmsSiteMng; @Autowired private ContentTagMng contentTagMng; public String getContextPath(){ String ctx=""; List<CmsSite> list = cmsSiteMng.getListFromCache(); CmsSite site =list.get(0); String res = ctx + RES_PATH + "/" + site.getPath() + "/" + site.getTplSolution(); ctx=res.substring(1); return ctx; } }
true
060f8ebafc4e220ccc18402e0ec54a15c40b4831
Java
Ioana-Sofia-Lazar/EdFocus
/app/src/main/java/com/ioanapascu/edfocus/others/StudentFragmentPagerAdapter.java
UTF-8
1,184
2.453125
2
[]
no_license
package com.ioanapascu.edfocus.others; import android.content.Context; import android.support.v4.app.Fragment; import android.support.v4.app.FragmentManager; import android.support.v4.app.FragmentPagerAdapter; import com.ioanapascu.edfocus.teacher.StudentActivityFragment; /** * Created by ioana on 2/28/2018. */ public class StudentFragmentPagerAdapter extends FragmentPagerAdapter { private final int PAGE_COUNT = 2; private String[] tabTitles = new String[]{"Grades", "Absences"}; private Context context; private String mStudentId, mClassId; public StudentFragmentPagerAdapter(FragmentManager fm, Context context, String studentId, String classId) { super(fm); this.context = context; mStudentId = studentId; mClassId = classId; } @Override public int getCount() { return PAGE_COUNT; } @Override public Fragment getItem(int position) { return StudentActivityFragment.newInstance(position, mStudentId, mClassId); } @Override public CharSequence getPageTitle(int position) { // Generate title based on item position return tabTitles[position]; } }
true
4b170a7d32bfa4baccc3a5a06e403dfb779dfd16
Java
Unidentified-Lin/CGUFollowMe
/src/com/cguim/cgufollowme/MapActivity.java
BIG5
13,345
1.75
2
[]
no_license
package com.cguim.cgufollowme; import min3d.core.Object3dContainer; import min3d.core.RendererActivity; import min3d.parser.IParser; import min3d.parser.Parser; import min3d.vos.Light; public class MapActivity extends RendererActivity { private Object3dContainer model; private float theta; private float pos_z = 0, pos_x = 0; private float old_pos_z = 0, old_pos_x = 0; private float move_X = 0, move_Y = 0; private float dX_M = 0, dY_M = 0; private float degrees_X = 0, degrees_Y = 0; private float radians_X, radians_Y; private float degrees_X_R, degrees_Y_R; private float radians_X_R, radians_Y_R; private float dX_R = 0, dY_R = 0; private float gTouchX1, gTouchY1, gTouchX2, gTouchY2; private float oldDistance, newDistance; private float CAM_RADIUS = 30; private float tempRadius = 30; private MyApplication myApp; private SensorManager sensorManager; private Sensor aSensor; private Sensor mSensor; float[] accelerometerValues = new float[3]; float[] magneticFieldValues = new float[3]; float[] smooth_accelerometerValues = new float[3]; float[] smooth_magneticFieldValues = new float[3]; TextView title; ToggleButton autoRotate, moveModel; Spinner spn; Button btn_over; ArrayAdapter<String> adapter; String[] PATH; String destination = null, location = null; int path = 0, step = 0; boolean rotate = false, had_last_position = false, move = false; @Override @Override protected void onCreateSetContentView() { requestWindowFeature(Window.FEATURE_NO_TITLE); setContentView(R.layout.map_layout); // LayoutInflater inflater = LayoutInflater.from(MapActivity.this); View layout = inflater.inflate(R.layout.gesture, null); AlertDialog.Builder builder = new AlertDialog.Builder(MapActivity.this); builder.setView(layout); builder.setTitle("ϥλ"); builder.setMessage("zLIJ\nվҫYjp\n沾ʼҫmΫnww"); builder.setNegativeButton("Tw", null); builder.create().show(); // *********PO|************** myApp = (MyApplication) getApplication(); location = myApp.getLocation(); // _I({bm) destination = myApp.getDestination(); // I(تa) pathway(location, destination); LinearLayout ll = (LinearLayout) this.findViewById(R.id.scene1Holder); ll.addView(_glSurfaceView); title = (TextView) this.findViewById(R.id.mapTitle); title.setText("تa:" + destination); autoRotate = (ToggleButton) this.findViewById(R.id.toggleButton1); autoRotate.setOnCheckedChangeListener(onChangeRotate); moveModel = (ToggleButton) this.findViewById(R.id.toggleButton2); moveModel.setOnCheckedChangeListener(onChangeMove); btn_over = (Button) this.findViewById(R.id.btn_over); btn_over.setOnClickListener(new OnClickListener() { @Override public void onClick(View v) { // TODO Auto-generated method stub sensorManager.unregisterListener(myListener); finish(); } }); spn = (Spinner) this.findViewById(R.id.spn_sub_place); adapter = new ArrayAdapter<String>(this, R.layout.spinner_layout, PATH); adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item); spn.setAdapter(adapter); spn.setSelection(0, false); spn.setOnItemSelectedListener(new OnItemSelectedListener() { @Override public void onItemSelected(AdapterView<?> parent, View view, int position, long id) { // TODO Auto-generated method stub step = position; onPause(); onResume(); } @Override public void onNothingSelected(AdapterView<?> arg0) { // TODO Auto-generated method stub } }); initSensor(); } @Override @Override @Override public void initScene() { Light light1 = new Light(); Light light2 = new Light(); Light light3 = new Light(); light1.position.setAll(3, 3, 0); light2.position.setAll(0, 3, 3); light3.position.setAll(0, 6, 0); scene.lights().add(light1); scene.lights().add(light2); scene.lights().add(light3); IParser parser = Parser.createParser(Parser.Type.MAX_3DS, getResources(), "com.cguim.cgufollowme:raw/path" + path + "_" + step, false); parser.parse(); model = parser.getParsedObject(); model.scale().x = model.scale().y = model.scale().z = 2f; // model.position().y = -1; // model.position().x = 7.5f; // model.position().z = -2; scene.addChild(model); // scene.camera().target = model.position(); scene.camera().position.x = 30; scene.camera().position.y = 0; scene.camera().position.z = 0; } @Override @Override @Override public void updateScene() { // Log.i("updateScene", "updateScene()"); /** wҦ---wҦ---wҦ---wҦ---wҦ---wҦ---wҦ---wҦ---wҦ--- */ if (rotate) { radians_X_R = degrees_X_R * ((float) Math.PI / 180); radians_Y_R = degrees_Y_R * ((float) Math.PI / 180); scene.camera().position.y = (float) Math.sin(radians_Y_R) * CAM_RADIUS; scene.camera().position.x = (float) Math.cos(radians_X_R) * (float) Math.cos(radians_Y_R) * CAM_RADIUS; scene.camera().position.z = (float) Math.sin(radians_X_R) * (float) Math.cos(radians_Y_R) * CAM_RADIUS; } else { /** Ҧ---Ҧ---Ҧ---Ҧ---Ҧ---Ҧ---Ҧ---Ҧ--- */ // ILwAO_̫m if (had_last_position) { dX_R = degrees_X_R * 6; dY_R = degrees_Y_R * 6; had_last_position = false; } dX_R = dX_R % 2160;// 360*6pixelAdX 0~2160@Ӵ` degrees_X = dX_R / 6; // 6pixel1 degrees_Y = dY_R / 6; if (degrees_Y < 0) { dY_R = 0; degrees_Y = 0; } else if (degrees_Y > 89) { dY_R = 534; degrees_Y = 89; } radians_X = degrees_X * ((float) Math.PI / 180); radians_Y = degrees_Y * ((float) Math.PI / 180); scene.camera().position.y = (float) Math.sin(radians_Y) * CAM_RADIUS; scene.camera().position.x = (float) Math.cos(radians_X) * (float) Math.cos(radians_Y) * CAM_RADIUS; scene.camera().position.z = (float) Math.sin(radians_X) * (float) Math.cos(radians_Y) * CAM_RADIUS; } /** Ҧ---Ҧ---Ҧ---Ҧ---Ҧ---Ҧ---Ҧ---Ҧ--- */ if (move) { if (rotate) theta = degrees_X_R * ((float) Math.PI / 180); else theta = degrees_X * ((float) Math.PI / 180); move_X = dX_M / 50; move_Y = dY_M / 50; if (move_X == 0 && move_Y == 0) { pos_z = old_pos_z; pos_x = old_pos_x; } else { pos_z = ((float) Math.sin(theta) * move_Y - (float) Math .cos(theta) * move_X) + old_pos_z; pos_x = ((float) Math.sin(theta) * move_X + (float) Math .cos(theta) * move_Y) + old_pos_x; } model.position().z = pos_z; model.position().x = pos_x; } } private GestureDetector detector = new GestureDetector(getBaseContext(), new OnGestureListener() { @Override public boolean onSingleTapUp(MotionEvent e) { // TODO Auto-generated method stub return false; } @Override public void onShowPress(MotionEvent e) { // TODO Auto-generated method stub } @Override public boolean onScroll(MotionEvent e1, MotionEvent e2, float distanceX, float distanceY) { // TODO Auto-generated method stub if (move) { dX_M = dX_M - distanceX; dY_M = dY_M - distanceY; } else { dX_R = dX_R - distanceX; dY_R = dY_R - distanceY; // hasChange = true; } return true; } @Override public void onLongPress(MotionEvent e) { // TODO Auto-generated method stub } @Override public boolean onFling(MotionEvent e1, MotionEvent e2, float velocityX, float velocityY) { // TODO Auto-generated method stub return false; } @Override public boolean onDown(MotionEvent e) { // TODO Auto-generated method stub return false; } }); @Override public boolean onTouchEvent(MotionEvent event) { int pointerCount = event.getPointerCount(); int action = MotionEventCompat.getActionMasked(event); if (pointerCount == 1) { if (detector.onTouchEvent(event)) { return true; } else { return false; } } else if (pointerCount == 2) { gTouchX1 = (float) event.getX(0); // Ĥ@IJI gTouchY1 = (float) event.getY(0); gTouchX2 = (float) event.getX(1); // ĤGIJI gTouchY2 = (float) event.getY(1); switch (action) { case MotionEvent.ACTION_POINTER_DOWN:// ĤGIJIQIU oldDistance = (float) Math.sqrt(Math.pow((gTouchX1 - gTouchX2), 2) + Math.pow((gTouchY1 - gTouchY2), 2)); return true; case MotionEvent.ACTION_MOVE: newDistance = (float) Math.sqrt(Math.pow((gTouchX1 - gTouchX2), 2) + Math.pow((gTouchY1 - gTouchY2), 2)); CAM_RADIUS = tempRadius / newDistance * oldDistance; if (CAM_RADIUS < 5) CAM_RADIUS = 5; else if (CAM_RADIUS > 80) CAM_RADIUS = 80; return true; case MotionEvent.ACTION_POINTER_UP: tempRadius = CAM_RADIUS; return true; } } return false; } private OnCheckedChangeListener onChangeRotate = new OnCheckedChangeListener() { @Override public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) { // TODO Auto-generated method stub if (isChecked) { // UP rotate = true; had_last_position = true; sensorManager.registerListener(myListener, aSensor, SensorManager.SENSOR_DELAY_GAME); sensorManager.registerListener(myListener, mSensor, SensorManager.SENSOR_DELAY_GAME); } else { // UP rotate = false; sensorManager.unregisterListener(myListener); } } }; private OnCheckedChangeListener onChangeMove = new OnCheckedChangeListener() { @Override public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) { // TODO Auto-generated method stub if (isChecked) { // }ҥ dX_M = 0; dY_M = 0; move = true; } else { // move = false; old_pos_z = pos_z; old_pos_x = pos_x; } } }; private void initSensor() { sensorManager = (SensorManager) getSystemService(SENSOR_SERVICE); aSensor = sensorManager.getDefaultSensor(Sensor.TYPE_ACCELEROMETER); mSensor = sensorManager.getDefaultSensor(Sensor.TYPE_MAGNETIC_FIELD); calculateOrientation(); } private void calculateOrientation() { // pਤ float[] values = new float[3]; float[] R = new float[9]; SensorManager.getRotationMatrix(R, null, smooth_accelerometerValues, smooth_magneticFieldValues);// ox}(ϥέ) SensorManager.getOrientation(R, values); // ngL@ƾڮ榡ഫAഫ degrees_X_R = (float) Math.toDegrees(values[0]);// degrees_Y_R = (float) Math.toDegrees(values[1]);// e // values[2] = (float) Math.toDegrees(values[2]);//k½u if (degrees_X_R > 0) degrees_X_R = (degrees_X_R); else degrees_X_R = (degrees_X_R) % 360; if (degrees_Y_R > 0) degrees_Y_R = 90 - degrees_Y_R; else degrees_Y_R = 90 + degrees_Y_R; } final SensorEventListener myListener = new SensorEventListener() { public void onAccuracyChanged(Sensor sensor, int accuracy) { // TODO Auto-generated method stub Log.i("Sensor_test", "onAccuracyChanged: " + sensor + ", accuracy: " + accuracy); } public void onSensorChanged(SensorEvent sensorEvent) { // TODO Auto-generated method stub if (sensorEvent.sensor.getType() == Sensor.TYPE_ACCELEROMETER) { accelerometerValues = sensorEvent.values; smooth_accelerometerValues = exponentialSmoothing( accelerometerValues, smooth_accelerometerValues, 0.0618f); } if (sensorEvent.sensor.getType() == Sensor.TYPE_MAGNETIC_FIELD) { magneticFieldValues = sensorEvent.values; smooth_magneticFieldValues = exponentialSmoothing( magneticFieldValues, smooth_magneticFieldValues, 0.0618f); } calculateOrientation(); } }; private float[] exponentialSmoothing(float[] input, float[] output, float alpha) { // ƥƪk if (output == null) return input; for (int i = 0; i < input.length; i++) { output[i] = output[i] + alpha * (input[i] - output[i]); } return output; } @Override public void onBackPressed() { // TODO Auto-generated method stub // super.onBackPressed(); sensorManager.unregisterListener(myListener); finish(); } public void pathway(String loc, String des) { if (loc.equals("")) { PATH = getResources().getStringArray(R.array.nopath); if (destination.equals("T޲zǨtt")) { path = 0; step = 2; } else { path = 2; step = 0; } } else { if (loc.equals("j-ԨF") && des.equals("T޲zǨtt")) { PATH = getResources().getStringArray(R.array.path0); path = 0; } else if (loc.equals("j-Ĥ@Ǥj1F") && des.equals("T޲zǨtt")) { PATH = getResources().getStringArray(R.array.path1); path = 1; }else{ PATH = getResources().getStringArray(R.array.path1); path = 2; step = 0; } } } }
true
14437a1baccbcb32e8cc1faf5bb902202139373c
Java
franklsf95/icpc-practice
/2013-PacNW/src/Languages.java
UTF-8
1,455
3.5625
4
[]
no_license
import java.util.*; public class Languages { static void readToDic(String buf, HashMap<String, ArrayList<String>> dic) { // System.out.println("Reading buffer: " + buf); String all[] = buf.split("[^a-zA-z'-]"); ArrayList<String> bucket = new ArrayList<String>(); for (int i = 1; i < all.length; i++) { bucket.add(all[i].toLowerCase()); } dic.put(all[0], bucket); } static void detect(String ln, HashMap<String, ArrayList<String>> dic) { // System.out.println("Detecting: " + ln); String words[] = ln.split("[^a-zA-z'-]"); for (String w : words) { // System.out.println(w); w = w.toLowerCase(); // iterate over the dictionary for (String lang : dic.keySet()) { ArrayList<String> b = dic.get(lang); if (b.contains(w)) { System.out.println(lang); return; } } } } public static void main(String[] args) { Scanner in = new Scanner(System.in); HashMap<String, ArrayList<String>> dic = new HashMap<String, ArrayList<String>>(); int N = in.nextInt(); in.nextLine(); for (int i = 0; i < N; i++) { String buf = in.nextLine(); readToDic(buf, dic); } // for (String k : dic.keySet()) { // System.out.println(" --- " + k); // ArrayList<String> b = dic.get(k); // for (String t : b) { // System.out.print(t + " || "); // } // System.out.println(); // } in.nextLine(); while (in.hasNextLine()) { String ln = in.nextLine(); detect(ln, dic); } } }
true
b59fdeeb245fe58f8785ffe67172108618a5e64d
Java
Alujixixi/StreetRecommed
/src/main/java/com/aluji/entities/UserStoreKey.java
UTF-8
655
2.296875
2
[]
no_license
package com.aluji.entities; /* * 在ScheduleTaskService中作为map的key存在 * * */ import lombok.AllArgsConstructor; import lombok.Data; import lombok.NoArgsConstructor; @Data @AllArgsConstructor @NoArgsConstructor public class UserStoreKey { private Integer userId; private Integer storeId; @Override public boolean equals(Object o) { if (this == o) return true; if (!(o instanceof UserStoreKey)) return false; UserStoreKey key = (UserStoreKey) o; return userId == key.userId && storeId == key.storeId; } @Override public int hashCode() { return 31 * userId + storeId; } }
true
9d566634a60d1698b5e2515defc08cfe80df88b9
Java
wzmyyj/OS
/app/src/main/java/com/osmeet/os/view/activity/NewFriendsActivity.java
UTF-8
1,769
2.0625
2
[]
no_license
package com.osmeet.os.view.activity; import android.support.annotation.NonNull; import android.widget.FrameLayout; import com.osmeet.os.R; import com.osmeet.os.app.bean.Friend; import com.osmeet.os.base.activity.BaseActivity; import com.osmeet.os.contract.NewFriendListContract; import com.osmeet.os.presenter.NewFriendsPresenter; import com.osmeet.os.view.panel.NewFriendsRecyclerPanel; import java.util.List; import butterknife.BindView; import butterknife.OnClick; public class NewFriendsActivity extends BaseActivity<NewFriendListContract.IPresenter> implements NewFriendListContract.IView { @Override protected void initPresenter() { mPresenter = new NewFriendsPresenter(activity, this); } @Override protected int getLayoutId() { return R.layout.activity_new_friends; } NewFriendsRecyclerPanel newFriendsRecyclerPanel; @Override protected void initPanels() { super.initPanels(); addPanels( newFriendsRecyclerPanel = new NewFriendsRecyclerPanel(context, mPresenter) ); } @OnClick(R.id.img_back) void back() { mPresenter.finish(); } @BindView(R.id.fl_panel) FrameLayout fl_panel; @Override protected void initView() { super.initView(); fl_panel.addView(getPanelView(0)); } @Override protected void initData() { super.initData(); mPresenter.loadNewFriendList(0); } @Override public void showNewFriendList(@NonNull List<Friend> friendList, int pageNum) { newFriendsRecyclerPanel.setDataList(friendList, pageNum); } @Override public void showAgreeNewFriend(@NonNull String userId) { newFriendsRecyclerPanel.agreeSuccess(userId); } }
true
b10a47284bfc4b33e874ce5d99323b732bbc555b
Java
uboger/newspublish
/src/com/boy/models/Hotnews.java
UTF-8
716
1.984375
2
[]
no_license
package com.boy.models; import java.io.Serializable; import java.util.Date; public class Hotnews implements Serializable { private Integer hid; private String title; private String content; private Date createtime; private int sign; public Integer getHid() { return hid; } public void setHid(Integer hid) { this.hid = hid; } public String getTitle() { return title; } public void setTitle(String title) { this.title = title; } public String getContent() { return content; } public void setContent(String content) { this.content = content; } public Date getCreatetime() { return createtime; } public void setCreatetime(Date createtime) { this.createtime = createtime; } }
true
1b6fb2b57780edfc483ca388b11c0fc29a17ab79
Java
pravich/AccountManagerPoc
/AccountManagerPoc/src/com/yggdrasil/europa/account/cache/WalletAccountCache.java
UTF-8
1,636
2.71875
3
[]
no_license
package com.yggdrasil.europa.account.cache; import java.util.Hashtable; import org.apache.logging.log4j.LogManager; import org.apache.logging.log4j.Logger; public class WalletAccountCache { private static Logger logger = LogManager.getLogger(WalletAccountCache.class); private static Hashtable<Integer, String> forwardCache = new Hashtable<Integer, String> (10000); private static Hashtable<String, WalletAccountCacheItem> reverseCache = new Hashtable<String, WalletAccountCacheItem>(10000); public static String getSessionToken(String accountId) { String sessionToken = forwardCache.get(accountId); if(sessionToken == null) { logger.debug("not found session token of " + accountId + "."); } else { logger.debug("accountId=" + accountId + " gets session token."); } return(sessionToken); } public static WalletAccountCacheItem getUserItem(String sessionToken) { WalletAccountCacheItem cacheItem = reverseCache.get(sessionToken); if(cacheItem == null) { logger.debug("not found UserAccountCacheItem of " + sessionToken + "."); } else { logger.debug("session token read [" + sessionToken + "] "); } return(cacheItem); } public static void setSessionToken(String sessionToken, WalletAccountCacheItem cacheItem) { logger.debug("accountId=" + cacheItem.accountId + " sets session token [" + sessionToken + "]."); if(forwardCache.containsKey(cacheItem.accountId)) { // removes previous session if exists. reverseCache.remove(forwardCache.get(cacheItem.accountId)); } forwardCache.put(cacheItem.accountId, sessionToken); reverseCache.put(sessionToken, cacheItem); } }
true
a7b7dff15fe46cfbaa4c4db937e14f91ce3fe41b
Java
coregenomics/imagej-cellprofiler-roi-plugin
/src/main/java/edu/uconn/CellProfilerROI.java
UTF-8
3,667
2.59375
3
[ "LicenseRef-scancode-public-domain" ]
permissive
/* * Copyright 2017 Pariksheet Nanda * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * 1. Redistributions of source code must retain the above copyright notice, * this list of conditions and the following disclaimer. * * 2. Redistributions in binary form must reproduce the above copyright notice, * this list of conditions and the following disclaimer in the documentation * and/or other materials provided with the distribution. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. */ package edu.uconn; import net.imagej.Dataset; import net.imagej.ImageJ; import net.imagej.ops.OpService; import net.imglib2.RandomAccessibleInterval; import net.imglib2.img.Img; import net.imglib2.type.numeric.RealType; import org.scijava.command.Command; import org.scijava.plugin.Parameter; import org.scijava.plugin.Plugin; import org.scijava.ui.UIService; import java.io.File; import java.util.ArrayList; import java.util.List; /** * This example illustrates how to create an ImageJ {@link Command} plugin. * <p> * The code here is a simple blur using ImageJ Ops. * </p> * <p> * You should replace the parameter fields with your own inputs and outputs, and * replace the {@link run} method implementation with your own logic. * </p> */ @Plugin(type = Command.class, menuPath = "Plugins>Cell Profiler ROI Importer") public class CellProfilerROI<T extends RealType<T>> implements Command { @Parameter private Dataset currentData; @Parameter private UIService uiService; @Parameter private OpService opService; @Override public void run() { final Img<T> image = (Img<T>) currentData.getImgPlus(); // // Enter image processing code here ... // The following is just a filtering example // final double[] sigmas = { 1.0, 3.0, 5.0 }; List<RandomAccessibleInterval<T>> results = new ArrayList<>(); for (double sigma : sigmas) { results.add(opService.filter().gauss(image, sigma)); } // display result for (RandomAccessibleInterval<T> elem : results) { uiService.show(elem); } } /** * This main function serves for development purposes. It allows you to run * the plugin immediately out of your integrated development environment * (IDE). * * @param args * whatever, it's ignored * @throws Exception */ public static void main(final String... args) throws Exception { // create the ImageJ application context with all available services final ImageJ ij = new ImageJ(); ij.ui().showUI(); // ask the user for a file to open final File file = ij.ui().chooseFile(null, "open"); if (file != null) { // load the dataset final Dataset dataset = ij.scifio().datasetIO().open(file.getPath()); // show the image ij.ui().show(dataset); // invoke the plugin ij.command().run(CellProfilerROI.class, true); } } }
true
c4dde98623f2d71fd22fe7fd45feb4008e8dc933
Java
zhanght86/ZhongShen
/sjzs/src/com/hnzskj/persist/dao/system/OperationLogDao.java
UTF-8
3,772
2.625
3
[]
no_license
package com.hnzskj.persist.dao.system; import java.io.Serializable; import java.util.LinkedHashMap; import com.hnzskj.common.Page; import com.hnzskj.persist.bean.system.OperationLog; public interface OperationLogDao { /** * * 方法描述:将操作日志存储到数据库中<br/> * 创建人:苏国庆 <br/> * 创建时间:2011-5-17 下午02:52:24<br/> * @param operationLog * @return * @version 1.0 */ public int save( OperationLog operationLog ); /** * * 方法描述:根据指定的id删除数据库中的一条记录 * 创建人:苏国庆 * 创建时间:2011-3-3 下午02:05:52 * @param id * @return 返回 1 表示删除成功 返回 0 表示删除失败 * @version 1.0 */ public int delete( int id ); /** * * 方法描述:删除一组记录,数据中记录了待删除的id * 创建人:苏国庆 * 创建时间:2011-3-3 下午02:11:30 * @param ids 要删除的id的数组 * @return 返回 int 所删除的记录的条数 * @version 1.0 */ public int delete( Serializable... ids); /** * * 方法描述:根据指定的id,从数据库中查询一条记录 ,如果记录不存在返回NULL * 创建人:苏国庆 * 创建时间:2011-3-3 下午02:14:39 * @param sql 指定查询的SQL语句 * @return 返回查询到的一个OperationLog对象,如果不存在返回NULL * @version 1.0 */ public OperationLog getById( String id ); /** * * 方法描述:根据指定条件返回查询到的记录的数目 * 创建人:苏国庆 * 创建时间:2011-3-4 下午05:17:45 * @param sqlCondition 指定的查询语句的条件字段如"where field1=?" * @param params * @return * @version 1.0 */ public int getCount( String sqlCondition, Object[] params); /** * * 方法描述:无条件查询所有<br/> * 创建人:苏国庆 <br/> * 创建时间:2011-5-26 下午03:56:24<br/> * @return * @version 1.0 */ public Page<OperationLog> searchOperationLog(String fields); /** * * 方法描述:无条件分布查询所有<br/> * 创建人:苏国庆 <br/> * 创建时间:2011-5-26 下午04:10:59<br/> * @param page * @return * @version 1.0 */ public Page<OperationLog> searchOperationLog(Page<OperationLog> page,String fields); /** * * 方法描述:根据查询条件分布查询<br/> * 创建人:苏国庆 <br/> * 创建时间:2011-5-26 下午04:11:17<br/> * @param page * @param sqlCondition * @param queryParams * @return * @version 1.0 */ public Page<OperationLog> searchOperationLog(Page<OperationLog> page,String fields, String sqlCondition,Object[] queryParams); /** * * 方法描述:无条件分页,按指定排序条件查询<br/> * 创建人:苏国庆 <br/> * 创建时间:2011-5-26 下午04:11:39<br/> * @param page * @param orderby * @return * @version 1.0 */ public Page<OperationLog> searchOperationLog(Page<OperationLog> page,String fields, LinkedHashMap<String, String> orderby); /** * 方法描述:指定查询,排序条件分页查询<br/> * 创建人:苏国庆 <br/> * 创建时间:2011-5-26 下午04:27:50<br/> * @param page * @param sqlCondition * @param queryParams * @param orderby * @return * @version 1.0 */ public Page<OperationLog> searchOperationLog(Page<OperationLog> page,String fields, String sqlCondition, Object[] queryParams, LinkedHashMap<String, String> orderby); }
true
cdae611ffb7e3433bf25ef3ab4f1723616e0b669
Java
gvardianez/Java_1_projects_Kolesnik
/lesson_2/GetInput.java
UTF-8
1,652
3.421875
3
[]
no_license
package lesson_2; import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import java.util.Scanner; public class GetInput { private static long inputNumber; public static String getUserInputString(String text) { String inputLine = null; System.out.print(text + " "); try { BufferedReader in = new BufferedReader(new InputStreamReader(System.in)); inputLine = in.readLine(); if (inputLine.length() == 0) { System.out.println("Некорректный ввод, повторите "); getUserInputString(""); } } catch (IOException e) { System.out.println("IOException: " + e); } return inputLine; } public static long getUserInputLong(String text) { System.out.print(text + " "); Scanner in = new Scanner(System.in); try { inputNumber = in.nextLong(); } catch (Exception e) { getUserInputLong("Некорректный ввод, повторите"); } return inputNumber; } public static int getUserInputPositive(String text) { System.out.print(text + " "); Scanner in = new Scanner(System.in); try { inputNumber = in.nextInt(); } catch (Exception e) { getUserInputPositive("Некорректный ввод, повторите"); } if (inputNumber < 0) { getUserInputPositive("Некорректный ввод, повторите"); } return (int) inputNumber; } }
true
165387678004277ecbd9c84353dcedb0119930b3
Java
noiz354/stuart-hackathon
/app/src/main/java/com/stuart/hackatonproject/util/ToastUtil.java
UTF-8
902
2.703125
3
[]
no_license
package com.stuart.hackatonproject.util; import android.content.Context; import android.text.TextUtils; import android.view.Gravity; import android.widget.TextView; import android.widget.Toast; /** * Created by User on 10/17/2017. */ public class ToastUtil { private static final int TOAST_LONG_SIZE = 20; //20 characters public static void showToast(Context context, Throwable e){ String message = e.getMessage(); if (!TextUtils.isEmpty(message)) { showToast(context, message); } } public static void showToast(Context context, String message){ Toast toast = Toast.makeText(context, message, message.length()> TOAST_LONG_SIZE ? Toast.LENGTH_LONG:Toast.LENGTH_SHORT); TextView v = (TextView) toast.getView().findViewById(android.R.id.message); if( v != null) v.setGravity(Gravity.CENTER); toast.show(); } }
true
7d76a90444c457c7607ab87318f751b31d6c77df
Java
AlexiaTorres/eclipse
/HOJA_1/src/ej23.java
UTF-8
1,298
3.78125
4
[]
no_license
import java.util.Scanner; public class ej23 { public static void main(String[] args) { Scanner teclado=new Scanner(System.in); //ENTORNO /* * c1,c2 caracteres */ char c1,c2; //PROCESO /* * leer c1 * leer c2 * if (c1>='a' && c1<='z' && c2>='a' && c2<='z') visualizar "ambas son minusculas" end if else if (c1>='a' && c1<='z' && c2>='A' && c2<='Z') visualizar "solo la primnera es minuscula" end if else if (c1>='A' && c1<='Z' && c2>='a' && c2<='z') visualizar "solo la segunda es minuscula" end if else if (c1>='A' && c1<='Z' && c2>='A' && c2<='Z') end if * FIN */ System.out.println("Introduce el primer caracter:"); c1=teclado.next().charAt(0); System.out.println("Introduce el segundo caracter:"); c2=teclado.next().charAt(0); if (c1>='a' && c1<='z' && c2>='a' && c2<='z'){ System.out.println("ambas son minusculas"); }else if (c1>='a' && c1<='z' && c2>='A' && c2<='Z') { System.out.println("solo la primnera es minuscula"); }else if (c1>='A' && c1<='Z' && c2>='a' && c2<='z') { System.out.println("solo la segunda es minuscula"); }else if (c1>='A' && c1<='Z' && c2>='A' && c2<='Z') { System.out.println("ninguna es minuscula"); } }}
true
a7d27a4d432bfbc4cd652f5279a2389d2d308fb5
Java
ayeshx/Food-Ordering-App
/src/java/entities/Meal.java
UTF-8
4,569
2.171875
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 entities; import java.io.Serializable; import java.util.List; import javax.persistence.Basic; import javax.persistence.Column; import javax.persistence.Entity; import javax.persistence.GeneratedValue; import javax.persistence.GenerationType; import javax.persistence.Id; import javax.persistence.JoinColumn; import javax.persistence.JoinTable; import javax.persistence.ManyToMany; import javax.persistence.ManyToOne; import javax.persistence.NamedQueries; import javax.persistence.NamedQuery; import javax.persistence.Table; import javax.validation.constraints.NotNull; import javax.validation.constraints.Size; import javax.xml.bind.annotation.XmlRootElement; import javax.xml.bind.annotation.XmlTransient; /** * * @author Ayesh */ @Entity @Table(name = "MEAL") @XmlRootElement @NamedQueries({ @NamedQuery(name = "Meal.findAll", query = "SELECT m FROM Meal m") , @NamedQuery(name = "Meal.findByMealId", query = "SELECT m FROM Meal m WHERE m.mealId = :mealId") , @NamedQuery(name = "Meal.findByMealName", query = "SELECT m FROM Meal m WHERE m.mealName = :mealName") , @NamedQuery(name = "Meal.findByMealDescr", query = "SELECT m FROM Meal m WHERE m.mealDescr = :mealDescr") , @NamedQuery(name = "Meal.findByPrice", query = "SELECT m FROM Meal m WHERE m.price = :price")}) public class Meal implements Serializable { private static final long serialVersionUID = 1L; @Id @GeneratedValue(strategy = GenerationType.IDENTITY) @Basic(optional = false) @Column(name = "MEAL_ID") private Integer mealId; @Basic(optional = false) @NotNull @Size(min = 1, max = 30) @Column(name = "MEAL_NAME") private String mealName; @Basic(optional = false) @NotNull @Size(min = 1, max = 50) @Column(name = "MEAL_DESCR") private String mealDescr; @Basic(optional = false) @NotNull @Column(name = "PRICE") private double price; @ManyToMany(mappedBy = "mealList") private List<Orders> ordersList; @JoinColumn(name = "MEAL_PROMO", referencedColumnName = "PROMO_ID") @ManyToOne private Promotions mealPromo; @JoinColumn(name = "REST_ID", referencedColumnName = "REST_ID") @ManyToOne(optional = false) private Restaurant restId; public Meal() { } public Meal(Integer mealId) { this.mealId = mealId; } public Meal(Integer mealId, String mealName, String mealDescr, double price) { this.mealId = mealId; this.mealName = mealName; this.mealDescr = mealDescr; this.price = price; } public Integer getMealId() { return mealId; } public void setMealId(Integer mealId) { this.mealId = mealId; } public String getMealName() { return mealName; } public void setMealName(String mealName) { this.mealName = mealName; } public String getMealDescr() { return mealDescr; } public void setMealDescr(String mealDescr) { this.mealDescr = mealDescr; } public double getPrice() { return price; } public void setPrice(double price) { this.price = price; } @XmlTransient public List<Orders> getOrdersList() { return ordersList; } public void setOrdersList(List<Orders> ordersList) { this.ordersList = ordersList; } public Promotions getMealPromo() { return mealPromo; } public void setMealPromo(Promotions mealPromo) { this.mealPromo = mealPromo; } public Restaurant getRestId() { return restId; } public void setRestId(Restaurant restId) { this.restId = restId; } @Override public int hashCode() { int hash = 0; hash += (mealId != null ? mealId.hashCode() : 0); return hash; } @Override public boolean equals(Object object) { // TODO: Warning - this method won't work in the case the id fields are not set if (!(object instanceof Meal)) { return false; } Meal other = (Meal) object; if ((this.mealId == null && other.mealId != null) || (this.mealId != null && !this.mealId.equals(other.mealId))) { return false; } return true; } @Override public String toString() { return "entities2.Meal[ mealId=" + mealId + " ]"; } }
true
9da94ca000fa816e15b10d9b585ea01d5a6246c4
Java
ShimantoKabir/TourManagementSystem
/app/src/main/java/com/example/maask/tourmanagementsystem/NearbyFile/NearbyShowingAdapter.java
UTF-8
1,670
2.296875
2
[]
no_license
package com.example.maask.tourmanagementsystem.NearbyFile; import android.content.Context; import android.support.annotation.NonNull; import android.support.annotation.Nullable; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.ArrayAdapter; import android.widget.TextView; import com.example.maask.tourmanagementsystem.R; import java.util.List; /** * Created by Maask on 1/20/2018. */ public class NearbyShowingAdapter extends ArrayAdapter<NearbyResponse.Result> { private Context context; private List<NearbyResponse.Result>results; public NearbyShowingAdapter(@NonNull Context context, List<NearbyResponse.Result> results) { super(context, R.layout.single_nearby_places,results); this.context = context; this.results = results; } @NonNull @Override public View getView(int position, @Nullable View convertView, @NonNull ViewGroup parent) { LayoutInflater inflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE); convertView = inflater.inflate(R.layout.single_nearby_places,parent,false); TextView place_name = convertView.findViewById(R.id.nearby_name); TextView place_address = convertView.findViewById(R.id.nearby_address); TextView place_rating = convertView.findViewById(R.id.nearby_rating); place_name.setText(results.get(position).getName()); place_address.setText("Address : "+results.get(position).getVicinity()); place_rating.setText("Rating : "+String.valueOf(results.get(position).getRating())); return convertView; } }
true
29d70237066047c89e8959cc3f6a631b2d778843
Java
terryliu1994/springBootDemo
/src/main/java/com/springboot/demo01/hr/mapper/HrUnitMapper.java
UTF-8
337
1.820313
2
[]
no_license
package com.springboot.demo01.hr.mapper; import com.springboot.demo01.hr.dto.HrUnit; import java.util.List; public interface HrUnitMapper { int deleteByPrimaryKey(Long unitId); int insert(HrUnit record); HrUnit selectByPrimaryKey(Long unitId); List<HrUnit> selectAll(); int updateByPrimaryKey(HrUnit record); }
true
5ade3b2fb269f2a49ee90a4caa068543e94e1e11
Java
adiscehajic/bitcamp
/W05D04/src/ba/bitcamp/w05d04/exercises/tasks/Workstation.java
UTF-8
2,440
3.296875
3
[]
no_license
package ba.bitcamp.w05d04.exercises.tasks; /** * This class describes a single workstation. It is a subclass * StationaryComputer class. These computers are much more complex than standard * computers. Workstations are intended for research and scientific work with * many calculations. * * @author adis.cehajic * */ public class Workstation extends StationaryComputer { /* * Declaring properties of workstation */ private Integer numberOfDisplays; private Integer numberOfProcessorCores; private Boolean hasECCMemory; /** * Constructor * * @param systemName * @param ram * @param price * @param processorSpeed * @param powerPSU * @param capacityHDD * @param numberOfDisplays * @param numberOfProcessorCores * @param hasECCMemory */ public Workstation(String systemName, Integer ram, Integer price, Integer processorSpeed, Integer powerPSU, Integer capacityHDD, Integer numberOfDisplays, Integer numberOfProcessorCores, Boolean hasECCMemory) { super(systemName, ram, price, processorSpeed, powerPSU, capacityHDD); this.numberOfDisplays = numberOfDisplays; this.numberOfProcessorCores = numberOfProcessorCores; this.hasECCMemory = hasECCMemory; } /** * Prints information about workstation */ public void printInformation() { super.printInformation(); String s = ""; s += "Number of displays: " + numberOfDisplays + "\n"; s += "Number of processor cores: " + numberOfProcessorCores + "\n"; s += "Has ECC memory: " + hasECCMemory + "\n"; System.out.println(s); } /** * Printing information about workstations. */ public void printTypeInfo() { System.out .println("These computers are much more complex than standard computers. " + "Workstations are intended for research and scientific work with " + "many calculations."); } /* * Get methods */ public Integer getNumberOfDisplays() { return numberOfDisplays; } public Integer getNumberOfProcessorCores() { return numberOfProcessorCores; } public Boolean getHasECCMemory() { return hasECCMemory; } /* * Set methods */ public void setNumberOfDisplays(Integer numberOfDisplays) { this.numberOfDisplays = numberOfDisplays; } public void setNumberOfProcessorCores(Integer numberOfProcessorCores) { this.numberOfProcessorCores = numberOfProcessorCores; } public void setHasECCMemory(Boolean hasECCMemory) { this.hasECCMemory = hasECCMemory; } }
true
2288095fe6f00e4ba73b2eef8e69025f5518d5c5
Java
sunyujia21/Project_Rock
/hrbcgj/7.28更新版/hrbcgj/servicesapp/com/cityinspector/guide/dao/GuideDaoHibernate.java
UTF-8
2,012
2.453125
2
[]
no_license
package com.cityinspector.guide.dao; import java.util.List; import java.util.Map; import org.hibernate.Transaction; import org.springframework.stereotype.Repository; import com.cloud.base.jdbchibernate.JdbcHibernateUtil; import com.cityinspector.guide.model.Guide; @Repository public class GuideDaoHibernate extends JdbcHibernateUtil { /** * 通过id得到某个对象 * @param id * @return */ public Guide getGuideById(String id) { return (Guide)getDataObject(Guide.class,id); } /** * 保存 * @param user * @return */ public Guide saveGuide(Guide guide) { if(guide.getId() == null || guide.getId().equals("")) { saveData(guide); } else { saveOrUpdate(guide); } return guide; } /** * 批量保存数据 * @param list * @return */ public synchronized boolean saveDataBatch(List<Guide> list) { boolean flag = true; Transaction tx = beginTransaction(); try { for(int i=0;i<list.size();i++) { Guide guide = list.get(i); session.save(guide); if (i == list.size()-1) { session.flush(); session.clear(); } } tx.commit(); closeSession(); } catch(Exception e) { e.printStackTrace(); tx.rollback(); flag = false; } finally { return flag; } } /** * 列表查询 * @param curPage * @param pageSize * @param whereStr * @return */ public Map searchGuide(Long curPage, Long pageSize,String whereStr) { String hql = "FROM Guide guide"; return queryData2MapByPage(curPage, pageSize, hql, whereStr); } /** * 删除数据 * @param user * @return */ public Guide delGuide(Guide guide) { return (Guide)delData(guide); } /** * 批量删除 * @param user * @return */ public void delGuideBatch(List<String> list) { String delHql = "DELETE Guide "; delDataBatch(delHql,list); } /** * 通过条件查询数据(非分页) */ public List getAllDataByWhere(String where) { String hql = "FROM Guide guide where 1=1 " + where; return getDataList(hql); } }
true
bc6375c6358954aa513faddeaaede7a49a17524c
Java
treasure-data/airlift
/http-client/src/test/java/io/airlift/http/client/TestingHttpServer.java
UTF-8
4,330
1.960938
2
[ "Apache-2.0" ]
permissive
/* * 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 io.airlift.http.client; import com.google.common.net.HostAndPort; import jakarta.servlet.Servlet; import org.eclipse.jetty.http2.server.HTTP2CServerConnectionFactory; import org.eclipse.jetty.server.Handler; import org.eclipse.jetty.server.HttpConfiguration; import org.eclipse.jetty.server.HttpConnectionFactory; import org.eclipse.jetty.server.SecureRequestCustomizer; import org.eclipse.jetty.server.Server; import org.eclipse.jetty.server.ServerConnector; import org.eclipse.jetty.server.SslConnectionFactory; import org.eclipse.jetty.server.handler.HandlerCollection; import org.eclipse.jetty.server.handler.gzip.GzipHandler; import org.eclipse.jetty.servlet.ServletContextHandler; import org.eclipse.jetty.servlet.ServletHolder; import org.eclipse.jetty.util.ssl.SslContextFactory; import java.util.Optional; import java.util.function.Consumer; import static java.util.Objects.requireNonNull; public class TestingHttpServer implements AutoCloseable { private final Server server; private final HostAndPort hostAndPort; public TestingHttpServer(Optional<String> keystore, Servlet servlet) throws Exception { this(keystore, servlet, httpConfiguration -> {}, Optional.empty()); } public TestingHttpServer(Optional<String> keystore, Servlet servlet, Consumer<HttpConfiguration> configurationDecorator, Optional<Handler> additionalHandle) throws Exception { requireNonNull(keystore, "keyStore is null"); requireNonNull(servlet, "servlet is null"); Server server = new Server(); HttpConfiguration httpConfiguration = new HttpConfiguration(); httpConfiguration.setSendServerVersion(false); httpConfiguration.setSendXPoweredBy(false); configurationDecorator.accept(httpConfiguration); ServerConnector connector; if (keystore.isPresent()) { httpConfiguration.addCustomizer(new SecureRequestCustomizer()); SslContextFactory.Server sslContextFactory = new SslContextFactory.Server(); sslContextFactory.setKeyStorePath(keystore.get()); sslContextFactory.setKeyStorePassword("changeit"); SslConnectionFactory sslConnectionFactory = new SslConnectionFactory(sslContextFactory, "http/1.1"); connector = new ServerConnector(server, sslConnectionFactory, new HttpConnectionFactory(httpConfiguration)); } else { HttpConnectionFactory http1 = new HttpConnectionFactory(httpConfiguration); HTTP2CServerConnectionFactory http2c = new HTTP2CServerConnectionFactory(httpConfiguration); connector = new ServerConnector(server, http1, http2c); } connector.setIdleTimeout(30000); connector.setName(keystore.map(path -> "https").orElse("http")); server.addConnector(connector); ServletHolder servletHolder = new ServletHolder(servlet); ServletContextHandler context = new ServletContextHandler(ServletContextHandler.NO_SESSIONS); context.addServlet(servletHolder, "/*"); HandlerCollection handlers = new HandlerCollection(); additionalHandle.ifPresent(handlers::addHandler); handlers.addHandler(context); GzipHandler gzipHandler = new GzipHandler(); gzipHandler.setHandler(handlers); server.setHandler(gzipHandler); this.server = server; this.server.start(); this.hostAndPort = HostAndPort.fromParts("localhost", connector.getLocalPort()); } public HostAndPort getHostAndPort() { return hostAndPort; } @Override public void close() throws Exception { server.setStopTimeout(3000); server.stop(); } }
true
ba6d31e8bcac6d98ad0b724f478637117faa0118
Java
EvgeniyLukas/ShopHome
/src/main/java/com/company/lukas/model/Department.java
UTF-8
1,055
2.6875
3
[]
no_license
package company.lukas.model; import java.util.Set; public class Department extends BaseEntity{ String name; String type; Set<Seller> sellers; public Department(Long id) { super(id); } public Department(Long id, String name, String type, Set<Seller> sellers) { super(id); this.name = name; this.type = type; this.sellers = sellers; } public String getName() { return name; } public void setName(String name) { this.name = name; } public String getType() { return type; } public void setType(String type) { this.type = type; } public Set<Seller> getSellers() { return sellers; } public void setSellers(Set<Seller> sellers) { this.sellers = sellers; } @Override public String toString() { return "Department{" + "name='" + name + '\'' + ", type='" + type + '\'' + ", sellers=" + sellers + '}'; } }
true
aaaa7a5dc4c9d65fee3f05117389a0298b2443ce
Java
thoersch/lingo24-java-sdk
/src/main/java/com/thoersch/lingo24/representations/JobStatus.java
UTF-8
381
2.078125
2
[]
no_license
package com.thoersch.lingo24.representations; public enum JobStatus { NEW("NEW"), ANALYZING("ANALYZING"), QUOTED("QUOTED"), IN_PROGRESS("IN_PROGRESS"), TRANSLATED("TRANSLATED"), CANCELLED("CANCELLED"); JobStatus(String value) { this.value = value; } private String value; public String getValue() { return value; } }
true
4560b4874d27e3addc73b2b97d904cd2596dc91d
Java
atarw/programming-contest-solutions
/cco/2001/CCO_01_P1_THE_MONKEY_DANCE.java
UTF-8
2,558
3.390625
3
[]
no_license
import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import java.io.PrintWriter; public class CCO_01_P1_THE_MONKEY_DANCE { static int[] next; static boolean[] vis; public static int cycle (int u) { int cyc = 0; while (true) { vis[u] = true; if (vis[next[u]]) break; u = next[u]; ++cyc; } return cyc; } public static void main (String[] t) throws IOException { BufferedReader in = new BufferedReader (new InputStreamReader (System.in)); PrintWriter out = new PrintWriter (System.out); while (true) { int N = Integer.parseInt (in.readLine ()); if (N == 0) break; next = new int[N]; vis = new boolean[N]; for (int n = 0, a, b; n < N; ++n) { t = in.readLine ().split (" "); a = Integer.parseInt (t[0]) - 1; b = Integer.parseInt (t[1]) - 1; next[a] = b; } long lcm = 1; for (int n = 0; n < N; ++n) if (!vis[n]) lcm = UTILITIES.lcm (lcm, 1 + cycle (n)); out.println (lcm); } out.close (); } private static class UTILITIES { static final double EPS = 10e-6; public static int lower_bound (int[] arr, int x) { int low = 0, high = arr.length, mid = -1; while (low < high) { mid = (low + high) / 2; if (arr[mid] >= x) high = mid; else low = mid + 1; } return low; } public static int upper_bound (int[] arr, int x) { int low = 0, high = arr.length, mid = -1; while (low < high) { mid = (low + high) / 2; if (arr[mid] > x) high = mid; else low = mid + 1; } return low; } public static long gcd (long a, long b) { return b == 0 ? a : gcd (b, a % b); } public static long lcm (long a, long b) { return a * b / gcd (a, b); } public static int fast_pow_mod (int b, int x, int mod) { if (x == 0) return 1; if (x == 1) return b; if (x % 2 == 0) return fast_pow_mod (b * b % mod, x / 2, mod) % mod; return b * fast_pow_mod (b * b % mod, x / 2, mod) % mod; } public static int fast_pow (int b, int x) { if (x == 0) return 1; if (x == 1) return b; if (x % 2 == 0) return fast_pow (b * b, x / 2); return b * fast_pow (b * b, x / 2); } public static long choose (long n, long k) { k = Math.min (k, n - k); long val = 1; for (int i = 0; i < k; ++i) val = val * (n - i) / (i + 1); return val; } public static long permute (int n, int k) { if (n < k) return 0; long val = 1; for (int i = 0; i < k; ++i) val = (val * (n - i)); return val; } } }
true
b875f9640795e2847d0d7cb188111d5e94601618
Java
chenliguan/HeartGuardServer
/src/cn/itcast/dao/impl/SmsDaoMySQLImpl.java
GB18030
2,764
2.71875
3
[]
no_license
package cn.itcast.dao.impl; import java.sql.Connection; import java.sql.PreparedStatement; import java.sql.ResultSet; import cn.itcast.dao.SmsDao; import cn.itcast.domain.Sms; import cn.itcast.exception.DaoException; import cn.itcast.util.JdbcUtil; //PreparedStatementʵ֣Ԥ䣩 public class SmsDaoMySQLImpl implements SmsDao { /** * ֤뵽ݿ * @param username */ public void addCode(String username,int code) { System.out.println("CodeϢݿ"); Connection conn = null; PreparedStatement stmt = null; try{ conn = JdbcUtil.getConnection(); // 12 stmt = conn.prepareStatement("insert into codes (username,code) values(?,?)"); // 3 stmt.setString(1, username); // 롰 stmt.setInt(2, code); stmt.executeUpdate(); // 45 }catch(Exception e){ throw new DaoException(e); }finally{ JdbcUtil.release(null, stmt, conn); // 6 } } /** * ûѯcodes * ͨSms֤ */ public Sms findCodeByUsername(String username) { Connection conn = null; PreparedStatement stmt = null; ResultSet rs = null; try{ conn = JdbcUtil.getConnection(); stmt = conn.prepareStatement("select code from codes where username=?"); stmt.setString(1, username); rs = stmt.executeQuery(); if(rs.next()){ Sms sms = new Sms(); sms.setCode(rs.getString("code")); return sms; }else return null; }catch(Exception e){ throw new DaoException(e); }finally{ JdbcUtil.release(rs, stmt, conn); } } /** * ûѯUser * ͨSms */ public Sms findPasswordByUsername(String username) { Connection conn = null; PreparedStatement stmt = null; ResultSet rs = null; try{ conn = JdbcUtil.getConnection(); stmt = conn.prepareStatement("select password from user where username=?"); stmt.setString(1, username); rs = stmt.executeQuery(); if(rs.next()){ Sms sms = new Sms(); sms.setPassword(rs.getString("password")); return sms; }else return null; }catch(Exception e){ throw new DaoException(e); }finally{ JdbcUtil.release(rs, stmt, conn); } } /** * ֻ֤ */ public void updateCode(String username, int code) { Connection conn = null; PreparedStatement stmt = null; try{ conn = JdbcUtil.getConnection(); // 12 stmt = conn.prepareStatement("update codes set code = ? where username= ?"); // 3 stmt.setInt(1, code); // 롰 stmt.setString(2, username); stmt.executeUpdate(); // 45 }catch(Exception e){ throw new DaoException(e); }finally{ JdbcUtil.release(null, stmt, conn); // 6 } } }
true
1c0366e2f7e6384af4a2cb518393ef94e8804159
Java
cucu2000/Programming-Class-Code
/Database Design/Project 3/Project3Code/src/sample/Controller.java
UTF-8
12,041
2.578125
3
[]
no_license
package sample; import Common.DBHelper; import Models.CourseInstructorStudent; import Models.Student; import javafx.collections.FXCollections; import javafx.collections.ObservableList; import javafx.event.ActionEvent; import javafx.event.EventHandler; import javafx.fxml.FXML; import javafx.fxml.Initializable; import javafx.scene.control.*; import javafx.scene.control.cell.PropertyValueFactory; import javafx.scene.input.MouseEvent; import java.io.IOException; import java.net.URL; import java.sql.*; import java.util.Optional; import java.util.ResourceBundle; public class Controller implements Initializable { // Student table and columns @FXML public TableView<Student> tblStudent; @FXML public TableColumn<Student, String> colStudentID; @FXML public TableColumn<Student, String> colfName; @FXML public TableColumn<Student, String> collName; @FXML public TableColumn<Student, String> colMajor; @FXML public TableColumn<Student, String> colYear; @FXML public TableColumn<Student, String> colEmail; @FXML public TableColumn<Student, String> colPhone; // Classes table @FXML public TableView<CourseInstructorStudent> tblCourse; @FXML public TableColumn<CourseInstructorStudent, String> colCourseID; @FXML public TableColumn<CourseInstructorStudent, String> colInstructorID; @FXML public TableColumn<CourseInstructorStudent, String> colCStudentID; // text areas @FXML public TextField txtStudentID; @FXML public TextField txtfName; @FXML public TextField txtlName; @FXML public TextField txtMajor; @FXML public TextField txtYear; @FXML public TextField txtEmail; @FXML public TextField txtPhone; @FXML public TextField txtInstructorID; @FXML public TextField txtCourseID; // buttons @FXML public Button btnNew; @FXML public Button btnEdit; @FXML public Button btnDelete; @FXML public Button btnAddCourse; @FXML public Button btnDeleteCourse; @Override public void initialize(URL url, ResourceBundle rb) { setupStudentTable(); loadStudentTable(); setupClassTable(); } // initialize student table private void setupStudentTable() { // set up student columns colStudentID.setCellValueFactory(new PropertyValueFactory<>("studentID")); colfName.setCellValueFactory(new PropertyValueFactory<>("firstName")); collName.setCellValueFactory(new PropertyValueFactory<>("lastName")); colEmail.setCellValueFactory(new PropertyValueFactory<>("email")); colMajor.setCellValueFactory(new PropertyValueFactory<>("major")); colYear.setCellValueFactory(new PropertyValueFactory<>("year")); colPhone.setCellValueFactory(new PropertyValueFactory<>("phone")); } // initialize class table private void setupClassTable() { colInstructorID.setCellValueFactory(new PropertyValueFactory<>("instructorID")); colCourseID.setCellValueFactory(new PropertyValueFactory<>("courseID")); colCStudentID.setCellValueFactory(new PropertyValueFactory<>("studentID")); } // load student table private void loadStudentTable() { try { tblStudent.setItems(null); Connection conn = DBHelper.connect(); assert conn != null; Statement stmt = conn.createStatement(); ResultSet rs = stmt.executeQuery("SELECT * FROM student;"); ObservableList<Student> data = FXCollections.observableArrayList(); while(rs.next()) { Student st = new Student( rs.getString("studentID"), rs.getString("fName"), rs.getString("lName"), rs.getString("major"), rs.getString("year"), rs.getString("email"), rs.getString("phone")); data.add(st); } tblStudent.setItems(data); conn.close(); } catch (SQLException ex) { System.out.println(ex.getMessage()); } } // Load course table private void loadCourseTable() { try { tblCourse.setItems(null); Connection conn = DBHelper.connect(); assert conn != null; Statement stmt = conn.createStatement(); ResultSet rs = stmt.executeQuery("SELECT * FROM courseinstructorstudent WHERE studentID = '" + getPosition() + "';"); ObservableList<CourseInstructorStudent> data = FXCollections.observableArrayList(); while(rs.next()) { CourseInstructorStudent cis = new CourseInstructorStudent( rs.getString("courseID"), rs.getString("instructorID"), rs.getString("studentID")); data.add(cis); } tblCourse.setItems(data); conn.close(); } catch (SQLException ex) { System.out.println(ex.getMessage()); } } // update SQL database public void edit (ActionEvent actionEvent) throws IOException { try { Connection conn = DBHelper.connect(); String SQL = "UPDATE student SET " + "studentID=?, " + "fName=?, " + "lName=?, " + "major=?, " + "year=?, " + "email=?, " + "phone=? " + "WHERE studentID = ?"; assert conn != null; PreparedStatement pst = conn.prepareStatement(SQL); pst.setString(1, txtStudentID.getText()); pst.setString(2, txtfName.getText()); pst.setString(3, txtlName.getText()); pst.setString(4, txtMajor.getText()); pst.setString(5, txtYear.getText()); pst.setString(6, txtEmail.getText()); pst.setString(7, txtPhone.getText()); pst.setString(8, getPosition()); pst.executeUpdate(); loadStudentTable(); conn.close(); } catch (SQLException ex) { System.out.println(ex.getMessage()); } } public void deleteStudent(ActionEvent actionEvent) { Alert alert = new Alert(Alert.AlertType.CONFIRMATION); alert.setTitle("Delete"); alert.setHeaderText("Delete Record"); alert.setContentText("Are you sure you want to delete?"); ButtonType buttonTypeYes = new ButtonType("Yes"); ButtonType buttonTypeNo = new ButtonType("No", ButtonBar.ButtonData.CANCEL_CLOSE); alert.getButtonTypes().setAll(buttonTypeYes, buttonTypeNo); Optional<ButtonType> result = alert.showAndWait(); if (result.get() == buttonTypeYes){ try { Connection conn = DBHelper.connect(); String SQL = "DELETE FROM student WHERE studentID=?;"; assert conn != null; PreparedStatement pst = conn.prepareStatement(SQL); pst.setString(1, getPosition()); pst.execute(); conn.close(); loadStudentTable(); } catch (SQLException ex) { System.out.println(ex.getMessage()); } } else { // ... user chose CANCEL or closed the dialog } } // add new student to database public void newStudent (ActionEvent actionEvent) throws IOException { try { Connection conn = DBHelper.connect(); String SQL = "INSERT INTO student " + "VALUES(?, ?, ?, ?, ?, ?, ?)"; assert conn != null; PreparedStatement pst = conn.prepareStatement(SQL); pst.setString(1, txtStudentID.getText()); pst.setString(2, txtfName.getText()); pst.setString(3, txtlName.getText()); pst.setString(4, txtMajor.getText()); pst.setString(5, txtYear.getText()); pst.setString(6, txtEmail.getText()); pst.setString(7, txtPhone.getText()); pst.executeUpdate(); loadStudentTable(); conn.close(); } catch (SQLException ex) { System.out.println(ex.getMessage()); } } // get student ID for SQL Queries private String getPosition() { TablePosition pos = (TablePosition)tblStudent.getSelectionModel().getSelectedCells().get(0); int index = pos.getRow(); Student selected = tblStudent.getItems().get(index); String selectString = selected.getStudentID(); return selectString; } // call selected student in table for value calls private Student getStudent() { TablePosition pos = (TablePosition)tblStudent.getSelectionModel().getSelectedCells().get(0); int index = pos.getRow(); Student selected = tblStudent.getItems().get(index); return selected; } // get Course ID for SQL queries private String getCoursePosition() { TablePosition pos = (TablePosition)tblCourse.getSelectionModel().getSelectedCells().get(0); int index = pos.getRow(); CourseInstructorStudent selected = tblCourse.getItems().get(index); String selectString = selected.getCourseID(); return selectString; } public void deleteCourse(ActionEvent actionEvent) { Alert alert = new Alert(Alert.AlertType.CONFIRMATION); alert.setTitle("Delete"); alert.setHeaderText("Delete Record"); alert.setContentText("Are you sure you want to delete?"); ButtonType buttonTypeYes = new ButtonType("Yes"); ButtonType buttonTypeNo = new ButtonType("No", ButtonBar.ButtonData.CANCEL_CLOSE); alert.getButtonTypes().setAll(buttonTypeYes, buttonTypeNo); Optional<ButtonType> result = alert.showAndWait(); if (result.get() == buttonTypeYes){ try { Connection conn = DBHelper.connect(); String SQL = "DELETE FROM courseinstructorstudent WHERE studentID=? AND courseID =?"; assert conn != null; PreparedStatement pst = conn.prepareStatement(SQL); pst.setString(1, getPosition()); pst.setString(2, getCoursePosition()); pst.execute(); conn.close(); loadCourseTable(); } catch (SQLException ex) { System.out.println(ex.getMessage()); } } else { // ... user chose CANCEL or closed the dialog } } // add new course to selected student public void newCourse(ActionEvent actionEvent) { try { Connection conn = DBHelper.connect(); String SQL = "INSERT INTO courseinstructorstudent " + "VALUES(?, ?, ?)"; assert conn != null; PreparedStatement pst = conn.prepareStatement(SQL); pst.setString(1, txtCourseID.getText()); pst.setString(2, txtInstructorID.getText()); pst.setString(3, getPosition()); pst.executeUpdate(); loadCourseTable(); conn.close(); } catch (SQLException ex) { System.out.println(ex.getMessage()); } } // load the classes when clicking on a student, and putting info in text fields public void clickView() { tblStudent.setOnMouseClicked(new EventHandler<MouseEvent>() { @Override public void handle(MouseEvent mouseEvent) { loadCourseTable(); txtStudentID.setText(getStudent().getStudentID()); txtfName.setText(getStudent().getFirstName()); txtlName.setText(getStudent().getLastName()); txtMajor.setText(getStudent().getMajor()); txtEmail.setText(getStudent().getEmail()); txtYear.setText(getStudent().getYear()); txtPhone.setText(getStudent().getPhone()); } }); } }
true
069d048c6240d641e40b22066cff2be246a2865c
Java
hudyc1/rewards
/src/main/java/com/cyberdesign/rewards/model/Product.java
UTF-8
2,695
2.609375
3
[]
no_license
package com.cyberdesign.rewards.model; import java.util.Date; import java.util.UUID; import org.joda.time.DateTime; import org.joda.time.format.DateTimeFormat; import org.joda.time.format.DateTimeFormatter; public class Product { String productId; String name; String description; int points; DateTime effectiveStart; DateTime effectiveEnd; Date startDate; Date endDate; DateTimeFormatter dtFormatter = DateTimeFormat.forPattern("yyyy-MM-dd"); public Product(String name) { super(); productId = UUID.randomUUID().toString(); this.name = name; } public Product(String name, String description, int points, DateTime effectiveStart, DateTime effectiveEnd) { super(); productId = UUID.randomUUID().toString(); this.name = name; this.description = description; this.points = points; this.effectiveStart = effectiveStart; this.effectiveEnd = effectiveEnd; this.startDate = effectiveStart.toDate(); this.endDate = effectiveEnd.toDate(); } public Product() { // TODO Auto-generated constructor stub } public String getProductId() { return productId; } public void setProductId(String productId) { this.productId = productId; } public void setProductId() { productId = UUID.randomUUID().toString(); } public String getName() { return name; } public void setName(String name) { this.name = name; } public String getDescription() { return description; } public void setDescription(String description) { this.description = description; } public int getPoints() { return points; } public void setPoints(int points) { this.points = points; } public DateTime getEffectiveStart() { return effectiveStart; } public void setEffectiveStart(DateTime effectiveStart) { this.effectiveStart = effectiveStart; this.startDate = effectiveStart.toDate(); } public DateTime getEffectiveEnd() { return effectiveEnd; } public void setEffectiveEnd(DateTime effectiveEnd) { this.effectiveEnd = effectiveEnd; this.endDate = effectiveEnd.toDate(); } public Date getStartDate() { return startDate; } public Date getEndDate() { return endDate; } /*public void setStartDate(Date startDate) { this.effectiveStart = new DateTime(startDate); this.startDate = effectiveStart.toDate(); } public void setEndDate(Date endDate) { this.effectiveEnd = new DateTime(endDate); this.endDate = effectiveEnd.toDate(); }*/ public void setStartDate(String startDate) { this.effectiveStart = new DateTime(startDate); this.startDate = effectiveStart.toDate(); } public void setEndDate(String endDate) { this.effectiveEnd = new DateTime(endDate); this.endDate = effectiveEnd.toDate(); } }
true
eba46bcba090b825532207e2fcc71dd4d68b2986
Java
zimenglan-sysu/DoubanApi
/src/org/nirvawolf/douban/api/song/Request.java
UTF-8
859
2.078125
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 org.nirvawolf.douban.api.song; import org.nirvawolf.douban.util.GlobleVarables; /** * * @author bruce */ public abstract class Request { private final String appName = "radio_desktop_win"; private final String version = "100"; protected String apiAddress = GlobleVarables.apiProtocool + "://" + GlobleVarables.apiDomainName + "/j/app/radio/people"; protected RequestDelegate delegate; public Request(RequestDelegate delegate) { apiAddress = apiAddress + "?app_name=" + appName + "&version=" + version; this.delegate = delegate; } abstract public void attemptToRequest(); }
true
6a33a3c36090bfea457a7be5cbb8e8e963642454
Java
hippalus/courier-tracking
/courier-geo-locations/src/main/java/com/courier/geolocations/configuration/FileProperties.java
UTF-8
529
1.53125
2
[]
no_license
package com.courier.geolocations.configuration; import lombok.Getter; import org.springframework.boot.context.properties.ConfigurationProperties; import org.springframework.boot.context.properties.EnableConfigurationProperties; import org.springframework.context.annotation.Configuration; import java.util.ArrayList; import java.util.List; @Configuration @EnableConfigurationProperties @ConfigurationProperties(prefix = "data") @Getter public class FileProperties { private List<String> filePaths = new ArrayList<>(); }
true
d6d937ff9b6cc852f93edd557176c833ae8a547c
Java
YYpp1220/jiavideo
/jv-register/src/main/java/com/jiavideo/JvRegisterApplication.java
UTF-8
678
1.851563
2
[]
no_license
package com.jiavideo; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.SpringBootApplication; import org.springframework.cloud.netflix.eureka.server.EnableEurekaServer; /** * 启动类 * @author Lenovo */ @SpringBootApplication @EnableEurekaServer public class JvRegisterApplication { /*private static final Logger LOG = LoggerFactory.getLogger(JvRegisterApplication.class);*/ public static void main(String[] args){ // 运行spring应用 SpringApplication.run(JvRegisterApplication.class, args); /*LOG.info("启动成功");*/ } }
true
e45872ce210902e11ebab08f3aa92119fd436356
Java
cotyboom/ISS---5D
/src/main/java/ro/ProiectISS/enumerable/Rol.java
UTF-8
93
1.867188
2
[]
no_license
package ro.ProiectISS.enumerable; public enum Rol { DOCTOR, DONATOR, PERSONAL }
true
7c3d0af1ac2427aca662fe70e97ec9e2d5b4e45b
Java
qingyunhui/daocaore
/cn.com.daocaore.bms/cn.com.daocaore.bms.common/src/main/java/cn/com/daocaore/bms/common/bean/DataTableInfo.java
UTF-8
1,505
2.328125
2
[]
no_license
package cn.com.daocaore.bms.common.bean; import java.io.Serializable; import java.util.List; import javax.servlet.http.HttpServletRequest; import lombok.Getter; import lombok.Setter; /*** ** @category 该对象中的属性必须与前端dataTable保持一致... ** @author qing.yunhui ** @email: 280672161@qq.com ** @createTime: 2017年5月17日上午10:28:18 **/ @Getter @Setter public class DataTableInfo <T> implements Serializable{ private static final long serialVersionUID = 1L; private List<T> data; //查询分页的数据集 private int recordsTotal;// 总记录数 private int recordsFiltered;// 过滤后的总记录数 private int startRow;//开始行 private int pageSize;////每页大小 private Boolean isPaging; //分页标识(true标识分页,false标识不分页) private int draw;//请求次数 private int pageCount;//总页数 public DataTableInfo(){} public DataTableInfo(HttpServletRequest request){ String startRow = request.getParameter("startRow");//开始的数据行数 String pageSize = request.getParameter("pageSize");//每页的数据数 // String draw = request.getParameter("draw");//DT传递的draw: this.setStartRow(Integer.parseInt(startRow)); this.setPageSize(Integer.parseInt(pageSize)); // this.setDraw(Integer.parseInt(draw)); this.pageCount = (Integer.parseInt(startRow) / Integer.parseInt(pageSize)) + 1; //计算页码 } }
true
256280b9a69e9fa984c9982bf1fe4fade898a574
Java
curtys/webprotege-attestation
/webprotege-client/src/main/java/edu/stanford/bmir/protege/web/client/viz/EntityGraphSettingsView.java
UTF-8
709
1.625
2
[ "BSD-2-Clause" ]
permissive
package edu.stanford.bmir.protege.web.client.viz; import com.google.gwt.user.client.ui.AcceptsOneWidget; import com.google.gwt.user.client.ui.IsWidget; import javax.annotation.Nonnull; /** * Matthew Horridge * Stanford Center for Biomedical Informatics Research * 2019-12-08 */ public interface EntityGraphSettingsView extends IsWidget { @Nonnull AcceptsOneWidget getFilterListContainer(); void setApplySettingsHandler(Runnable runnable); void setCancelSettingsHandler(Runnable runnable); void setApplySettingsAsProjectDefaultHandler(Runnable runnable); void setApplySettingsAsProjectDefaultVisible(boolean b); double getRankSpacing(); void setRankSpacing(double value); }
true
349827d2488c86c02a064b3f91e498a5439d237c
Java
Reddy6264/BookMySpot
/app/src/main/java/com/infinx/webservices/AppConfig.java
UTF-8
3,381
1.6875
2
[]
no_license
/******************************************************************************* * Copyright (c) 2014, INFINX (TIS Pvt. * Ltd.)(www.infinxservices.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.infinx.webservices; import java.text.SimpleDateFormat; /** * @author : MADHU REDDY KR * @email : madhusudhana.reddy@infinxservices.com * @mob : +91-9699221355,+91-9849221355 Created On 02-Sep-2014 11:20:20 AM */ public class AppConfig { public static final String URL = "http://114.79.155.219/BookMySlot/BookMySlotService.svc"; public static final String NAMESPACE = "http://tempuri.org/"; public static String SOAP_NAMESPACE = "http://tempuri.org/"; public static String ServiceContract = "http://tempuri.org/IBookMySlotService/"; // --------------- Time & Date Formats // ----------------- public static final String DATE_FORMAT = "yyyy-MM-dd"; public static final String DATE_FORMAT_YYYY_MM_DD = "yyyy-MM-dd"; public static final String DATE_FORMAT_DD_MM_YYYY = "dd-MM-yyyy"; public static final String TIME_FORMAT = "kk:mm a"; public static final String DATE_TIME_FORMAT = "yyyy-MM-dd kk:mm"; public static final String DATE_TIME_FORMAT_AA = "yyyy-MM-dd hh:mm aa"; public static final String DATE_TIME_FORMAT_DISPLAY_AA = "dd-MM-yyyy hh:mm aa"; public static final String DATE_TIME_FORMAT_DD_MMM_YYYY_HH_MM_AA = "dd-MMM-yyyy hh:mm aa"; public static final String DATE_TIME_FORMAT_YYYY_MM_DD_HH_MM_SS = "yyyy-MM-dd HH:mm:ss"; public static final String DATE_FORMAT_YYYY_MM_DD_HH_MM = "yyyy-MM-dd hh:mm"; public static final String DATE_TIME_FORMAT_MM_DD_YYYY_ = "dd-MM-yyyy hh:mm aa";// edit public static final SimpleDateFormat DISPLAY_DATE_FORMAT1 = new SimpleDateFormat( "yyyy-MM-dd"); public static final SimpleDateFormat DISPLAY_DATE_FORMAT2 = new SimpleDateFormat( "dd-MMM-yyyy"); public static final SimpleDateFormat DISPLAY_DATE_FORMAT3 = new SimpleDateFormat( "dd-MM-yyyy"); public static final SimpleDateFormat DISPLAY_TIME_FORMAT = new SimpleDateFormat( "hh:mm aa"); public static final SimpleDateFormat DISPLAY_DATE_TIME_FORMAT = new SimpleDateFormat( "dd-MMM-yyyy hh:mm aa"); public static final SimpleDateFormat DISPLAY_DATE_TIME_FORMAT_DD_MM = new SimpleDateFormat( "dd-MM-yyyy hh:mm aa"); public static final SimpleDateFormat YYYY_MM_DD_HH_MM_AA = new SimpleDateFormat( "yyyy-MM-dd hh:mm aa"); public static final SimpleDateFormat YYYY_MM_DD_HH_MM_24 = new SimpleDateFormat( "yyyy-MM-dd hh:mm"); public static final SimpleDateFormat YYYY_MM_DD_HH_MM_SS = new SimpleDateFormat( "yyyy-MM-dd HH:mm:ss"); public static String FONT_TREBUC = "trebuc.ttf"; public static String FONT_TREBUCD = "trebucbd.ttf"; public static String FONT_TREBUCBI = "trebucbi.ttf"; public static String FONT_TREBUCIT = "trebucit.ttf"; }
true
e408f880aae099838c7b15653933309515b66a3a
Java
hncboy/LeetCode
/src/com/hncboy/FindBottomLeftTreeValue.java
UTF-8
2,358
3.734375
4
[ "Apache-2.0" ]
permissive
package com.hncboy; import java.util.LinkedList; import java.util.Queue; /** * @author hncboy * @date 2021/11/23 9:28 * @description 513.找树左下角的值 * * 给定一个二叉树的 根节点 root,请找出该二叉树的 最底层 最左边 节点的值。 * 假设二叉树中至少有一个节点。 * * 示例 1: * 输入: root = [2,1,3] * 输出: 1 * * 示例 2: * 输入: [1,2,3,4,null,5,6,null,null,7] * 输出: 7 * * 提示: * 二叉树的节点个数的范围是 [1,104] * -231 <= Node.val <= 231 - 1 * * 通过次数 55,957 提交次数 76,520 * * 来源:力扣(LeetCode) * 链接:https://leetcode-cn.com/problems/find-bottom-left-tree-value * 著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。 */ public class FindBottomLeftTreeValue { public static void main(String[] args) { TreeNode node = new TreeNode(2); node.left = new TreeNode(1); node.right = new TreeNode(3); FindBottomLeftTreeValue f = new FindBottomLeftTreeValue(); System.out.println(f.findBottomLeftValue(node)); } public int findBottomLeftValue(TreeNode root) { if (root == null) { return -1; } Queue<TreeNode> queue = new LinkedList<>(); queue.add(root); // 存储每一层最左边的值 int leftValue = root.val; // 层序遍历 while (!queue.isEmpty()) { // 当前层的节点数量 int count = queue.size(); leftValue = queue.peek().val; // 对每一层的元素进行遍历 for (int i = 0; i < count; i++) { TreeNode node = queue.poll(); if (node.left != null) { queue.add(node.left); } if (node.right != null) { queue.add(node.right); } } } return leftValue; } private static class TreeNode { int val; TreeNode left; TreeNode right; TreeNode() { } TreeNode(int val) { this.val = val; } TreeNode(int val, TreeNode left, TreeNode right) { this.val = val; this.left = left; this.right = right; } } }
true
07f7891e003c800457d34ec74b1649952123d695
Java
Vahann/newsBlog
/src/main/java/servlet/LogServlet.java
UTF-8
774
2.34375
2
[]
no_license
package servlet; import manager.NewsManager; import model.News; import javax.servlet.ServletException; import javax.servlet.annotation.WebServlet; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import java.io.IOException; import java.util.List; @WebServlet(urlPatterns = "/log") public class LogServlet extends HttpServlet { private NewsManager newsManager = new NewsManager(); @Override protected void service(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { List<News> news = newsManager.getNews(); req.setAttribute("news", news); req.getRequestDispatcher("/WEB-INF/home.jsp").forward(req, resp); } }
true
f457b4ba1786aa2bb229a5d27420f470a48b7a69
Java
1583734440/delay-queue
/delay-queue-pro/src/main/java/com/delay/queue/producer/tasktest/Task.java
UTF-8
628
2.265625
2
[]
no_license
package com.delay.queue.producer.tasktest; import org.springframework.scheduling.annotation.Async; import org.springframework.stereotype.Component; /** * @Description TODO * @Date 2021/4/8 10:58 * @Author FU */ @Component public class Task { @Async("taskExecutor") public void doTaskOne(){ System.out.println("开始任务"); long start = System.currentTimeMillis(); try { Thread.sleep(5000); } catch (InterruptedException e) { e.printStackTrace(); } long end = System.currentTimeMillis(); System.out.println("结束任务"); } }
true
5e3837069ad2289a59ade73c79bf50562412b9d1
Java
sunafei/hr-api
/src/main/java/com/eplugger/core/query/JoinExpression.java
UTF-8
1,275
2.515625
3
[]
no_license
package com.eplugger.core.query; import lombok.AllArgsConstructor; import lombok.NoArgsConstructor; import javax.persistence.criteria.CriteriaBuilder; import javax.persistence.criteria.CriteriaQuery; import javax.persistence.criteria.Predicate; import javax.persistence.criteria.Root; import java.util.ArrayList; import java.util.List; /** * 联合表达式 * * @auther: SunAFei * @date: 2018/5/19 10:21 */ @NoArgsConstructor @AllArgsConstructor public class JoinExpression<T> implements Criterion<T> { private Criterion[] criterion; // 连接条件 多个 private String relation; // 连接类型 and/or @Override public Predicate toPredicate(Root<T> root, CriteriaQuery<?> query, CriteriaBuilder builder) { List<Predicate> predicates = new ArrayList<Predicate>(); for (int i = 0; i < this.criterion.length; i++) { predicates.add(this.criterion[i].toPredicate(root, query, builder)); } switch (relation) { case OR: return builder.or(predicates.toArray(new Predicate[predicates.size()])); case AND: return builder.and(predicates.toArray(new Predicate[predicates.size()])); default: return null; } } }
true
2b9902c90724262c3accebd145fa9eb95aa55635
Java
JVMR/Unknow
/src/entidad/UnidadOrganica.java
UTF-8
817
2.15625
2
[]
no_license
package entidad; public class UnidadOrganica { private String idUnidadOrganica; private String descripcionUnidad; private String idCargo; private String nombreUnidad; public String getIdUnidadOrganica() { return idUnidadOrganica; } public void setIdUnidadOrganica(String idUnidadOrganica) { this.idUnidadOrganica = idUnidadOrganica; } public String getDescripcionUnidad() { return descripcionUnidad; } public void setDescripcionUnidad(String descripcionUnidad) { this.descripcionUnidad = descripcionUnidad; } public String getIdCargo() { return idCargo; } public void setIdCargo(String idCargo) { this.idCargo = idCargo; } public String getNombreUnidad() { return nombreUnidad; } public void setNombreUnidad(String nombreUnidad) { this.nombreUnidad = nombreUnidad; } }
true
fb753e97ca28b9d03df7f361b11c1c947f2ad2ca
Java
carpenlc/legacy-EFD
/src/java/com/solers/delivery/content/consumer/InventoryRetriever.java
UTF-8
10,672
1.851563
2
[]
no_license
/**************************************************************** * * Solers, Inc. as the author of Enterprise File Delivery 2.1 (EFD 2.1) * source code submitted herewith to the Government under contract * retains those intellectual property rights as set forth by the Federal * Acquisition Regulations agreement (FAR). The Government has * unlimited rights to redistribute copies of the EFD 2.1 in * executable or source format to support operational installation * and software maintenance. Additionally, the executable or * source may be used or modified for by third parties as * directed by the government. * * (c) 2009 Solers, Inc. ***********************************************************/ package com.solers.delivery.content.consumer; import java.io.File; import java.io.FileFilter; import java.io.FileInputStream; import java.io.FileNotFoundException; import java.io.FileOutputStream; import java.io.IOException; import java.util.ArrayList; import java.util.Collections; import java.util.List; import java.util.Observable; import java.util.zip.GZIPInputStream; import org.apache.commons.io.IOUtils; import org.apache.log4j.Logger; import org.apache.tools.tar.TarEntry; import org.apache.tools.tar.TarInputStream; import org.springframework.beans.factory.annotation.Configurable; import com.solers.delivery.domain.ConsumerContentSet; import com.solers.delivery.inventory.InventoryFactory; import com.solers.delivery.transport.http.client.Transfer; import com.solers.delivery.transport.http.client.TransferInventory; import com.solers.delivery.transport.http.client.TransferService; /** * InventoryRetriever is used to retrieve inventories. It is used as part of the SynchronizationTask to backup the existing inventory, request a new inventory, * and the unpackage that inventory to the correct location. * * @author JGimourginas */ @Configurable("inventoryRetriever") public class InventoryRetriever extends Observable { private static final Logger log = Logger.getLogger(InventoryRetriever.class); private static final boolean IS_DEBUG_ENABLED = log.isDebugEnabled(); private static final int BUFFER_SIZE = 1024 * 1024; private int numBackups; public void setNumBackups(int numBackups) { this.numBackups = numBackups; } /** * Method to retrieve and extract the Inventory from the Supplier that manages the content set with which the SynchronizationTask must interact. If a * packaged inventory exists, the method will back it up. The new packaged Inventory is then placed in the same directory. Its contents are extracted to the * open inventory location for this consumer. Unlike the packaged inventory, no backup is made of the open inventory files. The boolean return value is in * place to prevent further execution if Inventory retrieval/extraction fails. * * @return true if Inventory retrieved, false otherwise */ public InventoryResult getNewInventory(ConsumerContentSet contentSet, long timestamp, TransferService transferService, String syncId) { String consumerContentSetName = contentSet.getName(); String supplierContentSetName = contentSet.getSupplierName(); if (IS_DEBUG_ENABLED) log.debug("Getting new inventory for " + consumerContentSetName); String packagedInventoryPath = InventoryFactory.getPackage(contentSet).getAbsolutePath(); String openInventoryDirPath = InventoryFactory.getOpenLocation(contentSet).getAbsolutePath(); // need to backup existing before overwriting with new inventory backupExistingPackagedInventory(packagedInventoryPath); // create transfer for inventory - Transport will stream directly to file system location, which is why backup // must be done first notifyObservers(State.REQUESTING); TransferInventory transfer = createInventoryTransfer(packagedInventoryPath, supplierContentSetName, timestamp, syncId); if (IS_DEBUG_ENABLED) log.debug("Making inventory request for " + consumerContentSetName); transfer = (TransferInventory)transferService.process(transfer); if (IS_DEBUG_ENABLED) log.debug("Got response for inventory request for " + consumerContentSetName); if (transfer == null) { return new InventoryResult(false, Transfer.Status.FAILED_TRANSFER); } if (transfer.failed()) { return new InventoryResult(false, transfer.getStatus()); } if (transfer.isNotModified()) { log.info("No changes in inventory for " + consumerContentSetName); return new InventoryResult(true, transfer.getStatus()); } File packagedInventory = new File(packagedInventoryPath); File openInventoryDirectory = new File(openInventoryDirPath); // if this directory does not exist, make it openInventoryDirectory.mkdirs(); //Extract the inventory data sent from the Supplier notifyObservers(State.UNARCHIVING); List<File> entries = Collections.emptyList(); try { entries = extractNewInventory(packagedInventory, openInventoryDirectory); //Fail if there were no entries in the bundle- an error condition. if (entries.size() == 0) { log.error("There were no entries in the provided bundle."); return new InventoryResult(false, transfer.getStatus()); } //A single entry may be a complete inventory if (entries.size() == 1) { if (entries.get(0).getName().endsWith(InventoryFactory.INDEX_EXTENSION)) { //we don't need to do any more. InventoryFactory scans for the latest //inventory and deletes stale entries. return new InventoryResult(true, transfer.getStatus()); } } //We have diffs, not an inventory, so apply them log.info(String.format("Merging %d differences into inventory for %s", entries.size(), consumerContentSetName)); notifyObservers(State.MERGING); long retval = InventoryFactory.applyDifferences( contentSet, entries.toArray(new File[entries.size()]) ); return new InventoryResult((retval > -1), transfer.getStatus()); } catch (IOException ioe) { log.error("Failed to extract new inventory.", ioe); return new InventoryResult(false, transfer.getStatus()); } finally { //Clean up unused difference files. notifyObservers(State.CLEANUP); File[] diffs = openInventoryDirectory.listFiles(new FileFilter() { @Override public boolean accept(File pathname) { return pathname.isFile() && pathname.getName().endsWith(InventoryFactory.DIFF_EXTENSION); } }); for (File diff : diffs) { boolean success = diff.delete(); if (!success) diff.deleteOnExit(); } } } private List<File> extractNewInventory(File packagedInventory, File openInventoryDirectory) throws IOException { List<File> entries = new ArrayList<File>(); FileInputStream in = null; FileOutputStream fos = null; TarInputStream tIn = null; try { in = new FileInputStream(packagedInventory); tIn = new TarInputStream(new GZIPInputStream(in)); TarEntry entry = null; while ((entry = tIn.getNextEntry()) != null) { File next = new File(openInventoryDirectory, entry.getName()); entries.add(next); fos = new FileOutputStream(next); byte[] buffer = new byte[BUFFER_SIZE]; int length = 0; while ((length = tIn.read(buffer)) >= 0) { fos.write(buffer, 0, length); } fos.close(); fos = null; } if (IS_DEBUG_ENABLED) log.debug("Inventory successfully extracted to " + openInventoryDirectory); return entries; } catch (FileNotFoundException e) { log.error("Could not find Packaged Inventory file: " + e.getMessage()); } finally { IOUtils.closeQuietly(in); IOUtils.closeQuietly(fos); IOUtils.closeQuietly(tIn); } return entries; } /** * Creats a backup of the existing packaged inventory for tracking. * * @param path * path to existing packaged inventory */ private void backupExistingPackagedInventory(String path) { notifyObservers(State.BACKUP); if (IS_DEBUG_ENABLED) log.debug("Backing up inventory: " + path); File packagedInventoryFile = new File(path); if (packagedInventoryFile.exists()) { File backup = new File(packagedInventoryFile.getPath() + "_" + System.currentTimeMillis() + ".bak"); packagedInventoryFile.renameTo(backup); File[] existingFiles = packagedInventoryFile.getParentFile().listFiles(); if (existingFiles.length > numBackups) { int numToDelete = existingFiles.length - numBackups; for (int i = 0; i < numToDelete; i++) { // listing will show the oldest backup first, so remove starting with the oldest existingFiles[i].delete(); } } } } /** * Creates a Transfer object for an Inventory request. The returned Transfer contains all the necessary fields need by the TransferService to obtain the * Inventory and place it on the file system. * * @return Transfer object that should be used to make an Inventory request. */ private TransferInventory createInventoryTransfer(String packagedInventoryPath, String supplierContentSetName, long timestamp, String syncId) { return new TransferInventory(packagedInventoryPath, supplierContentSetName, timestamp, syncId); } private enum State { BACKUP, REQUESTING, UNARCHIVING, MERGING, CLEANUP } }
true
939fa7f9edb8570e66945bbcf438c756148d9b84
Java
zhuharev/periscope-android-source
/src/retrofit/RequestBuilder.java
UTF-8
22,848
1.84375
2
[]
no_license
// Decompiled by Jad v1.5.8e. Copyright 2001 Pavel Kouznetsov. // Jad home page: http://www.geocities.com/kpdus/jad.html // Decompiler options: braces fieldsfirst space lnc package retrofit; import java.io.OutputStream; import java.io.UnsupportedEncodingException; import java.lang.annotation.Annotation; import java.lang.reflect.Array; import java.net.URLEncoder; import java.util.ArrayList; import java.util.Collections; import java.util.Iterator; import java.util.List; import java.util.Map; import java.util.Set; import retrofit.client.Header; import retrofit.client.Request; import retrofit.converter.Converter; import retrofit.http.Body; import retrofit.http.EncodedPath; import retrofit.http.EncodedQuery; import retrofit.http.EncodedQueryMap; import retrofit.http.Field; import retrofit.http.FieldMap; import retrofit.http.Part; import retrofit.http.PartMap; import retrofit.http.Path; import retrofit.http.Query; import retrofit.http.QueryMap; import retrofit.mime.FormUrlEncodedTypedOutput; import retrofit.mime.MultipartTypedOutput; import retrofit.mime.TypedOutput; import retrofit.mime.TypedString; // Referenced classes of package retrofit: // RestMethodInfo final class RequestBuilder implements RequestInterceptor.RequestFacade { static class MimeOverridingTypedOutput implements TypedOutput { private final TypedOutput _flddelegate; private final String mimeType; public String fileName() { return _flddelegate.fileName(); } public long length() { return _flddelegate.length(); } public String mimeType() { return mimeType; } public void writeTo(OutputStream outputstream) { _flddelegate.writeTo(outputstream); } MimeOverridingTypedOutput(TypedOutput typedoutput, String s) { _flddelegate = typedoutput; mimeType = s; } } private final String apiUrl; private TypedOutput body; private String contentTypeHeader; private final Converter converter; private final FormUrlEncodedTypedOutput formBody; private List headers; private final boolean isObservable; private final boolean isSynchronous; private final MultipartTypedOutput multipartBody; private final Annotation paramAnnotations[]; private StringBuilder queryParams; private String relativeUrl; private final String requestMethod; RequestBuilder(String s, RestMethodInfo restmethodinfo, Converter converter1) { apiUrl = s; converter = converter1; paramAnnotations = restmethodinfo.requestParamAnnotations; requestMethod = restmethodinfo.requestMethod; isSynchronous = restmethodinfo.isSynchronous; isObservable = restmethodinfo.isObservable; if (restmethodinfo.headers != null) { headers = new ArrayList(restmethodinfo.headers); } contentTypeHeader = restmethodinfo.contentTypeHeader; relativeUrl = restmethodinfo.requestUrl; s = restmethodinfo.requestQuery; if (s != null) { queryParams = (new StringBuilder("?")).append(s); } switch (_cls1..SwitchMap.retrofit.RestMethodInfo.RequestType[restmethodinfo.requestType.ordinal()]) { case 1: // '\001' formBody = new FormUrlEncodedTypedOutput(); multipartBody = null; body = formBody; return; case 2: // '\002' formBody = null; multipartBody = new MultipartTypedOutput(); body = multipartBody; return; case 3: // '\003' formBody = null; multipartBody = null; return; } throw new IllegalArgumentException((new StringBuilder("Unknown request type: ")).append(restmethodinfo.requestType).toString()); } private void addPathParam(String s, String s1, boolean flag) { if (s == null) { throw new IllegalArgumentException("Path replacement name must not be null."); } if (s1 == null) { throw new IllegalArgumentException((new StringBuilder("Path replacement \"")).append(s).append("\" value must not be null.").toString()); } if (flag) { try { String s2 = URLEncoder.encode(String.valueOf(s1), "UTF-8").replace("+", "%20"); relativeUrl = relativeUrl.replace((new StringBuilder("{")).append(s).append("}").toString(), s2); return; } catch (UnsupportedEncodingException unsupportedencodingexception) { throw new RuntimeException((new StringBuilder("Unable to convert path parameter \"")).append(s).append("\" value to UTF-8:").append(s1).toString(), unsupportedencodingexception); } } relativeUrl = relativeUrl.replace((new StringBuilder("{")).append(s).append("}").toString(), String.valueOf(s1)); return; } private void addQueryParam(String s, Object obj, boolean flag, boolean flag1) { if (obj instanceof Iterable) { obj = ((Iterable)obj).iterator(); do { if (!((Iterator) (obj)).hasNext()) { break; } Object obj1 = ((Iterator) (obj)).next(); if (obj1 != null) { addQueryParam(s, obj1.toString(), flag, flag1); } } while (true); return; } if (obj.getClass().isArray()) { int i = 0; for (int j = Array.getLength(obj); i < j; i++) { Object obj2 = Array.get(obj, i); if (obj2 != null) { addQueryParam(s, obj2.toString(), flag, flag1); } } return; } else { addQueryParam(s, obj.toString(), flag, flag1); return; } } private void addQueryParam(String s, String s1, boolean flag, boolean flag1) { if (s == null) { throw new IllegalArgumentException("Query param name must not be null."); } if (s1 == null) { throw new IllegalArgumentException((new StringBuilder("Query param \"")).append(s).append("\" value must not be null.").toString()); } String s2 = s; String s3 = s1; Object obj; StringBuilder stringbuilder; try { obj = queryParams; } // Misplaced declaration of an exception variable catch (String s) { throw new RuntimeException((new StringBuilder("Unable to convert query parameter \"")).append(s2).append("\" value to UTF-8: ").append(s3).toString(), s); } stringbuilder = ((StringBuilder) (obj)); if (obj != null) { break MISSING_BLOCK_LABEL_95; } s2 = s; s3 = s1; stringbuilder = new StringBuilder(); s2 = s; s3 = s1; queryParams = stringbuilder; s2 = s; s3 = s1; char c; if (stringbuilder.length() > 0) { c = '&'; } else { c = '?'; } s2 = s; s3 = s1; stringbuilder.append(c); obj = s; if (!flag) { break MISSING_BLOCK_LABEL_151; } s2 = s; s3 = s1; obj = URLEncoder.encode(s, "UTF-8"); s = s1; if (!flag1) { break MISSING_BLOCK_LABEL_172; } s2 = ((String) (obj)); s3 = s1; s = URLEncoder.encode(s1, "UTF-8"); s2 = ((String) (obj)); s3 = s; stringbuilder.append(((String) (obj))).append('=').append(s); return; } private void addQueryParamMap(int i, Map map, boolean flag, boolean flag1) { map = map.entrySet().iterator(); do { if (!map.hasNext()) { break; } Object obj1 = (java.util.Map.Entry)map.next(); Object obj = ((java.util.Map.Entry) (obj1)).getKey(); if (obj == null) { throw new IllegalArgumentException((new StringBuilder("Parameter #")).append(i + 1).append(" query map contained null key.").toString()); } obj1 = ((java.util.Map.Entry) (obj1)).getValue(); if (obj1 != null) { addQueryParam(obj.toString(), obj1.toString(), flag, flag1); } } while (true); } public final void addEncodedPathParam(String s, String s1) { addPathParam(s, s1, false); } public final void addEncodedQueryParam(String s, String s1) { addQueryParam(s, s1, false, false); } public final void addHeader(String s, String s1) { if (s == null) { throw new IllegalArgumentException("Header name must not be null."); } if ("Content-Type".equalsIgnoreCase(s)) { contentTypeHeader = s1; return; } List list = headers; Object obj = list; if (list == null) { obj = new ArrayList(2); headers = ((List) (obj)); } ((List) (obj)).add(new Header(s, s1)); } public final void addPathParam(String s, String s1) { addPathParam(s, s1, true); } public final void addQueryParam(String s, String s1) { addQueryParam(s, s1, false, true); } final Request build() { if (multipartBody != null && multipartBody.getPartCount() == 0) { throw new IllegalStateException("Multipart requests must contain at least one part."); } Object obj = apiUrl; StringBuilder stringbuilder = new StringBuilder(((String) (obj))); if (((String) (obj)).endsWith("/")) { stringbuilder.deleteCharAt(stringbuilder.length() - 1); } stringbuilder.append(relativeUrl); obj = queryParams; if (obj != null) { stringbuilder.append(((CharSequence) (obj))); } TypedOutput typedoutput = body; List list1 = headers; obj = typedoutput; List list = list1; if (contentTypeHeader != null) { if (typedoutput != null) { obj = new MimeOverridingTypedOutput(typedoutput, contentTypeHeader); list = list1; } else { obj = new Header("Content-Type", contentTypeHeader); if (list1 == null) { list = Collections.singletonList(obj); obj = typedoutput; } else { list1.add(obj); list = list1; obj = typedoutput; } } } return new Request(requestMethod, stringbuilder.toString(), list, ((TypedOutput) (obj))); } final void setArguments(Object aobj[]) { if (aobj == null) { return; } int j = aobj.length; int i = j; if (!isSynchronous) { i = j; if (!isObservable) { i = j - 1; } } label0: for (int k = 0; k < i; k++) { Object obj = aobj[k]; Object obj1 = paramAnnotations[k]; Object obj2 = ((Annotation) (obj1)).annotationType(); if (obj2 == retrofit/http/Path) { obj1 = (Path)obj1; obj2 = ((Path) (obj1)).value(); if (obj == null) { throw new IllegalArgumentException((new StringBuilder("Path parameter \"")).append(((String) (obj2))).append("\" value must not be null.").toString()); } addPathParam(((String) (obj2)), obj.toString(), ((Path) (obj1)).encode()); continue; } if (obj2 == retrofit/http/EncodedPath) { obj1 = ((EncodedPath)obj1).value(); if (obj == null) { throw new IllegalArgumentException((new StringBuilder("Path parameter \"")).append(((String) (obj1))).append("\" value must not be null.").toString()); } addPathParam(((String) (obj1)), obj.toString(), false); continue; } if (obj2 == retrofit/http/Query) { if (obj != null) { obj1 = (Query)obj1; addQueryParam(((Query) (obj1)).value(), obj, ((Query) (obj1)).encodeName(), ((Query) (obj1)).encodeValue()); } continue; } if (obj2 == retrofit/http/EncodedQuery) { if (obj != null) { addQueryParam(((EncodedQuery)obj1).value(), obj, false, false); } continue; } if (obj2 == retrofit/http/QueryMap) { if (obj != null) { obj1 = (QueryMap)obj1; addQueryParamMap(k, (Map)obj, ((QueryMap) (obj1)).encodeNames(), ((QueryMap) (obj1)).encodeValues()); } continue; } if (obj2 == retrofit/http/EncodedQueryMap) { if (obj != null) { addQueryParamMap(k, (Map)obj, false, false); } continue; } if (obj2 == retrofit/http/Header) { if (obj == null) { continue; } obj1 = ((retrofit.http.Header)obj1).value(); if (obj instanceof Iterable) { obj = ((Iterable)obj).iterator(); do { do { if (!((Iterator) (obj)).hasNext()) { continue label0; } obj2 = ((Iterator) (obj)).next(); } while (obj2 == null); addHeader(((String) (obj1)), obj2.toString()); } while (true); } if (obj.getClass().isArray()) { int l = 0; int j1 = Array.getLength(obj); do { if (l >= j1) { continue label0; } obj2 = Array.get(obj, l); if (obj2 != null) { addHeader(((String) (obj1)), obj2.toString()); } l++; } while (true); } addHeader(((String) (obj1)), obj.toString()); continue; } if (obj2 == retrofit/http/Field) { if (obj == null) { continue; } obj2 = (Field)obj1; obj1 = ((Field) (obj2)).value(); boolean flag = ((Field) (obj2)).encodeName(); boolean flag2 = ((Field) (obj2)).encodeValue(); if (obj instanceof Iterable) { obj = ((Iterable)obj).iterator(); do { do { if (!((Iterator) (obj)).hasNext()) { continue label0; } obj2 = ((Iterator) (obj)).next(); } while (obj2 == null); formBody.addField(((String) (obj1)), flag, obj2.toString(), flag2); } while (true); } if (obj.getClass().isArray()) { int i1 = 0; int k1 = Array.getLength(obj); do { if (i1 >= k1) { continue label0; } obj2 = Array.get(obj, i1); if (obj2 != null) { formBody.addField(((String) (obj1)), flag, obj2.toString(), flag2); } i1++; } while (true); } formBody.addField(((String) (obj1)), flag, obj.toString(), flag2); continue; } if (obj2 == retrofit/http/FieldMap) { if (obj == null) { continue; } obj1 = (FieldMap)obj1; boolean flag1 = ((FieldMap) (obj1)).encodeNames(); boolean flag3 = ((FieldMap) (obj1)).encodeValues(); obj = ((Map)obj).entrySet().iterator(); do { do { if (!((Iterator) (obj)).hasNext()) { continue label0; } obj2 = (java.util.Map.Entry)((Iterator) (obj)).next(); obj1 = ((java.util.Map.Entry) (obj2)).getKey(); if (obj1 == null) { throw new IllegalArgumentException((new StringBuilder("Parameter #")).append(k + 1).append(" field map contained null key.").toString()); } obj2 = ((java.util.Map.Entry) (obj2)).getValue(); } while (obj2 == null); formBody.addField(obj1.toString(), flag1, obj2.toString(), flag3); } while (true); } if (obj2 == retrofit/http/Part) { if (obj == null) { continue; } obj2 = ((Part)obj1).value(); obj1 = ((Part)obj1).encoding(); if (obj instanceof TypedOutput) { multipartBody.addPart(((String) (obj2)), ((String) (obj1)), (TypedOutput)obj); continue; } if (obj instanceof String) { multipartBody.addPart(((String) (obj2)), ((String) (obj1)), new TypedString((String)obj)); } else { multipartBody.addPart(((String) (obj2)), ((String) (obj1)), converter.toBody(obj)); } continue; } if (obj2 == retrofit/http/PartMap) { if (obj == null) { continue; } obj1 = ((PartMap)obj1).encoding(); obj = ((Map)obj).entrySet().iterator(); do { Object obj3; do { if (!((Iterator) (obj)).hasNext()) { continue label0; } obj2 = (java.util.Map.Entry)((Iterator) (obj)).next(); obj3 = ((java.util.Map.Entry) (obj2)).getKey(); if (obj3 == null) { throw new IllegalArgumentException((new StringBuilder("Parameter #")).append(k + 1).append(" part map contained null key.").toString()); } obj3 = obj3.toString(); obj2 = ((java.util.Map.Entry) (obj2)).getValue(); } while (obj2 == null); if (obj2 instanceof TypedOutput) { multipartBody.addPart(((String) (obj3)), ((String) (obj1)), (TypedOutput)obj2); } else if (obj2 instanceof String) { multipartBody.addPart(((String) (obj3)), ((String) (obj1)), new TypedString((String)obj2)); } else { multipartBody.addPart(((String) (obj3)), ((String) (obj1)), converter.toBody(obj2)); } } while (true); } if (obj2 == retrofit/http/Body) { if (obj == null) { throw new IllegalArgumentException("Body parameter value must not be null."); } if (obj instanceof TypedOutput) { body = (TypedOutput)obj; } else { body = converter.toBody(obj); } } else { throw new IllegalArgumentException((new StringBuilder("Unknown annotation: ")).append(((Class) (obj2)).getCanonicalName()).toString()); } } } private class _cls1 { static final int $SwitchMap$retrofit$RestMethodInfo$RequestType[]; static { $SwitchMap$retrofit$RestMethodInfo$RequestType = new int[RestMethodInfo.RequestType.values().length]; try { $SwitchMap$retrofit$RestMethodInfo$RequestType[RestMethodInfo.RequestType.FORM_URL_ENCODED.ordinal()] = 1; } catch (NoSuchFieldError nosuchfielderror) { } try { $SwitchMap$retrofit$RestMethodInfo$RequestType[RestMethodInfo.RequestType.MULTIPART.ordinal()] = 2; } catch (NoSuchFieldError nosuchfielderror1) { } try { $SwitchMap$retrofit$RestMethodInfo$RequestType[RestMethodInfo.RequestType.SIMPLE.ordinal()] = 3; } catch (NoSuchFieldError nosuchfielderror2) { } } } }
true
83b35c9c677e9a7e0dafcb02c88ee64efccbe122
Java
LD297/RSHRepository
/CMBT_RSH/RSH_Server/src/main/java/data/daoimpl/webstaffdaoimpl/WebSalesmanDaoImpl.java
UTF-8
2,173
2.265625
2
[]
no_license
package data.daoimpl.webstaffdaoimpl; import constant.ResultMessage; import data.dao.webstaffdao.WebSalesmanDao; import data.daohelper.DaoHelperFactory; import data.daohelper.WebManagerDaoHelper; import data.daohelper.WebSalesmanDaoHelper; import data.daohelperimpl.DaoHelperFactoryImpl; import po.WebSalesmanPO; import java.rmi.RemoteException; import java.rmi.server.UnicastRemoteObject; import java.util.ArrayList; import java.io.BufferedReader; import java.io.BufferedWriter; import java.io.FileReader; import java.io.FileWriter; import java.io.IOException; /** * Created by aa on 2016/11/22. */ public class WebSalesmanDaoImpl extends UnicastRemoteObject implements WebSalesmanDao { private static WebSalesmanDaoImpl webSalesmanDaoImpl; private WebSalesmanDaoHelper webSalesmanDaoHelper; private DaoHelperFactory daoHelperFactory; private WebSalesmanDaoImpl()throws RemoteException{ daoHelperFactory = new DaoHelperFactoryImpl(); webSalesmanDaoHelper = daoHelperFactory.getWebSalesManDaoHelper(); } public static WebSalesmanDaoImpl getInstance(){ if(webSalesmanDaoImpl == null){ try { webSalesmanDaoImpl = new WebSalesmanDaoImpl(); } catch (RemoteException e) { e.printStackTrace(); } } return webSalesmanDaoImpl; } public ResultMessage insert(WebSalesmanPO po) throws RemoteException { return webSalesmanDaoHelper.insert(po); } public ResultMessage update(WebSalesmanPO po)throws RemoteException { return webSalesmanDaoHelper.update(po); } public WebSalesmanPO findByID(String websalesmanID)throws RemoteException { return webSalesmanDaoHelper.findByID(websalesmanID); } public ArrayList<WebSalesmanPO> findByDistrict(String district)throws RemoteException { return webSalesmanDaoHelper.findByDistrict(district); } public ArrayList<WebSalesmanPO> getAll()throws RemoteException { return webSalesmanDaoHelper.getAll(); } @Override public String getNewID() throws RemoteException { return webSalesmanDaoHelper.getNewID(); } }
true
8c9507e89d211fb31b71b9c386c6dac6613e350a
Java
161250020/Summer_Learn
/src/剑指offer/二叉树中和为某一值的路径.java
UTF-8
1,381
3.640625
4
[]
no_license
package 剑指offer; import java.util.ArrayList; public class 二叉树中和为某一值的路径 { /** * 输入一颗二叉树的根节点和一个整数, * 打印出二叉树中结点值的和为输入整数的所有路径。 * 路径定义为从树的根结点开始往下一直到叶结点所经过的结点形成一条路径。 * (注意: 在返回值的list中,数组长度大的数组靠前) * */ private ArrayList<ArrayList<Integer>> lists=new ArrayList<>(); private ArrayList<Integer> list=new ArrayList<>(); public ArrayList<ArrayList<Integer>> FindPath(TreeNode root, int target) { if (root==null) return lists; list.add(root.val); target-=root.val; //list符合条件就添加 if (target==0&&root.left==null&&root.right==null) lists.add(new ArrayList<Integer>(list));//不可以直接加上list,因为list为一个对象 //list不符合条件就在root的左子树和右子树里面分别寻找 FindPath(root.left,target); FindPath(root.right,target); //将list此次递归添加的值去除,以免影响到其余递归 list.remove(list.size()-1); //是返回lists,而中间过程中FindPath的返回值没有用处, //所以对最终的返回值影响不大 return lists; } }
true
c38a484e47ba77ad1f138955f1fe51c640cf124e
Java
hoangkhangv97/projectfinaliot2018
/example/src/main/java/com/group3/androidthings/MVVM/View/NPNHomeView.java
UTF-8
221
1.617188
2
[ "MIT" ]
permissive
package com.group3.androidthings.MVVM.View; import org.json.JSONObject; public interface NPNHomeView extends IView { void onSuccessUpdateServer(JSONObject message); void onErrorUpdateServer(String message); }
true
780891ab2397a839988f442230eb45018d0b853f
Java
gratianmoise/CursJava
/CursJava/src/curs3/Rectangle.java
UTF-8
214
2.765625
3
[]
no_license
package curs3; public class Rectangle { double lenght; double width; String name; double calculeazaPerimetrul(){ return(2 * lenght + 2 *width); } double calculeazaAria() { return lenght * width; } }
true
8f4c9eb11cff962d92b2ce4dcdf6d48b24509104
Java
Geetha15/capg-virtual-class
/spring-boot-app-calculateage/src/main/java/com/capg/springboot/controller/UserRestController.java
UTF-8
525
2.21875
2
[]
no_license
package com.capg.springboot.controller; import java.time.LocalDate; import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RestController; import com.capg.springboot.model.User; @RestController @RequestMapping("/api") public class UserRestController { @GetMapping("/users") public User getUser() { User user=new User("Geetha", "Geetha@yahoo.com", LocalDate.of(1999, 8, 7), 345678976L); return user; } }
true
84b2039ab395cea8fed858e0ac8bc5d2b4c0f0c5
Java
ram100/TestProject
/Test/src/programs/FibonacciSeries.java
UTF-8
435
2.96875
3
[]
no_license
package programs; import java.util.Scanner; public class FibonacciSeries { public static void main(String args[]){ int maxNo=10; int prevNo=0; int nextNo=1; // Scanner scanner = new Scanner(System.in); // int maxNo = scanner.nextInt(); for (int i=0;i<maxNo;i++){ System.out.println("the value of prev no"+prevNo); int sum = prevNo+nextNo; prevNo=nextNo; nextNo=sum; } } }
true
908e49023efd173fc87f0a42c1741cde730ae00c
Java
mcqueide/Treinamento-JSF
/src/main/java/la/foton/treinamento/locadora/mbean/CadastroTituloMBean.java
UTF-8
1,827
2.28125
2
[]
no_license
package la.foton.treinamento.locadora.mbean; import java.io.Serializable; import java.util.ArrayList; import java.util.List; import javax.faces.bean.ManagedBean; import javax.faces.bean.ViewScoped; import javax.faces.model.SelectItem; @ManagedBean @ViewScoped public class CadastroTituloMBean implements Serializable { private static final long serialVersionUID = 1L; private String nome; private Double preco; private Double precoGourmet; private Integer quantidade; private String emailFornecedor; private Integer categoria; public Integer getCategoria() { return categoria; } public void setCategoria(Integer categoria) { this.categoria = categoria; } public String getNome() { return nome; } public void setNome(String nome) { this.nome = nome; } public Double getPreco() { return preco; } public void setPreco(Double preco) { this.preco = preco; } public Double getPrecoGourmet() { return precoGourmet; } public void setPrecoGourmet(Double precoGourmet) { this.precoGourmet = precoGourmet; } public Integer getQuantidade() { return quantidade; } public void setQuantidade(Integer quantidade) { this.quantidade = quantidade; } public String getEmailFornecedor() { return emailFornecedor; } public void setEmailFornecedor(String emailFornecedor) { this.emailFornecedor = emailFornecedor; } public void salvar(){ } public void calculaGourmet(){ precoGourmet = preco * 1.5; } public List<SelectItem> opcoesCategoria(){ List<SelectItem> itens = new ArrayList<SelectItem>(); itens.add(new SelectItem(1, "Terror")); itens.add(new SelectItem(2, "Humor")); itens.add(new SelectItem(3, "Suspense")); itens.add(new SelectItem(4, "Drama")); return itens; } }
true
9e0243781c881ac18da49b4a5ec457373633e9dd
Java
ckasper21/CS350
/SurveyTest Project/HW2/src/menu/CreateMenu.java
UTF-8
13,435
2.90625
3
[]
no_license
/** * Chris Kasper * CS350 - Survey Test Project * Last updated: November 1st, 2018 */ package menu; import questions.*; import surveytest.*; import java.io.*; import java.lang.reflect.Array; import java.util.*; public class CreateMenu extends Menu { protected Boolean isTest; public CreateMenu(Survey s, Boolean isTest) { super(s); if (isTest) { this.survey = new Test(); } else { this.survey = new Survey(); } this.menuName = "Create Menu"; this.numChoices = 7; this.isTest = isTest; this.menuOptions.add("Add a new T/F question"); this.menuOptions.add("Add a new multiple choice question"); this.menuOptions.add("Add a new short answer question"); this.menuOptions.add("Add a new essay question"); this.menuOptions.add("Add a new ranking question"); this.menuOptions.add("Add a new matching question"); this.menuOptions.add("<- Go back"); } // Set name for survey/test public void configSurvey() { if (isTest) { this.o.setDisplay("Please enter name for test: "); } else { this.o.setDisplay("Please enter name for survey "); } this.o.getDisplay(); this.survey.setName(this.in.getUserInput()); } // Get the survey/test with this object public Survey getSurvey() { return this.survey; } // Create a TrueFalse question public void createTrueFalse() { Question q = new TrueFalse(this.in,this.o); this.o.setDisplay("Enter the prompt for your True/False question:\n"); this.o.getDisplay(); q.setPrompt(this.in.getUserInput()); if (isTest) { Test t = (Test)this.survey; RCA ca = new RCA(this.in,this.o); this.o.setDisplay("Enter the correct answer (T/F):\n"); this.o.getDisplay(); ca.addResponse(); while (!ca.getResponses().get(0).contains("T") && !ca.getResponses().get(0).contains("F")) { ca.removeResponse(0); this.o.setDisplay("Enter a valid answer (T/F):\n"); this.o.getDisplay(); ca.addResponse(); } t.addAnswer(ca); } this.survey.addQuestion(q); } // Create MultipleChoice question public void createMultipleChoice() { int numChoices = 0; Question q = new MultipleChoice(this.in,this.o); this.o.setDisplay("Enter the prompt for your Multiple Choice question:\n"); this.o.getDisplay(); q.setPrompt(this.in.getUserInput()); while (numChoices == 0) { this.o.setDisplay("Enter the number of choices for your question:\n"); this.o.getDisplay(); try { numChoices = Integer.parseInt(this.in.getUserInput()); } catch (NumberFormatException e) { numChoices = 0; } } for (int i=0; i<numChoices;i++) { this.o.setDisplay("Enter choice#" + (i+1) + "\n"); this.o.getDisplay(); ((MultipleChoice) q).addChoice(this.in.getUserInput()); } int numAns = 0; while (numAns == 0) { this.o.setDisplay("How many answers does this question have?\n"); this.o.getDisplay(); try { numAns = Integer.parseInt(this.in.getUserInput()); if (numAns > numChoices || numAns < 1) { numAns = 0; } else { q.setMaxResponses(numAns); } } catch (NumberFormatException e) { numAns = 0; } } if (isTest) { int choiceNum = 0; RCA ca = new RCA(this.in,this.o); Test t = (Test)this.survey; ArrayList<String> ans = new ArrayList<String>(); char alphabet = 'A'; for (int j=0; j < q.getMaxResponses(); j++){ while (choiceNum == 0) { this.o.setDisplay("Enter the correct choice number:\n"); this.o.getDisplay(); try { choiceNum = Integer.parseInt(this.in.getUserInput()); if (choiceNum > numChoices || choiceNum < 1) { choiceNum = 0; } else { alphabet += choiceNum - 1; if (ans.contains(String.valueOf(alphabet))) { this.o.setDisplay("Answer already used\n"); this.o.getDisplay(); choiceNum = 0; } else { ans.add(String.valueOf(alphabet)); ca.addResponse(String.valueOf(alphabet)); alphabet = 'A'; } } } catch (NumberFormatException e) { choiceNum = 0; } } choiceNum = 0; } t.addAnswer(ca); } this.survey.addQuestion(q); } // Create a ShortAnswer question public void createShortAnswer() { Question q = new ShortAnswer(this.in,this.o); this.o.setDisplay("Enter the prompt for your Short Answer question:\n"); this.o.getDisplay(); q.setPrompt(this.in.getUserInput()); int charlimit = 0; while (charlimit == 0) { this.o.setDisplay("Enter character limit\n"); this.o.getDisplay(); try { charlimit = Integer.parseInt(this.in.getUserInput()); if (charlimit < 1) { charlimit = 0; } else { ((ShortAnswer) q).setCharLimit(charlimit); } } catch (NumberFormatException e) { charlimit = 0; } } int numAns = 0; while (numAns == 0) { this.o.setDisplay("How many answers does this question have?\n"); this.o.getDisplay(); try { numAns = Integer.parseInt(this.in.getUserInput()); if (numAns > numChoices || numAns < 1) { numAns = 0; } else { q.setMaxResponses(numAns); } } catch (NumberFormatException e) { numAns = 0; } } if (isTest) { RCA ca = new RCA(this.in,this.o); Test t = (Test)this.survey; String ans; for (int j=0; j < q.getMaxResponses(); j++){ this.o.setDisplay("Enter correct answer(s):\n"); this.o.getDisplay(); ans = this.in.getUserInput(); while (ans.length() > ((ShortAnswer) q).getCharLimit()) { this.o.setDisplay("Answer must be less then " + ((ShortAnswer) q).getCharLimit() + " characters \n"); this.o.getDisplay(); ans = this.in.getUserInput(); } ca.addResponse(ans); } t.addAnswer(ca); } this.survey.addQuestion(q); } // Create an Essay question public void createEssay() { Question q = new Essay(this.in,this.o); this.o.setDisplay("Enter the prompt for your Essay question:\n"); this.o.getDisplay(); q.setPrompt(this.in.getUserInput()); int numAns = 0; while (numAns == 0) { this.o.setDisplay("How many answers does this question have?\n"); this.o.getDisplay(); try { numAns = Integer.parseInt(this.in.getUserInput()); if (numAns > numChoices || numAns < 1) { numAns = 0; } else { q.setMaxResponses(numAns); } } catch (NumberFormatException e) { numAns = 0; } } if (isTest) { RCA ca = new RCA(this.in,this.o); Test t = (Test)this.survey; String ans; this.o.setDisplay("Enter correct answer(s)\n"); this.o.getDisplay(); for (int j=0; j < q.getMaxResponses(); j++){ ans = this.in.getUserInput(); ca.addResponse(ans); } t.addAnswer(ca); } this.survey.addQuestion(q); } // Create a Ranking question public void createRanking() { Question q = new Ranking(this.in,this.o); this.o.setDisplay("Enter the prompt for your Ranking question:\n"); this.o.getDisplay(); q.setPrompt(this.in.getUserInput()); int numAns = 0; while (numAns == 0) { this.o.setDisplay("How many items need to be ranked?\n"); this.o.getDisplay(); try { numAns = Integer.parseInt(this.in.getUserInput()); if (numAns < 1) { numAns = 0; } else { q.setMaxResponses(numAns); } } catch (NumberFormatException e) { numAns = 0; } } if (isTest) { RCA ca = new RCA(this.in,this.o); Test t = (Test)this.survey; String ans; this.o.setDisplay("Enter correct answer(s):\n"); this.o.getDisplay(); for (int j=0; j < q.getMaxResponses(); j++){ ans = this.in.getUserInput(); ca.addResponse(ans); } t.addAnswer(ca); } this.survey.addQuestion(q); } // Create a Matching question public void createMatching() { int numChoices = 0; Question q = new Matching(this.in,this.o); this.o.setDisplay("Enter the prompt for your Matching question:\n"); this.o.getDisplay(); q.setPrompt(this.in.getUserInput()); while (numChoices == 0) { this.o.setDisplay("Enter the number of choices for your question:\n"); this.o.getDisplay(); try { numChoices = Integer.parseInt(this.in.getUserInput()); } catch (NumberFormatException e) { numChoices = 0; } } for (int i=0; i<numChoices;i++) { this.o.setDisplay("Enter choice#" + (i+1) + "\n"); this.o.getDisplay(); ((Matching) q).addChoicesToMatch(this.in.getUserInput()); } for (int i=0; i<numChoices;i++) { this.o.setDisplay("Answer#" + (i+1) + " (enter any answer for one of the choices)\n"); this.o.getDisplay(); ((Matching) q).addChoice(this.in.getUserInput()); } q.setMaxResponses(numChoices); if (isTest) { int choiceNum = 0; RCA ca = new RCA(this.in,this.o); Test t = (Test)this.survey; ArrayList<Integer> ans = new ArrayList<Integer>(); for (int j=0; j < q.getMaxResponses(); j++){ while (choiceNum == 0) { this.o.setDisplay("Enter answer# for choice#" + (j+1) + ": \n"); this.o.getDisplay(); try { choiceNum = Integer.parseInt(this.in.getUserInput()); if (choiceNum > numChoices || choiceNum < 1) { choiceNum = 0; } else { if (ans.contains(choiceNum)) { this.o.setDisplay("Answer already used\n"); this.o.getDisplay(); choiceNum = 0; } else { ans.add(choiceNum); ca.addResponse(Integer.toString(choiceNum)); } } } catch (NumberFormatException e) { choiceNum = 0; } } choiceNum = 0; } t.addAnswer(ca); } this.survey.addQuestion(q); } // Run CreateMenu @Override public Menu run() { if (this.survey.getName().contains("")) { this.configSurvey(); } while (true) { int sel = 0; this.display(); sel = this.getSelection(); switch (sel) { case 1: this.createTrueFalse(); break; case 2: this.createMultipleChoice(); break; case 3: this.createShortAnswer(); break; case 4: this.createEssay(); break; case 5: this.createRanking(); break; case 6: this.createMatching(); break; case 7: return this; } } } }
true
a76383beb4f6ebb511061d38780fad3fdd951558
Java
Rethen/Poker
/paylib/src/main/java/com/changdupay/protocol/login/MobilePhoneRegisterRequestInfo.java
UTF-8
1,343
2.328125
2
[]
no_license
package com.changdupay.protocol.login; import org.json.JSONObject; import com.changdupay.encrypt.JsonUtils; import com.changdupay.protocol.base.BaseContent; import com.changdupay.protocol.base.BaseRequestInfo; import com.changdupay.protocol.base.PayConst; public class MobilePhoneRegisterRequestInfo extends BaseRequestInfo{ public MobilePhoneRegisterRequestInfo() { super(); Content = new MobilePhoneRegisterRequestContent(); ActionID = PayConst.MOBILEPHONEREGISTER_ACTION; RequestHeader.mActionID = ActionID; } public class MobilePhoneRegisterRequestContent extends BaseContent { public String mMobilePhone = ""; public String mPassword = ""; public String mVerifyCode = ""; public MobilePhoneRegisterRequestContent() { } public String toString() { try{ StringBuilder str = new StringBuilder(); str.append("MobilePhone:"); str.append(mMobilePhone); str.append(","); str.append("Password:"); str.append(mPassword); str.append(","); str.append("VerifyCode:"); str.append(mVerifyCode); String content = str.toString();//.replaceAll(" ", ""); JSONObject jsonObj = JsonUtils.string2JSON(content, ","); str = null; return jsonObj.toString(); } catch(Exception e) { e.printStackTrace(); } return null; } } }
true
3e16235708cba318ba10a69293529b80df88a455
Java
zcc815/ExamPratice
/src/Test/java/niuke/Day001/Exam02Demo01.java
UTF-8
1,744
3.84375
4
[]
no_license
package niuke.Day001; /** * 类的加载及顺序测试 * 测试结果:(输出顺序从上到下) * 父类静态变量 * 父类静态代码块one * 父类静态代码块second * 父类非静态变量 * 非静态语句one * 非静态语句second * 父类构造函数 * 父类方法(静态 非静态不分先后,谁在前被调用则谁先被执行) * 作者:张陈陈 * 时间:2019/9/2/19:24 */ public class Exam02Demo01 { //1.静态变量 static String test01 = TestDemo01(); //2.静态方法 static String TestDemo01() { System.out.println("父类静态变量"); return "静态变量"; } //3.静态代码块 static { System.out.println("父类静态代码块one"); } static { System.out.println("父类静态代码块second"); } //4.非静态变量 String test02 = TestDemo02(); //5.非静态变量测试方法 public String TestDemo02() { System.out.println("父类非静态变量"); return "父类非静态变量"; } //6.非静态语句块 { System.out.println("父类非静态语句one"); } { System.out.println("父类非静态语句second"); } //7.非静态方法 public void methodTest(){ System.out.println("父类非静态方法"); } //7.1静态方法 public static void staticMethodTest(){ System.out.println("父类静态方法"); } //8.构造函数 public Exam02Demo01() { System.out.println("父类构造函数"); } public static void main(String[] args) { Exam02Demo01 exam02Demo01 = new Exam02Demo01(); exam02Demo01.staticMethodTest(); exam02Demo01.methodTest(); } }
true
4516e80fa8f2c4747df607b174ca0527b3d18cd7
Java
shiv21081999/CodingNinjas
/TargetMarbles/Main.java
UTF-8
1,129
3.359375
3
[]
no_license
import java.util.*; import java.util.Arrays; import java.math.BigInteger; public class Main { public static void main(String args[]) { Scanner sc = new Scanner(System.in); int n = sc.nextInt(); int target = sc.nextInt(); int[] arr = new int[n]; for (int i = 0; i < arr.length; i++) { arr[i] = sc.nextInt(); } int i =0 , j = 0 , sum = 0; boolean flag = false; while(i<arr.length) { if(sum == target) { flag = true; break; } if(sum > target) { sum-= arr[i]; i++; continue; } sum += arr[j]; if(j<arr.length) j++; } if(flag == true) { System.out.println(true); for (int k = i; k < j; k++) { System.out.print(arr[k]+" "); } } else { System.out.println(false); } } }
true