method_id stringlengths 36 36 | cyclomatic_complexity int32 0 9 | method_text stringlengths 14 410k |
|---|---|---|
4dd1e423-39cf-481a-94bc-94e92b696ccb | 1 | @Override
public void add(Component component) {
if (mList != null) {
mList.add(component);
}
} |
8d81c57e-4143-4747-9da9-d8167f8e7ab8 | 4 | public void printString(TeaNode parent) {
String line = "|";
for (int i = 0; i < parent.level; i++) {
line += "-";
}
if (!parent.label.equals("")) {
line += "[" + parent.label + "]";
}
if (parent.classValue == null) {
line += parent.attribute;
} else {
line += " -> " + parent.classValue;
}
LOG.info(line);
for (TeaNode node : parent.children) {
printString(node);
}
} |
cad87b63-0063-47a7-ba0a-c12e102899f8 | 5 | private void jButton2ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton2ActionPerformed
// Start:
if (jTable1.isEditing()) {
JOptionPane.showMessageDialog(rootPane, "In part 3 select the cell with 'a' in the first column", "ERROR", JOptionPane.ERROR_MESSAGE);
}
else {
generalError = false;
if (!generalError) {
this.readTape();
}
if (!generalError) {
this.readTable();
}
if (!generalError) {
this.readIStage();
}
if (!generalError) {
g.start();
this.setSolution();
}
}
}//GEN-LAST:event_jButton2ActionPerformed |
88036668-bdfc-4899-8b58-47f5759e292a | 2 | public void test_add_RP_int_intarray_int() {
int[] values = new int[] {10, 20, 30, 40};
int[] expected = new int[] {10, 20, 30, 40};
OffsetDateTimeField field = new MockStandardDateTimeField();
int[] result = field.add(new TimeOfDay(), 2, values, 0);
assertEquals(true, Arrays.equals(expected, result));
values = new int[] {10, 20, 30, 40};
expected = new int[] {10, 20, 31, 40};
result = field.add(new TimeOfDay(), 2, values, 1);
assertEquals(true, Arrays.equals(expected, result));
values = new int[] {10, 20, 30, 40};
expected = new int[] {10, 20, 62, 40};
result = field.add(new TimeOfDay(), 2, values, 32);
assertEquals(true, Arrays.equals(expected, result));
values = new int[] {10, 20, 30, 40};
expected = new int[] {10, 21, 3, 40};
result = field.add(new TimeOfDay(), 2, values, 33);
assertEquals(true, Arrays.equals(expected, result));
values = new int[] {23, 59, 30, 40};
try {
field.add(new TimeOfDay(), 2, values, 33);
fail();
} catch (IllegalArgumentException ex) {}
values = new int[] {10, 20, 30, 40};
expected = new int[] {10, 20, 29, 40};
result = field.add(new TimeOfDay(), 2, values, -1);
assertEquals(true, Arrays.equals(expected, result));
values = new int[] {10, 20, 30, 40};
expected = new int[] {10, 19, 59, 40};
result = field.add(new TimeOfDay(), 2, values, -31);
assertEquals(true, Arrays.equals(expected, result));
values = new int[] {0, 0, 30, 40};
try {
field.add(new TimeOfDay(), 2, values, -31);
fail();
} catch (IllegalArgumentException ex) {}
} |
1b95610d-5c10-4010-a587-87e5d8e17830 | 5 | private void whois(CommandArgsIterator args_it) throws IOException
{
if (args_it.hasNext()) {
String user_name = args_it.next();
if (!args_it.hasNext()) {
Map<String, Client> users = this._server.getUsers();
String[] chan_names = null;
synchronized (users) {
Client user = users.get(user_name);
if (user != null) {
Map<String, Chan> chans = user.getChans();
synchronized (chans) {
chan_names = chans.keySet().toArray(new String[0]);
}
}
}
// Envoie la réponse hors des verrous.
if (chan_names != null) {
StringBuilder args = new StringBuilder("C");
for (String name : chan_names) {
args.append(" #");
args.append(name);
}
this.writeCommand(new Command('I', args.toString()));
} else
this.writeCommand(new Command('I', "D"));
this.traceEvent("Whois sur " + user_name);
this.writeCommand(Command.Ack);
} else
this.syntaxError();
} else
this.syntaxError();
} |
525f017f-936f-4ebc-9f74-baf6134f59f7 | 9 | void setOtherOptions() {
reverseMouseButtons2And3 = choices[mouseButtonIndex].getSelectedItem()
.equals("Reversed");
viewOnly = choices[viewOnlyIndex].getSelectedItem().equals("Yes");
if (viewer.vc != null)
viewer.vc.enableInput(!viewOnly);
shareDesktop = choices[shareDesktopIndex].getSelectedItem().equals(
"Yes");
String scaleString = choices[scaleCursorIndex].getSelectedItem();
if (scaleString.endsWith("%"))
scaleString = scaleString.substring(0, scaleString.length() - 1);
try {
scaleCursor = Integer.parseInt(scaleString);
} catch (NumberFormatException e) {
scaleCursor = 0;
}
if (scaleCursor < 10 || scaleCursor > 500) {
scaleCursor = 0;
}
if (requestCursorUpdates && !ignoreCursorUpdates && !viewOnly) {
labels[scaleCursorIndex].setEnabled(true);
choices[scaleCursorIndex].setEnabled(true);
} else {
labels[scaleCursorIndex].setEnabled(false);
choices[scaleCursorIndex].setEnabled(false);
}
if (viewer.vc != null)
viewer.vc.createSoftCursor(); // update cursor scaling
} |
171f5c94-43a2-4ab7-8a33-f6a4ca3352d3 | 8 | public String buildSearchString(String metr, String cont, String popu,
boolean greater, boolean exact) {
String qString = "SELECT * FROM " + dbase_name + " WHERE ";
ArrayList<String> queries = new ArrayList<String>();
if (!metr.equals("")) {
String str = "";
if (exact) {
str += "metropolis = \"" + metr + "\" ";
}else {
str += "metropolis LIKE \"" + "%" + metr + "%" + "\" ";
}
queries.add(str);
}
if (!cont.equals("")) {
String str = "";
if (exact) {
str += " continent = \"" + cont + "\" ";
} else {
str += " continent LIKE \"" + "%" + cont + "%" + "\" ";
}
queries.add(str);
}
if (!popu.equals("")) {
String str = "population ";
if (greater) {
str += "> ";
}else {
str += "< " + popu + " OR " + "population = ";
}
str += popu;
queries.add(str);
}
boolean first = true;
for (int i = 0; i < queries.size(); i++) {
if (!first) qString += " AND ";
qString += queries.get(i);
first = false;
}
qString += ";";
return qString;
} |
3d4b913a-6933-406c-8b57-9639dd235e7b | 6 | public int selectDivision(double[] v) {
int num = 0;
int[] topind = new int[RAND_DIM];
for (int i = 0; i < numberOfDimensions; i++) {
if (num < RAND_DIM || v[i] > v[topind[num - 1]]) {
if (num < RAND_DIM) {
topind[num++] = i;
} else {
topind[num - 1] = i;
}
// Bubble the right-most value to left.
int j = num - 1;
while (j > 0 && v[topind[j]] > v[topind[j - 1]]) {
// Swap.
int temp = topind[j];
topind[j] = topind[j - 1];
topind[j - 1] = temp;
j--;
}
}
}
int rnd = Utils.genRandomNumberInRange(0, num - 1);
return topind[rnd];
} |
37c31fc1-0b49-4306-857c-db8f38f11c7e | 6 | private void updateArduinoSensors() {
//get all actual Measurements from Arduino
//send 23 to get the data
RS485.hsWrite(sendBuffer,0,sendBuffer.length);
int readBytesSumm = 0;
int timeoutc =0;
byte[] sensorBytes = new byte[14];
//wait for an answer
while (readBytesSumm < 14 && timeoutc<20) {
readBytes = RS485.hsRead(readBuffer, 0, readBuffer.length);
if(readBytes>0) //arduino sends Data
{
for (int i = 0; i < readBytes; i++) {
sensorBytes[readBytesSumm+i]= readBuffer[i];
}
readBytesSumm+=readBytes;
}
timeoutc ++;
if(timeoutc>10){ //if timeout - 2nd. try
RS485.hsWrite(sendBuffer,0,sendBuffer.length);
readBytesSumm=0;
}
}
if(timeoutc==20) return;
this.UOdmometry = (double)(((sensorBytes[1])<<8) | (sensorBytes[0] & 0xff));
this.VOdometry = (double)(((sensorBytes[3])<<8) | (sensorBytes[2] & 0xff));
this.OdometryT = (int)((readBuffer[5]<<8) | (readBuffer[4] & 0xff));
this.FrontSensorDistance = (double)(((sensorBytes[7] & 0xff)<<8) | (sensorBytes[6] & 0xff));
this.FrontSideSensorDistance = (double)(((sensorBytes[9] & 0xff)<<8) | (sensorBytes[8] & 0xff));
this.BackSensorDistance = (double)(((sensorBytes[11] & 0xff)<<8) | (sensorBytes[10] & 0xff));
this.BackSideSensorDistance = (double)(((sensorBytes[13] & 0xff)<<8) | (sensorBytes[12] & 0xff));
this.controlOdo.addShift(this.UOdmometry,this.VOdometry,this.OdometryT);
this.navigationOdo.addShift(this.UOdmometry,this.VOdometry,this.OdometryT);
} |
12e2979e-196b-4ddd-9b37-da26bb1a3eda | 5 | public int executerRequeteMaj(Object... params) throws SQLException, IllegalStateException {
// Vérification de l'existence de la connexion.
if (this.conn == null) {
fermerConnexion();
throw new IllegalStateException("Impossible d'exécuter la requête car la connexion à la base de données n'a pas été établie");
}
// Vérification de l'existence de la requête préparée.
if (this.ps == null) {
fermerConnexion();
throw new IllegalStateException("Impossible d'exécuter une requête qui n'a pas été préparée");
}
// Passage des paramètres à la requête préparée.
try {
for (int i=0; i < params.length; i++)
this.ps.setObject(i+1, params[i]);
} catch (SQLException se) {
fermerConnexion();
throw new SQLException("Échec lors du passage des paramètres à la requête SQL"
+ " (" + se.getMessage() + ")", se);
}
// Nombre d'enregistrements affectés par la requête.
int nbEnreg;
// Exécution de la requête préparée.
try {
nbEnreg = this.ps.executeUpdate();
} catch (SQLException se) {
fermerConnexion();
throw new SQLException("Échec lors de l'exécution de la requête préparée : " + this.sql
+ " (" + se.getMessage() + ")", se);
}
return nbEnreg;
} |
dcbba30d-050a-4773-9be5-ba4c320a4a1f | 9 | int insertKeyRehash(double val, int index, int hash, byte state) {
// compute the double hash
final int length = _set.length;
int probe = 1 + (hash % (length - 2));
final int loopIndex = index;
int firstRemoved = -1;
/**
* Look until FREE slot or we start to loop
*/
do {
// Identify first removed slot
if (state == REMOVED && firstRemoved == -1)
firstRemoved = index;
index -= probe;
if (index < 0) {
index += length;
}
state = _states[index];
// A FREE slot stops the search
if (state == FREE) {
if (firstRemoved != -1) {
insertKeyAt(firstRemoved, val);
return firstRemoved;
} else {
consumeFreeSlot = true;
insertKeyAt(index, val);
return index;
}
}
if (state == FULL && _set[index] == val) {
return -index - 1;
}
// Detect loop
} while (index != loopIndex);
// We inspected all reachable slots and did not find a FREE one
// If we found a REMOVED slot we return the first one found
if (firstRemoved != -1) {
insertKeyAt(firstRemoved, val);
return firstRemoved;
}
// Can a resizing strategy be found that resizes the set?
throw new IllegalStateException("No free or removed slots available. Key set full?!!");
} |
ce20b9b0-4250-491e-ab6b-ba9124c09a20 | 8 | @Override
public String toString() {
switch (this) {
case SUNDAY: return "Su";
case MONDAY: return "M";
case TUESDAY: return "T";
case WEDNESDAY: return "W";
case THURSDAY: return "R";
case FRIDAY: return "F";
case SATURDAY: return "Sa";
case ANY: return " ";
default: throw new IllegalArgumentException();
}
} |
6d60b7eb-db94-4d1a-bdec-7b0766bd819c | 6 | String effTranslate(EffectType eff) {
switch (eff) {
case UTR_5_PRIME:
case START_GAINED:
return "5PRIME_UTR";
case UTR_3_PRIME:
return "3PRIME_UTR";
case NON_SYNONYMOUS_START:
case START_LOST:
return "NON_SYNONYMOUS_CODING";
case INTRON:
return "INTRONIC";
}
return eff.toString();
} |
a4903634-c6c4-4fbb-9fbf-4bf73d97073f | 7 | public static Reduce computeReduce(Sort sort, IORatioModel ioRatio) {
Reduce reduce = new Reduce();
FinalSortMerge eFinalSortMerge = sort.getFinalSortMerge();
MixSortMerge eMixSortMerge = sort.getMixSortMerge();
InMemorySortMerge eInMemorySortMerge = sort.getInMemorySortMerge();
assert(eFinalSortMerge != null || eMixSortMerge != null || eInMemorySortMerge != null);
//long inputkeyNum = 0; //equals "Reduce input groups" normally
long inputKeyValuePairsNum = 0; //equals "Reduce input records"
long inputBytes = sort.getReduceInputBytes(); // equals rawLength after merge in Sort
long outputKeyValuePairsNum; //equals "Reduce output records"
long outputBytes; // depends on "HDFS_BYTES_WRITTEN" and dfs.replication
if(eFinalSortMerge != null) {
inputKeyValuePairsNum += eFinalSortMerge.getRecords();
//inputBytes += eFinalSortMerge.getInMemorySegmentsSize();
}
if(eMixSortMerge != null) {
inputKeyValuePairsNum += eMixSortMerge.getInMemoryRecords() + eMixSortMerge.getOnDiskRecords();
//inputBytes += eMixSortMerge.getInMemorySegmentsSize() + eMixSortMerge.getOnDiskSegmentsSize();
}
if(eFinalSortMerge == null && eMixSortMerge == null && eInMemorySortMerge != null) {
System.err.println("No MixSortMerge or FinalSortMerge exist!");
}
outputKeyValuePairsNum = (long) (ioRatio.getReduceRecordsIoRatio() * inputKeyValuePairsNum);
outputBytes = (long) (ioRatio.getReduceBytesIoRatio() * inputBytes);
reduce.setInputkeyNum(0);
reduce.setInputKeyValuePairsNum(inputKeyValuePairsNum);
reduce.setInputBytes(inputBytes);
reduce.setOutputKeyValuePairsNum(outputKeyValuePairsNum);
reduce.setOutputBytes(outputBytes);
//System.out.println("[Reduce] <inputRecords = " + inputKeyValuePairsNum + ", inputBytes = " + inputBytes
// + ", outputRecords = " + outputKeyValuePairsNum + ", outputBytes = " + outputBytes + ">");
return reduce;
} |
144b1545-81db-4a16-8903-374b20dcdb73 | 7 | public static Integer lt(Object o1, Object o2){
if (o1 == null && o2 == null){
return 0;
} else if (o1 == null && o2 != null){
return 1;
} else if (o1 instanceof Number && o2 instanceof Number){
return ((Number)o1).doubleValue() < ((Number)o2).doubleValue() ? 1 : 0;
}
return 0;
} |
0b002a97-2223-406e-9f4f-a1d67fa89db3 | 7 | public String getValue(Keyword key) {
String value = "";
if (key.equals(Keyword.CONTENT)) {
value = content;
} else if (key.equals(Keyword.START)) {
value = start;
} else if (key.equals(Keyword.END)) {
value = end;
} else if (key.equals(Keyword.TYPE)) {
value = String.valueOf(type);
} else if (key.equals(Keyword.COMPLETED)) {
value = String.valueOf(isCompleted);
} else if (key.equals(Keyword.ARCHIVED)) {
value = String.valueOf(isArchived);
} else if (key.equals(Keyword.ALLDAY)) {
value = String.valueOf(isAllDayTask);
}
return value;
} |
d481a39c-c1cd-4405-a585-bfaf6286552d | 0 | public void setSpeed(int newSpeed)
{
Speed = newSpeed;
} |
dfe9ff71-1d5c-484b-87ab-b526ac332795 | 5 | @Override
public boolean equals(Object object) {
// TODO: Warning - this method won't work in the case the id fields are not set
if (!(object instanceof Province)) {
return false;
}
Province other = (Province) object;
if ((this.provinceID == null && other.provinceID != null) || (this.provinceID != null && !this.provinceID.equals(other.provinceID))) {
return false;
}
return true;
} |
6757d37f-2063-4940-819c-11beda6b59be | 9 | private void tabProdutosKeyReleased(java.awt.event.KeyEvent evt) {//GEN-FIRST:event_tabProdutosKeyReleased
performNavigateAction(evt);
if (evt.getKeyCode() == KeyEvent.VK_DOWN) {
if (booAlteracao) {
btnCancelar.doClick();
booAlteracao = false;
} else if (booInclusao) {
booInclusao = false;
}
setData(tabProdutos.getSelectedRow());
} else if (evt.getKeyCode() == KeyEvent.VK_UP) {
if (booAlteracao) {
btnCancelar.doClick();
booAlteracao = false;
} else if (booInclusao) {
booInclusao = false;
}
setData(tabProdutos.getSelectedRow());
} else if (evt.getKeyCode() == KeyEvent.VK_ENTER) {
if (booAlteracao) {
btnCancelar.doClick();
booAlteracao = false;
} else if (booInclusao) {
booInclusao = false;
}
setData(tabProdutos.getSelectedRow());
btnAlterar.doClick();
}
}//GEN-LAST:event_tabProdutosKeyReleased |
8ecdea4e-a9f8-4b3b-8950-dbde427e4e5f | 8 | @Override
public String stringify(int level) {
ArrayList<String> strArray = new ArrayList<String>();
int width = 0;
String strJSON;
for (Entry<Object, JSON> e : mapObject.entrySet()) {
strJSON = escape((String) e.getKey()) + ": " + e.getValue().stringify(level + 1);
strArray.add(strJSON);
width += strJSON.length() + 2;
}
if (width == 0)
width = 2;
String delim = "";
String indent = LINE_SEPARATOR;
StringBuilder sb = new StringBuilder("{");
int n = strArray.size();
if (widthForIndent >= 0 && width > widthForIndent) {
// do indent {インデントする場合}
for (int i = 0; i < level; ++i)
indent += indentString;
delim += indent;
for (String e : strArray) {
sb.append(delim);
sb.append(indentString);
sb.append(e);
delim = "," + indent;
}
if (n > 0)
sb.append(indent);
} else {
// do not indent {インデントしない場合}
for (String e : strArray) {
sb.append(delim);
sb.append(e);
delim = ", ";
}
}
sb.append("}");
return sb.toString();
} |
e47dec02-ae7f-4882-9793-245bd389f5ae | 4 | public void psvdIteration () {
initPara ();
boolean convergedY = false;
boolean convergedCb = false;
boolean convergedCr = false;
while (!convergedY) {
iter[0]++;
solveR(0);
solveD(0);
updatePara(0);
convergedY = judgeConverge(0);
// test
// if (iter[0] == 11) {
// convergedY = true;
// }
}
storeAndRoundDiag(0);
if (codeCbCr) {
while (!convergedCb) {
iter[1]++;
solveR(1);
solveD(1);
updatePara(1);
convergedCb = judgeConverge(1);
}
storeAndRoundDiag(1);
while (!convergedCr) {
iter[2]++;
solveR(2);
solveD(2);
updatePara(2);
convergedCr = judgeConverge(2);
}
storeAndRoundDiag(2);
}
} |
7f653324-2678-40f4-a954-14ab465449d2 | 7 | @Override
public void execute() {
if (Game.getClientState() != Game.INDEX_MAP_LOADED) {
Ivy.stop = 1000;
}
if (Game.getClientState() == Game.INDEX_MAP_LOADED && Ivy.stop == 1000) {
Ivy.stop = 50;
}
if (Ivy.client != Bot.client()) {
WidgetCache.purge();
Bot.context().getEventManager().addListener(this);
Ivy.client = Bot.client();
}
if (Walking.getEnergy() == 100 && !Walking.isRunEnabled()) {
Walking.setRun(true);
}
if (Widgets.get(640, 30).isOnScreen()) {
Widgets.get(640, 30).click(true);
}
} |
1e461eec-ff95-44fe-847a-4e547a3fb410 | 4 | private ArrayList<File> getAllFilesInDirectory(File directory) {
ArrayList<File> filesInDirectory = new ArrayList<File>();
File[] files = directory.listFiles();
System.out.println(directory.getPath());
for (int i = 0; i < files.length; i++) {
if (files[i].isFile()) {
filesInDirectory.add(files[i]);
}
if (files[i].isDirectory()) {
ArrayList<File> filesInSubDirectory = getAllFilesInDirectory(files[i]);
for (int j = 0; j < filesInSubDirectory.size(); j++) {
filesInDirectory.add(filesInSubDirectory.get(j));
}
}
}
return filesInDirectory;
} |
08fdaecc-7980-44bb-a386-ad189a624d48 | 2 | public static double[][] computeSpectrogram(double[] wavedata, int fft_window_length,
int fft_window_inc, String window_type) {
int segSize = wavedata.length;
int numWin = ((segSize - fft_window_length) / fft_window_inc) + 1;
FFT FFTreal = new FFT();
Window windowfunc = new Window(window_type);
double[][] spectrogram = new double[numWin][fft_window_length];
double[] frame = new double[fft_window_length];
int pos = 0; // start position for frame (considering overlap)
for (int i = 0; i < numWin; i++) {
/* take a frame from the input wavedata */
for (int k = 0; k < fft_window_length; k++) {
frame[k] = wavedata[pos + k];
}
/* multiply with window function */
frame = windowfunc.apply(frame);
/* compute power spectrum from real FFT and construct spectrogram */
spectrogram[i] = FFTreal.computeMagnitude(frame);
pos = pos + fft_window_inc;
}
/*
* NB: would need only fft_window_length/2 + 1 values. 1st value: DC, next
* fft_window_length/2 values are spectrum
*/
return spectrogram;
} |
ae8b0971-1d2e-431f-b389-b22431597548 | 1 | private void jButton3ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton3ActionPerformed
JFileChooser chooser = new JFileChooser("/");
chooser.setFileSelectionMode(JFileChooser.DIRECTORIES_ONLY);
int returnVal = chooser.showOpenDialog(this);
if(returnVal == JFileChooser.APPROVE_OPTION) {
jTextField4.setText(chooser.getSelectedFile().getPath());
}
}//GEN-LAST:event_jButton3ActionPerformed |
34713dc2-c890-45a2-bed7-4e4670a3197f | 0 | public String getFolderPath() {
return folderPath;
} |
e96149ef-871e-4b23-be13-c322d0cf3175 | 1 | public void accept(final MethodVisitor mv) {
Label[] labels = new Label[this.labels.size()];
for (int i = 0; i < labels.length; ++i) {
labels[i] = ((LabelNode) this.labels.get(i)).getLabel();
}
mv.visitTableSwitchInsn(min, max, dflt.getLabel(), labels);
} |
772bbe0a-1047-4882-bd10-fe173b64dea2 | 6 | @EventHandler(priority = EventPriority.LOWEST)
public void preprocessHandler(PlayerCommandPreprocessEvent event) {
if(event.isCancelled()) {
return;
}
if(event.getMessage().equalsIgnoreCase("/who") || event.getMessage().equalsIgnoreCase("/list") || event.getMessage().equalsIgnoreCase("/playerlist") || event.getMessage().equalsIgnoreCase("/online") || event.getMessage().equalsIgnoreCase("/players")) {
ListOnline list = new ListOnline(plugin);
list.List(event.getPlayer());
event.setCancelled(true);
}
} |
9e1c5ef2-4621-4c7d-80fb-698d8edf97ca | 3 | public Map<String, Object> getValues(boolean deep) {
Map<String, Object> result = new LinkedHashMap<String, Object>();
Configuration root = getRoot();
if (root != null && root.options().copyDefaults()) {
ConfigurationSection defaults = getDefaultSection();
if (defaults != null) {
result.putAll(defaults.getValues(deep));
}
}
mapChildrenValues(result, this, deep);
return result;
} |
d93f5357-c704-44ac-bbb2-4c88854cb1eb | 5 | public static DataType fromString(String value) {
switch (value) {
case "STRING": return STRING;
case "INTEGER": return INTEGER;
case "DOUBLE": return DOUBLE;
case "DATE": return DATE;
case "BOOLEAN": return BOOLEAN;
default: return null;
}
} |
de0af659-bc4d-4f38-a29a-c3e5deef423a | 0 | @Override
public void startSetup(Attributes atts) {
super.startSetup(atts);
setEnabled(false);
addActionListener(this);
Outliner.documents.addDocumentRepositoryListener(this);
} |
cd967027-624d-496a-ac7d-ae7d03f5e89e | 6 | @Test
public void testIsFullOutOfRange() {
Percolation p = new Percolation(10);
try {
p.isFull(-5, 5);
fail("Line above should throw exception");
} catch (IndexOutOfBoundsException e) {
/* Expected */
}
try {
p.isFull(0, 5);
fail("Line above should throw exception");
} catch (IndexOutOfBoundsException e) {
/* Expected */
}
try {
p.isFull(5, -5);
fail("Line above should throw exception");
} catch (IndexOutOfBoundsException e) {
/* Expected */
}
try {
p.isFull(5, 0);
fail("Line above should throw exception");
} catch (IndexOutOfBoundsException e) {
/* Expected */
}
try {
p.isFull(15, 5);
fail("Line above should throw exception");
} catch (IndexOutOfBoundsException e) {
/* Expected */
}
try {
p.isFull(5, 15);
fail("Line above should throw exception");
} catch (IndexOutOfBoundsException e) {
/* Expected */
}
} |
95889ac2-577c-4311-a320-2f581b6823cc | 1 | @Override
public int hashCode() {
int hash = 5;
hash = 37 * hash + (this.type != null ? this.type.hashCode() : 0);
return hash;
} |
125757b4-9e90-44e9-9a21-d3a9753b2271 | 3 | public void run() {
long lastTime = System.nanoTime();
long timer = System.currentTimeMillis();
final double ns = 1000000000.0 / 60.0;
double delta=0;
int frames=0;
int updates=0;
while(running){
long now = System.nanoTime();
delta += (now-lastTime) / ns;
lastTime=now;
while(delta >=1){
update();
updates++;
delta--;
}
render();
frames++;
if((System.currentTimeMillis() - timer) > 1000 ){
timer +=1000;
System.out.println(updates + " ups, "+ frames + " fps");
frame.setTitle(updates + " ups, "+ frames + " fps");
frames=0;
updates=0;
}
}
stop();
} |
0b0f5e84-4458-48fb-a7f0-a7f744baee1b | 2 | public void addFileVariablesAppearances(List<VariableAppearance> fileVariablesAppearances) {
fileVariablesAppearances = setFileToAppearanceList(fileVariablesAppearances);
for (VariableAppearance variableAppearance : fileVariablesAppearances) {
if (!this.fileVariablesAppearances.contains(variableAppearance)){
this.fileVariablesAppearances.add(variableAppearance);
}
}
Collections.sort(this.fileVariablesAppearances);
} |
b73bcdf2-4655-4399-8f5f-36ec873e6e36 | 5 | public Object [][] getDatos(){
Object[][] data = new String[getCantidadElementos()][colum_names.length];
//realizamos la consulta sql y llenamos los datos en "Object"
try{
if (colum_names.length>=0){
r_con.Connection();
String campos = colum_names[0];
for (int i = 1; i < colum_names.length; i++) {
campos+=",";
campos+=colum_names[i];
}
String consulta = ("SELECT "+campos+" "+
"FROM "+name_tabla+" WITH (INDEX("+indices_tabla[numero_ordenamiento_elegido]+"))");
PreparedStatement pstm = r_con.getConn().prepareStatement(consulta);
ResultSet res = pstm.executeQuery();
int i = 0;
while(res.next()){
for (int j = 0; j < colum_names.length; j++) {
data[i][j] = res.getString(j+1);
}
i++;
}
res.close();
}
} catch(SQLException e){
System.out.println(e);
} finally {
r_con.cierraConexion();
}
return data;
} |
b926f586-35ab-41c6-8b18-16ac9d114853 | 3 | @Override
public boolean equals(Object obj) {
if (obj == null) {
return false;
}
if (getClass() != obj.getClass()) {
return false;
}
final TabelProdSubBrand other = (TabelProdSubBrand) obj;
if (!Objects.equals(this.subBrandId, other.subBrandId)) {
return false;
}
return true;
} |
379dcd41-4358-4a22-88c7-c6a7dc0552fc | 7 | public String toString() {
String modstr = "";
switch (modifier) {
case ABOUT:
modstr = "[ABOUT]";
break;
case ESTIMATED:
modstr = "[ESTIMATED]";
break;
case CALCULATED:
modstr = "[CALCULATED]";
break;
case WFT_ESTIMATED:
modstr = "[WFT-ESTIMATED]";
break;
}
return (day == 0 ? "" : "" + day + " ") +
(month == 0 ? "" : gregorianMonthNames[month] + " ") +
fmtI4.format(year) + (oldStyle ? "/"+fmtI2.format((year+1)%100) : "") + modstr;
} |
a5808f1f-5eb4-4c4b-9e93-0d06a474272f | 9 | public static int hg_step6(int step, double[][] cost, int[] rowCover, int[] colCover, double maxCost, int[][] mask)
{
System.out.println("STEP 6");
//What STEP 6 does:
//Find smallest uncovered value in cost: a. Add it to every element of covered rows
//b. Subtract it from every element of uncovered columns. Go to step 4.
double minval = findSmallest(cost, rowCover, colCover, maxCost);
//double maxval = findLargest(cost, rowCover, colCover, maxCost);
double delta = minval;//maxCost - maxval;
//System.out.println("Weight delta = " + delta + " " + maxWeight);
for (int i=0; i<rowCover.length; i++)
{
for (int j=0; j<colCover.length; j++)
{
if (rowCover[i]==1)
{
cost[i][j] = cost[i][j] + minval;
}
if (colCover[j]==0)
{
cost[i][j] = cost[i][j] - minval;
}
}
}
EdgeSet es = new EdgeSet();
Float rowSmallest;
Float val = new Float(-1);
Float colSmallest;
for(int i = 0; i < cost[0].length; i++){
// colSmallest = new Float(Integer.MAX_VALUE);
// for(int j = 0; j < cost.length; j++){
// if(cost[j][i] < colSmallest && colCover[j] == 1){
// colSmallest = new Float(cost[j][i]);
// val = (float) ((float) (maxWeight - cost[j][i]) - originalRowLeast[i]);
// }
// }
if(hasStarredAndPrimedinCol(mask, cost, i))
p.set(i, new Float(p.get(i) + delta));
//p.set(i, val);
}
// find q values by iterating through each row
for(int i = 0; i < cost.length; i++){
// rowSmallest = new Float(0/*Integer.MAX_VALUE*/);
// for(int j = 0; j < cost[0].length; j++){
// if(cost[i][j] >= rowSmallest && rowCover[i] == 0){
// rowSmallest = new Float(cost[i][j]);
// val = (float) (maxWeight - cost[i][j] - originalRowLeast[i]);
// }
// }
val = new Float(0/*Integer.MAX_VALUE*/);
for(int j = 0; j < cost[0].length; j++){
if(array[i][j] - p.get(j) > val){
val = (float) array[i][j] - p.get(j);
}
}
// if(rowCover[i] == 0)
// q.set(i, new Float(q.get(i) - delta));
q.set(i, val);
}
// add to edgeset
es.add(q, p);
step = 4;
cameFromStep6 = true;
return step;
} |
c6786f2e-66a7-46bd-b1a6-78742e6a1651 | 6 | public String getDescription() {
if(fullDescription == null) {
if(description == null || isExtensionListInDescription()) {
fullDescription = description==null ? "(" : description + " (";
// build the description from the extension list
Enumeration<String> extensions = filters.keys();
if(extensions != null) {
fullDescription += "." + (String) extensions.nextElement();
while (extensions.hasMoreElements()) {
fullDescription += ", ." + (String) extensions.nextElement();
}
}
fullDescription += ")";
} else {
fullDescription = description;
}
}
return fullDescription;
} |
19a6b1d1-aa78-4c65-b584-65bef4a8733e | 3 | public boolean getScrollableTracksViewportWidth()
{
if (scrollableWidth == ScrollableSizeHint.NONE)
return false;
if (scrollableWidth == ScrollableSizeHint.FIT)
return true;
// STRETCH sizing, use the greater of the panel or viewport width
if (getParent() instanceof JViewport)
{
return (((JViewport)getParent()).getWidth() > getPreferredSize().width);
}
return false;
} |
93bea5a0-6f5d-4076-97d1-93a911dd69d5 | 0 | @Override
public double computeNetAssetValue() {
return 0;
} |
d16f9d61-55aa-4a8b-9e0d-5160b3d8da6d | 4 | private void updateGamePanel()
{
gamePanel.removeAll();
gamePanel.setLayout(new GridLayout(2,6));
Card[] deck = latest.getBoard().getDeck();
for(int i = 0; i < 6-deck.length; i++)
{
gamePanel.add(new JLabel());
}
for(Card c : deck)
{
JLabel label = getClickableCardLabel(c);
label.setHorizontalAlignment(SwingConstants.CENTER);
gamePanel.add(label);
}
for(int i = 0; i < 6; i++)
{
JPanel panel = getTreasureDisplayPanel(latest
.getBoard().getLoot(i), 6);
if(latest.getDay() == i)
{
panel.setBorder(BorderFactory.createLoweredBevelBorder());
}
else
{
panel.setBorder(BorderFactory.createLineBorder(Color.BLACK));
}
gamePanel.add(panel);
}
gamePanel.revalidate();
} |
5d671b05-13bc-4263-b0f5-664ad154f1d5 | 5 | public static void main(String[] args) {
Log.addListener(new ConsoleLogger());
Log.setDebugMode(false);
try {
TorrentManager.getInstance().load(XML_SETTINGS);
} catch (XMLException e) {}
catch (IOException e) {
Log.e("Eblast:: IOException", "IO problem");
}
if (System.getProperty("os.name").equals(MAC_OSX_NAME)) {
// Activate the OSX menu integration (if we are on OSX)
System.setProperty("apple.laf.useScreenMenuBar", "true");
}
// Activate the Clearlooks linux
try {
// Set the System LookAndFeel
UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
}
catch (Exception e) {
Log.e("LookAndFeel", "Cannot able to activate the LookAndFeel.");
}
EventQueue.invokeLater(new Runnable() {
public void run() {
try {
MainUI frame = new MainUI();
frame.setVisible(true);
} catch (Exception e) {
e.printStackTrace();
}
}
});
} |
71f7856c-4d56-4392-b9a8-0e618d3f7a98 | 2 | private void catchAction(HttpServletRequest request){
Enumeration paramNames = request.getParameterNames();
while(paramNames.hasMoreElements()) {
String paramName = (String)paramNames.nextElement();
String[] paramValues = request.getParameterValues(paramName);
if(paramValues.length != 0){
runAction(paramName, paramValues[0]);
}
}
} |
9861c922-04f2-49b3-9f00-0db913b4186d | 0 | public static void resetId()
{
id = 1;
} |
e34f255b-29cb-4288-876c-2556a02b43cd | 1 | private static String getStringFromDocument(Document doc) {
try {
DOMSource domSource = new DOMSource(doc);
StringWriter writer = new StringWriter();
StreamResult result = new StreamResult(writer);
TransformerFactory tf = TransformerFactory.newInstance();
Transformer transformer = tf.newTransformer();
transformer.transform(domSource, result);
return writer.toString();
} catch (TransformerException ex) {
ex.printStackTrace();
return null;
}
} |
6c5444b2-53ff-4e0a-b278-8e9e7ff4a24d | 5 | public static void main(String[] args) {
Meowzy bot = new Meowzy();
Log.consoleLog("Starting up...");
Config.loadConfiguration();
File check = new File("meowzy.db");
if(!check.exists()) {
bot.sql.resetDatabase();
}
try {
bot.connect(Config.getServerAddress());
} catch (NickAlreadyInUseException e) {
if (!Config.getAutoNickChange()) {
Log.consoleLog("Error", "Could not connect to server: " + Config.getServerAddress());
e.printStackTrace();
} else {
Log.consoleLog("Error", "Nick already in use!");
}
} catch (IOException e) {
Log.consoleLog("Error", "Could not connect to server: " + Config.getServerAddress());
e.printStackTrace();
} catch (IrcException e) {
Log.consoleLog("Error", "Could not connect to server: " + Config.getServerAddress());
e.printStackTrace();
}
} |
77e45d39-892a-4c06-822e-b45b949490f5 | 2 | public static URL getRenderURL(int typeID, short size) throws ApiException {
if(Arrays.binarySearch(renderSizes, size) < 0)
throw new ApiException("Invallid image size: "+Short.toString(size)+". Allowed sizes are: "+Arrays.toString(characterPortraitSizes));
try {
return new URL(IMAGE_SERVICE_URL+"/Render/"+Integer.toString(typeID)+"_"+Short.toString(size)+".png");
} catch (MalformedURLException e) {
throw new ApiException("Problem getting Render url for typeID: "+Integer.toString(typeID)+" with size: "+Short.toString(size), e);
}
} |
13f696b9-0501-4b51-8ba2-2d820efa4d3f | 2 | public static boolean isAllianceID(int id) {
try {
InputSource data;
String notCorp = "{\"info\":null,\"characters\":[]}";
data = Download
.getFromHTTP("http://evewho.com/api.php?type=allilist&id="
+ id);
BufferedReader bufferedReader = new BufferedReader(
new InputStreamReader(data.getByteStream(), "UTF-8"));
String line = bufferedReader.readLine();
bufferedReader.close();
if (line.equalsIgnoreCase(notCorp)) {
return false;
}
return true;
} catch (Exception e) {
e.printStackTrace();
return false;
}
} |
39e23b6c-88bf-4c26-a22a-d80f20a733fa | 3 | * @return Returns true if the cell is movable.
*/
public boolean isCellMovable(Object cell)
{
mxCellState state = view.getState(cell);
Map<String, Object> style = (state != null) ? state.getStyle()
: getCellStyle(cell);
return isCellsMovable() && !isCellLocked(cell)
&& mxUtils.isTrue(style, mxConstants.STYLE_MOVABLE, true);
} |
c91031b7-2cc0-4b33-867e-e3890d314329 | 7 | synchronized public void finished(int status, Recording rec){
// if the video downloaded successful remove the video from the list and
// update the database that the video download was successful
if(status == FINISHED_SUCCESSFUL){
LOG.info("The recording with id " + rec.getId() + " was downloaded sucessfully to " + rec.getFilename());
// now find the video with the respective ID again and remove it from the list
// find out which of the threads was successful and update the database accordingly
try {
for(Recording recording: _recordings){
if(recording.getId().equals(rec.getId())){
recording.setComplete();
break;
}
}
_rcm.update(rec);
// when everything is complete move the file from the temp directory to the real
// download directory
try {
File src = new File(Parameter.getTmpDirectory() + "/" + rec.getFilename());
File dest = new File(Parameter.getDownloadDirectory() + "/" + rec.getFilename());
if(!src.renameTo(dest)) LOG.debug("The file " + " was moved successfully to: ..");
} catch(Exception e){
LOG.error("Could not move file " + rec.getFilename() + "from temporary directory to download directory. The error was:" + e.getMessage());
}
} catch (SQLException ex){
LOG.error("Error when trying to set the recording with id " + rec.getId() + " to complete.");
LOG.error(ex.getMessage());
}
}
numberOfRunningThreads--;
// start the next download as long as there are videos left in the list
if(_trackkeeper.size() > 0){
this.startNext();
}
} |
936adb3b-0536-466d-95ed-4161e0db4062 | 3 | public void run() {
String producedData = "";
try {
while (true) {
if (producedData.length()>75) break;
producedData = new String("Hi! "+producedData);
sleep(1000); // It takes a second to obtain data.
theBuffer.putLine(producedData);
}
}
catch (Exception e) {
// Just let thread terminate (i.e., return from run).
}
} // run |
6993f7de-81cb-4dc0-b479-60654737a358 | 8 | public static Matrix read (BufferedReader input) throws java.io.IOException {
StreamTokenizer tokenizer= new StreamTokenizer(input);
// Although StreamTokenizer will parse numbers, it doesn't recognize
// scientific notation (E or D); however, Double.valueOf does.
// The strategy here is to disable StreamTokenizer's number parsing.
// We'll only get whitespace delimited words, EOL's and EOF's.
// These words should all be numbers, for Double.valueOf to parse.
tokenizer.resetSyntax();
tokenizer.wordChars(0,255);
tokenizer.whitespaceChars(0, ' ');
tokenizer.eolIsSignificant(true);
java.util.Vector v = new java.util.Vector();
// Ignore initial empty lines
while (tokenizer.nextToken() == StreamTokenizer.TT_EOL);
if (tokenizer.ttype == StreamTokenizer.TT_EOF)
throw new java.io.IOException("Unexpected EOF on matrix read.");
do {
v.addElement(Double.valueOf(tokenizer.sval)); // Read & store 1st row.
} while (tokenizer.nextToken() == StreamTokenizer.TT_WORD);
int n = v.size(); // Now we've got the number of columns!
double row[] = new double[n];
for (int j=0; j<n; j++) // extract the elements of the 1st row.
row[j]=((Double)v.elementAt(j)).doubleValue();
v.removeAllElements();
v.addElement(row); // Start storing rows instead of columns.
while (tokenizer.nextToken() == StreamTokenizer.TT_WORD) {
// While non-empty lines
v.addElement(row = new double[n]);
int j = 0;
do {
if (j >= n) throw new java.io.IOException
("Row " + v.size() + " is too long.");
row[j++] = Double.valueOf(tokenizer.sval).doubleValue();
} while (tokenizer.nextToken() == StreamTokenizer.TT_WORD);
if (j < n) throw new java.io.IOException
("Row " + v.size() + " is too short.");
}
int m = v.size(); // Now we've got the number of rows.
double[][] A = new double[m][];
v.copyInto(A); // copy the rows out of the vector
return new Matrix(A);
} |
f21c75cc-fc01-4e8c-9149-3f5e3b48b7fc | 8 | public UnitsSettings(final ScheduleDialog scheduleDialog) {
super(new FlowLayout(FlowLayout.LEFT, 0, 0));
input = new JTextField[6][];
JPanel p1 = new JPanel(new GridLayout(7, 3, 10, 5));
p1.add(new JLabel(" Number "));
p1.add(new JLabel("Stations"));
p1.add(new JLabel(" Cycles "));
for (int i = 0; i < 6; i++) {
input[i] = new JTextField[i > 3? 2 : 3];
for (int j = 0; j < 3; j++) {
if (i > 3 && j == 2)
p1.add(Box.createRigidArea(null));
else {
input[i][j] = new JTextField(6);
p1.add(input[i][j]);
}
}
}
JPanel p2 = new JPanel(new GridLayout(7, 1, 0, 5));
p2.add(Box.createRigidArea(null));
for (int i = 0; i < 6; i++) {
String text = FunctionType.values()[i].toString();
p2.add(new JLabel(text.charAt(0) + text.substring(1).toLowerCase()));
}
Border b1 = BorderFactory.createTitledBorder(null, "Functional Units", TitledBorder.LEFT, TitledBorder.TOP,
new Font("Consolas", Font.PLAIN, 19), Color.RED);
JPanel p3 = new JPanel(new BorderLayout(20, 0));
p3.add(p1);
p3.add(p2, BorderLayout.WEST);
p3.setBorder(BorderFactory.createCompoundBorder(b1, BorderFactory.createEmptyBorder(0, 10, 5, 10)));
JButton apply = new JButton("Apply");
apply.setFocusable(false);
apply.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
int[][] config;
Simulator simulator = (Simulator)scheduleDialog.getOwner();
try {
config = getConfiguration();
} catch (Exception ex) {
simulator.errorDialog.showError("Invalid/Missing input");
return;
}
try {
Simulator.processor.getUnitSet().setConfiguration(config);
scheduleDialog.refresh();
} catch (Exception ex) {
simulator.errorDialog.showError(ex.getMessage());
return;
}
}
});
rob = new InputBox("ROB Entries", 100, 8, null);
JPanel p4 = new JPanel(new BorderLayout(0, 5));
p4.add(rob);
p4.add(apply, BorderLayout.SOUTH);
p4.setBorder(BorderFactory.createCompoundBorder(BorderFactory.createTitledBorder(""), BorderFactory.createEmptyBorder(7, 10, 7, 10)));
setConfiguration(new int[][]{
{6},
{1, 2, 1},
{1, 2, 2},
{1, 2, 5},
{1, 2, 10},
{1, 2},
{1, 2},
});
add(p3);
add(Box.createRigidArea(new Dimension(10, 0)));
add(p4);
} |
04200789-a40a-4b16-988f-fa08159a698e | 1 | protected void initializePhase(int w) {
Arrays.fill(committedWorkers, false);
Arrays.fill(parentWorkerByCommittedJob, -1);
committedWorkers[w] = true;
for (int j = 0; j < dim; j++) {
minSlackValueByJob[j] = costMatrix[w][j] - labelByWorker[w]
- labelByJob[j];
minSlackWorkerByJob[j] = w;
}
} |
9257b5ea-791a-4398-90c8-3e32a675a254 | 6 | private static void main2(String[] args) {
Config.cmdline(args);
ThreadGroup g = HackThread.tg();
setupres();
MainFrame f = new MainFrame(800, 600);
if (Config.fullscreen)
f.setfs();
f.resetCenter();
f.g = g;
if (g instanceof haven.error.ErrorHandler) {
final haven.error.ErrorHandler hg = (haven.error.ErrorHandler) g;
hg.sethandler(new haven.error.ErrorGui(null) {
public void errorsent() {
hg.interrupt();
}
});
}
f.run();
dumplist(Resource.loadwaited, Config.loadwaited);
dumplist(Resource.cached(), Config.allused);
if (ResCache.global != null) {
try {
Collection<Resource> used = new LinkedList<Resource>();
for (Resource res : Resource.cached()) {
if (res.prio >= 0)
used.add(res);
}
Writer w = new OutputStreamWriter(
ResCache.global.store("tmp/allused"), "UTF-8");
try {
Resource.dumplist(used, w);
} finally {
w.close();
}
} catch (IOException e) {
}
}
} |
88a43471-73a5-455c-91f5-a60d0f2f49c5 | 0 | public NewParticipantMessage(String name) {
this.name = name;
} |
43caa787-a7e3-41ed-abf7-ec0919cb3eac | 1 | private IRemoteCallObject setResponse(long key, IRemoteCallObject response,
boolean complete, boolean error) {
IRemoteCallObject obj = getCallObj(key);
if (obj != null) {
obj.setResponseRemoteCallObject(response);
obj.setComplete(complete);
obj.setError(error);
}
return obj;
} |
247a7789-9915-44ff-a770-e13ef2e96b54 | 0 | public void setjScrollPane2(JScrollPane jScrollPane2) {
this.jScrollPane2 = jScrollPane2;
} |
e728f53e-c03c-4156-8872-ec41654bc2b1 | 7 | public static void receiveAndBounceMessage(String incomingMessage, Socket socket)
{
incomingMessage = incomingMessage.substring(6);
ServerSocket temp = null;
int id = Integer.parseInt(incomingMessage.split("\\\\")[0]);
String fileName = incomingMessage.split("\\\\")[1];
writeToAll("/file " + id + "\\" + fileName);
byte[] incomingBytes = new byte[1];
try
{
temp = new ServerSocket(Integer.parseInt(Resource.PORT)+10);
socket = temp.accept();
inStream = socket.getInputStream();
}
catch(Exception e) { e.printStackTrace(); }
baos = new ByteArrayOutputStream();
try
{
numBytes = inStream.read(incomingBytes, 0, incomingBytes.length);
do
{
baos.write(incomingBytes);
numBytes = inStream.read(incomingBytes);
} while (numBytes != -1);
inStream.close();
socket.close();
temp.close();
}
catch(IOException ex) { ex.printStackTrace(); }
for(int i = 0; i < userList.size(); i++)
{
try
{
socket = new Socket(clientThreads.get(i).IP.substring(1),Integer.parseInt(Resource.PORT) + clientThreads.get(i).ID);
bOut = new BufferedOutputStream(socket.getOutputStream());
}
catch (IOException e1) { e1.printStackTrace(); }
if (bOut != null)
{
byte[] outArray = baos.toByteArray();
try
{
bOut.write(outArray, 0, outArray.length);
bOut.flush();
bOut.close();
socket.close();
} catch (IOException ex) { ex.printStackTrace(); }
}
}
} |
66e8bbb1-07a5-4cc2-844f-2467e8eb6f32 | 5 | public double calculate(double a, double b)
{
switch (value)
{
case '+': return a+b;
case '-': return a-b;
case '*': return a*b;
case '/': return a/b;
case '^': return Math.pow(a, b);
}
return 0;
} |
cff798b2-bb0f-4d11-8094-a9d3d16a64d9 | 9 | public void scrollCellToView(JTable table, int rowIndex, int vColIndex) {
if (!(table.getParent() instanceof JViewport)) {
return;
}
JViewport viewport = (JViewport) table.getParent();
Rectangle rect = table.getCellRect(rowIndex, vColIndex, true);
Rectangle viewRect = viewport.getViewRect();
int x = viewRect.x;
int y = viewRect.y;
if (rect.x >= viewRect.x && rect.x <= (viewRect.x + viewRect.width - rect.width)){
} else if (rect.x < viewRect.x){
x = rect.x;
} else if (rect.x > (viewRect.x + viewRect.width - rect.width)) {
x = rect.x - viewRect.width + rect.width;
}
if (rect.y >= viewRect.y && rect.y <= (viewRect.y + viewRect.height - rect.height)){
} else if (rect.y < viewRect.y){
y = rect.y;
} else if (rect.y > (viewRect.y + viewRect.height - rect.height)){
y = rect.y - viewRect.height + rect.height;
}
viewport.setViewPosition(new Point(x,y));
} |
dd108df1-7536-4221-b292-e67bc67f2056 | 9 | public synchronized <U extends T> U put(U obj) {
if (obj == null) {
return null;
}
Entry<T>[] entries = mEntries;
int hash = hashCode(obj);
int index = (hash & 0x7fffffff) % entries.length;
for (Entry<T> e = entries[index], prev = null; e != null; e = e.mNext) {
T iobj = e.get();
if (iobj == null) {
// Clean up after a cleared Reference.
if (prev == null) {
entries[index] = e.mNext;
} else {
prev.mNext = e.mNext;
}
mSize--;
} else if (e.mHash == hash && obj.getClass() == iobj.getClass() && equals(obj, iobj)) {
// Found canonical instance.
return (U) iobj;
} else {
prev = e;
}
}
if (mSize >= mThreshold) {
cleanup();
if (mSize >= mThreshold) {
rehash();
entries = mEntries;
index = (hash & 0x7fffffff) % entries.length;
}
}
entries[index] = new Entry<T>(this, obj, hash, entries[index]);
mSize++;
return obj;
} |
3323d326-6b18-4160-8575-400a7d02fa17 | 5 | public static void unpackConfig(Archive container) {
Stream stream = new Stream(container.get("varp.dat"));
Varp.anInt702 = 0;
int cacheSize = stream.getUnsignedShort();
if (Varp.cache == null) {
Varp.cache = new Varp[cacheSize];
}
if (Varp.anIntArray703 == null) {
Varp.anIntArray703 = new int[cacheSize];
}
for (int i = 0; i < cacheSize; i++) {
if (Varp.cache[i] == null) {
Varp.cache[i] = new Varp();
}
Varp.cache[i].readValues(stream, i);
}
if (stream.offset != stream.payload.length) {
System.out.println("varptype load mismatch");
}
} |
c3d18bdc-1d48-4c92-b31b-9214a9031c9b | 5 | private static String select_action() {
String result = null;
System.out.print("available action: ");
Vector<String> actions = new Vector<String>(Arrays.asList("lvlup", "catacomb", "pack_of_wolves", "calendar", "pray"));
for(int i = 0; i < actions.size(); i++) {
System.out.print("[" + i + "]" + actions.get(i) +"; ");
}
System.out.println();
BufferedReader reader = new BufferedReader(new InputStreamReader(System.in));
String input = null;
try {
input = reader.readLine();
}catch (IOException e) {
e.printStackTrace();
}
int number;
try {
number = Integer.parseInt(input);
} catch (Exception e) {
ExceptionHandler.stringToInteger(input);
return null;
}
if(number >= actions.size() || number < 0) {
System.out.println("input number `" + number + "` is too big");
result = null;
} else {
result = actions.get(number);
}
return result;
} |
7d47ae2b-3413-4794-a878-1c568f4a970a | 0 | public int getFileCreatedMask() {
return JNotify.FILE_CREATED;
} |
fdcc7f8d-f24d-43b7-9a5b-aa9168ce42ea | 8 | private static String compute(String nBlocksStr, String kBlocksStr, int blocksCount) {
StringBuilder solutionStringBuilder = new StringBuilder();
double nBlocks[] = new double[blocksCount];
double kBlocks[] = new double[blocksCount];
int index = 0;
for (String blockToken : nBlocksStr.split("\\s")) {
nBlocks[index ++] = Double.parseDouble(blockToken);
}
index = 0;
for (String blockToken : kBlocksStr.split("\\s")) {
kBlocks[index ++] = Double.parseDouble(blockToken);
}
Arrays.sort(nBlocks);
Arrays.sort(kBlocks);
int minIndexNBlocks = 0;
int minIndexKBlocks = 0;
int maxIndexKBlocks = kBlocks.length - 1;
int nScore = 0;
// Deceitful War
while(minIndexNBlocks < nBlocks.length) {
if (nBlocks[minIndexNBlocks] < kBlocks[minIndexKBlocks]) {
// K scores
maxIndexKBlocks --;
} else {
// N scores
nScore ++;
minIndexKBlocks ++;
}
minIndexNBlocks ++;
}
solutionStringBuilder.append(String.valueOf(nScore));
solutionStringBuilder.append(" ");
// Regular War
minIndexNBlocks = 0;
minIndexKBlocks = 0;
maxIndexKBlocks = kBlocks.length - 1;
nScore = 0;
while (minIndexNBlocks < nBlocks.length) {
double chosenN = nBlocks[minIndexNBlocks];
boolean didKScore = false;
while(minIndexKBlocks < kBlocks.length) {
if (chosenN < kBlocks[minIndexKBlocks]) {
// K scores
didKScore = true;
kBlocks[minIndexKBlocks] = -1;
minIndexKBlocks ++;
break;
} else {
minIndexKBlocks ++;
}
}
minIndexKBlocks = 0;
if (!didKScore) {
nScore ++;
}
minIndexNBlocks ++;
}
solutionStringBuilder.append(String.valueOf(nScore));
return solutionStringBuilder.toString();
} |
91493874-726a-45a4-b873-3c5e35dc6c38 | 6 | @Override
public void actionPerformed(ActionEvent e) {
boolean selection = false;
DocUtils.buttonDoClick(e);
wordProcessor.area1.requestFocus();
String text = wordProcessor.area1.getSelectedText();
int start = 0, length = 0;
if (text != null) {
selection = true;
start = wordProcessor.area1.getSelectionStart();
length = text.length();
}
if (wordProcessor.italic.isSelected()) {
try {
if (selection) {
wordProcessor.doc.remove(start, length);
wordProcessor.doc.insertString(start, text, wordProcessor.doc.getStyle("italic"));
}
}
catch (BadLocationException ble) {
ble.printStackTrace();
}
}
else {
try {
if (selection) {
wordProcessor.doc.remove(start, length);
wordProcessor.doc.insertString(start, text, wordProcessor.doc.getStyle("regular"));
}
}
catch (BadLocationException ble) {
ble.printStackTrace();
}
}
} |
89fb5392-d1e6-41ef-b7d8-f7e1fa131e76 | 2 | protected void calcDIR_FileSize() {
byte[] bTemp = new byte[4];
for (int i = 28;i < 32; i++) {
bTemp[i-28] = bytesOfFAT32Element[i];
}
DIR_FileSize = byteArrayToInt(bTemp);
if (DIR_FileSize >= 1024) {
fileSize = DIR_FileSize / 1024;
fileSizeMod = "Кб";
} else {
fileSize = DIR_FileSize;
fileSizeMod = "байт";
}
} |
5a876aca-77f0-4ad0-bcb2-3408a4b41f5f | 7 | public String weekdayF()
{
int when = weekday();
if (when == 0)
return "Sunday";
else if (when == 1)
return "Monday";
else if (when == 2)
return "Tuesday";
else if (when ==3)
return "Wednesday";
else if (when ==4)
return "Thursday";
else if (when ==5)
return "Friday";
else if (when ==6)
return "Saturday";
else
return "";
} |
d9591d7a-e7b0-4824-8a23-fe01bf58af0c | 2 | public List<Juoma> haeJuomat() throws DAOPoikkeus {
// avataan yhteys
Connection yhteys = avaaYhteys();
ArrayList<Juoma> juomat = new ArrayList<Juoma>();
try {
// Haetaan tietokannasta tuotteet
String sql = "SELECT tuoteID, numero, nimi, hinta FROM Tuote WHERE tuoteryhmaID = 2 OR tuoteryhmaID = 3 AND aktiivinen = 1 ORDER BY numero ASC";
Statement haku = yhteys.createStatement();
ResultSet tulokset = haku.executeQuery(sql);
while (tulokset.next()) {
int id = tulokset.getInt("tuoteID");
int numero = tulokset.getInt("numero");
String nimi = tulokset.getString("nimi");
double hinta = tulokset.getDouble("hinta");
// LISÄTÄÄN TIEDOTTEET LISTAAN
juomat.add(new Juoma(numero, nimi, hinta, id));
}
} catch (Exception e) {
// Tapahtui jokin virhe?
throw new DAOPoikkeus("Tietokantahaku aiheutti virheen.", e);
} finally {
// Lopulta aina suljetaan yhteys!
suljeYhteys(yhteys);
}
return juomat;
} |
8a2ca31a-da90-4ed7-9fbe-399c84630395 | 1 | public static void initLevel() throws SlickException{
// game objects
meds = new ArrayList<Pickable>();
mobs = new ArrayList<Enemy>();
alpha = 0;
new Level(++level);
new Character(Level.startPoint.getX(), Level.startPoint.getY()-1);
timer = 10000;
if(level == -1){
Sounds.music.stop();
}
} |
4654d7a0-e39e-4460-ab94-6bc2e90d837d | 8 | public String readParameter(String name, boolean required) {
if (inAnApplet) {
String s = getParameter(name);
if ((s == null) && required) {
fatalError(name + " parameter not specified");
}
return s;
}
for (int i = 0; i < mainArgs.length; i += 2) {
if (mainArgs[i].equalsIgnoreCase(name)) {
try {
return mainArgs[i+1];
} catch (Exception e) {
if (required) {
fatalError(name + " parameter not specified");
}
return null;
}
}
}
if (required) {
fatalError(name + " parameter not specified");
}
return null;
} |
01a02853-535d-415a-8690-9bc271e2b38b | 6 | public static boolean getRoadsData(String pathName) {
DocumentBuilderFactory docBuilderFactory;
DocumentBuilder docBuilder;
Document document = null;
try {
docBuilderFactory = DocumentBuilderFactory.newInstance();
docBuilder = docBuilderFactory.newDocumentBuilder();
document = docBuilder.parse(new File(pathName));
document.getDocumentElement().normalize();
} catch (ParserConfigurationException e) {
System.err.println(pathName + " XML Format error.");
e.printStackTrace();
return false;
} catch (IOException e) {
System.err.println(pathName + " Write/Read error.");
e.printStackTrace();
return false;
} catch (SAXException e) {
System.err.println(pathName + " SAXException.");
e.printStackTrace();
return false;
}
NodeList names = document.getElementsByTagName("name");
NodeList coordinates = document.getElementsByTagName("coordinates");
ArrayList<String> rNames = new ArrayList<String>();
ArrayList<String> rCoordinates = new ArrayList<String>();
int j = 0;
for (int i = 0; i < names.getLength(); i++) {
if (names.item(i).getParentNode().getNodeName() == "Placemark"
|| coordinates.item(i).getParentNode().getNodeName() == "Placemark") {
rNames.add(names.item(i).getTextContent());
rCoordinates.add(coordinates.item(j).getTextContent()
.replaceAll(",0.0", ""));
j++;
}
}
return IOFiles.writeRoadsFile("cleanData/roadsData.txt", rNames,
rCoordinates);
} |
3112c87d-3fbc-4e2f-9d90-39406eeb804a | 0 | public boolean onNode(TreeNode node, double x, double y) {
return Math.sqrt(x * x + y * y) <= NODE_RADIUS;
} |
4e444ddf-e0e4-4a97-a081-bed8252882b4 | 8 | public static Cons kifVariableDeclarationsToStella(Stella_Object tree, boolean errorP) {
if (Logic.stellaVariableDeclarationsP(tree)) {
{
return (((Cons)(tree)));
}
}
else {
if (Logic.kifVariableDeclarationP(tree)) {
{
return (Cons.cons(Logic.oneKifVariableDeclarationToStella(tree), Stella.NIL));
}
}
else {
{ boolean testValue000 = false;
testValue000 = Stella_Object.consP(tree);
if (testValue000) {
{ boolean alwaysP000 = true;
{ Stella_Object d = null;
Cons iter000 = ((Cons)(tree));
loop000 : for (;!(iter000 == Stella.NIL); iter000 = iter000.rest) {
d = iter000.value;
if (!Logic.kifVariableDeclarationP(d)) {
alwaysP000 = false;
break loop000;
}
}
}
testValue000 = alwaysP000;
}
}
if (testValue000) {
{
{ ConsIterator it = ((Cons)(tree)).allocateIterator();
while (it.nextP()) {
it.valueSetter(Logic.oneKifVariableDeclarationToStella(it.value));
}
}
return (((Cons)(tree)));
}
}
else {
{
if (errorP) {
{ OutputStringStream stream000 = OutputStringStream.newOutputStringStream();
{ Object old$PrintreadablyP$000 = Stella.$PRINTREADABLYp$.get();
try {
Native.setBooleanSpecial(Stella.$PRINTREADABLYp$, true);
stream000.nativeStream.println("PARSING ERROR: Illegal declaration syntax: `" + tree + "'.");
Logic.helpSignalPropositionError(stream000, Logic.KWD_ERROR);
} finally {
Stella.$PRINTREADABLYp$.set(old$PrintreadablyP$000);
}
}
throw ((ParsingError)(ParsingError.newParsingError(stream000.theStringReader()).fillInStackTrace()));
}
}
return (null);
}
}
}
}
}
} |
3352f6e0-393c-439c-8b00-5d2836117f77 | 0 | public static void main(String[] args) throws IOException
{
Properties props = new Properties();
props.setProperty("email", "gmail");
OutputStream os = new FileOutputStream("D:\\Java SE\\src\\xml\\properties_into_xml\\exmaple.xml");
props.storeToXML(os, "Email", "UTF-8");
System.out.println("Done");
InputStream in = new FileInputStream("D:\\Java SE\\src\\xml\\properties_into_xml\\exmaple.xml");
props.loadFromXML(in);
String email = props.getProperty("email");
System.out.println(email);
} |
3fdb0b5d-9a26-40ba-aa4e-7ad0b6739f80 | 9 | protected void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
PrintWriter out = new PrintWriter(response.getOutputStream());
response.setContentType("application/json");
HostsSettings hostssettings = new HostsSettings();
JSONArray hypervisorList=null;
try {
hypervisorList = new JSONArray();
for(Host host : hostssettings.getHosts()) {
final Connect conn = Libvirt.getHypervisorConnection(host);
if(conn==null) continue;
//stopped machines
final String[] domains_inactive_name = conn.listDefinedDomains();
//active machine and state
final int[] ids=conn.listDomains();
final ArrayList<String> domains_active_name = new ArrayList<String>();
final ArrayList<String> domains_active_state = new ArrayList<String>();
Domain d=null;
for(int i=0; i< ids.length; i++){
d=conn.domainLookupByID(ids[i]);
domains_active_name.add(d.getName());
String st;
int x=d.isActive();
if(x==1)
st="running";
else if(x==0)
st="stopped";
else
st="error";
domains_active_state.add(st);
d.free();
}
//composizione oggetti json
//hypervisorList (array of hypervisor)
//hypervisor(name of hypervisor,machines)
//machines (name o machines,state)
JSONObject hypervisor = new JSONObject()
.put("ip",host.getName()+"@"+host.getHostname());
JSONArray machines = new JSONArray();
JSONObject vm_state=null;
//running domains
for(int k=0; k< domains_active_name.size();k++){
vm_state= new JSONObject()
.put("name", domains_active_name.get(k))
.put("status", domains_active_state.get(k));
machines.put(vm_state);
}
//stopped domains
for(int j=0; j< domains_inactive_name.length; j++){
vm_state = new JSONObject()
.put("name", domains_inactive_name[j])
.put("status", "stopped");
machines.put(vm_state);
}
hypervisor.put("machines", machines);
hypervisorList.put(hypervisor);
if(conn.close()!=0) System.out.println("errore chiusura connessione");
}
} catch (LibvirtException e) {e.printStackTrace();}
finally
{
System.gc();
}
out.println(hypervisorList);
out.close();
} |
2b85c5c1-62b1-43fd-8905-ec69ff49a6f8 | 4 | public void run() {
//Create Map
map = new HashMap<Double, Planet>();
for (Planet p : oldPlanets) {
map.put(p.getId(), p);
}
for (Planet p : currentPlanets) {
if (map.get(p.getId()) == null) {
continue;
}
if (!(map.get(p.getId()).getCoords().equals(p.getCoords()))) {
moved.add(p);
}
}
} |
ee5d4584-d674-4743-8a2a-8397b962597f | 7 | public int getDamage(){
int dmg = 0;
int rand = (int) (Math.random() * 100);
if(rand < 50){
dmg = level;
}else if(rand < 60){
dmg = (int) (level * 1.2);
}else if(rand < 70){
dmg = (int) (level * 1.4);
}else if(rand < 80){
dmg = (int) (level * 1.6);
}else if(rand < 90){
dmg = (int) (level * 1.8);
}else if(rand < 96){
dmg = (int) (level * 2.0);
}else if(rand < 100){
dmg = (int) (level * 4.0);
}
return dmg;
} |
ee84ebd1-4e95-4236-b628-f67d7270a0b3 | 1 | public Atom getLoc()
{
if(location != null)
return location;
else
return null;
} |
cce8cdcc-0fcf-4c4e-a606-2c040233e0c7 | 5 | private synchronized void rollback(){
// Do not show this window
this.setVisible(false);
JOptionPane.showMessageDialog(null,"Rolling Back Installation ...", "Software Rollback",JOptionPane.WARNING_MESSAGE);
if(installationDirectory != null){
// Get all the directories where the software was installed
File[] files = installationDirectory.listFiles();
if(files != null){
// Get the software directory name
String fileName = properties.getProperty("softwareDir");
// Find the directory to delete
for(File file : files){
// WARNING : Provide the right directory - otherwise this program will delete unwanted files
if(file.getName().equals(fileName)){
// Delete the directory
try{ InstallerUtils.deleteFile(file); }
catch(IOException e){ e.printStackTrace(); }
// Stop looking for other files to delete
break;
}
}
}
}
} |
bb3d1a8c-cb7b-446a-9577-088225aac780 | 6 | public static void main(String[] args) {
// read in bipartite network with 2N vertices and E edges
// we assume the vertices on one side of the bipartition
// are named 0 to N-1 and on the other side are N to 2N-1.
int N = Integer.parseInt(args[0]);
int E = Integer.parseInt(args[1]);
int s = 2*N, t = 2*N + 1;
FlowNetwork G = new FlowNetwork(2*N + 2);
for (int i = 0; i < E; i++) {
int v = StdRandom.uniform(N);
int w = StdRandom.uniform(N) + N;
G.addEdge(new FlowEdge(v, w, Double.POSITIVE_INFINITY));
StdOut.println(v + "-" + w);
}
for (int i = 0; i < N; i++) {
G.addEdge(new FlowEdge(s, i, 1.0));
G.addEdge(new FlowEdge(i + N, t, 1.0));
}
// compute maximum flow and minimum cut
FordFulkerson maxflow = new FordFulkerson(G, s, t);
StdOut.println();
StdOut.println("Size of maximum matching = " + (int) maxflow.value());
for (int v = 0; v < N; v++) {
for (FlowEdge e : G.adj(v)) {
if (e.from() == v && e.flow() > 0)
StdOut.println(e.from() + "-" + e.to());
}
}
} |
a55e0a04-a8d5-4844-a7b9-bd87d2fed963 | 0 | public String getID() {
return ID;
} |
ebf0c96a-d941-4d32-a50e-6de855246073 | 5 | public static RealMatrixExt median(RealMatrixExt[] matrices) {
int numMat = matrices.length;
double[] aggregator = new double[numMat];
int nRows = matrices[0].getRowDimension();
int nCols = matrices[0].getColumnDimension();
// TODO: check if #rows and #cols is equal in all matrices!
double[][] result = new double[nRows][nCols];
boolean center = !(numMat % 2 == 0);
int ctridx;
if (center)
ctridx = (numMat - 1) / 2;
else
ctridx = (numMat / 2) - 1;
for (int r = 0; r < nRows; r++) {
for (int c = 0; c < nCols; c++) {
for (int m = 0; m < numMat; m++) {
aggregator[m] = matrices[m].getEntry(r, c); // [r][c];
}
Arrays.sort(aggregator);
if (center)
result[r][c] = aggregator[ctridx];
else
result[r][c] = (aggregator[ctridx] + aggregator[ctridx + 1]) / 2;
}
}
RealMatrixExt resultM = new RealMatrixExt(result);
resultM.setType(matrices[0].getType()); // set type id to 1st matrix in
// array
return resultM;
} |
7f7f3b74-224a-4bdf-b56a-3f65d9c44c20 | 8 | @Override
public void cover(ImageBit[][] list) {
ImageBit ib = new ImageBit();
for (int i = 0; i < 50; i++) {
for (int j = 0; j < 50; j++) {
ib = list[i][j];
if (ib.isCovered()) {
continue;
}
LegoUtil.cover(ib, list, this.width, this.height,
BlockType.ThreeAndOne);
if (ib.isCovered()) {
System.out.println(ib.getX() + "," + ib.getY() + ","
+ ib.getRGB() + "," + ib.isCovered() + ","
+ ib.getBlockType());
twoAndOneList.add(ib);
draw(g, ib, this.width, this.height);
}
}
}
for (int i = 0; i < 50; i++) {
for (int j = 0; j < 50; j++) {
ib = list[i][j];
if (ib.isCovered()) {
continue;
}
LegoUtil.cover(ib, list, this.height, this.width, BlockType.OneAndThree);
if (ib.isCovered()) {
System.out.println(ib.getX() + "," + ib.getY() + "," + ib.getRGB() + ","
+ ib.isCovered() + "," + ib.getBlockType());
oneAndTwoList.add(ib);
draw(g, ib, this.height, this.width);
}
}
}
} |
9c049b0b-e7ca-445f-85c5-2634f25f35ff | 8 | public boolean execute() {
DonneesSimulation donnees = this.donnees;
Robot robot = donnees.getRobot(this.nRobot);
int temp = 0, is_incendie = 0;
boolean return_value = false;
for(int i = 0; i<donnees.getIncendies().size(); i++) { /* On vérifie qu'il y a bien un incendie sur la case du robot */
if (donnees.getIncendie(i).getCase().equal(robot.getPosition())) {
is_incendie = 1;
temp = i;
}
}
if (is_incendie == 0) { /* Si il n'y a pas d'incendie */
robot.setDateDisponibilite(1);
throw new Error("Le robot "+robot.getClass().getName().split("DonneesSimulation.")[1]+" numéro "+this.nRobot+" n'est pas sur un incendie");
}
Incendie incendie = donnees.getIncendie(temp);
if (incendie.getPotentielEau() == 0) { /* On regarde si l'incendie est déja éteint (à enlever par la suite si on enlève
l'incendie de la liste) */
System.out.println("Le robot "+robot.getClass().getName().split("DonneesSimulation.")[1]+" numéro "+this.nRobot+" veut intervenir mais l'incendie est déjà éteint\n");
robot.setDateDisponibilite(1);
return_value = true;
}
else if (robot.getReservoir() == 0) { /* On regarde si le réservoir du robot est vide */
System.out.println("Le réservoir du robot "+robot.getClass().getName().split("DonneesSimulation.")[1]+" numéro "+this.nRobot+" est vide\n");
robot.setDateDisponibilite(1);
return_value = true;
}
else {
int potentiel_incendie = incendie.getPotentielEau();
int volume_intervention_robot = robot.getVolumeIntervention();
double temps_intervention_robot = robot.getTempsIntervention();
long date_disponibilite;
if (potentiel_incendie > robot.getReservoir()) { /* On détermine la nouvelle date de disponibilité du robot selon
la capacité qu'à le robot à éteindre entièrement l'incendie ou non */
date_disponibilite = (int)((robot.getReservoir()/volume_intervention_robot)*temps_intervention_robot);
}
else {
date_disponibilite = (int)((potentiel_incendie/volume_intervention_robot)*temps_intervention_robot);
}
incendie.setNRobot(this.nRobot); /* On affecte le robot à l'incendie */
robot.setDateDisponibilite(date_disponibilite); /* On set la date de dispo du robot */
incendie.setPotentielEau(robot.deverserEau()); /* On diminue le potentiel en eau de l'incendie */
if(robot.getReservoir() == 0){
System.out.println("Le réservoir du robot "+robot.getClass().getName().split("DonneesSimulation.")[1]+" numéro "+this.nRobot+" vient de se vider " + incendie.getPotentielEau() + "\n");
robot.setDateDisponibilite(1);
return_value = true;
}
else System.out.println("Le robot "+robot.getClass().getName().split("DonneesSimulation.")[1]+" numéro "+this.nRobot+" vient de verser de l'eau sur l'incendie et son réservoir n'est plus que de "+robot.getReservoir());
if (incendie.getPotentielEau() == 0) { /* Si l'incendie est déjà éteint alors on dit au simu qu'on a finit le travail */
System.out.println("L'incendie " + robot.getNIncendie() + " est éteint !\n");
this.donnees.removeIncendie(incendie);
robot.setNIncendie(-1);
}
else { /* Sinon on lui dit qu'il faut continuer à agir au prochain T */
System.out.println("L'incendie n'est pas encore éteint et le réservoir du robot "+robot.getClass().getName().split("DonneesSimulation.")[1]+" numéro "+this.nRobot+" est de : "+robot.getReservoir());
this.setDate(1);
return_value = false;
}
}
return return_value;
} |
c58578c7-8e44-41bc-b946-5cd34e5ca9fa | 6 | public static TokenizerTable unstringifyTokenizerTable(String table) {
{ TokenizerTable result = TokenizerTable.newTokenizerTable();
int acode = (int) 'A';
String line = null;
int count = 0;
StringBuffer transitions = null;
char separator = '|';
int start = 0;
int end = 0;
end = Native.string_position(table, separator, start);
line = Native.string_subsequence(table, start, end);
start = end + 1;
count = ((int)(Native.stringToInteger(line)));
end = Native.string_position(table, separator, start);
line = Native.string_subsequence(table, start, end);
start = end + 1;
transitions = edu.isi.stella.javalib.Native.makeMutableString((((int)(count / 2.0))), Stella.NULL_CHARACTER);
{ int i = Stella.NULL_INTEGER;
int iter000 = 0;
int upperBound000 = ((int)((count / 2.0) - 1));
for (;iter000 <= upperBound000; iter000 = iter000 + 1) {
i = iter000;
edu.isi.stella.javalib.Native.mutableString_nthSetter(transitions, ((char) ((((int) (line.charAt((2 * i))) - acode) | ((((int) (line.charAt(((2 * i) + 1))) - acode) << 4))))), i);
}
}
result.transitions = transitions.toString();
end = Native.string_position(table, separator, start);
line = Native.string_subsequence(table, start, end);
start = end + 1;
count = ((int)(Native.stringToInteger(line)));
result.uniqueStateNames = Vector.newVector(count);
{ int i = Stella.NULL_INTEGER;
int iter001 = 0;
int upperBound001 = count - 1;
for (;iter001 <= upperBound001; iter001 = iter001 + 1) {
i = iter001;
end = Native.string_position(table, separator, start);
line = Native.string_subsequence(table, start, end);
start = end + 1;
(result.uniqueStateNames.theArray)[i] = (Stella.internKeyword(line));
}
}
end = Native.string_position(table, separator, start);
line = Native.string_subsequence(table, start, end);
start = end + 1;
count = ((int)(Native.stringToInteger(line)));
result.stateNames = Vector.newVector(count);
{ int i = Stella.NULL_INTEGER;
int iter002 = 0;
int upperBound002 = count - 1;
for (;iter002 <= upperBound002; iter002 = iter002 + 1) {
i = iter002;
end = Native.string_position(table, separator, start);
line = Native.string_subsequence(table, start, end);
start = end + 1;
(result.stateNames.theArray)[i] = (Stella.internKeyword(line));
}
}
end = Native.string_position(table, separator, start);
line = Native.string_subsequence(table, start, end);
start = end + 1;
count = ((int)(Native.stringToInteger(line)));
end = Native.string_position(table, separator, start);
line = Native.string_subsequence(table, start, end);
start = end + 1;
result.legalEofStates = Vector.newVector(count);
{ int i = Stella.NULL_INTEGER;
int iter003 = 0;
int upperBound003 = count - 1;
for (;iter003 <= upperBound003; iter003 = iter003 + 1) {
i = iter003;
switch (line.charAt(i)) {
case 'T':
(result.legalEofStates.theArray)[i] = Stella.TRUE_WRAPPER;
break;
case 'F':
(result.legalEofStates.theArray)[i] = Stella.FALSE_WRAPPER;
break;
default:
{ OutputStringStream stream000 = OutputStringStream.newOutputStringStream();
stream000.nativeStream.print("`" + line.charAt(i) + "' is not a valid case option");
throw ((StellaException)(StellaException.newStellaException(stream000.theStringReader()).fillInStackTrace()));
}
}
}
}
return (result);
}
} |
1f7177b0-579b-4cbd-ab1a-3aed79f0d9b8 | 5 | private static void appendJSONPair(StringBuilder json, String key, String value) throws UnsupportedEncodingException {
boolean isValueNumeric = false;
try {
if (value.equals("0") || !value.endsWith("0")) {
Double.parseDouble(value);
isValueNumeric = true;
}
} catch (NumberFormatException e) {
isValueNumeric = false;
}
if (json.charAt(json.length() - 1) != '{') {
json.append(',');
}
json.append(escapeJSON(key));
json.append(':');
if (isValueNumeric) {
json.append(value);
} else {
json.append(escapeJSON(value));
}
} |
4c382ab2-9214-4251-bc80-8eeeb76d2940 | 7 | public static void main(String[] args) {
// TODO code application logic here
int mult = 0;
for (int i = 1; i < 1000; i++) {
for (int j = i + 1; j < 1000; j++) {
for (int k = j + 1; k < 1000; k++) {
if (((i * i + j * j) == k * k) && (i + j + k == 1000)) {
mult = i * j * k;
break;
}
}
if (mult > 0) {
break;
}
}
if (mult > 0) {
break;
}
}
System.out.println(mult);
} |
37d1485b-5dc9-4799-8a50-29b20f2b3f19 | 8 | @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(ID())!=null)
{
mob.tell(target,null,null,L("<S-NAME> <S-IS-ARE> already tethered."));
return false;
}
if(!super.invoke(mob,commands,givenTarget,auto,asLevel))
return false;
final boolean success=proficiencyCheck(mob,0,auto);
if(success)
{
final CMMsg msg=CMClass.getMsg(mob,target,this,verbalCastCode(mob,target,auto),auto?L("<T-NAME> become(s) magically tethered!"):L("^S<S-NAME> chant(s) about a magical tether!^?"));
if(mob.location().okMessage(mob,msg))
{
mob.location().send(mob,msg);
lastRoom=mob.location();
beneficialAffect(mob,target,asLevel,0);
}
}
else
return beneficialWordsFizzle(mob,null,L("<S-NAME> chant(s) about a magical tether, but the magic fades."));
// return whether it worked
return success;
} |
6d99efa8-e0d2-47d6-b9a2-aad5f4b01fa6 | 8 | private void readAvgDays()
{
try
{
CsvReader csvReader = new CsvReader(sourceFileAvgDays);
if(csvReader.readHeaders() == true)
{
while(csvReader.readRecord()==true)
{
//apar_id,apar_name,address,place,province,Country_code,zip_code,telephone_1,comp_reg_no,acctype
// TODO : constants for each header ?
String id = csvReader.get("apar_id");
String client = csvReader.get("client");
String avg = csvReader.get("avg");
// TODO: only import this client for now
if(clientFilter.length()==0 || client.equalsIgnoreCase(clientFilter))
{
Company c = allCompanies.getCompanyFromId(id);
if(c!=null)
{
double val = XmlHelper.getDoubleFromXmlString(avg);
c.getAverageDaysToPaymentCollection().upsert(new DoubleDatedValue(Calendar.getInstance().getTime(), val));
}
}
}
}
csvReader.close();
}
catch(FileNotFoundException fnfe)
{
logger.warning(fnfe.getMessage());
}
catch(IOException ioe)
{
logger.warning(ioe.getMessage());
}
catch(Exception e)
{
logger.warning(e.getMessage());
}
} |
3383f255-02d8-4cb3-b2b2-3cc927549a0c | 7 | public void save()
{
AccessTasks tasks = new AccessTasks();
String title = txtTitle.getText();
User creator = null;
User assignedTo = null;
for (User u : users.getUsers())
{
if (u.getUserName().equals(lblCreatedByField.getText()))
{
creator = u;
}
if (u.getUserName().equals(cboxAssignedTo.getText()))
{
assignedTo = u;
}
}
Task task;
try
{
task = new Task(title, creator, assignedTo);
task.setComments(txtComments.getText());
task.setDescription(txtDescription.getText());
task.setUpdatedDate(Calendar.getInstance());
task.setPriority(PriorityCode.valueOf(cboxPriority.getText()));
task.setStatus(StatusCode.valueOf(cboxStatus.getText()));
final int MIN_YEAR = 1800;
Calendar currentDueDate = FormatDate
.convertDateTimeToCalendar(dueDate);
if (currentDueDate.get(Calendar.YEAR) < MIN_YEAR)
{
throw new IllegalArgumentException("Please enter a date with a year no less than " + MIN_YEAR);
}
task.setDueDate(currentDueDate);
try
{
double number;
number = Double.parseDouble(txtTimeEstimate.getText());
task.setTimeEstimate(number);
number = Double.parseDouble(txtTimeSpent.getText());
task.setTimeSpent(number);
}
catch (NumberFormatException nfe)
{
MyMessageBox error = new MyMessageBox(shell, "Error", "Please enter a non-negative numeric value for Time Estimate and Time Spent.", "OK");
error.open();
}
tasks.getTasks();
tasks.addTask(task);
MyMessageBox success = new MyMessageBox(shell, "Save succeeded", "Task has been saved", "OK");
success.open();
shell.close();
}
catch (IllegalArgumentException iae)
{
MyMessageBox error;
if (iae.getMessage() == null)
{
error = new MyMessageBox(shell, "Illegal Field", "Check your inputs", "OK");
}
else
{
error = new MyMessageBox(shell, "Illegal Field", iae.getMessage(), "OK");
}
error.open();
}
} |
0763a6f4-5c31-42ae-94fd-4140057112b0 | 8 | public CodeTree buildCodeTree() {
// Note that if two nodes have the same frequency, then the tie is broken by which tree contains the lowest symbol. Thus the algorithm is not dependent on how the queue breaks ties.
Queue<NodeWithFrequency> pqueue = new PriorityQueue<NodeWithFrequency>();
// Add leaves for symbols with non-zero frequency
for (int i = 0; i < frequencies.length; i++) {
if (frequencies[i] > 0)
pqueue.add(new NodeWithFrequency(new Leaf(i), i, frequencies[i]));
}
// Pad with zero-frequency symbols until queue has at least 2 items
for (int i = 0; i < frequencies.length && pqueue.size() < 2; i++) {
if (i >= frequencies.length || frequencies[i] == 0)
pqueue.add(new NodeWithFrequency(new Leaf(i), i, 0));
}
if (pqueue.size() < 2)
throw new AssertionError();
// Repeatedly tie together two nodes with the lowest frequency
while (pqueue.size() > 1) {
NodeWithFrequency nf1 = pqueue.remove();
NodeWithFrequency nf2 = pqueue.remove();
pqueue.add(new NodeWithFrequency(
new InternalNode(nf1.node, nf2.node),
Math.min(nf1.lowestSymbol, nf2.lowestSymbol),
nf1.frequency + nf2.frequency));
}
// Return the remaining node
return new CodeTree((InternalNode)pqueue.remove().node, frequencies.length);
} |
99effb73-056e-4fd1-9f1a-96dd8613f677 | 1 | public Object clone() {
// use reflection to create the correct subclass
Constructor constructor = getClass().getConstructors()[0];
try {
return constructor.newInstance(
new Object[] {(Animation)anim.clone()});
}
catch (Exception ex) {
// should never happen
ex.printStackTrace();
return null;
}
} |
fbcd2884-d530-41c4-966f-994ee86357c6 | 2 | @SuppressWarnings("unchecked")
public int getCorrectChoiceIndex() {
ArrayList<String> questionList = (ArrayList<String>) question;
for (int i = 0; i < questionList.size(); i++) {
if (questionList.get(i).equals((String)answer))
return i-1;
}
System.out.println("Cannot find correct choice index");
return -1;
} |
7919c087-0c31-4daa-ba7a-59bb308e535a | 0 | public BusyTile(Piece piece){
this.setImage(selectImage(piece));
this.setBorder(BorderFactory.createEmptyBorder());
this.color=piece.getColor();
} |
23321501-0207-4717-80ef-aca7a131d283 | 1 | public void clearBoard() {
for (Field field : this.fields) {
field.makeInactive();
field.clear();
}
} |
9ddfff8e-5118-46f6-91da-32c452d1599c | 5 | private void generateMatrix(){
for(int i=0;i<breite;i++){
for(int j=0;j<breite;j++){
if(i==j){
m.setElement(i, j, 2.0);//m.setElement(zeile, spalte, wert);
}else if(j==(i+1) || j==(i-1)){
m.setElement(i, j, -1.0);
}else{
m.setElement(i, j, 0.0);
}
}
}
} |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.