method_id
stringlengths 36
36
| cyclomatic_complexity
int32 0
9
| method_text
stringlengths 14
410k
|
|---|---|---|
585a6e93-0301-4dc6-aee7-6073abf81bed
| 9
|
public static void countMatchesWeighted(double minIDF, double minTFIDF) {
System.out.println("countMatchesWeighted running");
allDocPairs.clear();
Iterator it2 = dictionaryMap.entrySet().iterator();
while (it2.hasNext()) {
Map.Entry termEntry = (Map.Entry) it2.next();
String token = (String) termEntry.getKey();
ArrayList<String[]> postingsList = (ArrayList) termEntry.getValue();
for (int i = 0; i < postingsList.size() - 1; i++) {
for (int j = i + 1; j < postingsList.size(); j++) {
String combinedName = postingsList.get(i)[DOC_NAME] + "_" + postingsList.get(j)[DOC_NAME];
Double[] currentIDFArray = (Double[]) inverseDocFreqMap.get(token);
if (((Double.parseDouble(postingsList.get(i)[TFIDF_WEIGHT])) >= minTFIDF
|| (Double.parseDouble(postingsList.get(j)[TFIDF_WEIGHT])) >= minTFIDF)
&& currentIDFArray[IDF] >= minIDF) {
if (currentIDFArray[IDF] >= (minIDF + 1.0)) {
if (allDocPairs.containsKey(combinedName)) {
int count = allDocPairs.get(combinedName);
count = count + 2;
allDocPairs.put(combinedName, count);
} else {
allDocPairs.put(combinedName, 2);
}
} else {
if (allDocPairs.containsKey(combinedName)) {
int count = allDocPairs.get(combinedName);
count++;
allDocPairs.put(combinedName, count);
} else {
allDocPairs.put(combinedName, 1);
}
}
}
}
}
}
}
|
ba0d3e73-2ffb-4dcd-bc7a-3d304951ab6c
| 4
|
public void testCycNart() {
System.out.println("\n*** testCycNart ***");
try {
CycNart cycNart = new CycNart(ARITY_RELATION_FN, 1);
testCycObjectRetrievable(cycNart);
CycNart arityRelationFn1 = cycNart;
assertNotNull(cycNart);
assertEquals("(ArityRelationFn 1)", cycNart.toString());
assertEquals("(#$ArityRelationFn 1)", cycNart.cyclify());
CycNart cycNart2 = new CycNart(ARITY_RELATION_FN, 1);
assertEquals(cycNart.toString(), cycNart2.toString());
assertEquals(cycNart, cycNart2);
// compareTo
ArrayList narts = new ArrayList();
CycList<CycObject> nartCycList = new CycList<CycObject>();
nartCycList.add(YEAR_FN);
nartCycList.add(Integer.valueOf(2000));
CycNart year2K = new CycNart(nartCycList);
narts.add(year2K);
assertEquals("[(YearFn 2000)]", narts.toString());
CycConstant person =
getCyc().getKnownConstantByGuid(
CycObjectFactory.makeGuid("bd588092-9c29-11b1-9dad-c379636f7270"));
CycList nartCycList2 = new CycList<CycObject>();
nartCycList2.add(CONVEY_FN);
nartCycList2.add(person);
narts.add(new CycNart(nartCycList2));
CycList nartCycList3 = new CycList<CycObject>();
nartCycList3.add(ARITY_RELATION_FN);
nartCycList3.add(Integer.valueOf(1));
narts.add(new CycNart(nartCycList3));
Collections.sort(narts);
assertEquals("[(ArityRelationFn 1), (ConveyFn Person), (YearFn 2000)]",
narts.toString());
// hasFunctorAndArgs
assertTrue(arityRelationFn1.hasFunctorAndArgs());
assertFalse((new CycNart()).hasFunctorAndArgs());
// toCycList()
CycList cycList = new CycList<CycObject>();
cycList.add(ARITY_RELATION_FN);
cycList.add(Integer.valueOf(1));
assertEquals(cycList, arityRelationFn1.toCycList());
// check cfasl representation of narts in a list
CycList myNarts = new CycList<CycObject>();
myNarts.add(arityRelationFn1);
CycNart arityRelationFn2 = new CycNart(ARITY_RELATION_FN, 2);
myNarts.add(arityRelationFn2);
for (int i = 0; i < myNarts.size(); i++) {
assertTrue(myNarts.get(i) instanceof CycNart);
}
CycList command = new CycList();
command.add(CycObjectFactory.makeCycSymbol("csetq"));
command.add(CycObjectFactory.makeCycSymbol("my-narts"));
command.addQuoted(myNarts);
CycList myNartsBackFromCyc = getCyc().converseList(command);
for (int i = 0; i < myNartsBackFromCyc.size(); i++) {
assertTrue(myNartsBackFromCyc.get(i) instanceof CycNart);
CycNart myNartBackFromCyc = (CycNart) myNartsBackFromCyc.get(i);
assertTrue(myNartBackFromCyc.getFunctor() instanceof CycFort);
assertTrue(myNartBackFromCyc.getArguments() instanceof ArrayList);
ArrayList args = (ArrayList) myNartBackFromCyc.getArguments();
for (int j = 0; j < args.size(); j++) {
Object arg = args.get(j);
assertTrue(arg instanceof Integer);
}
}
// coerceToCycNart
CycNart cycNart4 = new CycNart(ARITY_RELATION_FN, Integer.valueOf(1));
assertEquals(cycNart4, CycNart.coerceToCycNart(cycNart4));
CycList cycList4 = new CycList<CycObject>();
cycList4.add(ARITY_RELATION_FN);
cycList4.add(Integer.valueOf(1));
assertEquals(cycNart2, CycNart.coerceToCycNart(cycList4));
// toXML, toXMLString
XMLStringWriter xmlStringWriter = new XMLStringWriter();
cycNart4.toXML(xmlStringWriter, 0, false);
System.out.println(xmlStringWriter.toString());
String cycNartXMLString = cycNart4.toXMLString();
System.out.println("cycNartXMLString\n" + cycNartXMLString);
Object object = CycObjectFactory.unmarshall(cycNartXMLString);
assertTrue(object instanceof CycNart);
assertEquals(cycNart4, (CycNart) object);
CycNart cycNart5 = new CycNart(THE_LIST, Integer.valueOf(1), "a string");
cycNartXMLString = cycNart5.toXMLString();
System.out.println("cycNartXMLString\n" + cycNartXMLString);
object = CycObjectFactory.unmarshall(cycNartXMLString);
assertTrue(object instanceof CycNart);
assertEquals(cycNart5, (CycNart) object);
// Check whether stringApiValue() behaves properly on a NART with a string argument
CycNart attawapiskat = new CycNart(CITY_NAMED_FN, "Attawapiskat", ONTARIO_CANADIAN_PROVINCE);
Object result = CycUtils.evalSubLWithWorker(getCyc(), attawapiskat.stringApiValue());
assertTrue(result instanceof CycNart);
assertEquals(attawapiskat, (CycNart) result);
// Check whether stringApiValue() behaves properly on a NART
// with a string that contains a character that needs to be escaped in SubL
CycNart hklmSam = new CycNart(REGISTRY_KEY_FN, "HKLM\\SAM");
Object result0 = CycUtils.evalSubLWithWorker(getCyc(), hklmSam.stringApiValue());
assertTrue(result0 instanceof CycNart);
assertEquals(hklmSam, (CycNart) result0);
/*
CycAssertion cycAssertion = getCyc().getAssertionById(Integer.valueOf(968857));
CycNart complexNart = (CycNart) cycAssertion.getFormula().second();
System.out.println(complexNart.toString());
System.out.println(complexNart.cyclify());
*/
} catch (Exception e) {
failWithException(e);
}
System.out.println("*** testCycNart OK ***");
}
|
1ecf8b56-bbad-446f-80dc-7d3f88202c66
| 1
|
private boolean jj_2_35(int xla) {
jj_la = xla; jj_lastpos = jj_scanpos = token;
try { return !jj_3_35(); }
catch(LookaheadSuccess ls) { return true; }
finally { jj_save(34, xla); }
}
|
25064de7-3349-4f55-ad2f-104b666cd0cf
| 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 GridSquare)) {
return false;
}
GridSquare other = (GridSquare) object;
if ((this.gridRef == null && other.gridRef != null) || (this.gridRef != null && !this.gridRef.equals(other.gridRef))) {
return false;
}
return true;
}
|
30104425-a49b-4f9a-a5db-1ad27847d13f
| 6
|
public void paint(Graphics g){
this.setDoubleBuffered(true);
Insets in = getInsets();
g.translate(in.left, in.top);
int[][] gameboard = logic.getGameBoard();
int cols = gameboard.length;
int rows = gameboard[0].length;
//draw borders
for (int i = 0;i<cols;i++) {
g.drawImage(border_left, 0, 100+100*i, this);
g.drawImage(border_right, 100 + gameboard.length *100, 100+100*i, this);
g.drawImage(border_top, 100+100*i, 0, this);
g.drawImage(border_bottom, 100+100*i, 100+gameboard.length*100, this);
}
//draw board
for (int c = 0; c < cols; c++){
for (int r = 0; r < rows; r++){
int player = gameboard[c][r];
if ((c+r)%2==0) g.drawImage(backgroundW, 100+100*c, 100+100*r, this);
else g.drawImage(backgroundB, 100+100*c, 100+100*r, this);
if (player == 1) // red = computer
g.drawImage(queen, 100+100*c, 100+100*r, this);
if (player == -1)//invalid
g.drawImage(invalid, 100+100*c, 100+100*r, this);
g.drawImage(part, 100+100*c, 100+100*r, this);
}
}
//draw corners
g.drawImage(corner_left_top, 0, 0, this);
g.drawImage(corner_left_bottom, 0, 100+rows*100, this);
g.drawImage(corner_right_top, 100+100*cols, 0, this);
g.drawImage(corner_right_bottom, 100+100*cols, 100+rows*100, this);
}
|
7c7169e7-bb85-4c3a-bc6a-76ae188bacdb
| 8
|
public void onUpdate()
{
super.onUpdate();
if (this.field_35126_c > 0)
{
--this.field_35126_c;
}
this.prevPosX = this.posX;
this.prevPosY = this.posY;
this.prevPosZ = this.posZ;
this.motionY -= 0.029999999329447746D;
if (this.worldObj.getBlockMaterial(MathHelper.floor_double(this.posX), MathHelper.floor_double(this.posY), MathHelper.floor_double(this.posZ)) == Material.lava)
{
this.motionY = 0.20000000298023224D;
this.motionX = (double)((this.rand.nextFloat() - this.rand.nextFloat()) * 0.2F);
this.motionZ = (double)((this.rand.nextFloat() - this.rand.nextFloat()) * 0.2F);
this.worldObj.playSoundAtEntity(this, "random.fizz", 0.4F, 2.0F + this.rand.nextFloat() * 0.4F);
}
this.pushOutOfBlocks(this.posX, (this.boundingBox.minY + this.boundingBox.maxY) / 2.0D, this.posZ);
double var1 = 8.0D;
EntityPlayer var3 = this.worldObj.getClosestPlayerToEntity(this, var1);
if (var3 != null)
{
double var4 = (var3.posX - this.posX) / var1;
double var6 = (var3.posY + (double)var3.getEyeHeight() - this.posY) / var1;
double var8 = (var3.posZ - this.posZ) / var1;
double var10 = Math.sqrt(var4 * var4 + var6 * var6 + var8 * var8);
double var12 = 1.0D - var10;
if (var12 > 0.0D)
{
var12 *= var12;
this.motionX += var4 / var10 * var12 * 0.1D;
this.motionY += var6 / var10 * var12 * 0.1D;
this.motionZ += var8 / var10 * var12 * 0.1D;
}
}
this.moveEntity(this.motionX, this.motionY, this.motionZ);
float var14 = 0.98F;
if (this.onGround)
{
var14 = 0.58800006F;
int var5 = this.worldObj.getBlockId(MathHelper.floor_double(this.posX), MathHelper.floor_double(this.boundingBox.minY) - 1, MathHelper.floor_double(this.posZ));
if (var5 > 0)
{
var14 = Block.blocksList[var5].slipperiness * 0.98F;
}
}
this.motionX *= (double)var14;
this.motionY *= 0.9800000190734863D;
this.motionZ *= (double)var14;
if (this.onGround)
{
this.motionY *= -0.8999999761581421D;
}
++this.xpColor;
++this.xpOrbAge;
if (this.xpOrbAge >= 6000)
{
this.setDead();
}
}
|
0a0f07cf-5bd7-4566-a183-d5178118f5d3
| 4
|
synchronized public void updateLog() {
try {
PrintWriter writer = new PrintWriter("log.txt", "UTF-8");
writer.println("allocatedmemory: " + this.maxSize);
writer.println("usedmemory: " + this.currSize);
writer.println("lastchunk: " + this.nextAvailableFileNo);
for(BackupFile file : files) {
writer.println("file: " + Packet.bytesToHex(file.getFileID()) + " " + file.getFilename() + " " + file.getReplicationDegree() + " " + file.getNumChunks());
}
for(BackupChunk chunk : backedUpChunks) {
String chunkData = "chunk: " + Packet.bytesToHex(chunk.getFileID()) + " " + chunk.getFilename() + " " + chunk.getChunkNo() + " " + chunk.getWantedReplicationDegree() + " " + chunk.getRepDeg() + " " + chunk.getSize();
for(InetAddress addr : chunk.getStored()) {
chunkData += " " + addr.getHostAddress();
}
writer.println(chunkData);
}
writer.close();
}
catch (Exception e) {
e.printStackTrace();
}
}
|
a9552b96-6f91-4564-9635-bd4ba060c315
| 7
|
public static boolean incrementAuctionEndTime( int auctionID, int incrementAmount ) throws DatabaseException {
Connection conn = null;
ResultSet rs = null;
PreparedStatement ps = null;
int uid, bids;
String qUpdateAuctionTime = "UPDATE auctiontime SET endingTime = endingTime + ? WHERE auctionID = ?";
try {
conn = DBPool.getInstance().getConnection();
ps = conn.prepareStatement( qUpdateAuctionTime );
ps.setInt( 1, incrementAmount );
ps.setInt( 2, auctionID );
int rowCount = ps.executeUpdate();
return rowCount > 0;
}
catch ( SQLException e ) {
System.out.println( "bridge " + e.toString() + e.getStackTrace() );
throw new DatabaseException( e.toString() );
}
finally {
try { if (rs != null) rs.close(); } catch(Exception e) { }
try { if (ps != null) ps.close(); } catch(Exception e) { }
try { if (conn != null) conn.close(); } catch(Exception e) { }
}
}
|
22447fb2-6cd1-450d-9f3c-69388aa22f5b
| 1
|
@Override
public String toString() {
StringBuilder string = new StringBuilder();
for (String key : commands.keySet()) {
string.append(key);
string.append(", ");
}
string.delete(string.length() - 2, string.length());
return string.toString();
}
|
8c8fa4cc-662f-454a-b57e-8be68589426a
| 7
|
private void rescaleDiameters(double[] realDiameters, int iteration) {
if (iteration > 5) {
return;
} else if (iteration == 0) {
double averageDiameter = 0;
for (int j = 0; j < nCircles; j++)
averageDiameter += realDiameters[j];
averageDiameter /= nCircles;
for (int j = 0; j < nCircles; j++)
diameters[j] = averageDiameter;
} else if (iteration < 5) {
for (int j = 0; j < nCircles; j++)
diameters[j] = diameters[j] - (iteration / 5.0) * (diameters[j] - realDiameters[j]);
} else {
for (int j = 0; j < nCircles; j++)
diameters[j] = realDiameters[j];
}
}
|
a06d7eb9-c951-49a5-80d2-afb3f721c2e8
| 6
|
final void method3049(ByteBuffer class348_sub49, int i, int i_0_) {
if (i_0_ != 31015)
anInt9470 = -15;
int i_1_ = i;
while_213_:
do {
do {
if (i_1_ != 0) {
if (i_1_ != 1) {
if (i_1_ == 2)
break;
break while_213_;
}
} else {
anInt9474 = class348_sub49.getShort();
break while_213_;
}
anInt9470 = class348_sub49.getShort();
break while_213_;
} while (false);
((Class348_Sub40) this).aBoolean7045
= class348_sub49.getUByte() == 1;
} while (false);
anInt9472++;
}
|
eccb5ca2-fa6d-4c8c-bb65-70e3a6918e7f
| 9
|
public void paint(Graphics g) {
int xh, yh, xm, ym, xs, ys, s = 0, m = 10, h = 10, xcenter, ycenter;
String today;
currentDate = new Date();
SimpleDateFormat formatter = new SimpleDateFormat("s",Locale.getDefault());
try {
s = Integer.parseInt(formatter.format(currentDate));
} catch (NumberFormatException n) {
s = 0;
}
formatter.applyPattern("m");
try {
m = Integer.parseInt(formatter.format(currentDate));
} catch (NumberFormatException n) {
m = 10;
}
formatter.applyPattern("h");
try {
h = Integer.parseInt(formatter.format(currentDate));
} catch (NumberFormatException n) {
h = 10;
}
formatter.applyPattern("EEE MMM dd HH:mm:ss yyyy");
today = formatter.format(currentDate);
xcenter=80;
ycenter=55;
// a= s* pi/2 - pi/2 (to switch 0,0 from 3:00 to 12:00)
// x = r(cos a) + xcenter, y = r(sin a) + ycenter
xs = (int)(Math.cos(s * 3.14f/30 - 3.14f/2) * 45 + xcenter);
ys = (int)(Math.sin(s * 3.14f/30 - 3.14f/2) * 45 + ycenter);
xm = (int)(Math.cos(m * 3.14f/30 - 3.14f/2) * 40 + xcenter);
ym = (int)(Math.sin(m * 3.14f/30 - 3.14f/2) * 40 + ycenter);
xh = (int)(Math.cos((h*30 + m/2) * 3.14f/180 - 3.14f/2) * 30 + xcenter);
yh = (int)(Math.sin((h*30 + m/2) * 3.14f/180 - 3.14f/2) * 30 + ycenter);
// Draw the circle and numbers
g.setFont(clockFaceFont);
g.setColor(handColor);
circle(xcenter,ycenter,50,g);
g.setColor(numberColor);
g.drawString("9",xcenter-45,ycenter+3);
g.drawString("3",xcenter+40,ycenter+3);
g.drawString("12",xcenter-5,ycenter-37);
g.drawString("6",xcenter-3,ycenter+45);
// Erase if necessary, and redraw
g.setColor(getBackground());
if (xs != lastxs || ys != lastys) {
g.drawLine(xcenter, ycenter, lastxs, lastys);
g.drawString(lastdate, 5, 125);
}
if (xm != lastxm || ym != lastym) {
g.drawLine(xcenter, ycenter-1, lastxm, lastym);
g.drawLine(xcenter-1, ycenter, lastxm, lastym); }
if (xh != lastxh || yh != lastyh) {
g.drawLine(xcenter, ycenter-1, lastxh, lastyh);
g.drawLine(xcenter-1, ycenter, lastxh, lastyh); }
g.setColor(numberColor);
g.drawString("", 5, 125);
g.drawString(today, 5, 125);
g.drawLine(xcenter, ycenter, xs, ys);
g.setColor(handColor);
g.drawLine(xcenter, ycenter-1, xm, ym);
g.drawLine(xcenter-1, ycenter, xm, ym);
g.drawLine(xcenter, ycenter-1, xh, yh);
g.drawLine(xcenter-1, ycenter, xh, yh);
lastxs=xs; lastys=ys;
lastxm=xm; lastym=ym;
lastxh=xh; lastyh=yh;
lastdate = today;
currentDate=null;
}
|
ec2e12e3-7be0-4e01-8b74-a99263ff265c
| 0
|
public List<AbstractResource> getResources() {
return this.resources;
}
|
6d582088-c9e4-4df7-a030-b316d1c67595
| 6
|
public void push(String stack, E element) {
synchronized(lock) {
if(STACK1.equals(stack)) {
array[tail1] = element;
tail1 += 3;
if(tail1 >= array.length) {
resize();
}
} else if (STACK2.equals(stack)) {
array[tail2] = element;
tail2 += 3;
if(tail2 >= array.length) {
resize();
}
} else if (STACK3.equals(stack)) {
array[tail3] = element;
tail3 += 3;
if(tail3 >= array.length) {
resize();
}
}
}
}
|
254cece0-b494-4cb6-919e-0326ed494141
| 6
|
public void readOpponentMoves(String[] moveInput) {
opponentMoves.clear();
for (int i = 1; i < moveInput.length; i++) {
try {
Move move;
if (moveInput[i + 1].equals("place_armies")) {
Region region = visibleMap.getRegion(Integer
.parseInt(moveInput[i + 2]));
String playerName = moveInput[i];
int armies = Integer.parseInt(moveInput[i + 3]);
move = new PlaceArmiesMove(playerName, region, armies);
i += 3;
} else if (moveInput[i + 1].equals("attack/transfer")) {
Region fromRegion = visibleMap.getRegion(Integer
.parseInt(moveInput[i + 2]));
if (fromRegion == null) // might happen if the region isn't
// visible
fromRegion = fullMap.getRegion(Integer
.parseInt(moveInput[i + 2]));
Region toRegion = visibleMap.getRegion(Integer
.parseInt(moveInput[i + 3]));
if (toRegion == null) // might happen if the region isn't
// visible
toRegion = fullMap.getRegion(Integer
.parseInt(moveInput[i + 3]));
String playerName = moveInput[i];
int armies = Integer.parseInt(moveInput[i + 4]);
move = new AttackTransferMove(playerName, fromRegion,
toRegion, armies);
i += 4;
} else { // never happens
continue;
}
opponentMoves.add(move);
} catch (Exception e) {
System.err.println("Unable to parse Opponent moves "
+ e.getMessage());
}
}
}
|
5e94f802-4a01-40f0-a802-8276b824209f
| 2
|
private void updateInfo() {
StyledDocument doc = info.getStyledDocument();
try {
doc.remove(0, doc.getLength());
for (int i = 0; i < content.length; i++) {
doc.insertString(doc.getLength(), content[i] + newline, doc.getStyle(style[i]));
}
}
catch (BadLocationException ble) {
System.err.println("Couldn't insert text into text pane.");
}
}
|
8c484638-acdc-41b3-a9f2-f55872f2873f
| 0
|
public void setFunGrado(String funGrado) {
this.funGrado = funGrado;
}
|
c470f0c2-92ce-41b7-8d9b-d4887cae3671
| 2
|
public static int getIndexOfUser(User u, ArrayList<User> users) {
int counter = 0;
for(User e:users) {
if(e.getUsername().equalsIgnoreCase(u.getUsername())) {
return counter;
}
counter++;
}
return -1;
}
|
79db446d-25ca-46eb-b473-c5505777039a
| 3
|
@Test
public void testPlayerHandSize() {
// tests that all players have about the same number of cards
int handSize = game.getPlayers().get(0).getCards().size();
for (Player p : game.getPlayers()) {
int currentSize = p.getCards().size();
Assert.assertTrue((handSize-2) < currentSize || (handSize+2) > currentSize || handSize == currentSize);
}
}
|
6dc0ea27-d0c5-432b-954c-77292f631d96
| 8
|
public boolean isDataValid()
{
Boolean retval = hasValidData;
if(retval == null)
{
final int n = pointVector.size();
if((n < 2) || ((n < 3) && !isOpen()))
{
hasValidData = new Boolean(false);
return false;
}
for(int i = 0; i < size(); i++)
{
for(int j = i + 2; j < size(); j++)
{
if(i != ((j + 1) % pointVector.size()))
{
if(
do_segments_intersect(
getPoint(i)[0],
getPoint(i)[1],
getPoint(i + 1)[0],
getPoint(i + 1)[1],
getPoint(j),
getPoint(j + 1)))
{
hasValidData = new Boolean(false);
return false;
}
}
}
}
retval=hasValidData=new Boolean(true);
}
return retval.booleanValue();
}
|
7deff947-a45c-40b3-b000-e23600b7e0bd
| 5
|
private void doPop(MouseEvent e){
int tilex = game.player.getX();
int tiley = game.player.getY();
if(tilex < game.tilemap.width && tilex >= 0 && tiley < game.tilemap.height && tiley >= 0) {
if(game.tilemap.items[tiley][tilex] != null) {
ItemPopupMenu menu = new ItemPopupMenu(game, tilex, tiley);
menu.show(e.getComponent(), e.getX(), e.getY());
} else {
System.out.println("tile is null");
}
}
}
|
d345c8ed-4c9b-4205-8c9e-d66470b63137
| 8
|
private boolean r_postlude() {
int among_var;
int v_1;
// repeat, line 75
replab0: while(true)
{
v_1 = cursor;
lab1: do {
// (, line 75
// [, line 77
bra = cursor;
// substring, line 77
among_var = find_among(a_1, 3);
if (among_var == 0)
{
break lab1;
}
// ], line 77
ket = cursor;
switch(among_var) {
case 0:
break lab1;
case 1:
// (, line 78
// <-, line 78
slice_from("y");
break;
case 2:
// (, line 79
// <-, line 79
slice_from("i");
break;
case 3:
// (, line 80
// next, line 80
if (cursor >= limit)
{
break lab1;
}
cursor++;
break;
}
continue replab0;
} while (false);
cursor = v_1;
break replab0;
}
return true;
}
|
819e3a08-8626-4b16-bd77-47f9e007f3ae
| 8
|
private void insertNode(Color color, Node root) {
int red = color.getRed();
int green = color.getGreen();
int blue = color.getBlue();
root.setReferences(root.getReferences() + 1);
String binary11 = Integer.toBinaryString(red);
String binary12 = Integer.toBinaryString(green);
String binary13 = Integer.toBinaryString(blue);
if (binary11.length() < 8) {
for (int i = binary11.length(); i < 8; i++) {
binary11 = "0" + binary11;
}
}
if (binary12.length() < 8) {
for (int i = binary12.length(); i < 8; i++) {
binary12 = "0" + binary12;
}
}
if (binary13.length() < 8) {
for (int i = binary13.length(); i < 8; i++) {
binary13 = "0" + binary13;
}
}
Node node = root;
for (int i = 0; i < 8; i++) {
String indexString = "" + (binary11.charAt(i) + "" + binary12.charAt(i) + "" + binary13.charAt(i));
int index = Integer.parseInt(indexString, 2);
if (node.getNode(index) == null) {
count++;
node.setNode(index, new Node());
node.getNode(index).setCount(count);
}
node.getNode(index).setFather(node);
node = node.getNode(index);
node.setReferences(node.getReferences() + 1);
}
node.setRed(node.getRed() + red);
node.setGreen(node.getGreen() + green);
node.setBlue(node.getBlue() + blue);
}
|
37064617-102c-4419-b4ca-73703a9a4b81
| 8
|
public void onMessage(String channel, String sender, String login, String hostname, String message) {
String msg = message.toLowerCase();
String[] msgSplit = msg.split(" ");
for (int i = 0; i < msgSplit.length; i++) {
String urlTitle = "";
if (isYoutube(msgSplit[i])) {
/*try {
urlTitle = "Youtube";//getYoutubeInfo(msgSplit[i]);
sendMessage(channel, sender + "'s YouTube URL: " + urlTitle);
break;
} catch (Exception ex1) {
ex1.printStackTrace();
}*/
break;
} else if (isUrl(msgSplit[i])) {
try {
urlTitle = getWebpageTitle(msgSplit[i]);
sendMessage(channel, sender + "'s URL: " + urlTitle);
break;
} catch (Exception ex1) {
ex1.printStackTrace();
}
}
}
if (!sender.equalsIgnoreCase(getNick())) {
sql.checkNote(channel, sender);
}
if (msgSplit[0].startsWith(Config.getCommandPrefix())) {
String commandName = msgSplit[0].replace(Config.getCommandPrefix(), "");
for (MasterCommand command : commands) {
if (commandName.equalsIgnoreCase(command.getCommandName())) {
Log.consoleLog("Command", sender + " issued command: " + message);
command.exec(channel, sender, commandName, msgSplit, login, hostname, message);
}
}
return;
}
Log.consoleLog("Message", "<" + channel + "> " + sender + ": " + message);
}
|
9d13d9ba-3613-425d-8099-3552a0947118
| 6
|
@Override
public boolean execute(CommandSender sender, String identifier,
String[] args) {
String playerName = args[0];
String titleId = args[1];
if (sender instanceof Player) {
try {
if (!DBManager.idExist(titleId)) {
sender.sendMessage("No titles exist with this id.");
return false;
}
if (!DBManager.hasTitle(playerName, titleId)) {
sender.sendMessage("Player does not have this title.");
return false;
}
if (DBManager.getTitleFromId(titleId) == null) {
sender.sendMessage("This title does not exist.");
return false;
}
if (DBManager.getTitleFromId(titleId) != null) {
DBManager.revokeTitle(playerName, titleId);
sender.sendMessage(FontFormat.translateString("Player "
+ playerName + " has lost the title: "
+ DBManager.getTitleFromId(titleId) + "&r."));
return true;
} else {
sender.sendMessage("There was an error granting a player a title");
}
} catch (Exception ex) {
plugin.getLogger().log(Level.SEVERE,
"Error executing Title Grant command.", ex);
return false;
}
return false;
}
sender.sendMessage("Only players can use this command");
return false;
}
|
02d60486-1481-4df7-b33f-9aca5d6c1f1d
| 4
|
public void fletchingComplex(int screen) {
if (screen == 1) {
clearMenu();
menuLine("1", "Bronze arrow", 882, 0);
menuLine("5", "Ogre arrow", 2866, 1);
menuLine("7", "Bronze 'brutal' arrow", 4773, 2);
menuLine("15", "Iron arrow", 884, 3);
menuLine("18", "Iron 'brutal' arrow", 4778, 4);
menuLine("30", "Steel arrow", 886, 5);
menuLine("33", "Steel 'brutal' arrow", 4783, 6);
menuLine("38", "Black 'brutal' arrow", 4788, 7);
menuLine("45", "Mithril arrow", 888, 8);
menuLine("49", "Mithril 'brutal' arrow", 4793, 9);
menuLine("60", "Adamant arrow", 890, 10);
menuLine("62", "Adamant 'brutal' arrow", 4798, 11);
menuLine("75", "Rune arrow", 892, 12);
menuLine("77", "Rune 'brutal' arrow", 4803, 13);
optionTab("Fletching", "Arrows", "Arrows", "Bows", "Darts",
"Milestones", "", "", "", "", "", "", "", "", "");
}
else if (screen == 2) {
clearMenu();
menuLine("5", "Shortbow", 841, 0);
menuLine("10", "Longbow", 839, 1);
menuLine("20", "Oak Shortbow", 843, 2);
menuLine("25", "Oak Longbow", 845, 3);
menuLine("30", "Ogre Composite Bow(After Zogre Flesh Eaters)",
4827, 4);
menuLine("35", "Willow Shortbow", 849, 5);
menuLine("40", "Willow Longbow", 847, 6);
menuLine("50", "Maple Shortbow", 853, 7);
menuLine("55", "Maple Longbow", 851, 8);
menuLine("65", "Yew Shortbow", 857, 9);
menuLine("70", "Yew Longbow", 855, 10);
menuLine("80", "Magic Shortbow", 861, 11);
menuLine("85", "Magic Longbow", 859, 12);
optionTab("Fletching", "Bows", "Arrows", "Bows", "Darts",
"Milestones", "", "", "", "", "", "", "", "", "");
}
else if (screen == 3) {
clearMenu();
menuLine("1", "Bronze Dart", 806, 0);
menuLine("22", "Iron Dart", 807, 1);
menuLine("37", "Steel Dart", 808, 2);
menuLine("52", "Mithril Dart", 809, 3);
menuLine("67", "Adamant Dart", 810, 4);
menuLine("81", "Rune Dart", 811, 5);
optionTab("Fletching", "Darts", "Arrows", "Bows", "Darts",
"Milestones", "", "", "", "", "", "", "", "", "");
}
else if (screen == 4) {
clearMenu();
menuLine("99", "Skill Mastery", c.getItems().skillcapes[c.playerFletching][0], 0);
optionTab("Fletching", "Milestones", "Arrows", "Bows", "Darts",
"Milestones", "", "", "", "", "", "", "", "", "");
}
}
|
844368f2-93bf-4c4e-be3b-f70bb8db59a1
| 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 CompanyPerson)) {
return false;
}
CompanyPerson other = (CompanyPerson) object;
if ((this.companyPersonPK == null && other.companyPersonPK != null) || (this.companyPersonPK != null && !this.companyPersonPK.equals(other.companyPersonPK))) {
return false;
}
return true;
}
|
fedb78cd-25ed-4f8d-afce-56fda7bf2fab
| 0
|
public void setEventBus( EventBus eventBus )
{
this.eventBus = eventBus;
}
|
089bbb8a-af7b-4e63-80f8-7dd9af55d354
| 4
|
public static void setMediaPath(String directory)
{
// check if the directory exists
File file = new File(directory);
if (!file.exists())
{
System.out.println("Sorry but " + directory +
" doesn't exist, try a different directory.");
FileChooser.pickMediaPath();
}
else {
/* check if there is an application properties object
* and if not create one
*/
if (appProperties == null)
appProperties = new Properties();
// set the media directory property
appProperties.put(MEDIA_DIRECTORY,directory);
// write out the application properties to a file
try {
// get the URL for where we loaded this class
Class<?> currClass = Class.forName("FileChooser");
URL classURL = currClass.getResource("FileChooser.class");
URL fileURL = new URL(classURL,PROPERTY_FILE_NAME);
String path = fileURL.getPath();
path = path.replace("%20"," ");
FileOutputStream out =
new FileOutputStream(path);
appProperties.store(out,
"Properties for the Simple Picture class");
out.close();
System.out.println("The media directory is now " +
directory);
} catch (Exception ex) {
System.out.println("Couldn't save media path to a file");
}
}
}
|
cc57bf89-e151-4741-8855-ab2400ebf523
| 8
|
void pushDuskObject(DuskObject objIn)
{
synchronized(objEntities)
{
if (objIn.intLocX < 0 || objIn.intLocY < 0 || objIn.intLocX >= MapColumns || objIn.intLocY >= MapRows)
{
return;
}
DuskObject objStore;
objStore = objEntities[objIn.intLocX][objIn.intLocY];
if (objIn == objStore) // needed to add this check
{ // as the invis condition
return; // adds the mob to update the
} // the flags
if (objStore == null)
{
objEntities[objIn.intLocX][objIn.intLocY] = objIn;
}else
{
while (objStore.objNext != null)
{
if (objIn == objStore) // needed to add this check
{ // as the invis condition
return; // adds the mob to update the
} // the flags
objStore = objStore.objNext;
}
objStore.objNext = objIn;
}
}
}
|
a45ceeda-1887-4eb6-a79d-0f86d2e3f9f3
| 7
|
public void update(float time)
{
HandleBlockSpawn(time);
for(int i = 0; i < ActiveBlock.size(); i++)
{
PuzzleBlock b = ActiveBlock.get(i);
b.update(time);
}
for(int i = 0; i < BlockMap.size(); i++)
{
for(int j = 0; j < BlockMap.get(i).size(); j++)
{
PuzzleBlock block = BlockMap.get(i).get(j);
block.update(time);
if(BlockMap.get(i).get(j).StateChanged() == true)
{
System.out.print(" state Changed ");
HandleBlockClustering(block);
block.StateIsChanged(false);
}
}
}
for(int i = 0; i < BlockMap.size(); i++)
{
for(int j = 0; j < BlockMap.get(i).size(); j++)
{
PuzzleBlock block = BlockMap.get(i).get(j);
if(!block.Alive)
{
//if(!block.Alive)
{
UpdateCollumn(i, time);
}
BlockMap.get(i).remove(j);
}
}
}
}
|
f10644bf-868d-4743-9fb8-0ce12af22bea
| 5
|
public boolean comparePuzzle(Puzzle p1)
{
boolean answer = true;
Puzzle solution = new Puzzle();
char s = p1.getID().charAt(0);
int x = s - 'A' + 1;
solution.loadPuzzle("solution" + x);
int row = 0;
int column = 0;
while (column != 9 && answer == true)
{
while (row != 9 && answer == true)
{
if (solution.getValueAtPosition(row, column) != p1.getValueAtPosition(row, column))
{
answer = false;
}
row++;
}
row = 0;
column++;
}
return answer;
}
|
2288e9c3-7d62-42e1-898e-b7e2cc2f6a61
| 1
|
public CtField getField(String name) throws NotFoundException {
CtField f = getField2(name);
if (f == null)
throw new NotFoundException("field: " + name + " in " + getName());
else
return f;
}
|
4a0d81c7-46eb-41d4-9ce1-40912570b31a
| 7
|
public boolean execute() {
Log.i(" ");
Log.i("Executing: " + Utils.cmdToString(cmd));
boolean success = false;
long startTime = System.currentTimeMillis();
try {
Runtime rt = Runtime.getRuntime();
Process p;
if (folder == null)
p = rt.exec(cmd);
else
p = rt.exec(cmd, null, folder);
StreamGobbler input = new StreamGobbler("input", p.getInputStream(), inputGobbler);
StreamGobbler error = new StreamGobbler("error", p.getErrorStream(), errorGobbler);
input.start();
error.start();
try {
int val = p.waitFor();
success = (val == 0);
input.join();
error.join();
p.destroy();
if (logType == FFMPEG) {
System.out.print("\n");
}
} catch (InterruptedException e) {
Log.d("InterruptedException. " + e.getMessage());
}
} catch (IOException e) {
Log.d("IOException. " + e.getMessage());
}
long elapsedTime = System.currentTimeMillis() - startTime;
if (elapsedTime > 3000) {
Log.i(String.format("Execution finished with %s in %s seconds", (success ? "success" : "fail"), Long.toString(elapsedTime / 1000)));
} else {
Log.i(String.format("Execution finished with %s in %s ms", (success ? "success" : "fail"), Long.toString(elapsedTime)));
}
return success;
}
|
43d2a48b-a012-4b7a-8473-1d75789bd380
| 4
|
public LogDialog(final Panel panel) {
setTitle("Log filter");
setBounds(1, 1, 250, 250);
Dimension size = getToolkit().getScreenSize();
setLocation(size.width / 3 - getWidth() / 3, size.height / 3
- getHeight() / 3);
this.setResizable(false);
setLayout(null);
JPanel pan1 = new JPanel();
pan1.setBorder(BorderFactory.createTitledBorder("Mask size"));
pan1.setBounds(0, 0, 250, 60);
JPanel pan2 = new JPanel();
pan2.setBorder(BorderFactory.createTitledBorder("Parameters"));
pan2.setBounds(0, 70, 250, 110);
JLabel coordLabel1 = new JLabel("Size ");
final JTextField coordX = new JTextField("7");
coordX.setColumns(3);
JLabel sigmaPanel = new JLabel("Sigma ");
final JTextField sigmaField = new JTextField("1");
sigmaField.setColumns(3);
JLabel thresholdPanel = new JLabel("Threshold ");
final JTextField thresholdField = new JTextField("50");
thresholdField.setColumns(3);
final JCheckBox zeroCrossCheckBox = new JCheckBox("Zero cross", true);
zeroCrossCheckBox.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent arg0) {
zeroCross = zeroCrossCheckBox.isSelected();
thresholdField.setEnabled(zeroCross);
}
});
JButton okButton = new JButton("OK");
okButton.setSize(250, 40);
okButton.setBounds(0, 180, 250, 40);
okButton.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
int size;
double sigma;
int threshold;
try {
size = Integer.valueOf(coordX.getText());
sigma = Double.valueOf(sigmaField.getText());
threshold = Integer.valueOf(thresholdField.getText());
} catch (NumberFormatException ex) {
new MessageFrame("Invalid values");
return;
}
if (size % 2 == 0) {
new MessageFrame("Invalid values");
return;
}
if (size < 2 * sigma) {
new MessageFrame("Mask size too small");
return;
}
if (zeroCross){
panel.setImage(MaskUtils.applyMaskAndZeroCross(
panel.getImage(), MaskFactory.buildLogMask(size, sigma), threshold));
} else {
panel.setImage(MaskUtils.applyMask(
panel.getImage(), MaskFactory.buildLogMask(size, sigma)));
}
panel.repaint();
dispose();
}
});
pan1.add(coordLabel1);
pan1.add(coordX);
pan2.add(sigmaPanel);
pan2.add(sigmaField);
pan2.add(thresholdPanel);
pan2.add(thresholdField);
pan2.add(zeroCrossCheckBox);
add(pan1);
add(pan2);
add(okButton);
}
|
3fbe2dfa-b3d3-426c-a820-8c7b7a0722db
| 2
|
public void init()
{
this.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
this.setLayout(new FlowLayout());
this.setResizable(false);
this.setLocationRelativeTo(null);
// Initialize labels.
startLevelLabel = new JLabel("Resolution Start Level: ");
stopLevelLabel = new JLabel("Resolution Stop Level: ");
agingFlagLabel = new JLabel("Aging Flag: ");
discretizationLabel = new JLabel("Discretization: ");
windowSizeLabel = new JLabel("Window Size: ");
agingThetaLabel = new JLabel("Aging Theta: ");
waveletFlagLabel = new JLabel("Wavelet Flag: ");
updateFrequencyLabel = new JLabel("Plot Update Frequency: ");
fileNameLabel = new JLabel("Sample Data File: ");
densityFrom = new JLabel("From: ");
densityTo = new JLabel("To: ");
waveletTypeLabel = new JLabel("Wavelet Type: ");
// Initialize textFields.
startLevel = new JTextField(Settings.startLevel + "" , 3);
stopLevel = new JTextField(Settings.stopLevel + "" , 3);
discretization = new JTextField(Settings.discretization + "" , 5);
windowSize = new JTextField(Settings.windowSize + "" , 10);
agingTheta = new JTextField(Settings.agingTheta + "", 5);
updateFrequency = new JTextField(Settings.updateFrequency + "", 10);
densityRangeFrom = new JTextField(Settings.densityRange[0] + "", 5);
densityRangeTo = new JTextField(Settings.densityRange[1] + "", 5);
// Initialize combo boxes.
String[] agingFlags = {"No Aging", "Caudle", "Window"};
agingFlag = new JComboBox<String>( agingFlags );
agingFlag.setSelectedIndex(Settings.windowAge); // sets the default to window aging. windowAging is constant 2 in Settings class.
waveletType = new JComboBox<String>( Settings.waveletTypes );
waveletType.setSelectedIndex(9);
// Initialize check Boxes.
waveletFlag = new JCheckBox("Enable wavelet.");
// Initialize buttons.
btnOpenFile = new JButton("Browse...");
btnSaveSettings = new JButton("Save settings");
btnSaveSettings.addActionListener(new ActionListener(){
public void actionPerformed(ActionEvent e){
saveSettings();
}
});
btnOpenFile.addActionListener(new ActionListener(){
public void actionPerformed(ActionEvent e){
fileChooser = new JFileChooser();
fileChooser.setCurrentDirectory( new java.io.File(".") );
fileChooser.setDialogTitle("Estimator Sample Data File");
fileChooser.setFileSelectionMode(JFileChooser.FILES_ONLY);
fileChooser.setAcceptAllFileFilterUsed(false);
if(fileChooser.showOpenDialog(null) == JFileChooser.APPROVE_OPTION)
{
java.io.File file = fileChooser.getSelectedFile();
try {
Settings.dataFile = file.getCanonicalPath();
} catch (IOException e1) {}
}
}
});
// Initialize panels.
waveletPanel = new JPanel( new FlowLayout() );
plotPanel = new JPanel( new FlowLayout() );
dataPanel = new JPanel( new FlowLayout() );
densityRangePanel = new JPanel( new FlowLayout() );
Border panelBorder = BorderFactory.createLineBorder(Color.BLACK, 2);
waveletPanel.setBorder( BorderFactory.createTitledBorder(panelBorder, "Wavelet Settings" ));
plotPanel.setBorder(BorderFactory.createTitledBorder(panelBorder, "Plot Settings" ));
dataPanel.setBorder(BorderFactory.createTitledBorder(panelBorder, "Data Settings" ));
densityRangePanel.setBorder(BorderFactory.createTitledBorder(panelBorder, "Density Range" ));
// Add waveletPanel components.
GridLayout wavPanelLayout = new GridLayout(0, 2);
waveletPanel.setLayout(wavPanelLayout);
waveletPanel.add(startLevelLabel); waveletPanel.add(startLevel);
waveletPanel.add(stopLevelLabel); waveletPanel.add(stopLevel);
waveletPanel.add(agingFlagLabel); waveletPanel.add(agingFlag);
waveletPanel.add(discretizationLabel); waveletPanel.add(discretization);
waveletPanel.add(windowSizeLabel); waveletPanel.add(windowSize);
waveletPanel.add(agingThetaLabel); waveletPanel.add(agingTheta);
waveletPanel.add(waveletTypeLabel); waveletPanel.add(waveletType);
waveletPanel.add(waveletFlagLabel); waveletPanel.add(waveletFlag);
// Add plotPanel components.
plotPanel.setPreferredSize( new Dimension(270, 55) );
plotPanel.add(updateFrequencyLabel); plotPanel.add(updateFrequency);
// Add dataPanel components.
dataPanel.setPreferredSize( new Dimension(270, 60) );
dataPanel.add(fileNameLabel);
dataPanel.add(btnOpenFile);
// Add densityRangePanel components.
densityRangePanel.setPreferredSize( new Dimension(270, 55) );
densityRangePanel.add(densityFrom);
densityRangePanel.add(densityRangeFrom);
densityRangePanel.add(densityTo);
densityRangePanel.add(densityRangeTo);
// Add the Panels to the frame.
content.add(waveletPanel, BorderLayout.LINE_START);
content.add(plotPanel, BorderLayout.LINE_START);
content.add(dataPanel, BorderLayout.LINE_START);
content.add(densityRangePanel, BorderLayout.LINE_START);
content.add(new JSeparator(JSeparator.HORIZONTAL));
content.add(btnSaveSettings);
}
|
88aac41a-a0f5-42fe-8bba-d505aa996786
| 0
|
public void save() throws SQLException {
Map<String, String> values = new HashMap<String, String>();
values.put("reminderAhead", String.valueOf(this.reminderAhead));
super.save(values);
}
|
71986bff-6608-4e9d-8695-27f5771117fa
| 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 Salarie)) {
return false;
}
Salarie other = (Salarie) object;
if ((this.num == null && other.num != null) || (this.num != null && !this.num.equals(other.num))) {
return false;
}
return true;
}
|
1c009def-915d-4ccb-b4ea-9433492ad8f9
| 5
|
private Color selectColourForButton(Keyboard keyboard, char key) {
int[] RGB = new int[3];
int all = keyboard.getAmountOfAllKeys();
int keyAmount = keyboard.getAmount(key);
double percentageOfKeyInFile = 100 * (double) keyAmount / all;
if (keyAmount == 0) {
return new Color(255, 255, 255);
}
if (percentageOfKeyInFile <= 5.0) {
RGB[0] = (int) Math.floor(percentageOfKeyInFile / 0.02);
RGB[1] = 255;
RGB[2] = 0;
} else if (percentageOfKeyInFile <= 10.0) {
RGB[0] = 255;
RGB[1] = 255 - (int) Math.floor((percentageOfKeyInFile - 5) / 0.02);
RGB[2] = 0;
} else if (percentageOfKeyInFile <= 30.0) {
RGB[0] = 255;
RGB[1] = 0;
RGB[2] = (int) Math.floor((percentageOfKeyInFile - 10) / 0.08);
} else if (percentageOfKeyInFile <= 50.0) {
RGB[0] = 255 - (int) Math.floor((percentageOfKeyInFile - 30) / 0.08);
RGB[1] = 1;
RGB[2] = 255;
} else {
RGB[0] = 0;
RGB[1] = 1;
RGB[2] = 255 - (int) Math.floor((percentageOfKeyInFile - 50) / 0.2);
}
Color rgb = new Color(RGB[0], RGB[1], RGB[2]);
return rgb;
}
|
7fc2c08c-b66f-4e6a-806e-42bc927a0341
| 6
|
private boolean tryMove(Shape newPiece, int newX, int newY){
for (int i = 0; i < 4; ++i) {
int x = newX + newPiece.x(i);
int y = newY - newPiece.y(i);
if (x < 0 || x >= BoardWidth || y < 0 || y >= BoardHeight)
return false;
if (shapeAt(x, y) != Tetrominoes.NoShape)
return false;
}
curPiece = newPiece;
curX = newX;
curY = newY;
repaint();
return true;
}
|
dcfafb52-4a9f-4d9b-9e9c-cd4c94465a0a
| 2
|
private void multiplicar(int columna, int fila, int[] datos) {
int index = 0;
int total = 1;
for (int i = 0; i < fila; i++) {
tableHtml += "<tr>";
for (int j = 0; j < columna; j++) {
total *= getNumero(datos, index);
tableHtml += "<td>" + getNumero(datos, index) + "</td>";
index++;
}
tableHtml += "<td>" + total + "</td></tr>\n";
total = 1;
}
}
|
d603834a-d50a-4946-b97c-5ba720fbe260
| 5
|
@Override
public void removeState(String toRemoveID) throws UnresolvedReferenceException {
State toRemove = this.getState(toRemoveID);
//Make sure that toRemove is not referenced in another state's transition table
for (State toCheck : this.getStates()) {
if (!toCheck.equals(toRemove)) {
for (char symbol : this.getAlphabet()) {
if (isStateReferencedInTableEntry(toCheck, symbol, toRemove)) {
throw new UnresolvedReferenceException("State " + toRemove.getID() + " is still referenced in entry (" + toCheck.getID() + "," + symbol + ")");
}
}
if (isStateReferencedInTableEntry(toCheck, DEFAULT_TAPE_SYMBOL, toRemove)) {
throw new UnresolvedReferenceException("State " + toRemove.getID() + " is still referenced in entry (" + toCheck.getID() + "," + DEFAULT_TAPE_SYMBOL + ")");
}
}
}
super.removeState(toRemoveID);
}
|
967cdaf5-0a0d-467f-97b3-d697d8bca214
| 2
|
public String execute(String[] args){
int intPriority = Integer.parseInt(args[1]);
if(intPriority < 1 || intPriority > 9)
return "ERROR: Priority is only 1 - 9!";
runList.setPriority(Long.parseLong(args[0]), intPriority);
return process.toString();
}
|
5550ed08-7158-446e-a63d-52bd4b8c525a
| 6
|
public boolean loadDataFiles(String filePath, String dataType) {
File folder = new File(filePath);
LoadDataWithJDBC obj2 = new LoadDataWithJDBC();
String filename = "";
File[] listOfFiles = folder.listFiles();
int count = 0;
try {
for (int i = 0; i < listOfFiles.length; i++) {
if (listOfFiles[i].isFile() && listOfFiles[i].getName().toString() != ".DS_Store") {
filename = listOfFiles[i].getName();
Date date = new Date();
count++;
//Start Time
WriteToFile.appendToFileMethod(count+" :: "+ new Timestamp(System.currentTimeMillis())+ " :: "+filename+ " \n", "/home/krish/Documents/CMPE226/Project1/logLoadTime.txt");
if(dataType.equals("weatherData"))
obj2.readAndLoadWeatherDataFromFileMethod(filePath+filename);
else
obj2.readAndLoadMetaFromFileMethod(filePath+filename);
//End Time
WriteToFile.appendToFileMethod(count+" :: "+ new Timestamp(System.currentTimeMillis())+ " :: "+filename+ " \n", "/home/krish/Documents/CMPE226/Project1/logLoadTime.txt");
File movefile = new File(filePath+filename);
if (movefile.renameTo(new File(filePath + "archive/"
+ movefile.getName()))) {
System.out.println("File is moved successful!");
} else {
System.out.println("File is failed to move!");
}
}
}
} catch (Exception e) {
System.out.println("File was not processed" + filename);
e.printStackTrace();
}
return true;
}
|
add05b35-0c22-4944-9895-385fa2671b5e
| 9
|
public static void main(String[] args) throws InterruptedException {
if (args.length == 0) {
System.err.println("usage: [-threads value] <files...>");
System.exit(1);
}
int numberOfThreads = 2;
int startIdx = 0;
if (args[0].equals("-threads")) {
startIdx = 2;
try {
numberOfThreads = Integer.parseInt(args[1]);
} catch (Exception e) {
System.err.println("Error parsing number of threads: " + e.getLocalizedMessage());
numberOfThreads = 2;
} finally {
if (numberOfThreads < 1) {
numberOfThreads = 2;
}
}
}
System.out.println("--------------------------------------------------------------------");
System.out.println("----------------------- CHECK TOA ORDER ----------------------------");
System.out.println("--------------------------------------------------------------------");
System.out.println("analyze " + printArgs(args) + " using " + numberOfThreads + " threads");
ComparingFiles[] threads = new ComparingFiles[numberOfThreads];
List<Pair> allCombinations = new LinkedList<>();
for (int x = startIdx; x < args.length; ++x) {
for (int y = x + 1; y < args.length; ++y) {
if (x == y) {
continue;
}
allCombinations.add(new Pair(x, y));
}
}
System.out.println("Collection for the threads is " + allCombinations);
final Iterator<Pair> iterator = allCombinations.iterator();
for (int i = 0; i < threads.length; ++i) {
threads[i] = new ComparingFiles(iterator,args,"Comparator-" + i);
threads[i].start();
}
for (ComparingFiles comparingFiles : threads) {
comparingFiles.join();
}
System.out.println("=========== FINISHED! ==============");
}
|
9a092edf-aaf6-4662-9828-c8463ca9de64
| 8
|
public static Module load_mod( byte[] header_1084_bytes, DataInput data_input ) throws IOException {
int num_channels, channel_idx, panning;
int sequence_length, restart_idx, sequence_idx;
int num_patterns, pattern_idx, instrument_idx;
Module module;
num_channels = calculate_num_channels( header_1084_bytes );
if( num_channels < 1 ) {
throw new IllegalArgumentException( "ProTracker: Unrecognised module format!" );
}
module = new Module();
module.song_title = ascii_text( header_1084_bytes, 0, 20 );
module.pal = ( num_channels == 4 );
module.global_volume = 64;
module.channel_gain = IBXM.FP_ONE * 3 / 8;
module.default_speed = 6;
module.default_tempo = 125;
module.set_num_channels( num_channels );
for( channel_idx = 0; channel_idx < num_channels; channel_idx++ ) {
panning = 64;
if( ( channel_idx & 0x03 ) == 0x01 || ( channel_idx & 0x03 ) == 0x02 ) {
panning = 192;
}
module.set_initial_panning( channel_idx, panning );
}
sequence_length = header_1084_bytes[ 950 ] & 0x7F;
restart_idx = header_1084_bytes[ 951 ] & 0x7F;
if( restart_idx >= sequence_length ) {
restart_idx = 0;
}
module.restart_sequence_index = restart_idx;
module.set_sequence_length( sequence_length );
for( sequence_idx = 0; sequence_idx < sequence_length; sequence_idx++ ) {
module.set_sequence( sequence_idx, header_1084_bytes[ 952 + sequence_idx ] & 0x7F );
}
num_patterns = calculate_num_patterns( header_1084_bytes );
module.set_num_patterns( num_patterns );
for( pattern_idx = 0; pattern_idx < num_patterns; pattern_idx++ ) {
module.set_pattern( pattern_idx, read_mod_pattern( data_input, num_channels ) );
}
module.set_num_instruments( 31 );
for( instrument_idx = 1; instrument_idx <= 31; instrument_idx++ ) {
module.set_instrument( instrument_idx, read_mod_instrument( header_1084_bytes, instrument_idx, data_input ) );
}
return module;
}
|
6438a379-075a-4527-8fa0-7ddc13159b99
| 0
|
public WaitForGameThread(PongWindow window) {
super("WaitForGameThread");
this.window = window;
}
|
15382203-53da-4195-bb3b-96720cc305ae
| 1
|
public static void main(String args[]) {
try {
int port =4321 ;
int poolSize =10;
//init forum sys
ForumSystem forumSystem = new ForumSystem();
User admin= forumSystem.startSystem("halevm@em.walla.com", "firstname", "admin", "1234");
//init reactor
Reactor reactor = startEchoServer(port, poolSize,forumSystem);
Thread thread = new Thread(reactor);
thread.start();
logger.info("Forum system is Ready to go on port " + reactor.getPort());
thread.join();
} catch (Exception e) {
e.printStackTrace();
}
}
|
ac5020dd-612e-4639-bd2a-ade4eb2c5d73
| 8
|
private void testSend(final TransactionResultData data) {
final Collection<InnerDataSubscription> allowed = _allowedDataIdentifications.get(data.getDataDescription());
final Collection<InnerDataSubscription> required = _requiredDataIdentifications.get(data.getDataDescription());
for(final TransactionDataset dataset : data.getData()) {
if(!allowed.contains(
new InnerDataSubscription(
dataset.getObject(), dataset.getDataDescription().getAttributeGroup(), dataset.getDataDescription().getAspect()
)
)) {
throw new IllegalArgumentException(
"Folgender Datensatz befindet sich nicht in der Liste der registrierten Anmeldungen: " + dataset
);
}
}
for(final InnerDataSubscription requiredSubscription : required) {
boolean found = false;
for(final TransactionDataset dataset : data.getData()) {
if(dataset.getObject().equals(requiredSubscription.getObject())
&& dataset.getDataDescription().getAttributeGroup().equals(requiredSubscription.getAttributeGroup())
&& dataset.getDataDescription().getAspect().equals(requiredSubscription.getAspect())) {
found = true;
break;
}
}
if(!found) {
throw new IllegalArgumentException(
"Folgende Datenidentifikation ist erforderlich für diese Transaktion, befindet sich aber nicht in den Daten: " + requiredSubscription
);
}
}
}
|
79a7c342-2b67-4e68-8684-c2622f0ea7b2
| 3
|
private void writeObject(ObjectOutputStream out) throws IOException {
out.writeUTF(getLevel().getName());
out.writeUTF(getLoggerName());
out.writeUTF(getMessage());
out.writeLong(getMillis());
out.writeInt(getParameters().length);
for (Object p : getParameters()) {
out.writeObject(p);
}
out.writeUTF(getResourceBundleName());
out.writeLong(getSequenceNumber());
out.writeUTF(getSourceClassName());
out.writeUTF(getSourceMethodName());
out.writeInt(getThreadID());
out.writeObject(getThrown());
out.writeInt(fields.size());
for (Entry<String, String> e : fields.entrySet()) {
out.writeUTF(e.getKey());
out.writeUTF((e.getValue() == null) ? CONST_NULL : e.getValue());
}
}
|
783029fd-dce8-4556-ab1e-5dea0d1b2ea7
| 4
|
public void keyReleased(KeyEvent e) {
int key = e.getKeyCode();
for (int i = 0; i < handler.objects.size(); i++) {
GameObject tempObject = handler.objects.get(i);
switch (tempObject.getID()) {
case Player:
switch (key) {
case KeyEvent.VK_D:
case KeyEvent.VK_A:
tempObject.setVelX(0);
break;
default:
break;
}
break;
default:
break;
}
}
}
|
64b8c71d-f8bc-4e6d-8238-e58d97bf86ba
| 0
|
public static void publishQueryEvent(TicketQueryArgs args) {
long sequence = _ringBuffer.next();
TicketQueryArgs event = _ringBuffer.get(sequence);
args.copyTo(event);
event.setSequence(sequence);
// 将消息放到车轮队列里,以便处理
_ringBuffer.publish(sequence);
}
|
e2b6ffbe-683e-4d2e-954d-b37160bed0a0
| 5
|
private boolean judgeRuleAuthorized(String deliQuery, ArrayList<String> paras, String localQuery) {
boolean authFlag = false;
if (localQuery.equalsIgnoreCase("null")) {
System.out.println("[checkQuery] null"); //
} else if (localQuery.equalsIgnoreCase("all")) {
System.out.println("[checkQuery] all"); //
authFlag = true;
} else {
String checkQuery = "( " + deliQuery + " ) except ( " + localQuery + " )";
System.out.println("[checkQuery] " + checkQuery); //
ListIterator<String> params = paras.listIterator();
DatabaseDao db = new DatabaseDaoImpl(domconfBundle);
ResultSet rs;
try {
rs = db.read(checkQuery, params);
if (!rs.next())
authFlag = true;
rs.close();
db.close();
} catch (ClassNotFoundException e) {
e.printStackTrace();
} catch (SQLException e) {
e.printStackTrace();
}
}
return authFlag;
}
|
1edbcb58-0ee7-41a3-b99e-c825d5ee0f50
| 1
|
public void deleteItem(Item item){
try{
session.beginTransaction();
session.delete(item);
session.getTransaction().commit();
}
catch(HibernateException e){
Main.getFrame().showError("A hozzáadás sikertelen volt: "+e.getMessage());
}
}
|
11a41f34-00f9-416f-b4d2-ff634997c277
| 2
|
@SuppressWarnings("empty-statement")
public boolean gagne(){
int i;
for(i=0; i < tabMarq.length && tabMarq[i] == 1; i++);
return (i >= tabMarq.length); // On à trouvé aucun false
}
|
31b4912c-93e8-4f90-bd9d-6bf94c2d9295
| 5
|
private int miehenAvecinPaikallaToistaSukupuolta(boolean mies) {
int pisteita = 0;
try {
if (paikka.getMiehenAvecinPaikka() != null) {
if (paikka.getMiehenAvecinPaikka().getSitsaaja().isMies()) {
if (mies == false) {
pisteita += 500;
}
} else {
if (mies == true) {
pisteita += 500;
}
}
}
} catch (UnsupportedOperationException e) {
}
return pisteita;
}
|
00b036b8-c8fc-46f5-8604-53445d58aad1
| 3
|
public void act(Matrix matrix, Player player) {
if (!isAlive) {
return;
}
LinkedList<Node> neighbours = matrix.allNeighbours(x, y);
if (neighbours.contains(matrix.getNode(player.getX(), player.getY()))) {
hit(player);
return;
}
ArrayList<Node> shortestRoute = matrix.shortestRoute(matrix.getNode(x, y), matrix.getNode(player.getX(), player.getY()), range, false);
if (shortestRoute == null) {
moveRandom(matrix);
return;
}
move(matrix, (Square)shortestRoute.get(1));
}
|
2f8d82c7-f36e-4781-b30e-0fcd99638285
| 8
|
public SummaryResult read(String filePath) {
BufferedReader in = null;
try {
in = new BufferedReader(new FileReader(filePath));
String s;
int line = 1;
FileSplitUtil util = new FileSplitUtil();
while ((s = in.readLine()) != null && !strategy.endReading()) {
}
int i = 0;
for (; (s = in.readLine()) != null && !strategy.endReading(); i++) {
// TODO read data from s;
strategy.preProcess(i, s);
}
return strategy.process();
} catch (FileNotFoundException e) {
log.warn("File: {} not found!", filePath);
} catch (IOException e) {
log.warn(e.getMessage(), e);
} finally {
if (in != null)
try {
in.close();
} catch (IOException e) {
in = null;
}
}
return SummaryResult.NoSummaryResult;
}
|
2fee17c0-40dd-4dee-b72e-80fb762f02d0
| 2
|
public static void scan(InputStream source, InputStream format) throws IOException{
Scanner scanner = new Scanner(source);
SimpleFormat sf = JAXB.unmarshal(format, SimpleFormat.class);
CSVParser parser = new CSVParser(sf);
Integer r = 0;
while (scanner.hasNext()) {
r++;
String line = scanner.nextLine();
System.out.println(parser.parse(line));
}
System.out.println("Max Date:" + parser.getMaxDate());
System.out.println("Min Date:" + parser.getMinDate());
for(Column c:sf.getColumns()){
System.out.println("Col[" + c.getNum() + "]:=[" + parser.getColumnMinDate(c.getNum()) + "," + parser.getColumnMaxDate(c.getNum()) + "]");
}
scanner.close();
}
|
4d2831cc-7a84-4396-b9c3-0e1663eab757
| 5
|
void testFormulaCalc( String fs, String sh )
{
WorkBookHandle book = new WorkBookHandle( fs );
sheetname = sh;
try
{
sht = book.getWorkSheet( sheetname );
}
catch( Exception e )
{
log.error( "TestFormulas failed.", e );
}
FormulaHandle f = null;
Double i = null;
/************************************
* Formula Parse test
**************************************/
if( sheetname.equalsIgnoreCase( "Sheet1" ) )
{
try
{
// one ref & ptgadd
sht.add( null, "A1" );
CellHandle c = sht.getCell( "A1" );
c.setFormula( "b1+5" );
f = c.getFormulaHandle();
i = (Double) f.calculate();
// two refs & ptgadd
sht.add( null, "A2" );
c = sht.getCell( "A2" );
c.setFormula( "B1+ A1" );
f = c.getFormulaHandle();
i = (Double) f.calculate();
// ptgsub
f.setFormula( "B1 - 5" );
i = (Double) f.calculate();
// ptgmul
f.setFormula( "D1 * F1" );
i = (Double) f.calculate();
// ptgdiv
f.setFormula( "E1 / F1" );
i = (Double) f.calculate();
// ptgpower
f.setFormula( "E1 ^ F1" );
i = (Double) f.calculate();
f.setFormula( "E1 > F1" );
Boolean b = (Boolean) f.calculate();
f.setFormula( "E1 >= F1" );
b = (Boolean) f.calculate();
f.setFormula( "E1 < F1" );
b = (Boolean) f.calculate();
f.setFormula( "E1 <= F1" );
b = (Boolean) f.calculate();
f.setFormula( "Pi()" );
i = (Double) f.calculate();
f.setFormula( "LOG(10,2)" );
i = (Double) f.calculate();
System.out.println( i.toString() );
f.setFormula( "ROUND(32.443,1)" );
i = (Double) f.calculate();
System.out.println( i.toString() );
f.setFormula( "MOD(45,6)" );
i = (Double) f.calculate();
System.out.println( i.toString() );
f.setFormula( "DATE(1998,2,4)" );
i = (Double) f.calculate();
System.out.println( i.toString() );
f.setFormula( "SUM(1998,2,4)" );
i = (Double) f.calculate();
System.out.println( i.toString() );
f.setFormula( "IF(TRUE,1,0)" );
i = (Double) f.calculate();
System.out.println( i.toString() );
f.setFormula( "ISERR(\"test\")" );
b = (Boolean) f.calculate();
System.out.println( b.toString() );
// many operand ptgfuncvar
f.setFormula( "SUM(12,3,2,4,5,1)" );
i = (Double) f.calculate();
System.out.println( i.toString() );
// test with a sub-calc
f.setFormula( "IF((1<2),1,0)" );
i = (Double) f.calculate();
System.out.println( i.toString() );
f.setFormula( "IF((1<2),MOD(45,6),1)" );
i = (Double) f.calculate();
System.out.println( i.toString() );
f.setFormula( "IF((1<2),if((true),8,1),1)" );
i = (Double) f.calculate();
System.out.println( i.toString() );
f.setFormula( "IF((SUM(23,2,3,4)<12),if((true),8,1),DATE(1998,2,4))" );
i = (Double) f.calculate();
System.out.println( i.toString() );
}
catch( CellNotFoundException e )
{
log.error( "TestFormulas failed.", e );
}
catch( FunctionNotSupportedException e )
{
log.error( "TestFormulas failed.", e );
}
catch( Exception e )
{
log.error( "TestFormulas failed.", e );
}
testWrite( "testCalcFormulas_out.xls" );
}
}
|
5bd0ac33-ba0a-4592-b4a4-46591a33d7d4
| 5
|
public static boolean viewPassengerByTrain(ObjectOutputStream toServer, ObjectInputStream fromServer, Scanner scanner) throws IOException, ClassNotFoundException {
log.debug("Start \"viewPassengerByTrain\" method");
System.out.println("Input train name");
String trainName = scanner.next().toLowerCase();
ViewPassengerByTrainRequestInfo request = new ViewPassengerByTrainRequestInfo(trainName);
log.debug("Send ViewPassengerByTrainRequestInfo to server");
toServer.writeObject(request);
Object o = fromServer.readObject();
if (o instanceof RespondInfo) {
if (((RespondInfo) o).getStatus() == RespondInfo.SERVER_ERROR_STATUS) {
System.out.println("Server error");
log.debug("Server error");
return false;
} else if (o instanceof ViewPassengerByTrainRespondInfo) {
ViewPassengerByTrainRespondInfo respond = (ViewPassengerByTrainRespondInfo) o;
log.debug("Received ViewPassengerByTrainRespondInfo from server");
if (respond.getStatus() == ViewPassengerByTrainRespondInfo.WRONG_TRAIN_NAME_STATUS) {
System.out.println("Wrong train name");
log.debug("Wrong train name");
return true;
}
List<Object[]> allPassenger = respond.getListAllPassengerByTrain();
System.out.println("Passenger:");
System.out.println("Firstname --- Lastname --- Birthday");
for (Object[] passenger : allPassenger) {
System.out.print(passenger[0] + " ");
System.out.print(passenger[1] + " ");
System.out.println(passenger[2]);
}
log.debug("Get all passenger");
return true;
}
}
log.error("Unknown object type");
return false;
}
|
9f1e9d6a-2ebe-47be-9537-55e0969f741e
| 7
|
public static void main(String[] args) throws Exception {
//input files
String pathNetinf = args[0];
String pathGroundTruth = args[1];
//nodes
HashSet<Integer> usedNodes = new HashSet<Integer>();
HashSet<String> predictedEdges = new HashSet<String>();
HashSet<String> trueEdges = new HashSet<String>();
//read netinf result
BufferedReader br = new BufferedReader(new FileReader(pathNetinf));
String line;
while ((line = br.readLine()) != null) {
String[] lineSplit = line.split("\\t+");
usedNodes.add(Integer.parseInt(lineSplit[0]));
usedNodes.add(Integer.parseInt(lineSplit[1]));
predictedEdges.add(line);
}
br.close();
//ground truth nodes
br = new BufferedReader(new FileReader(pathGroundTruth));
while ((line = br.readLine()) != null) {
String[] lineSplit = line.split("\\t+");
int A = Integer.parseInt(lineSplit[0]);
int B = Integer.parseInt(lineSplit[1]);
if(usedNodes.contains(A) && usedNodes.contains(B) && A!=B){
trueEdges.add(line);
//trueEdges.add(String.valueOf(B)+"\t"+String.valueOf(A));
}
}
br.close();
//stats
int totalTrue = trueEdges.size();
int totalPredicted = predictedEdges.size();
int totalRight = 0;
for( String p : predictedEdges){
if(trueEdges.contains(p)){
totalRight++;
}
}
//performance
double precision = (double)totalRight / (double)totalPredicted;
double recall = (double)totalRight / (double)totalTrue;
System.out.println("totalTrue: " + String.valueOf(totalTrue));
System.out.println("totalPredicted: " + String.valueOf(totalPredicted));
System.out.println("totalRight: " + String.valueOf(totalRight));
System.out.println("precision: " + String.valueOf(precision));
System.out.println("recall: " + String.valueOf(recall));
}
|
e70a6e44-fe2f-40cb-92b3-63cae15d1861
| 5
|
private Comparable[] mergeTwoArrays(Comparable[] a, Comparable[] b) {
Comparable[] merged = new Comparable[a.length + b.length];
int i = 0, j = 0, k = 0;
while (i < a.length && j < b.length) {
if (b[j].compareTo(a[i]) >= 1) {
merged[k++] = a[i++];
} else {
merged[k++] = b[j++];
}
}
while (i < a.length) {
merged[k++] = a[i++];
}
while (j < b.length) {
merged[k++] = b[j++];
}
return merged;
}
|
b7e4c62f-1798-4b41-95d2-26992ae77813
| 5
|
public static void main(String[] args) {
running = true;
// Preliminary stuff (config handler and packet manager setup)
System.out.println("Welcome to BBServer " + VERSION + ", the portal for Blazing Barrels multiplayer!");
File configFile = new File ("config.txt"); // File is within the jar for simplicity in testing
config = new Configuration(configFile);
config.loadValues();
pm = new PacketManager();
// Set up threads:
try {
sender = new SenderThread();
} catch (SocketException e) {
System.err.println("Failed to find an available port for packet transmission. Stopping the server...");
return;
} catch (SecurityException e) {
e.printStackTrace();
return;
}
try {
receiver = new ReceiverThread(config.getPort());
} catch (SocketException e) {
System.err.println("Failed to bind to port " + config.getPort() + " for packet receipt. Is it in use by " +
"another program?\nStopping the server...");
return;
} catch (SecurityException e) {
e.printStackTrace();
return;
}
input = new InputThread();
// Launch threads:
sender.start();
receiver.start();
input.start();
// Main loop
while(running) {
pm.runCycle();
}
// Cleanup:
System.out.println("Saving the server configuration...");
config.saveValues();
sender.terminate();
receiver.terminate();
System.out.println("\nServer closed.");
System.out.println(goodbyes[(int) (Math.random() * goodbyes.length)]);
}
|
62cf7b83-92b2-4f28-9966-4fa1146ad469
| 6
|
public void start() throws IOException {
System.out.println("GraphTrimmer started!");
PrintWriter errorLogWriter = new PrintWriter(new File(
"./logs/GraphTrimmer-error-log.txt"));
// PrintWriter logWriter = new PrintWriter("./logs/GraphTrimmer-log.txt");
int beforeCnt = 0, afterCnt = 0, finishedUsers = 0;
for (File file : fileList) {
try {
Long.parseLong(file.getName());
} catch (Exception e) {
continue;
}
// logWriter.println(file.getName() + " -> started");
// logWriter.flush();
FileInputStream fis = new FileInputStream(file);
DataInputStream dis = new DataInputStream(fis);
int size = dis.read(buffArr);
if (dis.available() > 0) {
System.err.println(file.getName() + " not red completely!!");
errorLogWriter
.println(file.getName() + " not red completely!!");
errorLogWriter.flush();
}
fis.close();
dis.close();
BufferedReader reader = new BufferedReader(new InputStreamReader(
new ByteArrayInputStream(buffArr, 0, size)));
BufferedWriter writer = new BufferedWriter(new FileWriter(new File(
outDir + file.getName())));
String s;
while ((s = reader.readLine()) != null) {
beforeCnt++;
if (set.contains(Long.parseLong(s))) {
writer.write(s + "\n");
afterCnt++;
}
}
reader.close();
writer.close();
// logWriter.write(file.getName() + "\tfinished.\n");
// logWriter.flush();
finishedUsers++;
if (finishedUsers % 10000 == 0) {
System.out.println(finishedUsers
+ " files finished, beforeCnt: " + beforeCnt
+ ", afterCnt: " + afterCnt);
}
}
// Percentage
// logWriter.write("\n\n*****\tFinished! .. beforeCnt: " + beforeCnt
// + ", afterCnt: " + afterCnt + ", trimmed Percentage: "
// + afterCnt * 100 / beforeCnt + "%\n");
System.out.println("\n\n*****\tFinished! .. beforeCnt: " + beforeCnt
+ ", afterCnt: " + afterCnt + ", trimmed-to-original Percentage: "
+ afterCnt * 100 / beforeCnt + "%");
errorLogWriter.close();
// logWriter.close();
}
|
db52025e-8635-47cb-8d7b-b617a1f12d0b
| 0
|
@Override
public void actionPerformed(ActionEvent e) {
CommandFromGod cmd = (CommandFromGod) e.getSource();
cmd.execute();
}
|
4cd093e4-d728-4617-ba84-7b7c5cb30f52
| 3
|
private JSONWriter end(char mode, char c) throws JSONException {
if (this.mode != mode) {
throw new JSONException(mode == 'a'
? "Misplaced endArray."
: "Misplaced endObject.");
}
this.pop(mode);
try {
this.writer.write(c);
} catch (IOException e) {
throw new JSONException(e);
}
this.comma = true;
return this;
}
|
5e559032-86e9-4fef-9131-7c694b6ef7c3
| 8
|
@Override
public boolean equals(Object obj) {
if (this == obj)
return true;
if (obj == null)
return false;
if (getClass() != obj.getClass())
return false;
Employee other = (Employee) obj;
if (deptId != other.deptId)
return false;
if (id != other.id)
return false;
if (name == null) {
if (other.name != null)
return false;
} else if (!name.equals(other.name))
return false;
return true;
}
|
7fe06c68-e3b4-4216-9772-58fe78ded05e
| 4
|
public boolean specspell(int castID, int casterY, int casterX, int offsetY, int offsetX, int angle, int speed, int startHeight, int endHeight, int enemyY,int enemyX, int Lockon)
{
try {
fcastid = castID;
fcasterY = casterY;
fcasterX = casterX;
foffsetY = offsetY;
foffsetX = offsetX;
fangle = angle;
fspeed = speed;
fsh = startHeight;
feh = endHeight;
fenemyY = enemyY;
fenemyX = enemyX;
fLockon = Lockon;
actionTimer = 0;
//Casts Spell In Hands
if(cast == false) {
createProjectile(casterY, casterX, offsetY, offsetX, angle, speed, castID, startHeight, endHeight, Lockon);
cast = true;
firingspell = true;
}
//Fires Projectile
if(cast == true && fired == false) {
firingspell = false;
cast = false;
fired = false;
}
} catch(Exception E) {
}
return true;
}
|
a214720c-f79c-4cfe-9d23-30ebb598a022
| 3
|
public final void accept(SpaceVisitor visitor) {
// The return type is captured, this gives the visitor a change
// to halt any further recursion in this space.
boolean proceed = visitor.visit(this);
if(proceed && !isLeaf()) {
for(Space space : nodes) {
space.accept(visitor);
}
}
}
|
92bee464-330b-4f09-b7f2-c8086e956e05
| 7
|
public HashMap<String, ?> getAll(HashMap<String, ?> map) {
Object def;
String[] loc;
for (String key : map.keySet()) {
try {
def = map.get(key);
loc = key.split(".");
if (def.getClass() == Boolean.class) {
getBoolean(loc[0], loc[1], (Boolean) def);
} else if (def.getClass() == Integer.class) {
getInteger(loc[0], loc[1], (Integer) def);
} else if (def.getClass() == String.class) {
getString(loc[0], loc[1], (String) def);
} else {
logConfigError(key);
}
} catch (Exception e) {
logConfigError(key);
}
}
def = null;
loc = null;
return map;
}
|
1834fdee-9d42-4f58-9727-7adabb787a24
| 2
|
public static ChunkCoord getChunkCoord(int x, int z, World world)
{
long hash = ((long)x & 0xFFFFFFFFL) | (((long)z & 0xFFFFFFFFL) << 32);
ChunkCoord coord = mCache.get(hash);
if(coord == null)
{
coord = new ChunkCoord(x, z, world);
mCache.put(hash, coord);
}
Validate.isTrue(coord.x == x && coord.z == z, String.format("Bad Lookup! hash: %s (%d,%d) (%d,%d)",hash, x, z, coord.x, coord.z));
return coord;
}
|
933bf642-f8ee-4ce2-853e-06185b8dec73
| 0
|
public void enable() {
super.enable();
_accelerator.setEnabled(true);
}
|
58954057-d35d-49bc-a548-8521b0636c3b
| 9
|
private void InsertionSort(List<Endpoint> endPoints,
List<Integer> lookUp)
{
int endpSize = endPoints.size();
for (int j = 1; j < endpSize; ++j)
{
Endpoint key = new Endpoint(endPoints.get(j));
int i = j - 1;
while (i >= 0 && key.compareTo(endPoints.get(i)) == -1)
{
Endpoint e0 = new Endpoint(endPoints.get(i));
Endpoint e1 = new Endpoint(endPoints.get(i+1));
if (e0.type.ordinal() == Endpoint.Type.BEGIN.ordinal())
{
if (e1.type.ordinal() == Endpoint.Type.END.ordinal())
{
if (e0.index < e1.index)
{
overLaps.remove(new Pair(e0.index, e1.index));
}
else
{
overLaps.remove(new Pair(e1.index, e0.index));
}
}
}
else
{
if (e1.type.ordinal() == Endpoint.Type.BEGIN.ordinal())
{
Rectangle r0 = new Rectangle(rectangles.get(e0.index));
Rectangle r1 = new Rectangle(rectangles.get(e1.index));
if (r0.TestIntersection(r1))
{
if (e0.index < e1.index)
{
overLaps.add(new Pair(e0.index, e1.index));
}
else
{
overLaps.add(new Pair(e1.index, e0.index));
}
}
}
}
endPoints.set(i, e1);
endPoints.set(i+1, e0);
lookUp.set(2*e1.index + e1.type.ordinal(), new Integer(i));
lookUp.set(2*e0.index + e0.type.ordinal(), new Integer(i+1));
i--;
}
endPoints.set(i+1, key);
lookUp.set(2*key.index + key.type.ordinal(), new Integer(i+1));
}
}
|
c476bcc3-5708-4087-a333-d6defb239dfe
| 8
|
public int get(byte[] data, int offset, int len) {
if (len == 0) return 0;
int dataLen = 0;
synchronized (signal) {
// see if we have enough data
while (getAvailable() <= 0) {
if (eof) return (-1);
try { signal.wait(1000); } catch (Exception e) { System.out.println("Get.Signal.wait:" + e); }
}
len = Math.min(len, getAvailable());
// copy data
if (getHere < putHere) {
int l = Math.min(len, putHere - getHere);
System.arraycopy(buffer, getHere, data, offset, l);
getHere += l;
if (getHere >= bufferSize) getHere = 0;
dataLen = l;
} else {
int l = Math.min(len, bufferSize - getHere);
System.arraycopy(buffer, getHere, data, offset, l);
getHere += l;
if (getHere >= bufferSize) getHere = 0;
dataLen = l;
if (len > l) dataLen += get(data, offset + l, len - l);
}
signal.notify();
}
return dataLen;
}
|
26b66687-3250-4c2a-84fd-588c32093415
| 5
|
@Override
public String execute() throws Exception {
System.out.println("from ajax: account :" + account + " , password: " + password);
user = this.service.login(account, password);
// Invalid Account
if(user == null) {
status = 2;
msg = "Invalid Account, plz check it out";
}
// Wrong Password
else if(account.equals(user.getU_account()) && !password.equals(user.getU_password())) {
status = 3;
msg = account; // save account content
}
// Validate Successful!!!
else if(account.equals(user.getU_account()) && password.equals(user.getU_password())) {
Cookie cookie = cookieUtil.generateCookie(user);
HttpServletResponse response = ServletActionContext.getResponse();
response.addCookie(cookie);
System.out.println("Add cookie succeed,cookie:" +
cookie.getName() + "--" + cookie.getValue());
// add user's info to session
session.put(com.ccf.action.user.UserLoginAction.USER_SESSION, user);
status = 1;
msg = "<a href=\"homepage\">" + user.getU_name() +
"</a> | <a href=\"logout\">log out(totally)</a>";
}
else {
status = 0;
msg = "Ooops! SHIT HAPPEND";
}
System.out.println("MSG:" + msg + " status" + status);
data = "{status:" + status + ",msg:'" + msg + "'}";
System.out.println(data);
return "map";
}
|
62169f7e-5745-48c6-a4f2-0a5441e8cc55
| 2
|
private static void generationBased(int start, int maxDepth) {
boolean done = false;
int i=start;
while (!done&&i<=maxDepth) {
project.generateAlternativesGeneration(i++);
project.log(path);
done = project.calculateEnergyConsumptionGeneration();
}
project.findBestSystemGeneration();
project.visualizeGeneration(path);
}
|
03e08687-e26a-4c9f-a9ea-2ec5d4907462
| 1
|
public Player(String[] newDeck, GameState gameState) {
playedLand = false;
this.life = 20;
this.deckList = newDeck;
deck = new ArrayList<Card>();
hand = new ArrayList<Card>();
this.gameState = gameState;
this.manaOpen = new int[6];
this.graveyard = new ArrayList<Card>();
//this.playerStyle = (int) Math.random() * 2;
this.playerStyle = 0;
for (String cardName : this.deckList) {
Card card = CardDB.getCard(cardName, this);
this.deck.add(card);
}
}
|
c9692182-8e31-4e48-9062-6609c7c9cb26
| 7
|
private void setUpLists(int level) {
strandOne.clear(); strandTwo.clear(); strandThree.clear(); strandFour.clear();
inPlayOne.clear(); inPlayTwo.clear(); inPlayThree.clear(); inPlayFour.clear();
score = 0;
progress = 0;
oddBalls.add(new CurrentBall(5, imageMap.get("greyBall"), imageMap.get("apcoli"), null, null, false, null));
switch(level) {
case 1: setUpLevelOne(); break;
case 2: setUpLevelTwo(); break;
case 3: setUpLevelThree(); break;
case 4: setUpLevelFour(); break;
case 5: setUpLevelFive(); break;
case 6: setUpLevelSix(); break;
case 7: setUpLevelSeven(); break;
}
getNextBall();
playing = true;
rotate();
repaint();
}
|
48645bab-e6e0-437b-b873-c51d86815010
| 6
|
private void copyRGBtoRGBA(ByteBuffer buffer, byte[] curLine) {
if(transPixel != null) {
byte tr = transPixel[1];
byte tg = transPixel[3];
byte tb = transPixel[5];
for(int i=1,n=curLine.length ; i<n ; i+=3) {
byte r = curLine[i];
byte g = curLine[i+1];
byte b = curLine[i+2];
byte a = (byte)0xFF;
if(r==tr && g==tg && b==tb) {
a = 0;
}
buffer.put(r).put(g).put(b).put(a);
}
} else {
for(int i=1,n=curLine.length ; i<n ; i+=3) {
buffer.put(curLine[i]).put(curLine[i+1]).put(curLine[i+2]).put((byte)0xFF);
}
}
}
|
960b8934-1ad1-4e37-9f69-642b765a1c4b
| 9
|
private void onMessageDecoded(final CoreMessage message) {
if (message.getType().equals(CoreMessageType.READY_TO_RECEIVE_FILE)) {
File file = new File(this.sendingFile.pathName);
try {
this.readingFile = new RandomAccessFile(file, "r");
this.readChannel = this.readingFile.getChannel();
this.beginSendingFile();
} catch (FileNotFoundException e) {
e.printStackTrace(System.out);
}
} else if (message.getType().equals(CoreMessageType.SEND_FILE_INFO)) {
CoreFileInfo fileInfo = (CoreFileInfo) message.getMessageData();
this.receivingFile = fileInfo;
this.localReceivingFile = this.fileReceivingEventHandler.onPrepareReceiving(this.receivingFile);
if (this.localReceivingFile != null) {
if (!localReceivingFile.exists()) {
File parentFile = localReceivingFile.getParentFile();
parentFile.mkdirs();
}
this.beginReceivingFile();
if (this.receivingFile.length > 0) {
this.addMessageToWriteQueue(new CoreMessage(CoreMessageType.READY_TO_RECEIVE_FILE, null));
} else {
this.finishReceivingFile(true);
}
} else {
this.addMessageToWriteQueue(new CoreMessage(CoreMessageType.FILE_RECEIVING_CANCELLED, null));
}
} else if (message.getType().equals(CoreMessageType.FILE_RECEIVED)) {
this.isWaitingRemote = false;
this.sendingFile = null;
this.fileSendingEventHandler = null;
this.doSendFile();
} else if (message.getType().equals(CoreMessageType.CANCEL_RECEIVING_FILE)) {
this.finishSendingFile(false);
// 停止文件传输,恢复默认读状态
this.selectionKey.interestOps(SelectionKey.OP_READ);
} else if (message.getType().equals(CoreMessageType.FILE_RECEIVING_CANCELLED)) {
this.isWaitingRemote = false;
this.sendingFile = null;
this.fileSendingEventHandler = null;
this.doSendFile();
} else {
GlobalUtil.threadExecutor().execute(new Runnable() {
@Override
public void run() {
onMessageReceived(message);
}
});
}
}
|
8dc46ce0-f911-4495-88e5-c92e0e66d1f0
| 9
|
@Override
public boolean doMove() {
int startSteps = curGb.stepCount;
prepareMovement();
while(true) {
if(!check) {
curGb.step(dir); // walk
break;
} else {
State s = curGb.newState();
int add = EflUtil.runToAddressLimit(0, dir, 100, curGb.pokemon.walkSuccessAddress, curGb.pokemon.walkFailAddress);
if(add == 0)
System.out.println("ERROR: didn't find walkSuccessAddress or walkFailAddress");
if(add != curGb.pokemon.walkSuccessAddress) { // test if we are in the walk animation
System.err.println("moving failed ("+(curGb.stepCount - startSteps)+")");
if((curGb.stepCount - startSteps) > 20) {
System.out.println("moving failed too often, giving up!");
return false;
}
curGb.restore(s);
curGb.step(); // wait frame; two frame delay so ending frame is ok
prepareMovement(); // find next walk frame
continue;
}
// curGb.step(); // finish frame
if(avoidEncounters) {
State finished = curGb.newState();
add = EflUtil.runToAddressLimit(0, 0, 100, curGb.pokemon.doWalkPreEncounterCheckAddress);
if(add == 0)
System.out.println("ERROR: didn't find doWalkPreEncounterCheckAddress");
else {
add = EflUtil.runToAddressLimit(0,dir, 100, curGb.pokemon.doWalkPostEncounterCheckAddress, curGb.pokemon.encounterCheckMainFuncEncounterAddress);
if(add == 0)
System.out.println("ERROR: didn't find doWalkPostEncounterCheckAddress or encounterCheckMainFuncEncounterAddress");
if(add == curGb.pokemon.doWalkPostEncounterCheckAddress) {
curGb.restore(finished);
break;
}
}
curGb.restore(s);
System.out.println("WalkStep: avoiding encounter ("+(curGb.stepCount - startSteps)+")");
curGb.step(); // wait one more frame; two frame delay so ending frame is ok
curGb.delayStepCount++;
prepareMovement(); // find next walk frame
continue;
} else
break;
}
}
return true;
}
|
802a68c9-9b4a-4da0-9436-6125b84619ef
| 0
|
public static void main(String args[]){
new Client();
}
|
718e5705-20e3-423e-b818-bb55521b10b0
| 7
|
public static void SymbolTest2()
{
int counter = 1;
// set up stdout for output
PrintStream stdout = new PrintStream( new FileOutputStream( FileDescriptor.out ) );
//
// Construct SymbolData Table
//
//
// When symbol stable is constructed, it creates one scope with the
// name supplied in the constructor argument. Ie. "Global" will the
// name of the top scope in this symbol stable
SymbolTable stable = new SymbolTable();
//
// Construct Lexer
//
Lexer lex = new Lexer();
lex.loadSourceFile("testcpp_good1.cpp");
//
// Fill In The SymbolData Table
//
Lexer.Token token = lex.new Token();
// init before loop
try {
token = lex.get_token();
} catch (SyntaxError e) {
// lexer should not throw syntax error
}
// Loop
while ( token.key != keyword.FINISHED ) {
token.print(stdout);
stdout.print( "On token <"+token.value + "> , ");
if (token.type == token_type.BLOCK) {
if ( token.value.equals("}") ) {
stdout.println("");
//
// Dump before Pop on '}'
//
stdout.println("Dumping symbol table before pop on }");
//TODO stable.dumpTable( stdout );
stdout.println("");
//
// Pop Scope
//
stdout.println("Popping a scope from the symbol table");
stable.popScope();
//
// Dump after Pop on '}'
//
stdout.println("Dumping symbol table after pop on }");
//TODO stable.dumpTable( stdout );
}
else if ( token.value.equals("{") ) {
//
// Push Scope
//
stdout.print("Pushing a new scope into the symbol table");
stable.pushFuncScope(""+ (counter++) );
}
else {
stdout.print("SHOULD NOT HAPPEDN");
}
}
else if (token.type == token_type.IDENTIFIER) {
stdout.print("Inserting into symbol table");
// Construct String
SymbolLocation loc = new SymbolLocation(1,1); // line number and column number
//
// Not working
//
// SymbolLocation loc = new SymbolLocation( lex.getColumnNum(), lex.getLineNum() );
// System.out.println( loc.lnum );
// System.out.println( loc.cnum );
var_type data = new var_type();
String name = token.value; //
data.var_name = new String(name);
// Construct var_type (Value)
data.v_type = token.key;
data.value = 0;
Symbol sym = new Symbol( loc, data );
// Insert into symbol table
SymbolDiagnosis d = stable.pushSymbol(sym);
stdout.print("Diagnosis : "+ d);
}
else {
stdout.print("Doing nothing");
}
stdout.println("");
// Get next token
try {
token = lex.get_token();
} catch (SyntaxError e) {
}
}
}
|
c40baf88-ada9-4470-b88f-17fba667d7f6
| 6
|
public String findFindWhat(String $_original_invoice) throws Exception {
if($_original_invoice.contains("map")){
return new DiscisionForMap().findOrShowMapof($_original_invoice);
}
else if($_original_invoice.contains("hotel")){
return findHotel($_original_invoice);
}
else if($_original_invoice.contains("location")){
return new DiscisionForMap().findOrShowMapof($_original_invoice);
}
else if($_original_invoice.contains("weather")){
return findWeather($_original_invoice,"weather");
}
else if($_original_invoice.contains("temperature")){
return findWeather($_original_invoice,"temperature");
}
else if($_original_invoice.contains("distance")){
return findDistance($_original_invoice);
}
else{
return "Sorry,Try again";
}
}
|
58830d1d-b1a2-458a-aea2-19a0aaa47a85
| 1
|
public void paint(Graphics g) {
if (img == null)
super.paint(g);
else
g.drawImage(img, 0, 0, null);
}
|
6e7dba83-837b-4aa8-8d8c-4145d896ef94
| 3
|
public void saveBounds() {
String keyPrefix = getWindowPrefsPrefix();
if (keyPrefix != null) {
Preferences prefs = getWindowPreferences();
boolean wasMaximized = (getExtendedState() & MAXIMIZED_BOTH) != 0;
if (wasMaximized || getExtendedState() == ICONIFIED) {
setExtendedState(NORMAL);
}
prefs.startBatch();
prefs.setValue(WINDOW_PREFERENCES, keyPrefix + KEY_LOCATION, getLocation());
prefs.setValue(WINDOW_PREFERENCES, keyPrefix + KEY_SIZE, getSize());
prefs.setValue(WINDOW_PREFERENCES, keyPrefix + KEY_MAXIMIZED, wasMaximized);
prefs.setValue(WINDOW_PREFERENCES, keyPrefix + KEY_LAST_UPDATED, System.currentTimeMillis());
prefs.endBatch();
}
}
|
cb27c2d8-36b4-4904-9147-9248f8027a45
| 8
|
private void adjustDirection() {
// set a random movement vector based on where the feeder is.
// will determine the quadrant to point vector to (relative to the
// feeder's current location).
if (currentLocation.x < Environment.getMinX()) { // on left edge
if (currentLocation.y < Environment.getMinY()) { // on top left corner
// set to random vector pointed at fourth quadrant
setRandomMovementVector(QUADRANT.FOUR);
}
else if (currentLocation.y > Environment.getMaxY()) { // on bottom left corner
// set to first quadrant
setRandomMovementVector(QUADRANT.ONE);
}
else { // just on left edge somewhere
// set to either the first or fourth quadrant
setRandomMovementVector(QUADRANT.ONE_OR_FOUR);
}
}
else if (currentLocation.x > Environment.getMaxX()) { // on right edge
if (currentLocation.y < Environment.getMinY()) { // on top right corner
// set to random vector pointed at third quadrant
setRandomMovementVector(QUADRANT.THREE);
}
else if (currentLocation.y > Environment.getMaxY()) { // on bottom right corner
// set to second quadrant
setRandomMovementVector(QUADRANT.TWO);
}
else { // just on right edge somewhere
// set to either the second or third quadrant
setRandomMovementVector(QUADRANT.TWO_OR_THREE);
}
}
else if (currentLocation.y < Environment.getMinY()) { // on top edge
// set to point to the third or fourth quad
setRandomMovementVector(QUADRANT.THREE_OR_FOUR);
// in checking y, we don't need to check x since it was checked
// above.
}
else if (currentLocation.y > Environment.getMaxY()) { // on bottom edge
// set to point to the first or second quad
setRandomMovementVector(QUADRANT.THREE_OR_FOUR);
}
}
|
ad8fb735-9e36-462f-87a4-94204568e8b8
| 6
|
public static Stella_Object accessRelationSlotValue(Relation self, Symbol slotname, Stella_Object value, boolean setvalueP) {
if (slotname == Stella.SYM_STELLA_ABSTRACTp) {
if (setvalueP) {
self.abstractP = BooleanWrapper.coerceWrappedBooleanToBoolean(((BooleanWrapper)(value)));
}
else {
value = (self.abstractP ? Stella.TRUE_WRAPPER : Stella.FALSE_WRAPPER);
}
}
else if (slotname == Stella.SYM_STELLA_PROPERTIES) {
if (setvalueP) {
KeyValueList.setDynamicSlotValue(self.dynamicSlots, Stella.SYM_STELLA_PROPERTIES, ((List)(value)), null);
}
else {
value = self.properties();
}
}
else {
if (setvalueP) {
KeyValueList.setDynamicSlotValue(self.dynamicSlots, slotname, value, null);
}
else {
value = self.dynamicSlots.lookup(slotname);
}
}
return (value);
}
|
c01477b0-8b8c-4f6e-9808-0f3666a8a391
| 8
|
public Object getObjectInstance(final Object ref, final Name name, final Context nameCtx, final Hashtable<?, ?> environment) throws Exception {
final ClassLoader classLoader = SecurityActions.getContextClassLoader();
if(classLoader == null) {
return ref;
}
final String factoriesProp = (String)environment.get(Context.OBJECT_FACTORIES);
if(factoriesProp != null) {
final String[] classes = factoriesProp.split(":");
for(String className : classes) {
try {
final Class<?> factoryClass = classLoader.loadClass(className);
final ObjectFactory objectFactory = ObjectFactory.class.cast(factoryClass.newInstance());
final Object result = objectFactory.getObjectInstance(ref, name, nameCtx, environment);
if(result != null) {
return result;
}
} catch(Throwable ignored) {
}
}
}
return null;
}
|
da1568d6-44b9-449e-9834-ca742b3df228
| 7
|
@Override
public <T extends Serializable> boolean unRegisterSubscriber(String subscriverId) {
LOGGER.log(Level.FINEST, "request unSubscription on OdynoDataBus");
for (Iterator<Subscriber<?, ?>> it = subscribers.iterator(); it.hasNext();) {
Subscriber<? extends Serializable, ? extends Filter<? extends Serializable>> subscriber = it.next();
if (subscriber.getIdentification().equals(subscriverId)) {
write.lock();
try {
subscriber.onChangeSystemStatus(DataBusServiceStatus.DESTROY);
return subscribers.remove(subscriber);
} finally {
write.unlock();
}
}
}
return false;
}
|
c4536561-fcfa-45ff-804e-ec112f611ff3
| 2
|
public void addComponent(Component component){
component.setOwner(this);
components.add(component);
if(Renderable.class.isInstance(component)){
renderers.add((Renderable)component);
}
if(Updatable.class.isInstance(component)){
updaters.add((Updatable)component);
}
}
|
b83cba5c-2e9c-4fbb-b71a-a2c247891f59
| 4
|
public void toggleOpen() {
if (moveTimer > 0) return;
containerOpen = !containerOpen;
if (containerOpen) {
Item active = getActiveItem();
if (active != Item.FIST && active != null) inventory.addItem(active, 1);
setActiveItem(Item.FIST);
}
}
|
0c169175-7d05-4f1c-aa88-324660332612
| 4
|
private boolean validate(String road) throws IOException, InputException
{
if (road == null ||road.equals(""))
return false;
InputStream fis;
BufferedReader br;
String line;
fis = new FileInputStream("data/road_names.txt"); //skal ændres til det rigtige fil navn
br = new BufferedReader(new InputStreamReader(fis, "LATIN1"));
while ((line = br.readLine()) != null) {
if (road.equalsIgnoreCase(line)) {
br.close();
return true;
}
}
br.close();
throw new InputException("Could not find " + road + "");
}
|
d57b40f0-cd3a-491c-b08c-7149ee9e88a6
| 7
|
@SuppressWarnings("deprecation")
public void addCbaseItem(ServiceInfo info) {
if( info.getServiceId() == -1 ) return;
// first create status array
conn.query("SELECT * FROM "+SCHEMA+".service_date_uptime where service_id = "+info.getServiceId());
ResultSet rs = conn.getQueryResult();
String uptimeDate = "";
String uptimeStatus = "";
try {
while( rs.next() ) {
uptimeDate += toNiceDate(rs.getDate("runtime"))+",";
uptimeStatus += String.valueOf(rs.getBoolean("status"))+",";
}
} catch (SQLException e) {
e.printStackTrace();
}
if( !uptimeDate.isEmpty() ) {
uptimeDate = uptimeDate.substring(0, uptimeDate.length()-1);
uptimeStatus = uptimeStatus.substring(0, uptimeStatus.length()-1);
}
conn.closeQuery();
String inserted = "";
conn.query("SELECT inserted FROM "+SCHEMA+".services where service_id = "+info.getServiceId());
rs = conn.getQueryResult();
try {
if( rs.next() ) {
Timestamp ts = rs.getTimestamp("inserted");
inserted = (ts.getYear()+1900)+"-"+(ts.getMonth()+1)+"-"+ts.getDate();
}
} catch (SQLException e1) {
e1.printStackTrace();
}
conn.closeQuery();
conn.prepare("INSERT INTO "+SCHEMA+".sweep (service_id, hs) VALUES"+
"(?, hstore(ARRAY['Link(text)','Resource(text)','Description(text)','Title(text)', '"+info.getType()+"(text)', " +
"'Uptime Date(text)@,', 'Uptime Status(bool)@,', 'Date Entered(date)'],ARRAY[?,?,?,?,?,?,?,?]))"
);
String url = info.getHost()+"/"+info.getPath()+"/"+info.getType();
PreparedStatement stmt = conn.getPreparedStatement();
try {
stmt.setInt(1, info.getServiceId());
stmt.setString(2, url);
stmt.setString(3, info.getType());
stmt.setString(4, info.getDescription());
stmt.setString(5, info.getTitle());
stmt.setString(6, url);
stmt.setString(7, uptimeDate);
stmt.setString(8, uptimeStatus);
stmt.setString(9, inserted);
stmt.execute();
stmt.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
|
43243292-f59e-46ed-a245-934335e8aa4e
| 1
|
ColorComboBoxRendererWrapper (JComboBox comboBox) {
this.renderer = comboBox.getRenderer();
if( renderer instanceof ColorComboBoxRendererWrapper ) {
throw new IllegalStateException("Custom renderer is already initialized."); //NOI18N
}
comboBox.setRenderer( this );
}
|
bd2b583f-30a4-4c61-b115-60b66fffbc71
| 3
|
public T dequeue() throws Exception {
T res;
if (s1.isEmpty()) {
throw new Exception("Empty queue");
}
while (!s1.isEmpty()) {
s2.push(s1.pop());
}
res = s2.pop();
while (!s2.isEmpty()) {
s1.push(s2.pop());
}
return res;
}
|
b97bc2a0-34e6-4a68-a59a-7f6ccd51aae5
| 9
|
public static ArrayList<String> separaTokens(String expr) throws Exception {
ArrayList<String> tokens;
String token = "";
boolean entreAspa = false;
expr = expr.trim();
if (expr.length() != 0) {
tokens = new ArrayList<String>();
entreAspa = false;
for (int i = 0; i < expr.length(); i++) {
if (expr.charAt(i) == '"') {
entreAspa = !entreAspa;
}
if ((!Character.isWhitespace(expr.charAt(i)) && expr.charAt(i) != ';') || entreAspa) {
token += expr.charAt(i);
} else {
if (token.length() != 0) {
tokens.add(token);
}
token = "";
}
}
if (token.length() != 0) {
tokens.add(token);
}
// se chegou no final e não encontrou o número correto de aspas, lança uma exceção avisando do erro
if (entreAspa) {
throw new IllegalArgumentException("Terminador da cadeia de caracteres \" nao encontrado");
}
return tokens;
} else {
return null;
}
}
|
3592dc0e-c727-43ef-9141-a711a2d44d8c
| 2
|
static void p2(int pos, int maxUsed) {
if(pos == k) {
System.out.println(Arrays.toString(a));
} else {
for(int i = maxUsed; i <= n; i++) {
a[pos] = i;
p2(pos+1,i);
}
}
}
|
51e33dba-18e9-4e91-a787-d39d191d18f9
| 0
|
public PolynomialTerm(double power) {
_power = power;
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.