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
3543277c13e77d9655ac1ed2178c7302438851c8
Java
FASTTRACKSE/FFSE1704.JavaWeb
/FFSE1704009_LKH_Nhat/Quan_Ly_Nhan_Su/src/ffse1704/jsf/entity/NhanSu.java
UTF-8
2,278
2.265625
2
[]
no_license
package ffse1704.jsf.entity; import javax.faces.bean.ManagedBean; import javax.faces.bean.RequestScoped; import javax.validation.constraints.NotNull; import org.hibernate.validator.constraints.Range; @ManagedBean @RequestScoped public class NhanSu { private String id; @NotNull(message = "Tên Nhân Sự không được để trống") private String hoTen; @NotNull(message = "Năm Sinh không được để trống") @Range(min=1900, max=2000, message = "Năm Sinh chỉ từ 1900 đến 2000") private String namSinh; @NotNull(message = "Giới Tính không được để trống") private String gioiTinh; @NotNull(message = "Hộ Khẩu không được để trống") private String hoKhau; @NotNull(message = "Ảnh Đại Diện không được để trống") private String avatar; private String STT; public NhanSu() { super(); } public NhanSu(String id) { super(); this.id = id; } public NhanSu(String id, String hoTen, String namSinh, String gioiTinh, String hoKhau, String avatar, String sTT) { super(); this.id = id; this.hoTen = hoTen; this.namSinh = namSinh; this.gioiTinh = gioiTinh; this.hoKhau = hoKhau; this.avatar = avatar; this.STT = sTT; } public NhanSu(String id, String hoTen, String namSinh, String gioiTinh, String hoKhau, String avatar) { super(); this.id = id; this.hoTen = hoTen; this.namSinh = namSinh; this.gioiTinh = gioiTinh; this.hoKhau = hoKhau; this.avatar = avatar; } public String getSTT() { return STT; } public void setSTT(String sTT) { STT = sTT; } public String getId() { return id; } public void setId(String id) { this.id = id; } public String getHoTen() { return hoTen; } public void setHoTen(String hoTen) { this.hoTen = hoTen; } public String getNamSinh() { return namSinh; } public void setNamSinh(String namSinh) { this.namSinh = namSinh; } public String getGioiTinh() { return gioiTinh; } public void setGioiTinh(String gioiTinh) { this.gioiTinh = gioiTinh; } public String getHoKhau() { return hoKhau; } public void setHoKhau(String hoKhau) { this.hoKhau = hoKhau; } public String getAvatar() { return avatar; } public void setAvatar(String avatar) { this.avatar = avatar; } }
true
3d8ce7eea473e817df7a399fa665df977f1bf814
Java
jefflai108/JAVA
/HW1-clai24/HW1Solutions/MagicNumber.java
UTF-8
1,613
4.4375
4
[]
no_license
//MagicNumber.java //CS 107, Spring 2016 //SOLUTION to HW1, Task 1 // //This program calculates the "magic number" for a baseball team that //is leading its division, given as input the number of games the team //has WON so far, the number of games the second-place team has LOST so //far, and the total number of games scheduled in a season. import java.util.Scanner; public class MagicNumber { public static void main(String[] args) { //Initialize a Scanner object so we can collect input from the keyboard Scanner keyboard = new Scanner(System.in); //Collect user input: 1st place team city and team name as a String, //then 1st place wins, 2nd place losses, and total games as ints. System.out.print("Please enter the first place team's city and name: "); String firstPlaceTeam = keyboard.nextLine(); //need nextLine() here, not next() System.out.print("Please enter their number of WINS so far: "); int wins = keyboard.nextInt(); System.out.print("Please enter the number of LOSSES so far for the second place team: "); int losses = keyboard.nextInt(); System.out.print("Please enter the total number of games per team: "); int totalGames = keyboard.nextInt(); //Calculate the magic number for the first place team int magicNumber = totalGames - wins - losses + 1; //Output the result System.out.println(); System.out.println("The " + firstPlaceTeam + " have a magic number of " + magicNumber + "."); } }
true
6626a79c8ededdc08243a03d3dccca4e9a96d89e
Java
nkhunters/CaptchaApp
/app/src/main/java/com/codelaxy/qwertpoiuy/FirebaseMessaging/MyFirebaseMessagingService.java
UTF-8
1,093
2.5
2
[]
no_license
package com.codelaxy.qwertpoiuy.FirebaseMessaging; import com.google.firebase.messaging.FirebaseMessagingService; import com.google.firebase.messaging.RemoteMessage; public class MyFirebaseMessagingService extends FirebaseMessagingService { @Override public void onMessageReceived(RemoteMessage remoteMessage) { super.onMessageReceived(remoteMessage); String title = null, body = null; //if the message contains data payload //It is a map of custom keyvalues //we can read it easily if(remoteMessage.getData().size() > 0){ title = remoteMessage.getData().get("str_title"); body = remoteMessage.getData().get("str_body"); } //getting the title and the body String click_action = remoteMessage.getNotification().getClickAction(); MyNotificationManager.getInstance(this).displayNotification(remoteMessage.getNotification().getTitle(), remoteMessage.getNotification().getBody(), click_action); //then here we can use the title and body to build a notification } }
true
17df2c619b5dfd7917906ef00727a54892d7a9ff
Java
dinhhoi1102/Spring-hibernate-manytomany
/src/main/java/com/aht/controller/MainController.java
UTF-8
2,506
2.203125
2
[]
no_license
package com.aht.controller; import java.util.Collection; import java.util.List; import java.util.Optional; import java.util.Set; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.http.HttpStatus; import org.springframework.http.ResponseEntity; import org.springframework.web.bind.annotation.DeleteMapping; import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.PathVariable; import org.springframework.web.bind.annotation.PostMapping; import org.springframework.web.bind.annotation.RequestBody; import org.springframework.web.bind.annotation.RestController; import com.aht.entities.Developer; import com.aht.entities.Project; import com.aht.service.DeveloperService; import com.aht.service.ProjectService; @RestController public class MainController { @Autowired private DeveloperService developerService; @Autowired private ProjectService projectService; @GetMapping(value="/developers") public ResponseEntity<Collection<Developer>> getAllDeveloper(){ Collection<Developer> developers = developerService.getAllDeveloper(); System.out.println(developers); return new ResponseEntity<Collection<Developer>>(developers,HttpStatus.OK); } @GetMapping(value="/developers/{id}") public ResponseEntity<Optional<Developer>> getDeveloperById(@PathVariable int id){ return new ResponseEntity<Optional<Developer>>((developerService.findDeveloperById(id)),HttpStatus.OK); } @PostMapping(value="/developers") public ResponseEntity<String> createDeveloper(@RequestBody Developer dev){ developerService.createDeveloper(dev); return new ResponseEntity<String>("created",HttpStatus.OK); } @DeleteMapping(value="developers/{id}") public ResponseEntity<String> deleteDeveloper(@PathVariable int id){ developerService.deleteDeveloper(id); return new ResponseEntity<String>("deleted",HttpStatus.OK); } @GetMapping(value="/projects") public ResponseEntity<List<Project>> getAllProject(){ List<Project> developers = projectService.getAllProject(); System.out.println(developers); return new ResponseEntity<List<Project>>(developers,HttpStatus.OK); } ///tim kiem theo id project cac developer lam @GetMapping(value="/developersf/{oo}") public ResponseEntity<List<Developer>> getDeveloperDoProject(@PathVariable("oo") int id){ System.out.println(id); return new ResponseEntity<List<Developer>>(developerService.getDeveloperFollowProject(id),HttpStatus.OK); } }
true
18291215be1db422457ce279729cbadab4e9b812
Java
flywind2/joeis
/src/irvine/oeis/a122/A122186.java
UTF-8
428
2.671875
3
[]
no_license
package irvine.oeis.a122; import irvine.oeis.LinearRecurrence; /** * A122186 First row sum of the <code>4 X 4</code> matrix <code>M^n</code>, where <code>M={{10, 9, 7, 4}, {9, 8, 6, 3}, {7, 6, 4, 2}, {4, 3, 2, 1}}</code>. * @author Sean A. Irvine */ public class A122186 extends LinearRecurrence { /** Construct the sequence. */ public A122186() { super(new long[] {-1, -4, 21, 23}, new long[] {1, 30, 707, 16886}); } }
true
f34ad644d134ebdbf4c66016f8624739437eb669
Java
samdeniyi/armdemo
/app/src/main/java/com/samadeniyi/armdemo/Logout.java
UTF-8
562
2.40625
2
[]
no_license
package com.samadeniyi.armdemo; import com.firebase.client.Firebase; import com.firebase.client.FirebaseException; public class Logout { static public boolean logout(){ boolean isLoggedOut = true; try{ Firebase reference = new Firebase("https://armdemo-b8b6f.firebaseio.com/users"); reference.child(UserDetails.username).child("isLoggedIn").setValue(false); }catch(FirebaseException e){ System.out.println("" + e.toString()); isLoggedOut = false; } return isLoggedOut; } }
true
5f60a26c8fa95a2b3f08bf80f919e83a3034c680
Java
Refactula/1MLoC
/MicroFuturistic/src/main/java/refactula/micro/futuristic/LoadTestF.java
UTF-8
3,469
2.296875
2
[]
no_license
package refactula.micro.futuristic; import refactula.micro.futuristic.frontend_f.FrontendServiceF; import refactula.micro.futuristic.model.BillingDetails; import refactula.micro.futuristic.model.Credits; import refactula.micro.futuristic.model.Email; import refactula.micro.futuristic.model.Token; import refactula.micro.futuristic.model.Username; import refactula.micro.futuristic.utils.Future; import refactula.micro.futuristic.utils.Futures; import java.util.ArrayList; import java.util.List; import java.util.Random; import java.util.concurrent.ConcurrentHashMap; import java.util.concurrent.ConcurrentMap; import java.util.concurrent.CountDownLatch; import java.util.function.Supplier; public class LoadTestF { private final Random random; private final int usersAmount; private final int messagesAmount; private final FrontendServiceF frontend; private final Supplier<Username> usernameSupplier; private final Supplier<Email> emailSupplier; private final Supplier<BillingDetails> billingDetailsSupplier; public LoadTestF( Random random, int usersAmount, int messagesAmount, FrontendServiceF frontend, Supplier<Username> usernameSupplier, Supplier<Email> emailSupplier, Supplier<BillingDetails> billingDetailsSupplier) { this.random = random; this.usersAmount = usersAmount; this.messagesAmount = messagesAmount; this.frontend = frontend; this.usernameSupplier = usernameSupplier; this.emailSupplier = emailSupplier; this.billingDetailsSupplier = billingDetailsSupplier; } public void run() { ConcurrentMap<Username, Token> tokens = new ConcurrentHashMap<>(); List<Username> users = new ArrayList<>(); List<Future<Void>> allTokensReceived = new ArrayList<>(); for (int i = 0; i < usersAmount; i++) { Username username = usernameSupplier.get(); Email email = emailSupplier.get(); users.add(username); Future<Void> tokenReceived = frontend.register(username, email).flatMap(token -> { tokens.put(username, token); return frontend.setBillingDetails(username, token, billingDetailsSupplier.get()) .flatMap(afterDetails -> frontend.deposit(username, token, Credits.withAmount(messagesAmount))); }); allTokensReceived.add(tokenReceived); } Future<List<Void>> simulationFinished = Futures.transform(allTokensReceived).flatMap(tokensReceived -> { List<Future<Void>> allTransfersMade = new ArrayList<>(); for (int i = 0; i < messagesAmount; i++) { Username sender = users.get(random.nextInt(users.size())); Username receiver = users.get(random.nextInt(users.size())); Future<Void> transferMade = frontend.transfer(sender, tokens.get(sender), receiver, Credits.withAmount(1)); allTransfersMade.add(transferMade); } return Futures.transform(allTransfersMade); }); CountDownLatch latch = new CountDownLatch(1); simulationFinished.map(done -> { latch.countDown(); return null; }); try { latch.await(); } catch (InterruptedException e) { Thread.currentThread().interrupt(); } } }
true
c11335c2fa8f9efb1e4f8b7be814cef30e049cb1
Java
UCLLWebontwikkeling3-project-2021/pageobjectpairprogramming-Wullaert-Jaison
/test/java/ContactPage.java
UTF-8
2,680
2.359375
2
[]
no_license
import org.openqa.selenium.By; import org.openqa.selenium.WebDriver; import org.openqa.selenium.WebElement; import org.openqa.selenium.support.FindBy; import java.util.ArrayList; import java.util.List; import static org.junit.Assert.assertEquals; public class ContactPage extends Page{ /** * @Author Yarne Vandenplas * @Author Jaison Wullaert */ @FindBy(id="firstName") private WebElement firstNameField; @FindBy(id="lastName") private WebElement lastNameField; @FindBy(id="date") private WebElement dateField; @FindBy(id="time") private WebElement timeField; @FindBy(id="gsm") private WebElement gsmField; @FindBy(id="email") private WebElement emailField; @FindBy(id="submitContact") private WebElement signUpButton; public ContactPage(WebDriver driver){ super(driver); this.driver.get(getPath()+ "?command=Contacts"); } public void setFirstName(String firstname){ firstNameField.clear(); firstNameField.sendKeys(firstname); } public void setLastName(String lastname){ lastNameField.clear(); lastNameField.sendKeys(lastname); } public void setDate(String date){ dateField.clear(); dateField.sendKeys(date); } public void setTime(String time){ timeField.clear(); timeField.sendKeys(time); } public void setEmail(String email){ emailField.clear(); emailField.sendKeys(email); } public void setGSM(String gsm){ gsmField.clear(); gsmField.sendKeys(gsm); } public ContactPage submitButton(){ WebElement button=driver.findElement(By.id("submitContact")); button.click(); return this; } public String getTitle(){ String title= driver.getTitle(); return title; } public Boolean containsUserWithName(String name){ ArrayList<WebElement> listItems=(ArrayList<WebElement>) driver.findElements(By.cssSelector("table tr")); boolean found=false; for (WebElement listItem:listItems) { if (listItem.getText().contains(name)) { found=true; } } return found; } public List<String> getErrorList(){ List<WebElement> test=driver.findElements(By.cssSelector("div.alert-danger ul li")); List<String> errors= new ArrayList<>(); for(WebElement error : test){ errors.add(error.getText()); } return errors; } public Boolean hasError(String error){ if(getErrorList().contains(error)){return true;} else{return false;} } }
true
4d68178ce4663f9373d8085d2c916896f3e30a85
Java
muhammad-zaidi/ICS3U1-Muhammad
/ICS3U.java/src/edu/hdsb/gwss/zaidi/ics3u/u5/PatternMatching.java
UTF-8
3,402
3.484375
3
[]
no_license
//// // * Name: Muhammad Zaidi // * Date: November 6, 2018 // * Version: v0.01 // * Description: check if words have the same structure package edu.hdsb.gwss.zaidi.ics3u.u5; import java.io.File; import java.io.FileNotFoundException; import java.io.PrintWriter; import java.util.Scanner; import java.util.StringTokenizer; /** * * @author 1zaidisye */ public class PatternMatching { /** * @param args the command line arguments */ public static void main(String[] args) throws FileNotFoundException { //CONSTANTS //VARIABLE //Listing variables String str; String firstWord; String secondWord; boolean makesSense; boolean isVowel; boolean isVowel2; //INPUT //OBJECT File file = new File("DATA31.txt"); //Writing out objects and scanners File Outfile = new File("OUT31.txt"); PrintWriter output2 = new PrintWriter(Outfile); Scanner input = new Scanner(file); StringTokenizer st; //SPLASH MESSAGE //INPUT //PROCESSING while (input.hasNext()) { //While there are more lines in the input, it will keep going str = input.nextLine(); st = new StringTokenizer(str); firstWord = st.nextToken(); //First word is the first token secondWord = st.nextToken(); //Second word is the second token firstWord = firstWord.toLowerCase(); secondWord = secondWord.toLowerCase(); makesSense = firstWord.length() == secondWord.length(); //If the first word is equal to the second word, it will continue, but if it is not, then there is no point in executing rest of code. if (makesSense) { for (int i = 0; i < firstWord.length(); i++) { //Checking both words if they have vowels at the same spot using switch/case switch (firstWord.charAt(i)) { case 'a': case 'e': case 'i': case 'o': case 'u': isVowel = true; break; default: isVowel = false; break; } switch (secondWord.charAt(i)) { case 'a': case 'e': case 'i': case 'o': case 'u': isVowel2 = true; break; default: isVowel2 = false; break; } if (isVowel != isVowel2) { //So if they don't have vowels at same spot, it doesnt make sense so it's false makesSense = false; } else { makesSense = true; } } } if (makesSense) { //If makes sense, then prints same, else it prints different System.out.println("same"); output2.println("same"); } else { System.out.println("different"); output2.println("different"); } } output2.close(); } //OUTPUT }
true
fd5bf9cf7b4d75988728f08b2542b66917481c83
Java
mcnameel/mcnameeioTest
/main/java/edu/xavier/csci260/atinlay/dal/TimeOff/TimeOffResponseDAOImpl.java
UTF-8
2,299
2.28125
2
[ "MIT" ]
permissive
package edu.xavier.csci260.atinlay.dal.TimeOff; import edu.xavier.csci260.atinlay.domain.TimeOff.TimeOffResponse; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.jdbc.core.JdbcTemplate; import java.util.List; /** * class ___ is a member of the OOOtracker_services project. * <p> * Created by Luke on 4/24/2017. */ public class TimeOffResponseDAOImpl implements TimeOffResponseDAO { @Autowired private JdbcTemplate jdbcTemplate; /* Integer cnt = jdbcTemplate.queryForObject( "SELECT count(*) FROM customer_pool WHERE id = ? AND level = 13)", Integer.class, id); return cnt != null && cnt > 0 */ @Override public List<TimeOffResponse> getTimeOffResById(Long id) { final String sql = "SELECT * FROM timeOffResponses WHERE id = ?"; return (List<TimeOffResponse>) jdbcTemplate.query( sql, new Object[]{ id }, new ResponseRowMapper() ); } @Override public List<TimeOffResponse> getTimeOffResByManager(String manager) { final String sql = "SELECT * FROM timeOffResponses WHERE manager = ?"; return (List<TimeOffResponse>) jdbcTemplate.query( sql, new Object[]{ manager }, new ResponseRowMapper() ); } @Override public List<TimeOffResponse> getAllTimeOffRes() { final String sql = "SELECT * FROM timeOffResponses"; return (List<TimeOffResponse>) jdbcTemplate.query(sql, new ResponseRowMapper()); } @Override public void createTimeOffResponse(TimeOffResponse timeOffResponse) { final String sql = "INSERT INTO timeOffResponses (id, manager, reason, description, approved) VALUES (?,?,?,?,?)"; jdbcTemplate.update(sql, timeOffResponse.getId(), timeOffResponse.getManager(), timeOffResponse.getReason(), timeOffResponse.getDescription(), timeOffResponse.getApproved() ); } @Override public void removeTimeOffResponse(TimeOffResponse timeOffResponse) { final String sqlStmt = "DELETE FROM timeOffResponses WHERE id = ?"; jdbcTemplate.update(sqlStmt, timeOffResponse.getId()); } }
true
10a61a81d173582ed5797f965ca156905daca688
Java
ariester/bank-scraper
/src/main/java/pl/astedler/bankscraper/scraper/mbank/page/LoginPage.java
UTF-8
3,001
2.234375
2
[]
no_license
package pl.astedler.bankscraper.scraper.mbank.page; import com.fasterxml.jackson.databind.JsonNode; import com.fasterxml.jackson.databind.ObjectMapper; import org.apache.http.client.fluent.Request; import org.apache.http.entity.StringEntity; import pl.astedler.bankscraper.exception.InvalidCredentialsException; import pl.astedler.bankscraper.scraper.mbank.jsonHelper.LoginJsonNode; import pl.astedler.bankscraper.scraper.mbank.request.RequestHeaders; import pl.astedler.bankscraper.scraper.mbank.request.RequestHelper; import pl.astedler.bankscraper.scraper.mbank.response.LoginResponse; import pl.astedler.bankscraper.scraper.model.UserCredentials; import pl.astedler.bankscraper.scraper.utils.RegexUtils; import java.io.IOException; public class LoginPage { private static final String SEED_REGEX = "app\\.initialize\\('(.*?)'"; //seed from app.initialize('seed' private static final String INVALID_CREDENTIALS_MESSAGE = "Nieprawidłowy identyfikator lub hasło."; private static final ObjectMapper mapper = new ObjectMapper(); private LoginPage() { } public static LoginResponse login(UserCredentials userCredentials) throws IOException, InvalidCredentialsException { Request postRequest = preparePostRequest(userCredentials); String responseContent = RequestHelper.postRequestAndGetResponseText(postRequest); JsonNode node = extractJson(responseContent); LoginResponse loginResponse = new LoginResponse(node); if (!loginResponse.isSuccessful()) handleError(loginResponse); return loginResponse; } private static Request preparePostRequest(UserCredentials userCredentials) throws IOException { String json = prepareJson(userCredentials); return Request.Post(MBankUrl.LOGIN_REQUEST_URL) .setHeaders(RequestHeaders.COMMON_HEADERS) .body(new StringEntity(json)); } private static String prepareJson(UserCredentials userCredentials) throws IOException { LoginJsonNode loginJson = new LoginJsonNode() .putUserCredentials(userCredentials) .putSeed(getSeed()) .putScenario("Default") .addUWAdditionalParamsNode() .addAdditionalFields(); return mapper.writeValueAsString(loginJson.getNode()); } private static String getSeed() throws IOException { String htmlPage = RequestHelper.getPage(MBankUrl.LOGIN_PAGE_URL); return RegexUtils.getFirstMatchOrCrash(SEED_REGEX, htmlPage); } private static JsonNode extractJson(String response) throws IOException { return mapper.readTree(response); } private static void handleError(LoginResponse loginResponse) throws InvalidCredentialsException { String error = loginResponse.getErrorMessageTitle(); if (error.equals(INVALID_CREDENTIALS_MESSAGE)) throw new InvalidCredentialsException(error); else throw new RuntimeException(error); } }
true
9ac6fb56dcd3f0ac25a72046afbc4a1a8472380e
Java
cooperbell/cooperbell_swd
/oral_exam2/18-20_MazeTraversal_Hard/src/MazeTraversalTest.java
UTF-8
3,255
3.3125
3
[]
no_license
/** * Driver class for the maze traversal algorithm */ public class MazeTraversalTest { /** * The 2D array maze */ public static char[][] maze = new char[12][12]; static { maze[0][0] = '#'; maze[0][1] = '#'; maze[0][2] = '#'; maze[0][3] = '#'; maze[0][4] = '#'; maze[0][5] = '#'; maze[0][6] = '#'; maze[0][7] = '#'; maze[0][8] = '#'; maze[0][9] = '#'; maze[0][10] = '#'; maze[0][11] = '#'; maze[1][0] = '#'; maze[1][1] = '.'; maze[1][2] = '.'; maze[1][3] = '.'; maze[1][4] = '#'; maze[1][5] = '.'; maze[1][6] = '.'; maze[1][7] = '.'; maze[1][8] = '.'; maze[1][9] = '.'; maze[1][10] = '.'; maze[1][11] = '#'; maze[2][0] = '.'; maze[2][1] = '.'; maze[2][2] = '#'; maze[2][3] = '.'; maze[2][4] = '#'; maze[2][5] = '.'; maze[2][6] = '#'; maze[2][7] = '#'; maze[2][8] = '#'; maze[2][9] = '#'; maze[2][10] = '.'; maze[2][11] = '#'; maze[3][0] = '#'; maze[3][1] = '#'; maze[3][2] = '#'; maze[3][3] = '.'; maze[3][4] = '#'; maze[3][5] = '.'; maze[3][6] = '.'; maze[3][7] = '.'; maze[3][8] = '.'; maze[3][9] = '#'; maze[3][10] = '.'; maze[3][11] = '#'; maze[4][0] = '#'; maze[4][1] = '.'; maze[4][2] = '.'; maze[4][3] = '.'; maze[4][4] = '.'; maze[4][5] = '#'; maze[4][6] = '#'; maze[4][7] = '#'; maze[4][8] = '.'; maze[4][9] = '#'; maze[4][10] = '.'; maze[4][11] = '#'; maze[5][0] = '#'; maze[5][1] = '#'; maze[5][2] = '#'; maze[5][3] = '#'; maze[5][4] = '.'; maze[5][5] = '#'; maze[5][6] = '.'; maze[5][7] = '#'; maze[5][8] = '.'; maze[5][9] = '#'; maze[5][10] = '.'; maze[5][11] = '.'; maze[6][0] = '#'; maze[6][1] = '.'; maze[6][2] = '.'; maze[6][3] = '#'; maze[6][4] = '.'; maze[6][5] = '#'; maze[6][6] = '.'; maze[6][7] = '#'; maze[6][8] = '.'; maze[6][9] = '#'; maze[6][10] = '.'; maze[6][11] = '#'; maze[7][0] = '#'; maze[7][1] = '#'; maze[7][2] = '.'; maze[7][3] = '#'; maze[7][4] = '.'; maze[7][5] = '#'; maze[7][6] = '.'; maze[7][7] = '#'; maze[7][8] = '.'; maze[7][9] = '#'; maze[7][10] = '.'; maze[7][11] = '#'; maze[8][0] = '#'; maze[8][1] = '.'; maze[8][2] = '.'; maze[8][3] = '.'; maze[8][4] = '.'; maze[8][5] = '.'; maze[8][6] = '.'; maze[8][7] = '.'; maze[8][8] = '.'; maze[8][9] = '#'; maze[8][10] = '.'; maze[8][11] = '#'; maze[9][0] = '#'; maze[9][1] = '#'; maze[9][2] = '#'; maze[9][3] = '#'; maze[9][4] = '#'; maze[9][5] = '#'; maze[9][6] = '.'; maze[9][7] = '#'; maze[9][8] = '#'; maze[9][9] = '#'; maze[9][10] = '.'; maze[9][11] = '#'; maze[10][0] = '#'; maze[10][1] = '.'; maze[10][2] = '.'; maze[10][3] = '.'; maze[10][4] = '.'; maze[10][5] = '.'; maze[10][6] = '.'; maze[10][7] = '#'; maze[10][8] = '.'; maze[10][9] = '.'; maze[10][10] = '.'; maze[10][11] = '#'; maze[11][0] = '#'; maze[11][1] = '#'; maze[11][2] = '#'; maze[11][3] = '#'; maze[11][4] = '#'; maze[11][5] = '#'; maze[11][6] = '#'; maze[11][7] = '#'; maze[11][8] = '#'; maze[11][9] = '#'; maze[11][10] = '#'; maze[11][11] = '#'; } /** * Instantiates MazeSolver object and runs the maze traversal method * @param args command line args */ public static void main(String[] args) { MazeSolver mazeSolver = new MazeSolver(maze, 2,0); mazeSolver.printMaze(); mazeSolver.mazeTraversal(2, 0); } }
true
effb997678f36f4f1bc1769e7550e82f4900c38e
Java
qiuwuhui/TestApp
/app/src/main/java/com/baolinetworktechnology/shejiquan/fragment/CollectCaseFragment.java
UTF-8
3,556
2.015625
2
[]
no_license
package com.baolinetworktechnology.shejiquan.fragment; import android.app.AlertDialog; import android.os.Bundle; import android.os.Handler; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.view.View.OnClickListener; import android.widget.AdapterView; import android.widget.TextView; import android.widget.AdapterView.OnItemLongClickListener; import com.baolinetworktechnology.shejiquan.R; import com.baolinetworktechnology.shejiquan.app.SJQApp; import com.baolinetworktechnology.shejiquan.view.CaseListView; import com.guojisheng.koyview.ExplosionField; /** * 案例收藏 * * @author JiSheng.Guo * */ public class CollectCaseFragment extends BaseFragment { private boolean mIsDeleteMode;//是否进入删除模式 private CaseListView mCaseListView; View view; @Override public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { super.onCreateView(inflater, container, savedInstanceState); if(view==null){ view = View.inflate(getActivity(), R.layout.fragment_collect_case, null); mCaseListView = (CaseListView) view.findViewById(R.id.caseListView); // mCaseListView.setChangData(true, // ExplosionField.attach2Window(getActivity())); // // mCaseListView.getRefreshableView().setOnItemLongClickListener( // new OnItemLongClickListener() { // // @Override // public boolean onItemLongClick(AdapterView<?> parent, // final View view, final int position, long id) { // // View dialogView = View.inflate(getActivity(), // R.layout.dialog_collect, null); // TextView titl = (TextView) dialogView // .findViewById(R.id.dialog_title); // titl.setText("确定要取消收藏?"); // final AlertDialog ad = new AlertDialog.Builder( // getActivity()).setView(dialogView).show(); // dialogView.findViewById(R.id.dialog_cancel) // .setOnClickListener(new OnClickListener() { // // @Override // public void onClick(View v) { // // ad.cancel(); // } // // }); // dialogView.findViewById(R.id.dialog_ok) // .setOnClickListener(new OnClickListener() { // // @Override // public void onClick(View v) { // mCaseListView // .delete(position - 1, view); // ad.cancel(); // } // }); // // return true; // } // }); } return view; } boolean first = true; @Override public void onResume() { super.onResume(); if (first) { new Handler().postDelayed(new Runnable() { @Override public void run() { if (SJQApp.user == null) return; mCaseListView.setUserGuid(SJQApp.user.guid, true); } }, 300); first = false; } else { if (SJQApp.isRrefresh) { if (SJQApp.user == null) return; mCaseListView.setUserGuid(SJQApp.user.guid, true); //SJQApp.isRrefresh=false; } } } // 设置是否编辑 public void setChangData(boolean is) { mCaseListView.setChangData(is); } // 设置是否编辑 public void setChangData(boolean is, ExplosionField mExplosionField) { // TODO Auto-generated method stub mCaseListView.setChangData(is, mExplosionField); } public void shuaxin(){ mCaseListView.setRefreshing(); } //是否进入批量删除模式 public void DeleteMode(boolean isdelete){ mIsDeleteMode = isdelete; mCaseListView.setDeleteMode(mIsDeleteMode); } public void batchDelete(){ mCaseListView.bitchdelete(); } }
true
99a2a8b03e2039ff8671a28cda8debd27c7748b6
Java
bellmit/zycami-ded
/src/main/java/d/v/c/t0/j0$b.java
UTF-8
1,705
1.921875
2
[]
no_license
/* * Decompiled with CFR 0.151. */ package d.v.c.t0; import com.zhiyun.cama.publish.UploadCEMediaInfo; import d.v.c.t0.j0; import java.io.Serializable; import java.util.HashMap; public class j0$b { private final HashMap a; public j0$b(long l10, UploadCEMediaInfo uploadCEMediaInfo) { HashMap<String, Object> hashMap; this.a = hashMap = new HashMap<String, Object>(); Serializable serializable = l10; String string2 = "templeteId"; hashMap.put(string2, serializable); if (uploadCEMediaInfo != null) { hashMap.put("mediaArr", uploadCEMediaInfo); return; } super("Argument \"mediaArr\" is marked as non-null but was passed a null value."); throw serializable; } public j0$b(j0 object) { HashMap hashMap; this.a = hashMap = new HashMap(); object = j0.a((j0)object); hashMap.putAll(object); } public j0 a() { HashMap hashMap = this.a; j0 j02 = new j0(hashMap, null); return j02; } public UploadCEMediaInfo b() { return (UploadCEMediaInfo)this.a.get("mediaArr"); } public long c() { return (Long)this.a.get("templeteId"); } public j0$b d(UploadCEMediaInfo object) { if (object != null) { this.a.put("mediaArr", object); return this; } object = new IllegalArgumentException("Argument \"mediaArr\" is marked as non-null but was passed a null value."); throw object; } public j0$b e(long l10) { HashMap hashMap = this.a; Long l11 = l10; hashMap.put("templeteId", l11); return this; } }
true
633740a48f66aedb1d14a42f32ca133ac8a106fe
Java
yuenkin/gadget
/src/main/java/com/hw/pps/gadget/chainengine/model/ExitInfo.java
UTF-8
738
1.960938
2
[]
no_license
/* * 文件名:ExitInfo.java * 版权:Copyright by www.yuenkin.com * 描述: * 修改人:Administrator * 修改时间:2018年3月2日 * 跟踪单号: * 修改单号: * 修改内容: */ package com.hw.pps.gadget.chainengine.model; import javax.xml.bind.annotation.XmlAccessType; import javax.xml.bind.annotation.XmlAccessorType; import javax.xml.bind.annotation.XmlElement; import javax.xml.bind.annotation.XmlRootElement; import lombok.Getter; import lombok.Setter; @Getter @Setter @XmlRootElement(name = "exitInfo") @XmlAccessorType(XmlAccessType.FIELD) public class ExitInfo { @XmlElement(name = "exitName") private String exitName; @XmlElement(name = "value") private String value; }
true
ea31ba2624cde98f125a7c02e896bbcbe5f1b5ef
Java
surila06/petrol_pump
/src/main/java/com/imagegrafia/petrolpump/controller/TotalizerController.java
UTF-8
668
1.945313
2
[]
no_license
package com.imagegrafia.petrolpump.controller; import java.util.List; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RestController; import com.imagegrafia.petrolpump.entity.Totalizer; import com.imagegrafia.petrolpump.service.TotalizerService; @RestController @RequestMapping("/") public class TotalizerController { @Autowired private TotalizerService totalizerService; @GetMapping public List<Totalizer> getTotalizerList() { return totalizerService.getAllList(); } }
true
438e5aeb4c47c90ac0b954420eb0eecff559ac52
Java
KevinOrtman/tsquery
/src/net/tsquery/model/Tag.java
UTF-8
4,362
2.375
2
[ "Apache-2.0" ]
permissive
/* * Copyright 2011 Facebook, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ /* Copyright 2013 Kevin Ortman * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package net.tsquery.model; import net.tsquery.data.hbase.IDMap; import java.util.Comparator; public class Tag { public ID keyID; public ID valueID; public String key = ""; public String value = ""; private static Comparator<Tag> keyComparator = new Comparator<Tag>() { @Override public int compare(Tag t1, Tag t2) { return t1.keyID.compareTo(t2.keyID); } }; private static class TagsArrayComparator implements Comparator<TagsArray> { private int[] map = new int[0]; private void ensureMapLength(int length) { if (length > map.length) { map = new int[length]; } } @Override public int compare(TagsArray tlist1, TagsArray tlist2) { // first set mapping between the two lists TagsArray shortList = tlist1; TagsArray longList = tlist2; if (tlist1.length() > tlist2.length()) { shortList = tlist2; longList = tlist1; } ensureMapLength(shortList.length()); // do the mapping for (int i = 0; i < shortList.length(); i++) { map[i] = longList.binarySearch(shortList.getOrdered(i)); } for (int i = 0; i < shortList.length(); i++) { if (map[i] < 0) { // skip this tag, as it doesn't exist in the other list continue; } int tagCmp = shortList.getOrdered(i).valueID.compareTo(longList .get(map[i]).valueID); if (tagCmp != 0) { return tagCmp; } } return 0; } } private void loadStringFields(IDMap idMap) { try { key = this.keyID.isNull() ? "NULL" : idMap.getTag(this.keyID); value = this.valueID.isNull() ? "NULL" : idMap .getTagValue(this.valueID); } catch (Exception e) { e.printStackTrace(); } } public Tag(byte[] rawKeyID, byte[] rawValueID, IDMap idMap) { this.keyID = new ID(rawKeyID); this.valueID = new ID(rawValueID); loadStringFields(idMap); } public Tag(ID keyID, ID valueID, IDMap idMap) { this.keyID = keyID; this.valueID = valueID; loadStringFields(idMap); } public static Comparator<TagsArray> arrayComparator() { // we need to create a separate instance because the comparator is // not thread safe, as it needs the temporary storage array return new TagsArrayComparator(); } @Override public String toString() { return "(" + key + "[" + keyID + "]:" + value + "[" + valueID + "])"; } public static String join(String glue, Tag[] tags) { String ret = ""; for (int i = 0; i < tags.length; i++) { if (i > 0) { ret += glue; } ret += tags[i].toString(); } return ret; } public static Comparator<Tag> keyComparator() { return keyComparator; } }
true
aa6627876874a63350a38fea9886b365aec8e515
Java
VadimYanovskij/SenlaCourses
/src/Task1/Task1.java
UTF-8
1,733
3.734375
4
[]
no_license
package Task1; // Создать программу, которая будет сообщать, является ли целое число, введенное пользователем, // чётным или нечётным, простым или составным. Если пользователь введёт не целое число, // то сообщать ему об ошибке. import java.io.IOException; import java.util.Scanner; public class Task1 { public static void main(String[] args) { boolean notOK = true; boolean isComposite = false; Scanner in = new Scanner(System.in); do { try { System.out.print("Введите число : "); int number = in.nextInt(); if (number % 2 == 0) System.out.println("Число " + number + " чётное"); else System.out.println("Число " + number + " нечётное"); for (int i = 2; i < number; i++) { if (number % i == 0) { isComposite = true; break; } } if (isComposite) System.out.println("Число " + number + " составное"); else System.out.println("Число " + number + " простое"); notOK = false; } catch (Exception e) { System.out.println("Введённые данные не являются целым числом"); in.nextLine(); } } while (notOK); } }
true
6df6c6635972c31c623863bf83c88eb74ebc5e84
Java
hetaoo/Janus
/janus-sdk/src/main/java/org/xujin/janus/damon/Server.java
UTF-8
382
2.015625
2
[]
no_license
package org.xujin.janus.damon; import org.xujin.janus.damon.idle.IIdleHandler; import java.util.Map; public interface Server { public void start(int port, Map processerMap, int readIdleTime, IIdleHandler readIdleHandler, int writeIdleTime, IIdleHandler writeIdleHandler, int allIdleTime, IIdleHandler allIdleHandler) throws Exception; public void stop() throws Exception; }
true
144881efb0ca2b543ff977ab07b42660563d3715
Java
Gerigo/BuildsAndDrinks
/src/main/java/be/home/repositories/IPersonRepository.java
UTF-8
205
1.625
2
[]
no_license
package be.home.repositories; import be.home.domain.Personne; import org.springframework.data.jpa.repository.JpaRepository; public interface IPersonRepository extends JpaRepository<Personne, String> { }
true
68e2ea4e2fbe115ae10c880bcad8fc19f0e06727
Java
timgle/utilcode
/mmall-facade/src/main/java/com/xyl/mmall/backend/vo/InvoiceInOrdSupplierVO.java
UTF-8
2,954
2.109375
2
[]
no_license
package com.xyl.mmall.backend.vo; import java.io.Serializable; import java.math.BigDecimal; import com.netease.print.daojar.meta.annotation.AnnonOfField; import com.xyl.mmall.order.enums.InvoiceInOrdSupplierState; /** * @author dingmingliang * */ public class InvoiceInOrdSupplierVO implements Serializable { /** * */ private static final long serialVersionUID = 20140909L; @AnnonOfField(desc = "订单id", primary = true, primaryIndex = 0) private long orderId; @AnnonOfField(desc = "收件人-姓名", type = "VARCHAR(16)") private String consigneeName; @AnnonOfField(desc = "收件人-电话", type = "VARCHAR(32)") private String consigneePhone = ""; @AnnonOfField(desc = "抬头", type = "VARCHAR(32)") private String title; /** * 详细地址 */ private String fullAddress; /** * 商品 */ private String goods; /** * 下单时间 */ private String orderDate; @AnnonOfField(desc = "快递号", type = "VARCHAR(32)") private String barCode; @AnnonOfField(desc = "快递公司", type = "VARCHAR(16)") private String expressCompanyName; @AnnonOfField(desc = "发票金额") private BigDecimal cash; @AnnonOfField(desc = "用户id", policy = true) private long userId; @AnnonOfField(desc = "状态") private InvoiceInOrdSupplierState state; public InvoiceInOrdSupplierState getState() { return state; } public void setState(InvoiceInOrdSupplierState state) { this.state = state; } public long getOrderId() { return orderId; } public void setOrderId(long orderId) { this.orderId = orderId; } public String getConsigneeName() { return consigneeName; } public void setConsigneeName(String consigneeName) { this.consigneeName = consigneeName; } public String getConsigneePhone() { return consigneePhone; } public void setConsigneePhone(String consigneePhone) { this.consigneePhone = consigneePhone; } public String getTitle() { return title; } public void setTitle(String title) { this.title = title; } public String getFullAddress() { return fullAddress; } public void setFullAddress(String fullAddress) { this.fullAddress = fullAddress; } public String getGoods() { return goods; } public void setGoods(String goods) { this.goods = goods; } public String getOrderDate() { return orderDate; } public void setOrderDate(String orderDate) { this.orderDate = orderDate; } public String getBarCode() { return barCode; } public void setBarCode(String barCode) { this.barCode = barCode; } public String getExpressCompanyName() { return expressCompanyName; } public void setExpressCompanyName(String expressCompanyName) { this.expressCompanyName = expressCompanyName; } public BigDecimal getCash() { return cash; } public void setCash(BigDecimal cash) { this.cash = cash; } public long getUserId() { return userId; } public void setUserId(long userId) { this.userId = userId; } }
true
f7e76b068de1045781b1e1f9e0160fddd69f46c5
Java
spring-projects/spring-kafka
/spring-kafka/src/main/java/org/springframework/kafka/listener/ListenerUtils.java
UTF-8
7,768
1.875
2
[ "Apache-2.0", "LicenseRef-scancode-unknown-license-reference" ]
permissive
/* * Copyright 2017-2023 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.springframework.kafka.listener; import java.io.ByteArrayInputStream; import java.io.IOException; import java.io.ObjectInputStream; import java.io.ObjectStreamClass; import java.util.function.Supplier; import org.apache.kafka.clients.consumer.ConsumerRecord; import org.apache.kafka.clients.consumer.OffsetAndMetadata; import org.springframework.core.log.LogAccessor; import org.springframework.kafka.support.serializer.DeserializationException; import org.springframework.kafka.support.serializer.SerializationUtils; import org.springframework.lang.Nullable; import org.springframework.util.Assert; import org.springframework.util.backoff.BackOff; import org.springframework.util.backoff.BackOffExecution; /** * Listener utilities. * * @author Gary Russell * @author Francois Rosiere * @author Antonio Tomac * @since 2.0 * */ public final class ListenerUtils { private ListenerUtils() { } private static final int DEFAULT_SLEEP_INTERVAL = 100; private static final int SMALL_SLEEP_INTERVAL = 10; private static final long SMALL_INTERVAL_THRESHOLD = 500; /** * Determine the type of the listener. * @param listener the listener. * @return the {@link ListenerType}. */ public static ListenerType determineListenerType(Object listener) { Assert.notNull(listener, "Listener cannot be null"); ListenerType listenerType; if (listener instanceof AcknowledgingConsumerAwareMessageListener || listener instanceof BatchAcknowledgingConsumerAwareMessageListener) { listenerType = ListenerType.ACKNOWLEDGING_CONSUMER_AWARE; } else if (listener instanceof ConsumerAwareMessageListener || listener instanceof BatchConsumerAwareMessageListener) { listenerType = ListenerType.CONSUMER_AWARE; } else if (listener instanceof AcknowledgingMessageListener || listener instanceof BatchAcknowledgingMessageListener) { listenerType = ListenerType.ACKNOWLEDGING; } else if (listener instanceof GenericMessageListener) { listenerType = ListenerType.SIMPLE; } else { throw new IllegalArgumentException("Unsupported listener type: " + listener.getClass().getName()); } return listenerType; } /** * Extract a {@link DeserializationException} from the supplied header name, if * present. * @param record the consumer record. * @param headerName the header name. * @param logger the logger for logging errors. * @return the exception or null. * @since 2.3 * @deprecated in favor of * {@link SerializationUtils#getExceptionFromHeader(ConsumerRecord, String, LogAccessor)}. */ @Deprecated @Nullable public static DeserializationException getExceptionFromHeader(final ConsumerRecord<?, ?> record, String headerName, LogAccessor logger) { return SerializationUtils.getExceptionFromHeader(record, headerName, logger); } /** * Convert a byte array containing a serialized {@link DeserializationException} to the * {@link DeserializationException}. * @param logger a log accessor to log errors. * @param value the bytes. * @return the exception or null if deserialization fails. * @since 2.8.1 * @deprecated in favor of * {@link SerializationUtils#getExceptionFromHeader(ConsumerRecord, String, LogAccessor)} or * {@link SerializationUtils#byteArrayToDeserializationException(LogAccessor, org.apache.kafka.common.header.Header)}. */ @Deprecated @Nullable public static DeserializationException byteArrayToDeserializationException(LogAccessor logger, byte[] value) { try { ObjectInputStream ois = new ObjectInputStream(new ByteArrayInputStream(value)) { boolean first = true; @Override protected Class<?> resolveClass(ObjectStreamClass desc) throws IOException, ClassNotFoundException { if (this.first) { this.first = false; Assert.state(desc.getName().equals(DeserializationException.class.getName()), "Header does not contain a DeserializationException"); } return super.resolveClass(desc); } }; return (DeserializationException) ois.readObject(); } catch (IOException | ClassNotFoundException | ClassCastException e) { logger.error(e, "Failed to deserialize a deserialization exception"); return null; } } /** * Sleep according to the {@link BackOff}; when the {@link BackOffExecution} returns * {@link BackOffExecution#STOP} sleep for the previous backOff. * @param backOff the {@link BackOff} to create a new {@link BackOffExecution}. * @param executions a thread local containing the {@link BackOffExecution} for this * thread. * @param lastIntervals a thread local containing the previous {@link BackOff} * interval for this thread. * @param container the container or parent container. * @throws InterruptedException if the thread is interrupted. * @since 2.7 */ public static void unrecoverableBackOff(BackOff backOff, ThreadLocal<BackOffExecution> executions, ThreadLocal<Long> lastIntervals, MessageListenerContainer container) throws InterruptedException { BackOffExecution backOffExecution = executions.get(); if (backOffExecution == null) { backOffExecution = backOff.start(); executions.set(backOffExecution); } Long interval = backOffExecution.nextBackOff(); if (interval == BackOffExecution.STOP) { interval = lastIntervals.get(); if (interval == null) { interval = Long.valueOf(0); } } lastIntervals.set(interval); if (interval > 0) { stoppableSleep(container, interval); } } /** * Sleep for the desired timeout, as long as the container continues to run. * @param container the container. * @param interval the timeout. * @throws InterruptedException if the thread is interrupted. * @since 2.7 */ public static void stoppableSleep(MessageListenerContainer container, long interval) throws InterruptedException { conditionalSleep(container::isRunning, interval); } /** * Sleep for the desired timeout, as long as shouldSleepCondition supplies true. * @param shouldSleepCondition to. * @param interval the timeout. * @throws InterruptedException if the thread is interrupted. * @since 3.0.9 */ public static void conditionalSleep(Supplier<Boolean> shouldSleepCondition, long interval) throws InterruptedException { long timeout = System.currentTimeMillis() + interval; long sleepInterval = interval > SMALL_INTERVAL_THRESHOLD ? DEFAULT_SLEEP_INTERVAL : SMALL_SLEEP_INTERVAL; do { Thread.sleep(sleepInterval); if (!shouldSleepCondition.get()) { break; } } while (System.currentTimeMillis() < timeout); } /** * Create a new {@link OffsetAndMetadata} using the given container and offset. * @param container a container. * @param offset an offset. * @return an offset and metadata. * @since 2.8.6 */ public static OffsetAndMetadata createOffsetAndMetadata(MessageListenerContainer container, long offset) { final OffsetAndMetadataProvider metadataProvider = container.getContainerProperties() .getOffsetAndMetadataProvider(); if (metadataProvider != null) { return metadataProvider.provide(new DefaultListenerMetadata(container), offset); } return new OffsetAndMetadata(offset); } }
true
e8c5bfc5de673706ffc74659f936215afbdc42ac
Java
beetrootfarmer/Chapter07_inheritance
/src/ch07_1_inheritance/Computer.java
UTF-8
295
2.828125
3
[]
no_license
package ch07_1_inheritance; public class Computer extends Calculator { @Override //annotation double areaCircle(double r) { System.out.println("Computer 객체의 areaCircle() 실행 "); return Math.PI * r * 1000; // A a1 = new A(); // ai. } } class A extends Object { }
true
930a98ecaed07fcdb0818d0d4a4a65bc5a9a72c4
Java
erkineren/java-spring-rest-api
/src/main/java/com/erkineren/demo/persistence/model/entity/User.java
UTF-8
1,152
2.34375
2
[]
no_license
package com.erkineren.demo.persistence.model.entity; import lombok.Data; import lombok.EqualsAndHashCode; import lombok.NoArgsConstructor; import lombok.ToString; import lombok.experimental.Accessors; import javax.persistence.*; import java.util.List; @Entity @Data @Accessors(chain = true) @ToString @EqualsAndHashCode @NoArgsConstructor @Table(name = "users") public class User { @Id @GeneratedValue private Long id; @Column(nullable = false) private String name; @Column(nullable = false) private String email; @Column(nullable = false) private String password; @Column(nullable = false) @Enumerated(EnumType.STRING) private Role role = Role.ROLE_USER; @OneToMany(mappedBy = "user", fetch = FetchType.LAZY, cascade = { CascadeType.PERSIST, CascadeType.MERGE, CascadeType.REFRESH }) private List<Product> products; public User(String name, String email, String password) { this.name = name; this.email = email; this.password = password; } public enum Role { ROLE_ADMIN, ROLE_USER, } }
true
18488b45613fcd76ad51c5ff63e00dcae8ad63b1
Java
SpongePowered/Sponge
/src/main/java/org/spongepowered/common/event/lifecycle/AbstractRegisterRegistryEvent.java
UTF-8
4,956
1.773438
2
[ "MIT", "LicenseRef-scancode-unknown-license-reference" ]
permissive
/* * This file is part of Sponge, licensed under the MIT License (MIT). * * Copyright (c) SpongePowered <https://www.spongepowered.org> * Copyright (c) contributors * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ package org.spongepowered.common.event.lifecycle; import io.leangen.geantyref.TypeToken; import org.spongepowered.api.Engine; import org.spongepowered.api.Game; import org.spongepowered.api.ResourceKey; import org.spongepowered.api.event.Cause; import org.spongepowered.api.event.lifecycle.RegisterRegistryEvent; import org.spongepowered.api.registry.DuplicateRegistrationException; import org.spongepowered.api.registry.RegistryRoots; import org.spongepowered.api.registry.RegistryType; import org.spongepowered.common.registry.RegistryLoader; import org.spongepowered.common.registry.SpongeRegistryHolder; import java.util.Map; import java.util.Objects; import java.util.function.Supplier; public abstract class AbstractRegisterRegistryEvent extends AbstractLifecycleEvent implements RegisterRegistryEvent { public AbstractRegisterRegistryEvent(final Cause cause, final Game game) { super(cause, game); } @Override public <T> RegistryType<T> register(final ResourceKey key, final boolean isDynamic) throws DuplicateRegistrationException { Objects.requireNonNull(key, "key"); final SpongeRegistryHolder holder = this.getHolder(); final RegistryType<T> type = RegistryType.of(RegistryRoots.SPONGE, key); holder.createRegistry(type, (RegistryLoader<T>) null, isDynamic); return type; } @Override public <T> RegistryType<T> register(final ResourceKey key, final boolean isDynamic, final Supplier<Map<ResourceKey, T>> defaultValues) throws DuplicateRegistrationException { Objects.requireNonNull(key, "key"); Objects.requireNonNull(defaultValues, "defaultValues"); final SpongeRegistryHolder holder = this.getHolder(); final RegistryType<T> type = RegistryType.of(RegistryRoots.SPONGE, key); holder.createRegistry(type, defaultValues, isDynamic); return type; } protected abstract SpongeRegistryHolder getHolder(); public static final class GameScopedImpl extends AbstractRegisterRegistryEvent implements RegisterRegistryEvent.GameScoped { public GameScopedImpl(final Cause cause, final Game game) { super(cause, game); } @Override protected SpongeRegistryHolder getHolder() { return (SpongeRegistryHolder) this.game; } } public static final class EngineScopedImpl<E extends Engine> extends AbstractRegisterRegistryEvent implements RegisterRegistryEvent.EngineScoped<E> { private final TypeToken<E> token; private final E engine; public EngineScopedImpl(final Cause cause, final Game game, final E engine) { super(cause, game); this.token = TypeToken.get((Class<E>) engine.getClass()); this.engine = engine; } @Override public TypeToken<E> paramType() { return this.token; } @Override protected SpongeRegistryHolder getHolder() { return (SpongeRegistryHolder) this.engine; } } public static final class WorldScopedImpl extends AbstractRegisterRegistryEvent implements RegisterRegistryEvent.WorldScoped { private final ResourceKey worldKey; public WorldScopedImpl(final Cause cause, final Game game, final ResourceKey worldKey) { super(cause, game); this.worldKey = worldKey; } @Override public ResourceKey worldKey() { return this.worldKey; } @Override protected SpongeRegistryHolder getHolder() { return (SpongeRegistryHolder) this.game.server().worldManager().world(this.worldKey).get(); } } }
true
9154d5c9fd83619e6a95de40b57278704885b279
Java
Ivoripuion/MyJAVA_work
/StaticTest.java
GB18030
750
3.859375
4
[]
no_license
class StaticTest { public static void main(String[] args) { System.out.println(Person.country); } } class Person { static String country="CN"; static int age; Person(){} public static void main() { System.out.println(country+"+"+age ); } } /* static һηγԱ staticεijԱж staticȶڡ staticεijԱһֵ÷ʽԱֱӵá. staticεǹݣд洢ݡ */ /*ע ֻ̬ܷʾ̬Ա(Ǿ̬ȿԷʾֿ̬ԷʷǾ̬) ̬вԶthis,superؼ֡ Ǿ̬ġ */
true
ca06f73767972a8490eb1220ea6c0d3e53ab275b
Java
iawong/MultiUserChat_Application
/ChatClient/src/UserListPane.java
UTF-8
3,840
3.03125
3
[]
no_license
import javax.swing.*; import java.awt.*; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import java.awt.event.MouseAdapter; import java.awt.event.MouseEvent; import java.io.IOException; public class UserListPane extends JPanel implements UserStatusListener { private final ChatClient client; private JList<String> userListUI; private DefaultListModel<String> userListModel; public UserListPane(ChatClient client) { this.client = client; this.client.addUserStatusListener(this); // create a scrolling panel that will contain all online users userListModel = new DefaultListModel<>(); userListUI = new JList<>(userListModel); setLayout(new BorderLayout()); JScrollPane scroll = new JScrollPane(userListUI); scroll.getViewport().getView().setBackground(new Color(35, 39, 42)); scroll.getViewport().getView().setForeground(Color.WHITE); add(scroll, BorderLayout.CENTER); // on double click, open a direct message window to the user userListUI.addMouseListener(new MouseAdapter() { @Override public void mouseClicked(MouseEvent e) { if (e.getClickCount() > 1) { String login = userListUI.getSelectedValue(); MessagePane messagePane = new MessagePane(client, login); JFrame f = new JFrame("Message: " + login); f.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE); f.setSize(500, 500); f.getContentPane().add(messagePane, BorderLayout.CENTER); f.setLocationRelativeTo(null); f.setVisible(true); } } }); // create a button that opens a group chat window Button enterGC = new Button("Open Group Chat"); enterGC.setBackground(new Color(153, 170, 181)); enterGC.setForeground(Color.WHITE); enterGC.setSize(100, 100); add(enterGC, BorderLayout.SOUTH); // on button click, open group chat window enterGC.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent e) { openGC(); } }); } /** * Open a group chat window. */ private void openGC() { try { client.joinGC("#groupchat"); } catch (IOException ioException) { ioException.printStackTrace(); } String login = userListUI.getSelectedValue(); GroupMessagePane groupMessagePane = new GroupMessagePane(client, login); JFrame f = new JFrame("Group Chat"); f.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE); f.setBackground(new Color(35, 39, 42)); f.setSize(400, 600); f.getContentPane().add(groupMessagePane, BorderLayout.CENTER); f.setLocationRelativeTo(null); f.setVisible(true); } @Override public void online(String login) { userListModel.addElement(login); } @Override public void offline(String login) { userListModel.removeElement(login); } public static void main(String[] args) { ChatClient client = new ChatClient("localhost", 7140); UserListPane userListPane = new UserListPane(client); JFrame frame = new JFrame("User List"); frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); frame.setSize(400, 600); frame.getContentPane().add(userListPane, BorderLayout.CENTER); frame.setVisible(true); if (client.connect()) { try { client.login("guest", "guest"); } catch (IOException e) { e.printStackTrace(); } } } }
true
6f46e67537e5e3ea73435a4e292773428b7cf273
Java
govtmirror/CoECI-OPM-Service-Credit-Redeposit-Deposit-Application
/Code/SCRD_BRE/src/java/ejb/gov/opm/scrd/services/impl/reporting/CurrentSuspenseReportResponseItem.java
UTF-8
5,434
2.203125
2
[ "Apache-2.0" ]
permissive
/* * Copyright (C) 2014 TopCoder Inc., All Rights Reserved. */ package gov.opm.scrd.services.impl.reporting; import java.math.BigDecimal; import java.util.Date; /** * <p> * This class serves as the response item object that contains result details * to be used to generate reports in {@link CurrentSuspenseReportService} service. * </p> * * <p> * <strong>Thread Safety: </strong> This class is mutable and not thread safe. * </p> * * @author faeton, AleaActaEst, j3_guile * @version 1.0 */ public class CurrentSuspenseReportResponseItem { /** * Flag to indicate ACH. */ private boolean isACH; /** * Payment status. */ private String paymentStatus; /** * Date. */ private Date date; /** * The batch number. */ private String batchNumber; /** * CSD. */ private String csd; /** * The amount. */ private BigDecimal amount; /** * Birth date of claimant. */ private Date birthDate; /** * The claimant. */ private String claimant; /** * The name. */ private String name; /** * Balance. */ private BigDecimal balance; /** * Account status. */ private String accountStatus; /** * Default constructor. */ public CurrentSuspenseReportResponseItem() { } /** * Gets the value of the field <code>paymentStatus</code>. * @return the paymentStatus */ public String getPaymentStatus() { return paymentStatus; } /** * Sets the value of the field <code>paymentStatus</code>. * @param paymentStatus the paymentStatus to set */ public void setPaymentStatus(String paymentStatus) { this.paymentStatus = paymentStatus; } /** * Gets the value of the field <code>date</code>. * @return the date */ public Date getDate() { return date; } /** * Sets the value of the field <code>date</code>. * @param date the date to set */ public void setDate(Date date) { this.date = date; } /** * Gets the value of the field <code>batchNumber</code>. * @return the batchNumber */ public String getBatchNumber() { return batchNumber; } /** * Sets the value of the field <code>batchNumber</code>. * @param batchNumber the batchNumber to set */ public void setBatchNumber(String batchNumber) { this.batchNumber = batchNumber; } /** * Gets the value of the field <code>csd</code>. * @return the csd */ public String getCsd() { return csd; } /** * Sets the value of the field <code>csd</code>. * @param csd the csd to set */ public void setCsd(String csd) { this.csd = csd; } /** * Gets the value of the field <code>amount</code>. * @return the amount */ public BigDecimal getAmount() { return amount; } /** * Sets the value of the field <code>amount</code>. * @param amount the amount to set */ public void setAmount(BigDecimal amount) { this.amount = amount; } /** * Gets the value of the field <code>birthDate</code>. * @return the birthDate */ public Date getBirthDate() { return birthDate; } /** * Sets the value of the field <code>birthDate</code>. * @param birthDate the birthDate to set */ public void setBirthDate(Date birthDate) { this.birthDate = birthDate; } /** * Gets the value of the field <code>claimant</code>. * @return the claimant */ public String getClaimant() { return claimant; } /** * Sets the value of the field <code>claimant</code>. * @param claimant the claimant to set */ public void setClaimant(String claimant) { this.claimant = claimant; } /** * Gets the value of the field <code>name</code>. * @return the name */ public String getName() { return name; } /** * Sets the value of the field <code>name</code>. * @param name the name to set */ public void setName(String name) { this.name = name; } /** * Gets the value of the field <code>balance</code>. * @return the balance */ public BigDecimal getBalance() { return balance; } /** * Sets the value of the field <code>balance</code>. * @param balance the balance to set */ public void setBalance(BigDecimal balance) { this.balance = balance; } /** * Gets the value of the field <code>accountStatus</code>. * @return the accountStatus */ public String getAccountStatus() { return accountStatus; } /** * Sets the value of the field <code>accountStatus</code>. * @param accountStatus the accountStatus to set */ public void setAccountStatus(String accountStatus) { this.accountStatus = accountStatus; } /** * Gets the value of the field <code>isACH</code>. * @return the isACH */ public boolean isACH() { return isACH; } /** * Sets the value of the field <code>isACH</code>. * @param isACH the isACH to set */ public void setACH(boolean isACH) { this.isACH = isACH; } }
true
9700673ca154aa4dd15e66d8b209e2aed8c629ad
Java
tdenijs/Gomoku
/app/src/main/java/tdenijs/gomoku/StreakType.java
UTF-8
119
1.765625
2
[ "MIT" ]
permissive
package tdenijs.gomoku; /** * Created by pdenijs on 4/4/17. */ public enum StreakType { HOR,VERT,DIAGD,DIAGU }
true
589e69d175c518a75fd0d0a615338687594cebde
Java
shiyunlai/TTT
/tools-abf-service/src/main/java/org/tis/tools/abf/module/ac/service/IAcAppService.java
UTF-8
2,155
1.96875
2
[]
no_license
package org.tis.tools.abf.module.ac.service; import com.baomidou.mybatisplus.service.IService; import org.tis.tools.abf.module.ac.controller.request.AcAppListRequest; import org.tis.tools.abf.module.ac.entity.AcApp; import org.tis.tools.abf.module.ac.entity.enums.AcAppType; import org.tis.tools.abf.module.ac.exception.AcManagementException; import org.tis.tools.abf.module.common.entity.enums.YON; import java.util.List; /** * acApp的Service接口类 * * @author Auto Generate Tools * @date 2018/04/23 */ public interface IAcAppService extends IService<AcApp> { /** * 应用新增 * @param appCode 应用代码 * @param appName 应用名称 * @param appType 应用类型 * @param url 访问地址 * @param ipAddr IP * @param ipPort 端口 * @param appDesc 应用描述 * @return AcApp */ AcApp creatRootApp(String appCode, String appName, AcAppType appType, String url, String ipAddr, String ipPort, String appDesc, YON isopen, String openDate) throws AcManagementException; /** * 修改应用 * @param guid * @param appCode 应用代码 * @param appName 应用名称 * @param appType 应用类型 * @param isopen 是否开通应用 * @param openDate 开通日期 * @param url 访问地址 * @param ipAddr IP * @param ipPort 端口 * @param appDesc 应用描述 * @return AcApp * @throws AcManagementException */ AcApp changeById(String guid,String appCode, String appName, AcAppType appType,YON isopen,String openDate ,String url, String ipAddr, String ipPort, String appDesc) throws AcManagementException; /** * 查询所有应用 * @return * @throws AcManagementException */ List<AcApp> queryAll() throws AcManagementException; /** * 批量查询应用 * @param acAppListRequest * @return */ List<AcApp> batchQuery(AcAppListRequest acAppListRequest) throws AcManagementException; /** * 删除应用 * @param id * @throws AcManagementException */ void moveApp(String id) throws AcManagementException; }
true
57069cb4d805675139a5d9e1dcc4af0644f01b00
Java
TinaTerKA/tasksLevelOne
/firstLevelTasks/src/main/java/javaCollections/necklaceMakingApp/Stone.java
UTF-8
361
2.328125
2
[]
no_license
package javaCollections.necklaceMakingApp; import lombok.*; @Data @AllArgsConstructor public class Stone { private String name; private int caratWeight; private int costUSA; private int clear; private int hardness; private String color; public boolean isGemstone() { return (this.hardness >= 8 && this.clear < 5); } }
true
2d57dff76e81f70c0657a5af378be7a6cd0059a9
Java
hageldave/JPlotter
/jplotter/src/main/java/hageldave/jplotter/color/DefaultColorScheme.java
UTF-8
760
3.1875
3
[ "MIT" ]
permissive
package hageldave.jplotter.color; import java.awt.*; /** * Enum containing predefined {@link ColorScheme}s, * which can be accessed through {@link #get()}. * * @author lucareichmann */ public enum DefaultColorScheme { LIGHT( new ColorScheme( Color.BLACK, Color.GRAY, Color.DARK_GRAY, new Color(0xdddddd), new Color(96, 96, 96), Color.WHITE ) ), DARK( new ColorScheme( 0xffdddddd, 0xffaaaaaa, 0xff666666, 0xff444444, 0xffbbbbbb, 0xff21232b ) ), ; private final ColorScheme scheme; private DefaultColorScheme (ColorScheme scheme) { this.scheme = scheme; } /** * Returns the preset's {@link ColorScheme} object * @return color scheme */ public ColorScheme get() { return this.scheme; } }
true
a0d6306ffb85a624397afb78fb9bffe49b8e252b
Java
fhasovic/GPSTracker
/app/src/main/java/com/example/filip/gpstracker/ui/tracking/presenter/map/MapFragmentPresenter.java
UTF-8
557
1.851563
2
[]
no_license
package com.example.filip.gpstracker.ui.tracking.presenter.map; import android.location.Location; import com.example.filip.gpstracker.pojo.Stats; /** * Created by Filip on 05/03/2016. */ public interface MapFragmentPresenter { void sendLocationToView(Location location); void sendLocationToFirebase(Location location); void sendStatsToFirebase(long startTime, long endTime); void requestLocationsFromFirebase(); void requestStatsForTrackingSession(); void createDialogDataForViewOnTrackingStopped(Stats statsToDisplay); }
true
0ad4ceb3f661bf588596cc17529ae13c273e905d
Java
XLowCold/Secondary
/app/src/main/java/com/example/secondary/ui/fragment/HomePageToolFragment.java
UTF-8
2,926
2.109375
2
[]
no_license
package com.example.secondary.ui.fragment; import android.app.AlertDialog; import android.content.Intent; import android.os.Bundle; import android.util.Log; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.ImageView; import android.widget.TextView; import com.example.secondary.R; import com.example.secondary.ui.activity.NerveTimeActivity; import com.example.secondary.ui.activity.FibonacciActivity; import com.example.secondary.ui.adapter.RVAdapter; import com.example.secondary.ui.activity.WeatherForecastActivity; import java.util.Arrays; import androidx.annotation.NonNull; import androidx.annotation.Nullable; import androidx.fragment.app.Fragment; import androidx.recyclerview.widget.DividerItemDecoration; import androidx.recyclerview.widget.RecyclerView; import androidx.recyclerview.widget.StaggeredGridLayoutManager; /** * 主页工具fragment */ public class HomePageToolFragment extends Fragment { private static final String TAG = "HomePageToolFragment"; private RecyclerView mRvGameList; private RVAdapter mRvAdapter; private static final String[] mToolNames = {"反应测速", "计算斐波那契数", "天气预报"}; public HomePageToolFragment() { } @Nullable @Override public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) { View view = inflater.inflate(R.layout.fragment_homepage_tool, container, false); initView(view); return view; } private void initView(View v) { mRvGameList = (RecyclerView) v.findViewById(R.id.rvGameList); mRvGameList.addItemDecoration(new DividerItemDecoration(getActivity(), DividerItemDecoration.VERTICAL)); initAdapter(); } private void initAdapter() { Class[] classes = { NerveTimeActivity.class, FibonacciActivity.class, WeatherForecastActivity.class }; //适配管理器 RecyclerView.LayoutManager layoutManager = new StaggeredGridLayoutManager(1, StaggeredGridLayoutManager.VERTICAL); mRvGameList.setLayoutManager(layoutManager); //适配器 mRvAdapter = new RVAdapter<String>(getActivity(), Arrays.asList(mToolNames) , R.layout.rv_item_homepage_tool_rvitem) { @Override public void bind(VH vh, String d, int pos) { vh.setTxt(R.id.tvDescript, d); ImageView imgIcon = vh.itemView.findViewById(R.id.imgIcon); //点击事件 vh.itemView.setOnClickListener(v -> { Log.d(TAG, "bind: 打开" + mToolNames[pos]); Intent intent = new Intent(); intent.setClass(getContext(), classes[pos]); getActivity().startActivity(intent); }); //长按 vh.itemView.setOnLongClickListener(v -> { AlertDialog builder = new AlertDialog.Builder(getContext()) .setMessage(((TextView) vh.fbi(R.id.tvDescript)).getText().toString()) .show(); return false; }); } }; mRvGameList.setAdapter(mRvAdapter); } }
true
8b25b4f8cae7c4f7107bc057bf5b493524d6ce67
Java
jiangyukun/2015January__
/src/main/java/me/jiangyu/company/web/RedEnvelopeController.java
UTF-8
1,271
2.25
2
[]
no_license
package me.jiangyu.company.web; import me.jiangyu.company.domain.RedEnvelope; import me.jiangyu.company.service.RedEnvelopeService; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Controller; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.ResponseBody; /** * Created by jiangyukun on 2015/1/20. */ @Controller @RequestMapping("/redEnvelope") public class RedEnvelopeController { private static final byte[] lock = new byte[0]; @Autowired private RedEnvelopeService redEnvelopeService; @RequestMapping("/get") @ResponseBody public String getRedEnvelope() { synchronized (lock) { RedEnvelope redEnvelope = redEnvelopeService.getRedEnvelope(); System.out.println(redEnvelope.getId() + " " + redEnvelope.getMoney()); return ""; } } @RequestMapping("/save") public String saveRedEnvelope() { for (int i = 1000; i > 0; i--) { RedEnvelope redEnvelope = new RedEnvelope(); redEnvelope.setFlag(true); redEnvelope.setMoney(i); redEnvelopeService.saveRedEnvelope(redEnvelope); } return ""; } }
true
3051f3f2ac4a7f1444b761237d5d1094bdd83af5
Java
wooloves39/smash_mario-bro
/android/SuperMario_2/SuperMario/app/src/main/java/com/example/parkjaeha/supermario/Map.java
UTF-8
1,554
2.359375
2
[]
no_license
package com.example.parkjaeha.supermario; /** * Created by woolo_so5omoy on 2017-08-21. */ public class Map { Tile[] tiles;//각 맵의 다른 모형의 타일 int obnum;//다른 모형의 타일 수 //void collision(CPlayer& player) { // player.mapobject_collsion = false; // if (player.down == false && player.GetStatus() != FLY_LEFT&&player.GetStatus() != FLY_RIGHT) { // for (int i = 0; i < obnum; ++i) { // for (int j = 0; j < tiles[i].Get_ob_num(); j++) { // if (player.GetPosition().x <= tiles[i].collisionPos(j).left)continue; // if (player.GetPosition().x >= tiles[i].collisionPos(j).right)continue; // if (player.GetPosition().y <= tiles[i].collisionPos(j).top - 30)continue; // if (player.GetPosition().y >= tiles[i].collisionPos(j).bottom)continue; // player.SetPosition(player.GetPosition().x, tiles[i].collisionPos(j).top - 20); // if (player.GetStatus() == JUMP_LEFT || player.GetStatus() == JUMP_RIGHT || // player.GetStatus() == FLY_LEFT || player.GetStatus() == FLY_RIGHT) { // player.SetStatus(player.GetStatus() % 2 + BASIC_RIGHT); // } // player.mapobject_collsion = true;//맵에 붙어 있을때 // player.fly = false; // player.m_bJump = false; // return; // } // } // } //} }
true
d22a42fb53cd9728a090dbd7b75cc4c4a7f0b7df
Java
timnederhoff/selenium-grid-dashboard
/src/main/java/org/selenium/tools/dashboard/services/services/SystemInfoLookupServiceASync.java
UTF-8
1,759
2.296875
2
[]
no_license
package org.selenium.tools.dashboard.services.services; import org.selenium.tools.dashboard.DashboardConfig; import org.selenium.tools.dashboard.model.SystemInfo; import org.springframework.http.client.SimpleClientHttpRequestFactory; import org.springframework.scheduling.annotation.Async; import org.springframework.scheduling.annotation.AsyncResult; import org.springframework.stereotype.Service; import org.springframework.web.client.RestClientException; import org.springframework.web.client.RestTemplate; import java.util.concurrent.Future; @Service public class SystemInfoLookupServiceASync { private RestTemplate restTemplate; public SystemInfoLookupServiceASync() { restTemplate = new RestTemplate(); ((SimpleClientHttpRequestFactory)restTemplate.getRequestFactory()).setConnectTimeout(DashboardConfig.config.getInt("system.connectTimeout")); ((SimpleClientHttpRequestFactory)restTemplate.getRequestFactory()).setReadTimeout(DashboardConfig.config.getInt("system.readTimeout")); } @Async public Future<SystemInfo> getSystemInfo(String baseUrl){ SystemInfo systemInfo; try { systemInfo = restTemplate.getForObject( baseUrl + ":" + DashboardConfig.config.getString("port") + DashboardConfig.config.getString("system.endpoint"), SystemInfo.class); systemInfo.setLoadedSuccessfully(true); } catch (RestClientException e) { e.printStackTrace(); systemInfo = new SystemInfo(); systemInfo.setLoadedSuccessfully(false); systemInfo.setErrorMessage(e.getMessage()); } return new AsyncResult<SystemInfo>(systemInfo); } }
true
4ddd5d06f9d5d3bd8760f39263ae9ab939b1915a
Java
nervermoretys/dsl
/src/main/java/com/meituan/dianping/distribute/calculator/StatementBaseListener.java
UTF-8
5,141
2.765625
3
[ "MIT" ]
permissive
// Generated from /Users/yangyongli/Projects/dsl/src/main/java/com/meituan/dianping/distribute/rule/Statement.g4 by ANTLR 4.7 package com.meituan.dianping.distribute.calculator; import org.antlr.v4.runtime.ParserRuleContext; import org.antlr.v4.runtime.tree.ErrorNode; import org.antlr.v4.runtime.tree.TerminalNode; /** * This class provides an empty implementation of {@link StatementListener}, * which can be extended to create a listener which only needs to handle a subset * of the available methods. */ public class StatementBaseListener implements StatementListener { /** * {@inheritDoc} * * <p>The default implementation does nothing.</p> */ @Override public void enterStatement(StatementParser.StatementContext ctx) { } /** * {@inheritDoc} * * <p>The default implementation does nothing.</p> */ @Override public void exitStatement(StatementParser.StatementContext ctx) { } /** * {@inheritDoc} * * <p>The default implementation does nothing.</p> */ @Override public void enterSinglePlusOrMinus(StatementParser.SinglePlusOrMinusContext ctx) { } /** * {@inheritDoc} * * <p>The default implementation does nothing.</p> */ @Override public void exitSinglePlusOrMinus(StatementParser.SinglePlusOrMinusContext ctx) { } /** * {@inheritDoc} * * <p>The default implementation does nothing.</p> */ @Override public void enterPlusOrMinus(StatementParser.PlusOrMinusContext ctx) { } /** * {@inheritDoc} * * <p>The default implementation does nothing.</p> */ @Override public void exitPlusOrMinus(StatementParser.PlusOrMinusContext ctx) { } /** * {@inheritDoc} * * <p>The default implementation does nothing.</p> */ @Override public void enterSingleTimesOrDiv(StatementParser.SingleTimesOrDivContext ctx) { } /** * {@inheritDoc} * * <p>The default implementation does nothing.</p> */ @Override public void exitSingleTimesOrDiv(StatementParser.SingleTimesOrDivContext ctx) { } /** * {@inheritDoc} * * <p>The default implementation does nothing.</p> */ @Override public void enterTimesOrDiv(StatementParser.TimesOrDivContext ctx) { } /** * {@inheritDoc} * * <p>The default implementation does nothing.</p> */ @Override public void exitTimesOrDiv(StatementParser.TimesOrDivContext ctx) { } /** * {@inheritDoc} * * <p>The default implementation does nothing.</p> */ @Override public void enterAtomNumber(StatementParser.AtomNumberContext ctx) { } /** * {@inheritDoc} * * <p>The default implementation does nothing.</p> */ @Override public void exitAtomNumber(StatementParser.AtomNumberContext ctx) { } /** * {@inheritDoc} * * <p>The default implementation does nothing.</p> */ @Override public void enterAtomToken(StatementParser.AtomTokenContext ctx) { } /** * {@inheritDoc} * * <p>The default implementation does nothing.</p> */ @Override public void exitAtomToken(StatementParser.AtomTokenContext ctx) { } /** * {@inheritDoc} * * <p>The default implementation does nothing.</p> */ @Override public void enterParenToken(StatementParser.ParenTokenContext ctx) { } /** * {@inheritDoc} * * <p>The default implementation does nothing.</p> */ @Override public void exitParenToken(StatementParser.ParenTokenContext ctx) { } /** * {@inheritDoc} * * <p>The default implementation does nothing.</p> */ @Override public void enterParen(StatementParser.ParenContext ctx) { } /** * {@inheritDoc} * * <p>The default implementation does nothing.</p> */ @Override public void exitParen(StatementParser.ParenContext ctx) { } /** * {@inheritDoc} * * <p>The default implementation does nothing.</p> */ @Override public void enterNumber(StatementParser.NumberContext ctx) { } /** * {@inheritDoc} * * <p>The default implementation does nothing.</p> */ @Override public void exitNumber(StatementParser.NumberContext ctx) { } /** * {@inheritDoc} * * <p>The default implementation does nothing.</p> */ @Override public void enterVariable(StatementParser.VariableContext ctx) { } /** * {@inheritDoc} * * <p>The default implementation does nothing.</p> */ @Override public void exitVariable(StatementParser.VariableContext ctx) { } /** * {@inheritDoc} * * <p>The default implementation does nothing.</p> */ @Override public void enterIdentifier(StatementParser.IdentifierContext ctx) { } /** * {@inheritDoc} * * <p>The default implementation does nothing.</p> */ @Override public void exitIdentifier(StatementParser.IdentifierContext ctx) { } /** * {@inheritDoc} * * <p>The default implementation does nothing.</p> */ @Override public void enterEveryRule(ParserRuleContext ctx) { } /** * {@inheritDoc} * * <p>The default implementation does nothing.</p> */ @Override public void exitEveryRule(ParserRuleContext ctx) { } /** * {@inheritDoc} * * <p>The default implementation does nothing.</p> */ @Override public void visitTerminal(TerminalNode node) { } /** * {@inheritDoc} * * <p>The default implementation does nothing.</p> */ @Override public void visitErrorNode(ErrorNode node) { } }
true
307d8d137408eaf8f7ab923d494297eb9fabc932
Java
session-zhen/erp_nesson
/erp2/src/main/java/com/hqyj/service/MenuService.java
UTF-8
130
1.726563
2
[]
no_license
package com.hqyj.service; import com.hqyj.pojo.Menu; public interface MenuService { public Menu getMenuById(String menuid); }
true
5e29b66f96897a2661ce5daf4fe68a5d6100f71f
Java
yulu1996/demo-2020
/junit-demo/src/test/java/CalculateTest.java
UTF-8
1,935
3.15625
3
[]
no_license
import org.junit.Test; import java.math.BigDecimal; import static org.junit.Assert.*; public class CalculateTest { BigDecimal bignum1 = new BigDecimal("11"); BigDecimal bignum2 = new BigDecimal("10.9"); BigDecimal a = new BigDecimal(11); BigDecimal b = new BigDecimal("10.9"); @Test public void tt(){ System.out.println(a.subtract(b)); assertEquals(new BigDecimal("9"),a.subtract(b)); } @Test public void testAdd(){ assertEquals(new BigDecimal("9"),new Calculate().add(bignum1, bignum2)); } @Test public void testSubstract(){ assertEquals(new BigDecimal("3"),new Calculate().subtract(bignum1, bignum2)); } @Test public void testMultiply(){ assertEquals(new BigDecimal("18"),new Calculate().multiply(bignum1, bignum2)); } @Test public void testDivide(){ assertEquals(new BigDecimal("2"),new Calculate().divide(bignum1, bignum2)); } String str1 = new String ("abc"); String str2 = new String ("abc"); String str3 = null; String str4 = "abc"; String str5 = "abc"; int val1 = 5; int val2 = 6; String[] expectedArray = {"one", "two", "three"}; String[] resultArray = {"one", "two", "three"}; @Test public void testAssert(){ //检查两个变量或者等式是否平等 assertEquals(str1, str2); //检查条件为真 assertTrue (val1 < val2); //检查条件为假 assertFalse(val1 > val2); //检查对象不为空 assertNotNull(str1); //检查对象为空 assertNull(str3); //检查两个相关对象是否指向同一个对象 assertSame(str4,str5); //检查两个相关对象是否不指向同一个对象 assertNotSame(str1,str3); //检查两个数组是否相等 assertArrayEquals(expectedArray, resultArray); } }
true
1c892d8eef01b1323155fba3b1627251509b7403
Java
Cal-D/Spring-night
/src/main/java/com/park/nov11/menu/MenuDAO.java
UTF-8
911
2.3125
2
[]
no_license
package com.park.nov11.menu; import java.util.List; import javax.servlet.http.HttpServletRequest; import org.apache.ibatis.session.SqlSession; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; @Service public class MenuDAO { @Autowired private SqlSession ss; public void getMenu(HttpServletRequest req) { List<Menu> menus = ss.getMapper(MenuMapper.class).getMenu(); //req.attribute에 마무리 req.setAttribute("menus",menus); //req.session.attribute //cookie 총 3가지가 있다. 이 3가지다 그 사이트 내에섬나 사용가능. //DB에 있는 데이터를 외부에서 쓰게 해주려면? //AJAX 서버를 만드ㅡㄹ어야 한다. } public Menus getMenuXML() { List<Menu> menus = ss.getMapper(MenuMapper.class).getMenu(); return new Menus(menus); } }
true
b5663671bd07bac5b83ea473098db25f74fae39e
Java
willesreis/javafx-screen-manager
/FXScreenManager/src/org/wsr/screenmanager/ScreenManager.java
UTF-8
3,534
2.890625
3
[]
no_license
package org.wsr.screenmanager; import java.io.IOException; import java.util.HashMap; import java.util.Map; import java.util.logging.Level; import java.util.logging.Logger; import javafx.animation.FadeTransition; import javafx.application.Application; import javafx.event.ActionEvent; import javafx.event.EventHandler; import javafx.fxml.FXMLLoader; import javafx.scene.Node; import javafx.scene.Parent; import javafx.scene.layout.StackPane; import javafx.util.Duration; import org.wsr.screenmanager.interfaces.ScreenController; import org.wsr.screenmanager.interfaces.ScreenEnum; /** * Manager to perform screen actions/transitions. * * @author willes.reis */ public class ScreenManager extends StackPane { /** * Stack of screens to be managed. */ private Map<ScreenEnum, Node> screens = new HashMap<ScreenEnum, Node>(); /** * Add screen to be managed. * * @param screenId Screen identification. * @param node Node to be putted inside pane. */ public void addScreen(ScreenEnum screenId, Node node) { screens.put(screenId, node); } /** * Define actual screen with fade transition. * * @param screenId Screen identification. * @return true to success defined, or false otherwise. */ public boolean setScreen(final ScreenEnum screenId) { if (screens.get(screenId) != null) { if (!getChildren().isEmpty()) { FadeTransition fadeOut = new FadeTransition(Duration.seconds(1.0)); fadeOut.setFromValue(1.0); fadeOut.setToValue(0.0); fadeOut.setNode(getChildren().get(0)); getChildren().remove(0); getChildren().add(0, screens.get(screenId)); fadeOut.setOnFinished( new EventHandler<ActionEvent>() { @Override public void handle(ActionEvent event) { FadeTransition fadeIn = new FadeTransition(Duration.seconds(1.0)); fadeIn.setFromValue(0.0); fadeIn.setToValue(1.0); fadeIn.setNode(getChildren().get(0)); getChildren().remove(0); getChildren().add(0, screens.get(screenId)); fadeIn.play(); } }); fadeOut.play(); } else { FadeTransition fadeIn = new FadeTransition(Duration.seconds(1.0)); fadeIn.setFromValue(0.0); fadeIn.setToValue(1.0); fadeIn.setNode(screens.get(screenId)); getChildren().add(screens.get(screenId)); fadeIn.play(); } return true; } else { System.out.println("Screen hasn't been loaded!"); return false; } } /** * Load screen with your template FXML. * * @param screenId Screen identification. * @param clazz Class to get resource. * @param resource Template name of FXML. * @return true to success load, or false otherwise. */ public boolean loadScreen(ScreenEnum screenId, Class<? extends Application> clazz, String resource) { try { FXMLLoader loader = new FXMLLoader(clazz.getResource(resource)); Parent screen = (Parent) loader.load(); ScreenController controller = (ScreenController) loader.getController(); controller.setScreenParent(this); addScreen(screenId, screen); return true; } catch (IOException ioe) { Logger.getLogger(ScreenManager.class.getName()).log(Level.ALL, ioe.getMessage()); return false; } } /** * Remove screen of the stack. * * @param screenId Screen identification. * @return true to success remove, or false otherwise. */ public boolean unloadScreen(String screenId) { if (screens.remove(screenId) == null) { System.out.println("Screen didn't exist!"); return false; } else { return true; } } }
true
8a38b2846bea0d30e4b87194faeeab65fb971a0d
Java
MTechPT1/PhotoLearn
/app/src/main/java/com/mtech/parttimeone/photolearn/util/AppUtil.java
UTF-8
1,504
2.0625
2
[]
no_license
package com.mtech.parttimeone.photolearn.util; import android.app.Activity; import android.support.v4.app.Fragment; import com.google.firebase.auth.FirebaseAuth; import com.mtech.parttimeone.photolearn.application.GlobalPhotoLearn; import com.mtech.parttimeone.photolearn.enumeration.UserType; /** * @author lechin * @date 3/30/18 */ public class AppUtil { public static String getUserName(Fragment f) { GlobalPhotoLearn globalPhotoLearn = (GlobalPhotoLearn) f.getActivity().getApplicationContext(); FirebaseAuth mAuth; String userName; mAuth = globalPhotoLearn.getmAuth(); userName = mAuth.getCurrentUser().getUid(); return userName; } public static UserType getMode(Fragment f) { GlobalPhotoLearn globalPhotoLearn = (GlobalPhotoLearn) f.getActivity().getApplicationContext(); UserType ut; ut = globalPhotoLearn.getmUserType(); return ut; } public static String getUserName(Activity a) { GlobalPhotoLearn globalPhotoLearn = (GlobalPhotoLearn) a.getApplicationContext(); FirebaseAuth mAuth; String userName; mAuth = globalPhotoLearn.getmAuth(); userName = mAuth.getCurrentUser().getUid(); return userName; } public static UserType getMode(Activity a) { GlobalPhotoLearn globalPhotoLearn = (GlobalPhotoLearn) a.getApplicationContext(); UserType ut; ut = globalPhotoLearn.getmUserType(); return ut; } }
true
9d17ce13051357f985159e28e6630be3340e90a6
Java
dnayak1/QuakeLocator
/app/src/main/java/com/dhirajnayak/quakelocator/utility/Constants.java
UTF-8
997
1.625
2
[]
no_license
package com.dhirajnayak.quakelocator.utility; /** * Created by dhirajnayak on 1/26/18. * constants to be used all over the application */ public class Constants { public static final String API_KEY = "32590abdb7534ead8c461814170411"; public static final String BASE_URL_CITY = "http://api.apixu.com/v1/"; public static final String BASE_URL="https://earthquake.usgs.gov/fdsnws/event/1/"; public static final String PLACES_KEY="places"; public static final String CITY_KEY="city"; public static final int CITY_KEY_REQ=100; public static final String USGS_URL="https://earthquake.usgs.gov/"; public static final int LOCATION_PERMISSION_REQUEST_CODE = 1234; public static final float DEFAULT_ZOOM=5f; public static final String START_DATE="startDate"; public static final String END_DATE="endDate"; public static final String START_TIME="startTime"; public static final String END_TIME="endTime"; public static final String CITY="city"; }
true
65d70c06f1020d0a71d85b0177b1e156756b5b9d
Java
daishuiyuan/daiyuan
/empSys/src/com/dy/empSys/web/SelectServlet.java
UTF-8
1,175
2.25
2
[]
no_license
package com.dy.empSys.web; import java.io.IOException; import javax.servlet.ServletContext; import javax.servlet.ServletException; import javax.servlet.annotation.WebServlet; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; @WebServlet("/SelectServlet") @SuppressWarnings("serial") public class SelectServlet extends HttpServlet{ @Override protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { //获取上下文 ServletContext context = req.getServletContext(); //获取全局参数 String encoding = context.getInitParameter("encoding"); //设置请求和响应编码 req.setCharacterEncoding(encoding); resp.setContentType("text/html;charset="+encoding); String id = req.getParameter("id"); String name = req.getParameter("name"); } @Override protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { doGet(req, resp); } }
true
59b9838384958934f676458691293f8d53bca27b
Java
RogerVFbr/microservices-poc-atividades
/src/main/java/com/soundlab/atividades/exceptions/ExternalServiceException.java
UTF-8
286
2.46875
2
[]
no_license
package com.soundlab.atividades.exceptions; public class ExternalServiceException extends RuntimeException{ public ExternalServiceException(String serviceName, String errorBody) { super(String.format("Erro no serviço externo '%s' -> %s", serviceName, errorBody)); } }
true
737f721041dad939b47fda4d2f80fe59c3851e4a
Java
aiq7520/shiro
/src/main/java/org/gege/shiro/charpter3/permission/MyRolePermissionResolver.java
UTF-8
367
2.140625
2
[]
no_license
package org.gege.shiro.charpter3.permission; import java.util.Collection; import org.apache.shiro.authz.Permission; import org.apache.shiro.authz.permission.RolePermissionResolver; public class MyRolePermissionResolver implements RolePermissionResolver { @Override public Collection<Permission> resolvePermissionsInRole(String roleString) { return null; } }
true
623135d10fc3bffd38ad9337f1b875cd77c90300
Java
GraphZero/Faust_IT
/src/main/java/com/faust/intership/users/ui/UsersController.java
UTF-8
2,427
2.4375
2
[]
no_license
package com.faust.intership.users.ui; import com.faust.intership.users.application.UsersCrudService; import com.faust.intership.users.application.commands.AddUserCommand; import com.faust.intership.users.application.commands.DeleteUserCommand; import com.faust.intership.users.application.commands.EditUserCommand; import com.faust.intership.users.domain.dto.UserDto; import lombok.RequiredArgsConstructor; import org.springframework.http.HttpStatus; import org.springframework.http.ResponseEntity; import org.springframework.web.bind.annotation.RequestBody; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestMethod; import org.springframework.web.bind.annotation.RestController; import java.util.List; @RestController @RequiredArgsConstructor public class UsersController { private final UsersCrudService usersCrudService; @RequestMapping(path = "/createUser", method = RequestMethod.POST, produces = "application/json") public ResponseEntity<String> createUser(@RequestBody final AddUserCommand addUserCommand){ System.out.println(addUserCommand); if ( usersCrudService.addUser(addUserCommand)){ return ResponseEntity.ok("\"Created user\""); } else{ return new ResponseEntity<>("\"Couldn't add user account.\"", HttpStatus.CONFLICT); } } @RequestMapping(path = "/deleteUser", method = RequestMethod.POST) public ResponseEntity<String> deleteUser(@RequestBody final DeleteUserCommand deleteUserCommand){ if ( usersCrudService.deleteUser(deleteUserCommand)){ return ResponseEntity.ok("\"Deleted user\""); } else{ return new ResponseEntity<>("\"User account doesn't exist.\"", HttpStatus.CONFLICT); } } @RequestMapping(path = "/findAllUsers", method = RequestMethod.GET) public ResponseEntity<List<UserDto>> findAllUsers(){ return ResponseEntity.ok(usersCrudService.findAllUsers()); } @RequestMapping(path = "/updateUser", method = RequestMethod.PATCH) public ResponseEntity<String> updateUser(@RequestBody final EditUserCommand editUserCommand){ if ( usersCrudService.editUser(editUserCommand)){ return ResponseEntity.ok("\"Edited user\""); } else{ return new ResponseEntity<>("\"Couldn't edit user account.\"", HttpStatus.CONFLICT); } } }
true
5e12650b62342a5a65a3ae839714f8428d5f6a82
Java
Xceptance/XLT
/src/test/java/com/xceptance/xlt/report/ReportGenerator_TimeBoundariesTest.java
UTF-8
8,949
2
2
[ "Apache-2.0", "LGPL-2.0-or-later", "BSD-3-Clause", "EPL-1.0", "CDDL-1.1", "EPL-2.0", "MPL-2.0", "MIT", "BSD-2-Clause", "LicenseRef-scancode-unknown-license-reference" ]
permissive
/* * Copyright (c) 2005-2023 Xceptance Software Technologies GmbH * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.xceptance.xlt.report; import java.io.File; import java.io.IOException; import java.lang.reflect.Method; import java.util.Arrays; import java.util.Properties; import org.apache.commons.vfs2.FileObject; import org.apache.commons.vfs2.VFS; import org.junit.Assert; import org.junit.Before; import org.junit.Rule; import org.junit.Test; import org.junit.rules.TemporaryFolder; import org.junit.runner.RunWith; import org.junit.runners.Parameterized; import org.junit.runners.Parameterized.Parameter; import org.junit.runners.Parameterized.Parameters; /** * Test {@linkplain ReportGenerator#getTimeBoundaries(long, long, long, boolean, boolean, boolean, long, long)}. Ramp up * time is not cut off. */ @RunWith(Parameterized.class) public class ReportGenerator_TimeBoundariesTest { /** * Dummy properties, empty */ private static final Properties PROPERTIES_DUMMY = new Properties(); /** * in milliseconds */ private static final long TIMESTAMP_START = 1420452000000L; // 20150105-100000 /** * in milliseconds */ private static final long TEST_ELAPSED_TIME = 7200000; // 2 hours /** * in milliseconds */ private static final long TIMESTAMP_END = TIMESTAMP_START + TEST_ELAPSED_TIME; // 20150105-120000 // 1420459200000 /** * 1 hour, in milliseconds */ private static final long DURATION = 3600000; private static final long DURATION_NOT_SPECIFIED = -1; /** * 1 second, in milliseconds */ private static final long PERIOD_1s = 1000; /** * 30 minutes, in milliseconds */ private static final long PERIOD_30m = 1800000; /** * 1 hour 30 minutes = 90 minutes, in milliseconds */ private static final long PERIOD_1h30m = 5400000; /** * 1 hour, in milliseconds */ private static final long PERIOD_1h = 3600000; /** * 24 hours, in milliseconds */ private static final long PERIOD_24h = 86400000; private File DUMMY_DIR; private FileObject DUMMY_INPUT_DIR; @Rule public final TemporaryFolder tempFolder = new TemporaryFolder(); @Parameters(name = "{index}: {0}") public static Iterable<Object[]> data() { /** * description<br> * from<br> * to<br> * duration<br> * isFromRelative<br> * isToRelative<br> * expectedFrom<br> * expectedTo */ return Arrays.asList(new Object[][] { { "<no_limit>", 0, Long.MAX_VALUE, DURATION_NOT_SPECIFIED, false, false, 0, Long.MAX_VALUE }, { "-from +0s", 0, Long.MAX_VALUE, DURATION_NOT_SPECIFIED, true, false, TIMESTAMP_START, Long.MAX_VALUE }, { "-to +0s", 0, 0, DURATION_NOT_SPECIFIED, false, true, 0, TIMESTAMP_START }, { "from +1s", PERIOD_1s, Long.MAX_VALUE, DURATION_NOT_SPECIFIED, true, false, TIMESTAMP_START + PERIOD_1s, Long.MAX_VALUE }, { "-to +1s", 0, PERIOD_1s, DURATION_NOT_SPECIFIED, false, true, 0, TIMESTAMP_START + PERIOD_1s }, { "-from -1s", -PERIOD_1s, Long.MAX_VALUE, DURATION_NOT_SPECIFIED, true, false, TIMESTAMP_END - PERIOD_1s, Long.MAX_VALUE }, { "-to -1s", 0, -PERIOD_1s, DURATION_NOT_SPECIFIED, false, true, 0, TIMESTAMP_END - PERIOD_1s }, { "-from 20150105-100000", TIMESTAMP_START, Long.MAX_VALUE, DURATION_NOT_SPECIFIED, false, false, TIMESTAMP_START, Long.MAX_VALUE }, { "-to 20150105-120000", 0, TIMESTAMP_END, DURATION_NOT_SPECIFIED, false, false, 0, TIMESTAMP_END }, { "-from +1h", PERIOD_1h, Long.MAX_VALUE, DURATION_NOT_SPECIFIED, true, false, TIMESTAMP_START + DURATION, Long.MAX_VALUE }, { "-to +1h", 0, PERIOD_1h, DURATION_NOT_SPECIFIED, false, true, 0, TIMESTAMP_START + DURATION }, { "-from +0s -l 1h", 0, Long.MAX_VALUE, DURATION, true, false, TIMESTAMP_START, TIMESTAMP_START + DURATION }, { "-from +1s -l 1h", PERIOD_1s, Long.MAX_VALUE, DURATION, true, false, TIMESTAMP_START + PERIOD_1s, TIMESTAMP_START + PERIOD_1s + DURATION }, { "-from +1s -l 0", PERIOD_1s, Long.MAX_VALUE, 0, true, false, TIMESTAMP_START + PERIOD_1s, TIMESTAMP_START + PERIOD_1s }, { "-to 20150105-120000 -l 1h", 0, TIMESTAMP_END, DURATION, false, false, TIMESTAMP_END - DURATION, TIMESTAMP_END }, { "-from 20150105-103000 -to 20150105-113000", TIMESTAMP_START + PERIOD_30m, TIMESTAMP_END - PERIOD_30m, DURATION_NOT_SPECIFIED, false, false, TIMESTAMP_START + PERIOD_30m, TIMESTAMP_END - PERIOD_30m }, { "-from +30m -to +1h30m", PERIOD_30m, PERIOD_1h30m, DURATION_NOT_SPECIFIED, true, true, TIMESTAMP_START + PERIOD_30m, TIMESTAMP_END - PERIOD_30m }, { "<BAD BUT POSSIBLE> -from +1s -l -1", PERIOD_1s, Long.MAX_VALUE, -1, true, false, TIMESTAMP_START + PERIOD_1s, Long.MAX_VALUE }, { "<BAD BUT POSSIBLE> 'from' negative, not relative, do not change", -1, Long.MAX_VALUE, DURATION_NOT_SPECIFIED, false, false, -1, Long.MAX_VALUE }, { "<BAD BUT POSSIBLE> 'from' more than 24h, not relative, do not change", PERIOD_24h + 1, Long.MAX_VALUE, DURATION_NOT_SPECIFIED, false, false, PERIOD_24h + 1, Long.MAX_VALUE } }); } @Parameter(value = 0) public String description; @Parameter(value = 1) public long from; @Parameter(value = 2) public long to; @Parameter(value = 3) public long duration; @Parameter(value = 4) public boolean isFromRelative; @Parameter(value = 5) public boolean isToRelative; @Parameter(value = 6) public long expectedFrom; @Parameter(value = 7) public long expectedTo; @Before public void init() throws IOException { DUMMY_DIR = tempFolder.getRoot(); DUMMY_INPUT_DIR = VFS.getManager().resolveFile(DUMMY_DIR.getAbsolutePath()); } /** * Invoke ReportGenerator's 'getTimeBoundaries' method with given parameters. */ @Test public void check() throws Exception { // create dummy report generator final ReportGenerator rg = new ReportGenerator(DUMMY_INPUT_DIR, DUMMY_DIR, true, false, null, PROPERTIES_DUMMY, null, null, null, null); // get access to method of interest final Method m = rg.getClass().getDeclaredMethod("getTimeBoundaries", long.class, long.class, long.class, boolean.class, boolean.class, boolean.class, long.class, long.class); m.setAccessible(true); // invoke method with test parameters final long[] calculatedTime = (long[]) m.invoke(rg, from, to, duration, false, isFromRelative, isToRelative, TIMESTAMP_START, TEST_ELAPSED_TIME); // validate calculations Assert.assertEquals(description + ": FROM", expectedFrom, calculatedTime[0]); Assert.assertEquals(description + ": TO", expectedTo, calculatedTime[1]); } }
true
8dd8000d4c251a6bf371912e1e63eea894585b9b
Java
pvnkmrksk/NCBSinfo
/app/src/main/java/com/rohitsuratekar/NCBSinfo/database/NotificationData.java
UTF-8
3,729
2.65625
3
[]
no_license
package com.rohitsuratekar.NCBSinfo.database; import android.content.ContentValues; import android.content.Context; import android.database.Cursor; import android.database.sqlite.SQLiteDatabase; import com.rohitsuratekar.NCBSinfo.database.models.NotificationModel; import java.util.ArrayList; import java.util.List; public class NotificationData { //Public constants //Do not change names. If you want, create new table and copy data from here public static final String TABLE_NOTIFICATIONS = "table_notifications"; public static final String KEY_ID = "notification_id"; public static final String TIMESTAMP = "notification_timestamp"; public static final String TITLE = "notification_title"; public static final String MESSAGE = "notification_message"; public static final String FROM = "notification_from"; public static final String EXTRA_VARIABLES = "notification_extravariables"; SQLiteDatabase db; public NotificationData(Context context) { Database db = new Database(context); this.db = db.getWritableDatabase(); } public void add(NotificationModel notification) { ContentValues values = new ContentValues(); values.put(TIMESTAMP, notification.getTimestamp()); values.put(TITLE, notification.getTitle()); values.put(MESSAGE, notification.getMessage()); values.put(FROM, notification.getFrom()); values.put(EXTRA_VARIABLES, notification.getExtraVariables()); // Inserting Row db.insert(TABLE_NOTIFICATIONS, null, values); db.close(); } public NotificationModel get(int id) { Cursor cursor = db.query(TABLE_NOTIFICATIONS, new String[] { KEY_ID, TIMESTAMP, TITLE, MESSAGE, FROM, EXTRA_VARIABLES }, KEY_ID + "=?", new String[] { String.valueOf(id) }, null, null, null, null); if (cursor != null){ cursor.moveToFirst(); } NotificationModel notification = new NotificationModel(cursor.getInt(0),cursor.getString(1), cursor.getString(2), cursor.getString(3), cursor.getString(4), cursor.getString(5)); // return contact cursor.close(); return notification; } public List<NotificationModel> getAll() { List<NotificationModel> notificationModelList = new ArrayList<NotificationModel>(); // Select All Query String selectQuery = "SELECT * FROM " + TABLE_NOTIFICATIONS; Cursor cursor = db.rawQuery(selectQuery, null); // looping through all rows and adding to list if (cursor.moveToFirst()) { do { NotificationModel notificationModel = new NotificationModel(); notificationModel.setId(Integer.parseInt(cursor.getString(0))); notificationModel.setTimestamp(cursor.getString(1)); notificationModel.setTitle(cursor.getString(2)); notificationModel.setMessage(cursor.getString(3)); notificationModel.setFrom(cursor.getString(4)); notificationModel.setExtraVariables(cursor.getString(5)); // Adding contact to list notificationModelList.add(notificationModel); } while (cursor.moveToNext()); } // return contact list cursor.close(); return notificationModelList; } // Delete all data public void clearAll() { db.execSQL("DELETE FROM " + TABLE_NOTIFICATIONS); db.close(); } // Deleting single contact public void delete(NotificationModel notification) { db.delete(TABLE_NOTIFICATIONS, KEY_ID + " = ?", new String[] { String.valueOf(notification.getId()) }); db.close(); } }
true
0dc379c1851acc1e7c2f699cee94349e39e0f186
Java
iarzaesteban/PAW_Unlu
/proyectos/Pto7/Cliente.java
UTF-8
3,339
3.25
3
[]
no_license
package Pto7; import java.rmi.NotBoundException; import java.rmi.RemoteException; import java.rmi.registry.LocateRegistry; import java.rmi.registry.Registry; import java.util.Scanner; import javax.swing.JOptionPane; public class Cliente { public static void main(String[] args) { try { Registry clientRMI = LocateRegistry.getRegistry("127.0.0.1", 33333); System.out.println("Lista de servicios disponibles: "); String[] services = clientRMI.list(); /*for (String service : services) { System.out.println(service); }*/ InterfazServer servicios = (InterfazServer) clientRMI.lookup(services[0]); menuPrincipal(servicios); } catch (RemoteException e) { e.printStackTrace(); } catch (NotBoundException e) { e.printStackTrace(); } } private static void menuPrincipal(InterfazServer servicios) { Scanner op = new Scanner(System.in); System.err.println("Escoja una opcion: "); System.out.println("1- Calcular numero random"); System.out.println("2- Verificar un numero si es primo o no"); System.out.println("3- Ver precision del numero PI"); System.out.println("0- Salir"); int opcion = op.nextInt(); while (opcion != 0) { switch (opcion) { case 1: numRandom(servicios); menuPrincipal(servicios); break; case 2: verPrimo(servicios); menuPrincipal(servicios); break; case 3: precisionPI(servicios); menuPrincipal(servicios); break; } } } private static void numRandom(InterfazServer servicios) { //Numero Random System.out.println("Operacion numero random "); NumeroRandom random = new NumeroRandom(); System.out.println("Ingrese desde "); Scanner desde = new Scanner(System.in); random.desde = desde.nextInt(); System.out.println("Ingrese hasta "); Scanner hasta = new Scanner(System.in); random.rango = (hasta.nextInt() - random.desde) +1; try { System.out.println("El numero random es: "+servicios.ejecutarTareas(random)); System.out.println("-----------------------------------"); menuPrincipal(servicios); } catch (RemoteException e) { System.out.println("holaaaaa"); e.printStackTrace(); } } private static void verPrimo(InterfazServer servicios) { //Numero Primo NumeroPrimo primo = new NumeroPrimo(); System.out.println("Ingrese numero para verificar si es primo"); Scanner numPrimo = new Scanner(System.in); primo.numero = numPrimo.nextInt(); try { System.out.println("El numero "+primo.numero+" es primo? " +servicios.ejecutarTareas(primo)); System.out.println("-----------------------------------"); menuPrincipal(servicios); } catch (RemoteException e) { // TODO Auto-generated catch block e.printStackTrace(); } } private static void precisionPI(InterfazServer servicios) { //Valor de PI System.out.println("Ingrese numero de precision para el calculo de PI"); ValorPI vPI = new ValorPI(); Scanner preciosionPI = new Scanner(System.in); vPI.precision = preciosionPI.nextInt(); try { System.out.println("El numero PI calculado es: "+ servicios.ejecutarTareas(vPI)); System.out.println("-----------------------------------"); menuPrincipal(servicios); } catch (RemoteException e) { // TODO Auto-generated catch block e.printStackTrace(); } } }
true
c5381976700ef8c3056c914a1f1fc71f24803741
Java
flywind2/joeis
/src/irvine/oeis/a006/A006907.java
UTF-8
878
2.875
3
[]
no_license
package irvine.oeis.a006; import irvine.math.partitions.IntegerPartition; import irvine.math.partitions.MurnaghanNakayama; import irvine.math.z.Z; import irvine.oeis.Sequence; /** * A006907 Number of zeros in character table of symmetric group <code>S_n</code>. * @author Sean A. Irvine */ public class A006907 implements Sequence { private int mN = 0; protected boolean accept(final int v) { return v == 0; } @Override public Z next() { ++mN; long count = 0; int[] lambda; int[] mu; final IntegerPartition part1 = new IntegerPartition(mN); while ((lambda = part1.next()) != null) { final IntegerPartition part2 = new IntegerPartition(mN); while ((mu = part2.next()) != null) { if (accept(MurnaghanNakayama.character(lambda, mu).signum())) { ++count; } } } return Z.valueOf(count); } }
true
39bb1bde3288c0c4591d8c68889e33a29ba3ca99
Java
duncan1201/VF
/netbeans/gas/domain_core/src/com/gas/domain/core/msa/FastaImportService.java
UTF-8
1,783
2.046875
2
[]
no_license
/* * To change this template, choose Tools | Templates * and open the template in the editor. */ package com.gas.domain.core.msa; import com.gas.common.ui.FileFormat; import com.gas.domain.core.IFileImportService; import com.gas.domain.core.fasta.Fasta; import com.gas.domain.core.fasta.FastaParser; import com.gas.domain.core.msa.clustalw.ClustalwParam; import java.io.File; import java.util.Date; import java.util.EnumSet; import org.openide.util.lookup.ServiceProvider; /** * * @author dq */ @ServiceProvider(service = IFileImportService.class) public class FastaImportService implements IFileImportService { @Override public String[] getExtensions() { return FileFormat.FASTA.getExts(); } /** * @return MSA if more than one sequence in the file; AnnotatedSeq if only * one sequence */ @Override public Object receive(File file) { Object ret; FastaParser parser = new FastaParser(); Fasta fasta = parser.parse(file); if (fasta.getSeqCount() > 1) { MSA msa = new MSA(); msa.setName("Alignment"); msa.setLastModifiedDate(new Date()); msa.setEntries(fasta); msa.setDesc(String.format("Imported from %s", file.getAbsolutePath())); msa.setType(msa.isDnaByGuess() ? "DNA" : "Protein"); msa.setClustalwParam(new ClustalwParam()); msa.setLength(fasta.getLength()); ret = msa; } else if (fasta.getSeqCount() == 1) { ret = fasta; } else { ret = null; } return ret; } @Override public EnumSet<FileFormat> getSupportedFileFormats() { EnumSet<FileFormat> ret = EnumSet.of(FileFormat.FASTA); return ret; } }
true
6c42cd03008589990270af068eab696a14ab4db1
Java
samskivert/reversi
/src/main/java/com/samskivert/reversi/server/SimpleServer.java
UTF-8
3,604
2
2
[ "BSD-3-Clause" ]
permissive
// // Reversi - A reversi implementation built directly atop Narya/Nenya/Vilya // http://github.com/samskivert/reversi/blob/master/LICENSE package com.samskivert.reversi.server; import com.google.inject.Inject; import com.google.inject.Injector; import com.google.inject.Singleton; import com.threerings.util.Name; import com.threerings.presents.data.ClientObject; import com.threerings.crowd.client.PlaceController; import com.threerings.crowd.data.BodyObject; import com.threerings.crowd.server.CrowdServer; import com.threerings.parlor.game.data.GameConfig; import com.threerings.parlor.server.ParlorManager; import com.samskivert.reversi.client.SimpleService; import com.samskivert.reversi.data.SimpleMarshaller; import com.samskivert.reversi.game.client.ReversiController; import static com.samskivert.reversi.Log.log; /** * The main entry point for the simple server. */ @Singleton public class SimpleServer extends CrowdServer { /** Configures dependencies needed by the Simple services. */ public static class SimpleModule extends CrowdServer.CrowdModule { @Override protected void configure () { super.configure(); } } /** * The main entry point for the simple server. */ public static void main (String[] args) { runServer(new SimpleModule(), new PresentsServerModule(SimpleServer.class)); } @Override // from CrowdServer public void init (Injector injector) throws Exception { super.init(injector); // register ourselves as providing the toybox service _invmgr.registerProvider(new SimpleProvider() { public void clientReady (ClientObject caller) { // if we have no waiter, or our waiter logged off, make this player wait (note: // this doesn't handle disconnected players, a real match making service should be // more robust) if (_waiter == null || !_waiter.isActive()) { _waiter = (BodyObject)caller; } else { final Name[] players = new Name[] { _waiter.getVisibleName(), ((BodyObject)caller).getVisibleName() }; try { // create the game location and it will take over from here _plreg.createPlace(new SimpleGameConfig(players)); } catch (Exception e) { log.warning("Failed to create game", "players", players, e); } } } protected BodyObject _waiter; }, SimpleMarshaller.class, SimpleService.GROUP); log.info("Simple server initialized."); } protected static class SimpleGameConfig extends GameConfig { public SimpleGameConfig (Name[] players) { this.players = players; } public int getGameId () { return 1; } public String getGameIdent () { return "reversi"; } public PlaceController createController () { return new ReversiController(); } public String getManagerClassName () { // don't use ReversiManager.class.getName() here, as this class will be loaded into the // client, which won't have ReversiManager in its jar file return "com.samskivert.reversi.game.server.ReversiManager"; } } // inject the parlor manager to cause it to register with the system @Inject protected ParlorManager _parmgr; }
true
6c4d20f4e3baa3b7c70174786f697561b441ce24
Java
bingely/God
/app/src/main/java/com/meetrend/haopingdian/adatper/NewExecutorListAdapter.java
UTF-8
3,376
2.109375
2
[]
no_license
package com.meetrend.haopingdian.adatper; import java.util.List; import net.tsz.afinal.FinalBitmap; import android.content.Context; import android.net.Uri; import android.os.Handler; import android.util.Log; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.BaseAdapter; import android.widget.ImageView; import android.widget.TextView; import com.facebook.drawee.view.SimpleDraweeView; import com.meetrend.haopingdian.R; import com.meetrend.haopingdian.bean.Executor; import com.meetrend.haopingdian.env.Server; import com.meetrend.haopingdian.widget.RoundImageView; public class NewExecutorListAdapter extends BaseAdapter { private LayoutInflater mInflater; private List<Executor> list; private Context context; public NewExecutorListAdapter(Context context, List<Executor> list) { this.list = list; this.context = context; mInflater = LayoutInflater.from(context); } // 混合布局 enum ITEM_TYPE { ALPHABET, MEMBER; } private static final int ITEM_TYPE_COUNAT = ITEM_TYPE.values().length; @Override public int getItemViewType(int position) { return getType(position) == ITEM_TYPE.ALPHABET ? 0 : 1; } @Override public boolean isEnabled(int position) { return getType(position) != ITEM_TYPE.ALPHABET; } private ITEM_TYPE getType(int position) { Executor executor = list.get(position); boolean flag = (executor.pinyinName.length() == 1); return flag ? ITEM_TYPE.ALPHABET : ITEM_TYPE.MEMBER; } @Override public int getViewTypeCount() { return ITEM_TYPE_COUNAT; } @Override public int getCount() { return list.size(); } @Override public Object getItem(int position) { return list.get(position); } @Override public long getItemId(int position) { return 0; } @Override public View getView(int position, View convertView, ViewGroup parent) { Executor item = list.get(position); int type = this.getItemViewType(position); ViewHolder holder = null; if (convertView == null) { holder = new ViewHolder(); switch (type) { case 0: convertView = mInflater.inflate( R.layout.member_select_list_item_layout, null); holder.alphabet = (TextView) convertView .findViewById(R.id.tv_alphabet); break; case 1: convertView = mInflater.inflate(R.layout.new_item_executor, null); //头像 holder.avatar = (SimpleDraweeView) convertView .findViewById(R.id.iv_executor_avatar); //执行人姓名 holder.name = (TextView) convertView .findViewById(R.id.tv_executorr_name); //选中标识 holder.rb_execute = (ImageView) convertView .findViewById(R.id.select_img); break; } convertView.setTag(holder); } else { holder = (ViewHolder) convertView.getTag(); } switch (type) { case 0: holder.alphabet.setText(item.pinyinName); break; case 1: holder.avatar.setImageURI(Uri.parse( Server.BASE_URL + item.entity.avatarId)); holder.name.setText(item.entity.userName); if (item.isSelected) { holder.rb_execute.setImageResource(R.drawable.check_on); }else { holder.rb_execute.setImageResource(R.drawable.check_off); } break; } return convertView; } class ViewHolder { public SimpleDraweeView avatar; public TextView name; public TextView alphabet; public ImageView rb_execute; } }
true
7573c08562d52ce4d4f5d0809923d79be2a37a36
Java
my2969500039/siso-java
/service/src/main/java/com/siso/web/street/AdminStreetService.java
UTF-8
341
1.703125
2
[]
no_license
package com.siso.web.street; import com.siso.entity.web.market.adminMarket; import com.siso.entity.web.region.market; import java.util.List; public interface AdminStreetService { //返回用户管理商铺 List<adminMarket> admin_market(String userNumber); //根据id返回超市 List<market>market_id(String id); }
true
79d060ef5049ae061153d58e5d42e0f15d43e06a
Java
garnel111/Triggerise-BE-Challenge
/src/main/java/domain/Product.java
UTF-8
1,655
2.984375
3
[]
no_license
package domain; import java.util.ArrayList; import java.util.List; import java.util.Objects; public class Product { private String code; private String name; private float price; private List<Rule> rulesApllied = new ArrayList<Rule>(); public List<Rule> getRulesApllied() { return rulesApllied; } public void setRulesApllied(List<Rule> rulesApllied) { this.rulesApllied = rulesApllied; } public String getCode() { return this.code; } public void setCode(String code) { this.code = code; } public String getName() { return this.name; } /** * @param name */ public void setName(String name) { this.name = name; } public float getPrice() { return this.price; } /** * @param price */ public void setPrice(float price) { this.price = price; } public Product(String code, String name, float price) { this.code = code; this.name = name; this.price = price; } @Override public boolean equals(Object o) { if (this == o) return true; if (!(o instanceof Product)) return false; Product product = (Product) o; return Float.compare(product.getPrice(), getPrice()) == 0 && getCode().equals(product.getCode()) && getName().equals(product.getName()); } @Override public int hashCode() { return Objects.hash(getCode(), getName(), getPrice(), getRulesApllied()); } @Override public String toString() { return "ProductCode:" + getCode() ; } }
true
1cf60597e0adbf030dee34062f5575bf89e6c91d
Java
rbeard47/asteroids
/Asteroids/src/program/DisplayManager.java
UTF-8
3,833
2.453125
2
[]
no_license
package program; import models.IGameComponent; import org.lwjgl.glfw.GLFWErrorCallback; import org.lwjgl.glfw.GLFWKeyCallback; import org.lwjgl.glfw.GLFWVidMode; import org.lwjgl.opengl.GL; import org.lwjgl.opengl.GLUtil; import org.lwjgl.system.Callback; import org.lwjgl.system.MemoryStack; import java.nio.IntBuffer; import java.util.List; import java.util.Vector; import static org.lwjgl.glfw.GLFW.*; import static org.lwjgl.system.MemoryStack.stackPush; import static org.lwjgl.system.MemoryUtil.NULL; public class DisplayManager { private final static int width = 800; private final static int height = 600; private static List<IGameComponent> gameComponents; private static List<IGameComponent> registeredInputComponents; private long window; private GLFWKeyCallback keyCallback; Callback debugProc; public DisplayManager() { gameComponents = new Vector<>(); registeredInputComponents = new Vector<>(); } public static int getWidth() { return width; } public static int getHeight() { return height; } public boolean addGameComponent(IGameComponent c) { return gameComponents.add(c); } public boolean removeGameComponent(IGameComponent c) { return gameComponents.remove(c); } public List<IGameComponent> components() { return gameComponents; } public long getWindow() { return window; } public void registerForKeyboardEvents(IGameComponent c) { registeredInputComponents.add(c); } public int getScreenWidth() { return width; } public int getScreenHeight() { return height; } public void createDisplay() { GLFWErrorCallback.createPrint(System.err).set(); if (!glfwInit()) { throw new IllegalStateException("Unabled to initialize GLFW"); } glfwDefaultWindowHints(); glfwWindowHint(GLFW_CONTEXT_VERSION_MAJOR, 3); glfwWindowHint(GLFW_CONTEXT_VERSION_MINOR, 2); glfwWindowHint(GLFW_OPENGL_PROFILE, GLFW_OPENGL_CORE_PROFILE); glfwWindowHint(GLFW_OPENGL_FORWARD_COMPAT, GLFW_TRUE); window = glfwCreateWindow(width, height, "OpenGL", NULL, NULL); if (window == NULL) { throw new RuntimeException("Failed to create the GLFW window"); } glfwSetKeyCallback(window, keyCallback = new KeyboardHandler()); // Get the thread stack and push a new frame try (MemoryStack stack = stackPush()) { IntBuffer pWidth = stack.mallocInt(1); // int* IntBuffer pHeight = stack.mallocInt(1); // int* // Get the window size passed to glfwCreateWindow glfwGetWindowSize(window, pWidth, pHeight); // Get the resolution of the primary monitor GLFWVidMode vidmode = glfwGetVideoMode(glfwGetPrimaryMonitor()); if (vidmode == null) { throw new RuntimeException("Failed to get the video mode of the primary monitor"); } glfwSetWindowPos( window, (vidmode.width() - pWidth.get(0)) / 2, (vidmode.height() - pHeight.get(0)) / 2 ); } // the stack frame is popped automatically //glfwWindowHint(GLFW_OPENGL_DEBUG_CONTEXT, GLFW_TRUE); glfwMakeContextCurrent(window); // Enable v-sync glfwSwapInterval(1); // Make the window visible glfwShowWindow(window); GL.createCapabilities(); //debugProc = GLUtil.setupDebugMessageCallback(); } public void updateDisplay() { } public void closeDisplay() { glfwDestroyWindow(window); } public float getAspectRatio() { return width / height; } }
true
5dd6da73e2396dbff357e9819cf7089c4629eb21
Java
aNNiMON/aScheduler
/src/com/annimon/scheduler/model/FacultyModel.java
UTF-8
822
2.65625
3
[]
no_license
package com.annimon.scheduler.model; import com.annimon.scheduler.dao.IDAO; import com.annimon.scheduler.data.Faculties; /** * Модель таблицы факультетов. * @author aNNiMON */ public class FacultyModel extends EntityTableModel<Faculties> { private static final String[] COLUMN_NAMES = { "ID", "Название", "Сокращение" }; public FacultyModel(IDAO<Faculties> dao) { super(dao); initTableModel(); } @Override protected String[] getColumnNames() { return COLUMN_NAMES; } @Override protected Object[] fillRow(int index) { Faculties fc = getEntity(index); return new Object[] { fc.getId(), fc.getName(), fc.getAbbreviation() }; } }
true
3c2c3aad26500a385c7064f0f0bf8ceec9003714
Java
vladislove80/runCRM_android
/app/src/main/java/com/gorulia/android/runcrmrun/realm/SourceListResultModelRealm.java
UTF-8
617
2.0625
2
[]
no_license
package com.gorulia.android.runcrmrun.realm; import io.realm.RealmList; import io.realm.RealmObject; import io.realm.annotations.PrimaryKey; public class SourceListResultModelRealm extends RealmObject { private RealmList<SourceResultModelRealm> list = new RealmList<>(); @PrimaryKey private String id; public String getId() { return id; } public void setId(String id) { this.id = id; } public RealmList<SourceResultModelRealm> getList() { return list; } public void setList(RealmList<SourceResultModelRealm> list) { this.list = list; } }
true
a4dc6afd96d304aace3fe491d84e5208ac583309
Java
tugcenurdaglar/covid
/app/src/main/java/com/tugcenurdaglar/retro/retrofit/ApiUtils.java
UTF-8
285
1.976563
2
[]
no_license
package com.tugcenurdaglar.retro.retrofit; public class ApiUtils { public static final String BASE_URL = "https://api.covid19api.com/"; public static CovidInterface getCovidInterface(){ return RetrofitClient.getClient(BASE_URL).create(CovidInterface.class); } }
true
3db5491fee30e2c60f7a372fb003ff4c3c00664b
Java
Longi94/Phoebe
/src/view/PickupView.java
UTF-8
1,292
3.046875
3
[]
no_license
package view; import model.Pickup; import java.awt.*; /** * Pickup kinézete * * @author Gergely Reményi * @since 2015.04.25. */ public class PickupView extends TrackObjectBaseView { //Referencia az objhektumra amit ki kell rajzolni. private Pickup pickup; /** * Konstruktor * * @param pickup az objektum amihez a view tartozik * @param tv a pálya nézet amire ki kell rajzolni */ public PickupView(Pickup pickup, TrackView tv) { super(pickup, tv); this.pickup = pickup; } /** * Pickup kirajzolása. * * @param graph amire rajzol * @param xOffset x eltolás * @param yOffset y eltolás * @param zoom nagyítás */ public void draw(Graphics graph, double xOffset, double yOffset, double zoom) { graph.setColor(Color.orange); int radius = (int) (pickup.getRadius() * zoom * 2); graph.fillOval(pickup.getPos().convertX(xOffset, zoom) - radius / 2, pickup.getPos().convertY(yOffset, zoom) - radius / 2, radius, radius); graph.setColor(Color.blue); graph.fillOval(pickup.getPos().convertX(xOffset, zoom) - radius / 4, pickup.getPos().convertY(yOffset, zoom) - radius / 4, radius / 2, radius / 2); } }
true
01cf7140495161f16de5e5feec1c6d2b51edc997
Java
armandgray/taapProject
/TAAP/phone/src/main/java/com/armandgray/taap/utils/MVCActivity.java
UTF-8
2,795
2.046875
2
[ "MIT" ]
permissive
package com.armandgray.taap.utils; import android.os.Bundle; import androidx.annotation.NonNull; import androidx.annotation.Nullable; import androidx.annotation.VisibleForTesting; import com.google.android.material.floatingactionbutton.FloatingActionButton; import androidx.appcompat.app.AppCompatActivity; import androidx.appcompat.widget.Toolbar; import android.view.Menu; import android.view.MenuItem; import android.view.MotionEvent; import android.view.View; import com.armandgray.taap.R; /** * Created by armandgray on 1/12/18. */ public abstract class MVCActivity< T extends ActivitySetupHelper.ActivityViewsInterface, U extends MVCActivityController > extends AppCompatActivity { @VisibleForTesting public T views; @VisibleForTesting public U controller; @NonNull protected View rootView; @Nullable protected Toolbar toolbar; @Nullable protected FloatingActionButton fab; private int menuId; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); } @Override public boolean onCreateOptionsMenu(Menu menu) { if (menuId == 0) { return false; } getMenuInflater().inflate(menuId, menu); return controller.onCreateOptionsMenu(menu); } @Override public boolean onOptionsItemSelected(MenuItem item) { controller.onOptionsItemSelected(item); return super.onOptionsItemSelected(item); } @Override public boolean dispatchTouchEvent(MotionEvent ev) { controller.dispatchTouchEvent(getCurrentFocus(), ev); return super.dispatchTouchEvent(ev); } public void setupActivity(int layoutId) { setContentView(layoutId); this.rootView = findViewById(android.R.id.content).getRootView(); assert this.rootView != null; this.toolbar = (Toolbar) rootView.findViewById(R.id.toolbar); this.fab = (FloatingActionButton) rootView.findViewById(R.id.fab); setSupportActionBar(toolbar); } public void setupActivity(int layoutId, int menuId) { setupActivity(layoutId); this.menuId = menuId; } protected void setViews(T views) { this.views = views; } protected void setController(U controller) { this.controller = controller; } @Override protected void onStart() { super.onStart(); if (controller == null) { throw new IllegalArgumentException(getLocalClassName() + " must assign controller (ie. Call setController())"); } if (views == null) { throw new IllegalArgumentException(getLocalClassName() + " must assign views (ie. Call setViews())"); } } }
true
bba63aff54e2a09fb3d5d374b8c9550fbcae9ca0
Java
rocioruizruiz/Java-Basics
/src/patrones/Decorator/Programa.java
UTF-8
884
3.390625
3
[]
no_license
package patrones.Decorator; /* * El patron Decorator añade funcionalidad a una clase de forma dinamica */ public class Programa { public static void main(String[] args) { Mascota gato = new Gato("Felix"); Mascota perro = new Perro("Golfo"); System.out.println(perro.getCaracteristicas()); System.out.println(gato.getCaracteristicas()); Mascota perroNadador = new Nadador(perro); System.out.println(perroNadador.getCaracteristicas()); Mascota perroSaltador = new Saltador(perro); System.out.println(perroSaltador.getCaracteristicas()); Mascota perroNadadorYSaltador = new Saltador(perroNadador); System.out.println(perroNadadorYSaltador.getCaracteristicas()); Mascota gatoNadador = new Nadador(new Gato("Silvestre")); System.out.println(gatoNadador.getCaracteristicas()); // Mascota perroNadador = new Nadador(perro); } }
true
91d50dcf8d95ddf3176d439af576875d20b11cfc
Java
likzn/Array
/src/LeetCode/DP/Leet357.java
UTF-8
398
2.859375
3
[]
no_license
package LeetCode.DP; /** * @author: Li jx * @date: 2019/8/13 17:03 * @description: */ public class Leet357 { public int countNumbersWithUniqueDigits(int n) { int[] dp = new int[n + 1]; dp[0] = 1; dp[1] = 10; for (int i = 2; i < n + 1; i++) { dp[i] = dp[i - 1] + (dp[i - 1] - dp[i - 2]) * (10 - (i - 1)); } return dp[n]; } }
true
df030cdf9a39e8641b681e1b9af5194496de38df
Java
tiagoferezin/faculdadeCodigos
/Proj4-1sem2015/src/br/com/cuml/dao/ConexaoFactory.java
MacCentralEurope
502
2.5
2
[]
no_license
package br.com.cuml.dao; import java.sql.Connection; import java.sql.DriverManager; import java.sql.SQLException; public class ConexaoFactory { public Connection getConexao() throws SQLException { Connection retorno = null; DriverManager.registerDriver(new oracle.jdbc.driver.OracleDriver()); retorno = DriverManager.getConnection( "jdbc:oracle:thin:@localhost:1521:xe", "tferezin", "152535"); System.out.println("CONEXO CRIADA COM SUCESSO"); return retorno; } }
true
4813d05ae606b02eaee46405033aec27d3fa0e93
Java
wiwqy/duboo-master
/mainsite/src/main/java/com/test/AppStart.java
UTF-8
580
1.65625
2
[]
no_license
package com.test; import javax.sql.DataSource; import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.EnableAutoConfiguration; import org.springframework.context.annotation.ComponentScan; import org.springframework.context.annotation.ImportResource; @ComponentScan @EnableAutoConfiguration(exclude={DataSource.class}) @ImportResource(value={"classpath:config/dubbo-register.xml","classpath:config/mvc-config.xml"}) public class AppStart { public static void main(String[] args) { SpringApplication.run(AppStart.class, args); } }
true
70f37eecdd648fe3fde81510075d35ce8364e68e
Java
arap-ngenoh/RealDriving
/src/users/InputController.java
UTF-8
5,782
2.09375
2
[]
no_license
package users; import com.jfoenix.controls.JFXButton; import com.jfoenix.controls.JFXComboBox; import enqure.EnqureController; import icons.DatabaseHandler; import java.net.URL; import java.sql.ResultSet; import java.sql.SQLException; import java.time.LocalDate; import java.util.Date; import java.util.ResourceBundle; import java.util.logging.Level; import java.util.logging.Logger; import javafx.collections.FXCollections; import javafx.collections.ObservableList; import javafx.event.ActionEvent; import javafx.fxml.FXML; import javafx.fxml.Initializable; import javafx.scene.control.Alert; import javafx.scene.control.DatePicker; import javafx.scene.control.TableColumn; import javafx.scene.control.TableView; import javafx.scene.control.TextField; import javafx.scene.control.cell.PropertyValueFactory; /** * FXML Controller class * * @author kRich */ public class InputController implements Initializable { ObservableList<InputModel> data = FXCollections.observableArrayList(); @FXML private JFXComboBox<String> type; @FXML private DatePicker date; @FXML private TextField amount; @FXML private JFXButton save; @FXML private TextField personel; @FXML private TableView<InputModel> p_display; @FXML private TableColumn<InputModel, Object> namecol; @FXML private TableColumn<InputModel, Integer> amountcol; @FXML private TableColumn<InputModel, Object> datecol; @FXML private TableColumn<InputModel, Object> typecol; @FXML private JFXButton clear1; /** * Initializes the controller class. */ @Override public void initialize(URL url, ResourceBundle rb) { type.getItems().removeAll( type.getItems()); type.getItems().addAll("Deposit","Withdraw"); initcol(); tablodoldur(); } public void clear(){ personel.clear(); amount.clear(); type.getSelectionModel().clearSelection(); } @FXML private void save(ActionEvent event) { String typee= type.getSelectionModel().getSelectedItem(); LocalDate dat=date.getValue(); String amount1=amount.getText(); String personel1=personel.getText(); Boolean flag=type.getSelectionModel().isEmpty()||amount1.isEmpty()||personel1.isEmpty(); if(flag){ Alert alert=new Alert(Alert.AlertType.ERROR); alert.setContentText("This Fields Should Not Be Blank"); alert.showAndWait(); alert.close(); } try { int amnt=Integer.parseInt(amount1); String query = "INSERT INTO bank(type,personel,dat,amounr) VALUES (" +"'"+typee+"',"+ "'"+ personel1+"',"+ "'"+date.getValue()+"',"+ ""+amnt+""+ ")"; DatabaseHandler handler = DatabaseHandler.getInstance(); if( handler.execAction(query)){ Alert alert=new Alert(Alert.AlertType.INFORMATION); alert.setContentText("You've added Records Succefully"); alert.showAndWait(); alert.close(); clear(); } else{ Alert alert=new Alert(Alert.AlertType.ERROR); alert.setContentText("error in adding expenses please try again"); alert.showAndWait(); alert.close(); } } catch(Exception e){ } } private void clear(ActionEvent event) { clear(); } private void initcol() { namecol.setCellValueFactory(new PropertyValueFactory<>("personel")); amountcol.setCellValueFactory(new PropertyValueFactory<>("amount")); datecol.setCellValueFactory(new PropertyValueFactory<>("dat")); typecol.setCellValueFactory(new PropertyValueFactory<>("type")); } private void tablodoldur() { LocalDate time = LocalDate.now(); String i =time.toString(); data.clear(); data = FXCollections.observableArrayList(); try{ DatabaseHandler handler = DatabaseHandler.getInstance(); String SQL="SELECT personel, amounr,dat,type FROM bank WHERE dat like 'i";// ON student.id=fees.id ResultSet rs = handler.execQuery(SQL); while (rs.next()) { String name = rs.getString("personel").toUpperCase(); String typee = rs.getString("type").toUpperCase(); Date datee = rs.getDate("dat"); int hey= rs.getInt("amounr"); data.add(new InputController.InputModel(name,hey,datee,typee)); } } catch (SQLException ex) { Logger.getLogger(EnqureController.class.getName()).log(Level.SEVERE, null, ex); } p_display.setItems(data); } @FXML private void remarks(ActionEvent event) { } @FXML private void handleRefresh(ActionEvent event) { } @FXML private void clear1(ActionEvent event) { } public class InputModel{ String personel; int amount; Date dat; String type; public InputModel(String personel, int amount, Date dat, String type) { this.personel = personel; this.amount = amount; this.dat = dat; this.type = type; } public String getPersonel() { return personel; } public int getAmount() { return amount; } public Date getDat() { return dat; } public String getType() { return type; } } }
true
94f7e88052b008ac2c8f2d89fbbe9eb4f763669a
Java
fendo8888/fendo-shiro
/src/main/java/com/fendo/shiro/config/ThymeleafConfig.java
UTF-8
690
1.898438
2
[]
no_license
/** * projectName: fendo-plus-boot * fileName: ThymeleafConfig.java * packageName: com.fendo.shiro.config * date: 2018-01-20 12:47 * copyright(c) 2017-2020 xxx公司 */ package com.fendo.shiro.config; import com.fendo.shiro.common.dialect.dict.DictDialect; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; /** * @version: V1.0 * @author: fendo * @className: ThymeleafConfig * @packageName: com.fendo.shiro.config * @description: thymeleaf 配置 * @data: 2018-01-20 12:47 **/ @Configuration public class ThymeleafConfig { @Bean public DictDialect ditDialect(){ return new DictDialect(); } }
true
ecd187bbc3ca67184993b2b1ce06b1940f206ea6
Java
Flipkart/hive
/ql/src/java/org/apache/hadoop/hive/ql/index/AggregateIndexHandler.java
UTF-8
6,450
1.867188
2
[ "Apache-2.0", "JSON", "BSD-3-Clause", "MIT", "LicenseRef-scancode-unknown-license-reference", "Python-2.0", "GPL-1.0-or-later", "BSD-2-Clause" ]
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.apache.hadoop.hive.ql.index; import java.util.LinkedHashMap; import java.util.List; import java.util.Map; import java.util.Set; import org.apache.hadoop.hive.conf.HiveConf; import org.apache.hadoop.hive.metastore.api.FieldSchema; import org.apache.hadoop.hive.metastore.api.Index; import org.apache.hadoop.hive.metastore.api.StorageDescriptor; import org.apache.hadoop.hive.metastore.api.Table; import org.apache.hadoop.hive.ql.exec.Task; import org.apache.hadoop.hive.ql.hooks.ReadEntity; import org.apache.hadoop.hive.ql.hooks.WriteEntity; import org.apache.hadoop.hive.ql.index.compact.CompactIndexHandler; import org.apache.hadoop.hive.ql.metadata.HiveException; import org.apache.hadoop.hive.ql.metadata.HiveUtils; import org.apache.hadoop.hive.ql.metadata.VirtualColumn; import org.apache.hadoop.hive.ql.optimizer.IndexUtils; import org.apache.hadoop.hive.ql.plan.PartitionDesc; /** * Index handler for indexes that have aggregate functions on indexed columns. * */ public class AggregateIndexHandler extends CompactIndexHandler { @Override public void analyzeIndexDefinition(Table baseTable, Index index, Table indexTable) throws HiveException { StorageDescriptor storageDesc = index.getSd(); if (this.usesIndexTable() && indexTable != null) { StorageDescriptor indexTableSd = storageDesc.deepCopy(); List<FieldSchema> indexTblCols = indexTableSd.getCols(); FieldSchema bucketFileName = new FieldSchema("_bucketname", "string", ""); indexTblCols.add(bucketFileName); FieldSchema offSets = new FieldSchema("_offsets", "array<bigint>", ""); indexTblCols.add(offSets); Map<String, String> paraList = index.getParameters(); if(paraList != null && paraList.containsKey("AGGREGATES")){ String propValue = paraList.get("AGGREGATES"); if(propValue.contains(",")){ String[] aggFuncs = propValue.split(","); for (int i = 0; i < aggFuncs.length; i++) { createAggregationFunction(indexTblCols, aggFuncs[i]); } }else{ createAggregationFunction(indexTblCols, propValue); } } indexTable.setSd(indexTableSd); } } private void createAggregationFunction(List<FieldSchema> indexTblCols, String property){ String[] aggFuncCol = property.split("\\("); String funcName = aggFuncCol[0]; String colName = aggFuncCol[1].substring(0, aggFuncCol[1].length() - 1); if(colName.contains("*")){ colName = colName.replace("*", "all"); } FieldSchema aggregationFunction = new FieldSchema("_" + funcName + "_of_" + colName + "", "bigint", ""); indexTblCols.add(aggregationFunction); } @Override protected Task<?> getIndexBuilderMapRedTask(Set<ReadEntity> inputs, Set<WriteEntity> outputs, Index index, boolean partitioned, PartitionDesc indexTblPartDesc, String indexTableName, PartitionDesc baseTablePartDesc, String baseTableName, String dbName) { List<FieldSchema> indexField = index.getSd().getCols(); String indexCols = HiveUtils.getUnparsedColumnNamesFromFieldSchema(indexField); //form a new insert overwrite query. StringBuilder command= new StringBuilder(); Map<String, String> partSpec = indexTblPartDesc.getPartSpec(); command.append("INSERT OVERWRITE TABLE " + HiveUtils.unparseIdentifier(indexTableName)); if (partitioned && indexTblPartDesc != null) { command.append(" PARTITION ( "); List<String> ret = getPartKVPairStringArray((LinkedHashMap<String, String>) partSpec); for (int i = 0; i < ret.size(); i++) { String partKV = ret.get(i); command.append(partKV); if (i < ret.size() - 1) { command.append(","); } } command.append(" ) "); } command.append(" SELECT "); command.append(indexCols); command.append(","); command.append(VirtualColumn.FILENAME.getName()); command.append(","); command.append(" collect_set ("); command.append(VirtualColumn.BLOCKOFFSET.getName()); command.append(") "); command.append(","); assert indexField.size()==1; Map<String, String> paraList = index.getParameters(); if(paraList != null && paraList.containsKey("AGGREGATES")){ command.append(paraList.get("AGGREGATES") + " "); } command.append(" FROM " + HiveUtils.unparseIdentifier(baseTableName)); Map<String, String> basePartSpec = baseTablePartDesc.getPartSpec(); if(basePartSpec != null) { command.append(" WHERE "); List<String> pkv = getPartKVPairStringArray((LinkedHashMap<String, String>) basePartSpec); for (int i = 0; i < pkv.size(); i++) { String partKV = pkv.get(i); command.append(partKV); if (i < pkv.size() - 1) { command.append(" AND "); } } } command.append(" GROUP BY "); command.append(indexCols + ", " + VirtualColumn.FILENAME.getName()); HiveConf builderConf = new HiveConf(getConf(), AggregateIndexHandler.class); builderConf.setBoolVar(HiveConf.ConfVars.HIVEMERGEMAPFILES, false); builderConf.setBoolVar(HiveConf.ConfVars.HIVEMERGEMAPREDFILES, false); builderConf.setBoolVar(HiveConf.ConfVars.HIVEMERGETEZFILES, false); Task<?> rootTask = IndexUtils.createRootTask(builderConf, inputs, outputs, command, (LinkedHashMap<String, String>) partSpec, indexTableName, dbName); return rootTask; } }
true
af31768c050196d98450058467815c5db9f25111
Java
IamClown/Android
/testRecyclerView/app/src/main/java/com/example/zyj/testrecyclerview/Fruit.java
UTF-8
423
2.53125
3
[]
no_license
package com.example.zyj.testrecyclerview; /** * Created by zyj on 2018/4/20. */ public class Fruit { private String fruitname; private int fruitiamge; public Fruit(String fruitname,int fruitiamge){ this.fruitiamge=fruitiamge; this.fruitname=fruitname; } public String getFruitname(){ return fruitname; } public int getFruitiamge(){ return fruitiamge; } }
true
165448a89f6c7b14cf9b78553a4398094cc5964a
Java
Shaoziyi/RTMDashboard
/src/test/java/VGCAutomationTesting/RTMDashboard/NewTest.java
UTF-8
1,120
2.203125
2
[]
no_license
package VGCAutomationTesting.RTMDashboard; import org.openqa.selenium.By; import org.openqa.selenium.WebDriver; import org.openqa.selenium.WebElement; import org.openqa.selenium.ie.InternetExplorerDriver; import org.testng.annotations.AfterMethod; import org.testng.annotations.BeforeMethod; import org.testng.annotations.Test; public class NewTest { private static WebDriver driver = null; @Test public void f() { System.setProperty("webdriver.ie.driver", "C:\\Users\\shaozi-y\\seleniumnode\\IEDriverServer.exe"); driver = new InternetExplorerDriver(); driver.get("http://www.baidu.com"); //浏览器访问百度 driver.manage().window().maximize();//浏览器maximize为100% System.out.println("1 page Title is :" + driver.getTitle());//获取网页的title final WebElement element = driver.findElement(By.id("kw"));//通过网页元素的id寻找百度的DOM element.sendKeys("读大学到底读什么");//输入搜索字 element.submit();//提交至百度所在的form driver.close(); } @BeforeMethod public void beforeMethod() { } @AfterMethod public void afterMethod() { } }
true
a27e3acfbc328d5ac2aaba4b2e1bada8a28ef520
Java
wumpz/fluent-dsl
/fluentdsl-maven-plugin/src/main/java/org/tw/fluentdsl/Idef.java
UTF-8
2,695
2.09375
2
[]
no_license
/* * #%L * fluentdsl-maven-plugin * %% * Copyright (C) 2016 fluentdsl * %% * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation, either version 2.1 of the * License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Lesser Public License for more details. * * You should have received a copy of the GNU General Lesser Public * License along with this program. If not, see * <http://www.gnu.org/licenses/lgpl-2.1.html>. * #L% */ package org.tw.fluentdsl; import java.util.ArrayList; import java.util.HashSet; import java.util.List; import java.util.Set; /** * Interface definition. * * @author toben */ class Idef { private final String name; private final List<Mdef> methods = new ArrayList<>(); private boolean hidden; public Idef(String name) { this(false, name); } public Idef(boolean hidden, String name) { this.hidden = hidden; this.name = name; } public String getName() { return name; } public List<Mdef> getMethods() { return methods; } private void addReturnTypeToAllVoidMethods(Set<Idef> processed, Idef idef, boolean recursive) throws FluentDslException { if (processed.contains(this)) { return; } processed.add(this); for (Mdef mdef : methods) { if (mdef.getSimpleReturnType() == null) { if (mdef.getReturnType() == null) { mdef.setReturnType(idef); } else if (recursive) { mdef.getReturnType().addReturnTypeToAllVoidMethods(processed, idef, recursive); } } } } public void addReturnTypeToAllVoidMethods(Idef idef, boolean recursive) throws FluentDslException { addReturnTypeToAllVoidMethods(new HashSet<Idef>(), idef, recursive); } public void addReturnTypeToAllVoidMethods(Idef idef) throws FluentDslException { addReturnTypeToAllVoidMethods(idef, false); } public boolean allReturnTypesSet() { for (Mdef mdef : methods) { if (mdef.getReturnType() == null) { return false; } } return true; } public boolean isHidden() { return hidden; } @Override public String toString() { return "Idef{" + "name=" + name + '}'; } }
true
cda88ee8a1ce31955401ab8f9d7fc6edf0677fb7
Java
ppk19052014/ppk
/dao/src/main/java/com/luxoft/vklinduhov/football/beans/Club.java
UTF-8
3,131
2.46875
2
[]
no_license
package com.luxoft.vklinduhov.football.beans; import org.springframework.data.mongodb.core.mapping.Document; import org.springframework.data.mongodb.core.mapping.Field; import org.springframework.format.annotation.DateTimeFormat; import java.util.ArrayList; import java.util.Date; import java.util.List; @Document(collection = "clubs") public class Club extends AbstractEntity{ @Field private String name; @Field private String foundDate; @Field private List<String> playerListId; @Field private String tournamentId; @Field private String tournamentName; public Club() { } public String getName() { return name; } public void setName(String name) { this.name = name; } public String getFoundDate() { return foundDate; } public void setFoundDate(String foundDate) { this.foundDate = foundDate; } public List<String> getPlayerListId() { return playerListId; } public void setPlayerListId(List<String> playerList) { this.playerListId = playerList; } public String getTournamentId() { return tournamentId; } public void setTournamentId(String tournamentId) { this.tournamentId = tournamentId; } public String getTournamentName() { return tournamentName; } public void setTournamentName(String tournamentName) { this.tournamentName = tournamentName; } public void addPlayerId(String playerId){ if(playerListId == null){ playerListId = new ArrayList<String>(); } playerListId.add(playerId); } @Override public boolean equals(Object o) { if (this == o) return true; if (o == null || getClass() != o.getClass()) return false; Club club = (Club) o; if (foundDate != null ? !foundDate.equals(club.foundDate) : club.foundDate != null) return false; if (name != null ? !name.equals(club.name) : club.name != null) return false; if (playerListId != null ? !playerListId.equals(club.playerListId) : club.playerListId != null) return false; if (tournamentId != null ? !tournamentId.equals(club.tournamentId) : club.tournamentId != null) return false; if (tournamentName != null ? !tournamentName.equals(club.tournamentName) : club.tournamentName != null) return false; return true; } @Override public int hashCode() { int result = name != null ? name.hashCode() : 0; result = 31 * result + (foundDate != null ? foundDate.hashCode() : 0); result = 31 * result + (playerListId != null ? playerListId.hashCode() : 0); result = 31 * result + (tournamentId != null ? tournamentId.hashCode() : 0); result = 31 * result + (tournamentName != null ? tournamentName.hashCode() : 0); return result; } @Override public String toString() { return name; } public List<String> getAllPlayersId() { return playerListId == null ? new ArrayList<String>() : new ArrayList<String>(playerListId); } }
true
1256e55ec7ebd389ef989ba610f8e0c290fea2db
Java
exedio/persistence
/runtime/testsrc/com/exedio/cope/ChangeHookDataBeforeTest.java
UTF-8
12,615
1.882813
2
[]
no_license
/* * Copyright (C) 2004-2015 exedio GmbH (www.exedio.com) * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 2.1 of the License, or (at your option) any later version. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA */ package com.exedio.cope; import static com.exedio.cope.instrument.Visibility.DEFAULT; import static com.exedio.cope.instrument.Visibility.NONE; import static java.nio.charset.StandardCharsets.US_ASCII; import static org.junit.jupiter.api.Assertions.assertAll; import static org.junit.jupiter.api.Assertions.assertEquals; import static org.junit.jupiter.api.Assertions.assertNotNull; import static org.junit.jupiter.api.Assertions.assertSame; import com.exedio.cope.DataField.ArrayValue; import com.exedio.cope.DataField.Value; import com.exedio.cope.instrument.Wrapper; import com.exedio.cope.instrument.WrapperInitial; import com.exedio.cope.instrument.WrapperType; import com.exedio.cope.junit.AssertionErrorChangeHook; import java.util.ArrayList; import java.util.Arrays; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; import org.opentest4j.AssertionFailedError; public class ChangeHookDataBeforeTest extends TestWithEnvironment { @Test void testDataOnlyCreate() { final MyItem i = new MyItem(encode("fieldVal")); assertAll( () -> assertEvents("Hook#new(field=fieldVal)"), () -> assertEquals("fieldVal / Hook#new", i.getField()), () -> assertEquals(null, i.getOther())); } @Test void testDataOnlyCreateDrop() { final MyItem i = new MyItem(encode("fieldVal(DROP)")); assertAll( () -> assertEvents("Hook#new(field=fieldVal(DROP))"), () -> assertEquals(null, i.getField()), () -> assertEquals(null, i.getOther())); } @Test void testDataOnlyCreateOther() { final MyItem i = new MyItem(encode("fieldVal(OTHER)")); assertAll( () -> assertEvents("Hook#new(field=fieldVal(OTHER))"), () -> assertEquals("fieldVal(OTHER) / Hook#new", i.getField()), () -> assertEquals("(OTHERnew)", i.getOther())); } @Test void testDataOnlyCreateOtherDrop() { final MyItem i = new MyItem(encode("fieldVal(OTHER)(DROP)")); assertAll( () -> assertEvents("Hook#new(field=fieldVal(OTHER)(DROP))"), () -> assertEquals(null, i.getField()), () -> assertEquals("(OTHERnew)", i.getOther())); } @Test void testDataOnlyMset() { final MyItem i = newMyItem(); i.setFieldMulti(encode("fieldVal")); assertAll( () -> assertEvents("Hook#set("+i+",field=fieldVal)"), () -> assertEquals("fieldVal / Hook#set", i.getField()), () -> assertEquals(null, i.getOther())); } @Test void testDataOnlyMsetDrop() { final MyItem i = newMyItem(); i.setFieldMulti(encode("fieldVal(DROP)")); assertAll( () -> assertEvents("Hook#set("+i+",field=fieldVal(DROP))"), () -> assertEquals(null, i.getField()), () -> assertEquals(null, i.getOther())); } @Test void testDataOnlyMsetOther() { final MyItem i = newMyItem(); i.setFieldMulti(encode("fieldVal(OTHER)")); assertAll( () -> assertEvents("Hook#set("+i+",field=fieldVal(OTHER))"), () -> assertEquals("fieldVal(OTHER) / Hook#set", i.getField()), () -> assertEquals("(OTHERset)", i.getOther())); } @Test void testDataOnlyMsetOtherDrop() { final MyItem i = newMyItem(); i.setFieldMulti(encode("fieldVal(OTHER)(DROP)")); assertAll( () -> assertEvents("Hook#set("+i+",field=fieldVal(OTHER)(DROP))"), () -> assertEquals(null, i.getField()), () -> assertEquals("(OTHERset)", i.getOther())); } @Test void testDataOnlySet() { final MyItem i = newMyItem(); i.setField(encode("fieldVal")); assertAll( () -> assertEvents("Hook#set("+i+",field=fieldVal)"), () -> assertEquals("fieldVal / Hook#set", i.getField()), () -> assertEquals(null, i.getOther())); } @Test void testDataOnlySetDrop() { final MyItem i = newMyItem(); i.setField(encode("fieldVal(DROP)")); assertAll( () -> assertEvents("Hook#set("+i+",field=fieldVal(DROP))"), () -> assertEquals(null, i.getField()), () -> assertEquals(null, i.getOther())); } @Test void testDataOnlySetOther() { final MyItem i = newMyItem(); i.setField(encode("fieldVal(OTHER)")); assertAll( () -> assertEvents("Hook#set("+i+",field=fieldVal(OTHER))"), () -> assertEquals("fieldVal(OTHER) / Hook#set", i.getField()), () -> assertEquals("(OTHERset)", i.getOther())); } @Test void testDataOnlySetOtherDrop() { final MyItem i = newMyItem(); i.setField(encode("fieldVal(OTHER)(DROP)")); assertAll( () -> assertEvents("Hook#set("+i+",field=fieldVal(OTHER)(DROP))"), () -> assertEquals(null, i.getField()), () -> assertEquals("(OTHERset)", i.getOther())); } @Test void testOtherOnlyCreate() { final MyItem i = new MyItem("otherVal"); assertAll( () -> assertEvents("Hook#new(other=otherVal)"), () -> assertEquals(null, i.getField()), () -> assertEquals("otherVal / Hook#new", i.getOther())); } @Test void testOtherOnlyCreateField() { final MyItem i = new MyItem("otherVal(FIELD)"); assertAll( () -> assertEvents("Hook#new(other=otherVal(FIELD))"), () -> assertEquals("(FIELDnew)", i.getField()), () -> assertEquals("otherVal(FIELD) / Hook#new", i.getOther())); } @Test void testOtherOnlySet() { final MyItem i = newMyItem(); i.setOther("otherVal"); assertAll( () -> assertEvents("Hook#set("+i+",other=otherVal)"), () -> assertEquals(null, i.getField()), () -> assertEquals("otherVal / Hook#set", i.getOther())); } @Test void testOtherOnlySetField() { final MyItem i = newMyItem(); i.setOther("otherVal(FIELD)"); assertAll( () -> assertEvents("Hook#set("+i+",other=otherVal(FIELD))"), () -> assertEquals("(FIELDset)", i.getField()), () -> assertEquals("otherVal(FIELD) / Hook#set", i.getOther())); } private static MyItem newMyItem() { final MyItem result = new MyItem(); assertEvents("Hook#new()"); assertEquals(null, result.getField()); assertEquals(null, result.getOther()); return result; } @WrapperType(indent=2, comments=false) private static final class MyItem extends Item { @Wrapper(wrap="*", visibility=NONE) @Wrapper(wrap="getArray", visibility=DEFAULT) @Wrapper(wrap="set", parameters=Value.class, visibility=DEFAULT) @WrapperInitial static final DataField field = new DataField().optional().lengthMax(500); @WrapperInitial static final StringField other = new StringField().optional(); String getField() { final byte[] array = getFieldArray(); return array!=null ? new String(array, US_ASCII) : null; } void setFieldMulti(final Value field) { set(SetValue.map(MyItem.field, field)); } MyItem() { this(SetValue.EMPTY_ARRAY); } MyItem(final Value field) { this(SetValue.map(MyItem.field, field)); } MyItem(final String other) { this(SetValue.map(MyItem.other, other)); } @com.exedio.cope.instrument.Generated @java.lang.SuppressWarnings({"RedundantSuppression","TypeParameterExtendsFinalClass","UnnecessarilyQualifiedInnerClassAccess"}) private MyItem( @javax.annotation.Nullable final com.exedio.cope.DataField.Value field, @javax.annotation.Nullable final java.lang.String other) throws com.exedio.cope.StringLengthViolationException { this(new com.exedio.cope.SetValue<?>[]{ com.exedio.cope.SetValue.map(MyItem.field,field), com.exedio.cope.SetValue.map(MyItem.other,other), }); } @com.exedio.cope.instrument.Generated private MyItem(final com.exedio.cope.SetValue<?>... setValues){super(setValues);} @com.exedio.cope.instrument.Generated @java.lang.SuppressWarnings({"RedundantSuppression","TypeParameterExtendsFinalClass","UnnecessarilyQualifiedStaticUsage"}) @javax.annotation.Nullable byte[] getFieldArray() { return MyItem.field.getArray(this); } @com.exedio.cope.instrument.Generated @java.lang.SuppressWarnings({"RedundantSuppression","TypeParameterExtendsFinalClass","UnnecessarilyQualifiedStaticUsage"}) void setField(@javax.annotation.Nullable final com.exedio.cope.DataField.Value field) { MyItem.field.set(this,field); } @com.exedio.cope.instrument.Generated @java.lang.SuppressWarnings({"RedundantSuppression","TypeParameterExtendsFinalClass","UnnecessarilyQualifiedStaticUsage"}) @javax.annotation.Nullable java.lang.String getOther() { return MyItem.other.get(this); } @com.exedio.cope.instrument.Generated @java.lang.SuppressWarnings({"RedundantSuppression","TypeParameterExtendsFinalClass","UnnecessarilyQualifiedStaticUsage"}) void setOther(@javax.annotation.Nullable final java.lang.String other) throws com.exedio.cope.StringLengthViolationException { MyItem.other.set(this,other); } @com.exedio.cope.instrument.Generated private static final long serialVersionUID = 1l; @com.exedio.cope.instrument.Generated private static final com.exedio.cope.Type<MyItem> TYPE = com.exedio.cope.TypesBound.newType(MyItem.class,MyItem::new); @com.exedio.cope.instrument.Generated private MyItem(final com.exedio.cope.ActivationParameters ap){super(ap);} } static final class MyHook extends AssertionErrorChangeHook { private final Type<?> type; private final DataField field; private final StringField other; MyHook(final Model model) { type = model.getType("MyItem"); assertNotNull(type); field = (DataField)type.getFeature("field"); assertNotNull(field); other = (StringField)type.getFeature("other"); assertNotNull(other); } @Override public SetValue<?>[] beforeNew(final Type<?> type, final SetValue<?>[] sv) { assertSame(this.type, type); return before("new", null, sv); } @Override public SetValue<?>[] beforeSet(final Item item, final SetValue<?>[] sv) { return before("set", item, sv); } private SetValue<?>[] before(final String operation, final Item item, final SetValue<?>[] sv) { final StringBuilder bf = new StringBuilder("Hook#" + operation + "("); final ArrayList<SetValue<?>> result = new ArrayList<>(); if(item!=null) bf.append(item); for(final SetValue<?> s : sv) { final Field<?> settable = (Field<?>)s.settable; final String value; if(bf.charAt(bf.length()-1)!='(') bf.append(","); bf.append(settable.getName() + '='); if(settable==field) { value = decode(s.value); if(!value.contains("(DROP)")) result.add(SetValue.map(field, encode(value + " / Hook#" + operation))); } else if(settable==other) { value = (String)s.value; if(!value.contains("(DROP)")) result.add(SetValue.map(other, value + " / Hook#" + operation)); } else { throw new AssertionFailedError(settable.getID()); } bf.append(value); if(value.contains("(FIELD)")) result.add(SetValue.map(field, encode("(FIELD" + operation + ")"))); if(value.contains("(OTHER)")) result.add(SetValue.map(other, "(OTHER" + operation + ")")); } bf.append(")"); addEvent(bf.toString()); return result.toArray(SetValue.EMPTY_ARRAY); } @Override public void afterNew (final Item item) {} @Override public void beforeDelete(final Item item) {} } private static final ArrayList<String> events = new ArrayList<>(); @BeforeEach final void cleanEvents() { events.clear(); } private static void assertEvents(final String... logs) { assertEquals(Arrays.asList(logs), events); events.clear(); } @SuppressWarnings("MethodOnlyUsedFromInnerClass") private static void addEvent(final String event) { assertNotNull(event); events.add(event); } private static final Model MODEL = Model.builder(). add(MyItem.TYPE). changeHooks(MyHook::new). build(); public ChangeHookDataBeforeTest() { super(MODEL); } @SuppressWarnings("MethodOnlyUsedFromInnerClass") private static String decode(final Object v) { return new String(((ArrayValue)v).array, US_ASCII); } private static ArrayValue encode(final String s) { return (ArrayValue)DataField.toValue(s.getBytes(US_ASCII)); } }
true
db282e988b07411d868f289488c86a7e90fc6de0
Java
thedonlasha98/ecommerce
/src/main/java/com/ecommerce/web/service/ProductServiceImpl.java
UTF-8
8,187
2.09375
2
[]
no_license
package com.ecommerce.web.service; import com.ecommerce.web.jwt.domain.Account; import com.ecommerce.web.domain.Product; import com.ecommerce.web.domain.ProductHist; import com.ecommerce.web.domain.ProductsTransaction; import com.ecommerce.web.exception.ErrorMessage; import com.ecommerce.web.exception.GeneralException; import com.ecommerce.web.model.BuyProductDto; import com.ecommerce.web.model.ProductDto; import com.ecommerce.web.jwt.repository.AccountRepository; import com.ecommerce.web.ropository.ProductHistRepository; import com.ecommerce.web.ropository.ProductRepository; import com.ecommerce.web.ropository.ProductsTransactionRepository; import com.ecommerce.web.utils.Constant; import org.springframework.beans.BeanUtils; import org.springframework.stereotype.Service; import org.springframework.transaction.annotation.Transactional; import java.math.BigDecimal; import java.time.LocalDateTime; import java.util.List; import static java.math.BigDecimal.ZERO; @Service public class ProductServiceImpl implements ProductService { private final ProductRepository productRepository; private final ProductHistRepository productHistRepository; private final AccountRepository accountRepository; private final ProductsTransactionRepository productsTransactionRepository; public ProductServiceImpl(ProductRepository productRepository, ProductHistRepository productHistRepository, AccountRepository accountRepository, ProductsTransactionRepository productsTransactionRepository) { this.productRepository = productRepository; this.productHistRepository = productHistRepository; this.accountRepository = accountRepository; this.productsTransactionRepository = productsTransactionRepository; } public static final String ACTIVE = "A"; public static final String CLOSED = "C"; public static final String ADD = "ADD"; public static final String MODIFY = "MODIFY"; public static final String ADD_CURRENT = "ADD_CURRENT"; public static final String DELETE = "DELETE"; public static final String CLOSE = "CLOSE"; public static final String ACTIVATE = "ACTIVATE"; @Override public String addProduct(ProductDto productDto) { String result = "Check current products!"; Product productExt = productRepository.findByProductAndUserId(productDto.getProduct(), productDto.getUserId()); if (productExt == null) { Product product = new Product(); BeanUtils.copyProperties(productDto, product); product.setStatus(ACTIVE); product = productRepository.save(product); /** create log **/ createLog(product, ADD); result = "Product is registered successfully!"; } else if (productExt.getStatus().equals(ACTIVE)) { /** create log **/ createLog(productExt, ADD_CURRENT); /** add current quantity **/ productExt.setQuantity(productExt.getQuantity() + productDto.getQuantity()); productRepository.save(productExt); result = "Current product quantity Increased by " + productDto.getQuantity() + "!"; } return result; } @Override public String modifyProduct(ProductDto productDto) { Product product = productRepository.findByIdAndUserId(productDto.getProductId(), productDto.getUserId()) .orElseThrow(() -> new GeneralException(ErrorMessage.PRODUCT_NOT_FOUND_WITH_PROVIDED_ID_AND_USER_ID)); /** create log **/ createLog(product, MODIFY); /** modify **/ BeanUtils.copyProperties(productDto, product); productRepository.save(product); return "Product is modify!"; } @Override public void deleteProduct(Long id, Long userId) { Product product = productRepository.findByIdAndUserId(id, userId) .orElseThrow(() -> new GeneralException(ErrorMessage.PRODUCT_NOT_FOUND_WITH_PROVIDED_ID_AND_USER_ID)); /** create log **/ createLog(product, DELETE); /** delete **/ productRepository.delete(product); } @Override public void closeProduct(Long id, Long userId) { Product product = productRepository.findByIdAndUserId(id, userId) .orElseThrow(() -> new GeneralException(ErrorMessage.PRODUCT_NOT_FOUND_WITH_PROVIDED_ID_AND_USER_ID)); /** create log **/ createLog(product, CLOSE); /** close **/ product.setStatus(CLOSED); productRepository.save(product); } @Override public void activateProduct(Long id, Long userId) { Product product = productRepository.findByIdAndUserId(id, userId).orElseThrow(() -> new GeneralException(ErrorMessage.PRODUCT_NOT_FOUND_WITH_PROVIDED_ID_AND_USER_ID)); /** create log **/ createLog(product, ACTIVATE); /** activate **/ product.setStatus(ACTIVE); productRepository.save(product); } @Override public List<Product> getProducts() { return productRepository.findAllByStatusOrderByIdDesc(ACTIVE); } @Transactional @Override public void buyProduct(BuyProductDto buyProductDto) { Product product = productRepository.getProductById(buyProductDto.getProductId()); if (product.getQuantity() >= buyProductDto.getQuantity()) { Account ownersAccount = accountRepository.getAccountByUserId(product.getUserId()); Account buyersAccount = accountRepository.getAccountByUserId(buyProductDto.getUserId()); BigDecimal amount = product.getPrice().multiply(BigDecimal.valueOf(buyProductDto.getQuantity())); BigDecimal comAmount = amount.multiply(BigDecimal.TEN).divide(Constant.HUNDRED); BigDecimal netAmount = amount.subtract(comAmount); if (buyersAccount.getBalance().compareTo(amount) >= 0) { ProductsTransaction productsTransaction = createTransaction( buyProductDto.getProductId(), buyersAccount.getId(), ownersAccount.getId(), buyProductDto.getQuantity(), amount, comAmount); ownersAccount.setBalance(ownersAccount.getBalance().add(netAmount)); buyersAccount.setBalance(buyersAccount.getBalance().subtract(amount)); accountRepository.save(buyersAccount); accountRepository.save(ownersAccount); productsTransactionRepository.save(productsTransaction); product.setQuantity(product.getQuantity() - buyProductDto.getQuantity()); if (product.getQuantity().equals(ZERO)) { product.setStatus(CLOSED); } productRepository.save(product); } else { throw new GeneralException(ErrorMessage.NOT_ENOUGH_BALANCE); } } else { throw new GeneralException(ErrorMessage.NOT_ENOUGH_QUANTITY_IN_STOCK); } } public void createLog(Product product, String event) { ProductHist productHist = new ProductHist(); BeanUtils.copyProperties(product, productHist); productHist.setProductId(product.getId()); productHist.setInpSysDate(LocalDateTime.now()); productHist.setEvent(event); productHistRepository.save(productHist); } public ProductsTransaction createTransaction(long productId, Long buyersAcct, Long ownersAcct, Integer Quantity, BigDecimal amount, BigDecimal comAmount) { ProductsTransaction productsTransaction = new ProductsTransaction(); productsTransaction.setProductId(productId); productsTransaction.setFromAcctId(buyersAcct); productsTransaction.setToAcctId(ownersAcct); productsTransaction.setQuantity(Quantity); productsTransaction.setAmount(amount); productsTransaction.setComAmount(comAmount); productsTransaction.setInpSysdate(LocalDateTime.now()); return productsTransaction; } }
true
4e09c59dbbe2bf1b2b2fcb9af64df390b93a6eee
Java
lidong2631/DS_Algorithms
/Binary Indexed Tree.java
UTF-8
1,212
3.3125
3
[]
no_license
int constructBITree(int arr[], int n) { int[] BITree = new int[n+1]; for(int i=1; i<=n; i++) BITree[i] = 0; for(int i=0; i<n; i++) updateBIT(BITree, n, i, arr[i]); return BITree; } void updateBIT(int BITree[], int n, int index, int val) { index = index + 1; while(index<=n) { BITree[index]+=val; // add val to current node of BITree index+=index & (-index); // go to current node's parent } } int getSUm(int BITree[], int index) { int sum = 0; index = index + 1; while(index>0) { sum+=BITree[index]; // add current element of BITree to sum index-=index & (-index); // go to current node's parent } return sum; } we can get Range Sum in logarithmic time by applying getSum(r)-getSum(l-1) http://www.geeksforgeeks.org/binary-indexed-tree-or-fenwick-tree-2/ The section sums are defined in such a way that queries and modifications to the table are executed in asymptotically equivalent time - O(\log n) in the worst case The initial process of building the Fenwick tree over a table of values runs in O(n \log n) time we can get Range Sum in logarithmic time by applying getSum(r)-getSum(l-1) http://www.geeksforgeeks.org/binary-indexed-tree-or-fenwick-tree-2/
true
879750454825f86af0f39fc8f09927a52b181f08
Java
rcaneppele/clines
/src/main/java/br/com/caelum/clines/shared/infra/GlobalExceptionHandler.java
UTF-8
3,248
2.234375
2
[]
no_license
package br.com.caelum.clines.shared.infra; import br.com.caelum.clines.shared.exceptions.AircraftModelNotFoundException; import br.com.caelum.clines.shared.exceptions.LocationNotFoundException; import br.com.caelum.clines.shared.exceptions.ResourceAlreadyExistsException; import br.com.caelum.clines.shared.exceptions.ResourceNotFoundException; import br.com.caelum.clines.shared.exceptions.ViolationException; import lombok.extern.slf4j.Slf4j; import org.springframework.context.support.DefaultMessageSourceResolvable; import org.springframework.http.HttpStatus; import org.springframework.web.bind.MethodArgumentNotValidException; import org.springframework.web.bind.annotation.ExceptionHandler; import org.springframework.web.bind.annotation.ResponseStatus; import org.springframework.web.bind.annotation.RestControllerAdvice; @Slf4j @RestControllerAdvice public class GlobalExceptionHandler { @ExceptionHandler(ResourceNotFoundException.class) @ResponseStatus(HttpStatus.NOT_FOUND) void handle(ResourceNotFoundException e) { log.info("[RESOURCE_NOT_FOUND] {}", e.getMessage()); } @ExceptionHandler(AircraftModelNotFoundException.class) @ResponseStatus(HttpStatus.BAD_REQUEST) ErrorView handle(AircraftModelNotFoundException e) { var message = e.getMessage(); log.info("[AIRCRAFT_MODEL_NOT_FOUND] {}", message); var errorView = new ErrorView(); errorView.addGenericError(message); return errorView; } @ExceptionHandler(ResourceAlreadyExistsException.class) @ResponseStatus(HttpStatus.CONFLICT) ErrorView handle(ResourceAlreadyExistsException e) { var message = e.getMessage(); var errorView = new ErrorView(); log.info("[RESOURCE_ALREADY_EXISTS] {}", message); errorView.addGenericError(message); return errorView; } @ExceptionHandler(MethodArgumentNotValidException.class) @ResponseStatus(HttpStatus.BAD_REQUEST) ErrorView handle(MethodArgumentNotValidException e) { var bindingResult = e.getBindingResult(); var errorView = new ErrorView(); bindingResult.getGlobalErrors().stream() .map(DefaultMessageSourceResolvable::getDefaultMessage) .forEach(errorView::addGenericError); bindingResult.getFieldErrors() .forEach(f -> errorView.addFieldError(f.getField(), f.getDefaultMessage())); log.info("[VALIDATION_ERROR] {}", errorView); return errorView; } @ExceptionHandler(LocationNotFoundException.class) @ResponseStatus(HttpStatus.BAD_REQUEST) ErrorView handle(LocationNotFoundException e) { var message = e.getMessage(); log.info("[LOCATION_NOT_FOUND] {}", message); var errorView = new ErrorView(); errorView.addGenericError(message); return errorView; } @ExceptionHandler(ViolationException.class) @ResponseStatus(HttpStatus.BAD_REQUEST) ErrorView handle(ViolationException e) { var errorView = new ErrorView(); e.getViolations() .stream() .map(Throwable::getMessage) .forEach(errorView::addGenericError); return errorView; } }
true
a34b71c8d0c969a3dd934f24f921c45bcbadee2c
Java
dezren39/movies_dpope3
/src/edu/cvtc/web/servlets/SearchController.java
UTF-8
2,093
2.546875
3
[]
no_license
package edu.cvtc.web.servlets; import java.io.IOException; import java.util.List; import java.util.stream.Collectors; import javax.servlet.ServletException; import javax.servlet.annotation.WebServlet; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import edu.cvtc.web.dao.MovieDao; import edu.cvtc.web.dao.implementation.MovieDaoException; import edu.cvtc.web.dao.implementation.MovieDaoImpl; import edu.cvtc.web.model.Movie; /** * Servlet implementation class SearchController */ @WebServlet("/Search") public class SearchController extends HttpServlet { private static final long serialVersionUID = 1L; /** * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response) */ protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { String target = null; try { final MovieDao movieDao = new MovieDaoImpl(); final List<Movie> movies = movieDao.retrieveMovies(); final String title = request.getParameter("title"); final String director = request.getParameter("director"); final List<Movie> filteredMovies = movies .stream() .filter((movie) -> movie.getTitle().toLowerCase().contains(title.toLowerCase())) .filter((movie) -> movie.getDirector().toLowerCase().contains(director.toLowerCase())) .collect(Collectors.toList()); request.setAttribute("movies", filteredMovies); target = "view-all.jsp"; } catch(MovieDaoException e) { e.printStackTrace(); throw new IOException("The workbook file has an invalid format."); } request.getRequestDispatcher(target).forward(request, response); } /** * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response) */ protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { doGet(request, response); } }
true
ecf386eb50ed34fecf3d76061758de33c9152001
Java
VladanStar/Folder-19
/JavaMTKompleksniBroj/src/javamtkompleksnibroj/KompleksniBroj.java
UTF-8
1,618
3.140625
3
[]
no_license
package javamtkompleksnibroj; class KompleksniBroj { private double r, i; public KompleksniBroj() { } public KompleksniBroj(double r, double i) { this.r = r; this.i = i; } public double getR() { return r; } public void setR(double r) { this.r = r; } public double getI() { return i; } public void setI(double i) { this.i = i; } public double Re() { return r; } public double Im() { return i; } public double moduo() { return Math.sqrt(r * r + i * i); } //staticki metod za konjugovan kompleksni broj //KompleksniBroj z = x.konjugovanBroj(); public KompleksniBroj konjugovaniBroj() { return new KompleksniBroj(this.r, -this.i); } public static KompleksniBroj zbir( KompleksniBroj a, KompleksniBroj b) { return new KompleksniBroj(a.r + b.r, a.i + b.i); } public KompleksniBroj dodaj(KompleksniBroj a) { return new KompleksniBroj(this.r + a.r, this.i + a.i); } public static KompleksniBroj proizvod( KompleksniBroj a, KompleksniBroj b) { return new KompleksniBroj(a.r * b.r - a.i * b.i, a.r * b.i + a.i * b.r); } public KompleksniBroj pomnozi(KompleksniBroj a) { return new KompleksniBroj(this.r * a.r - this.i * a.i, this.r * a.i + this.i * a.r); } @Override public String toString() { return "KompleksniBroj{" + "r=" + r + ", i=" + i + '}'; } }
true
e30d632fd0524e962e00469763571f73723e050e
Java
RicardoTavares16/DropMusic
/src/dropmusic/action/DropMusicAction.java
UTF-8
2,883
2.28125
2
[]
no_license
package dropmusic.action; import com.opensymphony.xwork2.ActionSupport; import dropmusic.model.DropMusicBean; import org.apache.struts2.interceptor.SessionAware; import java.util.Map; public class DropMusicAction extends ActionSupport implements SessionAware { private static final long serialVersionUID = 4L; private transient Map<String, Object> session; // To search: private String albumName; private String artistName; // To edit: private String newName; private String newDetails; @Override public String execute() throws Exception { DropMusicBean dropMusic = this.getDropMusicBean(); dropMusic.setUser(session.get("username").toString()); System.out.println("Executing DropMusic Action!"); if(this.newName != null && !this.newName.equals("")){ System.out.println(this.newName); dropMusic.setNewName(this.newName); if(dropMusic.getEditAlbumName()) { return "success"; } else { return ERROR; } } if(this.newDetails != null && !this.newDetails.equals("")) { System.out.println(this.newDetails); dropMusic.setNewDetails(this.newDetails); if(dropMusic.getEditAlbumDetails()) { return "success"; } else { return ERROR; } } if(this.albumName != null && !albumName.equals("")) { dropMusic.setAlbumName(this.albumName); if(!dropMusic.getGetAlbumData().isEmpty()){ return "success"; } } if(this.artistName != null && !artistName.equals("")) { dropMusic.setArtistName(this.artistName); if(!dropMusic.getGetArtistData().isEmpty()) { return "success"; } } if(!LoginAction.isPersonLogged(this.session)) return ERROR; return "success"; } public DropMusicBean getDropMusicBean() throws Exception { if(!session.containsKey(DropMusicBean.SESSION_MAP_KEY)) { this.setDropMusicBean(new DropMusicBean()); } return (DropMusicBean) session.get(DropMusicBean.SESSION_MAP_KEY); } public void setDropMusicBean(DropMusicBean dropMusicBean) { this.session.put(DropMusicBean.SESSION_MAP_KEY, dropMusicBean); } public void setAlbumName(String albumName) { this.albumName = albumName; } public void setArtistName(String artistName) { this.artistName = artistName; } public void setNewName(String newName) { this.newName = newName; } public void setNewDetails(String newDetails) { this.newDetails = newDetails; } @Override public void setSession(Map<String, Object> session) { this.session = session; } }
true
ee4c4e7123815f7a21804d18f98fa1f1715e4579
Java
pratapad/JavaTrainingSession
/JavaTrainingSession/src/JavaBasics/ConstructorConcept.java
UTF-8
902
3.890625
4
[]
no_license
package JavaBasics; public class ConstructorConcept { //Constructor means a class entity which is used to define some class features in the form of objects //have some properties //Doesn't return any value //looks like function but not a function //constructor can be loaded public ConstructorConcept(){ //zero parameter constructor System.out.println("zero parameter constructor"); } public ConstructorConcept(int i) { System.out.println("Single param constructor"); } public ConstructorConcept(int i, int j) { System.out.println("Two params constructor"); System.out.println("Print the value of i:"+i); System.out.println("Print the valu of j:"+j); } public static void main(String[] args) { ConstructorConcept cc= new ConstructorConcept(); ConstructorConcept cc1= new ConstructorConcept(20); ConstructorConcept cc2= new ConstructorConcept(20,30); } }
true
b5c07bc891a930a73c0c94a93714d70b326dbaa7
Java
mhromyk/algorithms
/src/main/java/org/mhromyk/algorithms/dynamicconnectivity/QuickUnionWeighted.java
UTF-8
921
3.09375
3
[]
no_license
package org.mhromyk.algorithms.dynamicconnectivity; public class QuickUnionWeighted implements UnionFind { private int[] element; private int[] depth; public QuickUnionWeighted(int n) { element = new int[n]; depth = new int[n]; for (int i=0;i<n;i++){ element[i]=i; depth[i]=0; } } public boolean connected(int p, int q) { return findRoot(p)==findRoot(q); } public void union(int p, int q) { // balance by linking root of smaller tree to root of larger tree int pRoot = findRoot(p); int qRoot = findRoot(q); if (pRoot == qRoot) return; if (depth[p]<=depth[q]){ element[pRoot]=qRoot; // depth[] } } private int findRoot(int node){ while (node!=element[node]){ node = element[node]; } return node; } }
true
207427ff3aac3629a0991b6f3d0faf0bce911823
Java
oreni/MyGasStation
/GasStation/src/GasStationBL/MainFuelPool.java
UTF-8
1,943
2.6875
3
[]
no_license
package GasStationBL; import java.util.concurrent.ExecutorService; import java.util.concurrent.Executors; import java.util.concurrent.RejectedExecutionException; import java.util.concurrent.TimeUnit; import GasStationExeptions.MainFuelStockEmptyException; import GasStationExeptions.MainFuelStockLowException; import GasStationExeptions.MainFuelStockOverFlow; import GasStationTasks.AbstractTask; public class MainFuelPool { private float maxCapacity; private float currentCapacity; private ExecutorService jobExecutorService; private final float redLine = 0.2f; public MainFuelPool(float maxCapacity, float currentCapacity) { this.maxCapacity = maxCapacity; this.currentCapacity = currentCapacity; this.jobExecutorService = Executors.newSingleThreadExecutor(); } public synchronized double getfuelAmount() { return currentCapacity; } public synchronized void pumpFuel(float numOfLitersWanted) throws MainFuelStockLowException, MainFuelStockEmptyException { if (currentCapacity - numOfLitersWanted < 0) { float numOfLitersGiven = currentCapacity; currentCapacity = 0; throw new MainFuelStockEmptyException(numOfLitersGiven); } currentCapacity -= numOfLitersWanted; if (currentCapacity / maxCapacity <= redLine) throw new MainFuelStockLowException(currentCapacity); } public synchronized void addFuel(float amount) throws MainFuelStockOverFlow { if (amount + currentCapacity > maxCapacity) { float diff = maxCapacity - currentCapacity; currentCapacity = maxCapacity; throw new MainFuelStockOverFlow(diff); } else currentCapacity += amount; } public void performTask(AbstractTask rmft) throws NullPointerException, RejectedExecutionException { jobExecutorService.execute(rmft); } public void close() throws InterruptedException, SecurityException { jobExecutorService.shutdown(); jobExecutorService.awaitTermination(Long.MAX_VALUE, TimeUnit.NANOSECONDS); } }
true
b20843c106252a4887d4c1dc43b5cf9621ddd982
Java
hudawei996/BluetoothPrinter
/app/src/main/java/com/wuyr/bluetoothprinter/customize/MySnackBar.java
UTF-8
1,165
2.140625
2
[ "Apache-2.0" ]
permissive
package com.wuyr.bluetoothprinter.customize; import android.support.annotation.NonNull; import android.support.annotation.Nullable; import android.support.design.widget.Snackbar; import android.view.View; import android.widget.TextView; import com.wuyr.bluetoothprinter.Application; import com.wuyr.bluetoothprinter.R; /** * Created by wuyr on 4/5/16 10:55 PM. */ public class MySnackBar { public static void show(@NonNull View view, @NonNull CharSequence text, int duration) { show(view, text, duration, null, null); } public static void show(@NonNull View view, @NonNull CharSequence text, int duration, @Nullable String actionText, @Nullable View.OnClickListener listener) { Snackbar snackbar = Snackbar.make(view, text, duration); Snackbar.SnackbarLayout root = (Snackbar.SnackbarLayout) snackbar.getView(); root.setBackgroundColor(Application.getContext().getResources().getColor(R.color.colorAccent)); ((TextView) root.findViewById(R.id.snackbar_text)).setTextColor( view.getResources().getColor(R.color.menu_text_color)); snackbar.show(); } }
true
42ca23cac2bf04f51ed00eafc5ec9686d03646e3
Java
mafuteru/Li_Jenny
/APLesson_09/Ex_04_Fibonacci.java
UTF-8
502
3.53125
4
[]
no_license
import java.util.Scanner; public class Ex_04_Fibonacci { public static void main(String[]args) { Scanner kb=new Scanner(System.in); System.out.println("Please enter your starting number:"); int start=kb.nextInt(); System.out.println("Please enter your sequence size: "); int size=kb.nextInt(); int[] seq=new int[size]; for(int i=0; i<seq.length; i++) { if(i==0||i==1) seq[i]=start; else { seq[i]=seq[i-1]+seq[i-2]; } System.out.print(seq[i]+" "); } } }
true
53284a1b1117f59ae76a94670d67a08876841bf7
Java
liutingwangrui/mvpdemo
/app/src/main/java/net/com/netdemo/MainActivity.java
UTF-8
1,534
2.15625
2
[]
no_license
package net.com.netdemo; import android.util.Log; import android.view.View; import android.widget.Button; import android.widget.EditText; import net.com.netdemo.base.BaseMvpActivity; import net.com.netdemo.login.LoginPresent; import net.com.netdemo.login.LoginView; import net.com.netdemo.login.bean.LoginInfo; import butterknife.BindView; public class MainActivity extends BaseMvpActivity<LoginPresent> implements LoginView { @BindView(R.id.editUSER) EditText editUSER; @BindView(R.id.editPWD) EditText editPWD; @BindView(R.id.but) Button button; private LoginPresent loginPresent=new LoginPresent(); @Override protected void initView() { loginPresent.mView=this; loginPresent.checkInfo(editUSER, editPWD, button); } @Override protected int getLayoutID() { return R.layout.activity_main; } /** * 数据返回结构的处理 * @param loginInfo */ @Override public void onLoginResult(LoginInfo loginInfo) { //登录成功后逻辑的处理 } @Override public void onListener(final boolean isClick) { Log.e("zzzzzzzzzzzzz",isClick+"---------"); button.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { if (isClick) { loginPresent.login(editUSER.getText().toString(), editPWD.getText().toString()); } } }); } }
true
dace64609099a354efeb7b5847d4f77799251478
Java
sistrans-B-01/proyecto
/src/main/java/uniandes/isis2304/parranderos/interfazDemo/InterfazAlohandesDemo.java
UTF-8
25,739
2.0625
2
[]
no_license
/**~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ * Universidad de los Andes (Bogotá - Colombia) * Departamento de Ingeniería de Sistemas y Computación * Licenciado bajo el esquema Academic Free License versión 2.1 * * Curso: isis2304 - Sistemas Transaccionales * Proyecto: Parranderos Uniandes * @version 1.0 * @author Germán Bravo * Julio de 2018 * * Revisado por: Claudia Jiménez, Christian Ariza * ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ */ package uniandes.isis2304.parranderos.interfazDemo; import java.awt.BorderLayout; import java.awt.Color; import java.awt.Desktop; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import java.io.BufferedWriter; import java.io.File; import java.io.FileReader; import java.io.FileWriter; import java.io.IOException; import java.lang.reflect.Method; import java.sql.Timestamp; import java.util.List; import javax.jdo.JDODataStoreException; import javax.swing.ImageIcon; import javax.swing.JFrame; import javax.swing.JLabel; import javax.swing.JMenu; import javax.swing.JMenuBar; import javax.swing.JMenuItem; import javax.swing.JOptionPane; import javax.swing.UIManager; import org.apache.log4j.Logger; import com.google.gson.Gson; import com.google.gson.JsonArray; import com.google.gson.JsonElement; import com.google.gson.JsonObject; import com.google.gson.stream.JsonReader; import uniandes.isis2304.parranderos.interfazApp.PanelDatos; import uniandes.isis2304.parranderos.negocio.AlohAndes; import uniandes.isis2304.parranderos.negocio.VOApartamento; import uniandes.isis2304.parranderos.negocio.VOCliente; import uniandes.isis2304.parranderos.negocio.VOOferta; import uniandes.isis2304.parranderos.negocio.VOOfertaApartamento; import uniandes.isis2304.parranderos.negocio.VOPropietario; import uniandes.isis2304.parranderos.negocio.VOReserva; /** * Clase principal de la interfaz * * @author Germán Bravo */ @SuppressWarnings("serial") public class InterfazAlohandesDemo extends JFrame implements ActionListener { /* **************************************************************** * Constantes *****************************************************************/ /** * Logger para escribir la traza de la ejecución */ private static Logger log = Logger.getLogger(InterfazAlohandesDemo.class.getName()); /** * Ruta al archivo de configuración de la interfaz */ private final String CONFIG_INTERFAZ = "./src/main/resources/config/interfaceConfigDemo.json"; /** * Ruta al archivo de configuración de los nombres de tablas de la base de datos */ private static final String CONFIG_TABLAS = "./src/main/resources/config/TablasBD_A.json"; /* **************************************************************** * Atributos *****************************************************************/ /** * Objeto JSON con los nombres de las tablas de la base de datos que se quieren utilizar */ private JsonObject tableConfig; /** * Asociación a la clase principal del negocio. */ private AlohAndes parranderos; /* **************************************************************** * Atributos de interfaz *****************************************************************/ /** * Objeto JSON con la configuración de interfaz de la app. */ private JsonObject guiConfig; /** * Panel de despliegue de interacción para los requerimientos */ private PanelDatos panelDatos; /** * Menú de la aplicación */ private JMenuBar menuBar; /* **************************************************************** * Métodos *****************************************************************/ /** * Construye la ventana principal de la aplicación. <br> * <b>post:</b> Todos los componentes de la interfaz fueron inicializados. */ public InterfazAlohandesDemo( ) { // Carga la configuración de la interfaz desde un archivo JSON guiConfig = openConfig ("Interfaz", CONFIG_INTERFAZ); // Configura la apariencia del frame que contiene la interfaz gráfica configurarFrame ( ); if (guiConfig != null) { crearMenu( guiConfig.getAsJsonArray("menuBar") ); } tableConfig = openConfig ("Tablas BD", CONFIG_TABLAS); parranderos = new AlohAndes (tableConfig); String path = guiConfig.get("bannerPath").getAsString(); panelDatos = new PanelDatos ( ); setLayout (new BorderLayout()); add (new JLabel (new ImageIcon (path)), BorderLayout.NORTH ); add( panelDatos, BorderLayout.CENTER ); } /* **************************************************************** * Métodos para la configuración de la interfaz *****************************************************************/ /** * Lee datos de configuración para la aplicación, a partir de un archivo JSON o con valores por defecto si hay errores. * @param tipo - El tipo de configuración deseada * @param archConfig - Archivo Json que contiene la configuración * @return Un objeto JSON con la configuración del tipo especificado * NULL si hay un error en el archivo. */ private JsonObject openConfig (String tipo, String archConfig) { JsonObject config = null; try { Gson gson = new Gson( ); FileReader file = new FileReader (archConfig); JsonReader reader = new JsonReader ( file ); config = gson.fromJson(reader, JsonObject.class); log.info ("Se encontró un archivo de configuración válido: " + tipo); } catch (Exception e) { // e.printStackTrace (); log.info ("NO se encontró un archivo de configuración válido"); JOptionPane.showMessageDialog(null, "No se encontró un archivo de configuración de interfaz válido: " + tipo, "Parranderos App", JOptionPane.ERROR_MESSAGE); } return config; } /** * Método para configurar el frame principal de la aplicación */ private void configurarFrame( ) { int alto = 0; int ancho = 0; String titulo = ""; if ( guiConfig == null ) { log.info ( "Se aplica configuración por defecto" ); titulo = "Parranderos APP Default"; alto = 300; ancho = 500; } else { log.info ( "Se aplica configuración indicada en el archivo de configuración" ); titulo = guiConfig.get("title").getAsString(); alto= guiConfig.get("frameH").getAsInt(); ancho = guiConfig.get("frameW").getAsInt(); } setDefaultCloseOperation( JFrame.EXIT_ON_CLOSE ); setLocation (50,50); setResizable( true ); setBackground( Color.WHITE ); setTitle( titulo ); setSize ( ancho, alto); } /** * Método para crear el menú de la aplicación con base em el objeto JSON leído * Genera una barra de menú y los menús con sus respectivas opciones * @param jsonMenu - Arreglo Json con los menùs deseados */ private void crearMenu( JsonArray jsonMenu ) { // Creación de la barra de menús menuBar = new JMenuBar(); for (JsonElement men : jsonMenu) { // Creación de cada uno de los menús JsonObject jom = men.getAsJsonObject(); String menuTitle = jom.get("menuTitle").getAsString(); JsonArray opciones = jom.getAsJsonArray("options"); JMenu menu = new JMenu( menuTitle); for (JsonElement op : opciones) { // Creación de cada una de las opciones del menú JsonObject jo = op.getAsJsonObject(); String lb = jo.get("label").getAsString(); String event = jo.get("event").getAsString(); JMenuItem mItem = new JMenuItem( lb ); mItem.addActionListener( this ); mItem.setActionCommand(event); menu.add(mItem); } menuBar.add( menu ); } setJMenuBar ( menuBar ); } /* **************************************************************** * Demos de RFC5 Mostrar uso de alohandes *****************************************************************/ /** * Demostración de creación de Propietario * Muestra la traza de la ejecución en el panelDatos * * Pre: La base de datos está vacía * Post: La base de datos está vacía */ /**public void demoPropietarios( ) { try { // Ejecución de la demo y recolección de los resultados // ATENCIÓN: En una aplicación real, los datos JAMÁS están en el código String nombrePropietario = "Juanito"; long numeroId= 123; String tipoId= "CC"; String tipoPropietario= "PROFESOR"; boolean errorPropietario = false; VOPropietario propietario = parranderos.adicionarPropietario(nombrePropietario, numeroId, tipoId, tipoPropietario); if (propietario == null) { errorPropietario = true; } // Generación de la cadena de caracteres con la traza de la ejecución de la demo String resultado = "Demo de creación y listado de Propietarios\n\n"; resultado += "\n\n************ Generando datos de prueba ************ \n"; if (errorPropietario) { resultado += "*** Exception creando propietario !!\n"; resultado += "*** Es probable que ese propietario ya existiera y hay restricción de UNICIDAD sobre el nombre del tipo de bebida\n"; resultado += "*** Revise el log de parranderos para más detalles\n"; } resultado += "Adicionado el propietario con nombre: " + nombrePropietario + "\n"; resultado += "\n\n************ Ejecutando la demo ************ \n"; resultado += "\n" + listarTiposBebida (lista); resultado += "\n\n************ Limpiando la base de datos ************ \n"; resultado += tbEliminados + " Tipos de bebida eliminados\n"; resultado += "\n Demo terminada"; panelDatos.actualizarInterfaz(resultado); } catch (Exception e) { // e.printStackTrace(); String resultado = generarMensajeError(e); panelDatos.actualizarInterfaz(resultado); } }**/ /** * Demostración de la consulta: Dar el id y el número de bebidas que sirve cada bar, siempre y cuando el bar sirva por los menos una bebida * Incluye el manejo de los tipos de bebida pues el tipo de bebida es llave foránea en las bebidas * Incluye el manajo de las bebidas * Incluye el manejo de los bares * Incluye el manejo de la relación sirven * Muestra la traza de la ejecución en el panelDatos * * Pre: La base de datos está vacía * Post: La base de datos está vacía */ public void demoRFC5 ( ) { try { // Ejecución de la demo y recolección de los resultados // ATENCIÓN: En una aplicación real, los datos JAMÁS están en el código VOPropietario propietario = parranderos.adicionarPropietario("Juan", 10, "CC", "EMPLEADO"); VOApartamento apto= parranderos.adicionarApartamento(2, "AGUA", "CL", propietario.getNumeroIdentificacion(), propietario.getTipoIdentificacion()); VOCliente cliente= parranderos.adicionarCliente("Oscar", 10, "CC", "PROFESOR"); VOCliente cliente1= parranderos.adicionarCliente("Oscar1", 10, "CC", "EMPLEADO"); VOCliente cliente2= parranderos.adicionarCliente("Oscar2", 10, "CC", "EGRESADO"); VOOferta oferta= parranderos.adicionarOferta(20, 5, 0, Timestamp.valueOf("2020-01-30 00:00:00"), Timestamp.valueOf("2020-01-01 00:00:00"),"UNA SEMANA", 1,"1", "Y"); VOOfertaApartamento ofeApto= parranderos.adicionarOfertaApartamento(oferta.getId(), apto.getUbicacion()); VOReserva reserva = parranderos.adicionarReserva(200000, 200000, Timestamp.valueOf("2020-01-08 00:00:00"), Timestamp.valueOf("2020-01-01 00:00:00"), "UNA SEMANA", cliente.getNumeroIdentificacion(), cliente.getTipoIdentificacion(), oferta.getId()); VOReserva reserva1= parranderos.adicionarReserva(200000, 200000, Timestamp.valueOf("2020-01-18 00:00:00"), Timestamp.valueOf("2020-01-11 00:00:00"), "UNA SEMANA", cliente1.getNumeroIdentificacion(), cliente1.getTipoIdentificacion(), oferta.getId()); VOReserva reserva2= parranderos.adicionarReserva(200000, 200000, Timestamp.valueOf("2020-01-28 00:00:00"), Timestamp.valueOf("2020-01-21 00:00:00"), "UNA SEMANA", cliente2.getNumeroIdentificacion(), cliente2.getTipoIdentificacion(), oferta.getId()); List <Object []> listaRFC5 = parranderos.darAnalisisOcupacion(); // Generación de la cadena de caracteres con la traza de la ejecución de la demo String resultado = "Demo de creación y listado de Clientes y la informacion de sus reservas\n\n"; resultado += "\n\n************ Ejecutando la demo ************ \n"; resultado += "\n" + listarRFC5 (listaRFC5); resultado += "\n Demo terminada"; panelDatos.actualizarInterfaz(resultado); } catch (Exception e) { // e.printStackTrace(); String resultado = generarMensajeError(e); panelDatos.actualizarInterfaz(resultado); } } /** * Demostración de la modificación: Aumentar en uno el número de sedes de los bares de una ciudad * Muestra la traza de la ejecución en el panelDatos * * Pre: La base de datos está vacía * Post: La base de datos está vacía */ /**public void demoAumentarSedesBaresEnCiudad ( ) { try { // Ejecución de la demo y recolección de los resultados // ATENCIÓN: En una aplicación real, los datos JAMÁS están en el código VOBar bar1 = parranderos.adicionarBar ("Los Amigos1", "Bogotá", "Bajo", 2); VOBar bar2 = parranderos.adicionarBar ("Los Amigos2", "Bogotá", "Bajo", 3); VOBar bar3 = parranderos.adicionarBar ("Los Amigos3", "Bogotá", "Bajo", 4); VOBar bar4 = parranderos.adicionarBar ("Los Amigos4", "Medellín", "Bajo", 5); List <VOBar> listaBares = parranderos.darVOBares (); long baresModificados = parranderos.aumentarSedesBaresCiudad("Bogotá"); List <VOBar> listaBares2 = parranderos.darVOBares (); long baresEliminados = parranderos.eliminarBarPorId (bar1.getId ()); baresEliminados += parranderos.eliminarBarPorId (bar2.getId ()); baresEliminados += parranderos.eliminarBarPorId (bar3.getId ()); baresEliminados += parranderos.eliminarBarPorId (bar4.getId ()); // Generación de la cadena de caracteres con la traza de la ejecución de la demo String resultado = "Demo de modificación número de sedes de los bares de una ciudad\n\n"; resultado += "\n\n************ Generando datos de prueba ************ \n"; resultado += "\n" + listarBares (listaBares); resultado += "\n\n************ Ejecutando la demo ************ \n"; resultado += baresModificados + " Bares modificados\n"; resultado += "\n" + listarBares (listaBares2); resultado += "\n\n************ Limpiando la base de datos ************ \n"; resultado += baresEliminados + " Bares eliminados\n"; resultado += "\n Demo terminada"; panelDatos.actualizarInterfaz(resultado); } catch (Exception e) { // e.printStackTrace(); String resultado = generarMensajeError(e); panelDatos.actualizarInterfaz(resultado); } }**/ /* **************************************************************** * Métodos administrativos *****************************************************************/ /** * Muestra el log de Parranderos */ public void mostrarLogParranderos () { mostrarArchivo ("parranderos.log"); } /** * Muestra el log de datanucleus */ public void mostrarLogDatanuecleus () { mostrarArchivo ("datanucleus.log"); } /** * Limpia el contenido del log de parranderos * Muestra en el panel de datos la traza de la ejecución */ public void limpiarLogParranderos () { // Ejecución de la operación y recolección de los resultados boolean resp = limpiarArchivo ("parranderos.log"); // Generación de la cadena de caracteres con la traza de la ejecución de la demo String resultado = "\n\n************ Limpiando el log de parranderos ************ \n"; resultado += "Archivo " + (resp ? "limpiado exitosamente" : "NO PUDO ser limpiado !!"); resultado += "\nLimpieza terminada"; panelDatos.actualizarInterfaz(resultado); } /** * Limpia el contenido del log de datanucleus * Muestra en el panel de datos la traza de la ejecución */ public void limpiarLogDatanucleus () { // Ejecución de la operación y recolección de los resultados boolean resp = limpiarArchivo ("datanucleus.log"); // Generación de la cadena de caracteres con la traza de la ejecución de la demo String resultado = "\n\n************ Limpiando el log de datanucleus ************ \n"; resultado += "Archivo " + (resp ? "limpiado exitosamente" : "NO PUDO ser limpiado !!"); resultado += "\nLimpieza terminada"; panelDatos.actualizarInterfaz(resultado); } /** * Limpia todas las tuplas de todas las tablas de la base de datos de parranderos * Muestra en el panel de datos el número de tuplas eliminadas de cada tabla */ public void limpiarBD () { try { // Ejecución de la demo y recolección de los resultados long eliminados [] = parranderos.limpiarAlohandes(); // Generación de la cadena de caracteres con la traza de la ejecución de la demo String resultado = "\n\n************ Limpiando la base de datos ************ \n"; resultado += eliminados [0] + " OfertaApartamento eliminados\n"; resultado += eliminados [1] + " OfertaVivienda eliminados\n"; resultado += eliminados [2] + " OfertaHabitacion eliminados\n"; resultado += eliminados [3] + " ServiciosAdicionales eliminadas\n"; resultado += eliminados [4] + " Reserva eliminados\n"; resultado += eliminados [5] + " Oferta eliminados\n"; resultado += eliminados [6] + " Habitacion eliminados\n"; resultado += eliminados [7] + " Apartamento eliminados\n"; resultado += eliminados [8] + " Vivienda eliminados\n"; resultado += eliminados [9] + " cliente eliminados\n"; resultado += eliminados [10] + " vecinos eliminados\n"; resultado += eliminados [11] + " dominio eliminados\n"; resultado += eliminados [12] + " propietario eliminados\n"; resultado += eliminados [13] + " rescolres eliminados\n"; resultado += eliminados [14] + " reservacolectiva eliminados\n"; resultado += "\nLimpieza terminada"; panelDatos.actualizarInterfaz(resultado); } catch (Exception e) { // e.printStackTrace(); String resultado = generarMensajeError(e); panelDatos.actualizarInterfaz(resultado); } } /** * Muestra la presentación general del proyecto */ public void mostrarPresentacionGeneral () { mostrarArchivo ("data/00-ST-ParranderosJDO.pdf"); } /** * Muestra el modelo conceptual de Parranderos */ public void mostrarModeloConceptual () { mostrarArchivo ("data/Modelo Conceptual Parranderos.pdf"); } /** * Muestra el esquema de la base de datos de Parranderos */ public void mostrarEsquemaBD () { mostrarArchivo ("data/Esquema BD Parranderos.pdf"); } /** * Muestra el script de creación de la base de datos */ public void mostrarScriptBD () { mostrarArchivo ("data/EsquemaParranderos.sql"); } /** * Muestra la arquitectura de referencia para Parranderos */ public void mostrarArqRef () { mostrarArchivo ("data/ArquitecturaReferencia.pdf"); } /** * Muestra la documentación Javadoc del proyectp */ public void mostrarJavadoc () { mostrarArchivo ("doc/index.html"); } /** * Muestra la información acerca del desarrollo de esta apicación */ public void acercaDe () { String resultado = "\n\n ************************************\n\n"; resultado += " * Universidad de los Andes (Bogotá - Colombia)\n"; resultado += " * Departamento de Ingeniería de Sistemas y Computación\n"; resultado += " * Licenciado bajo el esquema Academic Free License versión 2.1\n"; resultado += " * \n"; resultado += " * Curso: isis2304 - Sistemas Transaccionales\n"; resultado += " * Proyecto: Alohandes Uniandes\n"; resultado += " * @version 1.0\n"; resultado += " * @author Germán Bravo\n"; resultado += " * Julio de 2018\n"; resultado += " * \n"; resultado += " * Revisado por: Claudia Jiménez, Christian Ariza\n"; resultado += "\n ************************************\n\n"; panelDatos.actualizarInterfaz(resultado); } /* **************************************************************** * Métodos privados para la presentación de resultados y otras operaciones *****************************************************************/ /** * Genera una cadena de caracteres con la lista de parejas de números recibida: una línea por cada pareja * @param lista - La lista con las pareja * @return La cadena con una líea para cada pareja recibido */ private String listarRFC5 (List<Object[]> lista) { String resp = "El uso de alohandes es:\n"; int i = 1; for ( Object [] tupla : lista) { Object [] datos = tupla; String resp1 = i++ + ". " + "["; resp1 += "nombre: " + datos [0] + ", "; resp1 += "tipo cliente: " + datos [1]; resp1 += "dinero pagado: " + datos [2]; resp1 += "dias reservados: " + datos [3]; resp1 += "cant de reservas: " + datos [4]; resp1 += "]"; resp += resp1 + "\n"; } return resp; } /** * Genera una cadena de caracteres con la lista de parejas de objetos recibida: una línea por cada pareja * @param lista - La lista con las parejas (Bebedor, numero visitas) * @return La cadena con una línea para cada pareja recibido */ /**private String listarBebedorYNumVisitas (List<Object[]> lista) { String resp = "Los bebedores y el número visitas realizadas son:\n"; int i = 1; for (Object [] tupla : lista) { VOBebedor bdor = (VOBebedor) tupla [0]; int numVisitas = (int) tupla [1]; String resp1 = i++ + ". " + "["; resp1 += bdor + ", "; resp1 += "numVisitas: " + numVisitas; resp1 += "]"; resp += resp1 + "\n"; } return resp; } /** * Genera una cadena de caracteres con la descripción de la excepcion e, haciendo énfasis en las excepcionsde JDO * @param e - La excepción recibida * @return La descripción de la excepción, cuando es javax.jdo.JDODataStoreException, "" de lo contrario */ private String darDetalleException(Exception e) { String resp = ""; if (e.getClass().getName().equals("javax.jdo.JDODataStoreException")) { JDODataStoreException je = (javax.jdo.JDODataStoreException) e; return je.getNestedExceptions() [0].getMessage(); } return resp; } /** * Genera una cadena para indicar al usuario que hubo un error en la aplicación * @param e - La excepción generada * @return La cadena con la información de la excepción y detalles adicionales */ private String generarMensajeError(Exception e) { String resultado = "************ Error en la ejecución\n"; resultado += e.getLocalizedMessage() + ", " + darDetalleException(e); resultado += "\n\nRevise datanucleus.log y parranderos.log para más detalles"; return resultado; } /** * Limpia el contenido de un archivo dado su nombre * @param nombreArchivo - El nombre del archivo que se quiere borrar * @return true si se pudo limpiar */ private boolean limpiarArchivo(String nombreArchivo) { BufferedWriter bw; try { bw = new BufferedWriter(new FileWriter(new File (nombreArchivo))); bw.write (""); bw.close (); return true; } catch (IOException e) { // e.printStackTrace(); return false; } } /** * Abre el archivo dado como parámetro con la aplicación por defecto del sistema * @param nombreArchivo - El nombre del archivo que se quiere mostrar */ private void mostrarArchivo (String nombreArchivo) { try { Desktop.getDesktop().open(new File(nombreArchivo)); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } } /* **************************************************************** * Métodos de la Interacción *****************************************************************/ /** * Método para la ejecución de los eventos que enlazan el menú con los métodos de negocio * Invoca al método correspondiente según el evento recibido * @param pEvento - El evento del usuario */ @Override public void actionPerformed(ActionEvent pEvento) { String evento = pEvento.getActionCommand( ); try { Method req = InterfazAlohandesDemo.class.getMethod ( evento ); req.invoke ( this ); } catch (Exception e) { e.printStackTrace(); } } /* **************************************************************** * Programa principal *****************************************************************/ /** * Este método ejecuta la aplicación, creando una nueva interfaz * @param args Arreglo de argumentos que se recibe por línea de comandos */ public static void main( String[] args ) { try { // Unifica la interfaz para Mac y para Windows. UIManager.setLookAndFeel( UIManager.getCrossPlatformLookAndFeelClassName( ) ); InterfazAlohandesDemo interfaz = new InterfazAlohandesDemo( ); interfaz.setVisible( true ); } catch( Exception e ) { e.printStackTrace( ); } } }
true
20dfa8c73c46d7acf58a0cae7826db0fbbeeff98
Java
flywind2/joeis
/test/irvine/math/plantri/Min5ScannerTest.java
UTF-8
5,007
2.59375
3
[]
no_license
package irvine.math.plantri; import junit.framework.TestCase; /** * Tests the corresponding class. * @author Sean A. Irvine */ public class Min5ScannerTest extends TestCase { /* 3-connected planar triangulations with minimum degree 5 (plantri -m5), and 3-connected planar graphs (convex polytopes) with minimum degree 5 (plantri -pm5). triangulations polytopes nv ne nf all O-P all O-P 12 30 20 | 1 1 | 1 1 13 33 22 | 0 0 | 0 0 14 36 24 | 1 1 | 1 1 15 39 26 | 1 1 | 1 1 16 42 28 | 3 4 | 5 6 17 45 30 | 4 4 | 8 8 18 48 32 | 12 17 | 30 46 19 51 34 | 23 33 | 85 135 20 54 36 | 73 117 | 392 686 21 57 38 | 192 331 | 1587 2961 22 60 40 | 651 1180 | 7657 14744 23 63 42 | 2070 3899 | 36291 71207 */ public void testTriangulationsMin5() { assertEquals(1, new Plantri().count(12, 5, -1, -1, false, false, false, false)); assertEquals(0, new Plantri().count(13, 5, -1, -1, false, false, false, false)); assertEquals(1, new Plantri().count(14, 5, -1, -1, false, false, false, false)); assertEquals(1, new Plantri().count(15, 5, -1, -1, false, false, false, false)); assertEquals(3, new Plantri().count(16, 5, -1, -1, false, false, false, false)); assertEquals(4, new Plantri().count(17, 5, -1, -1, false, false, false, false)); assertEquals(12, new Plantri().count(18, 5, -1, -1, false, false, false, false)); assertEquals(23, new Plantri().count(19, 5, -1, -1, false, false, false, false)); assertEquals(73, new Plantri().count(20, 5, -1, -1, false, false, false, false)); assertEquals(192, new Plantri().count(21, 5, -1, -1, false, false, false, false)); assertEquals(651, new Plantri().count(22, 5, -1, -1, false, false, false, false)); } public void testTriangulationsMin5OP() { assertEquals(1, new Plantri().count(12, 5, -1, -1, true, false, false, false)); assertEquals(0, new Plantri().count(13, 5, -1, -1, true, false, false, false)); assertEquals(1, new Plantri().count(14, 5, -1, -1, true, false, false, false)); assertEquals(1, new Plantri().count(15, 5, -1, -1, true, false, false, false)); assertEquals(4, new Plantri().count(16, 5, -1, -1, true, false, false, false)); assertEquals(4, new Plantri().count(17, 5, -1, -1, true, false, false, false)); assertEquals(17, new Plantri().count(18, 5, -1, -1, true, false, false, false)); assertEquals(33, new Plantri().count(19, 5, -1, -1, true, false, false, false)); assertEquals(117, new Plantri().count(20, 5, -1, -1, true, false, false, false)); assertEquals(331, new Plantri().count(21, 5, -1, -1, true, false, false, false)); } public void testConvexPolytopesMin5() { assertEquals(1, new Plantri().count(12, 5, -1, -1, false, true, false, false)); assertEquals(0, new Plantri().count(13, 5, -1, -1, false, true, false, false)); assertEquals(1, new Plantri().count(14, 5, -1, -1, false, true, false, false)); assertEquals(1, new Plantri().count(15, 5, -1, -1, false, true, false, false)); assertEquals(5, new Plantri().count(16, 5, -1, -1, false, true, false, false)); assertEquals(8, new Plantri().count(17, 5, -1, -1, false, true, false, false)); assertEquals(30, new Plantri().count(18, 5, -1, -1, false, true, false, false)); assertEquals(85, new Plantri().count(19, 5, -1, -1, false, true, false, false)); assertEquals(392, new Plantri().count(20, 5, -1, -1, false, true, false, false)); assertEquals(1587, new Plantri().count(21, 5, -1, -1, false, true, false, false)); } public void testConvexPolytopesMin5OP() { assertEquals(1, new Plantri().count(12, 5, -1, -1, true, true, false, false)); assertEquals(0, new Plantri().count(13, 5, -1, -1, true, true, false, false)); assertEquals(1, new Plantri().count(14, 5, -1, -1, true, true, false, false)); assertEquals(1, new Plantri().count(15, 5, -1, -1, true, true, false, false)); assertEquals(6, new Plantri().count(16, 5, -1, -1, true, true, false, false)); assertEquals(8, new Plantri().count(17, 5, -1, -1, true, true, false, false)); assertEquals(46, new Plantri().count(18, 5, -1, -1, true, true, false, false)); assertEquals(135, new Plantri().count(19, 5, -1, -1, true, true, false, false)); assertEquals(686, new Plantri().count(20, 5, -1, -1, true, true, false, false)); } }
true
76ebce41d90cb7615567a4a6c542b0321f8fe21a
Java
Gohan19266/Thread
/src/app/App.java
UTF-8
987
3.671875
4
[]
no_license
package app; import java.util.Scanner; public class App extends Thread{ Scanner dato= new Scanner(System.in); String nombre,dia; double hora; public App(String nombre, String dia, double hora){ this.nombre= nombre; this.dia=dia; this.hora=hora; System.out.println("Ingresar Nombre: "); nombre=dato.nextLine(); System.out.println("Ingresar dia: "); dia= dato.nextLine(); System.out.println("Ingresar hora: "); hora= dato.nextDouble(); } @Override public void run(){ if(hora>13){ System.out.println(nombre+ " llego tarde el dia"+ dia); }else{ System.out.println(nombre+ "llego temprano el dia"+ dia); } } public static void main(String[]args) throws Exception{ Thread alum1= new App("", "", 0); alum1.start(); Thread.sleep(3000); Thread alum2= new App("", "", 0); alum2.start(); } }
true
29c5b6eabbb844ab2ee9b4f215dae2a93cec1302
Java
ly101112/think_in_java
/src/class10/test9/Test.java
UTF-8
601
3.671875
4
[]
no_license
/** * 第十章练习9 在方法里的内部类 */ package class10.test9; interface Test9 { void f(); } public class Test { public Test9 test() { class Tem implements Test9 { public Tem() { System.out.println("new " + getClass().getSimpleName()); } @Override public void f() { System.out.println(getClass().getSimpleName() + ".f"); } } return new Tem(); } public static void main(String[] args) { Test test = new Test(); test.test().f(); } }
true
f00bcc5e9161776b301c390e43b7fb961b5353ab
Java
hgrodriguez91/API-ProjectManager
/src/main/java/com/mybatis2/testdemo/mappers/proyectosMapper.java
UTF-8
515
1.992188
2
[]
no_license
package com.mybatis2.testdemo.mappers; import com.mybatis2.testdemo.entity.Proyecto; import org.apache.ibatis.annotations.Select; import java.util.ArrayList; public interface proyectosMapper { @Select("Select * from proyectos") ArrayList<Proyecto> getAllProyectos(); @Select("Select * from proyectos Where id=#{id}") Proyecto getProyectoById(); @Select("Select id, nombre, descripcion from proyectos where idcliente = #{id}") ArrayList<Proyecto> getProyectosByClientId(Integer id); }
true
cd1c439640cb4bd8372f2e6012e262169bd0ac0d
Java
bijon95/Shakeing
/app/src/main/java/com/najmul/femaleharasmentmonitoring/ViewData.java
UTF-8
701
2.265625
2
[]
no_license
package com.najmul.femaleharasmentmonitoring; import android.support.v7.app.AppCompatActivity; import android.os.Bundle; import android.widget.TextView; public class ViewData extends AppCompatActivity { TextView tv; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_view_data); tv = (TextView) findViewById(R.id.show_data); MyDBFunctions mf= new MyDBFunctions(getApplicationContext()); String[] data = mf.my_data() ; String s =""; for (int i = 0; i <data.length; i++){ s = s + data[i]+"\n\n"; } tv.setText(s); } }
true
f98f717cd684d2986ba9c07e578579345f5b3d5e
Java
NPE78/process-manager
/process-manager-messages-plugin/src/main/java/com/talanlabs/processmanager/messages/trigger/event/NewFileTriggerEvent.java
UTF-8
488
2.1875
2
[ "Apache-2.0" ]
permissive
package com.talanlabs.processmanager.messages.trigger.event; import com.talanlabs.processmanager.messages.trigger.api.Trigger; import java.io.File; public final class NewFileTriggerEvent extends FileTriggerEvent { public NewFileTriggerEvent(File f, Trigger source) { super(f, source); } @Override public String toString() { return "NEW FILE : " + getAttachment(); } @Override public boolean isNewFileEvent() { return true; } }
true
8536ad564000129a3357e739527efaa204d466f0
Java
MichalFoksa/Mqtt2InfluxDB
/src/main/java/org/influxdb/v08/dto/Serie.java
UTF-8
3,390
2.953125
3
[ "MIT" ]
permissive
package org.influxdb.v08.dto; import java.util.Arrays; import java.util.List; import java.util.Map; import com.google.common.base.Objects; import com.google.common.base.Preconditions; import com.google.common.base.Strings; import com.google.common.collect.Lists; import com.google.common.collect.Maps; /** * Representation of a InfluxDB database serie. * * @author stefan.majer [at] gmail.com * */ public class Serie { private final String name; String[] columns; Object[][] points; /** * Builder for a new Serie. * * A typical usage would look like: * * <br/> * <code> * Serie serie = new Serie.Builder("serieName") * .columns("time", "cpu_idle") * .values(System.currentTimeMillis(), 0.97) * .values(System.currentTimeMillis(), 0.99).build(); * </code> */ public static class Builder { private final String name; private final List<String> columns = Lists.newArrayList(); private final List<List<Object>> valueRows = Lists.newArrayList(); /** * @param name * the name of the Serie to create. */ public Builder(final String name) { super(); this.name = name; } /** * @param columnNames * the array of names of all columns. * @return this Builder instance. */ public Builder columns(final String... columnNames) { Preconditions.checkArgument(this.columns.isEmpty(), "You can only call columns() once."); this.columns.addAll(Arrays.asList(columnNames)); return this; } /** * @param values * the values for a single row. * @return this Builder instance. */ public Builder values(final Object... values) { Preconditions.checkArgument(values.length == this.columns.size(), "Value count differs from column count."); this.valueRows.add(Arrays.asList(values)); return this; } /** * Create a Serie instance. * * @return the created Serie. */ public Serie build() { Preconditions.checkArgument(!Strings.isNullOrEmpty(this.name), "Serie name must not be null or empty."); Serie serie = new Serie(this.name); serie.columns = this.columns.toArray(new String[this.columns.size()]); Object[][] points = new Object[this.valueRows.size()][this.columns.size()]; int row = 0; for (List<Object> values : this.valueRows) { points[row] = values.toArray(); row++; } serie.points = points; return serie; } } /** * @param name * the name of the serie. */ Serie(final String name) { this.name = name; } /** * @return the name */ public String getName() { return this.name; } /** * @return the columns */ public String[] getColumns() { return this.columns; } /** * @return the Points as a List of Maps with columnName to value. */ public List<Map<String, Object>> getRows() { List<Map<String, Object>> rows = Lists.newArrayList(); for (Object[] point : this.points) { int column = 0; Map<String, Object> row = Maps.newHashMap(); for (Object value : point) { row.put(this.columns[column], value); column++; } rows.add(row); } return rows; } /** * {@inheritDoc} */ @Override public String toString() { return Objects .toStringHelper(this.getClass()) .add("name", this.name) .add("c", Arrays.deepToString(this.columns)) .add("p", Arrays.deepToString(this.points)) .toString(); } }
true
fdeeb52409e0266e2626786dafc00128298e26f8
Java
piravinsat/Misc
/CS2840/src/LinearSearch.java
UTF-8
833
3.609375
4
[]
no_license
public class LinearSearch{ //n public static void main (String[] args) { int phone_book_size = 4; int index = 0; PhoneBookEntry phone_book[] = new PhoneBookEntry[phone_book_size]; phone_book[0] = new PhoneBookEntry(23143142, "John"); phone_book[1] = new PhoneBookEntry(2313213, "Bob"); phone_book[2] = new PhoneBookEntry(231434, "Mike"); phone_book[3] = new PhoneBookEntry(231321, "Dan"); while ((index < phone_book_size) && (phone_book[index].number != 32142141)) { index++; } if (index == phone_book_size) { System.out.println("Target number not found"); } else { System.out.println("Target number belongs to" + phone_book[index].name); } } }
true
20f5141f150f081011a98c456044177dd01682d6
Java
egovernments/DIGIT-OSS
/core-services/libraries/services-common/src/main/java/org/egov/common/contract/request/RequestInfo.java
UTF-8
629
1.59375
2
[ "MIT", "LicenseRef-scancode-generic-cla" ]
permissive
package org.egov.common.contract.request; import lombok.AllArgsConstructor; import lombok.Builder; import lombok.EqualsAndHashCode; import lombok.Getter; import lombok.NoArgsConstructor; import lombok.Setter; import lombok.ToString; @Getter @Setter @Builder @NoArgsConstructor @AllArgsConstructor @ToString @EqualsAndHashCode public class RequestInfo { private String apiId; private String ver; private Long ts; private String action; private String did; private String key; private String msgId; private String authToken; private String correlationId; private User userInfo; }
true
510d17c4c717fb403c2096688cd629599278e41c
Java
anchoranalysis/anchor
/anchor-feature/src/main/java/org/anchoranalysis/feature/calculate/NamedFeatureCalculateException.java
UTF-8
3,175
2.234375
2
[ "Apache-2.0", "MIT" ]
permissive
/*- * #%L * anchor-feature * %% * Copyright (C) 2010 - 2020 Owen Feehan, ETH Zurich, University of Zurich, Hoffmann-La Roche * %% * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. * #L% */ package org.anchoranalysis.feature.calculate; import org.anchoranalysis.core.exception.friendly.AnchorFriendlyCheckedException; /** * An exception that occurs when a feature fails to successfully calculate. * * <p>The feature may optionally have a name associated with it, to help identify it to the user. * * @author Owen Feehan */ public class NamedFeatureCalculateException extends AnchorFriendlyCheckedException { private static final long serialVersionUID = 1L; /** The message without any key identifier. */ private final String messageWithoutKey; /** * Creates with a general failure message that doesn't pertain to any particular feature. * * @param message the message. */ public NamedFeatureCalculateException(String message) { super(message); this.messageWithoutKey = message; } /** * Creates with a calculation error that doesn't pertain to any particular feature. * * @param cause reason for failure. */ public NamedFeatureCalculateException(Exception cause) { this(cause.toString()); } /** * Creates with a failure message associated with a particular feature. * * @param featureName a name to describe the feature whose calculation failed. * @param message the reason for failure. */ public NamedFeatureCalculateException(String featureName, String message) { super( String.format( "An error occurred when calculating feature '%s': %s", featureName, message)); messageWithoutKey = message; } /** * Removes any feature-name from the exception. * * @return a newly-created similar exception, but lacking any identifier for which feature * caused the exception. */ public FeatureCalculationException dropKey() { return new FeatureCalculationException(messageWithoutKey); } }
true
78330bce05cd146a11e903bbcc1610cc21952265
Java
Kowalski-RND/ytb-ninja
/src/main/java/ninja/ytb/senpai/dao/AbstractSenpaiDAO.java
UTF-8
1,187
2.265625
2
[ "MIT" ]
permissive
package ninja.ytb.senpai.dao; import java.io.Serializable; import java.util.List; import java.util.Map; import java.util.Optional; import org.hibernate.Criteria; import org.hibernate.Query; import org.hibernate.SessionFactory; import io.dropwizard.hibernate.AbstractDAO; public abstract class AbstractSenpaiDAO<T, I extends Serializable> extends AbstractDAO<T> { public AbstractSenpaiDAO(SessionFactory sessionFactory) { super(sessionFactory); } public T upsert(final T entity) { return persist(entity); } public final List<T> read(final String namedQuery) { return list(namedQuery(namedQuery)); } public final List<T> read(final Criteria criteria) { return list(criteria); } public final List<T> read(final String namedQuery, final Optional<Map<String, Object>> optionalParams) { Query query = super.namedQuery(namedQuery); if (optionalParams.isPresent()) { Map<String, Object> params = (Map<String, Object>) optionalParams.get(); for (Map.Entry<String, Object> param : params.entrySet()) { query.setParameter(param.getKey(), param.getValue()); } } return list(query); } public final T find(final I id) { return super.get(id); } }
true
1c60325ee046f4554bd96c6cc533e56dfb57c586
Java
fengtianjuedi/CommonMVC
/latte-core/src/main/java/com/wufeng/latte_core/database/UserProfile.java
UTF-8
1,118
2.078125
2
[]
no_license
package com.wufeng.latte_core.database; import org.greenrobot.greendao.annotation.Entity; import org.greenrobot.greendao.annotation.Id; import org.greenrobot.greendao.annotation.Generated; @Entity(nameInDb = "user_profile") public class UserProfile { @Id(autoincrement = true) private Long id; private String customerId; private String customerName; @Generated(hash = 957928604) public UserProfile(Long id, String customerId, String customerName) { this.id = id; this.customerId = customerId; this.customerName = customerName; } @Generated(hash = 968487393) public UserProfile() { } public Long getId() { return this.id; } public void setId(Long id) { this.id = id; } public String getCustomerId() { return this.customerId; } public void setCustomerId(String customerId) { this.customerId = customerId; } public String getCustomerName() { return this.customerName; } public void setCustomerName(String customerName) { this.customerName = customerName; } }
true