text
stringlengths 14
410k
| label
int32 0
9
|
---|---|
public void tableChanged(TableModelEvent e)
{
try {
// get the index of the inserted row
//tableModel.getRowSet().moveToCurrentRow();
int firstIndex = e.getFirstRow();
// create a new table model with the new data
tableModel = new FilesTableModel(tableModel.getList(), tableModel.getEntityManager());
tableModel.addTableModelListener(this);
// update the JTable with the data
admingui.updateFileTable();
// read the data in each column using getValueAt and display it on corresponding textfield
admingui.setFile_projNameComboBox( (String) tableModel.getValueAt(firstIndex, 1));
admingui.setFile_fileNameTextField( (String) tableModel.getValueAt(firstIndex, 3));
admingui.setFile_fileFormatTextField( (String) tableModel.getValueAt(firstIndex, 2));
admingui.setFile_fileLocationTextField( (String) tableModel.getValueAt(firstIndex, 4));
} catch(Exception exp) {
exp.getMessage();
exp.printStackTrace();
}
}
| 1 |
public void mousePress(int x, int y){
for(ImageButton imgs : controlButtons){
imgs.mousePressed(x, y);
}
for(LoopNode node : graphedInputs){
if(node.mouseClicked(x, y)){
movingInputTime = true;
this.node = node;
System.out.println(node);
}
}
}
| 3 |
private void initializeLogger() {
this.log = Logger.getLogger(this.getClass().getName());
try {
FileHandler fh = new FileHandler(this.getClass().getName()
.replace("class ", "")
+ ".log");
fh.setFormatter(new SimpleFormatter());
this.log.addHandler(fh);
} catch (SecurityException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
} catch (IOException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
if (this.verbose == 0)
this.log.setUseParentHandlers(false);
else
this.log.setUseParentHandlers(true);
this.log.setLevel(Level.ALL);
}
| 3 |
void setNodeDegree(ArrayList<Edge> edges){
this.incidentEdges = new ArrayList <Integer>();
//Initialize the array for saving degree over time
for (int i=0;i<this.numTimeSlices;i++){
this.degrees.add(0);
}
//For each time slice, count the number of edges containing the node
Edge currentEdge;
int degreeCount;
for (int i=0;i<edges.size();i++){
currentEdge = edges.get(i);
if (currentEdge.node1==this.id || currentEdge.node2 == this.id){
this.incidentEdges.add(i);
for (int t=0;t<this.numTimeSlices;t++){
if (currentEdge.persistence.get(t)==1){
degreeCount = this.degrees.get(t)+1;
if (degreeCount>this.maxDegree) this.maxDegree = degreeCount;
this.degrees.set(t, degreeCount);
}
}
}
}
}
| 7 |
int possibleMovesNum(Point[] grid, Pair pr) {
int possible = 0;
for (int i = 0; i < size; i++) {
for (int j = 0; j < size; j++) {
Point currentPoint = pointAtGridIndex(grid, i, j);
if (currentPoint.value == 0) {
continue;
}
for (Pair d : directionsForPair(pr)) {
if (isValidBoardIndex(i + d.p, j + d.q)){
Point possiblePairing = pointAtGridIndex(grid, i + d.p, j + d.q);
if (currentPoint.value == possiblePairing.value) {
possible = possible + 2; //if you pile on them and if they pile on you
}
}
}
}
}
return possible;
}
| 6 |
public static boolean download(String url, String toFile) {
// dScreen = new DownloadScreen();
try {
DownloadScreen.downLoadStarted(new File(toFile).getName()
.toString());
url = url.replace(" ", "%20");
URL urll = new URL(url);
System.out.println("Opening connection to " + url + "...");
URLConnection urlC = urll.openConnection();
// allow both GZip and Deflate (ZLib) encodings
urlC.setRequestProperty("Accept-Encoding", "gzip, deflate");
// set the user agent to pass Cloud-Flare
urlC.setRequestProperty("User-agent",
"Mozilla/4.0 (compatible; Catacomb-Snatch; UnKnown)");
// Print info about resource
Date date = new Date(urlC.getLastModified());
int fileSize = urlC.getContentLength();
System.out
.print("Copying resource (type: " + urlC.getContentType());
System.out.println(", modified on: " + date.toString() + ")...");
System.out.flush();
String encoding = urlC.getContentEncoding();
InputStream is = null;
if (encoding != null && encoding.equalsIgnoreCase("gzip")) {
is = new GZIPInputStream(urlC.getInputStream());
} else if (encoding != null && encoding.equalsIgnoreCase("deflate")) {
is = new InflaterInputStream(urlC.getInputStream(),
new Inflater(true));
} else {
is = urlC.getInputStream();
}
FileOutputStream fos = null;
fos = new FileOutputStream(toFile);
int oneChar, count = 0;
while ((oneChar = is.read()) != -1) {
fos.write(oneChar);
count++;
DownloadScreen.drawGraph(count, fileSize);
}
is.close();
fos.close();
System.out.println(count + " byte(s) of " + fileSize + " copied");
DownloadScreen.downloadEnd();
return true;
} catch (MalformedURLException e) {
System.err.println(e.toString());
return false;
} catch (UnknownHostException e) {
System.err.println(e.toString());
return false;
} catch (IOException e) {
System.out.println(e.getMessage());
System.err.println(e.toString());
return false;
}
}
| 8 |
public String getRoomLetter()
{
if(potion + fragment + trap > 1)
{
return "M";
}
else if(damagePotion == 1)
{
return "D";
}
else if(potion == 1)
{
return "P";
}
else if(trap == 1)
{
return "T";
}
else if(fragment == 1)
{
return "F";
}
else if(entrance)
{
return "I";
}
else if(exit)
{
return "O";
}
else
{
return " ";
}
}
| 7 |
private static List<PositionEntity> getMovePositionsSilver(final ChessBoardEntity b, final ChessmenEntity c) {
List<PositionEntity> result = null;
if (c.isPromote()) {
result = getMovePositionsGold(b, c);
} else {
result = new ArrayList<PositionEntity>();
PositionEntity p = null;
p = new PositionEntity(c.getPosition().getX() - 1, c.getPosition().getY() - 1);
if (enablePosition(b, p)) {
result.add(p);
}
p = new PositionEntity(c.getPosition().getX(), c.getPosition().getY() - 1);
if (enablePosition(b, p)) {
result.add(p);
}
p = new PositionEntity(c.getPosition().getX() + 1, c.getPosition().getY() - 1);
if (enablePosition(b, p)) {
result.add(p);
}
p = new PositionEntity(c.getPosition().getX() - 1, c.getPosition().getY() + 1);
if (enablePosition(b, p)) {
result.add(p);
}
p = new PositionEntity(c.getPosition().getX() + 1, c.getPosition().getY() + 1);
if (enablePosition(b, p)) {
result.add(p);
}
}
return result;
}
| 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(Login.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (InstantiationException ex) {
java.util.logging.Logger.getLogger(Login.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (IllegalAccessException ex) {
java.util.logging.Logger.getLogger(Login.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (javax.swing.UnsupportedLookAndFeelException ex) {
java.util.logging.Logger.getLogger(Login.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
}
//</editor-fold>
/* Create and display the form */
java.awt.EventQueue.invokeLater(() -> {
new Login().setVisible(true);
});
}
| 6 |
public Teacher1 getTeacher1() {
return teacher1;
}
| 0 |
public boolean isInProgress()
{
return "progress".equals(status) || "start".equals(status);
}
| 1 |
private void setFiles(String[] args) {
// TODO
if (args[0] != "-x") {
if (args.length == 4) {
cipher = args[1];
blockmode = args[2];
infile = args[3];
firstoutfile = args[4] + ".txt";
finaloutfile = args[4] + "_final.txt";
} else if (args.length == 4) {
cipher = args[1];
blockmode = args[2];
infile = args[3];
} else if (args.length == 3) {
cipher = args[1];
blockmode = args[2];
} else if (args.length == 2) {
cipher = args[1];
}
} else {
if (args.length == 4) {
infile = args[2];
firstoutfile = args[3] + ".txt";
finaloutfile = args[3] + "_final.txt";
} else if (args.length == 3) {
infile = args[2];
}
}
}
| 7 |
public void updateUniforms(Matrix4f worldMatrix, Matrix4f projectedMatrix, Material material)
{
if(material.getTexture() != null)
material.getTexture().bind();
else
RenderUtil.unbindTextures();
setUniform("transform", projectedMatrix);
setUniform("baseColor", material.getColor());
setUniform("ambientLight", ambientLight);
}
| 1 |
protected void executeMoneyDrop(final MOB source, final MOB conciergeM, final Environmental possibleCoins, final CMMsg addToMsg)
{
if(possibleCoins instanceof Coins)
{
final int destIndex=destinations.indexOfFirst(source);
if(destIndex>=0)
{
Quad<MOB,Room,Double,TrackingFlags> destT=destinations.get(destIndex);
final Room destR=destT.second;
final Double owed=Double.valueOf(destT.third.doubleValue() - ((Coins)possibleCoins).getTotalValue());
if(owed.doubleValue()>0.0)
{
destT.third=owed;
CMLib.commands().postSay(conciergeM,source,L("Ok, you still owe @x1.",CMLib.beanCounter().nameCurrencyLong(conciergeM,owed.doubleValue())),true,false);
return;
}
else
if(owed.doubleValue()<0.0)
{
final double change=-owed.doubleValue();
final Coins C=CMLib.beanCounter().makeBestCurrency(conciergeM,change);
if((change>0.0)&&(C!=null))
{
// this message will actually end up triggering the hand-over.
final CMMsg newMsg=CMClass.getMsg(conciergeM,source,C,CMMsg.MSG_SPEAK,L("^T<S-NAME> say(s) 'Heres your change.' to <T-NAMESELF>.^?"));
C.setOwner(conciergeM);
final long num=C.getNumberOfCoins();
final String curr=C.getCurrency();
final double denom=C.getDenomination();
C.destroy();
C.setNumberOfCoins(num);
C.setCurrency(curr);
C.setDenomination(denom);
destT.third=Double.valueOf(0.0);
addToMsg.addTrailerMsg(newMsg);
}
else
CMLib.commands().postSay(conciergeM,source,L("Gee, thanks. :)"),true,false);
}
((Coins)possibleCoins).destroy();
giveMerchandise(source, destR, conciergeM, source.location(), destT.fourth);
destinations.removeElementFirst(source);
}
else
if(!CMLib.flags().canBeSeenBy(source,conciergeM))
CMLib.commands().postSay(conciergeM,null,L("Wha? Where did this come from? Cool!"),false,false);
}
}
| 7 |
public String toString() {
StringBuilder sb = new StringBuilder();
sb.append("[").append(bits()).append("]");
sb.append(" ").append(type());
if (checkHealth()) sb.append(" check health");
if (grown()) sb.append(" grown");
if (grown() && type() == TreeType.WILLOW) sb.append(" branches: ").append(branches());
return sb.toString();
}
| 4 |
public void setError(String error) {
this.error = error;
try {
int retryIndex = error.indexOf("retry after ");
if (retryIndex > 0) {
int beginIndex = retryIndex + 12;
String substring = error.substring(beginIndex, beginIndex + 19);
retryAfterDate = DateUtils.getGMTConverter().convert(Date.class, substring);
}
} catch (Exception e) {
// ignore.
}
}
| 2 |
protected double generateClassValue(Instances data) throws Exception {
double result = Double.NaN;
switch (m_ClassType) {
case Attribute.NUMERIC:
result = m_Random.nextFloat() * 0.25
+ Math.abs(m_Random.nextInt())
% Math.max(2, m_NumNominal);
break;
case Attribute.NOMINAL:
result = Math.abs(m_Random.nextInt()) % data.numClasses();
break;
case Attribute.STRING:
String str = "";
for (int n = 0; n < m_Words.length; n++) {
if ( (n > 0) && (m_WordSeparators.length() != 0) )
str += m_WordSeparators.charAt(m_Random.nextInt(m_WordSeparators.length()));
str += m_Words[m_Random.nextInt(m_Words.length)];
}
result = data.classAttribute().addStringValue(str);
break;
case Attribute.DATE:
result = data.classAttribute().parseDate(
(2000 + m_Random.nextInt(100)) + "-01-01");
break;
case Attribute.RELATIONAL:
if (getRelationalClassFormat() != null) {
result = data.classAttribute().addRelation(getRelationalClassFormat());
}
else {
TestInstances dataset = new TestInstances();
dataset.setNumNominal(getNumRelationalNominal());
dataset.setNumNominalValues(getNumRelationalNominalValues());
dataset.setNumNumeric(getNumRelationalNumeric());
dataset.setNumString(getNumRelationalString());
dataset.setNumDate(getNumRelationalDate());
dataset.setNumInstances(getNumInstancesRelational());
dataset.setClassType(Attribute.NOMINAL); // dummy to avoid endless recursion, will be deleted anyway
Instances rel = new Instances(dataset.generate());
int clsIndex = rel.classIndex();
rel.setClassIndex(-1);
rel.deleteAttributeAt(clsIndex);
result = data.classAttribute().addRelation(rel);
}
break;
}
return result;
}
| 9 |
public Remote440 lookup(String objName, String className) throws Remote440Exception{
try {
RemoteObjectReference objRef = null;
Socket s = new Socket(registryIP, registryport);
OutputStreamWriter out = new OutputStreamWriter(s.getOutputStream());
out.write(objName+"\n");
out.flush();
ObjectInputStream in = new ObjectInputStream(s.getInputStream());
Object response = in.readObject();
if (response instanceof Reference) {
Reference ref = (Reference) response;
if (!ref.getfind()) {
System.out.println(objName + " hasn't been registered yet!");
throw new Remote440Exception("Remote Object not found!!");
}
objRef = new RemoteObjectReference(ref.getIP(), ref.getport(), className, objName);
}
s.close();
return objRef == null? null: (Remote440) objRef.localise();
} catch (UnknownHostException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} catch (ClassNotFoundException e) {
e.printStackTrace();
}
return null;
}
| 6 |
public static ACTIONS reverseACTION(ACTIONS value){
if(value == ACTIONS.ACTION_DOWN){
return ACTIONS.ACTION_UP;
}
if(value == ACTIONS.ACTION_UP){
return ACTIONS.ACTION_DOWN;
}
if(value == ACTIONS.ACTION_RIGHT){
return ACTIONS.ACTION_LEFT;
}
if(value == ACTIONS.ACTION_LEFT){
return ACTIONS.ACTION_RIGHT;
}
return ACTIONS.ACTION_NIL;
}
| 4 |
public String getHtml(WikiContext context) throws ChildContainerException {
try {
if (context.getAction().equals("confirm")) {
startTask();
sendRedirect(context, context.getPath());
return "Unreachable code";
}
boolean showBuffer = false;
String confirmTitle = null;
String cancelTitle = null;
String title = null;
switch (getState()) {
case STATE_WORKING:
showBuffer = true;
title = "Posting 'Like' message to NNTP...";
cancelTitle = "Cancel";
break;
case STATE_WAITING:
showBuffer = false;
title = "Confirm send of 'Like' message.";
confirmTitle = "Send";
cancelTitle = "Cancel";
break;
case STATE_SUCCEEDED:
showBuffer = true;
title = "Send Succeeded";
cancelTitle = "Done";
break;
case STATE_FAILED:
showBuffer = true;
title = "Send Failed";
confirmTitle = "Retry";
cancelTitle = "Done";
break;
}
setTitle(title);
StringWriter buffer = new StringWriter();
PrintWriter body = new PrintWriter(buffer);
body.println("<h3>" + escapeHTML(title) + "</h3>");
if (showBuffer) {
body.println("<pre>");
body.print(escapeHTML(getOutput()));
body.println("</pre>");
}
addButtonsHtml(context, body, confirmTitle, cancelTitle);
body.close();
return buffer.toString();
} catch (IOException ioe) {
context.logError("LikingVerson", ioe);
return "Error LikingVersion.";
}
}
| 7 |
private static Point[][] get64PlayersPositions() {
int maxPlayers = 64;
Point[][] pos = new Point[8][128];
for(int i = 0; i < maxPlayers;i++ ){
pos [0][i] = new Point(0,2*i);
}
for(int i = 0; i < maxPlayers/2;i++ ){
pos [1][i] = new Point(2 ,1+4*i);
}
for(int i = 0; i < maxPlayers/4;i++ ){
pos [2][i] = new Point(4 ,3+8*i);
}
for(int i = 0; i < maxPlayers/8;i++ ){
pos [3][i] = new Point(6 ,7+16*i);
}
for(int i = 0; i < maxPlayers/16;i++ ){
pos [4][i] = new Point(8 ,15+32*i);
}
for(int i = 0; i < maxPlayers/32;i++ ){
pos [5][i] = new Point(10 ,31+64*i);
}
for(int i = 0; i < maxPlayers/64;i++ ){
pos [6][i] = new Point(12 ,63+128*i);
}
return pos;
}
| 7 |
public final int getExtendedHeaderSize() {
return ((this.grouping_identity_byte == null ? 0 : 1)
+ (this.encryption_method == null ? 0 : 1) + (this.data_length_indicator == null ? 0
: 4));
}
| 3 |
public boolean isAccepted() {
Iterator it = myConfigurations.iterator();
while (it.hasNext()) {
PDAConfiguration configuration = (PDAConfiguration) it.next();
if (myAcceptance == FINAL_STATE) {
State currentState = configuration.getCurrentState();
if (configuration.getUnprocessedInput() == ""
&& myAutomaton.isFinalState(currentState)) {
return true;
}
} else if (myAcceptance == EMPTY_STACK) {
CharacterStack stack = configuration.getStack();
if (configuration.getUnprocessedInput() == ""
&& stack.height() == 0) {
return true;
}
}
}
return false;
}
| 7 |
void addConstructor(CtMember cons) {
cons.next = consTail.next;
consTail.next = cons;
if (consTail == fieldTail)
fieldTail = cons;
consTail = cons;
}
| 1 |
public QuickUnion(int n){
id = new int[n];
for(int i = 0; i < n; i++)
id[i]=i;
}
| 1 |
private PrintService getPrintService() {
// This method exists since some implementations throw a runtime
// exception if no printer was ever defined on the system.
try {
return mJob.getPrintService();
} catch (Exception exception) {
return null;
}
}
| 1 |
public MessageReceiver(BufferedReader inputMessageReceiver,
int fileTransferPort, int verbose) {
this.inputMessageReceiver = inputMessageReceiver;
this.fileReceiverThread = null;
this.fileTransferPort = fileTransferPort;
this.verbose = verbose;
}
| 0 |
@Override
public void draw(Graphics g) {
// If alive, draw picture of ragnaros
if (Alive) {
g.drawImage(img1, pos_x, pos_y, width, height, null);
}
// If dead, draw explosion
else {
g.drawImage(img2, pos_x, pos_y, width, height, null);
}
}
| 1 |
private List<Posicao> capturasPossiveisPeaoPreto(Posicao posicao) {
List<Posicao> capturasPossiveis = new ArrayList<>();
Peca peca;
/* verifica se nao esta na primeira linha */
if (posicao.getLinha() - 1 >= 0) {
/* verifica se nao esta na primeira coluna */
if (posicao.getColuna() - 1 >= 0) {
peca = this.getCasas(posicao.getColuna() - 1,
posicao.getLinha() - 1);
if (peca != null) /* se a peca de destino for branca, pode capturar */ {
if (peca.getCor().equals(Cores.branco)) {
capturasPossiveis
.add(new Posicao(posicao.getColuna() - 1,
posicao.getLinha() - 1));
}
}
}
/* verifica se nao esta na ultima coluna */
if (posicao.getColuna() + 1 <= 7) {
peca = this.getCasas(posicao.getColuna() + 1,
posicao.getLinha() - 1);
if (peca != null) /* se a peca de destino for branca, pode capturar */ {
if (peca.getCor().equals(Cores.branco)) {
capturasPossiveis
.add(new Posicao(posicao.getColuna() + 1,
posicao.getLinha() - 1));
}
}
}
}
return capturasPossiveis;
}
| 7 |
public Rabbit(boolean randomAge, Field field, Location location)
{
super(field, location);
setAge(0);
if(randomAge) {
setAge(getRandom().nextInt(MAX_AGE));
}
}
| 1 |
public default boolean checkLife() {
if (this.getCurrentHp() > 0) {
return true;
} else {
return false;
}
}
| 1 |
@Override
public void slaOpdrachtOp(OpdrachtCatalogus opdrachtCatalogus,
Opdracht opdracht) {
try {
String vraag = opdracht.getVraag();
String antwoord = opdracht.getAntwoord();
int maxAantalPogingen = opdracht.getMaxAantalPogingen();
String antwoordHint = opdracht.getAntwoordHint();
int maxAntwoordTijd = opdracht.getmaxAntwoordTijd();
OpdrachtCategorie opdrachtCategorie = opdracht
.getOpdrachtCategorie();
int opdrachtCategorieID = 0;
con = JDBCConnection.getConnection();
pst = con
.prepareStatement("select idopdrachtCategorieën from opdrachtcategorieën where opdrachtCategorieNaam=?");
pst.setString(1, opdrachtCategorie.toString());
rs = pst.executeQuery();
while (rs.next()) {
opdrachtCategorieID = rs.getInt(1);
}
String opdrachtClass = opdracht.getClass().getSimpleName();
if (opdrachtClass.equals("Meerkeuze")) {
int opdrachtSoortId = zoekOpdrachtsoortID("Meerkeuze");
int opdrachtID= maakOpdrachtAan(vraag, antwoord, maxAantalPogingen, antwoordHint, maxAntwoordTijd, opdrachtCategorieID, opdrachtSoortId);
String alleKeuzes = ((Meerkeuze) opdracht).getAlleKeuzes();
pst = con
.prepareStatement("insert into meerkeuzeopdrachten (idmeerkeuzeOpdrachten,alleKeuzes) values(?,?)");
pst.setInt(1, opdrachtID);
pst.setString(2, alleKeuzes);
pst.executeUpdate();
} else if (opdrachtClass.equals("Opsomming")) {
int opdrachtSoortId = zoekOpdrachtsoortID("Opsomming");
int opdrachtID= maakOpdrachtAan(vraag, antwoord, maxAantalPogingen, antwoordHint, maxAntwoordTijd, opdrachtCategorieID, opdrachtSoortId);
pst = con
.prepareStatement("insert into opsommingsopdrachten (idopsommingsOpdrachten) values(?)");
pst.setInt(1, opdrachtID);
pst.executeUpdate();
} else if (opdrachtClass.equals("Reproductie")) {
int opdrachtSoortId = zoekOpdrachtsoortID("Reproductie");
int opdrachtID= maakOpdrachtAan(vraag, antwoord, maxAantalPogingen, antwoordHint, maxAntwoordTijd, opdrachtCategorieID, opdrachtSoortId);
String trefwoorden = ((Reproductie) opdracht).getTrefwoorden();
int minAantalTrefwoorden = ((Reproductie) opdracht)
.getMinAantalJuisteTrefwoorden();
pst = con
.prepareStatement("insert into reproductieopdrachten (idreproductieOpdrachten,trefwoorden,minAantalTrefwoorden) values(?,?,?)");
pst.setInt(1, opdrachtID);
pst.setString(2, trefwoorden);
pst.setInt(3, minAantalTrefwoorden);
pst.executeUpdate();
}
opdrachtCatalogus.addOpdrachtToList(opdracht);
} catch (SQLException sqlex) {
System.out.println(sqlex.getMessage());
} catch (Exception e) {
System.out.println(e.getMessage());
}
}
| 6 |
public String getTag() {
return tag;
}
| 0 |
public ArrayList<Intersection> getNeighbours(Intersection node) {
ArrayList<Intersection> neighbours = new ArrayList<Intersection>();
for (Segment seg : node.getEdges()) {
if (seg.getNodeID1().equals(node)) {
if (seg.getNodeID2() != null) {
neighbours.add(seg.getNodeID2());
}
} else if (seg.getNodeID2().equals(node)) {
if (seg.getNodeID1() != null) {
neighbours.add(seg.getNodeID1());
}
}
}
return neighbours;
}
| 5 |
public void execute(Joueur jou){
Joueur proprio = this.getProprietaire();
if(jou.equals(proprio)){
return;
}
else if(proprio == null){
Scanner sc = new Scanner(System.in);
if(this.getLoyerBase() <= jou.getCash()){
System.out.println("Voulez-vous acheter cette compagnie : y/n Cela vous coutera : " + getPrixAchat() + "(toute autre réponses sont considerer comme 'n')");
String Answer = sc.nextLine();
if("y".equals(Answer)){
jou.addCompagnie(this);
jou.ajouterArgent(-getPrixAchat());
System.out.println("Achat effectué !\n");
}
else {
System.out.println("Vous n'achetez pas !");
}
}
else{
System.out.println("Vous ne pouvez pas acheter ce terrain, trop cher !");
}
}
else{
int nbComp= proprio.getNbCompagnies();
int aDebiter=0;
int [] buff = jou.getDes();
for(int i=0;i<buff.length-1;i++){
aDebiter = aDebiter+buff[i];
}
if(nbComp==1){
aDebiter=aDebiter*4;
}
else if(nbComp==2){
aDebiter=aDebiter*10;
}
jou.ajouterArgent(-aDebiter);
proprio.ajouterArgent(aDebiter);
}
}
| 7 |
private static AudioFormat audioFormatFromHeaderValue(int audioFormat) {
switch (audioFormat) {
case 0:
return AudioFormat.UNSPECIFIED;
case 1:
return AudioFormat.OGG_VORBIS;
case 2:
return AudioFormat.FLAC;
case 3:
return AudioFormat.PCM_S16LE;
default:
return null;
}
}
| 4 |
public int GetNumberOfPersonsCreated()
{
return personsCreated;
}
| 0 |
private final boolean finishOldWork() throws FatalError {
Output.printClockLn("Versuche alte Aufgaben zu beenden.", 2);
boolean returnValue = false;
switch (User.getStatus()) {
case work:
returnValue = PlanArbeiten.finish();
break;
case service:
returnValue = Aussendienst.finish();
break;
case training:
Output.printTabLn("Versuche das Training zu beenden.", 1);
Utils.visit("training");
returnValue = true;
break;
case nothing:
default:
returnValue = true;
break;
}
this.getCharacter();
return returnValue;
}
| 4 |
public int pwm() {
System.out.println(temperatureRange);
System.out.println(delay_on[temperatureRange]);
System.out.println(delay_off[temperatureRange]);
if(temperatureRange == 0 || temperatureRange == 7){
range();
return 1;
}
try{
while(Interupt == 0)
{
InLoop = 1;
//set all the pin On.
for(int j=0;j<8;j++){
setGpioPin(j, 1);
}
//delay the pin when it is On.
if(delay_on[temperatureRange]!=0){
Thread.sleep(delay_on[temperatureRange]);
}
//set all the pin Off.
for(int j=0;j<8;j++){
setGpioPin(j, 0);
}
//delay the pin when it is Off.
if(delay_off[temperatureRange]!=0){
Thread.sleep(delay_off[temperatureRange]);
}
}
}
catch(Exception ex){
gpio.shutdown();
ex.printStackTrace();
}
Interupt = 0;
InLoop = 0;
return 1;
}
| 8 |
public boolean method577(int arg0) {
if (objectTypes == null) {
if (modelIds == null) {
return true;
}
if (arg0 != 10) {
return true;
}
boolean flag1 = true;
for (int element : modelIds) {
flag1 &= Model.isCached(element & 0xffff);
}
return flag1;
}
for (int j = 0; j < objectTypes.length; j++) {
if (objectTypes[j] == arg0) {
return Model.isCached(modelIds[j] & 0xffff);
}
}
return true;
}
| 6 |
public void browserMoveObject(String objectName, String targetPath) {
String objectPath;
FileableCmisObject object;
if (browseFolder.isRootFolder()) {
objectPath = browseFolder.getPath() + objectName;
} else {
objectPath = browseFolder.getPath() + "/" + objectName;
}
try {
object = (FileableCmisObject) session.getObjectByPath(objectPath);
Folder target;
try {
target = (Folder) session.getObjectByPath(targetPath);
object.move(browseFolder, target);
} catch (CmisObjectNotFoundException e) {
System.out.println("Folder not found: " + e.getMessage());
} catch (ClassCastException e) {
System.out.println("Object is not a CMIS folder: "
+ e.getMessage());
}
} catch (CmisObjectNotFoundException e) {
System.out.println("Object not found: '" + objectPath + "': "
+ e.getMessage());
}
}
| 4 |
public void act(List<Actor> newRabbits)
{
incrementAge();
incrementHunger();
if(isAlive()) {
infectionChance(newRabbits);
}
if(isAlive()) {
giveBirth(newRabbits);
// Move towards a source of food if found.
Location location = getLocation();
Location newLocation = findFood(location);
if(avoidZombies()!=null) {
newLocation = avoidZombies();
}
else {
findFood(location);
}
if(newLocation == null) {
// No food found - try to move to a free location.
newLocation = getField().freeAdjacentLocation(location);
}
// See if it was possible to move.
if(newLocation != null) {
setLocation(newLocation);
}
else {
// Overcrowding.
setDead();
}
}
}
| 5 |
@Override
public void eUnset(int featureID) {
switch (featureID) {
case statePackage.STATE__PLAYERS:
getPlayers().clear();
return;
case statePackage.STATE__COUNTRY_STATE:
getCountryState().clear();
return;
case statePackage.STATE__TURN:
setTurn((Player)null);
return;
case statePackage.STATE__PHASE:
setPhase(PHASE_EDEFAULT);
return;
case statePackage.STATE__STATE:
setState(STATE_EDEFAULT);
return;
case statePackage.STATE__TROOPS_TO_SET:
setTroopsToSet(TROOPS_TO_SET_EDEFAULT);
return;
case statePackage.STATE__CONQUERED_COUNTRY:
setConqueredCountry(CONQUERED_COUNTRY_EDEFAULT);
return;
}
super.eUnset(featureID);
}
| 7 |
@Override
public void delete(Key key) {
Node x = this.root;
Node parent = x, temp;
temp = x;
while (x != null) {
int cmp = key.compareTo(x.key);
if (cmp < 0)
x = x.left;
else if (cmp > 0)
x = x.right;
else {
if (isLeaf(x)) {
if (parent.right != null && parent.right.equals(x))
parent.right = null;
else if (parent.left != null && parent.left.equals(x))
parent.left = null;
else if (parent.equals(x))
root = null;
}
}
parent = temp;
}
}
| 9 |
public void newGame(Difficulty difficulty) {
// set difficulty and creates a new board
this.height = difficulty.height();
this.width = difficulty.width();
this.nbMines = difficulty.nbMine();
this.nbFlags = 0;
cells = new Cell[width][height];
for (int i = 0; i < width; i++) {
for (int j = 0; j < height; j++) {
cells[i][j] = new Cell();
}
}
nbCellsLeft = width * height;
createMine(nbMines);
if (isCheating) {
isCheating = false;
cheat();
}
}
| 3 |
public int generateId() {
int res = 0;
File dir = new File(this.configDirectory);
File[] configs = dir.listFiles();
if (configs == null) {
return 0;
}
for (File file : configs) {
if (file.getName().equals("config.server")) {
FileInputStream fis = null;
BufferedInputStream bis = null;
BufferedReader reader = null;
try {
fis = new FileInputStream(file);
bis = new BufferedInputStream(fis);
reader = new BufferedReader(new InputStreamReader(bis));
String entry;
while ((entry = reader.readLine()) != null) {
res = Integer.parseInt(entry);
}
} catch (Exception e) {
e.printStackTrace();
} finally {
try {
fis.close();
bis.close();
reader.close();
} catch (IOException e) {
System.out.println("Error closing streams!");
e.printStackTrace();
}
}
}
}
FileWriter fw = null;
BufferedWriter out = null;
try {
fw = new FileWriter(this.configDirectory
+ System.getProperty("file.separator") + "config.server");
out = new BufferedWriter(fw);
int temp = res + 1;
out.write(Integer.toString(temp));
out.flush();
} catch (Exception e) {
System.out.println("Error writing to file!");
e.printStackTrace();
} finally {
try {
fw.close();
out.close();
} catch (IOException e) {
System.out.println("Error closing streams!");
e.printStackTrace();
}
}
return res + 1;
}
| 8 |
public void assinar() throws IOException, Exception{
int index = s.getCertificateList().getSelectionModel().getLeadSelectionIndex();
//System.out.println(s.getSigners().get(index));
ICPBrasilSigner signer = s.getSigners().get(index);
// System.out.println(new File("xmls/1.xml").exists());
FirstSignature command = new FirstSignature(new File("xmls/"+codRenavam+".xml"), signer);
File f = new File("assinados/"+codRenavam+".p7s");
if(f.exists())
f.delete();
FileOutputStream assinado = new FileOutputStream(new File("assinados/"+codRenavam+".p7s"));
assinado.write(command.execute(SignType.ADRB1V0));
assinado.close();
if(wirzzard){
// this.conectarLeitora();
ControllerSmartCard cs = new ControllerSmartCard(null, null);
cs.conectarLeitora();
String result = cs.gravar("assinados/"+codRenavam+".p7s");
System.out.println(result);
}
}
| 2 |
protected static <S> void verifyIsOuterClass(
Class<S> serviceClass, Class<? extends S> providerClass, Scope scope)
throws ServiceInstantiationException {
// If it's an inner class, it must be declared static
Class<?> declaringClass=providerClass.getDeclaringClass();
if (declaringClass!=null) {
Class<?>[] innerClasses=declaringClass.getDeclaredClasses();
for (Class<?> innerClass: innerClasses) {
if (!Modifier.isStatic(innerClass.getModifiers())) {
throw new ServiceInstantiationException(serviceClass,
"Could not instantiate service provider class "+
providerClass.getName()+" of service type "+
serviceClass.getName()+" in scope \""+scope+
"\" because it is an non-static inner class");
}
}
}
}
| 7 |
public MainWindow()
{
/**
* Initialisation des elements graphiques
*/
// Definition de la frame
frame = new JFrame("Automaton cellular");
frame.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
frame.setPreferredSize(new Dimension(1100, 600));
frame.setMinimumSize(new Dimension(1100, 600));
frame.setResizable(false);
// Creation du panel contenant la grille
backgroundPanel = new JPanel();
backgroundPanel.setLayout(new BorderLayout());
backgroundPanel.setBorder(new EmptyBorder(30,30,30,30));
backgroundPanel.setPreferredSize(new Dimension(500,500));
// Panel user interface
uiPanel = new JPanel();
uiPanel.setLayout(new GridLayout(5,1,5,5));
uiPanel.setBorder(new EmptyBorder(30,5,30,5));
uiPanel.setPreferredSize(new Dimension(500, 600));
uiPanel.setMinimumSize(new Dimension(500, 600));
// Panel choix taille grille
sizePanel = new JPanel();
// Panel choix obstacles et personnes
obsAndPersPanel = new JPanel();
obsAndPersPanel.setLayout(new GridLayout(3,2));
// Panel choix nombre d'entree
nbEntryPanel = new JPanel();
nbEntryPanel.setLayout(new GridLayout(3,2));
// Panel choix du positionnement des entrees
posEntryPanel = new JPanel();
posEntryPanel.setLayout(new GridLayout(0,4));
// Panel boutons
buttonsPanel = new JPanel();
buttonsPanel.setLayout(new GridLayout(3,3,5,5));
// Boutons
start = new JButton("start");
stop = new JButton("stop");
restart = new JButton("restart");
confirm = new JButton("confirm");
start.setEnabled(false);
restart.setEnabled(false);
stop.setEnabled(false);
buttonsPanel.add(confirm);
buttonsPanel.add(start);
buttonsPanel.add(stop);
buttonsPanel.add(restart);
fieldNbEntries = new JTextField();
fieldNbEntries.setText("[1,0]");
lblNbEntries = new JLabel("Entries: [x,y] ");
lblNbEntries.setLabelFor(fieldNbEntries);
NumberFormat percentFormat = NumberFormat.getNumberInstance();
percentFormat.setMinimumFractionDigits(2);
fieldLambda = new JFormattedTextField(percentFormat);
fieldLambda.setValue(lambda);
lblLambda = new JLabel("Diagonal movements value: ");
lblLambda.setLabelFor(lblLambda);
newFigure = new JCheckBox();
newFigure.setSelected(true);
newFigure.setEnabled(false);
lblnewFigure = new JLabel("Open a new chart");
lblnewFigure.setLabelFor(newFigure);
nbEntryPanel.add(lblLambda);
nbEntryPanel.add(fieldLambda);
nbEntryPanel.add(lblNbEntries);
nbEntryPanel.add(fieldNbEntries);
nbEntryPanel.add(lblnewFigure);
nbEntryPanel.add(newFigure);
// taille de la grille
Integer[] size = new Integer[SIZE_MAX];
for(int i = 1; i <= SIZE_MAX ; i++) size[i - 1] = i;
cbNbLigne = new JComboBox(size);
cbNbCol = new JComboBox(size);
lblSize = new JLabel("Grid size");
cbNbLigne.setSelectedIndex(nbLigneGrille-1);
cbNbCol.setSelectedIndex(nbColGrille-1);
JLabel lblligne = new JLabel("lines");
JLabel lblcol = new JLabel("columns");
sizePanel.add(lblSize);
sizePanel.add(cbNbLigne);
sizePanel.add(lblligne);
sizePanel.add(cbNbCol);
sizePanel.add(lblcol);
// Obstacles et Personnes
lblObstacles = new JLabel("Obstacles ([xStart,yStart;xEnd,yEnd]");
lblPersonnes = new JLabel("Persons ([x,y])");
fieldObstacles = new JTextField();
fieldObstacles.setText("[2,2;4,2][7,2;8,2][2,4;4,4][7,4;8,4][2,6;4,6][7,6;8,6][5,8;6,8]");
fieldObstacles.setMaximumSize(new Dimension(50, 30));
fieldPersonnes = new JTextField();
fieldPersonnes.setText("[2,1][3,1][4,1][7,1][8,1][2,3][3,3][4,3][7,3][8,3][2,5][3,5][4,5][7,5][8,5][6,9]");
lblObstacles.setLabelFor(fieldObstacles);
lblPersonnes.setLabelFor(fieldPersonnes);
obsAndPersPanel.add(lblObstacles);
obsAndPersPanel.add(fieldObstacles);
obsAndPersPanel.add(lblPersonnes);
obsAndPersPanel.add(fieldPersonnes);
uiPanel.add(sizePanel);
uiPanel.add(obsAndPersPanel);
uiPanel.add(nbEntryPanel);
uiPanel.add(posEntryPanel);
uiPanel.add(buttonsPanel);
// Ajout du panel a la frame + dessin + affichage
frame.add("Center",backgroundPanel);
frame.add("East",uiPanel);
frame.pack();
frame.setVisible(true);
/**
* Definition des actions liees aux boutons
*/
/**
* Permet de confirmer que la grille a creer est bien conforme
*/
confirm.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent arg0) {
nbLigneGrille = cbNbLigne.getSelectedIndex() + 1;
nbColGrille = (Integer) cbNbCol.getItemAt(cbNbCol.getSelectedIndex());
setEntries();
setPersonnes();
setObstacles();
if(areValidObstacles())
{
if(areValidPersonnes())
{
if(isValidEntry())
{
posEntryPanel.removeAll();
if(controlleur != null){
backgroundPanel.remove(controlleur.getDrawArea());
}
lambda = Float.parseFloat(fieldLambda.getText().replace(",","."));
if(newFigure.isSelected())
{
chartline = new ChartLine("Sortie des personnes");
}
Grid grille = new Grid(nbLigneGrille, nbColGrille, tabX, tabY, lambda, obstacles);
controlleur = new Controller(grille, personnes ,chartline);
backgroundPanel.add("Center",controlleur.getDrawArea());
frame.repaint();
frame.pack();
start.setEnabled(true);
}
else
{
JOptionPane.showMessageDialog(frame, "Entree(s) invalide(s)");
}
}else{
JOptionPane.showMessageDialog(frame, "Personne(s) invalide(s)");
}
}else
{
JOptionPane.showMessageDialog(frame, "Obstacle(s) invalide(s)");
}
}
});
/**
* Demarre la simulation
*/
start.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent arg0) {
controlleur.startSimulation();
stop.setEnabled(true);
start.setEnabled(false);
restart.setEnabled(true);
confirm.setEnabled(false);
newFigure.setEnabled(true);
}
});
/**
* Mets en pause la simulation
*/
stop.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent arg0) {
controlleur.stopSimulation();
start.setEnabled(true);
stop.setEnabled(false);
confirm.setEnabled(true);
}
});
/**
* Re-initialise la grille
*/
restart.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent arg0) {
stop.setEnabled(false);
backgroundPanel.remove(controlleur.getDrawArea());
if(newFigure.isSelected())
{
chartline = new ChartLine("Sortie des personnes");
}
Grid grille = new Grid(nbLigneGrille, nbColGrille, tabX, tabY, lambda, obstacles);
controlleur = new Controller(grille,personnes,chartline);
backgroundPanel.add("Center",controlleur.getDrawArea());
frame.repaint();
frame.pack();
start.setEnabled(true);
confirm.setEnabled(true);
}
});
}
| 7 |
public void updateUsks(PrintStream out) throws IOException, InterruptedException {
out.println("----------------------------------------");
out.println("Finding USKs...");
out.println("----------------------------------------");
Map<String, Integer> latest = new HashMap<String, Integer>();
for (String pageName : mOverlay.getNames()) {
Matcher matcher = USK_REGEX.matcher(mOverlay.getPage(pageName));
int count = 0;
while (matcher.find()) {
if (count == 0) {
out.println("[" + pageName +"]");
}
out.println(matcher.group());
int index = Integer.parseInt(matcher.group(3));
if (latest.get(matcher.group(2)) == null ||
latest.get(matcher.group(2)) < index) {
latest.put(matcher.group(2), index);
}
count++;
}
}
out.println("----------------------------------------");
out.println("Looking up latest versions...");
out.println("----------------------------------------");
FcpTools runner = new FcpTools(mFcpHost, mFcpPort, "jfniki");
FcpTools.setDebugOutput(out);
for (Map.Entry<String, Integer> entry : latest.entrySet()) {
String usk = String.format("%s%d/", entry.getKey(), entry.getValue());
FcpTools.CheckUsk cmd = runner.sendCheckUsk(usk);
runner.waitUntilAllFinished();
if (!cmd.getUri().equals(usk)) {
String[] fields = cmd.getUri().split("/");
latest.put(entry.getKey(),
Integer.parseInt(fields[fields.length -1]));
}
}
out.println("----------------------------------------");
out.println("Fixing pages...");
out.println("----------------------------------------");
for (String pageName : mOverlay.getNames()) {
updateUsksOnPage(latest, pageName, out);
}
}
| 8 |
public synchronized void disconnectClient (int ID)
{
//Closes the socket in addition to the input and output streams
try
{
((TcpThread) flexclients.get (ID)).Soutput.close ();
((TcpThread) flexclients.get (ID)).Sinput.close ();
((TcpThread) flexclients.get (ID)).socket.close ();
}
catch (Exception e)
{
}
//deletes the client from the client list
flexclients.remove (ID);
updateClients ();
}
| 1 |
public void testErodingPoolKeyedObjectPool() throws Exception {
try {
PoolUtils.erodingPool((KeyedObjectPool<Object, Object>)null);
fail("PoolUtils.erodingPool(KeyedObjectPool) must not allow a null pool.");
} catch(IllegalArgumentException iae) {
// expected
}
try {
PoolUtils.erodingPool((KeyedObjectPool<Object, Object>)null, 1f);
fail("PoolUtils.erodingPool(KeyedObjectPool, float) must not allow a null pool.");
} catch(IllegalArgumentException iae) {
// expected
}
try {
PoolUtils.erodingPool((KeyedObjectPool<Object, Object>)null, 0);
fail("PoolUtils.erodingPool(ObjectPool, float) must not allow a non-positive factor.");
} catch(IllegalArgumentException iae) {
// expected
}
try {
PoolUtils.erodingPool((KeyedObjectPool<Object, Object>)null, 1f, true);
fail("PoolUtils.erodingPool(KeyedObjectPool, float, boolean) must not allow a null pool.");
} catch(IllegalArgumentException iae) {
// expected
}
try {
PoolUtils.erodingPool((KeyedObjectPool<Object, Object>)null, 0, false);
fail("PoolUtils.erodingPool(ObjectPool, float, boolean) must not allow a non-positive factor.");
} catch(IllegalArgumentException iae) {
// expected
}
final List<String> calledMethods = new ArrayList<String>();
final InvocationHandler handler = new MethodCallLogger(calledMethods) {
@Override
public Object invoke(final Object proxy, final Method method, final Object[] args) throws Throwable {
Object o = super.invoke(proxy, method, args);
if (o instanceof Integer) {
// so getNumActive/getNumIdle are not zero.
o = new Integer(1);
}
return o;
}
};
// If the logic behind PoolUtils.erodingPool changes then this will need to be tweaked.
float factor = 0.01f; // about ~9 seconds until first discard
@SuppressWarnings("unchecked")
final KeyedObjectPool<Object, Object> pool = PoolUtils.erodingPool((KeyedObjectPool<Object, Object>)createProxy(KeyedObjectPool.class, handler), factor);
final List<String> expectedMethods = new ArrayList<String>();
assertEquals(expectedMethods, calledMethods);
final Object key = "key";
Object o = pool.borrowObject(key);
expectedMethods.add("borrowObject");
assertEquals(expectedMethods, calledMethods);
pool.returnObject(key, o);
expectedMethods.add("returnObject");
assertEquals(expectedMethods, calledMethods);
for (int i=0; i < 5; i ++) {
o = pool.borrowObject(key);
expectedMethods.add("borrowObject");
Thread.sleep(50);
pool.returnObject(key, o);
expectedMethods.add("returnObject");
assertEquals(expectedMethods, calledMethods);
expectedMethods.clear();
calledMethods.clear();
}
Thread.sleep(10000); // 10 seconds
o = pool.borrowObject(key);
expectedMethods.add("borrowObject");
pool.returnObject(key, o);
expectedMethods.add("getNumIdle");
expectedMethods.add("invalidateObject");
assertEquals(expectedMethods, calledMethods);
}
| 7 |
private int jjMoveStringLiteralDfa6_0(long old0, long active0)
{
if (((active0 &= old0)) == 0L)
return jjStartNfa_0(4, old0);
try { curChar = input_stream.readChar(); }
catch(java.io.IOException e) {
jjStopStringLiteralDfa_0(5, active0);
return 6;
}
switch(curChar)
{
case 101:
if ((active0 & 0x10000000L) != 0L)
return jjStartNfaWithStates_0(6, 28, 8);
return jjMoveStringLiteralDfa7_0(active0, 0x80L);
case 105:
return jjMoveStringLiteralDfa7_0(active0, 0x410000L);
case 111:
return jjMoveStringLiteralDfa7_0(active0, 0x81006000L);
case 116:
if ((active0 & 0x8000000L) != 0L)
return jjStartNfaWithStates_0(6, 27, 8);
break;
case 117:
return jjMoveStringLiteralDfa7_0(active0, 0x21000L);
default :
break;
}
return jjStartNfa_0(5, active0);
}
| 9 |
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(BrowseAndSearchGUI.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (InstantiationException ex) {
java.util.logging.Logger.getLogger(BrowseAndSearchGUI.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (IllegalAccessException ex) {
java.util.logging.Logger.getLogger(BrowseAndSearchGUI.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (javax.swing.UnsupportedLookAndFeelException ex) {
java.util.logging.Logger.getLogger(BrowseAndSearchGUI.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 BrowseAndSearchGUI().setVisible(true);
}
});
}
| 6 |
private JLabel getJLabel0() {
if (jLabel0 == null) {
jLabel0 = new JLabel();
jLabel0.setText("UPDATE OPERATION");
}
return jLabel0;
}
| 1 |
public static boolean[] stepPattern(boolean[] pattern) throws SolvingInitialisiationException{
boolean[] newPattern = new boolean[pattern.length];
for (int i = 0; i < pattern.length; i++){
newPattern[i] = pattern[i];
}
for (int i = 1; i < pattern.length; i++){
if (pattern[i] == false){
newPattern[i] = true;
return newPattern;
}
else{
newPattern[i] = false;
}
}
throw new SolvingInitialisiationException();
}
| 3 |
@Test
public void RunHeursticsSimulator() throws Exception {
populateArray();
System.out.format("\nPerfect Cache is %b, Perfect branch predictor is %b, width is %d\n\n",perfectCache,perfect_bpred,machWidth);
for(int i=2; i<10; i++){
traceName = traceNames[i];
testTrace = traceName + ".trace.gz";
String tracePath = "/project/cec/class/cse560/traces/" + testTrace;
//String tracePath = "traces/" + testTrace;
System.out.format("\n************Starting on trace %s.************\n",traceName);
if (heuristic.type == HeuristicType.heuristic_ALL) {
for (HeuristicType Looptype : HeuristicType.values())
{
if(perfectCache){//if we have a perfect cache it makes no sense to run these heuristics
if(Looptype == HeuristicType.heuristic_LOAD_MISSED || Looptype == HeuristicType.heuristic_LOADS_FIRST_MISSED)
continue;
}
if (Looptype == HeuristicType.heuristic_ALL)
continue;
else
{
PerfSim sim = new PerfSim(tracePath, nPregs);
sim.uopLimit = 1000000000;
sim.machineWidth = machWidth;
sim.bpredPenalty = branchPen;
sim.latencyMultiplier = latencyMultiplier;
sim.heurType = heurType;
sim.perfect_bpred_f = perfect_bpred;
sim.perfectCache_f = perfectCache;
sim.ROB.setMaxEntries(ROBsize);
heuristic.type = Looptype;
sim.heuristic = heuristic;
sim.simulate();
}
// setting back to all for next loop
heuristic.type = HeuristicType.heuristic_ALL;
}
}
else
{
PerfSim sim = new PerfSim(tracePath, nPregs);
sim.uopLimit = 1000000000;
sim.machineWidth = machWidth;
sim.cacheSz = cacheSz;
sim.bpredPenalty = branchPen;
sim.latencyMultiplier = latencyMultiplier;
sim.heurType = heurType;
sim.perfect_bpred_f = perfect_bpred;
sim.perfectCache_f = perfectCache;
sim.ROB.setMaxEntries(ROBsize);
sim.heuristic = heuristic;
sim.simulate();
}
System.out.format("Done with trace %s.\n",traceName);
}
}
| 7 |
private void setPlayers(List<Player> players) {
if (players == null)
throw new IllegalArgumentException("Players can't be null!");
this.players = players;
}
| 1 |
public synchronized T lookup(String requestURI) {
if (requestURI == null) {
throw new IllegalArgumentException("Request URI may not be null");
}
//Strip away the query part part if found
int index = requestURI.indexOf("?");
if (index != -1) {
requestURI = requestURI.substring(0, index);
}
// direct match?
T obj = this.map.get(requestURI);
if (obj == null) {
// pattern match?
String bestMatch = null;
for (Iterator<String> it = this.map.keySet().iterator(); it.hasNext();) {
String pattern = it.next();
if (matchUriRequestPattern(pattern, requestURI)) {
// we have a match. is it any better?
if (bestMatch == null
|| (bestMatch.length() < pattern.length())
|| (bestMatch.length() == pattern.length() && pattern.endsWith("*"))) {
obj = this.map.get(pattern);
bestMatch = pattern;
}
}
}
}
return obj;
}
| 9 |
public static Boolean dateIncrense(Date staticsDate){
Date d = new Date();
Date d1 = new Date();
Date d2 = new Date();
d1.setHours(0);
d1.setMinutes(0);
d1.setSeconds(0);
d2.setHours(23);
d2.setMinutes(59);
d2.setSeconds(59);
if(staticsDate.after(d1) && staticsDate.before(d2)){
return false;
}
return true;
}
| 2 |
public String getName() {
return this.name;
}
| 0 |
public Matrix solve(Matrix B) {
if (B.getRowDimension() != m) {
throw new IllegalArgumentException("Matrix row dimensions must agree.");
}
if (!this.isNonsingular()) {
throw new RuntimeException("Matrix is singular.");
}
// Copy right hand side with pivoting
int nx = B.getColumnDimension();
Matrix Xmat = B.getMatrix(piv,0,nx-1);
double[][] X = Xmat.getArray();
// Solve L*Y = B(piv,:)
for (int k = 0; k < n; k++) {
for (int i = k+1; i < n; i++) {
for (int j = 0; j < nx; j++) {
X[i][j] -= X[k][j]*LU[i][k];
}
}
}
// Solve U*X = Y;
for (int k = n-1; k >= 0; k--) {
for (int j = 0; j < nx; j++) {
X[k][j] /= LU[k][k];
}
for (int i = 0; i < k; i++) {
for (int j = 0; j < nx; j++) {
X[i][j] -= X[k][j]*LU[i][k];
}
}
}
return Xmat;
}
| 9 |
private void generateProfileFromText() {
if (arglist.size() != 1) {
System.err.println("Need to specify text file path");
return;
}
File file = new File(arglist.get(0));
if (!file.exists()) {
System.err.println("Need to specify existing text file path");
return;
}
String lang = get("lang");
if (lang == null) {
System.err.println("Need to specify langage code(-l)");
return;
}
FileOutputStream os = null;
try {
LangProfile profile = GenProfile.loadFromText(lang, file);
profile.omitLessFreq();
File profile_path = new File(lang);
os = new FileOutputStream(profile_path);
JSON.encode(profile, os);
} catch (JSONException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} catch (LangDetectException e) {
e.printStackTrace();
} finally {
try {
if (os!=null) os.close();
} catch (IOException e) {}
}
}
| 8 |
@Override
public boolean okMessage(Environmental affecting, CMMsg msg)
{
if(!super.okMessage(affecting,msg))
return false;
final MOB source=msg.source();
if(!canFreelyBehaveNormal(affecting))
return true;
final MOB observer=(MOB)affecting;
if((source!=observer)
&&(msg.amITarget(observer))
&&(msg.targetMinor()==CMMsg.TYP_GIVE)
&&(!CMSecurity.isAllowed(source,source.location(),CMSecurity.SecFlag.CMDROOMS))
&&(!(msg.tool() instanceof Coins))
&&(msg.tool() instanceof Item))
{
final double cost=cost((Item)msg.tool());
if(CMLib.beanCounter().getTotalAbsoluteShopKeepersValue(msg.source(),observer)<(cost))
{
final String costStr=CMLib.beanCounter().nameCurrencyShort(observer,cost);
CMLib.commands().postSay(observer,source,L("You'll need @x1 for me to identify that.",costStr),true,false);
return false;
}
return true;
}
return true;
}
| 9 |
private static void possible(ArrayList<String> list, City c, int turns, int times)
{
System.out.print("Called with " + turns + " number of turns, " + times + " iterations, and contents (" + list.size() + "): ");
for (int i = 0; i < list.size(); i++)
System.out.print(list.get(i) + " ");
System.out.println();
ArrayList<String> units = c.owner.techTree.allowedUnits;
//ArrayList<String> impr = c.owner.techTree.allowedCityImprovements;
int[] turnsUnits = new int[units.size()];
//int[] turnsImpr = new int[impr.size()];
if (times > 3) return;
for (int i = 0; i < units.size(); i++)
{
turnsUnits[i] = MenuSystem.calcQueueTurnsInt(c, units.get(i));
}
/*for (int i = 0; i < impr.size(); i++)
{
turnsImpr[i] = MenuSystem.calcQueueTurnsInt(c, impr.get(i));
}*/
for (int i = 0; i < turnsUnits.length; i++)
{
if (turnsUnits[i] <= 0) continue;
if (turns - turnsUnits[i] < 0)
{
masterList.add(list);
list.clear();
return;
}
else
{
//list.add(units.get(i));
ArrayList<String> temp = new ArrayList<String>(); //Pass a new object, not a reference
for (String stringy: list)
temp.add(stringy);
temp.add(units.get(i));
possible(temp, c, turns - turnsUnits[i], times+1);
}
}
/*for (int i = 0; i < turnsImpr.length; i++)
{
if (turnsImpr[i] <= 0) continue;
if (turns - turnsImpr[i] < 0)
{
masterList.add(list);
list.clear();
return;
}
else
{
list.add(impr.get(i));
possible(list, c, turns - turnsImpr[i], times+1);
}
}*/
}
| 7 |
private void calcHeuristic(TrieNode node) {
if (node.isLeaf()) {
node.setHeuristic(node.getDepth());
} else {
for (TrieNode child : node.getChildren().values()) {
calcHeuristic(child);
}
node.setHeuristic(getMaxChildHeuristic(node));
}
}
| 2 |
private static short[] findStartInstructions(InstructionSequence seq) {
int len = seq.length();
short[] inststates = new short[len];
Set<Integer> excSet = new HashSet<>();
for (ExceptionHandler handler : seq.getExceptionTable().getHandlers()) {
excSet.add(handler.from_instr);
excSet.add(handler.to_instr);
excSet.add(handler.handler_instr);
}
for (int i = 0; i < len; i++) {
// exception blocks
if (excSet.contains(new Integer(i))) {
inststates[i] = 1;
}
Instruction instr = seq.getInstr(i);
switch (instr.group) {
case GROUP_JUMP:
inststates[((JumpInstruction)instr).destination] = 1;
case GROUP_RETURN:
if (i + 1 < len) {
inststates[i + 1] = 1;
}
break;
case GROUP_SWITCH:
SwitchInstruction swinstr = (SwitchInstruction)instr;
int[] dests = swinstr.getDestinations();
for (int j = dests.length - 1; j >= 0; j--) {
inststates[dests[j]] = 1;
}
inststates[swinstr.getDefaultdest()] = 1;
if (i + 1 < len) {
inststates[i + 1] = 1;
}
}
}
// first instruction
inststates[0] = 1;
return inststates;
}
| 9 |
@Override
public void update(ChiVertex<Integer, Float> vertex, GraphChiContext context) {
if (vertex.numOutEdges() == 0) return;
RealVector latent_factor = ProblemSetup.latent_factors_inmem.getRowAsVector(vertex.getId());
try {
double squaredError = 0;
for(int e=0; e < vertex.numEdges(); e++) {
float observation = vertex.edge(e).getValue();
RealVector neighbor = ProblemSetup.latent_factors_inmem.getRowAsVector(vertex.edge(e).getVertexId());
double prediction = ALS.als_predict(neighbor, latent_factor);
squaredError += Math.pow(prediction - observation,2);
}
synchronized (this) {
validation_rmse += squaredError;
}
} catch (Exception err) {
throw new RuntimeException(err);
}
}
| 3 |
private void scanFile(String relativePath, File f, List<LessFileStatus> lstAddedLfs) {
if (!f.isFile())
throw new BugError("Bad file: " + f);
if (!f.getName().endsWith(".less") || ignoredList.contains(f))
return;
String lfsKey = getPathAndBaseName(f);
if (mapLessFileStatusByBaseName.containsKey(lfsKey))
return; // already added
File to = new File(f.getAbsolutePath().substring(0, f.getAbsolutePath().lastIndexOf(".less")) + ".css");
LessFileStatus lfs = new LessFileStatus(this, f, to, relativePath, conf.getShowUpdatedFilesDays());
mapLessFileStatusByBaseName.put(lfsKey, lfs);
filesWatcher.addFile(f);
filesWatcher.addFile(to);
lstAddedLfs.add(lfs);
if (!lfs.isUpToDate())
compile(lfs);
}
| 5 |
@Override
public void OnTrigger(Connection User, RoomItem Item, int Request, boolean UserHasRights)
{
if(User.Data.TeleporterId != 0) return; // esta usando un teleport
Room Room = Item.Environment.RoomManager.GetRoom(Item.RoomId);
if (Room != null)
{
int[] xy = Item.SquareInFront();
if ((User.Data.RoomUser.X == xy[0] && User.Data.RoomUser.Y == xy[1]) || (User.Data.RoomUser.X == Item.X && User.Data.RoomUser.Y == Item.Y))
{
if(User.Data.RoomUser.ActiveTask == 0)
{
int TeleId = Item.Environment.Teleports.GetTele(Item.Id);
if(TeleId != -1)
{
Item.ExtraData = "2";
Item.UpdateNeeded = true;
Item.TaskSteps = 2;
Item.ActiveTask = 1;
User.Data.RoomUser.AllowOverride = true;
User.Data.RoomUser.MoveTo(Item.X, Item.Y, false);
User.Data.RoomUser.TaskSteps = 2;
User.Data.RoomUser.ActiveTask = 1;
User.Data.TeleporterId = TeleId;
}
}
}
else
{
User.Data.RoomUser.MoveTo(xy[0], xy[1], true);
}
}
}
| 8 |
public Object retrieve(Comparable obj, BTNode aNode)
{
Comparable answer = null;
if(obj.compareTo(aNode.getData()) == 0)
answer = (Comparable)aNode.getData();
else if(obj.compareTo(aNode.getData())>0 && !aNode.isLeaf())
answer = (Comparable)retrieve(obj, aNode.getRight());
else if(obj.compareTo(aNode.getData())<0 && !aNode.isLeaf())
answer = (Comparable)retrieve(obj, aNode.getLeft());
return answer;
}
| 5 |
public Console() {
this.open = false;
this.cheatsAllowed = false;
this.commands = new ArrayList<Command>();
//Add all the default engine commands
this.addEngineCommands();
}
| 0 |
public static boolean downloadFile(String libName, File libPath, String libURL, List<String> checksums)
{
try
{
System.out.println(libURL);
URL url = new URL(libURL);
URLConnection connection = url.openConnection();
connection.setConnectTimeout(5000);
connection.setReadTimeout(5000);
InputSupplier<InputStream> urlSupplier = new URLISSupplier(connection);
Files.copy(urlSupplier, libPath);
if(checksumValid(libPath, checksums))
{
return true;
}
else
{
return false;
}
}
catch(FileNotFoundException fnf)
{
if(!libURL.endsWith(PACK_NAME))
{
fnf.printStackTrace();
}
return false;
}
catch(Exception e)
{
e.printStackTrace();
return false;
}
}
| 4 |
private void getDijkstra(int x_, int y_) {
PixelCost pixel;
while (queue.compareTo(dijkstra[x_ + w * y_]) < 0
&& (pixel = (PixelCost)queue.pop()) != null) {
int x = pixel.x;
int y = pixel.y;
double cost = pixel.cost;
if (dijkstra[x + w * y] <= cost)
continue;
dijkstra[x + w * y] = cost;
for (int i = 0; i < stepW.length; i++) {
int x2 = x + stepX[i];
int y2 = y + stepY[i];
if (x2 < 0 || y2 < 0 || x2 >= w || y2 >= h)
continue;
double newC = cost + stepW[i] + (ratioSpaceColor
* difference.difference(x, y, x2, y2));
if (dijkstra[x2 + w * y2] > newC) {
queue.add(newC, new PixelCost(x2,
y2, newC));
previous[x2 + w * y2] = x + w * y;
}
}
}
}
| 9 |
public static void main(String[] args) {
lerArquivo();
Treno t = new Treno(1000);
System.out.println("Lido todos os presentes");
AlgoritmoGenetico ag = new AlgoritmoGenetico(presentes, 10);
ag.inicializaCromosssomo(presentes);
for (int i = 0; i < 100; i++) {
ag.executaCrossover();
ag.executaMutacao();
ag.executaSelecao();
ag.avaliaSolucao();
}
escreverArquivo(ag.getMelhorCromossomo(),ag.getMelhorMetrica());
System.exit(0);
Instant inicio = Instant.now();
for (int i = 0; i < presentes.size(); i++) {
t.inserePresente(presentes.get(i));
}
Instant fim = Instant.now();
Duration duracao = Duration.between(inicio, fim);
long duracaoEmMilissegundos = duracao.toMillis();
int novaAltura = 0;
System.out.println(duracaoEmMilissegundos);
inicio = Instant.now();
Stack<Integer> pilha = new Stack<>();
for (Iterator<Integer> it = t.alturas.iterator(); it.hasNext();) {
novaAltura = it.next();
//pilha.addElement(novaAltura);
//System.out.print(novaAltura + " ");
if (novaAltura > maxAltura) {
maxAltura = novaAltura;
}
}
Set<Integer> todasAlturas = new TreeSet<>();
for (Presente presente : presentes) {
todasAlturas.add(presente.getZMax());
}
for (Integer integer : todasAlturas) {
pilha.addElement(integer);
}
ArrayList<Integer> todos = new ArrayList<>();
int qtde = pilha.size();
for (int i = 0; i < qtde; i++) {
ArrayList<Integer> altPre = new ArrayList<>();
int alt = pilha.pop();
for (Presente presente : presentes) {
if (presente.getZMax() == alt) {
altPre.add(presente.getId());
}
}
Collections.sort(altPre);
todos.addAll(altPre);
}
//Collections.reverse(todos);
calculaFitness(todos);
fim = Instant.now();
duracao = Duration.between(inicio, fim);
duracaoEmMilissegundos = duracao.toMillis();
System.out.println(duracaoEmMilissegundos);
escreverArquivo(presentes,0.0);
System.exit(0);
// Presente p1 = new Presente(1, 2, 4, 2);
// Presente p2 = new Presente(2, 2, 2, 3);
// Presente p3 = new Presente(3, 4, 4, 4);
// Presente p4 = new Presente(4, 4, 2, 5);
// Presente p5 = new Presente(5, 2, 2, 6);
// Presente p6 = new Presente(6, 2, 2, 7);
// Presente p7 = new Presente(7, 3, 3, 8);
//
//
// Treno t2 = new Treno(4);
// t2.imprimirTabela();
//
// t2.inserePresente(p1);
// System.out.println(p1.getX() + ":" + p1.getY() + ":" + p1.getZ());
// t2.imprimirTabela();
// imprimeVertices(p1.getVertices());
// t2.inserePresente(p2);
// System.out.println(p2.getX() + ":" + p2.getY() + ":" + p2.getZ());
// t2.imprimirTabela();
// imprimeVertices(p2.getVertices());
// t2.inserePresente(p3);
// System.out.println(p3.getX() + ":" + p3.getY() + ":" + p3.getZ());
// t2.imprimirTabela();
// imprimeVertices(p3.getVertices());
// t2.inserePresente(p4);
// System.out.println(p4.getX() + ":" + p4.getY() + ":" + p4.getZ());
// t2.imprimirTabela();
// imprimeVertices(p4.getVertices());
// t2.inserePresente(p5);
// System.out.println(p5.getX() + ":" + p5.getY() + ":" + p5.getZ());
// t2.imprimirTabela();
// imprimeVertices(p5.getVertices());
// t2.inserePresente(p6);
// System.out.println(p6.getX() + ":" + p6.getY() + ":" + p6.getZ());
// t2.imprimirTabela();
// imprimeVertices(p6.getVertices());
// t2.inserePresente(p7);
// System.out.println(p7.getX() + ":" + p7.getY() + ":" + p7.getZ());
// t2.imprimirTabela();
// imprimeVertices(p7.getVertices());
}
| 9 |
@Override
public boolean equals(Object obj) {
boolean result = false;
if (this == obj) {
result = true;
} else if(obj != null) {
DataProviderStatus status = null;
if(obj instanceof String) {
try {
status = DataProviderStatus.parse((String) obj);
} catch(Exception e) {
status = null;
result = false;
}
} else if(obj instanceof DataProviderStatus) {
status = (DataProviderStatus) obj;
}
if(status != null) {
if(this.name.equals(status.name) && this.status.equals(status.status)) {
if(Utilities.isNullOrWhitespace(this.version)) {
result = true;
} else {
result = this.version.equals(status.version);
}
}
}
}
return result;
}
| 9 |
public void readUntil() {
try {
// String line;
while (in.readUnsignedByte() == 0) {// gets 1 byte starter
int control;
int size;
byte[] data = null;
control = in.readUnsignedShort();// gets 2 byte control
size = in.readUnsignedShort();// gets 2 byte size of data(may
// increase size later..only
// supports 65.5 kbs of data
// transfer per command)
// System.out.println("["+control+"] size "+size+" data: "+data);
if (size > 0) {
data = new byte[size];
}
in.readFully(data, 0, size);// gets data
if (in.readUnsignedByte() == 255) {// gets 1 byte ender, if data
// too big, this wont be
// reached then theres error
doCommand(new DataPacket(control, data));
if(size > 0){//just for debugging purposes
if(control < 1000){
System.out.println("[" + control + "] "+ new String(data, "ISO-8859-1"));
}
else{System.out.println("[" + control + "] <Object> "+size+" bytes");}
}
else{System.out.println("[" + control + "]");}
}
else {
System.out.println("****ERROR**NO COMMAND ENDER****");
}
return;
}
} catch (SocketException e) {
System.out.println("Connection Socket Error\n");
SERVERRUNNING = false;
if(!MANUELDC){
Framework.Window.createIFrame("popup", new String[] {"<html><b>You were Disconnected from eMafia</b></html>","exit","html" });
}
} catch (Exception e) {
e.printStackTrace();
}
return;
}
| 8 |
private Object readArgument(char c) {
switch (c) {
case 'i' :
return readInteger();
case 'h' :
return readBigInteger();
case 'f' :
return readFloat();
case 'd' :
return readDouble();
case 's' :
return readString();
case 'c' :
return readChar();
case 'T' :
return Boolean.TRUE;
case 'F' :
return Boolean.FALSE;
}
return null;
}
| 8 |
public ClientSocketHandler(Socket s, ClientListManager t_list) {
csocket = s;
list = t_list;
}
| 0 |
@Override
public boolean equals(Object obj) {
if (obj == null) {
return false;
}
if (getClass() != obj.getClass()) {
return false;
}
final MavenVersion other = (MavenVersion) obj;
if ((this.majorVersion == null) ? (other.majorVersion != null) : !this.majorVersion.equals(other.majorVersion)) {
return false;
}
if ((this.featureVersion == null) ? (other.featureVersion != null) : !this.featureVersion.equals(other.featureVersion)) {
return false;
}
if ((this.bugfixVersion == null) ? (other.bugfixVersion != null) : !this.bugfixVersion.equals(other.bugfixVersion)) {
return false;
}
if (this.snapshot != other.snapshot) {
return false;
}
return true;
}
| 9 |
public static void main(String[] args) {
//wap to find square of 128 without using arithmetic operator and inbuilt functions
int y=128;
int z= y<<7;
System.out.println(z);
}
| 0 |
public void sortColors(int[] A) {
int left = 0;
int right = A.length - 1;
int current = 0;
while (current <= right) {
if (A[current] == 0) {
swap(A, current, left);
left++;
current++;
}
else if (A[current] == 2) {
swap(A, current, right);
right--;
}
else {
current++;
}
}
}
| 3 |
public void onEnable() {
persist = new Persistence(this);
persist.saveDefault();
saveDefaultConfig();
// whew all the handlers and managers...mostly
name = getConfig().getString("name");
longname = getConfig().getString("longname");
pHandler = new PlayerListener(this);
chat = new ChatManager(this);
command = new CommandManager(this);
PlayerManager.init();
ChannelManager.init();
PluginUtil.plugin = this;
permissions = PermissionsEx.getPermissionManager();
getLogger().setUseParentHandlers(false);
try {
fileHandler = new FileHandler(getDataFolder() + "/chat3.log", 1024 * 1024 * 1024, 1);
fileHandler.setFormatter(new LogFormatter());
getLogger().addHandler(fileHandler);
} catch (SecurityException | IOException e) {
System.out.println("Error opening log file, redirecting output to console.");
getLogger().setUseParentHandlers(true);
}
//mutelist
this.mutelist = MutelistManager.load(this);
//timeouts
TimeoutsManager.load(this);
// persistence
loadPlayers();
loadChannels();
// set up colored ranks and stuff
Player[] players = getServer().getOnlinePlayers();
for(int i = 0; i < players.length; i++) {
String result = PluginUtil.color(PluginUtil.formatUser(players[i].getName()));
if(result.length() > 16)
result = result.substring(0, 16);
players[i].setPlayerListName(result);
}
// start connecting to server
final MCNSAChat3 finalThis = this;
getServer().getScheduler().scheduleSyncRepeatingTask(this, new Runnable() {
public void run() {
if (thread == null) {
thread = new ClientThread(finalThis, finalThis.getLogger());
thread.start();
}
}
}, 0L, 200L);
//Timeouts
Bukkit.getScheduler().scheduleSyncRepeatingTask(finalThis, new Runnable() {
public void run() {
TimeoutManager timeoutTask = new TimeoutManager(finalThis, getLogger());
timeoutTask.start();
}
}, 0L, 600L);
//Tab list refreshing
Bukkit.getScheduler().scheduleSyncRepeatingTask(finalThis, new Runnable() {
public void run() {
PlayerRefresh.refreshTabList();
}
}, 0L, 600L);
}
| 4 |
* @param item The item to add to the queue.
* @throws FullQueueException if the queue is full
*/
public void enqueue(E item) throws FullQueueException {
if (this.isFull())
throw new FullQueueException();
array.add(null);
int index = array.size() - 1;
// Reheapify.
while (index > 1 && comp.compare(getParent(index), item) > 0) {
array.set(index, getParent(index));
index = getParentIndex(index);
}
// Store the new element.
array.set(index, item);
numItems++;
}
| 3 |
public static void DoTurn(PlanetWars pw) {
//Retrieve environment characteristics
//Are there characteristics you want to use instead, or are there more you'd like to use? Try it out!
int neutralPlanets = pw.NeutralPlanets().size();
int totalPlanetSize = 0;
for (Planet p : pw.NeutralPlanets()) {
totalPlanetSize += p.GrowthRate();
}
int averagePlanetSize = Math.round(totalPlanetSize/pw.NeutralPlanets().size());
//Use AdaptivityMap to get the bot which matches the current environment characteristics
String thisTurnBot = AdaptivityMap.get(neutralPlanets, averagePlanetSize);
if (thisTurnBot == null) {
System.err.println("WARNING: You have not entered bot data for this case. Using default bot");
DoRandomBotTurn(pw);
} else {
if (thisTurnBot.equals("BullyBot")) {
System.err.println("BullyBot is going to play this turn");
DoBullyBotTurn(pw);
} else if (thisTurnBot.equals("RandomBot")) {
System.err.println("RandomBot is going to play this turn");
DoRandomBotTurn(pw);
} else {
System.err.println("WARNING: Adaptivity map wants " + thisTurnBot +
" to play this turn, but this strategy is not implemented in this bot! Using default bot");
DoRandomBotTurn(pw);
}
}
}
| 4 |
public static void main(String[] args)
{
long startTime = System.currentTimeMillis();
if(args.length == 0){
System.out.println("Please provide the location of the trace files (Workload_trace_filename FTA_Path)!");
System.exit(1);
}
try {
String Work_fileName = args[0];
String FTA_Path = args[1];
String FTA_event_fileName = FTA_Path + "/event_trace.tab";
String FTA_platform_fileName = FTA_Path + "/platform.tab";
String FTA_node_fileName = FTA_Path + "/node.tab";
double TraceStartTime = 0;
// number of grid user entities + any Workload entities.
int num_user = 1;
Calendar calendar = Calendar.getInstance();
boolean trace_flag = false; // mean trace GridSim events
// Initialize the GridSim package without any statistical
// functionalities. Hence, no GridSim_stat.txt file is created.
System.out.println("Initializing GridSim package");
GridSim.init(num_user, calendar, trace_flag);
ResourceFileReader res = new ResourceFileReader(FTA_platform_fileName, FTA_node_fileName);
//////////////////////////////////////////
// As in the Gridsim, the failure is defined in the level of Machine, we
// consider a resource of X machines with one PE
//
// Creates one GridResource entity
int rating = 377; // rating of each PE in MIPS
int totalPE = 1; // total number of PEs for each Machine
int totalMachine = res.getNodeNum(); // total number of Machines
String resName = res.getPlatformName();
GridResource resource = createGridResource(resName, rating, totalMachine, totalPE);
//////////////////////////////////////////
// Creates an event list.
FailureFileReader failure = new FailureFileReader(FTA_event_fileName, TraceStartTime);
FailureGenerator failure_list = new FailureGenerator("Failure_1", resource.get_name(), failure);
//////////////////////////////////////////
// Creates a Workload trace entity.
WorkloadFileReader model = new WorkloadFileReader(Work_fileName, rating);
Workload workload = new Workload("Load_1", resource.get_name(), model);
//////////////////////////////////////////
// Starts the simulation in debug mode
boolean debug = false;
GridSim.startGridSimulation(debug);
if(!debug) {
long finishTime = System.currentTimeMillis();
System.out.println("The simulation took " + (finishTime - startTime) + " milliseconds");
}
// prints the Gridlets inside a Workload entity
ArrayList<Gridlet> newList = workload.getGridletList();
printGridletList(newList);
}
catch (Exception e) {
e.printStackTrace();
}
}
| 3 |
public JPanel getCommandBtnMenu() {
if (!isInitialized()) {
IllegalStateException e = new IllegalStateException("Call init first!");
throw e;
}
return this.comBtn;
}
| 1 |
public static void printDataItems(StringBuilder sb, List<? extends DataItem> items) {
for (DataItem item : items) {
printTypeRef(sb, item.getType());
sb.append(" ");
sb.append(item.getName());
if (item.isOptional()) {
sb.append("?");
}
sb.append(", ");
}
if (!items.isEmpty()) {
sb.deleteCharAt(sb.length() - 1);
sb.deleteCharAt(sb.length() - 1);
}
}
| 4 |
public Class<? extends Annotation> annotationOf(Field field) {
FieldStoreItem item = store.get(FieldStoreItem.createKey(field));
if(item != null) {
return item.getAnnotation();
}
return null;
}
| 2 |
@Override
public void infoSeePlayerOther(int number, boolean goalie, double distance, double direction, double distChange,
double dirChange, double bodyFacingDirection, double headFacingDirection) {
//Switch statement for custom operation of the Attackers
switch (this.getPlayer().getNumber()) {
case 2: case 3:
SeenPlayer seenPlayer = new SeenPlayer(number, goalie, distance, direction, distChange,
dirChange, bodyFacingDirection, headFacingDirection, false, true);
//If current agent can see the ball aswell as this player then calculate the distance to them
if (canSeeBall == true) {
seenPlayer.calculateDistance(distanceBall, distance, directionBall, direction);
} else {
//Else set the distance to far away
seenPlayer.distanceFromBall = 1000;
}
boolean found = false;
//This arraylist is for storing the seen players in memory, if the player has not been seen before then they are added to the array
//Loop through and find if the player already exists in the arraylist
for (int i = 0; i < allPlayers.size(); ++i) {
SeenPlayer player = allPlayers.get(i);
if (player.number == number && player.isTeammate == false) {
//update their details in the arraylist
allPlayers.set(i, seenPlayer);
found = true;
updatedThePlayerList = true;
}
}
//If they haven't been found in the arraylist then create them
if (found == false) {
allPlayers.add(seenPlayer);
updatedThePlayerList = true;
}
default:
break;
}
}
| 7 |
public static DatabaseEnvironment createTestEnvironment( String environment ) {
String[] temp = null;
String[] dbEnvironment = null;
if ( "H2".equalsIgnoreCase( environment ) ) {
temp = h2Parameters;
}
else if ( "ORACLE".equalsIgnoreCase( environment ) ) {
temp = oracleParameters;
}
dbEnvironment = new String[temp.length];
for ( int i = 0; i < temp.length; i++ ) {
if ( i == 0 ) {
dbEnvironment[0] = "TESTING";
}
else {
dbEnvironment[i] = temp[i];
}
}
return new DatabaseEnvironment( dbEnvironment );
}
| 4 |
@Override
public void Initialize()
{
super.Initialize();
instantiator = new int[sudokuSize][sudokuSize];
for (int i = 0; i < sudokuSize; i++) {
for (int j = 0; j < sudokuSize; j++) {
instantiator[i][j] = -1;
}
}
}
| 2 |
@Override
public ValueType returnedType(ValueType... types) throws Exception {
// Check the number of argument
if (types.length == 1) {
// if array
if (types[0] == ValueType.NONE) {
return ValueType.NONE;
}
// If numerical
if (types[0].isNumeric()) {
return ValueType.DOUBLE;
}
// if array
if (types[0] == ValueType.ARRAY) {
return ValueType.ARRAY;
}
// the type is incorrect
throw new EvalException(this.name() + " function does not handle "
+ types[0].toString() + " type");
}
// number of argument is incorrect
throw new EvalException(this.name()
+ " function only allows one numerical parameter");
}
| 4 |
private void modelsFromGrid(Grid grid, double[][] heightMap)
{
for (int r = 0; r < grid.rows; r++)
{
for (int c = 0; c < grid.cols; c++)
{
Tile t = grid.getTile(r,c);
for (BaseEntity en: t.occupants)
{
Group candidate = LevelManager.loadFromXML(EntityData.getUniqueModel(en.name), "partTexture", "colorTexture"+(int)en.owner.primaryBrickColor);
moveCandidate(candidate, r, c);
units.put(en, candidate);
}
if (t.improvement != null)
{
String texture = t.owner != null ? "colorTexture"+(int)t.improvement.owner.primaryBrickColor : "partTexture";
Group candidate = LevelManager.loadFromXML(EntityData.getUniqueModel(t.improvement.name), "partTexture", texture);
moveCandidate(candidate, r, c);
improvements.put(t.improvement, candidate);
}
Group candidate = getResources(t);
if (candidate != null)
{
resources.put(t, candidate);
moveCandidate(candidate, r, c);
}
candidate = getFeatures(t);
if (candidate != null)
{
features.put(t, candidate);
moveCandidate(candidate, r, c);
}
}
}
}
| 7 |
public int getDv() {
return dv;
}
| 0 |
public static String lTrimKeepTabs(final String value) {
if (value == null) {
return null;
}
String trimmed = value;
int offset = 0;
final int maxLength = value.length();
while (offset < maxLength && value.charAt(offset) == ' ') {
offset++;
}
if (offset > 0) {
trimmed = value.substring(offset);
}
return trimmed;
}
| 4 |
@Override
public void run()
{
while ( !socket.isClosed() )
{
try
{
Socket connection = socket.accept();
try
{
requestHandler( connection );
}
finally
{
try
{
if ( !connection.isClosed() )
connection.close();
}
catch ( IOException e )
{
HTTPConsole.log( Level.WARNING, "The connection was prematurely closed" );
}
}
}
catch ( Exception e )
{
if ( e instanceof java.io.IOException && stopping )
return;
HTTPConsole.logException( e, "Error while handling an HTTP request." );
}
}
}
| 6 |
public void moveParticle(Random rand) {
int[] copyProjectWorkUnitIndexes =
new int[projectWorkUnitIndexes.length];
System.arraycopy(
projectWorkUnitIndexes,
0,
copyProjectWorkUnitIndexes,
0,
projectWorkUnitIndexes.length
);
List<Integer> mutationIndexes = new ArrayList<Integer>();
int cnt = 0;
//magic number!
int subProjectActivities = 15;
for (int i = 0; i < velocity.length; i++) {
cnt++;
if (rand.nextDouble() <= Math.abs(velocity[i])) {
mutationIndexes.add(i);
}
if (cnt == subProjectActivities) {
cnt = 0;
int[] arrayOfMutationIndexes = list2array(mutationIndexes);
int[] copyOfArrayOfMutationIndexes =
new int[arrayOfMutationIndexes.length];
System.arraycopy(
arrayOfMutationIndexes,
0,
copyOfArrayOfMutationIndexes,
0,
arrayOfMutationIndexes.length
);
PSOUtil.shuffleSubArray(
arrayOfMutationIndexes,
arrayOfMutationIndexes.length,
rand
);
for (int j = 0; j < arrayOfMutationIndexes.length; j++) {
projectWorkUnitIndexes[copyOfArrayOfMutationIndexes[j]] =
copyProjectWorkUnitIndexes[arrayOfMutationIndexes[j]];
}
mutationIndexes.clear();
}
}
}
| 4 |
private static boolean isGeometricallyConnectedAtOnlyOneEnd(Spring spring1, Spring spring2) {
Point2D spring1Point1 = spring1.getLine().getP1();
Point2D spring1Point2 = spring1.getLine().getP2();
Point2D spring2Point1 = spring2.getLine().getP1();
Point2D spring2Point2 = spring2.getLine().getP2();
boolean s1P1AndS2P1AreConnected = spring1Point1.distance(spring2Point1) < POINT_DISTNACE_TO_INTERPRET_AS_CONNECTED;
boolean s1P1AndS2P2AreConnected = spring1Point1.distance(spring2Point2) < POINT_DISTNACE_TO_INTERPRET_AS_CONNECTED;
boolean s1P2AndS2P1AreConnected = spring1Point2.distance(spring2Point1) < POINT_DISTNACE_TO_INTERPRET_AS_CONNECTED;
boolean s1P2AndS2P2AreConnected = spring1Point2.distance(spring2Point2) < POINT_DISTNACE_TO_INTERPRET_AS_CONNECTED;
return (s1P1AndS2P1AreConnected && !s1P2AndS2P2AreConnected)
|| (s1P1AndS2P2AreConnected && !s1P2AndS2P1AreConnected)
|| (s1P2AndS2P1AreConnected && !s1P1AndS2P2AreConnected)
|| (s1P2AndS2P2AreConnected && !s1P1AndS2P1AreConnected);
}
| 7 |
private void handleHeaderField(Field field) throws HaltProcessingException, ParseException {
// If we don't have a field, no point continuing.
if (field == null) {
return;
}
Header header = Header.findHeader(field.getName());
// If we didn't resolve the header, then we don't need to pay attention to it.
if (header == null) {
return;
}
String value = field.getValue();
switch (header) {
case TO:
mMessageBuilder.to(value);
break;
case FROM:
if (!GITHUB_FROM.equalsIgnoreCase(value)) {
throw new HaltProcessingException();
}
mMessageBuilder.from(value);
break;
case SUBJECT:
if (!value.startsWith(GITHUB_SUBJECT)) {
throw new HaltProcessingException();
}
mMessageBuilder.subject(value);
break;
case DATE:
SimpleDateFormat simpleDateFormat = new SimpleDateFormat("EEE, d MMM yyyy HH:mm:ss Z");
mMessageBuilder.date(simpleDateFormat.parse(value));
}
}
| 8 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.