text stringlengths 14 410k | label int32 0 9 |
|---|---|
public static void cp(String srcPath, String dstPath) {
FileChannel in = null;
FileChannel out = null;
FileInputStream inStream = null;
FileOutputStream outStream = null;
try {
inStream = new FileInputStream(srcPath);
outStream = new FileOutputStream(dstPath);
in = inStream.getChannel();
out = outStream.getChannel();
in.transferTo(0, in.size(), out);
} catch (IOException e) {
e.printStackTrace();
} finally {
try {
if (inStream != null)
inStream.close();
} catch (IOException e) {
e.printStackTrace();
}
try {
if (in != null)
in.close();
} catch (IOException e) {
e.printStackTrace();
}
try {
if (outStream != null)
outStream.close();
} catch (IOException e) {
e.printStackTrace();
}
try {
if (out != null)
out.close();
} catch (IOException e) {
e.printStackTrace();
}
}
} | 9 |
public CtMethod[] getDeclaredMethods() {
CtMember.Cache memCache = getMembers();
CtMember mth = memCache.methodHead();
CtMember mthTail = memCache.lastMethod();
int num = CtMember.Cache.count(mth, mthTail);
CtMethod[] cms = new CtMethod[num];
int i = 0;
while (mth != mthTail) {
mth = mth.next();
cms[i++] = (CtMethod)mth;
}
return cms;
} | 1 |
@Override
protected void paintComponent(Graphics g) {
super.paintComponent(g);
int currentY = 0;
for (AccordionRootItem menu : getMenus()) {
menu.setSize(this.getWidth(), this.menusSize);
menu.setLocation(0, currentY);
if (menu == lastSelectedMenu && !menu.isSelected()) {
currentY += this.menusSize;
menu.getBranchPanel().setSize(this.getWidth(), this.hidingSize);
menu.getBranchPanel().setLocation(0, currentY);
currentY += this.hidingSize;
}
if (menu.isSelected()) {
currentY += this.menusSize;
menu.getBranchPanel().adjustItems(freeAvaiableRows);
menu.getBranchPanel().setSize(this.getWidth(), this.showingSize);
menu.getBranchPanel().setLocation(0, currentY);
currentY += this.showingSize;
} else if (!menu.isSelected() && menu != lastSelectedMenu) {
menu.getBranchPanel().setSize(0, 0);
currentY += this.menusSize;
}
}
update();
} | 6 |
private void writebuttonMouseClicked(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_writebuttonMouseClicked
// TODO add your handling code here:
String address=writeaddress.getText();
int addr=dec.NumberParser(address);
int val=dec.NumberParser(writevalue.getText());
if(addr != -100000 && val!= -100000){
mm.writeMemory(addr, val%256);
writeaddress.setText(""+addr%65536);
}else{
writeaddress.setText("0");
writevalue.setText("0");
}
}//GEN-LAST:event_writebuttonMouseClicked | 2 |
private GameState carpenterDay(GameState state, Card card)
{
Color faction = card.getFaction();
if(state.getPlayer(faction).checkCPU())
{
HashMap<GameState, String> choiceMap = dayActionWithPhrases(state, card);
GameState choice = state.getPlayer(faction)
.chooseState(choiceMap.keySet().toArray(new GameState[0]), card);
state.log(choiceMap.get(choice));
return choice;
}
else
{
while(true)
{
Player p = state.getPlayer(faction);
if(p.getDen().isEmpty()) //there are no pirates in the den to recruit
{
state.log("The Recruiter (" + card.abbreviate() +
") had nobody to recruit");
return state;
}
Card choice = p.getGUI().makeChoice("Choose one of these cards to recruit from your den:",
p.getDen().toArray(new Card[0]));
for(Card c : p.getDen())
{
if(c.equals(choice)) //we remove the card chosen and add it back to the hand
{
state.log("The Recruiter (" + card.abbreviate() +
") recruited " + c.abbreviate() + " from " + Faction.getPirateName(faction) +
"'s den to their hand");
state.getPlayer(faction).removeFromDen(c);
c.resetPhases();
state.getPlayer(faction).addToHand(c);
return state;
}
}
}
}
} | 5 |
private void igual() throws Exception{
op2 = pila.pop();
if (op2.getValor().equals("null"))
throw new Exception("Una de las variables esta sin inicializar!");
op1 = pila.pop();
if (op1.getValor().equals("null"))
throw new Exception("Una de las variables esta sin inicializar!");
Elem resultado = new Elem("boolean");
if(op1.getTipo().equals("boolean"))
{
int b1 = ((Boolean)op1.getValor()).booleanValue() ? 1 : 0;
int b2 = ((Boolean)op2.getValor()).booleanValue() ? 1 : 0;
resultado.setValor(b1 == b2);
}
else if(op1.getTipo().equals("character"))
resultado.setValor((((Character)op1.getValor()).charValue() == ((Character)op2.getValor()).charValue()));
else //Real, Entero o Natural
{
double f1 = op1.getTipo().equals("float")? (Double)op1.getValor() : ((Integer)op1.getValor()).doubleValue();
double f2 = op2.getTipo().equals("float")? (Double)op2.getValor() : ((Integer)op2.getValor()).doubleValue();
resultado.setValor(f1 == f2);
}
pila.push(resultado);
} | 8 |
@Override
protected void download() throws Exception {
int currPage = 1;
boolean hasPrev = true;
while(currPage <= this.totalPages && hasPrev) {
String url = String.format(Constant.VOA_AS_IT_IS_URL, currPage);
Util.print("Fetching info from %s...", url);
Document doc = Util.getConnection(url).get();
if (doc != null) {
Element divContainer = doc.getElementById("ctl00_ctl00_cpAB_cp1_repeaterListDivContent");
Element divPaging = divContainer.getElementById("ctl00_ctl00_cpAB_cp1_upperInfoContent");
Element prevElement = divPaging.select("span[class=prev]").first();
Util.print("prev-page: %s", prevElement);
hasPrev = (prevElement != null);
Elements divArticles = divContainer.select("div[class=archive_rowmm]");
for (Element article: divArticles) {
Element a = article.select("a[href]").first();
if (a != null) {
try {
this.getDetails(a.attr("href"));
} catch(Exception e0) {
Util.print("+++ Something's wrong. Retry #1.");
try {
this.getDetails(a.attr("href"));
} catch(Exception e1) {
Util.print("+++ Something's wrong. Retry #2.");
try {
this.getDetails(a.attr("href"));
} catch(Exception e2) {
Util.print("+++ Something's wrong. Retry #3.");
try {
this.getDetails(a.attr("href"));
} catch(Exception e3) {
throw e3;
}
}
}
}
}
}
}
Util.print("Done info from %s...", url);
currPage++;
}
} | 9 |
@Override
public String toString() {
return "SkillRating [ skillId=" + skillId
+ ", ratingId=" + ratingId + ", givenBy=" + givenBy + "]";
} | 0 |
public int getMachineIndexByName(String machineFileName){
ArrayList machines = getEnvironment().myObjects;
if(machines == null) return -1;
for(int k = 0; k < machines.size(); k++){
Object current = machines.get(k);
if(current instanceof Grammar){
Grammar cur = (Grammar)current;
if(cur.getFileName().equals(machineFileName)){
return k;
}
}
}
return -1;
} | 4 |
public void setModel(String value) {
this.model = value;
} | 0 |
public void WorldDone() {
gameaction = gameaction_t.ga_worlddone;
if (secretexit)
players[consoleplayer].didsecret = true;
if (isCommercial()) {
switch (gamemap) {
case 15:
case 31:
if (!secretexit)
break;
case 6:
case 11:
case 20:
case 30:
F.StartFinale();
break;
}
}
} | 9 |
public static QuadTree compressImage (int[][] image) {
if (image == null) {
throw new IllegalArgumentException();
} else if (image.length != image[0].length) {
throw new IllegalArgumentException();
} else if (!((image.length & (image.length - 1)) == 0)) { //checks if power of 2
throw new IllegalArgumentException();
}
//case where image is 1x1
if (image.length == 1) {
return new QuadTree(new QuadNode(image[0][0], 1));
} else if (image.length == 2) {
QuadNode root = getQuadNode(image, 0, 0, 2);
return new QuadTree(root);
} else {
QuadNode root = new QuadNode(image.length);
root.setQuadrant(QuadName.UpperLeft, getQuadNode(image, 0, 0,
image.length / 2));
root.setQuadrant(QuadName.UpperRight, getQuadNode(image, 0,
image.length/2, image.length / 2));
root.setQuadrant(QuadName.LowerRight, getQuadNode(image,
image.length/2, image.length/2, image.length / 2));
root.setQuadrant(QuadName.LowerLeft, getQuadNode(image,
image.length/2, 0, image.length / 2));
if (checkIfAll4ChildrenAreLeaves(root)) {
int color = root.getQuadrant(QuadName.UpperLeft).getRegionColor();
if ((color != root.getQuadrant(QuadName.UpperRight).getRegionColor()) ||
(color != root.getQuadrant(QuadName.LowerRight).getRegionColor()) ||
(color != root.getQuadrant(QuadName.LowerLeft).getRegionColor())) {
return new QuadTree(root);
}
else {
return new QuadTree(new QuadNode(color, image.length));
}
} else {
return new QuadTree(root);
}
}
} | 9 |
* @return continues with simulation
*/
@Override
public boolean goOn(StochasticSimulator process) {
if (process.getCurrentTime() >= maxTime) {
// if exceed maxTime then stop
return false;
} else {
// stop depending on model state
int numI = model.getNumberOfAgentsInState(IndividualStateType.INFECTED);
numI = numI + model.getNumberOfAgentsInState(IndividualStateType.EXPOSED);
int numR = model.getNumberOfAgentsInState( model.rates.getLastState() );
if ( numI <= 0.5 ) {
// if no more infecteds then stop
return false;
} else if ( numR > (model.getN()-0.5) ) {
// if all are recovered, or immune then stop
return false;
} else {
// else carry on
return true;
}
}
//throw new UnsupportedOperationException("Not supported yet."); //To change body of generated methods, choose Tools | Templates.
} | 3 |
private Component cycle(Component currentComponent, int delta) {
int index = -1;
loop : for (int i = 0; i < m_Components.length; i++) {
Component component = m_Components[i];
for (Component c = currentComponent; c != null; c = c.getParent()) {
if (component == c) {
index = i;
break loop;
}
}
}
// try to find enabled component in "delta" direction
int initialIndex = index;
while (true) {
int newIndex = indexCycle(index, delta);
if (newIndex == initialIndex) {
break;
}
index = newIndex;
//
Component component = m_Components[newIndex];
if (component.isEnabled() && component.isVisible() && component.isFocusable()) {
return component;
}
}
// not found
return currentComponent;
} | 8 |
public static void findCuts(String branch) {
if (branch == null || branch.length() < 2)
return;
// structure representing each cut, which will be mapped in a hash table with the key "weight center-of-gravity"
class WCG {
int startIndex;
int endIndex;
WCG(int s, int e) {
startIndex = s;
endIndex = e;
}
}
int length = branch.length();
int weight, currWeight, currSum;
double currCoG;
String key;
WCG found;
// iterate through each length of cut, starting with the largest possible
for (int cutLength = length / 2; cutLength > 0; cutLength--) {
HashMap<String, WCG> hashmap = new HashMap<String, WCG>(); // map is recycled after each cutLength
// i is the starting index of each cut trial, check every cutLength from left to right
for (int i = 0; i + cutLength - 1 < length; i++) {
// calculate weight and center of gravity of current cut
currWeight = 0;
currSum = 0;
currCoG = 0;
key = "";
for (int j = i, offset = 1; j < i + cutLength; j++, offset++) {
weight = Integer.valueOf(branch.substring(j, j + 1));
currWeight += weight;
currSum += weight * offset;
}
currCoG = (double) currSum / currWeight;
key += currWeight;
key += " ";
key += currCoG;
// check hashmap for matching weight and center of gravity for this cutLength, and that they do not overlap
found = hashmap.get(key);
if (found != null && found.endIndex < i) {
// success
System.out.print(found.startIndex + " " + i + " " + cutLength);
return;
}
key = "";
key += currWeight;
key += " ";
key += cutLength - currCoG + 1;
// check reverse orientation
found = hashmap.get(key);
if (found != null && found.endIndex < i) {
// success
System.out.print(found.startIndex + " " + i + " " + cutLength);
return;
}
// memo this cut otherwise
hashmap.put(key, new WCG(i, i + cutLength - 1));
}
}
// fail
System.out.println("Not found");
} | 9 |
void onSpace () {
if (focusItem == null) return;
if (!focusItem.isSelected ()) {
selectItem (focusItem, (getStyle () & SWT.MULTI) != 0);
redrawItem (focusItem.index, true);
}
if ((getStyle () & SWT.CHECK) != 0) {
focusItem.setChecked (!focusItem.checked);
}
showItem (focusItem);
Event event = new Event ();
event.item = focusItem;
notifyListeners (SWT.Selection, event);
if ((getStyle () & SWT.CHECK) == 0) return;
/* SWT.CHECK */
event = new Event ();
event.item = focusItem;
event.detail = SWT.CHECK;
notifyListeners (SWT.Selection, event);
} | 4 |
public List<ModelFiledDesc> getFileds() {
return fileds;
} | 0 |
private void erstelleXml() throws Exception
{
File file = new File(XMLPATH);
if(file.createNewFile())
{
BufferedWriter writer = null;
try
{
writer = new BufferedWriter(new FileWriter(file));
writer.write("<?xml version=\"1.0\" encoding=\"utf-8\" ?>\n");
writer.write("<struktur>\n");
writer.write("</struktur>");
writer.flush();
}
catch(Exception e)
{
throw e;
}
finally
{
if(writer != null)
{
writer.close();
}
}
}
} | 3 |
public Testcase getTestcase(StringSearchAlgorithm alg, int inputNumber, int numberOfExecutions, boolean showResult) {
File inputStringFile = new File(inputLocation + "source_string.i" + inputNumber);
File searchStringFile = new File(inputLocation + "search_string.i" + inputNumber);
BufferedReader reader = null;
String searchString = null;
String sourceString = null;
//Extract the input- and search-string from files into variables
try {
reader = new BufferedReader( new FileReader (inputStringFile));
String line = null;
StringBuilder stringBuilder = new StringBuilder();
String ls = System.getProperty("line.separator");
while( ( line = reader.readLine() ) != null ) {
stringBuilder.append( line );
stringBuilder.append( ls );
}
sourceString = stringBuilder.toString();
reader.close();
reader = new BufferedReader(new FileReader (searchStringFile));
stringBuilder = new StringBuilder();
while( ( line = reader.readLine() ) != null ) {
stringBuilder.append( line );
//stringBuilder.append( " " );
}
searchString = stringBuilder.toString();
reader.close();
} catch (IOException e) {
e.printStackTrace();
} finally {
try {
reader.close();
} catch (IOException e) {}
}
return new Testcase(alg, searchString, sourceString, numberOfExecutions, showResult);
} | 4 |
@Override
public void actionPerformed(ActionEvent e)
{
if (e.getSource() == d.wall)
{
d.mode = Mode.ADD_WALL;
}
if (e.getSource() == d.door)
{
d.mode = Mode.ADD_DOOR;
}
if (e.getSource() == d.enemy)
{
d.mode = Mode.ADD_ENEMY;
}
if (e.getSource() == d.trigger)
{
d.mode = Mode.ADD_TRIGGER;
}
if (e.getSource() == d.player)
{
d.mode = Mode.ADD_PLAYER;
}
if (e.getSource() == d.exit)
{
d.mode = Mode.ADD_LEVEL_END;
}
if (e.getSource() == d.pushable)
{
d.mode = Mode.ADD_PUSHABLE;
}
if (e.getSource() == d.breakableWall)
{
d.mode = Mode.ADD_BREAKABLE_WALL;
}
if (e.getSource() == d.save)
{
new ExportDialogue();
}
} | 9 |
public static void saveRate(Rate r){
try {
if(conn == null || conn.isClosed()){
conn = DatabaseConnection.getConnection();
}
} catch (SQLException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
try {
conn.setAutoCommit(false);
PreparedStatement stmnt = conn.prepareStatement("INSERT INTO Rates(description, rate) VALUES(?,?)");
stmnt.setString(1, r.getDescription());
stmnt.setFloat(2, r.getRate());
stmnt.execute();
conn.commit();
conn.setAutoCommit(true);
}
catch(SQLException e){
System.out.println("insert fail!! - " + e);
}
} | 4 |
public void firstTraverse(TreeNode tr,String path){
if(tr.left==null && tr.right == null){
path+=tr.val;
res.add(path);
return;
}else{
path= path+tr.val+"->";
}
if(tr.left!=null)
firstTraverse(tr.left,path);
if(tr.right!=null)
firstTraverse(tr.right,path);
} | 4 |
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(cuadrado.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (InstantiationException ex) {
java.util.logging.Logger.getLogger(cuadrado.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (IllegalAccessException ex) {
java.util.logging.Logger.getLogger(cuadrado.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (javax.swing.UnsupportedLookAndFeelException ex) {
java.util.logging.Logger.getLogger(cuadrado.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 cuadrado().setVisible(true);
}
});
} | 6 |
public boolean didTheySwear(String message) {
boolean found = false;
for (Map.Entry<String, String> entry : wordList.entrySet()) {
String thisWord = entry.getKey();
String thisRegex = "\\b"+thisWord+"\\b";
Pattern patt = Pattern.compile(thisRegex, Pattern.CASE_INSENSITIVE);
Matcher m = patt.matcher(message);
if (m.find()) {
found = true;
}
}
return found;
} | 2 |
@Override
public void sendPackage(APacket p, IIOHandler target) {
log.log(Level.FINE, "Sending Packet "+p+" to Target "+target);
if(side == Side.CLIENT&&target!=LOCAL()) {
if(SERVER != null) {
SERVER.sendPacket(p);
} else {
log.log(Level.FINE,"SERVER is equivalent to null when sending Package! Packet will be dropped!");
}
} else {
if(target!=null){
target.sendPacket(p);
}else{
log.log(Level.FINE, "Target is equivalent to null when sending Package! Packet will be dropped!");
}
}
} | 4 |
public String getSuffixText(byte[] bytes, int offset) {
try {
String name= null;
String pid= null;
String exceptionMessage= null;
StringBuffer suffix= new StringBuffer();
try {
SystemObject object = getSystemObject(bytes, offset);
if(object == null) return "id (null)";
name = object.getName();
pid = object.getPid();
}
catch(Exception e) {
exceptionMessage= " " + e.getLocalizedMessage();
}
if(pid == null || pid.equals("")) suffix.append("id");
else suffix.append("pid");
if(name!=null && !name.equals("")) suffix.append(" (Name: ").append(name).append(")");
if(exceptionMessage!=null) suffix.append(" ").append(exceptionMessage);
return suffix.toString();
}
catch(Exception ee) {
return "<<" + ee.getMessage() + ">>";
}
} | 8 |
public String retrieveValidPlateInfo(TableElement element) {
String invalidEntries = "\n\n";
String invalidMessage = " contains invalid entry: ";
// If everything is valid, then update the table element
if (TextField.MJD.hasValidTextEntry() && TextField.PLATE.hasValidTextEntry() && TextField.FIBER.hasValidTextEntry()) {
String plateInfo = TextField.MJD.getText() + "," + TextField.PLATE.getText() + "," + TextField.FIBER.getText();
element.setPlateInfo(plateInfo);
invalidEntries = "none";
} else if (TextField.MJD.hasValidTextEntry() && TextField.PLATE.hasValidTextEntry() && TextField.FIBER.getText().equals("")) {
String plateInfo = TextField.MJD.getText() + "," + TextField.PLATE.getText() + ",0";
element.setPlateInfo(plateInfo);
invalidEntries = "none";
} else {
// Handle invalid entries for error alert
if (!TextField.MJD.hasValidTextEntry())
invalidEntries += TextField.MJD + invalidMessage + TextField.MJD.getText() + "\n";
if (!TextField.PLATE.hasValidTextEntry())
invalidEntries += TextField.PLATE + invalidMessage + TextField.PLATE.getText() + "\n";
if (!TextField.FIBER.hasValidTextEntry())
invalidEntries += TextField.FIBER + invalidMessage + TextField.FIBER.getText() + "\n";
}
return invalidEntries;
} | 9 |
CultureListDialog(java.awt.Frame parent) {
super(parent, "Cultures", false);
GenericObject cultureGroups =
EUGFileIO.load(Main.filenameResolver.resolveFilename("common/cultures.txt"),
ParserSettings.getNoCommentSettings());
// No easy way to do this with an array, so use vector instead.
Vector<Vector<String>> cultureGroupNameTable =
new Vector<Vector<String>>();
for (GenericList group : cultureGroups.lists) {
String groupName = group.getName();
// String groupText = Text.getText(groupName);
for (String culture : group) {
Vector<String> vector = new Vector<String>(2);
vector.add(groupName);
// vector.add(groupText);
vector.add(culture);
// vector.add(Text.getText(culture));
cultureGroupNameTable.add(vector);
}
}
Vector<String> labels = new Vector<String>(4);
labels.add("Group");
// labels.add("Group display name");
labels.add("Culture");
// labels.add("Culture display name");
JTable cultureTable = new JTable(cultureGroupNameTable, labels);
cultureTable.setDefaultEditor(Object.class, null);
if (supportsRowSorter) {
cultureTable.setAutoCreateRowSorter(true);
} else {
System.out.println("Table sorting not supported.");
}
setLayout(new BorderLayout());
add(new JScrollPane(cultureTable), BorderLayout.CENTER);
setDefaultCloseOperation(DISPOSE_ON_CLOSE);
pack();
} | 3 |
private static String initialise(Token currentToken,
int[][] expectedTokenSequences,
String[] tokenImage) {
String eol = System.getProperty("line.separator", "\n");
StringBuffer expected = new StringBuffer();
int maxSize = 0;
for (int i = 0; i < expectedTokenSequences.length; i++) {
if (maxSize < expectedTokenSequences[i].length) {
maxSize = expectedTokenSequences[i].length;
}
for (int j = 0; j < expectedTokenSequences[i].length; j++) {
expected.append(tokenImage[expectedTokenSequences[i][j]]).append(' ');
}
if (expectedTokenSequences[i][expectedTokenSequences[i].length - 1] != 0) {
expected.append("...");
}
expected.append(eol).append(" ");
}
String retval = "Encountered \"";
Token tok = currentToken.next;
for (int i = 0; i < maxSize; i++) {
if (i != 0) retval += " ";
if (tok.kind == 0) {
retval += tokenImage[0];
break;
}
retval += " " + tokenImage[tok.kind];
retval += " \"";
retval += add_escapes(tok.image);
retval += " \"";
tok = tok.next;
}
retval += "\" at line " + currentToken.next.beginLine + ", column " + currentToken.next.beginColumn;
retval += "." + eol;
if (expectedTokenSequences.length == 1) {
retval += "Was expecting:" + eol + " ";
} else {
retval += "Was expecting one of:" + eol + " ";
}
retval += expected.toString();
return retval;
} | 8 |
public static void setAboutPanel(Class<? extends JPanel> aboutPanelClass) {
ABOUT_PANEL_CLASS = aboutPanelClass;
} | 1 |
private void ufotAlemmasOikeassaReunassa(Ufo ufo, int x) {
if (ufo.isVisible()) {
if (x >= RuudunLeveys - RuudunOikeaReuna && suunta != -1) {
suunta = -1;
Iterator i1 = ufot.iterator();
while (i1.hasNext()) {
ufo = (Ufo) i1.next();
ufo.setY(ufo.getY() + UfotLiikkuvatRivinALas);
}
}
}
} | 4 |
public void updateDataBase()
{
String masterHostName = null;
int masterPortNumber = 0;
String masterKey = null;
for (NodeState server : pool)
{
try
{
Registry registry = LocateRegistry.getRegistry(server.getHostname(), server.getPortNumber());
RemoteBullyPassiveNode stub = (RemoteBullyPassiveNode) registry.lookup(server.getKey());
NodeProperties masterProp = stub.getMasterServer();
masterKey = masterProp.getKey();
masterHostName = masterProp.getHostname();
masterPortNumber = masterProp.getPortNumber();
break;
} catch (RemoteException | NotBoundException e)
{
System.err.println(e);
}
}
if (masterHostName == null || masterPortNumber == 0 || masterKey == null)
{
masterHostName = self.getHostname();
masterPortNumber = self.getPortNumber();
masterKey = self.getKey();
}
try
{
Date latestLogDate = this.getLatestLogDate();
Registry registry = LocateRegistry.getRegistry(masterHostName, masterPortNumber);
RemoteBullyPassiveNode stub = (RemoteBullyPassiveNode) registry.lookup(masterKey);
List<EventLog> logsList = stub.getLogsToUpdate(latestLogDate);
for (EventLog eventLog : logsList)
{
executeLog(eventLog);
}
} catch (NullPointerException npe)
{
System.err.println("Nenhum servidor ligado");
// não precisa de fazer nenhum update
} catch (RemoteException | NotBoundException e)
{
System.err.println(e);
}
// block master database from accepting changes
// get new logs
//Date latestLogDate = this.getLatestLogDate();
//master.getObject();
// update db from new logs
// unblock master database
} | 8 |
public void removeOutgoingEdge(Edge out) throws MaltChainedException {
super.removeOutgoingEdge(out);
if (out.getTarget() != null) {
if (out.getType() == Edge.DEPENDENCY_EDGE && out.getTarget() instanceof DependencyNode) {
Node dependent = out.getTarget();
if (compareTo(dependent) > 0) {
leftDependents.remove((DependencyNode)dependent);
} else if (compareTo(dependent) < 0) {
rightDependents.remove((DependencyNode)dependent);
}
} else if (out.getType() == Edge.PHRASE_STRUCTURE_EDGE && out.getTarget() instanceof PhraseStructureNode) {
children.remove((PhraseStructureNode)out.getTarget());
}
}
} | 7 |
public void setList(List<Record> list) {
this.list = list;
} | 0 |
private void createTrayIcon() {
if(supported) {
URL iconUrl = ClassLoader.getSystemResource(Constants.ICON_FILE);
Image icon = new ImageIcon( iconUrl ).getImage();
PopupMenu menu = new PopupMenu();
openGuiMenuItem = new MenuItem();
settingsMenuItem = new MenuItem();
quitMenuItem = new MenuItem();
menu.add(openGuiMenuItem);
menu.add(settingsMenuItem);
menu.add(quitMenuItem);
trayIcon = new TrayIcon(icon, Constants.PROGRAM_NAME, menu);
trayIcon.setImageAutoSize(true);
refreshLabels();
openGuiMenuItem.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
for(int k=0; k<chatGuiListener.size(); ++k) {
chatGuiListener.get(k).openChatView();
}
}
});
settingsMenuItem.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
for(int k=0; k<chatGuiListener.size(); ++k) {
chatGuiListener.get(k).openSettingsView();
}
}
});
quitMenuItem.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent arg0) {
for(int k=0; k<chatGuiListener.size(); ++k) {
chatGuiListener.get(k).quit();
}
}
});
}
} | 4 |
private static boolean targetOverLineOnScreen( double sx, double sy, int ex, int ey, int tx, int ty ){
if( sx == ex && sy == ey ){
return true;
}
if( sx == ex ){
return tx > sx;
}
double m = (sy - ey) / (double)(sx - ex);
m = limitM( m );
double q = sy - m * sx;
return m * tx + q > ty;
} | 3 |
public void testConstructorEx1_TypeArray_intArray() throws Throwable {
try {
new Partial((DateTimeFieldType[]) null, new int[] {1});
fail();
} catch (IllegalArgumentException ex) {
assertMessageContains(ex, "must not be null");
}
} | 1 |
@Override
public String toString() {
return "DCSTrunk {"
+ (extReferences != null ? " extReferences [" + extReferences + "]" : "")
+ (cls != null ? " cls [" + cls + "]" : "")
+ (recommendedValue != null ? " recommendedValue [" + recommendedValue + "]" : "")
+ (quality != null ? " quality [" + quality + "]" : "")
+ (legacyReleasability != null ? " legacyReleasability [" + legacyReleasability + "]" : "")
+ (value != null ? " value [" + value + "]" : "")
+ (remarks != null ? " remarks [" + remarks + "]" : "")
+ (availability != null ? " availability [" + availability + "]" : "")
+ "}";
} | 8 |
public static void UperFirstName(){
try {
if(conn == null || conn.isClosed()){
conn = DatabaseConnection.getConnection();
}
} catch (SQLException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
try{
conn.setAutoCommit(false);
PreparedStatement stmnt = conn.prepareStatement("UPDATE Staff set first_name = CONCAT( UPPER( LEFT( first_name, 1 ) ) , SUBSTRING( first_name, 2 ))");
stmnt.execute();
conn.commit();
conn.setAutoCommit(true);
}catch(SQLException e){
e.printStackTrace();
}
} | 4 |
public static void main(String[]args) throws Exception{
if(args.length!=1){
System.err.println("Nombre d'arguments incorrect");
return;
}
LinkedRBinaryTree<?> tree=null;
try{
IO.openReader(args[0]);
String line;
// On parcourt toutes les expressions du fichier une a une
while((line = IO.readInstruction()) != null)
{
try{
// Tranformation en arbre
tree=new LinkedRBinaryTree(line);
// Derivation
LinkedRBinaryTree<?> d=tree.derive();
System.out.println("Expression initiale : "+tree+"\n"+"Expression derivee : "+d);
System.out.println("----------------------------------------------------------");
}
catch(IllegalInputException a){
System.err.println("Erreur lors de la conversion de la chaine de caracteres en arbre");
System.err.println("Details : "+a.getMessage());
System.err.println("----------------------------------------------------------");
}
catch(EmptyStackException p){
System.err.println("Erreur : operation pop sur une pile vide. Cela peut etre du a une expression illegale");
System.err.println("----------------------------------------------------------");
}
catch(ClassCastException c){
System.err.println("Erreur : On n'applique pas les derive d'exposant de fonctions");
System.err.println("----------------------------------------------------------");
}
}
}
catch(IOException e){
System.err.println("Erreur lors de la lecture du fichier d'entree");
System.err.println("Details : "+e.getMessage());
System.exit(1);
}
} | 8 |
public double getX() {
return x;
} | 0 |
public static void main(String args[]) {
int trials = 1000;
for (int i = 0; i < trials; i++) {
deal();
playWar();
reset();
}
System.out.println("Average Battles: " + battles/trials);
System.out.println("Average Wars: " + wars/trials);
} | 1 |
final void aa(short i, short i_582_) {
if (aShortArray5388 != null) {
if (!aBoolean5391 && i_582_ >= 0) {
TextureDefinition class12
= ((AbstractToolkit) aHa_Sub1_5353).aD4579.getTexture(i_582_ & 0xffff,
-6662);
if (((TextureDefinition) class12).aByte198 != 0
|| ((TextureDefinition) class12).aByte211 != 0)
aBoolean5391 = true;
}
for (int i_583_ = 0; i_583_ < anInt5351; i_583_++) {
if (aShortArray5388[i_583_] == i)
aShortArray5388[i_583_] = i_582_;
}
}
} | 7 |
public String getFriend(String IP, String name){
if(!name.toLowerCase().equals(InstantMessenger.user.toLowerCase())){
InstantMessenger.remUser = name;
frndName = name;
try{
sock = new Socket();
sock.connect(new InetSocketAddress(IP,6789), 1300);
DataInputStream s = new DataInputStream(sock.getInputStream());
String ans = s.readUTF();
if("no".equals(ans)){
return "no";
}
if(msgS == null)
msgS = new msgSend(sock);
msgRecv msgR = new msgRecv(sock,frndName);
msgR.start();
InstantMessenger.server.server.close();
InstantMessenger.server.stop();
return "yes";
} catch (IOException ex) {
JOptionPane.showMessageDialog(this, "Unable To Connect! Sorry!");
if(!InstantMessenger.server.isAlive())
InstantMessenger.server.start();
return "unable";
}
}
else{
JOptionPane.showMessageDialog(this, "Becoming a smartass huh? dont, bitch!");
return "unable";
}
} | 5 |
public void setPWFieldFonttype(Fonttype fonttype) {
if (fonttype == null) {
this.pWFieldFontType = UIFontInits.PWFIELD.getType();
} else {
this.pWFieldFontType = fonttype;
}
somethingChanged();
} | 1 |
public boolean editCounterevidence(Evidence c) {
Element evidenceE;
Evidence evidence;
boolean flag = false;
for (Iterator i = root.elementIterator("counterevidence"); i.hasNext();) {
evidenceE = (Element)i.next();
if (evidenceE.element("id").getText().equals(c.getId())) {
evidenceE.element("title").setText(c.getTitle());
evidenceE.element("description").setText(c.getTitle());
// Write to xml
try {
XmlUtils.write2Xml(fileName, document);
return true;
} catch (IOException ex) {
// TODO Auto-generated catch block
ex.printStackTrace();
}
flag = true;
break;
}
}
return flag;
} | 3 |
protected int readData( char[] chunkData, int pos )
{
int state = 0;
int start = pos;
StringBuilder sb = new StringBuilder();
while ( pos < chunkData.length && state != -1 )
{
switch ( state )
{
case 0: // reading text
if ( chunkData[pos] == '\\' )
state = 1;
else if ( chunkData[pos] == ']' )
state = -1;
else
sb.append( chunkData[pos] );
break;
case 1: // reading backslash
if ( chunkData[pos] == '\\' )
sb.append( '\\' );
else if ( chunkData[pos] == ']' )
sb.append( ']' );
state = 0;
break;
}
pos++;
}
realData = new char[sb.length()];
sb.getChars(0,realData.length,realData,0);
escapedData = escapeData( realData );
return pos - start;
} | 8 |
private void createDialog(final ArrayList<Boolean> list, final int index) {
final JDialog dialog = new JDialog();
Boolean bool = list.get(index);
dialog.setSize(360, 150);
dialog.setResizable(false);
dialog.getContentPane().setLayout(null);
dialog.setLocationRelativeTo(this);
dialog.setLayout(null);
JLabel lblEquipmentLabel = new JLabel("Czy dodać jako ekwipunek?");
lblEquipmentLabel.setBounds(25, 25, 200, 14);
dialog.add(lblEquipmentLabel);
final JCheckBox chckbxTrueOrFalse = new JCheckBox(
"Tak/Nie");
chckbxTrueOrFalse.setBounds(25, 47, 200, 23);
chckbxTrueOrFalse.setSelected(bool);
dialog.add(chckbxTrueOrFalse);
JButton btnOk = new JButton("Ok");
btnOk.setBounds(235, 70, 89, 23);
btnOk.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
boolean trueOrFalse = chckbxTrueOrFalse.isSelected();
if (trueOrFalse == true) {
list.set(index, true);
} else {
list.set(index, false);
}
dialog.dispose();
}
});
dialog.add(btnOk);
dialog.setVisible(true);
} | 1 |
@Override
public boolean equals(Object object) {
// TODO: Warning - this method won't work in the case the id fields are not set
if (!(object instanceof Privatstunde)) {
return false;
}
Privatstunde other = (Privatstunde) object;
if ((this.privatstundeid == null && other.privatstundeid != null) || (this.privatstundeid != null && !this.privatstundeid.equals(other.privatstundeid))) {
return false;
}
return true;
} | 5 |
public boolean overTwoTimes(int[] counts) {
for (int i = 0; i < counts.length; i++) {
if (counts[i] > 1)
return false;
}
return true;
} | 2 |
@Override
public void keyPressed(KeyEvent e) {
switch(e.getKeyCode()) {
case KeyEvent.VK_UP:
this.editor.getCursor().selectLineUp();
break;
case KeyEvent.VK_DOWN:
this.editor.getCursor().selectLineDown();
break;
case KeyEvent.VK_LEFT:
this.editor.getCursor().movePositionLeft();
break;
case KeyEvent.VK_RIGHT:
this.editor.getCursor().movePositionRight();
break;
case KeyEvent.VK_DELETE:
if(this.editor.getCursor().getCurrentPosition() < this.editor.getCursor().getCurrentLine().length())
this.editor.getSelectedLine().deleteCharAt(this.editor.getSelectedCharacterNb());
break;
case KeyEvent.VK_BACK_SPACE:
if(this.editor.getCursor().getCurrentPosition() > 0) {
this.editor.getSelectedLine().deleteCharAt(this.editor.getSelectedCharacterNb()-1);
this.editor.getCursor().movePositionLeft();
}
break;
}
view.getDocument().setText(this.editor.print());
} | 8 |
public Powerup(String powerUpTyp){
switch (PowerupTyp.valueOf(powerUpTyp)) {
case OWN_MOVE_FAST:
break;
case OWN_MOVE_SLOW:
break;
case ENEMY_MOVE_FAST:
break;
case ENEMY_MOVE_SLOW:
break;
case TABOO:
break;
case CONTROL_SWITCH:
break;
case RANDOM:
break;
case CHAINSAW:
break;
default:
break;
}
} | 8 |
protected void done(){
try
{
startButton.setEnabled( true ); // Enable the start button in the applet.
settingsButton.setEnabled( true ); // Enable the settings button in the applet.
stopButton.setEnabled( false ); // Disable the stop button in the applet.
if( stopButton.getText() == "Resume" ) stopButton.setText( "Stop" ); // Assign a proper label to the stop button.
} // end try{}
catch(Exception ex){}
} // end method protected void done(). | 2 |
@Override
public String toString() {
return this.map.toString();
} | 0 |
private void start_connecting (boolean wait_)
{
assert (connect);
// Choose I/O thread to run connecter in. Given that we are already
// running in an I/O thread, there must be at least one available.
IOThread io_thread = choose_io_thread (options.affinity);
assert (io_thread != null);
// Create the connecter object.
if (addr.protocol().equals("tcp")) {
TcpConnecter connecter = new TcpConnecter (
io_thread, this, options, addr, wait_);
//alloc_assert (connecter);
launch_child (connecter);
return;
}
if (addr.protocol().equals("ipc")) {
IpcConnecter connecter = new IpcConnecter (
io_thread, this, options, addr, wait_);
//alloc_assert (connecter);
launch_child (connecter);
return;
}
assert (false);
} | 2 |
private void cargarSetAprendizaje(){
DefaultTableModel temp = (DefaultTableModel) this.tablaSetAprendizaje.getModel();
String csvFile = "dataset/iris_aprendizaje.csv";
BufferedReader br = null;
String line = "";
String cvsSplitBy = ",";
try {
br = new BufferedReader(new FileReader(csvFile));
while ((line = br.readLine()) != null) {
String[] patron = line.split(cvsSplitBy);
Object nuevo[]= {patron[0], patron[1], patron[2], patron[3], patron[4]};
temp.addRow(nuevo);
}
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} catch (IndexOutOfBoundsException e) {
System.out.println("Error accediendo al csv");
} finally {
if (br != null) {
try {
br.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
} | 6 |
public Enumeration listOptions() {
Vector result = new Vector();
Enumeration en = super.listOptions();
while (en.hasMoreElements())
result.addElement(en.nextElement());
result.addElement(new Option(
"\tFull name and options of the evaluator analyzed.\n"
+"\teg: weka.attributeSelection.CfsSubsetEval",
"eval", 1, "-eval name [options]"));
result.addElement(new Option(
"\tFull name and options of the search method analyzed.\n"
+"\teg: weka.attributeSelection.Ranker",
"search", 1, "-search name [options]"));
result.addElement(new Option(
"\tThe scheme to test, either the evaluator or the search method.\n"
+"\t(Default: eval)",
"test", 1, "-test <eval|search>"));
if ((m_Evaluator != null) && (m_Evaluator instanceof OptionHandler)) {
result.addElement(new Option("", "", 0,
"\nOptions specific to evaluator "
+ m_Evaluator.getClass().getName()
+ ":"));
Enumeration enm = ((OptionHandler) m_Evaluator).listOptions();
while (enm.hasMoreElements())
result.addElement(enm.nextElement());
}
if ((m_Search != null) && (m_Search instanceof OptionHandler)) {
result.addElement(new Option("", "", 0,
"\nOptions specific to search method "
+ m_Search.getClass().getName()
+ ":"));
Enumeration enm = ((OptionHandler) m_Search).listOptions();
while (enm.hasMoreElements())
result.addElement(enm.nextElement());
}
return result.elements();
} | 7 |
@Override
public Step execute(Algebra algebra) {
Fraction frac = (Fraction) algebra;
//get factors of top and bottom
Map<AlgebraicParticle, Integer> factorsTop = factors(frac.getTop()),
factorsBottom = factors(frac.getBottom());
//find intersection of set of factors of top and bottom
Set<AlgebraicParticle> commonFactors = new HashSet<AlgebraicParticle>(factorsTop.keySet());
commonFactors.retainAll(factorsBottom.keySet());
//cancel all the common factors and add what doesn't cancel to the respective list
for(AlgebraicParticle element : commonFactors) {
Integer numTop = factorsTop.get(element), numBottom = factorsBottom.get(element);
//cancel the factors, and if there are more on top than bottom, leave some on top, else
//leave more on the bottom.
int numToCancel = numTop > numBottom ? numBottom : numTop;
int resultNumTop = numTop - numToCancel;
int resultNumBottom = numBottom - numToCancel;
//set the new coefficient for every factor (canceling)
factorsTop.put(element, resultNumTop);
factorsBottom.put(element, resultNumBottom);
}
//calculate the sign for the terms
boolean sign = factorsTop.containsKey(Number.NEGATIVE_ONE) == factorsBottom.containsKey(Number.NEGATIVE_ONE);
sign = sign == frac.sign();
//remove -1 & 1 from factors (if necessary) (have already tracked -1, so can ignore now)
factorsTop.remove(Number.NEGATIVE_ONE);
factorsBottom.remove(Number.NEGATIVE_ONE);
//we factored integers; now multiply the ones that didn't cancel
multiplyIntegers(factorsTop);
multiplyIntegers(factorsBottom);
AlgebraicParticle top = constructResult(factorsTop);
AlgebraicParticle bottom = constructResult(factorsBottom);
Fraction done = new Fraction(sign, top, bottom, frac.exponent());
AlgebraicParticle result = done;
//if the bottom is 1, the result is the top (any number divided by 1 is that number)
if(done.getBottom().equals(Number.ONE)) {
if(sign) result = done.getTop();
else result = done.getTop().cloneWithNewSign(sign);
}
Step step = new Step(result);
AlgebraicParticle[] commonFactorsArray = commonFactors.toArray(new AlgebraicParticle[commonFactors.size()]);
//if there were factors, explain. There aren't always factors; e.g. 4/1 simplifies to 4
int count = commonFactorsArray.length;
if(count != 0) {
step.explain("In the fraction ").explain(frac)
.explain(" the common factor" + (count == 1 ? " is " : "s are "))
.list(commonFactorsArray).explain(". Dividing top and bottom by ");
//specify the term to divide by if there's only 1, otherwise just say "these"
if(count == 1) step.explain(commonFactorsArray[0]);
else step.explain("these");
step.explain(" leaves ").explain(result).explain(".");
}
//there weren't any factors that could cancel
else step.explain("Simplify ").explain(frac).explain(" to get ").explain(result);
return step;
} | 7 |
public boolean playerCanExit() {
Car player = (Car) vehicles.get('A');
ArrayList<Coordinate> coords = this.getCoveredCoordinatesExcludingVehicle(player);
for (int i = player.position.x; i < gridSize; i++) {
if(coords.contains(new Coordinate(i, player.position.y))){
return false;
}
}
return true;
} | 2 |
public boolean equals(Object ob) {
if (super.equals(ob)) {
Candy other = (Candy) ob;
if (hardness != other.hardness)
return false;
}
return true;
} | 2 |
public void update(T t) throws SQLException {
Session session = null;
try {
session = HibernateUtil.getSessionFactory().openSession();
session.beginTransaction();
session.update(t);
session.getTransaction().commit();
} catch (Exception e) {
JOptionPane.showMessageDialog(null, e.getMessage(), "Ошибка данных", JOptionPane.OK_OPTION);
} finally {
if (session != null && session.isOpen()) {
session.close();
}
}
} | 3 |
public void setFoo(Boolean foo)
{
this.foo = foo;
} | 0 |
@Column(name = "sale_id")
@Id
public int getSaleId() {
return saleId;
} | 0 |
public String toString() {
if(this.b>=0)
return String.format("%.3f +%.3fi", this.a, this.b);
else
return String.format("%.3f %.3fi", this.a, this.b);
} | 1 |
private void addClade(DrawableNode root, TreeItem cladeInfo) {
//boolean add = false;
//We traverse the tree and look for a node that contains this clade, but
//that does not have any children that contain this clade
if (containsClade(root, cladeInfo.clade)) {
boolean found = false;
for(Node kid : root.getOffspring()) {
if (containsClade((DrawableNode)kid, cladeInfo.clade)) {
found = true;
addClade((DrawableNode)kid, cladeInfo);
}
}
if (!found) {
//Here the root contains this clade, but none of root's kids do, so add the clade here
//System.out.println("Clade " + cladeInfo.clade + " was not found in any kids, but was contained in this node, so adding here");
DrawableNode newNode = new DrawableNode();
newNode.addAnnotation("tips", cladeInfo.clade);
newNode.addAnnotation("support", new Double((double)cladeInfo.count/(double)numInputTrees).toString());
double height = cladeInfo.height;
newNode.addAnnotation("height", new Double(height).toString());
double var = cladeInfo.M2/(double)(cladeInfo.count-1.0);
//System.out.print("Var: " + var);
if (var>0) {
double stdev = Math.sqrt(var);
//System.out.println(" stdev : " + stdev);
newNode.addAnnotation("error", new Double(stdev).toString());
}
newNode.setParent(root);
root.addOffspring(newNode);
try {
double parentHeight = Double.parseDouble( root.getAnnotationValue("height") ) ;
newNode.setDistToParent( parentHeight- cladeInfo.height);
}
catch (Exception nfe) {
System.err.println("Could not read height value from root node, this means we can't set the node height for a node. Uh oh");
}
if (cladeInfo.cardinality==1) {
newNode.setLabel( cladeInfo.clade.replaceAll(labelSep, "") );
}
}
}
} | 7 |
public float[][] clone2df(float[][] orig){
int ii = orig.length;
int jj = orig[0].length;
float[][] temp = new float[ii][jj];
for (int i = 0; i<ii; i++){
for(int j = 0; j < jj; j++){
temp[i][j] = orig[i][j];
}
}
return temp;
} | 2 |
public int getPartyHealth(int i) {
if (i == 1) {
return bm.getHealth();
}
else if (i == 2) {
return n.getHealth();
}
else if (i == 3) {
return w.getHealth();
}
else if (i == 4) {
return d.getHealth();
}
else if (i == 5) {
return wm.getHealth();
}
else {
return 50;
}
} | 5 |
public String getCountryCode() {
return countryCode.get();
} | 0 |
public void loadConfig () {
File folder = getDataFolder();
PluginDescriptionFile pdfFile = getDescription();
File configFile = new File(getDataFolder(), "config.yml");
Properties settingsFile = new Properties();
if (! (folder.exists())) {
try {
folder.mkdir();
log.info("[More Mobs] Created folder.");
} catch (Exception ex) {
log.info("[More Mobs] Failed to create folder!");
getServer().getPluginManager().disablePlugin(plugin);
}
}
if (! configFile.exists()) {
try {
configFile.createNewFile();
FileOutputStream out = new FileOutputStream(configFile);
settingsFile.put("Version", Double.toString(version));
settingsFile.put("MaxSpawnLimit", Integer.toString(maxSpawnLimit.intValue()));
settingsFile.store(out, "Configuration file for More Mobs " + pdfFile.getVersion());
log.info("[More Mobs] Created configuration file.");
} catch (IOException ex) {
log.info("[More Mobs] Failed to create configuration file!");
}
} else {
try {
FileInputStream in = new FileInputStream(configFile);
try {
try {
settingsFile.load(in);
if (! settingsFile.getProperty("Version").equals(version)) {
FileOutputStream out = new FileOutputStream(configFile);
settingsFile.put("Version", Double.toString(version));
settingsFile.put("MaxSpawnLimit", Integer.toString(maxSpawnLimit.intValue()));
settingsFile.store(out, "Configuration file for More Mobs " + pdfFile.getVersion());
log.info("[More Mobs] Updating configuration file!");
}
} catch (NullPointerException ex) {
log.info("[More Mobs] Failed to update configuration file! Disabling plugin.");
getServer().getPluginManager().disablePlugin(plugin);
}
settingsFile.load(in);
maxSpawnLimit = Integer.valueOf(settingsFile.getProperty("MaxSpawnLimit"));
log.info("[More Mobs] Loaded configuration file.");
} catch (IOException ex) {
log.info("[More Mobs] Failed to load configuration file! Disabling plugin.");
getServer().getPluginManager().disablePlugin(plugin);
}
} catch (FileNotFoundException ex) {
log.info("[More Mobs] Failed to load configuration file! Disabling plugin.");
getServer().getPluginManager().disablePlugin(plugin);
}
}
} | 8 |
public boolean onCommand(CommandSender sender, Command cmd, String commandlabel, String[] args) {
final ChatColor red = ChatColor.RED;
final ChatColor yellow = ChatColor.YELLOW;
final ArrayList<Player> cPearl = CrazyFeet.CrazyPearl;
if(args.length < 1) {
if(sender instanceof Player) {
Player player = (Player) sender;
if(player.hasPermission("CrazyFeet.crazypearl")) {
if(cPearl.contains(player)) {
cPearl.remove(player);
player.sendMessage(yellow+"The tingling sensation fades away..");
return true;
} else {
cPearl.add(player);
player.sendMessage(yellow+"You feel a tingling sensation in your feet!");
return true;
}
} else {
player.sendMessage(red+"No permission");
return true;
}
}
} else if(args.length == 1){
if(sender.hasPermission("CrazyFeet.crazypearlother")) {
if(Bukkit.getServer().getPlayer(args[0]) != null) {
Player targ = Bukkit.getServer().getPlayer(args[0]);
if(cPearl.contains(targ)) {
cPearl.remove(targ);
targ.sendMessage(yellow+sender.getName()+" has disabled your CrazyPearl!");
sender.sendMessage(yellow+targ.getDisplayName()+"'s CrazyPearl has been disabled!");
return true;
} else {
cPearl.add(targ);
targ.sendMessage(yellow+sender.getName()+" has given you CrazyPearl!");
sender.sendMessage(yellow+targ.getDisplayName()+" has been given CrazyPearl!");
return true;
}
} else {
sender.sendMessage(red+"The player "+yellow+args[0]+red+" is either offline or does not exist!");
return true;
}
} else {
sender.sendMessage(red+"You do not have permission to toggle CrazyPearl on others.");
return true;
}
} else {
sender.sendMessage(red+"Incorrect usage. Use /crazyfeet for help!");
return true;
}
return false;
} | 8 |
public List<String> restoreIpAddresses(String s) {
int length = s.length();
if(length < 4 || length > 12)
return list;
for(int i=1;i<length -2;i++)
for (int j = i+1;j<length-1 ;j++ )
for (int k = j+1; k<=length ;k++ ) {
String ip1 = s.substring(0,i);
String ip2 = s.substring(i,j);
String ip3 = s.substring(j,k);
String ip4 = s.substring(k,length);
if(valid(ip1) && valid(ip2) && valid(ip3) && valid(ip4)){
String s1 = ip1+"."+ip2+"."+ip3+"."+ip4;
list.add(s1);
}
}
return list;
} | 9 |
@Override
public boolean queueBuffer( byte[] buffer )
{
// Stream buffers can only be queued for streaming sources:
if( errorCheck( channelType != SoundSystemConfig.TYPE_STREAMING,
"Buffers may only be queued for streaming sources." ) )
return false;
//ByteBuffer byteBuffer = ByteBuffer.wrap( buffer, 0, buffer.length );
ByteBuffer byteBuffer = (ByteBuffer) BufferUtils.createByteBuffer(
buffer.length ).put( buffer ).flip();
IntBuffer intBuffer = BufferUtils.createIntBuffer( 1 );
AL10.alSourceUnqueueBuffers( ALSource.get( 0 ), intBuffer );
if( checkALError() )
return false;
if( AL10.alIsBuffer( intBuffer.get( 0 ) ) )
millisPreviouslyPlayed += millisInBuffer( intBuffer.get( 0 ) );
checkALError();
AL10.alBufferData( intBuffer.get(0), ALformat, byteBuffer, sampleRate );
if( checkALError() )
return false;
AL10.alSourceQueueBuffers( ALSource.get( 0 ), intBuffer );
if( checkALError() )
return false;
return true;
} | 5 |
public void setHighThreshold(float threshold) {
if (threshold < 0)
throw new IllegalArgumentException();
highThreshold = threshold;
} | 1 |
public void nouveauTour(){
if (!aJoue() && !estMort()){
this.guerir();
}
this.aJoue = false;
} | 2 |
private ArrayList<Integer> determinePagesOfTermInSelectedChapters(ArrayList<Integer> termTotalPages, ArrayList<Integer> totalPagesInSelectedChapters){
if(totalPagesInSelectedChapters.size()!=0){
ArrayList<Integer> termTotalPagesWrapper = new ArrayList<Integer>(termTotalPages); //here to ensure no changes are made to the parameters.
ArrayList<Integer> totalPagesInSelectedChaptersWrapper = new ArrayList<Integer>(totalPagesInSelectedChapters); //here to ensure no changes are made to the parameters.
ArrayList<Integer> toRemove = new ArrayList<>();
for(Integer i: termTotalPagesWrapper){
boolean wasNotFound = true;
for(Integer j: totalPagesInSelectedChaptersWrapper){
if(i.equals(j)){
wasNotFound = false;
break;
}
}
if(wasNotFound){
toRemove.add(i);
}
}
//Remove pages that aren't in the specified chapters.
for(Integer i:toRemove){
termTotalPagesWrapper.remove(i);
}
return termTotalPagesWrapper;
}
//If the second parameter is an empty list just return the first parameter.
else {
return termTotalPages;
}
} | 6 |
public void Merge(Portfolio pleft, Portfolio pright, double wgt)
{
Collections.sort(pleft.pwlist,CINDEX);
Collections.sort(pright.pwlist,CINDEX);
int i = 0;
int j = 0;
Vector<PortWeight> newplist = new Vector<PortWeight>();
while (i < pleft.pwlist.size() && j < pright.pwlist.size())
{
PortWeight mypw = pleft.pwlist.get(i);
PortWeight p2pw = pright.pwlist.get(j);
if (mypw.index == p2pw.index)
{
newplist.add(new PortWeight(mypw.name, mypw.index, (mypw.weight * wgt) + (p2pw.weight * (1 - wgt))));
i++;
j++;
}
else if (mypw.index > p2pw.index)
{
newplist.add(new PortWeight(p2pw.name, p2pw.index,p2pw.weight * (1 - wgt)));
j++;
}
else if (p2pw.index > mypw.index)
{
newplist.add(new PortWeight(mypw.name, mypw.index,mypw.weight * wgt));
i++;
}
}
while (i < pleft.pwlist.size())
{
PortWeight mypw = pleft.pwlist.get(i);
newplist.add(new PortWeight(mypw.name, mypw.index,mypw.weight * wgt));
i++;
}
while (j < pright.pwlist.size())
{
PortWeight p2pw = pright.pwlist.get(j);
newplist.add(new PortWeight(p2pw.name, p2pw.index,p2pw.weight * (1 - wgt)));
j++;
}
pwlist = newplist;
} | 7 |
public int getCheckStart()
{
return _checkStart;
} | 0 |
public static String wypiszWynik(double[] tablicaWFormieNormalnej, boolean cons) {
String postacOgolna = "";
for (int i=tablicaWFormieNormalnej.length-1;i>1;i--){
if(tablicaWFormieNormalnej[i]!=1.0)
{
Double normalnaSkrocona=new BigDecimal(tablicaWFormieNormalnej[i]).setScale(3, BigDecimal.ROUND_HALF_UP).doubleValue();
postacOgolna += normalnaSkrocona;
}
if(tablicaWFormieNormalnej[i-1]<0)
postacOgolna += "x^{" + i + "} ";
else
postacOgolna += "x^{" + i + "} + " ;
}
if(tablicaWFormieNormalnej[1]!=1.0) postacOgolna += tablicaWFormieNormalnej[1];
postacOgolna += "x";
if(tablicaWFormieNormalnej[0]!=0.0) postacOgolna += " + " + tablicaWFormieNormalnej[0];
if(cons) postacOgolna += " + Const";
postacOgolna += "\n";
System.out.print(postacOgolna);
return postacOgolna;
} | 6 |
private void detachFrom(Component paramComponent)
{
if ((paramComponent instanceof ImageComponent)) {
((ImageComponent)paramComponent).removeImageListener(this);
} else if ((paramComponent instanceof ImageComposite)) {
((ImageComposite)paramComponent).removeImageListener(this);
} else if (((paramComponent instanceof Container)) && ((paramComponent instanceof ReportingContainer)))
{
Container localContainer = (Container)paramComponent;
((ReportingContainer)paramComponent).removeReportingContainerListener(this);
Component[] arrayOfComponent = localContainer.getComponents();
for (int i = 0; i < arrayOfComponent.length; i++) {
detachFrom(arrayOfComponent[i]);
}
}
if ((paramComponent instanceof ReportingComponent))
((ReportingComponent)paramComponent).removeReportingComponentListener(this);
} | 6 |
public void writestack()
{
File f=new File(name+".stack.back");
if (f.exists())
if (!f.delete())
{
printer.PrintMessage("failed to delete "+name+".stack.back");
return;
}
f= new File(name+".stack");
if (f.exists())
{
if (!f.renameTo(new File(name+".stack.back")))
{
printer.PrintMessage("failed to rename "+name+".stack");
return;
}
}
f= new File(name+".stack");
try
{
f.createNewFile();
} catch (IOException e)
{
printer.PrintMessage("failed to create "+name+".stack");
return;
}
try
{
BufferedWriter out = new BufferedWriter(new FileWriter(name+".stack", true));
for(Moneys m: money)
{
out.write(m.owner+" "+m.amount+"\r\n");
}
out.close();
f=new File(name+".stack.back");
if (f.exists())
if (!f.delete())
{
printer.PrintMessage("failed to delete "+name+".stack.back");
return;
}
}
catch (IOException e)
{
printer.PrintMessage("failed to write to "+name+".stack");
}
} | 9 |
@Override
public T next()
{
T current = next;
while (iterator.hasNext())
{
next = iterator.next();
if (next != skip)
{
break;
}
}
if (!iterator.hasNext())
{
next = null;
}
return current;
} | 3 |
public void notify(Object[] objects) {
Integer value = (Integer)objects[0];
if (value.equals(DISPLAY_PROJECT_VARIABLES)) {
displayProjectVariables();
} else if (value.equals(DISPLAY_DESTINATION_FOLDER)) {
displayDestinationFolder();
}
} | 2 |
public void paint(Graphics g) {
//Dibujamos la imagen de fondo
for(int i=0; i <= ANCHO_VENTANA/DIAMETRO_IMAGEN; i++)
for(int j=0; j <= ALTO_VENTANA/DIAMETRO_IMAGEN; j++)
g.drawImage(game.getImagen(), Math.round(i)*DIAMETRO_IMAGEN,Math.round(j)*DIAMETRO_IMAGEN, DIAMETRO_IMAGEN, DIAMETRO_IMAGEN, null );
//Dibujamos todos los objetos encima del fondo
for( int i = 0; i < game.getObjetos().size(); i++)
g.drawImage(game.getObjetos().get(i).getImagen(), Math.round(game.getObjetos().get(i).getPosX()),Math.round(game.getObjetos().get(i).getPosY()), DIAMETRO_IMAGEN, DIAMETRO_IMAGEN, null );
//Dibujamos a todos los personajes
for( int i = 0; i < game.getPersonajes().size(); i++){
g.drawImage(game.getPersonajes().get(i).getImagen(), Math.round(game.getPersonajes().get(i).getPosX()),Math.round(game.getPersonajes().get(i).getPosY()), DIAMETRO_IMAGEN, DIAMETRO_IMAGEN, null );
}
//Dibujamos a el Heroe
g.drawImage(game.getHeroe().getImagen(), Math.round(game.getHeroe().getPosX()), Math.round(game.getHeroe().getPosY()), DIAMETRO_IMAGEN, DIAMETRO_IMAGEN, null);
if(game.finalJuego() != CONTINUAR){
perderTiempo();
if(game.finalJuego() == WIN){
System.out.println("Ganaste");
g.setColor(Color.WHITE);
g.fillRect(0, 0, ANCHO_VENTANA, ALTO_VENTANA);
g.setColor(Color.BLACK);
g.drawString("GANASTE",ANCHO_VENTANA/2-36,ALTO_VENTANA/2);
}
else if(game.finalJuego() == GAMEOVER){
System.out.println("Perdiste");
g.setColor(Color.WHITE);
g.fillRect(0, 0, ANCHO_VENTANA, ALTO_VENTANA);
g.setColor(Color.BLACK);
g.drawString("GAME OVER",ANCHO_VENTANA/2-45,ALTO_VENTANA/2);
}
perderTiempo();
System.exit(0);
}
} | 7 |
@Override
public void initialize(URL arg0, ResourceBundle arg1) {
DateFormat df = new SimpleDateFormat("yyyy/MM");
Date d = new Date();
currentMonth = df.format(d);
lblDate.setText(currentMonth);
} | 0 |
public void testFormat_invalid() {
try {
DateTimeFormat.forPattern(null);
fail();
} catch (IllegalArgumentException ex) {}
try {
DateTimeFormat.forPattern("");
fail();
} catch (IllegalArgumentException ex) {}
try {
DateTimeFormat.forPattern("A");
fail();
} catch (IllegalArgumentException ex) {}
try {
DateTimeFormat.forPattern("dd/mm/AA");
fail();
} catch (IllegalArgumentException ex) {}
} | 4 |
@Override
public boolean visit(IResourceDelta delta) {
System.out.println("NEW EVENT");
System.out.println("================================");
System.out.println(delta.toString());
IResource res = delta.getResource();
switch(res.getType()) {
case IResource.FILE:
System.out.println("file resource");
switch(delta.getKind()) {
case IResourceDelta.ADDED:
System.out.println("added");
System.out.println("type: ");
break;
case IResourceDelta.REMOVED:
System.out.println("removed");
break;
case IResourceDelta.CHANGED:
System.out.println("changed");
break;
case IResourceDelta.CONTENT:
System.out.println("content");
break;
}
}
if ((delta.getFlags() | IResourceDelta.CONTENT) == IResourceDelta.CONTENT) {
ResourceAdapter adapter = new ResourceAdapter(res);
AchievementIndex store = AchievementIndex.getInstance();
for (final Achievement achievement : store.getAllAchievements()) {
if (!achievement.isCompleted()) {
// TODO: implement Achievement#analyze(ResourceAdapter) method
/*try {
if (achievement.analyze(adapter)) {
achievement.complete();
UIJob uiJob = new UIJob("Update UI") {
public IStatus runInUIThread(
IProgressMonitor monitor) {
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
NotifierDialog.notify("Achievement",
achievement.getName());
return Status.OK_STATUS;
}
};
uiJob.schedule();
}
} catch (Exception e) {
e.printStackTrace();
}*/
}
}
}
return true;
} | 8 |
public static int getOnePageRows() {
String maxNum = getHttpServletRequest().getParameter("onePageRows");
if (StringUtils.isNull(maxNum)) {
return 20;
} else {
return Integer.parseInt(maxNum);
}
} | 1 |
private void initDisplay() {
log.info("Initializing screen subsystem...");
try {
Display.setDisplayMode(new DisplayMode(x_res, y_res));
Display.create();
log.info("Screen initialized.");
} catch (LWJGLException e) {
log.error("Caught exception. Info: " + e.getMessage());
e.printStackTrace();
System.exit(1);
}
} | 1 |
public TValue get(TKey key) {
if (!enabled) return null;
TValue value;
value = mainCache.get(key);
if (value == null && useBuffer) {
value = buffer.get(key);
}
return value;
} | 3 |
@Override
public void deserialize(Buffer buf) {
int limit = buf.readUShort();
finishedQuestsIds = new short[limit];
for (int i = 0; i < limit; i++) {
finishedQuestsIds[i] = buf.readShort();
}
limit = buf.readUShort();
finishedQuestsCounts = new short[limit];
for (int i = 0; i < limit; i++) {
finishedQuestsCounts[i] = buf.readShort();
}
limit = buf.readUShort();
activeQuests = new QuestActiveInformations[limit];
for (int i = 0; i < limit; i++) {
activeQuests[i] = ProtocolTypeManager.getInstance().build(buf.readShort());
activeQuests[i].deserialize(buf);
}
} | 3 |
final private boolean updateActiveLayer()
{
assert (update_list.size() == 0);
//double total_change = 0;
total_change = 0;
num_updated = 0;
final Iterator<BandElement> it = layers[ZERO_LAYER].iterator();
while (it.hasNext())
{
final BandElement elem = it.next();
final int x = elem.getX();
final int y = elem.getY();
final int z = elem.getZ();
// get the delta Phi
final double delta_phi = getDeltaPhi(x, y, z);
// add absolute value of the net change of this voxel to the total change
total_change += Math.abs(delta_phi);
num_updated++;
// Calculate Phi value of the voxel after an executed update
final double temp_phi = phi.get(x, y, z) + delta_phi;
if (temp_phi < INSIDE * PHI_THRESHOLD)
{
// Will move to the inside of the active set
if (zeroLayerNeighbourMovement(x, y, z, ACTIVE_OUTSIDE))
{
//System.out.println("Called - zero layer neighbour movement");
continue;
}
/* this node will move inside, so update outside neigbours as they will move
into the zero set
*/
updateZeroLayerNeighbours(x, y, z, ZERO_LAYER + OUTSIDE, temp_phi, update_list);
it.remove();
inside_list.add(elem);
action.set(x, y, z, ACTIVE_INSIDE);
}
else if (temp_phi > OUTSIDE * PHI_THRESHOLD)
{
// Will move to the outside of the active set
if (zeroLayerNeighbourMovement(x, y, z, ACTIVE_INSIDE))
{
//System.out.println("Called - zero layer neighbour movement");
continue;
}
/* this node will move outside, so update inside neigbours as they will move
into the zero set
*/
updateZeroLayerNeighbours(x, y, z, ZERO_LAYER + INSIDE, temp_phi, update_list);
it.remove();
outside_list.add(elem);
action.set(x, y, z, ACTIVE_OUTSIDE);
}
else
{
// stays in active set, schedule for update
elem.setValue(temp_phi);
update_list.add(elem);
}
}
// All calculations are done, it is safe to do the updates now
final Iterator<BandElement> it2 = update_list.iterator();
while (it2.hasNext())
{
final BandElement elem = it2.next();
// was queued more than once, only update one time so continue
if (elem.getValue() == Double.MAX_VALUE) continue;
// set the updated phi value
phi.set(elem.getX(), elem.getY(), elem.getZ(), elem.getValue());
// tag the element so it is not updated again (would be expensive)
elem.setValue(Double.MAX_VALUE);
}
// check for convergence
if ( verbose > 0 )
IJ.log("Debug: Convergence = " + (total_change / num_updated) + ", change=" + total_change + ", num_updated=" + num_updated);
// if ((total_change / num_updated) < CONVERGENCE_FACTOR)
if ((total_change / num_updated) < CONVERGENCE_WEIGHT)
{
return true;
}
else return false;
} | 9 |
public void leftClicked(Location location){
if(!freezed){
if(isUnclickedState(location) || isDoubtedState(location)){
setRevealedState(location);
moved++;
setChanged();
notifyTimerChange.setMoved(moved);
notifyObservers(notifyTimerChange);
if(!freezed){
notifyReveal(location);
if(isBlankCell(location)){
release(location);
}
}
}
}
if(revealedMineCount == rows*columns - mineNumber){
win();
}
} | 6 |
public Object [][] getDatos(){
Object[][] data = new String[getCantidad_Cuentas ()][colum_names.length];
//realizamos la consulta sql y llenamos los datos en "Object"
try{
if (colum_names.length>=0){
r_con.Connection();
String campos = colum_names[0];
for (int i = 1; i < colum_names.length; i++) {
campos+=",";
campos+=colum_names[i];
}
String consulta = ("SELECT "+campos+" "+
"FROM "+name_tabla+" WITH (INDEX("+indices_tabla[numero_ordenamiento_elegido]+"))");
PreparedStatement pstm = r_con.getConn().prepareStatement(consulta);
ResultSet res = pstm.executeQuery();
int i = 0;
while(res.next()){
for (int j = 0; j < colum_names.length; j++) {
data[i][j] = res.getString(j+1);
}
i++;
}
res.close();
}
} catch(SQLException e){
System.out.println(e);
} finally {
r_con.cierraConexion();
}
return data;
} | 5 |
public void remove() {
throw new UnsupportedOperationException();
} | 0 |
public void save(){
try {
File dir = new File("stage");
if(! dir.exists() || !dir.isDirectory()){
dir.mkdir();
}
File stageData = new File(dir,"stage.data");
if(stageData.exists()){
stageData.delete();
}
ObjectOutputStream oos = new ObjectOutputStream(new FileOutputStream(stageData));
oos.writeObject(currentStageIndex);
oos.writeObject(daemonStages);
oos.writeObject(stages);
oos.writeObject(WorldClock.get().getCurTime());
} catch (Exception e) {
e.printStackTrace();
}
} | 4 |
@Override
public void doPost(HttpServletRequest req, HttpServletResponse res)throws ServletException, IOException{
res.setContentType("text/html");
Connection con = null;
String lausend = null;
String lausend1 = null;
PreparedStatement ps = null;
PreparedStatement ps1 = null;
String kandidaat=req.getParameter("kandidaat2");
String tokens []=kandidaat.split(" ");
String eesnimi=tokens[0];
String perenimi=tokens[1];
String partei=req.getParameter("partei2");
String regioon=req.getParameter("regioon2");
if(eesnimi.length()>0 && perenimi.length()>0 && partei.length()>0 && regioon.length()>0){
try{
DriverManager.registerDriver(new AppEngineDriver());
con = DriverManager.getConnection("jdbc:google:rdbms://valmindbyut:valimindbyut/evalimised");
lausend="insert into Voter(Isik) select Id from Isik where Eesnimi=(?) and Perenimi=(?);";
ps=con.prepareStatement(lausend);
ps.setString(1, "Allar");
ps.setString(2, "Soo");
ps.execute();
//TODO
lausend1="insert into Tulemused(Kandidaat,Valimine,Regioon, Voter) select Kandidaat.Id,Valimine.Id,Regioon.Id,Voter.Id from Kandidaat,Valimine,Regioon,Voter where Kandidaat.Id=(select Id from Kandidaat where Isik=(select Id from Isik where Eesnimi=(?) and Perenimi=(?))) and Valimini.Id=(select Id from Valimine where Tyyp='evalimine') and Regioon.Id=(select Id from Regioon where Nimi=(?)) and Voter.Id=(select Id from Voter where Isik=(select Id from Isik where Eesnimi=(?) and Perenimi=(?)));";
ps1=con.prepareStatement(lausend1);
ps1.setString(1, eesnimi);
ps1.setString(2, perenimi);
ps1.setString(3, regioon);
ps1.setString(4, "Allar");
ps1.setString(5, "Soo");
}
catch(Exception e){
e.printStackTrace();
}
finally{
if(con != null){
try{
con.close();
System.out.println("Yhendus suletud");
}
catch(SQLException ignore){
}
}
}
}
else{
System.out.println("Vajalikud v2ljad on t2itmata, palun prooviga uuesti");
}
} | 7 |
public Card(Rank rank, Suit suit) {
this.rank = rank;
this.suit = suit;
switch(rank) {
case Ace:
value = 1;
break;
case Two:
value = 2;
break;
case Three:
value = 3;
break;
case Four:
value = 4;
break;
case Five:
value = 5;
break;
case Six:
value = 6;
break;
case Seven:
value = 7;
break;
case Eight:
value = 8;
break;
case Nine:
value = 9;
break;
default:
value = 10;
break;
}
} | 9 |
@Override
public MovementAction testAction(Creature c) {
Direction action = this.checkForDirt(c);
if (action != null){
return Direction.convertDirToAct(action);
}
Sensor s = c.getSensor();
ArrayList<Direction> possibleDir = new ArrayList<Direction>();
for (Direction d : Direction.values()){
int value = (int) s.getSense(d.name() + DirtBasedAgentSenseConfig.TYPE_SUFFIX).getValue();
int dist = (int) s.getSense(d.name() + DirtBasedAgentSenseConfig.DISTANCE_SUFFIX).getValue();
if (value == Environment.WALL && dist == Environment.FAR){
possibleDir.add(d);
}
}
int value = r.nextInt(possibleDir.size());
// System.out.println("Possible Directions : " + possibleDir.size());
return Direction.convertDirToAct(possibleDir.get(value));
} | 4 |
@SuppressWarnings("unchecked")
@Post
public Representation handlePost(Representation entity){
try{
Form responseHeaders = (Form) getResponse().getAttributes().get("org.restlet.http.headers");
if (responseHeaders == null) {
responseHeaders = new Form();
getResponse().getAttributes().put("org.restlet.http.headers", responseHeaders);
}
responseHeaders.add("Access-Control-Allow-Origin", "*");
JSONObject returnMessage=new JSONObject();
JSONObject args=AddressUtil.parseArgs(entity.getText());
String tracemark=(String) args.get("tracemark")==null?null:AddressUtil.unescape((String) args.get("tracemark"));
String classname = (String) args.get("classname")==null?null:AddressUtil.unescape((String) args.get("classname"));
String methodname = (String) args.get("methodname")==null?null:AddressUtil.unescape((String) args.get("methodname"));
String params = (String) args.get("params")==null?null:AddressUtil.unescape((String) args.get("params"));
String levelStr= (String) args.get("level");
TraceLevel level = null;
if (levelStr!=null) {
level = TraceLevel.valueOf(levelStr);
}else {
level = TraceLevel.ALL;
}
Pipeline pipeline = DirectOutputTracker.instance.getPipeline(tracemark, classname, StackUtils.parseMethod(methodname, params, "%3B"),level);//%3B equals ';'
Auditor.getInstance().register(pipeline);
String link=(String) AddressUtil.constructJsonObject(getReference(), pipeline).get("accessibleAddress");
returnMessage.put("link", link);
Representation rep = new StringRepresentation(returnMessage.toJSONString(),MediaType.APPLICATION_JSON);
return rep;
} catch (Exception e) {
e.printStackTrace();
return null;
}
} | 7 |
public void handleHttpResponse(HttpResponse httpResponse, int expectedStatusCode) throws HttpExpectationException, ContractException, IOException {
int statusCode;
String body;
statusCode = httpResponse.getStatusLine().getStatusCode();
body = StringUtil.convertStreamToString(httpResponse.getEntity().getContent());
ApiClient.getLogger().info("resource [" + (StringUtil.isBlank(getLocation()) ? toString() : getLocation()) + "] received [" + statusCode + "] and expected [" + expectedStatusCode + "]");
ApiResponse apiResponse = null;
/*
* Only parse JSON if the content type indicates that the response body is JSON; some
* errors will be returned from the server without a body (401) or with
* an HTML body (502).
*/
Header contentTypeHeader = httpResponse.getFirstHeader("Content-Type");
if((contentTypeHeader != null) && (contentTypeHeader.getValue() != null) && contentTypeHeader.getValue().contains("json")) {
apiResponse = fromJson(body);
}
if (statusCode != expectedStatusCode) {
throw new HttpExpectationException(statusCode, expectedStatusCode, body, apiResponse);
}
if(apiResponse == null) {
throw new ContractException("Expected a JSON body instead of " + contentTypeHeader.getValue());
}
setRequestId(httpResponse.getFirstHeader("x-animoto-request-id").getValue());
if (getLocation() == null || StringUtil.isBlank(getLocation())) {
throw new ContractException("Expected location URL to be present.");
}
} | 8 |
Subsets and Splits
SQL Console for giganticode/java-cmpx-v1
The query retrieves a limited number of text entries within a specific length range, providing basic filtering but minimal analytical insight.