method_id stringlengths 36 36 | cyclomatic_complexity int32 0 9 | method_text stringlengths 14 410k |
|---|---|---|
88ec9300-ab87-4ebb-9c4e-1240e5a3fe3f | 8 | public boolean camposobrigatoriospreenchidos() {
if (TfCodFuncionario.getText().equals("") || TfFuncionario.getText().equals("")) {
msg.CampoObrigatorioNaoPreenchido(LbNotificacao, "Informe qual funcionário realizou o atendimento nesta venda!");
TfCodFuncionario.grabFocus();
return false;
}
if (TfCodCliente.getText().equals("") || TfCliente.getText().equals("")) {
msg.CampoObrigatorioNaoPreenchido(LbNotificacao, "Informe qual cliente está realizando a venda!");
TfCodCliente.grabFocus();
return false;
}
if (TfCodCondicaoPgto.getText().equals("") || TfCondicaoPgto.getText().equals("")) {
msg.CampoObrigatorioNaoPreenchido(LbNotificacao, "Informe qual a condição de pagamento escolhida pelo cliente!");
TfCodCondicaoPgto.grabFocus();
return false;
}
if (TbVenda.getRowCount() == 0 && TbVendaServ.getRowCount() == 0) {
msg.CampoObrigatorioNaoPreenchido(LbNotificacao, "Insira os produtos ou serviços desta venda!");
TfCodProduto.grabFocus();
return false;
}
return true;
} |
55f3eaea-7b06-4fee-84de-ef087723e5ab | 7 | void processKeyReleased(KeyEvent e) {
getModel().runKeyScript(KeyEvent.KEY_RELEASED, e.getKeyCode());
boolean b = false;
switch (e.getKeyCode()) {
case KeyEvent.VK_UP:
keyPressedCode = keyPressedCode ^ UP_PRESSED;
b = true;
break;
case KeyEvent.VK_DOWN:
keyPressedCode = keyPressedCode ^ DOWN_PRESSED;
b = true;
break;
case KeyEvent.VK_LEFT:
keyPressedCode = keyPressedCode ^ LEFT_PRESSED;
b = true;
break;
case KeyEvent.VK_RIGHT:
keyPressedCode = keyPressedCode ^ RIGHT_PRESSED;
b = true;
break;
}
if (b) {
processUserFieldsUponKeyOrMouseReleased();
}
if (getModel().getJob() == null || getModel().getJob().isStopped())
repaint();
// MUST not consume this event and leave this to the key binding to work. As a result, key binding
// must set KeyStroke with onKeyRelease flag set to true.
// if(hasFocus()) e.consume();
} |
ef3c72fc-1b65-44fd-aed7-e7bf5d4094d7 | 9 | private void initFileActions()
{
copyToOption.addActionListener(new ActionListener()
{
@Override
public void actionPerformed(ActionEvent e)
{
JFileChooser fileChooser = new JFileChooser();
fileChooser.setFileSelectionMode(JFileChooser.DIRECTORIES_ONLY);
// Return value will be JFileChooser.APPROVE_OPTION iff a folder was chosen. Any
// other value means the window was closed
int returnVal = fileChooser.showOpenDialog(null);
// We're a go
if(returnVal == JFileChooser.APPROVE_OPTION)
{
new GuiController().copyTo(MainFrame.getInstance().selectedFile,
fileChooser.getSelectedFile().toPath());
}
}
});
revisionsOption.addActionListener(new ActionListener()
{
@Override
public void actionPerformed(ActionEvent e)
{
RevisionDialog revisionWindow = new RevisionDialog(
FileOp.convertPath(MainFrame.getInstance().selectedFile));
revisionWindow.setLocationRelativeTo(MainFrame.getInstance());
revisionWindow.setModalityType(ModalityType.APPLICATION_MODAL);
revisionWindow.setVisible(true);
}
});
restoreAllOption.addActionListener(new ActionListener()
{
@Override
public void actionPerformed(ActionEvent e)
{
JFileChooser fileChooser = new JFileChooser();
fileChooser.setFileSelectionMode(JFileChooser.DIRECTORIES_ONLY);
// Return value will be JFileChooser.APPROVE_OPTION iff a folder was chosen. Any
// other value means the window was closed
int returnVal = fileChooser.showOpenDialog(null);
// We're a go
if(returnVal == JFileChooser.APPROVE_OPTION)
{
new GuiController().restoreBackup(fileChooser.getSelectedFile().toPath());
JOptionPane.showMessageDialog(MainFrame.getInstance(),
"All files in the backup directory have been restored to "
+ fileChooser.getSelectedFile().toString());
}
}
});
changeBackupDirOption.addActionListener(new ActionListener()
{
@Override
public void actionPerformed(ActionEvent e)
{
JFileChooser fileChooser = new JFileChooser();
fileChooser.setFileSelectionMode(JFileChooser.DIRECTORIES_ONLY);
// Return value will be JFileChooser.APPROVE_OPTION iff a folder was chosen. Any
// other value means the window was closed
int returnVal = fileChooser.showOpenDialog(null);
// We're a go
if(returnVal == JFileChooser.APPROVE_OPTION)
{
Path chosenPath = fileChooser.getSelectedFile().toPath();
// We must make sure that the selected path isn't a child of the live directory
// or vice versa
if(!chosenPath.startsWith(Main.liveDirectory)
&& !Main.liveDirectory.startsWith(chosenPath))
{
new GuiController().changeBackupDirectory(fileChooser.getSelectedFile().toPath());
}
else
{
JOptionPane.showMessageDialog(MainFrame.getInstance(),
"Backup directory cannot be a child of the live directory and vice versa.");
}
}
}
});
changeLiveDirOption.addActionListener(new ActionListener()
{
@Override
public void actionPerformed(ActionEvent e)
{
JFileChooser fileChooser = new JFileChooser();
fileChooser.setFileSelectionMode(JFileChooser.DIRECTORIES_ONLY);
// Return value will be JFileChooser.APPROVE_OPTION iff a folder was chosen. Any
// other value means the window was closed
int returnVal = fileChooser.showOpenDialog(null);
// We're a go
if(returnVal == JFileChooser.APPROVE_OPTION)
{
Path chosenPath = fileChooser.getSelectedFile().toPath();
// We must make sure that the selected path isn't a child of the live directory
// or vice versa
if(!chosenPath.startsWith(Main.backupDirectory)
&& !Main.backupDirectory.startsWith(chosenPath))
{
new GuiController().changeLiveDirectory(fileChooser.getSelectedFile().toPath());
MainFrame.getInstance().redrawTable(Main.liveDirectory);
}
else
{
JOptionPane.showMessageDialog(MainFrame.getInstance(),
"Live directory cannot be a child of the live directory and vice versa.");
}
}
}
});
settingsOption.addActionListener(new ActionListener()
{
@Override
public void actionPerformed(ActionEvent e)
{
// Create the setting dialog, position it in the center of the current window, and
// lock the current window while the settings window is open.
SettingsDialog settingsDialog = new SettingsDialog();
settingsDialog.setLocationRelativeTo(MainFrame.getInstance());
settingsDialog.setModalityType(ModalityType.APPLICATION_MODAL);
settingsDialog.setVisible(true);
}
});
exitOption.addActionListener(new ActionListener()
{
@Override
public void actionPerformed(ActionEvent e)
{
int choice = JOptionPane.showConfirmDialog(MainFrame.getInstance(),
"Are you sure you want to quit?", "Confirmation", JOptionPane.YES_NO_OPTION);
if(choice == JOptionPane.YES_OPTION)
{
System.exit(0);
}
}
});
} |
1c966fe3-ded0-4ef7-ba9c-c97070248b32 | 3 | @Override
public void run() {
BackupFile file = DistributedBackupSystem.fManager.getFileByName(filename);
int curChunk=0;
if(file != null) {
System.out.println("File exists");
for(curChunk=0;curChunk<file.getNumChunks();curChunk++) {
try {
DistributedBackupSystem.tManager.executeTask(TaskManager.TaskTypes.RESTORECHUNK, file.getFileID(), curChunk).get();
} catch (Exception e) {e.printStackTrace();}
}
}
} |
f4f7bd79-abab-4415-9dc9-ddf382d9e4d1 | 7 | @Override
public void deserialize(Buffer buf) {
houseId = buf.readInt();
if (houseId < 0)
throw new RuntimeException("Forbidden value on houseId = " + houseId + ", it doesn't respect the following condition : houseId < 0");
modelId = buf.readShort();
if (modelId < 0)
throw new RuntimeException("Forbidden value on modelId = " + modelId + ", it doesn't respect the following condition : modelId < 0");
worldX = buf.readShort();
if (worldX < -255 || worldX > 255)
throw new RuntimeException("Forbidden value on worldX = " + worldX + ", it doesn't respect the following condition : worldX < -255 || worldX > 255");
worldY = buf.readShort();
if (worldY < -255 || worldY > 255)
throw new RuntimeException("Forbidden value on worldY = " + worldY + ", it doesn't respect the following condition : worldY < -255 || worldY > 255");
mapId = buf.readInt();
subAreaId = buf.readShort();
if (subAreaId < 0)
throw new RuntimeException("Forbidden value on subAreaId = " + subAreaId + ", it doesn't respect the following condition : subAreaId < 0");
} |
c76d07df-9264-443a-8401-401b7e520ee8 | 4 | public void update() {
key.update();
if (key.up) y++;
if (key.down) y--;
if (key.left) x++;
if (key.right) x--;
} |
508b5e94-dbe5-4af7-a377-082ad218a20f | 6 | public void printShuffle(Graphics g) {
int q = 0;
int z = 250;
String name = null;
//basically the same code, just using the shuffled deck
for (int i = 0; i < deck.length; i++) {
if (deck[i].cardValue == 1) {
name = "A" + deck[i].suit;
} else if (deck[i].cardValue == 11) {
name = "J" + deck[i].suit;
} else if (deck[i].cardValue == 12) {
name = "Q" + deck[i].suit;
} else if(deck[i].cardValue == 13) {
name = "K" + deck[i].suit;
} else {
name = deck[i].cardValue + deck[i].suit;
}
poster = new MoviePoster(name);
if(q > 1000) {
q = 0;
z += 75;
}
Rectangle b = new Rectangle(q,z,50,75);
poster.draw(g,b);
q += 50;
}
} |
235ac7c8-7582-4bf6-86a3-10f1a82a3d78 | 4 | public synchronized static void deletePoll(String id, String mail) {
try {
XStream xstream = new XStream(new DomDriver());
File remFile = new File((String) Server.prop.get("pollFilePath"));
Polls[] allPolls = (Polls[]) xstream.fromXML(remFile);
List<Polls> retList = new ArrayList<Polls>(Arrays.asList(allPolls));
for (int i = 0; i < allPolls.length; i++) {
if (allPolls[i].getId().equals(id) && allPolls[i].getCreator().equals(mail)) {
retList.remove(i);
}
}
FileOutputStream fos = new FileOutputStream(remFile);
xstream.toXML(retList.toArray(new Polls[0]), fos);
fos.close();
} catch (Exception e) {
}
} |
a2069510-358f-4c4f-8030-ecb20021ca1a | 6 | protected long toLong(Object value) {
long number;
if (value instanceof Long) {
number = (Long) value;
} else if (value instanceof Integer) {
number = ((Integer) value).longValue();
} else if (value instanceof Short) {
number = ((Short) value).longValue();
} else if (value instanceof Byte) {
number = ((Byte) value).longValue();
} else if (value instanceof BigDecimal) {
number = ((BigDecimal) value).longValue();
} else if (value instanceof BigInteger) {
number = ((BigInteger) value).longValue();
} else {
throw new IllegalArgumentException("Type is not considered supported by @" + baseAnnotation.getSimpleName() + ": " + value.getClass().toString());
}
return number;
} |
3f289e5b-568d-4493-9557-4cbc063baa51 | 1 | public void printList(){
System.out.println("Name: " + this.name + ", Age: " + this.age + ", Illness: " + this.illness);
if (nextPatient != patientListStart){
nextPatient.printList();
}
} |
bd882f3c-79d1-47c2-9b51-489cdb888a49 | 7 | @Override
public void actionPerformed(ActionEvent e) {
if (e.getSource() == btnCreate) {
int amount = 0;
try {
amount = Integer.parseInt(txfAmount.getText().trim());
}
catch (NumberFormatException ex) {
JOptionPane.showMessageDialog(TraysCDialog.this,
"Please enter a valid number for the amount. ",
"Error", JOptionPane.ERROR_MESSAGE);
return;
}
ProductType productType = (ProductType) lstProduct
.getSelectedValue();
Stock stock = (Stock) lstStock.getSelectedValue();
if (productType != null && stock != null && amount > 0) {
try {
Service.createTrays(productType, stock, amount);
JOptionPane.showMessageDialog(TraysCDialog.this, amount
+ " trays were created and deposited at "
+ stock.getName() + ". ", "Created",
JOptionPane.INFORMATION_MESSAGE);
setVisible(false);
}
catch (OutOfStockSpaceException ex) {
JOptionPane.showMessageDialog(TraysCDialog.this,
ex.getMessage(), "Error",
JOptionPane.ERROR_MESSAGE);
}
catch (InconsistencyException ex) {
JOptionPane.showMessageDialog(TraysCDialog.this,
ex.getMessage(), "Error",
JOptionPane.ERROR_MESSAGE);
}
}
}
} |
0a378eaf-277d-46f1-b51b-f7a97a9f9f32 | 4 | public void delete(T t) {
for(ListNode<T> node=head; node!=null&&node.next!=null; node=node.next) {
ListNode<T> nextNode = node.next;
if(nextNode.value.equals(t)) {
if(nextNode == tail) {
tail = node;
tail.next = null;
} else {
node.next = node.next.next;
}
}
}
} |
47af0530-be09-4220-8232-86fb4a57f685 | 6 | @EventHandler(ignoreCancelled = true)
public void onSignChange(final SignChangeEvent change) {
if (!change.getPlayer().hasPermission("kiosk.create")) return;
final Sign state = (Sign) change.getBlock().getState();
for (int i = 0; i < change.getLines().length; i++)
state.setLine(i, change.getLines()[i]);
for (final Kiosk kiosk : this.kiosks)
if (kiosk.hasTrigger(state)) {
if (kiosk.create(change.getPlayer(), state))
for (int i = 0; i < state.getLines().length; i++)
change.setLine(i, state.getLines()[i]);
return;
}
} |
7d2aa49b-ddd5-489f-898c-7edbbc4f7391 | 7 | public static void initCells() throws IOException
{
GameConverter.cellStrings = new String[48];
GameConverter.cellStrings[0] = "WATER_UPLEFT_UP_UPRIGHT_LEFT_RIGHT_DOWNLEFT_DOWN_DOWNRIGHT";
GameConverter.cellStrings[1] = "WATER_UPLEFT_UP_UPRIGHT_LEFT_RIGHT_DOWNLEFT_DOWN_DOWNRIGHT_SPARKS";
GameConverter.cellStrings[3] = "WATER_UPLEFT_UP_LEFT_DOWNLEFT_DOWN";
GameConverter.cellStrings[4] = "WATER_UPLEFT_UP_UPRIGHT_LEFT";
GameConverter.cellStrings[5] = "WATER_UPLEFT_UP_UPRIGHT_LEFT_RIGHT_DOWNLEFT_DOWN";
GameConverter.cellStrings[6] = "WATER_UPLEFT_UP_UPRIGHT_LEFT_RIGHT";
GameConverter.cellStrings[7] = "WATER_UPLEFT_UP_UPRIGHT_LEFT_RIGHT_DOWN_DOWNRIGHT";
GameConverter.cellStrings[8] = "WATER_UPLEFT_UP_UPRIGHT_RIGHT";
GameConverter.cellStrings[9] = "WATER_UP_UPRIGHT_RIGHT_DOWN_DOWNRIGHT";
GameConverter.cellStrings[10] = "WATER_UPLEFT_UP_LEFT_RIGHT_DOWNLEFT_DOWN_DOWNRIGHT";
GameConverter.cellStrings[11] = "WATER_LEFT_RIGHT_DOWNLEFT_DOWN_DOWNRIGHT";
GameConverter.cellStrings[12] = "WATER_UP_UPRIGHT_LEFT_RIGHT_DOWNLEFT_DOWN_DOWNRIGHT";
GameConverter.cellStrings[13] = "WATER_UPLEFT_LEFT_DOWNLEFT_DOWN";
GameConverter.cellStrings[14] = "WATER_UPRIGHT_RIGHT_DOWNLEFT_DOWN_DOWNRIGHT";
GameConverter.cellStrings[15] = "THREE_TREES";
GameConverter.cellStrings[16] = "TWO_TREES";
GameConverter.cellStrings[17] = "MOUNT";
GameConverter.cellStrings[18] = "PLAIN";
GameConverter.cellStrings[19] = "HILL";
GameConverter.cellStrings[20] = "WAY_LEFT_RIGHT";
GameConverter.cellStrings[21] = "WAY_DOWN_UP";
GameConverter.cellStrings[22] = "WAY_LEFT_RIGHT_DOWN_UP";
GameConverter.cellStrings[23] = "WAY_LEFT_DOWN";
GameConverter.cellStrings[24] = "WAY_LEFT_UP";
GameConverter.cellStrings[25] = "WAY_RIGHT_UP";
GameConverter.cellStrings[26] = "WAY_RIGHT_DOWN";
GameConverter.cellStrings[27] = "BUILDING";
GameConverter.cellStrings[29] = "WATER_WAY_HORIZONTAL";
GameConverter.cellStrings[30] = "WATER_WAY_VERTICAL";
GameConverter.cellStrings[31] = "CAMP";
GameConverter.cellStrings[32] = "TEMPLE";
GameConverter.cellStrings[33] = "CITADEL_LEFT";
GameConverter.cellStrings[34] = "CITADEL";
GameConverter.cellStrings[35] = "CITADEL_RIGHT";
GameConverter.cellStrings[36] = "CITADEL_UP";
GameConverter.cellStrings[37] = "BUILDING";
GameConverter.cellStrings[38] = "CASTLE";
GameConverter.cellStrings[39] = "BUILDING";
GameConverter.cellStrings[40] = "CASTLE";
GameConverter.cellStrings[41] = "BUILDING";
GameConverter.cellStrings[42] = "CASTLE";
GameConverter.cellStrings[43] = "BUILDING";
GameConverter.cellStrings[44] = "CASTLE";
GameConverter.cellStrings[45] = "BUILDING";
GameConverter.cellStrings[46] = "CASTLE";
if (false)
{
Document infoDocument = XMLHelper.getDocumentFromZipPath(Client.imagesZipFile, "cells/info.xml");
NodeList images = infoDocument.getElementsByTagName("image");
String defaultImagesFolder = XMLHelper.getOneNode(infoDocument, "default_images_folder").getTextContent();
MyAssert.a(images.getLength() == CellType.number);
int typeAmount = CellType.number;
for (int i = 0; i < typeAmount; i++)
{
Node node = images.item(i);
String typeName = XMLHelper.getNodeAttributeValue(node, "type");
CellType type = CellType.getType(typeName);
String imageName = XMLHelper.getNodeAttributeValue(node, "image");
InputStream is = ZIPHelper.getIS(Client.imagesZipFile, "cells/" + defaultImagesFolder + imageName);
BufferedImage image = ImageIO.read(is);
for (int j = 0; j < 47; j++)
{
String name = "C:\\Projects\\AE\\tiles\\tiles0_" + (j < 10 ? "0" + j : j) + ".png";
BufferedImage image2 = ImageIO.read(new File(name));
if (GameConverter.imagesEquals(image, image2))
GameConverter.cellStrings[j] = typeName;
}
}
for (int i = 0; i < GameConverter.cellStrings.length; i++)
if (GameConverter.cellStrings[i] != null)
System.out.println("cellStrings[" + i + "] = \"" + GameConverter.cellStrings[i] + "\";");
}
} |
90cbf89e-8a86-4a96-8809-d3108bd818e2 | 0 | public Reserve getPieces() {
return pieces;
} |
bec38ca3-6a04-4b6b-9f8c-8a54ae2d380b | 2 | public boolean Exist(String Tea_ID, String PassCode) {
try {
StringBuffer sql = new StringBuffer();
sql.append(" select * from teacher where");
sql.append(" tea_ID='");
sql.append(Tea_ID);
sql.append("' && teacher_Passcode='");
sql.append(PassCode);
sql.append("';");
SQLHelper sqlHelper = new SQLHelper();
sqlHelper.sqlConnect();
ResultSet rs = sqlHelper.runQuery(sql.toString());
if (rs.next()) {
return true;
}
} catch (SQLException ex) {
Logger.getLogger(Student_DAO.class.getName()).log(Level.SEVERE, null, ex);
return false;
}
return false;
} |
4db280be-bdd0-4a8c-a855-612d8c24ae10 | 6 | @EventHandler
public void SilverfishSpeed(EntityDamageByEntityEvent event) {
Entity e = event.getEntity();
Entity damager = event.getDamager();
String world = e.getWorld().getName();
boolean dodged = false;
Random random = new Random();
double randomChance = plugin.getSilverfishConfig().getDouble("Silverfish.Speed.DodgeChance") / 100;
final double ChanceOfHappening = random.nextDouble();
if (ChanceOfHappening >= randomChance) {
dodged = true;
}
if (plugin.getSilverfishConfig().getBoolean("Silverfish.Speed.Enabled", true) && damager instanceof Silverfish && e instanceof Player && plugin.getConfig().getStringList("Worlds").contains(world) && !dodged) {
Player player = (Player) e;
player.addPotionEffect(new PotionEffect(PotionEffectType.SPEED, plugin.getSilverfishConfig().getInt("Silverfish.Speed.Time"), plugin.getSilverfishConfig().getInt("Silverfish.Speed.Power")));
}
} |
8ff6fdbd-8e1c-4854-b21c-3627ebab065b | 3 | public static String cmdInterpreter(String[] arg) {
try {
// String[] cmd = new String[arg.length + 2];
// System.arraycopy(BASH_CMD, 0, cmd, 0, BASH_CMD.length);
// System.arraycopy(arg, 0, cmd, BASH_CMD.length, arg.length);
for (String str : arg)
System.out.print(str + " ");
Process p = Runtime.getRuntime().exec(arg);
p.waitFor();
BufferedReader br = new BufferedReader(new InputStreamReader(
p.getInputStream()));
StringBuilder sb = new StringBuilder("");
String line;
while ((line = br.readLine()) != null) {
sb.append(line + "\n");
}
return sb.toString();
} catch (Exception e) {
e.printStackTrace();
return "nope";
}
} |
d4a5157f-3a94-4ba4-be58-7b0e3cc2f254 | 1 | public Color getColor() {
try {
int newR = Integer.parseInt(jTextField1.getText());
int newG = Integer.parseInt(jTextField2.getText());
int newB = Integer.parseInt(jTextField3.getText());
int newA = Integer.parseInt(jTextField4.getText());
r = newR;
g = newG;
b = newB;
a = newA;
} catch (NumberFormatException e) {
}
return new Color(r, g, b,a);
} |
b724db0b-87fd-44ff-b084-32b483e89fc5 | 8 | @Override
public int hashCode() {
final int PRIME = 31;
int result = super.hashCode();
result = PRIME * result + ((attendees == null) ? 0 : attendees.hashCode());
result = PRIME * result + day;
result = PRIME * result + ((description == null) ? 0 : description.hashCode());
result = PRIME * result + endHour;
result = PRIME * result + endMinute;
result = PRIME * result + ((eventType == null) ? 0 : eventType.hashCode());
result = PRIME * result + ((location == null) ? 0 : location.hashCode());
result = PRIME * result + month;
result = PRIME * result + ((organizer == null) ? 0 : organizer.hashCode());
result = PRIME * result + ((showStatus == null) ? 0 : showStatus.hashCode());
result = PRIME * result + startHour;
result = PRIME * result + startMinute;
result = PRIME * result + ((summary == null) ? 0 : summary.hashCode());
result = PRIME * result + ((uuid == null) ? 0 : uuid.hashCode());
result = PRIME * result + year;
return result;
} |
1855ae49-349d-404a-88f7-7a692bcf25b3 | 0 | public String getToolTip() {
return "Undoer - Click anywhere in the editor pane after clicking me.";
} |
9f44197d-fe63-4554-8bac-ee9d83529307 | 1 | State (String name, int id) throws IllegalArgumentException{
outgoingTransitions = new ArrayList<Transition>();
incomingTransitions = new ArrayList<Transition>();
prop = new State_Properties();
dfsNum = 0;
this.id = id;
if (name == null)
throw new IllegalArgumentException();
//name != null
prop.setName(name);
} |
b305bcd7-3c6f-4047-90d7-81894649efce | 4 | private void checkForAsyncExecutionFailure(List<Future<?>> asyncs) throws ProcessExecutionException {
for (Future<?> async : asyncs) {
if (!async.isDone())
continue;
awaitAsyncExecution(async);
}
} |
96cec53e-bcce-4733-8aac-708aa6b9e432 | 6 | public boolean tierraInvadida() {
NaveAlien n1;
int x = NUM_FILAS-1, y = NUM_COLUMNAS-1;
boolean tierraInvadida = false;
boolean continuarComprobando = true; //con comprobar una nave nos llega
while(x >= 0 && continuarComprobando) {
while(y >= 0 && continuarComprobando) {
n1 = listaNavesAliens[x][y]; //obtenemos la nave que ocupa la posicion x,y
if(n1 != null) { //si la nave no ha sido previamente eliminada
continuarComprobando = false;
//si la posicion en vertical de una nave es menor o igual que la de nuestra nave, nos han invadido
if(n1.getY() + 24 >= NaveHumana.getMiNaveHumana().getY()) {
tierraInvadida = true;
}//final de la comprobacion de invasion
} //final de si la nave es null
y--;
}//final del while que recorre las columnas
y=NUM_COLUMNAS-1;
x--;
}//final del while que recorre las filas
return tierraInvadida;
} |
34214e49-131f-4ba2-b720-d6c3264691bd | 0 | public void setLocation_id(String location_id) {
this.location_id = location_id;
setDirty();
} |
d021ff24-5918-4aa5-999d-80c62c648db0 | 0 | public static void question3() {
/*
QUESTION PANEL SETUP
*/
questionLabel.setText("What is your favourite day of the week?");
questionNumberLabel.setText("3");
/*
ANSWERS PANEL SETUP
*/
//resetting
radioButton1.setSelected(false);
radioButton2.setSelected(false);
radioButton3.setSelected(false);
radioButton4.setSelected(false);
radioButton5.setSelected(false);
radioButton6.setSelected(false);
radioButton7.setSelected(false);
radioButton8.setSelected(false);
radioButton9.setSelected(false);
radioButton10.setSelected(false);
radioButton11.setSelected(false);
radioButton12.setSelected(false);
radioButton13.setSelected(false);
radioButton14.setSelected(false);
//enability
radioButton1.setEnabled(true);
radioButton2.setEnabled(true);
radioButton3.setEnabled(true);
radioButton4.setEnabled(true);
radioButton5.setEnabled(true);
radioButton6.setEnabled(true);
radioButton7.setEnabled(true);
radioButton8.setEnabled(true);
radioButton9.setEnabled(false);
radioButton10.setEnabled(false);
radioButton11.setEnabled(false);
radioButton12.setEnabled(false);
radioButton13.setEnabled(false);
radioButton14.setEnabled(false);
//setting the text
radioButton1.setText("Monday");
radioButton2.setText("Tuesday");
radioButton3.setText("Wednesday");
radioButton4.setText("Thursday");
radioButton5.setText("Friday");
radioButton6.setText("Saturday");
radioButton7.setText("Sunday");
radioButton8.setText("All of them!");
radioButton9.setText("No used");
radioButton10.setText("No used");
radioButton11.setText("No used");
radioButton12.setText("No used");
radioButton13.setText("No used");
radioButton14.setText("No used");
// Calculating the best guesses and showing them.
Knowledge.calculateAndColorTheEvents();
} |
fd4f9032-04be-4d56-b65f-19425bab798e | 0 | public boolean isCatched() {
return catched;
} |
ab2f4a08-8e91-4953-9a4d-494d73c9209a | 1 | public void addValue(String key, String errorMessage) {
if(errorMap.get(key) == null){
ArrayList<String> list = new ArrayList<String>();
list.add(errorMessage);
errorMap.put(key, list);
}
else {
errorMap.get(key).add(errorMessage);
}
} |
4b2e9638-1b62-49ef-ad00-2375ae19846a | 4 | private DMemeGrid convertToGridB(Map mp) {
DMemeGrid grid = new DMemeGrid();
int rowIdx = 0;
int colIdx = 0;
Iterator it = mp.entrySet().iterator();
while (it.hasNext()) {
Map.Entry pairs = (Map.Entry) it.next();
Map<Integer, Integer> tmp = (TreeMap<Integer,Integer>)pairs.getValue();
grid.addColLabel(pairs.getKey().toString());
Iterator it2 = tmp.entrySet().iterator();
rowIdx = 0;
while (it2.hasNext()) {
Map.Entry item = (Map.Entry) it2.next();
Integer i = new Integer(item.getKey().toString());
String label = item.getKey().toString();
if (i > 0) {
label = String.format("+%d", i);
}
if (!grid.getRowLabels().contains(label)) {
grid.addRowLabel(label);
}
grid.addItem(rowIdx, colIdx, new DataMeme(item.getValue()));
rowIdx++;
}
colIdx++;
}
return grid;
} |
d632e817-d642-47e3-84bc-17a8e355b4b7 | 2 | @Override
public void startElement(String s, String s1, String elementName, Attributes attributes) throws SAXException {
// if current element is book , create new book
// clear tmpValue on start of element
if (elementName.equalsIgnoreCase("book")) {
bookTmp = new Book();
bookTmp.setId(attributes.getValue("id"));
bookTmp.setLang(attributes.getValue("lang"));
}
// if current element is publisher
if (elementName.equalsIgnoreCase("publisher")) {
bookTmp.setPublisher(attributes.getValue("country"));
}
} |
adfdbd88-866a-48f3-bc66-8e053778d21c | 6 | 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(GuiStartMenu.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (InstantiationException ex) {
java.util.logging.Logger.getLogger(GuiStartMenu.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (IllegalAccessException ex) {
java.util.logging.Logger.getLogger(GuiStartMenu.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (javax.swing.UnsupportedLookAndFeelException ex) {
java.util.logging.Logger.getLogger(GuiStartMenu.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
}
//</editor-fold>
/* Create and display the form */
java.awt.EventQueue.invokeLater(new Runnable() {
public void run() {
new GuiStartMenu().setVisible(true);
}
});
} |
aa03564b-81c6-4ea6-a253-1d8f506bd0e6 | 5 | @Test
public void depthest21opponent5()
{
for(int i = 0; i < BIG_INT; i++)
{
int numPlayers = 6; //assume/require > 1, < 7
Player[] playerList = new Player[numPlayers];
ArrayList<Color> factionList = Faction.allFactions();
playerList[0] = new Player(chooseFaction(factionList), new SimpleAI());
playerList[1] = new Player(chooseFaction(factionList), new DepthEstAI(2,1, new StandardEstimator()));
playerList[2] = new Player(chooseFaction(factionList), new SimpleAI());
playerList[3] = new Player(chooseFaction(factionList), new SimpleAI());
playerList[4] = new Player(chooseFaction(factionList), new SimpleAI());
playerList[5] = new Player(chooseFaction(factionList), new SimpleAI());
Color check = playerList[1].getFaction();
GameState state = new GameState(playerList, new Board(), gameDeck, gameBag, score);
Set<Player> winners = Game.run(state, new StandardSettings());
boolean won = false;
for(Player p : winners)
{
if(p.getFaction().equals(check))
{
won = true;
wins++;
if(winners.size() > 1)
{
tie++;
}
}
}
if(!won)
{
loss++;
}
}
assertEquals(true, wins/(wins+loss) > .8);
} |
106b90ac-5611-41bc-b327-3ced573642dc | 0 | @Basic
@Column(name = "amount")
public double getAmount() {
return amount;
} |
b4e7650b-0588-44b6-b421-bfd537704e2e | 4 | public Puzzle read(String input) {
List<Integer> data = getData(input);
switch (data.size()) {
case 1:
return new Puzzle1(data);
case 4:
return new Puzzle2(data);
case 16:
return new Puzzle4(data);
case 81:
return new Puzzle9(data);
default:
throw new IllegalArgumentException("Illegal size of data "
+ data.size());
}
} |
f1c00539-277d-4200-9443-b0875313ac6c | 0 | public void setModuleId(String moduleId) {
this.moduleId = moduleId;
} |
8b5c3a55-8220-463d-a7f0-3ef821849aeb | 0 | public BufferedImage getImage() {
return image;
} |
398ce5a1-d118-4ee5-9539-4d56f5edbb47 | 5 | public SemanticRec gen_assign_cast(SemanticRec left, SemanticRec right)
{
Type leftType = getTypeFromSR(left);
Type rightType = getTypeFromSR(right);
SemanticRec returnRec = null;
if (leftType == rightType)
{
//no cast needed
returnRec = right; //the expressions RecordType is unchanged
}
else if ((leftType == Type.INTEGER) && rightType == Type.FLOAT)
{
//cast to integer
castStackToI();
returnRec = new SemanticRec(RecordType.LITERAL, Type.INTEGER.toString()); //now an integer on the stack
}
else if (leftType == Type.FLOAT && (rightType == Type.INTEGER))
{
//cast to float
castStackToF();
returnRec = new SemanticRec(RecordType.LITERAL, Type.FLOAT.toString()); //now a float on the stack
}
else
{
//invalid cast
Parser.semanticError("Invalid cast from " + rightType + " to " + leftType);
}
return returnRec;
} |
fa909e8a-e33a-4278-b9f3-24dae1f515fd | 7 | public void preCombo(){
currentComboNo--;
if(currentComboNo >= 1){
spatial.getControl(LabelControl.class).changeText(comboList());
if(comboNumber == 4){
if(StoredInfo.level < 3){
spatial.getControl(LabelControl.class).changeText("Level 3");
}
}else if(comboNumber == 5){
if(StoredInfo.level < 8){
spatial.getControl(LabelControl.class).changeText("Level 8");
}
}else if(comboNumber == 6){
if(StoredInfo.level < 9){
spatial.getControl(LabelControl.class).changeText("Level 10");
}
}
setupComboMove();
}else{
currentComboNo = 1;
}
} |
0259129d-04b4-4209-8742-a2eb95d328bc | 1 | public static void main(String[] args) {
Launcher launcher = new Launcher();
launcher.initializeLogger(); // Couldn't think of anywhere else to put it
try {
launcher.showWelcomeView();
} catch(Exception ex) {
JOptionPane.showConfirmDialog(null,
"There was an error!\n" + ex.getMessage(), "Error!", JOptionPane.ERROR_MESSAGE);
}
} |
56b93975-af03-4b73-8a0d-1e848a479c71 | 8 | private static boolean containsEmbeddedWhitespace(String value) {
int state = 0;
for (int i = 0, len = value.length(); i < len; i++)
switch (value.charAt(i)) {
case ' ':
case '\t':
case '\r':
case '\n':
if (state == 1)
state = 2;
break;
default:
if (state == 2)
return true;
if (state == 0)
state = 1;
break;
}
return false;
} |
87c038b9-6d57-4054-bf36-e39e9c573656 | 6 | public Ray[][] initializeRays(double x, double y, double z, Screen screen, int xres, int yres){
Vector3D origin = new Vector3D(x,y,z);
Ray[][] rays;
//<= used as we want neat behaviour on bad exceptions rather than returning say a [50][0] array
if (screen ==null || xres <=0 || yres <= 0){rays = new Ray[0][0];}
else{
rays = new Ray[xres][yres];
for(int i =0; i < xres; i++){
for(int j=0; j < yres; j++){
Vector3D screenPoint = new Vector3D(SCALE,screen.getOrigin(),(((double)i)/xres)*screen.getL1(), screen.getV1(),(((double)j)/yres)*screen.getL2(),screen.getV2());
//System.out.println(screenPoint.getX() + " " +screenPoint.getY() + " " +screenPoint.getZ());
try{
rays[i][j] = new Ray(origin, screenPoint.subtract(SCALE,origin));
}catch (Exception e){System.out.println(e.toString());}
}
}
}
return rays;
} |
be8534cc-6808-4b79-8828-da621abfefe3 | 2 | private void checkPause()
{
// double check
if (paused)
{
synchronized (state)
{
// Actually pausing?
if (state.has(Pausing))
{
// Pause!
state.set(Paused);
// Notify all listeners of pause.
notifier.proxy().onServicePause(this, interrupt);
// Wait for the running or stopping state.
state.waitFor(Running | Stopping);
// Notify all listeners of resume.
notifier.proxy().onServiceResume(this, interrupt);
}
}
}
} |
3940ad99-706a-4f45-a3ae-49fc3ef425b7 | 1 | @Test
public void WhenAddingCollection_ExpectContainedSizeChange()
throws UnknownHostException {
int level = localhost_.getHostPath().length();
RoutingTable table = new RoutingTable();
table.setLocalhost(localhost_);
Assert.assertTrue(table.levelNumber() == level);
Assert.assertTrue(table.uniqueHostsNumber() == 0);
Host host0 = new PGridHost("127.0.0.1", 3000);
Host host1 = new PGridHost("127.0.0.1", 3001);
Collection<Host> list = new ArrayList<Host>(2);
list.add(host0);
list.add(host1);
table.addReference(level - 1, list);
Assert.assertTrue(table.levelNumber() == level);
Assert.assertTrue(table.contains(host0) && table.contains(host1));
Assert.assertTrue(table.uniqueHostsNumber() == 2);
} |
6481c3f0-4d94-40c4-b182-50bed4d212f7 | 9 | public boolean skipPast(String to) throws JSONException {
boolean b;
char c;
int i;
int j;
int offset = 0;
int length = to.length();
char[] circle = new char[length];
/*
* First fill the circle buffer with as many characters as are in the
* to string. If we reach an early end, bail.
*/
for (i = 0; i < length; i += 1) {
c = next();
if (c == 0) {
return false;
}
circle[i] = c;
}
/* We will loop, possibly for all of the remaining characters. */
for (;;) {
j = offset;
b = true;
/* Compare the circle buffer with the to string. */
for (i = 0; i < length; i += 1) {
if (circle[j] != to.charAt(i)) {
b = false;
break;
}
j += 1;
if (j >= length) {
j -= length;
}
}
/* If we exit the loop with b intact, then victory is ours. */
if (b) {
return true;
}
/* Get the next character. If there isn't one, then defeat is ours. */
c = next();
if (c == 0) {
return false;
}
/*
* Shove the character in the circle buffer and advance the
* circle offset. The offset is mod n.
*/
circle[offset] = c;
offset += 1;
if (offset >= length) {
offset -= length;
}
}
} |
b4509107-636b-4b98-84f0-4e81aafa49d7 | 1 | @Override
public void connectToClient(DiscoveredClient client) {
try {
new ChatGUI(client);
} catch (IOException e) {
System.out.println("Failed to connect!");
e.printStackTrace();
}
} |
8e8fe1e9-8675-431a-953f-9d5dc057a249 | 0 | public boolean isListening() {
return listening;
} |
55b30b32-5c27-4412-af94-e89223ba1590 | 2 | public void desconectar(long target) {
for (int i = 0; i < connections.getLength(); i++) {
Connection connection = connections.get(i);
if (connection.getTarget()==target) {
connection.desconectar();
connections.remove(i);
XmlToolkit.crearDesconexion(this.id,target);
}
}
} |
63987bdb-fe13-48d5-9aa3-09ec2f50908d | 0 | public StartScreen()
{
super("Go"); // renames the top of the frame
goBackground = new ImageIcon("gopic.png"); // sets the board I made as an image icon
JPanel topPane = new JPanel(); // new jpanel
topPane.setPreferredSize(new Dimension(500, 565)); // sets the size of the panel
add(topPane, BorderLayout.NORTH); // adds it to the jframe
buttons = new JPanel(new GridLayout(1, 2)); // creates the space for 2 buttons
buttons.setPreferredSize(new Dimension(500, 50)); // sets the space
start = new JButton("VS Computer"); // names the buttons
Ai = new JButton("VS Person");
help = new JButton("View Tutorials");
start.setPreferredSize(new Dimension(300, 100));// sets the button sizes
help.setPreferredSize(new Dimension(300, 100));
Ai.setPreferredSize(new Dimension(300,100));
buttons.add(start); // adds the buttons to the jframe
buttons.add(Ai);
buttons.add(help);
add(buttons, BorderLayout.SOUTH);// and to the bottom
start.addActionListener(this); // creates action listeners to the buttons
Ai.addActionListener(this);
help.addActionListener(this);
setSize(900, 600); // sets jframe size
pack(); // packs the jframe
setVisible(true); // shows the jframe
setResizable(false); // makes the screen not resizable
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); // exits the application on exit
Dimension screen = Toolkit.getDefaultToolkit().getScreenSize(); // gets the computer screen
// size
setLocation((screen.width - 500) / 2, (screen.height - 600) / 2); // puts the window in the
// middle of the screen
} |
4712ee7d-2330-47c0-9021-45980fd35af2 | 9 | private void getTilesInBombDir(int x, int y, int xdir, int ydir, List<Tile> tiles){
for(int i = 1; i < 4; ++i){
int xx = x + (i * xdir), yy = y + (i * ydir);
if(xx < 0 || xx >= w || yy < 0 || yy >= h) break;
Tile t = map[xx][yy];
if(t.type == Tile.CLEAR || t.type == Tile.BREAKABLE) tiles.add(t);
if(t.type == Tile.SOLID || t.type == Tile.BREAKABLE) break;
}
} |
fb925a67-f831-4502-be01-e25be0adc56a | 1 | @Override
public ArrayList<Edge> getEdgeList()
{
if (isParsed)
{
return edges;
} else
{
initiateParsing();
return edges;
}
} |
bbb34d46-6a67-44d2-ac56-1d773f0efea4 | 6 | 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(ModificarSenha.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (InstantiationException ex) {
java.util.logging.Logger.getLogger(ModificarSenha.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (IllegalAccessException ex) {
java.util.logging.Logger.getLogger(ModificarSenha.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (javax.swing.UnsupportedLookAndFeelException ex) {
java.util.logging.Logger.getLogger(ModificarSenha.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
}
//</editor-fold>
/* Create and display the form */
java.awt.EventQueue.invokeLater(new Runnable() {
public void run() {
new ModificarSenha().setVisible(true);
}
});
} |
d983357a-3edd-4962-9dfb-bf84bf0a642a | 8 | public static int Action(Client joueur) {
int tempDette = 0;
int choiceInt = -1;
boolean wrong = true;
boolean quit = true;
do {
System.out.println("Que voulez vous faire?"
+ "\n pour dormir tapez 1"
+ "\n pour appeler le room service tapez 2"
+ "\n pour partir tapez 3");
do {
String choice = keyboard.nextLine();
try {
choiceInt = Integer.parseInt(choice);
if (choiceInt != 1 && choiceInt != 2 && choiceInt != 3) {
throw new Exception("not 1, 2 or 3");
}
wrong = false;
} catch (Exception e) {
System.out.println("Mauvaise valeur inseree");
}
} while (wrong);
switch (choiceInt) {
case 1:
dormir(joueur);
break;
case 2:
tempDette += RoomService(joueur);
break;
default:
quit = false;
}
} while (quit);
return tempDette;
} |
e2c30516-f26f-418b-83ec-4e6029c46e2e | 6 | 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(TestTerbilang.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (InstantiationException ex) {
java.util.logging.Logger.getLogger(TestTerbilang.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (IllegalAccessException ex) {
java.util.logging.Logger.getLogger(TestTerbilang.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (javax.swing.UnsupportedLookAndFeelException ex) {
java.util.logging.Logger.getLogger(TestTerbilang.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
}
//</editor-fold>
/*
* Create and display the form
*/
java.awt.EventQueue.invokeLater(new Runnable() {
public void run() {
new TestTerbilang().setVisible(true);
}
});
} |
0caea3fc-a7aa-4c72-8a94-6aafe2e4588f | 3 | public boolean answer(int answer)
{
int answerTime = timer.getSeconds();
if (answer == getCurrentCount())
{
if (answer >= 17)
newTurn();
else
addCard();
timer.resetTimer();
timer.startTimer();
score += (11 - answerTime > 0) ? (11 - answerTime) : 0;
return true;
}
else
{
gameOver = true;
return false;
}
} |
704320ff-f82f-4b1f-a103-5588ca441ae2 | 2 | @Override
public boolean isComponent(JsonObject jsonObject) {
return jsonObject.get("hidey") != null &&
jsonObject.get("show-mcr") != null &&
jsonObject.get("type").getAsString().equals("coord");
} |
c993e02a-535a-4f1a-9991-4a1e9cf7f95b | 3 | public void saveMessage(MessageDTO messageDTO) throws DataProcessingException {
MailBox sender = mailBoxDAO.find(messageDTO.getSender());
if (sender == null) {
logger.warn("Mailbox with email " + messageDTO.getSender() + " does not exist");
throw new DataProcessingException(ExceptionType.mailBoxDoesNotExist);
}
MailBox receiver = null;
if (messageDTO.getReceiver() != null) {
receiver = mailBoxDAO.find(messageDTO.getReceiver());
}
if (receiver == null) {
logger.warn("Mailbox with email " + messageDTO.getReceiver() + " does not exist");
}
Message message = new Message(true, sender, receiver, messageDTO.getTheme(), messageDTO.getMessageBody());
save(message);
logger.info("Message successfully saved in draft messages of" + sender.getEmail());
} |
0cbf3575-7025-4cf2-bb60-cf103594c9c8 | 0 | public boolean end() {
return i == items.length;
} |
672f6c8b-c515-4f51-ae9b-937145fdf28b | 9 | public static TypeType arrayElementTypeFor(ClassData classData) {
if (classData == refArrayClassData) {
return TypeType.REF;
} else if (classData == boolArrayClassData) {
return TypeType.BOOLEAN;
} else if (classData == byteArrayClassData) {
return TypeType.BYTE;
} else if (classData == charArrayClassData) {
return TypeType.CHAR;
} else if (classData == shortArrayClassData) {
return TypeType.SHORT;
} else if (classData == intArrayClassData) {
return TypeType.INT;
} else if (classData == longArrayClassData) {
return TypeType.LONG;
} else if (classData == floatClassData) {
return TypeType.FLOAT;
} else if (classData == doubleClassData) {
return TypeType.DOUBLE;
} else {
throw new IllegalArgumentException();
}
} |
183a144b-68f0-41b9-8be0-cffc77f5bcdb | 3 | @Test
public void testReceiveTimeout_MessageAlreadyPresent() {
try {
consumer = new AbstractMessageConsumer(mockTopic) {
};
} catch (DestinationClosedException e) {
fail("Unexpected exception on constructor");
}
assertNotNull(mockTopic.getTopicSubscriber());
try {
Message msg = new MockMessage("TestMessage");
mockTopic.getTopicSubscriber().onMessage(msg);
FutureTask<Message> future = getMessageFuture(consumer, 100);
Message received = future.get(5, TimeUnit.MILLISECONDS);
assertNotNull("Received message is null ", received);
assertEquals("Message values dont match.", msg.getMessage(),
received.getMessage());
} catch (TimeoutException e) {
fail("Timeout did not happen on receive method");
} catch (Exception e) {
logger.error("Error while calling receiving message", e);
fail("Error while calling onMessage:" + e.getMessage());
}
} |
0b2d0fa0-48f4-48a3-944f-c93880785679 | 3 | public double checkSpeed() {
double dx = this.getDeltaX("BALL");
speedX = hitCounter * 0.3;
if(dx < 0) {
dx = -speedX;
}
if(dx > 0) {
dx = speedX;
}
if(dx == 0) {
dx = 0.3;
}
return dx;
} |
4420c307-d56f-44dd-b644-c6f7762b4a4a | 4 | private <T, R> R convert(ConvertType convertType, TypeConverter<T, R> typeConverter, T source, Class<R> targetClass) {
switch (convertType) {
case identity:
return (R) source;
case none:
return null; // TODO: later, return default null
case converter:
return typeConverter.convert(source);
case complex:
return as(targetClass, source);
default:
throw new RuntimeException("Mapper.convert: no ConvertType for " + source);
}
} |
458769b4-a0ed-4cde-8c58-a33d35d37aeb | 7 | @Override
public void init() {
log("Behave test. Usage : ant test-interactive-behave -Dpath=poly|ellipse|bspline");
log("Current parameter:"+getParam()+":");
Color stage_color = new Color(0xcc, 0xcc, 0xcc, 0xff);
Color rect_bg_color = new Color(0x33, 0x22, 0x22, 0xff);
Color rect_border_color = new Color(0, 0, 0, 0);
PathType path_type = PathType.PATH_POLY;
String knots_poly = ("M 0, 0 L 0, 300 L 300, 300 "
+ "L 300, 0 L 0, 0");
/* A spiral created with inkscake */
String knots_bspline = "M 34.285713,35.219326 "
+ "C 44.026891,43.384723 28.084874,52.378758 20.714286,51.409804 "
+ "C 0.7404474,48.783999 -4.6171866,23.967448 1.904757,8.0764719 "
+ "C 13.570984,-20.348756 49.798303,-26.746504 74.999994,-13.352108 "
+ "C 111.98449,6.3047056 119.56591,55.259271 99.047626,89.505034 "
+ "C 71.699974,135.14925 9.6251774,143.91924 -33.571422,116.17172 "
+ "C -87.929934,81.254291 -97.88804,5.8941057 -62.857155,-46.209236 "
+ "C -20.430061,-109.31336 68.300385,-120.45954 129.2857,-78.114021 "
+ "C 201.15479,-28.21129 213.48932,73.938876 163.80954,143.79074 "
+ "C 106.45226,224.43749 -9.1490153,237.96076 -87.85713,180.93363 "
+ "C -177.29029,116.13577 -192.00272,-12.937817 -127.61907,-100.49494 "
+ "C -55.390344,-198.72081 87.170553,-214.62275 183.57141,-142.87593 "
+ "C 290.59464,-63.223369 307.68641,92.835839 228.57145,198.07645";
if ("poly".equals(getParam())){
path_type = PathType.PATH_POLY;
} else if ("bspline".equals(getParam())){
path_type = PathType.PATH_BSPLINE;
} else if ("ellipse".equals(getParam())){
path_type = PathType.PATH_ELLIPSE;
}
System.out.println(":"+path_type);
Stage.getDefault().hideCursor();
Stage.getDefault().setColor(stage_color);
/* Make a hand */
Texture hand = Texture.createFromFile("src/test/resources/redhand.png");
Rectangle rect = new Rectangle();
rect.setSize(hand.getWidth(), hand.getHeight());
rect.setColor(rect_bg_color);
rect.setBorderWidth(10);
rect_border_color = Color.BLACK;
// TODO following like causes jvm to crash
// rect_border_color = Color.getColor("DarkSlateGray");
// if (rect_border_color == null) {
// log("warn: no color found for DarkSlateGray");
// }
rect.setBorderColor(rect_border_color);
add(rect, hand);
/* Make a timeline */
Timeline timeline = new Timeline(4000, 0){
public void onCompleted() {
int direction;
direction = getDirection();
if (direction == Timeline.DIRECTION_FORWARD)
direction = Timeline.DIRECTION_BACKWARD;
else
direction = Timeline.DIRECTION_FORWARD;
setDirection(direction);
}
};
timeline.setLoop(true);
/* Set an alpha func to power behaviour - ramp is constant rise */
Alpha alpha = new Alpha(timeline, Mode.LINEAR);
/* Create a behaviour for that alpha */
OpacityBehaviour o_behave = new OpacityBehaviour(alpha, (byte) 0X33, (byte) 0xff);
/* Apply it to our actor */
o_behave.apply(this);
Behaviour p_behave = null;
/* Make a path behaviour and apply that too */
switch (path_type) {
case PATH_POLY: {
Path path = new Path();
path.setDescription(knots_poly);
p_behave = new PathBehaviour(alpha, path);
}
break;
case PATH_ELLIPSE:
p_behave = new EllipseBehaviour(alpha, 200, 200, 400, 300,
RotateBehaviour.CLOCKWISE, 0.0, 360.0);
((EllipseBehaviour) p_behave).setAngleTilt(Rotation.X_AXIS,
45.0f);
((EllipseBehaviour) p_behave).setAngleTilt(Rotation.Z_AXIS,
45.0f);
break;
case PATH_BSPLINE: {
Path path = new Path();
path.setDescription(knots_bspline);
p_behave = new PathBehaviour(alpha, path);
}
break;
}
p_behave.apply(this);
/* start the timeline and thus the animations */
timeline.start();
log("Behave test init done");
} |
9289e0bb-ec58-486e-9280-19dd28899da9 | 3 | private String readString() throws EncodingException
{
int handle = readInt();
boolean inline = ((handle & 1) != 0);
handle = handle >> 1;
if (inline)
{
if (handle == 0)
return "";
byte[] data = readBytes(handle);
String str;
try
{
str = new String(data, "UTF-8");
}
catch (UnsupportedEncodingException e)
{
throw new EncodingException("Error parsing AMF3 string from " + data);
}
stringReferences.add(str);
return str;
}
else
{
return stringReferences.get(handle);
}
} |
d8424da0-4fa2-4c44-8111-f30534ec998b | 9 | public static Iterable<FileEntry> listFilesRelativeToClass(Class<?> clazz, String subdirectory) throws IOException {
ArrayList<FileEntry> list = new ArrayList<FileEntry>();
CodeSource src = clazz.getProtectionDomain().getCodeSource();
if (src == null) {
return list;
}
URL classpathEntry = src.getLocation();
try {
// Check if we're loaded from a folder
File file = new File(new File(classpathEntry.toURI()), subdirectory);
if (file.isDirectory()) {
return fileEntriesFor(file.listFiles());
}
} catch (URISyntaxException e) {
// Should never happen, because we know classpathentry is valid
throw new RuntimeException(e);
}
// We're not in a folder, so we must be in a jar or similar
subdirectory = subdirectory.replace(File.separatorChar, '/');
if (!subdirectory.endsWith("/")) {
subdirectory = subdirectory + "/";
}
ZipInputStream jarStream = new ZipInputStream(classpathEntry.openStream());
ZipEntry zipEntry;
while ((zipEntry = jarStream.getNextEntry()) != null) {
if (isChild(subdirectory, zipEntry.getName())) {
String basename = zipEntry.getName().substring(subdirectory.length());
int indexOfSlash = basename.indexOf('/');
if (indexOfSlash < 0 || indexOfSlash == basename.length() - 1) {
list.add(new FileEntry(basename));
}
}
}
return list;
} |
11838c5d-d368-4da5-b779-982f1be45b45 | 3 | public static boolean reflectGraphicsEnvironmentISHeadlessInstance(Object graphicsEnvironment, boolean defaultReturnIfNoMethod) {
try {
Class clazz = graphicsEnvironment.getClass();
Method isHeadlessInstanceMethod = clazz.getMethod("isHeadlessInstance", new Class[]{});
if (isHeadlessInstanceMethod != null) {
Object ret = isHeadlessInstanceMethod.invoke(
graphicsEnvironment, new Object[]{});
if (ret instanceof Boolean)
return ((Boolean) ret).booleanValue();
}
}
catch (Throwable t) {
logger.log(Level.FINE,
"ImageCache: Java 1.4 Headless support not found.");
}
return defaultReturnIfNoMethod;
} |
ed179d6a-3d61-446c-95e3-98a2fc4e0476 | 0 | @Override
public Iterator<Term> iterator() {
return new BSTIterator<Term>(this);
} |
d77606e3-edf3-473b-a1b0-55179b1428a3 | 9 | @Override
public boolean invoke(MOB mob, List<String> commands, Physical givenTarget, boolean auto, int asLevel)
{
MOB target=mob;
if((auto)&&(givenTarget!=null)&&(givenTarget instanceof MOB))
target=(MOB)givenTarget;
if(target.fetchEffect(this.ID())!=null)
{
mob.tell(target,null,null,L("<S-NAME> already <S-HAS-HAVE> a darkness globe around <S-HIM-HER>."));
return false;
}
if(!super.invoke(mob,commands,givenTarget,auto,asLevel))
return false;
final boolean success=proficiencyCheck(mob,0,auto);
final Room room=mob.location();
if((success)&&(room!=null))
{
final CMMsg msg=CMClass.getMsg(mob,target,this,verbalCastCode(mob,target,auto),
auto?L("^S<S-NAME> attain(s) a globe of darkness around <S-HIM-HER>!")
:L("^S<S-NAME> invoke(s) a darkness globe all around <S-HIM-HER>, enveloping everything!^?"));
if(room.okMessage(mob,msg))
{
room.send(mob,msg);
beneficialAffect(mob,target,asLevel,0);
room.recoverRoomStats();
}
}
else
beneficialWordsFizzle(mob,mob.location(),L("<S-NAME> attempt(s) to invoke darkness, but fail(s)."));
return success;
} |
3112f651-81b5-4cb5-a4a2-5ed542e27ee8 | 3 | public static boolean textureExists(String s)
{
File f = R2DFileUtility.getResource(s);
if(f.exists() && f.isFile() && f.getName().endsWith(".png"))
return true;
else
return false;
} |
0d2f5f50-fb05-45e5-8ffc-413a44342287 | 9 | @Override
public boolean equals(Object obj) {
if (this == obj)
return true;
if (obj == null)
return false;
if (getClass() != obj.getClass())
return false;
Trayectoria other = (Trayectoria) obj;
if (estacionDestino == null) {
if (other.estacionDestino != null)
return false;
} else if (!estacionDestino.equals(other.estacionDestino))
return false;
if (estacionOrigen == null) {
if (other.estacionOrigen != null)
return false;
} else if (!estacionOrigen.equals(other.estacionOrigen))
return false;
return true;
} |
38f1a4d1-114e-4db4-8361-8d0a7cdc24f0 | 5 | public int get_check_info()
{
int return_val = 0;
cur_phoneName = jtext_phone_name.getText().trim();
cur_phoneNum = jtext_phone_number.getText().trim();
cur_phoneAddress= jtext_address.getText().trim();
cur_phoneAddress = cur_phoneAddress.replaceAll("\n", " ");
if(cur_phoneNum.isEmpty())
{
jtext_thong_bao.setText("Không có số đt!");
return_val = -1;
}
else if(cur_phoneName.isEmpty())
{
jtext_thong_bao.setText("Không có tên!");
return_val = -2;
}
else if(cur_phoneAddress.isEmpty())
{
jtext_thong_bao.setText("Không có địa chỉ!");
return_val = -3;
}
if(cur_phoneNum.length() < 10 || cur_phoneNum.length() >= 12)
{
jtext_thong_bao.setText("Số điện thoại sai!");
return_val = -4;
}
return return_val;
} |
93f991ac-784d-4243-b2fa-28e2119532b4 | 7 | public void printDirectedDegreeDistribution(LinkSet L){
LinkSetNode N;
L.initTreeTraversal();
Map<Integer,Integer> inDegree = new HashMap<Integer,Integer>();
Map<Integer,Integer> outDegree = new HashMap<Integer,Integer>();
Set<Integer> nodeSet = new HashSet<Integer>();
int d;
while((N=L.getNextInOrder()) != null)
{
nodeSet.add(N.s);
nodeSet.add(N.d);
switch(N.w)
{
case 3: // bidirectional
addInMap(inDegree,N.s);
addInMap(inDegree,N.d);
addInMap(outDegree,N.s);
addInMap(outDegree,N.d);
break;
case 1: // source -> dest
addInMap(outDegree,N.s);
addInMap(inDegree,N.d);
break;
case 2: // dest -> source
addInMap(outDegree,N.d);
addInMap(inDegree,N.s);
break;
}
}
int ind;
int outd;
for(int i : nodeSet)
{
ind = inDegree.containsKey(i) ? inDegree.get(i) : 0;
outd = outDegree.containsKey(i) ? outDegree.get(i) : 0;
System.out.println(i + " " + ind + " " + outd + " " + (double)ind/(double)(ind+outd));
}
} |
87679695-576e-42d6-a8e5-e52b96a632f3 | 4 | public final void write(File xmlFile, ArrayList<Person> firsts,
ArrayList<Person> recurrings) throws Exception {
DocumentBuilderFactory docFactory = DocumentBuilderFactory
.newInstance();
DocumentBuilder docBuilder = docFactory.newDocumentBuilder();
Document doc = docBuilder.newDocument();
doc.setXmlStandalone(true);
// Document
Element document = createDocumentElem(doc);
doc.appendChild(document);
// CstmrDrctDbtInitn
Element root = doc.createElement("CstmrDrctDbtInitn");
document.appendChild(root);
// GrpHdr
Element header = createGrpHdrElem(doc, firsts, recurrings);
root.appendChild(header);
// FIRSTS
// PmtInf
if (firsts.size() > 0) {
Element pmtInfFirst = doc.createElement("PmtInf");
appendPmtInfHdr(pmtInfFirst, doc, firsts,
StaticString.PERSONS_FIRST);
appendCdtr(pmtInfFirst, doc);
Element dbtrFirst;
for (Person p : firsts) {
dbtrFirst = createDbtr(p, doc);
pmtInfFirst.appendChild(dbtrFirst);
}
root.appendChild(pmtInfFirst);
}
// RECURRINGS
// PmtInf
if (recurrings.size() > 0) {
Element pmtInfRec = doc.createElement("PmtInf");
appendPmtInfHdr(pmtInfRec, doc, recurrings,
StaticString.PERSONS_RECURRING);
appendCdtr(pmtInfRec, doc);
Element dbtrRec;
for (Person p : recurrings) {
dbtrRec = createDbtr(p, doc);
pmtInfRec.appendChild(dbtrRec);
}
root.appendChild(pmtInfRec);
}
// XML schreiben
TransformerFactory transformerFactory = TransformerFactory
.newInstance();
Transformer transformer = transformerFactory.newTransformer();
DOMSource source = new DOMSource(doc);
StreamResult result = new StreamResult(xmlFile);
transformer.transform(source, result);
} |
d90f5e9b-7ca6-468e-9b30-4bd1e0720290 | 6 | public static void main(String[] args) {
Scanner in = new Scanner(System.in);
System.out.print("Please, input arithmetic expression: ");
String equation = in.nextLine();
int counter = 0;
//go:{
for (int i = 0; i < equation.length(); i++) {
if (equation.charAt(i) == '(') {
counter++;
} else if (equation.charAt(i) == ')') {
counter--;
}
if (counter < 0) {
System.out.println("Expression is wrong. First position of the wrong right bracket is: "+ (i+1));
return;
}
}
if (counter == 0) {
System.out.println("Expression is correct");
} else if (counter > 0) {
System.out.println("Expression is wrong. We have " + counter + " wrong left bracket(s).");
}
} |
b2615f20-18a6-4899-95d8-da66a6fe7d8b | 2 | public static ReservaEstado create(String estado) {
ReservaEstado pedidoObject = null;
String nomeClasse = "br.com.implementacaoObserverWeb.state."
+ "PedidoEstado" + estado;
Class classe = null;
Object object = null;
try {
classe = Class.forName(nomeClasse);
object = classe.newInstance();
} catch (Exception ex) {
return null;
}
if (!(object instanceof ReservaEstado))
return null;
pedidoObject = (ReservaEstado) object;
return pedidoObject;
} |
69776437-00ac-4476-a562-cca83ed447cc | 3 | public CycList readCycList()
throws IOException {
int size = readInt();
if (trace == API_TRACE_DETAILED) {
debugNote("readCycList.size: " + size);
}
CycList cycList = new CycList(size);
for (int i = 0; i < size; i++) {
cycList.add(readObject());
}
if (trace == API_TRACE_DETAILED) {
debugNote("readCycList.readObject: " + cycList.toString());
}
return cycList;
} |
ce954c5d-f52f-4dce-90e6-3af7273b8dbc | 3 | @Override
public int compareTo(Ban ban) {
// not exactly equal but already exists
if (!ban.player.equalsIgnoreCase(this.player)) {
if (this.until.after(ban)) {
return 1;
} else if (this.until.before(ban)) {
return -1;
}
// would mean that the dates are equal, however, append it
return -1;
} else {
return 0;
}
} |
3ed819fb-4fc7-4beb-914e-571b98c4df46 | 6 | private static boolean isPrime( int n )
{
if( n == 2 || n == 3 )
return true;
if( n == 1 || n % 2 == 0 )
return false;
for( int i = 3; i * i <= n; i += 2 )
if( n % i == 0 )
return false;
return true;
} |
104444ce-2529-486e-9179-d7b4de08eadd | 4 | public static void main (String args[])
{
System.out.println("Welcome to the Movie List Application.");
System.out.println("There are 100 movies on the list.");
Scanner sc = new Scanner(System.in);
String choice = "y";
ArrayList<Movie> myListOfMovies = createArrayList();
System.out.println(myListOfMovies.size());
while (choice.equalsIgnoreCase("y"))
{
System.out.println("There are four categories: animated, drama, horror, and scifi");
System.out.println();
String personMovieCategory = Validator.getRequiredString(sc, "What category are you interested in? ");
Collection<Movie> matchedMovies = new TreeSet<>();
for(Movie movie : myListOfMovies) {
if (personMovieCategory.equalsIgnoreCase(movie.getGenre()))
{
matchedMovies.add(movie);
}
}
for (Movie movie : matchedMovies)
{
System.out.println(movie.getTitle());
}
choice = Validator.getRequiredString(sc, "Continue? (y/n): ");
System.out.println();
}
} |
5a81f2bb-8cbb-458e-877f-2e38f5f5b4be | 8 | @EventHandler
public void onSignClick(PlayerInteractEvent e) {
Player p = e.getPlayer();
if (e.getAction()==Action.RIGHT_CLICK_BLOCK||e.getAction()==Action.LEFT_CLICK_BLOCK) {
Block b = e.getClickedBlock();
if (b.getType()== Material.SIGN_POST||b.getType()==Material.WALL_SIGN) {
Sign s = (Sign) b.getState();
if (s.getLine(0).equalsIgnoreCase("§5[§3CTF§5]")&&s.getLine(1).equalsIgnoreCase("§d§nJoin")) {
p.performCommand("ctf join");
} else if (s.getLine(0).equalsIgnoreCase("§5[§3CTF§5]")&&s.getLine(1).equalsIgnoreCase("§2§nLeave")) {
p.performCommand("ctf leave");
}
}
}
} |
94cefea1-845b-4ab8-a93e-08971e7dbe8d | 0 | public String value() {
return value;
} |
01c26bfa-b9d6-4dd8-9f3c-1e7df7c61733 | 1 | public static void main(String[] args) {
Utility util = new Utility();
//util.splitWords("[Not a question!] radcombobox in client side");
File indexFile = new File("d:\\hadoop-2.2.0\\etc\\hadoop\\words.txt");
File contentFile = new File("d:\\hadoop-2.2.0\\etc\\hadoop\\content.txt");
Map<String, String> indexMap = util.buildKeyWordMap(indexFile);
List<SearchResult> searchResults = util.findPostByWord("but", indexMap, contentFile);
for(SearchResult result : searchResults) {
System.out.println(result.getPost().getTitle());
}
} |
1e0b4804-83b3-491f-866b-31f6125752b4 | 6 | public void attaquer(Positions pos)
{
if (this.plateau.getPlateau()[pos.getLigne()][pos.getColonne()] == EtatDesCases.LIBRE)
return;
Joueur joueurAttaque;
if (this.joueurEnCours == this.joueur1)
joueurAttaque = this.joueur2;
else
joueurAttaque = this.joueur1;
Perso persoSurPlateau = joueurAttaque.getPosMap().get(pos);
int distance = 0;
if (persoSurPlateau.getPos().getLigne() < this.persoEnCours.getPos().getLigne())
distance += this.persoEnCours.getPos().getLigne()-persoSurPlateau.getPos().getLigne();
else
distance += persoSurPlateau.getPos().getLigne() - this.getPersoEnCours().getPos().getLigne();
if (persoSurPlateau.getPos().getColonne() < this.getPersoEnCours().getPos().getColonne())
distance += this.getPersoEnCours().getPos().getColonne() - persoSurPlateau.getPos().getColonne();
else
distance += persoSurPlateau.getPos().getColonne() - this.getPersoEnCours().getPos().getColonne();
if (this.persoEnCours.getPortee() < distance)
{
System.out.println("Cible hors d'atteinte.");
return;
}
if (this.persoEnCours.getPtAttaque() < joueurAttaque.getPosMap().get(pos).getPtDefense())
return;
persoSurPlateau.modifierPtVie(this.persoEnCours.getPtAttaque()-joueurAttaque.getPosMap().get(pos).getPtDefense(), false);
} |
819226b9-ed19-465d-9fbe-84e930e8e928 | 9 | public static PDFDecrypter createDecryptor
(PDFObject encryptDict, PDFObject documentId, PDFPassword password)
throws
IOException,
EncryptionUnsupportedByPlatformException,
EncryptionUnsupportedByProductException,
PDFAuthenticationFailureException {
// none of the classes beyond us want to see a null PDFPassword
password = PDFPassword.nonNullPassword(password);
if (encryptDict == null) {
// No encryption specified
return IdentityDecrypter.getInstance();
} else {
PDFObject filter = encryptDict.getDictRef("Filter");
// this means that we'll fail if, for example, public key
// encryption is employed
if (filter != null && "Standard".equals(filter.getStringValue())) {
final PDFObject vObj = encryptDict.getDictRef("V");
int v = vObj != null ? vObj.getIntValue() : 0;
if (v == 1 || v == 2) {
final PDFObject lengthObj =
encryptDict.getDictRef("Length");
final Integer length =
lengthObj != null ? lengthObj.getIntValue() : null;
return createStandardDecrypter(
encryptDict, documentId, password, length, false,
StandardDecrypter.EncryptionAlgorithm.RC4);
} else if (v == 4) {
return createCryptFilterDecrypter(
encryptDict, documentId, password, v);
} else {
throw new EncryptionUnsupportedByPlatformException(
"Unsupported encryption version: " + v);
}
} else if (filter == null) {
throw new PDFParseException(
"No Filter specified in Encrypt dictionary");
} else {
throw new EncryptionUnsupportedByPlatformException(
"Unsupported encryption Filter: " + filter +
"; only Standard is supported.");
}
}
} |
ce598ce9-1686-4d12-8f65-af74fd32afd3 | 8 | private void processGridletSubmission(Sim_event ev)
{
if (trace_flag)
{
System.out.println(super.get_name() +
": received an SUBMIT_GRIDLET event. Clock: " + GridSim.clock());
}
/***********
We have to submit:
- the gridlet whose id comes with the event
- all the gridlets with the "gridletSub.getSubmitted() == false"
So, set the gridletSub.getSubmitted() to false for the gridlet whose
id comes with the event
***********/
int i = 0;
GridletSubmission gridletSub;
int resourceID[];
Random random = new Random(5); // a random generator with a random seed
int index;
Gridlet gl;
Integer obj;
int glID;
// This is because the initial GRIDLET_SUBMIT event, at the beginning
// of sims, does not have any gridlet id. We have to submit
// all the gridlets.
if (ev.get_data() instanceof Integer)
{
obj = (Integer) ev.get_data();
glID = obj.intValue(); // get the gridlet id.
}
else {
glID = 99; // a value at random, not used at all in this case
}
while (i < GridletSubmittedList_.size())
{
gridletSub = (GridletSubmission)GridletSubmittedList_.get(i);
if ( (gridletSub.getGridlet()).getGridletID() == glID )
{
// set this gridlet whose id comes with the event as not submitted,
// so that it is submitted as soon as possible.
((GridletSubmission) GridletSubmittedList_.get(i)).setSubmitted(false);
}
// Submit the gridlets with the "gridletSub.getSubmitted() == false"
if ( (gridletSub.getSubmitted() == false))
{
// we have to resubmit this gridlet
gl = ((GridletSubmission) GridletSubmittedList_.get(i)).getGridlet();
resourceID = getResList(); // Get list of resources from GIS
// If we have resources in the list
if ((resourceID != null) && (resourceID.length != 0))
{
index = random.nextInt(resourceID.length);
// make sure the gridlet will be executed from the begining
resetGridlet(gl);
// submits this gridlet to a resource
super.gridletSubmit(gl, resourceID[index]);
gridletSubmissionTime[gl.getGridletID()] = GridSim.clock();
// set this gridlet as submitted
((GridletSubmission) GridletSubmittedList_.get(i)).setSubmitted(true);
if (trace_flag)
{
System.out.println(super.get_name() +
": Sending Gridlet #" + i + " to " +
GridSim.getEntityName(resourceID[index]) +
" at clock: " + GridSim.clock());
// Write into a results file
write(super.get_name(), "Sending", gl.getGridletID(),
GridSim.getEntityName(resourceID[index]),
gl.getGridletStatusString(), GridSim.clock());
}
}
// No resources available at this moment, so schedule an event
// in the future. The event wil be in 15 min (900 sec), as
// resource failures may last several hours.
// This event includes the gridletID, so that the user will
// try to submit only this gridlet
else
{
super.send(super.get_id(), GridSimTags.SCHEDULE_NOW + 900,
GridUserFailureEx03.SUBMIT_GRIDLET,
new Integer(gl.getGridletID()) );
}
}// if (gridletSub.getSubmitted() == false)
i++;
} // while (i < GridletSubmittedList_.size())
} // processGridletSubmission |
cf10243a-6e2e-4354-a1b1-a50db3557ea9 | 2 | @Test
public void exceededCapacityTest() {
Student student1 = null;
Student student2 = null;
try {
student1 = familyService.findStudent(1);
student2 = familyService.findStudent(2);
} catch (InstanceNotFoundException e) {
fail("Activity not exists");
}
Activity activity = new Activity("Baloncesto Primaria", 1,
new BigDecimal(20.0), new BigDecimal(0), new HashSet<Student>());
try {
activityService.create(activity);
} catch (DuplicateInstanceException e) {
fail("Duplicated activity");
}
activityService.enrollmentStudentInActivity(student1, activity);
activityService.enrollmentStudentInActivity(student2, activity);
assertTrue(activityService.exceededCapacity(activity));
} |
95522aca-f99b-45f6-a27c-f3e986bab362 | 3 | private void resize() {
size = getWidth() < getHeight() ? getWidth() : getHeight();
width = getWidth();
height = getHeight();
if (width > 0 && height > 0) {
canvasBkg.setWidth(size);
canvasBkg.setHeight(size);
canvasFg.setWidth(size);
canvasFg.setHeight(size);
drawBackground();
drawForeground();
}
} |
002b3b12-471f-455d-a547-c75354ba00c0 | 1 | @Override
public List<Integer> save(List<Tourist> beans, GenericSaveQuery saveGeneric, Connection conn) throws DaoQueryException {
try {
return saveGeneric.sendQuery(SAVE_QUERY, conn, Params.fill(beans, (Tourist bean) -> {
Object[] obj = new Object[6];
obj[0] = bean.getOrder().getIdOrder();
obj[1] = bean.getFirstName();
obj[2] = bean.getMiddleName();
obj[3] = bean.getLastName();
obj[4] = bean.getBirthDate();
obj[5] = bean.getPassport();
return obj;
}));
} catch (DaoException ex) {
throw new DaoQueryException(ERR_TOURIST_SAVE, ex);
}
} |
21f45952-8946-4310-8b1f-d8ace005687e | 1 | public Object getElement(int index) {
LinkedElement<E> elem = findElement(index);
if (elem != null) {
return elem.getObj();
}
return null;
} |
5015d15b-64f7-4d43-a6f3-738f4cd77d1d | 1 | public boolean isUnity()
{
if (!isEmpty())
return first.next == null;
return false;
} |
c67ee580-7681-4c77-996e-251c2274c96c | 8 | public void move(){
if(destination != null){
if(location.x != destination.x){
if(Math.abs(location.x - destination.x) <= speed){
location.x = destination.x;
} else {
location.x += (location.x < destination.x) ? speed : -speed;
}
}
if(location.y != destination.y){
if(Math.abs(location.y - destination.y) <= speed)
{
location.y = destination.y;
} else {
location.y += (location.y < destination.y) ? speed : -speed;
}
}
if(destination.getLocation() == location.getLocation()){
destination = null;
}
}
} |
cbc2045a-7ce7-45bc-881d-4f9dc5ddcae0 | 3 | private void displayPlayAgain(String message) {
System.out.println("TicTacToeGameGUI::displayPlayAgain()");
int reply = JOptionPane.showConfirmDialog(null, message, message,
JOptionPane.YES_NO_OPTION);
if (reply == JOptionPane.YES_OPTION) {
m_game = new TicTacToeGame(m_playerOne, m_playerTwo);
m_game.setTurn(0);
for(int i = 0; i < BOARD_WIDTH; i++){
for(int j = 0; j < BOARD_HEIGHT; j++){
m_board[i][j].setIcon(m_bgImg);
}
}
}
} |
538e3abe-5209-4d6c-b70e-3fc5cbda9bad | 9 | private void loadRIBFromFile(String ribFilename) {
try {
logger.info("loading RIB from " + ribFilename);
FileReader fr = new FileReader(ribFilename);
BufferedReader br = new BufferedReader(fr);
String str = br.readLine();
int routes_total = 0;
int routes_read = 0;
while (str != null) {
routes_total++;
int message_type_size;
// check message format
if (str.startsWith("TABLE_DUMP2|")) {
message_type_size = 12;
} else if (str.startsWith("TABLE_DUMP|")) {
message_type_size = 11;
} else {
logger.trace("Update message does not start with 'TABLE_DUMP2|' or 'TABLE_DUMP|'. Skipping message...");
str = br.readLine();
continue;
}
// delete "TABLE_DUMP2|" or "TABLE_DUMP|"
str = str.substring(message_type_size);
// get name (number) of AS sent the update message
for (int i = 0; i < 3; i++) { // skip '|' 3 times
str = str.substring(str.indexOf("|") + 1);
}
int nameAS;
try { // parse AS's name
nameAS = Integer
.parseInt(str.substring(0, str.indexOf("|")));
} catch (NumberFormatException e) {
logger.trace(
"Can't parse the name of AS, which has sent the update message! Message will be skipped.",
e);
str = br.readLine();
continue;
}
if (!inputASs.contains(nameAS)) {
logger.trace("Update from AS "
+ nameAS
+ ", not contained in inputASs list found. Update message will be skipped.");
str = br.readLine();
continue;
}
// read prefix
Destination prefix;
String sprefix = str.substring(str.indexOf("|") + 1,
str.indexOf("/"));
try { // parse prefix
prefix = new Destination(Inet4Address.getByName(sprefix));
} catch (UnknownHostException e) {
logger.error(
"Can't parse prefix: "
+ sprefix
+ ". Update message will be skipped. It's normal if the prefix is IPv6, as I analyse only IPv4 prefixes.",
e);
str = br.readLine();
continue;
}
// read AS path
str = str.substring(str.indexOf("|") + 1); // delete AS name
str = str.substring(str.indexOf("|") + 1); // delete prefix
String ases = str.substring(0, str.indexOf("|"));
ASPath asPath = new ASPath(ases);
// add prefix with AS Path to the RIB!
announce(nameAS, prefix, asPath);
routes_read++;
str = br.readLine();
}
br.close();
fr.close();
logger.info(routes_read + " of " + routes_total
+ " loaded from RIB.");
} catch (FileNotFoundException e) {
logger.fatal("FileNotFound exception during reading RIB", e);
} catch (IOException e) {
logger.fatal("IO exception during reading RIB", e);
}
} |
5d3f3205-4af5-4144-bfb7-877dd576e986 | 6 | public static int dehexchar(char c) {
if (c >= '0' && c <= '9') {
return c - '0';
}
if (c >= 'A' && c <= 'F') {
return c - ('A' - 10);
}
if (c >= 'a' && c <= 'f') {
return c - ('a' - 10);
}
return -1;
} |
8906f7ba-bfed-4f64-ade8-11b5a40c14cf | 6 | public static String escape(String string) {
char c;
String s = string.trim();
StringBuffer sb = new StringBuffer();
int length = s.length();
for (int i = 0; i < length; i += 1) {
c = s.charAt(i);
if (c < ' ' || c == '+' || c == '%' || c == '=' || c == ';') {
sb.append('%');
sb.append(Character.forDigit((char)((c >>> 4) & 0x0f), 16));
sb.append(Character.forDigit((char)(c & 0x0f), 16));
} else {
sb.append(c);
}
}
return sb.toString();
} |
ae2da925-b2bf-43d9-af2e-722bfeaf217a | 5 | StringBuffer generateLayoutCode() {
StringBuffer code = new StringBuffer();
code.append("\t\tStackLayout stackLayout = new StackLayout ();\n");
if (stackLayout.marginWidth != 0) {
code.append("\t\tstackLayout.marginWidth = " + stackLayout.marginWidth + ";\n");
}
if (stackLayout.marginHeight != 0) {
code.append("\t\tstackLayout.marginHeight = " + stackLayout.marginHeight + ";\n");
}
code.append("\t\tshell.setLayout (stackLayout);\n");
for(int i = 0; i < children.length; i++) {
Control control = children[i];
code.append (getChildCode(control, i));
}
if (children.length > 0 && currentLayer != -1) {
code.append("\n\t\tstackLayout.topControl = " + names[currentLayer] + ";\n");
}
return code;
} |
ad0062c4-cc02-4b43-a068-4bc1ec4ffe4d | 8 | public BiCliqueGraph findBipartiteComplementAndVertexCoverComplement(HashSet<Integer> maximalCliqueK1, HashSet<Integer> maximalCliqueK2, Graph OrigGraph)
{
//Take bipartite complement from two maximal cliques and arrange the graph with minimal memory
int clique1Size = maximalCliqueK1.size();
int clique2Size = maximalCliqueK2.size();
System.out.println("Clique 1 : "+clique1Size);
System.out.println("Clique 2 : "+clique2Size);
//Remove the common nodes from maximal cliques
ArrayList<Integer> commonNode = findCommonNodesFromMaximalCliques(new ArrayList<Integer>(maximalCliqueK1), new ArrayList<Integer>(maximalCliqueK2));
int graphSize = clique1Size + clique2Size;
System.out.println("Original graph size 1 : "+OrigGraph.size());
Graph bipartiteGraph = new Graph(graphSize);
System.out.println("New graph size : "+graphSize);
CustomizedArrayList leftIndexArray = new CustomizedArrayList(clique1Size+1);
CustomizedArrayList rightIndexArray = new CustomizedArrayList(clique2Size+1);
ArrayList<Integer> indexArrayList = new ArrayList<Integer>();
int[] indexArray = new int[graphSize+1];
int leftVertexIndex = 1;
int rightVertexIndex = clique1Size + 1;
for(int u : maximalCliqueK1)
{
System.out.println("U Value : "+u);
for(int v : maximalCliqueK2)
{
System.out.println("V Value : "+v);
if((!OrigGraph.isNeighbor(u, v)) && (u!=v))
{
System.out.println("No Edge U :"+u+" V : "+v+" Left "+leftVertexIndex+" Right "+rightVertexIndex);
bipartiteGraph.addEdge(leftVertexIndex, rightVertexIndex);
bipartiteGraph.addEdge(rightVertexIndex, leftVertexIndex);
//Left index array doesnt have to be verified with contains method, because the u is iterated in the outer for loop. So it will be iterated only once
leftIndexArray.add(leftVertexIndex, u);
if(!rightIndexArray.contains(v))
{
rightIndexArray.add(rightVertexIndex, v);
rightVertexIndex++;
}
//indexArray[leftVertexIndex] = u;
//indexArray[rightVertexIndex] = v;
}
}
leftVertexIndex++;
//rightVertexIndex = clique1Size +1;
}
//Find the minimum vertex cover from the bipartite complement
MinimumVertexCover minVertexCover = new MinimumVertexCover();
BiPartiteGraph vertexCover = minVertexCover.getMinimumVertexCover(bipartiteGraph, leftVertexIndex, rightVertexIndex);
ArrayList<Integer> leftBiCliqueVertices = new ArrayList<Integer>();
ArrayList<Integer> rightBiCliqueVertices = new ArrayList<Integer>();
//Find vertex cover complement
for(int u : vertexCover.leftVertices)
{
for(int v : vertexCover.rightVertices)
{
if(!bipartiteGraph.isNeighbor(u, v))
{
leftBiCliqueVertices.add(leftIndexArray.get(u));
rightBiCliqueVertices.add(rightIndexArray.get(v));
}
}
}
System.out.println(vertexCover.leftVertices.size());
System.out.println(vertexCover.rightVertices.size());
//Validating biclique
boolean isValidBiClique = GraphValidationUtil.isValidBiClique(bipartiteGraph, leftBiCliqueVertices, rightBiCliqueVertices);
System.out.println("The BiClique is : "+isValidBiClique);
printBiGraph(bipartiteGraph, leftBiCliqueVertices, rightBiCliqueVertices);
return new BiCliqueGraph(leftBiCliqueVertices, rightBiCliqueVertices);
} |
a1f7b149-b638-48ef-ac56-ca257f622507 | 9 | public boolean newJudge(String one, String two) {
char[] oneChar = one.toCharArray();
char[] twoChar = two.toCharArray();
if (twoChar.length > oneChar.length + 1) {
return false;
}
for (int i = 0; i < oneChar.length; i++) {// start from c
int otherSize = i;// count other char which is not in one
boolean start = false;//
int currentIndex = i;
for (int j = 0; j < twoChar.length; j++) {
if (currentIndex > oneChar.length) {
if (twoChar.length > currentIndex + 1) {
return false;
} else {
return true;
}
}
if (twoChar[j] == oneChar[currentIndex]) { // c == c a==a t==t
if (start == true) {
currentIndex++;
} else {
start = true;
currentIndex++;
}
} else {
if (start == true) {
otherSize++;
if (otherSize > 1) {// other is
return false;
}
}
}
}
}
return true;
} |
3cf972c6-8f7d-4b21-bab9-2a20736a0233 | 7 | private void updateAllVQ() {
int c = movie.getCapacity();
for (int i = 0; i < numberOfAtoms; i++) {
try {
atom[i].updateVQ();
} catch (Exception e) {
atom[i].initializeVQ(c);
atom[i].updateVQ();
}
}
if (obstacles != null && !obstacles.isEmpty()) {
RectangularObstacle obs = null;
synchronized (obstacles.getSynchronizationLock()) {
for (int i = 0, n = obstacles.size(); i < n; i++) {
obs = obstacles.get(i);
if (obs.isMovable()) {
try {
obs.updateVQ();
} catch (Exception e) {
obs.initializeVQ(c);
obs.updateVQ();
}
}
}
}
}
} |
e1117c38-20cc-4425-99e1-8ae1a43f6b0c | 1 | public static void main(String[] args) throws FileNotFoundException {
Map<Integer, UserPreferences> treeMapUP = new TreeMap<Integer, UserPreferences>();
Map<Integer, ItemPreferences> treeMapIP = new TreeMap<Integer, ItemPreferences>();
readFile(treeMapUP, treeMapIP);
System.out.println("Op basis van users\n");
UserPreferences[] UP = new UserPreferences[treeMapUP.size()];
int index = 0;
for(UserPreferences up : treeMapUP.values()){
UP[index++] = up;
}
/*
System.out.println("\nOp basis van items\n");
for(ItemPreferences ip : treeMapIP.values()){
System.out.println(ip);
}
*/
Map<Integer, Map<Integer, Pearson>> pearsons = Pearson.getAllPearson(UP, 0.60);
Recommendation.getRecommendation(1, pearsons);
/*
System.out.println("\nRecommendations voor user 1\n");
System.out.println(Pearson.getRecommendations(treeMapUP.get(1), treeMapUP));
/*
for(UserPreferences up : treeMapUP.values()){
testUserHasItem(up, 101);
testUserHasItem(up, 103);
testUserHasItem(up, 106);
}
/*
ipArrayPointer = convertUPtoIP(UP, upArrayPointer, IP, ipArrayPointer);
quickSortIP(IP, 0, ipArrayPointer);
for(int i = 0; i < ipArrayPointer; i++){
IP[i].sort();
System.out.println(IP[i]);
}
*/
} |
042bd866-85fb-413d-8bb0-508101e79400 | 2 | public int getInt(int index) throws JSONException {
Object object = this.get(index);
try {
return object instanceof Number
? ((Number)object).intValue()
: Integer.parseInt((String)object);
} catch (Exception e) {
throw new JSONException("JSONArray[" + index +
"] is not a number.");
}
} |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.