text
stringlengths 14
410k
| label
int32 0
9
|
---|---|
public static void saveWindowOpt() {
synchronized (window_props) {
try {
window_props.store(new FileOutputStream("windows.conf"),
"Window config options");
} catch (IOException e) {
System.out.println(e);
}
}
} | 1 |
protected void search(String fileName){
File file = new java.io.File(fileName + ".html.txt");
File fileHistory = new java.io.File(fileName + ".history.txt");
FileWriter fw = null;
FileWriter fwHistory = null;
try {
fw = new FileWriter(file);
fwHistory = new FileWriter(fileHistory);
fw.write("Start: " + Calendar.getInstance().getTime() + "\r\n");
fwHistory.write("Stop: " + Calendar.getInstance().getTime() + "\r\n");
} catch (IOException e1) {
log.error("Write file error: " + e1.getMessage());
}
lastTime = Calendar.getInstance().getTimeInMillis();
while(!cobweb.getUnsearchQueue().isEmpty()){
final WebPage srb = cobweb.peekUnsearchQueue();// 查找列隊
try {
if (!cobweb.isSearched(srb.getUrl())) {
// 儲存 html code
// 儲存歷史紀錄
fwHistory.write(srb.getUrl() + "\r\n");
// 抓出此頁面內的超連結
if(srb.getDepth() <= getMaxSpyDepth()){
WebPage tmpSrb = processHtml(srb.getUrl(), srb.getDepth());
fw.write("<page_html_code url=\"" + srb.getUrl()+"\" level=\""+srb.getDepth() + "\">");
fw.write(tmpSrb.getHtmlCode());
// fw.write(engine.Parser.toPureHtml(srb));
fw.write("</page_html_code>\r\n");
tmpSrb = null;
}
// Thread.sleep(30000);
count++;
if(count % 50 == 0){
System.gc();
}
if (count % 100 == 0) {
fwHistory.write("Unsearch web links count: " + this.cobweb.getUnsearchList().size() + "\r\n");
fwHistory.write("Searched web links count: " + this.cobweb.getSearchedSites().size() + "\r\n");
long crossTime = Calendar.getInstance().getTimeInMillis() - lastTime;
fwHistory.write("100 fetch page waste time: " + crossTime + "毫秒("+ getRightNowTimeStr("-", ":", "_") + ")\r\n");
lastTime = Calendar.getInstance().getTimeInMillis();
System.gc();
}
if (count % 1000 == 0) {
count = 0;
fw.close();
fw = null;
file = null;
file = new java.io.File(createFileName() + ".html.txt");
fw = new FileWriter(file);
}
}
} catch (Exception ex) {
}
}
// Jobs finished, close files.
try {
fw.write("結束時間: " + Calendar.getInstance().getTime() + "\r\n");
fwHistory.write("結束時間: " + Calendar.getInstance().getTime() + "\r\n");
fw.close();
fwHistory.close();
} catch (IOException e) {
log.error("Jobs finished, close files failed: " + e.getMessage());
}
} | 9 |
public static void changeLendability(BookCopy bc, boolean lendable) {
try {
if(conn == null || conn.isClosed()){
conn = DatabaseConnection.getConnection();
}
} catch (SQLException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
try{
conn.setAutoCommit(false);
PreparedStatement stmnt = conn.prepareStatement("UPDATE BookCopies set lendable = ? WHERE copy_id = ?");
stmnt.setBoolean(1, lendable);
stmnt.setInt(2, bc.getCopyId());
stmnt.execute();
conn.commit();
conn.setAutoCommit(true);
}catch(SQLException e){
System.out.println("update fail!! - " + e);
}
} | 4 |
public boolean canFeed(CommandSender sender) {
if ( sender instanceof Player ) {
return this.hasPermission((Player)sender, "SheepFeed.feed");
}
return false; // can not feed from console
} | 1 |
@Override
public void actionPerformed(ActionEvent e) {
// TODO Auto-generated method stub
if(e.getSource() == comButton) {
String name = comTextField.getText();
InfoDownload infodownload = new InfoDownload();
if(infodownload.init(name)) {
infodownload.getinfo();
cc.add(new User(name));
loadChart();
}
else {
JOptionPane.showMessageDialog(null, "该用户不存在");
}
comTextField.setText("");
}
if(e.getSource() == comComboBox) {
loadChart();
}
} | 3 |
public static void main(String args[]) {
/* Set the Nimbus look and feel */
//<editor-fold defaultstate="collapsed" desc=" Look and feel setting code (optional) ">
/* If Nimbus (introduced in Java SE 6) is not available, stay with the default look and feel.
* For details see http://download.oracle.com/javase/tutorial/uiswing/lookandfeel/plaf.html
*/
try {
for (javax.swing.UIManager.LookAndFeelInfo info : javax.swing.UIManager.getInstalledLookAndFeels()) {
if ("Nimbus".equals(info.getName())) {
javax.swing.UIManager.setLookAndFeel(info.getClassName());
break;
}
}
} catch (ClassNotFoundException ex) {
java.util.logging.Logger.getLogger(Registration.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (InstantiationException ex) {
java.util.logging.Logger.getLogger(Registration.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (IllegalAccessException ex) {
java.util.logging.Logger.getLogger(Registration.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (javax.swing.UnsupportedLookAndFeelException ex) {
java.util.logging.Logger.getLogger(Registration.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
}
//</editor-fold>
/* Create and display the dialog */
java.awt.EventQueue.invokeLater(new Runnable() {
public void run() {
Registration dialog = new Registration(new javax.swing.JFrame(), true);
dialog.addWindowListener(new java.awt.event.WindowAdapter() {
@Override
public void windowClosing(java.awt.event.WindowEvent e) {
System.exit(0);
}
});
dialog.setVisible(true);
}
});
} | 6 |
public void criarAtividade(Atividade atividade) throws SQLException, atividadeExistente {
AtividadeDAO atividadeDAO = new AtividadeDAO();
Atividade atividadeExistente = null;
atividadeExistente = atividadeDAO.SelectATividadePorNome(atividade.getNome());
if (atividadeExistente == null) {
atividadeDAO.criarAtividade(atividade);
} else {
throw new atividadeExistente();
}
} | 1 |
@Override
public void onBlockBreak(BlockBreakEvent event) {
Block block = event.getBlock();
Player player = event.getPlayer();
if ((block.getTypeId() == 63) || (block.getTypeId() == 68)) {
Sign thisSign = (Sign) block.getState();
if (thisSign.getLine(0).equals("[WebAuction]")) {
if (!plugin.permission.has(player, "wa.remove")) {
event.setCancelled(true);
player.sendMessage(plugin.logPrefix + "You do not have permission to remove that");
} else {
player.sendMessage(plugin.logPrefix + "WebAuction sign removed.");
}
}
}
} | 4 |
public boolean isConnected() {
if (this.size() < 2) {
return true;
}
final Iterator<T> iterator = this.iterator();
final T source = iterator.next();
Deque<T> queue = new LinkedList<>();
Set<T> visited = new HashSet<T>();
queue.addLast(source);
visited.add(source);
while (queue.isEmpty() == false) {
final T current = queue.removeFirst();
for (final T child : current) {
if (visited.contains(child) == false) {
visited.add(child);
queue.addLast(child);
}
}
}
if (visited.size() != this.size()) {
return false;
}
for (final T node : visited) {
if (this.containsNode(node) == false) {
return false;
}
}
for (final T node : this) {
if (visited.contains(node) == false) {
return false;
}
}
return true;
} | 9 |
public TagExtracter(List<Line> tagLines) {
StringBuilder sb = new StringBuilder();
TagClosureCreator.TagClosure itemsHolder = new TagClosureCreator().getHolder();
TagClosureCreator.TagClosure deleteHolder = new TagClosureCreator().getHolder();
for (Line line : tagLines) {
sb.append(line.toString());
if (line.isRootTagStartLine()) {
rootTag.setStartLineNumber(line.getLineNumber());
} else if (line.isRootTagEndLine()) {
rootTag.setEndLineNumber(line.getLineNumber());
} else if (line.isItemsTagStartLine()) {
itemsHolder.getValue().setStartLineNumber(line.getLineNumber());
} else if (line.isItemsTagEndLine()) {
itemsHolder.getValue().setEndLineNumber(line.getLineNumber());
itemsTags.add(itemsHolder.getValue().clone());
itemsHolder.clear();
} else if (line.isDeleteTagStartLine()) {
deleteHolder.getValue().setStartLineNumber(line.getLineNumber());
} else if (line.isDeleteTagEndLine()) {
deleteHolder.getValue().setEndLineNumber(line.getLineNumber());
deleteTags.add(deleteHolder.getValue().clone());
deleteHolder.clear();
}
}
SAXParserFactory factory = SAXParserFactory.newInstance();
try {
SAXParser parser = factory.newSAXParser();
InputStream is = new ByteArrayInputStream(sb.toString().getBytes());
TagHandler tagHandler = new TagHandler();
parser.parse(is, tagHandler);
Tag generatorTag = tagHandler.getRootTag();
this.rootTag.setBinds(generatorTag.getBinds());
this.rootTag.setReplaces(generatorTag.getReplaces());
List<Tag> itemsTags = tagHandler.getItemsTag();
for (int i = 0; i < itemsTags.size(); i++) {
this.itemsTags.get(i).setBinds(itemsTags.get(i).getBinds());
this.itemsTags.get(i).setReplaces((itemsTags.get(i).getReplaces()));
}
} catch (ParserConfigurationException | SAXException | IOException e) {
throw Throwables.propagate(new SystemException(e));
}
} | 9 |
static long getOffsetOfChunk(int []vsize, int[] csize, int []start)
{
int [] volume = new int [vsize.length];
int []dsize = new int [vsize.length +1];
dsize[vsize.length]=1;
volume[0]=1;
for(int i = 1; i < volume.length; i++)
{
volume[i] = volume[i-1]*vsize[i-1];
}
for(int i = vsize.length -1 ; i >= 0; i--)
{
dsize[i] = dsize[i+1] *( (vsize[i] - start[i]) > csize[i]? csize[i]:(vsize[i] - start[i]));
}
int offset = 0;
for(int i = volume.length - 1; i >= 0 ; i--)
{
offset = offset + start[i] * volume[i]*dsize[i+1];
}
return offset;
} | 4 |
public void chooseDeleteMethod(Scanner a_scan) {
boolean wasDeleted = false;
System.out
.println("Please Select Deletion Method of Choice(1 or 2): "
+ "\n1)Delete by Name,\n2)Delete by techID)");
switch (getMenuChoiceNameOrId(a_scan)) {
case 1: {
String name;
name = inputStudentName(a_scan);
wasDeleted = test.deleteStudent(findStudent(name));
if (wasDeleted) {
System.out.println(name + " was deleted from the record.");
} else {
System.out
.println(name
+ " was not deleted from the record."
+ " Student may not exist in system, or was spelt incorrectly.");
}
break;
}
case 2: {
System.out.println("ID Deletion Method");
int a_id = scanInId(a_scan);
wasDeleted = test.deleteStudent(a_id);
if (wasDeleted) {
System.out.println("Student Number " + a_id
+ " was deleted from the record.");
} else {
System.out
.println("Student Number "
+ a_id
+ " was not deleted from the record. Student may not exist in system, or was spelt incorrectly.");
}
break;
}
}
} | 4 |
@RequestMapping(Routes.exerciciosbasicosRoda)
public String runExercise(HttpServletRequest request, Model model){
resolution = request.getParameter("resolution");
exercise.buildGrading(resolution);
if (exercise.hasCompileErrors != true) {
//exercicio.salvarBancoDeDados(codigoUsuario, conexao);
if (chooser.canDoNextExercise() == true) {
return "redirect:"+Routes.exerciciosbasicosNovo;
} else {
javax.swing.JOptionPane.showMessageDialog(null, "Parabéns. Você passou no teste!");
return "redirect:"+Routes.principal;
}
} else {
//exercicio.salvarBancoErroDeCompilacao(codigoUsuario, conexao);
if (exercise.endOfAttempts == true) {
if (chooser.canDoNextExercise() == true) {
javax.swing.JOptionPane.showMessageDialog(null, "Estouro de "
+ "quantidade de tentativas atingido. "
+ "Por favor, fazer o próximo exercício");
return "redirect:"+Routes.exerciciosbasicosNovo;
} else {
javax.swing.JOptionPane.showMessageDialog(null, "Você foi reprovado no teste");
return "redirect:"+Routes.principal;
}
}
else {
return "redirect:"+Routes.exerciciosbasicosAtualiza;
}
}
} | 4 |
private UsersReader() throws IOException {
try {
FileInputStream fin = new FileInputStream(MAP_DIR);
ObjectInputStream oos = new ObjectInputStream(fin);
userMap = (HashMap<Long, Integer>) oos.readObject();
oos.close();
} catch (Exception e) {
e.printStackTrace();
}
tr = new TreeMap<Integer, UserData>();
FileInputStream fin = new FileInputStream("UserObjects");
ObjectInputStream ois = new ObjectInputStream(fin);
while (true) {
try {
UserData s = (UserData) ois.readObject();
if (userMap.containsKey(s.id))
tr.put(userMap.get(s.id), s);
} catch (Exception e) {
fin.close();
ois.close();
break;
}
}
System.out.println("total users in users map tree "+tr.size());
} | 4 |
public boolean tryRotate() {
boolean valid = true;
incrementTYPE(true);
int[][] key = screen[row][col].key();
for (int i=0; i<3; i++) {
int r = row+key[i][0];
int c = col+key[i][1];
if (r < 0 || r >= NUM_ROWS || c < 0 || c >= NUM_COLS || dead[r][c] == true)
valid = false;
}
incrementTYPE(false);
if (valid)
commitRotate();
return valid;
} | 7 |
private int countNeighbours(int col,int row){
int total = 0;
total = getCell(col-1, row-1) ? total + 1 : total;
total = getCell( col , row-1) ? total + 1 : total;
total = getCell(col+1, row-1) ? total + 1 : total;
total = getCell(col-1, row ) ? total + 1 : total;
total = getCell(col+1, row ) ? total + 1 : total;
total = getCell(col-1, row+1) ? total + 1 : total;
total = getCell( col , row+1) ? total + 1 : total;
total = getCell(col+1, row+1) ? total + 1 : total;
return total;
} | 8 |
public static <T> T getTrackObjectFuzzyAt(World world, int x, int y, int z, Class<T> type) {
T object = getTrackObjectAt(world, x, y, z, type);
if (object != null)
return object;
object = getTrackObjectAt(world, x, y + 1, z, type);
if (object != null)
return object;
object = getTrackObjectAt(world, x, y - 1, z, type);
if (object != null)
return object;
return null;
} | 3 |
private void initSpritePanel() {
File path = new File(Preference.getSpriteLocation());
path.mkdirs();
List<SpritePackage> packages = new ArrayList<SpritePackage>();
File[] dirs = path.listFiles();
for (int i = 0; i < dirs.length; i++) {
File dir = dirs[i];
if (!dir.isDirectory()) continue;
String d = dir.getName();
String name = d;
File f = new File(dir, "info.txt");
if (f.exists()) {
try {
BufferedReader reader = new BufferedReader(new FileReader(f));
String line;
while ((line = reader.readLine()) != null) {
line = line.trim();
if (line.startsWith("name")) {
name = line.split("=")[1].trim();
}
}
reader.close();
} catch (Exception e) {
}
}
SpritePackage pack = new SpritePackage(name, d);
packages.add(pack);
}
String[] packs = Preference.getSpriteDirectories();
for (int i = 0; i < packs.length; i++) {
for (SpritePackage p : packages) {
if (p.getDir().equals(packs[i])) p.m_order = i;
}
}
Collections.sort(packages, new Comparator<SpritePackage>() {
public int compare(SpritePackage o1, SpritePackage o2) {
return new Integer(o1.m_order).compareTo(new Integer(o2.m_order));
}
});
lstPackages.setModel(
new DefaultComboBoxModel(packages.toArray(new SpritePackage[packages.size()])));
cmbSpriteDefaults.setModel(new DefaultComboBoxModel(SpriteLink.values()));
} | 9 |
private static MapPoint getTileAccordingToBuildingType(UnitTypes building) {
MapPoint buildTile = null;
boolean disableReportOfNoPlaceFound = false;
// Bunker
if (TerranBunker.getBuildingType().ordinal() == building.ordinal()) {
buildTile = TerranBunker.findTileForBunker();
}
// Supply Depot
// if (TerranSupplyDepot.getBuildingType().ordinal() ==
// building.ordinal()) {
// buildTile = TerranSupplyDepot.findTileForDepot();
// }
// Missile Turret
else if (TerranMissileTurret.getBuildingType().ordinal() == building.ordinal()) {
buildTile = TerranMissileTurret.findTileForTurret();
}
// Refinery
else if (TerranRefinery.getBuildingType().ordinal() == building.ordinal()) {
buildTile = TerranRefinery.findTileForRefinery();
disableReportOfNoPlaceFound = true;
}
// Base
else if (TerranCommandCenter.getBuildingType().ordinal() == building.ordinal()) {
buildTile = TerranCommandCenter.findTileForNextBase(false);
}
// Standard building
else {
// if (_skipCheckingForTurns > 0) {
// _skipCheckingForTurns--;
// return null;
// }
buildTile = findTileForStandardBuilding(building);
}
if (buildTile == null && !disableReportOfNoPlaceFound) {
System.out.println("# No tile found for: " + building.getType().getName() + " // error: "
+ ConstructionPlaceFinder.lastError + " // search radius: " + ConstructionPlaceFinder.lastRadius);
} else {
// System.out.println(building.name() + ": " + buildTile + " // search radius: "
// + ConstructionPlaceFinder.lastRadius);
}
return buildTile;
} | 6 |
@Override
public boolean activate() {
if(Variables.banking) {
return !ShadeLRC.fullInventory() && (Combat.getRock() == null || !Players.getLocal().isInCombat());
} else {
return Inventory.getCount() < 21 && (Combat.getRock() == null || !Players.getLocal().isInCombat());
}
} | 5 |
@Override
public int write(ResultSet rs) throws IOException,SQLException {
ResultSetMetaData md = rs.getMetaData();
int colCount = md.getColumnCount();
for (int i = 1; i <= colCount; i++) {
print(md.getColumnName(i) + "\t");
}
println();
int rowCount = 0;
while (rs.next()) {
++rowCount;
for (int i = 1; i <= colCount; i++) {
print(rs.getString(i) + "\t");
}
println();
}
return rowCount;
} | 3 |
private static void testCase1(){
CellEntry[][] cell = new CellEntry[][]{
{CellEntry.white, CellEntry.inValid, CellEntry.white, CellEntry.inValid, CellEntry.white, CellEntry.inValid, CellEntry.white, CellEntry.inValid},
{CellEntry.inValid, CellEntry.white, CellEntry.inValid, CellEntry.empty, CellEntry.inValid, CellEntry.empty, CellEntry.inValid, CellEntry.white},
{CellEntry.white, CellEntry.inValid, CellEntry.empty, CellEntry.inValid, CellEntry.empty, CellEntry.inValid, CellEntry.empty, CellEntry.inValid},
{CellEntry.inValid, CellEntry.empty, CellEntry.inValid, CellEntry.empty, CellEntry.inValid, CellEntry.black, CellEntry.inValid, CellEntry.empty},
{CellEntry.empty, CellEntry.inValid, CellEntry.empty, CellEntry.inValid, CellEntry.empty, CellEntry.inValid, CellEntry.empty, CellEntry.inValid},
{CellEntry.inValid, CellEntry.empty, CellEntry.inValid, CellEntry.empty, CellEntry.inValid, CellEntry.empty, CellEntry.inValid, CellEntry.empty},
{CellEntry.empty,CellEntry.inValid, CellEntry.black, CellEntry.inValid, CellEntry.empty, CellEntry.inValid, CellEntry.black, CellEntry.inValid},
{CellEntry.inValid, CellEntry.black, CellEntry.inValid, CellEntry.black, CellEntry.inValid, CellEntry.black, CellEntry.inValid, CellEntry.black}
};
System.out.println(Float.MIN_VALUE);
if(-600>Integer.MIN_VALUE){
System.out.println("Lele maje");///////
}
Board board = new Board(cell);
board.whitePieces = 7;
board.blackPieces = 7;
Vector<Move> resultantMoveSeq = new Vector<Move>();
//
alphaBeta(board, Player.black, 0, Integer.MIN_VALUE, Integer.MAX_VALUE, resultantMoveSeq);
board.Display();
displayMovesInVector(resultantMoveSeq);
} | 1 |
private FileChannel findOrCreateNewLogFile() {
long currentSyncTime = writer.getSyncTime();
resetCurrentChannel(currentMaxTxnTime);
for (int i = 0; i < logFiles.size(); i++) {
if (i == currentFilePosn) {
continue;
}
FileChannel channel = logFiles.get(i).getChannel();
long size = 0;
try {
size = channel.size();
} catch (IOException e1) {
e1.printStackTrace();
}
if (size == 0) {
continue;
}
try {
channel.position(0);
} catch (IOException e) {
}
ByteBuffer buffer = ByteBuffer.allocate(Long.SIZE/8);
try {
channel.read(buffer);
} catch (IOException e) {
e.printStackTrace();
}
buffer.flip();
long l = buffer.getLong();
if (currentSyncTime >= l) {
currentFilePosn = i;
resetCurrentChannel(Long.MAX_VALUE);
return channel;
}
}
// create new one
RandomAccessFile raf = null;
try {
raf = new RandomAccessFile(filePath+"/redolog"+logFiles.size(), "rw");
logFiles.add(raf);
currentFilePosn = logFiles.size()-1;
resetCurrentChannel(Long.MAX_VALUE);
} catch (FileNotFoundException e) {
e.printStackTrace();
}
return logFiles.get(currentFilePosn).getChannel();
} | 8 |
public synchronized void addGameListener(GameListener listener)
throws IllegalArgumentException {
if (listenerCount > gameListeners.length)
throw new IllegalArgumentException("Too many listeners");
this.gameListeners[listenerCount++] = listener;
} | 1 |
public static void encrypt(int[] value, int[] key) {
int sum = 0;
int delta = 0x9E3779B9;
for (int i = 0; i < ENCRYPT_ROUNDS; i++) {
value[0] += (((value[1] << 4) ^ (value[1] >> 5)) + value[1])
^ (sum + key[sum & 3]);
sum += delta;
value[1] += (((value[0] << 4) ^ (value[0] >> 5)) + value[0])
^ (sum + key[(sum >> 11) & 3]);
}
} | 1 |
protected List<String> getCraftableSpellRow(String spellName)
{
List<String> spellFound=null;
final List<List<String>> recipes=loadRecipes();
for(final List<String> V : recipes)
if(V.get(RCP_FINALNAME).equalsIgnoreCase(spellName))
{ spellFound=V; break;}
if(spellFound==null)
for(final List<String> V : recipes)
if(CMLib.english().containsString(V.get(RCP_FINALNAME),spellName))
{ spellFound=V; break;}
if(spellFound==null)
for(final List<String> V : recipes)
if(V.get(RCP_FINALNAME).toLowerCase().indexOf(spellName.toLowerCase())>=0)
{ spellFound=V; break;}
return spellFound;
} | 8 |
@Override
public void keyPressed(KeyEvent e) {
/**
* If the P key is pressed, pause or unpause the game
*/
if (e.getKeyCode() == KeyEvent.VK_P) {
if (gamePaused) {
unpauseGame();
} else {
pauseGame();
}
} else if (e.getKeyCode() == KeyEvent.VK_Q) {
GameEngine.getGameScreenManager().setGameScreen("mainMenu");
}
} | 3 |
public void body()
{
// wait for a little while for about 3 seconds.
// This to give a time for GridResource entities to register their
// services to GIS (GridInformationService) entity.
super.gridSimHold(3.0);
LinkedList resList = super.getGridResourceList();
// initialises all the containers
int totalResource = resList.size();
int resourceID[] = new int[totalResource];
String resourceName[] = new String[totalResource];
// a loop to get all the resources available
int i = 0;
for (i = 0; i < totalResource; i++)
{
// Resource list contains list of resource IDs
resourceID[i] = ( (Integer) resList.get(i) ).intValue();
// get their names as well
resourceName[i] = GridSim.getEntityName( resourceID[i] );
}
////////////////////////////////////////////////
// SUBMIT Gridlets
// determines which GridResource to send to
int index = myId_ % totalResource;
if (index >= totalResource) {
index = 0;
}
// sends all the Gridlets
Gridlet gl = null;
boolean success;
for (i = 0; i < list_.size(); i++)
{
gl = (Gridlet) list_.get(i);
// For even number of Gridlets, send with an acknowledgement
if (i % 2 == 0)
{
success = super.gridletSubmit(gl, resourceID[index],0.0,true);
System.out.println(name_ + ": Sending Gridlet #" +
gl.getGridletID() + " with status = " + success +
" to " + resourceName[index]);
}
// For odd number of Gridlets, send without an acknowledgement
else
{
success = super.gridletSubmit(gl, resourceID[index],0.0, false);
System.out.println(name_ + ": Sending Gridlet #" +
gl.getGridletID() + " with NO ACK so status = " +
success + " to " + resourceName[index]);
}
}
//////////////////////////////////////////
// CANCELING Gridlets
// hold for few period -- 100 seconds
super.gridSimHold(15);
System.out.println("<<<<<<<<< pause for 15 >>>>>>>>>>>");
// a loop that cancels an even number of Gridlet
for (i = 0; i < list_.size(); i++)
{
if (i % 2 == 0)
{
gl = super.gridletCancel(i, myId_, resourceID[index], 0.0);
System.out.print(name_ + ": Canceling Gridlet #" + i +
" at time = " + GridSim.clock() );
if (gl == null) {
System.out.println(" result = NULL");
}
else // if Cancel is successful, then add it into the list
{
System.out.println(" result = NOT null");
receiveList_.add(gl);
}
}
}
////////////////////////////////////////////////////////
// RECEIVES Gridlets back
// hold for few period - 1000 seconds since the Gridlets length are
// quite huge for a small bandwidth
super.gridSimHold(1000);
System.out.println("<<<<<<<<< pause for 1000 >>>>>>>>>>>");
// receives the gridlet back
int size = list_.size() - receiveList_.size();
for (i = 0; i < size; i++)
{
gl = (Gridlet) super.receiveEventObject(); // gets the Gridlet
receiveList_.add(gl); // add into the received list
System.out.println(name_ + ": Receiving Gridlet #" +
gl.getGridletID() + " at time = " + GridSim.clock() );
}
System.out.println(this.name_ + ":%%%% Exiting body() at time " +
GridSim.clock() );
// shut down I/O ports
shutdownUserEntity();
terminateIOEntities();
// Prints the simulation output
printGridletList(receiveList_, name_);
} | 8 |
public boolean equals(Object instance) {
if (instance instanceof PairNonOrdered<?>) {
PairNonOrdered<?> other = (PairNonOrdered<?>)instance;
return super.equals(other) || super.equals(other.reverse());
}
return false;
} | 5 |
public JSONObject putOnce(String key, Object value) throws JSONException {
if (key != null && value != null) {
if (this.opt(key) != null) {
throw new JSONException("Duplicate key \"" + key + "\"");
}
this.put(key, value);
}
return this;
} | 3 |
public void update(MainWindowModel mainWindowModel) {
setNumberOfPoints(mainWindowModel.getNumberOfPoints());
setTimeStep(mainWindowModel.getTimeStep());
setTimePeriod(mainWindowModel.getTimePeriod());
setXMin(mainWindowModel.getXMin());
setXMax(mainWindowModel.getXMax());
setYMin(mainWindowModel.getYMin());
setYMax(mainWindowModel.getYMax());
setIntegrationMethod(mainWindowModel.getIntegrationMethod());
setAngle(mainWindowModel.getAngle());
setPhi(mainWindowModel.getPhi());
setPsi(mainWindowModel.getPsi());
setTheta(mainWindowModel.getTheta());
setNumberOfSpheres(mainWindowModel.getNumberOfSpheres());
} | 0 |
public MasterMindAI(int level) {
int i = level;
if (i > 5) {
i = 5;
}
if (i < 0 ) {
i = 0;
}
this.level = (level+5)*500;
init();
} | 2 |
void createControlGroup () {
/*
* Create the "Control" group. This is the group on the
* right half of each example tab. It consists of the
* "Style" group, the "Other" group and the "Size" group.
*/
controlGroup = new Group (tabFolderPage, SWT.NONE);
controlGroup.setLayout (new GridLayout (2, true));
controlGroup.setLayoutData (new GridData(SWT.FILL, SWT.FILL, false, false));
controlGroup.setText (ControlExample.getResourceString("Parameters"));
/* Create individual groups inside the "Control" group */
createStyleGroup ();
createOtherGroup ();
createSetGetGroup();
createSizeGroup ();
createColorAndFontGroup ();
if (rtlSupport()) {
createOrientationGroup ();
}
/*
* For each Button child in the style group, add a selection
* listener that will recreate the example controls. If the
* style group button is a RADIO button, ensure that the radio
* button is selected before recreating the example controls.
* When the user selects a RADIO button, the current RADIO
* button in the group is deselected and the new RADIO button
* is selected automatically. The listeners are notified for
* both these operations but typically only do work when a RADIO
* button is selected.
*/
SelectionListener selectionListener = new SelectionAdapter () {
public void widgetSelected (SelectionEvent event) {
if ((event.widget.getStyle () & SWT.RADIO) != 0) {
if (!((Button) event.widget).getSelection ()) return;
}
recreateExampleWidgets ();
}
};
Control [] children = styleGroup.getChildren ();
for (int i=0; i<children.length; i++) {
if (children [i] instanceof Button) {
Button button = (Button) children [i];
button.addSelectionListener (selectionListener);
} else {
if (children [i] instanceof Composite) {
/* Look down one more level of children in the style group. */
Composite composite = (Composite) children [i];
Control [] grandchildren = composite.getChildren ();
for (int j=0; j<grandchildren.length; j++) {
if (grandchildren [j] instanceof Button) {
Button button = (Button) grandchildren [j];
button.addSelectionListener (selectionListener);
}
}
}
}
}
if (rtlSupport()) {
rtlButton.addSelectionListener (selectionListener);
ltrButton.addSelectionListener (selectionListener);
defaultOrietationButton.addSelectionListener (selectionListener);
}
} | 9 |
@Override
public void compute() {
// A very simple AI
boolean newShip = false;
if (currentOpponentShip == null || currentOpponentShip.getMorphsByIds().size() == 0) {
currentOpponentShip = findOpponentShip();
newShip = true;
}
// iterate over the user's ships and send them all engage the opponent ship
for (Ship ship : World.getWorld().getShips().values()) {
if (ship.getOwner().equals(user)) {
GoToShipAndEngage foundAI = null;
for (AI ai : ship.getAIList()) {
if (ai instanceof GoToShipAndEngage) {
foundAI = (GoToShipAndEngage) ai;
}
}
// FIXME This way of getting the targetted morph is dangerous
if (foundAI == null) {
foundAI = new GoToShipAndEngage(ship, currentOpponentShip.getMorphsByIds().values().iterator().next());
ship.getAIList().add(foundAI);
} else if (newShip) {
foundAI.setTarget(currentOpponentShip.getMorphsByIds().values().iterator().next());
}
}
}
} | 8 |
@Override
public int hashCode() {
int hash = 0;
hash += (id != null ? id.hashCode() : 0);
return hash;
} | 1 |
public static void printMatrix(double[][] matrix, String fp, String[] names, int[] perm, String format) throws FileNotFoundException {
File f = new File(fp);
FileUtils.makeSubDirsOnly(f);
PrintWriter out = new PrintWriter(f);
if (names != null) {
out.print("#");
for (int i = 0; i < names.length; i++) {
out.print(SEPARATOR);
out.print(names[(perm == null) ? i : perm[i]]);
}
out.println();
}
for (int i = 0; i < matrix.length; i++) {
if (names != null) {
out.print(names[(perm == null) ? i : perm[i]] + SEPARATOR);
}
for (int j = 0; j < matrix[i].length; j++) {
if (j > 0) {
out.print(SEPARATOR);
}
if (perm == null) {
out.printf(format, matrix[i][j]);
} else {
out.printf(format, matrix[perm[i]][perm[j]]);
}
}
out.println();
}
out.close();
} | 9 |
private void setHeightRatio() {
if(backup_orbit != null && orbit) {
System.arraycopy(((DataBufferInt)backup_orbit.getRaster().getDataBuffer()).getData(), 0, ((DataBufferInt)image.getRaster().getDataBuffer()).getData(), 0, image_size * image_size);
}
main_panel.repaint();
String ans = JOptionPane.showInputDialog(scroll_pane, "You are using " + height_ratio + " as height ratio.\nEnter the new height ratio.", "Height Ratio", JOptionPane.QUESTION_MESSAGE);
try {
double temp = Double.parseDouble(ans);
if(temp <= 0) {
main_panel.repaint();
JOptionPane.showMessageDialog(scroll_pane, "Height ratio number must be greater than 0.", "Error!", JOptionPane.ERROR_MESSAGE);
return;
}
height_ratio = temp;
setOptions(false);
progress.setValue(0);
resetImage();
backup_orbit = null;
whole_image_done = false;
if(d3) {
Arrays.fill(((DataBufferInt)image.getRaster().getDataBuffer()).getData(), 0, image_size * image_size, Color.BLACK.getRGB());
}
if(julia_map) {
createThreadsJuliaMap();
}
else {
createThreads();
}
calculation_time = System.currentTimeMillis();
if(julia_map) {
startThreads(julia_grid_first_dimension);
}
else {
startThreads(n);
}
}
catch(Exception ex) {
if(ans == null) {
main_panel.repaint();
}
else {
JOptionPane.showMessageDialog(scroll_pane, "Illegal Argument!", "Error!", JOptionPane.ERROR_MESSAGE);
main_panel.repaint();
}
}
} | 8 |
public Position<T> SearchNode(Position<T> root, T value)
throws InvalidPositionException {
BTPosition<T> BTroot = checkPosition(root);
while (BTroot != null) {
T currentV = BTroot.element();
if (currentV == value)
break;
if (comp.compare(currentV, value) > 0)
BTroot = BTroot.getLeft();
else
BTroot = BTroot.getRight();
}
return BTroot;
} | 3 |
private void delay() {
if (_packetDelay > 0) {
try {
Thread.sleep(_packetDelay);
}
catch (InterruptedException e) {
// Do nothing.
}
}
} | 2 |
@Override
public void actionPerformed(ActionEvent e)
{
if(e.getActionCommand().equals(classeString)) // Si on clic sur le boutton "Selectionner classe" on affiche les
// équipements
{
selectionClasse();
}
if(e.getActionCommand().equals(equipementString)) // Si on clic sur le boutton "Selectionner Equipement" on
// affiche
// les classes
{
selectionEquipement();
this.removeAll();
afficheChoixClassePersonnage();
}
if(e.getActionCommand().equals(ajoutClasseString)) // Si clic sur le boutton d'ajout de classe
{
ajoutClasse();
}
if(e.getActionCommand().equals(ajoutEquipementString))
{
ajoutEquipement();
}
} | 4 |
final void put(int i, Object object, long key, int i_5_) {
try {
anInt1092++;
if (i_5_ > anInt1084)
throw new IllegalStateException("s>cs");
method586(key);
anInt1086 -= i_5_;
while ((anInt1086 ^ 0xffffffff) > -1) {
Class348_Sub42_Sub8 class348_sub42_sub8
= ((Class348_Sub42_Sub8)
queue.removeFirst());
method585(class348_sub42_sub8, i ^ ~0x7cfa);
}
Class348_Sub42_Sub8_Sub2 class348_sub42_sub8_sub2
= new Class348_Sub42_Sub8_Sub2(object, i_5_);
hashTable.putNode(key, class348_sub42_sub8_sub2);
if (i != 31902)
anInt1086 = -106;
queue.add(class348_sub42_sub8_sub2);
((SubNode) class348_sub42_sub8_sub2).subnodeKey = 0L;
} catch (RuntimeException runtimeexception) {
throw Class348_Sub17.method2929(runtimeexception,
("jr.E(" + i + ','
+ (object != null ? "{...}"
: "null")
+ ',' + key + ',' + i_5_ + ')'));
}
} | 5 |
private void updateHasOne(Object obj, String column,
Map<String, Object> foreignKey) {
StringBuilder sb = new StringBuilder();
sb.append("update " + obj.getClass().getSimpleName() + " set ");
PreparedStatement stmt = null;
Connection connection = null;
try {
PropertyDescriptor[] pd = handler.getPropertyDescriptors(obj
.getClass());
Map<String, Object> belongsTo = AnnotationUtils.getBelongsTo(obj);
Map<String, Object> primaryKey = AnnotationUtils.getPrimaryKey(obj);
for (int i = 0; i < pd.length; i++) {
if ("class".equals(pd[i].getName())
|| foreignKey.get("column").equals(pd[i].getName())) {
continue;
}
if (pd[i].getName().equals(belongsTo.get("fieldName"))) {
continue;
}
Method getter = pd[i].getReadMethod();
Object value = getter.invoke(obj);
sb.append(pd[i].getName()).append("=").append("'")
.append(value).append("'");
if (i != pd.length - 1) {
sb.append(",");
}
}
if (obj != null) {
sb.append(",").append(column).append("=").append("'")
.append(foreignKey.get("value")).append("'");
}
sb.append(" where ").append(primaryKey.get("column")).append("='")
.append(primaryKey.get("value")).append("'");
connection = DB.getConnection();
stmt = connection.prepareStatement(sb.toString());
stmt.executeUpdate();
} catch (Exception e) {
throw new ExcuteQueryException(e);
} finally {
DbUtils.closeQuietly(stmt);
}
} | 7 |
public void draw(Graphics2D g) {
//Draw the background image so the board looks pretty.
g.drawImage(boardImage, 0, 0, null);
//We're gonna mess with the board so lets copy it.
Board temp = copy();
//Determine where each piece is.
String checkerColor, checkerType;
for (int i = 0; i < SIZE; i++)
for (int j = 0; j < SIZE; j++)
if (temp.moveToTop(i, j)) {
checkerColor = temp.pieces.get(temp.pieces.size() - 1).getColor();
checkerType = temp.pieces.get(temp.pieces.size() - 1).getType();
//Checker is regular.
if (checkerType.equals("RegularChecker")) {
//Color is blue.
if (checkerColor.equals("Blue"))
g.drawImage(blueCheckerImage, i * TILE_SIZE, j * TILE_SIZE, null);
//Color is red.
else if (checkerColor.equals("Red"))
g.drawImage(redCheckerImage, i * TILE_SIZE, j * TILE_SIZE, null);
//Checker is a king.
} else if (checkerType.equals ("King")) {
//Color is blue.
if (checkerColor.equals("Blue"))
g.drawImage(blueCheckerKingImage, i * TILE_SIZE, j * TILE_SIZE, null);
//Color is red.
else if (checkerColor.equals("Red"))
g.drawImage(redCheckerKingImage, i * TILE_SIZE, j * TILE_SIZE, null);
}
}
} | 9 |
public void run()
{
screen = createVolatileImage(pixel.width, pixel.height); //actually use the graphics card (less lag)
render();
if(!debugMode)
{
int twoPlayers = JOptionPane.showConfirmDialog(null, "Play with 2 players?", "2 Players?", JOptionPane.YES_NO_OPTION);
if(twoPlayers == 1) //they said no
isTwoPlayers = false;
else
isTwoPlayers = true;
}
else
{
isTwoPlayers = false;
}
if(!debugMode)
{
render();
JOptionPane.showMessageDialog(null, "Look away after ending your turn\n\n" +
"Normal Controls:\nClick - Bomb square\nSpace - End turn\n\n" +
"Editing Controls:\nE - Toggle editing mode\n" +
"R - Random ship arrangement\nArrows - Move ship\n" +
"Ctrl - Rotate ship\nSpace - Place ship / Finish placing ships");
}
while(isRunning)
{
tick(); //do math and any calculations
render(); //draw the objects
try
{
Thread.sleep(tickTime*(int)computerSpeed);
}catch(Exception e){ }
}
} | 5 |
void setUp(int width) {
for (int x = 0; x < width; x++) {
for (int y = 0; y < width; y++) {
Square square = squares[x][y];
if (uniform() < 0.5) {
square.setDirty(true);
}
if (uniform() < 0.1) {
square.setObstacle(true);
}
}
}
} | 4 |
private void init() {
int run_server = JOptionPane.showConfirmDialog(null, "Run the server ? ");
if (run_server == 0) {
server = new Server(this);
client = new Client(this, "localhost");
client.start();
} else if (run_server == 1) {
try {
client = new Client(this, JOptionPane.showInputDialog(null, "Enter IP: "));
client.start();
} catch (HeadlessException e) {
e.printStackTrace();
} catch (NumberFormatException e) {
e.printStackTrace();
}
} else if (run_server == 2) {
System.out.println("Exiting at 0.");
System.exit(0);
}
String username = JOptionPane.showInputDialog(null, "Enter Username:");
if (username == null) {
System.out.println("Exiting at 1.");
System.exit(1);
}
if (username.trim().equals("")) {
username = "Player";
}
String info = ""
+ "<html>"
+ "<h3>SETTINGS:</h3>"
+ "<table border=1>"
+ "<tr>"
+ "<td>Walk:</td>"
+ "<td style='color: green'>WASD or ARROWS KEYS</td>"
+ "</tr>"
+ "<tr>"
+ "<td>Shoot:</td>"
+ "<td style='color: green'>LEFT CLICK</td>"
+ "</tr>"
+ "<tr>"
+ "<td>1st Weapon:</td>"
+ "<td style='color: green'>1</td>"
+ "</tr>"
+ "<tr>"
+ "<td>2nd Weapon:</td>"
+ "<td style='color: green'>2</td>"
+ "</tr>"
+ "<tr>"
+ "<td>Speed Boost:</td>"
+ "<td style='color: green'>SHIFT</td>"
+ "</tr>"
+ "<tr>"
+ "<td>Toggle invisible:</td>"
+ "<td style='color: green'>I</td>"
+ "</tr>"
+ "</table>"
+ "<h4>Good Luck !!!</h3>"
+ "</html>";
JOptionPane.showMessageDialog(null, info);
player = new PlayerMP(10, 10, username, key, mouse, null, -1, true);
level.addEntity(player);
Packet00Login packet = new Packet00Login(player.getUsername(), player.getX(), player.getY(), player.getHP(), player.getUniqueID());
packet.writeData(client);
if (server != null) {
server.addConnections((PlayerMP) player, packet);
server.start();
Tonny tonny = new Tonny(100, 100, 100);
Packet05AddNPC packetNPC = new Packet05AddNPC((int) tonny.getX(), (int) tonny.getY(), tonny.getHP(), tonny.getUniqueID(), MobType.TONNY.getID());
packetNPC.writeData(client);
BadTonny bad_tonny = new BadTonny(170, 20, 20);
packetNPC = new Packet05AddNPC((int) bad_tonny.getX(), (int) bad_tonny.getY(), bad_tonny.getHP(), bad_tonny.getUniqueID(), MobType.BAD_TONNY.getID());
packetNPC.writeData(client);
bad_tonny = new BadTonny(200, 300, 100);
packetNPC = new Packet05AddNPC((int) bad_tonny.getX(), (int) bad_tonny.getY(), bad_tonny.getHP(), bad_tonny.getUniqueID(), MobType.BAD_TONNY.getID());
packetNPC.writeData(client);
bad_tonny = new BadTonny(250, 300, 100);
packetNPC = new Packet05AddNPC((int) bad_tonny.getX(), (int) bad_tonny.getY(), bad_tonny.getHP(), bad_tonny.getUniqueID(), MobType.BAD_TONNY.getID());
packetNPC.writeData(client);
}
} | 8 |
public Shape getShape(String shapeType){
if(shapeType == null){
return null;
}
if(shapeType.equalsIgnoreCase("CIRCLE")){
return new Circle();
}
else if (shapeType.equalsIgnoreCase("RECTANGLE")){
return new Rectangle();
}
else if (shapeType.equalsIgnoreCase("Square")){
return new Square();
}
return null;
} | 4 |
public void visitEnd() {
super.visitEnd();
if (fv != null) {
fv.visitEnd();
}
} | 1 |
public void run() throws ParsingException {
parseStack.push(new TerminalEntry(EOF));
parseStack.addToParseStack(ruleTable.find(startSymbol, startToken));
A = parseStack.peek();
getNextToken();
while ((A != null) && !A.isEof()) {
A = parseStack.peek();
if (A.isTerminal()) {
if (A.matches(i)) {
parseStack.pop();
if (parseStack.notEmpty()) {
A = parseStack.peek();
getNextToken();
}
} else {
throw new ParsingException("Terminal mismatch. Expected: " + A + " Found: " + i + "");
}
} else if (A.isSemanticEntry()) {
final SemanticNode node = nodeFactory.getNewNode(A);
node.runOnSemanticStack(semanticStack);
parseStack.pop();
} else {
if (isRuleContained(A, i)) {
parseStack.pop();
parseStack.addToParseStack(ruleTable.find(A, i));
A = parseStack.peek();
} else {
throw new ParsingException("Non-terminal mismatch. No entry in the table for: " + A + " , " + i);
}
}
}
if (!stream.isEmpty()) {
throw new ParsingException("Parser found the end of file marker but the token stream was not empty.");
}
} | 8 |
private Component cycle(Component currentComponent, int delta) {
int index = -1;
loop : for (int i = 0; i < m_Components.length; i++) {
Component component = m_Components[i];
for (Component c = currentComponent; c != null; c = c.getParent()) {
if (component == c) {
index = i;
break loop;
}
}
}
// try to find enabled component in "delta" direction
int initialIndex = index;
while (true) {
int newIndex = indexCycle(index, delta);
if (newIndex == initialIndex) {
break;
}
index = newIndex;
//
Component component = m_Components[newIndex];
if (component.isEnabled() && component.isVisible() && component.isFocusable()) {
return component;
}
}
// not found
return currentComponent;
} | 8 |
private static Object dialog(WindowType window, MessageType messageType,
String title, String message, JFrame parent) {
int swingType;
switch (messageType) {
case WARN:
swingType = JOptionPane.WARNING_MESSAGE; break;
case QUESTION:
swingType = JOptionPane.QUESTION_MESSAGE; break;
default:
swingType = JOptionPane.ERROR_MESSAGE;
}
if ( window.equals(WindowType.MESSAGE) ) {
JOptionPane.showMessageDialog(parent, message, title, swingType);
} else if ( window.equals(WindowType.CONFIRM) ) {
Object[] options = {"Ano", "Ne"};
int button = JOptionPane.showOptionDialog(parent, message, title,
JOptionPane.YES_NO_OPTION, swingType, null, options, options[0]);
return button == 0;
} else if ( window.equals(WindowType.INPUT) ) {
return JOptionPane.showInputDialog(parent, message, title, swingType);
}
return null;
} | 5 |
public static int[][] mul(int[][] a, int[][] b) {
int[][] result = new int[a.length][b.length];
for (int i = 0; i < a.length; i++) {
for (int j = 0; j < a.length; j++) {
result[i][j] = 0;
for (int N = 0; N < a.length; N++) {
result[i][j] += a[i][N] * b[N][j];
}
}
}
return result;
} | 3 |
public FeatureVector extract(String idref)
throws IDrefNotInSentenceException, RootNotInPathException, FeatureValueNotCalculatedException {
FeatureVector fv = new FeatureVector();
if (FeatureTypes.isUsedFeatureType("target"))
fv.addFeature("target", extractTarget());
if (FeatureTypes.isUsedFeatureType("synCat"))
fv.addFeature("synCat", extractSyntacticalCategory(idref));
if (FeatureTypes.isUsedFeatureType("position"))
fv.addFeature("position", extractPosition(idref));
//fv.addFeature("path", extractPath(idref));
if (FeatureTypes.isUsedFeatureType("path") || FeatureTypes.isUsedFeatureType("funcPath"))
extractPath(idref, fv);
if (FeatureTypes.isUsedFeatureType("head"))
fv.addFeature("head", extractHead(idref));
if (FeatureTypes.isUsedFeatureType("terminal"))
fv.addFeature("terminal", sentence.getNode(idref).isTerminal() ? "1" : "0");
if (FeatureTypes.isUsedFeatureType("nextHead"))
fv.addFeature("nextHead", extractNextHead(idref));
return fv;
} | 9 |
public boolean isValidSelection(DateModel<?> model) {
if (model.isSelected()) {
Calendar value = Calendar.getInstance();
value.set(model.getYear(), model.getMonth(), model.getDay());
value.set(Calendar.HOUR, 0);
value.set(Calendar.MINUTE, 0);
value.set(Calendar.SECOND, 0);
value.set(Calendar.MILLISECOND, 0);
switch (value.get(Calendar.DAY_OF_WEEK)) {
case Calendar.MONDAY:
case Calendar.TUESDAY:
case Calendar.WEDNESDAY:
case Calendar.THURSDAY:
case Calendar.FRIDAY:
return true;
default:
return false;
}
} else {
return true;
}
} | 7 |
@Override
public void endElement ( String uri, String localName, String qName )
throws SAXException {
if ( requestType.equals( Globals.requestStatus ) ) {
if ( qName.equals( XMLTags.Status ) ) {
return;
} else {
processStatusXml( qName );
}
} else if ( requestType.equals( Globals.requestMemoryByte ) ) {
if ( qName.equals( XMLTags.Memory ) ) {
return;
} else {
processMemoryXml( qName );
}
} else if ( requestType.equals( Globals.requestDateTime ) ) {
if ( qName.equals( XMLTags.DateTime ) ) {
if ( !currentElementText.isEmpty() ) {
// not empty meaning we have a status to report
// either OK or ERR
dt.setStatus( currentElementText );
}
return;
} else {
processDateTimeXml( qName );
}
} else if ( requestType.equals( Globals.requestVersion ) ) {
processVersionXml( qName );
} else {
// TODO request none, set an error?
}
currentElementText = "";
} | 8 |
private void initComponents() {
setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
wordsInSectionLbl = new JLabel();
wordsPane = new JScrollPane();
wordsTable = new JTable();
editWordLbl = new JLabel();
motherLangWordTextField = new JTextField();
translationTextField = new JTextField();
commitBtn = new JButton();
deleteWordBtn = new JButton();
backBtn = new JButton();
statusLbl = new JLabel();
//======== this ========
setResizable(false);
setTitle("Learning words - Edit card");
Container contentPane = getContentPane();
contentPane.setLayout(null);
//---- wordsInSectionLbl ----
wordsInSectionLbl.setText("Words in section '" + AddCard.getSelectedSection() + "':");
wordsInSectionLbl.setFont(new Font("Segoe UI", Font.BOLD, 14));
contentPane.add(wordsInSectionLbl);
wordsInSectionLbl.setBounds(new Rectangle(new Point(20, 25), wordsInSectionLbl.getPreferredSize()));
//======== wordsPane ========
{
//---- wordsTable ----
wordsTable.setSelectionMode(ListSelectionModel.SINGLE_SELECTION);
wordsTable.setModel(new SelectWordTableModel());
//----Set id column invisible-----
wordsTable.getColumnModel().getColumn(2).setMaxWidth(0);
wordsTable.getColumnModel().getColumn(2).setMinWidth(0);
wordsTable.getColumnModel().getColumn(2).setResizable(false);
wordsTable.getColumnModel().getColumn(2).setPreferredWidth(0);
//--------------------------------
wordsTable.addMouseListener(new MouseAdapter() {
@Override
public void mouseClicked(MouseEvent e) {
try {
int row = wordsTable.getSelectedRow();
motherLangWordTextField.setEnabled(true);
translationTextField.setEnabled(true);
commitBtn.setEnabled(true);
deleteWordBtn.setEnabled(true);
motherLangWordTextField.setText((wordsTable.getValueAt(row, 0)).toString());
translationTextField.setText((wordsTable.getValueAt(row, 1)).toString());
selectedCardId = (Integer)(wordsTable.getValueAt(row, 2));
} catch (Exception ex) {
ex.printStackTrace();
}
}
});
wordsPane.setViewportView(wordsTable);
}
contentPane.add(wordsPane);
wordsPane.setBounds(20, 50, wordsPane.getPreferredSize().width, 229);
//---- editWordLbl ----
editWordLbl.setText("Edit word and translation:");
editWordLbl.setFont(new Font("Segoe UI", Font.BOLD, 14));
contentPane.add(editWordLbl);
editWordLbl.setBounds(new Rectangle(new Point(20, 290), editWordLbl.getPreferredSize()));
contentPane.add(motherLangWordTextField);
motherLangWordTextField.setBounds(20, 320, 260, motherLangWordTextField.getPreferredSize().height);
contentPane.add(translationTextField);
translationTextField.setBounds(20, 350, 260, 21);
motherLangWordTextField.setEnabled(false);
translationTextField.setEnabled(false);
//---- commitBtn ----
commitBtn.setText("Commit");
contentPane.add(commitBtn);
commitBtn.setBounds(20, 380, 80, 30);
commitBtn.addActionListener(new CommitButtonListener(motherLangWordTextField, translationTextField, statusLbl, wordsTable));
commitBtn.setEnabled(false);
//---- deleteWordBtn ----
deleteWordBtn.setText("Delete word");
contentPane.add(deleteWordBtn);
deleteWordBtn.setBounds(105, 380, 105, 30);
deleteWordBtn.addActionListener(new DeleteWordButtonListener(motherLangWordTextField, translationTextField, statusLbl, wordsTable));
deleteWordBtn.setEnabled(false);
//---- backBtn ----
backBtn.setText("Back");
contentPane.add(backBtn);
backBtn.setBounds(215, 380, 80, 30);
backBtn.addActionListener(new BackButtonListener(this, user));
//---- statusLbl ----
statusLbl.setText("Select card to edit or delete. Words in cards must be unique!");
statusLbl.setFont(statusLbl.getFont().deriveFont(statusLbl.getFont().getStyle() | Font.BOLD));
contentPane.add(statusLbl);
statusLbl.setBounds(new Rectangle(new Point(20, 430), statusLbl.getPreferredSize()));
contentPane.setPreferredSize(new Dimension(505, 480));
pack();
setLocationRelativeTo(getOwner());
} | 1 |
public static TransactionSet DoApriori(TransactionSet transSet,double minSupportLevel) {
ItemSet initialItemSet = transSet.GetUniqueItems();//get all singular unique items and put them into a ItemSet object
TransactionSet finalLargeItemSet = new TransactionSet(); // resultant large itemsets
TransactionSet LargeItemSet = new TransactionSet(); // large itemset in each iteration
TransactionSet CandidateItemSet = new TransactionSet(); // candidate itemset in each iteration
// first iteration (1-item itemsets)
for (int i = 0; i < initialItemSet.getItemSet().size(); i++) {
Item candidateItem = initialItemSet.getItemSet().get(i);
ItemSet candidateItemSet = new ItemSet();
candidateItemSet.getItemSet().add(candidateItem);
double findSupport = transSet.findSupport(candidateItemSet);//calculate and find each successive support level for an transaction (remember it is an itemSet)
candidateItemSet.setItemSetSupport(findSupport/(transSet.getTransactionSet().size()));//Set each successive support level for its respective transaction (remember it is an itemSet)
//CandidateItemSet.getTransactionSet().add(candidateTrans);
if (candidateItemSet.getItemSetSupport() >= minSupportLevel) {
//candidateItemSet.getItemSet().add(candidateItem);
//Transaction candidateTrans = new Transaction(candidateItemSet);
CandidateItemSet.getTransactionSet().add(new Transaction(candidateItemSet));
}
}
CandidateItemSet = (CandidateItemSet.twoItemSubsets(CandidateItemSet, minSupportLevel, transSet));
// next iterations
int k = 3;
while (CandidateItemSet.getTransactionSet().size() != 0) {
//set LargeItemSetIteration from CandidateItemSet (pruning)
LargeItemSet.getTransactionSet().clear();
//System.out.println("START");
for (Transaction transaction : CandidateItemSet.getTransactionSet()) {//loop through each transaction in each TransactionSet
double findSupport = transSet.findSupport(transaction.getTransaction());//calculate and find each successive support level for an transaction (remember it is an itemSet)
transaction.getTransaction().setItemSetSupport(findSupport/(transSet.getTransactionSet().size()));//Set each successive support level for its respective transaction (remember it is an itemSet)
if (transaction.getTransaction().getItemSetSupport() >= minSupportLevel) {//Determine if the itemSet's support level meets or exceeds the supportThreshold to filter out
//System.out.println(transaction.toString() + "-" + findSupport);//debugging info
LargeItemSet.getTransactionSet().add(transaction);
//if (transaction.getTransaction().getItemSet().size() > 1) {// this might not work in the long run
finalLargeItemSet.getTransactionSet().add(transaction);//add the resultingLargeItemSet of final
//}
}
}
CandidateItemSet.getTransactionSet().clear();//clear up the candidates to prep for finding all subsets
//System.out.println("making candidates");
CandidateItemSet = (CandidateItemSet.findKItemSubsets(LargeItemSet.GetUniqueItems(), k));//Add all the combinations of subsets for a given set of unique items/ItemSets
//System.out.println("done making candidates");
k += 1;
}
return finalLargeItemSet;//final returned value
} | 5 |
@Override
public void renderContents(float interpolation) {
if(mainCollider != null)
mainCollider.drawCollider(0xffffff);
if(moveCollider != null)
moveCollider.drawCollider(0xffffff);
if(altMoveCollider != null)
altMoveCollider.drawCollider(0x00ff00);
if(rawMoveCollider != null)
rawMoveCollider.drawCollider(0x0000ff);
if(collision.collides)
{
Fonts.get("Arial").drawString("Colliding!", 10, 200, 20, 0xffffff);
Fonts.get("Arial").drawString(collision.correction.toString(), 10, 220, 20, 0xffffff);
}
} | 5 |
@Override
public void getFromPane(User u) throws InvalidFieldException {
String oID = u.getID();
u.setID(tfID.getText().trim());
GameData g = GameData.getCurrentGame();
if (!g.checkID(u, User.class)) {
if (oID != null)
u.setID(oID);
throw new InvalidFieldException(Field.USER_ID_DUP, "Duplicate ID, User (changing manually)");
}
//u.setID(tfID.getText());
u.setFirstName(tfFirstName.getText().trim());
u.setLastName(tfLastName.getText().trim());
// not necessary since we cant change the pts anyway
//u.setPoints(Integer.parseInt(labelPtsValue.getText()));
int item = cbUltPick.getSelectedIndex();
Contestant c = cbUltPick.getItemAt(item);
u.setUltimatePick(c);
item = cbWeeklyPick.getSelectedIndex();
c = cbWeeklyPick.getItemAt(item);
u.setWeeklyPick(c);
} | 2 |
public boolean similar(Object other) {
try {
if (!(other instanceof JSONObject)) {
return false;
}
Set set = this.keySet();
if (!set.equals(((JSONObject)other).keySet())) {
return false;
}
Iterator iterator = set.iterator();
while (iterator.hasNext()) {
String name = (String)iterator.next();
Object valueThis = this.get(name);
Object valueOther = ((JSONObject)other).get(name);
if (valueThis instanceof JSONObject) {
if (!((JSONObject)valueThis).similar(valueOther)) {
return false;
}
} else if (valueThis instanceof JSONArray) {
if (!((JSONArray)valueThis).similar(valueOther)) {
return false;
}
} else if (!valueThis.equals(valueOther)) {
return false;
}
}
return true;
} catch (Throwable exception) {
return false;
}
} | 9 |
public AttackResult attack(Territory target){
//assumes that troop strength of attacking territory is > 1
Integer[] aDice, dDice;
if(this.troopStrength > 3){
aDice = new Integer[3];
} else{
aDice = new Integer[this.troopStrength - 1];
}
if(target.getTroopStrength() > 1){
dDice = new Integer[2];
} else {
dDice = new Integer[1];
}
System.out.println("Attack dice");
for(int i = 0; i < aDice.length; i++){
aDice[i] = Util.diceRoll();
}
System.out.println("Defense Dice");
for(int i = 0; i < dDice.length; i++){
dDice[i] = Util.diceRoll();
}
System.out.println("Attacking Dice: " + aDice.toString());
System.out.println("Defending Dice: " + dDice.toString());
AttackResult res = new AttackResult(aDice,dDice);
System.out.println(aDice.length);
System.out.println(dDice.length);
this.troopStrength -= res.getAttackerLosses();
target.troopStrength -= res.getDefenderLosses();
if(target.troopStrength <= 0){
target.troopStrength = 0;
target.setOwnedBy(this.ownedBy);
do {
try{
target.setTroopStrength(Integer.valueOf((String) JOptionPane.showInputDialog(Graphics.frame, "How many reinforcements would you like to send?", "Reinforcements", JOptionPane.PLAIN_MESSAGE, null, null, null)));
}catch (java.lang.NumberFormatException e){
JOptionPane.showMessageDialog(null, "You must enter a valid integer response");
}
} while (target.getTroopStrength() < 1 || target.getTroopStrength() > this.troopStrength);
this.setTroopStrength(this.getTroopStrength() - target.getTroopStrength());
}
this.troopCount.setText(Integer.valueOf(this.troopStrength).toString());
target.troopCount.setText(Integer.valueOf(target.troopStrength).toString());
return res;
} | 8 |
public static void main(String[] args)
{
ArrayList list = new ArrayList();
list.add("hello");
list.add(new Integer(2));
String str = (String)list.get(0);
Integer in = (Integer)list.get(1);
// String in1 = (String)list.get(1); java.lang.Integer cannot be cast to java.lang.String
System.out.println(str);
System.out.println(in);
// System.out.println(in1);
} | 0 |
public void playGame(GUI gui, int matchNum, int totalMatches) {
gui.initaliseWorldMap(world, matchNum, totalMatches);
System.out.println("Total Food:" + world.getFoodNum());
try {
// Sleep thread for 3 seconds between each game for the player to observe the results
Thread.sleep(3000); // 3000ms
} catch (InterruptedException e) {
}
gui.updateUI(world, this);
for (int i = 0; i < 300000; i++) {
stepGame();
gui.updateUI(world, this);
//Use the following block to create a realtime simulation (lasts a 300,000 x number of ms specified in sleep(n))
// try {
// Thread.sleep(5); // 2ms sleep time between steps = 300,000x2ms = 10 minutes per game
// } catch (InterruptedException e) {}
}
endGame();
gui.updateUI(world, this);
} | 2 |
public String getName() {
return name;
} | 0 |
public boolean isChar() {
char c = symbol;
if ((c >= 65 && c <= 90) || (c >= 97 && c <= 122)) {
return true;
}
return false;
} | 4 |
private void searchForControllers()
{
Controller[] controllers = ControllerEnvironment.getDefaultEnvironment().getControllers();
for(int i = 0; i < controllers.length; i++)
{
Controller controller = controllers[i];
if (controller.getType() == Controller.Type.STICK ||
controller.getType() == Controller.Type.GAMEPAD ||
controller.getType() == Controller.Type.WHEEL ||
controller.getType() == Controller.Type.FINGERSTICK)
{
// Add new controller to the list of all controllers.
if(!foundControllers.contains(controller))
foundControllers.add(controller);
}
}
} | 6 |
public static boolean equal(List<Partition> listA, List<Partition> listB) {
if (listA.size() != listB.size()) {
return false;
}
for (int index = 0; index < listA.size(); index++) {
Partition a = listA.get(index);
Partition b = listB.get(index);
if ((a.mStart != b.mStart) ||
(a.mEnd != b.mEnd) ||
(a.mLength != b.mLength)) {
return false;
}
}
return true;
} | 5 |
public static void main(String[] args) {
if (args == null || args.length < 2) {
printHelp();
throw new IllegalArgumentException("Minimum 2 file pathes needed");
}
List<String> inputFileNames = new ArrayList<String>();
for (int i = 0; i < args.length - 1; i++ ) {
inputFileNames.add(args[i]);
}
String outputFileName = args[args.length - 1];
FileFormat inputFileFormat = checkFileFormat(inputFileNames);
FileFormat outputFileFormat = checkFileFormat(outputFileName);
if (inputFileFormat == FileFormat.CSV) {
if (outputFileFormat == FileFormat.CSV) {
new TicketService(new CsvReader(), new CsvWriter()).merge(inputFileNames, outputFileName);
} else if (outputFileFormat == FileFormat.XML) {
new TicketService(new CsvReader(), new JdomXmlWriter()).merge(inputFileNames, outputFileName);
} else {
printHelp();
throw new IllegalArgumentException("Output file has unsupported format");
}
} else if (inputFileFormat == FileFormat.XML) {
if (outputFileFormat == FileFormat.XML) {
new TicketService(new StaxReader(), new JdomXmlWriter()).merge(inputFileNames, outputFileName);
} else {
printHelp();
throw new IllegalArgumentException("XML have to merge in XML");
}
} else {
printHelp();
throw new IllegalArgumentException("Input file have invalid format");
}
} | 8 |
private TreeNode Statement() {
TreeNode tmp;
int line = t.lineNumber;
switch (t.id) {
case Constants.ID:
tmp = ExpressionSmt();
break;
case Constants.RETURN:
tmp = Return();
break;
case Constants.READ:
tmp = Read();
break;
case Constants.WRITE:
tmp = Write();
break;
case Constants.IF:
tmp = Selection();
break;
case Constants.WHILE:
tmp = Iteration();
break;
case Constants.LBRACE:
tmp = Compound();
break;
default:
throw new IllegalStateException(
"Unknown Statement Found Token = " + t.toString());
}
tmp.lineNumber = line;
return tmp;
} | 7 |
public void open(String[] onlines) {
if (onlines == null || onlines.length == 0)
return;
DedicatedUI ui = null;
String senderName = fPropertiesDB.getUserName();
String remoteIPAddress = null;
//
// Open only one dedicated window and remained recipients should
// be set into the Additional To: field. [V1.63]
//
int index;
for (index = 0; index < onlines.length; index++) {
remoteIPAddress = fMiscProtocol.probe(senderName, onlines[index]);
if (remoteIPAddress != null) {
ui = findOrCreate(remoteIPAddress, onlines[index]);
//
// Set null to the online recipient in onlines[] so that
// not-null entries means Off-Line.
//
onlines[index] = null;
index++;
break;
}
}
//
// If no online recipient was found, then do nothing.
//
if (ui == null)
return;
//
// If there are still remained onlines, then create a list of them.
//
String additionalTo = null;
for (; index < onlines.length; index ++) {
if (fMiscProtocol.probe(senderName, onlines[index]) != null) {
if (additionalTo == null)
additionalTo = onlines[index];
else
additionalTo += ", " + onlines[index];
onlines[index] = null; // see above
}
}
if(additionalTo != null)
ui.setAdditionalRecipients(additionalTo);
else
ui.setAdditionalRecipients("");
//
// Now make the DedicatedUI visible
//
ui.setVisible(true);
} | 9 |
private String buildFullPath(Class<?> aClass, Method method) {
int modifiers = method.getModifiers();
String modifier = "package-local";
if (Modifier.isPrivate(modifiers)) {
modifier = "private";
} else if (Modifier.isProtected(modifiers)) {
modifier = "protected";
} else if (Modifier.isPublic(modifiers)) {
modifier = "public";
}
String packageName = aClass.getPackage().getName();
String className = aClass.getSimpleName();
String methodName = method.getName();
return String.format("%s:%s:%s:%s", modifier, packageName, className, methodName);
} | 4 |
public static Method getAccessor(Class<?> declaringClass, String accessorname)
{
Method res = null;
if (declaringClass != null)
{
// check this class
try
{
res = declaringClass.getDeclaredMethod(accessorname);
}
catch (NoSuchMethodException e)
{
// do nothing, keep iterating up
}
if (res == null)
{
res = getAccessor(declaringClass.getSuperclass(), accessorname);
}
}
return res;
} | 4 |
private void loadLetterPoints() throws IOException, FileNotFoundException {
BufferedReader in = null;
try {
in = new BufferedReader(new FileReader(POINTS_FILE));
String line;
while((line = in.readLine())!=null){
line = line.trim();
int letterPoint = Integer.parseInt(line.substring(0, 2));
line = line.substring(2);
for(char c : line.toCharArray()){
points.put(new String(new char[]{c}), letterPoint);
}
}
in.close();
} catch (FileNotFoundException e) {
throw new FileNotFoundException();
} catch (IOException e) {
throw new IOException();
} finally {
if (in != null) {
try {
in.close();
} catch (IOException e) {
// ignore
}
}
}
} | 6 |
@Override
public ArrayList<Lot> findLots(Map<String, String> params) {
//проверка, что обязательные поля заполнены
if (!params.containsKey(MechanicSales.findParams.ARRIVAL_AIRPORT) ||
!params.containsKey(MechanicSales.findParams.DEPARTURE_AIRPORT) ||
!params.containsKey(MechanicSales.findParams.DEPARTURE_DATE_TIME_SINCE) ||
!params.containsKey(MechanicSales.findParams.DEPARTURE_DATE_TIME_TO))
return new ArrayList<Lot>();
//формируем основной запрос
//формирование дополнительных условий:
String additional = "";
if (params.containsKey(MechanicSales.findParams.MAX_PRICE))
additional += "and Price <= '" + params.get(MechanicSales.findParams.MAX_PRICE) + "'";
if (params.containsKey(MechanicSales.findParams.MIN_SEAT_CLASS))
additional += " and PlaceClass >= '" + params.get(MechanicSales.findParams.MIN_SEAT_CLASS) + "'";
//заполнение sql скрипта
Map<String, Object> pageVariables = dataToKey(new String [] { "AirportArrival", "AirportDeparture", "TimeDeparture_since", "TimeDeparture_to", "additional"},
params.get(MechanicSales.findParams.ARRIVAL_AIRPORT), params.get(MechanicSales.findParams.DEPARTURE_AIRPORT),
timestampToDatetime(params.get(MechanicSales.findParams.DEPARTURE_DATE_TIME_SINCE)),
timestampToDatetime(params.get(MechanicSales.findParams.DEPARTURE_DATE_TIME_TO)),
additional);
//формирование sql скрипта
String queryString = generateSQL("find_lot.sql", pageVariables);
try {
return execQuery(this.connect, queryString, new TResultHandler<ArrayList<Lot>>() {
@Override
public ArrayList<Lot> handler(ResultSet result) throws SQLException {
if (rowCounts(result) > 0) {
ArrayList<Lot> lots = new ArrayList<Lot>();
while (!result.isLast()) {
result.next();
SingleTicket tempST = new SingleTicket(result.getString("AirportDeparture"), //departureAirport
result.getString("AirportArrival"), //arrivalAirport
datetimeToDate(result.getString("TimeDeparture")), //departureTime
result.getLong("FlightTime"), //flightTime
result.getString("FlightName"), //flightNumber
toSeatClass(result.getLong("PlaceClass")), // seatClass
result.getString("PlaneName"), //planeModel
result.getInt("Price") //price
);
ArrayList<SingleTicket> a = new ArrayList<SingleTicket>();
a.add(tempST);
Ticket ticket = new TicketImp(a, true);
Lot l = new LotImp(ticket, datetimeToDate(result.getString("StartDate")),
datetimeToDate(result.getString("EndDate")), result.getInt("CurrentPrice"));
lots.add(l);
}
return lots;
}
else
return new ArrayList<Lot>();
}
});
} catch (SQLException e) {
e.printStackTrace();
}
return new ArrayList<Lot>();
} | 9 |
public ArrayList<GameObject> getAllAttached()
{
ArrayList<GameObject> result = new ArrayList<GameObject>();
for ( GameObject child : children )
result.addAll( child.getAllAttached() );
result.add( this );
return result;
} | 1 |
public boolean posNeg(int a, int b, boolean negative) {
if ( a<0 && b<0 && negative) return true;
if ( ( ( a<0 && b>0 ) || ( a>0 && b<0 ) ) && !negative ) return true;
return false;
} | 8 |
public String toString()
{
String res = "";
for (int i = 0; i < this.hauteur; i++)
{ // Parcours le premier tableau
for (int j = 0; j < this.largeur; j++)
{ // Parcours le second tableau
switch (this.background[i][j])
{
case MUR : res = res +"M"; break;
case HERBE : res = res +"H"; break;
case ROUTE : res = res +"R"; break;
case TERRE : res = res +"T"; break;
case TOWER : res = res +"O"; break;
case UNITE : res = res +"X"; break;
case QG : res = res + "G"; break;
}
res = res + " ";
}
res = res + "\n"; // Permet de revenir à la ligne au moment de passer à la ligne suivante du tableau
}
return res;
} | 9 |
public static void main(String[] args) throws IOException {
Scanner scan = new Scanner(System.in);
w: while (scan.hasNext()) {
int n = -1, con = 0;
boolean[] a = new boolean[101];
Arrays.fill(a, false);
ArrayList<Integer> ll = new ArrayList<Integer>();
HashSet<Integer> set = new HashSet<Integer>();
while ((n = scan.nextInt()) != 0) {
if (n == -1)
break w;
ll.add(n);
set.add(n);
}
Collections.sort(ll);
for (int i = ll.size() - 1; i >= 0; i--) {
n = ll.get(i);
if (n % 2 == 0 && set.contains(n / 2))
con++;
}
System.out.println(con);
}
} | 6 |
@Override
public EntidadBancaria get(int id) {
PreparedStatement preparedStatement;
EntidadBancaria entidadBancaria;
ResultSet resultSet;
Connection connection = connectionFactory.getConnection();
try {
preparedStatement = connection.prepareStatement("SELECT * FROM entidadbancaria WHERE idEntidadBancaria = ?");
preparedStatement.setInt(1, id);
resultSet = preparedStatement.executeQuery();
if (resultSet.next()) {
entidadBancaria = new EntidadBancaria();
entidadBancaria.setNombre(resultSet.getString("nombre"));
entidadBancaria.setFechaCreacion(resultSet.getDate("fechaCreacion"));
entidadBancaria.setCodigoEntidad(resultSet.getString("codigoEntidad"));
entidadBancaria.setIdEntidad(resultSet.getInt("idEntidadBancaria"));
if (resultSet.next()) {
throw new RuntimeException("Devuelve mas de una fila");
}
} else {
entidadBancaria = null;
}
} catch (SQLException ex) {
throw new RuntimeException(ex);
}
connectionFactory.closeConnection();
return entidadBancaria;
} | 3 |
public String toString()
{
StringBuilder sb = new StringBuilder();
sb.append("N: ");
sb.append(N);
sb.append("\tP: ");
sb.append(p);
sb.append("\tQ: ");
sb.append(q);
sb.append("\n");
for(int i = 0; i < N; ++i)
{
for(int j = 0; j < N; ++j)
{
sb.append(Odometer.intToOdometer(board[i][j]) + " ");
// Print gridlines
if((j + 1) % q == 0 && j != 0 && j != N-1)
{
sb.append("| ");
}
}
sb.append("\n");
// Print gridlines
if((i + 1) % p == 0 && i != 0 && i != N-1)
{
for(int k = 0; k < N+p-1; ++k)
{
sb.append("- ");
}
sb.append("\n");
}
}
return sb.toString();
} | 9 |
private static String[] formatEmpty(){
String[] cards = new String[60];
for(int i=0; i<60; i++){
cards[i]="Forest";
}
return cards;
} | 1 |
private void calculatePosition(){
nx = Math.cos(Math.toRadians(moveAngle));
ny = Math.sin(Math.toRadians(moveAngle));
x+=speed*nx;
y+=speed*ny;
if(x>MainWindow.WIDTH) x = -getWidth();
if(y>MainWindow.HEIGHT) y = -getHeight();
if(x+getWidth()<0) x = MainWindow.WIDTH;
if(y+getHeight()<0) y = MainWindow.HEIGHT;
} | 4 |
private static void setDefaultLookAndFeel(){
try {
for (LookAndFeelInfo info : UIManager.getInstalledLookAndFeels()) {
if ("Nimbus".equals(info.getName())) {
UIManager.setLookAndFeel(info.getClassName());
break;
}
}
} catch (UnsupportedLookAndFeelException e) {
getDebugWindow().printError("NimbusLookAndFeel was unable to be loaded, unsuported");
criticalError(e);
} catch (ClassNotFoundException e) {
getDebugWindow().printError("NimbusLookAndFeel was unable to be loaded, class not found");
criticalError(e);
} catch (InstantiationException e) {
getDebugWindow().printError("NimbusLookAndFeel was unable to be loaded, instantiation");
criticalError(e);
} catch (IllegalAccessException e) {
getDebugWindow().printError("NimbusLookAndFeel was unable to be loaded, illegalaccess");
criticalError(e);
} catch (Exception e) {
getDebugWindow().printError("NimbusLookAndFeel has encountered an error, " + e.getMessage());
criticalError(e);
} catch (Error e) {
getDebugWindow().printError("NimbusLookAndFeel has encountered an error, " + e.getMessage());
criticalError(e);
} catch (Throwable thr) {
getDebugWindow().printError("NimbusLookAndFeel has encountered an error, " + thr.getMessage());
criticalError(thr);
}
} | 9 |
private boolean fsk2001000FreqHalf (CircularDataBuffer circBuf,WaveData waveData,int pos) {
boolean out;
int sp=(int)samplesPerSymbol/2;
// First half
double early[]=do64FFTHalfSymbolBinRequest (circBuf,pos,sp,lowBin,highBin);
// Last half
double late[]=do64FFTHalfSymbolBinRequest (circBuf,(pos+sp),sp,lowBin,highBin);
// Feed the early late difference into a buffer
if ((early[0]+late[0])>(early[1]+late[1])) addToAdjBuffer(getPercentageDifference(early[0],late[0]));
else addToAdjBuffer(getPercentageDifference(early[1],late[1]));
// Calculate the symbol timing correction
symbolCounter=adjAdjust();
// Now work out the binary state represented by this symbol
double lowTotal=early[0]+late[0];
double highTotal=early[1]+late[1];
if (theApp.isInvertSignal()==false) {
if (lowTotal>highTotal) out=false;
else out=true;
}
else {
// If inverted is set invert the bit returned
if (lowTotal>highTotal) out=true;
else out=false;
}
// Is the bit stream being recorded ?
if (theApp.isBitStreamOut()==true) {
if (out==true) theApp.bitStreamWrite("1");
else theApp.bitStreamWrite("0");
}
return out;
} | 6 |
public static String encode(String value) {
String encoded = null;
try {
encoded = URLEncoder.encode(value, "UTF-8");
} catch (UnsupportedEncodingException ignore) {
}
StringBuffer buf = new StringBuffer(encoded.length());
char focus;
for (int i = 0; i < encoded.length(); i++) {
focus = encoded.charAt(i);
if (focus == '*') {
buf.append("%2A");
} else if (focus == '+') {
buf.append("%20");
} else if (focus == '%' && (i + 1) < encoded.length()
&& encoded.charAt(i + 1) == '7' && encoded.charAt(i + 2) == 'E') {
buf.append('~');
i += 2;
} else {
buf.append(focus);
}
}
return buf.toString();
} | 8 |
public Hunter(Field field, Location newLocation)
{
this.field = field;
setLocation(newLocation);
} | 0 |
protected void renderContinuousSegment() {
/* A lazy but effective line drawing algorithm */
final int dX = points[1].x - points[0].x;
final int dY = points[1].y - points[0].y;
int absdX = Math.abs(dX);
int absdY = Math.abs(dY);
if ((dX == 0) && (dY == 0)) return;
if (absdY > absdX) {
final int incfpX = (dX << 16) / absdY;
final int incY = (dY > 0) ? 1 : -1;
int fpX = points[0].x << 16; // X in fixedpoint format
while (--absdY >= 0) {
points[0].y += incY;
points[0].x = (fpX += incfpX) >> 16;
render(points[0]);
}
if (points[0].x == points[1].x) return;
points[0].x = points[1].x;
} else {
final int incfpY = (dY << 16) / absdX;
final int incX = (dX > 0) ? 1 : -1;
int fpY = points[0].y << 16; // Y in fixedpoint format
while (--absdX >= 0) {
points[0].x += incX;
points[0].y = (fpY += incfpY) >> 16;
render(points[0]);
}
if (points[0].y == points[1].y) return;
points[0].y = points[1].y;
}
render(points[0]);
} | 9 |
protected void processRequest(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
HttpSession session = request.getSession();
if(session != null){
String sleeveInput = (String) session.getAttribute("sleeveInput");
String openedPacks = request.getParameter("openedPacks");
if (sleeveInput == null || sleeveInput.replaceAll("[^1-5\\-]", "").length() != 38){
writeResponse(response, "{\"error\" : \"selectSleeves\"}");
return;
} else {
try {
api = new BoxMappingApi("GTC");
} catch (Throwable ex) {
writeResponse(response, "{\"error\" : \"setIsNotRecognised\"}");
return;
}
api.setSleeves(sleeveInput);
//api.setSleeves("123452534123-315241452315-534123241534");
}
if(openedPacks != null && !openedPacks.isEmpty()){
String[] packs = openedPacks.split("\n");
for (int i = 0; i < packs.length; i++) {
boolean hasNext = !(i == packs.length- 1);
String[] packInfo = packs[i].split("-");
if (packInfo.length != 2) {
System.out.println("Invalid opened pack info. Discarding " + packs[i] + ", example: L03-SoulRansom");
} else {
try{
api.selectCard(packInfo[0], packInfo[1], hasNext);
} catch (Exception e){
writeResponse(response, "{\"error\" : \"invalidEntryOrWrongRow\"}");
return;
}
}
}
}
writeResponse(response, api.jsonShowAll());
}
} | 9 |
public User(Socket s) throws IOException {
socket = s;
in = new BufferedReader(new InputStreamReader(socket.getInputStream()));
// Включение автосброса буферов:
out = new PrintWriter(new BufferedWriter(new OutputStreamWriter(
socket.getOutputStream())), true);
port = socket.getPort();
// Если какой либо, указанный выше класс выбросит исключение
// вызывающая процедура ответственна за закрытие сокета
// В противном случае нить(поток) закроет его.
start(); // Вызывает run()
UserList.add_user(port, this);
} | 0 |
public void render() {
root.renderAll();
for(GUI gui:guiLayer){
gui.render();
}
} | 1 |
@Override
public void out() throws Exception {
Object val = fa.getFieldValue();
// Object val = access;
// if (ens.shouldFire()) {
// DataflowEvent e = new DataflowEvent(ens.getController(), this, val);
//// DataflowEvent e = new DataflowEvent(ens.getController(), this, access.toObject());
// ens.fireOut(e);
// // the value might be altered
// val = e.getValue();
// }
// if data==null this unconsumed @Out, its OK but we do not want to set it.
if (fa.getData() != null) {
fa.getData().setValue0(val);
}
fa.out();
} | 1 |
public Renderer.CommandHandler getHandler(String symbol) {
if (handlers.containsKey(symbol))
return (CommandHandler) handlers.get(symbol);
return null;
} | 1 |
private static boolean isWhitespace(char c)
{
return c == ' ' || c == '\t' || c == '\r' || c == '\n';
} | 3 |
private void bindTexture(int texId) {
if (texId == boundTex) {
return;
}
glBindTexture(GL_TEXTURE_2D, texId);
boundTex = texId;
} | 1 |
public void visitInsn(final int opcode){
// adds the instruction to the bytecode of the method
code.putByte(opcode);
// update currentBlock
// Label currentBlock = this.currentBlock;
if(currentBlock != null)
{
if(compute == FRAMES)
{
currentBlock.frame.execute(opcode, 0, null, null);
}
else
{
// updates current and max stack sizes
int size = stackSize + Frame.SIZE[opcode];
if(size > maxStackSize)
{
maxStackSize = size;
}
stackSize = size;
}
// if opcode == ATHROW or xRETURN, ends current block (no successor)
if((opcode >= Opcodes.IRETURN && opcode <= Opcodes.RETURN)
|| opcode == Opcodes.ATHROW)
{
noSuccessor();
}
}
} | 6 |
public static String[] getIDs(Connection con, TableInfo tableInfo)
{
ArrayList<String> data = new ArrayList<String>();
try
{
PreparedStatement ps = con.prepareStatement("SELECT ID FROM " + tableInfo.tableName);
ResultSet rs = ps.executeQuery();
while (rs.next())
data.add(rs.getString("ID"));
rs.close();
}
catch (SQLException sqle)
{
if (sqle.getSQLState().equals("42X05"))
{
createTable(con, tableInfo);
}
else
{
System.out.println(sqle);
System.out.println("Incorrect table definition. Drop table "
+ tableInfo.tableName + " and rerun this program");
System.exit(0);
}
}
return (String[]) data.toArray(new String[data.size()]);
} | 3 |
public Object render(Scope scope, Statement statement, int tokenIndex)
throws PoslException {
switch (state) {
case NORMAL:
case OPTIONAL:
return scope.get(type, statement.get(tokenIndex));
case CONTEXT_PROPERTY:
return scope.get((String) parameter);
case SCOPE:
return scope;
// Collection is a special case which takes a Collection
// object and
// adds all the remaining arguments into that collection
case COLLECTION:
try {
Object list = type.getClass().newInstance();
ParameterizedType parameterizedType = (ParameterizedType) type
.getClass().getGenericSuperclass();
Type generic = parameterizedType.getActualTypeArguments()[0];
Method add = Collection.class.getDeclaredMethod("add",
Object.class);
for (int index = tokenIndex; index < statement.size(); ++index) {
add.invoke(list, scope.get(generic, statement.get(index)));
}
} catch (Exception e) {
throw new PoslException(statement.startPos(),
"failed to get COLLECTION");
}
case REFERENCE:
return new Reference(statement.get(tokenIndex), scope);
}
return null;
} | 8 |
public SlotType(String type) {
reward = new HashMap<ItemStack,Integer>();
fireworks = new HashMap<ItemStack,Integer>();
wrg = new WeightedRandomGenerator();
String typeNode = "types."+type;
String rewardNode = typeNode+".reward";
cost = Global.config().getInt(typeNode + ".cost");
Set<String> keys = null;
keys = Global.config().getConfigurationSection(rewardNode).getKeys(false);
for(String k : keys) {
String[] data = k.split(",");
ItemStack match = null;
if(data.length < 2) break;
if(data.length == 2) match = new ItemStack(Integer.parseInt(data[0]),1,Short.parseShort(data[1]));
reward.put(match,Global.config().getInt(rewardNode+"."+k+".money"));
fireworks.put(match,Global.config().getInt(rewardNode+"."+k+".fireworks"));
cmds.put(match,new ArrayList<String>(Global.config().getStringList(rewardNode+"."+k+".cmd")));
}
for(Integer w : Global.config().getIntegerList(typeNode+".items")) {
for(String s: Global.config().getStringList(typeNode+".items."+w)) {
String[] data = s.split(",");
ItemStack i = null;
if(data.length < 2) break;
if(data.length == 2) i = new ItemStack(Integer.parseInt(data[0]),1,Short.parseShort(data[1]));
wrg.add(i, w);
}
}
} | 7 |
public GUIChat(DataInputStream in, DataOutputStream out, RequestChatHandler rq, ComingRequestChatHandler commingRq) {
setResizable(false);
this.rq = rq;
this.commingRq = commingRq;
read = in;
write = out;
fc = new JFileChooser();
setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
setBounds(100, 100, 521, 520);
contentPane = new JPanel();
contentPane.setBorder(new EmptyBorder(5, 5, 5, 5));
setContentPane(contentPane);
contentPane.setLayout(null);
JScrollPane scrollPane = new JScrollPane();
scrollPane.setBounds(10, 48, 495, 321);
contentPane.add(scrollPane);
txtBoard = new JTextArea();
txtBoard.setEditable(false);
scrollPane.setViewportView(txtBoard);
JScrollPane scrollPane_1 = new JScrollPane();
scrollPane_1.setBounds(10, 396, 398, 84);
contentPane.add(scrollPane_1);
txtBox = new JTextArea();
txtBox.addKeyListener(this);
scrollPane_1.setViewportView(txtBox);
btnSend = new JButton("Send");
btnSend.addActionListener(this);
btnSend.setBounds(418, 415, 87, 47);
contentPane.add(btnSend);
JMenuBar menuBar = new JMenuBar();
menuBar.setBounds(0, 0, 456, 21);
contentPane.add(menuBar);
JMenu mnSetting = new JMenu("File");
menuBar.add(mnSetting);
menuSendFile = new JMenuItem("Send File");
menuSendFile.addActionListener(this);
mnSetting.add(menuSendFile);
} | 0 |
public String addingYear(String field, int before, int max)
{
String newField = "";
for(int i = 1; i <= field.length(); i++)
{
if(isNumber(field.substring(i - 1, i)))
{
newField = newField + field.substring(i - 1, i);
}
else
{
newField = "~invalid~";
break;
}
boolean over = false;
try
{
if(Integer.parseInt(newField) > (max - before))
{
over = true;
}
}catch(Exception e)
{
System.out.println("not a integer");
}
if(over)
{
System.out.println(newField + " > " + max);
newField = "~invalid over~";
break;
}
}
boolean under = false;
try
{
if(Integer.parseInt(newField) < 0)
{
under = true;
}
}catch(Exception e)
{
System.out.println("not a integer");
}
if(under)
{
newField = "~invalid under~";
}
newField = " ADD " + newField;
return newField;
} | 8 |