method_id stringlengths 36 36 | cyclomatic_complexity int32 0 9 | method_text stringlengths 14 410k |
|---|---|---|
be61e083-4ba5-4aa1-9d34-22ba372bc421 | 4 | public boolean checkTables() throws SQLException, ClassNotFoundException {
sqlClass();
DatabaseMetaData dbm = sqlCon().getMetaData();
ResultSet tables;
if (forumType.equalsIgnoreCase("xenforo")) {
tables = dbm.getTables(null, null, tablePref + "user", null);
} else if (forumType.equalsIgnoreCase("smf")
|| forumType.equalsIgnoreCase("ipb")) {
tables = dbm.getTables(null, null, tablePref + "members", null);
} else {
tables = dbm.getTables(null, null, tablePref + "users", null);
}
if (tables.next()) {
closeCon();
return true;
} else {
closeCon();
return false;
}
} |
34432a8d-b8e6-40ea-9d99-08777d60d9d1 | 8 | @Override
public void mouseClicked(MouseEvent e) {
if (_move != null) {
return;
}
Component c = _gameboard.findComponentAt(e.getX(), e.getY());
if (c instanceof PieceGUI) {
PieceGUI p = ((PieceGUI) c);
if (p.isSelected()) {
p.setSelected(false);
_selectedPiece = null;
} else {
if (_selectedPiece == null) {
if (_turn == p.getSide()) {
p.setSelected(true);
_selectedPiece = p;
}
} else {
int index = _selectedPiece.getIndex();
int index1 = p.getIndex();
_move = textPosition(index) + "-" + textPosition(index1);
}
}
} else {
if (_selectedPiece != null) {
int index = _selectedPiece.getIndex();
int index1;
Component[] cArray = _gameboard.getComponents();
for (index1 = 0; index1 < cArray.length; index1++) {
if (cArray[index1].equals(c)) {
break;
}
}
_move = textPosition(index) + "-" + textPosition(index1);
}
}
c.repaint();
} |
eff09643-c5b9-4193-b1b0-65794cc2199e | 6 | @Override
public boolean equals(Object obj) {
if (this == obj)
return true;
if (obj == null)
return false;
if (getClass() != obj.getClass())
return false;
FightState other = (FightState) obj;
if (!Arrays.deepEquals(atkCnt, other.atkCnt))
return false;
if (spareDamage != other.spareDamage)
return false;
if (spareEnemyDamage != other.spareEnemyDamage)
return false;
return true;
} |
0ea5bfaa-96be-4ff1-b164-79295d75dd6a | 9 | @Override
public boolean execute(String code)
{
int indexValue = 0;
int pointerToAdd = 0;
String effectiveAddress = "";
String val = "";
seperateCode(code);
// Get addressing mode.
int addressMode = getAddressingMethod(code);
try {
if (isIndirect) {
address = address.substring(0, address.indexOf("*"));
}
// Find address depending on the mode
if (addressMode == 0) {
executeLDA(this.address);
} else {
if (addressMode == 1 || addressMode == 3) {
indexValue = Integer.parseInt(ASCView.getIndexValue(this.register), 16);
effectiveAddress = Integer.toHexString(Integer.parseInt(this.address, 16) + indexValue);
}
if (addressMode == 2 || addressMode == 3) {
pointerToAdd = Integer.parseInt(address, 16);
if (isIndexed) {
int buffer = Integer.parseInt((String)ASCView.getMemoryTable().getValueAt(pointerToAdd, 0), 16);
buffer += indexValue;
effectiveAddress = formatText(Integer.toHexString(buffer));
} else {
effectiveAddress = formatText((String) ASCView.getMemoryTable().getValueAt((pointerToAdd), 0));
}
}
if (effectiveAddress.equalsIgnoreCase("dddd")) {
EmulatorControl.addError(new EmulatorError(">>ERROR<< AN ERROR OCCURED WITH THE LDA OPERATION.", 0));
return false;
}
// Execute using the address.
executeLDA(effectiveAddress);
}
} catch (NumberFormatException nfe) {
EmulatorControl.addError(new EmulatorError(">>ERROR<< AN ERROR OCCURED WITH THE LDA OPERATION.", 0));
return false;
}
Emulator.incrementProgramCounter();
return true;
} |
9419fe7b-6d74-4fcb-b7ba-5ecb859eb5e9 | 6 | public float[][] decode() throws IOException {
while(true) {
int len = dsp.synthesis_pcmout(pcmp, idxp);
if(len > 0) {
float[][] ret = new float[chn][];
for(int i = 0; i < chn; i++) {
ret[i] = new float[len];
System.arraycopy(pcmp[0][i], idxp[i], ret[i], 0, len);
}
dsp.synthesis_read(len);
return(ret);
}
Packet pkt = in.packet();
if(pkt == null)
return(null);
if((blk.synthesis(pkt) != 0) || (dsp.synthesis_blockin(blk) != 0))
throw(new VorbisException());
}
} |
680daba8-fad4-41c8-a2c2-a0fbf0b2551a | 2 | public static TestInstanceInfo getTestInstanceInfo(HierarchicalConfiguration testInstanceData) {
TestInstanceInfo testInstanceInfo = null;
if (testInstanceData != null) {
try {
testInstanceInfo = new TestInstanceInfo();
testInstanceInfo.setId(testInstanceData.getLong(ID_TAG));
testInstanceInfo.setName(testInstanceData.getString(NAME_TAG));
testInstanceInfo.setTestId(testInstanceData.getLong(TESTID_TAG));
testInstanceInfo.setTestName(testInstanceData.getString(TESTNAME_TAG));
testInstanceInfo.setStatus(QcTestStatus.fromValue(testInstanceData.getString(STATUS_TAG)));
testInstanceInfo.setTestSetId(testInstanceData.getLong(TESTSETID_TAG));
} catch (Exception e) {
log.error("Error while parsing test : " + testInstanceInfo.getName(), e);
}
}
return testInstanceInfo;
} |
93515403-5f57-4c73-aa75-d708a55609e0 | 0 | protected void initDefaultCommand() {} |
edfde7d4-7ae3-496e-b1d3-7bb26cfbc0af | 9 | private void jComboBox_AssetContractsActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jComboBox_AssetContractsActionPerformed
System.out.println("In Action for Asset Combo main tab");
/*String nymID = Utility.getKey(nymMap, (String) jComboBox1.getSelectedItem());
String assetID = Utility.getKey(assetMap, (String) jComboBox3.getSelectedItem());
String serverID = Utility.getKey(serverMap, (String) jComboBox2.getSelectedItem());*/
String nymID = "ALL";
String assetID = "ALL";
String serverID = "ALL";
if (nymMap != null && nymMap.size() > 0 && jComboBox_Nyms.getSelectedIndex() > 0) {
nymID = ((String[]) nymMap.get((Integer) jComboBox_Nyms.getSelectedIndex() - 1))[1];
}
if (assetMap != null && assetMap.size() > 0 && jComboBox_AssetContracts.getSelectedIndex() > 0) {
assetID = ((String[]) assetMap.get((Integer) jComboBox_AssetContracts.getSelectedIndex() - 1))[1];
}
if (serverMap != null && serverMap.size() > 0 && jComboBoxServerContracts.getSelectedIndex() > 0) {
serverID = ((String[]) serverMap.get((Integer) jComboBoxServerContracts.getSelectedIndex() - 1))[1];
}
System.out.print("nymiiidL:" + nymID);
loadAccount(assetID, serverID, nymID);
clearDetailPage();
} |
71c8e05f-30c7-403f-ad61-a27d2ce98cc2 | 0 | public long getT() {
return initTemps[1];
} |
69f5cc2f-2304-4779-b863-0636e45684e4 | 6 | public void handleCustomPayload(Packet250CustomPayload var1)
{
ModLoader.receivePacket(var1);
MessageManager inst = MessageManager.getInstance();
if (var1.channel.equals("REGISTER"))
{
try
{
String channels = new String(var1.data, "UTF8");
for (String channel : channels.split("\0"))
{
inst.addActiveChannel(netManager, channel);
}
}
catch (UnsupportedEncodingException ex)
{
ModLoader.throwException("NetClientHandler.handleCustomPayload", ex);
}
}
else if (var1.channel.equals("UNREGISTER"))
{
try
{
String channels = new String(var1.data, "UTF8");
for (String channel : channels.split("\0"))
{
inst.removeActiveChannel(netManager, channel);
}
}
catch (UnsupportedEncodingException ex)
{
ModLoader.throwException("NetClientHandler.handleCustomPayload", ex);
}
}
else
{
inst.dispatchIncomingMessage(netManager, var1.channel, var1.data);
}
} |
509c1925-d058-4923-b149-2647dc58d10b | 8 | protected void inAttrib(final char c)
{
switch(c)
{
case ' ': case '\t': case '\r': case '\n': changedTagState(State.INPOSTATTRIB); return;
case '=': changeTagState(State.BEFOREATTRIBVALUE); return;
case '<':
endEmptyAttrib(bufDex);
piece.innerStart = bufDex;
abandonTagState(State.BEFORETAG);
return;
case '>':
endEmptyAttrib(bufDex);
changeTagState(State.START);
piece.innerStart = bufDex;
return;
case '/':
endEmptyAttrib(bufDex);
changedTagState(State.BEGINTAGSELFEND);
return;
default: bufDex++; return;
}
} |
fe4d6623-1a4c-4b7e-a9bf-d8f8b41292b0 | 7 | static final void method1430
(int i, byte i_1_, int i_2_, int i_3_, int i_4_, int i_5_, int i_6_,
int i_7_, Mob class318_sub1_sub3_sub3,
Mob class318_sub1_sub3_sub3_8_) {
try {
anInt2567++;
int i_9_ = class318_sub1_sub3_sub3.method2425(-1);
if (i_9_ != -1) {
Object object = null;
RasterToolkit class105
= ((RasterToolkit)
Class348_Sub1_Sub1.aClass60_8807.method583((long) i_9_,
118));
if (class105 == null) {
ImageSprite[] class207s
= ImageSprite.loadSprites(Class21.indexLoader8, i_9_, 0);
if (class207s == null)
return;
class105
= Class348_Sub8.currentToolkit.createRasterForSprite(class207s[0], true);
Class348_Sub1_Sub1.aClass60_8807
.method582(class105, (long) i_9_, (byte) -115);
}
aa_Sub2.method165
(((Class318_Sub1) class318_sub1_sub3_sub3_8_).heightLevel,
i_5_, 0, i_3_ >> -1818761215,
((Class318_Sub1) class318_sub1_sub3_sub3_8_).xHash,
class318_sub1_sub3_sub3_8_.method2436((byte) 126) * 256,
((Class318_Sub1) class318_sub1_sub3_sub3_8_).anInt6388,
(byte) 92, i_6_ >> 1288222721, i_2_);
int i_10_ = i_7_ + (Class239_Sub21.anIntArray6062[0] + -18);
int i_11_
= -54 + (Class239_Sub21.anIntArray6062[1] + i_4_) - 16;
i_10_ += i / 4 * 18;
i_11_ += 18 * (i % 4);
int i_12_ = -76 / ((i_1_ - 3) / 38);
class105.method974(i_10_, i_11_);
if (class318_sub1_sub3_sub3 == class318_sub1_sub3_sub3_8_)
Class348_Sub8.currentToolkit.method3668(18, -1 + i_11_, -256,
i_10_ - 1, 18, 57);
Class338.method2663(-5590, i_10_ + -1, 18 + i_10_, i_11_ + -1,
i_11_ - -18);
Class318_Sub6 class318_sub6 = Class367.method3529(32564);
((Class318_Sub6) class318_sub6).anInt6426 = 16 + i_10_;
((Class318_Sub6) class318_sub6).anInt6427 = i_11_;
((Class318_Sub6) class318_sub6).aClass318_Sub1_Sub3_Sub3_6431
= class318_sub1_sub3_sub3;
((Class318_Sub6) class318_sub6).anInt6425 = i_11_ - -16;
((Class318_Sub6) class318_sub6).anInt6429 = i_10_;
DummyInputstream.aClass243_83.method1869(-87, class318_sub6);
}
} catch (RuntimeException runtimeexception) {
throw Class348_Sub17.method2929(runtimeexception,
("qk.G(" + i + ',' + i_1_ + ','
+ i_2_ + ',' + i_3_ + ',' + i_4_
+ ',' + i_5_ + ',' + i_6_ + ','
+ i_7_ + ','
+ (class318_sub1_sub3_sub3 != null
? "{...}" : "null")
+ ','
+ ((class318_sub1_sub3_sub3_8_
!= null)
? "{...}" : "null")
+ ')'));
}
} |
aa8438d3-6252-453c-a593-f8f90207a6f9 | 4 | private boolean checkResource(Collection list, int id)
{
boolean flag = false;
if (list == null || id < 0) {
return flag;
}
Integer obj = null;
Iterator it = list.iterator();
// a loop to find the match the resource id in a list
while ( it.hasNext() )
{
obj = (Integer) it.next();
if (obj.intValue() == id)
{
flag = true;
break;
}
}
return flag;
} |
33a6e55b-be68-4f18-bd69-7c71824134a6 | 1 | public void connectDb() {
startSQL();
try {
Class.forName("com.mysql.jdbc.Driver").newInstance();
con = DriverManager.getConnection(url, user, password);
st = con.createStatement();
} catch (Exception e) {
e.printStackTrace();
}
} |
096434c3-4a7a-4b58-8035-09f5a6b89eed | 8 | private void createErrorImage()
{
Image eImg = new Image(rfr.getW(), rfr.getH());
for(int i = 0; i < errorBlocks.size();i++)//find min and max
{
RGB[][] e = errorBlocks.get(i);
for(int y = 0; y < 16; y++)
{
for(int x = 0; x < 16; x++)
{
double err = getGrayPixel(e[x][y].getRGB());
if(err > max)
max = (int)err;
if(err < min)
min = (int)err;
}
}
}
for(int i = 0; i < errorBlocks.size();i++)
{
RGB[][] error = errorBlocks.get(i);
int xpos = (i % h) * 16;
int ypos = (i / h) * 16;
for(int y = 0; y < 16; y++)
{
for(int x = 0; x < 16; x++)
{
int[] rgb = new int[3];
int scaled = (int)(getGrayPixel(error[x][y].getRGB()) - min)*255/(max-min);
rgb[0] = rgb[1] = rgb[2] = scaled;
eImg.setPixel(xpos + x, ypos + y, rgb);
}
}
}
eImg.display("Error Image");
} |
d14bb3ec-08ae-4e81-b971-13d5ac027adc | 1 | public void setProtected(final boolean flag) {
int modifiers = classInfo.modifiers();
if (flag) {
modifiers |= Modifiers.PROTECTED;
} else {
modifiers &= ~Modifiers.PROTECTED;
}
classInfo.setModifiers(modifiers);
this.setDirty(true);
} |
56a4772d-b295-4197-a0b6-8f3137bd72f1 | 1 | private void sleep() {
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
throw new CrawlerException("main thread died. ", e);
}
} |
80cb8b9a-dc22-45c4-a05e-c020feeb43b1 | 4 | public ListRadio(String[] list, String selecionado)
{
setLayout(new FlowLayout(FlowLayout.LEFT));
setBorder(new EmptyBorder(-10, 0, 0, 0));
boolean primeiro = true;
for (String nome : list)
{
boolean marcado = false;
if (primeiro)
{
primeiro = false;
marcado = true;
}
if (selecionado != null && nome.equals(selecionado))
marcado = true;
lista.add(new JRadioButton(nome, marcado));
bg.add(lista.get(lista.size() - 1));
add(lista.get(lista.size() - 1));
}
} |
f76f3c3e-f288-400f-b0df-24bdf3f94441 | 1 | public void openDevice(int index) { // Opens the device takes in index you
// want to use
deviceIndex = index; // Sets the index to the parameter
try { // beginning of a try catch block
sender = JpcapSender.openDevice(devices[deviceIndex]); // Opens the
// selected
// device
} catch (IOException e) { // catches an input output error
// TODO Auto-generated catch block
e.printStackTrace(); // prints the throwable
}
} |
9bd0cbc7-ec02-498d-8321-97b91db6b702 | 9 | @Override
public void write(String currentDVDFile, String masterDVDFile)
throws FatalBackEndException {
FileWriter cdf, mdf;
try {
cdf = new FileWriter(currentDVDFile);
} catch (IOException ex) {
throw new FatalBackEndException(ex.getMessage(),
FileType.CurrentDVD, currentDVDFile);
}
try {
mdf = new FileWriter(masterDVDFile);
} catch (IOException ex) {
try {
cdf.close();
} catch (IOException e) {
e.printStackTrace();
}
throw new FatalBackEndException(ex.getMessage(),
FileType.NewMasterDVD, masterDVDFile);
}
TreeMap<Integer, MasterDVD> sorted_list = new TreeMap<Integer, MasterDVD>();
Iterator<MasterDVD> iter = masterList.values().iterator();
while (iter.hasNext()) {
MasterDVD temp = iter.next();
sorted_list.put(temp.getId(), temp);
}
try {
for (Integer i : sorted_list.keySet()) {
MasterDVD mdvd = sorted_list.get(i);
try {
mdf.write(mdvd.toString() + "\n");
} catch (IOException e1) {
throw new FatalBackEndException(e1.getMessage(),
FileType.NewMasterDVD, masterDVDFile);
}
try {
cdf.write(mdvd.get_cdvd().toString() + "\n");
} catch (IOException e) {
throw new FatalBackEndException(e.getMessage(),
FileType.CurrentDVD, currentDVDFile);
}
}
} finally {
try {
mdf.close();
} catch (IOException ex) {
ex.printStackTrace();
}
try {
cdf.close();
} catch (IOException ex) {
ex.printStackTrace();
}
}
} |
5eabc9f4-46ac-43ee-ada8-1d232fc78014 | 7 | public boolean SetBusActiveStatus(int busNumber, int inputBufferNumber, int packetSequence, int TIME, ConfigFile cfg)
{
//REMOVE IN CROSSBAR FABRIC TYPE
//only one bus present in this fabric type,
busNumber = 0;
//ensure valid busNumber chosen
if(((busNumber+1)<= VERTICALBUSES) && ((busNumber+1) > 0) &&
(busActiveStatus[busNumber] == false))
{
//check if bus free, or already used by a buffer
if ((currentInputBufferUsingTheBus[busNumber] == -1) ||
(currentInputBufferUsingTheBus[busNumber] == inputBufferNumber))
{
//System.out.println("busNumber :- "+(busNumber+1)+ " SIZE of currentInputBufferUsingTheBus: "+currentInputBufferUsingTheBus.length);
//set the status of the bus
busActiveStatus[busNumber] = true;
//remove the bus from available buses
availableBuses.remove(busNumber);
//add input buffer connected to a bus
inputConnectedToBus.add((Object)inputBufferNumber);
//keep track of the buffer using the bus
currentInputBufferUsingTheBus[busNumber] = inputBufferNumber;
//keep track of the packet sequence using the bus
sequence[busNumber] = packetSequence;
//set the recently used bus
recentBus = busNumber;
if(((String)cfg.GetConfig("GENERAL","Verbose")).compareToIgnoreCase("True") == 0)
{
Print(true, busNumber,packetSequence,true,TIME);
}
//successfully controlled the bus
return true;
}
}
if(((String)cfg.GetConfig("GENERAL","Verbose")).compareToIgnoreCase("True") == 0)
{
Print(false, busNumber,packetSequence,true,TIME);
}
//was unable to control the bus
return false;
} |
e09b0241-0dd8-48eb-bc88-b1b1f3f6c8b5 | 8 | public static void moveFile(File source, File dest){
StringBuilder debugMessage = new StringBuilder(64);
debugMessage.append("Unable to move:\n");
debugMessage.append(source.getPath());
debugMessage.append("\nto:\n");
debugMessage.append(dest.getPath());
debugMessage.append("\n\n");
// Make the parent folder
File destParent = dest.getParentFile();
if(destParent != null && ! destParent.exists() ){
if( ! destParent.mkdirs() )
debugMessage.append("Parent directory failed to create.\n");
}
// Try to rename the file
if( ! source.renameTo(dest) ){
// Rename failed, attempt to manually copy
try {
if( ! dest.exists() )
dest.createNewFile();
FileChannel sourceChan = new FileInputStream(source).getChannel();
FileChannel destination = new FileOutputStream(dest).getChannel();
long count =0;
long size = sourceChan.size();
while( count < size ){
count += destination.transferFrom(sourceChan, 0, size-count);
}
sourceChan.close();
destination.close();
if( size == count)
source.delete();
else
Main.handleException(
debugMessage.append("All of the file failed to copy for an unkown reason.\nOrginal File Size: ")
.append(size).append(" New File Size: ").append(count).toString(),
null, Main.WARN_LEVEL);
} catch(IOException ioe){
Main.handleException(debugMessage
.append("Rename and copy failed.").toString(),
ioe, Main.WARN_LEVEL);
}
}
} |
caa46388-6758-41fb-83f2-f7bee2950b51 | 3 | public void setLowerAndUpperBounds(double lower, double upper) {
if (data == null) {
return;
}
this.originalLowerBound = lower;
this.originalUpperBound = upper;
if (originalLowerBound < min) {
offset = Math.abs(originalLowerBound) + 10;
} else {
offset = Math.abs(min) + 10;
}
if (calibrationType == MEAN) {
lowerBound = (originalLowerBound + offset) * (mean + offset) / (min + offset) - offset;
upperBound = (originalUpperBound + offset) * (mean + offset) / (max + offset) - offset;
} else {
lowerBound = originalLowerBound;
upperBound = originalUpperBound;
}
hasBounds = true;
setDeviation();
} |
18fd3b9b-529d-4491-b626-c05f2836e164 | 4 | public void keyReleased(KeyEvent e){
int key = e.getKeyCode();
if (key == KeyEvent.VK_RIGHT || key == KeyEvent.VK_LEFT){
dx = 0;
}
if (key == KeyEvent.VK_UP || key == KeyEvent.VK_DOWN){
dy = 0;
}
} |
cb632c52-2d7d-4089-84d4-3343f4ae0d38 | 8 | public int canAdd(CardStack src)
{
if(orderedPair(this.top(), src.chosen()))
return 1;
// If stack clicked twice on & doubleclicking set to select all
// ordered cards, select them
else if(src == this)
{ if(doubleClickSelect && nSelected < nOrdered() && nSelected > 0)
{ select( nOrdered() );
return -1;
}
}
// If multiple cards can be removed from source stack, look at
// lowest ordered card, the move up until a match found
else if(src.lookBelow)
{ int nOrd = src.nOrdered();
int startI = src.nCards() - nOrd;
for(int srcI = startI; srcI < src.nCards(); ++srcI)
{ if(orderedPair(top(), src.cardAt(srcI)))
return src.nCards() - srcI;
}
}
return 0;
} |
81635795-d929-4616-a03b-0cf3fd1b34cb | 6 | public void damageDetection ()
{
if (character.equals("P1"))
{
P2AttackArea getHit = (P2AttackArea)getOneIntersectingObject(P2AttackArea.class);
hurt = false;
if (getHit != null)
{
hitpoint-= getHit.damageDealt();
hurt = true;
if (getHit.returnForceDirection())
x+= getHit.dealForce();
else
x-= getHit.dealForce();
}
}
else if (character.equals("P2"))
{
P1AttackArea getHit = (P1AttackArea)getOneIntersectingObject(P1AttackArea.class);
hurt = false;
if (getHit != null)
{
hurt = true;
hitpoint-= getHit.damageDealt();
if (getHit.returnForceDirection())
x+= getHit.dealForce();
else
x-= getHit.dealForce();
}
}
} |
4d5d3c98-10aa-4a4c-9ff6-95016d1855fb | 3 | private int computeColorDepth(int colorcount)
{
// color depth = log-base-2 of maximum number of simultaneous colors, i.e.
// bits per color-index pixel
if (colorcount <= 2)
return 1;
if (colorcount <= 4)
return 2;
if (colorcount <= 16)
return 4;
return 8;
} |
1778d482-c842-4c22-9783-19aabd5fd082 | 1 | public float[] clone1df(float[] orig){
int ii = orig.length;
float[] temp = new float[ii];
for (int i = 0; i<ii; i++){
temp[i] = orig[i];
}
return temp;
} |
7169d6e5-e513-46e5-a492-243ec616f06a | 7 | @Override
public void getAlleOpdrachten(OpdrachtCatalogus opdrachtCatalogus) {
try {
con = JDBCConnection.getConnection();
String query = "select opdrachten.idopdrachten, opdrachten.vraag,opdrachten.antwoord,opdrachten.maxAantalpogingen,opdrachten.antwoordHint,opdrachten.maxAntwoordTijd, opdrachtcategorieën.opdrachtCategorieNaam,meerkeuzeopdrachten.alleKeuzes from opdrachten left join (`opdrachtcategorieën`, opdrachtsoorten, meerkeuzeopdrachten) ON (`opdrachtcategorieën`.`idopdrachtCategorieën` = opdrachten.opdrachtenCategorie and opdrachtsoorten.idOpdrachtSoorten = opdrachten.soortOpdracht and meerkeuzeopdrachten.idmeerkeuzeOpdrachten= opdrachten.idopdrachten) where opdrachtsoorten.OpdrachtSoortenNaam='Meerkeuze'";
st = con.createStatement();
rs = st.executeQuery(query);
while (rs.next()) {
int id = rs.getInt(1);
String vraag = rs.getString(2);
String antwoord = rs.getString(3);
int maxAantalPogingen = rs.getInt(4);
String antwoordHint = rs.getString(5);
int maxAntwoordTijd = rs.getInt(6);
OpdrachtCategorie opdrachtCategorie = OpdrachtCategorie
.valueOf(rs.getString(7));
String alleKeuzes = rs.getString(8);
Opdracht opdr = new Meerkeuze(id, vraag, antwoord,
maxAantalPogingen, alleKeuzes, antwoordHint,
maxAntwoordTijd, opdrachtCategorie);
opdrachtCatalogus.getOpdrachten().add(opdr);
}
query = "select opdrachten.idopdrachten, opdrachten.vraag,opdrachten.antwoord,opdrachten.maxAantalpogingen,opdrachten.antwoordHint,opdrachten.maxAntwoordTijd, opdrachtcategorieën.opdrachtCategorieNaam from opdrachten left join (`opdrachtcategorieën`, opdrachtsoorten, opsommingsopdrachten) ON (`opdrachtcategorieën`.`idopdrachtCategorieën` = opdrachten.opdrachtenCategorie and opdrachtsoorten.idOpdrachtSoorten = opdrachten.soortOpdracht and opsommingsopdrachten.idopsommingsOpdrachten= opdrachten.idopdrachten) where opdrachtsoorten.OpdrachtSoortenNaam='Opsomming'";
rs = st.executeQuery(query);
while (rs.next()) {
int id = rs.getInt(1);
String vraag = rs.getString(2);
String antwoord = rs.getString(3);
int maxAantalPogingen = rs.getInt(4);
String antwoordHint = rs.getString(5);
int maxAntwoordTijd = rs.getInt(6);
OpdrachtCategorie opdrachtCategorie = OpdrachtCategorie
.valueOf(rs.getString(7));
Opdracht opdr = new Opsomming(vraag, antwoord,
maxAantalPogingen, antwoordHint, maxAntwoordTijd,
opdrachtCategorie);
opdrachtCatalogus.getOpdrachten().add(opdr);
}
query = "select opdrachten.idopdrachten, opdrachten.vraag,opdrachten.antwoord,opdrachten.maxAantalpogingen,opdrachten.antwoordHint,opdrachten.maxAntwoordTijd, opdrachtcategorieën.opdrachtCategorieNaam,reproductieopdrachten.trefwoorden,reproductieopdrachten.minAantalTrefwoorden from opdrachten left join (`opdrachtcategorieën`, opdrachtsoorten, reproductieopdrachten) ON (`opdrachtcategorieën`.`idopdrachtCategorieën` = opdrachten.opdrachtenCategorie and opdrachtsoorten.idOpdrachtSoorten = opdrachten.soortOpdracht and reproductieopdrachten.idreproductieOpdrachten = opdrachten.idopdrachten) where opdrachtsoorten.OpdrachtSoortenNaam='Reproductie'";
rs = st.executeQuery(query);
while (rs.next()) {
int id = rs.getInt(1);
String vraag = rs.getString(2);
String antwoord = rs.getString(3);
int maxAantalPogingen = rs.getInt(4);
String antwoordHint = rs.getString(5);
int maxAntwoordTijd = rs.getInt(6);
OpdrachtCategorie opdrachtCategorie = OpdrachtCategorie
.valueOf(rs.getString(7));
String trefwoorden = rs.getString(8);
int minAantalJuisteTrefwoorden = rs.getInt(9);
Opdracht opdr = new Reproductie(vraag, antwoord,
maxAantalPogingen, antwoordHint, maxAntwoordTijd,
trefwoorden, minAantalJuisteTrefwoorden,
opdrachtCategorie);
opdrachtCatalogus.getOpdrachten().add(opdr);
}
} catch (Exception e) {
System.out.println(e.getMessage());
} finally {
try {
if (rs != null) {
rs.close();
}
if (st != null) {
st.close();
}
closeConnection();
} catch (SQLException e) {
e.printStackTrace();
}
}
} |
8ee044b6-7b1d-4461-b6e8-c07cad1dc6a8 | 9 | public String convert(String s, int nRows) {
if (s == null || s.length() == 0 || nRows <= 0) {
return "";
}
if (nRows == 1) {
return s;
}
StringBuilder res = new StringBuilder();
//every 2 column will be (2 * row - 2)
int size = 2 * nRows - 2;
for (int i = 0; i < nRows; i++) {
for (int j = i; j < s.length(); j += size) {
//the first and the last row
res.append(s.charAt(j));
//add the rows between the first and the last
if (i != 0 && i != nRows - 1 && j + size - 2 * i < s.length()) {
res.append(s.charAt(j + size - 2 * i));
}
}
}
return res.toString();
} |
48048df8-6fba-490f-94b6-838428c07279 | 0 | @Test
public void testTruncate_trim()
{
String s = " Already short enough, when trimmed. ";
Assert.assertEquals(
"Already short enough, when trimmed.",
_helper.truncate(s, 35)
);
} |
d7eb1164-758e-48b9-b933-385d674f1074 | 3 | private DatabaseManager(ConnectionSource source){
this.source=source;
try {
TableUtils.createTableIfNotExists(source, Info.class);
QueryBuilder<Info, Integer> queryEvent=getInfoDao().queryBuilder();
queryEvent.where().eq("key", DATABASE_VERSION_KEY);
Info info=queryEvent.queryForFirst();
if(info==null){
init();
info=new Info();
info.key=DATABASE_VERSION_KEY;
info.value=Integer.toString(DATABASE_VERSION);
getInfoDao().create(info);
}
else{
int lastVersion=Integer.parseInt(info.value);
if(lastVersion < DATABASE_VERSION) upgrade(lastVersion, DATABASE_VERSION);
info.value=Integer.toString(DATABASE_VERSION);
getInfoDao().createOrUpdate(info);
}
} catch (SQLException e) {
e.printStackTrace();
}
} |
c7c19b1c-f9dc-4636-bd24-be52f0bc9a81 | 6 | public void DeleteProjeto(Projeto projeto) throws SQLException, excecaoDeletarElemento {
Connection conexao = null;
PreparedStatement comando = null;
try {
conexao = BancoDadosUtil.getConnection();
comando = conexao.prepareStatement(SQL_DELETE_UM_PROJETO);
comando.setInt(1, projeto.getIdProjeto());
comando.execute();
conexao.commit();
} catch (Exception e) {
if (conexao != null) {
conexao.rollback();
}
//throw new RuntimeException(e);
throw new excecaoDeletarElemento();
} finally {
if (comando != null && !comando.isClosed()) {
comando.close();
}
if (conexao != null && !conexao.isClosed()) {
conexao.close();
}
}
} |
d5b6cf0d-d2d9-4a21-9f95-4f9d7cc11b5d | 0 | public ArraysDataBase(){
arraysBase = new ArrayList<DataStructures>();
} |
94601815-aa14-4524-87b3-a7649cd12163 | 7 | public static Keyword continueForallProof(ControlFrame frame, Keyword lastmove) {
lastmove = lastmove;
{ boolean testValue000 = false;
if (frame.reversePolarityP) {
testValue000 = true;
}
else {
{
{ boolean alwaysP000 = true;
{ PatternVariable var = null;
Vector vector000 = ((Vector)(KeyValueList.dynamicSlotValue(frame.proposition.dynamicSlots, Logic.SYM_LOGIC_IO_VARIABLES, null)));
int index000 = 0;
int length000 = vector000.length();
loop000 : for (;index000 < length000; index000 = index000 + 1) {
var = ((PatternVariable)((vector000.theArray)[index000]));
if (!Logic.closedTermP(Logic.getDescription(Logic.logicalType(var)))) {
alwaysP000 = false;
break loop000;
}
}
}
testValue000 = alwaysP000;
}
if (!testValue000) {
testValue000 = Proposition.closedPropositionP(((Proposition)((frame.proposition.arguments.theArray)[0])));
}
}
}
if (testValue000) {
{
frame.state = Logic.KWD_ITERATIVE_FORALL;
return (Logic.KWD_MOVE_IN_PLACE);
}
}
else {
{
{ Keyword testValue001 = Logic.currentInferenceLevel().keyword;
if ((testValue001 == Logic.KWD_NORMAL) ||
(testValue001 == Logic.KWD_REFUTATION)) {
ControlFrame.overlayWithStrategyFrame(frame, Logic.KWD_UNIVERSAL_INTRODUCTION);
return (Logic.KWD_MOVE_IN_PLACE);
}
else {
return (Logic.KWD_FAILURE);
}
}
}
}
}
} |
3cfc5343-9b62-425d-8212-ed6a4dda3c9d | 5 | public void pedirAmistad(String Nick, String receptor) { //??
try {
String queryString = "INSERT INTO peticionAmistad ( emisor, receptor) VALUES(?,?)";
connection = getConnection();
ptmt = connection.prepareStatement(queryString);
ptmt.setString(1, Nick);
ptmt.setString(2, receptor);
ptmt.executeUpdate();
System.out.println("Data Added Successfully");
} catch (SQLException e) {
e.printStackTrace();
} finally {
try {
if (ptmt != null) {
ptmt.close();
}
if (connection != null) {
connection.close();
}
} catch (SQLException e) {
e.printStackTrace();
} catch (Exception e) {
e.printStackTrace();
}
}
} |
bcdddf5f-d460-4ac5-88b7-f3745abad7e2 | 0 | public String getConsumerSecret() {
return consumerSecret;
} |
5a34c106-6ab5-475e-8566-b95b0df63fb8 | 3 | public void actionListener (Action e) {
switch (e.getActionType()) {
case "start":
start(white_player);
break;
case "quit":
unRegisterPlayer(curPlayer.color);
end();
break;
case "move":
ActionMove mev = (ActionMove)e;
curPlayer.put(board, mev.x, mev.y);
process();
break;
default:
break;
}
} |
3e61afcb-f6f7-40e5-a792-f47a4cf70a89 | 2 | public EmailTest() {
bigLocal = new String("a");
for(int i = 0; i < 70; i++)
bigLocal = bigLocal.concat("a");
bigDomain = new String("c");
for(int i = 0; i < 257; i++)
bigDomain = bigDomain.concat("c");
bigDomain = bigDomain.concat(".com");
} |
679019d4-603c-4f25-91c9-479afea0f4fa | 8 | public static boolean isEffective(boolean player, int moveNum) {
int move = getMove(player,moveNum);
if(move <= 0)
return false;
int atkType = curGb.getROM()[curGb.pokemon.listMovesAddress + (move-1)*curGb.pokemon.listMovesEntryLength + 3];
int defenderTypeAddress = player ? curGb.pokemon.fightEnemyMonTypesAddress : curGb.pokemon.fightBattleMonTypesAddress;
int add = curGb.pokemon.listTypeMatchupAddress;
int dt1 = curGb.readMemory(defenderTypeAddress);
int dt2 = curGb.readMemory(defenderTypeAddress+1);
while(true) {
int at = curGb.getROM()[add++];
if(at == 0xFE) continue;
if(at == 0xFF) break;
int dt = curGb.getROM()[add++];
/*int eff = State.getROM()[add++];*/add++;
if(at == atkType && (dt == dt1 || dt == dt2))
return true;
}
return false;
} |
30493421-936b-40f1-9962-59709cdf7c1c | 0 | public FlipTest() {
} |
6954657d-ff17-48a6-b094-48a8ecf415d4 | 2 | public static ArrayList<Integer> getOtherServerIds() {
ArrayList<Integer> serverIds = new ArrayList<Integer>();
for (int i = 1; i <= 3; i++) {
if (i != serverId)
serverIds.add(i);
}
return serverIds;
} |
4107b797-70b9-4092-8afd-309dd93bc10c | 0 | public String getMobileLab() {
return MobileLab;
} |
fd1535b8-f30b-433c-98c8-e29288f3459b | 8 | private void method468()
{
super.modelHeight = 0;
anInt1650 = 0;
anInt1651 = 0;
anInt1646 = 0xf423f;
anInt1647 = 0xfff0bdc1;
anInt1648 = 0xfffe7961;
anInt1649 = 0x1869f;
for(int j = 0; j < anInt1626; j++)
{
int k = anIntArray1627[j];
int l = anIntArray1628[j];
int i1 = anIntArray1629[j];
if(k < anInt1646)
anInt1646 = k;
if(k > anInt1647)
anInt1647 = k;
if(i1 < anInt1649)
anInt1649 = i1;
if(i1 > anInt1648)
anInt1648 = i1;
if(-l > super.modelHeight)
super.modelHeight = -l;
if(l > anInt1651)
anInt1651 = l;
int j1 = k * k + i1 * i1;
if(j1 > anInt1650)
anInt1650 = j1;
}
anInt1650 = (int)Math.sqrt(anInt1650);
anInt1653 = (int)Math.sqrt(anInt1650 * anInt1650 + super.modelHeight * super.modelHeight);
anInt1652 = anInt1653 + (int)Math.sqrt(anInt1650 * anInt1650 + anInt1651 * anInt1651);
} |
e7a98bf0-c63b-42aa-bc3f-22fa50ce74cc | 3 | @Override
public void paint(Graphics2D g2d) {
//lo pintamos como sólido
super.paint(g2d);
try{
if(!disparos.isEmpty())//pintamos sus disparos si los hubiera
for(Disparo d: disparos) d.paint(g2d);
}catch(java.util.ConcurrentModificationException ex){
System.err.println("Disparador.paint()> java.util.ConcurrentModificationException");
}
} |
4e5dcd96-2e2e-493b-8d79-0dca643e1e05 | 1 | @Override
public void restoreHealth(int healing) {
if (this.curHP + healing >= this.maxHP) {
this.curHP = this.maxHP;
} else {
this.curHP += healing;
}
} |
5b9c4e9b-8e31-4e88-975c-beba9d30deff | 7 | public void notePhrase(String s, int id_phrase) throws SQLException {
Phrase comm;
comm = new Phrase(s);
Statement lanceRequete;
lanceRequete = connG.conn.createStatement();
ResultSet requete;
ArrayList<String> liste;
liste = new ArrayList<>();
liste = extraitAdjAdv(comm);//récupère la liste de mots du lexique
int note = 0;
for (int i = 0; i < liste.size(); i++) {
//requete pour récupérer les opinions
requete = lanceRequete.executeQuery("Select opinion from basenotee where lemme = '" + liste.get(i) + "'");
if (requete.next()) {
//si note == 0 pas de calcul
if (requete.getInt("opinion") != 0) {
if (requete.getInt("opinion") == -1) {
//inversion de l'opinion si Negation présente
if (comm.detectNegation()) {
note++;
} else {
note--;
}
} else {
//inversion de l'opinion si Negation présente
if (requete.getInt("opinion") == 1) {
if (comm.detectNegation()) {
note--;
} else {
note++;
}
}
}
}
}
requete.close();
}
Statement updateR;
updateR = connG.conn.createStatement();
//mise à jour de la table
updateR.executeUpdate("update phrase_demo set note = '" + note + "' where id_phrase = '"
+ id_phrase + "'");
updateR.close();
lanceRequete.close();
} |
401aae67-7c6b-46b5-9cda-857ba685ef29 | 9 | protected void getCloseCreatures() {
Thread creatureRadarThread = new Thread(new Runnable() {
@Override
public void run() {
try {// wait until the plants align properly
Thread.sleep(80);
} catch (InterruptedException e) {
e.printStackTrace();
}
// True if this creature is alive
while (isAlive()) {
// clone the Grid.plants, the centralised repository of
// plants, so there will less concurrent conflict
synchronized (Grid.simpleCreatures) {
List<SimpleCreature> cre = Collections
.synchronizedList(Grid.simpleCreatures);
for (Iterator<SimpleCreature> iterator = cre.iterator(); iterator
.hasNext();) {
SimpleCreature creature = iterator.next();
Point pos = creature.getPosition();
if (isInRange(pos)
&& creature.getCreautreNumber() != getCreautreNumber()) {
if (creaturesSeen != null && creature != null
&& !creaturesSeen.contains(creature)) {
if (creaturesSeen.size() > CREATURE_MEMORY) {
creaturesSeen.removeFirst();
}
creaturesSeen.add(creature);
}
}
}
}
}
}
});
creatureRadarThread.setDaemon(true);
creatureRadarThread.start();
} |
7bf5ec92-99b7-44e0-a362-a3946db5ae07 | 8 | public static AddItemDialog create(final Class type, final Object instance) {
final AddItemDialog dialog = new AddItemDialog();
for (final Method m : type.getMethods()) {
if (m.getName().startsWith("set")
&& (m.getParameterTypes().length == 1)) {
final String name = m.getName().substring(3);
Method g = null;
try {
g = type.getMethod("get" + name);
} catch (final Exception e) {
}
if (g == null) {
try {
g = type.getMethod("is" + name);
} catch (final Exception e) {
}
}
if (g == null) {
continue;
}
Object value = null;
try {
value = g.invoke(instance);
} catch (final Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
dialog.addItem(name, value);
}
}
return dialog;
} |
51b72d46-32cb-46b3-96cb-5ba261ee6a17 | 1 | private void register(List<String> watchedFiles) throws IOException
{
for(String watchedFile : watchedFiles)
{
String watchedDir = new File(watchedFile).getParentFile().getAbsolutePath();
Path dir = Paths.get(watchedDir);
// we are not watching for create and delete events for this directory
WatchKey key = dir.register(watcher, ENTRY_MODIFY);
this.watchedFiles.add(watchedFile);
keys.put(key, dir);
}
System.out.println("watcher registration done for: "+watchedFiles);
} |
4c97d464-b378-4693-a6de-75513302a7d8 | 5 | private HashFamily getHashFamily(double radius,String hashFamilyType,int dimensions){
HashFamily family = null;
if(hashFamilyType.equalsIgnoreCase("cos")){
family = new CosineHashFamily(dimensions);
}else if(hashFamilyType.equalsIgnoreCase("l1")){
int w = (int) (10 * radius);
w = w == 0 ? 1 : w;
family = new CityBlockHashFamily(w,dimensions);
}else if(hashFamilyType.equalsIgnoreCase("l2")){
int w = (int) (10 * radius);
w = w == 0 ? 1 : w;
family = new EuclidianHashFamily(w,dimensions);
}else{
new IllegalArgumentException(hashFamilyType + " is unknown, should be one of cos|l1|l2" );
}
return family;
} |
a975c1c5-d5e8-41c3-947f-803755129bf7 | 2 | static public Integer getZipFromString(String zipStr) {
Integer retVal = null;
try {
retVal = getIntegerFromSubString(zipStr, "-");
if (retVal == null) {
retVal = getIntegerFromString(zipStr);
}
} catch (Exception e) {
retVal = null;
}
return retVal;
} |
1cbba4cd-117c-4368-a504-10c756d8d1d5 | 3 | public void queueSound(FilenameURL filenameURL) {
if (!toStream) {
errorMessage("Method 'queueSound' may only be used for "
+ "streaming and MIDI sources.");
return;
}
if (filenameURL == null) {
errorMessage("File not specified in method 'queueSound'");
return;
}
synchronized (soundSequenceLock) {
if (soundSequenceQueue == null)
soundSequenceQueue = new LinkedList<FilenameURL>();
soundSequenceQueue.add(filenameURL);
}
} |
6483eadc-9a8a-42df-9945-e2f2fd54a429 | 7 | 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 ("Windows".equals(info.getName())) {
javax.swing.UIManager.setLookAndFeel(info.getClassName());
break;
}
}
} catch (ClassNotFoundException ex) {
java.util.logging.Logger.getLogger(Preferences.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (InstantiationException ex) {
java.util.logging.Logger.getLogger(Preferences.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (IllegalAccessException ex) {
java.util.logging.Logger.getLogger(Preferences.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (javax.swing.UnsupportedLookAndFeelException ex) {
java.util.logging.Logger.getLogger(Preferences.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
}
//</editor-fold>
/* Create and display the form */
java.awt.EventQueue.invokeLater(new Runnable() {
@Override
public void run() {
try {
new Preferences().setVisible(true);
} catch (IOException ex) {
Logger.getLogger(Preferences.class.getName()).log(Level.SEVERE, null, ex);
}
}
});
} |
668a3405-681c-4469-babf-0dd41c9b9776 | 1 | @Override
public boolean canAttack(Board board, Field currentField, Field occupiedField) {
return this.validSetupForAttack(currentField, occupiedField) && occupiedField.areAdjacentTo(currentField);
} |
80dbcc2f-2650-4d99-8ca0-79f7de35c2ef | 0 | public SolarSystemLoc(Ticker ticker) {
super(ticker);
initializationLevel();
} |
00f5d4af-d885-4a1b-a5b1-ae056615aac7 | 0 | public List<EventBranch> getEventBranchList() {
return eventBranchList;
} |
8312eda6-1c87-4610-b212-df6d5fd765c8 | 0 | public void setCueNaturaleza(String cueNaturaleza) {
this.cueNaturaleza = cueNaturaleza;
} |
e61cfb9b-a216-4bb7-944f-f02866a9d5f3 | 3 | public Point getPosn(ArrayList<Point> lst) {
Point result = this.from;
for (Point p : lst) {
if (p.x == this.from.x && p.y == this.from.y) {
result = this.to;
}
}
return result;
} |
94ae40e1-e298-44a7-aabf-925776e63b60 | 7 | public void addBook() {
// User inputs: isbn, title, mainAuthors, otherAuthors,
// publisher, year, subjects
JTextField isbnField = new JTextField(15);
JTextField titleField = new JTextField(20);
JTextField mainAuthorField = new JTextField(20);
JTextField otherAuthorsField = new JTextField(90);
JTextField publisherField = new JTextField(10);
JTextField yearField = new JTextField(10);
JTextField subjectsField = new JTextField(90);
Vector<String> list = getSubjectList();
JList subjectsList = new JList(list);
subjectsList.setVisibleRowCount(5);
subjectsList.setSelectionMode(ListSelectionModel.MULTIPLE_INTERVAL_SELECTION);
subjectsList.setLayoutOrientation(JList.VERTICAL_WRAP);
JComponent[] inputs = new JComponent[] {
new JLabel("isbn:"), isbnField,
new JLabel("Title:"), titleField,
new JLabel("Main author:"), mainAuthorField,
new JLabel("Other authors:"), otherAuthorsField,
new JLabel("Publisher:"), publisherField,
new JLabel("Year:"), yearField,
new JLabel("Subjects:"), subjectsList,
new JLabel("Add new subjects:"), subjectsField
};
int result = JOptionPane.showConfirmDialog(null, inputs,
"Enter book info", JOptionPane.OK_CANCEL_OPTION,
JOptionPane.WARNING_MESSAGE);
if (result == JOptionPane.OK_OPTION) {
String isbn = isbnField.getText();
String title = titleField.getText();
String mainAuthor = mainAuthorField.getText();
String[] otherAuthors = otherAuthorsField.getText().split(",");
String publisher = publisherField.getText();
int year = Integer.parseInt(yearField.getText());
String callNumber = randomString() + " " + randomString() + " "
+ Integer.toString(year);
// Retrieve list of subjects for book
Vector<String> subjects = new Vector<String>(5,1);
for (int i = 0; i < subjectsList.getSelectedValues().length; i++) {
subjects.addElement(subjectsList.getSelectedValues()[i].toString());
}
String[] newSubjects = subjectsField.getText().split(",");
Collections.addAll(subjects, newSubjects);
try {
// Insert new book into Book table
PreparedStatement ps = Library.con
.prepareStatement("INSERT INTO book (callNumber, isbn, title, mainAuthor, publisher, year) VALUES (?,?,?,?,?,?)");
ps.setString(1, callNumber);
ps.setString(2, isbn);
ps.setString(3, title);
ps.setString(4, mainAuthor);
ps.setString(5, publisher);
ps.setInt(6, year);
ps.executeUpdate();
Library.con.commit();
// Show Book table
Statement stmt = Library.con.createStatement();
ResultSet rs = stmt.executeQuery("SELECT * FROM Book");
LibraryGUI.showTable(rs, "addBookButton");
rs.close();
ps.close();
} catch (SQLException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
try {
for (int i = 0; i < otherAuthors.length; i++) {
// Add other entered authors into hasAuthor table
PreparedStatement ps = Library.con
.prepareStatement("INSERT INTO hasAuthor VALUES (?,?)");
ps.setString(1, callNumber);
ps.setString(2, otherAuthors[i]);
ps.executeUpdate();
Library.con.commit();
ps.close();
}
} catch (SQLException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
try {
for (int i = 0; i < subjects.size(); i++) {
// Add subjects into hasSubjects table
PreparedStatement ps = Library.con
.prepareStatement("INSERT INTO hasSubject VALUES (?,?)");
ps.setString(1, callNumber);
ps.setString(2, subjects.get(i));
ps.executeUpdate();
Library.con.commit();
ps.close();
}
} catch (SQLException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
}
} |
89e4380c-fe17-44b9-805f-72e0b4b0cf92 | 0 | @RequestMapping(value = "/store/employee/skills", method = RequestMethod.POST)
public String insertEmployeeSkillRatings(@RequestBody UserSkillSet userSkillSet ) {
ObjectMapper objectMapper = new ObjectMapper();
ObjectNode objectNode = objectMapper.createObjectNode();
employeeDao.insertSkillSet(userSkillSet);
objectNode.put("skills", "yoyo");
return objectNode.toString();
} |
252e3444-e8f5-44bf-97f4-fdb97bdedfd3 | 3 | public int execute() {
// Build info
/*String[] commands = YuccaCommandFactory.getImplementedCommands();
StringBuffer b = new StringBuffer( "Available commands: " );
for( int i = 0; i < commands.length; i++ ) {
if( i > 0 )
b.append( ", " );
b.append( commands[i] );
}
System.out.println( b.toString() );
*/
// Try to locate command
Command desiredCommand = null;
StringBuffer b = new StringBuffer( "Available commands: " );
java.util.Set<Command> supportedCommands = this.yuccaCommandFactory.getSupportedCommands();
//System.out.println( getClass() + " supported commands: " + supportedCommands );
Iterator<Command> iter = supportedCommands.iterator();
int i = 0;
while( iter.hasNext() && desiredCommand == null ) {
Command c = iter.next();
//if( c.getName().equalsIgnoreCase(this.helpName) )
// desiredCommand = c;
if( i > 0 )
b.append( ", " );
b.append( c.getName() );
i++;
}
//if( desiredCommand == null
// || desiredCommand.getClass().equals(this.getClass()) ) {
System.out.println( b.toString() );
/* } else {
System.out.println( "Help for '" + this.helpName + "' not yet available (not yet implemented @ " + getClass().getName() + ")." );
*/
// }
//}
return 0;
} |
0845fe31-a6bf-414a-ada2-7e1e45c3039e | 1 | public Iterator<Point2D> getPoints( final float start, final float end, final int nPoints ) {
if( nPoints == 1 ) {
return new Iterator<Point2D>() {
private boolean hasNext = true;
@Override
public boolean hasNext() {
return hasNext;
}
@Override
public Point2D next() {
hasNext = false;
return getPointAt( start + (end - start) / 2.0f );
}
@Override
public void remove() {
throw new UnsupportedOperationException();
}
};
} else {
return new Iterator<Point2D>() {
private int index;
@Override
public boolean hasNext() {
return index < nPoints;
}
@Override
public Point2D next() {
float position = start + (end - start) * (index / (nPoints - 1.0f));
index++;
return getPointAt( position );
}
@Override
public void remove() {
throw new UnsupportedOperationException();
}
};
}
} |
4bab4f8b-6533-4209-b30f-e7dafa77f8f7 | 4 | @Override
public void paint(Graphics g){
this.requestFocus();
Graphics2D tileGraphics = (Graphics2D) g;
for (int row = 0; row < Map.ARRAYSIZE; row++) {
for (int col = 0; col < Map.ARRAYSIZE; col++) {
tileGraphics.setColor(Color.BLACK);
tileGraphics.fillRect(row*tileSize, col*tileSize, tileSize, tileSize);
}
}
tileGraphics.setColor(Color.WHITE);
Font font = new Font("Dialog", Font.BOLD, 15);
tileGraphics.setFont(font);
if(storyIndex < 3){
tileGraphics.drawString(story[storyIndex], 80, 150);
}
if(storyIndex == 2){
tileGraphics.drawImage(dragonImage, 190, 200, null);
tileGraphics.drawString("Press the Space Bar to Begin Your Quest", 125, 500);
}
storyIndex++;
} |
aed503e5-0fc1-40c8-8bb6-9ad38ac9d6b1 | 4 | protected boolean in_grouping_b(char [] s, int min, int max)
{
if (cursor <= limit_backward) return false;
char ch = current.charAt(cursor - 1);
if (ch > max || ch < min) return false;
ch -= min;
if ((s[ch >> 3] & (0X1 << (ch & 0X7))) == 0) return false;
cursor--;
return true;
} |
f28ac6e1-b9db-4358-b70e-794777ca6739 | 8 | public boolean containsValidCustomerDetails() {
return isValidForename()
&& isValidSurname()
&& isValidHouseNum()
&& isValidStreet()
&& isValidPostcode()
&& isValidEmail()
&& isValidCardNum()
&& isValidPassword()
&& isMatchForPassword();
} |
1b6a5330-6fdc-48ec-b776-384b76eb1221 | 4 | public void paint(GC gc, int width, int height) {
if (!example.checkAdvancedGraphics()) return;
Device device = gc.getDevice();
if (ovalColorGB != null && ovalColorGB.getBgColor1() != null)
gc.setBackground(ovalColorGB.getBgColor1());
gc.setAntialias(aliasValues[aliasCombo.getSelectionIndex()]);
Path path = new Path(device);
float offsetX = 2*width/3f, offsetY = height/3f;
for(int i=0; i < 25; i++) {
path.addArc(offsetX-(50*i), offsetY-(25*i), 50+(100*i), 25+(50*i), 0, 360);
}
gc.fillPath(path);
path.dispose();
} |
23c76c58-162c-4eaa-89ec-83fffa5311fe | 0 | public void correct() {
System.out.println("correct method");
} |
95860a72-f4c4-431e-a8fd-69847bf776bb | 8 | public boolean checkBookValues(String isbn, String title, String author){
boolean resultCheck = false;
if(isbn.length() <= Model.getInstance().getBookIsbnSize() &&
title.length() <= Model.getInstance().getBookTitleSize() &&
author.length() <= Model.getInstance().getBookAuthorSize() && !(isbn.isEmpty()) ){
resultCheck = true;
}
else if(!(isbn.length() <= Model.getInstance().getBookIsbnSize()) || isbn.isEmpty()){
View.getInstance().printMessage(8);
}
else if(!(title.length() <= Model.getInstance().getBookTitleSize())){
View.getInstance().printErrorText(11);
}
else {View.getInstance().printErrorText(12);}
if(LOGGER.isLoggable(Level.FINE)){
LOGGER.log(Level.FINE, "The result of check book values is: ", resultCheck);}
return resultCheck;
} |
aa14ecc8-2992-447f-9107-09c1bdfbad4e | 6 | private static boolean isStalemateSituation(BotState state) {
boolean isStalemateSituation = true;
int ownIncome = state.getStartingArmies();
int opponentIncome = HeuristicMapModel.getGuessedOpponentIncome();
// No stalemate situation without seeing the opponent
if (state.getVisibleMap().getEnemyRegions(state).size() == 0) {
isStalemateSituation = false;
}
// No stalemate with income difference
if (ownIncome != opponentIncome) {
isStalemateSituation = false;
}
// No stalemate when the opponent can attack us without us deploying.
List<NeededDefenseArmies> neededDefenseArmiesList = NeededArmiesCalculator.neededDefenseArmiesList;
for (NeededDefenseArmies nDA : neededDefenseArmiesList) {
Region defenceRegion = nDA.region;
if (defenceRegion.getArmies() < nDA.fairDefenceArmiesDeployment) {
isStalemateSituation = false;
}
}
// No stalemate when we can attack the opponent without him deploying.
List<NeededAttackArmies> neededAttackArmiesList = NeededArmiesCalculator.neededAttackArmiesList;
for (NeededAttackArmies nAA : neededAttackArmiesList) {
Region attackRegion = nAA.region;
int maximumAttackArmies = attackRegion.getOwnSurroundingPossibleAttackArmies(state);
if (maximumAttackArmies > nAA.fairFightArmiesNoDeployment) {
isStalemateSituation = false;
}
}
return isStalemateSituation;
} |
1b1e1b4c-4ff1-44a8-be6d-fbaf31050c94 | 9 | public void calibrate() {
double minValue = minData;
double maxValue = maxData;
if (minAxisFlag== AT_ZERO) {
minValue = 0;
} else if (minAxisFlag == AT_VALUE) {
minValue = this.minValue;
}
if (maxAxisFlag== AT_ZERO) {
maxValue = 0;
} else if (maxAxisFlag == AT_VALUE) {
maxValue = this.maxValue;
}
double range = maxValue - minValue;
if (range < 0.0) {
range = 0.0;
}
epsilon = range * 1.0E-10;
if (isAutomatic) {
// We must find the optimum minMajorTick and maxMajorTick so
// that they contain the data range (minData to maxData) and
// are in the right order of magnitude
if (range < 1.0E-30) {
if (minData < 0.0) {
majorTick = Math.pow(10.0, Math.floor(log10(Math.abs(minData))));
minTick = Math.floor(minData / majorTick) * majorTick;
maxTick = 0.0;
} else if (minData > 0.0) {
majorTick = Math.pow(10.0, Math.floor(log10(Math.abs(minData))));
minTick = 0.0;
maxTick = Math.ceil(maxData / majorTick) * majorTick;
} else {
minTick = -1.0;
maxTick = 1.0;
majorTick = 1.0;
}
minorTick = majorTick;
majorTickCount = 1;
minorTickCount = 0;
} else {
// First find order of magnitude below the data range...
majorTick = Math.pow(10.0, Math.floor(log10(range)));
calcMinTick();
calcMaxTick();
calcMajorTick();
calcMinorTick();
}
}
minAxis = minTick;
maxAxis = maxTick;
handleAxisFlags();
isCalibrated=true;
} |
aa82434c-2df5-4ca9-9370-4514a487cdb5 | 5 | private int affecteNumCourt(String terrain) {
if (terrain.equals("Court central")) return 1;
else if (terrain.equals("Court annexe")) return 2;
else if (terrain.equals("Court d'entrainement 1")) return 3;
else if (terrain.equals("Court d'entrainement 2")) return 4;
else if (terrain.equals("Court d'entrainement 3")) return 5;
else return 6;
} |
8af92c68-d6c0-4ecd-8f8d-b15326a915a6 | 9 | public void updatePosition() {
//System.out.println(xPos + " " + yPos);
//System.out.println(xDestination + " yolo " + yDestination);
if (xPos < xDestination)
xPos+=2;
else if (xPos > xDestination)
xPos-=2;
if (yPos < yDestination)
yPos+=2;
else if (yPos > yDestination)
yPos-=2;
if (xPos == xDestination && yPos == yDestination && moving) {
moving = false;
agent.msgAtDestination();
}
if(xPos==-20 && yPos==-20)
{
}
} |
9c18a3e1-8fe2-483a-b09c-cb97e0ac1bdc | 2 | private void buildQuestionPanelP2() {
pnlNewQ2 = new JPanel();
pnlNewQ2.setLayout(new BoxLayout(pnlNewQ2, BoxLayout.X_AXIS));
pnlQTypeSwap = new JPanel();
cardQType = new CardLayout();
pnlQTypeSwap.setLayout(cardQType);
/* Multiple choice: */
ButtonGroup bg = new ButtonGroup();
rbAnsList = new ArrayList<JRadioButton>(4);
// multiple choice text fields:
tfMultiList = new ArrayList<JTextField>(4);
pnlMultiAns = new JPanel();
pnlMultiAns.setLayout(new GridLayout(4, 0, 0, 5));
// build the table:
String[] labels = { "A", "B", "C", "D" };
for (int i = 0; i < 4; i++) {
JRadioButton rb = new JRadioButton(labels[i]);
// rb.setPreferredSize(new Dimension((int)(rb.getWidth()*1.5d), rb.getHeight()));
JTextField ans = new JTextField("");
rbAnsList.add(rb);
tfMultiList.add(ans);
// add to button group
bg.add(rb);
// layout the row:
rb.setAlignmentX(JTextField.LEFT_ALIGNMENT);
JPanel subPane = new JPanel();
subPane.setLayout(new BoxLayout(subPane, BoxLayout.X_AXIS));
subPane.add(rb);
subPane.add(Box.createHorizontalStrut(5));
subPane.add(ans);
// put the sub panel inside the main container for the questions
pnlMultiAns.add(subPane);
}
rbAnsList.get(0).setSelected(true);
/* end multi choice */
/* short answer: */
pnlShortAns = new JPanel();
pnlShortAns.setLayout(new BoxLayout(pnlShortAns, BoxLayout.Y_AXIS));
lblQAnswer = new JLabel("Answer:");
tfShortAnswer = new JTextArea();
JScrollPane scroll = new JScrollPane(tfShortAnswer);
tfShortAnswer.setBorder(scroll.getBorder());
lblQAnswer.setAlignmentX(JLabel.LEFT_ALIGNMENT);
scroll.setAlignmentX(JScrollPane.LEFT_ALIGNMENT);
pnlShortAns.add(lblQAnswer);
pnlShortAns.add(Box.createVerticalStrut(10));
pnlShortAns.add(scroll);
/* end short */
pnlQTypeSwap.add(pnlMultiAns, TYPE_MULTI);
pnlQTypeSwap.add(pnlShortAns, TYPE_SHORT);
pnlQTypeSwap.setAlignmentX(JPanel.LEFT_ALIGNMENT);
//pnlQTypeSwap.setAlignmentY(JPanel.BOTTOM_ALIGNMENT);
/* buttons: */
btnNewQBack = new JButton("Back");
btnNewQSubmit = new JButton("Submit");
btnNewQBack.setAlignmentX(JButton.RIGHT_ALIGNMENT);
btnNewQSubmit.setAlignmentX(JButton.RIGHT_ALIGNMENT);
//btnNewQBack.setAlignmentY(JButton.BOTTOM_ALIGNMENT);
btnNewQSubmit.setAlignmentY(JButton.BOTTOM_ALIGNMENT);
btnNewQBack.setPreferredSize(btnNewQSubmit.getPreferredSize());
JPanel sub = new JPanel();
sub.setLayout(new BoxLayout(sub, BoxLayout.Y_AXIS));
sub.add(Box.createVerticalGlue());
sub.add(btnNewQBack);
sub.add(Box.createVerticalStrut(5));
sub.add(btnNewQSubmit);
//sub.add(Box.createVerticalStrut(5));
sub.setAlignmentY(JPanel.CENTER_ALIGNMENT);
/* end buttons */
pnlNewQ2.add(pnlQTypeSwap);
pnlNewQ2.add(Box.createHorizontalStrut(20));
pnlNewQ2.add(Box.createHorizontalGlue());
pnlNewQ2.add(sub);
if (rbMultChoice.isSelected()) {
cardQType.show(pnlQTypeSwap, TYPE_MULTI);
} else {
cardQType.show(pnlQTypeSwap, TYPE_SHORT);
}
} |
461483f6-24e9-496e-92f6-ae83364fe5b2 | 5 | public void paintIcon(Component c, Graphics g, int x, int y) {
Color color = c == null ? Color.GRAY : c.getBackground();
// In a compound sort, make each succesive triangle 20%
// smaller than the previous one.
int dx = (int)(size/2*Math.pow(0.8, priority));
int dy = descending ? dx : -dx;
// Align icon (roughly) with font baseline.
y = y + 5*size/6 + (descending ? -dy : 0);
int shift = descending ? 1 : -1;
g.translate(x, y);
// Right diagonal.
g.setColor(color.darker());
g.drawLine(dx / 2, dy, 0, 0);
g.drawLine(dx / 2, dy + shift, 0, shift);
// Left diagonal.
g.setColor(color.brighter());
g.drawLine(dx / 2, dy, dx, 0);
g.drawLine(dx / 2, dy + shift, dx, shift);
// Horizontal line.
if (descending) {
g.setColor(color.darker().darker());
} else {
g.setColor(color.brighter().brighter());
}
g.drawLine(dx, 0, 0, 0);
g.setColor(color);
g.translate(-x, -y);
} |
db5f1974-d9b3-4ca8-8d54-6a21fffe52a6 | 0 | public void movePegs() {
x.centerX = centerX - Peg.width;
z.centerX = centerX + Peg.width;
y.centerX = centerX;
x.centerY = centerY;
z.centerY = centerY;
y.centerY = centerY + Peg.height;
} |
41bfd8be-1881-44a9-a306-4b0fc80b93d8 | 6 | public Token read() throws IOException {
try {
while (reader.ready()) {
int c = reader.read();
if (Character.isWhitespace(c)) {
whitespaceReader.readValue(reader, c);
} else if (Character.isLetter(c)) {
return identifierReader.getToken(reader, c);
} else if (Character.isDigit(c)) {
return numberReader.getToken(reader, c);
} else if (c == '"') {
return stringReader.getToken(reader, c);
} else {
return symbolReader.getToken(reader, c);
}
}
return null;
} catch (IOException e) {
e.printStackTrace();
throw e;
}
} |
4f6cfba7-5348-4e8e-a81d-2f2747a44664 | 4 | public void setCellState(int x, int y, boolean alive)
{
if (x > 0 && x < width && y > 0 && y < height)
grid[y][x] = alive;
} |
f055d50e-b310-4526-addd-0f6da4870f58 | 5 | private void handleEvents(byte[] resp) {
if(resp == null || resp.length == 0) {
return;
}
RS232Packet respPacket = socket.parseResponse(resp);
creditAction = respPacket.getCreditAction();
rawFirmwareRevision = respPacket.getFirmwareRevision();
rawAcceptorModel = respPacket.getAcceptorModel();
PTalkEvent e;
for (Events type : respPacket.getInterpretedEvents()) {
// Is this an event that requires extra data?
switch (type) {
case Credit:
e = new CreditEvent(
this,
Utilities.bytesToString(resp),
respPacket.getBillName());
break;
case Escrowed:
e = new EscrowedEvent(
this,
Utilities.bytesToString(resp),
respPacket.getBillName());
break;
default:
e = new PTalkEvent(this, type, respPacket.getByteString());
}
// Notify any listeners that we have data
fireChangeEvent(e);
}
} |
1857985f-8c86-414b-b300-38f2b1ba1618 | 2 | public boolean simpleIsConcurrent(String pathExpression1, String pathExpression2, String operator1, String operator2, String type1, String type2){
if (pathExpression1.equals(pathExpression2)){
if (type1.equals(type2)){
return mutuallyExclusive(operator1, operator2, type1, type2);
} else {
System.err.println("Die Datentypen in den Bedingungen sind von unterschiedlichem Typ. Die Forderung, dass nur dieselben Typen verglichen werden koennen, wird verletzt!");
System.exit(0);
return false;
}
} else {
return true;
}
} |
47401ae5-d211-4d3f-9b9f-587ac64cd825 | 8 | private void buildQueryMapSet(Triple buildQuery){
Node subject = buildQuery.getSubject();
Node object = buildQuery.getObject();
Predicate predicate = buildQuery.getPredicate();
//Possible permutations of the query
String Q1 = "?"+" "+predicate.getIdentifier()+" "+object.getIdentifier();
String Q2 = subject.getIdentifier()+" "+"?"+" "+object.getIdentifier();
String Q3 = subject.getIdentifier()+" "+predicate.getIdentifier()+" "+"?.";
String Q4 = "?"+" "+predicate.getIdentifier()+" "+"?.";
String Q5 = subject.getIdentifier()+" "+"?"+" "+"?.";
String Q6 = "?"+" "+"?"+" "+object.getIdentifier();
String Q7 = "?"+" "+"?"+" "+"?.";
String Q8 = subject.getIdentifier()+" "+predicate.getIdentifier()+" "+object.getIdentifier();
//Add each query to its Map
if (queryMapSet.containsKey(Q1)) queryMapSet.get(Q1).add(buildQuery); else {queryMapSet.put(Q1, new HashSet<Triple>()); queryMapSet.get(Q1).add(buildQuery); }
if (queryMapSet.containsKey(Q2)) queryMapSet.get(Q2).add(buildQuery); else {queryMapSet.put(Q2, new HashSet<Triple>()); queryMapSet.get(Q2).add(buildQuery); }
if (queryMapSet.containsKey(Q3)) queryMapSet.get(Q3).add(buildQuery); else {queryMapSet.put(Q3, new HashSet<Triple>()); queryMapSet.get(Q3).add(buildQuery); }
if (queryMapSet.containsKey(Q4)) queryMapSet.get(Q4).add(buildQuery); else {queryMapSet.put(Q4, new HashSet<Triple>()); queryMapSet.get(Q4).add(buildQuery); }
if (queryMapSet.containsKey(Q5)) queryMapSet.get(Q5).add(buildQuery); else {queryMapSet.put(Q5, new HashSet<Triple>()); queryMapSet.get(Q5).add(buildQuery); }
if (queryMapSet.containsKey(Q6)) queryMapSet.get(Q6).add(buildQuery); else {queryMapSet.put(Q6, new HashSet<Triple>()); queryMapSet.get(Q6).add(buildQuery); }
if (queryMapSet.containsKey(Q7)) queryMapSet.get(Q7).add(buildQuery); else {queryMapSet.put(Q7, new HashSet<Triple>()); queryMapSet.get(Q7).add(buildQuery); }
if (queryMapSet.containsKey(Q8)) queryMapSet.get(Q8).add(buildQuery); else {queryMapSet.put(Q8, new HashSet<Triple>()); queryMapSet.get(Q8).add(buildQuery); }
// System.out.println("//-------//");
// printHashMap(queryMapSet);
// System.out.println("//-------//");
} |
234301dd-1f41-41c8-935a-8dfa4614f1a4 | 7 | private void Build()
{
greenPlants = ps.getGreenPlants();
plasticWrap = ps.getPlasticWrap();
roundRocks = ps.getRoundRocks();
energy = ps.getEnergy();
Dialog.message("I can build a solar still to collect");
Dialog.message("water over time for me to consume.\n", 2000);
Dialog.message("Materials needed -- 8 green plants, " + " 1 plastic wrap, 10 round rocks");
Dialog.message("Materials on hand -- " + greenPlants + " green plants, " +
plasticWrap + " plastic wrap, " + roundRocks + " round rocks.\n");
Dialog.message("This will also take 2 hours to complete and 40 energy.\n");
while(!valid)
{
Dialog.message("Actions -- BUILD, LEAVE");
choice = Input.getStringInput(sc);
if (choice.equalsIgnoreCase("BUILD"))
{
if(greenPlants >= 8 && plasticWrap >= 1
&& roundRocks >= 10 && energy >= 40)
{
Dialog.message("You kneel down into an open area.", 2000);
Dialog.message("Slowly you dig out a hole with your hands.", 2000);
Dialog.message("You place the container at the bottom");
Dialog.message("and surround it with fresh grass", 2500);
Dialog.message("You cover the top with your clear plastic wrap");
Dialog.message("and begin using the rocks to hold it in place.", 2500);
Dialog.message("Finnaly, you put a small rock in the");
Dialog.message("center to complete the solar still.\n", 2500);
Dialog.message("Solar Still complete!", 3000);
greenPlants -= 8;
plasticWrap -= 1;
roundRocks -= 10;
energy -= 40;
ps.setGreenPlants(greenPlants);
ps.setPlasticWrap(plasticWrap);
ps.setRoundRocks(roundRocks);
ps.setEnergy(energy);
ps.setHasSolar(true);
ps.updateTime(2);
}
else
{
Dialog.message("I don't have enough materials to build it.");
}
}
else if (choice.equalsIgnoreCase("LEAVE"))
{
Dialog.message("Maybe, I will build one later...", 2000);
}
else
{
System.out.println("Invalid command, try again.");
sc.nextLine();
continue;
}
valid = true;
}
} |
68704e92-d950-4de6-88b4-9a3856758e00 | 1 | public void show() {
if (getMessage() == null)
setMessage(DEFAULT_MESSAGE);
super.show();
} |
3e0e8ec1-c49e-4b8a-8909-a42769d7a3ce | 1 | public static void changeToParent(OutlinerCellRendererImpl textArea, JoeTree tree, OutlineLayoutManager layout) {
Node newSelectedNode = textArea.node.getParent();
if (newSelectedNode.isRoot()) {
return;
}
tree.setSelectedNodesParent(newSelectedNode.getParent());
tree.addNodeToSelection(newSelectedNode);
tree.setEditingNode(newSelectedNode);
// Redraw and Set Focus
layout.draw(newSelectedNode, OutlineLayoutManager.ICON);
} |
59c2c0ba-2b32-4dd3-baf4-03f9aa66d4fa | 4 | public void createTables() {
// Table PLAYER
if (!_sqLite.isTable("player")) {
try {
_sqLite.query("CREATE TABLE player("
+ "id INTEGER PRIMARY KEY AUTOINCREMENT, "
+ "playername TEXT UNIQUE COLLATE NOCASE);");
} catch (Exception e) {
// TODO
}
}
// Table LOGIN
if (!_sqLite.isTable("login")) {
try {
_sqLite.query("CREATE TABLE login("
+ "id INTEGER PRIMARY KEY AUTOINCREMENT, "
+ "id_player INTEGER NOT NULL, "
+ "time_login DATETIME NOT NULL DEFAULT (datetime('now', 'localtime')), "
+ "time_logout DATETIME, "
+ "time_online INTEGER, "
+ "time_afk DATETIME, "
+ "world TEXT, "
+ "x INT, "
+ "y INT, "
+ "z INT, "
+ "FOREIGN KEY(id_player) REFERENCES player(id) ON DELETE CASCADE);");
} catch (Exception e) {
// TODO
}
}
} |
6aff5488-e05f-4bd4-a40e-522fb9be1b80 | 7 | public void addOperator(BinaryOperator operator) {
if (!functionContextStack.isEmpty()) {
Integer sizeOperators = functionContextStack.peek().getSizeOperatorsForParameters();
if (sizeOperators != null) {
while (!operatorStack.isEmpty() &&
sizeOperators != operatorStack.size() &&
operator.compareTo(operatorStack.peek()) <= 0) {
final BinaryOperator binaryOperator =
operatorStack.pop();
applyOperator(binaryOperator);
}
}
} else {
while (!operatorStack.isEmpty() &&
operator.compareTo(operatorStack.peek()) <= 0) {
applyOperator(operatorStack.pop());
}
}
operatorStack.push(operator);
} |
be3b931b-52f8-45c1-b849-502384809b30 | 3 | public static ArrayList doit(ExtendedIterator<? extends OntResource> it, VelocityContext context) {
/* create our list of maps */
ArrayList list = new ArrayList();
for (OntResource r = null; it.hasNext(); ) {
r = it.next();
if (r.isAnon()) {
continue;
}
Map map = new HashMap();
map.put("name", r.getLocalName());
map.put("label", label(r));
map.put("comment", comment(r));
list.add(map);
}
return list;
} |
fa4ab541-1507-4599-b230-e3be13e3a155 | 2 | private void renderGrid(Graphics g) {
Coordinate worldSize = wb.getSize();
g.setColor(Color.red);
for (int i = 1; i <= worldSize.x; i++) {
Coordinate c1 = coordinateToPixel(i, 0);
Coordinate c2 = coordinateToPixel(i, worldSize.y);
g.drawLine(c1.x, c1.y - blockHeight / 2, c2.x, c2.y);
}
for (int i = 1; i <= worldSize.y; i++) {
Coordinate c1 = coordinateToPixel(0, i);
Coordinate c2 = coordinateToPixel(worldSize.x, i);
g.drawLine(c1.x + blockWidth / 2, c1.y, c2.x, c2.y);
}
} |
787a531e-99a5-4217-9c04-78e4b684524d | 5 | public static boolean correctOrder(String str){
//base case-if there are only 2 chars and the first and last are in correct order-true
if(str.length()==3 && (str.charAt(0)>str.charAt(2))){
return true;
}
//if the string is less than 3 chars long it returns true as impossible to determine
else if(str.length()<3){
return true;
}
else{
if(str.charAt(0)>str.charAt(2)&& str.charAt(1)<str.charAt(3)){
return correctOrder(str.substring(2, str.length()));
}
else{
return false;
}
}
} |
0c203b9c-16ca-4763-b8b5-ed45346d0865 | 8 | private static void countWords(String file,String count, String struct) {
DataCounter<String> counter = null;
// divide into several situations and create different structures
if(count.equals("-b"))
counter= new BinarySearchTree<String>(new StringComparator());
else if(count.equals("-m"))
counter = new MoveToFrontList<String>(new StringComparator());
else if(count.equals("-a"))
counter = new AVLTree<String>(new StringComparator());
else
System.err.println("error");
try {
FileWordReader reader = new FileWordReader(file);
String word = reader.nextWord();
while (word != null) {
counter.incCount(word);
word = reader.nextWord();
}
} catch (IOException e) {
System.err.println("Error processing " + file + " " + e);
System.exit(1);
}
DataCount<String>[] counts = getCountsArray(counter);
// get different info and use different method of sorting
if(struct.equals("-is"))
insertionSort(counts, new DataCountStringComparator());
else if(struct.equals("-hs"))
heapSort(counts, new DataCountStringComparator());
else
System.err.println("error");
for (DataCount<String> c : counts)
System.out.println(c.count + " \t" + c.data);
} |
28f69014-2847-4a12-b3b2-bd27033d7849 | 5 | public boolean search(int val) {
DLNode current = head;
if (this.head == null) {
return false;
}
while (current != null) {
if (val == current.getVal()) {
return true;
} else if (current.getVal() == Integer.MIN_VALUE) {
if (current.getList().search(val) == true) {
return true;
}
}
current = current.getNext();
}
return false;
} |
d08b5c70-40ed-4083-b04f-87bb11c55b34 | 9 | private void construct(Constraint[] constraints, int nconstraints) {
this.constraints=constraints;
this.nconstraints=nconstraints;
VERBOSE=CSPStrategy.VERBOSE;
variables=null;
nodes = new ConstraintList[nconstraints*2];
nvariables=0;
min=0;
max=0;
bestProbe=null;
// tally variables and count maximum mines
for (int i=0; i<nconstraints; ++i) {
BoardPosition[] vararray = constraints[i].getVariables();
for (int j=0; j<vararray.length; ++j) {
boolean found=false;
for (int k=0; k<nvariables; ++k)
if (nodes[k].variable.equals(vararray[j])) {
nodes[k].addConstraint(constraints[i]);
found=true;
break;
}
if (!found) {
if (nvariables>=nodes.length) {
// reallocate variables
ConstraintList[] newnodes =
new ConstraintList[nvariables*2];
System.arraycopy(nodes,0,newnodes,0,nvariables);
nodes=newnodes;
}
nodes[nvariables++] =
new ConstraintList(constraints[i],vararray[j]);
}
}
min+=constraints[i].getConstant();
}
/* Note: we used min here to tally the absolute maximum number of mines
* expected because this number is a good initial value for the minimum
* mines variables.
*/
// sort variables in decending order by number of constraints
Arrays.sort(nodes,0,nvariables);
if (nodes[0].nconstraints<nodes[nvariables-1].nconstraints)
System.err.println("WRONG ORDER!!!");
// create variables array
variables = new BoardPosition[nvariables];
for (int i=0; i<nvariables; ++i)
variables[i] = nodes[i].variable;
// create needed arrays
solutions = new int[min+1];
mines = new int[min+1][];
for (int i=0; i<=min; ++i)
mines[i] = new int[nvariables];
} |
6701a10a-17e1-4ab2-b58b-f6f0302ebb6b | 4 | private ArrayList<Boolean> getRowByLeftState(String state, String topOrBottom) {
ArrayList<Boolean> fullRow = new ArrayList<Boolean>();
if (topOrBottom.equals("top")) {
int index = topOfTableRow.indexOf(state);
if (index == -1 ) return fullRow;
fullRow = topTable.get(index);
} else if (topOrBottom.equals("bottom")) {
int index = bottomOfTableRow.indexOf(state);
if (index == -1 ) return fullRow;
fullRow = bottomTable.get(index);
}
return fullRow;
} |
d3e70072-8e16-4304-8d1c-7efeb0693a09 | 4 | public static void main(String[] args) {
System.out.println("Start");
InputStreamReader input = new InputStreamReader(System.in);
processor = new ValueFrequencyProcessor();
while (runing) {
int value = 0;
try {
value = input.read();
} catch (IOException e) {
//gracefully stop on error
e.printStackTrace();
runing = false;
continue;
}
if (value == 64 || value == -1) { // Stop and exit
System.out.println("Stop");
runing = false;
continue;
}
String result = processor.process(value);
System.out.println(((char)value) + "=" + result);
}
} |
50e075f7-6800-4fa3-a0ce-c9ae4b24483f | 1 | private void setToflagOthers(myDataList mylist) {
for (int i = 0; i < mylist.size() - 1; i++) {
((data) mylist.get(i)).setFlag(false);
}
} |
744a515c-f839-4fcc-8a6f-dca290a40996 | 9 | private void jComboBox1ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jComboBox1ActionPerformed
// TODO add your handling code here:
int chose = this.jComboBox1.getSelectedIndex();
if(chose==0) this.setParams(null, null, null,0,1,false);
if(chose==3) this.setParams("0","100","Parametr sepii",0,100,false);
if(chose==12) this.setParams("-100","100","Jasność",-100,100,false);
if(chose==15) this.setParams("-180","180","Obrot o kąt",-180,180,false);
if(chose==16) this.setParams("0","30%","Losowy szum %",0,30,false);
if(chose==17) this.setParams("0","30%","Losowy szum %",0,30,false);
if(chose==18) this.setParams("3","7","Rozmiar maski odszumiania",3,7,false);
if(chose==19) this.setParams("3","7","Rozmiar maski odszumiania",3,7,false);
if(chose==20) this.setParams("3","7","Rozmiar maski odszumiania",3,7,false);
}//GEN-LAST:event_jComboBox1ActionPerformed |
0a115c09-afb5-4a58-9c31-5bf90f8ffba8 | 9 | public Updater(Plugin plugin, int id, File file, UpdateType type, boolean announce) {
this.plugin = plugin;
this.type = type;
this.announce = announce;
this.file = file;
this.id = id;
this.updateFolder = plugin.getServer().getUpdateFolder();
final File pluginFile = plugin.getDataFolder().getParentFile();
final File updaterFile = new File(pluginFile, "Updater");
final File updaterConfigFile = new File(updaterFile, "config.yml");
if (!updaterFile.exists()) {
updaterFile.mkdir();
}
if (!updaterConfigFile.exists()) {
try {
updaterConfigFile.createNewFile();
} catch (final IOException e) {
plugin.getLogger().severe("The updater could not create a configuration in " + updaterFile.getAbsolutePath());
e.printStackTrace();
}
}
this.config = YamlConfiguration.loadConfiguration(updaterConfigFile);
this.config.options().header("This configuration file affects all plugins using the Updater system (version 2+ - http://forums.bukkit.org/threads/96681/ )" + '\n'
+ "If you wish to use your API key, read http://wiki.bukkit.org/ServerMods_API and place it below." + '\n'
+ "Some updating systems will not adhere to the disabled value, but these may be turned off in their plugin's configuration.");
this.config.addDefault("api-key", "PUT_API_KEY_HERE");
this.config.addDefault("disable", false);
if (this.config.get("api-key", null) == null) {
this.config.options().copyDefaults(true);
try {
this.config.save(updaterConfigFile);
} catch (final IOException e) {
plugin.getLogger().severe("The updater could not save the configuration in " + updaterFile.getAbsolutePath());
e.printStackTrace();
}
}
if (this.config.getBoolean("disable")) {
this.result = UpdateResult.DISABLED;
return;
}
String key = this.config.getString("api-key");
if (key.equalsIgnoreCase("PUT_API_KEY_HERE") || key.equals("")) {
key = null;
}
this.apiKey = key;
try {
this.url = new URL(Updater.HOST + Updater.QUERY + id);
} catch (final MalformedURLException e) {
plugin.getLogger().severe("The project ID provided for updating, " + id + " is invalid.");
this.result = UpdateResult.FAIL_BADID;
e.printStackTrace();
}
this.thread = new Thread(new UpdateRunnable());
this.thread.start();
} |
571aa95f-5b01-4edd-8e92-81b77f4853e3 | 7 | public static final void showCourses(DARSInfo.CLASS... classes) {
for (DARSInfo.CLASS curClass : classes) {
System.out.println(curClass.Subject + " " + curClass.Number);
}
Vector<CourseInfo> allCourse = CoursesFile.loadAllCourses();
for (CourseInfo course : allCourse) {
for (DARSInfo.CLASS curClass : classes) {
if(course.Subject.equals(curClass.Subject) && ((curClass.Number.endsWith("*") && curClass.Number.charAt(0) == course.CourseNumber.charAt(0)) || curClass.Number.equals(course.CourseNumber)) ) {
COURSE_DATA.add(course.getrowData());
table.repaint();
scrollPane.revalidate();
}
}
}
} |
a10bca75-dd5d-499f-b699-e7f3866a2625 | 5 | public boolean cast (Sorcerer sorcerer, Trigger trigger, Event event)
{
if (isOnCooldown(sorcerer))
return false;
cooldowns.put(sorcerer, System.currentTimeMillis() + 1000);
if (trigger.isInteractTriggered())
{
PlayerInteractEvent interactEvent = (PlayerInteractEvent) event;
interactEvent.setCancelled(true);
Location origin;
if (trigger.isBlockTriggered())
{
origin = interactEvent.getClickedBlock().getLocation();
}
else
{
Block originBlock =
sorcerer.getPlayer().getTargetBlock(transparentBlocks, 100);
if (originBlock.getType() == Material.AIR)
{
sorcerer.getPlayer().sendMessage(
ChatColor.RED + "No block in sight");
return false;
}
origin = originBlock.getLocation();
}
bigStrike(origin);
}
else if (trigger.isDamageTriggered())
{
EntityDamageByEntityEvent damageEvent =
(EntityDamageByEntityEvent) event;
littleStrike(damageEvent.getEntity().getLocation());
}
return true;
} |
832dcfad-7684-4321-8fa2-d7840ff230cf | 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 Unidade)) {
return false;
}
Unidade other = (Unidade) object;
if ((this.codigo == null && other.codigo != null) || (this.codigo != null && !this.codigo.equals(other.codigo))) {
return false;
}
return true;
} |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.