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 |
|---|---|---|---|---|---|---|---|---|---|---|---|
0dd5a76fd5bace7fcf8f09bcf34252cd43fd1801
|
Java
|
OscarNorman/OneVsOne
|
/src/main/java/io/github/OscarNorman/OneVsOne/OneVsOne.java
|
UTF-8
| 13,304
| 1.929688
| 2
|
[] |
no_license
|
package io.github.OscarNorman.OneVsOne;
import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.logging.Logger;
import net.milkbowl.vault.economy.Economy;
import org.bukkit.Bukkit;
import org.bukkit.ChatColor;
import org.bukkit.GameMode;
import org.bukkit.Location;
import org.bukkit.Material;
import org.bukkit.command.Command;
import org.bukkit.command.CommandSender;
import org.bukkit.configuration.file.FileConfiguration;
import org.bukkit.configuration.file.FileConfigurationOptions;
import org.bukkit.entity.Entity;
import org.bukkit.entity.Player;
import org.bukkit.event.EventHandler;
import org.bukkit.event.Listener;
import org.bukkit.event.entity.EntityDamageByEntityEvent;
import org.bukkit.event.entity.PlayerDeathEvent;
import org.bukkit.inventory.ItemStack;
import org.bukkit.inventory.PlayerInventory;
import org.bukkit.metadata.FixedMetadataValue;
import org.bukkit.metadata.Metadatable;
import org.bukkit.plugin.Plugin;
import org.bukkit.plugin.PluginManager;
import org.bukkit.plugin.RegisteredServiceProvider;
import org.bukkit.plugin.java.JavaPlugin;
public class OneVsOne extends JavaPlugin implements Listener{
private ArrayList<Game> pendingGames = new ArrayList<Game>();
private ArrayList<Game> activeGames = new ArrayList<Game>();
private ArrayList<Game> inProgressGames = new ArrayList<Game>();
private ArrayList<Game> challengedGames = new ArrayList<Game>();
public ArrayList<Location> startPoints = new ArrayList<Location>();
public static Economy econ = null;
private static final Logger log = Logger.getLogger("Minecraft");
@EventHandler
public void damageListener(EntityDamageByEntityEvent e){
if(e.getDamager() instanceof Player){
Player en = (Player) e.getDamager();
Player p = (Player) e.getEntity();
for(Game g:activeGames){
if((g.challenged==p||g.challenger==p)||(g.challenged==en||g.challenger==en)){
e.setCancelled(true);
}
}
}
}
@EventHandler
public void deathListener(PlayerDeathEvent e){
for(Game g:activeGames){
if((g.challenged==e.getEntity())){
g.challenged.teleport((Location) g.challenger.getMetadata("oldlocation"));
g.challenger.teleport((Location) g.challenger.getMetadata("oldlocation"));
g.winner=g.challenger;
endGame(g);
}
if((g.challenger==e.getEntity())){
g.challenged.teleport((Location) g.challenged.getMetadata("oldlocation"));
g.challenger.teleport((Location) g.challenger.getMetadata("oldlocation"));
g.winner=g.challenged;
endGame(g);
}
}
}
@Override
public void onEnable() {
PluginManager manager = getServer().getPluginManager();
manager.registerEvents(this, this);
if (!testForVault() ) {
log.severe(String.format("[%s] - No Vault Found!", getDescription().getName()));
return;
}
if (!setupEconomy() ) {
log.severe(String.format("[%s] - Vault Found, But No Economy Plugin! Monatary Rewards Will Not Work!", getDescription().getName()));
return;
}
this.saveDefaultConfig();
FileConfiguration config = this.getConfig();
Integer i = 1;
while(config.contains("arenalocations."+i)){
Location l = (Location) config.get("arenalocations."+i);
startPoints.add(l);
i+=1;
}
}
@Override
public void onDisable() {
// TODO Insert logic to be performed when the plugin is disabled
}
@Override
public boolean onCommand(CommandSender sender, Command cmd, String label, String[] args) {
if (Bukkit.getServer().getConsoleSender() == sender) {
sender.sendMessage("This command can only be run by a player.");
return true;
}
if (cmd.getName().equalsIgnoreCase("onevsone")) {
if(args.length>0){
if(args[0].equals("help")){
sender.sendMessage(ChatColor.DARK_GREEN+"+===---===---===OneVsOne===---===---===+");
sender.sendMessage(ChatColor.YELLOW+"This is the help for the OneVsOne Plugin");
sender.sendMessage(ChatColor.YELLOW+"Use "+ChatColor.DARK_GREEN+"/onevsone help"+ChatColor.YELLOW+" For This Help Message");
sender.sendMessage(ChatColor.YELLOW+"Use "+ChatColor.DARK_GREEN+"/onevsone <PlayerName>"+ChatColor.YELLOW+" To Challenge A Player To A 1v1");
sender.sendMessage(ChatColor.YELLOW+"Use "+ChatColor.DARK_GREEN+"/onevsone accept"+ChatColor.YELLOW+" To Accept A Challenge");
sender.sendMessage(ChatColor.YELLOW+"Use "+ChatColor.DARK_GREEN+"/onevsone deny"+ChatColor.YELLOW+" To Deny A Challenge");
sender.sendMessage(ChatColor.YELLOW+"Use "+ChatColor.DARK_GREEN+"/onevsone setlocation"+ChatColor.YELLOW+" To Set A 1v1 Spawn Point (This Is Usually Ops Only!)");
sender.sendMessage(ChatColor.DARK_GREEN+"+===---===---===--+==+--===---===---===+");
}
if(args[0].equals("accept")){
for(Game g:challengedGames){
if(g.challenged==(Player)sender){
g.challenger.sendMessage(ChatColor.YELLOW+sender.getName()+ChatColor.DARK_GREEN+" Accepted"+ChatColor.YELLOW+" Your Challenge!");
sender.sendMessage(ChatColor.YELLOW+"You "+ChatColor.DARK_GREEN+"Accepted"+ChatColor.YELLOW+" The Challenge!");
challengedGames.remove(g);
pendingGames.add(g);
g.myDenial.cancel();
g.myDenial=null;
checkStartGame();
return true;
}
}
sender.sendMessage(ChatColor.YELLOW+"You Have No Games To Accept!");
}
if(args[0].equals("deny")){
for(Game g:challengedGames){
if(g.challenged==(Player)sender){
g.challenger.sendMessage(ChatColor.YELLOW+sender.getName()+ChatColor.DARK_GREEN+" Denied"+ChatColor.YELLOW+" Your Challenge!");
sender.sendMessage(ChatColor.YELLOW+"You "+ChatColor.DARK_GREEN+"Denied"+ChatColor.YELLOW+" The Challenge!");
challengedGames.remove(g);
return true;
}
}
sender.sendMessage(ChatColor.YELLOW+"You Have No Games To Deny!");
}
if(args[0].equals("setlocation")){
if(((Player)sender).hasPermission("onevsone.createstart")){
Location loc = ((Entity) sender).getLocation();
startPoints.add(loc);
sender.sendMessage(ChatColor.YELLOW+"Location Set!");
FileConfiguration config = this.getConfig();
FileConfigurationOptions opt = config.options();
opt.header("1v1 Plugin Config");
config.createSection("arenalocations");
Integer i = 1;
for(Location l:startPoints){
config.set("arenalocations."+i,l);
i+=1;
}
try {
config.save(this.getDataFolder() + File.separator + "config.yml");
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
for(Player p:Bukkit.getOnlinePlayers()){
if(args[0].equals(p.getName())){
Player s = (Player)sender;
if(p.getName()!=s.getName()){
sender.sendMessage((ChatColor.DARK_GREEN+"You "+ChatColor.YELLOW+"Challenged "+ChatColor.DARK_GREEN+p.getName()));
p.sendMessage(ChatColor.DARK_GREEN+((Player)sender).getName()+ChatColor.YELLOW+" Would like to 1v1 You!");
p.sendMessage(ChatColor.DARK_GREEN+"/onevsone accept"+ChatColor.YELLOW+" to accept the challenge!");
p.sendMessage(ChatColor.DARK_GREEN+"/onevsone deny"+ChatColor.YELLOW+" to deny it :(");
//TODO check if either player is in a match
Game g = new Game();
g.challenged = p;
g.challenger = (Player)sender;
challengedGames.add(g);
DenialTimer dt = new DenialTimer(this);
g.myDenial=dt;
dt.startCountdown(60, p, g);
}else{
p.sendMessage(ChatColor.YELLOW+"You Can't Challenge Yourself Silly!");
}
return true;
}
}
}
else{
sender.sendMessage(ChatColor.DARK_GREEN+"+===---===---===OneVsOne===---===---===+");
sender.sendMessage(ChatColor.YELLOW+"This is the help for the OneVsOne Plugin");
sender.sendMessage(ChatColor.YELLOW+"Use "+ChatColor.DARK_GREEN+"/onevsone help"+ChatColor.YELLOW+" For This Help Message");
sender.sendMessage(ChatColor.YELLOW+"Use "+ChatColor.DARK_GREEN+"/onevsone <PlayerName>"+ChatColor.YELLOW+" To Challenge A Player To A 1v1");
sender.sendMessage(ChatColor.YELLOW+"Use "+ChatColor.DARK_GREEN+"/onevsone accept"+ChatColor.YELLOW+" To Accept A Challenge");
sender.sendMessage(ChatColor.YELLOW+"Use "+ChatColor.DARK_GREEN+"/onevsone deny"+ChatColor.YELLOW+" To Deny A Challenge");
sender.sendMessage(ChatColor.YELLOW+"Use "+ChatColor.DARK_GREEN+"/onevsone setlocation"+ChatColor.YELLOW+" To Set A 1v1 Spawn Point (This Is Usually Ops Only!)");
sender.sendMessage(ChatColor.DARK_GREEN+"+===---===---===--+==+--===---===---===+");
}
return true;
}
//If this has happened the function will return true.
// If this hasn't happened the value of false will be returned.
return false;
}
public void checkStartGame(){
while(pendingGames.size()>0&&startPoints.size()>0){
Game g = pendingGames.remove(0);
Location loc = startPoints.remove(0);
g.gameLoc=loc;
activeGames.add(g);
((Metadatable) g.challenged).setMetadata("oldLocation",new FixedMetadataValue(this,(g.challenged).getLocation()));
((Metadatable) g.challenger).setMetadata("oldLocation",new FixedMetadataValue(this,(g.challenger).getLocation()));
savePlayer(g.challenged,this);
savePlayer(g.challenger,this);
g.challenged.teleport(g.gameLoc);
g.challenger.teleport(g.gameLoc);
setInv(g.challenged,"items.equipment","items.armour",this);
setInv(g.challenged,"items.equipment","items.armour",this);
GameCountdown cd = new GameCountdown(this, g);
cd.startCountdown(10, "Starting in"+ChatColor.DARK_GREEN+" #");
}
}
public void startGame(Game game) {
game.challenged.sendMessage((ChatColor.YELLOW+"Go!"));
game.challenger.sendMessage((ChatColor.YELLOW+"Go!"));
for(Player p:Bukkit.getOnlinePlayers()){
if(p.getName()!=(game.challenged.getName())&&p.getName()!=(game.challenger.getName())){
game.challenged.hidePlayer(p);
game.challenger.hidePlayer(p);
inProgressGames.add(game);
activeGames.remove(game);
}
}
}
@SuppressWarnings("deprecation")
public void endGame(Game game){
game.challenged.setGameMode(GameMode.SURVIVAL);
game.challenger.setGameMode(GameMode.SURVIVAL);
restorePlayer(game.challenged, this);
restorePlayer(game.challenger, this);
if(game.winner!=null){
if(this.getConfig().getBoolean("monataryreward.enabled")){
if(econ!=null){
econ.depositPlayer(game.winner.getName(), this.getConfig().getDouble("monataryreward.amount"));
}
}
if(this.getConfig().getBoolean("itemreward.enabled")){
setInv(game.winner,"itemreward.items",null,this);
}
}
inProgressGames.remove(game);
}
private void restorePlayer(Player p,Plugin plugin){
//clear invs
PlayerInventory inv = p.getInventory();
inv.clear();
inv.setArmorContents(new ItemStack[4]);
ItemStack[] invStack=(ItemStack[])MetadataHelper.getMetadata("inv",plugin,p);
if(invStack!=null){
plugin.getLogger().info("Stack = "+ invStack.toString());
p.getInventory().setContents(invStack);
}
ItemStack[] armStack=(ItemStack[])MetadataHelper.getMetadata("armour",plugin,p);
if(armStack!=null){
plugin.getLogger().info("armStack = "+ armStack.toString());
p.getEquipment().setArmorContents(armStack);
}
}
private void savePlayer(Player p, Plugin plugin){
ItemStack[] armour = (p).getEquipment().getArmorContents();
ItemStack[] inv = (p).getInventory().getContents();
((Metadatable) p).setMetadata("armour",new FixedMetadataValue(plugin,armour));
((Metadatable) p).setMetadata("inv",new FixedMetadataValue(plugin,inv));
PlayerInventory inv1 = (p).getInventory();
inv1.clear();
inv1.setArmorContents(new ItemStack[4]);
}
@SuppressWarnings("deprecation")
private void setInv(Player p, String equipmentPath,String armourPath, Plugin plugin){
PlayerInventory inventory = p.getInventory();
if(equipmentPath!=null){
String[] items = plugin.getConfig().getString(equipmentPath).split(",");
for(String item:items){
String[] i = item.split(":");
String type = i[0];
int count = 1;
short meta = 0;
switch (i.length) {
case 1:
break;
case 2:
count = Integer.parseInt(i[1]);
break;
case 3:
count = Integer.parseInt(i[2]);
meta = Short.parseShort(i[1]);
break;
}
Material m = Material.matchMaterial(type);
if (m != null) {
ItemStack is;
if(meta!=0){
is = new ItemStack(m,count,meta);
inventory.addItem(is);
}else{
is = new ItemStack(m,count);
inventory.addItem(is);
}
} else {
p.sendMessage("Item "+i+" could not be found");
}
}
}
if(armourPath!=null){
ItemStack[] armour = new ItemStack[4];
String[] armours = plugin.getConfig().getString(armourPath).split(",");
if(armours.length==4){
for(int i=0;i<4;i++){
armour[i] = new ItemStack(Integer.parseInt(armours[i]));
}
inventory.setArmorContents(armour);
}
}
}
private boolean testForVault() {
if (getServer().getPluginManager().getPlugin("Vault") == null) {
return false;
}
return true;
}
private boolean setupEconomy() {
RegisteredServiceProvider<Economy> rsp = getServer().getServicesManager().getRegistration(Economy.class);
if (rsp == null) {
return false;
}
econ = rsp.getProvider();
return econ != null;
}
}
| true
|
6c69b25dc4092ca3078d0bbf0e36f39537c4a7a0
|
Java
|
huangshiqiang/demo
|
/code/cn.elwy.example/src/TheDefinitiveGuidetoSWTandJFace/com/swt/Chapter12/examples/ch12/TextPrinterExample.java
|
UTF-8
| 6,912
| 3.34375
| 3
|
[] |
no_license
|
package com.swt.Chapter12.examples.ch12;
import org.eclipse.swt.*;
import org.eclipse.swt.graphics.*;
import org.eclipse.swt.printing.*;
import org.eclipse.swt.widgets.*;
import java.io.*;
/**
* This class demonstrates printing text
*/
public class TextPrinterExample {
/**
* Runs the application
*/
public void run() {
Display display = new Display();
Shell shell = new Shell(display);
// Get the file to print
FileDialog fileChooser = new FileDialog(shell, SWT.OPEN);
String fileName = fileChooser.open();
if (fileName != null) {
// Have user select a printer
PrintDialog dialog = new PrintDialog(shell);
PrinterData printerData = dialog.open();
if (printerData != null) {
// Create the printer
Printer printer = new Printer(printerData);
try {
// Print the contents of the file
new WrappingPrinter(printer, fileName, getFileContents(fileName)).print();
} catch (Exception e) {
MessageBox mb = new MessageBox(shell, SWT.ICON_ERROR | SWT.OK);
mb.setMessage(e.getMessage());
mb.open();
}
// Dispose the printer
printer.dispose();
}
}
display.dispose();
}
/**
* Read in the file and return its contents
* @param fileName
* @return
* @throws FileNotFoundException
* @throws IOException
*/
private String getFileContents(String fileName) throws FileNotFoundException, IOException {
StringBuffer contents = new StringBuffer();
BufferedReader reader = null;
try {
// Read in the file
reader = new BufferedReader(new FileReader(fileName));
while (reader.ready()) {
contents.append(reader.readLine());
contents.append("\n"); // Throw away LF chars, and just replace CR
}
} finally {
if (reader != null)
try {
reader.close();
} catch (IOException e) {
}
}
return contents.toString();
}
/**
* The application entry point
* @param args the command line arguments
*/
public static void main(String[] args) {
new TextPrinterExample().run();
}
}
/**
* This class performs the printing, wrapping text as necessary
*/
class WrappingPrinter {
private Printer printer; // The printer
private String fileName; // The name of the file to print
private String contents; // The contents of the file to print
private GC gc; // The GC to print on
private int xPos, yPos; // The current x and y locations for print
private Rectangle bounds; // The boundaries for the print
private StringBuffer buf; // Holds a word at a time
private int lineHeight; // The height of a line of text
/**
* WrappingPrinter constructor
* @param printer the printer
* @param fileName the fileName
* @param contents the contents
*/
WrappingPrinter(Printer printer, String fileName, String contents) {
this.printer = printer;
this.fileName = fileName;
this.contents = contents;
}
/**
* Prints the file
*/
void print() {
// Start the print job
if (printer.startJob(fileName)) {
// Determine print area, with margins
bounds = computePrintArea(printer);
xPos = bounds.x;
yPos = bounds.y;
// Create the GC
gc = new GC(printer);
// Determine line height
lineHeight = gc.getFontMetrics().getHeight();
// Determine tab width--use three spaces for tabs
int tabWidth = gc.stringExtent(" ").x;
// Print the text
printer.startPage();
buf = new StringBuffer();
char c;
for (int i = 0, n = contents.length(); i < n; i++) {
// Get the next character
c = contents.charAt(i);
// Check for newline
if (c == '\n') {
printBuffer();
printNewline();
}
// Check for tab
else if (c == '\t') {
xPos += tabWidth;
} else {
buf.append(c);
// Check for space
if (Character.isWhitespace(c)) {
printBuffer();
}
}
}
printer.endPage();
printer.endJob();
gc.dispose();
}
}
/**
* Prints the contents of the buffer
*/
void printBuffer() {
// Get the width of the rendered buffer
int width = gc.stringExtent(buf.toString()).x;
// Determine if it fits
if (xPos + width > bounds.x + bounds.width) {
// Doesn't fit--wrap
printNewline();
}
// Print the buffer
gc.drawString(buf.toString(), xPos, yPos, false);
xPos += width;
buf.setLength(0);
}
/**
* Prints a newline
*/
void printNewline() {
// Reset x and y locations to next line
xPos = bounds.x;
yPos += lineHeight;
// Have we gone to the next page?
if (yPos > bounds.y + bounds.height) {
yPos = bounds.y;
printer.endPage();
printer.startPage();
}
}
/**
* Computes the print area, including margins
* @param printer the printer
* @return Rectangle
*/
Rectangle computePrintArea(Printer printer) {
// Get the printable area
Rectangle rect = printer.getClientArea();
// Compute the trim
Rectangle trim = printer.computeTrim(0, 0, 0, 0);
// Get the printer's DPI
Point dpi = printer.getDPI();
// Calculate the printable area, using 1 inch margins
int left = trim.x + dpi.x;
if (left < rect.x)
left = rect.x;
int right = (rect.width + trim.x + trim.width) - dpi.x;
if (right > rect.width)
right = rect.width;
int top = trim.y + dpi.y;
if (top < rect.y)
top = rect.y;
int bottom = (rect.height + trim.y + trim.height) - dpi.y;
if (bottom > rect.height)
bottom = rect.height;
return new Rectangle(left, top, right - left, bottom - top);
}
}
| true
|
0ed4b42f4f3c83bf257560f6ad2c03976a914f82
|
Java
|
go88hoontops/java
|
/ch05/StringEqualsExam.java
|
UHC
| 892
| 3.9375
| 4
|
[] |
no_license
|
package com.jh.ch05;
public class StringEqualsExam {
public static void main(String[] args) {
String strVal1 = "";
String strVal2 = "";
if (strVal1 == strVal2) {
System.out.println("strVal1 strVal2 ");
}else {
System.out.println("strVal1 strVal2 ٸ");
}
if(strVal1.equals(strVal2)) {
System.out.println("strVal1 strVal2 ڿ ");
}
String strVal3 = new String("");
String strVal4 = new String("");
if(strVal3 == strVal4) {
System.out.println("strVal3 strVal4 ");
}else {
System.out.println("strVal3 strVal4 ٸ");
}
if(strVal3.equals(strVal4)) {
System.out.println("strVal3 strVal4 ڿ ");
}
}
} // ڰ ġ ҷ
| true
|
07bcc9bba542183dd97ed6980ebecdc76d8e0ec6
|
Java
|
IBD-Technologies/NewGenEducationApp
|
/CohesiveReportEngine/ReportProcessing/src/java/com/ibd/cohesive/report/dbreport/dataSets/user/UVW_PARENT_STUDENT_ROLEMAPPING_DATASET.java
|
UTF-8
| 5,497
| 1.625
| 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.ibd.cohesive.report.dbreport.dataSets.user;
import com.ibd.cohesive.db.readbuffer.DBRecord;
import com.ibd.cohesive.db.readbuffer.IDBReadBufferService;
import com.ibd.cohesive.db.session.DBSession;
import com.ibd.cohesive.report.dbreport.dataModels.app.CONTRACT_MASTER;
import com.ibd.cohesive.report.dbreport.dataModels.user.UVW_PARENT_STUDENT_ROLEMAPPING;
import com.ibd.cohesive.report.dependencyinjection.ReportDependencyInjection;
import com.ibd.cohesive.util.IBDProperties;
import com.ibd.cohesive.util.exceptions.DBProcessingException;
import com.ibd.cohesive.util.exceptions.DBValidationException;
import com.ibd.cohesive.util.session.CohesiveSession;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.Map;
/**
*
* @author IBD Technologies
*/
public class UVW_PARENT_STUDENT_ROLEMAPPING_DATASET {
// ArrayList<UVW_PARENT_STUDENT_ROLEMAPPING> dataset;
public ArrayList<UVW_PARENT_STUDENT_ROLEMAPPING> getTableObject(String p_userID,CohesiveSession session,DBSession dbSession,ReportDependencyInjection inject)throws DBProcessingException,DBValidationException{
try{
dbg("inside UVW_PARENT_STUDENT_ROLEMAPPING_DATASET--->getTableObject",session);
IDBReadBufferService readBuffer =inject.getDBReadBufferService();
IBDProperties i_db_properties=session.getCohesiveproperties();
Map<String,DBRecord>l_userParentMap=null;
try
{
l_userParentMap=readBuffer.readTable("USER"+i_db_properties.getProperty("FOLDER_DELIMITER")+"User"+i_db_properties.getProperty("FOLDER_DELIMITER")+"User","USER", "UVW_PARENT_STUDENT_ROLEMAPPING", session, dbSession);
}
catch(DBValidationException ex){
if(ex.toString().contains("DB_VAL_011")||ex.toString().contains("DB_VAL_000")){
session.getErrorhandler().removeSessionErrCode("DB_VAL_000");
session.getErrorhandler().removeSessionErrCode("DB_VAL_011");
}else{
throw ex;
}
}
dbg("end of UVW_PARENT_STUDENT_ROLEMAPPING_DATASET--->getTableObject",session);
return convertDBtoReportObject(l_userParentMap,session) ;
}catch(DBProcessingException ex){
dbg(ex,session);
throw new DBProcessingException("DBProcessingException"+ex.toString());
}catch(DBValidationException ex){
dbg(ex,session);
throw ex;
}catch(Exception ex){
throw new DBProcessingException("DBProcessingException"+ex.toString());
}
}
private ArrayList<UVW_PARENT_STUDENT_ROLEMAPPING> convertDBtoReportObject(Map<String,DBRecord>p_userParentMap,CohesiveSession session)throws DBProcessingException{
ArrayList<UVW_PARENT_STUDENT_ROLEMAPPING>dataset=new ArrayList();
try{
dbg("inside UVW_PARENT_STUDENT_ROLEMAPPING convertDBtoReportObject",session);
if(p_userParentMap!=null&&!p_userParentMap.isEmpty()){
Iterator<DBRecord> recordIterator=p_userParentMap.values().iterator();
while(recordIterator.hasNext()){
DBRecord l_parentRecords=recordIterator.next();
UVW_PARENT_STUDENT_ROLEMAPPING parentRoleMap=new UVW_PARENT_STUDENT_ROLEMAPPING();
parentRoleMap.setUSER_ID(l_parentRecords.getRecord().get(0).trim());
parentRoleMap.setROLE_ID(l_parentRecords.getRecord().get(1).trim());
parentRoleMap.setSTUDENT_ID(l_parentRecords.getRecord().get(2).trim());
parentRoleMap.setVERSION_NUMBER(l_parentRecords.getRecord().get(3).trim());
parentRoleMap.setINSTITUTE_ID(l_parentRecords.getRecord().get(4).trim());
dataset.add(parentRoleMap);
}
}
else
{
UVW_PARENT_STUDENT_ROLEMAPPING service=new UVW_PARENT_STUDENT_ROLEMAPPING();
service.setUSER_ID(" ");
service.setROLE_ID(" ");
service.setSTUDENT_ID(" ");
service.setVERSION_NUMBER(" ");
service.setINSTITUTE_ID(" ");
dataset.add(service);
}
dbg("end of UVW_PARENT_STUDENT_ROLEMAPPING_DATASET convertDBtoReportObject",session);
}catch(Exception ex){
dbg(ex,session);
throw new DBProcessingException("DBProcessingException"+ex.toString());
}
return dataset;
}
public void dbg(String p_Value,CohesiveSession session) {
session.getDebug().dbg(p_Value);
}
public void dbg(Exception ex,CohesiveSession session) {
session.getDebug().exceptionDbg(ex);
}
}
| true
|
51c1864c80c22de3426822f42d39b4e2210e689d
|
Java
|
anneri51/prorekrut
|
/01_Allgemein/08_Eclipse/v1/test1/appClientModule/prorekrut/Main.java
|
UTF-8
| 396
| 1.539063
| 2
|
[] |
no_license
|
package prorekrut;
import java.sql.SQLException;
import javax.swing.*;
//import java.sql.Connection;
import prorekrut.frm.MainForm;
public class Main {
public static void main(String[] args) throws SQLException {
// TODO Auto-generated method stub
MainForm.createMainForm ();
}
/* (non-Java-doc)
* @see java.lang.Object#Object()
*/
public Main() {
super();
}
}
| true
|
7d2224724d64f5610b2047bc6ca822aa34cc52be
|
Java
|
abdelb12/app_sp
|
/src/main/java/com/tournoi/foot/model/Joueur.java
|
UTF-8
| 1,528
| 2.34375
| 2
|
[] |
no_license
|
package com.tournoi.foot.model;
import org.springframework.stereotype.Component;
@Component
public class Joueur {
private Integer idJoueur;
private String prenom;
private String nom;
private Integer age;
private float taille;
private Integer poste;
private String dateNaissance;
private Integer idEquipe;
public Integer getIdJoueur() {
return idJoueur;
}
public void setIdJoueur(Integer idJoueur) {
this.idJoueur = idJoueur;
}
public String getPrenom() {
return prenom;
}
public void setPrenom(String prenom) {
this.prenom = prenom;
}
public String getNom() {
return nom;
}
public void setNom(String nom) {
this.nom = nom;
}
public Integer getAge() {
return age;
}
public void setAge(Integer age) {
this.age = age;
}
public float getTaille() {
return taille;
}
public void setTaille(float taille) {
this.taille = taille;
}
public Integer getPoste() {
return poste;
}
public void setPoste(Integer poste) {
this.poste = poste;
}
public String getDateNaissance() {
return dateNaissance;
}
public void setDateNaissance(String dateNaissance) {
this.dateNaissance = dateNaissance;
}
public Integer getIdEquipe() {
return idEquipe;
}
public void setIdEquipe(Integer idEquipe) {
this.idEquipe = idEquipe;
}
@Override
public String toString() {
return "Joueur [idJoueur=" + idJoueur + ", prenom=" + prenom + ", nom=" + nom + ", age=" + age + ", taille="
+ taille + ", poste=" + poste + ", dateNaissance=" + dateNaissance + "]";
}
}
| true
|
e46d37ecf18070961301e8901f2f67170b3497c5
|
Java
|
ramamanne/cards
|
/src/main/java/com/interview/app/IDeck.java
|
UTF-8
| 142
| 1.945313
| 2
|
[] |
no_license
|
package com.interview.app;
/**
* Deck Operations
* @author Rama
*/
public interface IDeck {
void shuffle();
Card dealOneCard();
}
| true
|
579b9cbfbcaafc0e5d78fdaa830c22ffc3c3da73
|
Java
|
Plugway/commandLine_bot
|
/src/ObjectSerialization.java
|
UTF-8
| 711
| 2.9375
| 3
|
[] |
no_license
|
import java.io.*;
public class ObjectSerialization {
public static void serialize(Object o, String filePath) throws IOException //exceptions are handled in UserTableSerialization
{
var fileOut = new FileOutputStream(filePath, false);
var out = new ObjectOutputStream(fileOut);
out.writeObject(o);
out.close();
fileOut.close();
}
public static Object deserialize(String filePath) throws IOException, ClassNotFoundException {
var fileIn = new FileInputStream(filePath);
var in = new ObjectInputStream(fileIn);
var res = in.readObject();
in.close();
fileIn.close();
return res;
}
}
| true
|
09be272529b25e552f5e5b5442bb3ee29f97e283
|
Java
|
ycc0207/sdk-demo
|
/aegis-sdk-demo/src/main/java/com/epgis/offline/adapter/OfflineAllCityListAdapter.java
|
UTF-8
| 23,720
| 1.90625
| 2
|
[] |
no_license
|
package com.epgis.offline.adapter;
import android.content.Context;
import android.content.Intent;
import android.os.Handler;
import android.util.Log;
import android.util.SparseArray;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseExpandableListAdapter;
import android.widget.ExpandableListView;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;
import com.epgis.commons.utils.EncryptUtil;
import com.epgis.epgisapp.R;
import com.epgis.offline.DBException;
import com.epgis.offline.DownloadState;
import com.epgis.offline.OfflineMapCity;
import com.epgis.offline.OfflineMapManager;
import com.epgis.offline.OfflineMapProvince;
import com.epgis.offline.controller.AllCityController;
import com.epgis.offline.controller.DownloadCityController;
import com.epgis.offline.controller.OfflineMapDownloadController;
import com.epgis.offline.db.AllCity;
import com.epgis.offline.db.DownloadCity;
import com.epgis.offline.fragment.OfflineMapFragment;
import com.epgis.offline.service.DownloadService;
import com.epgis.offline.util.FileUtil;
import com.epgis.offline.util.NetworkUtil;
import com.epgis.offline.widget.PopupDialog;
import java.io.File;
import java.util.ArrayList;
import java.util.List;
/**
* Created by Lynn on 2019/3/15.
*/
public class OfflineAllCityListAdapter extends BaseExpandableListAdapter implements ExpandableListView.OnGroupCollapseListener, ExpandableListView.OnGroupExpandListener {
private String TAG = "OfflineMapManager";
private boolean isDebug = true;
private boolean[] isOpen;// 记录一级目录是否打开
private List<OfflineMapProvince> provinceList = null;
private SparseArray<ArrayList<OfflineMapCity>> cityInMap = null;
private OfflineMapManager offlineMapManager;
private Context mContext;
private Handler mHandler;
public static final String ITEM_CLICK_TYPE_DOWNLOAD_ALL = "DOWNLOAD_ALL";
public int mCityLastState = -1;
public int mLastAdCode = -1;
private boolean isScrolling;
private OfflineMapFragment mFragment;
// 字体按钮的样式
private int blueColor = 0xff0091ff; // 蓝色
private int BASE_MAP_AD_CODE = 100000;
private int redColor = 0xffff4546; // 红色
private int pause_grayColor = 0xff666666;// 暂停灰
private int finish_grayColor = 0xff999999; // 已下载灰
private ItemClickListener mItemClickListener;
private PopupDialog dialog;
public OfflineAllCityListAdapter(OfflineMapFragment fragment, Handler handler, List<OfflineMapProvince> provinceList, SparseArray<ArrayList<OfflineMapCity>> cityInMap) {
this.mFragment = fragment;
this.mContext = fragment.getActivity().getApplicationContext();
this.provinceList = provinceList;
this.cityInMap = cityInMap;
isOpen = new boolean[provinceList.size()];
mHandler = handler;
}
public interface ItemClickListener {
void onItemCliclk(String type, int position);
}
public void setOnItemCliclkListener(ItemClickListener itemCliclkListener) {
this.mItemClickListener = itemCliclkListener;
}
public void setScrolling(boolean scrolling) {
isScrolling = scrolling;
}
public boolean isScrolling() {
return isScrolling;
}
@Override
public int getGroupCount() {
return provinceList.size();
}
@Override
public int getChildrenCount(int groupPosition) {
OfflineMapProvince province = provinceList.get(groupPosition);
ArrayList<OfflineMapCity> cityList = cityInMap.get(province.getAdCode(), null);
if (cityList == null) {
return 0;
} else {
return cityList.size();
}
}
@Override
public Object getGroup(int groupPosition) {
return provinceList.get(groupPosition);
}
@Override
public Object getChild(int groupPosition, int childPosition) {
OfflineMapProvince province = provinceList.get(groupPosition);
ArrayList<OfflineMapCity> cityList = cityInMap.get(province.getAdCode(), null);
if (cityList == null) {
return null;
} else {
return cityList.get(childPosition);
}
}
@Override
public long getGroupId(int groupPosition) {
return groupPosition;
}
@Override
public long getChildId(int groupPosition, int childPosition) {
return childPosition;
}
@Override
public boolean hasStableIds() {
return true;
}
@Override
public View getGroupView(int groupPosition, boolean isExpanded, View convertView, ViewGroup parent) {
TextView groupName, tvDownload, proviceMapSize;
ImageView groupImage, download;
LinearLayout proviceUnDownAllLayout, proviceDownAllLayout;
if (convertView == null) {
convertView = (RelativeLayout) RelativeLayout.inflate(mContext, R.layout.offline_download_list_item_group, null);
}
groupName = (TextView) convertView.findViewById(R.id.tv_group_name);
download = (ImageView) convertView.findViewById(R.id.iv_group_image_download);
tvDownload = (TextView) convertView.findViewById(R.id.tv_group_image_download);
groupImage = (ImageView) convertView.findViewById(R.id.iv_group_image);
proviceMapSize = convertView.findViewById(R.id.text_data_size);
proviceUnDownAllLayout = convertView.findViewById(R.id.tv_group_image_undownload_layout);
proviceDownAllLayout = convertView.findViewById(R.id.tv_group_image_download_layout);
double size = ((int) (getTotalSize(provinceList.get(groupPosition)) / 1024.0 / 1024.0 * 100)) / 100.0;
proviceMapSize.setText(String.valueOf(size) + " M");
groupName.setText(provinceList.get(groupPosition).getProvinceName());
proviceUnDownAllLayout.setVisibility(View.VISIBLE);
proviceDownAllLayout.setVisibility(View.GONE);
if (isOpen.length <= 0) {
isOpen = new boolean[provinceList.size()];
}
if (isOpen[groupPosition]) {
groupImage.setImageDrawable(mContext.getResources().getDrawable(
R.drawable.offlinearrow_down));
} else {
groupImage.setImageDrawable(mContext.getResources().getDrawable(
R.drawable.offlinearrow_right));
}
if (mContext != null && provinceList != null && provinceList.size() > 0 && provinceList.get(groupPosition) != null) {
OfflineMapProvince province = provinceList.get(groupPosition);
if (province != null && province.getAdCode() != -1) {
ArrayList<OfflineMapCity> cityList = cityInMap.get(province.getAdCode(), null);
boolean isFinish = true;
boolean isDownLoading = false;
for (OfflineMapCity city : cityList) {
if (city.mStatus != DownloadState.state_download_completed) {
if (city.mStatus == DownloadState.state_download_doing) {
isDownLoading = true;
if (!isFinish) break;
}
isFinish = false;
}
}
if (isFinish) {
proviceUnDownAllLayout.setVisibility(View.GONE);
proviceDownAllLayout.setVisibility(View.VISIBLE);
} else {
if (!isDownLoading) {
proviceUnDownAllLayout.setEnabled(true);
download.setImageDrawable(mContext.getResources().getDrawable(R.drawable.offlinearrow_download));
} else {
proviceUnDownAllLayout.setEnabled(false);
download.setImageDrawable(mContext.getResources().getDrawable(R.drawable.offlinearrow_download));
}
proviceUnDownAllLayout.setVisibility(View.VISIBLE);
proviceDownAllLayout.setVisibility(View.GONE);
}
}
}
proviceUnDownAllLayout.setTag(groupPosition);
proviceUnDownAllLayout.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
showDialog(v);
}
});
return convertView;
}
public Long getTotalSize(OfflineMapProvince offlineMapProvince) {
Long mTotalSize = 0L;
ArrayList<OfflineMapCity> mCitys = cityInMap.get(offlineMapProvince.getAdCode(), null);
if (mCitys != null && mCitys.size() > 0) {
for (OfflineMapCity city : mCitys)
mTotalSize += city.getMapSize();
}
return mTotalSize;
}
private void showDialog(View v) {
if (dialog == null) {
dialog = new PopupDialog(mFragment.getContext(), R.layout.app_download_popup_view).builder();
}
View view = dialog.getLayoutView();
// 获取自定义Dialog布局中的控件
TextView title = (TextView) view.findViewById(R.id.app_collect_popup_title);
int position = -1;
if (v.getTag() != null) {
position = Integer.valueOf(v.getTag().toString());
title.setText(provinceList.get(position).getProvinceName());
}
TextView del = (TextView) view.findViewById(R.id.app_collect_popup_del);
del.setText("全部下载");
TextView cancel = (TextView) view.findViewById(R.id.app_collect_popup_cancel);
del.setOnClickListener(new MyClickListener(position));
cancel.setOnClickListener(new MyClickListener(position));
if (dialog != null) {
dialog.show();
}
}
// 自定义点击接口
class MyClickListener implements View.OnClickListener {
int mPosition;
private MyClickListener(int position) {
this.mPosition = position;
}
@Override
public void onClick(final View view) {
switch (view.getId()) {
case R.id.app_collect_popup_del:
ItemClick(ITEM_CLICK_TYPE_DOWNLOAD_ALL);
break;
case R.id.app_collect_popup_cancel:
ItemClick(null);
break;
}
}
private void ItemClick(String type) {
if (type != null) {
mItemClickListener.onItemCliclk(type, mPosition);
}
if (dialog != null) {
dialog.dismiss();
}
}
}
@Override
public View getChildView(int groupPosition, int childPosition, boolean isLastChild, View convertView, ViewGroup parent) {
final OfflineAllCityViewHolder holder;
final OfflineMapCity city = (OfflineMapCity) getChild(groupPosition, childPosition);
if (convertView == null) {
holder = new OfflineAllCityViewHolder();
convertView = (RelativeLayout) RelativeLayout.inflate(mContext, R.layout.offline_city_list_item_child, null);
holder.cityListViewContainer = (RelativeLayout) convertView.findViewById(R.id.download_city_list_item_container);
holder.tvCityName = (TextView) convertView.findViewById(R.id.tv_cityname);
holder.tvMapSize = (TextView) convertView.findViewById(R.id.tv_map_size);
holder.opreateStateImg = convertView.findViewById(R.id.img_operate);
holder.tvOperator = (TextView) convertView.findViewById(R.id.tv_operate);
holder.unDownLayout = convertView.findViewById(R.id.undown_layout);
holder.opreateLayout = convertView.findViewById(R.id.operate_layout);
convertView.setTag(holder);
} else {
holder = (OfflineAllCityViewHolder) convertView.getTag();
}
bindChildView(city, holder, groupPosition);
return convertView;
}
private void bindChildView(final OfflineMapCity cityItem, final OfflineAllCityViewHolder holder, final int groupPosition) {
// 绑定监听事件
holder.unDownLayout.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
if (cityItem == null) {
return;
}
int cityState = cityItem.mStatus;
switch (cityState) {
// 开始和重试才允许点击,其他状态全部在下载管理中控制
case DownloadState.state_undownload:
if (NetworkUtil.checkNetwork(mContext) == 0) {
Toast.makeText(mContext, "网络异常,请检查网络后重试!", Toast.LENGTH_LONG).show();
} else {
// 需要优先判断下载基础包
if(isDebug) Log.i(TAG,"now click adcode:" + provinceList.get(groupPosition).getAdCode());
if(provinceList.get(groupPosition).getAdCode() != OfflineMapDownloadController.getBaseMapAdCode()){
downloadBasePkg();
}
cityItem.setProCode(provinceList.get(groupPosition).getAdCode());
Intent startIntent = new Intent(mContext, DownloadService.class);
startIntent.setAction(DownloadService.ACTION_START);
startIntent.putExtra("OfflineMapCity", cityItem);
mContext.startService(startIntent);
if(isDebug) Log.i(TAG,"click state_undownload:start DownloadService");
}
break;
case DownloadState.state_download_doing:
case DownloadState.state_download_waiting:
case DownloadState.state_download_pause:
case DownloadState.state_download_completed:
//无法点击
break;
// 开始和重试才允许点击,其他状态全部在下载管理中控制
case DownloadState.state_data_error:
if (NetworkUtil.checkNetwork(mContext) == 0) {
Toast.makeText(mContext, "网络异常,请检查网络后重试!", Toast.LENGTH_LONG).show();
} else {
cityItem.setProCode(provinceList.get(groupPosition).getAdCode());
Intent startIntent = new Intent(mContext, DownloadService.class);
startIntent.setAction(DownloadService.ACTION_ERROR);
startIntent.putExtra("OfflineMapCity", cityItem);
mContext.startService(startIntent);
}
break;
}
}
});
// 1、刷新地图名称和大小
holder.tvCityName.setText(cityItem.getCityName());
double size = ((int) (cityItem.getMapSize() / 1024.0 / 1024.0 * 100)) / 100.0;
holder.tvMapSize.setText(String.valueOf(size) + " M");
if (cityItem.getMapSize() != 0) {
// 2、 刷新下载按钮状态
holder.unDownLayout.setVisibility(View.GONE);
holder.opreateLayout.setVisibility(View.GONE);
holder.opreateStateImg.setImageResource(R.drawable.offline_state_undown);
switch (cityItem.mStatus) {
case DownloadState.state_undownload:
//holder.tvOperator.setText("下载");
holder.unDownLayout.setVisibility(View.VISIBLE);
break;
case DownloadState.state_download_doing:
holder.tvOperator.setText("下载中");
holder.opreateLayout.setVisibility(View.VISIBLE);
break;
case DownloadState.state_download_waiting:
holder.tvOperator.setText("等待");
holder.opreateLayout.setVisibility(View.VISIBLE);
break;
case DownloadState.state_download_pause:
holder.tvOperator.setText("已暂停");
holder.opreateLayout.setVisibility(View.VISIBLE);
break;
case DownloadState.state_download_completed:
holder.opreateStateImg.setImageResource(R.drawable.offline_state_down);
holder.tvOperator.setText("已下载");
holder.opreateLayout.setVisibility(View.VISIBLE);
break;
case DownloadState.state_data_error:
holder.tvOperator.setText("重试");
holder.opreateLayout.setVisibility(View.VISIBLE);
break;
case DownloadState.state_upgrade:
holder.tvOperator.setText("有更新");
holder.opreateLayout.setVisibility(View.VISIBLE);
break;
default:
break;
}
}
}
public void downloadBasePkg() {
if(mContext != null) {
try {
DownloadCity downloadCity = DownloadCityController.getInstance(mContext).getDownloadCityByCityId(OfflineMapDownloadController.getBaseMapAdCode());
File file = new File(FileUtil.getAppSDCardMapPath(), EncryptUtil.getEncryptName(mContext, String.valueOf(OfflineMapDownloadController.getBaseMapAdCode())));
// 从未下载 或者 不在下载列表中 或者 下载列表中但并未开始
if (!file.exists() || downloadCity == null ||
(file.length() < downloadCity.getMapTotalSize() && downloadCity.getMapDownloadStatus() != DownloadState.state_download_doing)) {
Toast.makeText(mContext, "基础功能包是离线地图的基本依赖,需要优先下载", Toast.LENGTH_SHORT).show();
AllCity allCity = AllCityController.getInstance(mContext).getCityByAdCode(OfflineMapDownloadController.getBaseMapAdCode());
OfflineMapCity baseCity = new OfflineMapCity(allCity.getAdCode(), allCity.getCityName());
baseCity.setMapVersion(allCity.getMapVersion());
baseCity.setMapSize(allCity.getMapPkgSize());
baseCity.setProCode(OfflineMapDownloadController.getBaseMapProAdCode());// 插入基础功能包的proCode
Intent startIntent = new Intent(mContext, DownloadService.class);
startIntent.setAction(DownloadService.ACTION_START);
startIntent.putExtra("OfflineMapCity", baseCity);
mContext.startService(startIntent);
if(isDebug) Log.i(TAG,"downloadBasePkg start DownloadService");
}
} catch (DBException e) {
e.printStackTrace();
}
}
}
@Override
public boolean isChildSelectable(int groupPosition, int childPosition) {
return true;
}
@Override
public void onGroupCollapse(int groupPosition) {
isOpen[groupPosition] = false;
}
@Override
public void onGroupExpand(int groupPosition) {
isOpen[groupPosition] = true;
}
// 刷新下载进度 UI
private long curTime = 0;
public void updateProgress(OfflineMapCity fileBean) {
if (fileBean.getProCode() != null) {
for (OfflineMapCity data : cityInMap.get(fileBean.getProCode(), null)) {
if (data.getAdCode().equals(fileBean.getAdCode())) {
data.setMapSize(fileBean.getMapSize());
data.setDownloadedSize(fileBean.getDownloadedSize());
data.mStatus = fileBean.mStatus;
if (fileBean.mStatus != DownloadState.state_download_completed && System.currentTimeMillis() - curTime > 1000) {
curTime = System.currentTimeMillis();
notifyDataSetChanged();
}
return;
}
}
}
}
// 刷新下载错误 UI
public void unStart(OfflineMapCity fileBean) {
if (fileBean.getProCode() != null) {
for (OfflineMapCity data : cityInMap.get(fileBean.getProCode(), null)) {
if (data.getAdCode().equals(fileBean.getAdCode())) {
data.mStatus = DownloadState.state_undownload;
notifyDataSetChanged();
return;
}
}
}
}
// 刷新等待下载 UI
public void waiting(OfflineMapCity fileBean) {
if (fileBean.getProCode() != null) {
for (OfflineMapCity data : cityInMap.get(fileBean.getProCode(), null)) {
if (data.getAdCode().equals(fileBean.getAdCode())) {
data.mStatus = DownloadState.state_download_waiting;
notifyDataSetChanged();
return;
}
}
}
}
// 刷新开始下载 UI
public void start(OfflineMapCity fileBean) {
if (fileBean.getProCode() != null) {
for (OfflineMapCity data : cityInMap.get(fileBean.getProCode(), null)) {
if (data.getAdCode().equals(fileBean.getAdCode())) {
data.mStatus = DownloadState.state_download_doing;
notifyDataSetChanged();
return;
}
}
}
}
// 刷新暂停下载 UI
public void pause(OfflineMapCity fileBean) {
if (fileBean.getProCode() != null) {
for (OfflineMapCity data : cityInMap.get(fileBean.getProCode(), null)) {
if (data.getAdCode().equals(fileBean.getAdCode())) {
data.mStatus = DownloadState.state_download_pause;
notifyDataSetChanged();
return;
}
}
}
}
// 刷新下载结束 UI
public void finished(OfflineMapCity fileBean) {
if (fileBean.getProCode() != null) {
for (OfflineMapCity data : cityInMap.get(fileBean.getProCode(), null)) {
if (data.getAdCode().equals(fileBean.getAdCode())) {
data.mStatus = DownloadState.state_download_completed;
notifyDataSetChanged();
return;
}
}
}
}
// 刷新下载错误 UI
public void error(OfflineMapCity fileBean) {
if (fileBean.getProCode() != null) {
for (OfflineMapCity data : cityInMap.get(fileBean.getProCode(), null)) {
if (data.getAdCode().equals(fileBean.getAdCode())) {
data.mStatus = DownloadState.state_data_error;
notifyDataSetChanged();
return;
}
}
}
}
public class OfflineAllCityViewHolder {
public RelativeLayout cityListViewContainer; // Container
public TextView tvCityName; // 城市名字
public TextView tvMapSize; // 地图下载状态图标和离线地图的大小
public View unDownLayout;
public View opreateLayout;
public ImageView opreateStateImg;//状态
public TextView tvOperator; // 操作按钮:下载、更新、暂停、重试、继续、 已下载
}
}
| true
|
44aab9d644a79445aa676254b7f24a7086c4479b
|
Java
|
amlane/java-transportation
|
/src/transport/HorseFromVehicle.java
|
UTF-8
| 710
| 3.34375
| 3
|
[] |
no_license
|
package transport;
public class HorseFromVehicle extends AbstractVehicle {
private String name;
public HorseFromVehicle(String name, int fuel) {
// super means call the parent constructor
super(fuel);
this.fuel *= 2;
this.name = name;
}
// if you create a new HorseFromVehicle using just a name
public HorseFromVehicle(String name) {
this.name = name;
}
@Override
public String getPath() {
return "Gravel";
}
@Override
public String getName() {
return name;
}
@Override
public String toString() {
return "HorseFromVehicle{" + "name= " + name + "\'" + ", fuel= " + fuel + "}";
}
}
| true
|
e06ef0fde930c85f676a4124ca427f6bc9d072b6
|
Java
|
MDi-1/MDiRepository
|
/kodilla-stream/src/main/java/com/kodilla/stream/array/ArrayOperations.java
|
UTF-8
| 521
| 3.875
| 4
|
[] |
no_license
|
package com.kodilla.stream.array;
import java.util.stream.IntStream;
public interface ArrayOperations {
static double getAverage(int[] numbers) {
System.out.println("Exercise 7.5; displaying array values as follows:");
IntStream.rangeClosed(0, numbers.length - 1)
.map(s -> numbers[s])
.forEach(System.out::println);
return IntStream.rangeClosed(0, numbers.length - 1)
.map(s -> numbers[s])
.average().getAsDouble();
}
}
| true
|
1ede6f555ae9b48d5f61a9a84456672062766285
|
Java
|
alvisdeng/IoT
|
/Project1/jianpindProject1/PhotonTracker/src/developerworks/ajax/particle/Photon.java
|
UTF-8
| 2,192
| 2.875
| 3
|
[] |
no_license
|
package developerworks.ajax.particle;
public class Photon {
/**
id of the photon
*/
private String id;
/**
the time of last beat of photon
*/
private String lastBeat;
/**
the state information about the connection between photon and our servlet
*/
private String state;
/**
* Empty construction method
*/
public Photon() {}
/**
* Construction method with parameters
*
* @param id photon id
* @param lastBeat time of last heartbeat
* @param state state information about the connection
*/
public Photon(String id, String lastBeat, String state) {
this.id = id;
this.lastBeat = lastBeat;
this.state = state;
}
/**
* @return the id of photon
*/
public String getID() {
return id;
}
/**
* Set the id of photon
*
* @param id photon id
*/
public void setID(String id) {
this.id = id;
}
/**
* @return the time of last heartbeat
*/
public String getLastBeat() {
return lastBeat;
}
/**
* Set the time of last heartbeat of photon objext
*
* @param lastBeat time of last heartbeat
*/
public void setLastBeat(String lastBeat) {
this.lastBeat = lastBeat;
}
/**
* @return the state of connection
*/
public String getState() {
return state;
}
/**
* Set the connection information to be sent to client
*
* @param state the state of connection between photon and servlet
*/
public void setState(String state) {
this.state = state;
}
/**
* @return The encoded photon object
*/
public String toJson() {
StringBuilder json = new StringBuilder();
json.append("{\n");
json.append("\"generated\":" + "\"" + System.currentTimeMillis() + "\",\n");
json.append("\"photonId\":" + "\"" + getID() + "\",\n");
json.append("\"stateInfo\":" + "\"" + getState() + "\",\n");
json.append("\"lastBeat\":" + "\"" + getLastBeat() + "\"\n");
json.append("}");
return json.toString();
}
}
| true
|
59881682f4923b1b685afa8fcffbf316eb082cb4
|
Java
|
carsonshan/swingFactory
|
/src/main/java/net/saucefactory/swing/data/SFFieldDataAdapter.java
|
UTF-8
| 811
| 2.6875
| 3
|
[] |
no_license
|
package net.saucefactory.swing.data;
public class SFFieldDataAdapter implements ISFDataAdapter {
String fieldName;
public SFFieldDataAdapter(String fieldName) {
this.fieldName = fieldName;
}
public Object getValue(Object source) {
try {
return source.getClass().getField(fieldName).get(source);
} catch(Exception e) {
return null;
}
}
public void setValue(Object target, Object value) {
try {
target.getClass().getField(fieldName).set(target, value);
} catch(Exception e) {
return;
}
}
public boolean isValue(Object value, Object target) {
value = getValue(value);
if(value == null)
return target == null;
if(target == null)
return false;
return target.equals(value);
}
}
| true
|
7e782ee7ebbf99ad74c07e798af7e29695aefb3b
|
Java
|
cckmit/QcAndroid
|
/shop/src/main/java/cn/qingchengfit/shop/ui/inventory/ShopTimeFilterFragment.java
|
UTF-8
| 1,442
| 1.960938
| 2
|
[] |
no_license
|
package cn.qingchengfit.shop.ui.inventory;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.EditText;
import android.widget.TextView;
import cn.qingchengfit.saascommon.filtertime.FilterCustomFragment;
import cn.qingchengfit.shop.R;
/**
* Created by huangbaole on 2018/1/23.
*/
public class ShopTimeFilterFragment extends FilterCustomFragment {
@Nullable @Override
public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container,
@Nullable Bundle savedInstanceState) {
View view = super.onCreateView(inflater, container, savedInstanceState);
TextView textBack = view.findViewById(R.id.tv_absence_filter_reset);
EditText editStart = view.findViewById(R.id.edit_absence_start);
EditText editEnd = view.findViewById(R.id.edit_absence_end);
textBack.setText("重置");
textBack.setOnClickListener(new View.OnClickListener() {
@Override public void onClick(View v) {
editStart.setText("开始日期");
editEnd.setText("结束日期");
}
});
return view;
}
public static ShopTimeFilterFragment newInstance(String title) {
Bundle args = new Bundle();
args.putString("title",title);
ShopTimeFilterFragment fragment = new ShopTimeFilterFragment();
fragment.setArguments(args);
return fragment;
}
}
| true
|
9c966eaf7e8f89deeafb0845c351c6cdc20d8ccb
|
Java
|
zhouzms/getproject
|
/founding/src/main/java/com/zms/founding/manage/dao/UserDao.java
|
UTF-8
| 684
| 2.0625
| 2
|
[] |
no_license
|
package com.zms.founding.manage.dao;
import java.util.List;
import java.util.Map;
import org.apache.ibatis.annotations.Param;
import com.zms.founding.bean.User;
public interface UserDao {
/*
* 用户登录数据返回
*/
User loginDao(Map<String, Object> map);
/*
* 总用户数
*/
int userCount();
/*
* 分页的数据
*/
List<User> queryUser(@Param("sInteger") Integer sInteger,@Param("pagesize") Integer pagesize);
/**
* 用户保存
*/
int insert(User user);
/**
* 用户id查询
* */
User queryById(@Param("id") int id);
/**
* 更新用户信息
*/
int updateUser(User user);
/**
* 删除用户信息
*/
int deleteUser(User user);
}
| true
|
2326b49f73391df4ee0f9a8fac1a29d57e2ec919
|
Java
|
haluwama/RPNCalc
|
/src/InfixToPostfix.java
|
UTF-8
| 3,618
| 3.40625
| 3
|
[] |
no_license
|
import java.util.ArrayList;
import java.util.Stack;
public class InfixToPostfix {
private char[] digits = {'1', '2', '3', '4', '5', '6', '7', '8', '9', '.'};
private char[] operators = {'+', '-', '*', '/', '(', ')', '^'};
InfixToPostfix() {
}
public ArrayList<Element> toPostfix(String equation) {
ArrayList<Element> smashedEq = changeEquationToArrayList(equation);
ArrayList<Element> infixEq = new ArrayList<>();
Stack<Element> operators = new Stack<>();
for (int i = 0; i < smashedEq.size(); i++) {
if (smashedEq.get(i).getTyp() == Types.NUMBER) {
infixEq.add(smashedEq.get(i));
} else {
if (smashedEq.get(i).getOperator().equals("(")) {
operators.push(smashedEq.get(i));
} else if (smashedEq.get(i).getOperator().equals(")")) {
while (!operators.peek().getOperator().equals("(")) {
infixEq.add(operators.pop());
}
operators.pop();
while (operators.empty() != true) {
infixEq.add(operators.pop());
}
} else if (operators.empty()) {
operators.push(smashedEq.get(i));
} else if (operators.peek().getPriority() < smashedEq.get(i).getPriority()) {
operators.push(smashedEq.get(i));
} else if (operators.peek().getPriority() >= smashedEq.get(i).getPriority()) {
while (!operators.empty()) {
if (operators.peek().getPriority() >= smashedEq.get(i).getPriority())
infixEq.add(operators.pop());
else
break;
}
operators.push(smashedEq.get(i));
}
}
}
while (!operators.empty()) {
infixEq.add(operators.pop());
}
return infixEq;
}
private ArrayList<Element> changeEquationToArrayList(String equation) {
ArrayList<Element> smashedEq = new ArrayList<Element>();
String tmp = "";
for (int i = 0; i < equation.length(); i++) {
for (int j = 0; j < digits.length; j++) {
if (equation.charAt(i) == digits[j]) {
tmp = tmp + equation.charAt(i);
break;
}
}
for (int j = 0; j < operators.length; j++) {
if (equation.charAt(i) == operators[j]) {
if (tmp.length() > 0) {
smashedEq.add(new Element(Double.parseDouble(tmp), Types.NUMBER));
}
tmp = "" + equation.charAt(i);
switch (tmp) {
case "+":
smashedEq.add(new Element(tmp, Types.ADDITION));
break;
case "-":
smashedEq.add(new Element(tmp, Types.SUBTRACTION));
break;
case "*":
smashedEq.add(new Element(tmp, Types.MULTIPLICATION));
break;
case "/":
smashedEq.add(new Element(tmp, Types.DIVISION));
break;
case "(":
smashedEq.add(new Element(tmp, Types.PARENTHESIS_LEFT));
break;
case ")":
smashedEq.add(new Element(tmp, Types.PARENTHESIS_RIGHT));
break;
case "^":
smashedEq.add(new Element(tmp, Types.POWER));
break;
}
tmp = "";
}
}
}
//If tmp is length more tham 0, then tmp is number, because only when it's iterating through operators array there can be add a number.
if (tmp.length() > 0)
smashedEq.add(new Element(Double.parseDouble(tmp), Types.NUMBER));
return smashedEq;
}
/*
private int isUnrecognizableChars()
{
return 0;
}
*/
}
| true
|
cf137cc6c69a6799f2eb8fb318b30a120fce0c6f
|
Java
|
authrus/database
|
/authrus-database-sql/src/main/java/com/authrus/database/sql/compile/UpdateCompiler.java
|
UTF-8
| 3,343
| 2.421875
| 2
|
[] |
no_license
|
package com.authrus.database.sql.compile;
import static com.authrus.database.data.DataType.BOOLEAN;
import static com.authrus.database.data.DataType.SYMBOL;
import static com.authrus.database.data.DataType.TEXT;
import static com.authrus.database.sql.ParameterType.VALUE;
import java.util.Arrays;
import java.util.Collections;
import java.util.List;
import java.util.Map;
import com.authrus.database.data.DataType;
import com.authrus.database.sql.Parameter;
import com.authrus.database.sql.ParameterType;
import com.authrus.database.sql.Query;
import com.authrus.database.sql.Verb;
public class UpdateCompiler extends SelectCompiler {
public UpdateCompiler() {
this(Collections.EMPTY_MAP);
}
public UpdateCompiler(Map<String, String> translations) {
this.translations = translations;
}
@Override
public String compile(Query query, Object[] list) throws Exception {
Verb verb = query.getVerb();
String source = query.getSource();
String original = verb.getVerb();
String replace = translate(original);
if(replace == null) {
throw new IllegalStateException("Verb conversion for '" + source + "' was null");
}
List<Parameter> parameters = query.getParameters();
String table = query.getTable();
int count = parameters.size();
int index = 0;
if(table == null) {
throw new IllegalArgumentException("Update statement '" + source + "' does not specify a table");
}
StringBuilder builder = new StringBuilder();
builder.append(replace);
builder.append(" ");
builder.append(table);
builder.append(" set ");
for(int i = 0; i < count; i++) {
Parameter parameter = parameters.get(i);
ParameterType type = parameter.getType();
String column = parameter.getColumn();
Object value = parameter.getValue();
if(type != VALUE) {
value = list[index++];
}
if(i > 0) {
builder.append(", ");
}
builder.append(column);
builder.append(" = ");
if(value != null) {
String token = compileToken(value);
if(token == null) {
throw new IllegalArgumentException("Translation of '" + value +"' was null in '" + source + "'");
}
builder.append(token);
} else {
builder.append("null");
}
}
Object[] remainder = Arrays.copyOfRange(list, index, list.length);
String whereClause = compileWhere(query, remainder);
if(whereClause != null) {
builder.append(" ");
builder.append(whereClause);
}
return builder.toString();
}
public String compileToken(Object value) throws Exception {
Class type = value.getClass();
DataType data = DataType.resolveType(type);
String text = String.valueOf(value);
if(text.equalsIgnoreCase("null")) {
return text;
}
if(data == TEXT) {
return quote(text);
}
if(data == SYMBOL) {
return quote(text);
}
if(data == BOOLEAN) {
return quote(text);
}
return text;
}
}
| true
|
1a47a782773abf9602c79553acd3b5348ffa0465
|
Java
|
asouza/react-server-example
|
/src/main/java/br/com/asouza/reactor/daos/ResultSetIterator.java
|
UTF-8
| 907
| 2.890625
| 3
|
[] |
no_license
|
package br.com.asouza.reactor.daos;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.Iterator;
import java.util.function.Function;
/**
* Adapter that should transform {@link ResultSet} into an Iterable of some domain object
* @author alberto
*
* @param <T>
*/
public class ResultSetIterator<T> implements Iterable<T> {
private ResultSet resultSet;
private Function<ResultSet, T> transformer;
public ResultSetIterator(ResultSet resultSet,Function<ResultSet, T> transformer) {
this.resultSet = resultSet;
this.transformer = transformer;
}
@Override
public Iterator<T> iterator() {
return new Iterator<T>() {
@Override
public boolean hasNext() {
try {
return resultSet.next();
} catch (SQLException e) {
throw new RuntimeException(e);
}
}
@Override
public T next() {
return transformer.apply(resultSet);
}
};
}
}
| true
|
eb08a4bd0c240b5e412056c3c9b24d5d93d40eab
|
Java
|
mithundas79/Taxi-Driver
|
/src/com/chaos/driver/GestureHandler.java
|
UTF-8
| 151
| 1.773438
| 2
|
[] |
no_license
|
package com.chaos.driver;
import android.graphics.RectF;
public interface GestureHandler {
public boolean processGesture(String name,RectF rect);
}
| true
|
44312c063c23d2ec6ba1c8f7df4c61a92ce2ebe1
|
Java
|
wxwcase/LC_Solutions
|
/src/test/lc_easy/LC371_SumOf2IntsTest.java
|
UTF-8
| 815
| 2.609375
| 3
|
[] |
no_license
|
package test.lc_easy;
import main.lc_easy.LC371_SumOf2Ints;
import org.junit.jupiter.api.AfterEach;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import static org.junit.jupiter.api.Assertions.*;
/**
* Created by wwang on 12/15/2016.
*/
class LC371_SumOf2IntsTest {
LC371_SumOf2Ints sol;
@BeforeEach
void setUp() {
sol = new LC371_SumOf2Ints();
}
@AfterEach
void tearDown() {
sol = null;
}
@Test
void getSum1and2() {
int a = 1, b = 2;
assertEquals(3, sol.getSum(a, b));
}
@Test
void getSum10and21() {
int a = 10, b = 21;
assertEquals(31, sol.getSum(a, b));
}
@Test
void getSumTwoZeros() {
int a = 0, b = 0;
assertEquals(0, sol.getSum(a, b));
}
}
| true
|
a35bde4dbd92ed6322ea13731cd79f8cce9d0048
|
Java
|
JPeterson462/DigiTurtle-Engine
|
/src/engine/world/physics/PolyhedronBounds.java
|
UTF-8
| 5,478
| 2.59375
| 3
|
[] |
no_license
|
package engine.world.physics;
import java.util.ArrayList;
import org.joml.Quaternionf;
import org.joml.Vector2f;
import org.joml.Vector3f;
import utils.Accessor;
public class PolyhedronBounds implements Bounds {
private Accessor<Vector3f> getPosition;
private Accessor<Quaternionf> getOrientation;
private Polyhedron polyhedron;
private class Overlap {
private Vector3f overlapV, overlapN; // minimum translation vector, overlap axis
private float overlap = Float.MAX_VALUE; // overlap distance
private boolean aInB, bInA;
public Overlap() {
aInB = true;
bInA = true;
overlapV = new Vector3f();
overlapN = new Vector3f();
}
}
public PolyhedronBounds(Polyhedron polyhedron) {
this.polyhedron = polyhedron;
}
@Override
public void setAccessors(Accessor<Vector3f> getPosition, Accessor<Quaternionf> getOrientation) {
this.getPosition = getPosition;
this.getOrientation = getOrientation;
}
@Override
public boolean overlaps(Bounds other) {
return overlaps(other, new Overlap());
}
@Override
public Vector3f getOverlap(Bounds other) {
Overlap overlap = new Overlap();
if (overlaps(other, overlap)) {
overlap.overlapV.set(overlap.overlapN).mul(overlap.overlap);
return overlap.overlapV;
}
return null;
}
@Override
public Vector3f intersects(Ray ray) {
ArrayList<Vector3f> vertices = polyhedron.getVertices();
for (int v = 0; v < vertices.size() - 2; v++) {
Triangle triangle;
if ((v & 1) != 0) {
triangle = new Triangle(vertices.get(v + 0), vertices.get(v + 1), vertices.get(v + 2));
} else {
triangle = new Triangle(vertices.get(v + 0), vertices.get(v + 2), vertices.get(v + 1));
}
Vector3f intersection = triangle.intersects(ray);
if (intersection != null) {
return intersection;
}
}
return null;
}
private boolean overlaps(Bounds other, Overlap overlap) {
polyhedron.project(getOrientation.get(), getPosition.get());
if (other instanceof PolyhedronBounds) {
PolyhedronBounds polyOther = (PolyhedronBounds) other;
polyOther.polyhedron.project(polyOther.getOrientation.get(), polyOther.getPosition.get());
ArrayList<Vector3f> a = polyhedron.getVertices();
ArrayList<Vector3f> b = polyOther.polyhedron.getVertices();
Vector3f axis = new Vector3f(), edge1 = new Vector3f(), edge2 = new Vector3f();
Vector3f v1, v2, v3;
for (int v = 0; v < a.size() - 2; v++) {
if ((v & 1) != 0) {
v1 = a.get(v + 0);
v2 = a.get(v + 1);
v3 = a.get(v + 2);
} else {
v1 = a.get(v + 0);
v2 = a.get(v + 2);
v3 = a.get(v + 1);
}
edge1.set(v2).sub(v1);
edge2.set(v3).sub(v1);
axis.set(edge1).cross(edge2).normalize();
if (axis.lengthSquared() == 0) {
continue;
}
if (isSeparatingAxis(a, polyhedron.getPosition(), b, polyOther.polyhedron.getPosition(), axis, overlap)) {
return false;
}
}
for (int v = 0; v < b.size() - 2; v++) {
if ((v & 1) != 0) {
v1 = b.get(v + 0);
v2 = b.get(v + 1);
v3 = b.get(v + 2);
} else {
v1 = b.get(v + 0);
v2 = b.get(v + 2);
v3 = b.get(v + 1);
}
edge1.set(v2).sub(v1);
edge2.set(v3).sub(v1);
axis.set(edge1).cross(edge2).normalize();
if (axis.lengthSquared() == 0) {
continue;
}
if (isSeparatingAxis(a, polyhedron.getPosition(), b, polyOther.polyhedron.getPosition(), axis, overlap)) {
return false;
}
}
return true;
}
return false;
}
private boolean isSeparatingAxis(ArrayList<Vector3f> a, Vector3f aPosition, ArrayList<Vector3f> b, Vector3f bPosition, Vector3f axis, Overlap overlap) {
Vector3f offset = new Vector3f();
Vector2f rangeA = new Vector2f(), rangeB = new Vector2f();
offset.set(bPosition).sub(aPosition);
float projectedOffset = offset.dot(axis);
flattenPoints(a, axis, rangeA);
flattenPoints(b, axis, rangeB);
rangeB.add(projectedOffset, projectedOffset);
if (rangeA.x > rangeB.y || rangeB.x > rangeA.y) {
return true;
}
float overlapDistance;
if (rangeA.x < rangeB.x) {
overlap.aInB = false;
if (rangeA.y < rangeB.y) {
overlapDistance = rangeA.y - rangeB.x;
overlap.bInA = false;
} else {
float delta1 = rangeA.y - rangeB.x;
float delta2 = rangeB.y - rangeA.x;
overlapDistance = delta1 < delta2 ? delta1 : -delta2;
}
} else {
overlap.bInA = false;
if (rangeA.y > rangeB.y) {
overlapDistance = rangeA.y - rangeB.x;
overlap.aInB = false;
} else {
float delta1 = rangeA.y - rangeB.x;
float delta2 = rangeB.y - rangeA.x;
overlapDistance = delta1 < delta2 ? delta1 : -delta2;
}
}
float signedOverlapDistance = overlapDistance;
overlapDistance = Math.abs(overlapDistance);
if (overlapDistance < overlap.overlap) {
overlap.overlap = overlapDistance;
overlap.overlapN.set(axis.normalize());
if (signedOverlapDistance < 0) {
overlap.overlapN.negate();
}
}
return false;
}
private void flattenPoints(ArrayList<Vector3f> vertices, Vector3f axis, Vector2f projection) {
float min = axis.dot(vertices.get(0));
float max = min;
for (int i = 1; i < vertices.size(); i++) {
float dot = axis.dot(vertices.get(i));
if (dot < min) {
min = dot;
}
if (dot > max) {
max = dot;
}
}
projection.set(min, max);
}
}
| true
|
e4366012acbc8e317e1178219149dfa61c45fae2
|
Java
|
estevandiedrich/NotaFiscalEletronicaBrasileiraV20
|
/src/br/com/hs/nfe/dpecproc/DpecProcThread.java
|
ISO-8859-1
| 3,001
| 2.109375
| 2
|
[] |
no_license
|
package br.com.hs.nfe.dpecproc;
import java.io.File;
import java.io.FileInputStream;
import java.util.List;
import org.apache.commons.io.IOUtils;
import org.apache.log4j.Logger;
import br.com.hs.nfe.base.ThreadBase;
import br.com.hs.nfe.dao.NFeDAO;
import br.com.hs.nfe.dom.builder.DpecProcDocumentBuilder;
import br.com.hs.nfe.entity.Estabelecimento;
import br.com.hs.nfe.entity.Nfe;
import br.com.hs.nfe.file.FileManager;
import br.com.hs.nfe.hb.NFeUpdateCommand;
import br.com.hs.nfe.queue.DpecAutorizados;
import br.com.hs.nfe.queue.DpecDescompactados;
import br.com.hs.nfe.queue.DpecProcessados;
import br.com.hs.nfe.vo.NFeVO;
public class DpecProcThread extends ThreadBase{
private static final Logger logger = Logger.getLogger("DpecProcThread");
private Estabelecimento config = null;
private DpecProcDocumentBuilder documentBuilder = null;
private NFeDAO nfeDao = new NFeDAO();
public DpecProcThread(Estabelecimento config)
{
this.documentBuilder = new DpecProcDocumentBuilder();
this.config = config;
}
public void run()
{
Thread.currentThread().setName( "DpecProcThread_"+config.getCnpj()+"_"+config.getPe() );
logger.info("Iniciando thread DpecProcThread_"+config.getCnpj()+"_"+config.getPe() );
while ( super.isRunning() )
{
try
{
List<Nfe> nfeList = nfeDao.procuraDpecAutorizados(config.getCnpj(),config.getPe());
for(Nfe nfe:nfeList)
{
NFeVO enviNFeXML = DpecAutorizados.getInstance().getNFeVOPorChaveAcesso(nfe.getChaveAcesso());
if(enviNFeXML == null)
{
enviNFeXML = new NFeVO();
File retDPEC = new File(config.getEnvDpecXMLAutorizados()+File.separatorChar+nfe.getChaveAcesso()+"-dpec-aut.xml");
FileInputStream fis2 = new FileInputStream(retDPEC);
enviNFeXML.setChaveAcesso(nfe.getChaveAcesso());
enviNFeXML.setRetDpecXMLString(IOUtils.toString(fis2));
IOUtils.closeQuietly(fis2);
}
File enviNFe = new File(config.getEnviNFeXMLValidos()+File.separatorChar+nfe.getChaveAcesso()+".xml");
FileInputStream fis = new FileInputStream(enviNFe);
enviNFeXML.setNfeXMLString(IOUtils.toString(fis));
IOUtils.closeQuietly(fis);
String dpecProc = documentBuilder.dpecProcDocumentBuilder(enviNFeXML);
enviNFeXML.setDpecProc(dpecProc);
DpecProcessados.getInstance().add(enviNFeXML);
DpecDescompactados.getInstance().add(enviNFeXML);
FileManager.getInstance().saveFile(config.getEnvDpecXMLProcessados()+File.separatorChar+nfe.getChaveAcesso()+"-dpec-proc.xml", dpecProc);
nfe.setDpecProcessado('1');
NFeUpdateCommand updateCommand = new NFeUpdateCommand(nfe);
updateCommand.execute();
}
}
catch(Throwable t)
{
logger.error("Erro no capturado", t);
}
try
{
Thread.sleep( Integer.parseInt(config.getEnviNFeThreadSleep()) );
}
catch ( InterruptedException e )
{
logger.error("Problemas ao interromper a Thread DpecProcThread", e);
}
finally
{
}
}
}
}
| true
|
9d25a780509a9a3438f24ec3c002bb0e9238248e
|
Java
|
zlmone/PhoneManager-2
|
/app/src/main/java/com/example/security/ui/QueryNumberActivity.java
|
UTF-8
| 671
| 1.859375
| 2
|
[] |
no_license
|
package com.example.security.ui;
import android.app.Activity;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.widget.Button;
import android.widget.EditText;
import com.example.sunzhaohenan.phonemanager.R;
/**
* Created by sunzhaohenan on 2018/3/25.
*/
public class QueryNumberActivity extends Activity {
private EditText queryNumber_et;
private Button query_bt;
@Override
protected void onCreate(@Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
queryNumber_et=(EditText)findViewById(R.id.et_query_number);
query_bt=(Button)findViewById(R.id.bt_query);
}
}
| true
|
86a27f0a6b0ec63e49a8c9b6859af64f805fa38d
|
Java
|
cote/jaasbook
|
/src/java/util/LoggerInit.java
|
UTF-8
| 1,178
| 2.84375
| 3
|
[] |
no_license
|
package util;
import java.io.IOException;
import java.io.InputStream;
import java.security.AccessController;
import java.security.PrivilegedAction;
import java.util.logging.LogManager;
public class LoggerInit
{
static public void init()
{
AccessController.doPrivileged(new PrivilegedAction()
{
public Object run()
{
InputStream in = LoggerInit.class.getResourceAsStream("/logger.properties");
if (in != null)
{
try
{
LogManager.getLogManager().readConfiguration(in);
System.out.println("Configured logger with logger.properties");
}
catch (SecurityException e)
{
System.out.println("Error reconfiguring LogManager with logger.properties. Default logging will be used.");
}
catch (IOException e)
{
System.out.println("Error reconfiguring LogManager with logger.properties. Default logging will be used.");
}
}
else
{
System.out.println("logger.properties not found, using default Logger settings.");
}
return null;
}
});
}
}
| true
|
aec2969f229d8429a1bccce78d1ec71a70b357fb
|
Java
|
stalbot/catan_game
|
/server/src/com/steven/catanserver/Intersection.java
|
UTF-8
| 3,825
| 2.75
| 3
|
[] |
no_license
|
package com.steven.catanserver;
import java.util.*;
public class Intersection implements DataContainer.Keyable {
private int id;
private ArrayList<Integer> hexIds = new ArrayList<Integer>(3);
private transient HashSet<Hex> hexes = null;
private Boolean isCity = false;
private PlayerColor color = null;
private HarborType harborType;
private transient HashMap<Integer, Intersection> neighborIntersections = null;
private transient IntersectionData parent;
private DataContainer.KeyedRelation<Edge> neighboringEdges = null;
Intersection(int id) {
this.id = id;
}
Intersection(Intersection toCopy, IntersectionData parent) {
this.parent = parent;
this.hexIds = new ArrayList<Integer>(toCopy.hexIds);
this.isCity = toCopy.isCity;
this.color = toCopy.color;
this.harborType = toCopy.harborType;
for (Edge edge : toCopy.getNeighboringEdges().getAll())
if (edge != null)
this.getNeighboringEdges().add(edge);
this.id = toCopy.id;
}
private DataContainer.KeyedRelation<Edge> getNeighboringEdges() {
// if (this.parent == null)
// return null;
assert (this.parent != null);
if (this.neighboringEdges == null)
this.neighboringEdges = new DataContainer.KeyedRelation<Edge>(this.parent.getEdgeData());
if (this.neighboringEdges.getRawData() == null)
// if this was instantiated from GSON
this.neighboringEdges.setup(this.parent.getEdgeData());
return this.neighboringEdges;
}
void setParent(IntersectionData interd) {
this.parent = interd;
}
public void setHarborType(HarborType ht) {
this.harborType = ht;
}
public int getId() {
return this.id;
}
public HarborType getHarbor() {
return this.harborType;
}
public void setHexes(Collection<Hex> hexes) {
this.hexes = new HashSet<Hex>(hexes);
for (Hex hex : this.hexes)
if (hex != null)
// perfectly valid for this to be null along edge
this.hexIds.add(hex.getId());
}
public Iterable<Hex> getHexes() {
if (this.hexes == null) {
this.hexes = new HashSet<Hex>(3);
for (Integer i : this.hexIds) {
Board b = this.parent.getBoard();
this.hexes.add(b.getHex(i));
}
}
return this.hexes;
}
public void addEdge(Edge e) {
this.getNeighboringEdges().add(e);
}
public Iterable<Edge> getEdges() {
return this.getNeighboringEdges().getAll();
}
public Boolean hasSettlement() {
return this.color != null;
}
public List<Edge> getAllNeighboringEdges() {
return this.getNeighboringEdges().getAll();
}
public HashMap<Integer, Intersection> getNeighborIntersections() {
if (this.neighborIntersections == null) {
this.neighborIntersections = new HashMap<Integer, Intersection>(3);
for (Edge e : this.getEdges())
for (Intersection i : e.getIntersections())
if (i.getId() != this.getId())
this.neighborIntersections.put(i.getId(), i);
}
return this.neighborIntersections;
}
public Boolean canPlaceSettlement() {
if (this.hasSettlement())
return false;
// System.out.println("Neighbors " + this.getNeighborIntersections().values());
// System.out.println("Edges " + this.getEdges());
// System.out.println("Edge ids" + this.edgeIds);
for(Intersection inter : this.getNeighborIntersections().values())
if (inter.hasSettlement())
return false;
return true;
}
public void placeSettlement(Player p) {
// System.out.println("Placing settlement on intersection " + this.getId() + " with edge neighbors " + this.getNeighboringEdges().ids);
this.color = p.getPlayerColor();
}
public void placeCity(Player p) {
assert(this.color == p.getPlayerColor());
this.isCity = true;
}
public boolean canPlaceCity() {
return (!this.isCity && this.color != null);
}
public PlayerColor getSettlementColor() {
return this.color;
}
public boolean getIsCity() {
return this.isCity;
}
}
| true
|
c15bb4ee9c94db119fe036af7ecfd5d944f53e99
|
Java
|
kevingekun/examSystem
|
/examSystem/src/com/wondersgroup/falcon/Util/DateOptions.java
|
GB18030
| 1,061
| 2.390625
| 2
|
[] |
no_license
|
/**
* <p>Title: ̳</p>
* <p>Description: ̳</p>
* <p>Copyright: Copyright (c) 2004</p>
* <p>Company: 㹤</p>
* @author
* @version 2.0
*/
package com.wondersgroup.falcon.Util;
import java.util.ResourceBundle;
import org.apache.log4j.*;
final class DateOptions {
private static Logger log = Logger.getLogger(DateOptions.class);
private static final String OPTION_FILE_NAME = "fiyucore_util_DateOptions";
//default values
int serverHourOffset = 0;
DateOptions() {
try {
ResourceBundle res = ResourceBundle.getBundle(OPTION_FILE_NAME);
String strOffset = res.getString("SERVER_HOUR_OFFSET").trim();
serverHourOffset = Integer.parseInt(strOffset);
} catch (Exception e) {
String message = "fiyucore.util.ParamOptions: ܶȡļ: '" + OPTION_FILE_NAME + ".properties'. ȷϸļȷʵڣ";
log.error(message, e);
}
}//constructor
}
| true
|
9ccfb8b48a537c2d4faa01c85f005c2d32f95016
|
Java
|
blackducksoftware/hub-notification
|
/src/main/java/com/blackducksoftware/notification/batch/processor/JobCompletionNotificationListener.java
|
UTF-8
| 2,327
| 2.171875
| 2
|
[
"Apache-2.0"
] |
permissive
|
/**
* hub-notification
*
* Copyright (C) 2017 Black Duck Software, Inc.
* http://www.blackducksoftware.com/
*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
/*
*
*/
package com.blackducksoftware.notification.batch.processor;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.springframework.batch.core.BatchStatus;
import org.springframework.batch.core.JobExecution;
import org.springframework.batch.core.listener.JobExecutionListenerSupport;
import org.springframework.stereotype.Component;
/**
* The listener interface for receiving jobCompletionNotification events.
* The class that is interested in processing a jobCompletionNotification
* event implements this interface, and the object created
* with that class is registered with a component using the
* component's <code>addJobCompletionNotificationListener<code> method. When
* the jobCompletionNotification event occurs, that object's appropriate
* method is invoked.
*
* @see JobCompletionNotificationEvent
*/
@Component
public class JobCompletionNotificationListener extends JobExecutionListenerSupport {
/** The Constant log. */
private final Logger logger = LogManager.getLogger(JobCompletionNotificationListener.class);
/* (non-Javadoc)
* @see org.springframework.batch.core.listener.JobExecutionListenerSupport#afterJob(org.springframework.batch.core.JobExecution)
*/
@Override
public void afterJob(JobExecution jobExecution) {
if(jobExecution.getStatus() == BatchStatus.COMPLETED) {
logger.info("!!! JOB FINISHED!");
}
}
}
| true
|
270255e73e365c541802664d548c95d29c052ea1
|
Java
|
k-si/Autoium
|
/back end/autoium/src/main/java/run/autoium/utils/AToBUtils.java
|
UTF-8
| 3,252
| 2.8125
| 3
|
[] |
no_license
|
package run.autoium.utils;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import run.autoium.entity.MyAssert;
import java.lang.reflect.Constructor;
import java.lang.reflect.Method;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
/**
* 将一个类型转为另一个类型
*/
public class AToBUtils {
/**
* json字符串转为list对象
*
* @param json json字符串
* @param clazz list存储的对象
* @param <T> 泛型T,必须包含属性key和value
* @return list对象
*/
public static <T> List<T> jsonToList(String json, Class<T> clazz) {
JSONArray array = JSONArray.parseArray(json);
List<T> list = new ArrayList<>();
try {
for (int i = 0; i < array.size(); i++) {
JSONObject object = array.getJSONObject(i);
Constructor<T> constructor = clazz.getConstructor(String.class, String.class);
T t = constructor.newInstance(object.getString("key"), object.getString("value"));
list.add(t);
}
} catch (Exception e) {
e.printStackTrace();
}
return list;
}
/**
* 断言的json字符串转为list
*
* @param examine 断言
* @return
*/
public static List<MyAssert> examineToList(String examine) {
JSONArray array = JSONArray.parseArray(examine);
List<MyAssert> myAsserts = new ArrayList<>();
for (int i = 0; i < array.size(); i++) {
JSONObject object = array.getJSONObject(i);
MyAssert myAssert = new MyAssert();
myAssert.setDataSource(object.getInteger("dataSource"));
myAssert.setData(object.getString("data"));
myAssert.setExpress(object.getString("express"));
myAssert.setExpectRelation(object.getInteger("expectRelation"));
myAssert.setRelation(object.getString("relation"));
myAssert.setExpectType(object.getInteger("expectType"));
myAssert.setType(object.getString("type"));
myAssert.setExpectValue(object.getString("expectValue"));
myAsserts.add(myAssert);
}
return myAsserts;
}
/**
* list对象转为map
*
* @param list list对象
* @param clazz list存储的对象
* @param <T> 泛型T,必须包含属性key和value
* @return map对象
*/
public static <T> Map<String, String> listToMap(List<T> list, Class<T> clazz) {
Map<String, String> map = new HashMap<>();
try {
for (T t : list) {
Method getKey = t.getClass().getMethod("getKey");
getKey.setAccessible(true);
String key = (String) getKey.invoke(t);
Method getValue = t.getClass().getMethod("getValue");
getValue.setAccessible(true);
String value = (String) getValue.invoke(t);
if (key.length() != 0 && value.length() != 0) {
map.put(key, value);
}
}
} catch (Exception e) {
e.printStackTrace();
}
return map;
}
}
| true
|
5d0c1f1a5b92f7d7cb4285450c6dfcd80fb22a62
|
Java
|
automenta/chronoproof
|
/src/main/java/ws/prova/reference2/builtins/ProvaTypeImpl.java
|
UTF-8
| 1,781
| 2.1875
| 2
|
[] |
no_license
|
package ws.prova.reference2.builtins;
import java.util.List;
import ws.prova.agent2.Reagent;
import ws.prova.kernel2.Constant;
import ws.prova.kernel2.Derivation;
import ws.prova.kernel2.Goal;
import ws.prova.kernel2.KB;
import ws.prova.kernel2.PList;
import ws.prova.kernel2.Literal;
import ws.prova.kernel2.PObj;
import ws.prova.kernel2.Rule;
import ws.prova.kernel2.Variable;
import ws.prova.kernel2.VariableIndex;
import ws.prova.reference2.ProvaConstantImpl;
public class ProvaTypeImpl extends ProvaBuiltinImpl {
public ProvaTypeImpl(KB kb) {
super(kb,"type");
}
@Override
public boolean process(Reagent prova, Derivation node,
Goal goal, List<Literal> newLiterals, Rule query) {
Literal literal = goal.getGoal();
List<Variable> variables = query.getVariables();
PList terms = literal.getTerms();
PObj[] data = terms.getFixed();
if( data.length!=2 )
return false;
PObj lt = data[0];
if( lt instanceof VariableIndex ) {
VariableIndex varPtr = (VariableIndex) lt;
lt = variables.get(varPtr.getIndex()).getRecursivelyAssigned();
}
String className = null;
if( lt instanceof Constant )
className = ((Constant) lt).getObject().getClass().getName();
else if( lt instanceof Variable )
className = Variable.class.getName();
else
className = PList.class.getName();
PObj out = data[1];
if( out instanceof VariableIndex ) {
VariableIndex varPtr = (VariableIndex) out;
out = variables.get(varPtr.getIndex()).getRecursivelyAssigned();
}
if( out instanceof Constant ) {
return ((Constant) out).getObject().equals(className);
} else if( out instanceof Variable ) {
((Variable) out).setAssigned(ProvaConstantImpl.create(className));
}
return true;
}
}
| true
|
26b8cc4cc393be057016c022450a43f510c8dfd6
|
Java
|
ddatut/intro_Java_edition8
|
/Chapter09/Exercises/Exercise09_07.java
|
UTF-8
| 2,334
| 3.875
| 4
|
[] |
no_license
|
package Chapter09.Exercises;
import java.util.Scanner;
/**
*
* @author Shady Bajary
* @Exercise 9.7
* @Title Phone Keypads
*/
public class Exercise09_07 {
public static void main(String[] args) {
Scanner scan = new Scanner(System.in);
System.out.print("Enter a string: ");
String string = scan.nextLine();
string = string.toUpperCase();
StringBuilder number = new StringBuilder();
for (int i = 0; i < string.length(); i++) {
int num = getNumber(string.charAt(i));
if (num<= 9) {
number.append(num);
}else{
number.append((char)num);
}
}
System.out.println(number.toString());
}
public static int getNumber(char uppercaseLetter) {
int value = -1;
switch (uppercaseLetter) {
case '1':
value = 1;
break;
case '2':
case 'A':
case 'B':
case 'C':
value = 2;
break;
case '3':
case 'D':
case 'E':
case 'F':
value = 3;
break;
case '4':
case 'G':
case 'H':
case 'I':
value = 4;
break;
case '5':
case 'J':
case 'K':
case 'L':
value = 5;
break;
case '6':
case 'M':
case 'N':
case 'O':
value = 6;
break;
case '7':
case 'P':
case 'Q':
case 'R':
case 'S':
value = 7;
break;
case '8':
case 'T':
case 'U':
case 'V':
value = 8;
break;
case '9':
case 'W':
case 'X':
case 'Y':
case 'Z':
value = 9;
break;
case '0':
value = 0;
break;
default:
return uppercaseLetter;
}
return value;
}
}
| true
|
f28e0dc4007ae8029ed6d0ab7131adafcf353089
|
Java
|
alekhyabathula0801/FundooNotesBackend
|
/src/main/java/com/bridgelabz/demo/model/User.java
|
UTF-8
| 2,133
| 2.265625
| 2
|
[] |
no_license
|
package com.bridgelabz.demo.model;
import java.time.LocalDateTime;
import java.util.Set;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.ManyToMany;
import javax.persistence.Table;
import javax.validation.constraints.Email;
import javax.validation.constraints.NotEmpty;
import javax.validation.constraints.Pattern;
import org.hibernate.annotations.CreationTimestamp;
import org.hibernate.annotations.UpdateTimestamp;
import com.fasterxml.jackson.annotation.JsonIgnore;
import lombok.Getter;
import lombok.NoArgsConstructor;
import lombok.Setter;
@Entity
@Table(name = "user_details")
@Getter
@Setter
@NoArgsConstructor
public class User {
@Id
@GeneratedValue(strategy = GenerationType.AUTO)
private Long userId;
@NotEmpty(message="Please fill the first name")
@Column(nullable=false, length = 25)
private String firstName;
@NotEmpty(message="Please fill the last name")
@Column(nullable=false, length = 25)
private String lastName;
@Column(unique = true, nullable=false, length = 45)
@NotEmpty(message="Please fill the email")
@Email(message="Please enter valid email id")
private String email;
@Column(nullable=false)
@NotEmpty(message="Please fill the mobile number")
@Pattern(regexp = "[0-9]{10}", message = "Number should be 10 digit only")
private String mobileNumber;
@NotEmpty(message="Please fill the password")
@Column(nullable=false, length = 25)
@Pattern(regexp = "(?=.*[A-Z])(?=.*[^0-9a-zA-Z])(?=.*[0-9]).{8,}", message = "Password must contain atleast one capital letter, special character and number with minimum of 8 characters")
private String password;
@JsonIgnore
@Column(nullable=false)
@CreationTimestamp
private LocalDateTime createdDate = LocalDateTime.now();
@JsonIgnore
@Column(nullable=false)
@UpdateTimestamp
private LocalDateTime modifiedDate = LocalDateTime.now();
private boolean isVerified = false;
@ManyToMany(mappedBy="collaboratedUser")
@JsonIgnore
private Set<Note> collaboratedNote;
}
| true
|
0d93451c141a0905aef14838e929a0f2b2b6dee1
|
Java
|
TRSFinance/rms
|
/test/com/trs/rms/test/service/RmsTestService.java
|
UTF-8
| 558
| 1.8125
| 2
|
[] |
no_license
|
package com.trs.rms.test.service;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import com.trs.rms.base.dao.IDao;
import com.trs.rms.base.service.BasicServicveImpl;
@Service
@Transactional
public class RmsTestService extends BasicServicveImpl implements RmsTestServices {
public void test(){
System.out.println("我是业务层!");
}
@Autowired
public void setMyDao(IDao dao){
super.setDao(dao);
}
}
| true
|
6811058b158e88b5cfcaa64b04b14ed17953c527
|
Java
|
karol-dabrowski/news-app
|
/app/src/main/java/pl/karoldabrowski/newsapp/ArticleAdapter.java
|
UTF-8
| 1,657
| 2.546875
| 3
|
[
"MIT"
] |
permissive
|
package pl.karoldabrowski.newsapp;
import android.content.Context;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.TextView;
import java.util.List;
public class ArticleAdapter extends ArrayAdapter<Article> {
public ArticleAdapter(@NonNull Context context, List<Article> articles) {
super(context, 0, articles);
}
@NonNull
@Override
public View getView(int position, @Nullable View convertView, @NonNull ViewGroup parent) {
View listItemView = convertView;
if (listItemView == null) {
listItemView = LayoutInflater.from(getContext()).inflate(
R.layout.list_item, parent, false);
}
Article currentArticle = getItem(position);
TextView articleTitle = listItemView.findViewById(R.id.article_title);
articleTitle.setText(currentArticle.getTitle());
if(currentArticle.hasAuthor()) {
TextView articleAuthor = listItemView.findViewById(R.id.article_author);
articleAuthor.setText(currentArticle.getAuthor());
}
TextView articleSection = listItemView.findViewById(R.id.article_section);
articleSection.setText(currentArticle.getSection());
if(currentArticle.hasDate()) {
TextView articleDate = listItemView.findViewById(R.id.article_date);
articleDate.setText(currentArticle.getDate().replace('T', ' ').replace("Z", ""));
}
return listItemView;
}
}
| true
|
57c4ed60637fb9fc671817734a99eb4955ac795c
|
Java
|
uvardic/gerudok-refactored
|
/src/main/java/gerudok/controller/SlotPanelCanvasController.java
|
UTF-8
| 2,044
| 2.46875
| 2
|
[] |
no_license
|
package gerudok.controller;
import gerudok.view.desktop.Desktop;
import gerudok.view.desktop.DiagramFrame;
import gerudok.view.desktop.SlotPanel;
import java.awt.event.InputEvent;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import java.awt.event.MouseWheelEvent;
public class SlotPanelCanvasController extends MouseAdapter {
@Override
public void mousePressed(MouseEvent event) {
Desktop.getInstance().getSelectedSlotPanel().getCurrentState().mousePressed(event);
}
@Override
public void mouseReleased(MouseEvent event) {
Desktop.getInstance().getSelectedSlotPanel().getCurrentState().mouseReleased(event);
}
@Override
public void mouseDragged(MouseEvent event) {
Desktop.getInstance().getSelectedSlotPanel().getCurrentState().mouseDragged(event);
}
@Override
public void mouseMoved(MouseEvent event) {
Desktop.getInstance().getSelectedSlotPanel().getCurrentState().mouseMoved(event);
}
@Override
public void mouseWheelMoved(MouseWheelEvent event) {
DiagramFrame selectedDiagramFrame = Desktop.getInstance().getSelectedDiagramFrame();
if (isControlPressed(event))
mouseWheelZoom(event);
else if (isShiftPressed(event))
selectedDiagramFrame.adjustScrollBarsValue(0, event.getWheelRotation());
else
selectedDiagramFrame.adjustScrollBarsValue(event.getWheelRotation(), 0);
}
private boolean isControlPressed(MouseWheelEvent event) {
return (event.getModifiersEx() & InputEvent.CTRL_DOWN_MASK) != 0;
}
private boolean isShiftPressed(MouseWheelEvent event) {
return (event.getModifiersEx() & InputEvent.SHIFT_DOWN_MASK) != 0;
}
private void mouseWheelZoom(MouseWheelEvent event) {
SlotPanel slotPane = Desktop.getInstance().getSelectedSlotPanel();
double newScale = slotPane.calculateNewScaleForMouseWheelEvent(event);
slotPane.transformToNewScaleForMouseEvent(event, newScale);
}
}
| true
|
48ea41fa7df3d1635725e3b4ba561d0f3dbf712c
|
Java
|
Neembuu/neembuunow
|
/neembuu-android/srcs/output_jar.src/twitter4j/conf/ConfigurationContext.java
|
UTF-8
| 2,809
| 1.867188
| 2
|
[] |
no_license
|
package twitter4j.conf;
public final class ConfigurationContext
{
public static final String CONFIGURATION_IMPL = "twitter4j.configurationFactory";
public static final String DEFAULT_CONFIGURATION_FACTORY = "twitter4j.conf.PropertyConfigurationFactory";
private static final ConfigurationFactory factory;
/* Error */
static
{
// Byte code:
// 0: ldc 8
// 2: ldc 11
// 4: invokestatic 29 java/lang/System:getProperty (Ljava/lang/String;Ljava/lang/String;)Ljava/lang/String;
// 7: astore 5
// 9: aload 5
// 11: astore_1
// 12: aload_1
// 13: invokestatic 35 java/lang/Class:forName (Ljava/lang/String;)Ljava/lang/Class;
// 16: invokevirtual 39 java/lang/Class:newInstance ()Ljava/lang/Object;
// 19: checkcast 41 twitter4j/conf/ConfigurationFactory
// 22: putstatic 43 twitter4j/conf/ConfigurationContext:factory Ltwitter4j/conf/ConfigurationFactory;
// 25: return
// 26: astore_0
// 27: ldc 11
// 29: astore_1
// 30: goto -18 -> 12
// 33: astore 4
// 35: new 45 java/lang/AssertionError
// 38: dup
// 39: aload 4
// 41: invokespecial 49 java/lang/AssertionError:<init> (Ljava/lang/Object;)V
// 44: athrow
// 45: astore_3
// 46: new 45 java/lang/AssertionError
// 49: dup
// 50: aload_3
// 51: invokespecial 49 java/lang/AssertionError:<init> (Ljava/lang/Object;)V
// 54: athrow
// 55: astore_2
// 56: new 45 java/lang/AssertionError
// 59: dup
// 60: aload_2
// 61: invokespecial 49 java/lang/AssertionError:<init> (Ljava/lang/Object;)V
// 64: athrow
// Local variable table:
// start length slot name signature
// 26 1 0 localSecurityException java.lang.SecurityException
// 11 19 1 str1 String
// 55 6 2 localIllegalAccessException java.lang.IllegalAccessException
// 45 6 3 localInstantiationException java.lang.InstantiationException
// 33 7 4 localClassNotFoundException java.lang.ClassNotFoundException
// 7 3 5 str2 String
// Exception table:
// from to target type
// 0 9 26 java/lang/SecurityException
// 12 25 33 java/lang/ClassNotFoundException
// 12 25 45 java/lang/InstantiationException
// 12 25 55 java/lang/IllegalAccessException
}
public static Configuration getInstance()
{
return factory.getInstance();
}
public static Configuration getInstance(String paramString)
{
return factory.getInstance(paramString);
}
}
/* Location: F:\neembuu\Research\android_apps\output_jar.jar
* Qualified Name: twitter4j.conf.ConfigurationContext
* JD-Core Version: 0.7.0.1
*/
| true
|
5993d0ecea5b750d7e114c907ae9ac15745aa2d1
|
Java
|
Manolo8/SimpleCraft
|
/src/test/java/BigLetter.java
|
UTF-8
| 8,743
| 3.34375
| 3
|
[] |
no_license
|
import java.util.ArrayList;
import java.util.List;
public class BigLetter {
private static String[][] letters;
static {
letters = new String[31][6];
//A
letters[0][0] = "a";
letters[0][1] = "███";
letters[0][2] = "█░█";
letters[0][3] = "███";
letters[0][4] = "█░█";
letters[0][5] = "█░█";
//B
letters[1][0] = "b";
letters[1][1] = "██░";
letters[1][2] = "█░█";
letters[1][3] = "██░";
letters[1][4] = "█░█";
letters[1][5] = "██░";
//C
letters[2][0] = "c";
letters[2][1] = "███";
letters[2][2] = "█░░";
letters[2][3] = "█░░";
letters[2][4] = "█░░";
letters[2][5] = "███";
//D
letters[3][0] = "d";
letters[3][1] = "██░";
letters[3][2] = "█░█";
letters[3][3] = "█░█";
letters[3][4] = "█░█";
letters[3][5] = "██░";
//E
letters[4][0] = "e";
letters[4][1] = "███";
letters[4][2] = "█░░";
letters[4][3] = "██░";
letters[4][4] = "█░░";
letters[4][5] = "███";
//F
letters[5][0] = "f";
letters[5][1] = "███";
letters[5][2] = "█░░";
letters[5][3] = "██░";
letters[5][4] = "█░░";
letters[5][5] = "█░░";
//G
letters[6][0] = "g";
letters[6][1] = "███";
letters[6][2] = "█░░";
letters[6][3] = "███";
letters[6][4] = "█░█";
letters[6][5] = "███";
//H
letters[7][0] = "h";
letters[7][1] = "█░█";
letters[7][2] = "█░█";
letters[7][3] = "███";
letters[7][4] = "█░█";
letters[7][5] = "█░█";
//I
letters[8][0] = "i";
letters[8][1] = "░█░";
letters[8][2] = "░░░";
letters[8][3] = "░█░";
letters[8][4] = "░█░";
letters[8][5] = "░█░";
//J
letters[9][0] = "j";
letters[9][1] = "░██";
letters[9][2] = "░░█";
letters[9][3] = "░░█";
letters[9][4] = "░░█";
letters[9][5] = "███";
//K
letters[10][0] = "k";
letters[10][1] = "█░█";
letters[10][2] = "██░";
letters[10][3] = "█░░";
letters[10][4] = "██░";
letters[10][5] = "█░█";
//L
letters[11][0] = "l";
letters[11][1] = "█░░";
letters[11][2] = "█░░";
letters[11][3] = "█░░";
letters[11][4] = "█░░";
letters[11][5] = "███";
//M
letters[12][0] = "m";
letters[12][1] = "█░█";
letters[12][2] = "███";
letters[12][3] = "█░█";
letters[12][4] = "█░█";
letters[12][5] = "█░█";
//N
letters[13][0] = "n";
letters[13][1] = "███";
letters[13][2] = "█░█";
letters[13][3] = "█░█";
letters[13][4] = "█░█";
letters[13][5] = "█░█";
//O
letters[14][0] = "o";
letters[14][1] = "███";
letters[14][2] = "█░█";
letters[14][3] = "█░█";
letters[14][4] = "█░█";
letters[14][5] = "███";
//P
letters[15][0] = "p";
letters[15][1] = "██░";
letters[15][2] = "█░█";
letters[15][3] = "██░";
letters[15][4] = "█░░";
letters[15][5] = "█░░";
//Q
letters[16][0] = "q";
letters[16][1] = "██░";
letters[16][2] = "██░";
letters[16][3] = "██░";
letters[16][4] = "██░";
letters[16][5] = "███";
//R
letters[17][0] = "r";
letters[17][1] = "██░";
letters[17][2] = "█░█";
letters[17][3] = "██░";
letters[17][4] = "█░█";
letters[17][5] = "█░█";
//S
letters[18][0] = "s";
letters[18][1] = "░██";
letters[18][2] = "█░░";
letters[18][3] = "██░";
letters[18][4] = "░░█";
letters[18][5] = "███";
//T
letters[19][0] = "t";
letters[19][1] = "███";
letters[19][2] = "░█░";
letters[19][3] = "░█░";
letters[19][4] = "░█░";
letters[19][5] = "░█░";
//U
letters[20][0] = "u";
letters[20][1] = "█░█";
letters[20][2] = "█░█";
letters[20][3] = "█░█";
letters[20][4] = "█░█";
letters[20][5] = "███";
//V
letters[21][0] = "v";
letters[21][1] = "█░█";
letters[21][2] = "█░█";
letters[21][3] = "█░█";
letters[21][4] = "█░█";
letters[21][5] = "██░";
//W
letters[22][0] = "w";
letters[22][1] = "█░█";
letters[22][2] = "█░█";
letters[22][3] = "█░█";
letters[22][4] = "███";
letters[22][5] = "█░█";
//X
letters[23][0] = "posX";
letters[23][1] = "█░█";
letters[23][2] = "█░█";
letters[23][3] = "░█░";
letters[23][4] = "█░█";
letters[23][5] = "█░█";
//Y
letters[24][0] = "y";
letters[24][1] = "█░█";
letters[24][2] = "█░█";
letters[24][3] = "░█░";
letters[24][4] = "░█░";
letters[24][5] = "░█░";
//flag
letters[25][0] = "posZ";
letters[25][1] = "███";
letters[25][2] = "░░█";
letters[25][3] = "░█░";
letters[25][4] = "█░░";
letters[25][5] = "███";
//
letters[26][0] = " ";
letters[26][1] = "░░░";
letters[26][2] = "░░░";
letters[26][3] = "░░░";
letters[26][4] = "░░░";
letters[26][5] = "░░░";
//:
letters[27][0] = ":";
letters[27][1] = "░░░";
letters[27][2] = "░█░";
letters[27][3] = "░░░";
letters[27][4] = "░█░";
letters[27][5] = "░░░";
//(
letters[28][0] = "(";
letters[28][1] = "░██";
letters[28][2] = "█░░";
letters[28][3] = "█░░";
letters[28][4] = "█░░";
letters[28][5] = "░██";
//>
letters[29][0] = ">";
letters[29][1] = "░░░";
letters[29][2] = "██░";
letters[29][3] = "░░█";
letters[29][4] = "██░";
letters[29][5] = "░░░";
//1
letters[30][0] = "1";
letters[30][1] = "░█░";
letters[30][2] = "██░";
letters[30][3] = "░█░";
letters[30][4] = "░█░";
letters[30][5] = "███";
}
private static int findChar(char c) {
for (int i = 0; i < letters.length; i++) {
if (letters[i][0].charAt(0) == c) return i;
}
return -1;
}
public static void main(String[] args) {
String toWrite = "HI RAKIN".toLowerCase();
List<Integer> sequence = new ArrayList();
for (int i = 0; i < toWrite.length(); i++) {
sequence.add(findChar(toWrite.charAt(i)));
}
for (int t = 0; t < sequence.size(); t += 8) {
StringBuilder builder = new StringBuilder();
int length = 0;
int max = Math.min(t + 8, sequence.size());
for (int i = 1; i < 6; i++) {
for (int i1 = t; i1 < max; i1++) {
int c = sequence.get(i1);
if (i == 1) {
length += 4;
}
builder.append(letters[c][i]).append('░');
if (i1 + 1 == max) {
for (int d = length; d < 20; d++) builder.append('░');
}
}
if(i != 5)
builder.append('\n');
}
System.out.println(builder);
System.out.println("░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░");
}
}
}
| true
|
5530ddf7dd58b7d83dd1439527b6ca7f87356064
|
Java
|
thomasdarimont/testcontainers-java
|
/modules/redpanda/src/test/java/org/testcontainers/redpanda/RedpandaContainerTest.java
|
UTF-8
| 5,039
| 1.890625
| 2
|
[
"LicenseRef-scancode-unknown-license-reference",
"MIT"
] |
permissive
|
package org.testcontainers.redpanda;
import com.google.common.collect.ImmutableMap;
import org.apache.kafka.clients.admin.AdminClient;
import org.apache.kafka.clients.admin.AdminClientConfig;
import org.apache.kafka.clients.admin.NewTopic;
import org.apache.kafka.clients.consumer.ConsumerConfig;
import org.apache.kafka.clients.consumer.ConsumerRecord;
import org.apache.kafka.clients.consumer.ConsumerRecords;
import org.apache.kafka.clients.consumer.KafkaConsumer;
import org.apache.kafka.clients.producer.KafkaProducer;
import org.apache.kafka.clients.producer.ProducerConfig;
import org.apache.kafka.clients.producer.ProducerRecord;
import org.apache.kafka.common.serialization.StringDeserializer;
import org.apache.kafka.common.serialization.StringSerializer;
import org.junit.Test;
import org.rnorth.ducttape.unreliables.Unreliables;
import org.testcontainers.utility.DockerImageName;
import java.time.Duration;
import java.util.Collection;
import java.util.Collections;
import java.util.UUID;
import java.util.concurrent.TimeUnit;
import static org.assertj.core.api.Assertions.assertThat;
import static org.assertj.core.api.Assertions.assertThatThrownBy;
import static org.assertj.core.api.Assertions.tuple;
public class RedpandaContainerTest {
private static final String REDPANDA_IMAGE = "docker.redpanda.com/vectorized/redpanda:v22.2.1";
private static final DockerImageName REDPANDA_DOCKER_IMAGE = DockerImageName.parse(REDPANDA_IMAGE);
@Test
public void testUsage() throws Exception {
try (RedpandaContainer container = new RedpandaContainer(REDPANDA_DOCKER_IMAGE)) {
container.start();
testKafkaFunctionality(container.getBootstrapServers());
}
}
@Test
public void testUsageWithStringImage() throws Exception {
try (
// constructorWithVersion {
RedpandaContainer container = new RedpandaContainer("docker.redpanda.com/vectorized/redpanda:v22.2.1")
// }
) {
container.start();
testKafkaFunctionality(
// getBootstrapServers {
container.getBootstrapServers()
// }
);
}
}
@Test
public void testNotCompatibleVersion() {
assertThatThrownBy(() -> new RedpandaContainer("docker.redpanda.com/vectorized/redpanda:v21.11.19"))
.isInstanceOf(IllegalArgumentException.class)
.hasMessageContaining("Redpanda version must be >= v22.2.1");
}
private void testKafkaFunctionality(String bootstrapServers) throws Exception {
testKafkaFunctionality(bootstrapServers, 1, 1);
}
private void testKafkaFunctionality(String bootstrapServers, int partitions, int rf) throws Exception {
try (
AdminClient adminClient = AdminClient.create(
ImmutableMap.of(AdminClientConfig.BOOTSTRAP_SERVERS_CONFIG, bootstrapServers)
);
KafkaProducer<String, String> producer = new KafkaProducer<>(
ImmutableMap.of(
ProducerConfig.BOOTSTRAP_SERVERS_CONFIG,
bootstrapServers,
ProducerConfig.CLIENT_ID_CONFIG,
UUID.randomUUID().toString()
),
new StringSerializer(),
new StringSerializer()
);
KafkaConsumer<String, String> consumer = new KafkaConsumer<>(
ImmutableMap.of(
ConsumerConfig.BOOTSTRAP_SERVERS_CONFIG,
bootstrapServers,
ConsumerConfig.GROUP_ID_CONFIG,
"tc-" + UUID.randomUUID(),
ConsumerConfig.AUTO_OFFSET_RESET_CONFIG,
"earliest"
),
new StringDeserializer(),
new StringDeserializer()
);
) {
String topicName = "messages-" + UUID.randomUUID();
Collection<NewTopic> topics = Collections.singletonList(new NewTopic(topicName, partitions, (short) rf));
adminClient.createTopics(topics).all().get(30, TimeUnit.SECONDS);
consumer.subscribe(Collections.singletonList(topicName));
producer.send(new ProducerRecord<>(topicName, "testcontainers", "rulezzz")).get();
Unreliables.retryUntilTrue(
10,
TimeUnit.SECONDS,
() -> {
ConsumerRecords<String, String> records = consumer.poll(Duration.ofMillis(100));
if (records.isEmpty()) {
return false;
}
assertThat(records)
.hasSize(1)
.extracting(ConsumerRecord::topic, ConsumerRecord::key, ConsumerRecord::value)
.containsExactly(tuple(topicName, "testcontainers", "rulezzz"));
return true;
}
);
consumer.unsubscribe();
}
}
}
| true
|
09178f0d8d05f4ffdb79b736173d0cc2200d5928
|
Java
|
Maria-Kristina/Chat-Application
|
/Project/src/project/Main.java
|
UTF-8
| 658
| 2.421875
| 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 project;
import java.io.IOException;
/**
*
* @author Valtteri Pesu and Maria-Kristina Sillanmäki
*/
public class Main {
/**
* @param args the command line arguments
* @throws java.io.IOException
*/
public static void main(String[] args) throws IOException {
ChatServer cs = new ChatServer();
cs.serve();
//CommandInterpreter ci = new CommandInterpreter(System.in, System.out);
//ci.run();
}
}
| true
|
48493c136c14ab827c19d2e6a8a79d140450538f
|
Java
|
skkuse-adv/2019Fall_team2
|
/analysis/reverse-engineering/decompile-fitts-20191031-2200/sources/kr/co/popone/fitts/feature/store/browser/StoreBrowserActivity$onCreate$42.java
|
UTF-8
| 595
| 1.984375
| 2
|
[
"Apache-2.0"
] |
permissive
|
package kr.co.popone.fitts.feature.store.browser;
import io.reactivex.functions.Consumer;
import kr.co.popone.fitts.event.OrderEvent$OrderCompleteEvent;
final class StoreBrowserActivity$onCreate$42<T> implements Consumer<Object> {
final /* synthetic */ StoreBrowserActivity this$0;
StoreBrowserActivity$onCreate$42(StoreBrowserActivity storeBrowserActivity) {
this.this$0 = storeBrowserActivity;
}
public final void accept(Object obj) {
if (obj instanceof OrderEvent$OrderCompleteEvent) {
this.this$0.finish();
}
}
}
| true
|
3790d121eeb4ef816abd0b7e257af39ca98a1db2
|
Java
|
selbert/openshift
|
/src/main/java/ch/adesso/openshift/backend/hello/boundary/HelloResource.java
|
UTF-8
| 541
| 2.015625
| 2
|
[] |
no_license
|
package ch.adesso.openshift.backend.hello.boundary;
import javax.json.Json;
import javax.json.JsonArray;
import javax.json.JsonObject;
import javax.json.JsonObjectBuilder;
import javax.ws.rs.GET;
import javax.ws.rs.Path;
@Path("hello")
public class HelloResource {
@GET
public JsonArray getHello() {
JsonObject helloVSHN = Json.createObjectBuilder()
.add("hello", "vshn")
.build();
return Json.createArrayBuilder()
.add(helloVSHN)
.build();
}
}
| true
|
502a97c593e7bcf8629bf74d8f830e9c5af3eb8d
|
Java
|
yfyf510/Ronghetongxin
|
/BeiDouCommunication/app/src/main/java/com/zhbd/beidoucommunication/ui/fragment/EmailMSGFragment.java
|
UTF-8
| 4,045
| 2.1875
| 2
|
[] |
no_license
|
package com.zhbd.beidoucommunication.ui.fragment;
import android.content.Intent;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v4.app.Fragment;
import android.support.v4.widget.SwipeRefreshLayout;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.ListView;
import com.zhbd.beidoucommunication.R;
import com.zhbd.beidoucommunication.adapter.EmailMessageAdapter;
import com.zhbd.beidoucommunication.config.Constants;
import com.zhbd.beidoucommunication.db.DatabaseDao;
import com.zhbd.beidoucommunication.domain.EmailMessage;
import com.zhbd.beidoucommunication.ui.activity.ShowEmailActivity;
import com.zhbd.beidoucommunication.utils.SharedPrefUtil;
import com.zhbd.beidoucommunication.utils.ToastUtils;
import com.zhbd.beidoucommunication.view.RefreshLayout;
import java.util.ArrayList;
import butterknife.Bind;
import butterknife.ButterKnife;
/**
* 普通消息
* Created by zhangyaru on 2017/9/4.
*/
public class EmailMSGFragment extends Fragment implements
AdapterView.OnItemClickListener, SwipeRefreshLayout.OnRefreshListener {
// 下拉刷新控件
@Bind(R.id.refresh_layout)
RefreshLayout mRefreshLayout;
@Bind(R.id.side_pull_listview)
ListView mSidepullListView;
EmailMessageAdapter mAdapter;
private ArrayList<EmailMessage> mList;
/**
* 数据库操作类
*/
DatabaseDao dao;
@Nullable
@Override
public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.fragment_common_msg, null);
ButterKnife.bind(this, view);
init();
return view;
}
private void init() {
// 设置下拉刷新的进度条颜色
mRefreshLayout.setColorScheme(
new int[]{android.R.color.holo_blue_bright,
android.R.color.holo_green_light,
android.R.color.holo_orange_light,
android.R.color.holo_red_light});
mList = new ArrayList<>();
int userId = SharedPrefUtil.getInt(getContext(), Constants.USER_ID, 0);
dao = DatabaseDao.getInstance(getContext(), userId);
// 去重复查找,找到最新的消息
mList = dao.queryEmail();
// 设置适配器
mAdapter = new EmailMessageAdapter(mList, getActivity());
mSidepullListView.setAdapter(mAdapter);
// 设置条目点击监听
mSidepullListView.setOnItemClickListener(this);
// 设置刷新监听,这里不需要加载更多
mRefreshLayout.setOnRefreshListener(this);
}
@Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
Intent intent = new Intent(getActivity(), ShowEmailActivity.class);
EmailMessage email = mList.get(position);
intent.putExtra("address", email.getAddress());
intent.putExtra("content", email.getContent());
startActivity(intent);
}
@Override
public void onRefresh() {
mRefreshLayout.postDelayed(new Runnable() {
@Override
public void run() {
// 更新数据
mList.clear();
ArrayList<EmailMessage> messages = dao.queryEmail();
mList.addAll(messages);
//setData();
refresh();
ToastUtils.showToast(getActivity(), getResources().getString(R.string.update_success));
// 更新完后调用该方法结束刷新
mRefreshLayout.setRefreshing(false);
}
}, 1000);
}
private void refresh() {
mList.clear();
mList.addAll(dao.queryEmail());
mAdapter.setList(mList);
mAdapter.notifyDataSetChanged();
}
@Override
public void onStart() {
super.onStart();
refresh();
}
}
| true
|
a307f35b8e5b3e784e7e7234c7a53409ef52c01d
|
Java
|
itay-adi/ChatServer
|
/Message.java
|
UTF-8
| 166
| 2.015625
| 2
|
[] |
no_license
|
package il.co.ilrd.chat_server;
import java.io.Serializable;
public interface Message <K, D> extends Serializable{
public K getKey();
public D getData();
}
| true
|
3beaf09117b8a72af176622c6f4e97103825d470
|
Java
|
testingwithdaniel/selenium-test-benchmarking
|
/src/main/java/boilerplateTests/pages/stormy_herokuApp.java
|
UTF-8
| 2,875
| 2.234375
| 2
|
[] |
no_license
|
package boilerplateTests.pages;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.remote.RemoteWebDriver;
import utils.common.SeleniumUtils;
import utils.common.WebpageElements;
import java.util.List;
public class stormy_herokuApp {
public WebDriver driver ;
public stormy_herokuApp(WebDriver driver) {
this.driver=driver;
}
public static WebpageElements sendKeysBox= new WebpageElements("SendKeys-Test-Element","//*[@id='q']");
public static WebpageElements submitButton=new WebpageElements("Submit-Button","//input[@type='submit']");
public static WebpageElements getElements= new WebpageElements("FindElements-Test-Element","//div[@id='navcontainer']/ul/li");
public static WebpageElements FormName= new WebpageElements("Form-textBox-Name","//input[@id='testname']");
public static WebpageElements FormEmail = new WebpageElements("Form-Email-Name","//input[@id='testemail']");
public static WebpageElements FormCheckBox = new WebpageElements("Form-CheckBox","//input[@id='testcheckbox']");
public static WebpageElements FormDropDown = new WebpageElements("Form-DropDown","//select[@id='testcolor']");
public void SendKeysToTextBox(String textForSendKeys){
SeleniumUtils seleniumUtils = new SeleniumUtils(driver);
seleniumUtils.waitForElement(sendKeysBox);
seleniumUtils.sendKeys(sendKeysBox,textForSendKeys);
}
public void submitButtonClick(){
SeleniumUtils seleniumUtils = new SeleniumUtils(driver);
seleniumUtils.waitForElement(submitButton);
seleniumUtils.clickElement(submitButton);
}
public List<WebElement> getMultipleElements(){
SeleniumUtils seleniumUtils = new SeleniumUtils(driver);
seleniumUtils.waitForElement(getElements);
List<WebElement> elements=seleniumUtils.findMultipleElements(getElements);
return elements;
}
public void sendKeystoFormName(String textForSendKeys){
SeleniumUtils seleniumUtils = new SeleniumUtils(driver);
seleniumUtils.waitForElement(FormName);
seleniumUtils.sendKeys(FormName,textForSendKeys);
}
public void sendKeystoFormEmail(String textForSendKeys){
SeleniumUtils seleniumUtils = new SeleniumUtils(driver);
seleniumUtils.waitForElement(FormEmail);
seleniumUtils.sendKeys(FormEmail,textForSendKeys);
}
public void clickFormCheckBox(){
SeleniumUtils seleniumUtils = new SeleniumUtils(driver);
seleniumUtils.waitForElement(FormCheckBox);
seleniumUtils.clickElement(FormCheckBox);
}
public void selectDropDown(String value){
SeleniumUtils seleniumUtils = new SeleniumUtils(driver);
seleniumUtils.waitForElement(FormDropDown);
seleniumUtils.selectDropDownByValue(FormDropDown,value);
}
}
| true
|
c31bccbf35e10c27e35d26ea93788ab370298ecf
|
Java
|
jalexanderqed/SwingTree
|
/src/ninja/jalexander/Vertex.java
|
UTF-8
| 3,389
| 2.9375
| 3
|
[] |
no_license
|
package ninja.jalexander;
import java.util.LinkedList;
/**
* Created by john on 3/19/16.
*/
public class Vertex {
private double mass;
private double inverseMass;
private LinkedList<VertexEdgePair> neighbors = new LinkedList<VertexEdgePair>();
public NewtonState state = new NewtonState(0, 0, 0, 0);
public NewtonState nextState = new NewtonState(0, 0, 0, 0);
public Vertex(double m){
mass = m;
inverseMass = 1.0 / m;
}
public void update(double dt){
Derivative a, b, c, d;
a = evaluate(0, new Derivative(0, 0, 0, 0));
b = evaluate(dt * 0.5, a);
c = evaluate(dt * 0.5, b);
d = evaluate(dt * 0.5, c);
double dx = (1.0 / 6.0) * (a.dx + 2 * (b.dx + c.dx) + d.dx);
double dy = (1.0 / 6.0) * (a.dy + 2 * (b.dy + c.dy) + d.dy);
double ax = (1.0 / 6.0) * (a.ax + 2 * (b.ax + c.ax) + d.ax);
double ay = (1.0 / 6.0) * (a.ay + 2 * (b.ay + c.ay) + d.ay);
nextState = new NewtonState(state);
nextState.x += dx * dt;
nextState.y += dy * dt;
nextState.dx += ax * dt;
nextState.dy += ay * dt;
}
public void flip(){
state = nextState;
}
public Derivative evaluate(double dt,
Derivative d){
NewtonState newState = new NewtonState(state);
newState.x = state.x + d.dx * dt;
newState.y = state.y + d.dy * dt;
newState.dx = state.dx + d.ax * dt;
newState.dy = state.dy + d.ay * dt;
Derivative output = new Derivative(0, 0, 0, 0);
output.dx = newState.dx;
output.dy = newState.dy;
Acceleration a = calculateAcceleration(newState);
output.ax = a.ax;
output.ay = a.ay;
return output;
}
public Acceleration calculateAcceleration(NewtonState s){
double fx = 0;
double fy = 0;
for(VertexEdgePair p : neighbors){
NewtonVector vector = new NewtonVector(p.vertex.state, s);
double displacement = vector.length() - p.edge.restLength;
/*
System.out.println("Length: " + vector.length());
System.out.println("Rest Length: " + p.edge.restLength);
System.out.println("Displacement: " + displacement);
*/
vector.normalize();
fx -= p.edge.k * displacement * vector.x + p.edge.b * vector.dx;
fy -= p.edge.k * displacement * vector.y + p.edge.b * vector.dy;
}
if(Globals.doRepulsion) {
for (Vertex v : Globals.vertices) {
if (v == this) continue;
NewtonVector vector = new NewtonVector(v.state, state);
double dist = vector.length();
double multiplier = Globals.repulsiveMultiplier / (dist * dist);
fx += vector.x * multiplier;
fy += vector.y * multiplier;
}
}
if(Globals.gravity) fy += Globals.gravityConstant * mass;
return new Acceleration(fx * inverseMass, fy * inverseMass);
}
public void addNeighbor(VertexEdgePair p){
neighbors.add(p);
}
public double Mass(){
return mass;
}
public double InverseMass(){
return inverseMass;
}
public void changeMass(double m){
mass = m;
inverseMass = 1.0 / m;
}
}
| true
|
d636bd8ed4e785db9c59deba086755c1c9b7e119
|
Java
|
BSShubham97/AddressBook_All-Methods
|
/OptionMenu.java
|
UTF-8
| 1,983
| 3.609375
| 4
|
[] |
no_license
|
package com.bridgelabz;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Scanner;
class OptionMenu extends Methods {
public ArrayList<Contact> operation() {
Scanner scanner = new Scanner(System.in);
boolean run = true;
while (run) {
System.out.println("SELECT OPTION: \n 1. ADD CONTACT \n 2. DISPLAY CONTACTS \n 3. EDIT CONTACT \n 4. REMOVE CONTACT \n 0. EXIT ");
System.out.print("Enter option: ");
int choice = scanner.nextInt();
switch (choice) {
case 1:
ArrayList contactList = addPerson();
break;
case 2:
displayContacts();
break;
case 3:
editPerson();
break;
case 4:
removePerson();
break;
default:
run = false;
}
}
return contactList;
}
}
/**
* Purpose - create new Address Book
*/
class MultipleBooks {
public void createBook() {
HashMap<String, ArrayList<Contact>> bookList = new HashMap<>();
Scanner scanner = new Scanner(System.in);
while (true) {
OptionMenu option = new OptionMenu();
System.out.println("SELECT OPTION \n 1. CREATE ADDRESS BOOK / 0. EXIT ");
System.out.print("Enter Option: ");
int choice = scanner.nextInt();
switch (choice) {
case 1:
System.out.println("Enter Name: ");
String addBookName = scanner.next();
bookList.put(addBookName, option.operation());
break;
case 0:
System.exit(0);
}
}
}
}
| true
|
984fd35e1905d87a096e004df50bbe4b838e64ce
|
Java
|
RinesThaix/AprilAPI
|
/src/main/java/sexy/kostya/april/Producer.java
|
UTF-8
| 432
| 2.28125
| 2
|
[] |
no_license
|
package sexy.kostya.april;
import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
/**
* Created by k.shandurenko on 26/03/2019
*/
@Target(ElementType.TYPE)
@Retention(RetentionPolicy.RUNTIME)
public @interface Producer {
/**
* Name of the producer.
* @return producer's name.
*/
String value();
}
| true
|
a2987b8e60adf31446c9ebc77f3222121352b2f0
|
Java
|
vxkvankai/selenium_NO_Framework
|
/src/com/selenium_NO_Framework/ArraysFindMinunInRowandFindMaxInThatColumn.java
|
UTF-8
| 1,428
| 3.03125
| 3
|
[] |
no_license
|
package com.selenium_NO_Framework;
public class ArraysFindMinunInRowandFindMaxInThatColumn {
// array {2, 4, 5},
// {3, 0, 7},
// {1, 2, 9}};
//
// 1. FInd the minimum number
// 2.Identify the colum of the min number
// 3. find the max num in that column
// 4. Print the max number from that column
//
// You can also get more exposure about Apache POI API with selenium from below link
// http://www.guru99.com/all-about-excel-in-selenium-poi-jxl.htmlpackage coreJava;
/*
* 2 4 5
*
* 3 4 7
*
* 1 2 9
*/
//Maximum number from the array
public static void main(String[] args) {
// TODO Auto-generated method stub
int abc[][] = {{1, 4, 7}, {3, 2, 6}, {1, 2, 9}};
int min = abc[0][0];
int mincoloumn = 0;
for (int i = 0; i < 3; i++) {
for (int j = 0; j < 3; j++) {
if (abc[i][j] < min)//2
{
min = abc[i][j];
mincoloumn = j;
}
}
}
//=1
int max = abc[0][mincoloumn];
int k = 0;
while (k < 3) {
if (abc[k][mincoloumn] > max) {
max = abc[k][mincoloumn];
}
k++;
}
System.out.println(max);
}
}
| true
|
48f41c6d8cb1b42e1c41548ca933db6c5d348429
|
Java
|
juanguirp/NeuroLab2
|
/NeuroLabWs/src/co/edu/udea/iw/ws/dto/SolicitudPrestamoWs.java
|
UTF-8
| 2,664
| 2.375
| 2
|
[] |
no_license
|
package co.edu.udea.iw.ws.dto;
import java.util.Date;
import javax.xml.bind.annotation.XmlRootElement;
import co.edu.udea.iw.dto.Administrador;
import co.edu.udea.iw.dto.Dispositivo;
import co.edu.udea.iw.dto.Investigador;
/**
* Clase que almacena la informacion de una solicitud de prestamo.
* @author Juan Guillermo Restrepo Pineda <juan.restrepo48@udea.edu.co>
*
*/
@XmlRootElement
public class SolicitudPrestamoWs {
private int id;
private Dispositivo dispositivoSolicitado;
private Date fechaSolicitud;
private Investigador solicitante;
private Administrador adminProcesador;
private Boolean respuesta;
/**
* Constructores para un objeto de la clase SolicitudPrestamo.
*
* @param id
* - Numero que identifica una solicitud de prestamo.
* @param dispositivoSolicitado
* - Numero de identificacion del dispositivo solicitado.
* @param fechaSolicitud
* - Fecha en la que se hace la solicitud.
* @param solicitante
* - Identificacion del investigador que hace la solicitud
* @param adminProcesador
* -Identificacion del administrador que procesa la solicitud.
* @param respuesta
* - 0 o false: No aprobada, 1 o true: Aprobada
*/
public SolicitudPrestamoWs(int id, Dispositivo dispositivoSolicitado, Date fechaSolicitud, Investigador solicitante,
Administrador adminProcesador, Boolean respuesta) {
this.id = id;
this.dispositivoSolicitado = dispositivoSolicitado;
this.fechaSolicitud = fechaSolicitud;
this.solicitante = solicitante;
this.adminProcesador = adminProcesador;
this.respuesta = respuesta;
}
public SolicitudPrestamoWs() {
}
/*
* Getters y Setters para los atributos de una solicitud de prestamo.
*/
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public Dispositivo getDispositivoSolicitado() {
return dispositivoSolicitado;
}
public void setDispositivoSolicitado(Dispositivo dispositivoSolicitado) {
this.dispositivoSolicitado = dispositivoSolicitado;
}
public Date getFechaSolicitud() {
return fechaSolicitud;
}
public void setFechaSolicitud(Date fechaSolicitud) {
this.fechaSolicitud = fechaSolicitud;
}
public Investigador getSolicitante() {
return solicitante;
}
public void setSolicitante(Investigador solicitante) {
this.solicitante = solicitante;
}
public Administrador getAdminProcesador() {
return adminProcesador;
}
public void setAdminProcesador(Administrador adminProcesador) {
this.adminProcesador = adminProcesador;
}
public Boolean getRespuesta() {
return respuesta;
}
public void setRespuesta(Boolean respuesta) {
this.respuesta = respuesta;
}
}
| true
|
4d4ca4d06e72bf907f62c2d5b2f0ff5454f74639
|
Java
|
yhamed/rbrecap
|
/src/test/java/com/mycompany/myapp/web/rest/SprintResourceIT.java
|
UTF-8
| 20,839
| 1.859375
| 2
|
[] |
no_license
|
package com.mycompany.myapp.web.rest;
import com.mycompany.myapp.RbRecapApp;
import com.mycompany.myapp.domain.Sprint;
import com.mycompany.myapp.domain.UserStory;
import com.mycompany.myapp.repository.SprintRepository;
import com.mycompany.myapp.repository.search.SprintSearchRepository;
import com.mycompany.myapp.service.SprintService;
import com.mycompany.myapp.service.dto.SprintDTO;
import com.mycompany.myapp.service.mapper.SprintMapper;
import com.mycompany.myapp.web.rest.errors.ExceptionTranslator;
import com.mycompany.myapp.service.dto.SprintCriteria;
import com.mycompany.myapp.service.SprintQueryService;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import org.mockito.MockitoAnnotations;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.data.domain.PageImpl;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.web.PageableHandlerMethodArgumentResolver;
import org.springframework.http.MediaType;
import org.springframework.http.converter.json.MappingJackson2HttpMessageConverter;
import org.springframework.test.web.servlet.MockMvc;
import org.springframework.test.web.servlet.setup.MockMvcBuilders;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.validation.Validator;
import javax.persistence.EntityManager;
import java.util.Collections;
import java.util.List;
import static com.mycompany.myapp.web.rest.TestUtil.createFormattingConversionService;
import static org.assertj.core.api.Assertions.assertThat;
import static org.elasticsearch.index.query.QueryBuilders.queryStringQuery;
import static org.hamcrest.Matchers.hasItem;
import static org.mockito.Mockito.*;
import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.*;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.*;
/**
* Integration tests for the {@Link SprintResource} REST controller.
*/
@SpringBootTest(classes = RbRecapApp.class)
public class SprintResourceIT {
private static final Integer DEFAULT_SPRINT_NUMBER = 0;
private static final Integer UPDATED_SPRINT_NUMBER = 1;
private static final Boolean DEFAULT_ACTIVE = false;
private static final Boolean UPDATED_ACTIVE = true;
@Autowired
private SprintRepository sprintRepository;
@Autowired
private SprintMapper sprintMapper;
@Autowired
private SprintService sprintService;
/**
* This repository is mocked in the com.mycompany.myapp.repository.search test package.
*
* @see com.mycompany.myapp.repository.search.SprintSearchRepositoryMockConfiguration
*/
@Autowired
private SprintSearchRepository mockSprintSearchRepository;
@Autowired
private SprintQueryService sprintQueryService;
@Autowired
private MappingJackson2HttpMessageConverter jacksonMessageConverter;
@Autowired
private PageableHandlerMethodArgumentResolver pageableArgumentResolver;
@Autowired
private ExceptionTranslator exceptionTranslator;
@Autowired
private EntityManager em;
@Autowired
private Validator validator;
private MockMvc restSprintMockMvc;
private Sprint sprint;
@BeforeEach
public void setup() {
MockitoAnnotations.initMocks(this);
final SprintResource sprintResource = new SprintResource(sprintService, sprintQueryService);
this.restSprintMockMvc = MockMvcBuilders.standaloneSetup(sprintResource)
.setCustomArgumentResolvers(pageableArgumentResolver)
.setControllerAdvice(exceptionTranslator)
.setConversionService(createFormattingConversionService())
.setMessageConverters(jacksonMessageConverter)
.setValidator(validator).build();
}
/**
* Create an entity for this test.
*
* This is a static method, as tests for other entities might also need it,
* if they test an entity which requires the current entity.
*/
public static Sprint createEntity(EntityManager em) {
Sprint sprint = new Sprint()
.sprintNumber(DEFAULT_SPRINT_NUMBER)
.active(DEFAULT_ACTIVE);
return sprint;
}
/**
* Create an updated entity for this test.
*
* This is a static method, as tests for other entities might also need it,
* if they test an entity which requires the current entity.
*/
public static Sprint createUpdatedEntity(EntityManager em) {
Sprint sprint = new Sprint()
.sprintNumber(UPDATED_SPRINT_NUMBER)
.active(UPDATED_ACTIVE);
return sprint;
}
@BeforeEach
public void initTest() {
sprint = createEntity(em);
}
@Test
@Transactional
public void createSprint() throws Exception {
int databaseSizeBeforeCreate = sprintRepository.findAll().size();
// Create the Sprint
SprintDTO sprintDTO = sprintMapper.toDto(sprint);
restSprintMockMvc.perform(post("/api/sprints")
.contentType(TestUtil.APPLICATION_JSON_UTF8)
.content(TestUtil.convertObjectToJsonBytes(sprintDTO)))
.andExpect(status().isCreated());
// Validate the Sprint in the database
List<Sprint> sprintList = sprintRepository.findAll();
assertThat(sprintList).hasSize(databaseSizeBeforeCreate + 1);
Sprint testSprint = sprintList.get(sprintList.size() - 1);
assertThat(testSprint.getSprintNumber()).isEqualTo(DEFAULT_SPRINT_NUMBER);
assertThat(testSprint.isActive()).isEqualTo(DEFAULT_ACTIVE);
// Validate the Sprint in Elasticsearch
verify(mockSprintSearchRepository, times(1)).save(testSprint);
}
@Test
@Transactional
public void createSprintWithExistingId() throws Exception {
int databaseSizeBeforeCreate = sprintRepository.findAll().size();
// Create the Sprint with an existing ID
sprint.setId(1L);
SprintDTO sprintDTO = sprintMapper.toDto(sprint);
// An entity with an existing ID cannot be created, so this API call must fail
restSprintMockMvc.perform(post("/api/sprints")
.contentType(TestUtil.APPLICATION_JSON_UTF8)
.content(TestUtil.convertObjectToJsonBytes(sprintDTO)))
.andExpect(status().isBadRequest());
// Validate the Sprint in the database
List<Sprint> sprintList = sprintRepository.findAll();
assertThat(sprintList).hasSize(databaseSizeBeforeCreate);
// Validate the Sprint in Elasticsearch
verify(mockSprintSearchRepository, times(0)).save(sprint);
}
@Test
@Transactional
public void checkSprintNumberIsRequired() throws Exception {
int databaseSizeBeforeTest = sprintRepository.findAll().size();
// set the field null
sprint.setSprintNumber(null);
// Create the Sprint, which fails.
SprintDTO sprintDTO = sprintMapper.toDto(sprint);
restSprintMockMvc.perform(post("/api/sprints")
.contentType(TestUtil.APPLICATION_JSON_UTF8)
.content(TestUtil.convertObjectToJsonBytes(sprintDTO)))
.andExpect(status().isBadRequest());
List<Sprint> sprintList = sprintRepository.findAll();
assertThat(sprintList).hasSize(databaseSizeBeforeTest);
}
@Test
@Transactional
public void getAllSprints() throws Exception {
// Initialize the database
sprintRepository.saveAndFlush(sprint);
// Get all the sprintList
restSprintMockMvc.perform(get("/api/sprints?sort=id,desc"))
.andExpect(status().isOk())
.andExpect(content().contentType(MediaType.APPLICATION_JSON_UTF8_VALUE))
.andExpect(jsonPath("$.[*].id").value(hasItem(sprint.getId().intValue())))
.andExpect(jsonPath("$.[*].sprintNumber").value(hasItem(DEFAULT_SPRINT_NUMBER)))
.andExpect(jsonPath("$.[*].active").value(hasItem(DEFAULT_ACTIVE.booleanValue())));
}
@Test
@Transactional
public void getSprint() throws Exception {
// Initialize the database
sprintRepository.saveAndFlush(sprint);
// Get the sprint
restSprintMockMvc.perform(get("/api/sprints/{id}", sprint.getId()))
.andExpect(status().isOk())
.andExpect(content().contentType(MediaType.APPLICATION_JSON_UTF8_VALUE))
.andExpect(jsonPath("$.id").value(sprint.getId().intValue()))
.andExpect(jsonPath("$.sprintNumber").value(DEFAULT_SPRINT_NUMBER))
.andExpect(jsonPath("$.active").value(DEFAULT_ACTIVE.booleanValue()));
}
@Test
@Transactional
public void getAllSprintsBySprintNumberIsEqualToSomething() throws Exception {
// Initialize the database
sprintRepository.saveAndFlush(sprint);
// Get all the sprintList where sprintNumber equals to DEFAULT_SPRINT_NUMBER
defaultSprintShouldBeFound("sprintNumber.equals=" + DEFAULT_SPRINT_NUMBER);
// Get all the sprintList where sprintNumber equals to UPDATED_SPRINT_NUMBER
defaultSprintShouldNotBeFound("sprintNumber.equals=" + UPDATED_SPRINT_NUMBER);
}
@Test
@Transactional
public void getAllSprintsBySprintNumberIsInShouldWork() throws Exception {
// Initialize the database
sprintRepository.saveAndFlush(sprint);
// Get all the sprintList where sprintNumber in DEFAULT_SPRINT_NUMBER or UPDATED_SPRINT_NUMBER
defaultSprintShouldBeFound("sprintNumber.in=" + DEFAULT_SPRINT_NUMBER + "," + UPDATED_SPRINT_NUMBER);
// Get all the sprintList where sprintNumber equals to UPDATED_SPRINT_NUMBER
defaultSprintShouldNotBeFound("sprintNumber.in=" + UPDATED_SPRINT_NUMBER);
}
@Test
@Transactional
public void getAllSprintsBySprintNumberIsNullOrNotNull() throws Exception {
// Initialize the database
sprintRepository.saveAndFlush(sprint);
// Get all the sprintList where sprintNumber is not null
defaultSprintShouldBeFound("sprintNumber.specified=true");
// Get all the sprintList where sprintNumber is null
defaultSprintShouldNotBeFound("sprintNumber.specified=false");
}
@Test
@Transactional
public void getAllSprintsBySprintNumberIsGreaterThanOrEqualToSomething() throws Exception {
// Initialize the database
sprintRepository.saveAndFlush(sprint);
// Get all the sprintList where sprintNumber greater than or equals to DEFAULT_SPRINT_NUMBER
defaultSprintShouldBeFound("sprintNumber.greaterOrEqualThan=" + DEFAULT_SPRINT_NUMBER);
// Get all the sprintList where sprintNumber greater than or equals to UPDATED_SPRINT_NUMBER
defaultSprintShouldNotBeFound("sprintNumber.greaterOrEqualThan=" + UPDATED_SPRINT_NUMBER);
}
@Test
@Transactional
public void getAllSprintsBySprintNumberIsLessThanSomething() throws Exception {
// Initialize the database
sprintRepository.saveAndFlush(sprint);
// Get all the sprintList where sprintNumber less than or equals to DEFAULT_SPRINT_NUMBER
defaultSprintShouldNotBeFound("sprintNumber.lessThan=" + DEFAULT_SPRINT_NUMBER);
// Get all the sprintList where sprintNumber less than or equals to UPDATED_SPRINT_NUMBER
defaultSprintShouldBeFound("sprintNumber.lessThan=" + UPDATED_SPRINT_NUMBER);
}
@Test
@Transactional
public void getAllSprintsByActiveIsEqualToSomething() throws Exception {
// Initialize the database
sprintRepository.saveAndFlush(sprint);
// Get all the sprintList where active equals to DEFAULT_ACTIVE
defaultSprintShouldBeFound("active.equals=" + DEFAULT_ACTIVE);
// Get all the sprintList where active equals to UPDATED_ACTIVE
defaultSprintShouldNotBeFound("active.equals=" + UPDATED_ACTIVE);
}
@Test
@Transactional
public void getAllSprintsByActiveIsInShouldWork() throws Exception {
// Initialize the database
sprintRepository.saveAndFlush(sprint);
// Get all the sprintList where active in DEFAULT_ACTIVE or UPDATED_ACTIVE
defaultSprintShouldBeFound("active.in=" + DEFAULT_ACTIVE + "," + UPDATED_ACTIVE);
// Get all the sprintList where active equals to UPDATED_ACTIVE
defaultSprintShouldNotBeFound("active.in=" + UPDATED_ACTIVE);
}
@Test
@Transactional
public void getAllSprintsByActiveIsNullOrNotNull() throws Exception {
// Initialize the database
sprintRepository.saveAndFlush(sprint);
// Get all the sprintList where active is not null
defaultSprintShouldBeFound("active.specified=true");
// Get all the sprintList where active is null
defaultSprintShouldNotBeFound("active.specified=false");
}
@Test
@Transactional
public void getAllSprintsByUserStoryIsEqualToSomething() throws Exception {
// Initialize the database
UserStory userStory = UserStoryResourceIT.createEntity(em);
em.persist(userStory);
em.flush();
sprint.addUserStory(userStory);
sprintRepository.saveAndFlush(sprint);
Long userStoryId = userStory.getId();
// Get all the sprintList where userStory equals to userStoryId
defaultSprintShouldBeFound("userStoryId.equals=" + userStoryId);
// Get all the sprintList where userStory equals to userStoryId + 1
defaultSprintShouldNotBeFound("userStoryId.equals=" + (userStoryId + 1));
}
/**
* Executes the search, and checks that the default entity is returned.
*/
private void defaultSprintShouldBeFound(String filter) throws Exception {
restSprintMockMvc.perform(get("/api/sprints?sort=id,desc&" + filter))
.andExpect(status().isOk())
.andExpect(content().contentType(MediaType.APPLICATION_JSON_UTF8_VALUE))
.andExpect(jsonPath("$.[*].id").value(hasItem(sprint.getId().intValue())))
.andExpect(jsonPath("$.[*].sprintNumber").value(hasItem(DEFAULT_SPRINT_NUMBER)))
.andExpect(jsonPath("$.[*].active").value(hasItem(DEFAULT_ACTIVE.booleanValue())));
// Check, that the count call also returns 1
restSprintMockMvc.perform(get("/api/sprints/count?sort=id,desc&" + filter))
.andExpect(status().isOk())
.andExpect(content().contentType(MediaType.APPLICATION_JSON_UTF8_VALUE))
.andExpect(content().string("1"));
}
/**
* Executes the search, and checks that the default entity is not returned.
*/
private void defaultSprintShouldNotBeFound(String filter) throws Exception {
restSprintMockMvc.perform(get("/api/sprints?sort=id,desc&" + filter))
.andExpect(status().isOk())
.andExpect(content().contentType(MediaType.APPLICATION_JSON_UTF8_VALUE))
.andExpect(jsonPath("$").isArray())
.andExpect(jsonPath("$").isEmpty());
// Check, that the count call also returns 0
restSprintMockMvc.perform(get("/api/sprints/count?sort=id,desc&" + filter))
.andExpect(status().isOk())
.andExpect(content().contentType(MediaType.APPLICATION_JSON_UTF8_VALUE))
.andExpect(content().string("0"));
}
@Test
@Transactional
public void getNonExistingSprint() throws Exception {
// Get the sprint
restSprintMockMvc.perform(get("/api/sprints/{id}", Long.MAX_VALUE))
.andExpect(status().isNotFound());
}
@Test
@Transactional
public void updateSprint() throws Exception {
// Initialize the database
sprintRepository.saveAndFlush(sprint);
int databaseSizeBeforeUpdate = sprintRepository.findAll().size();
// Update the sprint
Sprint updatedSprint = sprintRepository.findById(sprint.getId()).get();
// Disconnect from session so that the updates on updatedSprint are not directly saved in db
em.detach(updatedSprint);
updatedSprint
.sprintNumber(UPDATED_SPRINT_NUMBER)
.active(UPDATED_ACTIVE);
SprintDTO sprintDTO = sprintMapper.toDto(updatedSprint);
restSprintMockMvc.perform(put("/api/sprints")
.contentType(TestUtil.APPLICATION_JSON_UTF8)
.content(TestUtil.convertObjectToJsonBytes(sprintDTO)))
.andExpect(status().isOk());
// Validate the Sprint in the database
List<Sprint> sprintList = sprintRepository.findAll();
assertThat(sprintList).hasSize(databaseSizeBeforeUpdate);
Sprint testSprint = sprintList.get(sprintList.size() - 1);
assertThat(testSprint.getSprintNumber()).isEqualTo(UPDATED_SPRINT_NUMBER);
assertThat(testSprint.isActive()).isEqualTo(UPDATED_ACTIVE);
// Validate the Sprint in Elasticsearch
verify(mockSprintSearchRepository, times(1)).save(testSprint);
}
@Test
@Transactional
public void updateNonExistingSprint() throws Exception {
int databaseSizeBeforeUpdate = sprintRepository.findAll().size();
// Create the Sprint
SprintDTO sprintDTO = sprintMapper.toDto(sprint);
// If the entity doesn't have an ID, it will throw BadRequestAlertException
restSprintMockMvc.perform(put("/api/sprints")
.contentType(TestUtil.APPLICATION_JSON_UTF8)
.content(TestUtil.convertObjectToJsonBytes(sprintDTO)))
.andExpect(status().isBadRequest());
// Validate the Sprint in the database
List<Sprint> sprintList = sprintRepository.findAll();
assertThat(sprintList).hasSize(databaseSizeBeforeUpdate);
// Validate the Sprint in Elasticsearch
verify(mockSprintSearchRepository, times(0)).save(sprint);
}
@Test
@Transactional
public void deleteSprint() throws Exception {
// Initialize the database
sprintRepository.saveAndFlush(sprint);
int databaseSizeBeforeDelete = sprintRepository.findAll().size();
// Delete the sprint
restSprintMockMvc.perform(delete("/api/sprints/{id}", sprint.getId())
.accept(TestUtil.APPLICATION_JSON_UTF8))
.andExpect(status().isNoContent());
// Validate the database is empty
List<Sprint> sprintList = sprintRepository.findAll();
assertThat(sprintList).hasSize(databaseSizeBeforeDelete - 1);
// Validate the Sprint in Elasticsearch
verify(mockSprintSearchRepository, times(1)).deleteById(sprint.getId());
}
@Test
@Transactional
public void searchSprint() throws Exception {
// Initialize the database
sprintRepository.saveAndFlush(sprint);
when(mockSprintSearchRepository.search(queryStringQuery("id:" + sprint.getId()), PageRequest.of(0, 20)))
.thenReturn(new PageImpl<>(Collections.singletonList(sprint), PageRequest.of(0, 1), 1));
// Search the sprint
restSprintMockMvc.perform(get("/api/_search/sprints?query=id:" + sprint.getId()))
.andExpect(status().isOk())
.andExpect(content().contentType(MediaType.APPLICATION_JSON_UTF8_VALUE))
.andExpect(jsonPath("$.[*].id").value(hasItem(sprint.getId().intValue())))
.andExpect(jsonPath("$.[*].sprintNumber").value(hasItem(DEFAULT_SPRINT_NUMBER)))
.andExpect(jsonPath("$.[*].active").value(hasItem(DEFAULT_ACTIVE.booleanValue())));
}
@Test
@Transactional
public void equalsVerifier() throws Exception {
TestUtil.equalsVerifier(Sprint.class);
Sprint sprint1 = new Sprint();
sprint1.setId(1L);
Sprint sprint2 = new Sprint();
sprint2.setId(sprint1.getId());
assertThat(sprint1).isEqualTo(sprint2);
sprint2.setId(2L);
assertThat(sprint1).isNotEqualTo(sprint2);
sprint1.setId(null);
assertThat(sprint1).isNotEqualTo(sprint2);
}
@Test
@Transactional
public void dtoEqualsVerifier() throws Exception {
TestUtil.equalsVerifier(SprintDTO.class);
SprintDTO sprintDTO1 = new SprintDTO();
sprintDTO1.setId(1L);
SprintDTO sprintDTO2 = new SprintDTO();
assertThat(sprintDTO1).isNotEqualTo(sprintDTO2);
sprintDTO2.setId(sprintDTO1.getId());
assertThat(sprintDTO1).isEqualTo(sprintDTO2);
sprintDTO2.setId(2L);
assertThat(sprintDTO1).isNotEqualTo(sprintDTO2);
sprintDTO1.setId(null);
assertThat(sprintDTO1).isNotEqualTo(sprintDTO2);
}
@Test
@Transactional
public void testEntityFromId() {
assertThat(sprintMapper.fromId(42L).getId()).isEqualTo(42);
assertThat(sprintMapper.fromId(null)).isNull();
}
}
| true
|
f24b736eac6efdd3d84f4b64fac1d9af74ae6a07
|
Java
|
valeriynefyodov/CourseCG
|
/FF_13312i_Nefedov_Span/src/FF_13312i_Nefedov_Span/model/Fill.java
|
UTF-8
| 1,795
| 3.21875
| 3
|
[] |
no_license
|
package FF_13312i_Nefedov_Span.model;
import java.awt.*;
import java.awt.image.BufferedImage;
import java.util.List;
/**
* Class describing fill component
* Implements Shape interface
*/
public class Fill implements Shape {
private List<Span> spans;
private Point seed;
private Color color;
private int type;
/**
* Constructor that allows to set BufferedImage to fill on, seed point, fill's type and fill's color
* @param img - BufferedImage to fill on
* @param seed - seed point
* @param type - fill's type
* @param color - fill's color: 0 - dark, 1 - bright
*/
public Fill(BufferedImage img, Point seed, int type, int color) {
this.seed = seed;
this.type = type;
if (color == 0)
this.color = Color.BLUE;
if (color == 1)
this.color = Color.YELLOW;
this.spans = Span.findAllSpans(img, this.type, this.seed, this.color);
}
@Override
public void draw(Graphics2D g) {
for (Span span : this.spans)
span.draw(g);
}
@Override
public String getShapeName() { return "FILL"; }
@Override
public Point getSeed() { return this.seed; }
@Override
public int getFillColor() {
int ret = -1;
if (this.color == Color.BLUE)
ret = 0;
if (this.color == Color.YELLOW)
ret = 1;
return ret;
}
@Override
public int getPC() { return this.type; };
@Override
public Point getCenter() { return null; };
@Override
public int getRadius() { return -1; }
@Override
public float getLineWidth() { return -1; }
@Override
public List<Point> getPoints() { return null; }
@Override
public void delete() { }
}
| true
|
08786236898edd33263b603187e484b7038f9746
|
Java
|
Galio666/EBD
|
/src/controllers/Usuario.java
|
UTF-8
| 1,399
| 2.5625
| 3
|
[
"MIT"
] |
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 controllers;
/**
*
* @author Tomas
*/
public class Usuario {
int id_usuario;
int id_cuenta;
String nickname;
public Usuario(int id_usuario, int id_cuenta, String nickname) {
this.id_usuario = id_usuario;
this.id_cuenta = id_cuenta;
this.nickname = nickname;
}
/**
* @return the id_usuario
*/
public int getId_usuario() {
return id_usuario;
}
/**
* @param id_usuario the id_usuario to set
*/
public void setId_usuario(int id_usuario) {
this.id_usuario = id_usuario;
}
/**
* @return the id_cuenta
*/
public int getId_cuenta() {
return id_cuenta;
}
/**
* @param id_cuenta the id_cuenta to set
*/
public void setId_cuenta(int id_cuenta) {
this.id_cuenta = id_cuenta;
}
/**
* @return the nickname
*/
public String getNickname() {
return nickname;
}
/**
* @param nickname the nickname to set
*/
public void setNickname(String nickname) {
this.nickname = nickname;
}
}
| true
|
e9cfe671c0901e64d64440b4e37a9222a3e83624
|
Java
|
glorypulse/quiz
|
/leetcode/30-Day_LeetCoding_Challenge/2021/0217/Solution.java
|
UTF-8
| 728
| 3.375
| 3
|
[] |
no_license
|
class Solution {
public int maxArea(int[] height) {
int length = height.length;
int left = 0;
int right = length - 1;
int max = 0;
while (left < right) {
int heightL = height[left];
int heightR = height[right];
max = Math.max(max, (right - left) * Math.min(heightL, heightR));
if (heightL <= heightR) {
while (left < right && heightL >= height[left]) {
left ++;
}
}
if (heightR <= heightL) {
while (left < right && heightR >= height[right]) {
right --;
}
}
}
return max;
}
}
| true
|
d6a2d029687a08083caeaf89c2434d4429f607e7
|
Java
|
talkxin/taxleopard
|
/src/com/auction/dao/AuctionReportDaoImpl.java
|
UTF-8
| 660
| 2.09375
| 2
|
[] |
no_license
|
package com.auction.dao;
import java.sql.SQLException;
import java.util.List;
import com.auction.entity.AcAuction;
import com.ibatis.sqlmap.client.SqlMapClient;
public class AuctionReportDaoImpl implements AuctionReportDao{
private SqlMapClient sqlMapClient;
public SqlMapClient getSqlMapClient() {
return sqlMapClient;
}
public void setSqlMapClient(SqlMapClient sqlMapClient) {
this.sqlMapClient = sqlMapClient;
}
public List<AcAuction> find(AcAuction auction) {
try {
return sqlMapClient.queryForList("findAllAuction",auction);
} catch (SQLException e) {
e.printStackTrace();
}
return null;
}
}
| true
|
b03df1950b1f2d472274eef616f9a76b5d2ba6e6
|
Java
|
BhanuPrasadG/OPTUS-WS-POC-CLIENT-CODE
|
/src/main/java/com/ibm/financing/credit/persistence/bo/EntityOrgDTO.java
|
UTF-8
| 1,509
| 2.265625
| 2
|
[] |
no_license
|
package com.ibm.financing.credit.persistence.bo;
import java.io.Serializable;
import org.springframework.stereotype.Repository;
@SuppressWarnings("serial")
public class EntityOrgDTO implements Serializable{
private int id_entity;
private String name;
private int level;
private int id_parent;
private EntityOrgDTO parent;
public EntityOrgDTO(int id_entity, String name, int id_parent, int level) {
super();
this.id_entity = id_entity;
this.name = name;
this.level = level;
this.id_parent = id_parent;
}
public EntityOrgDTO(int id_entity, String name, int level) {
super();
this.id_entity = id_entity;
this.name = name;
this.level = level;
}
@Override
public String toString() {
return "EntityOrg [id_entity=" + id_entity + ", name=" + name + ", level=" + level + ", id_parent=" + id_parent
+ ", parent=" + (parent!=null? parent.id_entity:null) + "]";
}
public EntityOrgDTO getParent() {
return parent;
}
public void setParent(EntityOrgDTO parent) {
this.parent = parent;
}
public int getId_entity() {
return id_entity;
}
public void setId_entity(int id_entity) {
this.id_entity = id_entity;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public int getLevel() {
return level;
}
public void setLevel(int level) {
this.level = level;
}
public int getId_parent() {
return id_parent;
}
public void setId_parent(int id_parent) {
this.id_parent = id_parent;
}
}
| true
|
032dbbf97493467600ee6abc0bde90cab0a4fc2f
|
Java
|
Jaun7707/Samples
|
/Sample_Classwork_Hashmap.java
|
UTF-8
| 9,772
| 3.421875
| 3
|
[] |
no_license
|
///////////////////////////////////////////////////////////////////////////////
// ALL STUDENTS COMPLETE THESE SECTIONS
// Main Class File: LoadBalancerMain.java
// File: SimpleHashMap.java
// Semester: CS302 Spring 2014
//
// Author: Joseph Hoffmann
// CS Login: josephh
// Lecturer's Name: Jim Skrentny
//
///////////////////////////////////////////////////////////////////////////////
import java.util.*;
/**
* This class implements a generic map based on hash tables using chained
* buckets for collision resolution.
*
* <p>A map is a data structure that creates a key-value mapping. Keys are
* unique in the map. That is, there cannot be more than one value associated
* with a same key. However, two keys can map to a same value.</p>
*
* <p>The <tt>SimpleHashMap</tt> class takes two generic parameters, <tt>K</tt>
* and <tt>V</tt>, standing for the types of keys and values respectively. Items
* are stored in a hash table. Hash values are computed from the
* <tt>hashCode()</tt> method of the <tt>K</tt> type objects.</p>
*
* <p>The chained buckets are implemented using Java's <tt>LinkedList</tt>
* class. When a hash table is created, its initial table size and maximum
* load factor is set to <tt>11</tt> and <tt>0.75</tt>. The hash table can hold
* arbitrarily many key-value pairs and resizes itself whenever it reaches its
* maximum load factor.</p>
*
* <p><tt>null</tt> values are not allowed in <tt>SimpleHashMap</tt> and a
* NullPointerException is thrown if used. You can assume that <tt>equals()</tt>
* and <tt>hashCode()</tt> on <tt>K</tt> are defined, and that, for two
* non-<tt>null</tt> keys <tt>k1</tt> and <tt>k2</tt>, if <tt>k1.equals(k2)</tt>
* then <tt>k1.hashCode() == k2.hashCode()</tt>. Do not assume that if the hash
* codes are the same that the keys are equal since collisions are possible.</p>
*/
public class SimpleHashMap<K, V> {
/**
* A map entry (key-value pair).
*/
public static class Entry<K, V> {
private K key;
private V value;
/**
* Constructs the map entry with the specified key and value.
*/
public Entry(K k, V v) {
key = k;
value = v;
}
/**
* Returns the key corresponding to this entry.
*
* @return the key corresponding to this entry
*/
public K getKey() {
return key;
}
/**
* Returns the value corresponding to this entry.
*
* @return the value corresponding to this entry
*/
public V getValue() {
return value;
}
/**
* Replaces the value corresponding to this entry with the specified
* value.
*
* @param value new value to be stored in this entry
* @return old value corresponding to the entry
*/
public V setValue(V value) {
V oldValue = value;
this.value = value;
return oldValue;
}
}
//Class fields
private int[] primes = {11,23,47,97,197,397,797,1597,3203,6421,
12853,25717,51437,102877,205759,411527,823117,1646237,
3292489,6584983,13169977,26339969,52679969,105359939,
210719881,421439783,842879579,1685759167};
private int primeIndex = 0;
private double size;
private double loadFactor;
private LinkedList<Entry<K,V>>[] hashTable;
/**
* Constructs an empty hash map with initial capacity <tt>11</tt> and
* maximum load factor <tt>0.75</tt>.
**/
public SimpleHashMap() {
//Initialize class fields
hashTable = (LinkedList<Entry<K, V>>[])
new LinkedList[primes[primeIndex]];
for(int i = 0; i < hashTable.length; i++)
hashTable[i] = new LinkedList<Entry<K, V>>();
primeIndex++;
size = 0;
loadFactor = 0.75;
}
/**
* Returns the value to which the specified key is mapped, or null if this
* map contains no mapping for the key.
*
* @param key the key whose associated value is to be returned
* @return the value to which the specified key is mapped, or <tt>null</tt>
* if this map contains no mapping for the key
* @throws NullPointerException if the specified key is <tt>null</tt>
*/
public V get(Object key) {
//Check for null parameter
if(key == null)
throw new NullPointerException();
//Find and return the object searched for
for(Entry<K, V> entry : hashTable[hashFunction(key)])
if(entry.getKey().equals(key))
return entry.getValue();
return null;
}
/**
* <p>Associates the specified value with the specified key in this map.
* Neither the key nor the value can be <tt>null</tt>. If the map
* previously contained a mapping for the key, the old value is replaced.</p>
*
* <p>If the load factor of the hash table after the insertion would exceed
* the maximum load factor <tt>0.75</tt>, then the resizing mechanism is
* triggered. The size of the table should grow at least by a constant
* factor in order to ensure the amortized constant complexity. You must also
* ensure that the new selected size is Prime. After that, all of the mappings
* are rehashed to the new table.</p>
*
* @param key key with which the specified value is to be associated
* @param value value to be associated with the specified key
* @return the previous value associated with <tt>key</tt>, or
* <tt>null</tt> if there was no mapping for <tt>key</tt>.
* @throws NullPointerException if the key or value is <tt>null</tt>
*/
public V put(K key, V value) {
//Check null parameters
if(key == null || value == null)
throw new NullPointerException();
//Check if insertion kills load size
if((size + 1)/(double) hashTable.length > 0.75)
resize();
//Insert
Entry<K, V> entry = new Entry<K, V>(key, value);
V oldValue = null;
for(Entry<K, V> sub : hashTable[hashFunction(key)]) {
oldValue = sub.getValue();
if(sub.getKey().equals(key)) {
hashTable[hashFunction(key)].remove(sub);
hashTable[hashFunction(key)].add(entry);
return oldValue;
}
}
hashTable[hashFunction(key)].add(entry);
size++;
return oldValue;
}
/**
* Removes the mapping for the specified key from this map if present. This
* method does nothing if the key is not in the hash table.
*
* @param key key whose mapping is to be removed from the map
* @return the previous value associated with <tt>key</tt>, or <tt>null</tt>
* if there was no mapping for <tt>key</tt>.
* @throws NullPointerException if key is <tt>null</tt>
*/
public V remove(Object key) {
//Check for null parameters
if(key == null)
throw new NullPointerException();
//Check for existence and remove if found
V oldValue = null;
for(int i = 0; i < hashTable[hashFunction(key)].size(); i++) {
Entry<K, V> sub = hashTable[hashFunction(key)].get(i);
oldValue = sub.getValue();
if(sub.getKey().equals(key)) {
hashTable[hashFunction(key)].remove(i);
size--;
return oldValue;
}
}
return oldValue;
}
/**
* Returns the number of key-value mappings in this map.
*
* @return the number of key-value mappings in this map
*/
public int size() {
return (int) size;
}
/**
* Returns a list of all the mappings contained in this map. This method
* will iterate over the hash table and collect all the entries into a new
* list. If the map is empty, return an empty list (not <tt>null</tt>).
* The order of entries in the list can be arbitrary.
*
* @return a list of mappings in this map
*/
public List<Entry<K, V>> entries() {
//Create a new list to be returned
LinkedList<Entry<K, V>> entries = new LinkedList<Entry<K, V>>();
//Iterate through the the hashTable and retrieve its items
for(LinkedList<Entry<K, V>> list : hashTable) {
if (list.size() != 0) {
for (Entry<K, V> entry : list)
entries.add(entry);
}
}
return entries;
}
/**
* Creates an index for a given key value.
*
* @param key key whose mapping is determined
* @return the index for the hashTable
*/
private int hashFunction(Object key) {
//Create an index according the to table size and objects hashFunc
int index = key.hashCode() % hashTable.length;
if(index < 0)
index = index + hashTable.length;
return index;
}
/**
* Resizes the hashTable to the closest prime number that is
* at least double the size of the old table. Deletes the old
* table and refills the new table with old values.
*/
private void resize() {
//Create a new hashTable
LinkedList<Entry<K,V>>[] newHashTable = (LinkedList<Entry<K, V>>[])
new LinkedList[primes[primeIndex]];
for(int i = 0; i < newHashTable.length; i++)
newHashTable[i] = new LinkedList<Entry<K, V>>();
primeIndex++;
//Replace the old table with the new one
List<Entry<K, V>> entries = entries();
hashTable = newHashTable;
size = 0;
//Fill the new hashTable with the old objects
for(Entry<K, V> entry : entries)
put(entry.getKey(), entry.getValue());
}
}
| true
|
2493cb3da49e84be8aeca0a2c72eaa7bc2500578
|
Java
|
tahsnerken47/Test
|
/src/main/java/practiceMethods/MaxNum.java
|
UTF-8
| 438
| 3.28125
| 3
|
[] |
no_license
|
package practiceMethods;
public class MaxNum {
public static int maxNum(){
int num1=25;
int num2=37;
int num3=29;
if(num1>num2 && num1>num3){
return num1;
}else if(num2>num3 && num2>num1){
return num2;
}else{
return num3;
}
}
public static void main(String[] args) {
System.out.println("smallestNum() = " + maxNum());
}
}
| true
|
57f78a299a370a6766f5718362d87866dade6fb3
|
Java
|
mirandacastaing/examen-2
|
/Examen2/src/main/java/com/cenfotec/examen2/service/GuionService.java
|
UTF-8
| 546
| 1.671875
| 2
|
[] |
no_license
|
package com.cenfotec.examen2.service;
import java.util.List;
import com.cenfotec.examen2.domain.Guion;
public interface GuionService {
public void saveGuion(Guion newGuion);
public List<Guion> getAllGuiones();
public Guion findGuionById(String id);
public List<Guion> findGuionesByObra(String obra);
public List<Guion> findGuionesByGenero(String genero);
public List<Guion> findGuionesByProduccion(boolean produccion);
public List<Guion> findGuionesByObraAndGenero(String obra, String genero);
public void deleteAllGuiones();
}
| true
|
241de0757b952a281739a814c098098783141320
|
Java
|
comhuhuan/monitor
|
/src/main/java/com/act/monitor/web/vo/NetWorkVo.java
|
UTF-8
| 1,541
| 1.835938
| 2
|
[] |
no_license
|
package com.act.monitor.web.vo;
import java.util.List;
public class NetWorkVo{
private String soft_version;
private String elementType; //状态类型
private String euID;
private String euIP;
private Long houseID;
private String houseName;
private String recordTime;
private Integer status;
public Integer getStatus() {
return status;
}
public void setStatus(Integer status) {
this.status = status;
}
private List<NetWorkInfoVo> networkInfo;
public String getSoft_version() {
return soft_version;
}
public void setSoft_version(String soft_version) {
this.soft_version = soft_version;
}
public String getElementType() {
return elementType;
}
public void setElementType(String elementType) {
this.elementType = elementType;
}
public String getEuID() {
return euID;
}
public void setEuID(String euID) {
this.euID = euID;
}
public String getEuIP() {
return euIP;
}
public void setEuIP(String euIP) {
this.euIP = euIP;
}
public Long getHouseID() {
return houseID;
}
public void setHouseID(Long houseID) {
this.houseID = houseID;
}
public String getHouseName() {
return houseName;
}
public void setHouseName(String houseName) {
this.houseName = houseName;
}
public List<NetWorkInfoVo> getNetworkInfo() {
return networkInfo;
}
public void setNetworkInfo(List<NetWorkInfoVo> networkInfo) {
this.networkInfo = networkInfo;
}
public String getRecordTime() {
return recordTime;
}
public void setRecordTime(String recordTime) {
this.recordTime = recordTime;
}
}
| true
|
d969747ffc7eb5367b149b298c85674e53e68d84
|
Java
|
luchoaglp/GoPay
|
/src/main/java/ar/com/gopay/exception/PaymentLinkException.java
|
UTF-8
| 178
| 1.859375
| 2
|
[] |
no_license
|
package ar.com.gopay.exception;
public class PaymentLinkException extends RuntimeException {
public PaymentLinkException(String message) {
super(message);
}
}
| true
|
3550e4115c808ba694bde17a9c0d803a7b006145
|
Java
|
agramar93/Android
|
/Maps2/src/com/example/maps2/MainActivity.java
|
UTF-8
| 10,640
| 2.015625
| 2
|
[] |
no_license
|
package com.example.maps2;
import java.io.File;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.List;
import android.annotation.SuppressLint;
import android.app.Activity;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.location.Address;
import android.location.Criteria;
import android.location.Geocoder;
import android.location.Location;
import android.location.LocationManager;
import android.net.Uri;
import android.os.Bundle;
import android.os.Environment;
import android.view.View;
import android.webkit.MimeTypeMap;
import android.webkit.URLUtil;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;
import com.google.android.gms.maps.CameraUpdateFactory;
import com.google.android.gms.maps.GoogleMap;
import com.google.android.gms.maps.GoogleMap.OnInfoWindowClickListener;
import com.google.android.gms.maps.GoogleMap.OnMarkerClickListener;
import com.google.android.gms.maps.MapFragment;
import com.google.android.gms.maps.model.LatLng;
import com.google.android.gms.maps.model.Marker;
import com.google.android.gms.maps.model.MarkerOptions;
@SuppressLint("SimpleDateFormat")
public class MainActivity extends Activity implements android.location.LocationListener{
private String img_string; //will be initialized later to a specific marker title
private String mickey = "http://winlab.rutgers.edu/~huiqing/mickey.png";
private String donald = "http://winlab.rutgers.edu/~huiqing/donald.jpg";
private String goofy = "http://winlab.rutgers.edu/~huiqing/goofy.png";
private String garfield = "http://winlab.rutgers.edu/~huiqing/garfield.jpg";
MainActivity thisActivity = this;
private Marker c;
private String distance;
private LatLng myLatLng,ml,dl,gl,gal;
private Location donaldlocation, mickeylocation, garfieldlocation, goofylocation;
private GoogleMap googleMap;
private double mylatitude;
private double mylongitude;
private Object distance_to_goofy;
private Object distance_to_garfield;
private Object distance_to_mickey;
private Object distance_to_donald;
private LocationManager locationManager;
//Get Initial Time of Friends instantiation
SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy/MM/dd HH:mm:ss");
Calendar cal = Calendar.getInstance();
String time_friends = dateFormat.format(cal.getTime()).substring(11) + "(hr)/(min)/(sec)";
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
//Download appropriate files by running AsyncTasks
new DownloadFileFromURL(thisActivity).execute(mickey);
new DownloadFileFromURL(thisActivity).execute(donald);
new DownloadFileFromURL(thisActivity).execute(goofy);
new DownloadFileFromURL(thisActivity).execute(garfield);
try {
//Set up the Map with appropriate markers
setUpMap();
} catch (IOException e) {
e.printStackTrace();
}
locationManager.requestLocationUpdates(LocationManager.NETWORK_PROVIDER, 600000,0, thisActivity);
}
//Contains a call to setMap, InfoWindow, and MarkerListener
@SuppressLint("NewApi")
private void setUpMap() throws IOException {
if(googleMap ==null){
googleMap = ((MapFragment) getFragmentManager().findFragmentById(R.id.map)).getMap();
if (googleMap != null) {
setMap();
/*
* Set up customized InfoWindow. Composed of a picture of a View
* containing an ImageView and a TextView.
*/
googleMap.setOnInfoWindowClickListener(new OnInfoWindowClickListener() {
public void onInfoWindowClick(Marker m){
Uri uri = Uri.parse("http://www.google.com");
Intent intent = new Intent(Intent.ACTION_VIEW, uri);
startActivity(intent);
}
});
googleMap.setInfoWindowAdapter(new GoogleMap.InfoWindowAdapter() {
@Override
public View getInfoWindow(Marker marker) {
return null;
}
@Override
public View getInfoContents(Marker marker) {
//Create the View for the Info Window
View v = getLayoutInflater().inflate(R.layout.info_window,null);
//Search proper directory for the appropriate image_file corresponding to marker
File rootDirectory = new File(Environment.getExternalStoragePublicDirectory(
Environment.DIRECTORY_PICTURES), "My Pictures");
if(img_string.length()>0){
String file_name = URLUtil.guessFileName(img_string, null, MimeTypeMap.getFileExtensionFromUrl(img_string));
File imgFile = new File(rootDirectory, file_name);
if(imgFile.exists()){
Bitmap myBitmap = BitmapFactory.decodeFile(imgFile.getAbsolutePath());
ImageView myImage = (ImageView) v.findViewById(R.id.imageView2);
myImage.setImageBitmap(myBitmap);
}
}
TextView markerLabel = (TextView) v.findViewById(R.id.another_label);
markerLabel.setText(distance);
return v;
}
});
/*
* Listens for a Marker Click Listener and based on what marker was clicked
* it initializes some data members so that Info Window displays the appropriate
* information.
*/
googleMap.setOnMarkerClickListener(new OnMarkerClickListener(){
@Override
public boolean onMarkerClick(Marker marker) {
String msg = marker.getTitle();
if(msg.equals("mickey")){
img_string = mickey;
distance = distance_to_mickey.toString() + "meters " + time_friends ;
} else if(msg.equals("donald")){
img_string = donald;
distance = distance_to_donald.toString() + "meters " + time_friends;
} else if(msg.equals("goofy")){
img_string = goofy;
distance = distance_to_goofy.toString() + "meters " + time_friends;
} else if(msg.equals("garfield")){
img_string = garfield;
distance = distance_to_garfield.toString() + "meters " + time_friends;
}
else{
img_string = "";
distance = "Latitude: "+ myLatLng.latitude + "Longitude: " + myLatLng.longitude;
}
return false;
}
});
}
}
}
//Sets up map with markers
public void setMap() throws IOException{
googleMap.setMyLocationEnabled(true);
locationManager = (LocationManager) getSystemService(LOCATION_SERVICE);
//Gets Last Locaiton
Criteria criteria = new Criteria();
String provider = locationManager.getBestProvider(criteria, true);
Location myLocation = locationManager.getLastKnownLocation(provider);
googleMap.setMapType(GoogleMap.MAP_TYPE_HYBRID);
//get location coordinates of current location
if(myLocation!=null){
mylatitude = myLocation.getLatitude();
mylongitude = myLocation.getLongitude();
myLatLng = new LatLng(mylatitude, mylongitude);
}
//Use Geocoder to find the address
Geocoder gc = new Geocoder(this);
List<Address> list = gc.getFromLocation(mylatitude, mylongitude,1);
Address add = list.get(0);
String locality = add.getLocality();
Toast.makeText(this, locality, Toast.LENGTH_LONG).show(); //Display the address
//Update the map to the currentlocation and add the currentLocationmarker
googleMap.moveCamera(CameraUpdateFactory.newLatLng(myLatLng));
googleMap.animateCamera(CameraUpdateFactory.zoomTo(20));
c = googleMap.addMarker(new MarkerOptions().position(new LatLng(mylatitude,mylongitude)).title("you are here!"));
//Add the appropriate friends markers
ml = new LatLng(40.51783, -74.465297);
googleMap.addMarker(
new MarkerOptions().position(ml)
.title("mickey").visible(true));
dl = new LatLng(40.51389, -74.433849);
googleMap.addMarker(
new MarkerOptions().position(dl)
.title("donald").visible(true));
gl = new LatLng(40.495527, -74.467142);
googleMap.addMarker(
new MarkerOptions().position(gl)
.title("goofy").visible(true));
gal = new LatLng(40.497127, -74.417056);
googleMap.addMarker(
new MarkerOptions().position(gal)
.title("garfield").visible(true));
//Create Locations for friends
donaldlocation = new Location("donald");
donaldlocation.setLatitude(dl.latitude);
donaldlocation.setLongitude(dl.longitude);
goofylocation = new Location("goofy");
goofylocation.setLatitude(gl.latitude);
goofylocation.setLongitude(gl.longitude);
garfieldlocation = new Location("garfield");
garfieldlocation.setLatitude(gal.latitude);
garfieldlocation.setLongitude(gal.longitude);
mickeylocation = new Location("mickey");
mickeylocation.setLatitude(ml.latitude);
mickeylocation.setLongitude(ml.longitude);
//Calculate Initial Distance
distance_to_donald = (int) myLocation.distanceTo(donaldlocation);
distance_to_goofy = (int) myLocation.distanceTo(goofylocation);
distance_to_garfield =(int) myLocation.distanceTo(garfieldlocation);
distance_to_mickey = (int) myLocation.distanceTo(mickeylocation);
}
@Override
public void onLocationChanged(Location location) {
mylatitude = location.getLatitude();
mylongitude = location.getLongitude();
myLatLng = new LatLng(mylatitude, mylongitude);
//Use Geocoder to find the address
Geocoder gc = new Geocoder(this);
List<Address> list = null;
try {
list = gc.getFromLocation(mylatitude, mylongitude,1);
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
Address add = list.get(0);
String locality = add.getLocality();
Toast.makeText(this, locality, Toast.LENGTH_LONG).show(); //Display the address
//Update the map to the currentlocation and add the currentLocationmarker
googleMap.moveCamera(CameraUpdateFactory.newLatLng(myLatLng));
googleMap.animateCamera(CameraUpdateFactory.zoomTo(20));
c.setPosition(myLatLng);
//updatedistance
distance_to_donald = (int) location.distanceTo(donaldlocation);
distance_to_goofy = (int) location.distanceTo(goofylocation);
distance_to_garfield =(int) location.distanceTo(garfieldlocation);
distance_to_mickey = (int) location.distanceTo(mickeylocation);
}
@Override
public void onStatusChanged(String provider, int status, Bundle extras) {
// TODO Auto-generated method stub
}
@Override
public void onProviderEnabled(String provider) {
// TODO Auto-generated method stub
}
@Override
public void onProviderDisabled(String provider) {
// TODO Auto-generated method stub
}
}
| true
|
1e1b8c14781bc9ac7b7f4e60b3d608bf71327713
|
Java
|
DCRUNNN/MovieTubeServer
|
/src/main/test/cn/edu/nju/movietubeserver/service/CommentServiceImplTest.java
|
UTF-8
| 3,198
| 1.90625
| 2
|
[] |
no_license
|
package cn.edu.nju.movietubeserver.service;
import cn.edu.nju.movietubeserver.MovieTubeServerMain;
import cn.edu.nju.movietubeserver.dao.CommentDao;
import cn.edu.nju.movietubeserver.model.domain.SimpleUser;
import cn.edu.nju.movietubeserver.model.po.CommentPo;
import io.swagger.models.auth.In;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.test.context.junit4.SpringRunner;
import org.springframework.transaction.annotation.Transactional;
import java.time.LocalDateTime;
import java.util.HashMap;
import java.util.Map;
import static org.junit.Assert.*;
/**
* @author zhaodeyu
* @classname CommentServiceImplTest
* @description TODO
* @date 2020-02-12 16:03
*/
@RunWith(SpringRunner.class)
@SpringBootTest(classes = MovieTubeServerMain.class)
@Transactional
public class CommentServiceImplTest {
@Autowired
CommentService commentService;
@Test
public void getBaseElasticSearchDao() {
assertNotNull(commentService.getBaseElasticSearchDao());
}
@Test
public void listRootCommentByMovieId() {
int pageNo = 0;
int pageSize = 10;
long movieId = 3114117;
Map<Integer, SimpleUser> simpleUserMap = new HashMap<>();
assertNotNull(commentService.listRootCommentByMovieId(pageNo, pageSize, movieId, simpleUserMap));
}
@Test
public void listReplyCommentOfRootComment() {
int pageNo = 0;
int pageSize = 10;
long movieId = 3114117;
String rootCommentId = "-1";
Map<Integer, SimpleUser> simpleUserMap = new HashMap<>();
assertNotNull(commentService.listReplyCommentOfRootComment(pageNo, pageSize, movieId, rootCommentId, simpleUserMap));
}
@Test
public void listUserPostComments() {
int pageNo = 0;
int pageSize = 10;
int userId = 1;
Map<Integer, SimpleUser> simpleUserMap = new HashMap<>();
assertNotNull(commentService.listUserPostComments(pageNo, pageSize, userId, simpleUserMap));
}
@Test
public void listUserReceiveComments() {
int pageNo = 0;
int pageSize = 10;
int userId = 1;
Map<Integer, SimpleUser> simpleUserMap = new HashMap<>();
assertNotNull(commentService.listUserReceiveComments(pageNo, pageSize, userId, simpleUserMap));
}
@Test
public void insertComment() {
// CommentPo commentPo = new CommentPo();
// commentPo.setParentCommentId("-1");
// commentPo.setRootCommentId("-1");
// commentPo.setMovieId((long) 3114117);
// commentPo.setFromUserId(1);
// commentPo.setToUserId(-1);
// commentPo.setContent("单元测试");
// commentPo.setCreateTime(LocalDateTime.now().toString());
// try {
// commentService.insertComment(commentPo);
// assertTrue(true);
// } catch (Exception e) {
// fail();
// }
}
@Test
public void deleteByCommentId() {
}
@Test
public void deleteByMovieId() {
}
@Test
public void convert() {
}
}
| true
|
f4698a5a25d6db58c97a52c8e71ef7e561767431
|
Java
|
emranhos1/Basic-Data-Entry
|
/src/main/java/com/jinanit/basicdataentry/dao/CategoryDao.java
|
UTF-8
| 842
| 1.703125
| 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.jinanit.basicdataentry.dao;
import com.jinanit.basicdataentry.model.Category;
import java.util.List;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Repository;
/**
*
* @author Istiaque && Emran
*/
@Repository
public class CategoryDao {
@Autowired
JdbcDao jdbcDao;
@SuppressWarnings("unchecked")
public List<Category> getCategory() {
String sSelectQuery = "SELECT id, initcap(cat_name) as cat_name FROM category";
List list = jdbcDao.getObjectList(sSelectQuery, new Object[]{}, Category.class);
return list;
}
}
| true
|
bf125f2d854daefe0977fad0a3c26c0e5c604f00
|
Java
|
yanndanielou/yanndanielou-programmation
|
/Java/PretsImmobiliers/src/hmi/editors/ChoixRemboursementAnticipeCapitalAvecDiminutionNombreEcheancesEcheanceMenuItem.java
|
UTF-8
| 779
| 2.0625
| 2
|
[] |
no_license
|
package hmi.editors;
import java.text.NumberFormat;
import model.Echeance;
import Core.ModificationAction.RemboursementAnticipeCapitalAction;
import Core.ModificationAction.RemboursementAnticipeCapitalAvecDiminutionNombreEcheancesAction;
public class ChoixRemboursementAnticipeCapitalAvecDiminutionNombreEcheancesEcheanceMenuItem extends ModificationEcheanceActionMenuItem {
private static final long serialVersionUID = -978794474604856189L;
public ChoixRemboursementAnticipeCapitalAvecDiminutionNombreEcheancesEcheanceMenuItem(int capitalRembourse, Echeance echeance) {
super("Avec diminution du nombre d'échéances", echeance);
modificationEcheanceAction = new RemboursementAnticipeCapitalAvecDiminutionNombreEcheancesAction(capitalRembourse, echeance);
}
}
| true
|
078f7d26c773cf9e2172f2b974d76dad2d7afb14
|
Java
|
caofujun/lqt
|
/src/com/nis/cdc/entity/CtgSys007Dictcontagion.java
|
UTF-8
| 3,569
| 1.617188
| 2
|
[] |
no_license
|
package com.nis.cdc.entity;
import com.nis.comm.entity.BaseEntity;
import java.io.Serializable;
import java.util.List;
import org.apache.ibatis.type.Alias;
@Alias("ctgSys007Dictcontagion")
public class CtgSys007Dictcontagion extends BaseEntity implements Serializable {
private String diseaseid;
private String diseasename;
private String zjf;
private String icd10;
private Long caninput;
private Long sexcard;
private Long sortseq;
private String parentid;
private String kindid;
private String kindname;
private Long isintestinal;
private Long isrespiratory;
private Long isnatural;
private Long ishemic;
private Long issexspread;
private Double scopetime;
private Long repeatCycle;
private Long isimportant;
private List<CtgSys007Dictcontagion> children;
private String iconCls;
public String getIconCls() {
return this.iconCls;
}
public void setIconCls(String iconCls) {
this.iconCls = iconCls;
}
public List<CtgSys007Dictcontagion> getChildren() {
return this.children;
}
public void setChildren(List<CtgSys007Dictcontagion> children) {
this.children = children;
}
public Long getRepeatCycle() {
return this.repeatCycle;
}
public void setRepeatCycle(Long repeatCycle) {
this.repeatCycle = repeatCycle;
}
public Long getIsimportant() {
return this.isimportant;
}
public void setIsimportant(Long isimportant) {
this.isimportant = isimportant;
}
public String getDiseaseid() {
return this.diseaseid;
}
public void setDiseaseid(String diseaseid) {
this.diseaseid = diseaseid;
}
public String getDiseasename() {
return this.diseasename;
}
public void setDiseasename(String diseasename) {
this.diseasename = diseasename;
}
public String getZjf() {
return this.zjf;
}
public void setZjf(String zjf) {
this.zjf = zjf;
}
public String getIcd10() {
return this.icd10;
}
public void setIcd10(String icd10) {
this.icd10 = icd10;
}
public Long getCaninput() {
return this.caninput;
}
public void setCaninput(Long caninput) {
this.caninput = caninput;
}
public Long getSexcard() {
return this.sexcard;
}
public void setSexcard(Long sexcard) {
this.sexcard = sexcard;
}
public Long getSortseq() {
return this.sortseq;
}
public void setSortseq(Long sortseq) {
this.sortseq = sortseq;
}
public String getParentid() {
return this.parentid;
}
public void setParentid(String parentid) {
this.parentid = parentid;
}
public String getKindid() {
return this.kindid;
}
public void setKindid(String kindid) {
this.kindid = kindid;
}
public String getKindname() {
return this.kindname;
}
public void setKindname(String kindname) {
this.kindname = kindname;
}
public Long getIsintestinal() {
return this.isintestinal;
}
public void setIsintestinal(Long isintestinal) {
this.isintestinal = isintestinal;
}
public Long getIsrespiratory() {
return this.isrespiratory;
}
public void setIsrespiratory(Long isrespiratory) {
this.isrespiratory = isrespiratory;
}
public Long getIsnatural() {
return this.isnatural;
}
public void setIsnatural(Long isnatural) {
this.isnatural = isnatural;
}
public Long getIshemic() {
return this.ishemic;
}
public void setIshemic(Long ishemic) {
this.ishemic = ishemic;
}
public Long getIssexspread() {
return this.issexspread;
}
public void setIssexspread(Long issexspread) {
this.issexspread = issexspread;
}
public Double getScopetime() {
return this.scopetime;
}
public void setScopetime(Double scopetime) {
this.scopetime = scopetime;
}
}
| true
|
aba16f631d8d10aaceaf2321ef210938967a2e54
|
Java
|
YUEIT/java_common
|
/common/src/main/java/cn/yue/base/common/widget/emoji/EmojiSort.java
|
UTF-8
| 1,822
| 2.171875
| 2
|
[] |
no_license
|
package cn.yue.base.common.widget.emoji;
import java.util.List;
import cn.yue.base.common.widget.keyboard.mode.IEmotionPage;
import cn.yue.base.common.widget.keyboard.mode.IEmotionSort;
/**
* Description : emoji分类
* Created by yue on 2018/11/16
*/
public class EmojiSort implements IEmotionSort {
private int sortIndex;
private int firstPagePosition;
private String sortName;
private String iconUrl;
private int iconResId;
private int count;
private List<EmojiPage> pageList;
public void setSortIndex(int sortIndex) {
this.sortIndex = sortIndex;
}
public void setFirstPagePosition(int firstPagePosition) {
this.firstPagePosition = firstPagePosition;
}
public void setSortName(String sortName) {
this.sortName = sortName;
}
public void setIconUrl(String iconUrl) {
this.iconUrl = iconUrl;
}
public void setIconResId(int iconResId) {
this.iconResId = iconResId;
}
public void setCount(int count) {
this.count = count;
}
public List<EmojiPage> getPageList() {
return pageList;
}
public void setPageList(List<EmojiPage> pageList) {
this.pageList = pageList;
}
@Override
public int getSortIndex() {
return sortIndex;
}
@Override
public int getFirstPagePosition() {
return firstPagePosition;
}
@Override
public String getSortName() {
return sortName;
}
@Override
public String getIconUrl() {
return iconUrl;
}
@Override
public int getImageResId() {
return iconResId;
}
@Override
public int getCount() {
return count;
}
@Override
public List<? extends IEmotionPage> getEmotionPage() {
return pageList;
}
}
| true
|
b65cb1dddb7dafc9c0a732a9caf79bdcee29c680
|
Java
|
MikuNyanya/RabbitBot
|
/src/main/java/gugugu/entity/apirequest/weibo/InfoWeiboHomeTimeline.java
|
UTF-8
| 478
| 1.617188
| 2
|
[
"MIT"
] |
permissive
|
package gugugu.entity.apirequest.weibo;
import lombok.Getter;
import lombok.Setter;
import java.util.List;
/**
* create by MikuLink on 2020/1/8 19:16
* for the Reisen
* 只解析了必要字段
* api文档:https://open.weibo.com/wiki/2/statuses/home_timeline
*/
@Getter
@Setter
public class InfoWeiboHomeTimeline {
//微博推文列表
private List<InfoStatuses> statuses;
//since_id 用于避免重复获取旧信息的字段
private Long since_id;
}
| true
|
3cb9b4788a1dd5db781d0f5d3b07d145d995a888
|
Java
|
SJLBenjamin/BarChartView
|
/app/src/main/java/com/example/barchartview/canvas/CanvasStackView.java
|
UTF-8
| 1,780
| 2.5625
| 3
|
[] |
no_license
|
package com.example.barchartview.canvas;
import android.content.Context;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Paint;
import android.graphics.Rect;
import android.util.AttributeSet;
import android.view.View;
import androidx.annotation.Nullable;
import com.example.barchartview.R;
/*
* 画布裁减和复原
* */
public class CanvasStackView extends View {
Paint mPaint;
Rect mRect;
public CanvasStackView(Context context) {
super(context);
initData();
}
public CanvasStackView(Context context, @Nullable AttributeSet attrs) {
super(context, attrs);
initData();
}
public CanvasStackView(Context context, @Nullable AttributeSet attrs, int defStyleAttr) {
super(context, attrs, defStyleAttr);
initData();
}
private void initData() {
mPaint= new Paint();
mRect = new Rect(0,0,300,300);
mPaint.setColor(Color.BLACK);
// ----------设置填充风格----------
mPaint.setStyle(Paint.Style.STROKE);
}
@Override
protected void onDraw(Canvas canvas) {
super.onDraw(canvas);
canvas.drawColor(Color.RED);
canvas.drawRect(mRect,mPaint);
canvas.save();//保存当前画布
//裁减一块区域
canvas.clipRect(100,100,800,800);
canvas.drawColor(Color.YELLOW);
canvas.save();//保存当前画布
canvas.clipRect(200,200,600,600);
canvas.drawColor(Color.BLUE);
canvas.save();//保存当前画布
canvas.restore();//将栈顶画布拿出
canvas.restore();//将栈顶画布拿出
canvas.restore();//将栈顶画布拿出
//canvas.drawColor(Color.BLACK);//设置为黑色
}
}
| true
|
d3077e14fb2cfd286d136c6f10136ea8c7b2c041
|
Java
|
22423shivam/CapgeminiADAPT
|
/RabbitMQ/Question1/src/main/java/Service/CustomerNotification.java
|
UTF-8
| 802
| 2.609375
| 3
|
[] |
no_license
|
package com.assignment1.CustomerProd.Service;
import com.assignment1.CustomerProd.Model.Customer;
import com.assignment1.CustomerProd.RabbitMQConfig;
import com.assignment1.CustomerProd.Repo.CustomerRepo;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
@Component
public class CustomerNotification {
@Autowired
CustomerRepo customerRepo;
/**
* use a new queue for consuming the customer produced
* each time a customer is added to the DB
*/
@RabbitListener(queues = RabbitMQConfig.queueName)
public void consumeMess(Customer customer){
customerRepo.save(customer);
System.out.println("Customer added to DB");
}
}
| true
|
8c56f0fc0103b97ae5a1a99975898eaa07beaf92
|
Java
|
Mizen314/challenge-birras-santander
|
/challenge-birras-santander-common/src/main/java/com/agreggio/challenge/birras/santander/common/entitie/AuditableEntity.java
|
UTF-8
| 1,209
| 2.046875
| 2
|
[] |
no_license
|
package com.agreggio.challenge.birras.santander.common.entitie;
import org.springframework.data.annotation.CreatedDate;
import org.springframework.data.annotation.LastModifiedDate;
import javax.persistence.Column;
import javax.persistence.MappedSuperclass;
import java.io.Serializable;
import java.sql.Timestamp;
@MappedSuperclass
public class AuditableEntity implements Serializable {
private static final long serialVersionUID = 1L;
@CreatedDate
@Column(name = "CREATE_DATE")
private Timestamp createDate;
@Column(name = "DELETE_DATE")
private Timestamp deleteDate;
@LastModifiedDate
@Column(name = "LAST_UPDATE")
private Timestamp lastUpdate;
public Timestamp getCreateDate() {
return createDate;
}
public void setCreateDate(Timestamp createDate) {
this.createDate = createDate;
}
public Timestamp getLastUpdate() {
return lastUpdate;
}
public Timestamp getDeleteDate() {
return deleteDate;
}
public void setDeleteDate(Timestamp deleteDate) {
this.deleteDate = deleteDate;
}
public void setLastUpdate(Timestamp lastUpdate) {
this.lastUpdate = lastUpdate;
}
}
| true
|
865fc78f04efbfb5193952fa54473bc0fdd0624d
|
Java
|
apache/lenya
|
/org.apache.lenya.module.export/src/main/java/org/apache/lenya/cms/export/Import.java
|
UTF-8
| 3,748
| 1.929688
| 2
|
[
"Apache-2.0"
] |
permissive
|
/*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
*/
package org.apache.lenya.cms.export;
import java.io.File;
import org.apache.lenya.cms.publication.Area;
import org.apache.lenya.cms.publication.Document;
import org.apache.lenya.cms.publication.Publication;
import org.apache.lenya.cms.usecase.AbstractUsecase;
import org.apache.lenya.utils.URLInformation;
/**
* Import content.
*/
public class Import extends AbstractUsecase {
private Importer importer;
protected void initParameters() {
super.initParameters();
//String pubId = new URLInformation(getSourceURL()).getPublicationId();
String pubId = new URLInformation().getPublicationId();
Publication pub = getSession().getPublication(pubId);
String path = getExampleContentPath(pub);
if (!new File(path).exists()) {
path = getExampleContentPath(getDefaultPub());
}
setParameter("path", path);
}
protected String getExampleContentPath(Publication publication) {
return publication.getSourceUri() + "/example-content";
}
protected Publication getDefaultPub() {
return getSession().getPublication("default");
}
protected void doCheckPreconditions() throws Exception {
super.doCheckPreconditions();
Area area = getArea();
Document[] doc = area.getDocuments();
String test = "test";
if (area.getDocuments().length > 0) {
addErrorMessage("You can't import anything because this publication already contains content.");
}
}
protected Area getArea() {
/*String url = getSourceURL();
URLInformation info = new URLInformation(url);*/
URLInformation info = new URLInformation();
String pubId = info.getPublicationId();
String areaName = info.getArea();
return getSession().getPublication(pubId).getArea(areaName);
}
protected void doCheckExecutionConditions() throws Exception {
super.doCheckExecutionConditions();
String path = getParameterAsString("path");
String baseUri = "file://" + path;
String sitetreeUri = baseUri + "/sitetree.xml";
if (!importer.checkSitetreeUri(sitetreeUri)){
addErrorMessage("The sitetree file does not exist in this directory.");
}
}
protected void doExecute() throws Exception {
super.doExecute();
String path = getParameterAsString("path");
/*Importer importer = new Importer(getLogger());
importer.setDocumentManager(getDocumentManager());
importer.setResourceTypeResolver(getResourceTypeResolver());
importer.setSourceResolver(getSourceResolver());*/
importer.setLogger(getLogger());
importer.importContent(getDefaultPub(), getArea(), path);
}
public Importer getImporter() {
return importer;
}
public void setImporter(Importer importer) {
this.importer = importer;
}
}
| true
|
92a04f213e1068e90f1a96c9972043ef981b1dd2
|
Java
|
chvvsubbu/problemsolving
|
/AmazonSets/src/com/codechef/Main.java
|
UTF-8
| 961
| 3.375
| 3
|
[] |
no_license
|
package com.codechef;
import java.util.Scanner;
public class Main {
public static String winOrLoss(String game) {
String gameresult = game.trim();
int chef = 0, comp = 0, result;
for (int i = 0; i < gameresult.length(); i++) {
result = gameresult.charAt(i) - '0';
if (result == 1)
chef++;
else
comp++;
if (chef == 11 && comp <= 9)
return "WIN";
else if (chef <= 9 && comp == 11)
return "LOOSE";
else if (chef >= 10 && comp >= 10) {
if ((chef - comp) == 2)
return "WIN";
else if ((comp - chef) == 2)
return "LOOSE";
}
}
return "LOOSE";
}
public static void main(String[] args) {
// TODO Auto-generated method stub
Scanner sc = new Scanner(System.in);
String st;
int T, i;
T = Integer.parseInt(sc.nextLine().trim());
for (i = 0; i <= T; i++) {
st = sc.nextLine();
sc.next
System.out.println(winOrLoss(st));
}
}
}
| true
|
85451927adf7e4fabbae2e4a7d30b110294c5a35
|
Java
|
JAYASHREEPATIL/JAVA_-DS-Algo
|
/GCDDemo.java
|
UTF-8
| 392
| 2.890625
| 3
|
[] |
no_license
|
import java.util.*;
public class GCDDemo
{
public static void main(String args[])
{
int a =90;
int b=34;
int c=0;
int max = 0;
int result=0;
if(a<b)
{
c=a;
}
else
{
c=b;
}
for(int i=1;i<=c;i++)
{
if((a%i==0) && (b%i==0) )
{
result=i;
max = Math.max(max,result);
}
}
int lcm = a/max * b/max * max;
System.out.println(lcm);
}
}
| true
|
3d8c0e13509ecff50f0f029d5532fd5ef46385cb
|
Java
|
chodkos/POS
|
/src/main/java/com/pos/transaction/Transaction.java
|
UTF-8
| 2,105
| 2.65625
| 3
|
[] |
no_license
|
package com.pos.transaction;
import com.pos.display.Display;
import com.pos.display.SimpleDisplay;
import com.pos.item.*;
import com.pos.printer.Printer;
import com.pos.printer.PrinterImpl;
import com.pos.reader.StubbedReader;
import com.pos.reader.Reader;
import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.List;
public class Transaction {
private Reader reader = new StubbedReader();
private Display display = new SimpleDisplay();
private ItemDao itemDao = new ItemDaoImpl();
private ItemService itemService = new ItemService(itemDao);
private Printer printer = new PrinterImpl();
private List<Item> scannedItems = new ArrayList<>();
public Transaction(Reader reader, Display display, ItemDao itemDao, ItemService itemService, Printer printer) {
this.reader = reader;
this.display = display;
this.itemDao = itemDao;
this.itemService = itemService;
this.printer = printer;
}
public Transaction() {
}
public void startTransaction() {
Code barcode = reader.read();
if (barcode.getBarcode().isEmpty()) {
display.codeIsEmpty();
return;
} else {
Item scannedItem = itemService.getItemByBarcode(barcode);
if(scannedItem == null){
display.itemNotFound();
}else {
display.showItem(scannedItem);
scannedItems.add(scannedItem);
}
}
}
public void checkout(){
BigDecimal totalprice = getTotalPrice(scannedItems);
display.showTotalPrice(totalprice);
printer.printReceipt(scannedItems, totalprice);
}
public BigDecimal getTotalPrice(List<Item> scannedItems){
BigDecimal sumOfPrices = new BigDecimal("0");
for (Item item : scannedItems){
sumOfPrices = sumOfPrices.add(item.getPrice());
}
return sumOfPrices;
}
public void clearResources(){
scannedItems.clear();
}
public List<Item> getScannedItems() {
return scannedItems;
}
}
| true
|
b5d19c386b7a13331c076dc5c817bd470078b5d8
|
Java
|
PolinkaBelozorovich/KMproject
|
/Desktop/labaaa7/src/main/java/pages/DeliveryPage.java
|
UTF-8
| 628
| 2.375
| 2
|
[] |
no_license
|
package pages;
import elements.*;
import extensions.FireFoxDriverEx;
import org.openqa.selenium.support.CacheLookup;
import org.openqa.selenium.support.FindBy;
public class DeliveryPage extends Page {
public DeliveryPage(FireFoxDriverEx driver) {
super(driver);
}
@FindBy(id = "total_checkout_amount")
@CacheLookup
public Html_Label price;
@FindBy(id = "make-order")
@CacheLookup
public Button bbutton;
public int getPrice(){
String stringValue = price.getText();
stringValue = stringValue.replaceAll(" ","");
return Integer.parseInt(stringValue);
}
}
| true
|
0c55b3fc1d2f25b3310bf6ca30946fc4fe66e42c
|
Java
|
limyjie/presentation
|
/src/main/java/org/lucas/blog/utils/StringUtil.java
|
UTF-8
| 308
| 1.679688
| 2
|
[] |
no_license
|
/**
* Author: lin
* Date: 2019/3/12 21:42
*/
package org.lucas.blog.utils;
public class StringUtil {
private StringUtil(){}
public static final String imgContext = "C:\\Users\\lin\\Pictures\\Saved Pictures\\";
public static final String imgUrlContext = "http://127.0.0.1:8080/file/img/";
}
| true
|
e74a4ea9e584ddf8765aee543aedee8f9369c52b
|
Java
|
andrelportella/WSConsumerAPI
|
/src/main/java/br/com/grupocidade/b2click/ws/model/response/ProdutoResponse.java
|
UTF-8
| 339
| 1.835938
| 2
|
[] |
no_license
|
package br.com.grupocidade.b2click.ws.model.response;
import br.com.grupocidade.b2click.ws.model.request.ProdutoWS;
public class ProdutoResponse extends ResponseError {
ProdutoWS response[];
public ProdutoWS[] getResponse() {
return response;
}
public void setResponse(ProdutoWS[] response) {
this.response = response;
}
}
| true
|
7ce02e46b77568bacb2c5ef76fe772cb36eb79e6
|
Java
|
zhangdafeihhh/springmvc-shiro
|
/src/main/java/mapper/mdbcarmanage/DriverInfoInterCityMapper.java
|
UTF-8
| 416
| 1.664063
| 2
|
[] |
no_license
|
package mapper.mdbcarmanage;
import com.zhuanche.entity.mdbcarmanage.DriverInfoInterCity;
public interface DriverInfoInterCityMapper {
int insert(DriverInfoInterCity record);
int insertSelective(DriverInfoInterCity record);
DriverInfoInterCity selectByPrimaryKey(Integer id);
int updateByPrimaryKeySelective(DriverInfoInterCity record);
int updateByPrimaryKey(DriverInfoInterCity record);
}
| true
|
fad10354c064c296944dcd9aa3d8a9b250731acf
|
Java
|
STAMP-project/dspot-experiments
|
/benchmark/test/org/springframework/batch/sample/JobOperatorFunctionalTests.java
|
UTF-8
| 4,187
| 2.171875
| 2
|
[] |
no_license
|
/**
* Copyright 2008-2009 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 org.springframework.batch.sample;
import java.util.List;
import java.util.Set;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.junit.Assert;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.batch.core.Job;
import org.springframework.batch.core.JobParametersBuilder;
import org.springframework.batch.core.configuration.JobRegistry;
import org.springframework.batch.core.launch.JobOperator;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(locations = { "/simple-job-launcher-context.xml", "/jobs/infiniteLoopJob.xml" })
public class JobOperatorFunctionalTests {
private static final Log LOG = LogFactory.getLog(JobOperatorFunctionalTests.class);
@Autowired
private JobOperator operator;
@Autowired
private Job job;
@Autowired
private JobRegistry jobRegistry;
@Test
public void testStartStopResumeJob() throws Exception {
String params = new JobParametersBuilder().addLong("jobOperatorTestParam", 7L).toJobParameters().toString();
long executionId = operator.start(job.getName(), params);
Assert.assertEquals(params, operator.getParameters(executionId));
stopAndCheckStatus(executionId);
long resumedExecutionId = operator.restart(executionId);
Assert.assertEquals(params, operator.getParameters(resumedExecutionId));
stopAndCheckStatus(resumedExecutionId);
List<Long> instances = operator.getJobInstances(job.getName(), 0, 1);
Assert.assertEquals(1, instances.size());
long instanceId = instances.get(0);
List<Long> executions = operator.getExecutions(instanceId);
Assert.assertEquals(2, executions.size());
// latest execution is the first in the returned list
Assert.assertEquals(resumedExecutionId, executions.get(0).longValue());
Assert.assertEquals(executionId, executions.get(1).longValue());
}
@Test
public void testMultipleSimultaneousInstances() throws Exception {
String jobName = job.getName();
Set<String> names = operator.getJobNames();
Assert.assertEquals(1, names.size());
Assert.assertTrue(names.contains(jobName));
long exec1 = operator.startNextInstance(jobName);
long exec2 = operator.startNextInstance(jobName);
Assert.assertTrue((exec1 != exec2));
Assert.assertTrue((!(operator.getParameters(exec1).equals(operator.getParameters(exec2)))));
// Give the asynchronous task executor a chance to start executions
Thread.sleep(1000);
Set<Long> executions = operator.getRunningExecutions(jobName);
Assert.assertTrue(executions.contains(exec1));
Assert.assertTrue(executions.contains(exec2));
int count = 0;
boolean running = (operator.getSummary(exec1).contains("STARTED")) && (operator.getSummary(exec2).contains("STARTED"));
while (((count++) < 10) && (!running)) {
Thread.sleep(100L);
running = (operator.getSummary(exec1).contains("STARTED")) && (operator.getSummary(exec2).contains("STARTED"));
}
Assert.assertTrue(String.format("Jobs not started: [%s] and [%s]", operator.getSummary(exec1), operator.getSummary(exec1)), running);
operator.stop(exec1);
operator.stop(exec2);
}
}
| true
|
4effae9cfa91b98873159ec4a2b0c5a56a9d8e1c
|
Java
|
atiwari0802/data-structures-algorithms
|
/src/test/java/arrays/MaximumSubArraySumTest.java
|
UTF-8
| 794
| 2.703125
| 3
|
[] |
no_license
|
package arrays;
import org.junit.jupiter.api.Assertions;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import java.util.List;
import static arrays.MaximumSubArraySum.MaxSubArrayWindow;
public class MaximumSubArraySumTest {
private MaximumSubArraySum maximumSubArraySum;
@BeforeEach
public void setup() {
maximumSubArraySum = new MaximumSubArraySum();
}
@Test
public void testMaxSubArraySum() {
List<Integer> input = List.of(-2, 1, -3, 4, -1, 2, 1, -5, 4);
MaxSubArrayWindow window = maximumSubArraySum.findMaxSubArraySumWithIndices(input);
Assertions.assertEquals(6, window.maxSum);
Assertions.assertEquals(3, window.startIndex);
Assertions.assertEquals(6, window.endIndex);
}
}
| true
|
badb981cc63f71bcf92ea5d86ff695fbd6fa5da2
|
Java
|
iamnestra/epe2android
|
/app/src/main/java/app/crud/firebase/crudandroid/ListaClientes.java
|
UTF-8
| 3,383
| 2.15625
| 2
|
[] |
no_license
|
package app.crud.firebase.crudandroid;
import android.content.Intent;
import android.support.annotation.NonNull;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.ListView;
import com.google.firebase.FirebaseApp;
import com.google.firebase.database.DataSnapshot;
import com.google.firebase.database.DatabaseError;
import com.google.firebase.database.DatabaseReference;
import com.google.firebase.database.FirebaseDatabase;
import com.google.firebase.database.ValueEventListener;
import java.util.ArrayList;
import java.util.List;
import app.crud.firebase.crudandroid.Model.Cliente;
import app.crud.firebase.crudandroid.Model.Producto;
public class ListaClientes extends AppCompatActivity {
ListView lis_lista;
private List<Cliente> listcliente = new ArrayList<Cliente>();
ArrayAdapter<Cliente> arrayAdapterCliente;
FirebaseDatabase firebaseDatabase;
DatabaseReference databaseReference;
Cliente clienteSelected;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_lista_clientes);
lis_lista = (ListView) findViewById(R.id.lis_list);
inicializarFirebase();
listarDatos();
lis_lista.setOnItemClickListener(new AdapterView.OnItemClickListener() {
@Override
public void onItemClick(AdapterView<?> adapterView, View view, int i, long l) {
clienteSelected = (Cliente) adapterView.getItemAtPosition(i);
String id = clienteSelected.getId();
String nombre = clienteSelected.getNombre();
String apellido = clienteSelected.getApellido();
String correo = clienteSelected.getCorreo();
String edad = clienteSelected.getEdad();
Intent intent = new Intent(ListaClientes.this,modificaCliente.class);
intent.putExtra("id",id);
intent.putExtra("nombre",nombre);
intent.putExtra("Apellido",apellido);
intent.putExtra("Correo",correo);
intent.putExtra("Edad",edad);
startActivity(intent);
}
});
}
private void listarDatos() {
databaseReference.child("Cliente").addValueEventListener(new ValueEventListener() {
@Override
public void onDataChange(@NonNull DataSnapshot dataSnapshot) {
listcliente.clear();
for (DataSnapshot objSnapshot : dataSnapshot.getChildren()){
Cliente c = objSnapshot.getValue(Cliente.class);
listcliente.add(c);
arrayAdapterCliente = new ArrayAdapter<Cliente>(ListaClientes.this, android.R.layout.simple_list_item_1, listcliente);
lis_lista.setAdapter(arrayAdapterCliente);
}
}
@Override
public void onCancelled(@NonNull DatabaseError databaseError) {
}
});
}
private void inicializarFirebase() {
FirebaseApp.initializeApp(this);
firebaseDatabase = firebaseDatabase.getInstance();
databaseReference = firebaseDatabase.getReference();
}
}
| true
|
da3ace9f9a0935d11c7dfbd1f004fa79fd2baffb
|
Java
|
alebianITBA/SS
|
/src/off_lattice/InitialParams.java
|
UTF-8
| 223
| 1.703125
| 2
|
[] |
no_license
|
package off_lattice;
public class InitialParams {
final int N;
final int L;
final float ETA;
public InitialParams(int n, int l, float ETA) {
N = n;
L = l;
this.ETA = ETA;
}
}
| true
|
7c53d8b8597ca447e2d8319d95e72269883061f0
|
Java
|
Aamirio/registration-service
|
/src/main/java/com/aamir/api/registration/service/UserRegistrationService.java
|
UTF-8
| 456
| 1.929688
| 2
|
[] |
no_license
|
package com.aamir.api.registration.service;
import com.aamir.api.registration.dto.User;
import com.aamir.api.registration.repository.UserRepository;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
@Service
public class UserRegistrationService {
@Autowired
private UserRepository userRepository;
public void registerUser(User user) {
userRepository.save(user);
}
}
| true
|
5330996a3a4f83f70f675d65e7150e6feb09310f
|
Java
|
yojan95/MediApp-Backend
|
/src/main/java/com/alexis/service/impl/MedicoServiceImpl.java
|
UTF-8
| 524
| 1.835938
| 2
|
[] |
no_license
|
package com.alexis.service.impl;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.alexis.model.Medico;
import com.alexis.repo.IGenericRepo;
import com.alexis.repo.IMedicoRepo;
import com.alexis.service.IMedicoService;
@Service
public class MedicoServiceImpl extends CRUDImpl<Medico, Integer> implements IMedicoService{
@Autowired
private IMedicoRepo repo;
@Override
protected IGenericRepo<Medico, Integer> getRepo() {
return repo;
}
}
| true
|
d17a737a54bfe8e457b1c79a2ffbf4262465b3da
|
Java
|
Elvinh/Whiteboard
|
/src/DLineModel.java
|
UTF-8
| 166
| 2.046875
| 2
|
[] |
no_license
|
public class DLineModel extends DShapeModel {
public DLineModel(int x, int y, int w, int h) {
super(x, y, w, h);
}
public DLineModel()
{
super();
}
}
| true
|
033b6c830490e6ad3c0a1f68c15b993bd5e6f22d
|
Java
|
AgnieszkaAga/agnieszka_buczek-kodilla_tester
|
/kodilla-basic-tests/src/main/java/com/kodilla/abstracts/homework/shape/ShapeProcessor.java
|
UTF-8
| 292
| 3.140625
| 3
|
[] |
no_license
|
package com.kodilla.abstracts.homework.shape;
public class ShapeProcessor {
public void process(Shape shape) {
System.out.println("The area of this shape is: "+shape.calculateArea());
System.out.println("The circuit of this shape is: "+shape.calcutateCircuit());
}
}
| true
|
a4e5b6448876fda6eb0a369259ffdee47b21d00f
|
Java
|
kumarivenu123/springboot-projects
|
/SpringBootApacheCamelApp/src/main/java/com/spring/boot/router/CamelRouter.java
|
UTF-8
| 1,761
| 2.375
| 2
|
[] |
no_license
|
package com.spring.boot.router;
import java.util.StringJoiner;
import org.apache.camel.RoutingSlip;
import org.apache.camel.builder.RouteBuilder;
import org.springframework.stereotype.Component;
@Component
public class CamelRouter extends RouteBuilder {
@Override
public void configure() throws Exception {
from("direct:test").log("test service started...").to("bean:camelRouterService?method=testservice").end();
// static route
from("direct:teststatic").log("test static service started...").bean(CamelRouter.class, "staticRouter").end();
from("direct:mytest1").log("test service started...").to("bean:camelRouterService?method=testStaticService1")
.end();
from("direct:mytest2").log("test service started...").to("bean:camelRouterService?method=testStaticService2")
.end();
from("direct:mytest3").log("test service started...").to("bean:camelRouterService?method=testStaticService3")
.end();
// dynamic route
from("direct:testdynamic").log("test dynamic service started...")
.recipientList(method("camelRouterService", "testDynamicRouter")).parallelProcessing().end();
from("direct:venuroute").log("venu service started...").to("bean:camelRouterService?method=venuService").end();
from("direct:ramaroute").log("rama service started...").to("bean:camelRouterService?method=ramaService").end();
from("direct:defaultroute").log("default service started...")
.to("bean:camelRouterService?method=defaultService").end();
}
@RoutingSlip
public static String staticRouter() {
StringJoiner router = new StringJoiner(",");
router.add("direct:mytest1");
router.add("direct:mytest2");
router.add("direct:mytest3");
return router.toString();
}
}
| true
|
f84157a6788c41010c359db77cba70be8fe552e9
|
Java
|
deepakverma75/Planet-Food-App
|
/src/planetfood/dao/UserDao.java
|
UTF-8
| 1,531
| 2.328125
| 2
|
[] |
no_license
|
package planetfood.dao;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import planetfood.dbutil.DBConnection;
import planetfood.pojo.User;
import planetfood.pojo.registerCashier;
public class UserDao {
public static String validateUser(User user)throws SQLException
{
Connection conn=DBConnection.getConnection();
String qry;
qry = "Select username from Users where userid=? and password=? and usertype=?";
PreparedStatement ps=conn.prepareStatement(qry);
ps.setString(1,user.getUserId());
ps.setString(2,user.getPassword());
ps.setString(3, user.getUserType());
ResultSet rs=ps.executeQuery();
String username=null;
if(rs.next())
{
username=rs.getString(1);
}
return username;
}
public static boolean registerUser(registerCashier register)throws SQLException
{
Connection conn=DBConnection.getConnection();
PreparedStatement ps=conn.prepareStatement("insert into users values(?,?,?,?,?)");
ps.setString(1,register.getUserId());
ps.setString(2, register.getEmpId());
ps.setString(3,register.getUserName());
ps.setString(4,register.getPassword());
ps.setString(5, register.getUserType());
int x=ps.executeUpdate();
return (x>0);
}
}
| true
|
f00ea5781ed323377af8a3c03b9b51c866b82881
|
Java
|
ysy15350/Redpacket_fc
|
/app/src/main/java/com/ysy15350/redpacket_fc/image_select/ImgSelectActivity.java
|
UTF-8
| 5,294
| 2.0625
| 2
|
[] |
no_license
|
package com.ysy15350.redpacket_fc.image_select;
import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
import com.jph.takephoto.app.TakePhoto;
import com.jph.takephoto.app.TakePhotoActivity;
import com.jph.takephoto.compress.CompressConfig;
import com.jph.takephoto.model.CropOptions;
import com.jph.takephoto.model.LubanOptions;
import com.jph.takephoto.model.TImage;
import com.jph.takephoto.model.TResult;
import com.jph.takephoto.model.TakePhotoOptions;
import com.ysy15350.ysyutils.common.CommFunAndroid;
import java.io.File;
import java.util.ArrayList;
/**
* Created by yangshiyou on 2017/9/12.
*/
public class ImgSelectActivity extends TakePhotoActivity {
//https://github.com/darsh2/MultipleImageSelect
//https://github.com/crazycodeboy/TakePhoto#安装说明
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
initData();
}
@Override
protected void onResume() {
super.onResume();
}
private int type = 1, width = 300, height = 300;
public void initData() {
//Toast.makeText(this, CommFunAndroid.getSharedPreferences("type") + "", Toast.LENGTH_SHORT).show();
Intent intent = null;
try {
intent = getIntent();
if (intent != null) {
type = CommFunAndroid.toInt32(CommFunAndroid.getSharedPreferences("type"), 0);//1:选择相册;2:拍照
width = intent.getIntExtra("width", 300);
height = intent.getIntExtra("height", 300);
}
if (type != 0)
initTakePhoto();
} catch (Exception e) {
e.printStackTrace();
}
}
TakePhoto takePhoto;
private void initTakePhoto() {
takePhoto = getTakePhoto();
configCompress(takePhoto);
configTakePhotoOption(takePhoto);
File file = new File(CommFunAndroid.getDiskCachePath(), "/temp/" + System.currentTimeMillis() + ".jpg");
if (!file.getParentFile().exists())
file.getParentFile().mkdirs();
Uri imageUri = Uri.fromFile(file);
if (type == 1) {
takePhoto.onPickMultiple(8);
//takePhoto.onPickMultipleWithCrop(8, getCropOptions(width, height));
} else if (type == 2) {
takePhoto.onPickFromCaptureWithCrop(imageUri, getCropOptions(width, height));
} else {
// this.finish();
}
CommFunAndroid.setSharedPreferences("type", "0");
}
@Override
public void takeSuccess(TResult result) {
ArrayList<TImage> list = result.getImages();
Intent intent = getIntent();
intent.putExtra("images", list);
setResult(RESULT_OK, intent);
type = 0;
this.finish();
}
@Override
public void takeFail(TResult result, String msg) {
this.finish();
}
@Override
public void takeCancel() {
this.finish();
}
private CropOptions getCropOptions(int width, int height) {
boolean withWonCrop = true;//false;
CropOptions.Builder builder = new CropOptions.Builder();
builder.setAspectX(width).setAspectY(height);//尺寸
// if (rgCropSize.getCheckedRadioButtonId() == R.id.rbAspect) {
// builder.setAspectX(width).setAspectY(height);//尺寸
// } else {
// builder.setOutputX(width).setOutputY(height);//比例
// }
builder.setWithOwnCrop(withWonCrop);
return builder.create();
}
/**
* 配置是否压缩
*
* @param takePhoto
*/
private void configCompress(TakePhoto takePhoto) {
//takePhoto.onEnableCompress(null,false);//不压缩
int maxSize = 5 * 1024 * 1024;//b
int width = 720;
int height = 435;
boolean showProgressBar = true;//是否显示压缩进度条rgShowProgressBar.getCheckedRadioButtonId() == R.id.rbShowYes ? true : false;
boolean enableRawFile = true;//拍照压缩后是否保存原图rgRawFile.getCheckedRadioButtonId() == R.id.rbRawYes ? true : false;
CompressConfig config;
int compressType = 2;
if (compressType == 1) {//自带压缩工具
config = new CompressConfig.Builder()
.setMaxSize(maxSize)
.setMaxPixel(width >= height ? width : height)
.enableReserveRaw(enableRawFile)
.create();
} else {//Luban压缩
LubanOptions option = new LubanOptions.Builder()
.setMaxHeight(height)
.setMaxWidth(width)
.setMaxSize(maxSize)
.create();
config = CompressConfig.ofLuban(option);
config.enableReserveRaw(enableRawFile);
}
takePhoto.onEnableCompress(config, showProgressBar);
}
private void configTakePhotoOption(TakePhoto takePhoto) {
TakePhotoOptions.Builder builder = new TakePhotoOptions.Builder();
builder.setWithOwnGallery(true);//是否使用TakePhoto自带相册
builder.setCorrectImage(true);//是否纠正拍照的照片旋转角度
takePhoto.setTakePhotoOptions(builder.create());
}
}
| true
|
03132968b8abf5f919626acb96f0882482f4ed07
|
Java
|
japetusland/tutorials
|
/jee8-jsr375/src/main/java/com/giapy/giapy_auth/data_access/User.java
|
UTF-8
| 2,080
| 2.421875
| 2
|
[
"MIT"
] |
permissive
|
package com.giapy.giapy_auth.data_access;
import java.io.Serializable;
import java.util.Collection;
import javax.persistence.Entity;
import javax.persistence.Id;
import javax.persistence.JoinColumn;
import javax.persistence.JoinTable;
import javax.persistence.ManyToMany;
import javax.persistence.NamedQuery;
import javax.persistence.Table;
@Entity
@Table(name="USERS")
@NamedQuery(name="User.findAll", query="select u from User u")
@NamedQuery(name="User.findByEmail", query="select u from User u where u.email=:email")
@NamedQuery(
name="User.getByRole",
query="select distinct u from User u inner join u.roles role where role.name=:role"
)
public class User implements Serializable {
@Id
private String email;
private String password;
@ManyToMany
@JoinTable(name="USERS_ROLES",
joinColumns= @JoinColumn(name="User", referencedColumnName="email"),
inverseJoinColumns= @JoinColumn(name="Role", referencedColumnName="name"))
private Collection<Role> roles;
private static final long serialVersionUID = 1L;
public User() {
super();
}
public User(String email, String password) {
this.email = email;
this.password = password;
}
public String getEmail() {
return this.email;
}
public void setEmail(String email) {
this.email = email;
}
public String getPassword() {
return this.password;
}
public void setPassword(String password) {
this.password = password;
}
public Collection<Role> getRoles() {
return roles;
}
public void setRoles(Collection<Role> roles) {
this.roles = roles;
}
@Override
public int hashCode() {
final int prime = 31;
int result = 1;
result = prime * result + ((email == null) ? 0 : email.hashCode());
return result;
}
@Override
public boolean equals(Object obj) {
if (this == obj)
return true;
if (obj == null)
return false;
if (getClass() != obj.getClass())
return false;
User other = (User) obj;
if (email == null) {
if (other.email != null)
return false;
} else if (!email.equals(other.email))
return false;
return true;
}
}
| true
|
b8b1ab77df30be9962f25c67855c91ade9fc162b
|
Java
|
jingdian1997/graduation-design
|
/graduation-shop/src/main/java/com/jd/graduation/Impl/CartServiceImpl.java
|
UTF-8
| 1,691
| 2.1875
| 2
|
[] |
no_license
|
package com.jd.graduation.Impl;
import com.jd.graduation.DO.CartDO;
import com.jd.graduation.DTO.CartChangeAmountDTO;
import com.jd.graduation.VO.BookVO;
import com.jd.graduation.VO.CartVO;
import com.jd.graduation.service.CartService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import java.util.Date;
import java.util.List;
@Service("CartServiceImpl")
public class CartServiceImpl extends CartService {
@Autowired
private BookServiceImpl bookService;
public void addToCart(Integer uid, Integer bid) throws Exception {
BookVO bookVO = bookService.selectOne(bid);
if (bookVO == null){
throw new Exception("错误的图书");
}
CartDO cartDO = new CartDO();
cartDO.setUid(uid);
cartDO.setBid(bid);
cartDO.setAmount(1);
cartDO.setCreateTime(new Date());
save(cartDO);
}
public void delete(Integer id, Integer uid) throws Exception {
CartDO cartDO = baseMapper.selectById(id);
if (cartDO == null || !cartDO.getUid().equals(uid)){
throw new Exception("你只能操作你的购物车");
}
removeById(id);
}
public List<CartVO> getAll(Integer uid) {
return baseMapper.selectByUid(uid);
}
public void changeAmount(CartChangeAmountDTO dto, Integer uid) throws Exception {
CartDO cartDO = baseMapper.selectById(dto.getId());
if (cartDO == null || !cartDO.getUid().equals(uid)){
throw new Exception("你只能操作你的购物车");
}
cartDO.setAmount(dto.getAmount());
updateById(cartDO);
}
}
| true
|
fceb3a1787b0fdfcf042272cf1d31faec49c8d68
|
Java
|
Neverslave/myblog1
|
/src/main/java/com/henry/myblog/service/LogService.java
|
UTF-8
| 188
| 1.882813
| 2
|
[] |
no_license
|
package com.henry.myblog.service;
import com.henry.myblog.model.Log;
import java.util.List;
public interface LogService {
int insertLog(Log log);
List<Log> queryAllLogs();
}
| true
|
124aa82fd2e14297cd1734c86a8c328d7d4769d8
|
Java
|
dahobt123/charterandgo-models
|
/src/main/java/com/charterandgo/model/Offer.java
|
UTF-8
| 4,225
| 2.265625
| 2
|
[] |
no_license
|
package com.charterandgo.model;
import org.json.JSONArray;
import org.json.JSONObject;
import java.io.Serializable;
import java.util.ArrayList;
import java.util.List;
public class Offer implements Serializable {
private int offerId;
private int totalExpectedPassengers;
private String warningTyoe;
private String warningText;
private List<OfferItem> offerItems = new ArrayList<>();
private List<Price> pricing = new ArrayList<>();
private JSONObject pricingNotes;
private RunwayItem runway;
private List<Tax> taxes = new ArrayList<>();
private List<Aircraft> aircraft = new ArrayList<>();
private ShopLists lists;
private List<AirportInfo> airports = new ArrayList<>();
public Offer() {
}
public String toString() {
StringBuilder builder = new StringBuilder();
builder.append(offerId + "-");
for (OfferItem item : offerItems) {
builder.append(item.toString() + "/");
}
if (runway != null) {
builder.append(runway.toString());
}
return builder.toString();
}
public JSONObject toJson() {
JSONObject obj = new JSONObject();
obj.put("offerId", offerId);
JSONArray array = new JSONArray();
obj.put("offerItems", array);
for (OfferItem item : offerItems) {
array.put(item.toJson());
}
if (pricing != null) {
JSONArray priceArray = new JSONArray();
for (Price price : pricing) {
priceArray.put(price.toJson());
}
obj.put("pricing", priceArray);
}
if (pricingNotes != null) {
obj.put("pricingNotes", pricingNotes);
}
if (runway != null) {
obj.put("runway", runway.toJson());
}
JSONArray taxArray = new JSONArray();
for (Tax tax : taxes) {
taxArray.put(tax.toJson());
}
obj.put("taxes", taxArray);
JSONArray aircrafts = new JSONArray();
for (Aircraft ac : aircraft) {
aircrafts.put(ac.toJson());
}
obj.put("aircraft", aircrafts);
return obj;
}
public int getOfferId() {
return offerId;
}
public void setOfferId(int offerId) {
this.offerId = offerId;
}
public List<OfferItem> getOfferItems() {
return offerItems;
}
public void setOfferItems(List<OfferItem> offerItems) {
this.offerItems = offerItems;
}
public RunwayItem getRunway() {
return runway;
}
public void setRunway(RunwayItem runway) {
this.runway = runway;
}
public List<Price> getPricing() {
return pricing;
}
public void setPricing(List<Price> pricing) {
this.pricing = pricing;
}
public void setTaxes(List<Tax> taxList) {
this.taxes = taxList;
}
public List<Tax> getTaxes() {
return taxes;
}
public String getWarningTyoe() {
return warningTyoe;
}
public void setWarningTyoe(String warningTyoe) {
this.warningTyoe = warningTyoe;
}
public String getWarningText() {
return warningText;
}
public void setWarningText(String warningText) {
this.warningText = warningText;
}
public List<Aircraft> getAircraft() {
return aircraft;
}
public void setAircraft(List<Aircraft> aircraft) {
this.aircraft = aircraft;
}
public ShopLists getLists() {
return lists;
}
public void setLists(ShopLists lists) {
this.lists = lists;
}
public List<AirportInfo> getAirports() {
return airports;
}
public void setAirports(List<AirportInfo> airports) {
this.airports = airports;
}
public int getTotalExpectedPassengers() {
return totalExpectedPassengers;
}
public void setTotalExpectedPassengers(int totalExpectedPassengers) {
this.totalExpectedPassengers = totalExpectedPassengers;
}
public JSONObject getPricingNotes() {
return pricingNotes;
}
public void setPricingNotes(JSONObject pricingNotes) {
this.pricingNotes = pricingNotes;
}
}
| true
|
31c51e951010705b45c4a61789f6a8bebba63c97
|
Java
|
elhananIsrael/TakeAndGo
|
/app/src/main/java/com/example/yyblumerandeiheller/takeandgo/controller/LookingForBusyCarService.java
|
UTF-8
| 4,473
| 2.390625
| 2
|
[] |
no_license
|
package com.example.yyblumerandeiheller.takeandgo.controller;
import android.app.Service;
import android.content.Intent;
import android.os.IBinder;
import android.app.NotificationManager;
import android.content.Context;
import android.support.annotation.Nullable;
import android.util.Log;
import android.widget.Toast;
import com.example.yyblumerandeiheller.takeandgo.model.backend.FactoryMethod;
import com.example.yyblumerandeiheller.takeandgo.model.entities.Car;
import java.util.ArrayList;
import java.util.Timer;
import java.util.TimerTask;
public class LookingForBusyCarService extends Service {
ArrayList<Car> carAvailable=new ArrayList();
ArrayList<Car> tempCarAvailable=new ArrayList();
ArrayList<Car> lastCarAvailable=new ArrayList();
boolean isFirstTime=true;
int id = 0, startId = -1;
boolean isRun = false;
final String TAG = "testService";
private Timer timer = new Timer();
static final int UPDATE_INTERVAL = 1000 * 10;
public static final String PARAM_OUT_MSG = "OUT_MESSAGE";
public static final String ACTION_RESP =
"takego_clientside.yaakovblumer.example.com.intent.action.MESSAGE_PROCESSED";
String serviceInfo()
{
return "service [" + id + "] startId = " + startId;
}
@Override
public int onStartCommand(Intent intent, int flags, int startId) {
// Let it continue running until it is stopped.
Toast.makeText(this, "Service Started", Toast.LENGTH_LONG).show();
timer.scheduleAtFixedRate(new TimerTask() {
public void run() {
/////////////////////////////////////////
if(isFirstTime)
{
isFirstTime=false;
carAvailable= FactoryMethod.getDataSource(FactoryMethod.Type.MySQL).allCarAvailable();
for (Car newCar : carAvailable) {
Intent broadcastIntent = new Intent();
broadcastIntent.setAction(ACTION_RESP);
broadcastIntent.addCategory(Intent.CATEGORY_DEFAULT);
broadcastIntent.putExtra(PARAM_OUT_MSG, "car with licenseNumber: " + newCar.getLicenseNumber() + " available.");
sendBroadcast(broadcastIntent);
Log.d("Take&Go-Service", "car with licenseNumber: " + newCar.getLicenseNumber() + " available.");
}
}
else {
tempCarAvailable=FactoryMethod.getDataSource(FactoryMethod.Type.MySQL).allCarAvailable();
lastCarAvailable.addAll(tempCarAvailable);
for (Car tempCarItem : tempCarAvailable) {
for (Car carItem : carAvailable) {
if (tempCarItem.getLicenseNumber().equals(carItem.getLicenseNumber()))
lastCarAvailable.remove(tempCarItem);
}}
carAvailable.clear();
carAvailable.addAll(tempCarAvailable);
if(!lastCarAvailable.isEmpty())
{
for (Car newCar : lastCarAvailable) {
Intent broadcastIntent = new Intent();
broadcastIntent.setAction(ACTION_RESP);
broadcastIntent.addCategory(Intent.CATEGORY_DEFAULT);
broadcastIntent.putExtra(PARAM_OUT_MSG, "new car with licenseNumber: " + newCar.getLicenseNumber() + " available.");
sendBroadcast(broadcastIntent);
Log.d("Take&Go-Service", "new car with licenseNumber: " + newCar.getLicenseNumber() + " available.");
}
}
}
}
}, 1, UPDATE_INTERVAL);
return START_STICKY;
}
@Override
public void onDestroy() {
super.onDestroy();
timer.cancel();
//
Object obj = getSystemService(Context.NOTIFICATION_SERVICE);
NotificationManager notificationManager = (NotificationManager)obj;
notificationManager.cancel(1234);
//
Log.d(TAG, serviceInfo() + " onDestroy ...");
isRun = false;
Toast.makeText(this, "Service Destroyed", Toast.LENGTH_LONG).show();
}
@Nullable
@Override
public IBinder onBind(Intent intent) {
return null;
}
}
| true
|
14154d98258dd5b9f5a5b7f47ebbab2d73061e36
|
Java
|
Wonjyeon/Android-Studio
|
/MyPicker/app/src/main/java/org/techtown/picker/OnDateTimeChangeListener.java
|
UTF-8
| 285
| 2.265625
| 2
|
[] |
no_license
|
package org.techtown.picker;
public interface OnDateTimeChangeListener {
// DatePicker -> 년,월,일 TimePicker -> 시, 분 => 합쳐서 받겠다!
public void OnDateTimeChange(DateTimePicker view,int year, int monthOfYear, int dayOfMonth, int hour, int minute);
}
| true
|
7d8c96abac3ece2c0ebca90eddaa647e243b9bea
|
Java
|
jguardado39/CS111B
|
/Assignments/Week13/conway/BlinkerCell.java
|
UTF-8
| 836
| 3.3125
| 3
|
[] |
no_license
|
package Assignments.Week13.conway;
public class BlinkerCell extends AbstractCell {
public BlinkerCell (int r, int c, ConwayWorld w) {
super(r, c, w);
}
public AbstractCell cellForNextGeneration() {
BlinkerCell next = new BlinkerCell(getRow(), getColumn(),world);
next.setIsAlive(willBeAliveInNextGeneration());
return next;
}
public boolean willBeAliveInNextGeneration() {
boolean aliveNextGen;
if(getIsAlive()) {
aliveNextGen = false;
} else {
aliveNextGen = true;
}
return aliveNextGen;
}
public char displayCharacter() {
char nextGenChar;
if(getIsAlive()) {
nextGenChar = '+';
} else {
nextGenChar = 'X';
}
return nextGenChar;
}
}
| true
|
eea60395244e9c3d4d4a559cb3dee4bc9108e705
|
Java
|
calimaborges/design-patterns
|
/command-pattern/src/main/java/br/com/borgescal/designpatterns/command/implementations/receivers/GarageDoor.java
|
UTF-8
| 546
| 3.015625
| 3
|
[] |
no_license
|
package br.com.borgescal.designpatterns.command.implementations.receivers;
public class GarageDoor {
String place;
public GarageDoor(String place) {
this.place = place;
}
public void up() {
System.out.println("Garage door up!");
}
public void down() {
System.out.println("Garage door down!");
}
public void stop() {
System.out.println("Garage door stopped!");
}
public void lightOn() {
System.out.println("Garage door light on!");
}
public void lightOff() {
System.out.println("Garage door light off!");
}
}
| true
|
d6daafeb28123b4c69893ee9dc4d6cbb7f3cdfaf
|
Java
|
Khramer/Patterns
|
/src/Patterns/Structural/Composite/CannedFood.java
|
UTF-8
| 182
| 2.96875
| 3
|
[] |
no_license
|
package Patterns.Structural.Composite;
public class CannedFood implements Item{
@Override
public void use() {
System.out.println("Это консерва");
}
}
| true
|
0e14f80962d3113d675973eed3f544cc2ab324eb
|
Java
|
Hague/FlenixRoads
|
/co/uk/silvania/roads/block/KerbBlock.java
|
UTF-8
| 2,237
| 2.1875
| 2
|
[] |
no_license
|
package co.uk.silvania.roads.block;
import co.uk.silvania.roads.Roads;
import net.minecraft.block.Block;
import net.minecraft.block.material.Material;
import net.minecraft.client.renderer.texture.IconRegister;
import net.minecraft.entity.EntityLivingBase;
import net.minecraft.item.ItemStack;
import net.minecraft.util.AxisAlignedBB;
import net.minecraft.util.MathHelper;
import net.minecraft.world.IBlockAccess;
import net.minecraft.world.World;
public class KerbBlock extends Block {
public KerbBlock(int id) {
super(id, Material.rock);
this.setCreativeTab(Roads.tabRoads);
this.setHardness(1.2F);
}
public void onBlockPlacedBy(World par1World, int par2, int par3, int par4, EntityLivingBase par5EntityLivingBase, ItemStack par6ItemStack)
{
int l = MathHelper.floor_double((double)(par5EntityLivingBase.rotationYaw * 4.0F / 360.0F) + 2.5D) & 3;
par1World.setBlockMetadataWithNotify(par2, par3, par4, l, 2);
}
public boolean renderAsNormalBlock() {
return false;
}
public boolean isOpaqueCube() {
return false;
}
public AxisAlignedBB getCollisionBoundingBoxFromPool(World par1World, int par2, int par3, int par4)
{
this.setBlockBoundsBasedOnState(par1World, par2, par3, par4);
return super.getCollisionBoundingBoxFromPool(par1World, par2, par3, par4);
}
public void setBlockBoundsBasedOnState(IBlockAccess par1IBlockAccess, int par2, int par3, int par4)
{
int l = par1IBlockAccess.getBlockMetadata(par2, par3, par4) & 7;
switch (l)
{
case 0:
default:
this.setBlockBounds(0.0F, -0.25F, 0.15F, 1.0F, -0.125F, 0.4F);
break;
case 1:
this.setBlockBounds(0.6F, -0.25F, 0.0F, 0.85F, -0.125F, 1.0F);
break;
case 2:
this.setBlockBounds(0.0F, -0.25F, 0.6F, 1.0F, -0.125F, 0.85F);
break;
case 3:
this.setBlockBounds(0.15F, -0.25F, 0.0F, 0.4F, -0.125F, 1.0F);
}
}
public void registerIcons(IconRegister iconRegister) {
blockIcon = iconRegister.registerIcon(Roads.modid + ":sidewalkBlockLight0");
}
}
| true
|
28e41e5e33973b2f81358e70c0dc300538f12c5b
|
Java
|
xrealm/tiktok-src
|
/sources/com/p280ss/android/ugc/effectmanager/common/p1730e/C43729a.java
|
UTF-8
| 451
| 1.859375
| 2
|
[] |
no_license
|
package com.p280ss.android.ugc.effectmanager.common.p1730e;
import java.io.Closeable;
import java.io.IOException;
/* renamed from: com.ss.android.ugc.effectmanager.common.e.a */
public final class C43729a {
/* renamed from: a */
public static void m138574a(Closeable closeable) {
if (closeable != null) {
try {
closeable.close();
} catch (IOException unused) {
}
}
}
}
| true
|
98e36647585fbd64cc74f40d5d8a5b42224943d1
|
Java
|
Liranai/Omega-ISG
|
/src/main/java/logic/ai/AlphaBetaMiniMax.java
|
UTF-8
| 15,202
| 3.078125
| 3
|
[] |
no_license
|
package logic.ai;
import java.util.concurrent.Callable;
import logic.OmegaLogic;
import model.Board;
import model.Move;
import model.Node;
public class AlphaBetaMiniMax extends ArtificialIntelligence implements Callable<Move> {
private int nodes_explored;
private static double MAX_DEPTH = 0.2;
public AlphaBetaMiniMax(int number) {
super(number);
nodes_explored = 0;
}
@Override
public String getName() {
return "AlphaBetaMiniMax";
}
@Override
public Move getMove(Board board) {
long intime = System.currentTimeMillis();
System.out.println("Getting ABMM move");
Node root = new Node(board.clone(), null, null);
Node best = alphaBeta(root, 0, Integer.MAX_VALUE, Integer.MIN_VALUE, true);
while(!best.getParent().equals(root)) {
best = best.getParent();
}
MAX_DEPTH += 0.15;
System.out.println("Time taken: " + (System.currentTimeMillis() - intime) + "ms");
return best.getMove();
}
@Override
public Move call() throws Exception {
return null;
}
public Node alphaBeta(Node node, int depth, int alpha, int beta, boolean min_max) {
// if (node.isTerminal()) {
// if(min_max)
// return -1;
// return 1;
// }
node.calculateValue(min_max ? super.playerNumber : super.playerNumber+1);
if (depth >= MAX_DEPTH) {
return node;
} else {
Node maxNode = null;
long time = System.currentTimeMillis();
for (Move move : OmegaLogic.getLegalMoves(node.getBoard())) {
Node newNode = alphaBeta(new Node(node.getBoard().clone(), move, node), depth + 1, alpha, beta, !min_max);
if (maxNode == null || newNode.getValue() > maxNode.getValue()) {
maxNode = newNode;
}
}
System.out.println("DEPTH: " + depth + " took " + (System.currentTimeMillis() - time) + "ms");
return maxNode;
}
// function alphabeta(node, depth, α, β, maximizingPlayer) is
// if depth = 0 or node is a terminal node then
// return the heuristic value of node
// if maximizingPlayer then
// value := −∞
// for each child of node do
// value := max(value, alphabeta(child, depth − 1, α, β, FALSE))
// α := max(α, value)
// if α ≥ β then
// break (* β cut-off *)
// return value
// else
// value := +∞
// for each child of node do
// value := min(value, alphabeta(child, depth − 1, α, β, TRUE))
// β := min(β, value)
// if α ≥ β then
// break (* α cut-off *)
// return value
}
}
// public Integer alphaBeta(Node2 node, int depth, int alpha, int beta, boolean min_max) {
// nodes_explored++;
// // TODO: Optional, output
//
// if (node.isTerminal()) {
// if (min_max)
// return -1;
// return 1;
// } else {
// if (previousNodes.containsKey(depth)) {
// for (Plane2 plane : node.getState().getPlanes().values()) {
// plane.setClusters(Cluster2.clusterPlane(plane, node.getState()));
// }
// for (Node2 previous : previousNodes.get(depth)) {
// if (previous.getState().isEqualTo(node.getState()))
// return (min_max ? Integer.MAX_VALUE : Integer.MIN_VALUE);
// }
// } else {
// previousNodes.put(depth, new ArrayList<Node2>());
// }
//
// previousNodes.get(depth).add(node);
//
// if (min_max) {
// int value = Integer.MIN_VALUE;
// Node2 child = null;
//
// searchloop: for (Plane2 plane : node.getState().getPlanes().values()) {
// plane.setClusters(Cluster2.clusterPlane(plane, node.getState()));
// for (Cluster2 cluster : plane.getClusters()) {
// cluster.analyseCluster(plane, node.getState());
// cluster.setClusterComplexForm(cluster.searchCluster(plane, node.getState()));
// }
// ArrayList<String> clusterTypes = plane.getClusterTypes();
// for (int i = 0; i < clusterTypes.size(); i++) {
//
// Cluster2 c1 = plane.getClustersOfString(clusterTypes.get(i)).get(0);
// for (int j = i; j < clusterTypes.size(); j++) {
// Cluster2 c2 = null;
// if (clusterTypes.get(i).equals(clusterTypes.get(j))) {
// ArrayList<Cluster2> secundairClusters = plane
// .getClustersOfStringExcluding(clusterTypes.get(j), c1);
// if (!secundairClusters.isEmpty()) {
// c2 = secundairClusters.get(0);
// }
// } else {
// ArrayList<Cluster2> secundairClusters = plane.getClustersOfString(clusterTypes.get(j));
// if (!secundairClusters.isEmpty()) {
// c2 = secundairClusters.get(0);
// }
// }
// if (c2 != null) {
// for (Vertex2 v1 : c1.getVertices().values()) {
// if (v1.getDegree() > 2)
// continue;
// for (Vertex2 v2 : c2.getVertices().values()) {
// if (v2.getDegree() > 2)
// continue;
// State2 childState = SproutsGameSolver2.modifyStateInPlane(node.getState(),
// plane.getUniqueID(), v1.getUniqueID(), v2.getUniqueID());
// child = new Node2(childState, node);
// value = Math.max(value, alphaBeta(child, depth + 1, alpha, beta, !min_max));
// alpha = Math.max(alpha, value);
// if (beta <= alpha)
// break searchloop;
// else
// node.addChild(child);
// }
// }
// }
// }
//
// c1 = plane.getClustersOfString(clusterTypes.get(i)).get(0);
// for (Vertex2 v1 : c1.getVertices().values()) {
// if (v1.getDegree() > 1) {
// continue;
// }
// ArrayList<Cluster2> clusters = new ArrayList<Cluster2>();
// for (Cluster2 c : plane.getClusters()) {
// if (c.equals(c1))
// continue;
// clusters.add(c);
// }
// if (clusters.isEmpty()) {
// State2 childState = SproutsGameSolver2.nooseModification(node.getState(),
// plane.getUniqueID(), v1.getUniqueID(), null);
// child = new Node2(childState, node);
// value = Math.max(value, alphaBeta(child, depth + 1, alpha, beta, !min_max));
// alpha = Math.max(alpha, value);
// if (beta <= alpha)
// break searchloop;
// else
// node.addChild(child);
// }
// for (int n = 0; n < clusters.size() * 2; n++) {
// String binary = Integer.toBinaryString(n);
// ArrayList<Cluster2> clusterSublist = new ArrayList<Cluster2>();
// for (int j = 0; j < binary.length(); j++) {
// if (binary.charAt(j) == '1')
// clusterSublist.add(clusters.get(j));
// }
// State2 childState = SproutsGameSolver2.nooseModification(node.getState(),
// plane.getUniqueID(), v1.getUniqueID(), clusterSublist);
// child = new Node2(childState, node);
// value = Math.max(value, alphaBeta(child, depth + 1, alpha, beta, !min_max));
// alpha = Math.max(alpha, value);
// if (beta <= alpha)
// break searchloop;
// else
// node.addChild(child);
// }
// }
//
// c1 = plane.getClustersOfString(clusterTypes.get(i)).get(0);
// for (Vertex2 v1 : c1.getVertices().values()) {
// if (v1.getDegree() > 2) {
// continue;
// }
// ArrayList<Cluster2> clusters = new ArrayList<Cluster2>();
// for (Cluster2 c : plane.getClusters()) {
// if (c.equals(c1))
// continue;
// clusters.add(c);
// }
// ArrayList<Vertex2> candidateVertices = new ArrayList<Vertex2>();
// for (Vertex2 v : c1.getVertices().values()) {
// if (v.equals(v1))
// continue;
// if (v.getDegree() > 2)
// continue;
// if (v.getUniqueID() <= v1.getUniqueID())
// continue;
// candidateVertices.add(v);
// }
// if (clusters.isEmpty()) {
// for (Vertex2 v2 : candidateVertices) {
// State2 childState = SproutsGameSolver2.loopModification(node.getState(),
// plane.getUniqueID(), v1.getUniqueID(), v2.getUniqueID(), null,
// c1.getVertices());
// child = new Node2(childState, node);
// value = Math.max(value, alphaBeta(child, depth + 1, alpha, beta, !min_max));
// alpha = Math.max(alpha, value);
// if (beta <= alpha)
// break searchloop;
// else
// node.addChild(child);
// }
// }
// for (int n = 0; n < clusters.size() * 2; n++) {
// String binary = Integer.toBinaryString(n);
// ArrayList<Cluster2> clusterSublist = new ArrayList<Cluster2>();
// for (int j = 0; j < binary.length(); j++) {
// if (binary.charAt(j) == '1')
// clusterSublist.add(clusters.get(j));
// }
// for (Vertex2 v2 : candidateVertices) {
// State2 childState = SproutsGameSolver2.loopModification(node.getState(),
// plane.getUniqueID(), v1.getUniqueID(), v2.getUniqueID(), clusterSublist,
// c1.getVertices());
// child = new Node2(childState, node);
// value = Math.max(value, alphaBeta(child, depth + 1, alpha, beta, !min_max));
// alpha = Math.max(alpha, value);
// if (beta <= alpha)
// break searchloop;
// else
// node.addChild(child);
// }
// }
// }
// }
// }
// return value;
// } else {
// int value = Integer.MAX_VALUE;
// Node2 child = null;
//
// searchloop: for (Plane2 plane : node.getState().getPlanes().values()) {
// plane.setClusters(Cluster2.clusterPlane(plane, node.getState()));
// for (Cluster2 cluster : plane.getClusters()) {
// cluster.analyseCluster(plane, node.getState());
// cluster.setClusterComplexForm(cluster.searchCluster(plane, node.getState()));
// }
// ArrayList<String> clusterTypes = plane.getClusterTypes();
// for (int i = 0; i < clusterTypes.size(); i++) {
//
// Cluster2 c1 = plane.getClustersOfString(clusterTypes.get(i)).get(0);
// for (int j = i; j < clusterTypes.size(); j++) {
// Cluster2 c2 = null;
// if (clusterTypes.get(i).equals(clusterTypes.get(j))) {
// ArrayList<Cluster2> secundairClusters = plane
// .getClustersOfStringExcluding(clusterTypes.get(j), c1);
// if (!secundairClusters.isEmpty()) {
// c2 = secundairClusters.get(0);
// }
// } else {
// ArrayList<Cluster2> secundairClusters = plane.getClustersOfString(clusterTypes.get(j));
// if (!secundairClusters.isEmpty()) {
// c2 = secundairClusters.get(0);
// }
// }
// if (c2 != null) {
// for (Vertex2 v1 : c1.getVertices().values()) {
// if (v1.getDegree() > 2)
// continue;
// for (Vertex2 v2 : c2.getVertices().values()) {
// if (v2.getDegree() > 2)
// continue;
// State2 childState = SproutsGameSolver2.modifyStateInPlane(node.getState(),
// plane.getUniqueID(), v1.getUniqueID(), v2.getUniqueID());
// child = new Node2(childState, node);
// value = Math.min(value, alphaBeta(child, depth + 1, alpha, beta, !min_max));
// beta = Math.min(beta, value);
// if (beta <= alpha)
// break searchloop;
// else
// node.addChild(child);
// }
// }
// }
// }
//
// c1 = plane.getClustersOfString(clusterTypes.get(i)).get(0);
// for (Vertex2 v1 : c1.getVertices().values()) {
// if (v1.getDegree() > 1) {
// continue;
// }
// ArrayList<Cluster2> clusters = new ArrayList<Cluster2>();
// for (Cluster2 c : plane.getClusters()) {
// if (c.equals(c1))
// continue;
// clusters.add(c);
// }
// if (clusters.isEmpty()) {
// State2 childState = SproutsGameSolver2.nooseModification(node.getState(),
// plane.getUniqueID(), v1.getUniqueID(), null);
// child = new Node2(childState, node);
// value = Math.min(value, alphaBeta(child, depth + 1, alpha, beta, !min_max));
// beta = Math.min(beta, value);
// if (beta <= alpha)
// break searchloop;
// else
// node.addChild(child);
// }
// for (int n = 0; n < clusters.size() * 2; n++) {
// String binary = Integer.toBinaryString(n);
// ArrayList<Cluster2> clusterSublist = new ArrayList<Cluster2>();
// for (int j = 0; j < binary.length(); j++) {
// if (binary.charAt(j) == '1')
// clusterSublist.add(clusters.get(j));
// }
// State2 childState = SproutsGameSolver2.nooseModification(node.getState(),
// plane.getUniqueID(), v1.getUniqueID(), clusterSublist);
// child = new Node2(childState, node);
// value = Math.min(value, alphaBeta(child, depth + 1, alpha, beta, !min_max));
// beta = Math.min(beta, value);
// if (beta <= alpha)
// break searchloop;
// else
// node.addChild(child);
// }
// }
//
// c1 = plane.getClustersOfString(clusterTypes.get(i)).get(0);
// for (Vertex2 v1 : c1.getVertices().values()) {
// if (v1.getDegree() > 2) {
// continue;
// }
// ArrayList<Cluster2> clusters = new ArrayList<Cluster2>();
// for (Cluster2 c : plane.getClusters()) {
// if (c.equals(c1))
// continue;
// clusters.add(c);
// }
// ArrayList<Vertex2> candidateVertices = new ArrayList<Vertex2>();
// for (Vertex2 v : c1.getVertices().values()) {
// if (v.equals(v1))
// continue;
// if (v.getDegree() > 2)
// continue;
// if (v.getUniqueID() <= v1.getUniqueID())
// continue;
// candidateVertices.add(v);
// }
// if (clusters.isEmpty()) {
// for (Vertex2 v2 : candidateVertices) {
// State2 childState = SproutsGameSolver2.loopModification(node.getState(),
// plane.getUniqueID(), v1.getUniqueID(), v2.getUniqueID(), null,
// c1.getVertices());
// child = new Node2(childState, node);
// value = Math.min(value, alphaBeta(child, depth + 1, alpha, beta, !min_max));
// beta = Math.min(beta, value);
// if (beta <= alpha)
// break searchloop;
// else
// node.addChild(child);
// }
// }
// for (int n = 0; n < clusters.size() * 2; n++) {
// String binary = Integer.toBinaryString(n);
// ArrayList<Cluster2> clusterSublist = new ArrayList<Cluster2>();
// for (int j = 0; j < binary.length(); j++) {
// if (binary.charAt(j) == '1')
// clusterSublist.add(clusters.get(j));
// }
// for (Vertex2 v2 : candidateVertices) {
// State2 childState = SproutsGameSolver2.loopModification(node.getState(),
// plane.getUniqueID(), v1.getUniqueID(), v2.getUniqueID(), clusterSublist,
// c1.getVertices());
// child = new Node2(childState, node);
// value = Math.min(value, alphaBeta(child, depth + 1, alpha, beta, !min_max));
// beta = Math.min(beta, value);
// if (beta <= alpha)
// break searchloop;
// else
// node.addChild(child);
// }
// }
// }
// }
// }
// return value;
// }
// }
// }
//}
| true
|