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
fa093c36d99415cb789e05bbb8cd3167fd2f3824
Java
AthinaDavari/JavaAssignment
/proderp/src/test/java/gr/aueb/dmst/pijavaparty/proderp/services/ValidVariablesTest.java
UTF-8
4,391
2.5625
3
[]
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 gr.aueb.dmst.pijavaparty.proderp.services; import org.junit.Test; import static org.junit.Assert.*; /** * * @author Natalia */ public class ValidVariablesTest { /** * An empty conrtuctor */ public ValidVariablesTest() { } /** * Test of isStringOnlyAlphabetAndWhiteSpaces method, of class ValidVariables. */ @Test public void testIsStringOnlyAlphabetAndWhiteSpaces() { System.out.println("isStringOnlyAlphabetAndWhiteSpaces"); String str = "52374ggs"; boolean expResult = false; boolean result = ValidVariables.isStringOnlyAlphabetAndWhiteSpaces(str); assertEquals(expResult, result); } /** * Test of isValidFullName method, of class ValidVariables. */ @Test public void testIsValidFullName() { System.out.println("isValidFullName"); String fullName = "Aliki Manou"; boolean expResult = true; boolean result = ValidVariables.isValidFullName(fullName); assertEquals(expResult, result); } /** * Test of isStringOnlyAlphabetAndNumbers method, of class ValidVariables. */ @Test public void testIsStringOnlyAlphabetAndNumbers() { System.out.println("isStringOnlyAlphabetAndNumbers"); String fullName = "Ali8"; boolean expResult = true; boolean result = ValidVariables.isStringOnlyAlphabetAndNumbers(fullName); assertEquals(expResult, result); } /** * Test of isValidEmailAddress method, of class ValidVariables. */ @Test public void testIsValidEmailAddress() { System.out.println("isValidEmailAddress"); String email = "hg5"; boolean expResult = false; boolean result = ValidVariables.isValidEmailAddress(email); assertEquals(expResult, result); } /** * Test of isValidAddress method, of class ValidVariables. */ @Test public void testIsValidAddress() { System.out.println("isValidAddress"); String address = "Trion Ierarxon 86, Larissa"; boolean expResult = true; boolean result = ValidVariables.isValidAddress(address); assertEquals(expResult, result); } /** * Test of isValidPhonenumber method, of class ValidVariables. */ @Test public void testIsValidPhonenumber() { System.out.println("isValidPhonenumber"); String phonenumber = "gd566666666666666666666666666666666666666"; boolean expResult = false; boolean result = ValidVariables.isValidPhonenumber(phonenumber); assertEquals(expResult, result); } /** * Test of isValidInteger method, of class ValidVariables. */ @Test public void testIsValidInteger() { System.out.println("isValidInteger"); String integer = "6.8"; boolean expResult = false; boolean result = ValidVariables.isValidInteger(integer); assertEquals(expResult, result); } /** * Test of isValidDouble method, of class ValidVariables. */ @Test public void testIsValidDouble() { System.out.println("isValidDouble"); String double_number = "Mary"; boolean expResult = false; boolean result = ValidVariables.isValidDouble(double_number); assertEquals(expResult, result); } /** * Test of isValidPassword method, of class ValidVariables. */ @Test public void testIsValidPassword() { System.out.println("isValidPassword"); String input = ".%6gwdye"; boolean expResult = false; boolean result = ValidVariables.isValidPassword(input); assertEquals(expResult, result); } /** * Test of isStringOnlyAlphabetAndNumbersAndWhiteSpaces method, of class ValidVariables. */ @Test public void testIsStringOnlyAlphabetAndNumbersAndWhiteSpaces() { System.out.println("isStringOnlyAlphabetAndNumbersAndWhiteSpaces"); String input = ".%6gwdye"; boolean expResult = false; boolean result = ValidVariables.isStringOnlyAlphabetAndNumbersAndWhiteSpaces(input); assertEquals(expResult, result); } }
true
1031cd4684d7e4cbcf6cf1e21b9d01537d0bb778
Java
ProjectEKA/data-notification-subscription
/src/main/java/in/projecteka/datanotificationsubscription/subscription/SubscriptionService.java
UTF-8
10,744
1.65625
2
[]
no_license
package in.projecteka.datanotificationsubscription.subscription; import com.google.common.collect.Sets; import in.projecteka.datanotificationsubscription.clients.LinkServiceClient; import in.projecteka.datanotificationsubscription.clients.UserServiceClient; import in.projecteka.datanotificationsubscription.clients.model.User; import in.projecteka.datanotificationsubscription.common.ClientError; import in.projecteka.datanotificationsubscription.common.GatewayServiceClient; import in.projecteka.datanotificationsubscription.subscription.model.GrantedSubscription; import in.projecteka.datanotificationsubscription.subscription.model.HIUSubscriptionRequestNotification; import in.projecteka.datanotificationsubscription.subscription.model.HIUSubscriptionRequestNotifyRequest; import in.projecteka.datanotificationsubscription.subscription.model.HipDetail; import in.projecteka.datanotificationsubscription.subscription.model.HiuDetail; import in.projecteka.datanotificationsubscription.subscription.model.ListResult; import in.projecteka.datanotificationsubscription.subscription.model.RequestStatus; import in.projecteka.datanotificationsubscription.subscription.model.SubscriptionEditAndApprovalRequest; import in.projecteka.datanotificationsubscription.subscription.model.SubscriptionResponse; import in.projecteka.datanotificationsubscription.subscription.model.SubscriptionSource; import lombok.AllArgsConstructor; import org.springframework.util.StringUtils; import reactor.core.publisher.Mono; import java.time.LocalDateTime; import java.time.ZoneOffset; import java.util.ArrayList; import java.util.List; import java.util.Set; import java.util.UUID; import java.util.stream.Collectors; @AllArgsConstructor public class SubscriptionService { private final UserServiceClient userServiceClient; private final GatewayServiceClient gatewayServiceClient; private final SubscriptionRepository subscriptionRepository; private final LinkServiceClient linkServiceClient; public Mono<ListResult<List<SubscriptionResponse>>> getSubscriptionsFor(String patientId, String hiuId, int limit, int offset) { //TODO: Cache findPatient return userServiceClient.userOf(patientId) .flatMap(user -> { String patientIdentifier = getPatientId(patientId, user); return subscriptionRepository.getSubscriptionsFor(patientIdentifier, hiuId, limit, offset); }); } private String getPatientId(String username, User user) { return StringUtils.isEmpty(user.getHealthIdNumber()) ? username : user.getHealthIdNumber(); } public Mono<SubscriptionResponse> getSubscriptionDetailsForID(String subscriptionId) { return subscriptionRepository.getSubscriptionDetailsForID(subscriptionId, true) .switchIfEmpty(Mono.error(ClientError.subscriptionRequestNotFound())); } public Mono<Void> editSubscription(String subscriptionId, SubscriptionEditAndApprovalRequest subscriptionEditRequest) { return subscriptionRepository.getSubscriptionDetailsForID(subscriptionId, false) .switchIfEmpty(Mono.error(ClientError.subscriptionRequestNotFound())) .flatMap(subscriptionResponse -> { Mono<Void> subscriptionEditPublisher; if (subscriptionEditRequest.isApplicableForAllHIPs()) { subscriptionEditPublisher = editSubscriptionApplicableForAllHIPs(subscriptionId, subscriptionEditRequest, subscriptionResponse); } else { subscriptionEditPublisher = editSubscriptionNotApplicableForAllHIPs(subscriptionId, subscriptionEditRequest, subscriptionResponse); } var hiuId = subscriptionResponse.getRequester().getId(); return subscriptionEditPublisher .then(buildHIUSubscriptionNotifyRequest(subscriptionEditRequest, subscriptionResponse)) .flatMap(notifyRequest -> gatewayServiceClient.subscriptionRequestNotify(notifyRequest, hiuId)); }); } private Mono<HIUSubscriptionRequestNotifyRequest> buildHIUSubscriptionNotifyRequest(SubscriptionEditAndApprovalRequest subscriptionEditRequest, SubscriptionResponse subscriptionResponse) { var subscriptionBuilder = HIUSubscriptionRequestNotification.Subscription.builder() .hiu(HiuDetail.builder() .id(subscriptionResponse.getRequester().getId()) .name(subscriptionResponse.getRequester().getName()) .build()) .patient(subscriptionResponse.getPatient()) .id(subscriptionResponse.getSubscriptionId()); var notificationBuilder = HIUSubscriptionRequestNotification.builder() .status(RequestStatus.GRANTED.name()) .subscriptionRequestId(UUID.fromString(subscriptionResponse.getSubscriptionRequestId())); var notifyRequestBuilder = HIUSubscriptionRequestNotifyRequest.builder() .requestId(UUID.randomUUID()) .timestamp(LocalDateTime.now(ZoneOffset.UTC)); if (subscriptionEditRequest.isApplicableForAllHIPs()) { var hiTypes = subscriptionEditRequest.getIncludedSources().get(0).getHiTypes(); var categories = subscriptionEditRequest.getIncludedSources().get(0).getCategories(); var period = subscriptionEditRequest.getIncludedSources().get(0).getPeriod(); var purpose = subscriptionEditRequest.getIncludedSources().get(0).getPurpose(); var excludedHips = subscriptionEditRequest.getExcludedSources().stream() .map(grantedSubscription -> grantedSubscription.getHip().getId().toLowerCase()) .collect(Collectors.toList()); return linkServiceClient.getUserLinks(subscriptionResponse.getPatient().getId()) .map(patientLinksResponse -> patientLinksResponse.getPatient().getLinks()) .map(links -> { var sources = links.stream() .map(link -> link.getHip().getId()) .filter(hipId -> !excludedHips.contains(hipId.toLowerCase())) .map(hipId -> GrantedSubscription.builder() .categories(categories) .hiTypes(hiTypes) .period(period) .purpose(purpose) .hip(HipDetail.builder().id(hipId).build()) .build()) .map(this::toSubscriptionSource) .collect(Collectors.toList()); var subscription = subscriptionBuilder.sources(sources).build(); var notification = notificationBuilder.subscription(subscription).build(); return notifyRequestBuilder.notification(notification).build(); }); } var sources = subscriptionEditRequest.getIncludedSources().stream() .map(this::toSubscriptionSource).collect(Collectors.toList()); var subscription = subscriptionBuilder.sources(sources).build(); var notification = notificationBuilder.subscription(subscription).build(); return Mono.just(notifyRequestBuilder.notification(notification).build()); } private HIUSubscriptionRequestNotification.Source toSubscriptionSource(GrantedSubscription grantedSubscription) { return HIUSubscriptionRequestNotification.Source.builder() .categories(grantedSubscription.getCategories()) .hip(grantedSubscription.getHip()) .period(grantedSubscription.getPeriod()) .build(); } private Mono<Void> editSubscriptionNotApplicableForAllHIPs(String subscriptionId, SubscriptionEditAndApprovalRequest subscriptionEditRequest, SubscriptionResponse subscriptionResponse) { Set<String> hipsToBeSetAsInactive = getHIPsToBeDeactivated(subscriptionResponse, subscriptionEditRequest.getIncludedSources()); return subscriptionRepository.editSubscriptionNotApplicableForAllHIPs(subscriptionId, subscriptionEditRequest.getIncludedSources(), hipsToBeSetAsInactive); } private Mono<Void> editSubscriptionApplicableForAllHIPs(String subscriptionId, SubscriptionEditAndApprovalRequest subscriptionEditRequest, SubscriptionResponse subscriptionResponse) { Set<String> hipsToBeSetAsInactive = getHIPsToBeDeactivated(subscriptionResponse, subscriptionEditRequest.getExcludedSources()); var includedSource = subscriptionEditRequest.getIncludedSources().get(0); return subscriptionRepository.editSubscriptionApplicableForAllHIPs(subscriptionId, hipsToBeSetAsInactive, includedSource, subscriptionEditRequest.getExcludedSources()); } private Set<String> getHIPsToBeDeactivated(SubscriptionResponse subscriptionResponse, List<GrantedSubscription> grantedSubscriptions) { Set<String> existingHipEntries = getAllExistingHIPsFromSources(subscriptionResponse); var currentExcludedHips = getHIPIdsFromGrantedSubscriptions(grantedSubscriptions); return Sets.difference(existingHipEntries, currentExcludedHips); } private Set<String> getAllExistingHIPsFromSources(SubscriptionResponse subscriptionResponse) { ArrayList<SubscriptionSource> allExistingSources = new ArrayList<>(); allExistingSources.addAll(subscriptionResponse.getIncludedSources()); allExistingSources.addAll(subscriptionResponse.getExcludedSources()); return getHIPIdsFromSources(allExistingSources); } private Set<String> getHIPIdsFromSources(List<SubscriptionSource> subscriptionSources) { return subscriptionSources.stream().map(source -> source.getHip().getId()).collect(Collectors.toSet()); } private Set<String> getHIPIdsFromGrantedSubscriptions(List<GrantedSubscription> grantedSubscriptions) { return grantedSubscriptions.stream().map(subscription -> subscription.getHip().getId()).collect(Collectors.toSet()); } }
true
b8e1b1c1db10535b9a8d98aebede2fd5522052ce
Java
ktokunaga3003/training
/workspace_sys/freemarknProto/src/jp/co/flm/util/Encryption.java
UTF-8
2,538
3.359375
3
[]
no_license
/** * jp.co.flm.util.Encryption * * All Rights Reserved, Copyright Fujitsu Learning Media Limited */ package jp.co.flm.util; import java.security.MessageDigest; import java.security.NoSuchAlgorithmException; /** * SHA256によるハッシュ化を実行するクラスです。 * @author FLM * @version 1.0 YYYY/MM/DD */ public class Encryption { /** * ハッシュ化の際にkeyに付加する文字列 * デフォルトは"FLMOnlineShoppStore" */ public static final String APPENDSTR = "FLMOnlineShoppStore"; /** * ハッシュ化の際のストレッチ回数 * デフォルトは1000 */ public static final int STRETCHCOUNT = 1000; /** * SHA256でtargetをハッシュ化し、16進数表記の文字列に変換した値を返却する。 * keyとAPPENDSTRにより作成されたソルト値を利用しているため、 * keyには重複しない値を指定すること * 戻り値であるハッシュ値はSTRETCHCOUNTで指定された回数ストレッチされている。 * * @param key ソルト値生成のための固有の値 * @param target ハッシュ化前の文字列 * @return ハッシュ化後の文字列 * @throws NoSuchAlgorithmException SHA256が利用できない場合 */ public static String getEncString(String key, String target) throws NoSuchAlgorithmException { // ソルト値 String salt = key + APPENDSTR; // 指定回数分ストレッチしたハッシュ値 String hash = ""; for (int i = 0; i < STRETCHCOUNT; i++) { hash = sha256(hash + salt + target); } return hash; } /** * SHA256でハッシュ化し、16進数表記の文字列に変換した値を返却する。 * @param beforeStr ハッシュ化前の文字列 * @return ハッシュ化後の文字列 * @throws NoSuchAlgorithmException SHA256が利用できない場合 * @throws IllegalArgumentException 引数がnullの場合 */ private static String sha256(String beforeStr) throws NoSuchAlgorithmException { // SHA256で暗号化したByte配列を取得する。 MessageDigest md = MessageDigest.getInstance("SHA-256"); md.update(beforeStr.getBytes()); byte[] hash = md.digest(); // 暗号化されたByte配列を16進数表記の文字列に変換する。 StringBuilder sb = new StringBuilder(); for (byte b : hash) { String hex = String.format("%02x", b); sb.append(hex); } String afterStr = sb.toString(); return afterStr; } }
true
6904c8fe10a95964d95de607c719af06a4eb2a6c
Java
jtallar/vestnet
/paw/model/src/main/java/ar/edu/itba/paw/model/enums/SearchField.java
UTF-8
877
2.890625
3
[]
no_license
package ar.edu.itba.paw.model.enums; /** * Enum for search fields */ public enum SearchField { PROJECT_NAME(1), PROJECT_SUMMARY(2), OWNER_NAME(3), OWNER_MAIL(4), PROJECT_LOCATION(5); private int value; SearchField(int value) { this.value = value; } /** Getters */ public int getValue() { return value; } /** * Gets the SearchField given the id. * @param id The id to search a match for. * @return The search field. PROJECT_NAME when there is no match. */ public static SearchField getEnum(int id) { for (SearchField field : values()) if (field.getValue() == id) return field; return PROJECT_NAME; } @Override public String toString() { return "SearchField{" + "value='" + value + '\'' + '}'; } }
true
b575b8511a442d540131a54a8b8c8167a882fa63
Java
3lectrologos/OpenCVTutorial
/src/com/tutorials/secondsight/filters/ImageDetectionFilter.java
UTF-8
6,484
2.109375
2
[]
no_license
package com.tutorials.secondsight.filters; import java.io.IOException; import java.util.ArrayList; import java.util.List; import org.opencv.android.Utils; import org.opencv.calib3d.Calib3d; import org.opencv.core.Core; import org.opencv.core.CvType; import org.opencv.core.Mat; import org.opencv.core.MatOfDMatch; import org.opencv.core.MatOfKeyPoint; import org.opencv.core.MatOfPoint; import org.opencv.core.MatOfPoint2f; import org.opencv.core.Point; import org.opencv.core.Scalar; import org.opencv.features2d.DMatch; import org.opencv.features2d.DescriptorExtractor; import org.opencv.features2d.DescriptorMatcher; import org.opencv.features2d.FeatureDetector; import org.opencv.features2d.KeyPoint; import org.opencv.highgui.Highgui; import org.opencv.imgproc.Imgproc; import android.content.Context; public class ImageDetectionFilter implements Filter { private final Mat mReferenceImage; private final MatOfKeyPoint mReferenceKeypoints = new MatOfKeyPoint(); private final Mat mReferenceDescriptors = new Mat(); private final Mat mReferenceCorners = new Mat(4, 1, CvType.CV_32FC2); private final MatOfKeyPoint mSceneKeypoints = new MatOfKeyPoint(); private final Mat mSceneDescriptors = new Mat(); private final Mat mCandidateSceneCorners = new Mat(4, 1, CvType.CV_32FC2); private final Mat mSceneCorners = new Mat(4, 1, CvType.CV_32FC2); private final MatOfPoint mIntSceneCorners = new MatOfPoint(); private final Mat mGraySrc = new Mat(); private final MatOfDMatch mMatches = new MatOfDMatch(); private final FeatureDetector mFeatureDetector = FeatureDetector.create(FeatureDetector.STAR); private final DescriptorExtractor mDescriptorExtractor = DescriptorExtractor.create(DescriptorExtractor.FREAK); private final DescriptorMatcher mDescriptorMatcher = DescriptorMatcher.create(DescriptorMatcher.BRUTEFORCE_HAMMING); List<Point> mDebug; private final Scalar mLineColor = new Scalar(0, 255, 0); public ImageDetectionFilter(final Context ctx, final int referenceImageResourceID) throws IOException { mReferenceImage = Utils.loadResource(ctx, referenceImageResourceID, Highgui.CV_LOAD_IMAGE_COLOR); final Mat referenceImageGray = new Mat(); Imgproc.cvtColor(mReferenceImage, referenceImageGray, Imgproc.COLOR_BGR2GRAY); Imgproc.cvtColor(mReferenceImage, mReferenceImage, Imgproc.COLOR_BGR2RGBA); mReferenceCorners.put(0, 0, new double[] {0, 0}); mReferenceCorners.put(1, 0, new double[] {referenceImageGray.cols(), 0}); mReferenceCorners.put(2, 0, new double[] {referenceImageGray.cols(), referenceImageGray.rows()}); mReferenceCorners.put(3, 0, new double[] {0, referenceImageGray.rows()}); mFeatureDetector.detect(referenceImageGray, mReferenceKeypoints); mDescriptorExtractor.compute(referenceImageGray, mReferenceKeypoints, mReferenceDescriptors); } @Override public void apply(Mat src, Mat dst) { Imgproc.cvtColor(src, mGraySrc, Imgproc.COLOR_RGBA2GRAY); mFeatureDetector.detect(mGraySrc, mSceneKeypoints); mDescriptorExtractor.compute(mGraySrc, mSceneKeypoints, mSceneDescriptors); mDescriptorMatcher.match(mSceneDescriptors, mReferenceDescriptors, mMatches); findSceneCorners(); draw(src, dst); } private void findSceneCorners() { mDebug = null; List<DMatch> matchesList = mMatches.toList(); if(matchesList.size() < 4) { // Too few matches to find homography return; } List<KeyPoint> referenceKeypointsList = mReferenceKeypoints.toList(); List<KeyPoint> sceneKeypointsList = mSceneKeypoints.toList(); double maxDist = 0; double minDist = Double.MAX_VALUE; for(DMatch match : matchesList) { double dist = match.distance; if(dist < minDist) minDist = dist; if(dist > maxDist) maxDist = dist; } if(minDist > 50) { mSceneCorners.create(0, 0, mSceneCorners.type()); return; } else if(minDist > 25) { return; } List<Point> goodReferencePointsList = new ArrayList<Point>(); List<Point> goodScenePointsList = new ArrayList<Point>(); double maxGoodMatchDist = 1.75 * minDist; for(DMatch match : matchesList) { if(match.distance < maxGoodMatchDist) { goodReferencePointsList.add( referenceKeypointsList.get(match.trainIdx).pt); goodScenePointsList.add(sceneKeypointsList.get(match.queryIdx).pt); } } if(goodReferencePointsList.size() < 4 || goodScenePointsList.size() < 4) { // Too few matches to find homography return; } mDebug = goodScenePointsList; // Find and apply homography MatOfPoint2f goodReferencePoints = new MatOfPoint2f(); goodReferencePoints.fromList(goodReferencePointsList); MatOfPoint2f goodScenePoints = new MatOfPoint2f(); goodScenePoints.fromList(goodScenePointsList); Mat h = Calib3d.findHomography(goodReferencePoints, goodScenePoints, Calib3d.FM_RANSAC, 5); Core.perspectiveTransform(mReferenceCorners, mCandidateSceneCorners, h); mCandidateSceneCorners.convertTo(mIntSceneCorners, CvType.CV_32S); if(Imgproc.isContourConvex(mIntSceneCorners)) { mCandidateSceneCorners.copyTo(mSceneCorners); } } protected void draw(final Mat src, final Mat dst) { if(dst != src) { src.copyTo(dst); } if(mSceneCorners.height() < 4) { int height = mReferenceImage.height(); int width = mReferenceImage.width(); int maxDimension = Math.min(dst.width(), dst.height()) / 2; double aspectRatio = width / (double) height; if(height > width) { height = maxDimension; width = (int)(height * aspectRatio); } else { width = maxDimension; height = (int)(width / aspectRatio); } Mat dstROI = dst.submat(0, height, 0, width); Imgproc.resize(mReferenceImage, dstROI, dstROI.size(), 0, 0, Imgproc.INTER_AREA); return; } Core.line(dst, new Point(mSceneCorners.get(0, 0)), new Point(mSceneCorners.get(1, 0)), mLineColor, 4); Core.line(dst, new Point(mSceneCorners.get(1, 0)), new Point(mSceneCorners.get(2, 0)), mLineColor, 4); Core.line(dst, new Point(mSceneCorners.get(2, 0)), new Point(mSceneCorners.get(3, 0)), mLineColor, 4); Core.line(dst, new Point(mSceneCorners.get(3, 0)), new Point(mSceneCorners.get(0, 0)), mLineColor, 4); } }
true
3f53a9ab2d0a34a779c76fc64e597793b6baeb3c
Java
VIXXPARK/javaAlgorithm
/programmers/전화번호목록/Solution.java
UTF-8
548
3.03125
3
[]
no_license
package programmers.전화번호목록; import java.util.*; public class Solution { public boolean solution(String[] phone_book){ Map<String,Boolean> map = new HashMap<>(); for(String number: phone_book){ map.put(number,true); } for(String number: phone_book){ for (int i = 0; i < number.length(); i++) { String temp = number.substring(0,i); if (map.containsKey(temp)) return false; } } return true; } }
true
cbf664ae8c64bd1a562e5b01ccd109567ad716e4
Java
michelleGong/ELog
/ELog/eloglibrary/src/main/java/com/mi/elog/FilePathGenerator.java
UTF-8
14,469
2.15625
2
[]
no_license
package com.mi.elog; import android.content.Context; import android.os.Environment; import android.os.SystemClock; import android.text.TextUtils; import com.mi.elog.acache.ACache; import java.io.File; import java.text.SimpleDateFormat; import java.util.Calendar; import java.util.Date; /** * 日志文件的生成器 * * @描述:该类根据需求的不同定义各种日志文件的存储策略 * @author:MichelleHong * @see */ public abstract class FilePathGenerator { public final String KEY_CURRENT_FILE_PATH = "current_log_file_path"; public final String KEY_ALL_FILE_NAME = "all_level_file_name"; public final String KEY_INFO_FILE_NAME = "info_level_file_name"; public final String KEY_ERROR_FILE_NAME = "error_level_file_name"; public final String KEY_DEBUG_FILE_NAME = "debug_level_file_name"; protected ACache aCache; protected String cacheDir = Environment.getExternalStorageDirectory()+File.separator+"cacheDir"+File.separator; protected final String FILENAMESPLIT = "-"; public static String logDirRoot = "/mnt/sdcard/androidYH/log"; public final static String LOGINALLFOLDER = "all_level"; public final static String LOGERRORFOLDER = "error_level"; public final static String LOGDEBUGFOLDER = "debug_level"; public final static String LOGINFOFOLDER = "info_level"; public final static String LOGWARNFOLDER = "warn_level"; public final static String LOGVERBOSEFOLDER = "verbose_level"; public static SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMdd"); protected String logFolder; public static String fileName_pre = "yhlog"; protected String suffix = ".log"; //上次写入的文件信息 /*protected String lastFileName; protected String lastFilePath; */ protected String targetpath; protected File file; protected String currentDateStr; protected long lastOperateTime = SystemClock.elapsedRealtime(); private FilePathGenerator() { throw new AssertionError(); } public FilePathGenerator(Context context, String fileName_pre, String suffix) { if (context == null) { throw new NullPointerException("while construct FilePathGenerator for wirting log to file,The context should not be null"); } if(TextUtils.isEmpty(logDirRoot)){ logDirRoot = context.getExternalFilesDir(null).getAbsolutePath() + File.separator + "log"; } if (!TextUtils.isEmpty(fileName_pre)) { this.fileName_pre = fileName_pre; } if (!TextUtils.isEmpty(suffix)) { this.suffix = suffix; } File file = getCacheDir(context); aCache = ACache.get(file); } private FilePathGenerator(Context context, String logDirRoot, String fileName_pre, String suffix) { this(context,fileName_pre,suffix); if (!TextUtils.isEmpty(logDirRoot)) { this.logDirRoot = logDirRoot; } } public FilePathGenerator(Context context, String fileName_pre, String suffix,boolean sharedCache) { if (context == null) { throw new NullPointerException("while construct FilePathGenerator for wirting log to file,The context should not be null"); } if(TextUtils.isEmpty(logDirRoot)){ logDirRoot = context.getExternalFilesDir(null).getAbsolutePath() + File.separator + "log"; } if (!TextUtils.isEmpty(fileName_pre)) { this.fileName_pre = fileName_pre; } if (!TextUtils.isEmpty(suffix)) { this.suffix = suffix; } if(sharedCache){ File file = new File(cacheDir); aCache = ACache.get(file); }else{ File file = getCacheDir(context); aCache = ACache.get(file); } } private FilePathGenerator(Context context, String logDirRoot, String fileName_pre, String suffix,boolean sharedCache) { this(context,fileName_pre,suffix,sharedCache); if (!TextUtils.isEmpty(logDirRoot)) { this.logDirRoot = logDirRoot; } } public abstract String generateFilePath(); public abstract boolean isNeedGenerate(); public abstract void onGernerate(String newPath, String oldPath); public synchronized final String getTargetpath() { long nowStamp = SystemClock.elapsedRealtime(); if(nowStamp - lastOperateTime > 1000){ Date currentDate = new Date(System.currentTimeMillis()); currentDateStr = sdf.format(currentDate); lastOperateTime = nowStamp; } if (isNeedGenerate()) { String newPath = generateFilePath(); onGernerate(newPath, targetpath); targetpath = newPath; } return targetpath; } public static class DefaultFilePathGenerator extends FilePathGenerator { public static long limitSingleLogFileSize = 1024 * 1024 * 10; //10M SimpleDateFormat sdf = FilePathGenerator.sdf; public DefaultFilePathGenerator(Context context, String fileName_pre, String suffix) { super(context, fileName_pre, suffix); } public DefaultFilePathGenerator(Context context, String logDirRoot, String fileName_pre, String suffix) { super(context, logDirRoot, fileName_pre, suffix); } public DefaultFilePathGenerator(Context context, String logDirRoot, String logFolder, String fileName_pre, String suffix) { super(context, logDirRoot, fileName_pre, suffix); this.logFolder = logFolder; } public DefaultFilePathGenerator(Context context, String fileName_pre, String suffix,boolean sharedCache) { super(context, fileName_pre, suffix,sharedCache); } public DefaultFilePathGenerator(Context context, String logDirRoot, String fileName_pre, String suffix,boolean sharedCache) { super(context, logDirRoot, fileName_pre, suffix,sharedCache); } public DefaultFilePathGenerator(Context context, String logDirRoot, String logFolder, String fileName_pre, String suffix,boolean sharedCache) { super(context, logDirRoot, fileName_pre, suffix,sharedCache); this.logFolder = logFolder; } @Override public String generateFilePath() { String path = null; if (TextUtils.isEmpty(logDirRoot)) { return path; //null } if (TextUtils.isEmpty(logFolder)) { return path; //null } File logDir = new File(logDirRoot + File.separator + logFolder); if (!logDir.exists()) { try { logDir.mkdirs(); } catch (Exception e) { e.printStackTrace(); } } // long nowStamp = SystemClock.elapsedRealtime(); // if(nowStamp - lastOperateTime > 1000*2){ // Date currentDate = new Date(System.currentTimeMillis()); // currentDateStr = sdf.format(currentDate); // lastOperateTime = nowStamp; // } if(TextUtils.isEmpty(currentDateStr)){ Date currentDate = new Date(System.currentTimeMillis()); currentDateStr = sdf.format(currentDate); } //创建日志文件 StringBuffer sb = new StringBuffer(); sb.append(fileName_pre); sb.append(FILENAMESPLIT); String lastFileName = ""; if(LOGINALLFOLDER.equals(logFolder)){ lastFileName = aCache.getAsString(KEY_ALL_FILE_NAME); android.util.Log.d("*DEBUG*1","1 "+lastFileName); }else if(LOGERRORFOLDER.equals(logFolder)){ lastFileName = aCache.getAsString(KEY_ERROR_FILE_NAME); }else if(LOGDEBUGFOLDER.equals(logFolder)){ lastFileName = aCache.getAsString(KEY_DEBUG_FILE_NAME); }else if(LOGINFOFOLDER.equals(logFolder)){ lastFileName = aCache.getAsString(KEY_INFO_FILE_NAME); } if(!TextUtils.isEmpty(lastFileName)){ String[] str_array = lastFileName.split(FILENAMESPLIT); if (str_array != null && str_array.length == 3) { android.util.Log.d("*DEBUG*2","2 "+currentDateStr+" "+str_array[1]); if (currentDateStr.equals(str_array[1])) { sb.append(currentDateStr); sb.append(FILENAMESPLIT); String str_last = str_array[2]; String[] suffix_array = str_last.split("\\."); if (suffix_array != null && suffix_array.length >= 2) { try { Integer fileIndex = Integer.parseInt(suffix_array[0]) + 1; sb.append(String.valueOf(fileIndex.intValue())); } catch (NumberFormatException e) { e.printStackTrace(); } } } else { sb.append(currentDateStr); sb.append(FILENAMESPLIT); sb.append("1"); } } else { sb.append(currentDateStr); sb.append(FILENAMESPLIT); sb.append("1"); } }else{ sb.append(currentDateStr); sb.append(FILENAMESPLIT); sb.append("1"); } sb.append(suffix); String strFilename = sb.toString(); file = new File(logDir, strFilename); if (!file.exists()) { try { file.createNewFile(); } catch (Exception e) { e.printStackTrace(); } } if(LOGINALLFOLDER.equals(logFolder)){ aCache.put(KEY_ALL_FILE_NAME,strFilename); android.util.Log.d("*DEBUG*3","3 "+strFilename); }else if(LOGERRORFOLDER.equals(logFolder)){ aCache.put(KEY_ERROR_FILE_NAME,strFilename); }else if(LOGDEBUGFOLDER.equals(logFolder)){ aCache.put(KEY_DEBUG_FILE_NAME,strFilename); }else if(LOGINFOFOLDER.equals(logFolder)){ aCache.put(KEY_INFO_FILE_NAME,strFilename); } path = file.getAbsolutePath(); return path; } @Override public boolean isNeedGenerate() { //the time that to write the log if(TextUtils.isEmpty(currentDateStr)){ Date currentDate = new Date(System.currentTimeMillis()); currentDateStr = sdf.format(currentDate); } String lastFileName = ""; if(LOGINALLFOLDER.equals(logFolder)){ lastFileName = aCache.getAsString(KEY_ALL_FILE_NAME); }else if(LOGERRORFOLDER.equals(logFolder)){ lastFileName = aCache.getAsString(KEY_ERROR_FILE_NAME); }else if(LOGDEBUGFOLDER.equals(logFolder)){ lastFileName = aCache.getAsString(KEY_DEBUG_FILE_NAME); }else if(LOGINFOFOLDER.equals(logFolder)){ lastFileName = aCache.getAsString(KEY_INFO_FILE_NAME); } if (TextUtils.isEmpty(lastFileName) || lastFileName == null || "".equals(lastFileName)) { return true; } else { File lastFile = new File(logDirRoot + File.separator + logFolder+File.separator+lastFileName); targetpath = logDirRoot + File.separator + logFolder+File.separator+lastFileName; if (lastFile == null || !lastFile.exists()) { return true; } if (lastFile.length() >= limitSingleLogFileSize) { return true; } String[] str_array = lastFileName.split(FILENAMESPLIT); if (str_array != null && str_array.length >= 3) { String lastfiledata = str_array[1]; if (currentDateStr.equals(lastfiledata)) { return false; } else { return true; } } else { return true; } } } @Override public void onGernerate(String newPath, String oldPath) { } } /** * 计算两个日期之间相差的天数 * * @param smdate 较小的时间 * @param bdate 较大的时间 * @return 相差天数 * @throws java.text.ParseException */ public static int daysBetween(Date smdate, Date bdate) throws java.text.ParseException { smdate = sdf.parse(sdf.format(smdate)); bdate = sdf.parse(sdf.format(bdate)); Calendar cal = Calendar.getInstance(); cal.setTime(smdate); long time1 = cal.getTimeInMillis(); cal.setTime(bdate); long time2 = cal.getTimeInMillis(); long between_days = (time2 - time1) / (1000 * 3600 * 24); return Integer.parseInt(String.valueOf(between_days)); } /** * 字符串的日期格式的计算 * * @throws java.text.ParseException */ public static int daysBetween(String smdate, String bdate) throws java.text.ParseException { Calendar cal = Calendar.getInstance(); cal.setTime(sdf.parse(smdate)); long time1 = cal.getTimeInMillis(); cal.setTime(sdf.parse(bdate)); long time2 = cal.getTimeInMillis(); long between_days = (time2 - time1) / (1000 * 3600 * 24); return Integer.parseInt(String.valueOf(between_days)); } public static File getCacheDir(Context context){ String cachePath; if(Environment.MEDIA_MOUNTED.equals(Environment.getExternalStorageState()) || !Environment.isExternalStorageRemovable()){ cachePath = context.getExternalCacheDir().getPath(); }else{ cachePath = context.getCacheDir().getPath(); } return new File(cachePath + File.separator + "ylogcache"+File.separator); } }
true
024abdb4fdf2402918b31312e5d32db159c17f0f
Java
Esaron/apps
/wakeOnLanServlet/src/servlet/WoLServlet.java
UTF-8
948
2.5
2
[]
no_license
package servlet; import java.io.IOException; import java.io.PrintWriter; import javax.servlet.*; import javax.servlet.http.*; public class WoLServlet extends HttpServlet { /** * */ private static final long serialVersionUID = -3385386385030875197L; public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { PrintWriter out = response.getWriter(); StringBuilder sb = new StringBuilder(); sb.append("<html>"); sb.append("<body>"); sb.append("<h1>Hi! Click the button below to turn on the server!</h1>"); sb.append("<form ACTION=\"/wake/perform\" METHOD=\"POST\">"); sb.append("<input name=\"send\" type=\"submit\" value=\"Wake Server\" />"); sb.append("</form>"); sb.append("</body>"); sb.append("</html>"); out.println(sb.toString()); } }
true
4aa375fd370999de267f0f4a3e0b924b6c60b4dc
Java
squirrelSun/Data_Structure
/Queue/MyQueue.java
UTF-8
640
3.40625
3
[]
no_license
package Queue; public class MyQueue { int[] elements; public MyQueue() { elements = new int[0]; } public void show() { for(int i=0;i<elements.length;i++) System.out.println(elements[i]); } public void add(int element) { int[] Arrery=new int[elements.length+1]; Arrery[Arrery.length-1]=element; for(int i=0;i<elements.length;i++) Arrery[i]=elements[i]; elements=Arrery; } public int poll() { int element=elements[0]; int[] Arrery=new int[elements.length-1]; for(int i=0;i<Arrery.length;i++) Arrery[i]=elements[i+1]; elements=Arrery; return element; } }
true
97e2945318e4afa2b1adf3cf47b3a108f2639966
Java
Goldiriath/Goldiriath
/src/main/java/net/goldiriath/plugin/game/mobspawn/MobSpawnProfile.java
UTF-8
9,888
2.03125
2
[]
no_license
package net.goldiriath.plugin.game.mobspawn; import java.util.HashSet; import java.util.Set; import java.util.logging.Logger; import lombok.Getter; import net.citizensnpcs.api.npc.NPC; import net.goldiriath.plugin.Goldiriath; import net.goldiriath.plugin.game.loot.LootProfile; import net.goldiriath.plugin.game.citizens.HostileMobBehavior; import net.goldiriath.plugin.game.citizens.HostileMobTrait; import net.goldiriath.plugin.util.ConfigLoadable; import net.goldiriath.plugin.util.Util; import net.goldiriath.plugin.util.Validatable; import net.pravian.aero.component.PluginComponent; import org.bukkit.ChatColor; import org.bukkit.Location; import org.bukkit.configuration.ConfigurationSection; import org.bukkit.entity.Ageable; import org.bukkit.entity.Entity; import org.bukkit.entity.EntityType; import org.bukkit.entity.LivingEntity; import org.bukkit.entity.Zombie; import org.bukkit.inventory.EntityEquipment; import org.bukkit.inventory.ItemStack; import org.bukkit.potion.PotionEffect; import org.bukkit.potion.PotionEffectType; public class MobSpawnProfile extends PluginComponent<Goldiriath> implements ConfigLoadable, Validatable { public static final int INFINITE_POTION_DURATION = 1000000; public static final int WANDER_RANGE = 15; // @Getter private final String id; @Getter private final MobSpawnManager manager; private final Logger logger; // @Getter private String customName; @Getter private long timeThreshold; @Getter private EntityType type; @Getter private int level; @Getter private int damage; @Getter private int health; @Getter private MobTier lootTier; @Getter private LootProfile lootProfile; @Getter private ItemStack hand; @Getter private ItemStack helmet; @Getter private ItemStack chestplate; @Getter private ItemStack leggings; @Getter private ItemStack boots; @Getter private final Set<PotionEffect> effects; public MobSpawnProfile(MobSpawnManager manager, String id) { super(manager.getPlugin()); this.id = id; this.manager = manager; this.logger = manager.getPlugin().getLogger(); this.effects = new HashSet<>(); } public NPC spawn(Location location) { final NPC npc; if (type == EntityType.PLAYER) { throw new UnsupportedOperationException("Players are not yet supported!"); } else { npc = manager.getPlugin().czb.createMob(type); } // Spawn npc.spawn(location); npc.setProtected(true); npc.addTrait(new HostileMobTrait(this)); npc.getDefaultGoalController().addBehavior(new HostileMobBehavior(manager.getPlugin(), npc, location, WANDER_RANGE), 1); // Setup final Entity entity = npc.getEntity(); if (!(entity instanceof LivingEntity)) { npc.destroy(); throw new UnsupportedOperationException("Non-living entities are not supported!"); } final LivingEntity mob = (LivingEntity) entity; // Set baby if (mob instanceof Zombie) { ((Zombie) mob).setBaby(false); } else if (entity instanceof Ageable) { ((Ageable) mob).setAdult(); } // Potion effects mob.addPotionEffects(effects); // Custom name if (customName != null) { npc.setName(customName); mob.setCustomName(customName); mob.setCustomNameVisible(true); } // Set equipment final EntityEquipment equipment = mob.getEquipment(); mob.setCanPickupItems(false); equipment.setItemInHandDropChance(0); if (hand != null) { equipment.setItemInHand(hand); } equipment.setHelmetDropChance(0); if (helmet != null) { equipment.setHelmet(helmet); } equipment.setChestplateDropChance(0); if (chestplate != null) { equipment.setChestplate(chestplate); } equipment.setLeggingsDropChance(0); if (leggings != null) { equipment.setLeggings(leggings); } equipment.setBootsDropChance(0); if (boots != null) { equipment.setBoots(boots); } return npc; } @Override public void loadFrom(ConfigurationSection config) { // Meta customName = config.getString("name", null); if (customName != null) { customName = ChatColor.translateAlternateColorCodes('&', customName); } timeThreshold = config.getInt("spawn_threshold", -1); final String entityTypeName = config.getString("type", null); if (entityTypeName == null) { type = null; } else { try { type = EntityType.valueOf(entityTypeName); } catch (IllegalArgumentException ex) { type = null; logger.warning("Could not load mobspawn profile '" + id + "'. Invalid entity type: " + entityTypeName); } } // Stats level = config.getInt("stats.level", -1); if (level == -1) { logger.warning("Could not load mobspawn profile '" + id + "'. Level field not present."); } damage = config.getInt("stats.damage", -1); health = config.getInt("stats.health", -1); if (health == -1) { logger.warning("Could not load mobspawn profile '" + id + "'. Health field not present."); } // Loot if (!config.contains("loot")) { lootProfile = null; lootTier = null; } else { String profileId = config.getString("loot.profile", null); lootProfile = plugin.ltm.getProfile(profileId); if (lootProfile == null) { logger.warning("Could not load mobspawn profile '" + id + "'. Invalid loot table id: " + profileId); } String tierName = config.getString("loot.tier", null); try { // TODO: Numerical mob tier support lootTier = MobTier.valueOf(tierName); } catch (Exception ex) { lootTier = null; logger.warning("Could not load mobspawn profile '" + id + "'. Invalid loot table id: " + tierName); } } // Items if (!config.contains("items")) { hand = null; helmet = null; chestplate = null; leggings = null; boots = null; } else { String s = config.getString("items.hand", null); if (s != null) { hand = Util.parseItem(s); if (hand == null) { logger.warning("Could not load mobspawn profile '" + id + "'. Invalid item: " + s); } } s = config.getString("items.helmet", null); if (s != null) { helmet = Util.parseItem(s); if (helmet == null) { logger.warning("Could not load mobspawn profile '" + id + "'. Invalid item: " + s); } } s = config.getString("items.chestplate", null); if (s != null) { chestplate = Util.parseItem(s); if (chestplate == null) { logger.warning("Could not load mobspawn profile '" + id + "'. Invalid item: " + s); } } s = config.getString("items.leggings", null); if (s != null) { leggings = Util.parseItem(s); if (leggings == null) { logger.warning("Could not load mobspawn profile '" + id + "'. Invalid item: " + s); } } s = config.getString("items.boots", null); if (s != null) { boots = Util.parseItem(s); if (boots == null) { logger.warning("Could not load mobspawn profile '" + id + "'. Invalid item: " + s); } } } if (damage == -1 && hand == null) { logger.warning("Could not load mobspawn profile '" + id + "'. Damage field not present and item not present. Must specify either to calculate attack damage."); } // Effects effects.clear(); if (config.contains("potions")) { for (String potionTypeName : config.getConfigurationSection("potions").getKeys(false)) { final PotionEffectType effectType = PotionEffectType.getByName(potionTypeName); if (effectType == null) { logger.warning("Ignoring potion effect for profile '" + id + "'. Unrecognised potion type: " + potionTypeName + "!"); continue; } final int amplifier = config.getInt("potions." + potionTypeName + ".amplifier", 1); final boolean ambient = config.getBoolean("potions." + potionTypeName + ".ambient", false); int duration = config.getInt("potions." + potionTypeName + ".duration", 200); if (duration <= 0) { duration = INFINITE_POTION_DURATION; } final PotionEffect effect = new PotionEffect(effectType, duration, amplifier, ambient); effects.add(effect); } } } public boolean hasTimeThreshold() { return timeThreshold >= 0; } @Override public boolean isValid() { return id != null && type != null && type.isAlive() && type.isSpawnable() && level != -1 && (damage != -1 || hand != null) && health != -1; } }
true
9119d8dab56a89288cf21b42b8eed49a05fb8d9e
Java
MJohn2/OOP-Assignment2
/src/assignment2/PostGrad.java
UTF-8
7,431
3.640625
4
[]
no_license
/** * PostGrad Class * Michael John * 19/10/2019 * PostGrad.java * * PostGrad.class is derived from the Student.Class. It has new variables to * allow getting marks from the user and computing the unit final mark for * PostGraduate students. * * * @author Michael John * @version 1.0 * @since 19/10/2019 */ package assignment2; import java.util.Scanner; class PostGrad extends Student{ double groupAssignment; double groupPresentation; double finalExam; final static int MAX_GROUPASSIGNMENT_SCORE = 100; final static int MAX_GROUPPRESENTATION_SCORE = 100; final static int MAX_FINALEXAM_MARKS = 100; //weights of how much assessments contribute to finalMark final static int GROUPASSIGNMENT_WEIGHT = 30; final static int GROUPPRESENTATION_WEIGHT = 20; final static int FINALEXAM_WEIGHT = 50; Scanner keyboard = new Scanner(System.in); /** * Overrides Student Class base constructor */ PostGrad(){ super(); } /** * Overrides Student Class constructor that sets PostGrad object with passed parameters * @param setTitle String - Students Title * @param first String - Students Title * @param last String - Students Title * @param number long - Students studentID * @param day Integer - Students day of birth * @param month Integer - Students month of birth * @param year Integer - Students year of birth */ PostGrad(String setTitle, String first, String last, long number, int day, int month, int year){ super(setTitle, first, last, number, day, month, year); } /** * Mutator to set this PostGraduates group assignment score * Contains error checking to ensure score entered is within allowable range */ public void setGroupAssignment(){ do{ System.out.println("Enter the mark for the Assignment (0-100)"); groupAssignment = Student.getInt(); } while (groupAssignment < 0 || groupAssignment > MAX_GROUPASSIGNMENT_SCORE); } /** * Mutator to set this PostGraduates group presentation score * Contains error checking to ensure score entered is within allowable range */ public void setGroupPresentation(){ do{ System.out.println("Enter the mark for the Group Presentation (0-100)"); groupPresentation = Student.getInt(); } while (groupPresentation < 0 || groupPresentation > MAX_GROUPPRESENTATION_SCORE); } /** * Mutator to set this PostGraduates group final exam score * Contains error checking to ensure score entered is within allowable range */ public void setFinalExam(){ do{ System.out.println("Enter the mark for the Final Exam (0-100)"); finalExam = Student.getInt(); } while (finalExam < 0 || finalExam > MAX_FINALEXAM_MARKS); } /** * Calls methods to set marks for all of this PostGrads assessments * Includes setGroupAssignment(), setGroupPresentation() and setFinalExam() */ @Override public void setMarks(){ setGroupAssignment(); setGroupPresentation(); setFinalExam(); } /** * Sets all marks for this student - used for testing * Expects students marks for assessments passed as parameters * No error checking provided * @param assignment Double - assignment score * @param presentation Double - presentation score * @param exam Double - exam score */ public void setMarks(double Assignment, double Presentation, double Exam){ //testing!!!! groupAssignment = Assignment; groupPresentation = Presentation; finalExam = Exam; } /** * Computes and sets this students Final mark * Computes this PostGrads scores for assessments then computes assessment contributions to final mark * Requires PostGrad to have marks entered previously * Uses Student.setGrade(overallMark) to get PostGrads grade * Overrides ancestor Student Class method */ @Override public void computeMark(){ double overallMark; overallMark = (groupAssignment / 100) * GROUPASSIGNMENT_WEIGHT; overallMark = overallMark + (groupPresentation / 100) * GROUPPRESENTATION_WEIGHT; overallMark = overallMark + (finalExam / MAX_FINALEXAM_MARKS) * FINALEXAM_WEIGHT; setGrade(overallMark); } /** * Prints average of Final marks for students * Expects PostGrads marks to be entered * Overrides by ancestor Student class * Contains exception handling for divide by 0 if no student marks entered yet * @param array Array of Students find PostGrads to compute the combined average mark * @return Returns the PostGrads combined average as a double */ public static double getStudentsAverage(Student[] array){ double marksTotal = 0; int studentsCount = 0; //checks whole array for Postgrad objects and combines total of finalMarks for(int i = 0; i < array.length; i++){ if(array[i] instanceof PostGrad){ studentsCount++; marksTotal = marksTotal + array[i].getMark(); //uses ancestor Student.getMark() to get private finalMark } } //prevents division by 0 which will always happen as no student marks have been entered try{ if(studentsCount == 0) throw new Exception("Can not divide by 0"); } catch(Exception e){ System.out.println(e.getMessage()); System.out.println("No student overall marks entered"); System.out.println("Input student data before choosing students average mark"); return(0); } return marksTotal / studentsCount; } /** * Compares PostGrad's finalMark with the class average * Overrides ancestor class * @param array The array of students to get PostGrad's from and compare to the PostGrad average */ public static void aboveAverage(Student[] array){ double average = PostGrad.getStudentsAverage(array); int postGradsCount = 0; int aboveAverageCount = 0; if(average != 0){ for(int i = 0; i < arrayEntryLength(array); i++){ if(array[i] instanceof PostGrad){ postGradsCount++; if(array[i].getMark() >= average) aboveAverageCount++; } } System.out.println(aboveAverageCount + " Postgraduates scored equal to or above average"); System.out.println(postGradsCount - aboveAverageCount + " Postgraduates scored below average\n"); } else System.out.println("Computing average mark failed. Enter students marks first\n"); } /** * Print all PostGrad information to screen including final mark and grade * Excludes individual assessment marks * @return Returns all student information printed to screen, formatted with titles * @Override Overrides Student toString() */ @Override public String toString(){ return "PostGraduate\n" + super.toString(); } }
true
7e2b8aa0ff1185b538e812d87fe854efca0fa510
Java
JamesVeug/Hotel
/src/Objects/Entity.java
UTF-8
5,399
3.046875
3
[]
no_license
package Objects; import java.awt.*; import java.util.*; import java.io.File; import javax.swing.ImageIcon; import Hotel.HotelMap; import Hotel.MapPoint; import java.awt.geom.Rectangle2D; public class Entity extends ObjectBase { protected File entityFile; protected Dimension size; protected ImageIcon drawImage; // All extra properties for the entity such as "nextLevel" for doors protected Map<String,String> properties = new HashMap<String,String>(); public Entity(){} /** * When importing the entity list, this will assign all the properties for the entity * Scanner is also used to assign the entity buttons to our entity selection list found in /Entities. * *Class *{ * Key * { * Property * } * . * . * . *} */ public Entity(String D, Scanner scan) { while(scan.hasNext()) { // End of entity if(scan.hasNext("}")) { // No more to add into this scanner break; } // Property Key Name String key = scan.next(); // Start of property scan.next(); // { if(key.equalsIgnoreCase("Image")){ saveImage(scan.next()); } else if(key.equalsIgnoreCase("ID")){ setID(scan.next()); } else if(key.equalsIgnoreCase("MapPoint")){ setPosition(new MapPoint(scan.nextDouble(),scan.nextDouble(),scan.nextDouble())); } else{ putProperty(key,scan.next()); } scan.next(); // } } } /** * Makes a clone of the given entityType * If a placedMapPoint is not supplied, then the entity will be given the same position as the supplied entityType */ public Entity(Entity entityType, MapPoint... placedMapPoint){ // Copy the instructions of the given entityType saveImage(entityType.getDirectory()); properties.putAll(entityType.properties); size = new Dimension( drawImage.getIconWidth(), drawImage.getIconHeight() ); if( placedMapPoint.length > 0 ) position = new MapPoint(placedMapPoint[0]); else position = new MapPoint(entityType.getPosition()); } /** * Draws the image of the entity */ public void draw(Graphics g, HotelMap map){ draw(g); }; /** * Draws the image of the entity */ public void draw(Graphics g){ g.drawImage(drawImage.getImage(), position.getX(), position.getY(), size.width, size.height, null); }; /** * Assigns a new ImageIcon to the direct image in the directory and sets up the dimensions of the icon. */ public void saveImage(String directory){ //drawImage_directory = directory; entityFile = new File(directory); drawImage = new ImageIcon(directory); size = new Dimension( drawImage.getIconWidth(), drawImage.getIconHeight() ); } /** * Returns an ArrayList of Strings that contain which should be saved from this class and it's super classes */ public ArrayList<String> getSaveInfo() { ArrayList<String> saveInfo = new ArrayList<String>(); saveInfo.addAll(super.getSaveInfo()); saveInfo.add("SaveCharacter"); saveInfo.add("{"); saveInfo.add("\t" + getProperty("SaveCharacter").charAt(0)); saveInfo.add("}"); saveInfo.add("Image"); saveInfo.add("{"); saveInfo.add("\t" + drawImage.getDescription()); saveInfo.add("}"); for(String key : properties.keySet()){ saveInfo.add(key); saveInfo.add("{"); saveInfo.add("\t" + properties.get(key)); saveInfo.add("}"); } return saveInfo; } public boolean on(double x, double y, double z){ return ( x >= position.X() && x <= (position.X()+size.width) && y >= position.Y() && y <= (position.Y()+size.height) ); } public boolean on(MapPoint point){ return ( point.X() >= position.X() && point.X() <= (position.X()+size.width) && point.Y() >= position.Y() && point.Y() <= (position.Y()+size.height) ); } public int width(){ return size.width; } public int height(){ return size.height; } public String getDirectory(){ return entityFile.getAbsolutePath(); } /** * Unique Properties of the Entity that are defined in entityList.txt or when loading a saved Map */ public String getProperty(String key){ return properties.get(key); } public Map<String,String> getProperties(){ return properties; } public boolean hasProperty(String key){ return properties.containsKey(key); } public void putProperty(String key, String value){ properties.put(key,value); } public Rectangle2D getBounds(){ return new Rectangle2D.Double(position.X(),position.Y(),size.width, size.height); } public void drawSelection(Graphics g) { MapPoint pos = new MapPoint(position).translate(-2, -2, 0); Image img = new ImageIcon("resources/Entities/sprites/selection.png").getImage(); g.drawImage(img,pos.getX(),pos.getY(),size.width+4,size.height+4,null); } }
true
574a8a15e016b9d26c260e13dd43c6fc676f213a
Java
czarscripting/OSBot2
/DreamBlaster/src/com/blaster/util/ScriptTimer.java
UTF-8
669
2.828125
3
[]
no_license
package com.blaster.util; import java.util.Date; public class ScriptTimer { public long start; private Date lastDate; public ScriptTimer start() { return new ScriptTimer(); } public ScriptTimer() { reset(); } public ScriptTimer reset() { start = System.currentTimeMillis(); return this; } public long time() { long end = System.currentTimeMillis(); return end - start; } public int getSeconds() { return (int) (time() / 1000L); } public int getMinutes() { return (int) (getSeconds() / 60L); } public int getHours() { final int sec = (int) (time() / 1000), h = sec / 3600, m = sec / 60 % 60, s = sec % 60; return (int) h; } }
true
2f3d05346c09aa6851b424a476ca6d87891c4721
Java
julischuster/Ejercicio1
/src/paquete/MainActivity.java
UTF-8
989
2.765625
3
[]
no_license
package paquete; public class MainActivity { public static PaqueteTuristico paquetemascaro; public static double preciomascaro = 0; public static void main(String args[]) { Individuo cliente1 = new Cliente("juan", 2000); Paquetes paquetehabitaciones = new PaqueteHabitaciones(50, 2, 1.2); Paquetes paquetefijo = new PaqueteFijo(500, 1.25); Paquetes paquetesaldo = new PaqueteSaldo(1.1); PaqueteTuristico paquete1 = new PaqueteTuristico(paquetefijo); PaqueteTuristico paquete2 = new PaqueteTuristico(paquetehabitaciones); double precio = cliente1.comprarPaquete(paquete1); if(precio > preciomascaro){ preciomascaro = precio; paquetemascaro = paquete1; } cliente1.comprarPaquete(paquete2); System.out.println(preciomascaro + ""); System.out.println(cliente1.getSaldo() + ""); System.out.println(cliente1.getListaPaquetesComprados().size()); System.out.println(cliente1.getGastosTotales()); } public void validarsieselmascaro(){ } }
true
e44da3fce65501e0caa9561576ff716574dd6f42
Java
AD-SergioRamos5/Ejercicios-Propuestos-6
/Ejercicios Propuestos 6/Ejercicio3.java
UTF-8
1,427
3.46875
3
[]
no_license
import java.io.*; import java.util.Scanner; import java.nio.charset.StandardCharsets; public class Ejercicio3 { public static void main(String [] args) { if (! (new File("anotaciones.txt")).exists() ) { System.out.println("No he encontrado anotaciones.txt"); return; } System.out.println("Leyendo fichero..."); Scanner entrada; try { BufferedReader fichero = new BufferedReader(new InputStreamReader(new FileInputStream("anotaciones.txt"), StandardCharsets.UTF_8)); String linea = null; linea = fichero.readLine(); String seguir; entrada = new Scanner(System.in); int contador = 0; while (linea != null) { System.out.println(linea); linea = fichero.readLine(); contador++; if(contador == 10) { contador = 0; System.out.println("Pulsa Enter para continuar..."); seguir= entrada.nextLine(); } } fichero.close(); } catch (IOException e) { System.out.println( "Ha habido problemas: " + e.getMessage() ); } System.out.println("Fin de la lectura."); } }
true
d7c0d67f7b363cfa2a9017e7b269a62afaba6f66
Java
lsylive/DataAnalysis
/analysisCommon/src/com/liusy/web/tag/ButtonTag.java
UTF-8
2,162
1.9375
2
[]
no_license
// ButtonTag.java package com.liusy.web.tag; import com.liusy.core.util.Const; import com.liusy.core.util.Session; import java.util.Map; import javax.servlet.http.HttpSession; import javax.servlet.jsp.JspException; import javax.servlet.jsp.PageContext; import javax.servlet.jsp.tagext.BodyContent; // Referenced classes of package com.liusy.web.tag: // BaseTag, TagUtils public class ButtonTag extends BaseTag { private static final long serialVersionUID = 1L; private String value; private String code; private String icon; public ButtonTag() { } public int doStartTag() throws JspException { return 2; } public int doEndTag() throws JspException { Session session = (Session)pageContext.getSession().getAttribute(Const.SESSION); if (code != null && !code.equals("") && !session.getPrivileges().containsKey(code)) return 6; StringBuffer out = new StringBuffer(""); out.append("<a "); if (styleid != null) out.append((new StringBuilder(" id=\"")).append(styleid).append("\"").toString()); if (name != null) out.append((new StringBuilder(" name=\"")).append(name).append("\"").toString()); if (styleClass != null) out.append((new StringBuilder(" class=\"")).append(styleClass).append("\"").toString()); else out.append(" class=\"btnStyle\""); if (onclick != null) out.append((new StringBuilder(" href=\"javascript:")).append(onclick).append(";\"").toString()); if (title != null) out.append((new StringBuilder(" title=\"")).append(title).append("\"").toString()); out.append(" ><strong>"); if (icon != null) out.append((new StringBuilder("<span class=\"")).append(icon).append("\">&nbsp;</span>").toString()); out.append(getBodyContent().getString()); out.append("</strong></a>"); TagUtils.write(pageContext, out.toString()); return 6; } public void release() { super.release(); value = null; } public void setValue(String x) { value = x; } public String getCode() { return code; } public void setCode(String code) { this.code = code; } public String getIcon() { return icon; } public void setIcon(String icon) { this.icon = icon; } }
true
fa35a8c5f30a63fd7e1ae659e418ea2e31bc1fb1
Java
SenchenkoDV/JD2016-08-29
/src/by/it/emelyanov/jd02_05/Message.java
UTF-8
211
1.835938
2
[]
no_license
package by.it.emelyanov.jd02_05; public interface Message { String MESSAGE_WELCOME = "message.welcome"; String MESSAGE_USERNAME = "message.username"; String MESSAGE_QUESTION = "message.question"; }
true
8f4768ba6ae6a83fedcac9fd21a0dcae7e298103
Java
1wangxueyan2/SKS-MC
/src/com/more/mes/aps/month/base/MonthAction.java
UTF-8
3,132
1.695313
2
[]
no_license
package com.more.mes.aps.month.base; import java.util.List; import javax.servlet.http.HttpServletRequest; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; import com.more.fw.core.base.core.action.ModelAction; import com.more.fw.core.base.login.model.UserDto; import com.more.fw.core.common.method.CommMethod; import com.more.fw.core.common.method.Constants; import com.more.fw.core.common.method.SpringContextUtil; import com.more.fw.core.dbo.model.service.ModelService; import com.more.fw.core.dbo.model.service.impl.base.FuncService; import com.more.mes.aps.service.base.GetCommonInfo; /** * 要根据对应的视图模型/基础信息:视图公用类的名称来替换继承类SuperServer * */ public class MonthAction implements FuncService { private static final ModelService modelService = (ModelService) SpringContextUtil.getBean("modelService"); private static final String PC_PREFIX = "DJ26"; private static final Log log = LogFactory.getLog("com.more.mes.aps.service.MonthAction"); @SuppressWarnings({ "static-access" }) @Override public String exeFunc(ModelAction modelAction, ModelService modelService) { HttpServletRequest request = modelAction.getRequest(); UserDto loginUser = CommMethod.getSessionUser(); String oper = request.getParameter("operator"); //--------------------------------------------------------------update by cc 2018-5-21 String jsonData=null; List ajaxList=null; HttpServletRequest httpServletRequest = modelAction.getRequest(); if("getMonthGantt".equals(oper)){ jsonData=GetCommonInfo.getMonthGantt(httpServletRequest); } else if("saveMonthGantt".equals(oper)){ jsonData=GetCommonInfo.saveMonthGantt(httpServletRequest,modelAction,modelService).toString(); } else if("deleteMonthPlanTask".equals(oper)){ jsonData=GetCommonInfo.deleteMonthPlanTask(httpServletRequest,modelService).toString(); } /*else if("getSplitInfo".equals(oper)){ ajaxList=GetCommonInfo.getSplitInfo(httpServletRequest); }*/ else if("saveSplit".equals(oper)){ jsonData=GetCommonInfo.saveSplit(httpServletRequest,modelAction,modelService).toString(); } else if("getMonthPlanDoc".equals(oper)){ ajaxList=GetCommonInfo.getMonthPlanDoc(httpServletRequest,modelAction,modelService); } else if("getSingleStepWorkTime".equals(oper)){ jsonData=GetCommonInfo.getSingleStepWorkTime(httpServletRequest); } else if("getProjectByContian".equals(oper)){ ajaxList=GetCommonInfo.getProjectByContian(httpServletRequest); } else if("validateMonthCanToDelete".equals(oper)){ ajaxList=GetCommonInfo.validateMonthCanToDelete(httpServletRequest); } else if("getPlanMonumberInfo".equals(oper)){ ajaxList=GetCommonInfo.getPlanMonumberInfo(httpServletRequest); } if(null!=jsonData){//直接返回json,适用于没有分页的情况下 return modelAction.outJson(jsonData,Constants.CHARACTER_ENCODING_UTF_8); } else if(null!=ajaxList){//返回List,适用于有分页的情况下 modelAction.setAjaxList(ajaxList); return modelAction.AJAX; } else { return modelAction.AJAX; } } }
true
93f268599beb93623eaf01b5e008a3f2956516aa
Java
kalyssao/tlc_trader
/src/Bond.java
UTF-8
269
2.6875
3
[]
no_license
public class Bond extends Trade{ private double dividend; public double calcDividend(){ return this.dividend; } Bond(String id, String symbol, int quantity, double div){ super(id, symbol, quantity); this.dividend = div; } }
true
58999b492124730184cd0c8f86f29b038d093942
Java
hammedopejin/Capstone-Stage-2---Freegan
/app/src/main/java/com/planetpeopleplatform/freegan/utils/Utils.java
UTF-8
16,066
1.828125
2
[ "Apache-2.0" ]
permissive
package com.planetpeopleplatform.freegan.utils; import android.app.Activity; import android.content.Context; import android.database.Cursor; import android.graphics.Bitmap; import android.graphics.BitmapFactory; import android.net.Uri; import android.os.Environment; import android.os.ParcelFileDescriptor; import android.provider.MediaStore; import android.support.annotation.NonNull; import android.support.design.widget.CoordinatorLayout; import android.support.design.widget.Snackbar; import android.text.TextUtils; import com.google.firebase.auth.FirebaseAuth; import com.google.firebase.database.DataSnapshot; import com.google.firebase.database.DatabaseError; import com.google.firebase.database.DatabaseReference; import com.google.firebase.database.ValueEventListener; import com.planetpeopleplatform.freegan.R; import com.planetpeopleplatform.freegan.model.Message; import com.planetpeopleplatform.freegan.model.User; import java.io.Closeable; import java.io.File; import java.io.FileDescriptor; import java.io.FileInputStream; import java.io.FileNotFoundException; import java.io.FileOutputStream; import java.io.IOException; import java.text.DateFormat; import java.text.SimpleDateFormat; import java.util.Date; import java.util.HashMap; import java.util.List; import java.util.Locale; import static butterknife.internal.Utils.listOf; import static com.planetpeopleplatform.freegan.utils.Constants.firebase; import static com.planetpeopleplatform.freegan.utils.Constants.kCHATROOMID; import static com.planetpeopleplatform.freegan.utils.Constants.kCOUNTER; import static com.planetpeopleplatform.freegan.utils.Constants.kDATE; import static com.planetpeopleplatform.freegan.utils.Constants.kLASTMESSAGE; import static com.planetpeopleplatform.freegan.utils.Constants.kMEMBERS; import static com.planetpeopleplatform.freegan.utils.Constants.kMESSAGE; import static com.planetpeopleplatform.freegan.utils.Constants.kMESSAGEID; import static com.planetpeopleplatform.freegan.utils.Constants.kPOSTID; import static com.planetpeopleplatform.freegan.utils.Constants.kPRIVATE; import static com.planetpeopleplatform.freegan.utils.Constants.kRECENT; import static com.planetpeopleplatform.freegan.utils.Constants.kRECENTID; import static com.planetpeopleplatform.freegan.utils.Constants.kSTATUS; import static com.planetpeopleplatform.freegan.utils.Constants.kTYPE; import static com.planetpeopleplatform.freegan.utils.Constants.kUSERID; import static com.planetpeopleplatform.freegan.utils.Constants.kWITHUSERUSERID; import static com.planetpeopleplatform.freegan.utils.Constants.kWITHUSERUSERNAME; public class Utils { private static final String SCHEME_FILE = "file"; private static final String SCHEME_CONTENT = "content"; private static final String TAG = Utils.class.getSimpleName(); public final static String DF_SIMPLE_STRING_WITH_DETAILS = "yyyy-MM-dd hh:mm:ss a"; public final static String DF_SIMPLE_STRING = "yyyyMMdd_HHmmss"; public static String startChat(User user1, User user2, String postId) { String userId1 = user1.getObjectId(); String userId2 = user2.getObjectId(); String chatRoomId = ""; int value = userId1.compareTo(userId2); if (value < 0) { chatRoomId = userId1 + userId2 + postId; } else { chatRoomId = userId2 + userId1 + postId; } List<String> members = listOf(userId1, userId2); createRecent(userId1, chatRoomId, members, userId2, user2.getUserName(), postId, kPRIVATE); createRecent(userId2, chatRoomId, members, userId1, user1.getUserName(), postId, kPRIVATE); return chatRoomId; } public static void updateChatStatus(HashMap<String, Object> message, String chatRoomId) { HashMap<String, Object> values = new HashMap<String, Object>(); values.put(kSTATUS, Message.STATUS_READ); firebase.child(kMESSAGE).child(chatRoomId).child(((String) message.get(kMESSAGEID))).updateChildren(values); } private static void createRecent(final String userId, final String chatRoomId, final List<String> members, final String withUserUserId, final String withUserUsername, final String postId, final String type) { firebase.child(kRECENT).orderByChild(kCHATROOMID).equalTo(chatRoomId) .addListenerForSingleValueEvent(new ValueEventListener() { @Override public void onDataChange(@NonNull DataSnapshot dataSnapshot) { Boolean create = true; if (dataSnapshot.exists()) { for (Object recent : ((HashMap<String, Object>) dataSnapshot.getValue()).values()) { HashMap<String, Object> currentRecent = (HashMap<String, Object>) recent; if (currentRecent.get(kUSERID).equals(userId)) { create = false; } firebase.child(kRECENT).orderByChild(kCHATROOMID).equalTo((String) currentRecent.get(kCHATROOMID)) .addValueEventListener(new ValueEventListener() { @Override public void onDataChange(@NonNull DataSnapshot dataSnapshot) { } @Override public void onCancelled(@NonNull DatabaseError databaseError) { } }); } } if (create && !(userId.equals(withUserUserId))) { createRecentItem(userId, chatRoomId, members, withUserUserId, withUserUsername, postId, type); } } @Override public void onCancelled(@NonNull DatabaseError databaseError) { } }); } private static void createRecentItem(String userId, String chatRoomId, List<String> members, String withUserUserId, String withUserUsername, String postId, String type) { DatabaseReference reference = firebase.child(kRECENT).push(); String recentId = reference.getKey(); SimpleDateFormat sfd = new SimpleDateFormat(DF_SIMPLE_STRING_WITH_DETAILS); String date = sfd.format(new Date()); HashMap<String, Object> recent = new HashMap<String, Object>(); recent.put(kRECENTID, recentId); recent.put(kUSERID, userId); recent.put(kCHATROOMID, chatRoomId); recent.put(kMEMBERS, members); recent.put(kWITHUSERUSERNAME, withUserUsername); recent.put(kWITHUSERUSERID, withUserUserId); recent.put(kLASTMESSAGE, ""); recent.put(kCOUNTER, 0); recent.put(kDATE, date); recent.put(kPOSTID, postId); recent.put(kTYPE, type); reference.setValue(recent); } public static class DateHelper { public static ThreadLocal<DateFormat> DF_SIMPLE_FORMAT = new ThreadLocal<DateFormat>() { @Override protected DateFormat initialValue() { return new SimpleDateFormat(DF_SIMPLE_STRING_WITH_DETAILS, Locale.US); } }; } public static void updateRecents(String chatRoomId, final String lastMessage) { firebase.child(kRECENT).orderByChild(kCHATROOMID).equalTo(chatRoomId).addListenerForSingleValueEvent(new ValueEventListener() { @Override public void onDataChange(@NonNull DataSnapshot dataSnapshot) { if (dataSnapshot.exists()) { for (Object recent : (((HashMap<String, Object>) dataSnapshot.getValue()).values())) { updateRecentItem((HashMap<String, Object>) recent, lastMessage); } } } @Override public void onCancelled(@NonNull DatabaseError databaseError) { } }); } private static void updateRecentItem(HashMap<String, Object> recent, String lastMessage) { SimpleDateFormat sfd = new SimpleDateFormat(DF_SIMPLE_STRING_WITH_DETAILS); String date = sfd.format(new Date()); Long counter = (Long) recent.get(kCOUNTER); if (!(recent.get(kUSERID).equals(FirebaseAuth.getInstance().getCurrentUser().getUid()))) { counter += 1; } HashMap<String, Object> newRecent = new HashMap<String, Object>(); newRecent.put(kLASTMESSAGE, lastMessage); newRecent.put(kCOUNTER, counter); newRecent.put(kDATE, date); firebase.child(kRECENT).child(((String) recent.get(kRECENTID))).updateChildren(newRecent); } public static void clearRecentCounter(String chatRoomID) { firebase.child(kRECENT).orderByChild(kCHATROOMID).equalTo(chatRoomID).addListenerForSingleValueEvent(new ValueEventListener() { @Override public void onDataChange(@NonNull DataSnapshot dataSnapshot) { if (dataSnapshot.exists()) { for (Object recent : (((HashMap<String, Object>) dataSnapshot.getValue()).values())) { HashMap<String, Object> currentRecent = (HashMap<String, Object>) recent; if (currentRecent.get(kUSERID).equals(FirebaseAuth.getInstance().getCurrentUser().getUid())) { clearRecentCounterItem(currentRecent); } } } } @Override public void onCancelled(@NonNull DatabaseError databaseError) { } }); } private static void clearRecentCounterItem(HashMap<String, Object> recent) { firebase.child(kRECENT).child(((String) recent.get(kRECENTID))).child(kCOUNTER).setValue(0); } public static File decodeFile(File f) { Bitmap b = null; //Decode image size BitmapFactory.Options o = new BitmapFactory.Options(); o.inJustDecodeBounds = true; FileInputStream fis = null; try { fis = new FileInputStream(f); BitmapFactory.decodeStream(fis, null, o); fis.close(); } catch (FileNotFoundException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } int IMAGE_MAX_SIZE = 1024; int scale = 1; if (o.outHeight > IMAGE_MAX_SIZE || o.outWidth > IMAGE_MAX_SIZE) { scale = (int) Math.pow(2, (int) Math.ceil(Math.log(IMAGE_MAX_SIZE / (double) Math.max(o.outHeight, o.outWidth)) / Math.log(0.5))); } //Decode with inSampleSize BitmapFactory.Options o2 = new BitmapFactory.Options(); o2.inSampleSize = scale; try { fis = new FileInputStream(f); b = BitmapFactory.decodeStream(fis, null, o2); fis.close(); } catch (FileNotFoundException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } try { FileOutputStream out = new FileOutputStream(f); if (b != null) { b.compress(Bitmap.CompressFormat.JPEG, 100, out); } out.flush(); out.close(); } catch (Exception e) { e.printStackTrace(); } return f; } /** * This is useful when an image is available in sdcard physically. */ public static String getPathFromUri(Uri uriPhoto, Context context) { if (uriPhoto == null) return null; if (SCHEME_FILE.equals(uriPhoto.getScheme())) { return uriPhoto.getPath(); } else if (SCHEME_CONTENT.equals(uriPhoto.getScheme())) { final String[] filePathColumn = {MediaStore.MediaColumns.DATA, MediaStore.MediaColumns.DISPLAY_NAME}; Cursor cursor = null; try { cursor = context.getContentResolver().query(uriPhoto, filePathColumn, null, null, null); if (cursor != null && cursor.moveToFirst()) { final int columnIndex = (uriPhoto.toString() .startsWith("content://com.google.android.gallery3d")) ? cursor .getColumnIndex(MediaStore.MediaColumns.DISPLAY_NAME) : cursor.getColumnIndex(MediaStore.MediaColumns.DATA); if (columnIndex != -1) { String filePath = cursor.getString(columnIndex); if (!TextUtils.isEmpty(filePath)) { return filePath; } } } } catch (IllegalArgumentException e) { // Nothing we can do e.printStackTrace(); } catch (SecurityException ignored) { // Nothing we can do ignored.printStackTrace(); } finally { if (cursor != null) cursor.close(); } } return null; } public static String getPathFromGooglePhotosUri(Uri uriPhoto, Context context) { if (uriPhoto == null) return null; FileInputStream input = null; FileOutputStream output = null; try { ParcelFileDescriptor pfd = context.getContentResolver().openFileDescriptor(uriPhoto, "r"); FileDescriptor fd = null; if (pfd != null) { fd = pfd.getFileDescriptor(); } if (fd != null) { input = new FileInputStream(fd); } String tempFilename = getTempFilename(context); output = new FileOutputStream(tempFilename); int read; byte[] bytes = new byte[4096]; if (input != null) { while ((read = input.read(bytes)) != -1) { output.write(bytes, 0, read); } } return tempFilename; } catch (IOException ignored) { // Nothing we can do } finally { closeSilently(input); closeSilently(output); } return null; } private static void closeSilently(Closeable c) { if (c == null) return; try { c.close(); } catch (Throwable t) { // Do nothing } } private static String getTempFilename(Context context) throws IOException { File outputDir = context.getCacheDir(); File outputFile = File.createTempFile("image", "tmp", outputDir); return outputFile.getAbsolutePath(); } public static String SplitString(String email) { String[] split = email.split("@"); return split[0]; } public static File getOutputMediaFile(Context context) { File mediaStorageDir = new File(context.getExternalFilesDir( Environment.DIRECTORY_PICTURES), context.getString(R.string.app_name)); if (!mediaStorageDir.exists()) { if (!mediaStorageDir.mkdirs()) { return null; } } String timeStamp = new SimpleDateFormat(DF_SIMPLE_STRING).format(new Date()); return new File(mediaStorageDir.getPath() + File.separator + "IMG_" + timeStamp + ".jpg"); } public static void closeOnError(CoordinatorLayout coordinatorLayout, Activity activity) { Snackbar.make(coordinatorLayout, R.string.err_data_not_available_string, Snackbar.LENGTH_SHORT).show(); activity.finish(); } }
true
077d20841ddefdbac1f2d213fa81638a1fb90d80
Java
Dragberry/hp
/happytime-core/src/main/java/by/happytime/domain/Order.java
UTF-8
5,780
2.4375
2
[]
no_license
package by.happytime.domain; import java.math.BigDecimal; import java.util.Date; import java.util.HashSet; import java.util.Set; import javax.persistence.CascadeType; import javax.persistence.Column; import javax.persistence.Entity; import javax.persistence.Enumerated; import javax.persistence.FetchType; import javax.persistence.JoinColumn; import javax.persistence.ManyToOne; import javax.persistence.OneToMany; import javax.persistence.Table; import javax.persistence.Temporal; import javax.persistence.TemporalType; import org.apache.commons.collections4.CollectionUtils; @Entity @Table(name = "`order`") public class Order extends AbstractEntity { private static final long serialVersionUID = 8075684027785421996L; @Column(name = "order_date") @Temporal(TemporalType.TIMESTAMP) private Date orderDate; @Enumerated @Column(name = "status") private OrderStatus status; @Column(name = "first_name") private String firstName; @Column(name = "last_name") private String lastName; @Column(name = "country") private String country; @Column(name = "city") private String city; @Column(name = "street") private String street; @Column(name = "house") private Integer house; @Column(name = "housing") private Integer housing; @Column(name = "flat") private Integer flat; @Column(name = "postal_code") private String postalCode; @Column(name = "email") private String email; @Column(name = "phone") private String phone; @Column(name = "additional_info") private String additionalInfo; @OneToMany(fetch = FetchType.EAGER, cascade = {CascadeType.ALL}) @JoinColumn(name = "order_id") private Set<OrderUnit> orderUnits = new HashSet<OrderUnit>(); @ManyToOne @JoinColumn(name = "user_id") private User user; @Override public String toString() { StringBuilder builder = new StringBuilder(); builder.append("Order id: " + getId() + "\n"); builder.append(getFirstName() + " " + getLastName() + "\n"); builder.append("Phone: " + getPhone() + "\n"); builder.append("Street: " + getStreet() + "\n"); builder.append("House: " + getHouse() + "\n"); if (getHousing() != null) { builder.append("Housing: " + getHousing() + "\n"); } builder.append("Flat: " + getFlat() + "\n"); builder.append("Additional Info: " + getAdditionalInfo() + "\n"); builder.append("\nProducts:\n"); if (CollectionUtils.isNotEmpty(getOrderUnits())) { int index = 1; BigDecimal fullCost = BigDecimal.ZERO; for (OrderUnit unit : getOrderUnits()) { builder.append("\t" + index + ".Product id: " + unit.getProduct().getId() + "\n"); builder.append("\t Product title: " + unit.getProduct().getTitle() + "\n"); builder.append("\t Product cost: " + unit.getProduct().getCost() + "\n"); builder.append("\t Product quantity: " + unit.getQuantity() + "\n"); builder.append("\t Product full cost: " + unit.getFullCost() + "\n\n"); fullCost = fullCost.add(unit.getFullCost()); index++; } builder.append("\nOrder cost: " + fullCost); } return builder.toString(); } public Date getOrderDate() { return orderDate; } public void setOrderDate(Date orderDate) { this.orderDate = orderDate; } public OrderStatus getStatus() { return status; } public void setStatus(OrderStatus status) { this.status = status; } public String getFirstName() { return firstName; } public void setFirstName(String firstName) { this.firstName = firstName; } public String getLastName() { return lastName; } public void setLastName(String lastName) { this.lastName = lastName; } public String getEmail() { return email; } public void setEmail(String email) { this.email = email; } public String getPhone() { return phone; } public void setPhone(String phone) { this.phone = phone; } public Set<OrderUnit> getOrderUnits() { return orderUnits; } public void setOrderUnits(Set<OrderUnit> orderUnits) { this.orderUnits = orderUnits; } public User getUser() { return user; } public void setUser(User user) { this.user = user; } public String getCountry() { return country; } public void setCountry(String country) { this.country = country; } public String getCity() { return city; } public void setCity(String city) { this.city = city; } public String getStreet() { return street; } public void setStreet(String street) { this.street = street; } public Integer getHouse() { return house; } public void setHouse(Integer house) { this.house = house; } public Integer getHousing() { return housing; } public void setHousing(Integer housing) { this.housing = housing; } public Integer getFlat() { return flat; } public void setFlat(Integer flat) { this.flat = flat; } public String getPostalCode() { return postalCode; } public void setPostalCode(String postalCode) { this.postalCode = postalCode; } public String getAdditionalInfo() { return additionalInfo; } public void setAdditionalInfo(String additionalInfo) { this.additionalInfo = additionalInfo; } }
true
050b60c3fce49fead346ddf6e50ebb0be1ee7410
Java
Gnaixuj/RuN.sg
/app/src/main/java/com/example/cz2006trial/model/Point.java
UTF-8
1,234
2.71875
3
[]
no_license
package com.example.cz2006trial.model; import com.google.android.gms.maps.model.LatLng; public class Point { // name of a point marker on a map private String name; // coordinates of a point marker on a map private LatLng location; // description of a point marker on a map private String description; // type of a point marker on a map private String type; // constructor to initialize Point public Point(String name, LatLng location, String description, String type) { this.name = name; this.location = location; this.description = description; this.type = type; } public String getDescription() { return description; } public LatLng getLocation() { return location; } public String getName() { return name; } public String getType() { return type; } public void setDescription(String description) { this.description = description; } public void setLocation(LatLng location) { this.location = location; } public void setName(String name) { this.name = name; } public void setType(String type) { this.type = type; } }
true
3731b75e1d314b493812dc9b54eb990667b9530c
Java
blueskyee/LeetCode
/src/Searcha2DMatrixII_240.java
UTF-8
1,633
3.40625
3
[]
no_license
/** * Created by henry on 2021/2/21. */ public class Searcha2DMatrixII_240 { public static void main(String[] args){ int[][] matrix = {{1,4,7,11,15},{2,5,8,12,19},{3,6,9,16,22},{10,13,14,17,24},{18,21,23,26,30}}; Searcha2DMatrixII_240 s2 = new Searcha2DMatrixII_240(); System.out.println(s2.searchMatrix(matrix, 8)); } /*if the target is greater than the value in current position, then the target can not be in entire row of current position because the row is sorted, if the target is less than the value in current position, then the target can not in the entire column because the column is sorted too.*/ public boolean searchMatrix(int[][] matrix, int target) { if(matrix == null) return false; int m = matrix.length, n = matrix[0].length; int row = 0, col = n - 1; while(row < m && col >= 0){ if(matrix[row][col] == target){ return true; }else if(matrix[row][col] > target){ col--; }else{ row++; } } return false; } /*public boolean searchMatrix(int[][] matrix, int target) { if(matrix == null) return false; int m = matrix.length, n = matrix[0].length; int i = 0, j = n - 1; while(i < m){ if(matrix[i][j] == target){ return true; }else if(matrix[i][j] > target){ if(j == 0) break; else j--; }else{ i++; j = n - 1; } } return false; }*/ }
true
d5e5ff9401b7003a885dd33a84cf31870ff43e3b
Java
oswin5656/CardsAgainstHumanity
/src/game/package-info.java
UTF-8
280
1.789063
2
[]
no_license
/** * Contains classes that have to do with the actual game of Cards Against Humanity itself. * @version CAH1.0 * @since CAH1.0 * @author Holt Maki * @see {@linkplain HouseRules}, {@linkplain CAH_Game}, {@linkplain CAH_GameComponents}, {@linkplain RulesMaker} */ package game;
true
8a3898a4cdf8182226558112cef041815001453c
Java
freelanceapp/Tadlaly
/app/src/main/java/com/semicolon/tadlaly/Activities/MyAdsActivity.java
UTF-8
4,963
1.929688
2
[]
no_license
package com.semicolon.tadlaly.Activities; import android.content.Context; import android.content.Intent; import android.os.Bundle; import android.os.Handler; import android.support.design.widget.TabLayout; import android.support.v4.app.Fragment; import android.support.v4.view.ViewPager; import android.support.v7.app.AppCompatActivity; import android.widget.ImageView; import com.semicolon.tadlaly.Adapters.MyAdsPagerAdapter; import com.semicolon.tadlaly.Fragments.CurrentAds_Fragment; import com.semicolon.tadlaly.Fragments.OldAds_Fragment; import com.semicolon.tadlaly.Models.MyAdsModel; import com.semicolon.tadlaly.R; import com.semicolon.tadlaly.language.LocalManager; import java.util.List; import java.util.Locale; import io.paperdb.Paper; public class MyAdsActivity extends AppCompatActivity { private TabLayout tab; private ViewPager pager; private MyAdsPagerAdapter adapter; private CurrentAds_Fragment ads_fragment; private ImageView back; private String current_language; @Override protected void attachBaseContext(Context newBase) { Paper.init(newBase); super.attachBaseContext(LocalManager.updateResources(newBase,LocalManager.getLanguage(newBase))); } @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_my_ads); initView(); } private void initView() { current_language = Paper.book().read("language", Locale.getDefault().getLanguage()); back = findViewById(R.id.back); if (current_language.equals("ar")) { back.setRotation(180f); } tab = findViewById(R.id.tab); pager = findViewById(R.id.pager); tab.setupWithViewPager(pager); adapter = new MyAdsPagerAdapter(getSupportFragmentManager()); AddFragments(); pager.setAdapter(adapter); back.setOnClickListener(view -> { if (pager.getCurrentItem()==0) { if (ads_fragment.inNormalMode) { finish(); }else { ads_fragment.onBack(); } }else { pager.setCurrentItem(0); } }); pager.addOnPageChangeListener(new ViewPager.OnPageChangeListener() { @Override public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) { } @Override public void onPageSelected(int position) { } @Override public void onPageScrollStateChanged(int state) { } }); } private void AddFragments() { ads_fragment = new CurrentAds_Fragment(); adapter.AddFragments(ads_fragment); adapter.AddFragments(new OldAds_Fragment()); adapter.AddTitle(getString(R.string.curr)); adapter.AddTitle(getString(R.string.prev)); } @Override public void onBackPressed() { if (pager.getCurrentItem()==0) { if (ads_fragment.inNormalMode) { super.onBackPressed(); }else { ads_fragment.onBack(); } }else { pager.setCurrentItem(0); } } @Override protected void onStart() { super.onStart(); adapter.notifyDataSetChanged(); } public void UpdateAds(MyAdsModel myAdsModel) { Intent intent = new Intent(this, UpdateAdsActivity.class); intent.putExtra("ad_details",myAdsModel); startActivityForResult(intent,78); } @Override protected void onActivityResult(int requestCode, int resultCode, Intent data) { super.onActivityResult(requestCode, resultCode, data); List<Fragment> fragmentList = getSupportFragmentManager().getFragments(); for (Fragment fragment : fragmentList) { fragment.onActivityResult(requestCode, resultCode, data); } if (requestCode==78) { if (resultCode==RESULT_OK) { adapter = (MyAdsPagerAdapter) pager.getAdapter(); new Handler() .postDelayed(new Runnable() { @Override public void run() { CurrentAds_Fragment currentAds_fragment = (CurrentAds_Fragment) adapter.getItem(0); OldAds_Fragment oldAds_fragment = (OldAds_Fragment) adapter.getItem(1); currentAds_fragment.getData(1); oldAds_fragment.getData(1); } },1); } } } }
true
f339b2643ac03ac1226085371a468eb0ac4f0a4f
Java
tp900/Weather
/app/src/main/java/com/tp900/weather/util/Utility.java
UTF-8
3,930
2.296875
2
[]
no_license
package com.tp900.weather.util; import android.text.TextUtils; import com.google.gson.Gson; import com.google.gson.JsonArray; import com.google.gson.reflect.TypeToken; import com.tp900.weather.db.City; import com.tp900.weather.db.County; import com.tp900.weather.db.Province; import com.tp900.weather.gson.Weather; import org.json.JSONArray; import org.json.JSONObject; import java.util.List; public class Utility { public static boolean HandleProvinceResponse(String response){ if(!TextUtils.isEmpty(response)){ try{ JSONArray jsonArray= new JSONArray(response); // Gson gson=new Gson(); // List<Province> provinces = gson.fromJson(response,new TypeToken<List<Province>>(){}.getType()); if(null !=jsonArray&&jsonArray.length()>0){ for (int i = 0 ;i<jsonArray.length();i++) { JSONObject jsonObject = jsonArray.getJSONObject(i); Province province = new Province(); province.setProvinceCode(jsonObject.getInt("id")); province.setProvinceName(jsonObject.getString("name")); province.save(); } } return true; }catch (Exception ex){ ex.printStackTrace(); } } return false; } public static boolean HandleCityResponse(String response,int provinceId){ if(!TextUtils.isEmpty(response)){ try{ JSONArray jsonArray= new JSONArray(response); // Gson gson=new Gson(); // List<Province> provinces = gson.fromJson(response,new TypeToken<List<Province>>(){}.getType()); if(null !=jsonArray&&jsonArray.length()>0){ for (int i = 0 ;i<jsonArray.length();i++) { JSONObject jsonObject = jsonArray.getJSONObject(i); City city = new City(); city.setCityCode(jsonObject.getInt("id")); city.setCityName(jsonObject.getString("name")); city.setProvinceId(provinceId); city.save(); } } return true; }catch (Exception ex){ ex.printStackTrace(); } } return false; } public static boolean HandleCountyRespone(String response,int cityId){ if(!TextUtils.isEmpty(response)){ try{ JSONArray jsonArray= new JSONArray(response); // Gson gson=new Gson(); // List<Province> provinces = gson.fromJson(response,new TypeToken<List<Province>>(){}.getType()); if(null !=jsonArray&&jsonArray.length()>0){ for (int i = 0 ;i<jsonArray.length();i++) { JSONObject jsonObject = jsonArray.getJSONObject(i); County county = new County(); county.setCityId(cityId); county.setCountyName(jsonObject.getString("name")); county.setWeatherId(jsonObject.getString("weather_id")); county.save(); } } return true; }catch (Exception ex){ ex.printStackTrace(); } } return false; } public static Weather HandleWeatherResponse(String response){ try{ JSONObject jsonObject = new JSONObject(response); JSONArray jsonArray = jsonObject.getJSONArray("HeWeather6"); String weatherContent = jsonArray.getJSONObject(0).toString(); return new Gson().fromJson(weatherContent,Weather.class); }catch (Exception ex){ex.printStackTrace();} return null; } }
true
343c5e3425e7604fa9b0954a0af0fcf6088e7896
Java
samuelcsouza/Yu-Gi-Oh
/src/br/inatel/yugioh/view/EditarMonstro.java
UTF-8
34,026
2.125
2
[]
no_license
package br.inatel.yugioh.view; import br.inatel.yugioh.control.Deck; import br.inatel.yugioh.model.Carta; import br.inatel.yugioh.model.CartaMonstro; import static br.inatel.yugioh.view.AlterarCartas.indiceSelecionado; import java.io.File; import java.util.ArrayList; import javax.swing.ImageIcon; import javax.swing.JFileChooser; import javax.swing.JOptionPane; /** * * @author Samuel */ public class EditarMonstro extends javax.swing.JFrame { private Deck d = new Deck(); private ArrayList<Carta> baralho; public EditarMonstro() { initComponents(); baralho = d.lerDeck(); this.setLocationRelativeTo(null); // Centralizar a Tela } /** * This method is called from within the constructor to initialize the form. * WARNING: Do NOT modify this code. The content of this method is always * regenerated by the Form Editor. */ @SuppressWarnings("unchecked") // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents private void initComponents() { lbl_id = new javax.swing.JLabel(); lbl_type = new javax.swing.JLabel(); lbl_efeito = new javax.swing.JLabel(); lbl_nome = new javax.swing.JLabel(); lbl_nivel = new javax.swing.JLabel(); jLabel3 = new javax.swing.JLabel(); jLabel4 = new javax.swing.JLabel(); lbl_def = new javax.swing.JLabel(); lbl_atk = new javax.swing.JLabel(); lbl_atributo = new javax.swing.JLabel(); lbl_Carta = new javax.swing.JLabel(); lbl_img = new javax.swing.JLabel(); jPanel2 = new javax.swing.JPanel(); nome = new javax.swing.JLabel(); txt_nome = new javax.swing.JTextField(); atributo = new javax.swing.JLabel(); nivel = new javax.swing.JLabel(); atk = new javax.swing.JLabel(); txt_atk = new javax.swing.JTextField(); def = new javax.swing.JLabel(); txt_def = new javax.swing.JTextField(); lbl_tipoMonstro = new javax.swing.JLabel(); lbl_tipo = new javax.swing.JLabel(); txt_tipo = new javax.swing.JTextField(); desc = new javax.swing.JLabel(); scr_efeito = new javax.swing.JScrollPane(); txt_desc = new javax.swing.JTextArea(); btn_img = new javax.swing.JButton(); id = new javax.swing.JLabel(); txt_ID = new javax.swing.JTextField(); combo_nivel = new javax.swing.JComboBox<>(); combo_atributo = new javax.swing.JComboBox<>(); btn_ok = new javax.swing.JButton(); combo_tipo = new javax.swing.JComboBox<>(); btn_cancelar = new javax.swing.JButton(); lbl_titulo = new javax.swing.JLabel(); lbl_fundo = new javax.swing.JLabel(); setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE); setResizable(false); getContentPane().setLayout(new org.netbeans.lib.awtextra.AbsoluteLayout()); lbl_id.setHorizontalAlignment(javax.swing.SwingConstants.RIGHT); lbl_id.setToolTipText(""); lbl_id.setHorizontalTextPosition(javax.swing.SwingConstants.LEFT); getContentPane().add(lbl_id, new org.netbeans.lib.awtextra.AbsoluteConstraints(680, 400, 30, 10)); lbl_type.setFont(new java.awt.Font("Tahoma", 1, 12)); // NOI18N getContentPane().add(lbl_type, new org.netbeans.lib.awtextra.AbsoluteConstraints(460, 410, 140, 30)); lbl_efeito.setVerticalAlignment(javax.swing.SwingConstants.TOP); getContentPane().add(lbl_efeito, new org.netbeans.lib.awtextra.AbsoluteConstraints(460, 440, 260, 40)); lbl_nome.setFont(new java.awt.Font("Dialog", 1, 21)); // NOI18N lbl_nome.setToolTipText(""); getContentPane().add(lbl_nome, new org.netbeans.lib.awtextra.AbsoluteConstraints(460, 80, 210, 40)); getContentPane().add(lbl_nivel, new org.netbeans.lib.awtextra.AbsoluteConstraints(450, 120, 260, 30)); jLabel3.setFont(new java.awt.Font("Tahoma", 1, 14)); // NOI18N jLabel3.setText("DEF/"); getContentPane().add(jLabel3, new org.netbeans.lib.awtextra.AbsoluteConstraints(640, 480, -1, 20)); jLabel4.setFont(new java.awt.Font("Tahoma", 1, 14)); // NOI18N jLabel4.setText("ATK/"); getContentPane().add(jLabel4, new org.netbeans.lib.awtextra.AbsoluteConstraints(550, 480, -1, 20)); lbl_def.setFont(new java.awt.Font("Tahoma", 1, 14)); // NOI18N getContentPane().add(lbl_def, new org.netbeans.lib.awtextra.AbsoluteConstraints(680, 480, 40, 20)); lbl_atk.setFont(new java.awt.Font("Tahoma", 1, 14)); // NOI18N getContentPane().add(lbl_atk, new org.netbeans.lib.awtextra.AbsoluteConstraints(590, 480, 40, 20)); getContentPane().add(lbl_atributo, new org.netbeans.lib.awtextra.AbsoluteConstraints(680, 80, 37, 37)); lbl_Carta.setIcon(new javax.swing.ImageIcon(getClass().getResource("/br/inatel/yugioh/img/card/monsterPNG.png"))); // NOI18N getContentPane().add(lbl_Carta, new org.netbeans.lib.awtextra.AbsoluteConstraints(420, 50, -1, -1)); getContentPane().add(lbl_img, new org.netbeans.lib.awtextra.AbsoluteConstraints(460, 150, 250, 250)); jPanel2.setBackground(new java.awt.Color(255, 255, 255)); jPanel2.setOpaque(false); nome.setFont(new java.awt.Font("Tahoma", 1, 24)); // NOI18N nome.setText("Nome"); txt_nome.setFont(new java.awt.Font("Tahoma", 0, 22)); // NOI18N txt_nome.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { txt_nomeActionPerformed(evt); } }); atributo.setFont(new java.awt.Font("Tahoma", 1, 24)); // NOI18N atributo.setText("Atributo"); nivel.setFont(new java.awt.Font("Tahoma", 1, 24)); // NOI18N nivel.setText("Nível"); atk.setFont(new java.awt.Font("Tahoma", 0, 24)); // NOI18N atk.setText("ATK"); txt_atk.setFont(new java.awt.Font("Tahoma", 0, 24)); // NOI18N txt_atk.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { txt_atkActionPerformed(evt); } }); def.setFont(new java.awt.Font("Tahoma", 0, 24)); // NOI18N def.setText("DEF"); txt_def.setFont(new java.awt.Font("Tahoma", 0, 24)); // NOI18N txt_def.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { txt_defActionPerformed(evt); } }); lbl_tipoMonstro.setFont(new java.awt.Font("Tahoma", 1, 24)); // NOI18N lbl_tipoMonstro.setText("Tipo da Carta"); lbl_tipo.setFont(new java.awt.Font("Tahoma", 1, 24)); // NOI18N lbl_tipo.setText("Tipo"); txt_tipo.setFont(new java.awt.Font("Tahoma", 0, 24)); // NOI18N txt_tipo.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { txt_tipoActionPerformed(evt); } }); desc.setFont(new java.awt.Font("Tahoma", 1, 24)); // NOI18N desc.setText("Efeito ou Descrição"); txt_desc.setColumns(20); txt_desc.setRows(5); scr_efeito.setViewportView(txt_desc); btn_img.setFont(new java.awt.Font("Tahoma", 0, 12)); // NOI18N btn_img.setText("Selecionar Imagem"); btn_img.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { btn_imgActionPerformed(evt); } }); id.setFont(new java.awt.Font("Tahoma", 1, 24)); // NOI18N id.setText("ID"); txt_ID.setFont(new java.awt.Font("Tahoma", 0, 24)); // NOI18N txt_ID.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { txt_IDActionPerformed(evt); } }); combo_nivel.setFont(new java.awt.Font("Tahoma", 0, 24)); // NOI18N combo_nivel.setModel(new javax.swing.DefaultComboBoxModel<>(new String[] { "1", "2", "3", "4", "5", "6", "7", "8", "9", "10", "11", "12" })); combo_nivel.setSelectedIndex(-1); combo_nivel.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { combo_nivelActionPerformed(evt); } }); combo_atributo.setFont(new java.awt.Font("Tahoma", 0, 24)); // NOI18N combo_atributo.setModel(new javax.swing.DefaultComboBoxModel<>(new String[] { "Trevas", "Terra", "Fogo", "Luz", "Água", "Vento", "Divino" })); combo_atributo.setSelectedIndex(-1); combo_atributo.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { combo_atributoActionPerformed(evt); } }); btn_ok.setFont(new java.awt.Font("Tahoma", 1, 12)); // NOI18N btn_ok.setText("OK"); btn_ok.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { btn_okActionPerformed(evt); } }); combo_tipo.setFont(new java.awt.Font("Tahoma", 0, 24)); // NOI18N combo_tipo.setModel(new javax.swing.DefaultComboBoxModel<>(new String[] { "Normal", "Efeito", "Ritual", "Fusão" })); combo_tipo.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { combo_tipoActionPerformed(evt); } }); btn_cancelar.setFont(new java.awt.Font("Tahoma", 1, 12)); // NOI18N btn_cancelar.setText("Cancelar"); btn_cancelar.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { btn_cancelarActionPerformed(evt); } }); javax.swing.GroupLayout jPanel2Layout = new javax.swing.GroupLayout(jPanel2); jPanel2.setLayout(jPanel2Layout); jPanel2Layout.setHorizontalGroup( jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(jPanel2Layout.createSequentialGroup() .addContainerGap() .addGroup(jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(jPanel2Layout.createSequentialGroup() .addComponent(btn_img) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE) .addComponent(btn_cancelar) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addComponent(btn_ok)) .addGroup(jPanel2Layout.createSequentialGroup() .addGroup(jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false) .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, jPanel2Layout.createSequentialGroup() .addComponent(atk) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED) .addComponent(txt_atk, javax.swing.GroupLayout.PREFERRED_SIZE, 110, javax.swing.GroupLayout.PREFERRED_SIZE) .addGap(50, 50, 50) .addComponent(def) .addGap(18, 18, 18) .addComponent(txt_def)) .addComponent(desc) .addComponent(nome, javax.swing.GroupLayout.PREFERRED_SIZE, 118, javax.swing.GroupLayout.PREFERRED_SIZE) .addComponent(txt_nome, javax.swing.GroupLayout.PREFERRED_SIZE, 369, javax.swing.GroupLayout.PREFERRED_SIZE) .addComponent(scr_efeito)) .addGroup(jPanel2Layout.createSequentialGroup() .addGroup(jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING, false) .addGroup(javax.swing.GroupLayout.Alignment.LEADING, jPanel2Layout.createSequentialGroup() .addComponent(atributo) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED) .addComponent(combo_atributo, 0, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)) .addComponent(txt_tipo, javax.swing.GroupLayout.PREFERRED_SIZE, 222, javax.swing.GroupLayout.PREFERRED_SIZE)) .addComponent(lbl_tipo)) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED) .addGroup(jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false) .addComponent(id) .addGroup(jPanel2Layout.createSequentialGroup() .addComponent(nivel) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED) .addComponent(combo_nivel, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)) .addComponent(txt_ID)))) .addGap(0, 1, Short.MAX_VALUE)) .addGroup(jPanel2Layout.createSequentialGroup() .addComponent(lbl_tipoMonstro, javax.swing.GroupLayout.PREFERRED_SIZE, 222, javax.swing.GroupLayout.PREFERRED_SIZE) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED) .addComponent(combo_tipo, 0, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))) .addContainerGap()) ); jPanel2Layout.setVerticalGroup( jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(jPanel2Layout.createSequentialGroup() .addComponent(nome, javax.swing.GroupLayout.PREFERRED_SIZE, 25, javax.swing.GroupLayout.PREFERRED_SIZE) .addGap(5, 5, 5) .addComponent(txt_nome, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addGroup(jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE) .addComponent(atributo) .addComponent(nivel) .addComponent(combo_nivel, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE) .addComponent(combo_atributo, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addGroup(jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE) .addComponent(lbl_tipo) .addComponent(id)) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addGroup(jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE) .addComponent(txt_tipo, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE) .addComponent(txt_ID, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED) .addGroup(jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE) .addComponent(lbl_tipoMonstro) .addComponent(combo_tipo, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addComponent(desc) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addComponent(scr_efeito, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addGroup(jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE) .addComponent(txt_def, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE) .addComponent(def)) .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE) .addComponent(atk) .addComponent(txt_atk, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED) .addGroup(jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addComponent(btn_img) .addGroup(jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE) .addComponent(btn_ok) .addComponent(btn_cancelar))) .addGap(22, 22, 22)) ); getContentPane().add(jPanel2, new org.netbeans.lib.awtextra.AbsoluteConstraints(10, 50, 390, 480)); lbl_titulo.setFont(new java.awt.Font("Tahoma", 1, 24)); // NOI18N lbl_titulo.setText("Editar Carta Monstro"); getContentPane().add(lbl_titulo, new org.netbeans.lib.awtextra.AbsoluteConstraints(270, 10, -1, -1)); lbl_fundo.setIcon(new javax.swing.ImageIcon(getClass().getResource("/br/inatel/yugioh/img/wallpaper_35.png"))); // NOI18N getContentPane().add(lbl_fundo, new org.netbeans.lib.awtextra.AbsoluteConstraints(0, 0, 780, 550)); pack(); }// </editor-fold>//GEN-END:initComponents private void txt_nomeActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_txt_nomeActionPerformed }//GEN-LAST:event_txt_nomeActionPerformed private void txt_atkActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_txt_atkActionPerformed }//GEN-LAST:event_txt_atkActionPerformed private void txt_defActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_txt_defActionPerformed }//GEN-LAST:event_txt_defActionPerformed private void txt_tipoActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_txt_tipoActionPerformed }//GEN-LAST:event_txt_tipoActionPerformed private void btn_imgActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btn_imgActionPerformed escolherImagem(); // Selecionar Imagem da Carta }//GEN-LAST:event_btn_imgActionPerformed private void txt_IDActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_txt_IDActionPerformed }//GEN-LAST:event_txt_IDActionPerformed private void combo_nivelActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_combo_nivelActionPerformed setarNivel(); // Nivel selecionado }//GEN-LAST:event_combo_nivelActionPerformed private void combo_atributoActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_combo_atributoActionPerformed setarIconeAtributo(); // Atributo selecionado }//GEN-LAST:event_combo_atributoActionPerformed private void btn_okActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btn_okActionPerformed botaoOK(); // botão OK }//GEN-LAST:event_btn_okActionPerformed private void combo_tipoActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_combo_tipoActionPerformed setarTipoCarta(); // Tipo da carta }//GEN-LAST:event_combo_tipoActionPerformed private void btn_cancelarActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btn_cancelarActionPerformed AlterarCartas ac = new AlterarCartas(); ac.setVisible(true); this.dispose(); }//GEN-LAST:event_btn_cancelarActionPerformed /** * @param args the command line arguments */ public static void main(String args[]) { /* Set the Nimbus look and feel */ //<editor-fold defaultstate="collapsed" desc=" Look and feel setting code (optional) "> /* If Nimbus (introduced in Java SE 6) is not available, stay with the default look and feel. * For details see http://download.oracle.com/javase/tutorial/uiswing/lookandfeel/plaf.html */ try { for (javax.swing.UIManager.LookAndFeelInfo info : javax.swing.UIManager.getInstalledLookAndFeels()) { if ("Nimbus".equals(info.getName())) { javax.swing.UIManager.setLookAndFeel(info.getClassName()); break; } } } catch (ClassNotFoundException ex) { java.util.logging.Logger.getLogger(EditarMonstro.class.getName()).log(java.util.logging.Level.SEVERE, null, ex); } catch (InstantiationException ex) { java.util.logging.Logger.getLogger(EditarMonstro.class.getName()).log(java.util.logging.Level.SEVERE, null, ex); } catch (IllegalAccessException ex) { java.util.logging.Logger.getLogger(EditarMonstro.class.getName()).log(java.util.logging.Level.SEVERE, null, ex); } catch (javax.swing.UnsupportedLookAndFeelException ex) { java.util.logging.Logger.getLogger(EditarMonstro.class.getName()).log(java.util.logging.Level.SEVERE, null, ex); } //</editor-fold> //</editor-fold> /* Create and display the form */ java.awt.EventQueue.invokeLater(new Runnable() { public void run() { new EditarMonstro().setVisible(true); } }); } // Variables declaration - do not modify//GEN-BEGIN:variables private javax.swing.JLabel atk; private javax.swing.JLabel atributo; private javax.swing.JButton btn_cancelar; private javax.swing.JButton btn_img; private javax.swing.JButton btn_ok; private javax.swing.JComboBox<String> combo_atributo; private javax.swing.JComboBox<String> combo_nivel; private javax.swing.JComboBox<String> combo_tipo; private javax.swing.JLabel def; private javax.swing.JLabel desc; private javax.swing.JLabel id; private javax.swing.JLabel jLabel3; private javax.swing.JLabel jLabel4; private javax.swing.JPanel jPanel2; private javax.swing.JLabel lbl_Carta; private javax.swing.JLabel lbl_atk; private javax.swing.JLabel lbl_atributo; private javax.swing.JLabel lbl_def; private javax.swing.JLabel lbl_efeito; private javax.swing.JLabel lbl_fundo; private javax.swing.JLabel lbl_id; private javax.swing.JLabel lbl_img; private javax.swing.JLabel lbl_nivel; private javax.swing.JLabel lbl_nome; private javax.swing.JLabel lbl_tipo; private javax.swing.JLabel lbl_tipoMonstro; private javax.swing.JLabel lbl_titulo; private javax.swing.JLabel lbl_type; private javax.swing.JLabel nivel; private javax.swing.JLabel nome; private javax.swing.JScrollPane scr_efeito; private javax.swing.JTextField txt_ID; private javax.swing.JTextField txt_atk; private javax.swing.JTextField txt_def; private javax.swing.JTextArea txt_desc; private javax.swing.JTextField txt_nome; private javax.swing.JTextField txt_tipo; // End of variables declaration//GEN-END:variables private void botaoOK() { // Variáveis auxiliares int atk = 0; int def = 0; if (!txt_atk.getText().equals("") && !txt_def.getText().equals("") && !txt_ID.getText().equals("") && !txt_nome.getText().equals("") && !txt_desc.getText().equals("") && !txt_tipo.getText().equals("") && combo_atributo.getSelectedItem() != null && combo_nivel.getSelectedItem() != null && combo_tipo.getSelectedItem() != null) { // Verifica se alguns dados são numéricos // Ataque try { atk = Integer.parseInt(txt_atk.getText()); } catch (NumberFormatException e) { JOptionPane.showMessageDialog(rootPane, "Insira um valor numérico para o ATK!!"); txt_atk.setText(""); } // Defesa try { def = Integer.parseInt(txt_def.getText()); } catch (NumberFormatException e) { JOptionPane.showMessageDialog(rootPane, "Insira um valor numérico para a DEF!!"); txt_def.setText(""); } // Chama a proxima tela e salva as informações CartaMonstro m = new CartaMonstro(); m.setAtk(atk); m.setAtributo(combo_atributo.getSelectedItem() + ""); m.setDef(def); m.setID(txt_ID.getText()); m.setNivel(combo_nivel.getSelectedIndex() + 1); m.setNome(txt_nome.getText()); m.setTipo(combo_tipo.getSelectedItem() + ""); m.seteMonstro(true); m.setImg(lbl_img.getIcon()); // Efeito do monstro if (m.getTipo().equals("Normal")) { m.setDescricao(txt_desc.getText()); } else { m.setEfeito(txt_desc.getText()); } baralho.set(indiceSelecionado, m); d.salvarDeck(baralho); JOptionPane.showMessageDialog(rootPane, "Monstro Editado com Sucesso!"); indiceSelecionado = 0; // Sai da tela e volta pro menu AlterarCartas ac = new AlterarCartas(); ac.setVisible(true); this.dispose(); } } public void limparDados() { txt_ID.setText(""); txt_atk.setText(""); txt_def.setText(""); txt_desc.setText(""); txt_nome.setText(""); txt_tipo.setText(""); combo_atributo.setSelectedItem(null); lbl_atributo.setIcon(null); combo_nivel.setSelectedIndex(0); lbl_nivel.setIcon(null); combo_tipo.setSelectedItem("Normal"); lbl_img.setIcon(null); } private void escolherImagem() { JFileChooser file = new JFileChooser(); file.setFileSelectionMode(JFileChooser.FILES_ONLY); // Diretorio padrão File dir = new File("src\\br\\inatel\\yugioh\\content"); file.setCurrentDirectory(dir); int i = file.showSaveDialog(null); if (i == 1) { lbl_img.setText(""); } else { File arquivo = file.getSelectedFile(); ImageIcon img = new ImageIcon(arquivo.getAbsolutePath()); lbl_img.setIcon(img); preencherDados(); } } private void setarIconeAtributo() { // Referenciando as imagens ImageIcon trevas = new ImageIcon("src\\br\\inatel\\yugioh\\img\\atr\\atr_dark.png"); ImageIcon terra = new ImageIcon("src\\br\\inatel\\yugioh\\img\\atr\\atr_earth.png"); ImageIcon fogo = new ImageIcon("src\\br\\inatel\\yugioh\\img\\atr\\atr_fire.png"); ImageIcon luz = new ImageIcon("src\\br\\inatel\\yugioh\\img\\atr\\atr_light.png"); ImageIcon agua = new ImageIcon("src\\br\\inatel\\yugioh\\img\\atr\\atr_water.png"); ImageIcon vento = new ImageIcon("src\\br\\inatel\\yugioh\\img\\atr\\atr_wind.png"); ImageIcon god = new ImageIcon("src\\br\\inatel\\yugioh\\img\\atr\\atr_divine.png"); // Se o atributo for selecionado, muda o label if (combo_atributo.getSelectedItem().equals("Trevas")) { lbl_atributo.setIcon(trevas); } if (combo_atributo.getSelectedItem().equals("Divino")) { lbl_atributo.setIcon(god); } if (combo_atributo.getSelectedItem().equals("Terra")) { lbl_atributo.setIcon(terra); } if (combo_atributo.getSelectedItem().equals("Fogo")) { lbl_atributo.setIcon(fogo); } if (combo_atributo.getSelectedItem().equals("Luz")) { lbl_atributo.setIcon(luz); } if (combo_atributo.getSelectedItem().equals("Água")) { lbl_atributo.setIcon(agua); } if (combo_atributo.getSelectedItem().equals("Vento")) { lbl_atributo.setIcon(vento); } } private void setarNivel() { ImageIcon nv1 = new ImageIcon("src\\br\\inatel\\yugioh\\img\\nv\\nivel1.png"); ImageIcon nv2 = new ImageIcon("src\\br\\inatel\\yugioh\\img\\nv\\nivel2.png"); ImageIcon nv3 = new ImageIcon("src\\br\\inatel\\yugioh\\img\\nv\\nivel3.png"); ImageIcon nv4 = new ImageIcon("src\\br\\inatel\\yugioh\\img\\nv\\nivel4.png"); ImageIcon nv5 = new ImageIcon("src\\br\\inatel\\yugioh\\img\\nv\\nivel5.png"); ImageIcon nv6 = new ImageIcon("src\\br\\inatel\\yugioh\\img\\nv\\nivel6.png"); ImageIcon nv7 = new ImageIcon("src\\br\\inatel\\yugioh\\img\\nv\\nivel7.png"); ImageIcon nv8 = new ImageIcon("src\\br\\inatel\\yugioh\\img\\nv\\nivel8.png"); ImageIcon nv9 = new ImageIcon("src\\br\\inatel\\yugioh\\img\\nv\\nivel9.png"); ImageIcon nv10 = new ImageIcon("src\\br\\inatel\\yugioh\\img\\nv\\nivel10.png"); ImageIcon nv11 = new ImageIcon("src\\br\\inatel\\yugioh\\img\\nv\\nivel11.png"); ImageIcon nv12 = new ImageIcon("src\\br\\inatel\\yugioh\\img\\nv\\nivel12.png"); if (combo_nivel.getSelectedItem().equals("1")) { lbl_nivel.setIcon(nv1); } if (combo_nivel.getSelectedItem().equals("2")) { lbl_nivel.setIcon(nv2); } if (combo_nivel.getSelectedItem().equals("3")) { lbl_nivel.setIcon(nv3); } if (combo_nivel.getSelectedItem().equals("4")) { lbl_nivel.setIcon(nv4); } if (combo_nivel.getSelectedItem().equals("5")) { lbl_nivel.setIcon(nv5); } if (combo_nivel.getSelectedItem().equals("6")) { lbl_nivel.setIcon(nv6); } if (combo_nivel.getSelectedItem().equals("7")) { lbl_nivel.setIcon(nv7); } if (combo_nivel.getSelectedItem().equals("8")) { lbl_nivel.setIcon(nv8); } if (combo_nivel.getSelectedItem().equals("9")) { lbl_nivel.setIcon(nv9); } if (combo_nivel.getSelectedItem().equals("10")) { lbl_nivel.setIcon(nv10); } if (combo_nivel.getSelectedItem().equals("11")) { lbl_nivel.setIcon(nv11); } if (combo_nivel.getSelectedItem().equals("12")) { lbl_nivel.setIcon(nv12); } } private void setarTipoCarta() { // Referenciando as imagens ImageIcon monster = new ImageIcon("src\\br\\inatel\\yugioh\\img\\card\\monsterPNG.png"); ImageIcon effect = new ImageIcon("src\\br\\inatel\\yugioh\\img\\card\\effectPNG.png"); ImageIcon fusion = new ImageIcon("src\\br\\inatel\\yugioh\\img\\card\\fusionPNG.png"); ImageIcon ritual = new ImageIcon("src\\br\\inatel\\yugioh\\img\\card\\ritualPNG.png"); // Mudando a imagem da carta de acordo com a opção do usuário if (combo_tipo.getSelectedItem().equals("Normal")) { lbl_Carta.setIcon(monster); } if (combo_tipo.getSelectedItem().equals("Efeito")) { lbl_Carta.setIcon(effect); } if (combo_tipo.getSelectedItem().equals("Ritual")) { lbl_Carta.setIcon(ritual); } if (combo_tipo.getSelectedItem().equals("Fusão")) { lbl_Carta.setIcon(fusion); } } private void preencherDados() { // Setando o tipo da carta (Desenho) lbl_type.setText("[" + txt_tipo.getText() + " / " + combo_tipo.getSelectedItem() + "]"); // Ataque da Carta lbl_atk.setText(txt_atk.getText()); // Ataque da Carta (Desenho) // Defesa da Carta lbl_def.setText(txt_def.getText()); // Defesa da Carta (Desenho) // Nome da Carta lbl_nome.setText(txt_nome.getText()); // Efeito ou descrição lbl_efeito.setText(txt_desc.getText()); // Id da carta lbl_id.setText(txt_ID.getText()); } }
true
692f81183e5b2dadea6a87b68489c8011d0ae678
Java
YuanKJ-/HoVerticalCalendarView
/app/src/main/java/com/ykj/calendar/bean/WhCalendarBean.java
UTF-8
2,209
2.453125
2
[ "Apache-2.0" ]
permissive
package com.ykj.calendar.bean; import android.os.Parcel; import android.os.Parcelable; /** * Created by admin on 2015/6/9. */ public class WhCalendarBean implements Parcelable{ private long beginDate; private long endDate; private String type; private String beginFormat; private String endFormat; public long getBeginDate() { return beginDate; } public void setBeginDate(long beginDate) { this.beginDate = beginDate; } public long getEndDate() { return endDate; } public void setEndDate(long endDate) { this.endDate = endDate; } public String getType() { return type; } public void setType(String type) { this.type = type; } public String getBeginFormat() { return beginFormat; } public void setBeginFormat(String beginFormat) { this.beginFormat = beginFormat; } public String getEndFormat() { return endFormat; } public void setEndFormat(String endFormat) { this.endFormat = endFormat; } @Override public int describeContents() { return 0; } @Override public void writeToParcel(Parcel dest, int flags) { dest.writeLong(beginDate); dest.writeLong(endDate); dest.writeString(type); dest.writeString(beginFormat); dest.writeString(endFormat); } public static final Creator<WhCalendarBean> CREATOR = new Creator<WhCalendarBean>() { @Override public WhCalendarBean createFromParcel(Parcel source) { WhCalendarBean whCalendarBean = new WhCalendarBean(); whCalendarBean.beginDate = source.readLong(); //读取beginData whCalendarBean.endDate = source.readLong(); //读取endDate whCalendarBean.type = source.readString(); //读取type whCalendarBean.beginFormat = source.readString(); //读取beginFormat whCalendarBean.endFormat = source.readString(); //读取endFormat return whCalendarBean; } @Override public WhCalendarBean[] newArray(int size) { return new WhCalendarBean[size]; } }; }
true
b6ce4de28e565194f528311849d0308549ef37ff
Java
alipay/alipay-sdk-java-all
/v2/src/main/java/com/alipay/api/response/AlipayTradeSettleConfirmResponse.java
UTF-8
1,221
1.992188
2
[ "Apache-2.0" ]
permissive
package com.alipay.api.response; import com.alipay.api.internal.mapping.ApiField; import com.alipay.api.AlipayResponse; /** * ALIPAY API: alipay.trade.settle.confirm response. * * @author auto create * @since 1.0, 2023-07-21 21:11:55 */ public class AlipayTradeSettleConfirmResponse extends AlipayResponse { private static final long serialVersionUID = 2664316676422898633L; /** * 确认结算请求流水号,开发者自行生成并保证唯一性,作为业务幂等性控制 */ @ApiField("out_request_no") private String outRequestNo; /** * 本次确认结算的实际结算金额,单位为元。 */ @ApiField("settle_amount") private String settleAmount; /** * 支付宝交易号 */ @ApiField("trade_no") private String tradeNo; public void setOutRequestNo(String outRequestNo) { this.outRequestNo = outRequestNo; } public String getOutRequestNo( ) { return this.outRequestNo; } public void setSettleAmount(String settleAmount) { this.settleAmount = settleAmount; } public String getSettleAmount( ) { return this.settleAmount; } public void setTradeNo(String tradeNo) { this.tradeNo = tradeNo; } public String getTradeNo( ) { return this.tradeNo; } }
true
fe81587d9bbbc2068434e6f28366f8cfb2882d88
Java
thecodemonkeyau/taskadapter
/connectors/connector-msp/src/main/java/com/taskadapter/connector/msp/MSPExceptions.java
UTF-8
795
2.078125
2
[]
no_license
package com.taskadapter.connector.msp; import java.io.FileNotFoundException; import net.sf.mpxj.MPXJException; import com.taskadapter.connector.definition.exceptions.BadConfigException; import com.taskadapter.connector.definition.exceptions.ConnectorException; import com.taskadapter.connector.definition.exceptions.EntityProcessingException; public final class MSPExceptions { public static ConnectorException convertException(Exception e) { if (e instanceof FileNotFoundException) return new BadConfigException("Bad project file name: " + e.getMessage(), e); return new EntityProcessingException(e); } public static ConnectorException convertException(MPXJException e) { return new EntityProcessingException(e); } }
true
4027717f0e7f08f838664ceeaebfaf5baf5fc20a
Java
Gemmmm/yuxiu
/src/main/java/com/tc/yuxiu/model/SpecItems.java
UTF-8
1,008
2.078125
2
[]
no_license
package com.tc.yuxiu.model; import com.alibaba.fastjson.JSONArray; import java.util.List; import java.util.Map; public class SpecItems { @Override public String toString() { return "SpecItems{" + "goodsId=" + goodsId + ", token='" + token + '\'' + ", specItemsIdses=" + specItemsIdses + '}'; } private Integer goodsId; private String token; private List<Map<String,Object>> specItemsIdses; public Integer getGoodsId() { return goodsId; } public void setGoodsId(Integer goodsId) { this.goodsId = goodsId; } public String getToken() { return token; } public void setToken(String token) { this.token = token; } public List<Map<String, Object>> getSpecItemsIdses() { return specItemsIdses; } public void setSpecItemsIdses(List<Map<String, Object>> specItemsIdses) { this.specItemsIdses = specItemsIdses; } }
true
2700cda5d8ae526dc4b8262ff05acc7c73b197a6
Java
spelinar/Szablony_TO
/sample-oop-project/src/main/java/com/mycompany/oop/abstractfactory/ConcreteFactory2.java
UTF-8
475
2.328125
2
[]
no_license
/* * To change this license header, choose License Headers in Project Properties. * To change this template file, choose Tools | Templates * and open the template in the editor. */ package com.mycompany.oop.abstractfactory; /** * * @author 4 */ public class ConcreteFactory2 implements AbstractFactory { public AbstractProductA createProductA() { return new ProductA2(); } public AbstractProductB createProductB() { return new ProductB2(); } }
true
bd63638ccf3d0df239de5fff727c369857fa8d15
Java
Adefy/AdefyAndroid
/AdefyLib/src/main/java/com/sit/adefy/animations/Animation.java
UTF-8
336
2.40625
2
[]
no_license
package com.sit.adefy.animations; public class Animation { // Signals that we've already animated, prevents future starts private boolean mActive = false; public void rendererAnimateStep(long time) {} public boolean isActive() { return mActive; } public void setActive(boolean active) { mActive = active; } }
true
ca52be3a88b7154fb97b7348915847b33018a9f2
Java
qiuyunduo/vhr
/vhrserver/vhr-mapper/src/main/java/cn/qyd/vhr/mapper/AdjustSalaryMapper.java
UTF-8
405
1.757813
2
[]
no_license
package cn.qyd.vhr.mapper; import cn.qyd.vhr.bean.AdjustSalary; public interface AdjustSalaryMapper { int deleteByPrimaryKey(Integer id); int insert(AdjustSalary record); int insertSelective(AdjustSalary record); AdjustSalary selectByPrimaryKey(Integer id); int updateByPrimaryKeySelective(AdjustSalary record); int updateByPrimaryKey(AdjustSalary record); }
true
6553a968f1ad68c1ee770fb7e13ed4615bbcb01e
Java
e3rasdg4no/android
/app/src/main/java/com/eragano/eraganoapps/fragment/KinerjaFragment.java
UTF-8
3,314
2.03125
2
[]
no_license
package com.eragano.eraganoapps.fragment; import android.graphics.Color; import android.support.annotation.Nullable; import android.support.v4.app.FragmentTabHost; import android.support.v7.app.AppCompatActivity; import android.os.Bundle; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.TabHost; import android.widget.TextView; import com.eragano.eraganoapps.R; import com.eragano.eraganoapps.informasi.ArtikelActivity; import com.eragano.eraganoapps.informasi.CuacaActivity; import com.eragano.eraganoapps.performa.InputKinerja; public class KinerjaFragment extends android.support.v4.app.Fragment { private FragmentTabHost mTabHost; @Nullable @Override public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { mTabHost = new FragmentTabHost(getActivity()); mTabHost.setup(getActivity(), getChildFragmentManager(), R.id.content2); mTabHost.addTab(mTabHost.newTabSpec("input").setIndicator("Input Kinerja"), InputKinerja.class, null); mTabHost.addTab(mTabHost.newTabSpec("lihat").setIndicator("Lihat Kinerja"), ArtikelActivity.class, null); TextView textView = (TextView) mTabHost.getTabWidget().getChildAt(0).findViewById(android.R.id.title); textView.setTextColor(Color.parseColor("#FFFFFF")); TextView text2View = (TextView) mTabHost.getTabWidget().getChildAt(1).findViewById(android.R.id.title); text2View.setTextColor(Color.parseColor("#000000")); mTabHost.getTabWidget().getChildAt(0).setBackgroundColor(Color.parseColor("#62C16F")); mTabHost.getTabWidget().getChildAt(1).setBackgroundColor(Color.parseColor("#FFFFFF")); mTabHost.setOnTabChangedListener(new TabHost.OnTabChangeListener() { @Override public void onTabChanged(String tabId) { String tab = tabId; if (tab.equals("input")) { TextView textView = (TextView) mTabHost.getTabWidget().getChildAt(0).findViewById(android.R.id.title); textView.setTextColor(Color.parseColor("#FFFFFF")); TextView text2View = (TextView) mTabHost.getTabWidget().getChildAt(1).findViewById(android.R.id.title); text2View.setTextColor(Color.parseColor("#000000")); mTabHost.getTabWidget().getChildAt(0).setBackgroundColor(Color.parseColor("#62C16F")); mTabHost.getTabWidget().getChildAt(1).setBackgroundColor(Color.parseColor("#FFFFFF")); } else { TextView textView = (TextView) mTabHost.getTabWidget().getChildAt(1).findViewById(android.R.id.title); textView.setTextColor(Color.parseColor("#FFFFFF")); TextView text2View = (TextView) mTabHost.getTabWidget().getChildAt(0).findViewById(android.R.id.title); text2View.setTextColor(Color.parseColor("#000000")); mTabHost.getTabWidget().getChildAt(1).setBackgroundColor(Color.parseColor("#62C16F")); mTabHost.getTabWidget().getChildAt(0).setBackgroundColor(Color.parseColor("#FFFFFF")); } } }); return mTabHost; } }
true
276b242e40eb75f9f82d40e3c81efcbb75a481cf
Java
BastianBertram/GIPF-Game
/src/com/gipf/client/game/player/bot/BotMoveThread.java
UTF-8
2,737
2.765625
3
[]
no_license
package com.gipf.client.game.player.bot; import java.util.ArrayList; import com.gipf.client.game.GameController; import com.gipf.client.game.player.bot.action.Action; import com.gipf.client.player.bot.algorithm.Algorithm; import com.gipf.client.player.bot.evaluation.EvaluationFunction; public class BotMoveThread extends Thread { public static long runTime = 0; public static int runs = 0; private GameController gameController; private EvaluationFunction evaluator; private Algorithm algorithm; private Bot bot; public BotMoveThread(Bot bot, GameController gameController, Algorithm algorithm, EvaluationFunction evaluator) { this.gameController = gameController; this.algorithm = algorithm; this.evaluator = evaluator; this.bot = bot; } public void run() { long start = System.nanoTime(); // computation for move // Node root = new Node(null, this.gameController.getController().getGame().copy(), null, true); // System.out.println("evaluated root"); // this.bot.getGenerator().generateTree(2, root, this.bot, this.bot.getLogic()); // System.out.println(new Tree(root).bfSearch(root).size()); ArrayList<Action> actions = this.algorithm.calculateBestActions(this.gameController.getController().getGame().copy(), this.bot, this.evaluator); // System.out.println("calculated acions"); // Complicated row? Bot remove thread gets information if (actions.size() > 1) { ArrayList<Action> upcomingActions = new ArrayList<Action>(); for (int i = 1; i < actions.size(); i++) upcomingActions.add(actions.get(i)); this.bot.setUpcomingActions(upcomingActions); } long end = System.nanoTime(); runTime += end - start; runs++; // System.out.println("average runtime: " + runTime / (runs * 1000000.0) + "ms at " + runs + " runs, current run time: " + (end - start) + " miliseconds = " + ((end - start) / 1000000.0) + " ms with " + " algo: " + this.algorithm.getClass().getName() +"."); // System.out.println(); // used for making bots move visible if (end - start < 166700000) { try { Thread.sleep((166700000 - (end - start)) / 1000000); } catch (InterruptedException e) { Thread.currentThread().interrupt(); } } // do move this.gameController.getController().getGamePanel().getButtons()[actions.get(0).getPoints()[0].getX()][actions.get(0).getPoints()[0].getY()].doClick(); // visualise direction choice try { Thread.sleep(250); } catch (InterruptedException e) { Thread.currentThread().interrupt(); } this.gameController.getController().getGamePanel().getButtons()[actions.get(0).getPoints()[1].getX()][actions.get(0).getPoints()[1].getY()].doClick(); } }
true
37c84c9da80e83cd25e8f25ba8e00059e1b1a2ab
Java
coletteemurphy/advent1
/src/com/colette/Advent.java
UTF-8
2,367
3
3
[]
no_license
package com.colette; import java.io.*; import java.io.InputStream; import java.util.Arrays; import java.util.List; public class Advent { public static void main(String[] args) { System.out.println("hello world"); //calculateFuel() //checkOpCode } public static void checkOPCode() { List list = Arrays.asList(1,0,0,3,1,1,2,3,1,3,4,3,1,5,0,3,2,1,13,19,1,9,19,23,2,13,23,27, 2,27,13,31,2,31,10,35,1,6,35,39,1,5,39,43,1,10,43,47,1,5,47,51,1,13,51, 55,2,55,9,59,1,6,59,63,1,13,63,67,1,6,67,71,1,71,10,75,2,13,75,79,1,5,79, 83,2,83,6,87,1,6,87,91,1,91,13,95,1,95,13,99,2,99,13,103,1,103,5,107,2,107, 10,111,1,5,111,115,1,2,115,119,1,119,6,0,99,2,0,14,0); } public static void calculateFuel()throws FileNotFoundException, IOException { FileInputStream fis = getFileInputStream("/Users/colette/IdeaProjects/advent1/src/com/colette/input.txt"); System.out.println("Total file size to read (in bytes) : " + fis.available()); BufferedReader reader = new BufferedReader(new InputStreamReader(fis)); String thisLine = null; int total = 0; while ((thisLine = reader.readLine() )!= null) { int mass = Integer.parseInt(thisLine); total += getFuelForInitialAndFuel(mass); } System.out.println(total); } public static int getFuelForInitialAndFuel(int mass) { int firstFuel = getFuelForMass(mass); int fuelForFuel = getFuelForFuel(firstFuel); return firstFuel + fuelForFuel; } public static int getFuelForFuel(int fuel){ boolean fuelReachedZero = false; int total = 0; int newFuel = fuel; while (newFuel >= 0) { int newResult = getFuelForMass( newFuel); if (newResult > 0){ total += newResult; } newFuel = newResult; } return total; } public static int getFuelForMass(int mass) { //create an int int massDividedByThree = mass/3; return massDividedByThree - 2; } private static FileInputStream getFileInputStream(String fileName) throws IOException { File file = new File(fileName); return new FileInputStream(file); } }
true
e23757f261fafc1dae765dadade40461b1a232bf
Java
smartdriver001/CoreJavaHorstmannExamples
/src/c08examples/Ex04.java
UTF-8
428
3.234375
3
[]
no_license
package c08examples; import java.util.stream.Stream; public class Ex04 { public static void main(String[] args) { Double pow = Math.pow(2, 48); Stream<Long> s = linearCongruentialGenerator(1, 25214903917L, 11, pow.longValue()); s.forEach(System.out::println); } private static Stream<Long> linearCongruentialGenerator(long seed, long a, long c, long m) { return Stream.iterate(seed, x -> (a * x + c) % m); } }
true
aa3d1ad5b34f71e7cdce72cc71b91fa10cb404b3
Java
mukundlal/WorksApp
/app/src/main/java/thozhilali/com/thozhilali/Welcome.java
UTF-8
1,066
2.09375
2
[]
no_license
package thozhilali.com.thozhilali; import android.animation.ObjectAnimator; import android.content.Intent; import android.support.v7.app.AppCompatActivity; import android.os.Bundle; import android.view.animation.LinearInterpolator; import android.widget.ProgressBar; import java.util.Timer; import java.util.TimerTask; import java.util.logging.Handler; public class Welcome extends AppCompatActivity { ProgressBar p; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_welcome); p=(ProgressBar)findViewById(R.id.pg1) ; p.setProgress(0); Timer t= new Timer(); t.schedule(new TimerTask(){ public void run() { Welcome.this.runOnUiThread(new Runnable() { public void run() { p.setProgress(100); startActivity(new Intent(Welcome.this,Home.class)); } }); } }, 2000); } }
true
1941a3c386e6ec10dcf660f06bce96542c9a5ead
Java
zhurongzeng/biz
/src/main/java/com/niu/biz/po/InformationInfo.java
UTF-8
2,401
1.90625
2
[]
no_license
package com.niu.biz.po; import com.niu.biz.annotation.GeneratedUID; import lombok.Data; import lombok.NonNull; import javax.persistence.Column; import javax.persistence.Entity; import javax.persistence.Id; import javax.persistence.Table; /** * 资讯消息表Model对象 * * @author xiaohean * @date 2018-05-10 */ @Data @Entity @Table(name = "t_information_info") public class InformationInfo extends BasePO { /** * 资讯序号 */ @Id @GeneratedUID private String dataId; /** * 标题 */ @Column private String title; /** * 内容 */ @Column private String content; /** * 内容VIP收费 */ @Column(name = "contentVip") private String contentVip; /** * 讲师用户号 */ @Column private String tchUserName; /** * 是否发布 */ @Column private String sendFlag; /** * 发布时间 */ @Column private String sendDatetime; /** * 资讯单价 */ @Column private Integer price; /** * 资讯类别 */ @Column private String feeType; /** * 评论人A用户号 */ @Column(name = "comment_User_A") private String commentUserA; /** * 评论A内容 */ @Column(name = "comment_A") private String commentA; /** * 评论A时间 */ @Column(name = "comment_Time_A") private String commentTimeA; /** * 评论人B用户号 */ @Column(name = "comment_User_B") private String commentUserB; /** * 评论B内容 */ @Column(name = "comment_B") private String commentB; /** * 评论B时间 */ @Column(name = "comment_Time_B") private String commentTimeB; /** * 备用字段1 */ @Column private String bizStr1; /** * 备用字段2 */ @Column private String bizStr2; /** * 备用字段3 */ @Column private String bizText; /** * 业务编号1 */ @Column private String bizNo1; /** * 业务编号2 */ @Column private String bizNo2; /** * 业务编号3 */ @Column private String bizNo3; /** * 备注 */ @Column private String remark; /** * 描述 */ @Column private String description; }
true
ffe01f7b341b71e2c7d39b330189a2ec3bc031ce
Java
melfandary/AuctionHouse
/src/theauctionhouse/DebitPayment.java
UTF-8
246
1.890625
2
[]
no_license
package theauctionhouse; public class DebitPayment implements payMethod { @Override public void pay(int amount, String sender, String reciever) { ; //To change body of generated methods, choose Tools | Templates. } }
true
0575ab0da192a92fe7c7db08e17bd40c3953028f
Java
RE-CoderMJ/Java
/12_IO/src/com/kh/chap03_char/run/FileCharRun.java
UTF-8
239
1.703125
2
[]
no_license
package com.kh.chap03_char.run; import com.kh.chap03_char.model.dao.FileCharDao; public class FileCharRun { public static void main(String[] args) { FileCharDao dao = new FileCharDao(); //dao.fileSave(); dao.fileRead(); } }
true
1f07f6acf7b9bfd17d51215d7b6e871ba3f73baa
Java
zct1115/Course
/app/src/main/java/com/example/zct11/course/message/Downloadmessage.java
UTF-8
962
2.609375
3
[]
no_license
package com.example.zct11.course.message; /** * Created by zct11 on 2017/11/4. */ public class Downloadmessage { private String url; private String name; private String size; public Downloadmessage(String url, String name, String size) { this.url = url; this.name = name; this.size = size; } public String getSize() { return size; } public void setSize(String size) { this.size = size; } public String getUrl() { return url; } public void setUrl(String url) { this.url = url; } public String getName() { return name; } public void setName(String name) { this.name = name; } @Override public String toString() { return "Downloadmessage{" + "url='" + url + '\'' + ", name='" + name + '\'' + ", size='" + size + '\'' + '}'; } }
true
85de70962c858f920038b6d33aaa7d7201527ccf
Java
akashagrahari/chessGame
/src/test/java/com/example/game/model/piece/QueenPieceTest.java
UTF-8
3,502
2.5
2
[]
no_license
package com.example.game.model.piece; import com.example.game.model.PieceType; import com.example.game.model.PlayerColour; import com.example.game.model.Position; import com.example.game.model.Spot; import org.junit.Assert; import org.junit.Before; import org.junit.Test; import org.mockito.Mockito; import static com.example.game.constants.ChessConstants.GRID_SIZE; import static com.example.game.constants.ChessConstants.QUEEN_POSITION; /** * Created by akash on 26/9/18. */ public class QueenPieceTest { private QueenPiece queenPiece; private Position positionFrom; private Position positionToX1; private Position positionToX2; private Position positionToY1; private Position positionToY2; private Position positionToDiagnol; private Spot spot; private Position positionToIllegal; private Spot[][] chessGrid = new Spot[GRID_SIZE][GRID_SIZE]; @Before public void setup() { PieceTestUtils.generateGrid(chessGrid); queenPiece = Mockito.spy(new QueenPiece(PlayerColour.WHITE)); positionFrom = new Position(2,3); positionToX1 = new Position(4,3); positionToX2 = new Position(1,3); positionToY1 = new Position(2,1); positionToY2 = new Position(2,4); positionToDiagnol = new Position(4,5); spot = new Spot(); positionToIllegal = new Position(3,5); } @Test public void testSetInitialPosition() { Mockito.doReturn(0).when((Piece) queenPiece).getStartingRow1(); queenPiece.setInitialPosition(chessGrid); Assert.assertEquals(chessGrid[0][QUEEN_POSITION].getPiece().getPieceType(), PieceType.QUEEN); } @Test public void testIsValidMoveType() { Mockito.doReturn(false).when((Piece) queenPiece).moveCapturesOwnUnit(PlayerColour.WHITE, spot); Assert.assertTrue(queenPiece.isValidMoveType(positionFrom, positionToX1, PlayerColour.WHITE, spot)); Assert.assertTrue(queenPiece.isValidMoveType(positionFrom, positionToX2, PlayerColour.WHITE, spot)); Assert.assertTrue(queenPiece.isValidMoveType(positionFrom, positionToY1, PlayerColour.WHITE, spot)); Assert.assertTrue(queenPiece.isValidMoveType(positionFrom, positionToY2, PlayerColour.WHITE, spot)); Assert.assertTrue(queenPiece.isValidMoveType(positionFrom, positionToDiagnol, PlayerColour.WHITE, spot)); Assert.assertFalse(queenPiece.isValidMoveType(positionFrom, positionToIllegal, PlayerColour.WHITE, spot)); Mockito.doReturn(true).when((Piece) queenPiece).moveCapturesOwnUnit(PlayerColour.WHITE, spot); Assert.assertFalse(queenPiece.isValidMoveType(positionFrom, positionToX1, PlayerColour.WHITE, spot)); Assert.assertFalse(queenPiece.isValidMoveType(positionFrom, positionToX2, PlayerColour.WHITE, spot)); Assert.assertFalse(queenPiece.isValidMoveType(positionFrom, positionToY1, PlayerColour.WHITE, spot)); Assert.assertFalse(queenPiece.isValidMoveType(positionFrom, positionToY2, PlayerColour.WHITE, spot)); Assert.assertFalse(queenPiece.isValidMoveType(positionFrom, positionToDiagnol, PlayerColour.WHITE, spot)); } @Test public void testIsMoveThroughOtherPieces() { Assert.assertFalse(queenPiece.isMoveThroughOtherPieces(positionFrom, positionToX1, chessGrid)); chessGrid[3][3] = new Spot(new BishopPiece(PlayerColour.BLACK)); Assert.assertTrue(queenPiece.isMoveThroughOtherPieces(positionFrom, positionToX1, chessGrid)); } }
true
b0171d3df71ddf651a11520e5049a543ab5cbcb0
Java
StajicVladimir/ITAcademy
/JavaFXFXML/src/javafxfxml/JavaFXFXML.java
UTF-8
1,231
2.375
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 javafxfxml; import java.net.URL; import javafx.application.Application; import javafx.fxml.FXMLLoader; import javafx.scene.Scene; import javafx.scene.layout.AnchorPane; import javafx.scene.layout.VBox; import javafx.stage.Stage; /** * * @author Vladimir */ public class JavaFXFXML extends Application { /** * @param args the command line arguments */ public static void main(String[] args) { // TODO code application logic here Application.launch(args); } @Override public void start(Stage primaryStage) throws Exception { URL fxmlUrl = getClass().getClassLoader().getResource("fxml/proba.fxml"); VBox root = FXMLLoader.<VBox>load(fxmlUrl); //AnchorPane root = FXMLLoader.<AnchorPane>load(fxmlUrl); //SayHelloController c = new SayHelloController(); // VBox root = FXMLLoader.load(fxmlUrl); Scene scene = new Scene(root); primaryStage.setScene(scene); primaryStage.show(); } }
true
fc8aa7cf934ba2cfe40d0b416cb7d40761d84850
Java
xeonye/portal
/portal_admin/src/main/java/com/infosmart/service/DwpasCModuleInfoService.java
UTF-8
1,187
2.125
2
[]
no_license
package com.infosmart.service; import java.util.List; import java.util.Map; import com.infosmart.po.DwpasCmoduleInfo; public interface DwpasCModuleInfoService { /** * 根据菜单id,dateType获得模块信息 * * @param dateType * @param menuId * @return */ List<DwpasCmoduleInfo> getDwpasCmoduleInfoByMenuId(String menuId, String dateType); /** * 根据ID查询模块信息 * * @param moduleId * @return */ DwpasCmoduleInfo getDwpasCmoduleInfoById(String moduleId); /** * 插入模块信息 * * @param map */ void insertDwpasCmoduleInfo(Map<String, Integer> map) throws Exception; /** * 删除模块信息 * * @param menuId */ void deleteDwpasCmoduleInfo(List<String> menuId) throws Exception; /** * 删除模块信息 * * @param menuId */ void deleteDwpasCmoduleInfoById(String moduleId) throws Exception; /** * 根据菜单id集合获得模块信息 * * @param menuIds * @return */ List<DwpasCmoduleInfo> getDwpasCmoduleInfoByMenuIds(List<String> menuIds); /** * 根据菜单id更新模块信息 * * @param info */ void updateDwpasCModuleInfo(DwpasCmoduleInfo info) throws Exception; }
true
047ed13c118c893d3dce85579b5014f2304a7a05
Java
rdx7777/CodersTrust-solutions-13-radoslaw
/src/test/java/pl/coderstrust/search/SearchingTestBase.java
UTF-8
2,692
3.109375
3
[]
no_license
package pl.coderstrust.search; import org.junit.jupiter.api.BeforeAll; import org.junit.jupiter.api.Test; import static org.assertj.core.api.Assertions.assertThat; import static org.junit.jupiter.api.Assertions.assertThrows; public abstract class SearchingTestBase { public abstract SearchingMethod getSearchingMethod(); private static int[] arrayToSearch; @BeforeAll private static void setup() { arrayToSearch = new int[6_000_000]; for (int i = 0; i < 6_000_000; i++) { arrayToSearch[i] = i; } } @Test void shouldSearchFirstElement() { // given System.out.print("First element searched by <<" + getSearchingMethod().getClass() + ">> found in "); // when long startTime = System.nanoTime(); int result = getSearchingMethod().search(arrayToSearch, 0); long endTime = System.nanoTime(); System.out.println((endTime - startTime) + " nanoseconds."); // then assertThat(result).isEqualTo(0); } @Test void shouldSearchMiddleElement() { // given System.out.print("Middle element searched by <<" + getSearchingMethod().getClass() + ">> found in "); // when long startTime = System.nanoTime(); int result = getSearchingMethod().search(arrayToSearch, 2_999_999); long endTime = System.nanoTime(); System.out.println((endTime - startTime) + " nanoseconds."); // then assertThat(result).isEqualTo(2_999_999); } @Test void shouldSearchLastElement() { // given System.out.print("Last element searched by <<" + getSearchingMethod().getClass() + ">> found in "); // when long startTime = System.nanoTime(); int result = getSearchingMethod().search(arrayToSearch, 5_999_999); long endTime = System.nanoTime(); System.out.println((endTime - startTime) + " nanoseconds."); // then assertThat(result).isEqualTo(5_999_999); } @Test void shouldSearchNotExistingElement() { // given System.out.print("Not existing element was searched by <<" + getSearchingMethod().getClass() + ">> for "); // when long startTime = System.nanoTime(); int result = getSearchingMethod().search(arrayToSearch, 6_000_000); long endTime = System.nanoTime(); System.out.println((endTime - startTime) + " nanoseconds."); // then assertThat(result).isEqualTo(-1); } @Test void shouldThrowExceptionForNullArray() { assertThrows(IllegalArgumentException.class, () -> getSearchingMethod().search(null, 1)); } }
true
963f4c8d8a5388c2ad1cf017a42e51e86220ac20
Java
Scrin/DerpBot
/src/main/java/fi/derpnet/derpbot/handler/impl/GeoIp.java
UTF-8
4,467
2.453125
2
[]
no_license
package fi.derpnet.derpbot.handler.impl; import com.maxmind.geoip2.DatabaseReader; import com.maxmind.geoip2.exception.GeoIp2Exception; import com.maxmind.geoip2.model.CityResponse; import com.maxmind.geoip2.record.City; import com.maxmind.geoip2.record.Country; import com.maxmind.geoip2.record.Location; import com.maxmind.geoip2.record.Postal; import com.maxmind.geoip2.record.RepresentedCountry; import com.maxmind.geoip2.record.Traits; import fi.derpnet.derpbot.connector.IrcConnector; import fi.derpnet.derpbot.controller.MainController; import fi.derpnet.derpbot.handler.SimpleMessageHandler; import fi.derpnet.derpbot.util.CommandUtils; import java.io.IOException; import java.net.InetAddress; import java.net.UnknownHostException; public class GeoIp implements SimpleMessageHandler { private DatabaseReader databaseReader; @Override public void init(MainController controller) { try { databaseReader = new DatabaseReader.Builder(this.getClass().getResourceAsStream("/GeoLite2-City.mmdb")).build(); } catch (IOException e) { } } @Override public String getCommand() { return "!geoip"; } @Override public String getHelp() { return "Looks up an IP address or hostname from GeoIP2 database"; } @Override public String handle(String sender, String recipient, String message, IrcConnector ircConnector) { if (!message.startsWith("!geoip ")) { return null; } try { String lookup = CommandUtils.getFirstParameter(message); InetAddress ipAddress = InetAddress.getByName(lookup); if (ipAddress.isSiteLocalAddress()) { return "Local address"; } String hostname = ipAddress.getCanonicalHostName(); String ip = ipAddress.getHostAddress(); CityResponse response = databaseReader.city(ipAddress); Country country = response.getCountry(); City city = response.getCity(); Postal postal = response.getPostal(); Location location = response.getLocation(); RepresentedCountry representedCountry = response.getRepresentedCountry(); Traits traits = response.getTraits(); StringBuilder sb = new StringBuilder(); if (hostname != null && !hostname.equals(ip)) { sb.append(hostname).append(" (").append(ip).append(") = "); } else { sb.append(ip).append(" = "); } if (city != null && city.getName() != null) { sb.append(city.getName()).append(", "); } if (postal != null && postal.getCode() != null) { sb.append(postal.getCode()).append(", "); } if (country != null && country.getName() != null) { sb.append(country.getName()).append(", "); } if (location != null) { sb.append("Lat: ").append(location.getLatitude()).append(" Lon: ").append(location.getLongitude()).append(" Accuracy radius: ").append(location.getAccuracyRadius()).append("km"); } else if (", ".equals(sb.substring(sb.length() - 2, sb.length()))) { sb.delete(sb.length() - 2, sb.length()); } if (representedCountry != null && representedCountry.getType() != null) { sb.append(" (Type: ").append(representedCountry.getType()).append(')'); } if (traits != null) { if (traits.getAutonomousSystemNumber() != null && traits.getAutonomousSystemOrganization() != null) { sb.append(" ASN: ").append(traits.getAutonomousSystemNumber()).append(" (").append(traits.getAutonomousSystemOrganization()).append(')'); } if (traits.getIsp() != null) { sb.append(" ISP: ").append(traits.getIsp()); } if (traits.getOrganization() != null) { sb.append(" Organization: ").append(traits.getOrganization()); } } return sb.length() > 0 ? sb.toString() : null; } catch (UnknownHostException ex) { return "Unknown host"; } catch (IOException ex) { return "Lookup failed"; } catch (GeoIp2Exception ex) { return "Lookup failed: " + ex.getMessage(); } } }
true
997a73d3a0e631de0c410840be120d514f196bab
Java
PauloSimoes/CalculatorProject
/calculator-api/src/test/resources/io/critical/start/calculator/tests/CalculatorJsonModule.java
UTF-8
502
1.507813
2
[]
no_license
package io.critical.start.calculator.tests; import com.fasterxml.jackson.databind.module.SimpleModule; import io.critical.start.calculator.Calculator; import org.springframework.stereotype.Service; @Service public class CalculatorJsonModule extends SimpleModule { private static final long serialVersionUID = 1L; public CalculatorJsonModule() { this.addDeserializer(Calculator.class, new CalculatorDeserializer()); this.addSerializer(Calculator.class, new CalculatorSerializer()); } }
true
7da31c16fcd03643dd29acf225c160b2eeccfb93
Java
VinsentY/JavaPratice
/静态初始化顺序.java
UTF-8
1,000
3.875
4
[]
no_license
package rely; class Bowl { public Bowl(int marker) { System.out.println("Bowl(" + marker + "Construtor )"); } void f1(int marker) { System.out.println("f1(" + marker + ")"); } } class Table { static Bowl bowl1 = new Bowl(1); public Table() { System.out.println("Table() Construtor"); } void f2(int marker) { System.out.println("f2(" + marker + ")"); } static Bowl bowl2 = new Bowl(2); } class Cupboard { Bowl bowl3 = new Bowl(3); static Bowl bowl4 = new Bowl(4); public Cupboard() { System.out.println("Cupboard() Construtor"); } void f3(int marker) { System.out.println("f3(" + marker + ")"); } static Bowl bowl = new Bowl(5); } public class Test { public static void main(String args[]) { System.out.println("Creating new Cupboard() in main"); new Cupboard(); System.out.println("Creating new Cupboard() in main"); new Cupboard(); table.f2(1); cupboard.f3(1); } static Table table = new Table(); static Cupboard cupboard = new Cupboard(); }
true
38edc58c9fd5431e57b02fcf31a64ea9ff4ae48e
Java
Yphas0128/ypier_cloud
/ypier-sqlserver/src/main/java/cn/ypier/SqlServerApplication.java
UTF-8
610
1.679688
2
[]
no_license
package cn.ypier; import org.mybatis.spring.annotation.MapperScan; import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.SpringBootApplication; import org.springframework.cloud.client.discovery.EnableDiscoveryClient; import org.springframework.cloud.openfeign.EnableFeignClients; /** * @Author Ypier */ @SpringBootApplication @EnableDiscoveryClient @MapperScan(value = "cn.ypier.mapper") @EnableFeignClients public class SqlServerApplication { public static void main(String[] args) { SpringApplication.run(SqlServerApplication.class,args); } }
true
c534ef7bee5b2d16177c4c6823aa302f678f84aa
Java
FadyFouad/DoctorStatus
/src/com/etaTech/Main.java
UTF-8
2,865
3.8125
4
[]
no_license
package com.etaTech; import java.util.Arrays; import java.util.Calendar; import java.util.HashMap; import java.util.stream.IntStream; /**************************************************** *** Created by Fady Fouad on 7/7/2019 at 23:04.*** ***************************************************/ public class Main { public static void main(String[] args) { int []days = {0,1,2,3,4}; // work From Sat To Wednesday int fromHour=8; int toHour=22; String state = getStatusOfDoctorOpenedOrClosed(days,fromHour,toHour); System.out.println(state); } // Function should return a string depending on current date and time, as an example: // 1) “Opened: Closes at 8 PM” // 2) “Closed: Opens at Mon 4 PM” // doctorDays: The days of the week the doctor is available (0 = Saturday, 1 = Sunday, .... , 6 = Friday) // fromHour: for the defined day in the same index, the start hour in 24h format // toHour: for the defined day in the same index, the end hour in 24h format private static String getStatusOfDoctorOpenedOrClosed(int[] doctorDays, int fromHour, int toHour) { int []workHours = IntStream.rangeClosed(fromHour,toHour).toArray(); StringBuilder state = new StringBuilder(); Calendar c = Calendar.getInstance(); int dayOfWeek = c.get(Calendar.DAY_OF_WEEK); int hourNow = c.get(Calendar.HOUR_OF_DAY); HashMap<Integer,String>days = new HashMap<>(); // This to Print Name of the day instead of Numbers days.put(0,"Saturday"); days.put(1,"Sunday"); days.put(2,"Monday"); days.put(3,"Tuesday"); days.put(4,"Wednesday"); days.put(5,"Thursday"); days.put(6,"Friday"); boolean containsDay = Arrays.stream(doctorDays).anyMatch(i -> i == dayOfWeek); //check if today in the array boolean containsHour = Arrays.stream(workHours).anyMatch(i -> i == hourNow); //check if the hour now in the array int nextWorkDay; try { nextWorkDay = doctorDays[dayOfWeek]+1; //get the next day in the work array }catch (IndexOutOfBoundsException e){ nextWorkDay = doctorDays[0]; //if friday is the weekend goto first day in the array } if (containsDay&&containsHour){ state.append("Doctor is available Today\n close at").append(toHour).append(":00"); //doctor at work } if (containsDay&&!containsHour){ state.append("Doctor is close " + "Open At ").append(days.get(nextWorkDay)).append(" at ").append(fromHour).append(":00"); //doctor finished his work } if (!containsDay){ state.append("Doctor is not available Today\n open at").append(days.get(nextWorkDay)).append(" at ").append(toHour).append(":00"); //doctor at holiday } return state.toString(); } }
true
1bed2ade0c4b8afdf85779fb75441cac28c3d609
Java
iberotec/my-proyect-dawiijpa
/ my-proyect-dawiijpa/ProyectoExamen_V3/src/edu/cibertec/bean/Respuestas_Usuario.java
UTF-8
2,931
2.046875
2
[]
no_license
package edu.cibertec.bean; import javax.persistence.Column; import javax.persistence.Entity; import javax.persistence.Id; import javax.persistence.IdClass; import javax.persistence.JoinColumn; import javax.persistence.ManyToOne; import javax.persistence.NamedQuery; import javax.persistence.Table; @Entity(name = "RESP_USUARIO") @Table(name = "tb_res_usu") @NamedQuery(name = "selecPregunta", query = "SELECT c FROM RESP_USUARIO c WHERE c.strCodExamen =:codigo") @IdClass(Respuestas_UsuarioPK.class) public class Respuestas_Usuario { @Id @Column(name = "codExBD") private String strcodExBD; @Id @Column(name = "codigo") private String strcodigo; @Id @Column(name = "codPR") private String strcodPR; @Column(name = "respuest_1") private String strrespuest_1; @Column(name = "respuest_2") private String strrespuest_2; @Column(name = "respuest_3") private String strrespuest_3; @Column(name = "respuest_4") private String strrespuest_4; @Column(name = "respuest_5") private String strrespuest_5; @ManyToOne(optional = false) @JoinColumn(name = "codigo", referencedColumnName = "codigo", insertable = false, updatable = false) private Usuario usuario; @ManyToOne(optional = false) @JoinColumn(name = "codPR", referencedColumnName = "codPR", insertable = false, updatable = false) private Pregunta pregunta; public Pregunta getPregunta() { return pregunta; } public void setPregunta(Pregunta pregunta) { this.pregunta = pregunta; } public Usuario getUsuario() { return usuario; } public void setUsuario(Usuario usuario) { this.usuario = usuario; } public String getStrcodExBD() { return strcodExBD; } public void setStrcodExBD(String strcodExBD) { this.strcodExBD = strcodExBD; } public String getStrcodigo() { return strcodigo; } public void setStrcodigo(String strcodigo) { this.strcodigo = strcodigo; } public String getStrcodPR() { return strcodPR; } public void setStrcodPR(String strcodPR) { this.strcodPR = strcodPR; } public String getStrrespuest_1() { return strrespuest_1; } public void setStrrespuest_1(String strrespuest_1) { this.strrespuest_1 = strrespuest_1; } public String getStrrespuest_2() { return strrespuest_2; } public void setStrrespuest_2(String strrespuest_2) { this.strrespuest_2 = strrespuest_2; } public String getStrrespuest_3() { return strrespuest_3; } public void setStrrespuest_3(String strrespuest_3) { this.strrespuest_3 = strrespuest_3; } public String getStrrespuest_4() { return strrespuest_4; } public void setStrrespuest_4(String strrespuest_4) { this.strrespuest_4 = strrespuest_4; } public String getStrrespuest_5() { return strrespuest_5; } public void setStrrespuest_5(String strrespuest_5) { this.strrespuest_5 = strrespuest_5; } }
true
43555c771a4f94da81e2212ab52def0621f3edb9
Java
s335shar/Garg
/src/Basics3.java
UTF-8
1,687
2.03125
2
[]
no_license
import static io.restassured.RestAssured.given; import static org.hamcrest.Matchers.equalTo; import java.io.FileInputStream; import java.io.FileNotFoundException; import java.io.IOException; import java.util.Properties; import Files.resources; import Files.PayLoad; import org.testng.annotations.BeforeTest; import org.testng.annotations.Test; import io.restassured.RestAssured; import io.restassured.http.ContentType; import io.restassured.path.json.JsonPath; import io.restassured.response.Response; public class Basics3 { Properties prop = new Properties(); @BeforeTest public void getData() throws IOException { FileInputStream fis = new FileInputStream("C:\\Users\\s335shar\\eclipse-workspace\\DemoRestAPI\\src\\Files\\env.properties"); prop.load(fis); } @Test public void DeleteData() { // TODO Auto-generated method stub RestAssured.baseURI=prop.getProperty("HOST"); Response res = given(). queryParam("key",prop.getProperty("key")). body(PayLoad.geBodyData()). when(). post(resources.getPostData()). then().assertThat().statusCode(200).and().contentType(ContentType.JSON).and().body("status", equalTo("OK")).extract().response(); String responseString = res.asString(); System.out.println(responseString); JsonPath js = new JsonPath(responseString); String PlaceID = js.get("place_id"); System.out.println(PlaceID); given().queryParam("key","qaclick123").body("{" + "\"place_id\":\""+PlaceID+"\""+ "}" ).when().post("/maps/api/place/delete/json").then().assertThat().statusCode(200).and().contentType(ContentType.JSON).and().body("status", equalTo("OK")); } }
true
9dd334d7b3591a9c4781e6e4330b6554f42e0e07
Java
WidedBa/4P55WH8
/src/DAO/Connexion.java
UTF-8
599
2.125
2
[]
no_license
package DAO; import javax.persistence.EntityManager; import javax.persistence.EntityManagerFactory; import javax.persistence.Persistence; public class Connexion { public Connexion() { } private EntityManager entityManager; protected EntityManager getEntityManager() { if(entityManager==null) { EntityManagerFactory emf= Persistence.createEntityManagerFactory("AppSMS"); entityManager=emf.createEntityManager(); } return entityManager; } protected void setEntityManager(EntityManager entityManager) { this.entityManager = entityManager; } }
true
7b15dfa5effedb2ceaacb5801d4f33c9c40bac21
Java
pure-study/java-not-web
/javatest-gradle/src/main/java/net/will/javatest/basicconcept/jdk8/ConvertFuncImplViaMethodRef.java
UTF-8
243
2.484375
2
[]
no_license
package net.will.javatest.basicconcept.jdk8; public class ConvertFuncImplViaMethodRef { public Integer convertWithIntegerValueOf(String s) { IConvertFunc<String, Integer> t = Integer::valueOf; return t.convert(s); } }
true
b68f015b7f76285a835b2a4d63a1445dab0142c9
Java
mingyang66/spring-parent
/demo-emily-spring-boot/src/main/java/com/emily/infrastructure/test/test/SensitiveTest.java
UTF-8
701
2
2
[]
no_license
package com.emily.infrastructure.test.test; import com.emily.infrastructure.json.JsonUtils; import com.emily.infrastructure.sensitive.SensitiveUtils; import com.emily.infrastructure.test.po.json.JsonRequest; /** * 脱敏工具类 * @author Emily * @since Created in 2023/4/17 5:07 PM */ public class SensitiveTest { public static void main(String[] args) { JsonRequest request = new JsonRequest(); request.setUsername("田雨橙"); request.setPassword("123456"); request.setFieldKey("email"); request.setFieldValue("1383612596@qq.com"); System.out.println(JsonUtils.toJSONPrettyString(SensitiveUtils.acquireElseGet(request))); } }
true
e953ff1f591c9e6b37d600cfc8d6170207fb3b2e
Java
vinu5683/BackendSpringBoot
/src/main/java/com/backendforthehindu/the_hindu_backend/TheHinduBackendApplication.java
UTF-8
351
1.640625
2
[]
no_license
package com.backendforthehindu.the_hindu_backend; import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.SpringBootApplication; @SpringBootApplication public class TheHinduBackendApplication { public static void main(String[] args) { SpringApplication.run(TheHinduBackendApplication.class, args); } }
true
e6668e20ea4e2e1420bbc40a489e78d554618130
Java
seniscz/metadata-management
/hive/src/test/java/HiveHook.java
UTF-8
2,067
2.28125
2
[]
no_license
import org.apache.hadoop.hive.conf.HiveConf; import org.apache.hadoop.hive.metastore.HiveMetaStoreClient; import org.apache.hadoop.hive.metastore.api.FieldSchema; import org.apache.hadoop.hive.metastore.api.MetaException; import org.apache.hadoop.hive.metastore.api.NoSuchObjectException; import org.apache.hadoop.hive.metastore.api.Table; import org.apache.thrift.TException; import java.util.List; /** * @ClassName HiveHook * @Description TODO * @Author chezhao * @Date 2020/9/21 11:38 * @Version 1.0 **/ public class HiveHook { public static void main(String[] args) { HiveConf hiveConf = new HiveConf(); //hiveConf.addResource("hive-site.xml"); hiveConf.set("hive.metastore.uris", "thrift://dev-kafka03:9083,thrift://dev-kudu02:9083,thrift://dev-master:9083"); try { System.out.println("===hiveConf ======>" + hiveConf.getAllProperties()); HiveMetaStoreClient hiveMetaStoreClient = new HiveMetaStoreClient(hiveConf); hiveMetaStoreClient.setMetaConf("hive.metastore.client.capability.check","false"); List<String> tablesList = hiveMetaStoreClient.getAllTables("default"); System.out.print("default 库下面所有的表: "); for (String str : tablesList) { System.out.print(str + "\t"); } System.out.println(); //获取表信息 System.out.println("default.user_info 表信息: "); Table table = hiveMetaStoreClient.getTable("default", "user_info"); List<FieldSchema> fieldSchemaList = table.getSd().getCols(); for (FieldSchema schema : fieldSchemaList) { System.out.println("字段: " + schema.getName() + ", 类型: " + schema.getType()); } hiveMetaStoreClient.close(); } catch (MetaException e) { e.printStackTrace(); } catch (NoSuchObjectException e) { e.printStackTrace(); } catch (TException e) { e.printStackTrace(); } } }
true
2a4b9a2cf95539a2e7575c6bd4a24a0554cd0420
Java
Alexander175/The-Betweenlands
/java/thebetweenlands/world/teleporter/TeleporterBetweenlands.java
UTF-8
559
2.25
2
[]
no_license
package thebetweenlands.world.teleporter; import net.minecraft.entity.Entity; import net.minecraft.world.Teleporter; import net.minecraft.world.WorldServer; public class TeleporterBetweenlands extends Teleporter { //TODO: No special functionality yet, just for testing purposes public TeleporterBetweenlands(WorldServer worldServer) { super(worldServer); } //Just putting this here to stop nether portals appearing in the overworld @Override public void placeInPortal(Entity pEntity, double posX, double posY, double posZ, float rotationYaw) { } }
true
7d8c8ab9f96ab27fdddfdea78aa2b1e90dd6f67e
Java
gevoulga/spring-boot-quickfixj
/quickfixj-spring-boot-starter-flux/src/test/java/ch/voulgarakis/spring/boot/starter/quickfixj/flux/ReactiveFixSessionTest.java
UTF-8
5,644
1.929688
2
[ "Apache-2.0" ]
permissive
/* * Copyright (c) 2020 Georgios Voulgarakis * * 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 ch.voulgarakis.spring.boot.starter.quickfixj.flux; import ch.voulgarakis.spring.boot.starter.quickfixj.session.FixSessionManager; import org.junit.jupiter.api.Test; import org.junit.jupiter.api.extension.ExtendWith; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Qualifier; import org.springframework.boot.test.context.SpringBootTest; import org.springframework.test.annotation.DirtiesContext; import org.springframework.test.context.TestPropertySource; import org.springframework.test.context.junit.jupiter.SpringExtension; import quickfix.Message; import quickfix.SessionID; import quickfix.field.QuoteID; import quickfix.field.QuoteReqID; import quickfix.fix43.Quote; import quickfix.fix43.QuoteRequest; import reactor.core.publisher.Flux; import reactor.core.publisher.Mono; import reactor.core.scheduler.Schedulers; import reactor.test.StepVerifier; import java.time.Duration; import java.util.List; import java.util.Random; import java.util.concurrent.atomic.AtomicInteger; import java.util.stream.Collectors; @ExtendWith(SpringExtension.class) @SpringBootTest(classes = ReactiveFixSessionTestContext.class) @TestPropertySource("classpath:fixSessionTest.properties") @DirtiesContext //Stop port already bound issues from other tests public class ReactiveFixSessionTest { private static final Logger LOG = LoggerFactory.getLogger(ReactiveFixSessionTest.class); private static final SessionID SESSION_ID = new SessionID("FIX.4.3", "TEST_CLIENT2", "FIX"); @Autowired private FixSessionManager sessionManager; @Autowired @Qualifier("TEST2") private ReactiveFixSessionImpl fixSession; @Test public void testBurstSubscription() { QuoteRequest quoteRequest = new QuoteRequest(new QuoteReqID(Long.toString(0L))); Flux<Message> messageFlux = fixSession.sendAndSubscribe(() -> quoteRequest) .doOnSubscribe(subscription -> burstOf20QuotesWithDifferentIdEvery100millis()); StepVerifier .create(messageFlux) .expectSubscription() .expectNoEvent(Duration.ofMillis(100)) .expectNextCount(20) .thenAwait(Duration.ofMillis(200)) .expectNextCount(20) .thenCancel() .verify(Duration.ofSeconds(2)); } private void burstOf20QuotesWithDifferentIdEvery100millis() { Flux.interval(Duration.ofMillis(100)) .take(2) .repeat(1) .flatMap(i -> { LOG.debug("tick: {}", i); Quote quote = new Quote(new QuoteID(Long.toString(i))); quote.set(new QuoteReqID(Long.toString(i))); return Flux.just(quote) .repeat(19) .map(Message::clone); }) .parallel() .runOn(Schedulers.elastic()) .subscribe(quote -> { LOG.debug("Sending to Session Manager: {}", quote); sessionManager.fromApp((Message) quote, SESSION_ID); }); LOG.info("Sending burst of quotes"); } @Test public void testRandomSubscription() { List<Long> longs = new Random() .longs(1000, 0, 5).boxed() .collect(Collectors.toList()); long count = longs.stream().filter(i -> i == 0).count(); LOG.info("Random quotes: {}", count); AtomicInteger counter = new AtomicInteger(); QuoteRequest quoteRequest = new QuoteRequest(new QuoteReqID(Long.toString(0L))); Flux<Message> messageFlux = fixSession.sendAndSubscribe(() -> quoteRequest) .doOnSubscribe(subscription -> randomQuotes(longs)) .doOnNext(message -> LOG.info("Progress: {}/{}", counter.incrementAndGet(), count)); StepVerifier .create(messageFlux) .expectSubscription() .expectNextCount(count) .thenCancel() .verify(Duration.ofSeconds(10)); } private void randomQuotes(List<Long> longs) { Mono.delay(Duration.ofMillis(100)) .thenMany(Flux .fromIterable(longs) .map(i -> { LOG.debug("tick: {}", i); Quote quote = new Quote(new QuoteID(Long.toString(i))); quote.set(new QuoteReqID(Long.toString(i))); return quote; }) .parallel() .runOn(Schedulers.elastic()) ) .subscribe(quote -> { LOG.debug("Sending to Session Manager: {}", quote); sessionManager.fromApp(quote, SESSION_ID); }); LOG.info("Sending random quotes"); } }
true
70ea10522db320831e695dfc57eb2b6077f4e4bb
Java
javierpep/TestCLean
/data/src/main/java/co/jperezp/data/Interfaces/onShakeAction.java
UTF-8
103
1.914063
2
[]
no_license
package co.jperezp.data.Interfaces; public interface onShakeAction { public void shakeAction(); }
true
a90c2dd490aaed4e25891f20e31b83714866117f
Java
zhiqinghuang/zest-java
/core/runtime/src/main/java/org/qi4j/runtime/injection/provider/ThisInjectionProviderFactory.java
UTF-8
5,189
1.765625
2
[ "Apache-2.0", "BSD-3-Clause", "MIT", "W3C" ]
permissive
/* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ package org.qi4j.runtime.injection.provider; import java.lang.reflect.Constructor; import java.lang.reflect.InvocationHandler; import java.lang.reflect.Proxy; import org.qi4j.api.composite.CompositeDescriptor; import org.qi4j.api.util.Classes; import org.qi4j.bootstrap.InvalidInjectionException; import org.qi4j.functional.Iterables; import org.qi4j.runtime.composite.ProxyGenerator; import org.qi4j.runtime.injection.DependencyModel; import org.qi4j.runtime.injection.InjectionContext; import org.qi4j.runtime.injection.InjectionProvider; import org.qi4j.runtime.injection.InjectionProviderFactory; import org.qi4j.runtime.model.Resolution; import static org.qi4j.functional.Iterables.first; import static org.qi4j.functional.Iterables.iterable; /** * JAVADOC */ public final class ThisInjectionProviderFactory implements InjectionProviderFactory { @Override @SuppressWarnings( "unchecked" ) public InjectionProvider newInjectionProvider( Resolution bindingContext, DependencyModel dependencyModel ) throws InvalidInjectionException { if( bindingContext.model() instanceof CompositeDescriptor ) { // If Composite type then return real type, otherwise use the specified one final Class<?> thisType = dependencyModel.rawInjectionType(); Iterable<Class<?>> injectionTypes = null; if( Classes.assignableTypeSpecification( thisType ).satisfiedBy( bindingContext.model() ) ) { injectionTypes = bindingContext.model().types(); } else { CompositeDescriptor acd = ( (CompositeDescriptor) bindingContext.model() ); for( Class<?> mixinType : acd.mixinTypes() ) { if( thisType.isAssignableFrom( mixinType ) ) { Iterable<? extends Class<?>> iterable = iterable( thisType ); injectionTypes = (Iterable<Class<?>>) iterable; break; } } if( injectionTypes == null ) { throw new InvalidInjectionException( "Composite " + bindingContext.model() + " does not implement @This type " + thisType.getName() + " in fragment " + dependencyModel.injectedClass().getName() ); } } return new ThisInjectionProvider( injectionTypes ); } else { throw new InvalidInjectionException( "Object " + dependencyModel.injectedClass() + " may not use @This" ); } } @SuppressWarnings( {"raw", "unchecked"} ) private static class ThisInjectionProvider implements InjectionProvider { Constructor proxyConstructor; private Class[] interfaces; private ThisInjectionProvider( Iterable<Class<?>> types ) { try { Class proxyClass; if( Proxy.class.isAssignableFrom( first( types ) ) ) { proxyClass = first( types ); } else { Class<?> mainType = first( types ); interfaces = Iterables.toArray( Class.class, Iterables.<Class>cast( types ) ); proxyClass = ProxyGenerator.createProxyClass(mainType.getClassLoader(), interfaces); } proxyConstructor = proxyClass.getConstructor( InvocationHandler.class ); } catch( Exception e ) { // Ignore e.printStackTrace(); } } @Override public Object provideInjection( InjectionContext context ) { try { InvocationHandler handler = context.compositeInstance(); if( handler == null ) { handler = context.proxyHandler(); } return proxyConstructor.newInstance( handler ); } catch( Exception e ) { throw new InjectionProviderException( "Could not instantiate @This proxy", e ); } } } }
true
e42b97ce11767656f4bbf88459349b67d45d091e
Java
Auch-Auch/avito_source
/sources/com/google/android/gms/internal/mlkit_vision_face/zzbb.java
UTF-8
1,332
2.21875
2
[]
no_license
package com.google.android.gms.internal.mlkit_vision_face; import java.util.Iterator; import java.util.Map; public class zzbb<K, V> extends zzbg<K> { public final Map<K, V> zzb; public zzbb(Map<K, V> map) { this.zzb = (Map) zzj.zza(map); } @Override // java.util.AbstractCollection, java.util.Collection, java.util.Set public void clear() { this.zzb.clear(); } @Override // java.util.AbstractCollection, java.util.Collection, java.util.Set public boolean contains(Object obj) { return this.zzb.containsKey(obj); } @Override // java.util.AbstractCollection, java.util.Collection, java.util.Set public boolean isEmpty() { return this.zzb.isEmpty(); } @Override // java.util.AbstractCollection, java.util.Collection, java.util.Set, java.lang.Iterable public Iterator<K> iterator() { return new zzaw(this.zzb.entrySet().iterator()); } @Override // java.util.AbstractCollection, java.util.Collection, java.util.Set public boolean remove(Object obj) { if (!contains(obj)) { return false; } this.zzb.remove(obj); return true; } @Override // java.util.AbstractCollection, java.util.Collection, java.util.Set public int size() { return this.zzb.size(); } }
true
a0476009ea0dc84ef46a77be4887b308a0707172
Java
salvanos/isyfact-benutzerverwaltung
/isy-benutzerverwaltung-core/src/main/java/de/bund/bva/isyfact/benutzerverwaltung/persistence/basisdaten/dao/RollenDao.java
UTF-8
2,613
2.203125
2
[ "Apache-2.0" ]
permissive
package de.bund.bva.isyfact.benutzerverwaltung.persistence.basisdaten.dao; /*- * #%L * IsyFact Benutzerverwaltung Core * %% * Copyright (C) 2016 - 2017 Bundesverwaltungsamt (BVA) * %% * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * #L% */ import de.bund.bva.isyfact.benutzerverwaltung.common.datentyp.Paginierung; import de.bund.bva.isyfact.benutzerverwaltung.common.datentyp.Sortierung; import de.bund.bva.isyfact.benutzerverwaltung.core.rollenverwaltung.RolleSuchkriterien; import de.bund.bva.isyfact.benutzerverwaltung.persistence.basisdaten.entity.Rolle; import de.bund.bva.pliscommon.persistence.dao.Dao; import java.util.Collection; import java.util.List; /** * Beschreibt den Datenbankzugriff für Rollen. * * @author Stefan Dellmuth, msg systems ag */ public interface RollenDao extends Dao<Rolle, Long> { /** * Sucht eine Rolle anhand ihrer ID. * * @param rollenId ID der Rolle * @return die Rolle, falls eine gefunden wurde, oder {@code null}. */ Rolle sucheMitRollenId(String rollenId); /** * Sucht eine Menge von Rollen anhand ihrer IDs. * * @param rollenIds IDs der Rollen * @return eine Liste aller Rollen, die zu den IDs gefunden wurden. */ List<Rolle> sucheMitRollenIds(Collection<String> rollenIds); /** * Diese Methode filtert und sortiert eine Treffermenge an Rollen und gibt diese zurueck. * * @param suchkriterien Suchkriterien, nach denen gefiltert wird * @param sortierung Sortierung der Ergebnisliste (Attribut und Richtung) * @param paginierung Informationen zur Paginierung * @return anhand der Kriterien gefilterte, sortierte und gemäß der Paginierung geschnittene * Ergebnisliste. */ List<Rolle> sucheMitFilter(RolleSuchkriterien suchkriterien, Sortierung sortierung, Paginierung paginierung); /** * Zählt die Benutzer, welche den Suchkriterien entsprechen. * * @param suchkriterien Suchkriterien * @return die Anzahl solcher Benutzer. */ long zaehleMitKriterien(RolleSuchkriterien suchkriterien); }
true
f9ec4d4af68f6a98dd02b7879aed95453f51541e
Java
shubhamsaxenacg/TrainingAssignments_DayWise
/Day 1/Assignment1/Student.java
UTF-8
2,389
3.890625
4
[]
no_license
import java.util.*; //contains constructor which takes the input of marks for three students class Marks{ int marksSubject1; int marksSubject2; int marksSubject3; int totalMarks; int averageMarks; Scanner sc = new Scanner(System.in); Marks() { System.out.print("Enter the marks for subject1"); marksSubject1= sc.nextInt(); System.out.print("Enter the marks for subject2"); marksSubject2= sc.nextInt(); System.out.print("Enter the marks for subject3"); marksSubject3= sc.nextInt(); //........Calculates the total marks and average marks for individual students... totalMarks= marksSubject1+marksSubject2+marksSubject3; averageMarks= totalMarks/3; } } public class Student{ public static void main(String args[]) { int subject1Total,subject2Total,subject3Total; int subject1Average,subject2Average,subject3Average; Marks student1 = new Marks(); Marks student2 = new Marks(); Marks student3 = new Marks(); System.out.print("\n Total Marks of Student1 is "+student1.totalMarks); System.out.print("\n Average Marks of Student1 is "+student1.averageMarks); System.out.print("Total Marks of Student1 is "+student2.totalMarks); System.out.print("Average Marks of Student1 is "+student2.averageMarks); System.out.print("Total Marks of Student1 is "+student3.totalMarks); System.out.print("Average Marks of Student1 is "+student3.averageMarks); //...........Calculating the total marks for individual subjects subject1Total= student1.marksSubject1+ student2.marksSubject1+ student3.marksSubject1; subject2Total= student1.marksSubject2+ student2.marksSubject2+ student3.marksSubject2; subject3Total= student1.marksSubject3+ student2.marksSubject3+ student3.marksSubject3; //...........Average of individual students........ subject1Average = subject1Total/3; subject2Average = subject2Total/3; subject3Average = subject3Total/3; //........Printing the results......... System.out.print("Total of Subject1 is "+subject1Total); System.out.print("Total of Subject2 is "+subject2Total); System.out.print("Total of Subject3 is "+subject3Total); System.out.print("Average of Subject1 is "+subject1Average); System.out.print("Average of Subject2 is "+subject2Average); System.out.print("Average of Subject3 is "+subject3Average); } }
true
efd9b9108a99900d5408cadb7f5bdac2219a3c5c
Java
daminimehra28/DoctorsDoor
/app/src/main/java/com/app/doctorsdoor/web/exception/PDException.java
UTF-8
217
2.046875
2
[]
no_license
package com.app.doctorsdoor.web.exception; /** * Created by Pulah on 06-09-2018 3:22 PM. */ public class PDException extends Exception { public PDException(String exception) { super(exception); } }
true
c4cbe1e0fc91c4f9f7c35b58a1e85e146738ae9c
Java
cash2one/hospitalAdmin
/jumper-hospital-admin/src/main/java/com/jumper/hospital/vo/VONewsChanelAdd.java
UTF-8
803
2.125
2
[]
no_license
package com.jumper.hospital.vo; public class VONewsChanelAdd { /** 结果 **/ private String result; /** 默认订阅条数 **/ private long defaultNum; /** 状态为显示的条数 **/ private long showNum; public VONewsChanelAdd() { super(); } public VONewsChanelAdd(String result, long defaultNum, long showNum) { super(); this.result = result; this.defaultNum = defaultNum; this.showNum = showNum; } public String getResult() { return result; } public void setResult(String result) { this.result = result; } public long getDefaultNum() { return defaultNum; } public void setDefaultNum(long defaultNum) { this.defaultNum = defaultNum; } public long getShowNum() { return showNum; } public void setShowNum(long showNum) { this.showNum = showNum; } }
true
88900a5ca88f0a64ed6f4be45704c146e39ed768
Java
apmasell/gisql-gui
/src/com/sun/forums/filteringtable/TableModelFilter.java
UTF-8
326
1.835938
2
[]
no_license
package com.sun.forums.filteringtable; import javax.swing.table.TableModel; public interface TableModelFilter { void addFilteree(FilteringTableModel filteringTableModel); void removeFiltreee(FilteringTableModel filteringTableModel); boolean shouldDisplay(FilteringTableModel source, TableModel base_tm, int row); }
true
df5b13a8dd86069d902ddaababf1527412a38ac4
Java
DarkerMinecraft/3DGameEngine
/src/com/darkerminecraft/Game.java
UTF-8
1,990
2.546875
3
[]
no_license
package com.darkerminecraft; import org.joml.Vector3f; import com.darkerminecraft.entity.Entity; import com.darkerminecraft.graphics.Camera; import com.darkerminecraft.graphics.DisplayManager; import com.darkerminecraft.graphics.Light; import com.darkerminecraft.graphics.Loader; import com.darkerminecraft.graphics.MasterRenderer; import com.darkerminecraft.graphics.model.RawModel; import com.darkerminecraft.graphics.model.TexturedModel; import com.darkerminecraft.graphics.textures.ModelTexture; import com.darkerminecraft.shaders.entities.EntityShader; import com.darkerminecraft.threads.OBJThread; import com.darkerminecraft.threads.TextureThread; public class Game { public static final Object SYNCOBJECT = new Object(); public static void main(String[] args) throws Exception { synchronized (SYNCOBJECT) { OBJThread objThread = new OBJThread(); objThread.start(); SYNCOBJECT.wait(); TextureThread textureThread = new TextureThread(); textureThread.start(); SYNCOBJECT.wait(); DisplayManager.createDisplay(); textureThread.loadBinding(); MasterRenderer renderer = new MasterRenderer(); RawModel model = Loader.loadToVAO("dragon"); ModelTexture modelTexture = TextureThread.getDefualtTexture("purple"); modelTexture.setShineDamper(10); modelTexture.setReflectivity(1); TexturedModel texturedModel = new TexturedModel(model, modelTexture); Entity entity = new Entity(texturedModel, new Vector3f(0, 0, -25), 0, 0, 0, 1); EntityShader shader = new EntityShader(); Camera camera = new Camera(); Light light = new Light(new Vector3f(0, 0, -20), new Vector3f(1, 1, 1)); while (DisplayManager.isDisplayRunning()) { entity.increaseRotation(.2f, .2f, .2f); camera.move(); renderer.prepare(); shader.start(); shader.loadLight(light); renderer.render(entity); shader.stop(); DisplayManager.updateDisplay(); } DisplayManager.destoryDisplay(); } } }
true
128281517a1ba587f80f01a5b18d7a0af74c60dc
Java
BeLikeYangY/In-Class-Assignment-11
/app/src/main/java/com/example/android/inclassassignment11_yangy/ItemActivity.java
UTF-8
991
2.28125
2
[]
no_license
package com.example.android.inclassassignment11_yangy; import android.content.Intent; import android.support.v7.app.AppCompatActivity; import android.os.Bundle; import android.widget.ImageView; import android.widget.TextView; public class ItemActivity extends AppCompatActivity { private ImageView itemPhoto; private TextView itemTitle; private TextView itemDesc; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_item); itemPhoto= (ImageView) findViewById(R.id.item_info_photo); itemTitle= (TextView) findViewById(R.id.item_info_title); itemDesc= (TextView) findViewById(R.id.item_info_desc); Intent intent=getIntent(); Item item= (Item) intent.getSerializableExtra("Item"); itemPhoto.setImageResource(item.getPhotoId()); itemTitle.setText(item.getTitle()); itemDesc.setText(item.getDesc()); } }
true
d97be67cc02524aa7db81080179565aa20a29f2e
Java
JonathanBergers/TwitterApp
/app/src/main/java/saxion/nl/twitterapp/activities/BaseActivity.java
UTF-8
12,071
1.84375
2
[]
no_license
package saxion.nl.twitterapp.activities; import android.graphics.drawable.BitmapDrawable; import android.graphics.drawable.Drawable; import android.os.Bundle; import android.support.v4.app.Fragment; import android.support.v4.app.FragmentActivity; import android.support.v7.widget.Toolbar; import android.util.Log; import android.view.MenuItem; import android.view.View; import android.widget.AdapterView; import android.widget.FrameLayout; import com.melnykov.fab.FloatingActionButton; import com.mikepenz.materialdrawer.Drawer; import com.mikepenz.materialdrawer.DrawerBuilder; import com.mikepenz.materialdrawer.accountswitcher.AccountHeader; import com.mikepenz.materialdrawer.accountswitcher.AccountHeaderBuilder; import com.mikepenz.materialdrawer.model.DividerDrawerItem; import com.mikepenz.materialdrawer.model.PrimaryDrawerItem; import com.mikepenz.materialdrawer.model.ProfileDrawerItem; import com.mikepenz.materialdrawer.model.interfaces.IDrawerItem; import com.rengwuxian.materialedittext.MaterialEditText; import java.util.List; import oauth.signpost.OAuth; import saxion.nl.twitterapp.fragments.BaseFragment; import saxion.nl.twitterapp.model.Model; import saxion.nl.twitterapp.model.Status; import saxion.nl.twitterapp.model.User; import saxion.nl.twitterapp.util.Resources; import topicus.nl.twitterapp.R; public class BaseActivity extends FragmentActivity { protected FrameLayout frameLayout; protected Drawer navigationDrawer; protected User currentUser; protected FloatingActionButton plusButton; protected MaterialEditText editTextBar; private boolean search = false; private Model model = Model.getInstance(); protected static final int IDENT_TIMELINE = 69; protected static final int IDENT_FRIENDS = -69; protected static final int IDENT_USER = 6969; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.base_layout); frameLayout = (FrameLayout) findViewById(R.id.frame); editTextBar = (MaterialEditText) findViewById(R.id.editTextBase); plusButton = (FloatingActionButton) findViewById(R.id.fabItem); plusButton.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { onFABClick(); } }); retrieveCurrentUser(); } private boolean checkFirstTime(){ String oAuthString = getSharedPreferences(Resources.SHARED_PREFERENCES, MODE_PRIVATE).getString(OAuth.OAUTH_TOKEN_SECRET, null); if(oAuthString == null){ return true; } return false; } private void onFABClick(){ if(search){ retrieveSearch(editTextBar.getText().toString()); }else{ postTweet(editTextBar.getText().toString()); } } /**Retrieves all the data and builds the nav drawer * */ protected void buildNavigationDrawer(){ Drawable acc_icon = new BitmapDrawable(currentUser.getBitmap()); ProfileDrawerItem profile = new ProfileDrawerItem().withName(currentUser.getName()).withIcon(acc_icon); Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar); toolbar.setTitle("TwitterClient"); toolbar.inflateMenu(R.menu.main); toolbar.setOnMenuItemClickListener(new Toolbar.OnMenuItemClickListener() { @Override public boolean onMenuItemClick(MenuItem item) { if (item.getItemId() == R.id.action_logout) { BaseActivity.this.finish(); } if(item.getItemId() == R.id.action_post_tweet) { search = false; editTextBar.setHint("Tweet posten"); editTextBar.setFloatingLabelText("Tweet posten"); editTextBar.setMaxCharacters(140); } if(item.getItemId() == R.id.action_search_tweet){ search = true; editTextBar.setHint("Tweet zoeken"); editTextBar.setFloatingLabelText("Tweet zoeken"); editTextBar.setMaxCharacters(60); } return false; } }); AccountHeader a = new AccountHeaderBuilder() .withActivity(this) .addProfiles(profile) .withHeaderBackground(getDrawable(R.drawable.twitter_header)) .build(); navigationDrawer = new DrawerBuilder() .withAccountHeader(a) .withActivity(this) .withActionBarDrawerToggle(true) .withToolbar(toolbar) .withTranslucentStatusBar(true) //.withHeader(R.layout.navigation_header).withHeaderDivider(true) .withHeaderClickable(true) .build(); drawerBuildBase(); setOnItemClickListener(); retrieveTimeLine(); } protected void postTweet(final String text){ new Thread(new Runnable() { @Override public void run() { model.updateStatus(text); runOnUiThread(new Runnable() { @Override public void run() { if(BaseFragment.instance != null){ ((BaseFragment) BaseFragment.instance).refreshTimeLine(); } } }); } }).start(); } private void drawerBuildBase(){ navigationDrawer.addItem(new PrimaryDrawerItem().withDescription("Timeline").withIdentifier(IDENT_TIMELINE)); navigationDrawer.addItem(new DividerDrawerItem()); navigationDrawer.addItem(new PrimaryDrawerItem().withDescription("Friends").withIdentifier(IDENT_FRIENDS)); } //** INFLATION ** // /** * Inflate a view in the frame layout * * @param layoutResId * @return the created view */ protected View inflateInFrame(int layoutResId) { return getLayoutInflater().inflate(layoutResId, frameLayout); } /** * Inflate a fragment in the frame layout * @param fragment */ protected void inflateInFrame(Fragment fragment){ getSupportFragmentManager() .beginTransaction() .replace(R.id.frame, fragment).commit(); } // --- INFLATION ---// // ** RETRIEVAL ** // protected void retrieveTimeLine(){ new Thread(new Runnable() { List<Status> tweets; @Override public void run() { try { tweets = Model.getInstance().retrieveTimeline(); } catch (Exception e) { e.printStackTrace(); } runOnUiThread(new Runnable() { @Override public void run() { if (BaseFragment.instance != null) { BaseFragment.instance.items = tweets; BaseFragment.instance.updateCards(); }else{ inflateInFrame(BaseFragment.newInstance(tweets, false)); } } }); } }).start(); } protected void retrieveTimeLineUser(final User user){ new Thread(new Runnable() { List<Status> tweets; @Override public void run() { try { tweets = Model.getInstance().retrieveTimeline(user); } catch (Exception e) { e.printStackTrace(); } runOnUiThread(new Runnable() { @Override public void run() { if (BaseFragment.instance != null) { BaseFragment.instance.items = tweets; BaseFragment.instance.updateCards(); }else{ inflateInFrame(BaseFragment.newInstance(tweets, true)); } } }); } }).start(); } protected void retrieveCurrentUser(){ new Thread(new Runnable() { protected User user ; @Override public void run() { try { user = model.retrieveCurrenntUser(); } catch (Exception e) { e.printStackTrace(); } runOnUiThread(new Runnable() { @Override public void run() { currentUser = user; Log.d("BASEAC", currentUser.getName()); buildNavigationDrawer(); } }); } }).start(); } protected void retrieveSearch(final String search){ new Thread(new Runnable() { List<Status> tweets; @Override public void run() { try { tweets = Model.getInstance().searchTweets(search); } catch (Exception e) { e.printStackTrace(); } runOnUiThread(new Runnable() { @Override public void run() { if (BaseFragment.instance != null) { BaseFragment.instance.items = tweets; BaseFragment.instance.updateCards(); }else{ inflateInFrame(BaseFragment.newInstance(tweets, true)); } } }); } }).start(); } protected void retrieveFriends(){ new Thread(new Runnable() { List<User> friends; @Override public void run() { try { friends = Model.getInstance().retrieveFriends(); } catch (Exception e) { e.printStackTrace(); } runOnUiThread(new Runnable() { @Override public void run() { navigationDrawer.removeAllItems(); drawerBuildBase(); for(User u : friends){ navigationDrawer.addItem(new ProfileDrawerItem().withTag(u).withIdentifier(IDENT_USER).withName(u.getName())); } } }); } }).start(); } // --- RETRIEVAL ---// // ** On click listener ** // /**Important, * Determins the methods that need to be called when a user clicks on an item, * Note: calls the on..click method, which needs to be overidden by sub activities * */ protected void setOnItemClickListener(){ navigationDrawer.setOnDrawerItemClickListener(new Drawer.OnDrawerItemClickListener() { @Override public boolean onItemClick(AdapterView<?> adapterView, View view, int i, long l, IDrawerItem iDrawerItem) { Object tag = iDrawerItem.getTag(); Log.d("TYPE", iDrawerItem.getType()); switch (iDrawerItem.getIdentifier()) { case IDENT_TIMELINE : retrieveTimeLine(); break; case IDENT_FRIENDS : retrieveFriends(); break; case IDENT_USER :retrieveTimeLineUser((User)tag); } return true; } }); } // ** ON CLICKS ** // // -- ON CLICKS -- // }
true
76cb3e1f06dc0007c3f6dfe33cf4c55651791c08
Java
y0mchy/Equation
/src/QuadraticEquation.java
UTF-8
1,172
3.75
4
[]
no_license
// サブクラスQuadraticEquationを書く public class QuadraticEquation extends Equation { private double a, b, c; public QuadraticEquation(double a, double b, double c) { this.name = "QuadraticEquation"; this.a = a; this.b = b; this.c = c; } @Override public void print() { System.out.println(name + ": (" + a + ")x^2 + (" + b + ")x + (" + c + ") = 0"); } @Override public void solve() { if (a == 0) { if (b == 0) { System.out.println("任意の実数xについても成り立つ"); } else { double x = -c / b; System.out.println("x = " + x); } } else { double d = b * b - 4 * a * c; if (d > 0) { double x1 = (-b + Math.sqrt(d)) / (2 * a); double x2 = (-b - Math.sqrt(d)) / (2 * a); System.out.println("x1 = " + x1 + ", x2 = " + x2); } else if (d == 0) { double x = -b / (2 * a); System.out.println("x = " + x + "(重解)"); } else { double real = -b / (2 * a); double imaginary = Math.sqrt(-1 * d) / (2 * a); System.out.println("x1 = " + real + " + " + imaginary + "i"); System.out.println("x2 = " + real + " - " + imaginary + "i"); } } System.out.println(); } }
true
f94823de8b5baac4e13ac294beecf84b30fcda63
Java
marivgil/VSApp-Backend
/src/main/java/model/Round.java
UTF-8
591
2.28125
2
[]
no_license
package model; import javax.persistence.Id; public class Round{ @Id private String code; private String name; private String coordinator; public String getCode() { return code; } public void setCode(String code) { this.code = code; } public String getName() { return name; } public void setName(String name) { this.name = name; } public String getCoordinator() { return coordinator; } public void setCoordinator(String coordinator) { this.coordinator = coordinator; } }
true
6611f871ee7490a8efd048be32beaeb874299463
Java
pom30526/algo
/day0306/maxandmin.java
UTF-8
224
2.5625
3
[]
no_license
package day0306; import java.util.Scanner; public class maxandmin { public static void main(String[] args) { Scanner sc = new Scanner(System.in); int x, y; x=sc.nextInt(); y=sc.nextInt(); System.out.println(x); } }
true
a48c094d6a5713b0cf7fb07d820f34f852c56f81
Java
QingGuang233/TimerExecutor
/src/com/qing_guang/TimerExecutor/plugin/cond/FakemanCondition.java
UTF-8
468
2.015625
2
[]
no_license
package com.qing_guang.TimerExecutor.plugin.cond; import com.qing_guang.TimerExecutor.plugin.main.Main; import org.bukkit.command.CommandSender; import org.bukkit.plugin.java.JavaPlugin; import java.util.ArrayList; import java.util.Collections; import java.util.List; public class FakemanCondition implements Condition{ @Override public List<CommandSender> getMatches() { return Collections.singletonList(JavaPlugin.getPlugin(Main.class).getFakeman()); } }
true
a22c6f51a1a4729b9026adb5d630de0eae3d79b1
Java
Saukalt41/DuchessOfDamascus
/src/BYUI/cit260/DuchessOfDamascus/control/YahtzeeControl.java
UTF-8
5,038
2.484375
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 BYUI.cit260.DuchessOfDamascus.control; import java.util.Objects; import java.util.Random; /** * * @author Blanco */ public class YahtzeeControl { public YahtzeeControl() { } private static int rollOne; private static int rollTwo; private int playerResult; private int ghostResult; int playerScore; int npcScore; int playerWinCount; int npcWinCount; Random number = new Random(); @Override public String toString() { return "YahtzeeControl{" + "playerResult=" + playerResult + ", ghostResult=" + ghostResult + ", playerScore=" + playerScore + ", npcScore=" + npcScore + ", playerWinCount=" + playerWinCount + ", npcWinCount=" + npcWinCount + ", number=" + number + '}'; } public static int getRollOne() { return rollOne; } public static void setRollOne(int rollOne) { YahtzeeControl.rollOne = rollOne; } public static int getRollTwo() { return rollTwo; } public static void setRollTwo(int rollTwo) { YahtzeeControl.rollTwo = rollTwo; } public int getPlayerResult() { return playerResult; } public void setPlayerResult(int playerResult) { this.playerResult = playerResult; } public int getGhostResult() { return ghostResult; } public void setGhostResult(int ghostResult) { this.ghostResult = ghostResult; } public int getPlayerScore() { return playerScore; } public void setPlayerScore(int playerScore) { this.playerScore = playerScore; } public int getNpcScore() { return npcScore; } public void setNpcScore(int npcScore) { this.npcScore = npcScore; } public int getPlayerWinCount() { return playerWinCount; } public void setPlayerWinCount(int playerWinCount) { this.playerWinCount = playerWinCount; } public int getNpcWinCount() { return npcWinCount; } public void setNpcWinCount(int npcWinCount) { this.npcWinCount = npcWinCount; } public Random getNumber() { return number; } public void setNumber(Random number) { this.number = number; } @Override public int hashCode() { int hash = 5; hash = 97 * hash + this.playerResult; hash = 97 * hash + this.ghostResult; hash = 97 * hash + this.playerScore; hash = 97 * hash + this.npcScore; hash = 97 * hash + this.playerWinCount; hash = 97 * hash + this.npcWinCount; hash = 97 * hash + Objects.hashCode(this.number); return hash; } @Override public boolean equals(Object obj) { if (obj == null) { return false; } if (getClass() != obj.getClass()) { return false; } final YahtzeeControl other = (YahtzeeControl) obj; if (this.playerResult != other.playerResult) { return false; } if (this.ghostResult != other.ghostResult) { return false; } if (this.playerScore != other.playerScore) { return false; } if (this.npcScore != other.npcScore) { return false; } if (this.playerWinCount != other.playerWinCount) { return false; } if (this.npcWinCount != other.npcWinCount) { return false; } return true; } public int rolls() { return number.nextInt(30) + 6; } public int playerResult() { playerResult = rolls(); return playerResult; } public int ghostResult() { ghostResult = rolls(); return ghostResult; } public String trackPoints() { String message; playerScore = playerResult; npcScore = ghostResult; if (playerScore > npcScore) { npcWinCount++; } else if (playerScore < npcScore) { playerWinCount++; } while (npcWinCount <= 2 || playerWinCount <= 2) { playerResult(); ghostResult(); } if (playerWinCount == 3) { message = "You Win!"; } else if (npcWinCount == 3) { message = "you lose"; }else{ message = "try again"; } return message; } double trackPoints(double playerScore, double npcScore, double playerNewWinCount, double npcNewWinCount) { throw new UnsupportedOperationException("Not supported yet."); //To change body of generated methods, choose Tools | Templates. } }
true
317060037b75357c3ebca601655ef6e7c5d16a77
Java
liuhao128/questionnaire
/src/main/java/com/tinyspot/question/mapper/AnswerMapper.java
UTF-8
610
2.078125
2
[]
no_license
package com.tinyspot.question.mapper; import com.tinyspot.question.entity.Answers; import org.apache.ibatis.annotations.Mapper; import org.apache.ibatis.annotations.Param; import org.apache.ibatis.annotations.Select; import java.util.List; /** * @Author tinyspot * @Time 2019/12/5-19:49 */ @Mapper public interface AnswerMapper { /* 根据记录id和问卷id查询答案们 */ @Select("select * from answers where record_id=#{recordId} and paper_id=#{paperId}") List<Answers> getAnswersByRecordIdAndPaperId(@Param("recordId") Integer recordId, @Param("paperId") Integer paperId); }
true
54244c72868c68f8b1083cf82937a57e6c29592e
Java
YousefKhrais/Software_Security_Blockchain_Implementation
/src/Blockchain.java
UTF-8
3,046
3.09375
3
[]
no_license
import java.util.ArrayList; public class Blockchain { public ArrayList<Block> chain; public ArrayList<Transaction> pendingTransactions; public int difficulty; public int miningReward; public Blockchain() { this.pendingTransactions = new ArrayList<>(); this.chain = new ArrayList<>(); this.chain.add(createGenesisBlock()); this.miningReward = 500; this.difficulty = 2; } public Block createGenesisBlock() { return new Block(new ArrayList<>(), "0"); } public Block getLatestBlock() { return chain.get(chain.size() - 1); } public void minePendingTransactions(String miningRewardAddress) { Block block = new Block(this.pendingTransactions, this.getLatestBlock().hash); block.mineBlock(this.difficulty); this.chain.add(block); this.pendingTransactions.clear(); this.pendingTransactions.add(new Transaction(this.getLatestBlock().hash, miningRewardAddress, this.miningReward)); } public void addTransaction(Transaction transaction) throws Exception { if (transaction.fromAddress == null || transaction.toAddress == null) { throw new RuntimeException("Transaction must include from and to address"); } if (!transaction.isValid()) { throw new RuntimeException("Cannot add invalid transaction to chain"); } if (transaction.amount <= 0) { throw new RuntimeException("Transaction amount should be higher than 0"); } // if (this.getBalanceOfAddress(transaction.fromAddress) < transaction.amount) { // throw new RuntimeException("Not enough balance"); // } System.out.println("Transaction Added : " + transaction); this.pendingTransactions.add(transaction); } public double getBalanceOfAddress(String address) { double balance = 0; for (Block block : this.chain) { for (Transaction transaction : block.transactions) { if (transaction.fromAddress.equals(address)) { balance -= transaction.amount; } if (transaction.toAddress.equals(address)) { balance += transaction.amount; } } } return balance; } public boolean isChainValid() throws Exception { for (int i = 1; i < this.chain.size(); i++) { Block currentBlock = this.chain.get(i); Block previousBlock = this.chain.get(i - 1); if (!currentBlock.hasValidTransactions()) { return false; } if (!currentBlock.hash.equals(Utils.calculateHash(currentBlock.previousHash + currentBlock.timeStamp + currentBlock.transactions.toString() + currentBlock.nonce))) { //return false; } if (!currentBlock.previousHash.equals(previousBlock.hash)) { return false; } } return true; } }
true
4a84a5c3bd08db8b0db97171b49f8fde45c9762f
Java
benwazza/hammer
/src/self/build/MainImpl.java
UTF-8
1,020
1.53125
2
[ "Apache-2.0" ]
permissive
/* * Copyright 2008-2009 Ben Warren * * 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 build; public final class MainImpl implements Main { Artifacts artifacts; Prepare prepare; Quality quality; Package pkg; Main me; public void all() { me.quality(); pkg.dist(); pkg.updateBootstrap(); } public void quality() { prepare.clean(); artifacts.publish(); quality.preCompile(); quality.postCompile(); } }
true
fd5a2354b94fd2d68e9e843124d5ba532e3892de
Java
happy6eve/cap-other
/cap-fileload/src/main/java/com/comtop/cap/runtime/dwr/CapFileUpload.java
UTF-8
3,734
2.15625
2
[]
no_license
/****************************************************************************** * Copyright (C) 2015 ShenZhen ComTop Information Technology Co.,Ltd * All Rights Reserved. * 本软件为深圳康拓普开发研制。未经本公司正式书面同意,其他任何个人、团体不得使用、 * 复制、修改或发布本软件. *****************************************************************************/ package com.comtop.cap.runtime.dwr; import java.io.File; import java.io.IOException; import java.util.HashMap; import java.util.List; import java.util.Map; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpSession; import org.apache.commons.fileupload.FileItem; import org.apache.commons.fileupload.FileUploadBase.FileSizeLimitExceededException; import org.apache.commons.fileupload.FileUploadException; import org.apache.commons.fileupload.disk.DiskFileItemFactory; import org.apache.commons.fileupload.servlet.ServletFileUpload; import comtop.org.directwebremoting.dwrp.CommonsFileUpload; import comtop.org.directwebremoting.event.SessionProgressListener; import comtop.org.directwebremoting.extend.FormField; import comtop.org.directwebremoting.extend.ServerException; import comtop.org.directwebremoting.extend.SimpleInputStreamFactory; import comtop.org.directwebremoting.io.InputStreamFactory; /** * FIXME 类注释信息 * * @author lizhiyong * @since jdk1.6 * @version 2015年12月3日 lizhiyong */ public class CapFileUpload extends CommonsFileUpload { /** FIXME */ private static final int DEFAULT_SIZE_THRESHOLD = 262144; @Override public Map<String, FormField> parseRequest(HttpServletRequest req) throws ServerException { File location = new File(System.getProperty("java.io.tmpdir")); DiskFileItemFactory itemFactory = new DiskFileItemFactory(DEFAULT_SIZE_THRESHOLD, location); ServletFileUpload fileUploader = new ServletFileUpload(itemFactory); fileUploader.setHeaderEncoding("UTF-8"); if (getFileUploadMaxBytes() > 0) { fileUploader.setFileSizeMax(getFileUploadMaxBytes()); } HttpSession session = req.getSession(false); if (session != null) { fileUploader.setProgressListener(new SessionProgressListener(session)); session.setAttribute("CANCEL_UPLOAD", null); session.setAttribute(PROGRESS_LISTENER, fileUploader.getProgressListener()); } try { Map<String, FormField> map = new HashMap<String, FormField>(); List<FileItem> fileItems = fileUploader.parseRequest(req); for (final FileItem fileItem : fileItems) { FormField formField; if (fileItem.isFormField()) { formField = new FormField(fileItem.getString()); } else { InputStreamFactory inFactory = new SimpleInputStreamFactory(fileItem.getInputStream()); formField = new FormField(fileItem.getName(), fileItem.getContentType(), fileItem.getSize(), inFactory); } map.put(fileItem.getFieldName(), formField); } return map; } catch (FileSizeLimitExceededException fsle) { throw new ServerException("One or more files is larger (" + fsle.getActualSize() + " bytes) than the configured limit (" + fsle.getPermittedSize() + " bytes)."); } catch (IOException ex) { throw new ServerException("Upload failed: " + ex.getMessage(), ex); } catch (FileUploadException ex) { throw new ServerException("Upload failed: " + ex.getMessage(), ex); } } }
true
8703c2ea5c0c9f9278c0a5a1ab36a87e9d680d47
Java
CAMI-challenge/ObjectStorageWrapper
/objectstoragewrapper-swift/src/main/java/cami/objectstoragewrapper/swift/SwiftFile.java
UTF-8
1,263
2.453125
2
[]
no_license
package cami.objectstoragewrapper.swift; import cami.objectstoragewrapper.core.IFile; import org.openstack4j.model.storage.object.SwiftObject; import java.util.Date; public class SwiftFile implements IFile { private final SwiftObject swiftObject; private final String name; private final String path; protected SwiftFile(SwiftObject object) { this.swiftObject = object; int index = object.getName().lastIndexOf('/'); this.name = object.getName().substring(index + 1); this.path = object.getName(); } @Override public String getPath() { return path; } @Override public String getName() { return name; } @Override public Date getTimeStamp() { return this.swiftObject.getLastModified(); } @Override public int hashCode() { return path == null || name == null ? 0 : path.hashCode() + name.hashCode(); } @Override public boolean equals(Object obj) { if (this == obj) return true; if (obj == null) return false; SwiftFile other = (SwiftFile) obj; if (path == null) { return other.path == null; } return path.equals(other.path); } }
true
62bdac518bf3d85b8e7885183779bb5b6e8695d0
Java
MacarenaBS/AplicacionesInteractivas
/src/model/Factura.java
ISO-8859-1
8,778
2.890625
3
[]
no_license
/*==================================================*/ /*=====================Package======================*/ /*==================================================*/ package model; /*==================================================*/ /*=====================Imports======================*/ /*==================================================*/ import java.util.ArrayList; import java.util.Date; import java.util.List; /*==================================================*/ /*===================End Imports====================*/ /*==================================================*/ /** * @author ezequiel.de-luca * @version 1.0 */ public class Factura { /*==================================================*/ /*====================Variables=====================*/ /*==================================================*/ private Integer intNumero; private String strDescripcion; private Date objFecha; private List<ItemFactura> colProductos; /*==================================================*/ /*===================Constructor====================*/ /*==================================================*/ /** * Crea una nueva factura * @param intNumero Nmero de Factura * @param strDescripcion Descripcin * @param objFecha Fecha de facturacin */ public Factura (Integer intNumero, String strDescripcion, Date objFecha) { this.setNumero(intNumero); this.setDescripcion(strDescripcion); this.setFecha(objFecha); this.colProductos = new ArrayList<ItemFactura>(); } /*==================================================*/ /*=================End Constructor==================*/ /*==================================================*/ /*==================================================*/ /*==========Devuelve el nmero de factura===========*/ /*==================================================*/ /** * @return Nmero de factura */ public Integer getNumero() { /*==================================================*/ /*================Devuelve el nmero================*/ /*==================================================*/ return intNumero; } /*==================================================*/ /*===================End Function===================*/ /*==================================================*/ /*==================================================*/ /*==========Establece el nmero de factura==========*/ /*==================================================*/ /** * Establece el nmero de factura. * @param intValue Nmero de factura */ public void setNumero(Integer intValue) { /*==================================================*/ /*===============Establece el nmero================*/ /*==================================================*/ this.intNumero = intValue; } /*==================================================*/ /*==================End Procedure===================*/ /*==================================================*/ /*==================================================*/ /*======Devuelve la descripcin de la factura=======*/ /*==================================================*/ /** * @return Descripcin */ public String getDescripcion() { /*==================================================*/ /*==============Devuelve la descipcin==============*/ /*==================================================*/ return strDescripcion; } /*==================================================*/ /*===================End Function===================*/ /*==================================================*/ /*==================================================*/ /*======Establece la descipcin de la factura=======*/ /*==================================================*/ /** * Establece la descipcin de la factura. * @param strValue Descripcin */ public void setDescripcion(String strValue) { /*==================================================*/ /*=============Establece la descripcin=============*/ /*==================================================*/ this.strDescripcion = strValue; } /*==================================================*/ /*==================End Procedure===================*/ /*==================================================*/ /*==================================================*/ /*=========Devuelve la fecha de facturacin=========*/ /*==================================================*/ /** * @return Fecha de facturacin */ public Date getFecha() { /*==================================================*/ /*================Devuelve la fecha=================*/ /*==================================================*/ return objFecha; } /*==================================================*/ /*===================End Function===================*/ /*==================================================*/ /*==================================================*/ /*========Establece la fecha de facturacin=========*/ /*==================================================*/ /** * Establece la fecha de facturacin * @param objValue Fecha de facturacin */ public void setFecha(Date objValue) { /*==================================================*/ /*================Establece la fecha================*/ /*==================================================*/ this.objFecha = objValue; } /*==================================================*/ /*==================End Procedure===================*/ /*==================================================*/ /*==================================================*/ /*====Devuelve la lista de productos facturados=====*/ /*==================================================*/ /** * @return Lista de productos facturados */ public List<ItemFactura> getProductos() { /*==================================================*/ /*========Devuelve los productos facturados=========*/ /*==================================================*/ return colProductos; } /*==================================================*/ /*===================End Function===================*/ /*==================================================*/ /*==================================================*/ /*===Agrega un producto a la lista de facturacin===*/ /*==================================================*/ /** * Agrega un producto a la lista de facturacin. * @param objCantidad Producto y cantidad a facturar */ public void addProducto(ItemFactura objCantidad) { /*==================================================*/ /*=====Agrega un producto y cantidad solicitada=====*/ /*==================================================*/ this.getProductos().add(objCantidad); } /*==================================================*/ /*==================End Procedure===================*/ /*==================================================*/ /*==================================================*/ /*=====================Add Item=====================*/ /*==================================================*/ public void addItem(Producto objProducto, Integer intCantidad) { /*==================================================*/ /*====================Variables=====================*/ /*==================================================*/ ItemFactura objItem; /*==================================================*/ /*====================Crear Item====================*/ /*==================================================*/ objItem = new ItemFactura(objProducto, intCantidad); /*==================================================*/ /*================Agregar a la Lista================*/ /*==================================================*/ this.colProductos.add(objItem); } /*==================================================*/ /*==================End Procedure===================*/ /*==================================================*/ /*==================================================*/ /*======================Equals======================*/ /*==================================================*/ // public boolean equals(Factura objFactura) // { // /*==================================================*/ // /*==================Return Results==================*/ // /*==================================================*/ // return (this.getNumero() == objFactura.getNumero()); // } public boolean isFactura(int intNumeroFactura){ return this.intNumero == intNumeroFactura; } /*==================================================*/ /*===================End Function===================*/ /*==================================================*/ } /*==================================================*/ /*====================End Class=====================*/ /*==================================================*/
true
560b8598476b1df17cee3561c61c7adeae41473f
Java
rakesh440/register
/Register/src/main/java/com/vis/dao/EmployeeService.java
UTF-8
572
1.726563
2
[]
no_license
package com.vis.dao; import org.hibernate.SessionFactory; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.orm.hibernate3.HibernateTemplate; import org.springframework.transaction.support.TransactionTemplate; import com.vis.model.UserRegistration; public class EmployeeService { @Autowired private SessionFactory sessionFactory; @Autowired private HibernateTemplate hibernateTemplate; @Autowired private TransactionTemplate transactionTemplate; public void register(UserRegistration e){ } }
true
bdadc9c7ef5a999bad3bd0fa58f5a0f495c04a8f
Java
moutainhigh/jysmall
/qhjys_mall_action/src/cn/qhjys/mall/mapper/FqAcardUserLotteryMapper.java
UTF-8
1,014
1.804688
2
[]
no_license
package cn.qhjys.mall.mapper; import cn.qhjys.mall.entity.FqAcardUserLottery; import cn.qhjys.mall.entity.FqAcardUserLotteryExample; import java.util.List; import org.apache.ibatis.annotations.Param; public interface FqAcardUserLotteryMapper { long countByExample(FqAcardUserLotteryExample example); int deleteByExample(FqAcardUserLotteryExample example); int deleteByPrimaryKey(Long id); int insert(FqAcardUserLottery record); int insertSelective(FqAcardUserLottery record); List<FqAcardUserLottery> selectByExample(FqAcardUserLotteryExample example); FqAcardUserLottery selectByPrimaryKey(Long id); int updateByExampleSelective(@Param("record") FqAcardUserLottery record, @Param("example") FqAcardUserLotteryExample example); int updateByExample(@Param("record") FqAcardUserLottery record, @Param("example") FqAcardUserLotteryExample example); int updateByPrimaryKeySelective(FqAcardUserLottery record); int updateByPrimaryKey(FqAcardUserLottery record); }
true
2a94020a2c9d6ad375ea9a5eeef97ea658e322a1
Java
vincenttuan/Java20210726
/study/src/main/java/com/study/day22/SayHello.java
UTF-8
82
1.90625
2
[]
no_license
package com.study.day22; public interface SayHello { void hello(String name); }
true
554e5112ca6f9fa3fcc7a683816be2917ad41d01
Java
sasikiran007/BSNLMCQ
/app/src/main/java/com/apps/kanchan/mcq/POJOs/Question.java
UTF-8
1,182
2.40625
2
[]
no_license
package com.apps.kanchan.mcq.POJOs; import java.util.ArrayList; import java.util.List; /** * Created by root on 14/12/18. */ public class Question { private String mQuestion; private ArrayList<String> mOptions; private int correctOption; private int mImageResourceId; private boolean isLocked; public Question(String question) { mQuestion = question; correctOption = -1; mImageResourceId = 0; isLocked = false; } public String getQuestion() { return mQuestion; } public void setQuestion(String mQuestion) { this.mQuestion = mQuestion; } public int getCorrectOption() { return correctOption; } public void setCorrectOption(int writeOption) { this.correctOption = writeOption; } public ArrayList<String> getOptions() { return mOptions; } public void setOptions(ArrayList<String> mOptions) { this.mOptions = mOptions; } public int getImageResourceId() { return mImageResourceId; } public void setImageResourceId(int mImageResourceId) { this.mImageResourceId = mImageResourceId; } }
true
6d5e1c226dce2d3faf9af7ef31ec6e14acf3fce3
Java
johimesa/Centripio
/order-service/src/main/java/com/geekshirt/orderservice/controller/OrderController.java
UTF-8
1,998
2.4375
2
[]
no_license
package com.geekshirt.orderservice.controller; import com.geekshirt.orderservice.dto.OrderRequest; import com.geekshirt.orderservice.dto.OrderResponse; import com.geekshirt.orderservice.entities.Order; import com.geekshirt.orderservice.service.OrderService; import com.geekshirt.orderservice.util.EntityDtoConverter; import io.swagger.annotations.Api; import io.swagger.annotations.ApiOperation; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.http.HttpStatus; import org.springframework.http.ResponseEntity; import org.springframework.web.bind.annotation.*; import java.util.ArrayList; import java.util.Date; import java.util.List; @Api @RestController public class OrderController { @Autowired private OrderService orderService; @Autowired private EntityDtoConverter entityDtoConverter; @ApiOperation(value = "Retrieve all existed orders", notes = "This operation returns all orders") @GetMapping(value = "order") public ResponseEntity<List<OrderResponse>> findAll() { List<Order> list = orderService.finAllOrders(); return new ResponseEntity<>(entityDtoConverter.convertEntityToDto(list), HttpStatus.OK); } @ApiOperation(value = "Retrieve an order based on ID", notes = "This operation returns an order using it ID") @GetMapping(value = "order/{orderId}") public ResponseEntity<OrderResponse> findById(@PathVariable String orderId) { Order order = orderService.findById(orderId); return new ResponseEntity<>(entityDtoConverter.convertEntityToDto(order), HttpStatus.OK); } @ApiOperation(value = "Creates an Order", notes = "This operation creates a new order") @PostMapping(value = "order/create") public ResponseEntity<OrderResponse> createOrder(@RequestBody OrderRequest request) { Order order = orderService.createOrder(request); return new ResponseEntity<>(entityDtoConverter.convertEntityToDto(order), HttpStatus.CREATED); } }
true
44de779c92e2585177c4a6c4b3e5836ed0242d4d
Java
trangnguyen88/362_warehouse
/src/main/java/com/champion/dao/BaseDAO.java
UTF-8
2,259
2.640625
3
[]
no_license
package com.champion.dao; import javax.swing.plaf.nimbus.State; import java.sql.*; public class BaseDAO { public BaseDAO(){ connect(); } protected Connection connection = null; private boolean connect(){ try { Class.forName("com.mysql.jdbc.Driver"); } catch (ClassNotFoundException e) { e.printStackTrace(); return false; } try { this.connection = DriverManager .getConnection("jdbc:mysql://localhost:3306/warehouse","root", "root123$"); } catch (SQLException e) { e.printStackTrace(); return false; } return true; } protected ResultSet getResultSet(String query){ Statement stmt = null; try { stmt = this.connection.createStatement(); return stmt.executeQuery(query); } catch (SQLException e) { e.printStackTrace(); return null; } } protected int executeScalar(String query){ Statement stmt = null; try { stmt = this.connection.createStatement(); ResultSet records = stmt.executeQuery(query); if(records.next()){ return records.getInt(1); } } catch (SQLException e) { e.printStackTrace(); return 0; } finally { if (stmt != null) { try { stmt.close(); } catch (SQLException e) { e.printStackTrace(); } } } return 0; } protected int executeUpdate(String query){ Statement stmt = null; try { stmt = this.connection.createStatement(); return stmt.executeUpdate(query); } catch (SQLException e) { e.printStackTrace(); return 0; } finally { if (stmt != null) { try { stmt.close(); } catch (SQLException e) { e.printStackTrace(); } } } } }
true
6611b4a9badfed24c7c4c26e1ae56ab63505b22a
Java
landsharkd/r1mini-command
/src/main/java/com/phicomm/smarthome/command/dao/RegistidMapper.java
UTF-8
797
1.867188
2
[]
no_license
package com.phicomm.smarthome.command.dao; import com.phicomm.smarthome.command.model.dao.RegistidModel; import java.util.List; import org.apache.ibatis.annotations.Param; import org.apache.ibatis.annotations.Result; import org.apache.ibatis.annotations.Results; import org.apache.ibatis.annotations.Select; public interface RegistidMapper { @Select("select * from ph_registration where uid=#{uid}") @Results({@Result(property = "id", column = "id"), @Result(property = "uid", column = "uid"), @Result(property = "platform", column = "platform"), @Result(property = "registid", column = "registration_id"), @Result(property = "osType", column = "os_type")}) public List<RegistidModel> queryRegistidByUid(@Param("uid") String uid); }
true
709ed8bcd702cbe4e18d31b5ce054e9568153d6c
Java
sligokid/twitter4j-spring-mvc
/src/main/java/ie/eirwig/servlet/CsoServlet.java
UTF-8
2,993
2.40625
2
[]
no_license
package ie.eirwig.servlet; import ie.eirwig.spring.entity.CsoCityEntity; import ie.eirwig.spring.entity.CsoFileParser; import ie.eirwig.spring.entity.CsoType; import java.io.IOException; import java.io.PrintWriter; import java.util.Date; import java.util.HashMap; import java.util.List; import java.util.Map; import javax.servlet.annotation.WebServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import org.json.simple.JSONValue; /** * The Class CsoServlet services requests for CSO data. */ @WebServlet("/CSO") public class CsoServlet extends BaseHttpServlet { private static final long serialVersionUID = 1L; @Override protected void runPrintWriter(HttpServletRequest request, HttpServletResponse response) throws IOException { String key = request.getParameter("key"); CsoFileParser parser = getCsoFileParser(key); printEachCityCsoToWriter(response, parser); } @SuppressWarnings("deprecation") private void printEachCityCsoToWriter(HttpServletResponse response, CsoFileParser parser) throws IOException { Map<String, Integer> cityCounts = new HashMap<String, Integer>(); PrintWriter printWriter = response.getWriter(); int total = 0; List<CsoCityEntity> csoData = parser.getCsoData(); for (CsoCityEntity entity : csoData) { cityCounts.put(entity.getCity(), Integer.parseInt(entity.getCount())); // delay reload printWriter.print("retry: 30000\n"); printWriter.print("data:" + "{\n"); printWriter.print("data:\"date\": \"" + new Date().toLocaleString() + "\",\n"); printWriter.print("data:\"city\": \"" + entity.getCity() + "\",\n"); printWriter.print("data:\"lat\": " + entity.getLattitude() + ",\n"); printWriter.print("data:\"lng\": " + entity.getLongditude() + ",\n"); printWriter.print("data:\"count\": " + entity.getCount() + ",\n"); printWriter.print("data:\"cities\": " + JSONValue.toJSONString(cityCounts) + ",\n"); printWriter.print("data:\"total\": " + (total += Integer.parseInt(entity.getCount())) + "\n"); printWriter.print("data:" + "}\n\n"); printWriter.flush(); try { Thread.currentThread(); Thread.sleep(100); } catch (InterruptedException e) { e.printStackTrace(); } } } private CsoFileParser getCsoFileParser(String key) throws IOException { if (key != null) { if ("single-m".equals(key)) { return new CsoFileParser(CsoType.T1_2SGLM); } if ("single-f".equals(key)) { return new CsoFileParser(CsoType.T1_2SGLF); } if ("single-t".equals(key)) { return new CsoFileParser(CsoType.T1_2SGLT); } if ("ethnic-ie".equals(key)) { return new CsoFileParser(CsoType.T2_1IEN); } if ("ethnic-uk".equals(key)) { return new CsoFileParser(CsoType.T2_1UKN); } if ("ethnic-pl".equals(key)) { return new CsoFileParser(CsoType.T2_1PLN); } if ("ethnic-lt".equals(key)) { return new CsoFileParser(CsoType.T2_1LTN); } } return new CsoFileParser(CsoType.T1_1AGETT); } }
true
045a09ea7f9e5a72bb4201abe8c480aa0aad87ae
Java
EvgenyUmansky/Project_ATDB
/src/org/bgu/ise/ddb/registration/RegistarationController.java
UTF-8
6,425
2.59375
3
[]
no_license
/** * */ package org.bgu.ise.ddb.registration; import java.io.IOException; import java.time.LocalDate; import java.time.LocalDateTime; import javax.servlet.http.HttpServletResponse; import org.bgu.ise.ddb.ParentController; import org.bgu.ise.ddb.User; import org.springframework.http.HttpStatus; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestMethod; import org.springframework.web.bind.annotation.RequestParam; import org.springframework.web.bind.annotation.ResponseBody; import org.springframework.web.bind.annotation.RestController; import com.mongodb.MongoClient; import com.mongodb.BasicDBObject; import com.mongodb.DB; import com.mongodb.DBCollection; import com.mongodb.DBCursor; import com.mongodb.DBObject; /** * @author Alex * */ @RestController @RequestMapping(value = "/registration") public class RegistarationController extends ParentController{ /** * The function checks if the username exist, * in case of positive answer HttpStatus in HttpServletResponse should be set to HttpStatus.CONFLICT, * else insert the user to the system and set to HttpStatus in HttpServletResponse HttpStatus.OK * @param username * @param password * @param firstName * @param lastName * @param response */ @RequestMapping(value = "register_new_customer", method={RequestMethod.POST}) public void registerNewUser(@RequestParam("username") String username, @RequestParam("password") String password, @RequestParam("firstName") String firstName, @RequestParam("lastName") String lastName, HttpServletResponse response){ System.out.println(username+" "+password+" "+lastName+" "+firstName); try { if(isExistUser(username)) { HttpStatus status = HttpStatus.CONFLICT; response.setStatus(status.value()); return; } MongoClient mongoClient = new MongoClient("localhost", 27017); DB db = mongoClient.getDB("ProjectATDB"); DBCollection collection = db.getCollection("Registration"); BasicDBObject addQuery = new BasicDBObject(); addQuery.put("username", username); addQuery.put("firstname", firstName); addQuery.put("lastname", lastName); addQuery.put("password", password); addQuery.put("date", LocalDate.now()); // to use for retrieve users from last n days collection.insert(addQuery); mongoClient.close(); HttpStatus status = HttpStatus.OK; response.setStatus(status.value()); }catch(Exception ex) { System.out.println(ex); } } /** * The function returns true if the received username exist in the system otherwise false * @param username * @return * @throws IOException */ @RequestMapping(value = "is_exist_user", method={RequestMethod.GET}) public boolean isExistUser(@RequestParam("username") String username) throws IOException{ System.out.println(username); //:TODO your implementation //https://www.baeldung.com/java-mongodb try (MongoClient mongoClient = new MongoClient("localhost", 27017);){ DB db = mongoClient.getDB("ProjectATDB"); DBCollection collection = db.getCollection("Registration"); BasicDBObject searchQuery = new BasicDBObject(); searchQuery.put("username", username); DBCursor cursor = collection.find(searchQuery); while (cursor.hasNext()) { return true; } }catch(Exception ex) { System.out.println(ex); } return false; } /** * The function returns true if the received username and password match a system storage entry, otherwise false * @param username * @return * @throws IOException */ @RequestMapping(value = "validate_user", method={RequestMethod.POST}) public boolean validateUser(@RequestParam("username") String username, @RequestParam("password") String password) throws IOException{ System.out.println(username+" "+password); //:TODO your implementation try(MongoClient mongoClient = new MongoClient("localhost", 27017);) { DB db = mongoClient.getDB("ProjectATDB"); DBCollection collection = db.getCollection("Registration"); BasicDBObject searchQuery = new BasicDBObject(); searchQuery.put("username", username); searchQuery.put("password", password); DBCursor cursor = collection.find(searchQuery); while (cursor.hasNext()) { return true; } }catch(Exception ex) { System.out.println(ex); } return false; } /** * The function retrieves number of the registered users in the past n days * @param days * @return * @throws IOException */ @RequestMapping(value = "get_number_of_registred_users", method={RequestMethod.GET}) public int getNumberOfRegistredUsers(@RequestParam("days") int days) throws IOException{ System.out.println(days+""); int result = 0; //:TODO your implementation try(MongoClient mongoClient = new MongoClient("localhost", 27017);){ LocalDateTime now = LocalDateTime.now(); LocalDateTime date = now.minusDays(days); DB db = mongoClient.getDB("ProjectATDB"); DBCollection collection = db.getCollection("Registration"); BasicDBObject searchQuery = new BasicDBObject(); searchQuery.put("date", new BasicDBObject("$gt", date)); DBCursor cursor = collection.find(searchQuery); while (cursor.hasNext()) { result++; cursor.next(); } }catch(Exception ex) { System.out.println(ex); } return result; } /** * The function retrieves all the users * @return */ @RequestMapping(value = "get_all_users",headers="Accept=*/*", method={RequestMethod.GET},produces="application/json") @ResponseBody @org.codehaus.jackson.map.annotate.JsonView(User.class) public User[] getAllUsers(){ //:TODO your implementation User u = new User("alex", "alex", "alex"); System.out.println(u); try(MongoClient mongoClient = new MongoClient("localhost", 27017);){ DB db = mongoClient.getDB("ProjectATDB"); DBCollection collection = db.getCollection("Registration"); DBCursor cursor = collection.find(); // all users User[] users = new User[cursor.size()]; int i = 0; while (cursor.hasNext()) { DBObject tempObj = cursor.next(); User temp = new User((String)tempObj.get("username"), (String)tempObj.get("firstname"),(String)tempObj.get("lastname")); users[i] = temp; i++; } return users; }catch(Exception ex) { System.out.println(ex); } return new User[]{u}; } }
true
81b381882c27f48e6dc41940eb839187524f5dfb
Java
bouzaien/medical-appointment-scheduling
/src/controle/Visite_ActiveC.java
UTF-8
3,479
2.765625
3
[]
no_license
package controle; import java.util.ArrayList ; import java.util.Date ; import java.util.List ; import metier.Doctor ; import metier.Patient ; import presentation.Patient_ActiveP ; import presentation.Visite_ActiveP ; import rdv.Visite ; public class Visite_ActiveC { private Visite_ActiveP presentation ; private Visite abstraction ; private List<Patient> patients ; private List<Doctor> doctors ; private VisitesRecord_C visitesRecordC ; public Visite_ActiveC (VisitesRecord_C visitesRecord) { presentation = new Visite_ActiveP (this, visitesRecord.getPresentation ().getStage ()) ; visitesRecordC = visitesRecord ; } public void setAbstraction (Visite visite) { abstraction = visite ; // premier rôle du contrôle : obtention des données pour la présentation Date date = visite.getDate () ; String patient = null ; float price = visite.getPrice (); if (visite.getPatient () != null) { patient = visite.getPatient ().getLastName () + " " + visite.getPatient ().getFirstName () ; } String doctor = null; if (visite.getDoctor () != null) { doctor = visite.getDoctor ().getLastName () + " " + visite.getDoctor ().getFirstName () ; } // c'est également ici que le composant joue son rôle de contrôleur en obtenant les bonnes listes de patients et docteurs à présenter à l'utilisateur patients = visitesRecordC.getPatients () ; doctors = visitesRecordC.getDoctors (); // et en les traduisant ensuite en listes de String à afficher avant de mettre à jour sa présentation List<String> patientsString = new ArrayList<String> () ; for (Patient a : patients) { patientsString.add (a.getLastName () + " " + a.getFirstName ()) ; } List<String> doctorsString = new ArrayList<String> () ; for (Doctor b : doctors) { doctorsString.add (b.getLastName () + " " + b.getFirstName ()) ; } presentation.update (date, patient,price, doctor, patientsString , doctorsString ) ; } public void activate () { presentation.show () ; } public Visite getAbstraction () { return abstraction ; } public Visite_ActiveP getPresentation () { return presentation ; } //------------------------------------------------------------------------------------- // méthode d'appel en provenance de la présentation pour signifier qu'une édition a été réalisée //------------------------------------------------------------------------------------- public void editionComplete () { // il faut récupérer toutes les informations éditées dans la préentation et les transférer vers l'abstraction int doctor = presentation.getDoctor () ; if (doctor < doctors.size ()) { abstraction.setDoctor (doctors.get (doctor)) ; } else { abstraction.setDoctor (null) ; } int patient = presentation.getPatient () ; if (patient < patients.size ()) { abstraction.setPatient (patients.get (patient)) ; } else { abstraction.setPatient (null) ; } abstraction.setDate (presentation.getDate ()) ; abstraction.setPrice (Float.parseFloat (presentation.getPrice ())) ; // on doit ensuite prévenir le gestionnaire de patients que l'édition est terminée avec succès visitesRecordC.updateVisite (this) ; } }
true
e964e49407b3cf06a10703a3202505f56a2c872d
Java
at-study/at-study-java-core-2
/src/main/java/lections/lesson5/custom_exceptions/NegativeAgeException.java
UTF-8
215
2.34375
2
[]
no_license
package lections.lesson5.custom_exceptions; public class NegativeAgeException extends IllegalAgeException { public NegativeAgeException() { super("Возраст отрицательный"); } }
true
87fb63201ff9176d6214b483ec30546147036459
Java
sjxxcode/custom_view
/src/main/java/com/sj/custom_view/practice/touch/MultiTouchActivity.java
UTF-8
750
1.9375
2
[]
no_license
package com.sj.custom_view.practice.touch; import android.os.Bundle; import android.support.annotation.Nullable; import android.support.v4.app.FragmentActivity; import com.sj.custom.R; import com.sj.custom_view.MyClick; /** * Created by SJ on 2019/1/10. */ public class MultiTouchActivity extends FragmentActivity { @Override protected void onCreate(@Nullable Bundle savedInstanceState) { super.onCreate(savedInstanceState); this.setContentView(R.layout.act_mutil_touch_layout_1); this.findViewById(R.id.mutil_1).setOnClickListener(new MyClick(this, MultiTouchView1.class, R.id.layout)); this.findViewById(R.id.mutil_2).setOnClickListener(new MyClick(this, MultiTouchView2.class, R.id.layout)); } }
true
c2b48c74730a2d69302b1c2ed89e30510c6b8dca
Java
SeerLabs/CiteSeerX
/src/java/edu/psu/citeseerx/myciteseer/dao/GroupDAOImpl.java
UTF-8
19,247
1.789063
2
[ "Apache-2.0" ]
permissive
/* * Copyright 2007 Penn State University * 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 edu.psu.citeseerx.myciteseer.dao; import java.sql.ResultSet; import java.sql.SQLException; import java.sql.Types; import java.util.List; import javax.sql.DataSource; import org.springframework.context.ApplicationContextException; import org.springframework.dao.DataAccessException; import org.springframework.jdbc.core.SqlParameter; import org.springframework.jdbc.core.support.JdbcDaoSupport; import org.springframework.jdbc.object.MappingSqlQuery; import org.springframework.jdbc.object.SqlUpdate; import org.springframework.jdbc.support.GeneratedKeyHolder; import org.springframework.jdbc.support.KeyHolder; import org.springframework.security.GrantedAuthority; import org.springframework.security.GrantedAuthorityImpl; import edu.psu.citeseerx.myciteseer.acl.PermissionManager; import edu.psu.citeseerx.myciteseer.domain.Account; import edu.psu.citeseerx.myciteseer.domain.Group; import edu.psu.citeseerx.myciteseer.domain.GroupMember; /** * GroupDAO implementation using MYSQL as a persistent storage. * @author Juan Pablo Fernandez Ramirez * @version $$Rev$$ $$Date$$ */ public class GroupDAOImpl extends JdbcDaoSupport implements GroupDAO { protected InsertGroup insertGroup; protected InsertGroupMember insertGroupMember; protected GetGroupMapping getGroupMapping; protected GroupExistsMapping groupExistsMapping; protected GetGroupsMapping getGroupsMapping; protected DeleteGroup deleteGroup; protected GetGroupMembersMapping getGroupMembersMapping; protected UpdateGroup updateGroup; protected RemoveMember removeMember; protected ValidateUser validateUser; protected GetGroupAuthoritiesByUsernameMapping getGroupAuthoritiesByUsernameMapping; protected GetIsGroupMemberMapping getIsGroupMemberMapping; private PermissionManager permissionManager; /** * @param permissionManager Object to manipulate ACL entries related to * groups. */ public void setPermissionManager(PermissionManager permissionManager) { this.permissionManager = permissionManager; } //- setPermissionManager /* (non-Javadoc) * @see org.springframework.dao.support.DaoSupport#initDao() */ protected void initDao() throws ApplicationContextException { initMappingSqlQueries(); } //- initDao protected void initMappingSqlQueries() { this.insertGroup = new InsertGroup(getDataSource()); this.insertGroupMember = new InsertGroupMember(getDataSource()); this.getGroupMapping = new GetGroupMapping(getDataSource()); this.groupExistsMapping = new GroupExistsMapping(getDataSource()); this.getGroupsMapping = new GetGroupsMapping(getDataSource()); this.deleteGroup = new DeleteGroup(getDataSource()); this.getGroupMembersMapping = new GetGroupMembersMapping(getDataSource()); this.updateGroup = new UpdateGroup(getDataSource()); this.removeMember = new RemoveMember(getDataSource()); this.validateUser = new ValidateUser(getDataSource()); this.getGroupAuthoritiesByUsernameMapping = new GetGroupAuthoritiesByUsernameMapping(getDataSource()); this.getIsGroupMemberMapping = new GetIsGroupMemberMapping(getDataSource()); } //- initMappingSqlQueries /* (non-Javadoc) * @see edu.psu.citeseerx.myciteseer.dao.GroupDAO#addGroup(edu.psu.citeseerx.myciteseer.domain.Group) */ public Group addGroup(Group group) throws DataAccessException { Long groupID = insertGroup.run(group); group.setId(groupID); // Add the owner of the group as a member addMember(group, group.getOwner(), false); return group; } //- addGroup /* (non-Javadoc) * @see edu.psu.citeseerx.myciteseer.dao.GroupDAO#addMember(edu.psu.citeseerx.myciteseer.domain.Group, java.lang.String, boolean) */ public void addMember(Group group, String userid, boolean validating) throws DataAccessException { insertGroupMember.run(group.getId(), userid, validating); if (group.getOwner().toLowerCase().compareTo(userid.toLowerCase()) == 0) { permissionManager.addAdminPermission(group, userid); }else{ permissionManager.addReadPermission(group, userid); } } //- addMember /* (non-Javadoc) * @see edu.psu.citeseerx.myciteseer.dao.GroupDAO#isNameRepeated(edu.psu.citeseerx.myciteseer.domain.Group, edu.psu.citeseerx.myciteseer.domain.Account) */ public boolean isNameRepeated(Group group, Account account) throws DataAccessException { boolean exists = false; List<Group> groups = groupExistsMapping.run(group, account); if (groups.size() > 0 && (groups.get(0).getId() != group.getId()) ) { exists = true; } return exists; } //- isNameRepeated /* (non-Javadoc) * @see edu.psu.citeseerx.myciteseer.dao.GroupDAO#getGroup(long, edu.psu.citeseerx.myciteseer.domain.Account) */ public Group getGroup(long groupID) throws DataAccessException { Group theGroup = null; List<Group> groups = getGroupMapping.run(groupID); if (groups.size() > 0) { theGroup = (Group)groups.get(0); } return theGroup; } //- getGroup /* (non-Javadoc) * @see edu.psu.citeseerx.myciteseer.dao.GroupDAO#getGroups(java.lang.String) */ public List<Group> getGroups(String username) throws DataAccessException { return getGroupsMapping.run(username); } //- getGroups /* (non-Javadoc) * @see edu.psu.citeseerx.myciteseer.dao.GroupDAO#deleteGroup(edu.psu.citeseerx.myciteseer.domain.Group) */ public void deleteGroup(Group group) throws DataAccessException { deleteGroup.run(group); // delete the group ACL information permissionManager.deleteACL(group); } //- deleteGroup /* (non-Javadoc) * @see edu.psu.citeseerx.myciteseer.dao.GroupDAO#getMembers(edu.psu.citeseerx.myciteseer.domain.Group) */ public List<GroupMember> getMembers(Group group) throws DataAccessException { return getGroupMembersMapping.run(group); } //- getGroupMembers /* (non-Javadoc) * @see edu.psu.citeseerx.myciteseer.dao.GroupDAO#updateGroup(edu.psu.citeseerx.myciteseer.domain.Group) */ public void updateGroup(Group group) throws DataAccessException { updateGroup.run(group); } //- updateGroup /* (non-Javadoc) * @see edu.psu.citeseerx.myciteseer.dao.GroupDAO#leaveGroup(edu.psu.citeseerx.myciteseer.domain.Group, java.lang.String) */ public void leaveGroup(Group group, String userid) throws DataAccessException { removeMember.run(group, userid); // Remove permissions permissionManager.deletePermissions(group, userid); } //- leaveGroup /* (non-Javadoc) * @see edu.psu.citeseerx.myciteseer.dao.GroupDAO#removeMember(edu.psu.citeseerx.myciteseer.domain.Group, java.lang.String) */ public void removeMember(Group group, String userid) throws DataAccessException { removeMember.run(group, userid); // Remove permissions permissionManager.deletePermissions(group, userid); } //- removeMember /* (non-Javadoc) * @see edu.psu.citeseerx.myciteseer.dao.GroupDAO#validateUser(long, java.lang.String) */ public void validateUser(Group group, String userid) throws DataAccessException { validateUser.run(group, userid); } //- validateUser /* (non-Javadoc) * @see edu.psu.citeseerx.myciteseer.dao.GroupDAO#getGroupAuthorities(java.lang.String) */ public List<GrantedAuthority> getGroupAuthorities(String username) throws DataAccessException { return getGroupAuthoritiesByUsernameMapping.run(username); } //- getGroupAuthorities /* (non-Javadoc) * @see edu.psu.citeseerx.myciteseer.dao.GroupDAO#isMember(edu.psu.citeseerx.myciteseer.domain.Group, java.lang.String) */ public boolean isMember(Group group, String userid) throws DataAccessException { List<String> users = getIsGroupMemberMapping.run(group, userid); return !(users.isEmpty()); } //- isMember /* * Utility classes providing SQL access */ private static final String DEF_INSERT_GROUP_STATEMENT = "insert into groups values (NULL, ?, ?, ?, ?)"; protected class InsertGroup extends SqlUpdate { public InsertGroup(DataSource ds) { setDataSource(ds); setSql(DEF_INSERT_GROUP_STATEMENT); declareParameter(new SqlParameter(Types.VARCHAR)); declareParameter(new SqlParameter(Types.VARCHAR)); declareParameter(new SqlParameter(Types.VARCHAR)); declareParameter(new SqlParameter(Types.VARCHAR)); setReturnGeneratedKeys(true); compile(); } //- InsertGroup.InsertGroup public Long run(Group group) { Object[] params = new Object[] { group.getName(), group.getDescription(), group.getOwner(), group.getAuthority() }; KeyHolder holder = new GeneratedKeyHolder(); update(params, holder); return new Long(holder.getKey().longValue()); } //- InsertGroup.run } //- class InsertGroup private static final String DEF_INSERT_GROUP_MEMBERS_STATEMENT = "insert into group_members values (?, ?, ?)"; protected class InsertGroupMember extends SqlUpdate { public InsertGroupMember(DataSource ds) { setDataSource(ds); setSql(DEF_INSERT_GROUP_MEMBERS_STATEMENT); declareParameter(new SqlParameter(Types.BIGINT)); declareParameter(new SqlParameter(Types.VARCHAR)); declareParameter(new SqlParameter(Types.TINYINT)); compile(); } //- InsertGroupMember.InsertGroupMember public int run(long groupID, String userid, boolean validating) { Object[] params = new Object[] { groupID, userid, new Boolean(validating) }; return update(params); } //- InsertGroupMember.run } //- class InsertGroupMember private static final String DEF_GROUP_NAME_ALREADY_EXISTS_QUERY = "select id, name, description, owner, authority from groups g " + "where name = ?"; protected class GroupExistsMapping extends MappingSqlQuery { public GroupExistsMapping(DataSource ds) { super(ds, DEF_GROUP_NAME_ALREADY_EXISTS_QUERY); declareParameter(new SqlParameter(Types.VARCHAR)); } //- GroupExistsMapping.GroupExistsMapping protected Group mapRow(ResultSet rs, int rownum) throws SQLException { Group group = new Group(); group.setId(rs.getLong("id")); group.setName(rs.getString("name")); group.setDescription(rs.getString("description")); group.setOwner(rs.getString("owner")); group.setAuthority(rs.getString("authority")); return group; } //- GroupExistsMapping.MapRow public List<Group> run(Group group, Account account) { Object[] params = new Object[] { group.getName() }; return execute(params); } //- GroupExistsMapping.run } //- GroupExistsMapping private static final String DEF_GET_GROUP_QUERY = "select id, name, description, owner, authority from groups " + "where id = ?"; protected class GetGroupMapping extends MappingSqlQuery { public GetGroupMapping(DataSource ds) { super(ds, DEF_GET_GROUP_QUERY); declareParameter(new SqlParameter(Types.BIGINT)); } //- GetGroupMapping.GetCollectionMapping protected Group mapRow(ResultSet rs, int rownum) throws SQLException { Group group = new Group(); group.setId(rs.getLong("id")); group.setName(rs.getString("name")); group.setDescription(rs.getString("description")); group.setOwner(rs.getString("owner")); group.setAuthority(rs.getString("authority")); return group; } //- GetGroupMapping.mapRow public List<Group> run(long groupID) { Object[] params = new Object[] {groupID}; return execute(params); } //- GetGroupMapping.run } //- class GetGroupMapping private static final String DEF_GET_USER_GROUPS_QUERY = "select g.id, g.name, g.description, g.owner, g.authority, " + "gm.userid from groups g inner join group_members gm on " + "g.id = gm.groupid where gm.userid = ?"; protected class GetGroupsMapping extends MappingSqlQuery { public GetGroupsMapping(DataSource ds) { super(ds, DEF_GET_USER_GROUPS_QUERY); declareParameter(new SqlParameter(Types.VARCHAR)); } //- GetGroupsMapping.GetGroupsMapping protected Group mapRow(ResultSet rs, int rownum) throws SQLException { Group group = new Group(); group.setId(rs.getLong("id")); group.setName(rs.getString("name")); group.setDescription(rs.getString("description")); group.setOwner(rs.getString("owner")); group.setAuthority(rs.getString("authority")); return group; } //- GetGroupsMapping.mapRow public List<Group> run(String username) { Object[] params = new Object[] { username }; return execute(params); } //- GetGroupsMapping.run } // class GetGroupsMapping private static final String DEF_DELETE_GROUP_STATEMENT = "delete from groups where id = ?"; protected class DeleteGroup extends SqlUpdate { public DeleteGroup(DataSource ds) { setDataSource(ds); setSql(DEF_DELETE_GROUP_STATEMENT); declareParameter(new SqlParameter(Types.BIGINT)); compile(); } //- DeleteGroup.DeleteGroup public int run(Group group) { Object[] params = new Object[] { group.getId() }; return update(params); } //- DeleteGroup.run } //- class DeleteGroup private static final String DEF_GET_GROUP_MEMBERS_QUERY = "select u.userid, u.firstName, u.middleName, u.lastName, u.email, " + "u.affil1, u.affil2, u.country, u.province, u.webPage, " + "m.groupid, m.validating FROM users u " + "inner join group_members m ON u.userid = m.userid WHERE m.groupid = ?"; protected class GetGroupMembersMapping extends MappingSqlQuery { public GetGroupMembersMapping(DataSource ds) { super(ds, DEF_GET_GROUP_MEMBERS_QUERY); declareParameter(new SqlParameter(Types.BIGINT)); } //- GetGroupMembersMapping.GetGroupMembersMapping protected GroupMember mapRow(ResultSet rs, int rownum) throws SQLException { GroupMember groupMember = new GroupMember(); Account member= new Account(); member.setUsername(rs.getString("userid")); member.setFirstName(rs.getString("firstName")); member.setMiddleName(rs.getString("middleName")); member.setLastName(rs.getString("lastName")); member.setEmail(rs.getString("email")); member.setAffiliation1(rs.getString("affil1")); member.setAffiliation2(rs.getString("affil2")); member.setCountry(rs.getString("country")); member.setProvince(rs.getString("province")); member.setWebPage(rs.getString("webPage")); groupMember.setGroupId(rs.getLong("groupID")); groupMember.setMember(member); groupMember.setValidating(rs.getBoolean("validating")); return groupMember; } //- GetGroupMembersMapping.mapRow public List<GroupMember> run(Group group) { Object[] params = new Object[] { group.getId() }; return execute(params); } //- GetGroupMembersMapping.run } //- class GetGroupMembersMapping private static final String DEF_UPDATE_GROUP_STATEMENT = "update groups set name = ?, description = ? where id = ?"; protected class UpdateGroup extends SqlUpdate { public UpdateGroup(DataSource ds) { setDataSource(ds); setSql(DEF_UPDATE_GROUP_STATEMENT); declareParameter(new SqlParameter(Types.VARCHAR)); declareParameter(new SqlParameter(Types.VARCHAR)); declareParameter(new SqlParameter(Types.BIGINT)); } //- UpdateGroup.UpdateGroup int run(Group group) { Object[] params = new Object[] { group.getName(), group.getDescription(), group.getId() }; return update(params); } //- UpdateGroup.run } //- class UpdateGroup private static final String DEF_DEL_USER_FROM_GROUP_STMT = "delete group_members gm from group_members gm inner join groups g " + "on g.id = gm.groupid where gm.groupid = ? and gm.userid = ? and " + "g.owner <> gm.userid"; protected class RemoveMember extends SqlUpdate { public RemoveMember(DataSource ds) { setDataSource(ds); setSql(DEF_DEL_USER_FROM_GROUP_STMT); declareParameter(new SqlParameter(Types.BIGINT)); declareParameter(new SqlParameter(Types.VARCHAR)); compile(); } //- RemoveUserGroup.RemoveUserGroup public int run(Group group, String userid) { Object[] params = new Object[] {group.getId(), userid}; return update(params); } //- RemoveUserGroup.run } //- class RemoveUserGroup private final static String DEF_VALIDATE_USER_STMT = "update group_members set validating = 0 where groupid = ? " + "and userid = ?"; protected class ValidateUser extends SqlUpdate { public ValidateUser(DataSource ds) { setDataSource(ds); setSql(DEF_VALIDATE_USER_STMT); declareParameter(new SqlParameter(Types.BIGINT)); declareParameter(new SqlParameter(Types.VARCHAR)); compile(); } //- ValidateUser.ValidateUserGroup public int run(Group group, String userid) { Object[] params = new Object[] {group.getId(), userid}; return update(params); } //- ValidateUser.run } //- class ValidateUser private static final String DEF_GROUP_AUTHORITIES_BY_USERNAME_QUERY = "select g.authority from groups g inner join group_members gm on " + "g.id = gm.groupid where gm.userid = ?"; protected class GetGroupAuthoritiesByUsernameMapping extends MappingSqlQuery { public GetGroupAuthoritiesByUsernameMapping(DataSource ds) { super(ds, DEF_GROUP_AUTHORITIES_BY_USERNAME_QUERY); declareParameter(new SqlParameter(Types.VARCHAR)); } //- GetGroupAuthoritiesByUsernameMapping.GetGroupAuthoritiesByUsernameMapping protected GrantedAuthority mapRow(ResultSet rs, int rownum) throws SQLException { GrantedAuthority authority = new GrantedAuthorityImpl(rs.getString("authority")); return authority; } //- GetGroupAuthoritiesByUsernameMapping.mapRow public List<GrantedAuthority> run(String username) { Object[] params = new Object[] { username }; return execute(params); } //- GetUserNotInGroupByIDMapping.run } //- class GetUserNotInGroupByIDMapping private static final String DEF_IS_GROUP_MEMBER_QUERY = "select userid from group_members where groupid = ? and userid = ?"; protected class GetIsGroupMemberMapping extends MappingSqlQuery { public GetIsGroupMemberMapping(DataSource ds) { super(ds, DEF_IS_GROUP_MEMBER_QUERY); declareParameter(new SqlParameter(Types.BIGINT)); declareParameter(new SqlParameter(Types.VARCHAR)); } //- GetIsGroupMemberMapping.GetIsGroupMemberMapping protected String mapRow(ResultSet rs, int rownum) throws SQLException { String username = rs.getString("userid"); return username; } //- GetIsGroupMemberMapping.mapRow public List<String> run(Group group, String username) { Object[] params = new Object[] {group.getId(), username }; return execute(params); } //- GetIsGroupMemberMapping.run } //- class GetIsGroupMemberMapping } //- GroupDAOImpl
true
5dde17e0586274dc7207d0ffbbe864b00d3c6086
Java
binjiewang/FundingOnline
/atcrowdfunding01adminparent/atcrowdfunding03-admin-component/src/main/java/com/atguigu/crowd/mvc/handler/AdminHandler.java
UTF-8
3,743
2.09375
2
[]
no_license
package com.atguigu.crowd.mvc.handler; import com.atguigu.crowd.constant.CrowdConstant; import com.atguigu.crowd.entity.Admin; import com.atguigu.crowd.service.api.AdminService; import com.github.pagehelper.PageInfo; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.security.access.prepost.PreAuthorize; 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.RequestParam; import javax.servlet.http.HttpSession; /** * 用户登录/登出处理 * @author binjiewang */ @Controller public class AdminHandler { @Autowired private AdminService adminService; @RequestMapping("/admin/do/login.html") public String doLogin(@RequestParam("loginAcct")String loginAcct, @RequestParam("userPswd")String userPswd, HttpSession session){ Admin admin = adminService.getAdminByLoginAcct(loginAcct,userPswd); session.setAttribute(CrowdConstant.ATTR_NAME_LOGIN_ADMIN,admin); //为了防止表单重复提交,使用重定向 return "redirect:/admin/to/main/page.html"; } @RequestMapping("/admin/do/logout.html") public String doLoginOut(HttpSession session){ session.invalidate(); return "redirect:/admin/to/login/page.html"; } /** * 用户分页查询 * @param keyword * @param pageNum * @param pageSize * @param modelMap * @return */ @RequestMapping("/admin/get/page.html") public String getAdminPage( @RequestParam(value = "keyword",defaultValue = "")String keyword, @RequestParam(value = "pageNum",defaultValue = "1")Integer pageNum, @RequestParam(value = "pageSize",defaultValue = "5")Integer pageSize, ModelMap modelMap ){ PageInfo<Admin> adminPage = adminService.getAdminPage(keyword, pageNum, pageSize); modelMap.addAttribute(CrowdConstant.ATTR_NAME_PAGE_INFO, adminPage); return "admin-page"; } /** * 新增用户 */ //进入方法之前权限验证 @PreAuthorize("hasAuthority('user:save')") @RequestMapping("/save/admin.html") public String saveAdmin(Admin admin){ adminService.saveAdmin(admin); return "redirect:/admin/get/page.html?pageNum="+Integer.MAX_VALUE; } @RequestMapping("/admin/remove/{adminId}/{pageNum}/{keyword}.html") public String removeAdmin(@PathVariable("adminId")Integer adminId, @PathVariable("pageNum")Integer pageNum, @PathVariable("keyword")String keyword, HttpSession session ){ Admin admin = (Admin) session.getAttribute(CrowdConstant.ATTR_NAME_LOGIN_ADMIN); if(adminId.equals(admin.getId())){ throw new RuntimeException(CrowdConstant.MESSAGE_DELETE_INFO); } adminService.remove(adminId); return "redirect:/admin/get/page.html?pageNum="+pageNum+"&keyword="+keyword; } @RequestMapping("admin/to/edit/page.html") public String editAdmin(@RequestParam("adminId")Integer adminId,ModelMap modelMap){ Admin admin = adminService.getAdminByid(adminId); modelMap.addAttribute("admin",admin); return "admin-edit"; } @RequestMapping("/admin/update.html") public String update(Admin admin, @RequestParam("pageNum") Integer pageNum, @RequestParam("keyword") String keyword){ adminService.update(admin); return "redirect:/admin/get/page.html?pageNum="+pageNum+"&keyword="+keyword; } }
true
b0e14537f5283c7c0c15362c483f038c2a4f9be4
Java
brendoncheung/rxjava-basics
/src/main/java/com/alephreach/main/operators/TransformingOperators.java
UTF-8
7,639
3.625
4
[]
no_license
package com.alephreach.main.operators; import com.alephreach.main.GlobalUtils; import io.reactivex.Observable; import io.reactivex.functions.Function; import io.reactivex.functions.Predicate; import java.time.LocalDate; import java.time.format.DateTimeFormatter; import java.util.Comparator; import java.util.concurrent.TimeUnit; public class TransformingOperators { private static void map() { // For a given Observable<T>, the map() operator will transform a T emission into an R // emission using the provided Function<T,R> lambda. We have already used this operator // many times, turning strings into lengths. Here is a new example: we can take raw date // strings and use the map() operator to turn each one into a LocalDate emission, as shown // in the following code snippet: DateTimeFormatter dtf = DateTimeFormatter.ofPattern("M/d/yyyy"); Function<String, LocalDate> mapper = s -> LocalDate.parse(s, dtf); // Observable<String> --mapper--> Observable<LocalDate> --> consumer Observable.just("1/3/2016", "5/9/2016", "10/12/2016") .map(mapper) // after the mapping, the emission will be of type LocalDate .subscribe(d -> System.out.println(d)); } private static void cast() { // A simple, map-like operator to cast each emission to a different type is cast(). If we want // to take Observable<String> and cast each emission to an object (and return an // Observable<Object>), we could use the map() operator like this: Observable<Object> items1 = Observable.just("Alpha", "Beta", "Gamma").map(s -> (Object) s); // But a shorthand we can use instead is cast(), and we can simply pass the class type we // want to cast to, as shown in the following code snippet: Observable<Object> items2 = Observable.just("Alpha", "Beta", "Gamma").cast(Object.class); } private static void startWith() { // For a given Observable<T>, the startWith() operator allows you to insert a T emission // that precedes all the other emissions. For instance, if we have an Observable<String>that // emits items on a menu we want to print, we can use startWith() to append a title header // first: Observable.just("Coffee", "Tea", "Espresso", "Latte") .startWith("COFFEE SHOP MENU") .subscribe(s -> System.out.println(s)); Observable.just("Coffee", "Tea", "Espresso", "Latte") .startWithArray("------------", "COFFEE SHOP MENU", "------------") .subscribe(s -> System.out.println(s)); } private static void defaultIfEmpty() { // For a given Observable<T>, we can specify a default T emission // if no emissions occur when onComplete() is called. Predicate<String> condition = s -> s.startsWith("S"); GlobalUtils.getStringJustObservable() .filter(condition) .defaultIfEmpty("None found") .subscribe(s -> System.out.println(s)); } private static void switchIfEmpty() { // Similar to defaultIfEmpty(), switchIfEmpty() specifies a different Observable to // emit values from if the source Observable is empty. This allows you specify a different // sequence of emissions in the event that the source is empty rather than emitting just one // value. Predicate<String> condiiton = s -> s.startsWith("Z"); GlobalUtils.getStringJustObservable() .filter(condiiton) .switchIfEmpty(Observable.just("Zeta", "Eta", "Theta")) .subscribe(s -> System.out.println(s)); } private static void sorted() { // If you have a finite Observable<T> emitting items that implement Comparable<T>, you // can use sorted() to sort the emissions. Internally, it will collect all the emissions and then // re-emit them in their sorted order. In the following code snippet, we sort emissions // from Observable<Integer>so that they are emitted in their natural order: Observable.just(16, 5, 7, 5, 4, 8, 9) .sorted() .subscribe(i -> System.out.println(i)); Observable.just(6, 2, 5, 7, 1, 4, 9, 8, 3) .sorted(Comparator.reverseOrder()) .subscribe(System.out::println); GlobalUtils.getStringJustObservable() .sorted((x,y) -> Integer.compare(x.length(), y.length())) .subscribe(System.out::println); } private static void delay() { // We can postpone emissions using the delay() operator. It will hold any received emissions // and delay each one for the specified time period. If we wanted to delay emissions by three // seconds, we could do it like this: // {------3 second------, emission} // delay() operatets on a different scheduler, therefore we need sleep() GlobalUtils.getStringJustObservable() .delay(3, TimeUnit.SECONDS) .subscribe(s -> System.out.println(s)); GlobalUtils.sleep(5000); // Because delay() operates on a different scheduler (such as Observable.interval()), we // need to leverage a sleep() method to keep the application alive long enough to see this // happen. // Each emission will be delayed by three seconds. You can pass an optional third // Boolean argument indicating whether you want to delay error notifications as well. // For more advanced cases, you can pass another Observable as your delay() argument, // and this will delay emissions until that other Observable emits something. } private static void repeat() { // The repeat() operator will repeat subscription upstream after onComplete() a specified // number of times. GlobalUtils.getStringJustObservable() .repeat(2) .subscribe(s -> System.out.println(s), Throwable::printStackTrace, () -> System.out.println("onComplete")); } private static void scan() { // The scan() method is a rolling aggregator. For every emission, you add it to an // accumulation. Then, it will emit each incremental accumulation. // // For instance, you can emit the rolling sum for each emission by passing a lambda to // thescan() method that adds each next emission to the accumulator: Observable.just(5, 4, 6, 7, 14, 1, 19) .scan((accumulator, next) -> { System.out.println("accumulator: " + accumulator); System.out.println("next: " + next); return 0; // this return is to the accumulator }) .subscribe(i -> System.out.println(i)); Observable.just(5, 4, 6, 7, 14, 1, 19) .scan((accumulator, next) -> accumulator + next) .subscribe(i -> System.out.println(i)); } private static void fibonacci(int index) { Observable.range(1, index) // 1 to 10 inclusive .scan((accumulator, next) -> accumulator + next) .subscribe(i -> System.out.println(i)); } public static void main(String[] args) { // map(); // cast(); // startWith(); // defaultIfEmpty(); // switchIfEmpty(); // sorted(); // delay(); // repeat(); // scan(); fibonacci(10); // broken lol } }
true
12fdb5c76e36d3bff9e3d64d8e302e3cb2c8ae47
Java
nihar01/Academia_ESD
/src/main/java/com/example/erp/service/CoursesService.java
UTF-8
351
1.953125
2
[]
no_license
package com.example.erp.service; import com.example.erp.bean.Courses; import com.example.erp.dao.CoursesDao; import com.example.erp.dao.impl.CoursesDaoImpl; import java.util.List; public class CoursesService { CoursesDao coursesDao=new CoursesDaoImpl(); public List<Courses> getCourses (){ return coursesDao.getCourses(); } }
true
06b468bee19d4a6bc329437658e72a569c7f0bea
Java
aristid-lavri/framed-text
/app/src/main/java/example/com/framedtext/FramedText.java
UTF-8
3,213
2.515625
3
[]
no_license
package example.com.framedtext; import android.content.Context; import android.content.res.TypedArray; import android.graphics.Canvas; import android.graphics.Color; import android.graphics.Paint; import android.graphics.Rect; import android.util.AttributeSet; import android.view.View; /** * Created by AGNAMC on 7/5/2016. */ public class FramedText extends View { // create attributes objects String mText; float mTextSize; String mTextColor; String mFrameColor; // bounds of text Rect mBounds; // for drawing Paint mPaint; public FramedText(Context context) { super(context); } public FramedText(Context context, AttributeSet attrs) { super(context, attrs); // retrieve attributes values from attrs.xml file TypedArray typedArray = context.getTheme().obtainStyledAttributes(attrs, R.styleable.FramedText, 0, 0); try{ mText = typedArray.getString(R.styleable.FramedText_text); mTextSize = typedArray.getDimension(R.styleable.FramedText_textSize, 0); mTextColor = typedArray.getString(R.styleable.FramedText_textColor); mFrameColor = typedArray.getString(R.styleable.FramedText_frameColor); } finally { typedArray.recycle(); } if (mText == null) mText = " "; mTextSize = (mTextSize == 0) ? 24f : mTextSize; if (mTextColor == null) mTextColor = "#000000"; if (mFrameColor == null) mFrameColor = "#000000"; init(context); } private void init(Context context) { float density = context.getResources().getDisplayMetrics().density; mBounds = new Rect(); mPaint = new Paint(Paint.ANTI_ALIAS_FLAG); mPaint.setTextSize(mTextSize * density); // get bounds of text , stored im mBounds mPaint.getTextBounds(mText, 0, mText.length(), mBounds); } public String getText() { return mText; } public void setText(String text) { mText = text; invalidate(); requestLayout(); } public float getTextSize() { return mTextSize; } public void setTextSize(float textSize) { mTextSize = textSize; invalidate(); requestLayout(); } public String getTextColor() { return mTextColor; } public void setTextColor(String textColor) { mTextColor = textColor; invalidate(); requestLayout(); } public String getFrameColor() { return mFrameColor; } public void setFrameColor(String frameColor) { mFrameColor = frameColor; invalidate(); requestLayout(); } @Override protected void onDraw(Canvas canvas) { super.onDraw(canvas); canvas.translate( (int) ((getWidth() - mBounds.width()) / 2.0f), (int) ((getHeight() - mBounds.height()) / 2.0f)); mPaint.setColor(Color.parseColor(mTextColor)); canvas.drawText(mText, 0.0f, 0.0f, mPaint); mPaint.setColor(Color.parseColor(mFrameColor)); mPaint.setStyle(Paint.Style.STROKE); canvas.drawRect(mBounds, mPaint); } }
true