method_id
stringlengths 36
36
| cyclomatic_complexity
int32 0
9
| method_text
stringlengths 14
410k
|
|---|---|---|
80772a7b-3902-4391-8a8f-c1adee6d3b05
| 1
|
private static void displayEmployees(ResultSet rs)throws SQLException{
StringBuilder bf = new StringBuilder();
while (rs.next()){
bf.append(rs.getString("name")).append(" ");
bf.append(rs.getString("username")).append(" ");
bf.append(rs.getString("pass")).append(" ");
bf.append(rs.getDate("dob")).append(" ");
bf.append(rs.getString("phone"));
System.out.println(bf.toString());
bf.delete(0, bf.length());
}
}
|
fc635804-a453-416d-b967-e48aee883be5
| 7
|
@Override
public void run() throws Exception {
try {
ConfigFile importFile = new ConfigFile(plugin);
ConfigSQL importSQL = new ConfigSQL(plugin);
if (!importSQL.checkDatabase()) {
throw new Exception("Could not connect to database !");
}
for (String player : importFile.getAllPlayers()) {
for (String group : importFile.getPlayerGroups(player)) {
importSQL.addPlayerGroup(player, group);
}
for (Entry<String, Boolean> permission : importFile.getPlayerPermissions(player).entrySet()) {
importSQL.addPlayerPermission(player, permission.getKey(), permission.getValue());
}
for (String world : importFile.getPlayerWorlds(player)) {
for (Entry<String, Boolean> permission : importFile.getPlayerPermissions(player, world).entrySet()) {
importSQL.addPlayerPermission(player, world, permission.getKey(), permission.getValue());
}
}
}
} catch (Exception e) {
throw e;
}
}
|
327eada9-807f-4987-8508-e1b3d1eba63b
| 8
|
private float[] getColors() {
int c = r.nextInt(8);
float[] b = new float[3];
switch (c) {
case 0: // yellow
b[0] = 181f / 255f;
b[1] = 137f / 255f;
b[2] = 0f / 255f;
break;
case 1: // orange
b[0] = 203f / 255f;
b[1] = 75f / 255f;
b[2] = 22f / 255f;
break;
case 2: // red
b[0] = 220f / 255f;
b[1] = 50f / 255f;
b[2] = 47f / 255f;
break;
case 3: // magenta
b[0] = 211f / 255f;
b[1] = 54f / 255f;
b[2] = 130f / 255f;
case 4: // violet
b[0] = 108f / 255f;
b[1] = 113f / 255f;
b[2] = 196f / 255f;
break;
case 5: // blue
b[0] = 38f / 255f;
b[1] = 139f / 255f;
b[2] = 210f / 255f;
break;
case 6: // cyan
b[0] = 42f / 255f;
b[1] = 161f / 255f;
b[2] = 152f / 255f;
break;
case 7: // green
b[0] = 133f / 255f;
b[1] = 153f / 255f;
b[2] = 0f / 255f;
break;
}
return b;
}
|
4ca08abb-803c-4e5f-a339-6f016d4ed6c7
| 3
|
private static void applyLocalAddressSetting(String strLclAdr,
List<InetAddress> lTmp) {
for(InetAddress iaTmp: lTmp)
if (strLclAdr.equals(iaTmp.getHostAddress()))
EzimNetwork.localAddress = iaTmp;
if (null == EzimNetwork.localAddress)
{
EzimLogger.getInstance().warning
(
"Invalid local address setting \"" + strLclAdr
+ "\"."
);
}
}
|
ced46340-069e-43fa-a89e-ae2c56bd45dd
| 7
|
private void bottomPossibleMoves(Piece piece, Position position)
{
int x1 = position.getPositionX();
int y1 = position.getPositionY();
if(y1 >= 1 && y1 <= 7)
{
boolean pieceNotFound = true;
for (int i = y1 - 1; pieceNotFound && (i >= 0) && (board.getChessBoardSquare(x1, i).getPiece().getPieceColor() != piece.getPieceColor()); i--)
{
// System.out.print(" " + coordinateToPosition(x1, i));
Position newMove = new Position(x1, i);
piece.setPossibleMoves(newMove);
if (board.getChessBoardSquare(x1, i).getPiece().getPieceType() != board.getBlankPiece().getPieceType())
{
pieceNotFound = false;
if(board.getChessBoardSquare(x1, i).getPiece().getPieceColor() != piece.getPieceColor())
{
// System.out.print("*");
}
}
}
}
}
|
4f4544dc-b2e9-4694-95e6-6f00289aca6f
| 9
|
public static void main(String[] args) throws IOException {
BufferedReader in = new BufferedReader(new InputStreamReader(System.in));
String line = "";
StringBuilder out = new StringBuilder();
while ((line = in.readLine()) != null && line.length() != 0) {
int times = Integer.parseInt(line.trim());
for (int i = 0; i < times; i++) {
String[] info = in.readLine().trim().split(" ");
int rem = Integer.parseInt(info[1]);
char[] names = info[2].toCharArray();
HashSet<Character> set = new HashSet<Character>(names.length);
int ans = 0, k;
for (int j = 1; j < names.length; j++) {
set.clear();
k = (j - rem < 0) ? 0 : j - rem;
for (; k < j; k++)
if (k >= 0 && !set.contains(names[k]))
set.add(names[k]);
if (set.contains(names[j]))
ans++;
}
out.append("Case " + (i + 1) + ": " + ans + "\n");
}
}
System.out.print(out);
}
|
90b98e2a-c4d8-4c53-ae17-b3b4031c1ba2
| 7
|
public void writeResultes() {
try {
BufferedWriter bw = new BufferedWriter(new FileWriter(zoneID + "-results.txt"));
if (!created.isEmpty()) {
bw.write("New Planets\n---------------------\n");
for (Planet p : created) {
bw.write(p.outputNewPlanet() + "\n");
}
bw.write("\n\n");
}
if (!destroyed.isEmpty()) {
bw.write("Destroyed Planets\n---------------------\n");
for (Planet p : destroyed) {
bw.write(p.toString() + "\n");
}
bw.write("\n\n");
}
if (!restored.isEmpty()) {
bw.write("Restored Planets\n---------------------\n");
for (Planet p : restored) {
bw.write(p.toString() + "\n");
}
}
bw.close();
} catch (IOException ex) {
//Must learn how to use logger...
//Logger.getLogger(HypsPlanetInfo.class.getName()).log(Level.SEVERE, null, ex);
}
}
|
f066d987-a3ba-456f-b733-6aabda60dc5e
| 6
|
public static void main(String args[]) {
/* Set the Nimbus look and feel */
//<editor-fold defaultstate="collapsed" desc=" Look and feel setting code (optional) ">
/* If Nimbus (introduced in Java SE 6) is not available, stay with the default look and feel.
* For details see http://download.oracle.com/javase/tutorial/uiswing/lookandfeel/plaf.html
*/
try {
for (javax.swing.UIManager.LookAndFeelInfo info : javax.swing.UIManager.getInstalledLookAndFeels()) {
if ("Nimbus".equals(info.getName())) {
javax.swing.UIManager.setLookAndFeel(info.getClassName());
break;
}
}
} catch (ClassNotFoundException ex) {
java.util.logging.Logger.getLogger(MUsuarios.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (InstantiationException ex) {
java.util.logging.Logger.getLogger(MUsuarios.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (IllegalAccessException ex) {
java.util.logging.Logger.getLogger(MUsuarios.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (javax.swing.UnsupportedLookAndFeelException ex) {
java.util.logging.Logger.getLogger(MUsuarios.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
}
//</editor-fold>
//</editor-fold>
/* Create and display the form */
java.awt.EventQueue.invokeLater(new Runnable() {
public void run() {
new MUsuarios(null).setVisible(true);
}
});
}
|
bc26d629-9de9-46fe-96f1-d132be0d923f
| 8
|
static String findTableName(String cmd) {
if (cmd != null) {
StringBuilder buffer = new StringBuilder();
Scanner scanner = new Scanner(cmd);
try {
while (scanner.hasNextLine()) {
final String line = scanner.nextLine();
buffer.append(line.replaceAll("/\\*.*?\\*/|//.*", ""));
buffer.append(' ');
}
} finally {
scanner.close();
}
Pattern p = Pattern.compile(PTN1, Pattern.CASE_INSENSITIVE);
Matcher m = p.matcher(buffer);
if (m.matches()) {
String afterFrom = m.group(1);
String[] words = afterFrom.split("\\s");
boolean foundComma = false;
for (int i = 0; i < 2 && i < words.length; i++) {
String word = words[i];
if (word.indexOf(',') >= 0) {
foundComma = true;
}
}
if (!foundComma) {
String word = words[0];
if (word.matches("[A-Za-z0-9_\\.]+")) {
return word;
}
}
}
}
return "";
}
|
5dcc55e6-d78c-4687-a8e4-438dc90a705b
| 6
|
public int getAtk(int npc) {
switch (npc) {
case 2627:
return 30;
case 2630:
return 50;
case 2631:
return 100;
case 2741:
return 150;
case 2743:
return 450;
case 2745:
return 650;
}
return 100;
}
|
f9cd8849-8ce7-4eaf-a113-40aa7fa8fa7c
| 8
|
public void A_Vote(String AID, String UID, int vote) // vote can be 0 or 1
{
//check if this user have previously voted for this question
int __c__=0;
int currentVote;
try (Connection conn = DriverManager.getConnection(dbURL, username, password))
{
//Update the DB
String sql = "SELECT ID,VOTE FROM UTA.ANSWER_VOTE WHERE UID="+UID+" AND AID="+AID;
PreparedStatement statement = conn.prepareStatement(sql);
ResultSet rs = statement.executeQuery();
if(rs.next())
{
currentVote = rs.getInt("VOTE");
__c__ = 1;
if(vote!=currentVote)
{
__c__=2;
sql = "UPDATE UTA.ANSWER_VOTE SET VOTE="+Integer.toString(vote)+" WHERE ID="+rs.getString("ID");
statement.close();
statement = conn.prepareStatement(sql);
statement.executeUpdate();
}
}
else
{
sql = "INSERT INTO UTA.ANSWER_VOTE(UID,AID,VOTE) VALUES("+UID+","+AID+","+Integer.toString(vote)+")";
statement.close();
statement = conn.prepareStatement(sql);
statement.executeUpdate();
}
statement.close();
// Find the user_id of the person who asked the question
String sql2="SELECT USER_ID FROM UTA.ANSWERS WHERE ANSWER_ID="+AID;
statement = conn.prepareStatement(sql2);
rs = statement.executeQuery();
if(!rs.next()) return;
String UID2 = rs.getString("USER_ID");
statement.close();
// update the answer rank and user credit
if(__c__ != 1) // the rank has changed
{
if(vote ==1) // increment the rank
{
if(__c__ == 2)
{
sql="UPDATE UTA.ANSWERS SET RANK=RANK+2 WHERE ANSWER_ID="+AID;
sql2 = "UPDATE UTA.USERProfile SET CREDIT=CREDIT+2 WHERE USER_ID="+UID2;
}
else
{
sql="UPDATE UTA.ANSWERS SET RANK=RANK+1 WHERE ANSWER_ID="+AID;
sql2 = "UPDATE UTA.USERProfile SET CREDIT=CREDIT+1 WHERE USER_ID="+UID2;
}
}
else // decrement the rank
{
if(__c__ == 2)
{
sql="UPDATE UTA.ANSWERS SET RANK=RANK-2 WHERE ANSWER_ID="+AID;
sql2 = "UPDATE UTA.USERProfile SET CREDIT=CREDIT-2 WHERE USER_ID="+UID2;
}
else
{
sql="UPDATE UTA.ANSWERS SET RANK=RANK-1 WHERE ANSWER_ID="+AID;
sql2 = "UPDATE UTA.USER_CREDIT SET CREDIT=CREDIT-1 WHERE USER_ID="+UID2;
}
}
statement = conn.prepareStatement(sql);
statement.executeUpdate();
statement.close();
//statement = conn.prepareStatement(sql2);
//statement.executeUpdate();
//statement.close();
}
conn.close();
//Add the id of questioner
} catch (SQLException ex) {
ex.printStackTrace();
}
}
|
f8b1c4bf-f12a-4dcc-ad82-466b698fb396
| 6
|
private void calcHeading() {
int lastCoordIndex = mCoordIndex - 1;
if (lastCoordIndex < 0) {
lastCoordIndex = COORD_BUFFER_SIZE - 1;
}
// only continue if all of the coords exist
if (!Double.isNaN(mLat[mCoordIndex])
&& !Double.isNaN(mLon[mCoordIndex])
&& !Double.isNaN(mLat[lastCoordIndex])
&& !Double.isNaN(mLon[lastCoordIndex])) {
double tempHeading = getBearing(mLat[lastCoordIndex],
mLon[lastCoordIndex], mLat[mCoordIndex], mLon[mCoordIndex]);
if (Double.isNaN(mHeading)) {
mHeading = tempHeading;
} else {
mHeading = (mHeading + tempHeading) / 2.0;
}
}
}
|
e731fcdc-a98c-4c3b-a55a-a9c778d53ee8
| 6
|
public static String escape(String string) {
char c;
String s = string.trim();
StringBuffer sb = new StringBuffer();
int length = s.length();
for (int i = 0; i < length; i += 1) {
c = s.charAt(i);
if (c < ' ' || c == '+' || c == '%' || c == '=' || c == ';') {
sb.append('%');
sb.append(Character.forDigit((char)((c >>> 4) & 0x0f), 16));
sb.append(Character.forDigit((char)(c & 0x0f), 16));
} else {
sb.append(c);
}
}
return sb.toString();
}
|
7ecad1c6-2243-4261-ba6f-446b798caec3
| 0
|
public double getSpeedY(){
return speedY;
}
|
96b7914e-7071-4893-9163-7c041ef6b7c4
| 1
|
@Override
public void includeSource() {
for (File f : layout.asdFiles()) {
this.addPackage(f);
}
}
|
ffc5de53-1a65-48ce-992b-c6316e97206c
| 6
|
@Override
public T deserialize(JsonParser jp, DeserializationContext dc) throws IOException, JsonProcessingException {
T entity = createEntity();
while (true) {
JsonToken token = jp.nextValue();
if (token == null) {
break;
}
if (token.equals(JsonToken.END_OBJECT)) {
break;
}
String keyName = jp.getCurrentName();
if (keyName == null) {
continue;
}
if (keyName.equals("id")) {
String id = jp.getText();
entity.setId(id);
continue;
}
if (token.equals(JsonToken.START_ARRAY)) {
deserializeArrayNode(jp, keyName, dc, entity);
} else {
deserializeUniqueNode(jp, keyName, dc, entity);
}
}
return entity;
}
|
7fcf991a-4b5f-4974-b9f0-669bd4c31379
| 6
|
public static void computeSlotInverses(Slot self) {
if (((Symbol)(KeyValueList.dynamicSlotValue(self.dynamicSlots, Stella.SYM_STELLA_SLOT_INVERSE, null))) == null) {
return;
}
if (Slot.multiValuedSlotWithDuplicatesP(self)) {
Stella.STANDARD_WARNING.nativeStream.println("Warning: Can't define an inverse on slot `" + self + "' because it allows duplicate values.");
KeyValueList.setDynamicSlotValue(self.dynamicSlots, Stella.SYM_STELLA_SLOT_INVERSE, null, null);
return;
}
{ Stella_Class inverseclass = ((Stella_Class)(self.type().surrogateValue));
Slot inverseslot = Stella_Class.lookupSlot(inverseclass, ((Symbol)(KeyValueList.dynamicSlotValue(self.dynamicSlots, Stella.SYM_STELLA_SLOT_INVERSE, null))));
if (inverseslot != null) {
if (Slot.multiValuedSlotWithDuplicatesP(inverseslot)) {
Stella.STANDARD_WARNING.nativeStream.println("Warning: Can't define an inverse on slot `" + inverseslot + "' because it allows duplicate values.");
KeyValueList.setDynamicSlotValue(self.dynamicSlots, Stella.SYM_STELLA_SLOT_INVERSE, null, null);
KeyValueList.setDynamicSlotValue(inverseslot.dynamicSlots, Stella.SYM_STELLA_SLOT_INVERSE, null, null);
return;
}
if (!inverseslot.activeP()) {
KeyValueList.setDynamicSlotValue(inverseslot.dynamicSlots, Stella.SYM_STELLA_SLOT_INVERSE, self.slotName, null);
inverseslot.finalizeSlotTypeComputations();
}
KeyValueList.setDynamicSlotValue(inverseslot.dynamicSlots, Stella.SYM_STELLA_INVERSE, self, null);
Slot.attachInverseSlotDemon(self);
KeyValueList.setDynamicSlotValue(self.dynamicSlots, Stella.SYM_STELLA_INVERSE, inverseslot, null);
Slot.attachInverseSlotDemon(inverseslot);
return;
}
if (inverseclass == null) {
{
Stella.STANDARD_WARNING.nativeStream.println("Warning: Can't finalize inverse slot computation for slot `" + self + "'");
Stella.STANDARD_WARNING.nativeStream.println(" because the class `" + self.type() + "' is not defined.");
}
;
}
else {
{
Stella.STANDARD_WARNING.nativeStream.println("Warning: Can't finalize inverse slot computation for slot `" + self + "'");
Stella.STANDARD_WARNING.nativeStream.println(" because the inverse slot `" + ((Symbol)(KeyValueList.dynamicSlotValue(self.dynamicSlots, Stella.SYM_STELLA_SLOT_INVERSE, null))) + "' does not exist.");
}
;
}
}
}
|
3e38b01a-e00f-446a-8c28-75f604be4d55
| 9
|
private void createHelper() {
for (Map.Entry<String, XMLLayoutData> entry : componentsLayoutMap.entrySet()) {
String componentId = entry.getKey();
XMLLayoutData xmlLayoutData = entry.getValue();
Object topData = null;
Object bottomData = null;
Object leftData = null;
Object rightData = null;
if (xmlLayoutData.topData == "") {
topData = FormLayoutHelper.TOP;
} else if (xmlLayoutData.topData != null) {
topData = componentsIdMap.get(xmlLayoutData.topData);
}
if (xmlLayoutData.bottomData == "") {
bottomData = FormLayoutHelper.BOTTOM;
} else if (xmlLayoutData.bottomData != null) {
bottomData = componentsIdMap.get(xmlLayoutData.bottomData);
}
if (xmlLayoutData.leftData == "") {
leftData = FormLayoutHelper.LEFT;
} else if (xmlLayoutData.leftData != null) {
leftData = componentsIdMap.get(xmlLayoutData.leftData);
}
if (xmlLayoutData.rightData == "") {
rightData = FormLayoutHelper.RIGHT;
} else if (xmlLayoutData.rightData != null) {
rightData = componentsIdMap.get(xmlLayoutData.rightData);
}
helper.addComponent(componentsIdMap.get(componentId), topData, bottomData, leftData, rightData);
}
}
|
14e58ca9-2c20-4dcc-ae20-e8720196d848
| 0
|
public boolean getCell(int x, int y) {
return grid[x][y];
}
|
b54ae1ef-23af-4e2c-b0e9-174c831a1111
| 2
|
private boolean contactsExist(Set<Contact> contacts) {
Iterator contactsIterator = contacts.iterator();
while(contactsIterator.hasNext()) {
if(!contactExists((Contact) contactsIterator.next())) {
return false;
}
}
return true;
}
|
da3484f0-408d-4476-aaae-2f4eea86ef8c
| 7
|
public final Pino etsiPolku(int alkuX, int alkuY, int loppuX, int loppuY, String tietorakenne) {
if (!tarkistaX(alkuX) || !tarkistaY(alkuY) || !tarkistaX(loppuX) || !tarkistaY(loppuY)) {
throw new IllegalArgumentException("Annetun koordinaatin täytyy olla kartalla.");
}
Pino polku;
//Ohjelmaa voidaan ajaa kolmella eri tietorakenteella joka tallentaa
//käymättömät noodit. Keko-toteutus on oletusarvona.
if (tietorakenne.contains("PQ")) {
LaskentaPQ laskenta = new LaskentaPQ(this.noodit, this.leveys, this.korkeus);
polku = laskenta.etsiPolku(alkuX, alkuY, loppuX, loppuY);
} else if (tietorakenne.contains("AVL")) {
LaskentaAvl laskenta = new LaskentaAvl(this.noodit, this.leveys, this.korkeus);
polku = laskenta.etsiPolku(alkuX, alkuY, loppuX, loppuY);
}
LaskentaKeko laskenta = new LaskentaKeko(this.noodit, this.leveys, this.korkeus);
polku = laskenta.etsiPolku(alkuX, alkuY, loppuX, loppuY);
if(this.kuva != null){
piirraKuva(polku.teeKopio());
}
return polku;
}
|
6eb70b81-198d-4fb3-bcee-02f745ea11ce
| 3
|
private byte[] readBytes( int db, int ln )
{
byte[] b = new byte[ln];
RandomAccessFile f = ( db==0 ? fdbf : db==1 ? ffpt : fcdx );
try { f.read(b); } catch (IOException e) { e.printStackTrace(); }
return b;
}
|
55bad0d7-48f7-4b85-a02d-fbf11905c6a7
| 0
|
@Override
protected void onStart() {
frame = new AuthFrame(this);
MineOS.getDesktop().addFrame(frame);
}
|
9aeb9df8-0622-460a-abda-2fb84fa11663
| 6
|
@Override
public void writeAVLData(OutputStream out) {
PrintStream ps = new PrintStream(out);
ps.print("\n#=======================================\n"); // SURFACE | (keyword)
ps.print("SURFACE\n"); // SURFACE | (keyword)
ps.printf(locale, "%1$s\n", this.getName()); //Main Wing | surface name string
ps.printf(locale, "#Nchord Cspace [Nspan Sspace]\n" + formatInteger(1) + formatFloat(1,2),
this.getNchord(), this.getCspace());
if (this.getNspan() != 0){
ps.printf(locale, formatInteger(1) + formatFloat(1,2),
this.getNspan(), this.getSspace()); //12 1.0 20 -1.5 | Nchord Cspace [ Nspan Sspace ]
}
ps.print("\n");
ps.print("YDUPLICATE\n"); //YDUPLICATE | (keyword)
ps.printf(locale, formatFloat(1) + "\n", this.getYdupl()); //0.0 | Ydupl
if (this.getdX() != 0 || this.getdY() != 0 || this.getdZ() != 0){
ps.print("TRANSLATE\n"); //TRANSLATE | (keyword)
ps.printf(locale, "#dX dY dZ\n" + formatFloat(3) + "\n",
this.getdX(), this.getdY(), this.getdZ()); //10.0 0.0 0.5 | dX dY dZ
}
if (this.getdAinc() != 0){
ps.print("ANGLE\n"); //ANGLE | (keyword)
ps.printf(locale, "#dAinc\n" + formatFloat(1) + "\n", this.getdAinc()); //2.0 | dAinc
}
for(Section sect : this.getSections()){
sect.writeAVLData(out);
}
}
|
08b73b5b-9be1-4701-8d45-a496e38fc395
| 8
|
private void goRoom(Command command) {
if (!command.hasSecondWord()) {
// if there is no second word, we don't know where to go...
System.out.println("Go where?");
return;
}
String direction = command.getSecondWord();
if (direction.equals("back")) {
player.subtractLocationHistory();
printLocationInfo();
lookForNPCMessage();
return;
}
// Special cases.
if (player.getLocation().getName().equals("antechamber") && direction.equals("west")) {
System.out.println("Carefully sneaking into the living room, you hear something running violently towards you from behind. You don't have enough time to turn your head around before you feel a heavy blow to the back of your head and everything goes black!");
player.clearLocationHistory();
player.clearInventory();
System.out.println("You wake up freezing on the wet stone floor of an ancient prison cell, your head resting in a small pool of blood. For some reason whoever guards this place left the door open. Perhaps the note lying next to you might reveal something.\n");
player.addLocationHistory(rooms.get("cell1"));
printLocationInfo();
return;
}
if (player.getLocation().getName().equals("hallwayB1") && direction.equals("north")) {
System.out.println("\n\nThere's nothing but a black void on the other side of the door. You doubt the idea but since you have no other choice, you walk right out. It seems there is no gravity, neither any oxygen and you start to choke. But at the same time everything fades and soon you can't even feel your body.");
System.out.println("\nYou wake up sleeping on the grass of a green meadow in a forest. The sky is clear and the sun shines strongly into your eyes. Looking to your left, Hrangst lies dead, pale as snow. It seems Zuul kept his word.");
System.out.println("\n\nCongratulations upon beating 'Zuul's Dungeon'!\n");
quit(new Command("quit", null));
}
// Regular operation.
// Try to leave current room through chosen exit.
Exit chosenExit = player.getLocation().getExit(direction);
if (chosenExit == null) {
System.out.println("There's no room in that direction.\n");
return;
}
Room nextRoom = chosenExit.getNeighbour();
if (!chosenExit.getUnlocked()) {
System.out.println("The door is locked.\n");
return;
}
player.addLocationHistory(nextRoom);
printLocationInfo();
lookForNPCMessage();
}
|
051cceba-4df1-4ede-bb39-e80c988f924a
| 9
|
private void run() {
ElevatorStrategy str = strategies[strategy];
//we expect 300 arrivals in an hour
//lambda = 1/4 since we expect 1 arrival per 12 sec == 4 time units, the mean is therefore 1/0.25
// new value for 2hrs/300 persons: 1/0.125
ExponentialDistribution e = new ExponentialDistribution((1/0.25));
int timeForArrival = (int)(e.sample());
test.add(timeForArrival);
//time 2400 = 2h
while (time < 1200){
System.out.println("--------------------------------Time: "+time+"---------------------------");
//generates persons with help from a exponential distribution
if (timeForArrival == time){
Person newPerson = generatePerson();
//add the new person to their current floor
Floor currentFloor = floorList.get(newPerson.getPosition());
currentFloor.addPerson(newPerson);
//the new person will push the button on the floor unless it's already pushed
if (newPerson.direction == 1){
if (!currentFloor.isbtnUpOn()){
currentFloor.setbtnUpOn(true);
str.addToWaitingList(newPerson);
}
}
else {
if (!currentFloor.isbtnDownOn()){
currentFloor.setbtnDownOn(true);
str.addToWaitingList(newPerson);
}
}
System.out.println("new person "+ newPerson.getID()+" at: "+ newPerson.getPosition() +" dest: "+newPerson.getDestination());
//generate person from poisson distribution
peopleInSystem.add(newPerson);
id++;
//generate the new time for arrival
timeForArrival = (int)(e.sample())+time+1;
test.add(timeForArrival);
}
for (Elevator elev : elevators) {
if (elev.denied.size() > 0){
for (Person p : elev.denied) {
str.addToWaitingList(p);
}
elev.denied.clear();
}
}
str.getElevator(elevators, type, floorList);
//timestep
for (Elevator elevator : elevators) {
elevator.timeStep(time, floorList);
}
time++;
}
// for (int i = 0; i <40; i++) {
// System.out.println((int)(e.sample()));
// }
}
|
782f9b27-adee-4f03-9d60-56bbbfec9edc
| 1
|
public static String booleanToString(boolean bool) {
if(bool)
return "ON";
else
return "OFF";
}
|
dbe9183d-112b-419b-a659-d79fcfc32bcd
| 4
|
private boolean fill() {
if (fill)
return true;
if (cMap.size() < tMap.size())
return false;
for (Character key : cMap.keySet()) {
if (cMap.get(key) < tMap.get(key))
return false;
}
fill = true;
return true;
}
|
0632e6c3-fb5d-4dc4-b214-d1fb652d56b3
| 4
|
@Override
public ArrayList<BoardPosition> getPossibleMoves(Board board, BoardPosition startingPosition) {
ArrayList<BoardPosition> possibleMoves = new ArrayList<BoardPosition>();
DiagonalMove toTopLeft = new DiagonalMove();
DiagonalMove toTopRight = new DiagonalMove();
DiagonalMove toBottomLeft = new DiagonalMove();
DiagonalMove toBottomRight = new DiagonalMove();
StraightMove down = new StraightMove();
StraightMove up = new StraightMove();
StraightMove right = new StraightMove();
StraightMove left = new StraightMove();
int x = startingPosition.getColumn();
int y = startingPosition.getRow();
BoardPosition topLeftDest = x > y
? new BoardPosition(x-y, y-y)
: new BoardPosition(x-x, y-x);
BoardPosition topRightDest = y < 7 - x
? new BoardPosition(x + y, y - y)
: new BoardPosition(x + (7-x), y - (7-x));
BoardPosition bottomLeftDest = y < 7 - x
? new BoardPosition(x - x, y + x)
: new BoardPosition(x - (7-y), y + (7-y));
BoardPosition bottomRightDest = x > y
? new BoardPosition(x + (7-x), y + (7-x))
: new BoardPosition(x + (7-y), y + (7-y));
toTopLeft.setDestination(startingPosition, topLeftDest, getColor());
toTopRight.setDestination(startingPosition, topRightDest, getColor());
toBottomLeft.setDestination(startingPosition, bottomLeftDest, getColor());
toBottomRight.setDestination(startingPosition, bottomRightDest, getColor());
down.setDestination(startingPosition, new BoardPosition(startingPosition.getColumn(), 7), getColor());
up.setDestination(startingPosition, new BoardPosition(startingPosition.getColumn(), 0), getColor());
right.setDestination(startingPosition, new BoardPosition(7, startingPosition.getRow()), getColor());
left.setDestination(startingPosition, new BoardPosition(0, startingPosition.getRow()), getColor());
possibleMoves.addAll(toTopLeft.getPossibleDestinations(board));
possibleMoves.addAll(toTopRight.getPossibleDestinations(board));
possibleMoves.addAll(toBottomLeft.getPossibleDestinations(board));
possibleMoves.addAll(toBottomRight.getPossibleDestinations(board));
possibleMoves.addAll(down.getPossibleDestinations(board));
possibleMoves.addAll(up.getPossibleDestinations(board));
possibleMoves.addAll(right.getPossibleDestinations(board));
possibleMoves.addAll(left.getPossibleDestinations(board));
return possibleMoves;
}
|
7b6e8bb0-b92c-409b-b655-b8c828a82240
| 9
|
boolean isInsertionValid(int toInsert, int x, int y)
{
//toInsert MUST be between 1 and TABLE_SIZE:
if(toInsert < 1 || toInsert > TABLE_SIZE)
{
return false;
}
//location is not empty
if(table[x][y] != 0)
{
return false;
}
//check column
for(int i = 0; i < TABLE_SIZE; ++i)
{
if(i == x)
continue;
if(table[i][y] == toInsert)
return false;
}
//check row
for(int i = 0; i < TABLE_SIZE; ++i)
{
if(i == y)
continue;
if(table[x][i] == toInsert)
return false;
}
//check small rectangles
return checkSmallRect(toInsert, x, y);
// return true;
}
|
2a63d491-35f0-4606-a77c-ac2a78bc7e17
| 9
|
public settings(){
initialize();
prefl = Preferences.userRoot().node("com.camray.bill.login$1");
db=new DBConnection();
con=db.acquireConnection();
prefs = Preferences.userRoot().node(this.getClass().getName());
tbl=new JTextField(15);
tbl.setText(prefs.getInt("table", 40)+"");
tx=new JTextField(15);
tx.setText(prefs.getInt("tax", 5)+"");
resadpwdf=new JTextField(15);
resusrpwdf=new JTextField(15);
if(!prefl.getBoolean("admin", false)){
tbl.setEditable(false);
tx.setEditable(false);
resadpwdf.setEditable(false);
resusrpwdf.setEditable(false);
}
JPanel panel = new JPanel(new GridBagLayout());
GridBagConstraints gbc = new GridBagConstraints();
gbc.insets = new Insets(2,2,2,2);
//gbc.weighty = 1.0; // allows vertical dispersion
addComponents(new JLabel("Number of Tables:"), tbl, panel, gbc);
addComponents(new JLabel("Tax:"), tx, panel, gbc);
addComponents(new JLabel("Reset Admin Password:"),resadpwdf, panel, gbc);
addComponents(new JLabel("Reset User Password"),resusrpwdf, panel, gbc);
JButton ok=new JButton("OK");
ok.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
// TODO Auto-generated method stub
frame.dispose();
}
});
JButton cancel=new JButton("Cancel");
cancel.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
// TODO Auto-generated method stub
frame.dispose();
}
});
JButton Apply =new JButton("Apply");
Apply.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
// TODO Auto-generated method stub
// TODO Auto-generated method stub
int result = JOptionPane.showConfirmDialog(null,
"Apply Changes?", "Apply?", JOptionPane.YES_NO_OPTION);
if (result == JOptionPane.YES_OPTION) {
//db
String adminp=resadpwdf.getText().toString()+"";
String otherp=resusrpwdf.getText().toString()+"";
if(!adminp.isEmpty()){
if(!(adminp.matches("[a-zA-Z0-9]+"))){
JOptionPane.showMessageDialog(frame,
"Please enter a valid admin password \n" +
"should contain A-Z or 0-9 or a-z only");
}else{
String update="update camry.user_list set password='"+adminp+
"' where user_name=?";
PreparedStatement ps;
try {
ps = con.prepareStatement(update);
ps.setString(1, "admin");
int i=ps.executeUpdate();
con.close();
} catch (SQLException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
}
}
if(!otherp.isEmpty() ){
String newp=prefl.get("user","");
if(!(otherp.matches("[a-zA-Z0-9]+"))){
JOptionPane.showMessageDialog(frame,
"Please enter a valid password for regular user \n" +
"should contain A-Z or 0-9 or a-z only");
}else{
con=db.acquireConnection();
String update="update camry.user_list set password='"+otherp+
"' where user_name=?";
PreparedStatement ps;
try {
ps = con.prepareStatement(update);
ps.setString(1, "user");
int i=ps.executeUpdate();
con.close();
} catch (SQLException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
}
}
setPreference();
} else if (result == JOptionPane.NO_OPTION) {
System.out.println("Do nothing");
}
}
});
panel.add(Apply);
panel.add(ok);
panel.add(cancel);
frame.add(panel);
}
|
76020477-c285-4b52-9971-7852dfd6a7d3
| 2
|
@Override
public void onEnable() {
this.saveDefaultConfig();
listeners.register();
try {
this.getConfig().load(configFile);
} catch (IOException e) {
e.printStackTrace();
} catch (InvalidConfigurationException e) {
e.printStackTrace();
}
Bukkit.getPluginManager().callEvent(new MultikillConfigurationEvent((YamlConfiguration)this.getConfig()));
}
|
e71dcfe7-dfb5-4697-bd5a-b21705f0cf98
| 1
|
public void updateTable() {
if(_table != null) {
_table.putNumber("Value", get()*2/255.0-1);
}
}
|
0bb8bffb-119b-4dc8-8f9f-10e43cfa5f37
| 3
|
public ActionDispatch(View _v) {
this.v=_v;
v.autorize.addActionListener(new ActionListener(){
@Override
public void actionPerformed(ActionEvent e) {
if ((v.port1.getText()!=null)||(v.adress1.getText()!=null)||(v.name.getText()!=null))
{
port=Integer.parseInt(v.port1.getText().trim());
setConnection(v.adress1.getText().trim(),port);
}
}});
}
|
1b781ff4-911c-4303-a300-645cb2579bb9
| 4
|
public static BranchGroup crear(Vector3f posInicial,
tipoFigura tipoFigura,
Float ancho, Float alto, Float largo,
Appearance apariencia,
String urlObjeto, Float escala) throws Exception {
// Creamos el BranchGroup que vamos a devolver
BranchGroup objetoBG = new BranchGroup();
BranchGroup auxBG = new BranchGroup();
if (tipoFigura.equals(tipoFigura.rectangulo)) {
Box cubo = new Box(ancho, alto, largo, apariencia);
cubo.setAppearance(apariencia);
auxBG.addChild(cubo);
objetoBG.addChild(MiLibreria3D.trasladarEstatico(MiLibreria3D.escalarEstatico(auxBG, escala), posInicial));
} else if (tipoFigura.equals(tipoFigura.esfera)) {
Sphere esfera = new Sphere(ancho, apariencia);
esfera.setAppearance(apariencia);
auxBG.addChild(esfera);
objetoBG.addChild(MiLibreria3D.trasladarEstatico(MiLibreria3D.escalarEstatico(auxBG, escala), posInicial));
} else if (tipoFigura.equals(tipoFigura.cilindro)) {
Cylinder cilindro = new Cylinder(ancho, alto, apariencia);
cilindro.setAppearance(apariencia);
auxBG.addChild(cilindro);
objetoBG.addChild(MiLibreria3D.trasladarEstatico(MiLibreria3D.escalarEstatico(auxBG, escala), posInicial));
} else if (tipoFigura.equals(tipoFigura.objetoOBJ)) {
Scene scene = getOBJ(urlObjeto);
objetoBG.addChild(MiLibreria3D.trasladarEstatico(MiLibreria3D.escalarEstatico(scene.getSceneGroup(), escala), posInicial));
} else {
throw new Exception("Error al crear la figura");
}
return objetoBG;
}
|
e69cfa40-3d4e-4565-9efe-6057a6656641
| 9
|
public String[][] getResultSetTable(String where, int pageNo, int rowCount) {
System.out.println("getResultSetTable" + tableNameSup);
String[][] ret = new String[tableFieldSup.length][1]; //col,rowの順
Properties props = new Properties();
props.setProperty("user", rolename);
props.setProperty("password", password);
Connection con = null;
try {
Class.forName("org.postgresql.Driver");
con = DriverManager.getConnection(url, props);
System.out.println("データベースに接続しました。");
//自動コミットを無効にする
//con.setAutoCommit(false);
//ステートメント作成
Statement stmt = con.createStatement(ResultSet.TYPE_SCROLL_SENSITIVE, ResultSet.CONCUR_READ_ONLY);
//列数取得
// ResultSet rs = stmt.executeQuery("SELECT COUNT(*) FROM " + tableNameSup);
// rs.next();
// int rows = rs.getInt("COUNT");
// System.out.println(rows);
//Order by
StringBuilder sb = new StringBuilder();
sb.append(" ORDER BY ");
String sep = "";
for (int i = 0; i < tablePrimarySup.length; i++) {
sb.append(sep);
sb.append(tablePrimarySup[i]);
sep = ",";
}
//行数取得
// String SQL = "SELECT COUNT(*) FROM " + tableNameSup + " " + where + sb.toString();
// logDebug(SQL);
// ResultSet rs = stmt.executeQuery(SQL);
// rs.next();
// int rows = rs.getInt("COUNT");
// System.out.println("rows:" + rows);
// rs.close();
//SQLの実行
String Offset = " LIMIT " + rowCount + " OFFSET " + (rowCount * pageNo);
String SQL = "SELECT * FROM " + tableNameSup + " " + where + sb.toString() + " " + Offset;
logDebug(SQL);
ResultSet rs = stmt.executeQuery(SQL);
/*
rs.setFetchDirection(ResultSet.FETCH_FORWARD);
rs.last();
int rows = rs.getRow() - 1;
rs.setFetchDirection(ResultSet.FETCH_REVERSE);
rs.first();
logDebug("rows:" + rows);
int cols = tableFieldSup.length;
logDebug("cols:" + cols);
//配列の枠を作成
ret = new String[cols][rows + 1]; //タイトル分1行多い
*/
ResultSetMetaData rsmd= rs.getMetaData();
List listRs = new ArrayList();
//配列の枠を作成
String[] wk = new String[rsmd.getColumnCount()];
for (int i = 1; i <= rsmd.getColumnCount(); i++) { //列の数は1から
logDebug("取得RSカラム名:" + rsmd.getColumnName(i));
wk[i - 1] = rsmd.getColumnName(i);
}
listRs.add(wk);
//Data
int idx = 0;
while (rs.next()) {
wk = new String[rsmd.getColumnCount()];
for (int j = 0; j < rsmd.getColumnCount(); j++) {
wk[j] = rs.getString(j + 1);
}
listRs.add(wk);
}
//ArrayListから2次元配列を作成
ret = (String[][])listRs.toArray(new String[0][0]);
printRS(ret);
rs.close();
//ステートメントのクローズ
stmt.close();
//コミットする
//con.commit();
} catch (ClassNotFoundException e) {
System.err.println("JDBCドライバが見つかりませんでした。");
} catch (SQLException e) {
System.err.println("エラーコード : " + e.getSQLState());
System.err.println("エラーメッセージ: " + e.getMessage());
e.printStackTrace();
} catch (Exception e) {
e.printStackTrace();
} finally {
try {
if (con != null) {
con.close();
System.out.println("データベースとの接続を切断しました。");
}
} catch (Exception e) {
e.printStackTrace();
}
}
//ret = sortArray(ret);
return ret;
}
|
908248e7-5c70-4f8a-ad92-e12d821b810b
| 0
|
ENCODE(String value){
this.value = value;
}
|
21e43bdc-f648-4c3c-8833-5272d3b302ac
| 4
|
public List<KrakenMove> actions(String color) {
ArrayList<KrakenMove> moves=new ArrayList<KrakenMove>();
for(int i = 0;i<rowBoard;i++)
for(int j = 0;j<colBoard;j++)
if (board[i][j] != null &&
board[i][j].getColor().equals(color))
addActionsItem(new XYLocation(i,j),moves);
return moves;
}
|
34c00ac8-66e8-47a8-a64a-d3ab0bf79907
| 0
|
public void setLabo(Labo labo) {
this.labo = labo;
}
|
68f94196-2130-475b-a1fd-1d6e2e1edaff
| 4
|
@Override
public String format( Cell cell )
{
// make sure to return the empty string for blank cells
// getting the calendar coerces to double and thus gets zero
if( ((cell instanceof CellHandle) && ((CellHandle) cell).isBlank()) || "".equals( cell.getVal() ) )
{
return "";
}
if( cell.getCellType() == Cell.TYPE_STRING )
{
return String.format( text_format, (String) cell.getVal() );
}
Calendar date = DateConverter.getCalendarFromCell( cell );
return format( date.getTime() );
}
|
598eaf0b-cd24-4583-95ff-b8fd9b923c7c
| 7
|
private E getResult(boolean findMax) {
int index = 0;
Entry<Integer, Double> result = null;
if (findMax == true) {
Iterator<Entry<Integer, Double>> s = fitScores.entrySet().iterator();
for (; s.hasNext(); )
{
Entry<Integer, Double> curr = s.next();
if (result == null)
{
result = curr;
}
else if (curr.getValue() > result.getValue())
{
result = curr;
}
}
} else {
Iterator<Entry<Integer, Double>> s = fitScores.entrySet().iterator();
for (; s.hasNext(); )
{
Entry<Integer, Double> curr = s.next();
if (result == null)
{
result = curr;
}
else if (curr.getValue() < result.getValue())
{
result = curr;
}
}
}
bestFit = currGen.get(result.getKey());
return individual.decode(currGen.get(result.getKey()));
}
|
9ee1a895-8405-465c-9d4b-da798751a9d2
| 5
|
private int[] getBoundaryPositions(ByteBuffer b, byte[] boundary) {
int matchcount = 0;
int matchbyte = -1;
List<Integer> matchbytes = new ArrayList<Integer>();
for (int i = 0; i < b.limit(); i++) {
if (b.get(i) == boundary[matchcount]) {
if (matchcount == 0)
matchbyte = i;
matchcount++;
if (matchcount == boundary.length) {
matchbytes.add(matchbyte);
matchcount = 0;
matchbyte = -1;
}
} else {
i -= matchcount;
matchcount = 0;
matchbyte = -1;
}
}
int[] ret = new int[matchbytes.size()];
for (int i = 0; i < ret.length; i++) {
ret[i] = matchbytes.get(i);
}
return ret;
}
|
bcd307d2-1ca1-49b0-8277-a34ef7392f0e
| 7
|
public GamePanel(final SupportPanel supportPanel, final int numberOfPlayers) {
this.numberOfPlayers = numberOfPlayers;
setLocation(0, 0);
setSize(600, 600);
setLayout(null);
setBackground(Color.BLACK);
this.supportPanel = supportPanel;
map = new HashMap<String, ImageIcon>();
mapInt = new int[getWidth()][getHeight()];
loadMap();
supportPanel.changeLife1(3);
if (numberOfPlayers == 2) {
supportPanel.changeLife2(3);
}
Runnable runnable = new GameRunnable(actionObjectsList, shellList, this, mapInt, supportPanel);
Thread thread = new Thread(runnable);
thread.start();
final JButton keyListener = new JButton();
keyListener.addKeyListener(new KeyListener() {
@Override
public void keyTyped(KeyEvent e) {
}
@Override
public void keyPressed(KeyEvent e) {
if (tank1.getAction(e.getKeyCode())) {
tank1.setActionMove(e.getKeyCode());
tank1.setActionShot(e.getKeyCode());
}
if (numberOfPlayers == 2) {
if (tank2.getAction(e.getKeyCode())) {
tank2.setActionMove(e.getKeyCode());
tank2.setActionShot(e.getKeyCode());
}
}
}
@Override
public void keyReleased(KeyEvent e) {
if (tank1.getAction(e.getKeyCode())) {
tank1.setActionMove(-1);
tank1.setActionShot(-1);
}
if (numberOfPlayers == 2) {
if (tank2.getAction(e.getKeyCode())) {
tank2.setActionMove(-1);
tank2.setActionShot(-1);
}
}
}
});
add(keyListener);
setVisible(true);
}
|
d1f1dae3-d0f3-4777-b3e4-40ec4f3426a2
| 0
|
public static void main(String[] args) {
int x = 1, y = 1;
int a = 0, b = 0;
x++; ++y;
System.out.println("a = " + a + ", b = " + b + ", x = " + x + ", y = " + y);
//a = 0, b = 0, x = 2, y = 2
a = x++; b = ++y;
System.out.println("a = " + a + ", b = " + b + ", x = " + x + ", y = " + y);
//a = 2, b = 3, x = 3, y = 3
a = x--; b = --y;
System.out.println("a = " + a + ", b = " + b + ", x = " + x + ", y = " + y);
//a = 3, b = 2, x = 2, y = 2
}
|
af9cc985-f476-439b-8aba-c984f803edf1
| 7
|
private void setupShells(HashMap<String, String> shells) {
String sh = "";
String shclassstr = "";
// temporary storage for fully qualified classnames,
// serves the purpose of not loading classes twice.
HashMap<String, Class<?>> shellclasses = new HashMap<String, Class<?>>(shells.size());
for (Iterator<String> iter = shells.keySet().iterator(); iter.hasNext();) {
try {
// first we get the key
sh = iter.next();
// then the fully qualified shell class string
Object obj = shells.get(sh);
if (obj instanceof Shell) {
log.debug("shell [" + sh + "] already instanciated");
this.shells.put(sh, obj);
continue;
}
shclassstr = (String) obj;
log.debug("Preparing Shell [" + sh + "] " + shclassstr);
// now we check if the class is already loaded.
// If,then we reference the same class object and thats it
if (shellclasses.containsKey(shclassstr)) {
this.shells.put(sh, shellclasses.get(shclassstr));
log.debug("Class [" + shclassstr + "] already loaded, using cached class object.");
} else {
// we get the class object (e.g. load it because its new)
Class<?> shclass = Class.forName(shclassstr);
// and put it to the shells, plus our "class object cache"
this.shells.put(sh, shclass);
shellclasses.put(shclassstr, shclass);
log.debug("Class [" + shclassstr + "] loaded and class object cached.");
}
} catch (Exception e) {
log.error("setupShells()", e);
}
}
}// setupShells
|
ddb1a21d-5615-453c-a8d4-4224ad8d9b51
| 4
|
public void Displaymessage(String msg) {
boolean test = false;
if (test || m_test) {
System.out.println("GameWindow :: Displaymessage() BEGIN");
}
getDrawing().Message(msg);
if (test || m_test) {
System.out.println("GameWindow :: Displaymessage() END");
}
}
|
7604a4b6-357a-4464-af72-db8df92d8ed0
| 5
|
public static void conexion()
{
try
{
connection = DriverManager.getConnection("jdbc:sqlite:usuarios.db");
statement = connection.createStatement();
try
{
statement.executeUpdate("create table usuarios (Telefono string, Nombre string, Apellido1 string, Apellido2 string, Nick string, Contrasenya string )");
}
catch (SQLException e)
{
if (!e.getMessage().equals("table usuarios already exists"))
e.printStackTrace();
}
try
{
statement.executeUpdate("create table amigos (Telefono1 string, Telefono2 string, Nombre1 string, Nombre2 string)");
}
catch (SQLException e)
{
if (!e.getMessage().equals("table amigos already exists"))
e.printStackTrace();
}
}
catch (SQLException e)
{
e.printStackTrace();
}
}
|
3c58c3c3-fedf-4f0a-b758-7d0c82b019be
| 2
|
@Override
public int compareTo(Player otherPlayer) {
if (otherPlayer == null)
throw new IllegalArgumentException("The given arguments are invalid!");
final int res = Integer.compare(this.playerNumber, otherPlayer.playerNumber);
if (res == 0)
return Integer.compare(this.getRemainingActions(), otherPlayer.remainingActions);
return res;
}
|
cebc915f-e0b5-46d0-943c-5371e3529141
| 0
|
public String getUrl() {
return url;
}
|
3b0f5685-d7f0-4db6-9f1b-d14b5cf42d76
| 1
|
public void setGaussianKernelWidth(int gaussianKernelWidth) {
if (gaussianKernelWidth < 2)
throw new IllegalArgumentException();
this.gaussianKernelWidth = gaussianKernelWidth;
}
|
edfce40c-c746-43da-8a4b-12c4481d426b
| 7
|
@Override
public void executeMsg(final Environmental myHost, final CMMsg msg)
{
super.executeMsg(myHost,msg);
if((msg.source().location()!=null)
&&(msg.targetMinor()==CMMsg.TYP_DAMAGE)
&&((msg.value())>0)
&&(msg.tool()==this)
&&(msg.target() instanceof MOB))
{
final int chance = (int)Math.round(Math.random() * 20.0);
if(chance == 10)
{
final Ability poison = CMClass.getAbility("Poison");
if(poison!=null)
poison.invoke(msg.source(),(MOB)msg.target(), true,phyStats().level());
}
}
}
|
21e856a5-f200-4a64-841d-125eef8202e9
| 7
|
public static void startupModules() {
{ Object old$Module$000 = Stella.$MODULE$.get();
Object old$Context$000 = Stella.$CONTEXT$.get();
try {
Native.setSpecial(Stella.$MODULE$, Stella.$STELLA_MODULE$);
Native.setSpecial(Stella.$CONTEXT$, ((Module)(Stella.$MODULE$.get())));
if (Stella.currentStartupTimePhaseP(2)) {
_StartupModules.helpStartupModules1();
}
if (Stella.currentStartupTimePhaseP(4)) {
Stella.$SUBCONTEXT_REVISION_POLICY$ = Stella.KWD_CLEAR;
Stella.$SHADOWEDSURROGATES$.setDefaultValue(null);
Stella.$DEFINE_MODULE_HOOKS$ = HookList.newHookList();
Stella.$MODULE_NON_STRUCTURAL_OPTIONS$ = Cons.cons(Stella.KWD_DOCUMENTATION, Stella.NIL);
}
if (Stella.currentStartupTimePhaseP(5)) {
Stella.defineStellaTypeFromStringifiedSource("(DEFTYPE NAME OBJECT)");
}
if (Stella.currentStartupTimePhaseP(6)) {
Stella.finalizeClasses();
}
if (Stella.currentStartupTimePhaseP(7)) {
_StartupModules.helpStartupModules2();
Stella.defineFunctionObject("ALL-CONTEXTS", "(DEFUN (ALL-CONTEXTS (ITERATOR OF CONTEXT)) () :PUBLIC? TRUE :DOCUMENTATION \"Return an iterator that generates all contexts.\")", Native.find_java_method("edu.isi.stella.Stella", "allContexts", new java.lang.Class [] {}), null);
Stella.defineFunctionObject("FILTER-MODULE?", "(DEFUN (FILTER-MODULE? BOOLEAN) ((SELF OBJECT) (ITERATOR ALL-PURPOSE-ITERATOR)))", Native.find_java_method("edu.isi.stella.Stella_Object", "filterModuleP", new java.lang.Class [] {Native.find_java_class("edu.isi.stella.Stella_Object"), Native.find_java_class("edu.isi.stella.AllPurposeIterator")}), null);
Stella.defineFunctionObject("ALL-MODULES", "(DEFUN (ALL-MODULES (ITERATOR OF MODULE)) () :PUBLIC? TRUE :DOCUMENTATION \"Return an iterator that generates all modules.\")", Native.find_java_method("edu.isi.stella.Stella", "allModules", new java.lang.Class [] {}), null);
Stella.defineFunctionObject("LIST-MODULES", "(DEFUN (LIST-MODULES (CONS OF MODULE)) ((KB-ONLY? BOOLEAN)) :PUBLIC? TRUE :COMMAND? TRUE :DOCUMENTATION \"Returns a cons of all modules defined in PowerLoom. If `kb-only?'\nis `true', then any modules which are code only or just namespaces are not returned.\")", Native.find_java_method("edu.isi.stella.Stella", "listModules", new java.lang.Class [] {java.lang.Boolean.TYPE}), Native.find_java_method("edu.isi.stella.Cons", "listModulesEvaluatorWrapper", new java.lang.Class [] {Native.find_java_class("edu.isi.stella.Cons")}));
Stella.defineFunctionObject("ALL-INCLUDED-MODULES", "(DEFUN (ALL-INCLUDED-MODULES (ITERATOR OF MODULE)) ((SELF MODULE)) :PUBLIC? TRUE :DOCUMENTATION \"Generate a sequence of all modules included\nby 'self', inclusive, starting from the highest ancestor and working\ndown to 'self' (which is last).\")", Native.find_java_method("edu.isi.stella.Module", "allIncludedModules", new java.lang.Class [] {Native.find_java_class("edu.isi.stella.Module")}), null);
Stella.defineFunctionObject("VISIBLE-MODULES", "(DEFUN (VISIBLE-MODULES (CONS OF MODULE)) ((FROM MODULE)) :DOCUMENTATION \"Return a list of all modules visible from module `from' (or `*module*'\nif `from' is NULL. The generated modules are generated from most to\nleast-specific and will start with the module `from'.\" :PUBLIC? TRUE)", Native.find_java_method("edu.isi.stella.Module", "visibleModules", new java.lang.Class [] {Native.find_java_class("edu.isi.stella.Module")}), null);
Stella.defineFunctionObject("HELP-MEMOIZE-VISIBLE-MODULES", "(DEFUN (HELP-MEMOIZE-VISIBLE-MODULES (CONS OF MODULE)) ((FROM MODULE)))", Native.find_java_method("edu.isi.stella.Module", "helpMemoizeVisibleModules", new java.lang.Class [] {Native.find_java_class("edu.isi.stella.Module")}), null);
Stella.defineFunctionObject("CARDINAL-MODULE?", "(DEFUN (CARDINAL-MODULE? BOOLEAN) ((SELF MODULE)))", Native.find_java_method("edu.isi.stella.Module", "cardinalModuleP", new java.lang.Class [] {Native.find_java_class("edu.isi.stella.Module")}), null);
Stella.defineFunctionObject("VISIBLE-FROM?", "(DEFUN (VISIBLE-FROM? BOOLEAN) ((VIEWEDCONTEXT CONTEXT) (FROMCONTEXT CONTEXT)) :PUBLIC? TRUE)", Native.find_java_method("edu.isi.stella.Context", "visibleFromP", new java.lang.Class [] {Native.find_java_class("edu.isi.stella.Context"), Native.find_java_class("edu.isi.stella.Context")}), null);
Stella.defineFunctionObject("CLEAR-ONE-CONTEXT", "(DEFUN CLEAR-ONE-CONTEXT ((SELF CONTEXT)))", Native.find_java_method("edu.isi.stella.Context", "clearOneContext", new java.lang.Class [] {Native.find_java_class("edu.isi.stella.Context")}), null);
Stella.defineFunctionObject("HELP-CLEAR-CONTEXT", "(DEFUN HELP-CLEAR-CONTEXT ((SELF CONTEXT)))", Native.find_java_method("edu.isi.stella.Context", "helpClearContext", new java.lang.Class [] {Native.find_java_class("edu.isi.stella.Context")}), null);
Stella.defineFunctionObject("CLEAR-CONTEXT", "(DEFUN CLEAR-CONTEXT ((SELF CONTEXT)) :PUBLIC? TRUE :DOCUMENTATION \"Destroy all objects belonging to 'self' or any of its subcontexts.\")", Native.find_java_method("edu.isi.stella.Context", "clearContext", new java.lang.Class [] {Native.find_java_class("edu.isi.stella.Context")}), null);
Stella.defineFunctionObject("CALL-CLEAR-MODULE", "(DEFUN CALL-CLEAR-MODULE (|&REST| (NAME NAME)) :PUBLIC? TRUE :COMMAND? TRUE :EVALUATE-ARGUMENTS? TRUE :LISP-MACRO? FALSE :DOCUMENTATION \"Destroy all objects belonging to module `name' or any of its children.\nIf no `name' is supplied, the current module will be cleared after\nconfirming with the user. Important modules such as STELLA are protected\nagainst accidental clearing.\")", Native.find_java_method("edu.isi.stella.Stella", "callClearModule", new java.lang.Class [] {Native.find_java_class("edu.isi.stella.Cons")}), Native.find_java_method("edu.isi.stella.Cons", "callClearModuleEvaluatorWrapper", new java.lang.Class [] {Native.find_java_class("edu.isi.stella.Cons")}));
Stella.defineFunctionObject("CLEAR-MODULE", "(DEFUN CLEAR-MODULE (|&REST| (NAME NAME)) :PUBLIC? TRUE :COMMAND? TRUE :EVALUATE-ARGUMENTS? FALSE :DOCUMENTATION \"Destroy all objects belonging to module `name' or any of its children.\nIf no `name' is supplied, the current module will be cleared after\nconfirming with the user. Important modules such as STELLA are protected\nagainst accidental clearing.\")", Native.find_java_method("edu.isi.stella.Stella", "clearModule", new java.lang.Class [] {Native.find_java_class("edu.isi.stella.Cons")}), Native.find_java_method("edu.isi.stella.Cons", "clearModuleEvaluatorWrapper", new java.lang.Class [] {Native.find_java_class("edu.isi.stella.Cons")}));
Stella.defineFunctionObject("STARTUP-MODULES", "(DEFUN STARTUP-MODULES () :PUBLIC? TRUE)", Native.find_java_method("edu.isi.stella._StartupModules", "startupModules", new java.lang.Class [] {}), null);
{ MethodSlot function = Symbol.lookupFunction(Stella.SYM_STELLA_STARTUP_MODULES);
KeyValueList.setDynamicSlotValue(function.dynamicSlots, Stella.SYM_STELLA_METHOD_STARTUP_CLASSNAME, StringWrapper.wrapString("_StartupModules"), Stella.NULL_STRING_WRAPPER);
}
}
if (Stella.currentStartupTimePhaseP(8)) {
Stella.finalizeSlots();
Stella.cleanupUnfinalizedClasses();
}
if (Stella.currentStartupTimePhaseP(9)) {
Stella_Object.inModule(((StringWrapper)(Stella_Object.copyConsTree(StringWrapper.wrapString("STELLA")))));
Stella.defineStellaGlobalVariableFromStringifiedSource("(DEFGLOBAL *SUBCONTEXT-REVISION-POLICY* KEYWORD :CLEAR :DOCUMENTATION \"Controls actions reflexive transitive closure of\n subcontexts when a context is revised.\n Values are ':destroy' -- destroy subcontexts;\n ':clear' -- clear contents of subcontexts;\n ':preserve' -- don't disturb subcontexts.\")");
Stella.defineStellaGlobalVariableFromStringifiedSource("(DEFSPECIAL *SHADOWEDSURROGATES* (CONS OF SYMBOL) NULL :DOCUMENTATION \"Holds list of symbols representing surrogates\nto be shadowed during module finalization.\")");
Stella.defineStellaGlobalVariableFromStringifiedSource("(DEFGLOBAL *DEFINE-MODULE-HOOKS* HOOK-LIST (NEW HOOK-LIST) :DOCUMENTATION \"HOOK-LIST called by 'define-module', applied to a\n'module' argument.\")");
Stella.defineStellaGlobalVariableFromStringifiedSource("(DEFGLOBAL *MODULE-NON-STRUCTURAL-OPTIONS* (CONS OF KEYWORD) (BQUOTE (:DOCUMENTATION)) :PUBLIC? FALSE :DOCUMENTATION \"List of non-structural options for Module definitions.\nUsed in testing for module changes and in updating non-structurally changed\nmodules.\")");
KeyValueList.setDynamicSlotValue(Stella.$ROOT_MODULE$.dynamicSlots, Stella.SYM_STELLA_CLEARABLEp, Stella.FALSE_WRAPPER, Stella.FALSE_WRAPPER);
KeyValueList.setDynamicSlotValue(Stella.$STELLA_MODULE$.dynamicSlots, Stella.SYM_STELLA_CLEARABLEp, Stella.FALSE_WRAPPER, Stella.FALSE_WRAPPER);
KeyValueList.setDynamicSlotValue(Stella.$COMMON_LISP_MODULE$.dynamicSlots, Stella.SYM_STELLA_CLEARABLEp, Stella.FALSE_WRAPPER, Stella.FALSE_WRAPPER);
}
} finally {
Stella.$CONTEXT$.set(old$Context$000);
Stella.$MODULE$.set(old$Module$000);
}
}
}
|
bba3c758-6912-47ed-98ae-ad1279116ae5
| 8
|
private void node() {
// Grab the string up to the colon
int start = position;
for (char c = current(); hasNext(); c = next()) {
if (c == ':') break;
if (c == '#') error("Illegal character in key. The pound sign # is reserved for comments.");
}
// Verify that there is, in fact, a colon now
if (current() != ':') {
position = line.replaceAll("\\s+$", "").length(); // Trim trailing whitespace
error("A key must always be followed by a colon.");
}
// If so, extract the key string.
String key = line.substring(start, position);
// Add the tokens
stream.add(new KeyToken(key, line, lineCount, start));
stream.add(new ColonToken(line, lineCount, position));
// If no more symbols, or only whitespace, return
if (!hasNext() || isRestWhitespace()) {
return;
}
// Otherwise, advance past the colon, and require a space
if (next() != ' ') {
error("There must be a space between the colon and the value.");
}
// Advance past the space
next();
// Consume the remaining part of the line, and trim off whitespace
start = position;
String value = consume().trim();
// If it's just whitespace, ignore it
if (value.length() == 0) {
return;
}
// Otherwise, make a value token
stream.add(new ValueToken(value, line, lineCount, start));
}
|
f3c90edb-dc7b-4a60-8271-c397f482697f
| 3
|
private void addRelatedTag(ArrayList<Integer> tagList) {
for (int tag : tagList) {
if (!selectedTags.contains(tag) && !relatedTags.contains(tag)) {
relatedTags.add(tag);
}
}
}
|
14ee0ba5-ea9a-4597-8b45-74043659d0e4
| 3
|
private static void addFileToTarGz(TarArchiveOutputStream tOut, String path, String base) throws IOException {
File f = new File(path);
String entryName = base + f.getName();
TarArchiveEntry tarEntry = new TarArchiveEntry(f, entryName);
tOut.setLongFileMode(TarArchiveOutputStream.LONGFILE_GNU);
tOut.putArchiveEntry(tarEntry);
if (f.isFile()) {
IOUtils.copy(new FileInputStream(f), tOut);
tOut.closeArchiveEntry();
} else {
tOut.closeArchiveEntry();
File[] children = f.listFiles();
if (children != null) {
for (File child : children) {
addFileToTarGz(tOut, child.getAbsolutePath(), entryName + "/");
}
}
}
}
|
f40d7319-d11a-4116-b385-b2e3e352c731
| 1
|
public void playGame(ArrayList<Player> players, Dealer dealer, int numPlayers){
initialDeal(players, dealer, numPlayers);
updatePlayers(players, dealer, numPlayers);
checkForWin(players,dealer,numPlayers);
while (winner.isEmpty()){
moreDeals(players, dealer, numPlayers);
}
PlayAgain();
}
|
fcf9fbea-a53e-4dc9-a27a-74eb23ddfb9e
| 3
|
public boolean playGenerateScriptFile(String device, String host,
String port, String path, String name) {
serialNumber = device;
ClientManipulationScript.host = host;
ClientManipulationScript.port = port;
File fOutputDir = new File(path);
if (!fOutputDir.exists()) {
fOutputDir.mkdirs();
}
outputFile = path + File.separator + name;
File f = new File(outputFile);
if (!f.exists()) {
try {
out = new BufferedWriter(new FileWriter(outputFile));
return true;
} catch (IOException e) {
e.printStackTrace();
}
}
return false;
}
|
6e80fb4b-cd13-44d9-bc7b-921748e8924f
| 5
|
@Override
public void run() {
try {
String line;
while ((line = this.in.readLine()) != null) {
int space_pos = line.indexOf(" ");
if (space_pos != -1) {
try {
Object obj = this.decodeData(line.substring(space_pos + 1));
this.execute(line.substring(0, space_pos), obj);
} catch (Exception e) {
System.out.println(e.getMessage());
}
}
}
} catch (Exception e) {
System.out.println(e.getMessage());
} finally {
try {
JOptionPane.showMessageDialog(null, "Connexion perdue !");
socket.close();
} catch (IOException e) {
System.out.println(e.getMessage());
}
}
}
|
22532c62-f8a9-4fb9-b75d-272e1bffe607
| 6
|
public boolean onCommand(CommandSender sender, Command command,
String label, String[] args) {
if (!plugin.hasPerm(sender, "spawnmob", false)) {
sender.sendMessage(ChatColor.YELLOW
+ "You do not have permission to use /" + label);
return true;
}
Player player = (Player) sender;
int[] ignore = { 8, 9 };
Location loc = (new AimBlock(player, 300, 0.2, ignore))
.getTargetBlock().getLocation();
loc.setY(1.5 + loc.getY());
if (args.length == 1) {
EntityType ct = this.getType(args[0], sender);
if (ct != null) {
player.getWorld().spawnEntity(loc, ct);
player.sendMessage(CraftEssence.premessage
+ "You have spawned a " + ct.getName());
} else {
sender.sendMessage(CraftEssence.premessage
+ "creature not found.");
}
return true;
}
if (args.length == 2) {
EntityType ct = this.getType(args[0], sender);
int ammount = Integer.parseInt(args[1]);
if (ct != null) {
for (int i = 0; i < ammount; i++) {
player.getWorld().spawnEntity(loc, ct);
}
player.sendMessage(CraftEssence.premessage
+ "You have spawned " + ammount + " " + ct.getName()
+ "'s");
} else {
sender.sendMessage(CraftEssence.premessage
+ "creature not found.");
}
return true;
}
return false;
}
|
b4d42032-b8e8-4ada-b23d-dfa99ae61ec9
| 7
|
public static String doubleToString(double d) {
if (Double.isInfinite(d) || Double.isNaN(d)) {
return "null";
}
// Shave off trailing zeros and decimal point, if possible.
String string = Double.toString(d);
if (string.indexOf('.') > 0 && string.indexOf('e') < 0
&& string.indexOf('E') < 0) {
while (string.endsWith("0")) {
string = string.substring(0, string.length() - 1);
}
if (string.endsWith(".")) {
string = string.substring(0, string.length() - 1);
}
}
return string;
}
|
77c5f5d5-54bd-4d90-b671-91e9249f8149
| 7
|
@Override
public String format(LogRecord arg) {
String resultat = "";
Level lvl = arg.getLevel();
if (lvl.equals(Level.CONFIG)) {
resultat += "<tr class=\"config\">";
}
if (lvl.equals(Level.WARNING)) {
resultat += "<tr class=\"warning\">";
}
if (lvl.equals(Level.INFO)) {
resultat += "<tr class=\"info\">";
}
if (lvl.equals(Level.SEVERE)) {
resultat += "<tr class=\"severe\">";
}
if (lvl.equals(Level.FINE)) {
resultat += "<tr class=\"fine\">";
}
if (lvl.equals(Level.FINEST)) {
resultat += "<tr class=\"finest\">";
}
resultat += "<td>" + arg.getSourceClassName() + "</td>";
if (arg.getSourceMethodName().equals("<init>")) {
resultat += "<td>Constructeur</td>";
} else {
resultat += "<td>" + arg.getSourceMethodName() + "</td>";
}
resultat += "<td>" + arg.getMessage() + "</td></tr>\n";
return resultat;
}
|
828fc510-4b5c-4878-b18f-166a69e33cde
| 6
|
private void requestHitStay(Player activePlayer, Dealer dealer, DeckInterface deck,
Message mg) {
if (activePlayer.getHand().getValue() == 21){
mg.displayMessage(12);
}
//loops while not busted
while (activePlayer.getHand().getValue() < 21){
String input = null;
//hit or stay message
mg.displayMessage(5 ,
activePlayer.getHand().getValue());
try{
//collect response from user
input = ms.nextLine().toUpperCase();
//hit logic
if (input.equals("H")) {
mg.displayMessage(8);
dealer.drawCardToHand(activePlayer.getHand(), deck);
setHandValue(activePlayer.getHand(), dealer, deck);
}else if (input.equals("S")) {
mg.displayMessage(11);
break;
}
}catch(NumberFormatException e){
//let loop repeat
}
//player bust
if (activePlayer.getHand().getValue() > 21){
mg.displayMessage(10);
}
activePlayer.getHand().printHand(deck);
mg.displayMessage(6,
activePlayer.getHand().getValue());
}
}
|
3503e781-6e62-45c4-9cdf-078ee0925e00
| 6
|
public static void main(String args[]) {
/* Set the Nimbus look and feel */
//<editor-fold defaultstate="collapsed" desc=" Look and feel setting code (optional) ">
/* If Nimbus (introduced in Java SE 6) is not available, stay with the default look and feel.
* For details see http://download.oracle.com/javase/tutorial/uiswing/lookandfeel/plaf.html
*/
try {
for (javax.swing.UIManager.LookAndFeelInfo info : javax.swing.UIManager.getInstalledLookAndFeels()) {
if ("Nimbus".equals(info.getName())) {
javax.swing.UIManager.setLookAndFeel(info.getClassName());
break;
}
}
} catch (ClassNotFoundException ex) {
java.util.logging.Logger.getLogger(excepWind.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (InstantiationException ex) {
java.util.logging.Logger.getLogger(excepWind.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (IllegalAccessException ex) {
java.util.logging.Logger.getLogger(excepWind.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (javax.swing.UnsupportedLookAndFeelException ex) {
java.util.logging.Logger.getLogger(excepWind.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
}
//</editor-fold>
/* Create and display the dialog */
java.awt.EventQueue.invokeLater(new Runnable() {
public void run() {
excepWind dialog = new excepWind(new javax.swing.JFrame(), true,"exc");
dialog.addWindowListener(new java.awt.event.WindowAdapter() {
@Override
public void windowClosing(java.awt.event.WindowEvent e) {
System.exit(0);
}
});
dialog.setVisible(true);
}
});
}
|
b8ba666c-1400-42aa-ae7d-d0d1c0e40350
| 8
|
public static int checksMultiples(int[][] numberArray, int rowNumber, int columnNumber){
int largestProduct = 0;
int sum = 0;
//checks vertical, horizontal, and diagonal
try {
sum = numberArray[rowNumber][columnNumber]*numberArray[rowNumber][columnNumber+1]*numberArray[rowNumber][columnNumber+2]*numberArray[rowNumber][columnNumber+3];
largestProduct = isLargest(sum,largestProduct);
}
catch (ArrayIndexOutOfBoundsException e) {
}
try {
sum = numberArray[rowNumber][columnNumber]*numberArray[rowNumber][columnNumber-1]*numberArray[rowNumber][columnNumber-2]*numberArray[rowNumber][columnNumber-3];
largestProduct = isLargest(sum,largestProduct);
}
catch (ArrayIndexOutOfBoundsException e) {
}
try {
sum = numberArray[rowNumber][columnNumber]*numberArray[rowNumber+1][columnNumber]*numberArray[rowNumber+2][columnNumber]*numberArray[rowNumber+3][columnNumber];
largestProduct = isLargest(sum,largestProduct);
}
catch (ArrayIndexOutOfBoundsException e) {
}
try {
sum = numberArray[rowNumber][columnNumber]*numberArray[rowNumber-1][columnNumber]*numberArray[rowNumber-2][columnNumber]*numberArray[rowNumber-3][columnNumber];
largestProduct = isLargest(sum,largestProduct);
}
catch (ArrayIndexOutOfBoundsException e) {
}
try {
sum = numberArray[rowNumber][columnNumber]*numberArray[rowNumber+1][columnNumber+1]*numberArray[rowNumber+2][columnNumber+2]*numberArray[rowNumber+3][columnNumber+3];
largestProduct = isLargest(sum,largestProduct);
}
catch (ArrayIndexOutOfBoundsException e) {
}
try {
sum = numberArray[rowNumber][columnNumber]*numberArray[rowNumber-1][columnNumber-1]*numberArray[rowNumber-2][columnNumber-2]*numberArray[rowNumber-3][columnNumber-3];
largestProduct = isLargest(sum,largestProduct);
}
catch (ArrayIndexOutOfBoundsException e) {
}
try {
sum = numberArray[rowNumber][columnNumber]*numberArray[rowNumber-1][columnNumber+1]*numberArray[rowNumber-2][columnNumber+2]*numberArray[rowNumber-3][columnNumber+3];
largestProduct = isLargest(sum,largestProduct);
}
catch (ArrayIndexOutOfBoundsException e) {
}
try {
sum = numberArray[rowNumber][columnNumber]*numberArray[rowNumber+1][columnNumber-1]*numberArray[rowNumber+2][columnNumber-2]*numberArray[rowNumber+3][columnNumber-3];
largestProduct = isLargest(sum,largestProduct);
}
catch (ArrayIndexOutOfBoundsException e) {
}
return largestProduct;
}
|
68ae248a-91b3-40a1-878c-e8cdcedfa026
| 5
|
public void paint(Graphics g) {
g.setColor(Color.WHITE);
g.fillRect(0, 0, getWidth(), getHeight());
Ball[] balls = model.getBalls();
MyBall myBall = model.getMyBall();
for(int i = 0; i < balls.length; i++){
if(!balls[i].isDead){
g.setColor(colors[i]);
g.fillOval(balls[i].getX(), balls[i].getY(),
balls[i].BALL_SIZE, balls[i].BALL_SIZE);
}
else{
int red = (colors[i].getRed() + 5 >= 255)? 255: colors[i].getRed() + 5;
int blue = (colors[i].getBlue() + 5 >= 255)? 255: colors[i].getBlue() + 5;
int green = (colors[i].getGreen() + 5 >= 255)? 255: colors[i].getGreen() + 5;
colors[i] = new Color(red, green, blue);
g.setColor(colors[i]);
g.fillOval(balls[i].getX(), balls[i].getY(),
balls[i].BALL_SIZE, balls[i].BALL_SIZE);
}
}
g.setColor(Color.black);
g.fillOval(myBall.getX(), myBall.getY(),
myBall.BALL_SIZE, myBall.BALL_SIZE);
g.drawString(String.format("Time: %4.1fs", (double)(elapsedTime) / 1000), 720, 20);
}
|
3261920d-d242-4dfc-94a1-a56c1ebfd1e4
| 8
|
private void postPlugin(Plugin plugin, boolean isPing) throws IOException {
// The plugin's description file containg all of the plugin data such as name, version, author, etc
PluginDescriptionFile description = plugin.getDescription();
// Construct the post data
String data = encode("guid") + '=' + encode(guid)
+ encodeDataPair("version", description.getVersion())
+ encodeDataPair("server", Bukkit.getVersion())
+ encodeDataPair("players", Integer.toString(Bukkit.getServer().getOnlinePlayers().length))
+ encodeDataPair("revision", String.valueOf(REVISION));
// If we're pinging, append it
if (isPing) {
data += encodeDataPair("ping", "true");
}
// Add any custom data available for the plugin
Set<Graph> graphs = getOrCreateGraphs(plugin);
// Acquire a lock on the graphs, which lets us make the assumption we also lock everything
// inside of the graph (e.g plotters)
synchronized(graphs) {
Iterator<Graph> iter = graphs.iterator();
while (iter.hasNext()) {
Graph graph = iter.next();
// Because we have a lock on the graphs set already, it is reasonable to assume
// that our lock transcends down to the individual plotters in the graphs also.
// Because our methods are private, no one but us can reasonably access this list
// without reflection so this is a safe assumption without adding more code.
for (Plotter plotter : graph.getPlotters()) {
// The key name to send to the metrics server
// The format is C-GRAPHNAME-PLOTTERNAME where separator - is defined at the top
// Legacy (R4) submitters use the format Custom%s, or CustomPLOTTERNAME
String key = String.format("C%s%s%s%s", CUSTOM_DATA_SEPARATOR, graph.getName(), CUSTOM_DATA_SEPARATOR, plotter.getColumnName());
// The value to send, which for the foreseeable future is just the string
// value of plotter.getValue()
String value = Integer.toString(plotter.getValue());
// Add it to the http post data :)
data += encodeDataPair(key, value);
}
}
}
// Create the url
URL url = new URL(BASE_URL + String.format(REPORT_URL, plugin.getDescription().getName()));
// Connect to the website
URLConnection connection;
// Mineshafter creates a socks proxy, so we can safely bypass it
// It does not reroute POST requests so we need to go around it
if (isMineshafterPresent()) {
connection = url.openConnection(Proxy.NO_PROXY);
} else {
connection = url.openConnection();
}
connection.setDoOutput(true);
// Write the data
OutputStreamWriter writer = new OutputStreamWriter(connection.getOutputStream());
writer.write(data);
writer.flush();
// Now read the response
BufferedReader reader = new BufferedReader(new InputStreamReader(connection.getInputStream()));
String response = reader.readLine();
// close resources
writer.close();
reader.close();
if (response.startsWith("ERR")) {
throw new IOException(response); //Throw the exception
} else {
// Is this the first update this hour?
if (response.contains("OK This is your first update this hour")) {
synchronized (graphs) {
Iterator<Graph> iter = graphs.iterator();
while (iter.hasNext()) {
Graph graph = iter.next();
for (Plotter plotter : graph.getPlotters()) {
plotter.reset();
}
}
}
}
}
//if (response.startsWith("OK")) - We should get "OK" followed by an optional description if everything goes right
}
|
895529f7-cd19-4eef-89c0-6290e75e484e
| 4
|
public void print(AbstractPiece [][] chessboard){
int x = 8;
System.out.println(" \tA\tB\tC\tD\tE\tF\tG\tH");
for(int row = 0; row < chessboard.length; row++){
System.out.print(x);
x--;
for(int column = 0; column < chessboard[0].length; column++){
if(chessboard[row][column] == EMPTY)
{if((row + column) % 2== 0)System.out.print("\t#");
else chessboard[row][column].draw();
}
else
chessboard[row][column].draw();
}
System.out.println();
}
}
|
fc9fea17-460f-4100-a011-56907ca63446
| 6
|
public int cellToOffset(int row, int col) {
// Check row and column individually to prevent them being invalid
// values but still pointing to a valid offset in the buffer.
if (row<0 || row>=getRowCount() ||
col<0 || col>15) { // Don't include last column (ascii dump)
return -1;
}
int offs = row*16 + col;
return (offs>=0 && offs<model.getByteCount()) ? offs : -1;
}
|
2f22b5b2-ae34-4244-9f40-b03a3712bd44
| 9
|
public static boolean areCompatible(Class a, Class b) {
if (a.isAssignableFrom(b)) return true;
if (a == Integer.class && b == int.class) return true;
if (a == int.class && b == Integer.class) return true;
if (a == BigDecimal.class && b == Integer.class) return true;
if (a == Integer.class && b == BigDecimal.class) return true;
return false;
}
|
73897759-4165-4647-a97a-e8a986845974
| 4
|
@Override
public void init()
{
super.init();
rwFirst = ByteTools.readShort( getByteAt( 0 ), getByteAt( 1 ) );
rwLast = ByteTools.readShort( getByteAt( 2 ), getByteAt( 3 ) );
colFirst = (short) getByteAt( 4 );
colLast = (short) getByteAt( 5 );
cchFile = ByteTools.readShort( getByteAt( 6 ), getByteAt( 7 ) );
if( cchFile > 0 )
{
//A - fHighByte (1 bit): A bit that specifies whether the characters in rgb are double-byte characters.
// 0x0 All the characters in the string have a high byte of 0x00 and only the low bytes are in rgb.
// 0x1 All the characters in the string are saved as double-byte characters in rgb.
// reserved (7 bits): MUST be zero, and MUST be ignored.
byte encoding = getByteAt( 8 );
refType = getByteAt( 9 ); // 1= simple-file-path-dcon 2= self-reference
if( refType != 2 ) // TODO: handle external refs ...
{
log.warn( "PivotTable: External Data Sources are not supported" );
}
byte[] tmp = getBytesAt( 10, (cchFile - 1) * (encoding + 1) );
try
{
if( encoding == 0 )
{
fileName = new String( tmp, DEFAULTENCODING );
}
else
{
fileName = new String( tmp, UNICODEENCODING );
}
}
catch( UnsupportedEncodingException e )
{
log.warn( "encoding PivotTable name in DCONREF: " + e, e );
}
}
log.debug( "DCONREF: rwFirst:" + rwFirst + " rwLast:" + rwLast + " colFirst:" + colFirst + " colLast:" + colLast + " cchFile:" + cchFile + " fileName:" + fileName );
}
|
287b30dd-c859-4463-8527-9077572515ce
| 5
|
public void printIterative(JTreeNode n){
final Deque<JTreeNode<T>> nodeTracker = new ArrayDeque<>();
nodeTracker.push(n);
while(!nodeTracker.isEmpty()){
while(n.getLeftNode()!= null && !n.getLeftNode().isVisited()) {
nodeTracker.push(n.getLeftNode());
n = n.getLeftNode();
}
System.out.println(n.getValue());
n.setVisited(true);
nodeTracker.pop();
if(n.getRightNode()!=null && !n.getRightNode().isVisited()){
nodeTracker.push(n.getRightNode());
}
n = nodeTracker.peek();
}
}
|
530619a6-d512-4421-bf7d-966c79dd17ff
| 9
|
protected String separateExternalScripts(String script) {
// externalScripts.clear();
// when external blocks intertwine with mouse blocks, they will be reduced to "external #". When
// they are passed to the mouse callback, setScript(String) will be called, which subsequently
// calls this method. If we clear the externalScripts map every time, then the "external #" stored
// in the previous setScript call will be lost.
if (script == null)
return null;
String lowerCase = script.toLowerCase();
int beg = lowerCase.indexOf("beginexternal");
int end = lowerCase.indexOf("endexternal");
int beg0 = -1;
byte index = 0;
while (beg != -1 && end != -1) {
String s = script.substring(beg + 14, end).trim();
externalScripts.put(index++, s);
beg0 = beg;
beg = lowerCase.indexOf("beginexternal", end);
if (beg0 == beg) // infinite loop
break;
end = lowerCase.indexOf("endexternal", beg);
}
String[] split = script.split("(?i)(beginexternal|endexternal)[\\s&&[^\\r\\n]]*;");
int n = split.length;
for (int i = 0; i < n; i++)
split[i] = split[i].trim();
int m = 0;
for (Byte x : externalScripts.keySet()) {
for (int i = m; i < n; i++) {
if (split[i].equals(externalScripts.get(x))) {
split[i] = "external " + x + ";";
m = i + 1;
}
}
}
script = "";
for (String s : split) {
script += s;
}
return script;
}
|
4c6dd945-33cd-4ae1-ba8b-8e0f8dbd52d8
| 9
|
protected void processOtherEvent(Sim_event ev)
{
switch ( ev.get_tag() )
{
case GridSimTags.SEND_AR_CREATE:
case GridSimTags.SEND_AR_CREATE_IMMEDIATE:
handleCreateReservation(ev);
break;
case GridSimTags.SEND_AR_COMMIT_ONLY:
handleCommitOnly(ev);
break;
case GridSimTags.SEND_AR_COMMIT_WITH_GRIDLET:
handleCommitReservation(ev);
break;
case GridSimTags.SEND_AR_CANCEL:
handleCancelReservation(ev);
break;
case GridSimTags.SEND_AR_QUERY:
handleQueryReservation(ev);
break;
case GridSimTags.SEND_AR_MODIFY:
handleModifyReservation(ev);
break;
case GridSimTags.SEND_AR_LIST_BUSY_TIME:
case GridSimTags.SEND_AR_LIST_FREE_TIME:
handleQueryTime(ev);
break;
default:
/**** // NOTE: Give to the scheduler to process other tags
System.out.println(super.get_name() + ".processOtherEvent(): " +
"Unable to handle request from GridSimTags with " +
"tag number " + ev.get_tag() );
*****/
super.policy_.processOtherEvent(ev);
break;
}
}
|
fab95a17-0b44-4a9e-8f7d-bab1ab64016e
| 6
|
public boolean equals( Object other ) {
if ( _set.equals( other ) ) {
return true; // comparing two trove sets
} else if ( other instanceof Set ) {
Set that = ( Set ) other;
if ( that.size() != _set.size() ) {
return false; // different sizes, no need to compare
} else { // now we have to do it the hard way
Iterator it = that.iterator();
for ( int i = that.size(); i-- > 0; ) {
Object val = it.next();
if ( val instanceof Long ) {
long v = ( ( Long ) val ).longValue();
if ( _set.contains( v ) ) {
// match, ok to continue
} else {
return false; // no match: we're done
}
} else {
return false; // different type in other set
}
}
return true; // all entries match
}
} else {
return false;
}
}
|
092c4882-a271-4fba-84f2-e6a5f01fd22c
| 2
|
private int testaaPystyrivi(Piste p0) {
Piste p1 = new Piste(p0.getX(), p0.getY() - hahmonKorkeus);
for (int i = 0; i < hahmonKorkeus; i++) {
if (testaaPiste(p1)) {
break;
}
p1.siirra(0, 1);
}
return p0.getY() - p1.getY();
}
|
20e42ad7-b204-440a-9065-df7cbb7768dd
| 7
|
public RequestLauncher(){
InputStream stream = null;
try
{
DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
factory.setValidating(true);
factory.setIgnoringElementContentWhitespace(true);
DocumentBuilder builder = factory.newDocumentBuilder();
stream = new FileInputStream("./Queries/queries.xml");
NodeList requestListAsNode = builder.parse(stream).getElementsByTagName("text");
requestList = new String[requestListAsNode.getLength()];
for(int index = 0; index < requestListAsNode.getLength(); index++)
requestList[index] = requestListAsNode.item(index).getTextContent().trim();
} catch (ParserConfigurationException e) {
e.printStackTrace();
} catch (FileNotFoundException e) {
System.out.println("Queries file not found");
} catch (SAXException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
finally{
if(stream != null){
try {
stream.close();
}
catch (IOException e){
e.printStackTrace();
}
}
}
}
|
7b853970-7dcc-4fe7-bbdb-7c27fb0ebf1c
| 8
|
private void fixUpdateFile(String updatesFilename) throws IOException {
File original = new File(updatesFilename);
FileReader fr = new FileReader(original);
BufferedReader br = new BufferedReader(fr);
File converted = new File(updatesFilename + ".converted");
FileWriter fwr = new FileWriter(converted);
BufferedWriter bwr = new BufferedWriter(fwr);
String update = br.readLine();
while (update != null) {
String str = update;
for (int i = 1; i <= 2; i++) { // go to peer AS
str = str.substring(str.indexOf("|") + 1);
}
String updateType = str.substring(0, str.indexOf("|"));
if (updateType.equals("W")) { // there is no way to determine
// correct AS for prefix withdrawals
// as there is no AS Path
bwr.write(update);
bwr.newLine();
update = br.readLine();
continue;
}
for (int i = 1; i <= 2; i++) { // go to peer AS
str = str.substring(str.indexOf("|") + 1);
}
// convert peerAS name to integer
int peerAS = Integer.parseInt(str.substring(0, str.indexOf("|")));
// go to AS Path
str = str.substring(str.indexOf("|") + 1);
str = str.substring(str.indexOf("|") + 1);
int firstASinASPath;
if ((str.indexOf(" ") == -1) || (str.indexOf(" ") > 5)) { // in case
// when
// there
// is
// only
// 1 AS
// in AS
// path
firstASinASPath = Integer.parseInt(str.substring(0,
str.indexOf("|")));
} else {
firstASinASPath = Integer.parseInt(str.substring(0,
str.indexOf(" ")));
}
// compare peerAS with first AS in AS Path
if (peerAS != firstASinASPath) {
update = update.replaceFirst(String.valueOf(peerAS),
String.valueOf(firstASinASPath));
}
// write fixed update
bwr.write(update);
bwr.newLine();
// read next line
update = br.readLine();
}
fr.close();
bwr.close();
fwr.close();
// rename original file to .old
File old = new File(updatesFilename + ".old");
if (old.exists()) {
throw new IOException("file " + updatesFilename
+ ".old already exists!");
} else {
original.renameTo(old);
// and then rename .converted to original
converted.renameTo(original);
}
}
|
bb8cb9b8-b297-44c8-997b-4667d2ed87c3
| 6
|
public static void main(String args[]) {
/* Set the Nimbus look and feel */
//<editor-fold defaultstate="collapsed" desc=" Look and feel setting code (optional) ">
/* If Nimbus (introduced in Java SE 6) is not available, stay with the default look and feel.
* For details see http://download.oracle.com/javase/tutorial/uiswing/lookandfeel/plaf.html
*/
try {
for (javax.swing.UIManager.LookAndFeelInfo info : javax.swing.UIManager.getInstalledLookAndFeels()) {
if ("Nimbus".equals(info.getName())) {
javax.swing.UIManager.setLookAndFeel(info.getClassName());
break;
}
}
} catch (ClassNotFoundException ex) {
java.util.logging.Logger.getLogger(Frm_ConEmpresa.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (InstantiationException ex) {
java.util.logging.Logger.getLogger(Frm_ConEmpresa.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (IllegalAccessException ex) {
java.util.logging.Logger.getLogger(Frm_ConEmpresa.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (javax.swing.UnsupportedLookAndFeelException ex) {
java.util.logging.Logger.getLogger(Frm_ConEmpresa.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
}
//</editor-fold>
/* Create and display the form */
java.awt.EventQueue.invokeLater(new Runnable() {
public void run() {
new Frm_ConEmpresa().setVisible(true);
}
});
}
|
48d87613-a2e4-4dce-a5e1-a5abfe511f91
| 7
|
public static List<Class<?>> processDirectory(File directory, String pkgname) {
ArrayList<Class<?>> classes = new ArrayList<Class<?>>();
log("Reading Directory '" + directory + "'");
// Get the list of the files contained in the package
String[] files = directory.list();
for (int i = 0; i < files.length; i++) {
String fileName = files[i];
String className = null;
// we are only interested in .class files
if (fileName.endsWith(".class")) {
// removes the .class extension
className = pkgname + '.' + fileName.substring(0, fileName.length() - 6);
}
log("FileName '" + fileName + "' => class '" + className + "'");
if (className != null) {
classes.add(loadClass(className));
}
//If the file is a directory recursively class this method.
File subdir = new File(directory, fileName);
if (subdir.isDirectory()) {
classes.addAll(processDirectory(subdir, pkgname + '.' + fileName));
}
}
return classes;
}
|
1114dc4e-7a4d-49db-8cf1-fe628c904439
| 2
|
public POP3Server(){
sTrace = new SystemTrace();
sTrace.setDebug(Proxy.DEBUG);
internAccounts.put("collector", "123");
int counter = 0; // Z�hlt die erzeugten Bearbeitungs-Threads
try {
/* Server-Socket erzeugen */
welcomeSocket = new ServerSocket(POP3_TEST_PORT_NUMBER);
while (true) { // Server laufen IMMER
sTrace.debug("TCP Server: Waiting for connection - listening TCP port "
+ POP3_TEST_PORT_NUMBER);
/*
* Blockiert auf Verbindungsanfrage warten --> nach
* Verbindungsaufbau Standard-Socket erzeugen und
* connectionSocket zuweisen
*/
connectionSocket = welcomeSocket.accept();
/* Neuen Arbeits-Thread erzeugen und den Socket �bergeben */
threadPool.execute(new POP3ServerThread(++counter, connectionSocket,
internAccounts));
}
} catch (IOException e) {
sTrace.error(e.toString());
}
}
|
cb3a7f67-5734-47b9-ac8e-23f877ea570e
| 8
|
private void notCriticalMove() {
int center = gameField.getFieldSize()/2;
if(!gameField.isFill(center,center)){
gameField.putO(center,center);
}
else {
if(checkVerticalWin(2)) {
finishVerticalLine(criticalVertical,1);
}
if (checkHorizontalWin(2)) {
finishHorizontalLine(criticalHorizontal,1);
}
if(checkLeftDiagonalWin(2)) {
finishLeftDiagonal(1);
}
if(checkRightDiagonalWin(2)) {
finishRightDiagonal(1);
}
else {
int x = 0;
int y = 0;
while (gameField.isFill(x,y)) {
if(x < gameField.getFieldSize() - 1) {
x++;
}
else if(y <= gameField.getFieldSize() - 1) {
x = 0;
y++;
}
}
gameField.putO(x,y);
}
}
}
|
441aa68e-d9e9-4aec-b17e-a96b61783d4a
| 0
|
@Override
public void focusGained(final FocusEvent e) {
JTextField tf = (JTextField) e.getComponent();
tf.selectAll();
oldValue = tf.getText();
}
|
a9d917ba-8182-44ab-b62e-337a93cf8cbe
| 8
|
public WorldPanel(World world) {
this.model = world;
this.worldMap = model.getWorldMap();
this.worldGUI = new WorldNodePanel[4][4];
try {
gold = ImageIO.read(new File("src/main/resources/images/gold2.png"));
pit = ImageIO.read(new File("src/main/resources/images/pit2.png"));
wumpus = ImageIO.read(new File("src/main/resources/images/wumpus2.png"));
hunter = ImageIO.read(new File("src/main/resources/images/hunter2.png"));
empty = ImageIO.read(new File("src/main/resources/images/default.png"));
} catch (IOException ex) {
// handle exception...
if(log.isLoggable(Logger.WARNING))
log.log(Logger.WARNING, ex.getMessage().toString());
}
this.setBorder(new TitledBorder(null, "World", TitledBorder.LEADING, TitledBorder.TOP, null, null));
// this.setBounds(10, 10, 350, 350);
this.setBounds(0, 0, 350, 350);
this.setPreferredSize(new Dimension(350,350));
gbl = new GridBagLayout();
gbl.columnWidths = new int[]{25, 75, 75, 75, 75, 0};
gbl.rowHeights = new int[]{80, 75, 75, 75, 14, 0};
gbl.columnWeights = new double[]{0.0, 0.0, 0.0, 0.0, 0.0, Double.MIN_VALUE};
gbl.rowWeights = new double[]{0.0, 0.0, 0.0, 0.0, 0.0, Double.MIN_VALUE};
this.setLayout(gbl);
label = new JLabel("x");
label.setHorizontalAlignment(SwingConstants.CENTER);
gbc = new GridBagConstraints();
gbc.anchor = GridBagConstraints.NORTHWEST;
gbc.insets = new Insets(5, 5, 0, 0);
gbc.gridx = 1;
gbc.gridy = 4;
this.add(label, gbc);
//x-Label (horizontal)
for (int i=0; i<4;i++) {
label = new JLabel(""+(i+1));
gbc = new GridBagConstraints();
gbc.anchor = GridBagConstraints.NORTH;
gbc.fill = GridBagConstraints.HORIZONTAL;
gbc.insets = new Insets(5, 5, 0, 0);
gbc.gridx = i+1;
gbc.gridy = 4;
this.add(label, gbc);
label.setHorizontalAlignment(SwingConstants.CENTER);
}
label = new JLabel("y");
gbc = new GridBagConstraints();
gbc.anchor = GridBagConstraints.SOUTH;
gbc.fill = GridBagConstraints.HORIZONTAL;
gbc.insets = new Insets(5, 5, 0, 0);
gbc.gridx = 0;
gbc.gridy = 3;
this.add(label, gbc);
label.setHorizontalAlignment(SwingConstants.CENTER);
//y-Label (vertical)
for (int j=0; j<4;j++) {
label = new JLabel(""+(j+1));
gbc = new GridBagConstraints();
gbc.fill = GridBagConstraints.BOTH;
if (j==0)
gbc.insets = new Insets(10, 5, 0, 0);
else
gbc.insets = new Insets(5, 5, 0, 0);
gbc.gridx = 0;
gbc.gridy = ((j+4)-(j*2)-1);
this.add(label, gbc);
label.setHorizontalAlignment(SwingConstants.CENTER);
}
for (int i=0; i<4; i++) {
for (int j=0; j<4; j++) {
worldGUI[i][j] = new WorldNodePanel(gold);
gbc = new GridBagConstraints();
gbc.fill = GridBagConstraints.BOTH;
if(j==3)
gbc.insets = new Insets(10, 5, 0, 0);
else
gbc.insets = new Insets(5, 5, 0, 0);
gbc.gridx = i+1;//1;
gbc.gridy = ((j+4)-(j*2)-1);
this.add(worldGUI[i][j], gbc);
}
}
setValues(worldMap);
model.addWorldModelListener(new WorldModelListener() {
public void worldModelChanged(final WorldNode[][] world) {
setValues(world);
}
});
}
|
94758d88-ed49-4cba-9294-1eea8c95c956
| 7
|
public Tile(String type){
id = type;
if(type.equals("G")){
tileType = TileType.GRASS;
grassTiles++;
}
else if(type.equals("V")){
tileType = TileType.VOID;
voidTiles++;
}
else if(type.equals("S")){
tileType = TileType.SPAWN;
spawnTiles++;
}
else if(type.equals("E")){
tileType = TileType.EXPLOSIUM;
resources = 2;
explosiumTiles++;
}
else if(type.equals("R")){
tileType = TileType.RUBIDIUM;
resources = 2;
rubidiumTiles++;
}
else if(type.equals("C")){
tileType = TileType.SCRAP;
resources = 2;
scrapTiles++;
}
else if(type.equals("O")){
tileType = TileType.ROCK;
rockTiles++;
}
else {
Debug.error("Error: Unknown tile type '" + type + "'");
}
totalTiles++;
}
|
f1fc0c1e-2bba-44b8-8a88-57b8153b08b7
| 6
|
private void computeCanBeAvail(final ExprInfo exprInfo) {
final Iterator blocks = cfg.nodes().iterator();
// Go through every PHI-statement of the exprInfo.
while (blocks.hasNext()) {
final Block block = (Block) blocks.next();
final Phi phi = exprInfo.exprPhiAtBlock(block);
if (phi == null) {
continue;
}
if (!phi.canBeAvail()) {
continue;
}
if (phi.downSafe()) {
continue;
}
final Iterator e = cfg.preds(block).iterator();
// We determined above that:
// 1. This PHI-statement is not down safe
// 2. It is currently can be available
// Now, if one of the PHI-statement's operands is tack (null),
// reset "can be avail" for this PHI-statement.
while (e.hasNext()) {
final Block pred = (Block) e.next();
final Def operand = phi.operandAt(pred);
if (operand == null) {
resetCanBeAvail(exprInfo, phi);
break;
}
}
}
}
|
316c7b8e-37a3-485e-9464-7a7a1263bf1d
| 4
|
public String addStation(String stationName) throws IOException {
String message = "";
log.debug("Start method \"addStation\"");
if (stationName == null || "".equals(stationName)) {
message = "Введите название станции";
return message;
}
List<String> allStation = getAllStation();
if (allStation.contains(stationName)) {
log.debug("Send AddStationRespondInfo to client with STATION_ALREADY_EXISTS");
message = "Станция с таким названием уже существует";
return message;
}
Station station = new Station(stationName);
if (!stationDAO.saveStation(station)) {
log.debug("Send AddStationRespondInfo to client with SERVER_ERROR_STATUS");
message = "Server error status";
return message;
} else {
log.debug("Send AddStationRespondInfo to client with OK_STATUS");
message = "Станция успешно добавлена";
return message;
}
}
|
ff76c466-a3b6-4671-a8db-9904dff9e0a8
| 3
|
private int getLastActivity(ASPlayer data, TableType table) {
switch(table) {
case DAY: return data.lastDay.activity;
case WEEK: return data.lastWeek.activity;
case MONTH: return data.lastMonth.activity;
default: plugin.severe("Invalid Type in getLastActivity");
}
return 0;
}
|
ebd997a1-4903-4901-a475-03f76cf4a178
| 9
|
public static Field loadFieldFromFile(){
Field field = null;
int wigth;
int height;
int[][] bombs;
int[][] visibleCells = null;
int[][] flags = null;
try (FileInputStream inpFile = new FileInputStream(DEFAULT_SAVE_PATH)) {
int flag = inpFile.read();
String s = "";
while (flag != -1){
s += (char) flag;
flag = inpFile.read();
}
// Получем массив загружемых элементов и проверяем его размер
String[] loadedElements = s.split(GLOBAL_SPLITTER);
if (loadedElements.length < MIN_ELEMENT_COUNT || loadedElements.length > MAX_ELEMENT_COUNT){
throw new IOException(FILE_STRUCTURE_ERROR);
}
// Обработаем ширину
wigth = Integer.parseInt(getValueFromString(loadedElements, PREF_WIGHT));
// Обработаем высоту
height = Integer.parseInt(getValueFromString(loadedElements, PREF_HEIGHT));
// Обработаем массив с бомбами
String bombStr = getValueFromString(loadedElements, PREF_BOMBS);
bombs = stringToCoordArray(bombStr);
// Обработаем открытиые ячейки если они есть
String visibleStr = getValueFromString(loadedElements, PREF_VISIBLE, false);
if (visibleStr != null) {
visibleCells = stringToCoordArray(visibleStr);
}
// Обработаем флаги если они есть
String flagStr = getValueFromString(loadedElements, PREF_FLAG, false);
if (flagStr != null) {
flags = stringToCoordArray(flagStr);
}
if (visibleCells != null) {
field = new Field(height, wigth, bombs, visibleCells);
} else {
field = new Field(height, wigth, bombs);
}
if (flags != null) {
field.setFlag(flags);
}
System.out.println(DEFAULT_READ_FILE_SUCCESS);
} catch (NumberFormatException e){
System.out.println(FILE_VALUE_ERROR);
} catch (Exception e) {
System.out.println(DEFAULT_READ_FILE_ERROR);
System.out.println(e.getMessage());
}
return field;
}
|
29007637-3c33-4235-99c6-8922b649065d
| 5
|
public void run() {
long lastTime = System.nanoTime();
double unprocessed = 0;
double nsPerTick = 1000000000.0 / 60;
int frames = 0;
int ticks = 0;
long lastTimer1 = System.currentTimeMillis();
init();
while (running) {
long now = System.nanoTime();
boolean shouldRender = false;
unprocessed += (now - lastTime) / nsPerTick;
lastTime = now;
while (unprocessed >= 1) {
ticks++;
update(1 / 60.);
unprocessed -= 1;
shouldRender = true;
}
if (shouldRender) {
frames++;
draw();
}
try {
Thread.sleep(2);
} catch (InterruptedException e) {
e.printStackTrace();
}
if (System.currentTimeMillis() - lastTimer1 > 1000) {
lastTimer1 += 1000;
System.out.println(ticks + " ticks, " + frames + " fps");
frames = 0;
ticks = 0;
}
}
}
|
55cbfe4d-506c-49c3-a4f4-9acdde15e8bc
| 0
|
private void swap(int[] array, int left, int right){
int temp = array[left];
array[left] = array[right];
array[right] = temp;
}
|
c2e69399-557b-4a18-a0e6-6add5881cee1
| 9
|
private Tuple<Integer, Integer> computeResizeBox(int cssWidth,
int cssHeight, FSImage fsImage) {
if (cssWidth == -1 && cssHeight == -1) {
return null;
}
int newWidth = -1;
int newHeight = fsImage.getHeight();
// Downsize an maintain aspect ratio...
if (fsImage.getWidth() > cssWidth && cssWidth > -1) {
newWidth = cssWidth;
newHeight = (newWidth * fsImage.getHeight()) / fsImage.getWidth();
}
if (cssHeight > -1 && newHeight > cssHeight) {
newHeight = cssHeight;
newWidth = (newHeight * fsImage.getWidth()) / fsImage.getHeight();
}
// No resize required
if (newWidth == -1) {
return null;
}
// No upscaling!
if (newWidth > fsImage.getWidth() || newWidth > fsImage.getHeight()) {
return null;
}
return new Tuple<Integer, Integer>(newWidth, newHeight);
}
|
a335aecd-901b-4421-bb2d-bfc3ad99957f
| 0
|
public static void main( String[] args ) {
System.out.println("Hello item2!");
BuilderPattern bp = new BuilderPattern.Builder("Readme of item2", "2nd day")
.location("Toronto")
.pageno(80)
.build();
System.out.println(bp.val(99));
System.out.println(bp.val());
}
|
82b8be5a-e6d7-41f3-b440-5e4b1d7c1d14
| 3
|
@Override
public void execute(CommandSender arg0, String[] arg1) {
if(arg0.hasPermission("bungeesuite.whois")){
if(arg1.length>0){
if(PlayerManager.playerExists(arg1[0])){
PlayerManager.getPlayerInformation(arg0, arg1[0]);
}else{
arg0.sendMessage(Messages.PLAYER_DOES_NOT_EXIST);
}
}else{
arg0.sendMessage("/whois (player/nick)");
}
}else{
arg0.sendMessage(Messages.NO_PERMISSION);
}
}
|
8b708667-724e-4c28-a3b1-7084ac3d434c
| 3
|
public void rotate() {
shape = block.rotate();
point.setLocation(location);
// Check if by rotating we've gone out of bounds, and make corrections
while (point.x + shape.getMinX() < 0) { point.translate(1, 0); }
while (point.x + shape.getMaxX() >= pane.getCols()) { point.translate(-1, 0); }
// Check and make sure we're not rotating into any previously placed blocks
if (assertLegal(pane, shape, point, block, location)) {
free();
block = block.rotate();
location.setLocation(point);
calcShadowDrop();
draw();
}
}
|
56262d90-260d-48d2-84f0-a04973b688fd
| 5
|
public CollisionBox getCollisionBox() {
if(box == null) {
box = new ComplexShape();
if(hasNorthWall()) {
box.addShape(new Rectangle(this.getPosition().getX(), this.getPosition().getY() -
0.05f, 1f, 0.1f));
}
if(hasWestWall()) {
box.addShape(new Rectangle(this.getPosition().getX() - 0.05f,
this.getPosition().getY(), 0.1f, 1f));
}
for(int i = 0; i < this.props.size(); i++) {
box.addShape(props.get(i).getCollisionBox());
}
}
if(box.getLines().size() == 0) {
return null;
}else{
return box;
}
}
|
6be6f431-e994-4ced-9c85-dfc637456c13
| 6
|
public void addTotal(FacWarStat stat) {
if (stat instanceof CharacterKills) {
characterKillsTotal.add((CharacterKills) stat);
} else if (stat instanceof CharacterVictoryPoints) {
characterVictoryPointsTotal.add((CharacterVictoryPoints) stat);
} else if (stat instanceof CorporationKills) {
corporationKillsTotal.add((CorporationKills) stat);
} else if (stat instanceof CorporationVictoryPoints) {
corporationVictoryPointsTotal.add((CorporationVictoryPoints) stat);
} else if (stat instanceof FactionKills) {
factionKillsTotal.add((FactionKills) stat);
} else if (stat instanceof FactionVictoryPoints) {
factionVictoryPointsTotal.add((FactionVictoryPoints) stat);
}
}
|
cb829e46-3a46-4d9f-98e7-eb12fed47833
| 7
|
public void drawPieces() {
/* Iterate over pieces here */
/* xCoord and yCoord points start at the top left corner with (0,0)
* and go to the bottom left corner with (n,m) where n and m are the
* x and y dimensions of the board, respectively */
if (game != null) {
for (int i = 0; i < yBoardDim; i++) {
for (int j = 0; j < xBoardDim; j++) {
Piece.Type pT = game.board.array[i][j].type;
int xOutputPoint = xGridMin + (xSpacing * (j));
int yOutputPoint = yGridMin + (ySpacing * (i));
if (pT == Piece.Type.WHITE) {
drawPiece(pieceType.WHITE, xOutputPoint, yOutputPoint);
} else if (pT == Piece.Type.BLACK) {
drawPiece(pieceType.BLACK, xOutputPoint, yOutputPoint);
} else if ((pT == Piece.Type.BLACKSACRIFICE) ||
(pT == Piece.Type.WHITESACRIFICE)) {
drawPiece(pieceType.SACRIFICED, xOutputPoint, yOutputPoint);
} else {
continue;
}
}
}
}
}
|
994d90ad-a33c-4268-84aa-5052d7e430c6
| 2
|
public void secondDFSwithG() {// nodesSortedbyFt is in f(n) increasing
// order, so get from the last
for (int fromNode = totalNumNodes - 1; fromNode > 0; fromNode--) {
curLeader = nodesSortedbyFt[fromNode];
// if not explored then go ahead, otherwise break
if (!nodesStatus.get(curLeader)) {
// curLeader = nodesSortedbyFt[fromNode]; // is 1 less than real
// node No.
// create the list with current node as leader
sccsOfLeader.put(curLeader, new LinkedList<Integer>());
DFSforG(curLeader);
}
}
}
|
9e33bf0d-9000-446b-8efa-3e9d0a2d056c
| 4
|
private void templateWithWordList( String wikiText, String templateId ) {
int idx = findTemplate( wikiText, templateId );
if( idx < 0 ) {
return;
}
int endIdx = wikiText.indexOf( '}', idx );
if( endIdx < 0 ) {
return;
}
String wordStr = wikiText.substring( idx, endIdx );
String[] words = wordStr.split( "\\|" );
for( int w = 0; w < words.length; w++ ) {
String word = words[w];
word = word.trim();
if( !isValidWord( word ) ) {
continue;
}
addWord( word );
}
}
|
6a5d5b1c-02a7-435e-9f4a-4d06f524d083
| 3
|
public int readLatestLoginId(String playerName) {
int idLogin = 0;
try {
ResultSet rs = _sqLite.query("SELECT login.* FROM player, login "
+ "WHERE player.playername = '" + playerName + "' "
+ "AND player.id = login.id_player "
+ "ORDER BY login.time_login DESC LIMIT 1;");
if (rs.next()) {
try {
idLogin = rs.getInt("id");
} catch (SQLException e) {
e.printStackTrace();
}
}
} catch (SQLException e) {
e.printStackTrace();
}
return idLogin;
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.