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 |
|---|---|---|---|---|---|---|---|---|---|---|---|
56fd31403b03fbd140c74d44515f4d8c2d047595 | Java | Avocadososemix/caverns | /src/main/java/Main.java | UTF-8 | 1,828 | 2.875 | 3 | [] | no_license |
import BinarySpacePartition.BinarySpacePartition;
import GameLogic.Level;
import javafx.application.Application;
import java.io.IOException;
import static javafx.application.Application.launch;
import javafx.fxml.FXMLLoader;
import javafx.scene.Parent;
import javafx.scene.Scene;
import javafx.stage.Stage;
/*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
/**
*
* @author lkaranko
*/
public class Main extends Application {
/**
* This method creates the Javafx panel for the program.
*
* @param primaryStage
* @throws IOException
*/
@Override
public void start(Stage primaryStage) throws IOException {
Parent root = setScene(primaryStage);
Scene scene = new Scene(root, 600, 500);
primaryStage.setScene(scene);
primaryStage.setTitle("Cavern Explorer");
primaryStage.show();
}
/**
* Loads the FXML for the GUI, and returns it to the Scene setting method.
*
* @param PrimaryStage
* @return
* @throws IOException
*/
private Parent setScene(Stage PrimaryStage) throws IOException {
FXMLLoader loader = new FXMLLoader();
loader.setLocation(getClass().getResource("/GUI.fxml"));
Parent root = loader.load();
return root;
}
public static void main(String[] args) {
// Level test1 = new Level(150,150);
// test1.fillWithWalls();
// BinarySpacePartition BSP = new BinarySpacePartition(8);
// test1 = BSP.generateBSP(test1);
// test1.randomWalk();
// test1.printLevel();
// System.out.println("Done.");
// System.exit(0);
launch(args);
}
}
| true |
db7988b63e4b80ea4ccf75f8f0958e3e47214caf | Java | Skyfire156/ProjectPortfolio | /Downtimeapp (Java)/Downtime App/src/downtimeapp/Downtimeapp.java | UTF-8 | 8,217 | 2.59375 | 3 | [] | no_license | /*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package downtimeapp;
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.util.logging.Level;
import java.util.logging.Logger;
public class Downtimeapp {
Player character;
Database data;
DowntimeGUI gui;
public static void main(String[] args) {
Downtimeapp program = new Downtimeapp();
}
public Downtimeapp(){
data = new Database();
try {
character = loadData();
} catch (IOException ex) {
Logger.getLogger(Downtimeapp.class.getName()).log(Level.SEVERE, null, ex);
} catch (ClassNotFoundException ex) {
Logger.getLogger(Downtimeapp.class.getName()).log(Level.SEVERE, null, ex);
}
if(character == null)
character = new Player(data);
//to be deleted once testing is done
/**
character.day = 168;
Building test = new Building(data);
test.name = "Tavern";
character.buildings.add(test);
character.adminbuildRoom(test, "Bar", true, 0);
character.adminbuildRoom(test, "Common Room", true, 0);
character.adminbuildRoom(test, "Kitchen", true, 0);
character.adminbuildRoom(test, "Lavatory", true, 0);
character.adminbuildRoom(test, "Office", true, 0);
character.adminbuildRoom(test, "Storage", true, 0);
character.adminbuildRoom(test, "Secret Room", true, 0);
character.adminbuildRoom(test, "Sewer Access", true, 0);
character.adminbuildRoom(test, "Stall", true, 0);
character.adminbuildRoom(test, "Lodging", true, 0);
character.adminbuildRoom(test, "Storefront", true, 0);
Building firstguild = new Building(data);
firstguild.name = "Thieves' Guild";
character.orgs.add(firstguild);
character.adminbuildRoom(firstguild, "Soldiers", false, 0);
character.adminbuildRoom(firstguild, "Scofflaws", false, 0);
character.adminbuildRoom(firstguild, "Robbers", false, 0);
character.adminbuildRoom(firstguild, "Cutpurses", false, 0);
character.adminbuildRoom(firstguild, "Cutpurses", false, 0);
character.adminbuildRoom(firstguild, "Mage", false, 0);
Building manor = new Building(data);
manor.name = "City Manor";
character.buildings.add(manor);
character.adminbuildRoom(manor, "Armory", true, 0);
character.adminbuildRoom(manor, "Auditorium", true, 0);
character.adminupgradeRoom(manor, manor.rooms.get(1), "Furnish", true);
character.adminbuildRoom(manor, "Auditorium", true, 0);
character.adminupgradeRoom(manor, manor.rooms.get(2), "Furnish", true);
character.adminbuildRoom(manor, "Bar", true, 0);
character.adminbuildRoom(manor, "Bath", true, 0);
character.adminbuildRoom(manor, "Bath", true, 0);
character.adminbuildRoom(manor, "Bedroom", true, 0);
character.adminupgradeRoom(manor, manor.rooms.get(6), "Furnish", true);
character.adminbuildRoom(manor, "Bedroom", true, 0);
character.adminbuildRoom(manor, "Bedroom", true, 0);
character.adminbuildRoom(manor, "Bedroom", true, 0);
character.adminbuildRoom(manor, "Courtyard", true, 0);
character.adminupgradeRoom(manor, manor.rooms.get(10), "Furnish", true);
character.adminbuildRoom(manor, "Courtyard", true, 0);
character.adminupgradeRoom(manor, manor.rooms.get(11), "Furnish", true);
character.adminbuildRoom(manor, "Defensive Wall", true, 0);
character.adminbuildRoom(manor, "Gatehouse", true, 0);
character.adminbuildRoom(manor, "Escape Route", true, 0);
character.adminbuildRoom(manor, "Kitchen", true, 0);
character.adminbuildRoom(manor, "Lavatory", true, 0);
character.adminbuildRoom(manor, "Lavatory", true, 0);
character.adminbuildRoom(manor, "Office", true, 0);
character.adminbuildRoom(manor, "Sewer Access", true, 0);
character.adminbuildRoom(manor, "Sitting Room", true, 0);
character.adminupgradeRoom(manor, manor.rooms.get(20), "Furnish", true);
character.adminbuildRoom(manor, "Stall", true, 0);
character.adminbuildRoom(manor, "Storage", true, 0);
character.storedgp = 1463;
character.Goods = 14;
character.Influence = 10;
character.Labor = 30;
for(int i = 0; i<10; i++){
Building tden = new Building(data);
tden.name = "Thief Den";
character.buildings.add(tden);
character.adminbuildRoom(tden, "Common Room", true, 0);
character.adminbuildRoom(tden, "Bar", true, 0);
character.adminbuildRoom(tden, "False Front", true,0);
character.adminbuildRoom(tden, "Storage", true,0);
}
for(int i = 0; i<12; i++){
Building tguild = new Building(data);
tguild.name = "Thief Guild";
character.orgs.add(tguild);
character.adminbuildRoom(tguild, "Scofflaws", false, 0);
character.adminbuildRoom(tguild, "Robbers", false, 0);
character.adminbuildRoom(tguild, "Cutpurses", false, 0);
}
for(int i = 0; i<3; i++){
Building tden = new Building(data);
tden.name = "Thief Den";
character.buildings.add(tden);
character.adminbuildRoom(tden, "Common Room", true, (156+5*i));
character.adminbuildRoom(tden, "Bar", true,(156+5*i));
character.adminbuildRoom(tden, "False Front", true,(156+5*i));
character.adminbuildRoom(tden, "Storage", true,(156+5*i));
if(i==2){
Building tguild = new Building(data);
tguild.name = "Thief Guild";
character.orgs.add(tguild);
character.adminbuildRoom(tguild, "Scofflaws", false, 166);
character.adminbuildRoom(tguild, "Robbers", false, 166);
character.adminbuildRoom(tguild, "Cutpurses", false, 166);
}
}
**/
//end to be deleted
gui = new DowntimeGUI(character, this);
gui.setVisible(true);
fillGUI();
gui.updateGUI();
}
public Player loadData() throws FileNotFoundException, IOException, ClassNotFoundException{
String loadpath = "DowntimeSave.sav";
File savedgame = new File(loadpath);
FileInputStream loadfile = new FileInputStream(savedgame);
Player room;
try (ObjectInputStream loaddata = new ObjectInputStream(loadfile)) {
room = (Player) loaddata.readObject();
}
return room;
}
public void saveData(Player savdata){
FileOutputStream savefile = null;
try {
File newsave = new File("DowntimeSave.sav");
savefile = new FileOutputStream(newsave);
ObjectOutputStream savedata = new ObjectOutputStream(savefile);
savedata.writeObject(savdata);
savedata.close();
} catch (FileNotFoundException ex) {
Logger.getLogger(Downtimeapp.class.getName()).log(Level.SEVERE, null, ex);
} catch (IOException ex) {
Logger.getLogger(Downtimeapp.class.getName()).log(Level.SEVERE, null, ex);
} finally {
try {
savefile.close();
} catch (IOException ex) {
Logger.getLogger(Downtimeapp.class.getName()).log(Level.SEVERE, null, ex);
}
}
}
public void fillGUI(){
for(Building build: character.buildings){
gui.addBuilding(true);
}
for(Building build: character.orgs){
gui.addBuilding(false);
}
}
} | true |
f998bbfaa3f8f9b1f530b098dcd4d8502522680b | Java | djgupta2013/Login-Register-webService | /LoginRegistrationProject/src/studentInterfaceImpl/StudentImpl.java | UTF-8 | 5,960 | 2.609375 | 3 | [] | no_license | package studentInterfaceImpl;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import bean.Otp;
import bean.User;
import connection.ConnectionProvider;
import studentInterfaceDao.StudentInterface;
public class StudentImpl implements StudentInterface{
Connection connection=null;
PreparedStatement preparedStatement=null;
@Override
public String login(User user) {
connection=ConnectionProvider.getConn();
try {
preparedStatement=connection.prepareStatement("select * from login where email=? and password=?");
preparedStatement.setString(1, user.getEmail());
preparedStatement.setString(2, user.getPassword());
ResultSet resultSet=preparedStatement.executeQuery();
if(resultSet.next()){
return "success";
}
else{
return "Incorrect password and email";
}
} catch (Exception e) {
e.printStackTrace();
}
return "Please register first";
}
@Override
public String register(User user) {
connection=ConnectionProvider.getConn();
try {
preparedStatement=connection.prepareStatement("select * from login where email=?");
preparedStatement.setString(1, user.getEmail());
ResultSet resultSet=preparedStatement.executeQuery();
if(resultSet.next()){
return "User already exist...";
}
else
{
PreparedStatement preparedStatement2=connection.prepareStatement("insert into login values(?,?,?)");
preparedStatement2.setString(1, user.getName());
preparedStatement2.setString(2, user.getPassword());
preparedStatement2.setString(3, user.getEmail());
preparedStatement2.executeUpdate();
return "success";
}
} catch (Exception e) {
e.printStackTrace();
}
return "fail";
}
@Override
public String delete(User user) {
connection=ConnectionProvider.getConn();
try {
preparedStatement=connection.prepareStatement("delete from login where email=?");
preparedStatement.setString(1, user.getEmail());
int flag = preparedStatement.executeUpdate();
if(flag == 1){
return "succeccfully delete";
}
else{
return "wrong email id";
}
} catch (Exception e) {
e.printStackTrace();
}
return "wrong email id";
}
@Override
public String findId(User user) {
connection=ConnectionProvider.getConn();
try {
preparedStatement=connection.prepareStatement("select * from login where email=?");
preparedStatement.setString(1, user.getEmail());
ResultSet resultSet= preparedStatement.executeQuery();
boolean flag=false;
while(resultSet.next()) {
String name=resultSet.getString("name");
String password=resultSet.getString("password");
String email=resultSet.getString("email");
flag=true;
System.out.println("Name : " +name+"\nPasswor : "+password+"\nEmail : "+email);
}
if(flag){
return "succeccfully find";
}
else{
return "email id not exist";
}
} catch (Exception e) {
e.printStackTrace();
}
return "wrong email id";
}
@Override
public String findAllId(User user) {
connection=ConnectionProvider.getConn();
try {
preparedStatement=connection.prepareStatement("select * from login ");
//preparedStatement.setString(1, user.getEmail());
ResultSet resultSet= preparedStatement.executeQuery();
boolean flag=false;
while(resultSet.next()) {
String name=resultSet.getString("name");
String password=resultSet.getString("password");
String email=resultSet.getString("email");
flag=true;
System.out.println("Name : " +name+"\nPasswor : "+password+"\nEmail : "+email);
}
if(flag){
return "succeccfully find";
}
else{
return "table empty";
}
} catch (Exception e) {
e.printStackTrace();
}
return "wrong email id";
}
@Override
public String update(User user) {
connection=ConnectionProvider.getConn();
try {
int flag = 0;
//update name
if((user.getName()!=null)&&(user.getEmail()!=null)&&(user.getPassword()==null)){
preparedStatement=connection.prepareStatement("update login set name=? where email=? ");
preparedStatement.setString(1, user.getName());
preparedStatement.setString(2, user.getEmail());
//flag= preparedStatement.executeUpdate();
}
//update password
else if(user.getPassword()!=null&&(user.getEmail()!=null)&&(user.getName()==null)){
preparedStatement=connection.prepareStatement("update login set password=? where email=? ");
preparedStatement.setString(1, user.getPassword());
preparedStatement.setString(2, user.getEmail());
//flag= preparedStatement.executeUpdate();
}
//update email
else if(user.getNewEmail()!=null&&(user.getEmail()!=null)){
preparedStatement=connection.prepareStatement("update login set email=? where email=? ");
preparedStatement.setString(1, user.getNewEmail());
preparedStatement.setString(2, user.getEmail());
}
//update name and email both
else if((user.getName()!=null)&&(user.getPassword()!=null)&&(user.getEmail()!=null)){
preparedStatement=connection.prepareStatement("update login set name=?, password=? where email=? ");
preparedStatement.setString(1, user.getName());
preparedStatement.setString(2, user.getPassword());
preparedStatement.setString(3, user.getEmail());
}
flag= preparedStatement.executeUpdate();
if(flag==1){
return "succeccfully update";
}
else{
return "{'msg' : 'enter wrong email'}";
}
} catch (Exception e) {
e.printStackTrace();
}
return "wrong email id";
}
@Override
public String verifyOtp(Otp otp) {
return null;
}
}
| true |
47ae820a80f6d1bcb7def0727f7e3a86c99eefb9 | Java | failry/dine | /dine/src/main/java/com/dine/service/impl/ProductServiceImpl.java | UTF-8 | 4,388 | 2.453125 | 2 | [] | no_license | package com.dine.service.impl;
import com.dine.entiry.ProductInfo;
import com.dine.dto.CartDTO;
import com.dine.enums.ProductStatusEnum;
import com.dine.enums.ResultEnum;
import com.dine.exception.SellException;
import com.dine.repository.ProductInfoRepository;
import com.dine.service.ProductService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Example;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import java.util.List;
import java.util.Optional;
/**
*
*/
@Service
public class ProductServiceImpl implements ProductService {
@Autowired
private ProductInfoRepository repository;
@Override
public Optional<ProductInfo> findOne(String productId) {
ProductInfo productInfo = new ProductInfo();
productInfo.setProductId(productId);
Example<ProductInfo> example = Example.of(productInfo);
return repository.findOne(example);
}
@Override
public List<ProductInfo> findUpAll() {
return repository.findByProductStatus(ProductStatusEnum.UP.getCode());
}
@Override
public Page<ProductInfo> findAll(Pageable pageable) {
return repository.findAll(pageable);
}
@Override
public ProductInfo save(ProductInfo productInfo) {
return repository.save(productInfo);
}
@Override
@Transactional
public void increaseStock(List<CartDTO> cartDTOList) {
for (CartDTO cartDTO: cartDTOList) {
ProductInfo productInfo = new ProductInfo();
productInfo.setProductId(cartDTO.getProductId());
Optional<ProductInfo> opt = repository.findOne(Example.of(productInfo));
if (!opt.isPresent()) {
throw new SellException(ResultEnum.PRODUCT_NOT_EXIST);
}
Integer result = productInfo.getProductStock() + cartDTO.getProductQuantity();
productInfo.setProductStock(result);
repository.save(productInfo);
}
}
@Override
@Transactional
public void decreaseStock(List<CartDTO> cartDTOList) {
for (CartDTO cartDTO: cartDTOList) {
Optional<ProductInfo> opt = repository.findById(cartDTO.getProductId());
if (!opt.isPresent()) {
throw new SellException(ResultEnum.PRODUCT_NOT_EXIST);
}
ProductInfo productInfo = opt.get();
Integer result = productInfo.getProductStock() - cartDTO.getProductQuantity();
if (result < 0) {
throw new SellException(ResultEnum.PRODUCT_STOCK_ERROR);
}
productInfo.setProductStock(result);
repository.save(productInfo);
}
}
@Override
public ProductInfo onSale(String productId) {
ProductInfo productInfoExample = new ProductInfo();
productInfoExample.setProductId(productId);
Example<ProductInfo> example = Example.of(productInfoExample);
Optional<ProductInfo> opt = repository.findOne(example);
if (!opt.isPresent()) {
throw new SellException(ResultEnum.PRODUCT_NOT_EXIST);
}
if (opt.get().getProductStatusEnum() == ProductStatusEnum.UP) {
throw new SellException(ResultEnum.PRODUCT_STATUS_ERROR);
}
ProductInfo productInfo = opt.get();
//更新
productInfo.setProductStatus(ProductStatusEnum.UP.getCode());
return repository.save(productInfo);
}
@Override
public ProductInfo offSale(String productId) {
ProductInfo productInfoExample = new ProductInfo();
productInfoExample.setProductId(productId);
Example<ProductInfo> example = Example.of(productInfoExample);
Optional<ProductInfo> opt = repository.findOne(example);
if (!opt.isPresent()) {
throw new SellException(ResultEnum.PRODUCT_NOT_EXIST);
}
ProductInfo productInfo = opt.get();
if (productInfo.getProductStatusEnum() == ProductStatusEnum.DOWN) {
throw new SellException(ResultEnum.PRODUCT_STATUS_ERROR);
}
//更新
productInfo.setProductStatus(ProductStatusEnum.DOWN.getCode());
return repository.save(productInfo);
}
}
| true |
e72eb75ffb70bd78883555c6411521b7c7b15ecc | Java | tandser/hibernate | /src/main/java/ru/tandser/hibernate/models/Amount.java | UTF-8 | 1,511 | 3.09375 | 3 | [] | no_license | package ru.tandser.hibernate.models;
import java.io.Serializable;
import java.math.BigDecimal;
import java.util.Currency;
import java.util.Objects;
public class Amount implements Serializable {
private BigDecimal amount;
private Currency currency;
public Amount(BigDecimal amount, Currency currency) {
this.amount = amount;
this.currency = currency;
}
@Override
public boolean equals(Object obj) {
if (this == obj) {
return true;
}
if (obj == null || getClass() != obj.getClass()) {
return false;
}
Amount that = (Amount) obj;
return Objects.equals(this.amount, that.amount) &&
Objects.equals(this.currency, that.currency);
}
@Override
public int hashCode() {
return Objects.hash(amount, currency);
}
@Override
public String toString() {
return amount.intValue() + " " + currency.getCurrencyCode();
}
public static Amount valueOf(String amount) {
String[] split = amount.split(" ");
return new Amount(new BigDecimal(split[0]), Currency.getInstance(split[1]));
}
/* Setters and Getters */
public BigDecimal getAmount() {
return amount;
}
public void setAmount(BigDecimal amount) {
this.amount = amount;
}
public Currency getCurrency() {
return currency;
}
public void setCurrency(Currency currency) {
this.currency = currency;
}
} | true |
fd9e6211d62e6489094f006628b48cf1d5b2a888 | Java | shannah/CN1FontBox | /src/com/codename1/ui/FontBoxFontProvider.java | UTF-8 | 5,517 | 2.40625 | 2 | [
"Apache-2.0"
] | permissive | /*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package com.codename1.ui;
import com.codename1.io.ConnectionRequest;
import com.codename1.io.FileSystemStorage;
import com.codename1.io.Log;
import com.codename1.io.NetworkManager;
import com.codename1.io.Storage;
import java.io.IOException;
import java.io.InputStream;
import java.util.HashMap;
import java.util.Map;
import org.apache.fontbox.ttf.TTFParser;
import org.apache.fontbox.ttf.TrueTypeFont;
/**
* A font provider for the FontBox library that should be registered with
ca.weblite.pisces.TTFFont so that it can make use of true-type fonts loaded through
fontbox.
*
* Currently this only provides a facade for truetype fonts even though fontbox
* likely has support for many more kinds. Additional types would probably require
* a little work to be able to generate Glyphs in teh correct format.
* @author shannah
*/
public class FontBoxFontProvider implements TTFFont.FontProvider{
Map<String, TrueTypeFont> ttfMap = new HashMap<String, TrueTypeFont>();
private static FontBoxFontProvider defaultProvider = null;
public static FontBoxFontProvider getDefaultProvider(){
if ( defaultProvider == null ){
defaultProvider = new FontBoxFontProvider();
TTFFont.addProvider(defaultProvider);
}
return defaultProvider;
}
/**
* Returns a font that has been previously loaded into the provider in the
* specified pixel size.
* @param name The name of the font (should match name provided by loadTTF()
* when the font was loaded.
* @param size
* @return The specified font or null if it hasn't been loaded.
*/
public TTFFont getFont(String name, float size) {
if ( ttfMap.containsKey(name)){
return ttfMap.get(name).getFont(name, size);
} else {
try {
InputStream fontStream = Display.getInstance().getResourceAsStream(null, "/"+name+".ttf");
if (fontStream != null) {
loadTTF(name, fontStream);
if ( ttfMap.containsKey(name)){
return ttfMap.get(name).getFont(name, size);
}
}
} catch (Exception ex){}
return null;
}
}
/**
* Loads a True Type font from an input stream. This must be called before
the getFont() method will be able to retrieve the font.
* @param name The name of the font. Used for looking up later via {@link #getFont(java.lang.String, float) }
* @param is InputStream with the .ttf file contents.
* @throws IOException
*/
public void loadTTF(String name, InputStream is) throws IOException{
if (ttfMap.containsKey(name)) {
return;
}
TTFParser parser = new TTFParser();
TrueTypeFont font = parser.parseTTF(is);
ttfMap.put(name, font);
}
/**
* Loads a font from storage if available. If not found, downloads font from
* url and saves it to storage.
* @param name The name of the font. Used for looking up later via {@link #getFont(java.lang.String, float) }
* @param storageKey The storage key where font should be stored.
* @param url The url where the font should be downloaded.
* @throws IOException
*/
public void createFontToStorage(String name, String storageKey, String url) throws IOException {
if (ttfMap.containsKey(name)) {
return;
}
Storage s = Storage.getInstance();
if (s.exists(storageKey)) {
loadTTF(name, s.createInputStream(storageKey));
return;
}
ConnectionRequest req = new ConnectionRequest();
req.setFailSilently(true);
req.setHttpMethod("GET");
req.setPost(false);
req.setDestinationStorage(storageKey);
req.setUrl(url);
NetworkManager.getInstance().addToQueueAndWait(req);
if (s.exists(storageKey)) {
loadTTF(name, s.createInputStream(storageKey));
return;
}
}
/**
* Loads a font from the file system if available. If not found, downloads font from
* url and saves it to the file system.
* @param name The name of the font. Used for looking up later via {@link #getFont(java.lang.String, float) }
* @param path The file system path where the font should be saved.
* @param url The url where the font may be downloaded.
* @throws IOException
*/
public void createFontToFileSystem(String name, String path, String url) throws IOException {
FileSystemStorage s = FileSystemStorage.getInstance();
if (s.exists(path)) {
loadTTF(name,s.openInputStream(path));
return;
}
ConnectionRequest req = new ConnectionRequest();
req.setFailSilently(true);
req.setHttpMethod("GET");
req.setPost(false);
req.setDestinationFile(path);
req.setUrl(url);
NetworkManager.getInstance().addToQueueAndWait(req);
if (s.exists(path)) {
loadTTF(name, s.openInputStream(path));
return;
}
}
/**
* Clears the font cache.
*/
public void clearFontCache(){
ttfMap.clear();
}
}
| true |
cd54db40afb99a4f86e8026ab6177be0da0cf835 | Java | KwonYI/WieV | /BackEnd/Project_A405/src/main/java/com/web/project/model/hr/Company.java | UTF-8 | 631 | 1.945313 | 2 | [] | no_license | package com.web.project.model.hr;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import com.fasterxml.jackson.annotation.JsonInclude;
import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;
@Entity
@Data
@NoArgsConstructor
@AllArgsConstructor
@JsonInclude(JsonInclude.Include.NON_NULL)
public class Company {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private int comSeq;
private String comName;
private String comLogo;
private String comAddress;
private String comHomepage;
}
| true |
c1e97b431f28667525145ddfd223e6f8e269eedf | Java | JRodrigues123/CMSC203-Workspace | /CMSC203_Lab1/src/MovieDriver.java | UTF-8 | 1,493 | 3.75 | 4 | [] | no_license | /**
*
* @author justinrodrigues
*/
import java.util.Scanner;
public class MovieDriver {
public static void main(String[] args) {
//Created Scanner
@SuppressWarnings("resource")
Scanner in = new Scanner(System.in);
Movie m1 = new Movie();
//Holds the movie's title and rating
String title;
String rating;
//Answer yes or no
String ans = "";
//Holds the amount of tickets
int tickets;
//This will allow the loop to repeat or not
int checkTheLoop = 1;
do{
//Tells the user to enter the title
System.out.println("Enter the name of the movie: ");
title = in.nextLine();
//Sets the titla of the movie to the Movie Class
m1.setTitle(title);
//Now asks the user to enter the rating
System.out.println("Enter the movie rating: ");
rating = in.nextLine();
//Sets the rating in the Movie class
m1.setRating(rating);
//Prompts the user
System.out.println("Enter the amount of tickets sold: ");
tickets = in.nextInt();
//Set the tickets in Movie
m1.setSoldTickets(tickets);
//This is the output
System.out.println(m1.toString());
System.out.println("Would you like to try again? Enter y or n");
in.next();
ans = in.nextLine();
//Check if it will loop or not
if(ans.equals("n")) {
checkTheLoop = 0;
}
} while(checkTheLoop == 1);
System.out.println("You are done boyo");
}
}
| true |
1f0314bf1b7975db57ea57d3987b80246b03b50e | Java | sitharaSasindu/Chat-Application | /Chat_CLient/build/generated/jax-wsCache/ChatService/chat/Message.java | UTF-8 | 2,596 | 2.328125 | 2 | [] | no_license |
package chat;
import javax.xml.bind.annotation.XmlAccessType;
import javax.xml.bind.annotation.XmlAccessorType;
import javax.xml.bind.annotation.XmlType;
/**
* <p>Java class for message complex type.
*
* <p>The following schema fragment specifies the expected content contained within this class.
*
* <pre>
* <complexType name="message">
* <complexContent>
* <restriction base="{http://www.w3.org/2001/XMLSchema}anyType">
* <sequence>
* <element name="lastEdited" type="{http://www.w3.org/2001/XMLSchema}string" minOccurs="0"/>
* <element name="messageContent" type="{http://www.w3.org/2001/XMLSchema}string" minOccurs="0"/>
* <element name="sender" type="{http://www.w3.org/2001/XMLSchema}string" minOccurs="0"/>
* </sequence>
* </restriction>
* </complexContent>
* </complexType>
* </pre>
*
*
*/
@XmlAccessorType(XmlAccessType.FIELD)
@XmlType(name = "message", propOrder = {
"lastEdited",
"messageContent",
"sender"
})
public class Message {
protected String lastEdited;
protected String messageContent;
protected String sender;
/**
* Gets the value of the lastEdited property.
*
* @return
* possible object is
* {@link String }
*
*/
public String getLastEdited() {
return lastEdited;
}
/**
* Sets the value of the lastEdited property.
*
* @param value
* allowed object is
* {@link String }
*
*/
public void setLastEdited(String value) {
this.lastEdited = value;
}
/**
* Gets the value of the messageContent property.
*
* @return
* possible object is
* {@link String }
*
*/
public String getMessageContent() {
return messageContent;
}
/**
* Sets the value of the messageContent property.
*
* @param value
* allowed object is
* {@link String }
*
*/
public void setMessageContent(String value) {
this.messageContent = value;
}
/**
* Gets the value of the sender property.
*
* @return
* possible object is
* {@link String }
*
*/
public String getSender() {
return sender;
}
/**
* Sets the value of the sender property.
*
* @param value
* allowed object is
* {@link String }
*
*/
public void setSender(String value) {
this.sender = value;
}
}
| true |
799be8f72ac514580baacd43f418d03e236d87da | Java | nabilaalifia/todolist | /src/it/simoli/todolist/EditActivity.java | UTF-8 | 1,978 | 2.671875 | 3 | [] | no_license | package it.simoli.todolist;
import android.os.Bundle;
import android.app.Activity;
import android.content.Context;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
public class EditActivity extends Activity {
private final String TAG = "EditActivity";
private static Context context = null;
private EditText myEditText = null;
private Button cancelButton = null;
private Button updateButton = null;
private ToDoRow todoRow = null;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
context = getApplicationContext();
setContentView(R.layout.activity_edit);
// Get references to UI
updateButton = (Button) findViewById(R.id.updateButton);
cancelButton = (Button) findViewById(R.id.cancelButton);
myEditText = (EditText) findViewById(R.id.myEditText2);
// Set event listeners
updateButton.setOnClickListener(updateListener);
cancelButton.setOnClickListener(cancelListener);
// Get current entity
todoRow = MainActivity.getRowToEdit();
// Set text to the entity text
myEditText.setText(todoRow.getTask());
}
private OnClickListener cancelListener = new OnClickListener() {
public void onClick(View v) {
Log.v(TAG, "Cancel button clicked!");
// Kill this activity!
finish();
}
};
private OnClickListener updateListener = new OnClickListener() {
public void onClick(View v) {
Log.v(TAG, "Update button clicked!");
// Update the entity
todoRow.setTask(myEditText.getText().toString());
// Save data
MainActivity.saveData();
// A task was updated. Here we will just display
// a toast to the user.
String message = getResources().getString(R.string.task_updated_successfully);
Util.showToast(context, message);
// Kill this activity!
finish();
}
};
}
| true |
d7df1e21c40e2062ebe7d7a858ca11dafe82ef59 | Java | LielBarouch/Eshop | /Product.java | UTF-8 | 1,339 | 2.96875 | 3 | [] | no_license | package Eshop;
public class Product {
protected String name;
protected int id;
protected double price;
protected double discount;
public Product(String name, int id, double price, double discount) {
this.name = name;
this.id = id;
this.price = price;
this.discount = discount;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public int getId() {
return id;
}
public void setId(int id) {
this.id = id+1000;
}
public double getPrice() {
return price;
}
public void setPrice(double price) {
this.price = price;
}
public double getDiscount() {
return discount;
}
public void setDiscount(int discount) {
this.discount = discount;
}
public void changePrice(double price){
this.price = price;
}
public void changeDiscount(int discount){
this.discount=discount;
}
public String toString() {
return "Product{" +
"name='" + name + '\'' +
", id=" + id +
", price=" + price +
", discount=" + discount +
'}';
}
}
| true |
24314fc3e7d1a7d5f63ff72fd74451c84c8252da | Java | IcyEzra/JavaProgramming2020_B21 | /src/day10_IfElseStatement/WarmupTasks.java | UTF-8 | 1,657 | 3.9375 | 4 | [] | no_license | package day10_IfElseStatement;
public class WarmupTasks {
public static void main(String[] args) {
//Task 1 Valid Triangle
String shape = "Triangle";
int num1 = 50;
int num2 = 70;
int num3 = 90;
boolean isTriangle = num1 + num2 + num3 == 180;
boolean notaTriangle = !isTriangle; //this line was not needed
if(isTriangle){
System.out.println(shape +" is a triangle");
}
if(notaTriangle){
System.out.println(shape + " is not a triangle");
}
System.out.println("============================================");
//Task 2 Maximum and minimum ( use integers from previous task)
boolean num1isMax = num1 > num2 && num1 > num3;
boolean num2isMax = num2 > num1 && num2 > num3;
boolean num3isMax = num3 > num1 && num3 > num2;
if(num1isMax){
System.out.println(num1 + " is maximum number");
}
if(num2isMax){
System.out.println(num2 + " is maximum number");
}
if(num3isMax){
System.out.println(num3 + " is maximum number");
}
//If number is minimum, alternative method
boolean num1isMin = num1 < num2 && num1 < num3;
boolean num2isMin = !num1isMin && num2 < num3;
boolean num3isMin = !num1isMin && !num2isMin;
String str = " is minimum number";
if(num1isMin){
System.out.println(num1 + str);
}
if(num2isMin){
System.out.println(num2 + str);
}
if(num3isMin){
System.out.println(num3 + str);
}
}
}
| true |
ca12d57c4ab49fee0969e4a6cf6a39f5d97e15d7 | Java | jconverter/jconverter | /src/main/java/org/jconverter/typesolver/TypeSolverChain.java | UTF-8 | 834 | 2.5 | 2 | [
"Apache-2.0"
] | permissive | package org.jconverter.typesolver;
import java.lang.reflect.Type;
import java.util.List;
import java.util.function.Function;
import org.jcategory.ChainOfResponsibilityExhaustedException;
import org.jcategory.strategy.ChainOfResponsibility;
public class TypeSolverChain<T> extends ChainOfResponsibility<TypeSolver<T>, Type> /*implements TypeSolver<T>*/ {
public TypeSolverChain(List<TypeSolver<T>> responsibilityChain) {
super(responsibilityChain, UnrecognizedObjectException.class);
}
@Override
public Type apply(Function<TypeSolver<T>, Type> evaluator) {
try {
return super.apply(evaluator);
} catch(ChainOfResponsibilityExhaustedException e) {
throw new UnrecognizedObjectException(e);
}
}
// @Override
// public Type inferType(T object) {
// return apply(new TypeSolverChainEvaluator<T>(object));
// }
}
| true |
b614acfebe7f0a6a7dae4f544d79c606c0c28c62 | Java | zhangdian/marketing | /src/main/java/com/bd17kaka/marketing/dao/UserInfoDaoImpl.java | UTF-8 | 1,635 | 2.28125 | 2 | [] | no_license | package com.bd17kaka.marketing.dao;
import java.sql.Types;
import java.util.List;
import org.apache.commons.lang.StringEscapeUtils;
import org.springframework.jdbc.core.simple.ParameterizedBeanPropertyRowMapper;
import org.springframework.stereotype.Repository;
import com.bd17kaka.marketing.po.UserInfo;
@Repository(value = "userInfoDao")
public class UserInfoDaoImpl extends SpringJDBCDaoSupport implements
UserInfoDao {
private static final String TableName = "user_info";
@Override
public boolean insert(UserInfo userInfo) {
String sql = "insert into "
+ TableName
+ " values(user_id,?,?,?,?,?,now())";
Object[] args = new Object[] {
StringEscapeUtils.escapeSql(userInfo.getUserName()),
StringEscapeUtils.escapeSql(userInfo.getPasswd()),
StringEscapeUtils.escapeSql(userInfo.getEmail()),
userInfo.getUserType(),
userInfo.getUserStatus(),
};
int[] argTypes = new int[] {
Types.VARCHAR,
Types.VARCHAR,
Types.VARCHAR,
Types.INTEGER,
Types.INTEGER};
return 0 < this.getJdbcTemplate().update(sql, args, argTypes);
}
@Override
public UserInfo get(String userName, String passwd) {
String sql = "select * from " + TableName + " where user_name=? and passwd=?";
Object[] args = new Object[]{userName, passwd};
int[] argTypes = new int[]{Types.VARCHAR, Types.VARCHAR};
List<UserInfo> listUser = this.getJdbcTemplate().query(sql, args, argTypes, ParameterizedBeanPropertyRowMapper.newInstance(UserInfo.class));
if(listUser == null || listUser.size() <= 0) return null;
return listUser.get(0);
}
}
| true |
b1fb5b2eb5bb6bc5f74ffa66e9ef8a473911c502 | Java | lee-chance/RAUM | /src/main/java/com/MajorCompany/RAUM/dto/SSB/paymentList.java | UTF-8 | 1,923 | 2.234375 | 2 | [] | no_license | package com.MajorCompany.RAUM.dto.SSB;
public class paymentList {
private String payment;
private String seq;
private String orderdate;
private String name;
private String image;
private String size;
private String qty;
private String price;
private String checked;
private String status;
public paymentList() {
// TODO Auto-generated constructor stub
}
public paymentList(String payment, String seq, String orderdate, String name, String image, String size, String qty,
String price, String checked, String status) {
super();
this.payment = payment;
this.seq = seq;
this.orderdate = orderdate;
this.name = name;
this.image = image;
this.size = size;
this.qty = qty;
this.price = price;
this.checked = checked;
this.status = status;
}
public String getPayment() {
return payment;
}
public void setPayment(String payment) {
this.payment = payment;
}
public String getSeq() {
return seq;
}
public void setSeq(String seq) {
this.seq = seq;
}
public String getOrderdate() {
return orderdate;
}
public void setOrderdate(String orderdate) {
this.orderdate = orderdate;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getImage() {
return image;
}
public void setImage(String image) {
this.image = image;
}
public String getSize() {
return size;
}
public void setSize(String size) {
this.size = size;
}
public String getQty() {
return qty;
}
public void setQty(String qty) {
this.qty = qty;
}
public String getPrice() {
return price;
}
public void setPrice(String price) {
this.price = price;
}
public String getChecked() {
return checked;
}
public void setChecked(String checked) {
this.checked = checked;
}
public String getStatus() {
return status;
}
public void setStatus(String status) {
this.status = status;
}
}
| true |
e886af853c0d3121998a436b412c0df2514764a4 | Java | MCC-Java/Poliklinik-Monolith-Indri-William | /src/main/java/com/mcc/poliklinik/services/JadwalService.java | UTF-8 | 1,010 | 1.945313 | 2 | [] | no_license | /*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package com.mcc.poliklinik.services;
import com.mcc.poliklinik.entities.Jadwal;
import com.mcc.poliklinik.repositories.JadwalRepository;
import java.util.List;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
/**
*
* @author ASUS
*/
@Service
public class JadwalService {
@Autowired
JadwalRepository jadwalRepository;
public List<Jadwal> getAll() {
return jadwalRepository.findAll();
}
public void save(Jadwal jadwal) {
jadwalRepository.save(jadwal);
}
public void delete(Integer id) {
jadwalRepository.delete(new Jadwal(id));
}
public Jadwal findById(Integer id) {
return jadwalRepository.findById(id).get();
}
}
| true |
e291827b657085a2fbe0a9811b2b48c9ffcf2e5a | Java | padenot/Summon | /src/fr/neamar/summon/holder/AppHolder.java | UTF-8 | 292 | 1.726563 | 2 | [] | no_license | package fr.neamar.summon.holder;
public class AppHolder extends Holder {
public String name = "";
public String nameLowerCased = "";
public String displayName = ""; // App name with markers to put query text
// in bold
public String packageName;
public String activityName;
}
| true |
08304cfd88f04c28874e5b58ed1d6c407a3fe2a7 | Java | andreagrance30/EventosFinal | /src/java/py/com/metre/administracionBase/cdi/ControladorBarrio.java | UTF-8 | 4,693 | 2.09375 | 2 | [] | no_license | package py.com.metre.administracionBase.cdi;
import java.io.Serializable;
import java.util.List;
import org.apache.log4j.Logger;
import javax.ejb.EJB;
import javax.enterprise.context.SessionScoped;
import javax.inject.Inject;
import javax.inject.Named;
import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;
import py.com.metre.administracionBase.ejb.BarrioEJB; /* Se importan las clases a ser utilizadas en el controlador*/
import py.com.metre.administracionBase.ejb.CiudadEJB; /* Desde cada controlador se puede acceder a todas las tablas de la base de datos mediante las clases correspondientes */
import py.com.metre.administracionBase.jpa.Barrio;
import py.com.metre.administracionBase.jpa.Ciudad;
import py.com.metre.administracionBase.jsf.JsfUtil;
/**
*
* @author Andrea
*/
@Named
@SessionScoped
public class ControladorBarrio implements Serializable {
Logger logger = Logger.getLogger(Barrio.class);
@PersistenceContext
protected EntityManager em;
@EJB
private BarrioEJB barrioEJB;
private Barrio barrioSeleccionado;
private Barrio barrioNuevo;
private List<Barrio> listaBarrio;
private Ciudad ciudadSeleccionado;
private List<Ciudad> listaCiudad;
@EJB
private CiudadEJB CiudadEJB;
private
@Inject
LoginControlador loginControlador;
public Barrio getBarrioNuevo() {
if (barrioNuevo == null) {
this.barrioNuevo = new Barrio();
}
return this.barrioNuevo;
}
public void setBarrioNuevo(Barrio barrio) {
if (barrio != null) {
this.barrioNuevo = barrio;
}
}
public Barrio getBarrioSeleccionado() {
if (barrioSeleccionado == null) {
barrioSeleccionado = new Barrio();
return barrioSeleccionado;
}
return barrioSeleccionado;
}
public void setBarrioSeleccionado(Barrio barrio) {
if (barrio != null) {
this.barrioSeleccionado = barrio;
}
}
public List<Barrio> getListaBarrio() {
listaBarrio = barrioEJB.listarTodos();
return listaBarrio;
}
public void setListaBarrio(List<Barrio> listaBarrio) {
this.listaBarrio = listaBarrio;
}
public List<Ciudad> getCiudad() {
try {
listaCiudad = CiudadEJB.listarTodos();
} catch (Exception ex) {
System.out.println("Error en carga de Listado de Ciudad:" + ex.getMessage());
return null;
}
return listaCiudad;
}
public Ciudad getCiudadSeleccionado() {
return ciudadSeleccionado;
}
public void setCiudadSeleccionado(Ciudad ciudadSeleccionado) {
if (ciudadSeleccionado != null) {
this.ciudadSeleccionado = ciudadSeleccionado;
barrioSeleccionado.setCiudadid(ciudadSeleccionado);
}
}
public void update() {
try {
if (this.barrioSeleccionado != null) {
barrioEJB.actualizar(barrioSeleccionado);
JsfUtil.agregarMensajeExito("Se ha actualizado correctamente.");
resetearCampos();
}
} catch (Exception ex) {
JsfUtil.agregarMensajeErrorGlobal(ex, "No se pudo actualizar: " + ex);
resetearCampos();
}
}
public void listar() {
if (this.barrioSeleccionado != null) {
barrioEJB.getBarrioPorId(barrioSeleccionado);
}
}
public void add() {
try {
barrioNuevo.setCiudadid(ciudadSeleccionado);
barrioEJB.insertar(barrioNuevo);
JsfUtil.agregarMensajeExito("Se ha guardado correctamente.");
resetearCampos();
} catch (Exception ex) {
JsfUtil.agregarMensajeErrorGlobal(ex, "Error al intentar guardar: " + ex);
resetearCampos();
}
}
private boolean validar() {
if (ciudadSeleccionado == null || ciudadSeleccionado.getId() == null) {
JsfUtil.agregarMensajeErrorCampo("Ciudad", "Debe seleccionar un ciudad");
return false;
}
return true;
}
public void delete() {
try {
if (this.barrioSeleccionado != null) {
barrioEJB.eliminar(barrioSeleccionado);
JsfUtil.agregarMensajeExito("El registro fue eliminado correctamente.");
}
} catch (Exception e) {
JsfUtil.agregarMensajeErrorGlobal(e, "Ocurrio un error al eliminar:" + e);
}
}
private void resetearCampos() {
barrioSeleccionado = null;
barrioNuevo = null;
ciudadSeleccionado= null;
}
}
| true |
d300382d49c117e1eb9e56d4ab2d7044981409e7 | Java | marcseid/Prog2 | /src/Tutorium_Termin_6/MannschaftenMain.java | UTF-8 | 1,110 | 3.359375 | 3 | [] | no_license | package Tutorium_Termin_6;
import java.util.HashMap;
import java.util.Map;
import java.util.Scanner;
public class MannschaftenMain {
public static void main(String[] args) {
Mannschaft aJugend = new Mannschaft("A Jugend");
aJugend.addSpieler(new Spieler("Julian", 1));
aJugend.addSpieler(new Spieler("Heinz", 10));
Mannschaft bJugend = new Mannschaft("B Jugend");
bJugend.addSpieler(new Spieler("Michael", 8));
bJugend.addSpieler(new Spieler("Johannes", 7));
Map<String, Mannschaft> mannschaften = new HashMap<>();
mannschaften.put(aJugend.getName(), aJugend);
mannschaften.put(bJugend.getName(), bJugend);
try(Scanner scanner = new Scanner(System.in)) {
System.out.print("Mannschaft: ");
String name = scanner.nextLine();
Mannschaft mannschaft = mannschaften.get(name);
if(mannschaft != null) {
for(Spieler spieler : mannschaft.getSpieler()) {
System.out.println(spieler.getName());
}
}
}
}
}
| true |
e83392665805283692bccc941c96ac52f2a35b89 | Java | nthung2112/NthSettings | /src/com/nth/settings/utils/Common.java | UTF-8 | 924 | 2.25 | 2 | [] | no_license | package com.nth.settings.utils;
import android.content.ContentResolver;
import android.preference.CheckBoxPreference;
import android.preference.ListPreference;
public class Common
{
public ContentResolver cr;
public Common(ContentResolver content)
{
cr = content;
}
public void initList(ListPreference lp)
{
lp.setValueIndex(SettingsUtils.getPreferenceInt(cr, lp.getKey(), 0));
lp.setSummary(lp.getEntry());
}
public void initCheckbox(CheckBoxPreference cb)
{
int i = SettingsUtils.getPreferenceInt(cr, cb.getKey(), 0);
boolean b = (i == 1) ? true : false;
cb.setChecked(b);
}
public void initCheckbox(CheckBoxPreference cb, int k)
{
int i = SettingsUtils.getPreferenceInt(cr, cb.getKey(), k);
boolean b = (i == 1) ? true : false;
cb.setChecked(b);
}
public void setSummary(String key, ListPreference lp)
{
if (key.equals(lp.getKey()))
{
lp.setSummary(lp.getEntry());
}
}
}
| true |
f92c1c0f20a866c6441a7ef542e79866d401cd08 | Java | fercotrena/serenity_bdd | /src/test/java/com/automationpractice/utils/PropertyReader.java | UTF-8 | 377 | 2.328125 | 2 | [] | no_license | package com.automationpractice.utils;
import java.util.ResourceBundle;
public class PropertyReader {
private ResourceBundle configFile;
public PropertyReader() {
try {
configFile = ResourceBundle.getBundle("base");
} catch (Exception ex) {
ex.printStackTrace();
}
}
public String getProperty(String key) {
return this.configFile.getString(key);
}
}
| true |
6a06d58d31af3127cf797418cb107aa5e0032b8c | Java | guylerme/menthor-patterns | /net.menthor.patternRecognition/src/net/menthor/patternRecognition/wizard/phasePattern/PhasePatternWizard.java | UTF-8 | 947 | 2.40625 | 2 | [] | no_license | package net.menthor.patternRecognition.wizard.phasePattern;
import net.menthor.patternRecognition.phasePattern.PhasePattern;
import net.menthor.patternRecognition.phasePattern.PhaseOccurrence;
import net.menthor.patternRecognition.wizard.PatternWizard;
import net.menthor.patternRecognition.wizard.FinishingPage;
import net.menthor.patternRecognition.wizard.PresentationPage;
public class PhasePatternWizard extends PatternWizard {
public PhasePatternWizard(PhaseOccurrence ptrn) {
super(ptrn, PhasePattern.getPatternInfo().name);
}
@Override
public void addPages() {
finishing = new FinishingPage();
presentation = new PresentationPage(PhasePattern.getPatternInfo().name, PhasePattern.getPatternInfo().acronym,
ptrn.toString(), PhasePattern.getPatternInfo().description);
addPage(presentation);
addPage(finishing);
}
public PhaseOccurrence getPtrn() {
return (PhaseOccurrence) ptrn;
}
} | true |
f0b84a9cd26d16bf588b1089ec7236c02b0a9f94 | Java | alvi17/GMA_App | /app/src/main/java/gma_chakra/gma_app/Ack_Resources.java | UTF-8 | 1,712 | 2.0625 | 2 | [] | no_license | package gma_chakra.gma_app;
import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.util.DisplayMetrics;
import android.view.View;
import android.widget.Button;
import android.widget.LinearLayout;
import android.widget.ScrollView;
/**
* Created by Alvi17 on 10/15/2015.
*/
public class Ack_Resources extends Activity{
ScrollView scrollView;
int w,h;
float density;
Button mainMenu;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.ack_resources);
scrollView=(ScrollView)findViewById(R.id.ackScroll);
LinearLayout.LayoutParams parms=(LinearLayout.LayoutParams)scrollView.getLayoutParams();
DisplayMetrics dMetrics = new DisplayMetrics();
this.getWindowManager().getDefaultDisplay().getMetrics(dMetrics);
density = dMetrics.density;
w = Math.round(dMetrics.widthPixels / density);
h = Math.round(dMetrics.heightPixels / density);
parms.height=dMetrics.heightPixels-Math.round(150*density);
// scrollView.setLayoutParams(parms);
mainMenu=(Button)findViewById(R.id.ack_main_button5);
mainMenu.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
Intent intent=new Intent(Ack_Resources.this,MainMenuClass.class);
startActivity(intent);
finish();
}
});
}
@Override
public void onBackPressed() {
Intent intent=new Intent(Ack_Resources.this,MainMenuClass.class);
startActivity(intent);
finish();
}
}
| true |
3e0685de60a22cd10045bc2f3778307cdfeba6ec | Java | rrifcode/Project2 | /MainModel/src/com/cskaoyan/controller/PassengerController.java | UTF-8 | 22,306 | 2.296875 | 2 | [] | no_license | package com.cskaoyan.controller;
import com.cskaoyan.bean.Passenger;
import com.cskaoyan.service.PassengerService;
import com.cskaoyan.utils.Downorder;
import com.cskaoyan.utils.Page;
import com.cskaoyan.utils.PassengerVO;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.ArrayList;
@Controller
public class PassengerController {
@Autowired
PassengerService passengerService;
//旅客信息首页-自动搜索/手动搜索
@RequestMapping("/Passenger/tolist.do")
public String tolistPassenger(String txtname, Integer currentPage, Model model) {
ArrayList<Passenger> passengers;//旅客
if (currentPage == null) {
currentPage = 1;
}
//总页数
int totalPage;
//每页有几条数据
int limit = 2;
//每页的起始记录是第几条记录
int offset;
//总的旅客
double totalPassenger;
//判断是否搜索
if (txtname == null || txtname.isEmpty()) {
//当没有进行搜索,则显示所有的记录
//计算offset
offset = (currentPage - 1) * limit;
//使用包装类
PassengerVO passengerVO = new PassengerVO(limit, offset);
//所有的旅客
passengers = passengerService.selectPassengersList(passengerVO);
//旅客总数
totalPassenger = passengerService.countAllPassenger();
//总页数
totalPage = (int) Math.ceil(totalPassenger / limit);
Page<Passenger> passengerPage = new Page<>();
//传入总页数
passengerPage.setTotalPage(totalPage);
//传入所有的旅客
passengerPage.setResult(passengers);
//传入当前页
passengerPage.setCurrentPage(currentPage);
//放入域对象
model.addAttribute("list", passengerPage);
return "/WEB-INF/jsp/passenger/list.jsp";
} else {
offset = (currentPage - 1) * limit;
//产生包装类
PassengerVO passengerVO1 = new PassengerVO(limit, offset);
passengerVO1.setName("%" + txtname + "%");
passengerVO1.setLimit(limit);
passengerVO1.setOffset(offset);
passengers = passengerService.findPassengerByName(passengerVO1);
//求出符合条件的人的个数
totalPassenger = passengerService.countAllPassengerByName("%" + txtname + "%");
//求出页面总数
totalPage = (int) Math.ceil(totalPassenger / limit);
//把所求的信息放到page中
Page<Passenger> passengerPage1 = new Page<>();
passengerPage1.setCurrentPage(currentPage);
passengerPage1.setTotalPage(totalPage);
passengerPage1.setResult(passengers);
model.addAttribute("list", passengerPage1);
model.addAttribute("txtname", txtname);
return "/WEB-INF/jsp/passenger/list.jsp";
}
}
//实现下拉框
@RequestMapping("/Passenger/toadd.do")
public String addDownList(Model model) {
/* mav1.addAttribute("listGender", passengerDownOrdersService.findGender());
mav1.addAttribute("listNation", passengerDownOrdersService.findNation());
mav1.addAttribute("listEducationDegree", passengerDownOrdersService.findCultureLevel());
mav1.addAttribute("listPassengerLevel", passengerDownOrdersService.findPassengerLevel());
mav1.addAttribute("listPapers", passengerDownOrdersService.findLicenseCategory());
mav1.addAttribute("listThingReason", passengerDownOrdersService.findReason());
modelAndView.setViewName("/WEB-INF/jsp/passenger/add.jsp");
return modelAndView;*/
ArrayList<Downorder> listGender = new ArrayList<>();//性别下拉菜单 默认-男31
Downorder Gender = new Downorder(31, "男");
Downorder Gender1 = new Downorder(1, "女");
listGender.add(Gender);
listGender.add(Gender1);
ArrayList<Downorder> listNation = new ArrayList<>();//民族下拉菜单 默认-汉33
Downorder Nation = new Downorder(33, "汉");
Downorder Nation1 = new Downorder(1, "苗");
Downorder Nation2 = new Downorder(2, "壮");
Downorder Nation3 = new Downorder(3, "其他");
listNation.add(Nation);
listNation.add(Nation1);
listNation.add(Nation2);
listNation.add(Nation3);
ArrayList<Downorder> listEducationDegree = new ArrayList<>();//文化程度 默认-高中-43
Downorder EducationDegree = new Downorder(43, "高中");
Downorder EducationDegree1 = new Downorder(1, "无");
Downorder EducationDegree2 = new Downorder(2, "小学");
Downorder EducationDegree3 = new Downorder(3, "初中");
Downorder EducationDegree4 = new Downorder(4, "大专");
Downorder EducationDegree5 = new Downorder(5, "本科");
Downorder EducationDegree6 = new Downorder(6, "研究生");
Downorder EducationDegree7 = new Downorder(7, "硕士");
Downorder EducationDegree8 = new Downorder(8, "博士");
Downorder EducationDegree9 = new Downorder(9, "其他");
listEducationDegree.add(EducationDegree);
listEducationDegree.add(EducationDegree1);
listEducationDegree.add(EducationDegree2);
listEducationDegree.add(EducationDegree3);
listEducationDegree.add(EducationDegree4);
listEducationDegree.add(EducationDegree5);
listEducationDegree.add(EducationDegree6);
listEducationDegree.add(EducationDegree7);
listEducationDegree.add(EducationDegree8);
listEducationDegree.add(EducationDegree9);
ArrayList<Downorder> listPassengerLevel = new ArrayList<>();//旅客级别 默认-首次-52
Downorder PassengerLevel = new Downorder(52, "首次");
Downorder PassengerLevel1 = new Downorder(1, "熟客");
Downorder PassengerLevel2 = new Downorder(2, "VIP");
listPassengerLevel.add(PassengerLevel);
listPassengerLevel.add(PassengerLevel1);
listPassengerLevel.add(PassengerLevel2);
ArrayList<Downorder> listPapers = new ArrayList<>();//证件类型 默认-身份证-37
Downorder Papers = new Downorder(37, "二代身份证");
Downorder Papers1 = new Downorder(1, "护照");
Downorder lPapers2 = new Downorder(2, "其他");
listPapers.add(Papers);
listPapers.add(Papers1);
listPapers.add(lPapers2);
ArrayList<Downorder> listThingReason = new ArrayList<>();//事由 默认-个人旅行-51
Downorder ThingReason = new Downorder(51, "个人旅行");
Downorder ThingReason1 = new Downorder(1, "公务出差");
listThingReason.add(ThingReason);
listThingReason.add(ThingReason1);
//放入值
model.addAttribute("listGender", listGender);
model.addAttribute("listNation", listNation);
model.addAttribute("listEducationDegree", listEducationDegree);
model.addAttribute("listPassengerLevel", listPassengerLevel);
model.addAttribute("listPapers", listPapers);
model.addAttribute("listThingReason", listThingReason);
return "/WEB-INF/jsp/passenger/add.jsp";
}
//把数据插入表中
@RequestMapping("/Passenger/add.do")
public String add(Passenger passenger) throws ServletException, IOException, ServletException, IOException {
switch (passenger.getGenderID()) {
case "1":
passenger.setGenderName("女");
break;
case "31":
passenger.setGenderName("男");
break;
}
switch (passenger.getNationID()) {
case "33":
passenger.setNationName("汉");
break;
case "1":
passenger.setNationName("苗族");
break;
case "2":
passenger.setNationName("壮");
break;
case "3":
passenger.setNationName("其他");
break;
}
switch (passenger.getPassengerLevelID()) {
case "52":
passenger.setPassengerLevelName("首次");
break;
case "1":
passenger.setPassengerLevelName("熟客");
break;
case "2":
passenger.setPassengerLevelName("VIP");
break;
}
switch (passenger.getPapersID()) {
case "37":
passenger.setPapersName("二代身份证");
break;
case "1":
passenger.setPapersName("护照");
break;
case "2":
passenger.setPapersName("其他");
break;
}
switch (passenger.getEducationDegreeID()) {
case "43":
passenger.setEducationDegree("高中");
break;
case "1":
passenger.setEducationDegree("无");
break;
case "2":
passenger.setEducationDegree("小学");
break;
case "3":
passenger.setEducationDegree("初中");
break;
case "4":
passenger.setEducationDegree("大专");
break;
case "5":
passenger.setEducationDegree("本科");
break;
case "6":
passenger.setEducationDegree("研究生");
break;
case "7":
passenger.setEducationDegree("硕士");
break;
case "8":
passenger.setEducationDegree("博士");
break;
case "9":
passenger.setEducationDegree("其他");
break;
}
switch (passenger.getThingReasonID()) {
case "51":
passenger.setThingReason("个人旅行");
break;
case "1":
passenger.setThingReason("公务出差");
break;
}
System.out.println(passenger);
//添加passenger
passengerService.addPassenger(passenger);
return "/Passenger/tolist.do";
}
//实现修改页面的下拉框
@RequestMapping("/Passenger/toupdate.do")
public String updateDownList(String id, Model model) {
// mav2.addAttribute("listGender", passengerDownOrdersService.findGender());
// mav2.addAttribute("listNation", passengerDownOrdersService.findNation());
// mav2.addAttribute("listEducationDegree", passengerDownOrdersService.findCultureLevel());
// mav2.addAttribute("listPassengerLevel", passengerDownOrdersService.findPassengerLevel());
// mav2.addAttribute("listPapers", passengerDownOrdersService.findLicenseCategory());
// mav2.addAttribute("listThingReason", passengerDownOrdersService.findReason());
// Passenger passengerById = passengerService.findPassengerById(Integer.parseInt(id));
// //借助map把修改前的信息放在修改页面
// HashMap<String, String> list = new HashMap<>();
// list.put("name",passengerById.getName());
// //String.valueOf(passengerById.getId())中的passengerById.getId()是int型,此方法把int型转化为String型
// list.put("id",String.valueOf(passengerById.getId()));
// //添上会报500
// //list.put("genderID",passengerById.getGenderName());
// //list.put("nationID",passengerById.getNationName());
// //list.put("educationDegreeID",passengerById.getEducationDegreeID());
// //list.put("passengerLevelID",passengerById.getPassengerLevelName());
// //list.put("papersID",passengerById.getPapersName());
// //list.put("thingReasonID",passengerById.getThingReasonID());
// list.put("name",passengerById.getName());
// list.put("birthDate",passengerById.getBirthDate());
// list.put("papersValidity",passengerById.getPapersValidity());
// list.put("profession",passengerById.getProfession());
// list.put("papersNumber",passengerById.getPapersNumber());
// list.put("unitsOrAddress",passengerById.getUnitsOrAddress());
// list.put("whereAreFrom",passengerById.getWhereAreFrom());
// list.put("whereToGo",passengerById.getWhereToGo());
// list.put("contactPhoneNumber",passengerById.getContactPhoneNumber());
// list.put("remarks",passengerById.getRemarks());
// mav2.addAttribute("list",list);
// modelAndView.setViewName("/WEB-INF/jsp/passenger/update.jsp?id="+id);
// return modelAndView;
ArrayList<Downorder> listGender = new ArrayList<>();//性别下拉菜单 默认-男31
Downorder Gender = new Downorder(31, "男");
Downorder Gender1 = new Downorder(1, "女");
listGender.add(Gender);
listGender.add(Gender1);
ArrayList<Downorder> listNation = new ArrayList<>();//民族下拉菜单 默认-汉33
Downorder Nation = new Downorder(33, "汉");
Downorder Nation1 = new Downorder(1, "苗");
Downorder Nation2 = new Downorder(2, "壮");
Downorder Nation3 = new Downorder(3, "其他");
listNation.add(Nation);
listNation.add(Nation1);
listNation.add(Nation2);
listNation.add(Nation3);
ArrayList<Downorder> listEducationDegree = new ArrayList<>();//文化程度 默认-高中-43
Downorder EducationDegree = new Downorder(43, "高中");
Downorder EducationDegree1 = new Downorder(1, "无");
Downorder EducationDegree2 = new Downorder(2, "小学");
Downorder EducationDegree3 = new Downorder(3, "初中");
Downorder EducationDegree4 = new Downorder(4, "大专");
Downorder EducationDegree5 = new Downorder(5, "本科");
Downorder EducationDegree6 = new Downorder(6, "研究生");
Downorder EducationDegree7 = new Downorder(7, "硕士");
Downorder EducationDegree8 = new Downorder(8, "博士");
Downorder EducationDegree9 = new Downorder(9, "其他");
listEducationDegree.add(EducationDegree);
listEducationDegree.add(EducationDegree1);
listEducationDegree.add(EducationDegree2);
listEducationDegree.add(EducationDegree3);
listEducationDegree.add(EducationDegree4);
listEducationDegree.add(EducationDegree5);
listEducationDegree.add(EducationDegree6);
listEducationDegree.add(EducationDegree7);
listEducationDegree.add(EducationDegree8);
listEducationDegree.add(EducationDegree9);
ArrayList<Downorder> listPassengerLevel = new ArrayList<>();//旅客级别 默认-首次-52
Downorder PassengerLevel = new Downorder(52, "首次");
Downorder PassengerLevel1 = new Downorder(1, "熟客");
Downorder PassengerLevel2 = new Downorder(2, "VIP");
listPassengerLevel.add(PassengerLevel);
listPassengerLevel.add(PassengerLevel1);
listPassengerLevel.add(PassengerLevel2);
ArrayList<Downorder> listPapers = new ArrayList<>();//证件类型 默认-身份证-37
Downorder Papers = new Downorder(37, "二代身份证");
Downorder Papers1 = new Downorder(1, "护照");
Downorder lPapers2 = new Downorder(2, "其他");
listPapers.add(Papers);
listPapers.add(Papers1);
listPapers.add(lPapers2);
ArrayList<Downorder> listThingReason = new ArrayList<>();//事由 默认-个人旅行-51
Downorder ThingReason = new Downorder(51, "个人旅行");
Downorder ThingReason1 = new Downorder(1, "公务出差");
listThingReason.add(ThingReason);
listThingReason.add(ThingReason1);
//查出需要回显的passenger对象
Passenger passenger = passengerService.findPassengerById(Integer.parseInt(id));
//放入值
model.addAttribute("list",passenger);
model.addAttribute("listGender", listGender);
model.addAttribute("listNation", listNation);
model.addAttribute("listEducationDegree", listEducationDegree);
model.addAttribute("listPassengerLevel", listPassengerLevel);
model.addAttribute("listPapers", listPapers);
model.addAttribute("listThingReason", listThingReason);
return"/WEB-INF/jsp/passenger/update.jsp";
}
//点击修改页面-修改按钮
@RequestMapping("/Passenger/update")
public String updateInformation(Passenger passenger, Model model) throws ServletException, IOException {
// //未修改前的信息放在add.jsp上
// modelAndView.addObject("list", passengerService.findPassengerById(passenger.getId()));
// modelAndView.setViewName("/WEB-INF/jsp/passenger/update.jsp");
// return modelAndView
/* Passenger passengerById = passengerService.findPassengerById(Integer.parseInt(id));
//更新
passengerById.setName(request.getParameter("name"));
passengerById.setBirthDate(request.getParameter("birthDate"));
passengerById.setPapersValidity(request.getParameter("papersValidity"));
passengerById.setProfession(request.getParameter("profession"));
passengerById.setPapersNumber(request.getParameter("papersNumber"));
passengerById.setUnitsOrAddress(request.getParameter("unitsOrAddress"));
passengerById.setWhereAreFrom(request.getParameter("whereAreFrom"));
passengerById.setWhereToGo(request.getParameter("whereToGo"));
passengerById.setContactPhoneNumber(request.getParameter("contactPhoneNumber"));
passengerById.setRemarks(request.getParameter("remarks"));
passengerById.setGenderName(request.getParameter("genderID"));
passengerById.setNationName(request.getParameter("nationID"));
passengerById.setEducationDegreeID(request.getParameter("educationDegreeID"));
passengerById.setPassengerLevelName(request.getParameter("passengerLevelID"));
passengerById.setPapersName(request.getParameter("papersID"));
passengerById.setThingReasonID(request.getParameter("thingReasonID"));
int i = Integer.parseInt(id);
int log = passengerService.updatePassenger(passengerById);
System.out.println(passengerById);*/
switch (passenger.getGenderID()) {
case "1":
passenger.setGenderName("女");
break;
case "31":
passenger.setGenderName("男");
break;
}
switch (passenger.getNationID()) {
case "33":
passenger.setNationName("汉");
break;
case "1":
passenger.setNationName("苗族");
break;
case "2":
passenger.setNationName("壮");
break;
case "3":
passenger.setNationName("其他");
break;
}
switch (passenger.getPassengerLevelID()) {
case "52":
passenger.setPassengerLevelName("首次");
break;
case "1":
passenger.setPassengerLevelName("熟客");
break;
case "2":
passenger.setPassengerLevelName("VIP");
break;
}
switch (passenger.getPapersID()) {
case "37":
passenger.setPapersName("二代身份证");
break;
case "1":
passenger.setPapersName("护照");
break;
case "2":
passenger.setPapersName("其他");
break;
}
switch (passenger.getEducationDegreeID()) {
case "43":
passenger.setEducationDegree("高中");
break;
case "1":
passenger.setEducationDegree("无");
break;
case "2":
passenger.setEducationDegree("小学");
break;
case "3":
passenger.setEducationDegree("初中");
break;
case "4":
passenger.setEducationDegree("大专");
break;
case "5":
passenger.setEducationDegree("本科");
break;
case "6":
passenger.setEducationDegree("研究生");
break;
case "7":
passenger.setEducationDegree("硕士");
break;
case "8":
passenger.setEducationDegree("博士");
break;
case "9":
passenger.setEducationDegree("其他");
break;
}
switch (passenger.getThingReasonID()) {
case "51":
passenger.setThingReason("个人旅行");
break;
case "1":
passenger.setThingReason("公务出差");
break;
}
//根据id更新 passenger
int log = passengerService.updatePassenger(passenger);
//更新后跳转到tolist.do页面
return "/Passenger/tolist.do";
}
@RequestMapping("/Passenger/delete.do")
public void deletePassenger(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
//删除得到的id参数是
String ids = request.getParameter("id");
String[] split = ids.split(",");
for (String id : split) {
//根据id删除
passengerService.deletePassengerById(Integer.parseInt(id));
}
request.getRequestDispatcher("tolist.do").forward(request, response);
}
} | true |
d467178f7996b5c80ac8588eb4fd175774c2b36c | Java | P79N6A/icse_20_user_study | /methods/Method_1017178.java | UTF-8 | 116 | 1.742188 | 2 | [] | no_license | public IndexRequestBuilder index(String index,String type){
return client.getClient().prepareIndex(index,type);
}
| true |
e342e3f637a858b22184bde35ecacc98d3d0f5f6 | Java | jparkerpearson/APT-sets-java | /APT Set 3/src/UnderCoverCoder.java | UTF-8 | 1,833 | 3.453125 | 3 | [] | no_license | import java.util.HashMap;
public class UnderCoverCoder {
public int totalNotes(String[] clips, String[] notes) {
// make all lowercase
// loop through .charat add everything in to map
// }
for ( int i=0; i<clips.length;i++)
{
clips[i]=clips[i].replaceAll("\\s","");
clips[i]=clips[i].toLowerCase();
}
for ( int i=0; i<notes.length;i++)
{
notes[i]=notes[i].replaceAll("\\s","");
notes[i]=notes[i].toLowerCase();
}
HashMap<Character,Integer> lettersOccured = new HashMap<Character,Integer>();
int counter=0;
for (String s:clips)
{
for (int i=0; i<s.length();i++)
{
if(lettersOccured.containsKey(s.charAt(i)))
{
lettersOccured.put(s.charAt(i), lettersOccured.get(s.charAt(i)) + 1);
}
else
{
lettersOccured.put(s.charAt(i),1);
}
}
}
for (String s:notes)
{
boolean decider=true;
HashMap<Character,Integer> lettersNeeded = new HashMap<Character,Integer>();
for (int i=0; i<s.length();i++)
{
if(lettersNeeded.containsKey(s.charAt(i)))
{
lettersNeeded.put(s.charAt(i), lettersNeeded.get(s.charAt(i)) + 1);
}
else
{
lettersNeeded.put(s.charAt(i),1);
}
}
for(Character letter:lettersNeeded.keySet())
{
if(lettersOccured.get(letter)==null || lettersNeeded.get(letter)>lettersOccured.get(letter))
{
decider=false;
}
}
if (decider)
counter++;
}
return counter;
}
public static void main(String [] args)
{
String[] tester = {"Programming is fun " };
String[] tester2= {"program ", " programmer ", " gaming ", " sing ", " NO FUN "};
UnderCoverCoder test = new UnderCoverCoder();
System.out.println(test.totalNotes(tester, tester2));
}
}
| true |
2d7ae82c4176b11c9e34cd7e1e234b6e9fb21f8d | Java | yangfancoming/mybatis | /src/main/java/org/apache/ibatis/builder/IncompleteElementException.java | UTF-8 | 496 | 1.914063 | 2 | [
"Apache-2.0",
"BSD-3-Clause"
] | permissive |
package org.apache.ibatis.builder;
public class IncompleteElementException extends BuilderException {
private static final long serialVersionUID = -3697292286890900315L;
public IncompleteElementException() {
super();
}
public IncompleteElementException(String message, Throwable cause) {
super(message, cause);
}
public IncompleteElementException(String message) {
super(message);
}
public IncompleteElementException(Throwable cause) {
super(cause);
}
}
| true |
a52e7da3f4109eeb52b8916ceec253c23f7df005 | Java | renandpaula/RestServiceAluno | /src/main/java/br/edu/ucsal/restalunos/viewer/model/Aluno.java | UTF-8 | 1,275 | 2.515625 | 3 | [] | no_license | package br.edu.ucsal.restalunos.viewer.model;
import com.fasterxml.jackson.annotation.JsonIgnore;
import com.fasterxml.jackson.annotation.JsonProperty;
public class Aluno {
private String nome;
@JsonIgnore
private Turma turma;
private String nomeTurma;
private int matricula;
public Aluno() {
}
public Aluno(String nome) {
this.nome = nome;
}
public Aluno(String nome, Turma turma) {
this.nome = nome;
this.turma = turma;
}
public Aluno(String nome, int matricula) {
this.nome = nome;
this.matricula = matricula;
}
public Aluno(String nome, Turma turma, int matricula) {
this.nome = nome;
this.turma = turma;
this.matricula = matricula;
}
public String getNome() {
return nome;
}
public void setNome(String nome) {
this.nome = nome;
}
public Turma getTurma() {
return turma;
}
public void setTurma(Turma turma) {
this.turma = turma;
}
public int getMatricula() {
return matricula;
}
public void setMatricula(int matricula) {
this.matricula = matricula;
}
@JsonProperty("turma")
public String getNomeTurma() {
return nomeTurma;
}
public void setNomeTurma(String nomeTurma) {
this.nomeTurma = nomeTurma;
}
}
| true |
57550ba9803b2c11d4d02ff8759418a7dbb64932 | Java | v1nc3ntl1/learn-java | /PackageChallenge/src/com/learning/Series.java | UTF-8 | 1,301 | 3.859375 | 4 | [] | no_license | package com.learning;
public class Series {
public static int nSum(int n) {
int sum = 0;
int previousInt = 0;
for (int i = 1; i < n; i++) {
sum += (previousInt + i);
previousInt = previousInt + i;
System.out.println(previousInt);
}
return sum;
}
public static int factorial(int n) {
if (n == 0){
return 1;
}
int sum = 0;
int current;
for (int i = 1; i <= n; i++) {
current = 1;
for (int j = 1; j <= i; j++) {
current *= j;
}
//System.out.println("Current element is " + current);
sum += current;
}
return sum;
}
public static int fibonacci(int n) {
if (n ==0){
return 0;
}else if (n == 1){
return 1;
}
int sum = 0;
int current = 0;
int firstPrevious = 1;
int secondPrevious = 0;
for (int i = 1; i <= n; i++) {
current = firstPrevious + secondPrevious;
System.out.println("current is " + current);
firstPrevious=secondPrevious;
secondPrevious = current;
sum += current;
}
return sum;
}
}
| true |
4b838a99a02712dfd4e1dd9840cc4c7b00a1b0d0 | Java | markzgwu/mobileapps | /lbs/src/org/examples/v2/DrawGrids.java | UTF-8 | 874 | 3.171875 | 3 | [] | no_license | package org.examples.v2;
import java.awt.*;
import java.awt.event.*;
class Grids extends Canvas {
int width, height, rows, columns;
Grids(int w, int h, int r, int c) {
setSize(width = w, height = h);
rows = r;
columns = c;
}
public void paint(Graphics g) {
int k;
width = getSize().width;
height = getSize().height;
int htOfRow = height / (rows);
for (k = 0; k < rows; k++)
g.drawLine(0, k * htOfRow , width, k * htOfRow );
int wdOfRow = width / (columns);
for (k = 0; k < columns; k++)
g.drawLine(k*wdOfRow , 0, k*wdOfRow , height);
}
}
public class DrawGrids extends Frame {
DrawGrids(String title, int w, int h, int rows, int columns) {
setTitle(title);
Grids grid = new Grids(w, h, rows, columns);
add(grid);
}
public static void main(String[] args) {
new DrawGrids("Draw Grids", 200, 200, 2, 10).setVisible(true);
}
}
| true |
454bf029d43e16dfd522b426572e79e6a62fa0ce | Java | sven-meyenberger/JavaTraining | /src/main/java/stage/AdvancedStage.java | UTF-8 | 1,118 | 2.671875 | 3 | [
"Unlicense"
] | permissive | package stage;
import javafx.application.Application;
import javafx.fxml.FXMLLoader;
import javafx.scene.Parent;
import javafx.scene.Scene;
import javafx.stage.Stage;
import javafx.stage.StageStyle;
public class AdvancedStage extends Application {
@Override
public void start(Stage primaryStage) throws Exception {
Parent parent = FXMLLoader.load(getClass().getResource("/Window.fxml"));
Scene scene;
String osName = System.getProperty("os.name");
if( osName != null && osName.startsWith("Windows") ) {
scene = (new Shadow()).getShadowScene(parent);
primaryStage.initStyle(StageStyle.TRANSPARENT);
} else {
scene = new Scene(parent);
primaryStage.initStyle(StageStyle.UNDECORATED);
}
scene.getStylesheets().add("/css.css");
primaryStage.setTitle("Test");
primaryStage.setScene( scene );
primaryStage.setMinHeight(200.0d);
primaryStage.setMinWidth(300.0d);
primaryStage.show();
}
public static void main(String[] args) {
launch(args);
}
}
| true |
38d70d88f66cfae73d9b05f8a3a981551805adf5 | Java | gunsliderua-second/profiles-loader | /app/src/main/java/denys/salikhov/exam01/profileloader/ui/AvatarActivity.java | UTF-8 | 695 | 2.0625 | 2 | [] | no_license | package denys.salikhov.exam01.profileloader.ui;
import android.os.Bundle;
import android.support.v7.app.ActionBarActivity;
import denys.salikhov.exam01.profileloader.R;
public class AvatarActivity extends ActionBarActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_avatar);
String avatarURL = getIntent().getStringExtra(UserListFragment.IProfileClickHandler.AVATAR_EXTRA);
if (avatarURL != null) {
BigAvatarFragment bigAvatarFragment = (BigAvatarFragment) getSupportFragmentManager().findFragmentById(R.id.fragment_big_avatar);
bigAvatarFragment.updateAvatar(avatarURL);
}
}
}
| true |
8abb87f3a0744c970d3dfac95ca45b4a15bf4703 | Java | cylgtl/jiancha | /src/main/java/org/jeecgframework/web/system/service/impl/DynamicDataSourceServiceImpl.java | UTF-8 | 1,392 | 2.109375 | 2 | [] | no_license | package org.jeecgframework.web.system.service.impl;
import java.util.List;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.jeecgframework.core.common.service.impl.CommonServiceImpl;
import org.jeecgframework.web.system.service.DynamicDataSourceService;
import org.jeecgframework.web.system.entity.DynamicDataSourceEntity;
@Service("dynamicDataSourceService")
@Transactional
public class DynamicDataSourceServiceImpl extends CommonServiceImpl implements DynamicDataSourceService {
/**初始化数据库信息,TOMCAT启动时直接加入到内存中**/
public List<DynamicDataSourceEntity> initDynamicDataSource() {
DynamicDataSourceEntity.DynamicDataSourceMap.clear();
List<DynamicDataSourceEntity> dynamicSourceEntityList = this.commonDao.findAll(DynamicDataSourceEntity.class);
for (DynamicDataSourceEntity dynamicSourceEntity : dynamicSourceEntityList) {
DynamicDataSourceEntity.DynamicDataSourceMap.put(dynamicSourceEntity.getDbKey(), dynamicSourceEntity);
}
return dynamicSourceEntityList;
}
public static DynamicDataSourceEntity getDbSourceEntityByKey(String dbKey) {
DynamicDataSourceEntity dynamicDataSourceEntity = DynamicDataSourceEntity.DynamicDataSourceMap.get(dbKey);
return dynamicDataSourceEntity;
}
public void refleshCache() {
initDynamicDataSource();
}
} | true |
67ce5477cfc4f9bca8a5b5b59cd08809fa223388 | Java | craigmcc/bookcase-client-test | /src/test/java/org/craigmcc/bookcase/client/AuthorClientTest.java | UTF-8 | 10,771 | 2.203125 | 2 | [
"Apache-2.0"
] | permissive | /*
* Copyright 2020 craigmcc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.craigmcc.bookcase.client;
import org.craigmcc.bookcase.model.Anthology;
import org.craigmcc.bookcase.model.Author;
import org.craigmcc.bookcase.model.Book;
import org.craigmcc.bookcase.model.Series;
import org.craigmcc.library.shared.exception.BadRequest;
import org.craigmcc.library.shared.exception.NotFound;
import org.craigmcc.library.shared.exception.NotUnique;
import org.junit.Before;
import org.junit.Test;
import java.util.ArrayList;
import java.util.List;
import static java.lang.Boolean.TRUE;
import static org.hamcrest.MatcherAssert.assertThat;
import static org.hamcrest.Matchers.greaterThan;
import static org.hamcrest.Matchers.is;
import static org.hamcrest.Matchers.notNullValue;
import static org.junit.Assert.assertThrows;
import static org.junit.Assert.fail;
public class AuthorClientTest extends AbstractClientTest {
// Instance Variables ----------------------------------------------------
private final AnthologyClient anthologyClient = new AnthologyClient();
private final AuthorClient authorClient = new AuthorClient();
private final BookClient bookClient = new BookClient();
private final SeriesClient seriesClient = new SeriesClient();
// Lifecycle Methods -----------------------------------------------------
@Before
public void before() {
if ((depopulateEnabled == null) || (TRUE == depopulateEnabled)) {
depopulate();
}
if ((populateEnabled == null) || (TRUE == populateEnabled)) {
populate();
}
}
// Test Methods ----------------------------------------------------------
// delete() tests
@Test
public void deleteHappy() throws Exception {
if (disabled()) {
return;
}
List<Author> authors = authorClient.findAll();
assertThat(authors.size(), is(greaterThan(0)));
for (Author author : authors) {
/* (Not true for actual test data)
// Test data should not have any authors with no anthologies
List<Anthology> anthologies = findAnthologiesByAuthorId(author.getId());
assertThat(anthologies.size(), greaterThan(0));
*/
/* (Not true for actual test data)
// Test data should not have any authors with no books
List<Book> books = findBooksByAuthorId(author.getId());
assertThat(books.size(), greaterThan(0));
*/
/* (Not true for actual test data)
// Test data should not have any authors with no series
List<Series> series = findSeriesByAuthorId(author.getId());
assertThat(series.size(), greaterThan(0));
*/
// Delete and verify we can no longer retrieve it
authorClient.delete(author.getId());
assertThrows(NotFound.class,
() -> authorClient.find(author.getId()));
// Delete should have cascaded to anthologies/books/series
assertThat(findAnthologiesByAuthorId(author.getId()).size(), is(0));
assertThat(findBooksByAuthorId(author.getId()).size(), is(0));
assertThat(findSeriesByAuthorId(author.getId()).size(), is(0));
}
// We should have deleted all authors
assertThat(authorClient.findAll().size(), is(0));
}
@Test
public void deleteNotFound() throws Exception {
if (disabled()) {
return;
}
assertThrows(NotFound.class,
() -> authorClient.delete(Long.MAX_VALUE));
}
// find() tests
@Test
public void findHappy() throws Exception {
List<Author> authors = authorClient.findAll();
for (Author author : authors) {
Author found = authorClient.find(author.getId());
assertThat(found.equals(author), is(true));
}
}
@Test
public void findNotFound() throws Exception {
assertThrows(NotFound.class,
() -> authorClient.find(Long.MAX_VALUE));
}
// findAll() tests
@Test
public void findAllHappy() throws Exception {
List<Author> authors = authorClient.findAll();
assertThat(authors, is(notNullValue()));
assertThat(authors.size(), is(greaterThan(0)));
String previousName = null;
for (Author author : authors) {
String thisName = author.getLastName() + "|" + author.getFirstName();
if (previousName != null) {
assertThat(thisName, is(greaterThan(previousName)));
}
previousName = thisName;
}
}
// insert() tests
@Test
public void insertHappy() throws Exception {
if (disabled()) {
return;
}
Author author = newAuthor();
Author inserted = authorClient.insert(author);
assertThat(inserted.getId(), is(notNullValue()));
assertThat(inserted.getVersion(), is(0));
try {
Author found = authorClient.find(inserted.getId());
assertThat(found.equals(inserted), is(true));
} catch (Exception e) {
fail("Should not have thrown an exception: " + e.getMessage());
}
}
@Test
public void insertBadRequest() throws Exception {
if (disabled()) {
return;
}
// Completely empty instance
final Author author0 = new Author();
assertThrows(BadRequest.class,
() -> authorClient.insert(author0));
// Missing firstName field
final Author author1 = newAuthor();
author1.setFirstName(null);
assertThrows(BadRequest.class,
() -> authorClient.insert(author1));
// Missing lastName field
final Author author2 = newAuthor();
author2.setLastName(null);
assertThrows(BadRequest.class,
() -> authorClient.insert(author2));
}
@Test
public void insertNotUnique() throws Exception {
if (disabled()) {
return;
}
Author author = new Author("Barney", "Rubble", "New Notes about Barney");
author.setId(null);
assertThrows(NotUnique.class,
() -> authorClient.insert(author));
}
// update() tests --------------------------------------------------------
@Test
public void updateHappy() throws Exception {
if (disabled()) {
return;
}
// Get original entity
Author original = findFirstAuthorByName("Pebbles");
// Update this entity
Author author = original.clone();
try {
Thread.sleep(100);
} catch (InterruptedException e) {
/* Ignore */;
}
author.setFirstName(author.getFirstName() + " Updated");
Author updated = authorClient.update(author.getId(), author);
// Validate this entity
assertThat(updated.getId(), is(author.getId()));
assertThat(updated.getPublished(), is(author.getPublished()));
assertThat(updated.getUpdated(), is(greaterThan(original.getUpdated())));
assertThat(updated.getVersion(), is(greaterThan(original.getVersion())));
assertThat(updated.getFirstName(), is(original.getFirstName() + " Updated"));
assertThat(updated.getLastName(), is(original.getLastName()));
}
@Test
public void updateBadRequest() throws Exception {
if (disabled()) {
return;
}
// Get original entity
Author original = findFirstAuthorByName("Rubble");
try {
Thread.sleep(100);
} catch (InterruptedException e) {
/* Ignore */;
}
// Missing firstName field
final Author author1 = original.clone();
author1.setFirstName(null);
assertThrows(BadRequest.class,
() -> authorClient.update(author1.getId(), author1));
// Missing lastName field
final Author author2 = original.clone();
author2.setLastName(null);
assertThrows(BadRequest.class,
() -> authorClient.update(author2.getId(), author2));
}
@Test
public void updateNotUnique() throws Exception {
if (disabled()) {
return;
}
Author author = findFirstAuthorByName("Flintstone");
author.setFirstName("Barney");
author.setLastName("Rubble");
assertThrows(NotUnique.class,
() -> authorClient.update(author.getId(), author));
}
// Private Methods -------------------------------------------------------
private List<Anthology> findAnthologiesByAuthorId(Long authorId) throws Exception {
List<Anthology> in = anthologyClient.findAll();
List<Anthology> out = new ArrayList<>();
for (Anthology check : in) {
if (authorId.equals(check.getAuthorId())) {
out.add(check);
}
}
return out;
}
private Author findFirstAuthorByName(String name) throws Exception {
List<Author> authors = authorClient.findByName(name);
assertThat(authors.size(), is(greaterThan(0)));
return authors.get(0);
}
private List<Book> findBooksByAuthorId(Long authorId) throws Exception {
List<Book> in = bookClient.findAll();
List<Book> out = new ArrayList<>();
for (Book check : in) {
if (authorId.equals(check.getAuthorId())) {
out.add(check);
}
}
return out;
}
private List<Series> findSeriesByAuthorId(Long authorId) throws Exception {
List<Series> in = seriesClient.findAll();
List<Series> out = new ArrayList<>();
for (Series check : in) {
if (authorId.equals(check.getAuthorId())) {
out.add(check);
}
}
return out;
}
private Author newAuthor() throws Exception {
List<Author> authors = authorClient.findAll();
assertThat(authors.size(), is(greaterThan(0)));
return new Author(
"Another",
"Rubble",
"Notes about Another Rubble");
}
}
| true |
0f10acbae141b9364eb2faa79b18e53dc271f36b | Java | buruqinshouburu/Login | /src/com/itheima/web/Servlet/LoginServlet.java | UTF-8 | 2,419 | 2.453125 | 2 | [] | no_license | package com.itheima.web.Servlet;
import com.itheima.domain.User;
import com.itheima.dao.UserDao;
import org.apache.commons.beanutils.BeanUtils;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.lang.reflect.InvocationTargetException;
import java.util.Map;
@WebServlet( "/loginCheck")
public class LoginServlet extends HttpServlet {
@Override
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws IOException {
request.setCharacterEncoding("utf-8");
/* String username=request.getParameter("username");
String password=request.getParameter("password");*/
User user=new User();
/*user.setUsername(username);
user.setPassword(password);*/
UserDao dao=new UserDao();
Map<String, String[]> parameterMap = request.getParameterMap();
try {
BeanUtils.populate(user,parameterMap);
} catch (IllegalAccessException e) {
e.printStackTrace();
} catch (InvocationTargetException e) {
e.printStackTrace();
}
User userCheck= dao.login(user);
if(userCheck!=null){
/* response.setContentType("text/html;charset=utf-8");
response.getWriter().write("登录成功!用户名,欢迎您");*/
request.setAttribute("user",user);
try {
request.getRequestDispatcher("successServlet").forward(request,response);
} catch (ServletException e) {
e.printStackTrace();
}
}else {
/* response.setContentType("text/html;charset=utf-8");
response.getWriter().write("登录失败,用户名或密码错误");*/
try {
request.getRequestDispatcher("failServle").forward(request,response);
} catch (ServletException e) {
e.printStackTrace();
}
}
/* System.out.println(username);
System.out.println(password);
System.out.println(user);*/
}
@Override
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
this.doPost(request,response);
}
}
| true |
14483ddb5a2e00df99390586087e53671fb0e7e8 | Java | jason790/SmartDosing | /SmartDosingKhanV1/Smart_Dispenser/src/com/example/smart_dispenser/Nurse.java | UTF-8 | 1,869 | 2.15625 | 2 | [] | no_license | package com.example.smart_dispenser;
import com.vaadin.addon.touchkit.ui.NavigationView;
import com.vaadin.data.Container;
import com.vaadin.event.ItemClickEvent;
import com.vaadin.event.ItemClickEvent.ItemClickListener;
import com.vaadin.ui.Button;
import com.vaadin.ui.Button.ClickEvent;
import com.vaadin.ui.Button.ClickListener;
import com.vaadin.ui.CssLayout;
import com.vaadin.ui.Table;
import data.dbhelper;
public class Nurse extends NavigationView {
Shiftshow sv= new Shiftshow();
dbhelper medicinetable= new dbhelper();
Table table = new Table();
Button shift= new Button("Shift");
Container container = medicinetable.getNursetable();
dbhelper patienttable= new dbhelper();
public void attach()
{
super.attach();
setCaption("Nurses");
buildview();
}
private void buildview() {
// TODO Auto-generated method stub
CssLayout cd= new CssLayout();
shift.setEnabled(false);
//table.setSizeFull();
table.setContainerDataSource(container);
table.setWidth("100%");
table.setColumnHeader("NurseSSN", "Nurse SSN");
table.setColumnHeader("FirstName", "First Name");
table.setColumnHeader("LastName", "Last Name");
table.setSelectable(true);
table.addListener(new ItemClickListener(){
public void itemClick(ItemClickEvent event) {
// TODO Auto-generated method stub
shift.setEnabled(true);
}});
shift.addListener(new ClickListener(){
public void buttonClick(ClickEvent event) {
// TODO Auto-generated method stub
Object id = table.getValue();
String ssn = (String)table.getContainerProperty(id,"NurseSSN").getValue();
sv.showtreatment(ssn);
sv.setWidth("80%");
sv.showRelativeTo(getNavigationBar());
}});
shift.setWidth("30%");
cd.addComponent(table);
cd.addComponent(shift);
cd.setSizeFull();
setContent(cd);
}
}
| true |
345105c983bcfc492361e0c9b6a8f0b49691d3dd | Java | AncientMariner/jax | /src/main/java/jaxb/validation/Validation.java | UTF-8 | 1,587 | 2.4375 | 2 | [
"MIT"
] | permissive | package jaxb.validation;
import org.xml.sax.SAXException;
import javax.xml.XMLConstants;
import javax.xml.transform.Source;
import javax.xml.transform.stream.StreamSource;
import javax.xml.validation.Schema;
import javax.xml.validation.SchemaFactory;
import javax.xml.validation.Validator;
import java.io.File;
import java.io.IOException;
import java.net.MalformedURLException;
import java.net.URL;
public class Validation {
public static void main(String[] args) {
URL schemaFile = null;
try {
schemaFile = new URL("http://java.sun.com/xml/ns/j2ee/web-app_2_4.xsd");
} catch (MalformedURLException e) {
e.printStackTrace();
}
Source xmlFile = new StreamSource(new File("employee.xml"));
SchemaFactory schemaFactory = SchemaFactory
.newInstance(XMLConstants.W3C_XML_SCHEMA_NS_URI);
Schema schema = null;
try {
schema = schemaFactory.newSchema(schemaFile);
} catch (SAXException e) {
e.printStackTrace();
}
Validator validator = schema.newValidator();
try {
try {
validator.validate(xmlFile);
} catch (IOException e) {
e.printStackTrace();
}
System.out.println(xmlFile.getSystemId() + " is valid");
} catch (SAXException e) {
System.out.println(xmlFile.getSystemId() + " is NOT valid");
System.out.println("Reason: " + e.getLocalizedMessage());
}
}
}
| true |
70772fdc80f65afeea77897ed9a8ce9a42934e16 | Java | rupesh2053/employeemgmt | /src/java/com/servlet/ShowAllServlet.java | UTF-8 | 1,656 | 2.421875 | 2 | [] | no_license | package com.servlet;
import com.employee.EmployeeRecord;
import com.employee.dao.EmployeeDao;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.List;
import javax.servlet.*;
import javax.servlet.http.*;
public class ShowAllServlet extends HttpServlet {
protected void processRequest(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
response.setContentType("text/html");
PrintWriter out=response.getWriter();
out.println("<h1>Employees List</h1>");
EmployeeDao dao = new EmployeeDao();
List<EmployeeRecord> list = dao.getAllEmployees();
out.print("<table border='1' width='100%'");
out.print("<tr><th>Id</th><th>Name</th><th>Email</th><th>Address</th><th>Salary</th><th>Phone No.</th><th>Edit</th><th>Delete</th></tr>");
for(EmployeeRecord e :list){
out.print("<tr><td>"+ e.getEmpid()+"</td><td>"+e.getName()+"</td><td>"+e.getEmail()+"</td><td>"+e.getAddress()+"</td><td>"+e.getSalary()+"</td><td>"+e.getPhoneno()+"</td><td><a href='EditServlet?id="+e.getEmpid()+"'>edit</a></td><td><a href='DeleteServlet?id="+e.getEmpid()+"'>delete</a></td></tr>");
}
out.print("</table>");
out.close();
}
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
processRequest(request,response);
}
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
processRequest(request,response);
}
}
| true |
5cde73f778cfb2d3bba40293471c85eebb5ee7a5 | Java | jun-hyeji/jblog | /jblog/src/main/java/com/bitacademy/jblog/service/UsersService.java | UTF-8 | 357 | 1.789063 | 2 | [] | no_license | package com.bitacademy.jblog.service;
import com.bitacademy.jblog.vo.UserVo;
public interface UsersService {
public UserVo login(String id,String pw); //로그인
public boolean idCheck(String id); //id중복체크
public boolean userInsert(UserVo uvo); //회원가입
public Long selectUserNo(String id);
public String selectId(Long userNo);
}
| true |
dfa7f1620ebf596cd9daced9e92063a6f74ac250 | Java | KalhanVithana/Rest-api-backend | /Rest-api-Backend/User/src/main/java/com/user/User/Resource/UserResource.java | UTF-8 | 5,381 | 2.421875 | 2 | [] | no_license | package com.user.User.Resource;
import java.security.NoSuchAlgorithmException
;
import java.util.ArrayList;
import javax.annotation.security.RolesAllowed;
import javax.ws.rs.Consumes;
import javax.ws.rs.DELETE;
import javax.ws.rs.GET;
import javax.ws.rs.HeaderParam;
import javax.ws.rs.POST;
import javax.ws.rs.PUT;
import javax.ws.rs.Path;
import javax.ws.rs.PathParam;
import javax.ws.rs.Produces;
import javax.ws.rs.core.MediaType;
import javax.ws.rs.core.Response;
import com.user.User.Customer.model.Customer;
import com.user.User.Customer.repository.CustomerRepository;
import com.user.User.Repository.UserRepository;
import com.user.User.model.User;
import com.user.responsebean.CustomerResponse;
import com.user.services.JwtTokenSerives;
@Path("acc")
public class UserResource {
UserRepository repo = new UserRepository();
JwtTokenSerives tokenSerives=new JwtTokenSerives();
CustomerResponse res = new CustomerResponse();
CustomerRepository cus = new CustomerRepository();
@GET
@Produces({MediaType.APPLICATION_JSON,MediaType.APPLICATION_XML})
public ArrayList<User> getuser() {
return repo.getUsers();
}
@GET
@Path("get")
@Produces({MediaType.APPLICATION_JSON,MediaType.APPLICATION_XML})
public ArrayList<User> getuser2() {
return repo.getUsers();
}
@GET
@Path("a/{id}")
@Produces({MediaType.APPLICATION_JSON,MediaType.APPLICATION_XML})
public User getuser(@PathParam("id")int id) {
System.out.println("get one user called");
return repo.getOneUser(id);
}
@POST
@Path("regi")
@Consumes({MediaType.APPLICATION_JSON,MediaType.APPLICATION_XML})
public Response RegisterUser(User s1,@HeaderParam("Authcode")String token,@HeaderParam("uname")String name) {
System.out.println("insert called");
System.out.println(s1);
boolean isAuth = tokenSerives.verifyToken(token, name);
if(isAuth) {
repo.create(s1);
return Response.status(200).entity("Success").build();
}else {
return Response.status(401).entity("Not Aoth").build();
}
}
@PUT
@Path("update")
@Consumes({MediaType.APPLICATION_JSON,MediaType.APPLICATION_XML})
public User UpdateUser(User s1) {
System.out.println("update user called");
System.out.println(s1);
repo.Update(s1);
return s1;
}
@DELETE
@Path("delete/{id}")
public Response DeleteUser(@PathParam("id")int id,@HeaderParam("Authcode")String token,@HeaderParam("uname")String name) {
System.out.println("delete called");
System.out.println("sucessfully deleted");
boolean isAuth = tokenSerives.verifyToken(token, name);
if(isAuth) {
User a = repo.getOneUser(id);
if(a.getId()!= 0)
repo.Delete(id);
return Response.status(200).entity("Success").build();
}else {
return Response.status(401).entity("Not Aoth").build();
}
}
@POST
@Path("log")
@Produces({MediaType.APPLICATION_JSON})
public Response secureMethod(User s1) {
System.out.println("login sucss");
System.out.println("sucessfuly loged");
User data = repo.login(s1);
if(data!=null) {
String token;
try {
token = tokenSerives.issueToken(data.getName());
boolean found= tokenSerives.verifyToken(token,data.getName());
data.setToken(token);
System.out.println(found);
System.out.println(res.getName());
return Response.status(200).entity(data).build();
} catch (NoSuchAlgorithmException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
return Response.status(200).entity("User Not Found.!").build();
}
@GET
@Path("/Customers")
@Produces({MediaType.APPLICATION_JSON,MediaType.APPLICATION_XML})
public ArrayList<Customer> getallRegisteredCustomer(){
return cus.getAllCustomerRegisterd();
}
@GET
@Path("cus/{id}")
@Produces({MediaType.APPLICATION_JSON,MediaType.APPLICATION_XML})
public Response getuser3(@HeaderParam("Authcode")String token,@HeaderParam("name")String name,@PathParam("id")int id,User s1) {
boolean isAuth = tokenSerives.verifyToken(token, name);
if(isAuth) {
cus.CustomerProfile(id);
return Response.status(200).entity(cus.CustomerProfile(id)).build();
}else {
return Response.status(401).entity("Not Aoth").build();
}
}
@DELETE
@Path("de/{id}")
public Response DeleteUser1(@PathParam("id")int id,@HeaderParam("Authcode")String token,@HeaderParam("uname")String name) {
System.out.println("delete called");
System.out.println("sucessfully deleted");
boolean isAuth = tokenSerives.verifyToken(token, name);
if(isAuth) {
Customer a = cus.CustomerProfile(id);
if(a.getId()!= 0)
cus.Delete(id);
return Response.status(200).entity("Success").build();
}else {
return Response.status(401).entity("Not Aoth").build();
}
}
@DELETE
@Path("de/{id}")
public Response DeleteUserPayment(@PathParam("id")int id,@HeaderParam("Authcode")String token,@HeaderParam("uname")String name) {
System.out.println("delete called");
System.out.println("sucessfully deleted");
boolean isAuth = tokenSerives.verifyToken(token, name);
if(isAuth) {
Customer a = cus.CustomerProfile(id);
if(a.getId()!= 0)
cus.Delete(id);
return Response.status(200).entity("Success").build();
}else {
return Response.status(401).entity("Not Aoth").build();
}
}
}
| true |
9a1ef37e71a1dac296ba5fee05aa626044db8922 | Java | mtbdc-dy/zhongds01 | /sa_center/sacenter-parent/sacenter-receive/src/main/java/com/ai/sacenter/receive/teaminvoke/out/impl/UpdcFSVImpl.java | UTF-8 | 19,471 | 1.671875 | 2 | [] | no_license | package com.ai.sacenter.receive.teaminvoke.out.impl;
import java.rmi.RemoteException;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import com.ai.sacenter.IUpdcContext;
import com.ai.sacenter.SFException;
import com.ai.sacenter.center.SFCenterFactory;
import com.ai.sacenter.common.UpfsvcManager;
import com.ai.sacenter.i18n.ExceptionFactory;
import com.ai.sacenter.i18n.SFESFaultException;
import com.ai.sacenter.provision.IUpfwmFactory;
import com.ai.sacenter.provision.valuebean.IOVUpffmxOffer;
import com.ai.sacenter.provision.valuebean.IOVUpfwmOffer;
import com.ai.sacenter.provision.valuebean.IOVUpfwmResponse;
import com.ai.sacenter.receive.exigence.IExigenceFactory;
import com.ai.sacenter.receive.exigence.valuebean.IOVMsgFExigence;
import com.ai.sacenter.receive.exigence.valuebean.IOVMocketExigence;
import com.ai.sacenter.receive.exigence.valuebean.IOVMocketRespone;
import com.ai.sacenter.receive.order.IOrderFactory;
import com.ai.sacenter.receive.order.valuebean.IOVRocketExigence;
import com.ai.sacenter.receive.teaminvoke.out.interfaces.IUpdcFSV;
import com.ai.sacenter.receive.teaminvoke.valuebean.RocketFMessage;
import com.ai.sacenter.receive.teaminvoke.valuebean.RocketFRsRspMessage;
import com.ai.sacenter.receive.util.ExigenceUtils;
import com.ai.sacenter.receive.util.OrderUtils;
import com.ai.sacenter.receive.valuebean.IOVMsgFResponse;
import com.ai.sacenter.teaminvoke.UpdcFactory;
import com.ai.sacenter.util.UpfwmUtils;
/**
* <p>Title: ucmframe</p>
* <p>Description: </p>
* <p>Copyright: Copyright (c) 2011-10-14</p>
* <p>Company: AI(NanJing)</p>
* @author maohuiyun
* @version 2.0
*
*/
public class UpdcFSVImpl implements IUpdcFSV {
protected final static Log log = LogFactory.getLog( UpdcFSVImpl.class );
public UpdcFSVImpl() {
super();
}
/* (non-Javadoc)
* @see com.ai.sacenter.receive.teaminvoke.out.interfaces.IUpdcFSV#rocketReceiveAsyn(com.ai.sacenter.receive.teaminvoke.valuebean.RocketFMessage, com.ai.sacenter.SFException)
*/
public void rocketReceiveAsyn(RocketFMessage fromRocket, SFException aEXCEPTION) throws SFException, Exception {
try
{
IOVRocketExigence _rocket = OrderUtils.IRocket._jj_rocket(fromRocket, aEXCEPTION);
SFCenterFactory.pushCenterInfo( _rocket.getREGION_ID() );
UpfsvcManager.getMBean().beginTransaction();
try
{
IOrderFactory.getIOrderSV().orderReceiveAsyn( new IOVRocketExigence[]{_rocket}, aEXCEPTION );
UpfsvcManager.getMBean().commitTransaction();
}
catch( java.lang.Exception exception ){
UpfsvcManager.getMBean().rollbackTransaction();
throw exception;
}
finally{
SFCenterFactory.popCenterInfo();
}
}
finally{
}
}
/* (non-Javadoc)
* @see com.ai.sacenter.receive.teaminvoke.out.interfaces.IUpdcFSV#rocketCompleteAsyn(com.ai.sacenter.receive.teaminvoke.valuebean.RocketFMessage, com.ai.sacenter.SFException)
*/
public void rocketCompleteAsyn(RocketFMessage fromRocket, SFException aEXCEPTION) throws SFException, Exception {
try
{
IOVRocketExigence _rocket = OrderUtils.IRocket._jj_rocket(fromRocket, aEXCEPTION);
SFCenterFactory.pushCenterInfo( _rocket.getREGION_ID() );
UpfsvcManager.getMBean().beginTransaction();
try
{
IOrderFactory.getIOrderSV().orderCompleteAsyn( new IOVRocketExigence[]{_rocket}, aEXCEPTION );
UpfsvcManager.getMBean().commitTransaction();
}
catch( java.lang.Exception exception ){
UpfsvcManager.getMBean().rollbackTransaction();
throw exception;
}
finally{
SFCenterFactory.popCenterInfo();
}
}
finally{
}
}
/* (non-Javadoc)
* @see com.ai.sacenter.receive.teaminvoke.out.interfaces.IUpdcFSV#orderTransparent(com.ai.sacenter.provision.valuebean.IOVUpfwmOffer, com.ai.sacenter.provision.valuebean.IOVUpffmxOffer, com.ai.sacenter.IUpdcContext)
*/
public IOVMsgFResponse orderTransparent(IOVUpfwmOffer fromUpfwm,
IOVUpffmxOffer fromOffer,
IUpdcContext aContext) throws RemoteException, Exception {
IOVMsgFResponse fromASK = null;
UpfsvcManager.getMBean().beginTransaction();
try
{
IOVUpfwmResponse fromNetWork = null;
UpfwmUtils.ICustom._wrap( fromUpfwm, fromOffer, aContext );
fromNetWork = IUpfwmFactory.getIUpfwmSV().finishSFUpfwmSync(fromUpfwm, aContext);
fromASK = OrderUtils.IRocket._jj_response(fromUpfwm, fromNetWork);
UpfsvcManager.getMBean().commitTransaction();
}
catch( java.lang.Exception exception ){
UpfsvcManager.getMBean().rollbackTransaction();
throw exception;
}
finally{
UpfsvcManager.finishMBean();
}
return fromASK;
}
/* (non-Javadoc)
* @see com.ai.sacenter.receive.teaminvoke.out.interfaces.IUpdcFSV#orderReceive(com.ai.sacenter.receive.teaminvoke.valuebean.RocketFMessage)
*/
public RocketFRsRspMessage orderReceive(RocketFMessage fromMetaMX) throws RemoteException, Exception {
RocketFRsRspMessage fromRsBody = null;
try
{
IOVRocketExigence _rocket = OrderUtils.IRocket._jj_rocket( fromMetaMX );
SFCenterFactory.pushCenterInfo( _rocket.getREGION_ID() );
UpfsvcManager.getMBean().beginTransaction();
try
{
IOVMsgFResponse _response = IOrderFactory.getIOrderSV().orderReceive( _rocket );
String _rspBody = OrderUtils.IRocket._jj_response( _response );
fromRsBody = new RocketFRsRspMessage( _rocket, _rspBody );
UpfsvcManager.getMBean().commitTransaction();
}
catch( java.lang.Exception exception ){
UpfsvcManager.getMBean().rollbackTransaction();
SFException aEXCEPTION = ExceptionFactory.getServiceFault( exception );
throw aEXCEPTION;
}
finally{
SFCenterFactory.popCenterInfo();
}
}
catch( SFESFaultException exception ){
java.lang.Exception _exception = ExceptionFactory.getPrimitive( exception );
throw _exception;
}
catch( java.lang.Exception exception ){
try{
SFException aEXCEPTION = ExceptionFactory.getException( exception );
rocketCompleteAsyn(fromMetaMX, aEXCEPTION);
}
catch( java.lang.Exception _exception ){
log.error( _exception.getMessage(), _exception );
}
throw exception;
}
finally{
UpfsvcManager.finishMBean();
}
return fromRsBody;
}
/* (non-Javadoc)
* @see com.ai.sacenter.receive.teaminvoke.out.interfaces.IUpdcFSV#orderReceiveAsyn(com.ai.sacenter.receive.teaminvoke.valuebean.RocketFMessage)
*/
public void orderReceiveAsyn(RocketFMessage fromRocket) throws RemoteException, Exception {
try
{
IOVRocketExigence _rocket = OrderUtils.IRocket._jj_rocket( fromRocket );
SFCenterFactory.pushCenterInfo( _rocket.getREGION_ID() );
UpfsvcManager.getMBean().beginTransaction();
try
{
IOrderFactory.getIOrderSV().orderReceiveAsyn( new IOVRocketExigence[]{ _rocket } );
UpfsvcManager.getMBean().commitTransaction();
}
catch( java.lang.Exception exception ){
log.error( exception.getMessage(), exception );
UpfsvcManager.getMBean().rollbackTransaction();
throw exception;
}
finally{
SFCenterFactory.popCenterInfo();
}
}
catch( java.lang.Exception exception ){
log.error( exception.getMessage(), exception );
SFException aEXCEPTION = ExceptionFactory.getException( exception );
rocketReceiveAsyn(fromRocket, aEXCEPTION);
}
finally{
UpfsvcManager.finishMBean();
}
}
/* (non-Javadoc)
* @see com.ai.sacenter.receive.teaminvoke.out.interfaces.IUpdcFSV#rocketTransparent(com.ai.sacenter.provision.valuebean.IOVUpfwmOffer, com.ai.sacenter.provision.valuebean.IOVUpffmxOffer, com.ai.sacenter.IUpdcContext)
*/
public IOVMocketRespone rocketTransparent(IOVUpfwmOffer fromUpfwm, IOVUpffmxOffer fromOffer, IUpdcContext aContext) throws RemoteException, Exception {
IOVMocketRespone fromRsRsp = null;
UpfsvcManager.getMBean().beginTransaction();
try
{
IOVUpfwmResponse fromNetWork = null;
UpfwmUtils.ICustom._wrap( fromUpfwm, fromOffer, aContext );
fromNetWork = IUpfwmFactory.getIUpfwmSV().finishSFUpfwmSync(fromUpfwm, aContext);
fromRsRsp = ExigenceUtils.IRocket._jj_response(fromUpfwm, fromNetWork);
UpfsvcManager.getMBean().commitTransaction();
}
catch( java.lang.Exception exception ){
UpfsvcManager.getMBean().rollbackTransaction();
throw exception;
}
finally{
UpfsvcManager.finishMBean();
}
return fromRsRsp;
}
/* (non-Javadoc)
* @see com.ai.sacenter.receive.teaminvoke.out.interfaces.IUpdcFSV#rocketReceive(com.ai.sacenter.receive.teaminvoke.valuebean.RocketFMessage)
*/
public RocketFRsRspMessage rocketReceive(RocketFMessage fromRocket) throws RemoteException, Exception {
RocketFRsRspMessage fromRsBody = null;
try
{
IOVMsgFExigence _rocket = ExigenceUtils.IRocket._jj_rocket( fromRocket );
SFCenterFactory.pushCenterInfo( _rocket.getORDER().getROCKET().getREGION_ID() );
UpfsvcManager.getMBean().beginTransaction();
try
{
IOVMocketRespone _response = IExigenceFactory.getIUpdcSV().rocketReceive( _rocket );
String _rspBody = ExigenceUtils.IRocket._jj_response( _response );
fromRsBody = new RocketFRsRspMessage( _rocket, _rspBody );
UpfsvcManager.getMBean().commitTransaction();
}
catch( java.lang.Exception exception ){
UpfsvcManager.getMBean().rollbackTransaction();
SFException aEXCEPTION = ExceptionFactory.getServiceFault( exception );
throw aEXCEPTION;
}
finally{
SFCenterFactory.popCenterInfo();
}
}
catch( SFESFaultException exception ){
java.lang.Exception _exception = ExceptionFactory.getPrimitive( exception );
throw _exception;
}
catch( java.lang.Exception exception ){
try{
SFException aEXCEPTION = ExceptionFactory.getException( exception );
rocketCompleteAsyn(fromRocket, aEXCEPTION);
}
catch( java.lang.Exception _exception ){
log.error( _exception.getMessage(), _exception );
}
throw exception;
}
finally{
UpfsvcManager.finishMBean();
}
return fromRsBody;
}
/* (non-Javadoc)
* @see com.ai.sacenter.receive.teaminvoke.out.interfaces.IUpdcFSV#rocketReceiveAsyn(com.ai.sacenter.receive.teaminvoke.valuebean.RocketFMessage)
*/
public void rocketReceiveAsyn(RocketFMessage fromRocket) throws RemoteException, Exception {
try
{
IOVMsgFExigence _rocket = ExigenceUtils.IRocket._jj_rocket( fromRocket );
SFCenterFactory.pushCenterInfo( _rocket.getORDER().getROCKET().getREGION_ID() );
UpfsvcManager.getMBean().beginTransaction();
try
{
IExigenceFactory.getIUpdcSV().rocketReceiveAsyn( new IOVMsgFExigence[]{ _rocket });
UpfsvcManager.getMBean().commitTransaction();
}
catch( java.lang.Exception exception ){
log.error( exception.getMessage(), exception );
UpfsvcManager.getMBean().rollbackTransaction();
throw exception;
}
finally{
SFCenterFactory.popCenterInfo();
}
}
catch( java.lang.Exception exception ){
log.error( exception.getMessage(), exception );
SFException aEXCEPTION = ExceptionFactory.getException( exception );
rocketReceiveAsyn(fromRocket, aEXCEPTION);
}
finally{
UpfsvcManager.finishMBean();
}
}
/* (non-Javadoc)
* @see com.ai.sacenter.receive.teaminvoke.out.interfaces.IUpdcFSV#rocketCompleteAsyn(com.ai.sacenter.receive.teaminvoke.valuebean.RocketFMessage)
*/
public RocketFRsRspMessage rocketCompleteAsyn(RocketFMessage fromRocket) throws RemoteException, Exception {
RocketFRsRspMessage fromRsBody = null;
try
{
IOVMocketRespone _rocket = ExigenceUtils.IRocket._jj_complete( fromRocket );
SFCenterFactory.pushCenterInfo( _rocket.getORDER().getROCKET().getREGION_ID() );
UpfsvcManager.getMBean().beginTransaction();
try
{
IOVMocketRespone _response = IExigenceFactory.getIUpdcSV().rocketComplete( _rocket );
String _rspBody = ExigenceUtils.IRocket._jj_response( _response );
fromRsBody = new RocketFRsRspMessage( _rocket, _rspBody );
UpfsvcManager.getMBean().commitTransaction();
}
catch( java.lang.Exception exception ){
UpfsvcManager.getMBean().rollbackTransaction();
SFException aEXCEPTION = ExceptionFactory.getServiceFault( exception );
throw aEXCEPTION;
}
finally{
SFCenterFactory.popCenterInfo();
}
}
catch( SFESFaultException exception ){
java.lang.Exception _exception = ExceptionFactory.getPrimitive( exception );
throw _exception;
}
catch( java.lang.Exception exception ){
try{
SFException aEXCEPTION = ExceptionFactory.getException( exception );
rocketCompleteAsyn(fromRocket, aEXCEPTION);
}
catch( java.lang.Exception _exception ){
log.error( _exception.getMessage(), _exception );
}
throw exception;
}
finally{
UpfsvcManager.finishMBean();
}
return fromRsBody;
}
/* (non-Javadoc)
* @see com.ai.sacenter.receive.teaminvoke.out.interfaces.IUpdcFSV#rabbitReceiveAsyn(com.ai.sacenter.receive.teaminvoke.valuebean.RocketFMessage)
*/
public void rabbitReceiveAsyn(RocketFMessage fromRocket) throws RemoteException, Exception {
try
{
IOVMocketExigence _rocket = ExigenceUtils.IRocket._jj_mocket( fromRocket );
SFCenterFactory.pushCenterInfo( _rocket.getREGION_ID() );
UpfsvcManager.getMBean().beginTransaction();
try
{
IExigenceFactory.getIUpdcSV().rabbitReceiveAsyn( new IOVMocketExigence[]{ _rocket } );
UpfsvcManager.getMBean().commitTransaction();
}
catch( java.lang.Exception exception ){
UpfsvcManager.getMBean().rollbackTransaction();
SFException aEXCEPTION = ExceptionFactory.getServiceFault( exception );
throw aEXCEPTION;
}
finally{
SFCenterFactory.popCenterInfo();
}
}
catch( SFESFaultException exception ){
java.lang.Exception _exception = ExceptionFactory.getPrimitive( exception );
throw _exception;
}
catch( java.lang.Exception exception ){
try{
SFException aEXCEPTION = ExceptionFactory.getException( exception );
rocketCompleteAsyn(fromRocket, aEXCEPTION);
}
catch( java.lang.Exception _exception ){
log.error( _exception.getMessage(), _exception );
}
throw exception;
}
finally{
UpfsvcManager.finishMBean();
}
}
/* (non-Javadoc)
* @see com.ai.sacenter.receive.teaminvoke.out.interfaces.IUpdcFSV#orderTurnRedo(java.lang.String, long, java.lang.String, java.lang.String)
*/
public void orderTurnRedo(String aVM_ORDER_ID,
long aTASK_ID,
String aVM_ORG_ID,
String aVM_STAFF_ID) throws RemoteException, Exception {
java.util.HashMap fromASK = new java.util.HashMap();
UpfsvcManager.getMBean().beginTransaction();
try
{
UpdcFactory.getIUpdcSV().finishSFTaskRedo( new long[]{aTASK_ID},
aVM_ORG_ID,
aVM_STAFF_ID,
fromASK);
UpfsvcManager.getMBean().commitTransaction();
}
catch( java.lang.Exception aEXCEPTION ){
UpfsvcManager.getMBean().rollbackTransaction();
throw aEXCEPTION;
}
finally{
UpfsvcManager.finishMBean();
if( fromASK != null ){ fromASK.clear(); fromASK = null; }
}
}
/* (non-Javadoc)
* @see com.ai.sacenter.receive.teaminvoke.out.interfaces.IUpdcFSV#orderComplete(java.lang.String, long, java.lang.String, java.lang.String, java.lang.String)
*/
public void orderComplete(String aVM_ORDER_ID,
long aTASK_ID,
String aVM_REASON,
String aVM_ORG_ID,
String aVM_STAFF_ID) throws RemoteException, Exception {
java.util.HashMap fromASK = new java.util.HashMap();
UpfsvcManager.getMBean().beginTransaction();
try
{
UpdcFactory.getIUpdcSV().finishSFTaskComplete( new long[]{aTASK_ID},
aVM_REASON,
aVM_ORG_ID,
aVM_STAFF_ID,
fromASK);
UpfsvcManager.getMBean().commitTransaction();
}
catch( java.lang.Exception aEXCEPTION ){
UpfsvcManager.getMBean().rollbackTransaction();
throw aEXCEPTION;
}
finally{
UpfsvcManager.finishMBean();
if( fromASK != null ){ fromASK.clear(); fromASK = null; }
}
}
/* (non-Javadoc)
* @see com.ai.sacenter.receive.teaminvoke.out.interfaces.IUpdcFSV#orderException(java.lang.String, long, java.lang.String, java.lang.String, java.lang.String)
*/
public void orderException(String aVM_ORDER_ID,
long aTASK_ID,
String aVM_REASON,
String aVM_ORG_ID,
String aVM_STAFF_ID) throws RemoteException, Exception {
java.util.HashMap fromASK = new java.util.HashMap();
UpfsvcManager.getMBean().beginTransaction();
try
{
UpdcFactory.getIUpdcSV().finishSFTaskException( new long[]{aTASK_ID},
aVM_REASON,
aVM_ORG_ID,
aVM_STAFF_ID,
fromASK);
UpfsvcManager.getMBean().commitTransaction();
}
catch( java.lang.Exception aEXCEPTION ){
UpfsvcManager.getMBean().rollbackTransaction();
throw aEXCEPTION;
}
finally{
UpfsvcManager.finishMBean();
if( fromASK != null ){ fromASK.clear(); fromASK = null; }
}
}
/* (non-Javadoc)
* @see com.ai.sacenter.receive.teaminvoke.out.interfaces.IUpdcFSV#suspendSFOrder(java.lang.String, java.lang.String, java.lang.String, java.lang.String)
*/
public void suspendSFOrder(String aVM_ORDER_ID,
String aBILL_ID,
String aVM_REASON,
String aADDIN_XML) throws RemoteException, Exception {
UpfsvcManager.getMBean().beginTransaction();
try
{
UpdcFactory.getIUpdcSV().suspendSFOrder(aVM_ORDER_ID,
aBILL_ID,
aVM_REASON,
aADDIN_XML);
UpfsvcManager.getMBean().commitTransaction();
}
catch( java.lang.Exception aEXCEPTION ){
UpfsvcManager.getMBean().rollbackTransaction();
throw aEXCEPTION;
}
finally{
UpfsvcManager.finishMBean();
}
}
/* (non-Javadoc)
* @see com.ai.sacenter.receive.teaminvoke.out.interfaces.IUpdcFSV#resumeSFOrder(java.lang.String, java.lang.String, java.lang.String, java.lang.String)
*/
public void resumeSFOrder(String aVM_ORDER_ID, String aBILL_ID, String aVM_REASON, String aADDIN_XML) throws RemoteException, Exception {
UpfsvcManager.getMBean().beginTransaction();
try
{
UpdcFactory.getIUpdcSV().resumeSFOrder(aVM_ORDER_ID,
aBILL_ID,
aVM_REASON,
aADDIN_XML);
UpfsvcManager.getMBean().commitTransaction();
}
catch( java.lang.Exception aEXCEPTION ){
UpfsvcManager.getMBean().rollbackTransaction();
throw aEXCEPTION;
}
finally{
UpfsvcManager.finishMBean();
}
}
/* (non-Javadoc)
* @see com.ai.sacenter.receive.teaminvoke.out.interfaces.IUpdcFSV#cancelSFOrder(java.lang.String, java.lang.String, java.lang.String, java.lang.String)
*/
public void cancelSFOrder(String aVM_ORDER_ID,
String aBILL_ID,
String aVM_REASON,
String aADDIN_XML) throws RemoteException, Exception {
UpfsvcManager.getMBean().beginTransaction();
try
{
UpdcFactory.getIUpdcSV().cancelSFOrder(aVM_ORDER_ID,
aBILL_ID,
aVM_REASON,
aADDIN_XML);
UpfsvcManager.getMBean().commitTransaction();
}
catch( java.lang.Exception aEXCEPTION ){
UpfsvcManager.getMBean().rollbackTransaction();
throw aEXCEPTION;
}
finally{
UpfsvcManager.finishMBean();
}
}
/* (non-Javadoc)
* @see com.ai.sacenter.receive.teaminvoke.out.interfaces.IUpdcFSV#getASKOrder(long, java.lang.String, java.lang.String)
*/
public java.util.HashMap getASKOrder(long aVM_ORDER_ID,
String aBILL_ID,
String aADDIN_XML) throws RemoteException, Exception {
java.util.HashMap fromASK = null;
UpfsvcManager.getMBean().beginTransaction();
try
{
fromASK = UpdcFactory.getIUpdcSV().getASKOrder(aVM_ORDER_ID,
aBILL_ID,
aADDIN_XML);
UpfsvcManager.getMBean().commitTransaction();
}
catch( java.lang.Exception aEXCEPTION ){
UpfsvcManager.getMBean().rollbackTransaction();
throw aEXCEPTION;
}
finally{
UpfsvcManager.finishMBean();
}
return fromASK;
}
} | true |
8e21da7e0a111cc3cb2dd75a5bcf44e593fbd8de | Java | kamochu/sds | /sds_message_processor/src/com/sds/core/conf/TextConfigs.java | UTF-8 | 970 | 2.015625 | 2 | [] | no_license | package com.sds.core.conf;
/**
*
* @author Samuel Kamochu
*/
public class TextConfigs {
/**
* General technical failure text to be
*/
public final static String GEN_TECHNICAL_FAILURE_TEXT = "Dear customer. We are unable to process your request at the moment. Please try again later. Thank you.";
/**
* Subscription requests processing messages
*/
public final static String SUBSCRIPTION_TECHNICAL_ERROR = "Dear customer, we have received your request and your profile will be updated accordingly.";
/**
* Matcher SMS
*/
public final static String MATCHER_SDP_STATUS_INACTIVE_TEXT = "Dear customer. To starting enjoying discovery dtaing services, please send REGISTER to 60010.";
public final static String MATCHER_REGISTRATION_PENDING_TEXT = "Dear customer. To starting enjoying discovery dtaing services, we need to know what you are looking for. Reply with 1. for Partner 2. for Friend 3. for Sex. E.g. 2";
}
| true |
d0be80dbd50e9bd5020abab8edc969600830a5e0 | Java | benNek/AsgardAscension | /src/com/nekrosius/asgardascension/utils/TribeUtils.java | UTF-8 | 1,262 | 3 | 3 | [
"MIT"
] | permissive | package com.nekrosius.asgardascension.utils;
import java.util.ArrayList;
import java.util.List;
import org.bukkit.Location;
import org.bukkit.entity.Entity;
import org.bukkit.entity.Player;
public class TribeUtils {
public TribeUtils() {
// It's empty because why not?
}
public Location getCenterLocation(Location loc1, Location loc2){
Location loc = new Location(loc1.getWorld(), 0, 0, 0);
double x = (loc1.getX() + loc2.getX()) / 2;
double z = (loc1.getZ() + loc2.getZ()) / 2;
loc.setX(x);
loc.setY(loc1.getY());
loc.setZ(z);
return loc;
}
public List<Player> getNearbyPlayers(Location loc, double radius){
List<Player> players = new ArrayList<>();
for(Entity e : loc.getWorld().getEntities()){
if(e instanceof Player && loc.distance(e.getLocation()) <= radius){
players.add((Player)e);
}
}
return players;
}
public double getSmashDamageByTribeLevel(int level) {
switch(level) {
case 1:
return 3;
case 2:
return 4;
case 3:
return 6;
case 4:
return 7;
default:
return 0;
}
}
public double getFireballDamageByTribeLevel(int level, boolean direct) {
if(direct){
return 10;
}
else{
if(level == 1 || level == 2)
return 4;
else
return 6;
}
}
}
| true |
462bb4206b636b8edb36d1210e43ea127a712a31 | Java | meet-007/spring-core-practice | /practice/src/main/java/com/spring/practice/SimpleFactory.java | UTF-8 | 506 | 2.796875 | 3 | [] | no_license | package com.spring.practice;
import org.springframework.context.annotation.Bean;
import org.springframework.stereotype.Component;
@Component
public class SimpleFactory {
@Bean(name = "lion")
Animal Lion() {
final Lion lion = new Lion();
lion.setSpeed(44);
lion.setType("4asdfasdf");
lion.setWeight(42);
return lion;
}
@Bean(name = "tiger")
Animal Tiger() {
final Tiger tiger = new Tiger();
tiger.setSpeed(44);
tiger.setType("4asdfasdf");
tiger.setWeight(42);
return tiger;
}
}
| true |
672b3ddcc76625c226451a688b98aed0a44e998e | Java | rexlNico/RexlTech | /src/main/java/de/rexlnico/rexltech/utils/init/SoundInit.java | UTF-8 | 1,066 | 2.234375 | 2 | [] | no_license | package de.rexlnico.rexltech.utils.init;
import de.rexlnico.rexltech.RexlTech;
import net.minecraft.util.ResourceLocation;
import net.minecraft.util.SoundEvent;
import net.minecraftforge.event.RegistryEvent;
import net.minecraftforge.eventbus.api.SubscribeEvent;
import net.minecraftforge.registries.IForgeRegistry;
public class SoundInit {
public static final SoundEvent JETPACK = new SoundEvent(new ResourceLocation(RexlTech.MODID + "jetpack"));
public static final SoundEvent CRUSHER = new SoundEvent(new ResourceLocation(RexlTech.MODID + "crusher"));
public static final SoundEvent COAL_GENERATOR = new SoundEvent(new ResourceLocation(RexlTech.MODID + "coal_generator"));
@SubscribeEvent
public void registerSounds(RegistryEvent.Register<SoundEvent> event) {
IForgeRegistry<SoundEvent> registry = event.getRegistry();
registry.register(JETPACK.setRegistryName("jetpack"));
registry.register(CRUSHER.setRegistryName("crusher"));
registry.register(COAL_GENERATOR.setRegistryName("coal_generator"));
}
}
| true |
bda7a1989e383fc4fde595745ccaa9e2855ee0dc | Java | mrtamm/sqlstore | /src/test/java/ws/rocket/sqlstore/connection/SharedConnectionManagerTest.java | UTF-8 | 2,564 | 2.09375 | 2 | [
"Apache-2.0"
] | permissive | /*
* Copyright 2014 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
*
* 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 ws.rocket.sqlstore.connection;
import static org.mockito.Mockito.mock;
import static org.testng.Assert.assertEquals;
import static org.testng.Assert.assertNotNull;
import static org.testng.Assert.assertNull;
import java.sql.Connection;
import javax.sql.DataSource;
import org.testng.annotations.Test;
/**
* Tests for {@link SharedConnectionManager} class.
*/
@Test
public class SharedConnectionManagerTest {
public void shouldReturnNullForInstance() {
assertNull(SharedConnectionManager.getInstance());
}
public void shouldReturnConnectionManagerInstance() {
assertNull(SharedConnectionManager.getInstance());
try {
SharedConnectionManager.register(mock(Connection.class));
assertNotNull(SharedConnectionManager.getInstance());
assertEquals(SharedConnectionManager.getInstance().getClass(), SingleConnectionManager.class);
} finally {
SharedConnectionManager.unregister();
assertNull(SharedConnectionManager.getInstance());
}
}
public void shouldReturnDataSourceManagerInstance() {
assertNull(SharedConnectionManager.getInstance());
try {
SharedConnectionManager.register(mock(DataSource.class));
assertNotNull(SharedConnectionManager.getInstance());
assertEquals(SharedConnectionManager.getInstance().getClass(),
DataSourceConnectionManager.class);
} finally {
SharedConnectionManager.unregister();
assertNull(SharedConnectionManager.getInstance());
}
}
@Test(expectedExceptions = NullPointerException.class)
public void shouldRegisterFailOnNoConnection() {
assertNull(SharedConnectionManager.getInstance());
SharedConnectionManager.register((Connection) null);
}
@Test(expectedExceptions = NullPointerException.class)
public void shouldRegisterFailOnNoDataSource() {
assertNull(SharedConnectionManager.getInstance());
SharedConnectionManager.register((DataSource) null);
}
}
| true |
de518eb505ad47989b0aa04a48d43972fe16485e | Java | minxc/iEMPv7 | /emp-platform/system/system-core/src/main/java/org/minxc/emp/syetem2/service/SystemDataSourceServiceImpl.java | UTF-8 | 1,157 | 2.125 | 2 | [
"Apache-2.0"
] | permissive | package org.minxc.emp.syetem2.service;
import org.minxc.emp.system.api2.model.SystemDataSource;
import org.minxc.emp.system.api2.service.SystemDataSourceService;
import org.minxc.emp.syetem2.manager.SystemDataSourceManager;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.stereotype.Service;
import javax.sql.DataSource;
/**
* <pre>
* 描述:系统数据源对其他模块的服务类
* 作者:min.xianchang
* 邮箱:xianchangmin@126.com
* 日期:2018年1月29日 上午10:42:46
* 版权:summer
* </pre>
*/
@Service
public class SystemDataSourceServiceImpl implements SystemDataSourceService {
@Autowired
SystemDataSourceManager sysDataSourceManager;
@Override
public SystemDataSource getByKey(String key) {
return sysDataSourceManager.getByKey(key);
}
@Override
public DataSource getDataSourceByKey(String key) {
return sysDataSourceManager.getDataSourceByKey(key);
}
@Override
public JdbcTemplate getJdbcTemplateByKey(String key) {
return sysDataSourceManager.getJdbcTemplateByKey(key);
}
}
| true |
0b92fc4f3dbe70a5c25bc2ea704ad1057e0b9957 | Java | openGDA/gda-core | /uk.ac.gda.client.live.stream/src/uk/ac/gda/client/live/stream/view/LiveStreamMenuContribution.java | UTF-8 | 7,595 | 1.859375 | 2 | [] | no_license | /*-
* Copyright © 2017 Diamond Light Source Ltd.
*
* This file is part of GDA.
*
* GDA is free software: you can redistribute it and/or modify it under the
* terms of the GNU General Public License version 3 as published by the Free
* Software Foundation.
*
* GDA is distributed in the hope that it will be useful, but WITHOUT ANY
* WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
* FOR A PARTICULAR PURPOSE. See the GNU General Public License for more
* details.
*
* You should have received a copy of the GNU General Public License along
* with GDA. If not, see <http://www.gnu.org/licenses/>.
*/
package uk.ac.gda.client.live.stream.view;
import static uk.ac.gda.client.live.stream.view.StreamViewUtility.getSecondaryId;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;
import java.util.TreeMap;
import org.apache.commons.lang.StringUtils;
import org.eclipse.core.expressions.Expression;
import org.eclipse.core.runtime.IConfigurationElement;
import org.eclipse.core.runtime.Platform;
import org.eclipse.jface.action.Action;
import org.eclipse.jface.action.MenuManager;
import org.eclipse.ui.IWorkbenchPage;
import org.eclipse.ui.PartInitException;
import org.eclipse.ui.PlatformUI;
import org.eclipse.ui.menus.ExtensionContributionFactory;
import org.eclipse.ui.menus.IContributionRoot;
import org.eclipse.ui.services.IServiceLocator;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import gda.factory.Finder;
import uk.ac.diamond.daq.epics.connector.EpicsV3DynamicDatasetConnector;
import uk.ac.diamond.daq.epics.connector.EpicsV4DynamicDatasetConnector;
/**
* This processes {@link CameraConfiguration}s in the client Spring and generates the menu items to allow them to be
* opened. If no {@link CameraConfiguration}s are found it does nothing.
*
* @author James Mudd
*/
public class LiveStreamMenuContribution extends ExtensionContributionFactory {
private static final Logger logger = LoggerFactory.getLogger(LiveStreamMenuContribution.class);
@Override
public void createContributionItems(IServiceLocator serviceLocator, IContributionRoot additions) {
logger.debug("Adding menu items for live streams...");
// Find all the implemented cameras. This is currently using the finder but could use OSGi instead.
final List<CameraConfiguration> cameras = Finder.listLocalFindablesOfType(CameraConfiguration.class);
final Map<String, CameraConfiguration> cameraMap = new HashMap<>();
for (CameraConfiguration camConfig : cameras) {
if (camConfig.getDisplayName() != null) {
cameraMap.put(camConfig.getDisplayName(), camConfig);
} else {
logger.warn("No display name was set for camera id: {}. Using id instead", camConfig.getName());
cameraMap.put(camConfig.getName(), camConfig);
}
}
if (cameraMap.isEmpty()) {
logger.debug("No camera configurations found");
return;
}
// We have some cameras
logger.debug("Found {} cameras", cameras.size());
// Build a map for each stream type
final Map<String, CameraConfiguration> mjpegCameras = new TreeMap<>();
final Map<String, CameraConfiguration> epicsCameras = new TreeMap<>();
final Map<String, CameraConfiguration> pvaCameras = new TreeMap<>();
for (Entry<String, CameraConfiguration> cam : cameraMap.entrySet()) {
// If a URL is set add to MJPEG map
if (cam.getValue().getUrl() != null) {
mjpegCameras.put(cam.getKey(), cam.getValue());
}
// If PV is set add to EPICS map
if (cam.getValue().getArrayPv() != null) {
epicsCameras.put(cam.getKey(), cam.getValue());
}
// If PVA PV is set add to PVA map
if (cam.getValue().getPvAccessPv() != null) {
pvaCameras.put(cam.getKey(), cam.getValue());
}
}
// Now need to build the menus, first MJPEG
if (!mjpegCameras.isEmpty()) {
final MenuManager mjpegMenu = new MenuManager("MJPEG Streams");
for (Entry<String, CameraConfiguration> cam : mjpegCameras.entrySet()) {
mjpegMenu.add(createMenuAction(cam, StreamType.MJPEG));
}
// Add to the window menu always shown
additions.addContributionItem(mjpegMenu, Expression.TRUE);
}
// Now EPICS Array streams
if (!epicsCameras.isEmpty()) {
// Check if EPICS streams can work, i.e. id uk.ac.gda.epics bundle is available
try {
// Make the class load if not available will throw
EpicsV3DynamicDatasetConnector.class.getName();
// Only build the menu if EPICS streams can work
final MenuManager epicsMenu = new MenuManager("EPICS Streams");
for (Entry<String, CameraConfiguration> cam : epicsCameras.entrySet()) {
epicsMenu.add(createMenuAction(cam, StreamType.EPICS_ARRAY));
}
// Add to the window menu always shown
additions.addContributionItem(epicsMenu, Expression.TRUE);
}
catch (NoClassDefFoundError e) {
logger.error("Camera configurations including EPICS PVs were found but EPICS bundle (uk.ac.gda.epics) is not avaliable", e);
}
}
// PV Access streams
if (!pvaCameras.isEmpty()) {
// Check if EPICS streams can work, i.e. id uk.ac.gda.epics bundle is available
try {
// Make the class load if not available will throw
EpicsV4DynamicDatasetConnector.class.getName();
// Only build the menu if EPICS streams can work
final MenuManager pvaMenu = new MenuManager("PV Access Streams");
for (Entry<String, CameraConfiguration> cam : pvaCameras.entrySet()) {
pvaMenu.add(createMenuAction(cam, StreamType.EPICS_PVA));
}
// Add to the window menu always shown
additions.addContributionItem(pvaMenu, Expression.TRUE);
}
catch (NoClassDefFoundError e) {
logger.error("Camera configurations including PVA PVs were found but EPICS bundle (uk.ac.gda.epics) is not avaliable", e);
}
}
logger.debug("Finished creating menu items for live streams");
}
/**
* Creates an {@link Action} which will open a {@link LiveStreamView} for the given camera and stream type.
*
* @param cameraConfig The camera to open
* @param streamType The stream type to open
* @return The created menu action
*/
private Action createMenuAction(Entry<String, CameraConfiguration> cameraConfig, StreamType streamType) {
return new Action(cameraConfig.getKey()) {
@Override
public void run() {
logger.debug("Opening {} {} stream", cameraConfig.getKey(), streamType.displayName);
String viewId=LiveStreamView.ID;
String secondaryId = getSecondaryId(cameraConfig.getValue(), streamType);
if (StringUtils.isNotBlank(cameraConfig.getValue().getViewID())) {
// if the CameraConfiguration has viewId set in bean definition, use that
viewId = cameraConfig.getValue().getViewID();
} else if (getViewID(secondaryId)!=null) {
//if the view is already registered by a plugin, return its ID, don't create a new one
viewId=getViewID(secondaryId);
secondaryId=null; // since the viewId already contains the secondaryId
}
try {
PlatformUI.getWorkbench().getActiveWorkbenchWindow().getActivePage().
showView(viewId, secondaryId, IWorkbenchPage.VIEW_ACTIVATE);
} catch (PartInitException e) {
logger.error("Error opening Stream view for {} {}", cameraConfig.getKey(), streamType.displayName, e);
}
}
};
}
private String getViewID(String key) {
IConfigurationElement[] elements = Platform.getExtensionRegistry().getConfigurationElementsFor("org.eclipse.ui.views");
for (IConfigurationElement each : elements) {
if (each.getAttribute("id").contains(key)) {
return each.getAttribute("id");
}
}
return null;
}
}
| true |
2fc1c0065739b28e47b859d73aaea64445b3fb1b | Java | macosong/riskManagement | /src/main/java/nju/agile/riskmanagement/service/StandardService.java | UTF-8 | 1,431 | 2.078125 | 2 | [] | no_license | package nju.agile.riskmanagement.service;
import com.github.pagehelper.PageHelper;
import nju.agile.riskmanagement.mapper.StandardMapper;
import nju.agile.riskmanagement.pojo.SAndS;
import nju.agile.riskmanagement.pojo.StandardWords;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import java.util.List;
@Service
@Transactional
public class StandardService {
@Autowired
StandardMapper standardMapper;
/*
* 显示列表
*/
public List<StandardWords> getStandard(int page, int rows){
PageHelper.startPage(page, rows);
PageHelper.orderBy("standard_pur_id asc");
List<StandardWords> standard_words = standardMapper.getStandard();
return standard_words;
}
/*
* 删除词条
*/
public void delStandard(int standardPurId) {
standardMapper.delStandard(standardPurId);
}
/*
* 编辑词条
*/
public void editStandard(StandardWords standard_words) {
standardMapper.editStandard(standard_words);
}
/*
* 添加匹配
*/
public void addMatch(SAndS s_and_S) {
standardMapper.addMatch(s_and_S);
}
/*
* 添加词条
*/
public void addStandard(StandardWords standard_words) {
standardMapper.addStandard(standard_words);
}
}
| true |
cc867eafbadab51cb79fc5e65442d6df4911f82d | Java | bernhardroth3/code | /snippets/engine-plugin-signal-to-azure-eventhub/signal-to-AzureEventHub-engine-plugin/src/main/java/com/camunda/consulting/eventhub/plugin/AttachEventHubProducerParseListener.java | UTF-8 | 1,584 | 2 | 2 | [
"Apache-2.0"
] | permissive | package com.camunda.consulting.eventhub.plugin;
import org.camunda.bpm.engine.delegate.ExecutionListener;
import org.camunda.bpm.engine.impl.bpmn.parser.AbstractBpmnParseListener;
import org.camunda.bpm.engine.impl.bpmn.parser.BpmnParseListener;
import org.camunda.bpm.engine.impl.pvm.process.ActivityImpl;
import org.camunda.bpm.engine.impl.pvm.process.ScopeImpl;
import org.camunda.bpm.engine.impl.util.xml.Element;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import static org.camunda.bpm.engine.impl.bpmn.parser.BpmnParse.SIGNAL_EVENT_DEFINITION;
public class AttachEventHubProducerParseListener extends AbstractBpmnParseListener implements BpmnParseListener {
private final Logger LOGGER = LoggerFactory.getLogger(AttachEventHubProducerParseListener.class);
@Override
public void parseIntermediateThrowEvent(Element intermediateEventElement, ScopeImpl scope, ActivityImpl activity) {
attachEventHubListener(intermediateEventElement, activity);
}
@Override
public void parseEndEvent(Element endEventElement, ScopeImpl scope, ActivityImpl activity) {
attachEventHubListener(endEventElement, activity);
}
private void attachEventHubListener(Element intermediateEventElement, ActivityImpl activity) {
Element signalEventDefinitionElement = intermediateEventElement.element(SIGNAL_EVENT_DEFINITION);
if (signalEventDefinitionElement != null) {
LOGGER.debug("Adding signal to event hub listener to " + activity.getId());
activity.addListener(ExecutionListener.EVENTNAME_END, new SignalToEventHubListener());
}
}
}
| true |
e3c1327211bbd5e2769061b1b9259c6b64e2684b | Java | johannawiberg/TDA367project | /src/main/java/viewcontroller/PanelItemManager.java | UTF-8 | 2,074 | 3 | 3 | [] | no_license | package viewcontroller;
import com.google.inject.Inject;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import javafx.scene.effect.DropShadow;
import javafx.scene.layout.AnchorPane;
import javafx.scene.layout.FlowPane;
import javafx.scene.paint.Color;
import model.Course;
public class PanelItemManager {
@Inject private PageFactory pageFactory;
// Method used to display all Courses
public void showActiveCourses(
FlowPane activeCoursesFlowpane, MainPage parent, final List<Course> courses)
throws IOException {
activeCoursesFlowpane.getChildren().clear();
for (Course course :
sortCourses(true, courses)) { // Runs through all the courses to only show the correct ones
AnchorPane courseItem = this.pageFactory.createCoursePanelItem(course, parent);
setShadow(courseItem);
activeCoursesFlowpane.getChildren().add(courseItem);
}
}
// Method that displays all inactive courses
public void showInactiveCourses(
FlowPane inactiveCoursesFlowpane, MainPage parent, final List<Course> courses)
throws IOException {
inactiveCoursesFlowpane.getChildren().clear();
for (Course course :
sortCourses(false, courses)) { // Runs through all the courses to only show the correct ones
AnchorPane courseItem = this.pageFactory.createCoursePanelItem(course, parent);
setShadow(courseItem);
inactiveCoursesFlowpane.getChildren().add(courseItem);
}
}
private List<Course> sortCourses(Boolean status, final List<Course> courses) {
List<Course> tempCourses = new ArrayList<>();
for (Course course : courses) {
if (course.isActive() == status) {
tempCourses.add(course);
}
}
return tempCourses;
}
private void setShadow(
AnchorPane courseItem) { // Make the CourseListItems to have a shadow around them
DropShadow dropShadow = new DropShadow();
dropShadow.setColor(Color.DARKGRAY);
dropShadow.setOffsetX(3);
dropShadow.setOffsetY(3);
courseItem.setEffect(dropShadow);
}
}
| true |
beccdecaa1f0c3040abd9eafea985d1685dff1e7 | Java | michelebof/introsde-2016-assignment-1 | /src/HealthProfileReader.java | UTF-8 | 6,357 | 2.65625 | 3 | [] | no_license | import java.io.IOException;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;
import javax.xml.xpath.XPath;
import javax.xml.xpath.XPathConstants;
import javax.xml.xpath.XPathExpression;
import javax.xml.xpath.XPathExpressionException;
import javax.xml.xpath.XPathFactory;
import org.w3c.dom.Document;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;
import org.xml.sax.SAXException;
public class HealthProfileReader {
Document doc;
XPath xpath;
public void loadXML() throws ParserConfigurationException, SAXException, IOException {
DocumentBuilderFactory domFactory = DocumentBuilderFactory.newInstance();
domFactory.setNamespaceAware(true);
DocumentBuilder builder = domFactory.newDocumentBuilder();
doc = builder.parse("people.xml");
//creating xpath object
getXPathObj();
}
public XPath getXPathObj() {
XPathFactory factory = XPathFactory.newInstance();
xpath = factory.newXPath();
return xpath;
}
/**
* The health profile reader gets information from the command line about
* weight and height and calculates the BMI of the person based on this
* parameters
*
* @param args
* @throws XPathExpressionException
* @throws IOException
* @throws SAXException
* @throws ParserConfigurationException
*/
public static void main(String[] args)throws ParserConfigurationException, SAXException,
IOException, XPathExpressionException{
int argCount = args.length;
HealthProfileReader test = new HealthProfileReader();
test.loadXML();
if (argCount == 0) {
System.out.println("Give me at least a method.");
} else {
String method = args[0];
if (method.equals("displayProfile")) {
String personId = args[1];
test.displayProfile(personId);
} else if (method.equals("displayHealthProfile")) {
String personId = args[1];
test.displayHealthProfile(personId);
} else if (method.equals("all")) {
test.displayAll();
} else if (method.equals("displayProfilebyWeight")) {
Double weight = Double.parseDouble(args[1]);
String condition = args[2];
test.displayProfilebyWeight(weight,condition);
} else{
System.out.println("The system did not find the method '"+method+"'");
}
}
}
private String getFirstname(String personId) throws XPathExpressionException{
XPathExpression expr = xpath.compile("/people/person[@id='" + personId + "']/firstname/text()");
Node node = (Node) expr.evaluate(doc, XPathConstants.NODE);
return node.getTextContent();
}
private String getLastname(String personId) throws XPathExpressionException{
XPathExpression expr = xpath.compile("/people/person[@id='" + personId + "']/lastname/text()");
Node node = (Node) expr.evaluate(doc, XPathConstants.NODE);
return node.getTextContent();
}
private String getBirth(String personId) throws XPathExpressionException{
XPathExpression expr = xpath.compile("/people/person[@id='" + personId + "']/birthdate/text()");
Node node = (Node) expr.evaluate(doc, XPathConstants.NODE);
return node.getTextContent();
}
private double getWeight(String personId) throws XPathExpressionException{
XPathExpression expr = xpath.compile("/people/person[@id='" + personId + "']/healthprofile/weight/text()");
Node node = (Node) expr.evaluate(doc, XPathConstants.NODE);
return Double.parseDouble(node.getTextContent());
}
private double getHeight(String personId) throws XPathExpressionException{
XPathExpression expr = xpath.compile("/people/person[@id='" + personId + "']/healthprofile/height/text()");
Node node = (Node) expr.evaluate(doc, XPathConstants.NODE);
return Double.parseDouble(node.getTextContent());
}
private double getBmi(String personId) throws XPathExpressionException{
XPathExpression expr = xpath.compile("/people/person[@id='" + personId + "']/healthprofile/bmi/text()");
Node node = (Node) expr.evaluate(doc, XPathConstants.NODE);
return Double.parseDouble(node.getTextContent());
}
// function that display HealthProfile of the person with id=personid
private void displayHealthProfile(String personId) throws XPathExpressionException {
HelpProfile p = new HelpProfile();
p.setFirstname(this.getFirstname(personId));
p.setWeight(this.getWeight(personId));
p.setHeight(this.getHeight(personId));
p.setBmi(this.getBmi(personId));
System.out.println(p.HealthProfiletoString());
}
//Function that display all the people in the XML
private void displayAll() throws XPathExpressionException {
//Save all the people id in a NodeList nodes
XPathExpression expr = xpath.compile("//@id");
NodeList nodes = (NodeList) expr.evaluate(doc, XPathConstants.NODESET);
//for each node in nodes execute displayProfile function with id in node
for(int i = 0; i< nodes.getLength();i++){
this.displayProfile(nodes.item(i).getTextContent());
}
}
//Function that display all the people that fulfill the condition
private void displayProfilebyWeight(double weight, String condition) throws XPathExpressionException{
//Save all the people id in a NodeList nodes that fulfill the condition
XPathExpression expr = xpath.compile("//person[healthprofile/weight " + condition + "'" + weight + "']/@id");
NodeList nodes = (NodeList) expr.evaluate(doc, XPathConstants.NODESET);
//for each node in nodes execute displayProfile function with id in node
for(int i = 0; i< nodes.getLength();i++){
this.displayProfile(nodes.item(i).getTextContent());
}
}
//Function that display the profile of the person given the personID
private void displayProfile(String personId) throws XPathExpressionException {
HelpProfile p = new HelpProfile();
p.setFirstname(this.getFirstname(personId));
p.setLastname(this.getLastname(personId));
p.setBirthdate(this.getBirth(personId));
p.setWeight(this.getWeight(personId));
p.setHeight(this.getHeight(personId));
p.setBmi(this.getBmi(personId));
System.out.println(p.toString());
}
}
| true |
47f2ae700c1ac15dbbd8313fe1dfaccab6690ae6 | Java | TiffyZ/Mobile-Computing-Project-eReader-ebook-reader-app | /eReader/src/activity/MainActivity.java | GB18030 | 3,490 | 2.3125 | 2 | [] | no_license | package activity;
import java.util.ArrayList;
import java.util.List;
import com.zzj.z_reader.R;
import adapter.ShelfAdapter;
import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.view.KeyEvent;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.ListView;
import bean.BookInfo;
import component.MyAjustBackgroundDialog;
import component.MyAjustFontColorDialog;
import component.MyAjustFontSizeDialog;
import component.MyAjustPaperMode;
import service.BookInfoService;
import service.BookInfoServiceImpl;
import shared.SetupShared;
import util.ToastUtil;
/**
* the book shelf
*/
public class MainActivity extends Activity {
private ListView lvShelf;
private ShelfAdapter adapter;
private MyAjustPaperMode myAjustPaperMode;
private MyAjustFontSizeDialog myAjustFontSizeDialog;
private MyAjustFontColorDialog myAjustFontColorDialog;
private MyAjustBackgroundDialog myAjustBackgroundDialog;
private List<BookInfo> bookInfos = new ArrayList<BookInfo>();
private BookInfoService bookInfoService;
private long exitTime;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
SetupShared.initSetupShared(getApplication());
lvShelf = (ListView) findViewById(R.id.lvShelf);
myAjustPaperMode = new MyAjustPaperMode(this);
myAjustFontSizeDialog = new MyAjustFontSizeDialog(this);
myAjustFontColorDialog = new MyAjustFontColorDialog(this);
myAjustBackgroundDialog = new MyAjustBackgroundDialog(this);
bookInfoService = new BookInfoServiceImpl(getBaseContext());
update();
}
private void update() {
bookInfos.clear();
bookInfos.addAll(bookInfoService.getAllBookInfo());
adapter = new ShelfAdapter(getBaseContext(), bookInfos,
mShelfItemOnClick);
lvShelf.setAdapter(adapter);
adapter.notifyDataSetChanged();
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.main, menu);
return true;
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case R.id.action_open:
Intent intent = new Intent(getBaseContext(), FileListActivity.class);
startActivityForResult(intent, 1);
return true;
case R.id.set_font_color:
myAjustFontColorDialog.show();
break;
case R.id.set_font_size:
myAjustFontSizeDialog.show();
break;
case R.id.set_background:
myAjustBackgroundDialog.show();
break;
case R.id.set_page_effect:
myAjustPaperMode.show();
break;
default:
}
return super.onOptionsItemSelected(item);
}
OnClickListener mShelfItemOnClick = new OnClickListener() {
@Override
public void onClick(View v) {
Intent intent = new Intent(MainActivity.this, MyReadActivity.class);
intent.putExtra("filePath", bookInfos.get(v.getId()).path);
startActivityForResult(intent, 1);
}
};
@Override
public boolean onKeyDown(int keyCode, KeyEvent event) {
// TODO Auto-generated method stub
if (keyCode == KeyEvent.KEYCODE_BACK
&& event.getAction() == KeyEvent.ACTION_DOWN) {
if ((System.currentTimeMillis() - exitTime) > 800) // System.currentTimeMillis()ۺʱã϶2000
{
ToastUtil.show(this, "press again to exit");
exitTime = System.currentTimeMillis();
} else {
this.finish();
System.exit(0);
}
}
return true;
}
} | true |
52cdc3908dd76322a038eb68d7a5963dcbb38734 | Java | Sahapap-Usadee/hht_demo | /app/src/main/java/com/jastec/hht_demo/remote/IMyAPI.java | UTF-8 | 940 | 1.695313 | 2 | [] | no_license | package com.jastec.hht_demo.remote;
import com.jastec.hht_demo.model.MsPg;
import com.jastec.hht_demo.model.TerTest;
import java.util.List;
import io.reactivex.Observable;
import okhttp3.ResponseBody;
import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.http.Body;
import retrofit2.http.GET;
import retrofit2.http.POST;
public interface IMyAPI {
//http://localhost:58073/api/Login
@POST("api/Register")
Observable<String> registerUser(@Body TerTest user);
@POST("api/Login")
Observable<String> LoginUser(@Body TerTest user);
//http://localhost:5000/api/Program http://localhost:5000/api/Program
@GET("api/Program")
// Call<List<MsPg>> GetPg();
Observable<List<MsPg>> GetPg();
@POST("api/Login/user1")
// Call<List<MsPg>> GetPg();
Observable<String> GetUSER_COUNT(@Body List<TerTest> user);
// @GET("api/Program")
// void GetPg(Callback<List<MsPg>> listCallback);
}
| true |
a540fdc90a26897a8cb4291c59efb02a06bfeb0e | Java | jojoldu/devbeginner | /src/test/java/com/blogcode/RepositoryTests.java | UTF-8 | 3,943 | 2.171875 | 2 | [] | no_license | package com.blogcode;
import com.blogcode.member.domain.Member;
import com.blogcode.member.repository.MemberRepository;
import com.blogcode.oauth.domain.Facebook;
import com.blogcode.posting.domain.Posting;
import com.blogcode.posting.repository.PostingRepository;
import com.blogcode.reply.domain.Reply;
import com.blogcode.reply.repository.ReplyRepository;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.junit.Before;
import org.junit.Ignore;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.autoconfigure.orm.jpa.DataJpaTest;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Sort;
import org.springframework.security.oauth2.provider.OAuth2Authentication;
import org.springframework.test.context.junit4.SpringRunner;
import java.util.List;
import java.util.stream.Collectors;
import static org.hamcrest.CoreMatchers.is;
import static org.junit.Assert.assertThat;
/**
* Created by jojoldu@gmail.com on 2016-12-13
* Blog : http://jojoldu.tistory.com
* Github : http://github.com/jojoldu
*/
@RunWith(SpringRunner.class)
@DataJpaTest
public class RepositoryTests {
@Autowired
private ReplyRepository replyRepository;
@Autowired
private PostingRepository postingRepository;
@Autowired
private MemberRepository<Member> memberRepository;
@Autowired
private MemberRepository<Facebook> facebookRepository;
private Facebook facebook;
@Before
public void setup () {
facebook = new Facebook("이동욱", "jojoldu", "jojoldu@gmail.com", "http://facebook/image");
}
@Test
public void test_Java8TimeAndJpa () {
replyRepository.save(new Reply(0, facebook, "테스트"));
}
@Test
@Ignore
public void test_ReplayPaging() {
for(int i=0;i<10;i++) {
for(int j=0;j<100;j++){
replyRepository.save(new Reply(i, facebook, "테스트 "+i+" 와 "+j));
}
}
PageRequest pageRequest = new PageRequest(0, 30);
List<Reply> replies = replyRepository.findByPostingIdx(0, pageRequest).collect(Collectors.toList());
assertThat(replies.get(0).getIdx(), is(1L));
assertThat(replies.get(29).getIdx(), is(30L));
assertThat(replies.size(), is(30));
PageRequest descPageRequest = new PageRequest(1, 30, Sort.Direction.ASC, "idx");
List<Reply> descReplies = replyRepository.findByPostingIdx(0, descPageRequest).collect(Collectors.toList());
assertThat(descReplies.get(0).getIdx(), is(31L));
assertThat(descReplies.get(29).getIdx(), is(60L));
PageRequest descPageRequest2 = new PageRequest(1, 30, Sort.Direction.DESC, "idx");
List<Reply> descReplies2 = replyRepository.findByPostingIdx(0, descPageRequest2).collect(Collectors.toList());
assertThat(descReplies2.get(0).getIdx(), is(70L));
assertThat(descReplies2.get(29).getIdx(), is(41L));
}
@Test
public void test_Reply와Member관계() {
Member member = memberRepository.save(facebook);
postingRepository.save(new Posting(member, "테스트입니다."));
Posting posting = postingRepository.findAll().get(0);
replyRepository.save(new Reply(posting.getIdx(), member, "댓글입니다."));
Reply reply = replyRepository.findAll().get(0);
Member author = memberRepository.findAll().get(0);
assertThat(reply.getMember().getIdx(), is(author.getIdx()));
}
@Test
public void test_Facebook과Member관계 () {
Posting posting = new Posting(facebook, "facebook");
postingRepository.save(posting);
Member member = postingRepository.findAll().get(0).getMember();
Facebook facebook = facebookRepository.findAll().get(0);
assertThat(postingRepository.findAll().get(0).getMember().getIdx(), is(1L));
}
}
| true |
df3e0f45ef2ffc93533bd4b2e4d73623777d510b | Java | rahulsachint/IntJava | /src/ttl/intjava/dao/DaoFactory.java | UTF-8 | 168 | 1.554688 | 2 | [] | no_license | package ttl.intjava.dao;
public class DaoFactory {
public static BaseDAO getStudentDao() {
//return new MysqlStudentDAO();
return new InMemoryStudentDao();
}
}
| true |
e9cd60434d4e55cace08ad9e26a4ac3691ca3e2a | Java | SebaSphere/GameStagesFabric | /ItemModule/src/main/java/com/dolphin2point0/gamestagesfabric/itemmodule/HashMapItemStageCheckerImpl.java | UTF-8 | 2,162 | 2.578125 | 3 | [
"MIT"
] | permissive | package com.dolphin2point0.gamestagesfabric.itemmodule;
import com.dolphin2point0.gamestagesfabric.itemmodule.api.ItemStageChecker;
import com.dolphin2point0.gamestagesfabric.api.GameStagesAPI;
import net.minecraft.entity.player.PlayerEntity;
import net.minecraft.item.Item;
import java.util.Arrays;
import java.util.HashMap;
import java.util.List;
public class HashMapItemStageCheckerImpl implements ItemStageChecker {
HashMap<Item, String[]> hashMap = new HashMap<>();
@Override
public void addStageToItem(Item item, String stage) {
if(stage == null || item == null) {
return;
}
if(hashMap.containsKey(item)) {
String[] oldStageArray = hashMap.get(item);
if(!Arrays.asList(oldStageArray).contains(stage)) {
String[] newStageArray = new String[oldStageArray.length + 1];
System.arraycopy(oldStageArray, 0, newStageArray, 0, oldStageArray.length);
newStageArray[oldStageArray.length] = stage;
hashMap.put(item, newStageArray);
}
} else {
hashMap.put(item, new String[]{stage});
}
}
@Override
public void addStagesToItem(Item item, String[] stages) {
for (String stage: stages) {
addStageToItem(item, stage);
}
}
@Override
public void removeStageFromItem(Item item, String stage) {
if(stage == null || item == null) {
return;
}
if(hashMap.get(item).length > 1) {
List<String> listArray = Arrays.asList(hashMap.get(item));
if(listArray.contains(stage)) {
listArray.remove(stage);
hashMap.put(item, (String[]) listArray.toArray());
}
} else {
hashMap.remove(item);
}
}
@Override
public boolean itemUsableByPlayer(PlayerEntity p, Item i) {
if(hashMap.containsKey(i)) {
for (String stage: hashMap.get(i)) {
if(!GameStagesAPI.hasStage(p, stage)) {
return false;
}
}
}
return true;
}
}
| true |
e5cd8cb2a9d0effaa81ae8a683ac1f748ee1f607 | Java | leee549/cloud-mall | /mall-product/src/main/java/cn/lhx/mall/MallProductApplication.java | UTF-8 | 873 | 1.695313 | 2 | [] | no_license | package cn.lhx.mall;
import org.mybatis.spring.annotation.MapperScan;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.cache.annotation.EnableCaching;
import org.springframework.cloud.client.discovery.EnableDiscoveryClient;
import org.springframework.cloud.openfeign.EnableFeignClients;
import org.springframework.session.data.redis.config.annotation.web.http.EnableRedisHttpSession;
/**
* @author Administrator
*/
@EnableRedisHttpSession //整合springsession
@EnableDiscoveryClient
@EnableFeignClients(basePackages = "cn.lhx.mall.product.feign")
@SpringBootApplication
@MapperScan("cn.lhx.mall.product.dao")
public class MallProductApplication {
public static void main(String[] args) {
SpringApplication.run(MallProductApplication.class, args);
}
}
| true |
1ad341ceaf8bf2ac304a430055c9ce89d0ad6284 | Java | P79N6A/icse_20_user_study | /methods/Method_1016274.java | UTF-8 | 418 | 2.9375 | 3 | [] | no_license | /**
* Returns maximum dimension combined from specified components dimensions.
* @param components components
* @return maximum dimension
*/
public static Dimension max(final Component... components){
Dimension max=components.length > 0 ? components[0].getPreferredSize() : new Dimension(0,0);
for (int i=1; i < components.length; i++) {
max=max(max,components[i].getPreferredSize());
}
return max;
}
| true |
9105083abc0eb100f952dc1b3a975ada75c410a4 | Java | hulixia1992/lixia.hu | /HuLixia/app/src/main/java/com/example/drum/hulixia/util/image_cache/LocalCacheUtils.java | UTF-8 | 1,784 | 2.40625 | 2 | [] | no_license | package com.example.drum.hulixia.util.image_cache;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.os.Environment;
import android.util.Log;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
/**
* Created by hulixia on 2016/8/10.
* 图片存入磁盘工具
*/
public class LocalCacheUtils {
private static final String CACHE_PATH = Environment.getExternalStorageDirectory().getAbsolutePath() + "/HuLiXia";
private static LocalCacheUtils localCacheUtils;
private LocalCacheUtils() {
}
public static LocalCacheUtils getLocalCacheUtils() {
if (localCacheUtils == null) {
synchronized (LocalCacheUtils.class) {
localCacheUtils = new LocalCacheUtils();
}
}
return localCacheUtils;
}
public static Bitmap getBitmap(String url) {
// fileName = MD5Encoder.encode(url);
File file = new File(CACHE_PATH, url);
try {
Bitmap bitmap = BitmapFactory.decodeStream(new FileInputStream(file));
return bitmap;
} catch (FileNotFoundException e) {
e.printStackTrace();
return null;
}
}
public static void setBitmap(String url, Bitmap bitmap) {
File file = new File(CACHE_PATH, url);
File parentFile = file.getParentFile();
if (!parentFile.exists()) {
parentFile.mkdirs();
}
//把图片保存至本地
try {
bitmap.compress(Bitmap.CompressFormat.JPEG, 100, new FileOutputStream(file));
} catch (FileNotFoundException e) {
e.printStackTrace();
}
Log.i("hulixia", "sd卡缓存");
}
}
| true |
2cd4d86b78a412b543dc22754271a4a382f1a25e | Java | yxjme/LoadImageDemo | /app/src/main/java/com/deringmobile/jbh/loadimagedemo/loadimage/LoadImageManager.java | UTF-8 | 3,469 | 2 | 2 | [] | no_license | package com.deringmobile.jbh.loadimagedemo.loadimage;
import android.content.Context;
import android.graphics.drawable.Drawable;
import android.support.annotation.Nullable;
import android.util.DisplayMetrics;
import android.view.ViewGroup;
import android.widget.ImageView;
import com.bumptech.glide.Glide;
import com.bumptech.glide.load.DataSource;
import com.bumptech.glide.load.engine.DiskCacheStrategy;
import com.bumptech.glide.load.engine.GlideException;
import com.bumptech.glide.request.RequestListener;
import com.bumptech.glide.request.RequestOptions;
import com.bumptech.glide.request.target.Target;
import com.deringmobile.jbh.loadimagedemo.R;
import com.deringmobile.jbh.loadimagedemo.activity.MainActivity;
import com.deringmobile.jbh.loadimagedemo.activity.MyApp;
/**
* Created by zbsdata on 2017/8/29.
*/
public class LoadImageManager {
private static LoadImageManager manager;
public static LoadImageManager newStanence(){
if(manager==null){
manager=new LoadImageManager();
}
return manager;
}
public void loadImage(String url, ImageView imageView){
}
public void loadImage(final Context context, String url, int w, int h, final ImageView imge){
RequestOptions opts=new RequestOptions();
opts.diskCacheStrategy(DiskCacheStrategy.ALL);
opts.error(R.mipmap.ic_launcher);
opts.placeholder(R.mipmap.ic_launcher);
// opts.transform(new CircleCrop(MainActivity.this));//
Glide.with(context)
.load(url)
.apply(opts)
.listener(new RequestListener<Drawable>() {
@Override
public boolean onLoadFailed(@Nullable GlideException e, Object model, Target<Drawable> target, boolean isFirstResource) {
return false;
}
@Override
public boolean onResourceReady(Drawable resource, Object model, Target<Drawable> target, DataSource dataSource, boolean isFirstResource) {
if (imge == null) {
return false;
}
if (imge.getScaleType() != ImageView.ScaleType.FIT_XY) {
imge.setScaleType(ImageView.ScaleType.FIT_XY);
}
ViewGroup.LayoutParams params = imge.getLayoutParams();
int vw = imge.getWidth() - imge.getPaddingLeft() - imge.getPaddingRight();
float scale = (float) vw / (float) resource.getIntrinsicWidth();
int vh = Math.round(resource.getIntrinsicHeight() * scale);
params.height = vh + imge.getPaddingTop() + imge.getPaddingBottom();
DisplayMetrics displayMetrics = context.getResources().getDisplayMetrics();
int width=displayMetrics.widthPixels;
int height=displayMetrics.heightPixels;
params.height=width/2-imge.getPaddingLeft()-imge.getPaddingRight();
params.width=width/2-imge.getPaddingTop()-imge.getPaddingBottom();
imge.setScaleType(ImageView.ScaleType.CENTER_CROP);
imge.setLayoutParams(params);
return false;
}
})
.into(imge);
}
}
| true |
8c68cca4d6771c689558c5c396212683b376c9b7 | Java | galaxyfeeder/Beaconfy-Android | /Beacons/src/com/tomorrowdev/beacons/MM.java | UTF-8 | 1,216 | 3.390625 | 3 | [] | no_license | package com.tomorrowdev.beacons;
public class MM {
int minor, major;
private int deathCount = 0;
double distance;
public MM(int major, int minor) {
this.minor = minor;
this.major = major;
}
public MM(int major, int minor, double distance) {
this.minor = minor;
this.major = major;
this.distance = distance;
}
public int getMinor() {
return minor;
}
public void setMinor(int minor) {
this.minor = minor;
}
public int getMajor() {
return major;
}
public void setMajor(int major) {
this.major = major;
}
public int getDeathCount() {
return deathCount;
}
public void setDeathCount(int deathCount) {
this.deathCount = deathCount;
}
public void increaseDeathCountByOne() {
deathCount++;
}
public double getDistance() {
return distance;
}
public void setDistance(double distance) {
this.distance = distance;
}
/**
* Overrided method used by the list to check if it's the same object.
*/
@Override
public boolean equals(Object object){
boolean sameSame = false;
if(object != null && object instanceof MM){
sameSame = this.major == ((MM) object).getMajor() && this.minor == ((MM) object).getMinor();
}
return sameSame;
}
}
| true |
813552c17173ce569505fdd29302ddd84c1fb73d | Java | zgs17951/RubiksCubeSolver-2 | /src/solver/CaptureButton.java | UTF-8 | 730 | 2.78125 | 3 | [] | no_license | package solver;
import android.content.Context;
import android.view.View;
import android.widget.Button;
/**
* CaptureButton class so that perhaps one day, the bulk of its code won't be in the SolverActivity
* @author Andy Zhang
*/
public class CaptureButton extends Button{
private int face = 0;
/**
* Initializes a new CaptureButton
* @param context Context of the button; for now, always SolverActivity
* @param x x-coordinate of the Button on screen
* @param y y-coordinate of the Button on screen
*/
public CaptureButton(Context context, int x, int y) {
super(context);
setText("Capture");
setX(x);
setY(y);
// Ideally, the OnClickListener is in here too, but it references too many variables
}
}
| true |
9c8e51414f4041a7633426e7df544a09b078c861 | Java | bellmit/MSFM | /client/Java/translator/com/cboe/consumers/callback/OrderStatusConsumerFactory.java | UTF-8 | 1,556 | 2.21875 | 2 | [] | no_license | package com.cboe.consumers.callback;
import com.cboe.application.shared.*;
import com.cboe.util.*;
import com.cboe.util.event.*;
import com.cboe.delegates.callback.*;
import com.cboe.interfaces.callback.*;
import com.cboe.idl.cmiCallback.*;
import com.cboe.presentation.common.logging.GUILoggerHome;
/**
* Factory used to create CMIOrderStatusConsumers.
*
* @author Derek T. Chambers-Boucher
* @version 03/16/1999
*/
public class OrderStatusConsumerFactory
{
/**
* OrderStatusConsumerFactory constructor.
*
* @author Derek T. Chambers-Boucher
*/
public OrderStatusConsumerFactory()
{
super();
}
/**
* This method creates a new CMIOrderStatusConsumer callback Corba object.
*
* @author Derek T. Chambers-Boucher
*
* @param channelType the event channel type to publish on.
* @param eventProcessor the event channel to publish on.
*/
public static CMIOrderStatusConsumer create(EventChannelAdapter eventProcessor)
{
try
{
OrderStatusConsumer orderStatusConsumer = new OrderStatusConsumerImpl(eventProcessor);
OrderStatusConsumerDelegate delegate= new OrderStatusConsumerDelegate(orderStatusConsumer);
org.omg.CORBA.Object corbaObject = (org.omg.CORBA.Object)RemoteConnectionFactory.find().register_object (delegate);
return CMIOrderStatusConsumerHelper.narrow (corbaObject);
}
catch (Exception e)
{
GUILoggerHome.find().exception(e, "OrderStatusConsumerFactory.create");
return null;
}
}
}
| true |
ef6a3730c3274711e23c1bde1202a3acdd36709a | Java | oliveira-sidnei/sohs3411 | /ess/src/main/java/br/com/ins/bean/GeraBoletoBean.java | UTF-8 | 4,679 | 1.929688 | 2 | [] | no_license | package br.com.ins.bean;
import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.io.Serializable;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import javax.annotation.PostConstruct;
import javax.ejb.EJB;
import javax.faces.bean.ManagedBean;
import javax.faces.bean.ViewScoped;
import javax.servlet.http.HttpSession;
import org.primefaces.model.DefaultStreamedContent;
import org.primefaces.model.StreamedContent;
import br.com.ins.control.ControladorAluguel;
import br.com.ins.control.ControladorEmail;
import br.com.ins.control.ControladorEvento;
import br.com.ins.control.ControladorLojista;
import br.com.ins.control.ControladorMensagens;
import br.com.ins.control.ControladorPerfil;
import br.com.ins.core.Aluguel;
import br.com.ins.core.Loja;
import br.com.ins.core.Lojista;
import br.com.ins.core.Usuario;
import br.com.ins.services.SessionUtils;
@ViewScoped
@ManagedBean
public class GeraBoletoBean implements Serializable {
private static final long serialVersionUID = 1L;
@EJB
ControladorAluguel controladorAluguel;
@EJB
ControladorMensagens controladorMensagens;
@EJB
ControladorLojista controladorLojista;
@EJB
ControladorEmail controladorEmail;
@EJB
ControladorEvento controladorEvento;
@EJB
ControladorPerfil controladorPerfil;
private Integer idAluguelSelecionado = new Integer(0);
private List<Aluguel> alugueis = new ArrayList<Aluguel>();
private Aluguel aluguelSelecionado;
private Lojista lojistaSelecionado;
private Usuario usuarioSessao;
HttpSession session = SessionUtils.getSession();
private StreamedContent content;
@PostConstruct
public void iniciar() {
usuarioSessao = (Usuario) session.getAttribute("username");
lojistaSelecionado = controladorLojista.buscaLojistaPorUsuario(usuarioSessao);
}
public boolean verificaAcesso() {
if (usuarioSessao.getPerfil().getDescricao().equals(controladorPerfil.buscaPerfilLojista().getDescricao())) {
return true;
} else {
return false;
}
}
public String retornaDataString(Date dataConsultada) {
try {
SimpleDateFormat sdf = new SimpleDateFormat("dd/MM/yyyy");
String dataString = sdf.format(dataConsultada);
return dataString;
}catch(Exception e) {
return null;
}
}
// public void downloadBoleto(Integer idAluguel) throws IOException {
// Aluguel aluguelDownload = controladorAluguel.buscaAluguel(idAluguel);
// ByteArrayInputStream inputStream = controladorAluguel.selecionaDocumento(aluguelDownload);
// setContent(new DefaultStreamedContent(inputStream, "application/x-download", "boleto " + aluguelDownload.getLoja().getCnpj() + ".pdf"));
// inputStream.close();
//
// }
public void detalhaHistoricoFinanceiro(Loja loja) {
alugueis = controladorAluguel.buscaAluguelPorLoja(loja);
}
public void detalhaAluguel(Aluguel aluguel) {
aluguelSelecionado = aluguel;
System.out.println(aluguelSelecionado.getListaItensAluguel().size());
}
public void enviarEmail() {
System.out.println("Enviando e-mail...");
// controladorEmail.enviaEmail(controladorEvento.buscaEvento(1));
}
public void geraBoleto(Aluguel aluguelConsultado) {
if (aluguelConsultado.getDocumento() == null) {
content = controladorAluguel.gereBoleto(aluguelConsultado);
controladorMensagens.addMsgInfo("boleto.gerado");
} else {
System.out.println("CAINDO AQUI");
controladorMensagens.addMsgErro("boleto.existente");
}
}
public String redireciona() {
controladorMensagens.addMsgAlerta("boleto.existente");
return "consultaFuncionarios.xhtml";
}
public Integer getIdAluguelSelecionado() {
return idAluguelSelecionado;
}
public void setIdAluguelSelecionado(Integer idAluguelSelecionado) {
this.idAluguelSelecionado = idAluguelSelecionado;
}
public Aluguel getAluguelSelecionado() {
return aluguelSelecionado;
}
public void setAluguelSelecionado(Aluguel aluguelSelecionado) {
this.aluguelSelecionado = aluguelSelecionado;
}
public StreamedContent getContent() {
return content;
}
public void setContent(StreamedContent content) {
this.content = content;
}
public List<Aluguel> getAlugueis() {
return alugueis;
}
public void setAlugueis(List<Aluguel> alugueis) {
this.alugueis = alugueis;
}
public Lojista getLojistaSelecionado() {
return lojistaSelecionado;
}
public void setLojistaSelecionado(Lojista lojistaSelecionado) {
this.lojistaSelecionado = lojistaSelecionado;
}
}
| true |
3487b391251df53a76b4b7db2278bb73443ce35b | Java | sunilkumarg1986/HackerRank | /Java/Challenges/Cracking_the_coding_interview/Sorting_Comparator/Checker.java | UTF-8 | 969 | 4.03125 | 4 | [] | no_license | /*
Comparators are used to compare two objects. In this challenge, you'll create a comparator and use it to sort an array.
The Player class is provided in the editor below; it has two fields:
A string, .
An integer, .
Given an array of Player objects, write a comparator that sorts them in order of decreasing score; if or more players have the same score,
sort those players alphabetically by name. To do this, you must create a Checker class that implements the Comparator interface,
then write an int compare(Player a, Player b) method implementing the Comparator.compare(T o1, T o2) method.
*/
import java.util.Comparator;
class Checker implements Comparator<Player>{
@Override
public int compare(Player o1, Player o2) {
int result=0;
if(o1.score>o2.score)
result=1;
else if(o1.score<o2.score)
result=-1;
else if(o1.score==o2.score)
return o1.name.compareTo(o2.name);
return -result;
}
}
| true |
6945ab906944ff864a245ddc6c061f28f464128a | Java | Mefi100feLL/Sales | /app/src/main/java/com/PopCorp/Sales/Activities/LoginActivity.java | UTF-8 | 5,685 | 1.984375 | 2 | [] | no_license | package com.PopCorp.Sales.Activities;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.preference.PreferenceManager;
import android.support.v7.app.AppCompatActivity;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;
import com.PopCorp.Sales.Data.User;
import com.PopCorp.Sales.Net.NetHelper;
import com.PopCorp.Sales.R;
import com.PopCorp.Sales.SD;
import com.PopCorp.Sales.SalesApplication;
import java.net.CookieHandler;
import java.net.CookieManager;
import java.net.CookiePolicy;
import java.net.HttpCookie;
import java.util.List;
import retrofit.Callback;
import retrofit.RetrofitError;
import retrofit.client.Response;
public class LoginActivity extends AppCompatActivity {
private static final String LOG_LOGIN = "LOGIN";
private CookieManager cookieManager;
private EditText email;
private EditText password;
private EditText nameReg;
private EditText emailReg;
private EditText passwordReg;
private EditText passwordRegRepeat;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_login);
cookieManager = new CookieManager(null, CookiePolicy.ACCEPT_ALL);
CookieHandler.setDefault(cookieManager);
email = (EditText) findViewById(R.id.activity_login_email);
password = (EditText) findViewById(R.id.activity_login_password);
final Button signIn = (Button) findViewById(R.id.activity_login_sign_in);
signIn.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
if (email.getText().toString().isEmpty() || password.getText().toString().isEmpty()) {
return;
}
signIn(email.getText().toString(), password.getText().toString());
}
});
nameReg = (EditText) findViewById(R.id.activity_login_reg_name);
emailReg = (EditText) findViewById(R.id.activity_login_reg_email);
passwordReg = (EditText) findViewById(R.id.activity_login_reg_password);
passwordRegRepeat = (EditText) findViewById(R.id.activity_login_reg_password_repeat);
Button signUp = (Button) findViewById(R.id.activity_login_sign_up);
signUp.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
if (emailReg.getText().toString().isEmpty() || nameReg.getText().toString().isEmpty() ||
passwordReg.getText().toString().isEmpty() || passwordRegRepeat.getText().toString().isEmpty()) {
return;
}
if (!passwordReg.getText().toString().equals(passwordRegRepeat.getText().toString())){
return;
}
((SalesApplication) getApplication()).getService().signUp(nameReg.getText().toString(), emailReg.getText().toString(), passwordReg.getText().toString(),
passwordRegRepeat.getText().toString(), new Callback<Response>() {
@Override
public void success(Response response, Response response2) {
if (registrationSuccess(response)){
signIn(emailReg.getText().toString(), passwordReg.getText().toString());
}
}
@Override
public void failure(RetrofitError error) {
Toast.makeText(LoginActivity.this, error.getMessage(), Toast.LENGTH_SHORT).show();
}
});
}
});
}
private boolean registrationSuccess(Response response) {
String body = NetHelper.stringFromResponse(response);
return false;
}
private void signIn(final String email, String password){
((SalesApplication) getApplication()).getService().signIn(email, password, SD.REMEMBER_ME, new Callback<Response>() {
@Override
public void success(Response response, Response response2) {
boolean findedCookie = false;
List<HttpCookie> cookies = cookieManager.getCookieStore().getCookies();
for (HttpCookie cookie : cookies){
if (cookie.getName().startsWith(SD.HOST_NAME)){
User newUser = new User(NetHelper.stringFromResponse(response), email, cookie);
SharedPreferences sPref = PreferenceManager.getDefaultSharedPreferences(getApplicationContext());
SharedPreferences.Editor editor = sPref.edit();
editor.putString(SD.PREFS_CURRENT_USER, newUser.getId()).apply();
newUser.putInDB(((SalesApplication) getApplication()).getDB());
findedCookie = true;
}
}
if (!findedCookie){
Toast.makeText(LoginActivity.this, R.string.error_not_availible_email_or_password, Toast.LENGTH_SHORT).show();
}
}
@Override
public void failure(RetrofitError error) {
Toast.makeText(LoginActivity.this, error.getMessage(), Toast.LENGTH_SHORT).show();
}
});
}
}
| true |
89ccf3423c981010ef148a50a18927a5068ff68f | Java | AY1920S2-CS2103T-F10-3/main | /src/main/java/seedu/nova/model/schedule/Day.java | UTF-8 | 5,263 | 3.125 | 3 | [
"MIT"
] | permissive | package seedu.nova.model.schedule;
import java.time.LocalDate;
import java.time.LocalTime;
import java.util.Collections;
import java.util.LinkedList;
import java.util.List;
import seedu.nova.model.schedule.event.Event;
import seedu.nova.model.schedule.event.Lesson;
import seedu.nova.model.schedule.event.WeakEvent;
import seedu.nova.model.schedule.event.exceptions.EventNotFoundException;
import seedu.nova.model.schedule.event.exceptions.TimeOverlapException;
import seedu.nova.model.util.Copyable;
import seedu.nova.model.util.time.slotlist.DateTimeSlotList;
/**
* The type Day.
*/
public class Day implements Copyable<Day> {
private List<Event> events;
private LocalDate date;
private DateTimeSlotList freeSlots;
/**
* Instantiates a new Day.
*
* @param date the date
*/
public Day(LocalDate date) {
events = new LinkedList<>();
this.date = date;
freeSlots = DateTimeSlotList.ofDay(date);
}
private Day(List<Event> events, LocalDate date, DateTimeSlotList freeSlots) {
this.events = events;
this.date = date;
this.freeSlots = freeSlots;
}
/**
* Adds event.
*
* @param event the event
*/
public void addEvent(Event event) {
boolean canAdd = true;
for (Event curr: events) {
canAdd = checkCanAdd(event, curr);
if (!canAdd) {
break;
}
}
if (canAdd) {
events.add(event);
freeSlots.excludeDuration(event.getDtd());
Collections.sort(events);
} else {
throw new TimeOverlapException();
}
}
/**
* Checks if a given event overlaps with an existing event.
* @param event the given event
* @param curr the existing event
* @return boolean that determines if there is no overlap
*/
boolean checkCanAdd(Event event, Event curr) {
boolean canAdd = true;
LocalTime currStart = curr.getStartTime();
LocalTime currEnd = curr.getEndTime();
boolean haveSameStart = currStart.equals(event.getStartTime());
boolean haveSameEnd = currEnd.equals(event.getEndTime());
boolean eventStartIsBetween = isBetween(event.getStartTime(), currStart, currEnd);
boolean eventEndIsBetween = isBetween(event.getEndTime(), currStart, currEnd);
if (haveSameStart || haveSameEnd || eventStartIsBetween || eventEndIsBetween) {
canAdd = false;
}
return canAdd;
}
/**
* determines if a given time is in between 2 other times
* @param time the given time
* @param start the start time
* @param end the end time
* @return a boolean
*/
boolean isBetween(LocalTime time, LocalTime start, LocalTime end) {
int isAfterStart = time.compareTo(start);
int isBeforeEnd = time.compareTo(end);
return isAfterStart > 0 && isBeforeEnd < 0;
}
/**
* Add lesson.
*
* @param lesson the lesson
*/
public void addLesson(Lesson lesson) {
Lesson tmp = new Lesson(lesson);
tmp.setDate(date);
addEvent(tmp);
}
/**
* Removes an event.
*
* @param index index of event in the LinkedList
*/
Event deleteEvent(int index) {
if (index >= events.size()) {
throw new EventNotFoundException();
}
Event deleted = events.remove(index);
freeSlots.includeDuration(deleted.getDtd());
if (deleted instanceof WeakEvent) {
WeakEvent wkE = (WeakEvent) deleted;
wkE.destroy();
}
return deleted;
}
/**
* Removes an event.
*
* @param event event to be removed
*/
boolean deleteEvent(Event event) {
events.remove(event);
freeSlots.includeDuration(event.getDtd());
if (event instanceof WeakEvent) {
WeakEvent wkE = (WeakEvent) event;
wkE.destroy();
}
return true;
}
/**
* Adds a note to an event.
*
* @param index index of event in the LinkedList
* @return String representing the event with added note
*/
public String addNote(String desc, int index) {
if (index >= events.size()) {
throw new EventNotFoundException();
}
events.get(index).addNote(desc);
return events.get(index).toString();
}
public List<Event> getEventList() {
return events;
}
/**
* View the events for the day.
*
* @return the string of events
*/
public String view() {
StringBuilder sb = new StringBuilder();
int index = 0;
for (Event event : events) {
sb.append(++index);
sb.append(". ");
sb.append(event);
sb.append("\n");
}
return sb.toString();
}
/**
* Get free slots in the form of DateTimeDuration
*
* @return List of DateTimeDuration
*/
public DateTimeSlotList getFreeSlotList() {
return freeSlots;
}
@Override
public Day getCopy() {
return new Day(new LinkedList<>(events), date, freeSlots.getCopy());
}
}
| true |
e5382fe066744cb5ba9313ac9799fcb7e08f6637 | Java | xMlex/l2walker | /java/fw/connection/login/clientpackets/RequestServerLogin.java | UTF-8 | 315 | 1.773438 | 2 | [] | no_license | package fw.connection.login.clientpackets;
public class RequestServerLogin extends LoginClientPacket {
@Override
public void excecute() {
writeC(0x02);
writeD(getClient().geLoginOk()[0]);
writeD(getClient().geLoginOk()[1]);
writeC(getClient().getServerId());
writeB(new byte[14]);
}
}
| true |
cb275030dd60ed0920a8cbe5dac9edbfab18f1b9 | Java | xbkaishui/common-web | /src/main/java/cn/gniic/common/mybatisplus/MybatisPlusSqlInjector.java | UTF-8 | 1,707 | 2.078125 | 2 | [] | no_license | package cn.gniic.common.mybatisplus;
import com.baomidou.mybatisplus.core.injector.AbstractMethod;
import com.baomidou.mybatisplus.core.injector.AbstractSqlInjector;
import com.baomidou.mybatisplus.core.injector.methods.Delete;
import com.baomidou.mybatisplus.core.injector.methods.DeleteById;
import com.baomidou.mybatisplus.core.injector.methods.Insert;
import com.baomidou.mybatisplus.core.injector.methods.SelectById;
import com.baomidou.mybatisplus.core.injector.methods.SelectCount;
import com.baomidou.mybatisplus.core.injector.methods.SelectList;
import com.baomidou.mybatisplus.core.injector.methods.SelectObjs;
import com.baomidou.mybatisplus.core.injector.methods.SelectPage;
import com.baomidou.mybatisplus.core.injector.methods.Update;
import com.baomidou.mybatisplus.core.injector.methods.UpdateById;
import com.baomidou.mybatisplus.extension.injector.methods.additional.InsertBatchSomeColumn;
import java.util.List;
import java.util.stream.Collectors;
import java.util.stream.Stream;
/**
* <p>
* MybatisPlusSql注入器
* </p>
*
* @author Caratacus
*/
public class MybatisPlusSqlInjector extends AbstractSqlInjector {
@Override
public List<AbstractMethod> getMethodList() {
return Stream.of(
new Insert(),
new InsertBatchSomeColumn(t -> true),
new Delete(),
new DeleteById(),
new Update(),
new UpdateById(),
new UpdateAllColumnById(),
new SelectById(),
new SelectCount(),
new SelectObjs(),
new SelectList(),
new SelectPage()
).collect(Collectors.toList());
}
}
| true |
b5f3444ff898688174af26f1df871c5fde4aeb1d | Java | pietrobraione/sushi | /master/src/main/java/sushi/execution/minimizer/MinimizerProblemFactory.java | UTF-8 | 6,422 | 2.8125 | 3 | [] | no_license | package sushi.execution.minimizer;
import java.io.BufferedReader;
import java.io.IOException;
import java.nio.file.Files;
import java.util.List;
import java.util.TreeSet;
import sushi.exceptions.TerminationException;
abstract class MinimizerProblemFactory<P extends MinimizerProblem> {
/** The parameters. */
protected final MinimizerParameters parameters;
/** The total number of branches. */
protected final int nBranches;
/** The total number of traces. */
protected final int nTraces;
/** The set containing all the branch numbers. */
protected final TreeSet<Integer> branchNumbers;
/** The set containing all the trace numbers. */
protected final TreeSet<Integer> traceNumbers;
/**
* The set of all the branch numbers that must be ignored
* because they are not coverage targets.
*/
protected final TreeSet<Integer> branchNumbersToIgnore;
/**
* The set of all the trace numbers that must be ignored
* because they have been already tried during previous
* iterations.
*/
protected final TreeSet<Integer> traceNumbersToIgnore;
/** The number of rows in the linear problem. */
protected int rows;
/** The number of columns in the linear problem. */
protected int cols;
MinimizerProblemFactory(MinimizerParameters parameters) throws IOException {
this.parameters = parameters;
this.nBranches = (int) Files.lines(this.parameters.getBranchesFilePath()).count();
this.nTraces = (int) Files.lines(this.parameters.getCoverageFilePath()).count();
//branch numbers are just all the numbers between 0 and nBranches - 1
this.branchNumbers = new TreeSet<>();
for (int branchNumber = 0; branchNumber < this.nBranches; ++branchNumber) {
this.branchNumbers.add(branchNumber);
}
//trace numbers are just all the numbers between 0 and nTraces - 1
this.traceNumbers = new TreeSet<>();
for (int traceNumber = 0; traceNumber < this.nTraces; ++traceNumber) {
this.traceNumbers.add(traceNumber);
}
//the branches to ignore are those that the user do not want to cover
this.branchNumbersToIgnore = branchNumbersToIgnore();
//also, we shall ignore all the branches that are not covered
//by any trace (it might happen at first iteration, since a JBSE
//instance may record a branch in the branches file, and then
//crash before producing any coverage info)
this.branchNumbersToIgnore.addAll(branchesThatMayNotBeCovered());
//the branches to ignore are those that the user do not want to cover
this.traceNumbersToIgnore = traceNumbersToIgnore();
//calculates the number of rows and cols for the optimization problem
this.rows = this.nBranches - this.branchNumbersToIgnore.size();
this.cols = this.nTraces - this.traceNumbersToIgnore.size();
if (this.rows == 0 || this.cols == 0) {
throw new TerminationException("Minimizer invoked with no branches to cover and/or no traces that cover the uncovered branches");
}
}
void ignore(List<Integer> traceNumbers) throws IOException, NumberFormatException {
this.traceNumbersToIgnore.addAll(traceNumbers);
this.branchNumbersToIgnore.addAll(notCoveredBranches());
this.rows = this.nBranches - this.branchNumbersToIgnore.size();
this.cols = this.nTraces - this.traceNumbersToIgnore.size();
}
boolean isEmpty() {
return this.rows == 0 || this.cols == 0;
}
private TreeSet<Integer> branchNumbersToIgnore() throws IOException {
final TreeSet<Integer> retVal = new TreeSet<>();
try (final BufferedReader r = Files.newBufferedReader(this.parameters.getBranchesToIgnoreFilePath())) {
String line;
while ((line = r.readLine()) != null) {
retVal.add(Integer.parseInt(line.trim()));
}
}
return retVal;
}
private TreeSet<Integer> branchesThatMayNotBeCovered() throws IOException {
final TreeSet<Integer> retVal = new TreeSet<>(this.branchNumbers);
try (final BufferedReader r = Files.newBufferedReader(this.parameters.getCoverageFilePath())) {
String line;
while ((line = r.readLine()) != null) {
final String[] fields = line.split(",");
for (int i = 3; i < fields.length; ++i) {
final int branchNumber = Integer.parseInt(fields[i].trim());
retVal.remove(branchNumber);
}
}
}
return retVal;
}
private TreeSet<Integer> traceNumbersToIgnore() throws IOException {
final TreeSet<Integer> retVal = new TreeSet<>();
try (final BufferedReader r = Files.newBufferedReader(this.parameters.getTracesToIgnoreFilePath())) {
String line;
while ((line = r.readLine()) != null) {
retVal.add(Integer.parseInt(line.trim()));
}
}
return retVal;
}
private TreeSet<Integer> notCoveredBranches() throws IOException, NumberFormatException {
final TreeSet<Integer> mayBeCovered = new TreeSet<>();
try (final BufferedReader r = Files.newBufferedReader(this.parameters.getCoverageFilePath())) {
String line;
int traceNumber = 0;
while ((line = r.readLine()) != null) {
if (this.traceNumbersToIgnore.contains(traceNumber)) {
++traceNumber;
continue;
}
final String[] fields = line.split(",");
for (int i = 3; i < fields.length; ++i) {
final int branchNumber = Integer.parseInt(fields[i].trim());
mayBeCovered.add(branchNumber);
}
++traceNumber;
}
}
final TreeSet<Integer> retVal = new TreeSet<Integer>(this.branchNumbers);
retVal.removeAll(mayBeCovered);
return retVal;
}
/**
* Builds a MIP problem for detecting the optimal subset of all
* traces that covers the same set of branches. The MIP problem
* is structured as follows.
* <pre>
* Minimize c_1 * x_1 + c_2 * x_2 + ... c_t * x_t
* subject to
* a_1_1 * x_1 + ... + a_1_t * x_t >= 1
* ...
* a_b_1 * x_1 + ... + a_b_t * x_t >= 1
* where
* x_1 binary
* ...
* x_t binary
* </pre>
* where t is the number of traces, x_1 ... x_t are binary variables
* stating whether the associated trace belongs to the optimal subset
* or not, c_1 ... c_t are the costs of the traces, b is the number of
* branches, a_i_j is 1 if trace j covers branch i, otherwise 0. Actually
* the problem is slightly more complex than that because the method allows
* to exclude some branches and some traces.
*
* @return a {@link MinimizerProblem}.
* @throws IOException if reading some file fails.
* @throws NumberFormatException if some file has wrong format.
*/
abstract P makeProblem() throws IOException, NumberFormatException;
}
| true |
10dbc9fce96f18769506885c83c3ffca873215be | Java | naveenkumarsahu1/QuizApp3 | /app/src/main/java/com/example/quiz_app/Home_Page.java | UTF-8 | 1,788 | 2.21875 | 2 | [] | no_license | package com.example.quiz_app;
import android.os.Bundle;
import android.app.Activity;
import android.content.Intent;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.ImageView;
public class Home_Page extends Activity {
ImageView img_technical,img_aptitude;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_home__page);
img_aptitude=(ImageView)findViewById(R.id.img_aptitude);
img_technical=(ImageView)findViewById(R.id.img_technical);
img_aptitude.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v)
{
Intent ob=new Intent(Home_Page.this,Apptitude_Qu_Page.class);
startActivity(ob);
}
});
img_technical.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v)
{
Intent ob=new Intent(Home_Page.this,Programming_Quiz.class);
startActivity(ob);
}
});
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.programming__quiz, menu);
return super.onCreateOptionsMenu(menu);
}
@Override
public boolean onMenuItemSelected(int featureId, MenuItem item)
{
switch (item.getItemId())
{
case R.id.about_us:
Intent ob=new Intent(Home_Page.this,About_us.class);
startActivity(ob);
break;
case R.id.instruction:
Intent ob1=new Intent(Home_Page.this,Instruction.class);
startActivity(ob1);
break;
default:
break;
}
return super.onMenuItemSelected(featureId, item);
}
}
| true |
c0257819645153a3f73f43ed1563ea33836ac32f | Java | hee4245/Parking | /app/src/main/java/com/bug/parking/camera/MyCamera.java | UTF-8 | 6,428 | 2.109375 | 2 | [
"Apache-2.0"
] | permissive | package com.bug.parking.camera;
import android.app.Activity;
import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Matrix;
import android.graphics.Point;
import android.graphics.PointF;
import android.graphics.drawable.Drawable;
import android.hardware.Camera;
import android.os.Handler;
import android.support.v7.app.ActionBar;
import android.util.Log;
import android.widget.Toast;
import com.bug.parking.activity.MainActivity;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.List;
/**
* Created by json on 15. 8. 1..
*/
public class MyCamera {
private static final String TAG = "MyCamera";
private static final String fileName = "park.png";
private Context context;
private Camera camera;
private Camera.Size pictureSize;
private Point displaySize = new Point();
private int statusBarHeight = 0;
private PointF scaleRatio = new PointF();
private Camera.PictureCallback pictureCallback;
private MainActivity.Callback afterTakePicture;
private float whRatio;
public MyCamera(Context context, MainActivity.Callback afterTakePicture, float whRatio) {
try {
this.context = context;
this.afterTakePicture = afterTakePicture;
this.whRatio = whRatio;
// initCamera();
initPictureCallback();
} catch (Exception e) {
Log.d(TAG, "Error init camera: " + e.getMessage());
}
}
public void initCamera() {
camera = Camera.open();
camera.setDisplayOrientation(90);
Camera.Parameters params = camera.getParameters();
params.setRotation(90);
params.setFocusMode(Camera.Parameters.FOCUS_MODE_CONTINUOUS_PICTURE);
((Activity) context).getWindowManager().getDefaultDisplay().getRealSize(displaySize);
statusBarHeight = Math.round(25 * context.getResources().getDisplayMetrics().density);
pictureSize = camera.new Size(Integer.MAX_VALUE, Integer.MAX_VALUE);
List<Camera.Size> sizes = params.getSupportedPictureSizes();
for (Camera.Size size : sizes) {
if (size.height >= displaySize.x && size.width <= pictureSize.width && size.height <= pictureSize.height) {
pictureSize = size;
}
}
if (pictureSize.width > 0 && pictureSize.height > 0) {
params.setPictureSize(pictureSize.width, pictureSize.height);
}
camera.setParameters(params);
scaleRatio.x = (float) (displaySize.x) / (float) pictureSize.height;
scaleRatio.y = (float) (displaySize.y - statusBarHeight) / (float) pictureSize.width;
}
public void destroyCamera() {
camera.release();
camera = null;
}
private void initPictureCallback() {
pictureCallback = new Camera.PictureCallback() {
@Override
public void onPictureTaken(byte[] data, Camera camera) {
Handler handler = new Handler();
handler.post(new SavePhotoRunnable(data));
}
};
}
private void savePhoto(byte[] data) {
FileOutputStream fos;
try {
fos = context.openFileOutput(fileName, Context.MODE_PRIVATE);
int inSampleSize = calculateInSampleSize(data);
BitmapFactory.Options options = new BitmapFactory.Options();
options.inSampleSize = inSampleSize;
// options.inJustDecodeBounds = false;
Bitmap sampledBitmap = BitmapFactory.decodeByteArray(data, 0, data.length, options);
Matrix matrix = new Matrix();
matrix.setRotate(90.0f);
matrix.postScale(scaleRatio.x / (float) inSampleSize, scaleRatio.y / (float) inSampleSize);
int actionBarHeight = 0;
ActionBar actionBar = ((MainActivity) context).getSupportActionBar();
if (actionBar != null)
actionBarHeight = actionBar.getHeight();
int picturePosX = Math.round((float) actionBarHeight / scaleRatio.y);
int picturePosY = 0;
int pictureWidth = Math.round(sampledBitmap.getHeight() * whRatio / scaleRatio.y);
int pictureHeight = Math.round(sampledBitmap.getHeight() / scaleRatio.x);
Bitmap croppedBitmap = Bitmap.createBitmap(sampledBitmap, picturePosX, picturePosY, pictureWidth, pictureHeight, matrix, true);
sampledBitmap = null;
croppedBitmap.compress(Bitmap.CompressFormat.JPEG, 80, fos);
croppedBitmap = null;
fos.close();
afterTakePicture.callback();
} catch (FileNotFoundException e) {
Log.e(TAG, "File not found: " + e.getMessage());
} catch (IOException e) {
Log.e(TAG, "Error accessing file: " + e.getMessage());
} catch (Exception e) {
Toast.makeText(context, e.getMessage(), Toast.LENGTH_LONG).show();
}
}
private int calculateInSampleSize(byte[] data) {
int inSampleSize = 1;
BitmapFactory.Options options = new BitmapFactory.Options();
options.inJustDecodeBounds = true;
BitmapFactory.decodeByteArray(data, 0, data.length, options);
if (options.outWidth > 0 || options.outHeight > 0) {
float scaleWidth = (float) options.outHeight / (float) displaySize.x;
float scaleHeight = (float) options.outWidth / (float) displaySize.y;
float scale = Math.min(scaleWidth, scaleHeight);
while (inSampleSize * 2 <= scale)
inSampleSize *= 2;
}
return inSampleSize;
}
private String getPicturePath() {
// return "" + context.getExternalFilesDir(null).toString() + "/" + fileName;
return context.getFilesDir().toString() + "/" + fileName;
}
public Camera getCamera() {
return camera;
}
public Drawable getPicture() {
return Drawable.createFromPath(getPicturePath());
}
public void takePicture() {
camera.takePicture(null, null, pictureCallback);
}
private class SavePhotoRunnable implements Runnable {
byte[] data;
public SavePhotoRunnable(byte[] data) {
this.data = data;
}
public void run() {
savePhoto(data);
}
}
}
| true |
bb9b53d749359511199bb0f329fe7bea93404e56 | Java | mobends/MoBends | /src/main/java/goblinbob/mobends/core/animation/controller/IAnimationController.java | UTF-8 | 519 | 2.34375 | 2 | [
"MIT"
] | permissive | package goblinbob.mobends.core.animation.controller;
import goblinbob.mobends.core.data.EntityData;
import javax.annotation.Nullable;
import java.util.Collection;
/*
* This interface is responsible for updating animation for each
* instance of an AnimatedEntity.
*
* It's a member of an EntityData instance, and it holds all
* the information about the current animation's state.
* */
public interface IAnimationController<T extends EntityData<?>>
{
@Nullable
Collection<String> perform(T entityData);
}
| true |
7961107de6b1a048be16d35bb2362f2449139405 | Java | bewithme/dl4j-zoo-modelx-model | /src/main/java/org/freeware/dl4j/modelx/utils/ExtendedFileUtils.java | UTF-8 | 1,282 | 2.671875 | 3 | [
"Apache-2.0"
] | permissive | package org.freeware.dl4j.modelx.utils;
import org.apache.commons.io.FileUtils;
import java.io.File;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Iterator;
import java.util.List;
public class ExtendedFileUtils extends FileUtils{
public static void makeDirs(String dirs){
File saveDirFile = new File(dirs);
if (!saveDirFile.exists()) {
saveDirFile.mkdirs();
}
}
public static List<String> getFileNameList(File fileDir) {
List<String> fileNameList=new ArrayList<String>();
if(fileDir.isDirectory()){
File[] fileList=fileDir.listFiles();
for(File file:fileList){
fileNameList.add(file.getName());
}
}
return fileNameList;
}
public static List<File> listFiles(String directory,String[] extensions,Boolean recursive) {
File fileDirectory=new File(directory);
Collection<File> fileList=FileUtils.listFiles(fileDirectory, extensions, recursive);
String uselessFilePrefix="._";
Iterator<File> iterator=fileList.iterator();
List<File> retList=new ArrayList<File>();
while(iterator.hasNext()) {
File file=iterator.next();
if(!file.getName().startsWith(uselessFilePrefix)) {
retList.add(file);
}
}
return retList;
}
}
| true |
131237fde4b164387dcef33abd183dafa9fac08c | Java | GuoxinL/spring-boot-demo | /spring-demo-aop/src/main/java/pub/guoxin/aop/aspect/TestAspect.java | UTF-8 | 996 | 2.140625 | 2 | [] | no_license | package pub.guoxin.aop.aspect;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Pointcut;
import org.aspectj.lang.reflect.MethodSignature;
import org.springframework.stereotype.Component;
import pub.guoxin.aop.anno.QueryCache;
import java.lang.reflect.Method;
/**
* Created by guoxin on 17-11-23.
*/
@Aspect
@Component
public class TestAspect {
@Pointcut("@annotation(pub.guoxin.aop.anno.QueryCache)")
public void pointcut(){}
@Around("pointcut()")
public Object interceptor(ProceedingJoinPoint proceedingJoinPoint) throws Throwable {
long beginTime = System.currentTimeMillis();
MethodSignature signature = (MethodSignature) proceedingJoinPoint.getSignature();
Method method = signature.getMethod(); //被拦截方法
String namespace = method.getAnnotation(QueryCache.class).namespace();
return null;
}
}
| true |
f8c19531cf8838538a2dacc9a170cd5832ff6a26 | Java | vexsnare/javaprog | /src/main/java/designpatterns/Singleton/App.java | UTF-8 | 237 | 2.390625 | 2 | [] | no_license | package designpatterns.Singleton;
/**
* Created by vinaysaini on 11/14/16.
*/
public class App {
public static void main(String[] args) {
Singleton singleton = Singleton.getInstance();
singleton.display();
}
}
| true |
7f956597306cdaa81de2ca92693de82e910cb8b4 | Java | zhongxingyu/Seer | /Diff-Raw-Data/2/2_fb9f219bdd47a4ce430abddfbc4ced15e714ca35/PropertiesConfiguration/2_fb9f219bdd47a4ce430abddfbc4ced15e714ca35_PropertiesConfiguration_s.java | UTF-8 | 6,628 | 2.421875 | 2 | [] | no_license | // $Id$
/*
* Copyright 2004 The Apache Software Foundation
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.ftpserver.config;
import java.io.IOException;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.Enumeration;
import java.util.Iterator;
import java.util.Properties;
import org.apache.ftpserver.ftplet.Configuration;
import org.apache.ftpserver.ftplet.FtpException;
/**
* Properties based configuration.
*
* @author <a href="mailto:rana_b@yahoo.com">Rana Bhattacharyya</a>
*/
public
class PropertiesConfiguration implements Configuration {
private Properties prop;
private String prefix = "config.";
/**
* Private constructor - used internally to get configuration subset.
*/
private PropertiesConfiguration() {
}
/**
* Constructor - set the properties input stream.
*/
public PropertiesConfiguration(InputStream in) throws IOException {
// load properties
prop = new Properties();
prop.load(in);
}
/**
* Constructor - set the properties.
*/
public PropertiesConfiguration(Properties prop) {
prop = new Properties(prop);
}
/**
* Is empty?
*/
public boolean isEmpty() {
boolean empty = true;
Enumeration keys = prop.propertyNames();
while(keys.hasMoreElements()) {
String key = (String)keys.nextElement();
if(key.startsWith(prefix)) {
empty = false;
break;
}
}
return empty;
}
/**
* Get string - if not found throws FtpException.
*/
public String getString(String param) throws FtpException {
String val = prop.getProperty(prefix + param);
if(val == null) {
throw new FtpException("Not found : " + param);
}
return val;
}
/**
* Get string - if not found returns the default value.
*/
public String getString(String param, String defaultVal) {
return prop.getProperty(prefix + param, defaultVal);
}
/**
* Get integer - if not found throws FtpException.
*/
public int getInt(String param) throws FtpException {
String val = prop.getProperty(prefix + param);
if(val == null) {
throw new FtpException("Not found : " + param);
}
try {
return Integer.parseInt(val);
}
catch(Exception ex) {
throw new FtpException("PropertiesConfiguration.getInt()", ex);
}
}
/**
* Get int - if not found returns the default value.
*/
public int getInt(String param, int defaultVal) {
int retVal = defaultVal;
try {
retVal = getInt(param);
}
catch(Exception ex) {
}
return retVal;
}
/**
* Get long - if not found throws FtpException.
*/
public long getLong(String param) throws FtpException {
String val = prop.getProperty(prefix + param);
if(val == null) {
throw new FtpException("Not found : " + param);
}
try {
return Long.parseLong(val);
}
catch(Exception ex) {
throw new FtpException("PropertiesConfiguration.getLong()", ex);
}
}
/**
* Get long - if not found returns the default value.
*/
public long getLong(String param, long defaultVal) {
long retVal = defaultVal;
try {
retVal = getLong(param);
}
catch(Exception ex) {
}
return retVal;
}
/**
* Get boolean - if not found throws FtpException.
*/
public boolean getBoolean(String param) throws FtpException {
String val = prop.getProperty(prefix + param);
if(val == null) {
throw new FtpException("Not found : " + param);
}
return val.equalsIgnoreCase("true");
}
/**
* Get boolean - if not found returns the default value.
*/
public boolean getBoolean(String param, boolean defaultVal) {
boolean retVal = defaultVal;
try {
retVal = getBoolean(param);
}
catch(Exception ex) {
}
return retVal;
}
/**
* Get double - if not found throws FtpException.
*/
public double getDouble(String param) throws FtpException {
String val = prop.getProperty(prefix + param);
if(val == null) {
throw new FtpException("Not found : " + param);
}
try {
return Double.parseDouble(val);
}
catch(Exception ex) {
throw new FtpException("PropertiesConfiguration.getDouble()", ex);
}
}
/**
* Get double - if not found returns the default value.
*/
public double getDouble(String param, double defaultVal) {
double retVal = defaultVal;
try {
retVal = getDouble(param);
}
catch(Exception ex) {
}
return retVal;
}
/**
* Get sub configuration.
*/
public Configuration subset(String param) {
PropertiesConfiguration subConfig = new PropertiesConfiguration();
subConfig.prop = prop;
subConfig.prefix = prefix + param + '.';
return subConfig;
}
/**
* Get configuration keys.
*/
public Iterator getKeys() {
ArrayList arr = new ArrayList();
for(Enumeration en = prop.keys(); en.hasMoreElements(); ) {
String key = (String)en.nextElement();
if(!key.startsWith(prefix)) {
continue;
}
key = key.substring(prefix.length());
arr.add(key);
}
return arr.iterator();
}
}
| true |
fb519b5a1303775adb3af56e541811f939cf8a4b | Java | ronsalas/bischeck | /src/main/java/com/ingby/socbox/bischeck/jepext/AverageMad.java | UTF-8 | 4,084 | 2.828125 | 3 | [] | no_license | /*
#
# Copyright (C) 2010-2012 Anders Håål, Ingenjorsbyn AB
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 2 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program. If not, see <http://www.gnu.org/licenses/>.
#
*/
package com.ingby.socbox.bischeck.jepext;
import java.util.*;
import org.nfunk.jep.*;
import org.nfunk.jep.function.PostfixMathCommand;
/**
* Calculating the max value in a array of values
*/
public class AverageMad extends PostfixMathCommand {
private boolean supportNull = false;
/**
* Constructor.
*/
public AverageMad() {
// Use a variable number of arguments
numberOfParameters = -1;
this.supportNull = Util.getSupportNull();
}
public AverageMad(boolean supportNull) {
// Use a variable number of arguments
numberOfParameters = -1;
this.supportNull = supportNull;
}
/**
* Calculate the average value but removing outliers based on Median Absolute
* Deviation with a fixed threshold of 3.0 TODO make the threshold be the
* first parameter in the list or make a smarter analysis of method to use,
* not just MAD, based on the number of data in the set, variance, etc
*
*/
@SuppressWarnings("unchecked")
@Override
public void run(Stack stack) throws ParseException {
checkStack(stack);
if (curNumberOfParameters < 1) {
throw new ParseException(
"No arguments for Average MAD - median average deviation");
}
// Get the first parameter that has to be the threshold
// Double threshold = (Double) stack.pop();
Double threshold = 3.0;
Object param;
ArrayList<Double> orginalValues = new ArrayList<Double>();
int i = 0;
while (i < (curNumberOfParameters)) {
param = stack.pop();
if (!(supportNull && param instanceof Null)) {
orginalValues.add((Double) param);
}
i++;
}
// calculate median
Double median = median(orginalValues);
ArrayList<Double> absMedianValues = new ArrayList<Double>();
// calculate mad by abs(median - value) for each
for (Double value : orginalValues) {
absMedianValues.add(Math.abs(value - median));
}
Double mad = median(absMedianValues);
// select only values in the range of the mad*threshold => removing the
// outliers
int count = 0;
int index = 0;
Double sum = new Double(0);
while (index < absMedianValues.size()) {
if (absMedianValues.get(index) < mad * threshold) {
sum += orginalValues.get(index);
count++;
}
index++;
}
if (index > 0) {
stack.push(sum / count);
} else {
stack.push(new Null());
}
}
private Double median(ArrayList<Double> median1) {
// Calculate the median
Double medianValue = null;
Object[] objectArr = median1.toArray();
Double[] median = Arrays.copyOf(objectArr, objectArr.length,
Double[].class);
// get the numbers into a sorted order
Arrays.sort(median);
if ((median.length & 1) == 0) {
// even number of parameters
medianValue = (median[median.length / 2 - 1] + median[median.length / 2]) / 2;
} else {
// odd number of parameters
medianValue = median[median.length / 2];
}
return medianValue;
}
} | true |
1d4f2d36614b7e529b0937ed1bb5a2221b783d59 | Java | KrasuckiD/antyklegro | /src/main/java/com/controller/UserAccountControllerImpl.java | UTF-8 | 1,474 | 2.34375 | 2 | [] | no_license | package com.controller;
import com.domain.UserAccount;
import com.dto.UserDto;
import com.exeption.IncorrectPasswordOrEmailException;
import com.exeption.UserAlreadyExistException;
import com.service.UserAccountService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;
import java.util.Optional;
@RestController
public class UserAccountControllerImpl implements UserAccountController {
@Autowired
public UserAccountControllerImpl(UserAccountService service) {
this.service = service;
}
private UserAccountService service;
@Override
@RequestMapping(path = "/register", method = RequestMethod.POST)
public ResponseEntity<UserAccount> addUserToDtb
(@RequestBody UserDto userDto) throws UserAlreadyExistException {
return Optional.ofNullable(service.createUser(userDto))
.map(ResponseEntity::ok)
.orElseThrow(UserAlreadyExistException::new);
}
@Override
@RequestMapping(path = "/login", method = RequestMethod.POST)
public ResponseEntity<UserDto> loginUser
(@RequestBody UserDto userDto)
throws IncorrectPasswordOrEmailException {
return Optional.ofNullable(service.getUserByEmailAndPassword(userDto))
.map(ResponseEntity::ok)
.orElseThrow(IncorrectPasswordOrEmailException::new);
}
}
| true |
5654b16279dd5958f5498af8181b86eb5d23dbc2 | Java | rayferric/comet | /comet-core/src/main/java/com/rayferric/comet/core/scenegraph/resource/video/texture/ImageTexture.java | UTF-8 | 3,338 | 2.21875 | 2 | [
"MIT"
] | permissive | package com.rayferric.comet.core.scenegraph.resource.video.texture;
import com.rayferric.comet.core.engine.Engine;
import com.rayferric.comet.core.math.Vector2i;
import com.rayferric.comet.core.video.recipe.texture.Texture2DRecipe;
import com.rayferric.comet.core.util.ResourceLoader;
import com.rayferric.comet.core.video.util.texture.TextureFormat;
import org.lwjgl.system.MemoryStack;
import org.lwjgl.system.MemoryUtil;
import java.nio.Buffer;
import java.nio.ByteBuffer;
import java.nio.FloatBuffer;
import java.nio.IntBuffer;
import static org.lwjgl.stb.STBImage.*;
public class ImageTexture extends Texture {
public ImageTexture(boolean fromJar, String path, boolean filter) {
this.fromJar = fromJar;
this.path = path;
this.filter = filter;
load();
}
@Override
public boolean load() {
if(!super.load()) return false;
Engine.getInstance().getLoaderPool().execute(() -> {
try {
try(MemoryStack stack = MemoryStack.stackPush()) {
IntBuffer widthBuf = stack.mallocInt(1);
IntBuffer heightBuf = stack.mallocInt(1);
IntBuffer channelsBuf = stack.mallocInt(1);
stbi_set_flip_vertically_on_load(true);
ByteBuffer srcData = ResourceLoader.readBinaryFileToNativeBuffer(fromJar, path);
boolean hdr = stbi_is_hdr_from_memory(srcData);
Buffer data;
if(hdr) {
data = stbi_loadf_from_memory(srcData, widthBuf, heightBuf, channelsBuf, 0);
} else {
data = stbi_load_from_memory(srcData, widthBuf, heightBuf, channelsBuf, 0);
}
MemoryUtil.memFree(srcData);
if(data == null)
throw new RuntimeException("Failed to read image file.\n" + path);
Vector2i size = new Vector2i(widthBuf.get(0), heightBuf.get(0));
int channels = channelsBuf.get(0);
TextureFormat format = switch(channels) {
case 1 -> hdr ? TextureFormat.R32F : TextureFormat.R8;
case 2 -> hdr ? TextureFormat.RG32F : TextureFormat.RG8;
case 3 -> hdr ? TextureFormat.RGB32F : TextureFormat.RGB8;
case 4 -> hdr ? TextureFormat.RGBA32F : TextureFormat.RGBA8;
default -> throw new RuntimeException("Texture has more than 4 channels.");
};
Texture2DRecipe recipe = new Texture2DRecipe(() -> {
if(hdr)
stbi_image_free((FloatBuffer)data);
else
stbi_image_free((ByteBuffer)data);
}, data, size, format, filter);
serverHandle.set(Engine.getInstance().getVideoServer().scheduleResourceCreation(recipe));
finishLoading();
}
} catch(Throwable e) {
e.printStackTrace();
System.exit(1);
}
});
return true;
}
private final boolean fromJar;
private final String path;
private final boolean filter;
}
| true |
753eecc7abfdf6a6086c15142cdb28393d46b514 | Java | vip96300/finance-parent | /finance-common/src/main/java/com/rw/finance/common/pass/eynon/MessageDigest.java | UTF-8 | 1,759 | 2.5 | 2 | [] | no_license | package com.rw.finance.common.pass.eynon;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import com.rw.finance.common.pass.eynon.utils.Digest;
public class MessageDigest implements Digest {
private static final Logger log = LoggerFactory.getLogger(MessageDigest.class);
private String algorithm;
private String provider;
public MessageDigest(final String algorithm, final String provider) {
this.algorithm = algorithm;
this.provider = provider;
}
public MessageDigest(final String algorithm) {
this(algorithm, null);
}
public void setProvider(final String provider) {
this.provider = provider;
}
@Override
public byte[] sign(final byte[] bytes) throws Exception {
try {
final java.security.MessageDigest digit = (this.provider == null) ? java.security.MessageDigest.getInstance(this.algorithm) : java.security.MessageDigest.getInstance(this.algorithm, this.provider);
digit.update(bytes);
return digit.digest();
} catch (Exception e) {
throw new Exception("BUILD SIGNATURE FAIL", e);
}
}
@Override
public boolean verify(final byte[] bytes, final byte[] signedArray) {
try {
return isEqual(this.sign(bytes), signedArray);
} catch (Exception e) {
log.error("验证异常:", e);
return false;
}
}
private static boolean isEqual(byte[] digesta, byte[] digestb) {
if (digesta.length != digestb.length) {
return false;
}
int result = 0;
for (int i = 0; i < digesta.length; i++) {
result |= digesta[i] ^ digestb[i];
}
return result == 0;
}
} | true |
2afdc81d5e125b93b5986a72e9a8d5ed598fa03e | Java | luxurymask/recommendation.clustering | /src/clustering/TimeTreeNodeClusteror.java | UTF-8 | 4,201 | 2.640625 | 3 | [] | no_license | package clustering;
import java.io.File;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;
/**
* 子任务划分。
*
* @author liuxl
*/
public class TimeTreeNodeClusteror {
/**
* 探索图根节点。
*/
RCSTNode root;
/**
* RCST节点id-RCST节点Map(所有节点)
*/
Map<String, RCSTNode> idNodeMap = new HashMap<String, RCSTNode>();
/**
* RCST节点id-RCST节点Map(查询节点)
*/
Map<String, RCSTNode> queryIdNodeMap = new HashMap<String, RCSTNode>();
/**
* RCST节点id-RCST节点Map(点击节点)
*/
Map<String, RCSTNode> clickIdNodeMap = new HashMap<String, RCSTNode>();
List<RCSTRelation> parentedRelationList = new ArrayList<RCSTRelation>();
List<RCSTRelation> brotherhoodRelationList = new ArrayList<RCSTRelation>();
public TimeTreeNodeClusteror(String graphMLFilePath) {
File graphMLFile = new File(graphMLFilePath);
initNodes(graphMLFile);
}
/**
* 从graphML中读取所有节点。
*
* @param graphMLFile
* 探索图文件。
* @return 所有节点个数。
*/
private int initNodes(File graphMLFile) {
try {
DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
DocumentBuilder builder = factory.newDocumentBuilder();
Document doc = builder.parse(graphMLFile);
// 读取节点信息。
NodeList nodeList = doc.getElementsByTagName("node");
for (int i = 0; i < nodeList.getLength(); i++) {
Node node = nodeList.item(i);
if (node instanceof Element) {
String nodeType = ((Element) node).getAttribute("type");
RCSTType rcstType = new RCSTType(nodeType);
String nodeId = ((Element) node).getAttribute("id");
long timestamp = Long.parseLong(((Element) node).getAttribute("time"));
String nodeContent;
if(rcstType.isQueryType()){
nodeContent = ((Element) node).getElementsByTagName("queryText").item(0).getTextContent();
queryIdNodeMap.put(nodeId, new RCSTNode(nodeId, rcstType, nodeContent, timestamp));
}else if(rcstType.isClickType()){
nodeContent = ((Element) node).getElementsByTagName("title").item(0).getTextContent();
clickIdNodeMap.put(nodeId, new RCSTNode(nodeId, rcstType, nodeContent, timestamp));
}else{
}
}
}
// 读取边信息。
NodeList edgeList = doc.getElementsByTagName("edge");
for (int i = 0; i < edgeList.getLength(); i++) {
Node edge = edgeList.item(i);
if (edge instanceof Element) {
String sourceId = ((Element) edge).getAttribute("source");
String targetId = ((Element) edge).getAttribute("target");
RCSTNode sourceNode = idNodeMap.get(sourceId);
RCSTNode targetNode = idNodeMap.get(targetId);
targetNode.setFather(sourceNode);
sourceNode.addChild(targetNode);
}
}
} catch (Exception e) {
System.out.println(e);
}
//没啥用,应该删除关系类的设计。
setRelations();
//设置根节点。
root = idNodeMap.get("0");
//递归设置节点宽度。
setSubTreeWidth(root);
return idNodeMap.size();
}
/**
* 设置任意两节点间的RCST关系。
*/
private void setRelations(){
for(Map.Entry<String, RCSTNode> entry1 : idNodeMap.entrySet()){
RCSTNode node1 = entry1.getValue();
for(Map.Entry<String, RCSTNode> entry2 : idNodeMap.entrySet()){
RCSTNode node2 = entry2.getValue();
if(node1 != node2){
RCSTRelation rcstRelation;
if((rcstRelation = new RCSTRelation(node1, node2)).isParentedRelation()){
parentedRelationList.add(rcstRelation);
}else if(rcstRelation.isBrotherhoodRelation()){
brotherhoodRelationList.add(rcstRelation);
}else{
}
}
}
}
}
/**
* 递归设置节点宽度。
* @param root 待设置节点。
*/
private void setSubTreeWidth(RCSTNode root){
//TODO
if(root.childrenList.size() == 0) root.setSubTreeWidth(1);
for(RCSTNode node : root.childrenList){
setSubTreeWidth(node);
}
}
}
| true |
bb97e030ccc9648825f04cd167cbf8573e034579 | Java | Stringxukang/repositoryidea | /day07/src/com/heima_09/Quadrangle.java | UTF-8 | 124 | 1.554688 | 2 | [] | no_license | package com.heima_09;
public class Quadrangle {
public static void draw(Quadrangle q){
//somesentence
}
}
| true |
f16c1f366d923b83e83b7c1351c29236d471e54a | Java | creative-active-technology/entity-service-hrm | /entity-service-hrm/entity-service-hrm/src/main/java/com/inkubator/hrm/dao/impl/PositionDaoImpl.java | UTF-8 | 4,506 | 1.960938 | 2 | [] | no_license | /*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package com.inkubator.hrm.dao.impl;
import com.inkubator.datacore.dao.impl.IDAOImpl;
import com.inkubator.hrm.dao.PositionDao;
import com.inkubator.hrm.entity.Department;
import com.inkubator.hrm.entity.Position;
import com.inkubator.hrm.entity.Position;
import com.inkubator.hrm.web.search.PositionSearchParameter;
import java.util.List;
import org.hibernate.Criteria;
import org.hibernate.FetchMode;
import org.hibernate.criterion.Order;
import org.hibernate.criterion.Projections;
import org.hibernate.criterion.Restrictions;
import org.hibernate.sql.JoinType;
import org.springframework.context.annotation.Lazy;
import org.springframework.stereotype.Repository;
/**
*
* @author Deni Husni FR
*/
@Repository
@Lazy
public class PositionDaoImpl extends IDAOImpl<Position> implements PositionDao {
@Override
public Class<Position> getEntityClass() {
return Position.class;
}
@Override
public List<Position> getByParam(PositionSearchParameter searchParameter, int firstResult, int maxResults, Order order) {
Criteria criteria = getCurrentSession().createCriteria(getEntityClass());
doSearchPositiontByParam(searchParameter, criteria);
criteria.setFetchMode("posBiaya", FetchMode.JOIN);
criteria.setFetchMode("department", FetchMode.JOIN);
criteria.setFetchMode("golonganJabatan", FetchMode.JOIN);
criteria.setFetchMode("educationLevel", FetchMode.JOIN);
criteria.setFetchMode("skJabatan", FetchMode.JOIN);
criteria.setFetchMode("grade", FetchMode.JOIN);
criteria.addOrder(order);
criteria.setFirstResult(firstResult);
criteria.setMaxResults(maxResults);
return criteria.list();
}
@Override
public Long getTotalPositionByParam(PositionSearchParameter searchParameter) {
Criteria criteria = getCurrentSession().createCriteria(getEntityClass());
doSearchPositiontByParam(searchParameter, criteria);
return (Long) criteria.setProjection(Projections.rowCount()).uniqueResult();
}
private void doSearchPositiontByParam(PositionSearchParameter searchParameter, Criteria criteria) {
if (searchParameter.getCostCenterName() != null) {
criteria.add(Restrictions.eq("po.posBiayaName", searchParameter.getCostCenterName()));
}
if (searchParameter.getCostCenterCode() != null || searchParameter.getCostCenterName() != null) {
criteria.createAlias("posBiaya", "po", JoinType.INNER_JOIN);
}
if (searchParameter.getCostCenterCode() != null) {
criteria.add(Restrictions.eq("po.posBiayaCode", searchParameter.getCostCenterCode()));
}
if (searchParameter.getDepartementName() != null) {
criteria.createAlias("department", "d", JoinType.INNER_JOIN);
criteria.add(Restrictions.eq("d.departmentName", searchParameter.getDepartementName()));
}
if (searchParameter.getEducationName() != null) {
criteria.createAlias("educationLevel", "ed", JoinType.INNER_JOIN);
criteria.add(Restrictions.eq("ed.pendidikanLevelName", searchParameter.getEducationName()));
}
if (searchParameter.getNomorSk() != null) {
criteria.createAlias("skJabatan", "sk", JoinType.INNER_JOIN);
criteria.add(Restrictions.eq("sk.skNomor", searchParameter.getNomorSk()));
}
if (searchParameter.getParentCode() != null) {
criteria.add(Restrictions.eq("position.positionCode", searchParameter.getParentCode()));
}
if (searchParameter.getPositionCode() != null) {
criteria.add(Restrictions.eq("positionCode", searchParameter.getPositionCode()));
}
if (searchParameter.getGradeName() != null) {
criteria.createAlias("grade", "gd", JoinType.INNER_JOIN);
criteria.add(Restrictions.eq("gd.gradeName", searchParameter.getGradeName()));
}
if (searchParameter.getGolonganJabatanName() != null) {
criteria.createAlias("golonganJabatan", "gj", JoinType.INNER_JOIN);
criteria.add(Restrictions.eq("gj.golonganJabatanCode", searchParameter.getGolonganJabatanName()));
}
}
}
| true |
1f8368996dffbc02c7b75e99cb3ca8622919c874 | Java | nguyendinhthuan789/LazadaSite | /LzaProject_DataDriven/src/UI_Map/UI_SearchPage.java | UTF-8 | 1,227 | 2.09375 | 2 | [] | no_license | package UI_Map;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.support.FindBy;
import org.openqa.selenium.support.PageFactory;
public class UI_SearchPage {
public UI_SearchPage(WebDriver driver) {
// TODO Auto-generated constructor stub
PageFactory.initElements(driver, this);
}
// Fill textbox search
@FindBy(xpath="//*[@class='c-header-search__input-group-textbox c-header-search__input-group-textbox_search']")
private WebElement TxtSearch;
// Fill icon search
@FindBy(xpath="//*[@class='c-header-search__input-group-button-container']")
private WebElement Search;
//Get Error Search Failed
@FindBy(xpath="")
private WebElement msgErrorFailer;
//Fill Txt Search
public WebElement GetTxtSearch(){
return TxtSearch;
}
public void SetTxtSearch(WebElement TxtSearch){
this.TxtSearch=TxtSearch;
}
//Fill icon Seach
public WebElement getIconSeach(){
return Search;
}
public void setIconSearch(WebElement IconSearch){
this.Search=IconSearch;
}
//Error Search Failed
public WebElement getErrorFailer(){
return msgErrorFailer;
}
public void setErrorFailer(WebElement msgFailer){
this.msgErrorFailer=msgFailer;
}
}
| true |
e8926762c33c7cf8ae78756988154eb49f51d54d | Java | BartoszNowacki/PopularMovies | /app/src/main/java/com/example/rewan/ui/detail/DetailPresenter.java | UTF-8 | 5,582 | 2.046875 | 2 | [] | no_license | package com.example.rewan.ui.detail;
import android.content.IntentFilter;
import android.database.Cursor;
import android.support.annotation.NonNull;
import android.util.Log;
import com.example.rewan.R;
import com.example.rewan.base.BasePresenter;
import com.example.rewan.model.Movie;
import com.example.rewan.model.Review;
import com.example.rewan.model.Video;
import com.example.rewan.network.NetworkHelper;
import com.example.rewan.network.NetworkStateDataListener;
import com.example.rewan.retrofit.DataService;
import com.example.rewan.utils.CallType;
import com.example.rewan.utils.DateConverter;
import com.example.rewan.utils.ImagePathBuilder;
import com.google.gson.Gson;
import com.google.gson.JsonArray;
import com.google.gson.JsonObject;
import com.google.gson.reflect.TypeToken;
import java.lang.reflect.Type;
import java.util.List;
import java.util.Locale;
import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;
class DetailPresenter
extends BasePresenter<DetailContract.View>
implements DetailContract.Presenter<DetailContract.View>, NetworkStateDataListener {
private final String API_KEY;
private NetworkHelper networkHelper;
private DataService dataService;
private String LANG;
private String id;
private final String TAG = "DetailPresenter";
DetailPresenter(DataService dataService, String API_KEY){
Log.d(TAG, "DetailPresenter: ok");
networkHelper = new NetworkHelper(this);
this.dataService = dataService;
this.API_KEY = API_KEY;
LANG = Locale.getDefault().getLanguage();
}
//region get methods
public String getTitle(){
return Movie.MovieTags.MOVIE_TITLE;
}
public String getPosterPath(String endpoint){
ImagePathBuilder imagePathBuilder = new ImagePathBuilder();
return imagePathBuilder.posterPathBuilder(endpoint);
}
String getReleaseYear(String date){
DateConverter dateConverter = new DateConverter();
return dateConverter.convertDate(date);
}
public String getPoster(){
return Movie.MovieTags.MOVIE_POSTER;
}
String getBackdrop(){
return Movie.MovieTags.MOVIE_BACKDROP;
}
public String getPlot(){
return Movie.MovieTags.MOVIE_PLOT;
}
public String getRelease(){
return Movie.MovieTags.MOVIE_RELEASE;
}
public String getVote(){
return Movie.MovieTags.MOVIE_VOTE;
}
String getID(){
return Movie.MovieTags.ID;
}
//end region
void setID(String id){
this.id = id;
}
public void makeCall() {
Call<JsonObject> videosCall = dataService.loadVideos(id, API_KEY);
makeCallWithType(videosCall, CallType.VIDEO);
Call<JsonObject> reviewsCall = dataService.loadReviews(id, API_KEY);
makeCallWithType(reviewsCall, CallType.REVIEW);
}
/**
* Call methods from retrofit interface. It can be used by diffrent types of calls
* @param typeCall
* @param callType
*/
private void makeCallWithType (Call<JsonObject> typeCall, final CallType callType){
typeCall.enqueue(new Callback<JsonObject>() {
@Override
public void onResponse(@NonNull Call<JsonObject> call, @NonNull Response<JsonObject> response) {
if (response.isSuccessful()) {
JsonArray moviesJsonArray = response.body().getAsJsonArray("results");
if (isViewAttached()) {
switch(callType){
case VIDEO:
videosResponse(moviesJsonArray);
break;
case REVIEW:
reviewsResponse(moviesJsonArray);
break;
}
}
} else {
int httpCode = response.code();
view.showErrorMessage(String.valueOf(httpCode));
}
}
@Override
public void onFailure(@NonNull Call<JsonObject> call, @NonNull Throwable t) {
view.showErrorMessage(t.getMessage());
}
});
}
/**
* Convert response from network service and sets adapter. Used for videos data
* @param videosJsonArray
*/
private void videosResponse(JsonArray videosJsonArray){
Gson gson = new Gson();
Type listType = new TypeToken<List<Video>>() {
}.getType();
view.setVideosAdapter((List<Video>) gson.fromJson(videosJsonArray, listType));
}
/**
* Convert response from network service and sets adapter. Used for reviews data
* @param reviewsJsonArray
*/
private void reviewsResponse(JsonArray reviewsJsonArray){
Gson gson = new Gson();
Type listType = new TypeToken<List<Review>>() {
}.getType();
view.setReviewsAdapter((List<Review>) gson.fromJson(reviewsJsonArray, listType));
}
IntentFilter getIntentFilter() {
return networkHelper.getIntentFilter();
}
NetworkHelper getReceiver() {
return networkHelper;
}
/**
* Convert string vote to float and its is divided by 2. This number is converted for RatingBar reason
* @param vote
*/
public float convertToFloat(String vote){
return Float.parseFloat(vote)/2;
}
@Override
public void sendNetworkAvailableMessage() {
view.showMessage(R.string.network_available);
}
}
| true |
3711ea229c4cd32de907cfe49f40b916bb088ae6 | Java | fuzhen5/dsAlgo | /src/main/java/com/gbase/dsAlgo/sort/QuickSort3Ways.java | UTF-8 | 1,545 | 3.5 | 4 | [] | no_license | package com.gbase.dsAlgo.sort;
import java.util.Random;
import com.gbase.dsAlgo.util.SortUtil;
/**
* 三路快速排序
* @author wangf
*
*/
public class QuickSort3Ways {
public static void main(String[] args) {
int n = 1000000;
Integer[] arr = SortUtil.generateRandomArray(n, 0, 100);
Integer[] arr1 = arr.clone();
SortUtil.testSort(QuickSort3Ways.class, "quickSort3Ways", arr, arr.length);
SortUtil.testSort(QuickSort2.class, "quickSort2", arr1, arr1.length);
}
public static<T extends Comparable<T>> void quickSort3Ways(T[] arr, int n) {
quickSort3Ways(arr, 0, n-1);
}
/**
* 对数组 arr[l...r] 进行3路快速排序
* 将 arr[l...r]分为 <v ; ==v; >v 三部分
* 之后递归对 <v ; >v 两部分继续进行三路快速排序
*
* @param arr
* @param i
* @param j
*/
private static<T extends Comparable<T>> void quickSort3Ways(T[] arr, int l, int r) {
if (r - l <= 15) {
InsertionSort.optimizedInsertionSort(arr, l, r);
return;
}
// partition
int index = new Random().nextInt(r - l + 1) + l;
SortUtil.swap(arr, l, index);
T v = arr[l];
int lt = l; // arr[l+1...lt] < v
int gt = r+1; // arr[gt,r] > v
int i = l + 1;// arr[lt+1,i) == v
while( i < gt) {
if(arr[i].compareTo(v) < 0) {
SortUtil.swap(arr, i, lt+1);
lt++;
i++;
} else if(arr[i].compareTo(v) == 0) {
i++;
} else {
SortUtil.swap(arr,gt-1,i);
gt--;
}
}
SortUtil.swap(arr, l, lt);
lt --;
quickSort3Ways(arr, l, lt);
quickSort3Ways(arr, gt, r);
}
}
| true |
38068e0192c7e066ce1448204837df2bd0b50b5a | Java | 497022407/Haoyu-Wang-s-university-assignments-Svn-repository- | /fcs/week-03/practical-03/Problem05/Problem05.java | UTF-8 | 1,590 | 3.71875 | 4 | [] | no_license | // student ID: a1785394
// student name: Haoyu Wang
// calculate determinant of matrix
import java.util.*;
public class Problem05{ //declare calss
public static void main(String[] args){ //declare function main
int dimension, result = 0; //declare int variable
// create Scanner object
Scanner input = new Scanner(System.in);
//print prompt message
System.out.println("please input dimension: ");
//get input of dimension
dimension = input.nextInt();
//create array
int[][] matrix = new int[dimension][dimension];
//get input of matrix
if(dimension == 2 || dimension == 3){
for(int i = 0; i < dimension; ++i){
for(int j = 0; j < dimension; ++j){
System.out.print("please input [" + (i + 1) + ']' + '[' + (j + 1) + "]: ");
matrix[i][j] = input.nextInt();
System.out.println();
}
}
}else{ //if dimension inputed is unaccaptable, print information
System.out.println("The dimension is unacceptable");
}
if(dimension == 2){ // if the dimension is 2, calculate determinant of 2x2
result = matrix[0][0] * matrix[1][1] - matrix[0][1] * matrix[1][0];
}
else if(dimension == 3){ // if the dimension is 3, calculate determinant of 3x3
result = matrix[0][0] * matrix[1][1] * matrix[2][2] + matrix[0][1] * matrix[1][2] * matrix[2][0] + matrix[0][2] * matrix[1][0] * matrix[2][1] - matrix[0][2] * matrix[1][1] * matrix[2][0] - matrix[0][1] * matrix[1][0] * matrix[2][2] - matrix[0][0] * matrix[1][2] * matrix[2][1];
}
// print the determinant of the matrix
System.out.println("Determinant: " + result);
}
} | true |
e3eff672e0c4892cebf7d5aadc5571cf1020ebff | Java | s2iwi2s/fasttrackd-student-work | /spring-assessment-social-media-optimize-prime/src/main/java/com/cooksys/assessment/socialmedia/mappers/UserMapper.java | UTF-8 | 879 | 2.046875 | 2 | [] | no_license | package com.cooksys.assessment.socialmedia.mappers;
import java.util.Set;
import org.mapstruct.Mapper;
import org.mapstruct.Mapping;
import com.cooksys.assessment.socialmedia.dtos.ProfileDto;
import com.cooksys.assessment.socialmedia.dtos.UserRequestDto;
import com.cooksys.assessment.socialmedia.dtos.UserResponseDto;
import com.cooksys.assessment.socialmedia.entities.Profile;
import com.cooksys.assessment.socialmedia.entities.User;
@Mapper(componentModel = "spring")
public interface UserMapper {
public User requestDtoToEntity(UserRequestDto userDto);
@Mapping(source = "credentials.username", target = "username")
public UserResponseDto entityToResponsetDto(User user);
@Mapping(source = "credentials.username", target = "username")
public Set<UserResponseDto> entitiesToResponseDtos(Set<User> users);
public Profile profiletoToEntity(ProfileDto userDto);
}
| true |
7bb9130cf30bf008cef5e7ddba142e3bfa9e6470 | Java | luocaca/TestGitHub | /app/src/main/java/net/fengg/app/lcb/adapter/ProductAdapter.java | UTF-8 | 5,349 | 2.109375 | 2 | [] | no_license | package net.fengg.app.lcb.adapter;
import java.util.ArrayList;
import java.util.List;
import android.text.TextUtils;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.EditText;
import android.widget.LinearLayout;
import android.widget.TextView;
import com.hldj.hmyg.DActivity2;
import com.hldj.hmyg.R;
import com.hldj.hmyg.bean.Product;
import com.hy.utils.ValueGetInfo;
public class ProductAdapter extends BaseAdapter {
private final List<Boolean> selected = new ArrayList<Boolean>();
private LayoutInflater inflater;
private List<Product> list;
StoreAdapter adapter;
int storePosition;
DActivity2 context;
public ProductAdapter(DActivity2 context, List<Product> list,
StoreAdapter adapter, int storePosition) {
this.inflater = LayoutInflater.from(context);
this.list = list;
this.adapter = adapter;
this.storePosition = storePosition;
this.context = context;
for (int j = 0; j < list.size(); j++) {
getSelect().add(false);
}
}
public List<Boolean> getSelect() {
return selected;
}
@Override
public View getView(final int position, View convertView, ViewGroup parent) {
ViewHolder holder = null;
if (convertView == null) {
convertView = inflater.inflate(R.layout.product_item, null);
holder = new ViewHolder();
holder.cb_select = (CheckBox) convertView
.findViewById(R.id.cb_select);
holder.tv_content = (TextView) convertView
.findViewById(R.id.tv_content);
holder.tv_price = (TextView) convertView
.findViewById(R.id.tv_price);
holder.ll_quantity = (LinearLayout) convertView
.findViewById(R.id.ll_quantity);
holder.tv_quantity = (TextView) convertView
.findViewById(R.id.tv_quantity);
holder.btn_edit = (Button) convertView.findViewById(R.id.btn_edit);
holder.ll_edit_quantity = (LinearLayout) convertView
.findViewById(R.id.ll_edit_quantity);
holder.btn_decrease = (Button) convertView
.findViewById(R.id.btn_decrease);
holder.btn_increase = (Button) convertView
.findViewById(R.id.btn_increase);
holder.et_quantity = (EditText) convertView
.findViewById(R.id.et_quantity);
holder.btn_done = (Button) convertView.findViewById(R.id.btn_done);
convertView.setTag(holder);
} else {
holder = (ViewHolder) convertView.getTag();
}
final EditText et_quantity = holder.et_quantity;
final TextView tv_quantity = holder.tv_quantity;
final LinearLayout l_quantity = holder.ll_quantity;
final LinearLayout le_quantity = holder.ll_edit_quantity;
final Product product = list.get(position);
holder.tv_content.setText(product.getCount() + "");
holder.tv_price.setText(ValueGetInfo.doubleTrans1(product.getPrice()) + "");
holder.btn_edit.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
l_quantity.setVisibility(View.GONE);
le_quantity.setVisibility(View.VISIBLE);
}
});
holder.btn_done.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
l_quantity.setVisibility(View.VISIBLE);
le_quantity.setVisibility(View.GONE);
product.setCount(Integer.parseInt(et_quantity.getText()
.toString()));
tv_quantity.setText(et_quantity.getText().toString());
context.updateAmount();
}
});
holder.et_quantity.setText(product.getCount() + "");
holder.tv_quantity.setText(product.getCount() + "");
holder.cb_select.setChecked(selected.get(position));
holder.cb_select.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
selected.set(position, !selected.get(position));
if (selected.contains(false)) {
adapter.getSelect().set(storePosition, false);
} else {
adapter.getSelect().set(storePosition, true);
}
if (adapter.getSelect().contains(false)) {
context.checkAll(false);
} else {
context.checkAll(true);
}
context.updateAmount();
adapter.notifyDataSetChanged();
}
});
holder.btn_decrease.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
if (!(TextUtils.isEmpty(et_quantity.getText().toString()) || "1"
.equals(et_quantity.getText().toString()))) {
et_quantity.setText(Integer.parseInt(et_quantity.getText()
.toString()) - 1 + "");
}
}
});
holder.btn_increase.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
if (TextUtils.isEmpty(et_quantity.getText().toString())) {
et_quantity.setText("1");
} else {
et_quantity.setText(Integer.parseInt(et_quantity.getText()
.toString()) + 1 + "");
}
}
});
return convertView;
}
@Override
public int getCount() {
return list.size();
}
@Override
public Object getItem(int position) {
return list.get(position);
}
@Override
public long getItemId(int position) {
return position;
}
public class ViewHolder {
CheckBox cb_select;
TextView tv_content;
TextView tv_price;
LinearLayout ll_quantity;
TextView tv_quantity;
Button btn_edit;
LinearLayout ll_edit_quantity;
EditText et_quantity;
Button btn_decrease;
Button btn_increase;
Button btn_done;
}
}
| true |
e5d9dab54e8806d054ca2c4fdd1968ce06d88bfd | Java | youyuge34/ACM_Personal_Training | /2-2/src/hanxin.java | UTF-8 | 609 | 2.9375 | 3 | [] | no_license | import java.io.FileInputStream;
import java.util.Scanner;
public class hanxin {
public static void main(String[] args) {
int count=0;
int i;
Scanner in=new Scanner(System.in);
try{in=new Scanner(new FileInputStream("data.in"));}catch(Exception e){}
while (in.hasNext()){
int a = in.nextInt();
int b = in.nextInt();
int c = in.nextInt();
for(i=10;i<101;i++){
if((i%3==a)&&(i%5==b)&&(i%7)==c ){
break;
}
}
count++;
if(i==101){
System.out.println("Case "+count+": No answer");
}
else{
System.out.println("Case "+count+": "+i);
}
}
in.close();
}}
| true |
2abddfb990ca8e8ee6ca696f80dfdc1384fe8d01 | Java | cz67998/datastructure | /src/main/java/com/wangzhou/datastructure/stack/solution/LetterSolution.java | UTF-8 | 2,048 | 3.625 | 4 | [] | no_license | package com.wangzhou.datastructure.stack.solution;
import com.wangzhou.datastructure.stack.ArrayStack;
import java.util.Objects;
import java.util.Stack;
/**
* Created by IDEA
* author:wangzhou
* Date:2019/4/15
* Time:8:59
**/
public class LetterSolution {
private Stack stack;
public boolean isVaild(String s) {
ArrayStack stack = new ArrayStack();
for(int i = 0 ; i < s.length() ; i ++){
char c = s.charAt(i);
if(c == '(' || c == '[' || c == '{')
stack.push(c);
else{
if(stack.isEmpty())
return false;
char topChar = (char)stack.pop();
if(c == ')' && topChar != '(')
return false;
if(c == ']' && topChar != '[')
return false;
if(c == '}' && topChar != '{')
return false;
}
}
return stack.isEmpty();
}
@Override
public int hashCode() {
return Objects.hash(this.stack);
}
@Override
public boolean equals(Object obj) {
if (this == obj) {
return true;
}
if (obj == null) {
return false;
}
if (getClass() != obj.getClass()) {
return false;
}
LetterSolution letterSolution = (LetterSolution) obj;
return Objects.equals(this.stack, ((LetterSolution) obj).stack);
}
public static void main(String[] args) {
System.out.println(new LetterSolution().isVaild("(("));
// System.out.println(new LetterSolution().isVaild("([)]"));
ArrayStack stack = new ArrayStack();
stack.push("a");
stack.push("b");
System.out.println(stack.toString());
System.out.println(stack.pop());
System.out.println(stack.pop());
System.out.println(new Integer(1).equals(new Integer(1)));
System.out.println(new Integer(1) == new Integer(1));
System.out.println(1 == 1);
}
}
| true |
01567b0d68ce731e42f9a7101b0173352b52a6d4 | Java | mengtiancheng/zot-team-jxing | /src/com/zot/xing/dao/subscribe/WorkOrderAS.java | UTF-8 | 1,603 | 2.234375 | 2 | [] | no_license | /**
* 服务预定接口
*/
package com.zot.xing.dao.subscribe;
import java.util.Date;
import java.util.List;
/**
* @author jack
*
*/
public interface WorkOrderAS {
/**
* 增加一个 新订单
* @param workOrder
*/
public void addPreSubscribeService(XingWorkOrderBO workOrder);
/**
* 订单状态变更为服务中
*/
public void updateWorkOrderToGoing(XingWorkOrderBO workOrder);
/**
* 订单状态变更为结束
*/
public void updateWorkOrderToOver(XingWorkOrderBO workOrder);
/**
* 根据订单号,修改评价类型和评价内容
* @param id
* @param evalType 评价类型
* @param evalDesc 评价内容
*/
public void updateWorkOrderEval(String id,String evalType,String evalDesc);
/**
* 更新投诉处理结果
* @param id
* @param evalResult
*/
public void updateWorkOrderEvalResult(String id,String evalResult);
/**
* 根据客户Id查询客户订单信息,查询此客户的所有订单
* @param cusId 客户ID
* @return
*/
public List<XingWorkOrderBO> queryWorkOrderByCusID(String cusId);
/**
* 根据用户ID查询客户服务信息,时间默认为当天
* @param cusId 客户ID
* @param beginTime 开始时间
* @param endTime 结束时间
* @return
*/
public List<XingWorkOrderBO> queryWorkOrderByCusID(String cusId,Date beginTime,Date endTime);
/**
* 根据用户ID查询客户正在服务的订单
* @param cusId 客户ID
* @return
*/
public List<XingWorkOrderBO> queryGoingWorkOrderByCusID(String cusId);
}
| true |
6d41290af664021870846858ee3ede0441c43426 | Java | antoniovazquezaraujo/AEDI | /AED1y2/src/aed1/ejercicios/ContarIntervalos.java | UTF-8 | 1,143 | 3.84375 | 4 | [] | no_license | package aed1.ejercicios;
public class ContarIntervalos {
public static int menoresA(int min, int datos[]) {
for (int n = 0; n < datos.length; n++) {
if (datos[n] >= min) {
return n;
}
}
return datos.length;
}
public static int mayoresA(int max, int datos[]) {
for (int n = 0; n < datos.length; n++) {
if (datos[n] > max) {
return datos.length - n;
}
}
return 0;
}
public static int entreIntervalo(int desde, int hasta, int datos[]) {
return datos.length - menoresA(desde, datos) - mayoresA(hasta, datos);
}
public static void main(String[] args) {
/*
* int datos[] = new int[1000]; for (int n = 0; n < 1000; n++) {
* datos[n] = (n / 10) % 100; System.out.println(n+ ":" + datos[n] +
* ", "); }
*/
int datos[] = new int[10];
datos[0] = 1;
datos[1] = 1;
datos[2] = 1;
datos[3] = 2;
datos[4] = 2;
datos[5] = 3;
datos[6] = 4;
datos[7] = 4;
datos[8] = 5;
datos[9] = 6;
assert (menoresA(2, datos) == 3);
assert (mayoresA(4, datos) == 2);
assert (entreIntervalo(2, 4, datos) == 5);
System.out.println("Ok");
}
}
| true |
95f51b1cb351adb13bc207002ec61a10797bfcb6 | Java | ZoneMo/com.tencent.mm | /src/com/tencent/mm/app/plugin/URISpanHandlerSet$EmotionStoreUriSpanHandler.java | UTF-8 | 1,622 | 1.539063 | 2 | [] | no_license | package com.tencent.mm.app.plugin;
import android.content.Intent;
import android.os.Bundle;
import com.tencent.mm.aj.c;
import com.tencent.mm.pluginsdk.n;
import com.tencent.mm.pluginsdk.ui.applet.ah;
import com.tencent.mm.pluginsdk.ui.d.f;
@URISpanHandlerSet.a
class URISpanHandlerSet$EmotionStoreUriSpanHandler
extends URISpanHandlerSet.BaseUriSpanHandler
{
URISpanHandlerSet$EmotionStoreUriSpanHandler(URISpanHandlerSet paramURISpanHandlerSet)
{
super(paramURISpanHandlerSet);
}
final boolean a(ah paramah, f paramf)
{
if (type == 29)
{
if (paramf != null) {
paramf.a(paramah);
}
paramf = new Intent();
paramf.putExtra("entrance_scence", 3);
paramf.putExtra("extra_id", (String)paramah.c(String.class));
paramf.putExtra("preceding_scence", 3);
c.c(URISpanHandlerSet.a(apd), "emoji", ".ui.EmojiStoreDetailUI", paramf);
return true;
}
return false;
}
final boolean a(String paramString, boolean paramBoolean, n paramn, Bundle paramBundle)
{
return false;
}
final ah aZ(String paramString)
{
if (paramString.trim().startsWith("weixin://emoticonstore/"))
{
int i = paramString.lastIndexOf("/");
String str = "";
if (i != -1) {
str = paramString.substring(i + 1);
}
return new ah(paramString, 29, str);
}
return null;
}
final int[] lL()
{
return new int[] { 29 };
}
}
/* Location:
* Qualified Name: com.tencent.mm.app.plugin.URISpanHandlerSet.EmotionStoreUriSpanHandler
* Java Class Version: 6 (50.0)
* JD-Core Version: 0.7.1
*/ | true |
23073ccfeba0c16509fc21d8e979b3475d7bf0b7 | Java | CunDeveloper/AlumniGroupService | /school-friend-service-webapp/src/main/java/com/nju/edu/cn/software/domain/AlumniQuestion.java | UTF-8 | 1,880 | 2.265625 | 2 | [] | no_license | package com.nju.edu.cn.software.domain;
import java.util.ArrayList;
import java.util.List;
import com.fasterxml.jackson.annotation.JsonIgnore;
import com.nju.edu.cn.software.entity.AuthorInfo;
public class AlumniQuestion extends BaseEntity {
private String problem;
private String description;
private String imgPaths;
private AuthorInfo author;
private int replayCount;
private boolean isSolved;
private int whoScan;
private String label;
@JsonIgnore
private List<String> images = new ArrayList<>();
public String getProblem() {
return problem;
}
public void setProblem(String problem) {
this.problem = problem;
}
public String getDescription() {
return description;
}
public void setDescription(String description) {
this.description = description;
}
public String getImgPaths() {
return imgPaths;
}
public void setImgPaths() {
StringBuilder builder = new StringBuilder();
for(String path:images){
builder.append(path);
builder.append(",");
}
if(builder.length()>0){
builder.deleteCharAt(builder.length()-1);
}
this.imgPaths = builder.toString();
}
public AuthorInfo getAuthor() {
return author;
}
public void setAuthor(AuthorInfo author) {
this.author = author;
}
public int getReplayCount() {
return replayCount;
}
public void setReplayCount(int replayCount) {
this.replayCount = replayCount;
}
public boolean isSolved() {
return isSolved;
}
public void setSolved(boolean isSolved) {
this.isSolved = isSolved;
}
public int getWhoScan() {
return whoScan;
}
public void setWhoScan(int whoScan) {
this.whoScan = whoScan;
}
public List<String> getImages() {
return images;
}
public void setImages(List<String> images) {
this.images = images;
setImgPaths();
}
public String getLabel() {
return label;
}
public void setLabel(String label) {
this.label = label;
}
}
| true |
92473a5e2b9c134a48ec8dcf2dae74cbb91d4129 | Java | Supzle/lab3_1 | /TestSystem/src/Control/Display.java | UTF-8 | 1,417 | 2.859375 | 3 | [] | no_license | package Control;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.*;
import View.ComandView;
public class Display {
ComandView CV;
Frame frame=new Frame("display");
JButton[] btn = new JButton[13];
void clsvis(int s, int t) {
for (int i = s; i < t; i ++)
btn[i].setVisible(false);
}
public Display(ComandView cv) {
CV = cv;
btn[0] =new JButton("Create a new Survey");
btn[1] =new JButton("Create a new Test");
btn[2] =new JButton("Display Survey");
btn[3] =new JButton("Display a Test");
btn[4] =new JButton("Save a Survey");
btn[5] =new JButton("Save a Test");
btn[6] =new JButton("Modify a Survey");
btn[7] =new JButton("Modify a Test");
btn[8] =new JButton("Take a Survey");
btn[9] =new JButton("Take a Test");
btn[10] =new JButton("Look survey outcome");
btn[11] =new JButton("Look test outcome");
btn[12] =new JButton("Quit");
for (int i = 0; i < 13;i ++) {
frame.add(btn[i]);
btn[i].setVisible(false);
final int j=i;
btn[i].addActionListener(new ActionListener(){
public void actionPerformed(ActionEvent e) {
CV.action_choose(j);
clsvis(0,13);
}
});
}
frame.setLayout(new FlowLayout());
frame.setSize(500,400);
frame.setVisible(true);
}
public void printFirstMenu() {
for (int i = 0; i < 13;i ++) {
btn[i].setVisible(true);
}
}
}
| true |
9b27a6445ac47378c564baafef34170baec0a072 | Java | yangyuqi/android_hxd | /app/src/main/java/com/zhejiang/haoxiadan/model/requestData/in/LuceneListData.java | UTF-8 | 3,714 | 1.796875 | 2 | [] | no_license | package com.zhejiang.haoxiadan.model.requestData.in;
/**
* Created by KK on 2017/9/13.
*/
public class LuceneListData {
private long vo_id;// 是 String
private String vo_title;// 是 String
private String vo_type;// 搜索属性 否 String
private String vo_storeId;// 商家ID 否 String
private int vo_goods_salenum;// 商品销量 否 String
private double vo_store_price;// 商品价格 否 String
private String vo_main_photo_url;// 商品图片路径 否 String
private int vo_goods_collect;// 商品收藏数 否 String
private int monthlySales;// 月销量 否 String
private String storeArea;// 否 String
private String mainIndustry;// 否 String
private String mainProducts;// 否 String
private String yearSales;// 否 String
private int salesVolume;// 否 String
private String goodsLuceneList;// 否 String
private String goods_numType ;
public String getGoods_numType() {
return goods_numType;
}
public long getVo_id() {
return vo_id;
}
public void setVo_id(long vo_id) {
this.vo_id = vo_id;
}
public void setGoods_numType(String goods_numType) {
this.goods_numType = goods_numType;
}
public String getVo_title() {
return vo_title;
}
public void setVo_title(String vo_title) {
this.vo_title = vo_title;
}
public String getVo_type() {
return vo_type;
}
public void setVo_type(String vo_type) {
this.vo_type = vo_type;
}
public String getVo_storeId() {
return vo_storeId;
}
public void setVo_storeId(String vo_storeId) {
this.vo_storeId = vo_storeId;
}
public int getVo_goods_salenum() {
return vo_goods_salenum;
}
public void setVo_goods_salenum(int vo_goods_salenum) {
this.vo_goods_salenum = vo_goods_salenum;
}
public double getVo_store_price() {
return vo_store_price;
}
public void setVo_store_price(double vo_store_price) {
this.vo_store_price = vo_store_price;
}
public String getVo_main_photo_url() {
return vo_main_photo_url;
}
public void setVo_main_photo_url(String vo_main_photo_url) {
this.vo_main_photo_url = vo_main_photo_url;
}
public int getVo_goods_collect() {
return vo_goods_collect;
}
public void setVo_goods_collect(int vo_goods_collect) {
this.vo_goods_collect = vo_goods_collect;
}
public int getMonthlySales() {
return monthlySales;
}
public void setMonthlySales(int monthlySales) {
this.monthlySales = monthlySales;
}
public String getStoreArea() {
return storeArea;
}
public void setStoreArea(String storeArea) {
this.storeArea = storeArea;
}
public String getMainIndustry() {
return mainIndustry;
}
public void setMainIndustry(String mainIndustry) {
this.mainIndustry = mainIndustry;
}
public String getMainProducts() {
return mainProducts;
}
public void setMainProducts(String mainProducts) {
this.mainProducts = mainProducts;
}
public String getYearSales() {
return yearSales;
}
public void setYearSales(String yearSales) {
this.yearSales = yearSales;
}
public int getSalesVolume() {
return salesVolume;
}
public void setSalesVolume(int salesVolume) {
this.salesVolume = salesVolume;
}
public String getGoodsLuceneList() {
return goodsLuceneList;
}
public void setGoodsLuceneList(String goodsLuceneList) {
this.goodsLuceneList = goodsLuceneList;
}
}
| true |
6b3cf79e9d7ef566ba5c6eca919cd047a873f2d5 | Java | REBOOTERS/DoraemonKit | /Android/java/doraemonkit/src/main/java/com/didichuxing/doraemonkit/widget/tableview/format/FastTextDrawFormat.java | UTF-8 | 1,929 | 2.421875 | 2 | [
"Apache-2.0"
] | permissive | package com.didichuxing.doraemonkit.widget.tableview.format;
import android.graphics.Canvas;
import android.graphics.Paint;
import android.graphics.Rect;
import com.didichuxing.doraemonkit.widget.tableview.bean.Column;
import com.didichuxing.doraemonkit.widget.tableview.utils.DrawUtils;
import com.didichuxing.doraemonkit.widget.tableview.TableConfig;
import java.util.HashMap;
public class FastTextDrawFormat<T> extends TextDrawFormat<T> {
private String HEIGHT_KEY = "dk_height";
private HashMap<String, Integer> cacheMap = new HashMap<>();
@Override
public int measureWidth(Column<T> column, int position) {
int width = 0;
String value = column.format(position);
Integer maxLengthValue = cacheMap.get(column.getColumnName());
if (maxLengthValue == null) {
width = comperLength(column, value);
} else if (value.length() > maxLengthValue) {
width = comperLength(column, value);
}
return width;
}
private int comperLength(Column<T> column, String value) {
TableConfig config = TableConfig.getInstance();
Paint paint = config.getPaint();
config.contentStyle.fillPaint(paint);
cacheMap.put(column.getColumnName(), value.length());
return (int) paint.measureText(value);
}
@Override
public int measureHeight(Column<T> column, int position) {
int height;
if (cacheMap.get(HEIGHT_KEY) == null) {
TableConfig config = TableConfig.getInstance();
Paint paint = config.getPaint();
config.contentStyle.fillPaint(paint);
cacheMap.put(HEIGHT_KEY, DrawUtils.getTextHeight(paint));
}
height = cacheMap.get(HEIGHT_KEY);
return height;
}
protected void drawText(Canvas c, String value, Rect rect, Paint paint) {
DrawUtils.drawSingleText(c, paint, rect, value);
}
}
| true |