text
stringlengths 14
410k
| label
int32 0
9
|
---|---|
@Override
public boolean equals(Object obj) {
if (this == obj)
return true;
if (obj == null)
return false;
if (getClass() != obj.getClass())
return false;
TestDescriptor other = (TestDescriptor) obj;
if (!getOuterType().equals(other.getOuterType()))
return false;
if (size != other.size)
return false;
return true;
}
| 5 |
@Override
public int hashCode() {
final int prime = 31;
int result = 1;
result = prime * result + ((code == null) ? 0 : code.hashCode());
return result;
}
| 1 |
public void create(int x, int y, double d, double e, Color color) {
for (Particle p : particles) {
if (!p.active) {
p.life = 0.05F;
p.x = x;
p.y = y;
p.yV = d;
p.xV = e;
p.active = true;
p.color = color;
return;
}
}
}
| 2 |
public static void main(String[] args){
UCIParams p = new UCIParams();
for(int a = 0; a < args.length; a++){
try{
if(args[a].equals("--hash")){ //sets main hash size (must be power of 2)
p.hashSize = Integer.parseInt(args[++a]);
} else if(args[a].equals("--pawnHash")){ //sets pawn hash size (must be power of 2)
p.pawnHashSize = Integer.parseInt(args[++a]);
} else if(args[a].equals("--no-info")){ //turns off chess.uci info printing (ie, pv, score, time, etc)
p.printInfo = false;
} else if(args[a].equals("--ignore-quit")){ //turns off handling of uci quit command (need C-c to shutdown)
p.ignoreQuit = true;
} else if(args[a].equals("--warm-up")){ //warm up the jvm
p.warmUp = true;
} else if(args[a].equals("--extras")){ //turn on console controller extensions
p.controllerExtras = true;
} else if(args[a].equals("--profile")){ //profile engine on passed fen file then exit
p.profile = true;
p.profileFen = args[++a];
}
} catch(Exception e){
System.out.println("error, incorrect args");
System.exit(1);
}
}
new UCI(p);
}
| 9 |
@Override
public void componentResized(ComponentEvent ce) {
FRAME_HEIGHT = this.getHeight();
FRAME_WIDTH = this.getWidth();
FONT_SIZE = (FRAME_HEIGHT / 100) * 4;
LABEL_SIZE = new Dimension(FRAME_WIDTH/5 + FONT_SIZE*2, FONT_SIZE + FONT_SIZE/4);
for (Component p : getComponents()) {
if (p instanceof AbleToResizeGUI) {
((AbleToResizeGUI) p).resizeGUI();
}
}
}
| 2 |
protected void activate(){ // Activation de l'Environnement en creant un tableau de cellule et en lan�ant tous ces agents cellules
requestRole(Societe.SOCIETE , Societe.SIMU , Societe.CARTE );
// Créer la grille de jeu (grille de cellule)
for (int i=0 ; i < this.longueur; i++){
for (int j=0 ; j < this.largeur ; j++){
Coord actual = new Coord (i,j); //(*10 pour l'affichage)
this.carte[i][j] = new Cellule(actual,this);
launchAgent(this.carte[i][j]);
}
}
Random r = new Random();
int valeur ;
int valeur2 ;
valeur = r.nextInt(this.longueur-1 - (ObjectMap.vision)) + (ObjectMap.vision / 2);
valeur2 = r.nextInt(this.largeur-1 - (ObjectMap.vision)) + (ObjectMap.vision / 2);
for (int i =0 ; i<this.al.length ; i++){
this.carte[valeur][valeur2].add(new Forum (this.carte[valeur][valeur2], this.al[i]));
this.forum[i] = (Forum)this.carte[valeur][valeur2].objet;
valeur = r.nextInt(this.longueur-1 - (ObjectMap.vision)) + (ObjectMap.vision / 2);
valeur2 = r.nextInt(this.largeur-1 - (ObjectMap.vision)) + (ObjectMap.vision / 2);
}
}
| 3 |
public boolean itemDeposit(WebInventoryMeta wim) {
// Unsupported action
if (!this.canDeposit) {
this.player.sendMessage(MineAuction.prefix + ChatColor.RED
+ MineAuction.lang.getString("action_invalid_deposit"));
return false;
}
try {
// Save item to database
// exist in database (a - update, b - insert)
Connection conn = MineAuction.db.getConnection();
PreparedStatement ps = null;
// Fix duplicite items records, restack them at database
// DatabaseUtils.fixItemStacking()
// Same item is in database, update him
if (DatabaseUtils.isItemInDatabase(wim,
DatabaseUtils.getPlayerId(this.player.getUniqueId()))
&& wim.getItemStack().getMaxStackSize() > 1) {
short durability = ItemUtils.canHaveDamage(wim.getId()) ? 0
: wim.getDurability();
ps = conn
.prepareStatement("UPDATE ma_items SET qty = qty + ? WHERE playerID = ? AND itemID= ? AND itemDamage = ? AND enchantments = ? AND lore = ?");
ps.setInt(1, wim.getItemQty());
ps.setInt(2,
DatabaseUtils.getPlayerId(this.player.getUniqueId()));
ps.setInt(3, wim.getId());
ps.setShort(4, durability);
ps.setString(5, wim.getItemEnchantments());
ps.setString(6, wim.getLore());
ps.executeUpdate();
} else {
short durability = ItemUtils.canHaveDamage(wim.getId()) ? 0
: wim.getDurability();
ps = conn
.prepareStatement("INSERT INTO `ma_items` (`playerID`, `itemID`, `itemDamage`, `qty`, `itemMeta`, `enchantments`, `lore`) VALUES (?, ?, ?,?, ?, ?, ?)");
ps.setInt(1,
DatabaseUtils.getPlayerId(this.player.getUniqueId()));
ps.setInt(2, wim.getId());
ps.setShort(3, durability);
ps.setInt(4, wim.getItemQty());
ps.setString(5, wim.getItemMeta());
ps.setString(6, wim.getItemEnchantments());
ps.setString(7, wim.getLore());
ps.execute();
}
// Refresh inventory if it is set in config
if (MineAuction.config.getBool("plugin.performance.refresh"))
this.refreshInventory();
return true;
} catch (Exception e) {
e.printStackTrace();
return false;
}
}
| 7 |
public <T> T loadConfig(Class<T> cl, String configPath) {
try {
T config = cl.newInstance();
Map<String, String> map = FileUtil
.readKeyValueConfigFile(configPath);
if (map == null) {
Log.e(TAG + ":" + " read configfile error filepath is "
+ configPath == null ? "null" : configPath);
return null;
}
for (String key : map.keySet()) {
invokeGetMethod(config, cl, key, map.get(key));
}
return config;
} catch (InstantiationException e) {
e.printStackTrace();
} catch (IllegalAccessException e) {
e.printStackTrace();
} catch (SecurityException e) {
e.printStackTrace();
} catch (IllegalArgumentException e) {
e.printStackTrace();
} catch (NoSuchMethodException e) {
e.printStackTrace();
} catch (InvocationTargetException e) {
e.printStackTrace();
}
return null;
}
| 9 |
public static String cPath(String path) {
for (int i = 0; i < path.length(); i++) {
if (path.charAt(i) == '/' && File.separatorChar != '/') {
path = path.substring(0, i) + File.separator + path.substring(i + 1);
}
}
return path;
}
| 3 |
* @param directory
* @param input
* @param output
* @param error
* @return int
*/
public static int executeShellCommand(Stella_Object command, String directory, InputStream input, OutputStream output, OutputStream error) {
{ ShellProcess self000 = ShellProcess.newShellProcess();
self000.command = OntosaurusUtil.parseShellCommand(command);
self000.directory = ((directory != null) ? directory : ".");
self000.inputStream = input;
self000.outputStream = output;
self000.errorStream = error;
{ ShellProcess process = self000;
process.startProcess();
{ Thread outputthread = ((output != null) ? Thread.newThread(Native.find_java_method("edu.isi.stella.InputStream", "copyStreamToStream", new java.lang.Class [] {Native.find_java_class("edu.isi.stella.InputStream"), Native.find_java_class("edu.isi.stella.OutputStream")}), Stella.vector(Cons.cons(process.nativeStdout, Cons.cons(process.outputStream, Stella.NIL)))) : ((Thread)(null)));
Thread errorthread = ((error != null) ? Thread.newThread(Native.find_java_method("edu.isi.stella.InputStream", "copyStreamToStream", new java.lang.Class [] {Native.find_java_class("edu.isi.stella.InputStream"), Native.find_java_class("edu.isi.stella.OutputStream")}), Stella.vector(Cons.cons(process.nativeStderr, Cons.cons(process.errorStream, Stella.NIL)))) : ((Thread)(null)));
if (outputthread != null) {
outputthread.startThread();
}
if (errorthread != null) {
errorthread.startThread();
}
if (input != null) {
InputStream.copyStreamToStream(input, process.nativeStdin);
Stream.closeStream(process.nativeStdin);
}
if (outputthread != null) {
outputthread.waitForCompletion();
}
if (errorthread != null) {
errorthread.waitForCompletion();
}
process.waitForCompletion();
process.destroyProcess();
return (process.exitStatus);
}
}
}
}
| 8 |
@Override
public double compute(double[] params) {
double a = params[0];
double b = params[1];
switch (type) {
case ADD:
return a + b;
case SUBTRACT:
return a - b;
case MULTIPLY:
return a * b;
case DIVIDE:
return a / b;
case POWER:
return Math.pow(a, b);
}
return a;
}
| 5 |
private Token jj_consume_token(int kind) throws ParseException {
Token oldToken;
if ((oldToken = token).next != null) token = token.next;
else token = token.next = token_source.getNextToken();
jj_ntk = -1;
if (token.kind == kind) {
jj_gen++;
if (++jj_gc > 100) {
jj_gc = 0;
for (int i = 0; i < jj_2_rtns.length; i++) {
JJCalls c = jj_2_rtns[i];
while (c != null) {
if (c.gen < jj_gen) c.first = null;
c = c.next;
}
}
}
return token;
}
token = oldToken;
jj_kind = kind;
throw generateParseException();
}
| 6 |
private void jBtnAceptarActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jBtnAceptarActionPerformed
// TODO add your handling code here:
try {
if (flagcli) {
//Le Codigo
Connection connPed = Conexion.GetConnection();
connPed.setAutoCommit(false);
Connection connProd = Conexion.GetConnection();
connProd.setAutoCommit(false);
Connection connPedHas = Conexion.GetConnection();
connPedHas.setAutoCommit(false);
Connection connUpdate = Conexion.GetConnection();
connUpdate.setAutoCommit(false);
String empleado = JOptionPane.showInputDialog("Confirmar");
String sqlEmpVerif = "SELECT idempleados FROM empleados WHERE idempleados = ?";
String sqlUpdateProd = "UPDATE productos "
+ "SET cantidad = cantidad - ? "
+ "WHERE idproductos = ? ";
String sqlNewPedido = "INSERT INTO pedidos(precio_total,clientes_idclientes,empleados_idempleados,descuento) "
+ "VALUES( ?, ?, ?, ?)";
String sqlPedHas = "INSERT INTO productos_has_pedidos(productos_idProductos, pedidos_idpedidos, cantidad_pedido) "
+ "VALUES(?, ?, ?)";
//Verifica si existe el empleado
PreparedStatement psConf = connPed.prepareStatement(sqlEmpVerif);
//Actualiza las cantidades de los productos
PreparedStatement psUpdate = connUpdate.prepareStatement(sqlUpdateProd);
//Inserta el pedido en tabla pedidos
PreparedStatement psProd = connProd.prepareStatement(sqlNewPedido);
//Inserta en la tabla productos_has_pedidos
PreparedStatement psPedHas = connPedHas.prepareStatement(sqlPedHas);
psConf.setString(1, empleado);
ResultSet rs = psConf.executeQuery();
if (rs.next()) {
try {
//productos_has_pedidos(productos_idProductos, pedidos_idpedidos,cantidad_pedido)
psProd.setString(1, jLblPrecio.getText());
psProd.setString(2, (String) tmcli.getValueAt(jTableClientes.getSelectedRow(), 0));
psProd.setString(3, empleado);
psProd.setDouble(4, Double.parseDouble(jTxtFldDescuento.getText()));
psProd.execute();
connProd.commit();
String sql = "SELECT `AUTO_INCREMENT` - 1 "
+ " FROM INFORMATION_SCHEMA.TABLES "
+ " WHERE TABLE_SCHEMA = 'gamecrush' "
+ " AND TABLE_NAME = 'pedidos' ";
Connection connLast = Conexion.GetConnection();
PreparedStatement ps = connLast.prepareStatement(sql);
lastId = ps.executeQuery();
lastId.next();
String lastIdPed = lastId.getString(1);
int rows2 = jTablePedido.getRowCount();
for (int j = 0; j < rows2; j++) {
psUpdate.setInt(1, (int) tmped.getValueAt(j, 2));
psUpdate.setString(2, (String) tmped.getValueAt(j, 0));
psUpdate.executeUpdate();
connUpdate.commit();
}
for (int j = 0; j < rows2; j++) {
psPedHas.setString(1, (String) tmped.getValueAt(j, 0));
psPedHas.setString(2, lastIdPed);
psPedHas.setInt(3, (int) tmped.getValueAt(j, 2));
psPedHas.execute();
connPedHas.commit();
}
cancelPedido();
} catch (SQLException e) {
JOptionPane.showMessageDialog(this, e.getErrorCode() + ": " + e.getMessage());
}
} else {
JOptionPane.showMessageDialog(this, "Empleado no encontrado");
}
} else {
JOptionPane.showMessageDialog(this, "Por favor seleccione un cliente.");
}
} catch (SQLException | HeadlessException e) {
System.out.println(e.getMessage());
}
}//GEN-LAST:event_jBtnAceptarActionPerformed
| 6 |
@Override
public void deleteOfOldResults() throws SQLException {
switch (driverName) {
case "org.h2.Driver":
statement = connection.prepareStatement(deleteOfOldResultsStringH2);
break;
case "com.mysql.jdbc.Driver":
statement = connection.prepareStatement(deleteOfOldResultsStringMySQl);
break;
default:
System.out.println("Not true name of the driver.");
}
statement.execute();
statement.close();
}
| 2 |
public final GalaxyXLinkingParser.modifier_return modifier() throws RecognitionException {
GalaxyXLinkingParser.modifier_return retval = new GalaxyXLinkingParser.modifier_return();
retval.start = input.LT(1);
int modifier_StartIndex = input.index();
CommonTree root_0 = null;
Token set88=null;
CommonTree set88_tree=null;
try {
if ( state.backtracking>0 && alreadyParsedRule(input, 14) ) { return retval; }
// C:\\Users\\Timo\\EclipseProjects\\GalaxyX\\build\\classes\\com\\galaxyx\\parser\\GalaxyXLinkingParser.g:137:2: ( PUBLIC | PRIVATE )
// C:\\Users\\Timo\\EclipseProjects\\GalaxyX\\build\\classes\\com\\galaxyx\\parser\\GalaxyXLinkingParser.g:
{
root_0 = (CommonTree)adaptor.nil();
set88=(Token)input.LT(1);
if ( (input.LA(1)>=PRIVATE && input.LA(1)<=PUBLIC) ) {
input.consume();
if ( state.backtracking==0 ) adaptor.addChild(root_0, (CommonTree)adaptor.create(set88));
state.errorRecovery=false;state.failed=false;
}
else {
if (state.backtracking>0) {state.failed=true; return retval;}
MismatchedSetException mse = new MismatchedSetException(null,input);
throw mse;
}
}
retval.stop = input.LT(-1);
if ( state.backtracking==0 ) {
retval.tree = (CommonTree)adaptor.rulePostProcessing(root_0);
adaptor.setTokenBoundaries(retval.tree, retval.start, retval.stop);
}
}
catch (RecognitionException re) {
reportError(re);
recover(input,re);
retval.tree = (CommonTree)adaptor.errorNode(input, retval.start, input.LT(-1), re);
}
finally {
if ( state.backtracking>0 ) { memoize(input, 14, modifier_StartIndex); }
}
return retval;
}
| 9 |
public void test_getValue_long_long() {
assertEquals(0, MillisDurationField.INSTANCE.getValue(0L, 567L));
assertEquals(1234, MillisDurationField.INSTANCE.getValue(1234L, 567L));
assertEquals(-1234, MillisDurationField.INSTANCE.getValue(-1234L, 567L));
try {
MillisDurationField.INSTANCE.getValue(((long) (Integer.MAX_VALUE)) + 1L, 567L);
fail();
} catch (ArithmeticException ex) {}
}
| 1 |
public void updateTo(int index) {
if (index >= 0 && index < chain.size()) {
if (currentIndex > index) {
//Go back
for (int i = currentIndex; i > index; i--) {
chain.get(i).revert();
}
} else if (currentIndex < index) {
//Go forwards
for (int i = currentIndex + 1; i <= index; i++) {
chain.get(i).restore();
}
}
currentIndex = index;
notifyOfUpdate();
}
}
| 6 |
public SLKeyframe(SLConfig cfg, float duration) {
this.cfg = cfg;
this.duration = duration;
for (SLSide s : SLSide.values()) {
cmpsWithStartSide.put(s, new ArrayList<Component>());
cmpsWithEndSide.put(s, new ArrayList<Component>());
}
}
| 1 |
public Message getNextMessage () throws IOException {
// check for pending message from peek.
if (pending != null) {
Message msg = pending;
pending = null;
return msg;
}
// read incoming message from wrapped channel
Message msg = next.getNextMessage();
if (msg == null)
return null;
// get length of message
int size = (msg.getByte() << 8) | msg.getByte();
// check for padding (block ciphers)
int padding = 0;
if ((size & 0x8000) == 0)
padding = msg.getByte();
else
size &= 0x7FFF;
// extract message data.
byte[] data = msg.getArray (size);
//-------------------------------------------------------------
// check for decryption
//-------------------------------------------------------------
if (decrypter != null) {
// decrypt message
data = decrypter.process (data);
if (data == null)
throw new IOException ("Decryption failed!");
// remove padding.
if (padding > 0)
size -= padding;
}
//-------------------------------------------------------------
// check for message digest
//-------------------------------------------------------------
if (hasher != null) {
// check digest
int pos = hasher.checkMessage (data, size, countIn);
if (pos < 0)
throw new IOException ("Hash mismatch");
// move message to begin of buffer
size -= pos;
System.arraycopy (data, pos, data, 0, size);
}
// construct Styx message from data
countIn++;
Message msgIn = new Message (data, size);
return msgIn;
}
| 8 |
public static File getFile(String path) {
return new File(path);
}
| 0 |
public boolean batchExecIntQuery(String command, Vector<int[]> values) throws SQLException
{
boolean value = false;
Connection connection = null;
PreparedStatement stmt = null;
try
{
Class.forName(driver);
connection = DriverManager.getConnection(url, username, passwd);
connection.setAutoCommit(false);
stmt = connection.prepareStatement(command);
for (int i = 0; i < values.size(); i++)
{
int[] val = values.get(i);
for (int j = 0; j < val.length; j++)
{
stmt.setInt((j + 1), val[j]);
}
stmt.addBatch();
}
stmt.executeBatch();
value = true;
connection.commit();
stmt.close();
stmt = null;
connection.close();
connection = null;
}
catch (BatchUpdateException b)
{
System.err.println("SQLException: " + b.getMessage());
System.err.println("SQLState: " + b.getSQLState());
System.err.println("Message: " + b.getMessage());
System.err.println("Vendor: " + b.getErrorCode());
System.err.println("Update counts: ");
value = false;
connection.rollback();
}
catch (Exception e)
{
System.out.println(e);
value = false;
connection.rollback();
}
finally
{
if (stmt != null)
{
try
{
stmt.close();
}
catch (SQLException e)
{
}
stmt = null;
}
if (connection != null)
{
try
{
connection.close();
}
catch (SQLException e)
{
}
connection = null;
}
}
return value;
}
| 8 |
public static boolean check(int row, int col) {
for (int prev = 1; prev < col; prev++)
if (board[prev] == row // Verify row
|| (Math.abs(board[prev] - row) == Math.abs(prev - col))) // Verify
// diagonals
return false;
return true;
}
| 3 |
public boolean attemptCast(Player p) {
if (!Mana.hasMana(p, manaCost)) {
p.sendMessage(ChatColor.RED + "You do not have enough mana to cast this spell.");
return false;
} else {
String name = p.getName();
long t = System.currentTimeMillis();
if (!cast.containsKey(name)) {
cast.put(name, t);
Mana.drainMana(p, manaCost);
return true;
} else {
long c = cast.get(name);
// if time elapsed since last cast is greater than cooldown
// allow
if (t - c > cooldownMS) {
cast.put(name, t);
Mana.drainMana(p, manaCost);
return true;
} else {
p.sendMessage(ChatColor.RED + "You must wait " + (cooldownMS / 1000) + " seconds between casts.");
return false;
}
}
}
}
| 3 |
@Override
public void actionPerformed(ActionEvent e) {
if((e).getSource() == view.getButtons()[CANCELMOVE]){
view.setVisible(false);
model.getMove().resetTerritories();
model.nextPhase();
}else if((e).getSource() == view.getButtons()[MOVE]){
view.setVisible(false);
model.getMove().moveUnits(view.getSlider().getValue());
if(model.getBattle().shallMove()){
model.getBattle().shallNotMove();
}
}else if((e).getSource() == view.getButtons()[SLIDERMINUS] && view.getSlider().getValue() > 1){
view.getSlider().setValue(view.getSlider().getValue() - 1);
}else if((e).getSource() == view.getButtons()[SLIDERPLUS] && view.getSlider().getValue() < view.getSlider().getMaximum()){
view.getSlider().setValue(view.getSlider().getValue() + 1);
}
}
| 7 |
@Override
public void execute(Map<String, Object> map, MainFrame frame) {
System.out.println("Receive Confirm Msg" + map);
String origin = (String) map.get("Origin");
Map<String, Object> reply = (Map<String, Object>) Utilities.deserialize((byte[]) map.get("Content"));
Boolean isConfirmed = (Boolean) reply.get("Reply");
Integer event = (Integer) reply.get("Event");
switch (event) {
case Event.INVITATION:
case Event.INVITATION_RO:
Set<String> invitee = LocalInfo.getInviteeCandidate();
String ip = (String) reply.get("IP");
Integer port = (Integer) reply.get("Port");
if (invitee.contains(ip + ":" + port) && isConfirmed) {
invitee.remove(ip + ":" + port);
LocalInfo.addPeer(origin, new Peer(ip, port));
}
break;
case Event.KICKOUT_REQEUST:
String target = (String) reply.get("Target");
VoteTool.vote(origin);
if (VoteTool.isComplete()) {
LocalSender.sendKickoutCommandMsg(target.getBytes());
}
break;
case Event.LOCK_REQUEST:
VoteTool.vote(origin);
if (VoteTool.isComplete()) {
LocalSender.sendLockCommandMsg();
}
break;
}
}
| 8 |
public void renderPiston(TileEntityPiston par1TileEntityPiston, double par2, double par4, double par6, float par8)
{
Block block = Block.blocksList[par1TileEntityPiston.getStoredBlockID()];
if (block != null && par1TileEntityPiston.getProgress(par8) < 1.0F)
{
Tessellator tessellator = Tessellator.instance;
bindTextureByName("/terrain.png");
RenderHelper.disableStandardItemLighting();
GL11.glBlendFunc(GL11.GL_SRC_ALPHA, GL11.GL_ONE_MINUS_SRC_ALPHA);
GL11.glEnable(GL11.GL_BLEND);
GL11.glDisable(GL11.GL_CULL_FACE);
if (Minecraft.isAmbientOcclusionEnabled())
{
GL11.glShadeModel(GL11.GL_SMOOTH);
}
else
{
GL11.glShadeModel(GL11.GL_FLAT);
}
tessellator.startDrawingQuads();
tessellator.setTranslation(((float)par2 - (float)par1TileEntityPiston.xCoord) + par1TileEntityPiston.getOffsetX(par8), ((float)par4 - (float)par1TileEntityPiston.yCoord) + par1TileEntityPiston.getOffsetY(par8), ((float)par6 - (float)par1TileEntityPiston.zCoord) + par1TileEntityPiston.getOffsetZ(par8));
tessellator.setColorOpaque(1, 1, 1);
if (block == Block.pistonExtension && par1TileEntityPiston.getProgress(par8) < 0.5F)
{
blockRenderer.renderPistonExtensionAllFaces(block, par1TileEntityPiston.xCoord, par1TileEntityPiston.yCoord, par1TileEntityPiston.zCoord, false);
}
else if (par1TileEntityPiston.shouldRenderHead() && !par1TileEntityPiston.isExtending())
{
Block.pistonExtension.setHeadTexture(((BlockPistonBase)block).getPistonExtensionTexture());
blockRenderer.renderPistonExtensionAllFaces(Block.pistonExtension, par1TileEntityPiston.xCoord, par1TileEntityPiston.yCoord, par1TileEntityPiston.zCoord, par1TileEntityPiston.getProgress(par8) < 0.5F);
Block.pistonExtension.clearHeadTexture();
tessellator.setTranslation((float)par2 - (float)par1TileEntityPiston.xCoord, (float)par4 - (float)par1TileEntityPiston.yCoord, (float)par6 - (float)par1TileEntityPiston.zCoord);
blockRenderer.renderPistonBaseAllFaces(block, par1TileEntityPiston.xCoord, par1TileEntityPiston.yCoord, par1TileEntityPiston.zCoord);
}
else
{
blockRenderer.renderBlockAllFaces(block, par1TileEntityPiston.xCoord, par1TileEntityPiston.yCoord, par1TileEntityPiston.zCoord);
}
tessellator.setTranslation(0.0D, 0.0D, 0.0D);
tessellator.draw();
RenderHelper.enableStandardItemLighting();
}
}
| 7 |
public void setDuplicate(boolean duplicate){
this.duplicate = duplicate;
}
| 0 |
public void putAll( Map<? extends Double, ? extends Integer> map ) {
Iterator<? extends Entry<? extends Double,? extends Integer>> it =
map.entrySet().iterator();
for ( int i = map.size(); i-- > 0; ) {
Entry<? extends Double,? extends Integer> e = it.next();
this.put( e.getKey(), e.getValue() );
}
}
| 8 |
public int getSelection()
{
if(selectionOvalY == 94) return 1;
else if(selectionOvalY == 114) return 2;
else if(selectionOvalY == 134) return 3;
else if(selectionOvalY == 154) return 4;
else if(selectionOvalY == 174) return 5;
return 0;
}
| 5 |
public void launchDialog(){
NotificationFactory.notify("https://au.finance.yahoo.com/", "Visit finance.yahoo.com to look up Stock Symbols");
JTextField stockfield = new JTextField("");
JRadioButton fullscreen = new JRadioButton();
JRadioButton testdata = new JRadioButton();
JSlider slider_size = new JSlider(1000, 100000, 10000);
JPanel panel = new JPanel(new GridLayout(0, 1));
panel.add(new JLabel("STOCK SYMBOL: "));
panel.add(stockfield);
fullscreen.add(new JLabel(" FULLSCREEN"));
panel.add(fullscreen);
fullscreen.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
if(launchfullscreen){
launchfullscreen = false;
} else {
launchfullscreen = true;
}
}
});
testdata.add(new JLabel(" TEST DATA"));
panel.add(testdata);
testdata.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
if(intest){
intest = false;
} else {
intest = true;
}
}
});
panel.add(new JLabel("Memory Size"));
panel.add(slider_size);
int result = JOptionPane.showConfirmDialog(null, panel, "Stocker",
JOptionPane.WARNING_MESSAGE, JOptionPane.PLAIN_MESSAGE);
if (result == JOptionPane.OK_OPTION) {
System.out.println(stockfield.getText().trim().toUpperCase() + ", " + slider_size.getValue());
configSplash();
launchStocker(stockfield.getText().trim().toUpperCase(), slider_size.getValue());
} else {
System.exit(0);
}
}
| 3 |
private void validateCustomerInfo(HttpServletRequest request, Customer customer) {
if (!customer.isValid())
request.setAttribute("error", "true");
if (!customer.isValidGivenName())
request.setAttribute("invalidGivenName", "Given Name must not be empty and number");
if (!customer.isValidSurname())
request.setAttribute("invalidSurname", "Surname must not be empty and number");
if (!customer.isValidAddress())
request.setAttribute("invalidAddress", "Address must not be empty and special character");
if (!customer.isValidEmail())
request.setAttribute("invalidEmail", "Email has an invalid email format");
if (!customer.isValidCountry())
request.setAttribute("invalidCountry", "Country name must not be empty and number");
if (!customer.isValidState())
request.setAttribute("invalidState", "State must not be empty and number");
if (!customer.isValidPoscode())
request.setAttribute("invalidPostCode", "Postcode must not be empty and characters");
if (!customer.isValidCreditNo())
request.setAttribute("invalidCreditNo", "Credit Number must not be empty and characters");
}
| 9 |
public int getTextDisplayedWidth(String text) {
if (text == null)
return 0;
int width = 0;
/*
* Iterate through every character in the text.
*/
for (int c = 0; c < text.length(); c++) {
/*
* If the current character is the start of a colour
* code or a crown code we can skip it as it will be
* stripped out later and therefore not be displayed.
*/
if (text.charAt(c) == '@'
&& c + 4 < text.length()
&& text.charAt(c + 4) == '@') {
c += 4;
} else {
/*
* Add the displayed width of the current character's
* glyph to the total width of the text.
*/
width += glyphDisplayWidth[text.charAt(c)];
}
}
return width;
}
| 5 |
@Override
public int hashCode() {
int result = item != null ? item.hashCode() : 0;
result = 31 * result + (item2 != null ? item2.hashCode() : 0);
result = 31 * result + (item3 != null ? item3.hashCode() : 0);
result = 31 * result + (item4 != null ? item4.hashCode() : 0);
result = 31 * result + (item5 != null ? item5.hashCode() : 0);
result = 31 * result + (item6 != null ? item6.hashCode() : 0);
result = 31 * result + (item7 != null ? item7.hashCode() : 0);
return result;
}
| 7 |
public double weightedGeometricMean_as_double() {
if (!weightsSupplied) {
System.out.println("weightedGeometricMean_as_double: no weights supplied - unweighted value returned");
return this.geometricMean_as_double();
} else {
boolean holdW = Stat.weightingOptionS;
if (weightingReset) {
if (weightingOptionI) {
Stat.weightingOptionS = true;
} else {
Stat.weightingOptionS = false;
}
}
double gmean = 0.0D;
switch (type) {
case 1:
double[] dd = this.getArray_as_double();
double[] ww = this.getArray_as_double();
gmean = Stat.geometricMean(dd, ww);
break;
case 12:
BigDecimal[] bd = this.getArray_as_BigDecimal();
BigDecimal[] wd = this.getArray_as_BigDecimal();
gmean = Stat.geometricMean(bd, wd);
bd = null;
wd = null;
break;
case 14:
throw new IllegalArgumentException("Complex cannot be converted to double");
default:
throw new IllegalArgumentException("This type number, " + type + ", should not be possible here!!!!");
}
Stat.weightingOptionS = holdW;
return gmean;
}
}
| 6 |
final void da(int i, int i_254_, int i_255_, int[] is) {
try {
anInt7528++;
float f
= (((float) i_254_
* (((Class101_Sub3) ((OpenGlToolkit) this).aClass101_Sub3_7760)
.aFloat5754))
+ (((Class101_Sub3) ((OpenGlToolkit) this).aClass101_Sub3_7760)
.aFloat5756) * (float) i
+ (((Class101_Sub3) ((OpenGlToolkit) this).aClass101_Sub3_7760)
.aFloat5784) * (float) i_255_
+ (((Class101_Sub3) ((OpenGlToolkit) this).aClass101_Sub3_7760)
.aFloat5751));
if (f < (float) ((OpenGlToolkit) this).anInt7826
|| f > (float) anInt7814)
is[0] = is[1] = is[2] = -1;
else {
int i_256_
= (int) ((float) ((OpenGlToolkit) this).anInt7771
* (((float) i_254_
* (((Class101_Sub3)
((OpenGlToolkit) this).aClass101_Sub3_7760)
.aFloat5750))
+ (((Class101_Sub3)
((OpenGlToolkit) this).aClass101_Sub3_7760)
.aFloat5770) * (float) i
+ (((Class101_Sub3)
((OpenGlToolkit) this).aClass101_Sub3_7760)
.aFloat5781) * (float) i_255_
+ (((Class101_Sub3)
((OpenGlToolkit) this).aClass101_Sub3_7760)
.aFloat5747))
/ f);
int i_257_
= (int) ((((Class101_Sub3)
((OpenGlToolkit) this).aClass101_Sub3_7760).aFloat5772
+ (((float) i
* (((Class101_Sub3)
((OpenGlToolkit) this).aClass101_Sub3_7760)
.aFloat5761))
+ (((Class101_Sub3)
((OpenGlToolkit) this).aClass101_Sub3_7760)
.aFloat5769) * (float) i_254_
+ (((Class101_Sub3)
((OpenGlToolkit) this).aClass101_Sub3_7760)
.aFloat5762) * (float) i_255_))
* (float) ((OpenGlToolkit) this).anInt7794 / f);
if (!(((OpenGlToolkit) this).aFloat7872 <= (float) i_256_)
|| !((float) i_256_ <= ((OpenGlToolkit) this).aFloat7835)
|| !(((OpenGlToolkit) this).aFloat7836 <= (float) i_257_)
|| !(((OpenGlToolkit) this).aFloat7830 >= (float) i_257_))
is[0] = is[1] = is[2] = -1;
else {
is[2] = (int) f;
is[0] = (int) (-((OpenGlToolkit) this).aFloat7872
+ (float) i_256_);
is[1] = (int) (-((OpenGlToolkit) this).aFloat7836
+ (float) i_257_);
}
}
} catch (RuntimeException runtimeexception) {
throw Class348_Sub17.method2929(runtimeexception,
("qo.da(" + i + ',' + i_254_ + ','
+ i_255_ + ','
+ (is != null ? "{...}" : "null")
+ ')'));
}
}
| 8 |
private void leftPossibleMoves(Piece piece, Position position)
{
int x1 = position.getPositionX();
int y1 = position.getPositionY();
if(x1 >= 1 && x1 <= 7)
{
boolean pieceNotFound = true;
for (int i = x1 - 1; pieceNotFound && (i >= 0) && (board.getChessBoardSquare(i, y1).getPiece().getPieceColor() != piece.getPieceColor()); i--)
{
// System.out.print(" " + coordinateToPosition(i, y1));
Position newMove = new Position(i, y1);
piece.setPossibleMoves(newMove);
if (board.getChessBoardSquare(i, y1).getPiece().getPieceType() != board.getBlankPiece().getPieceType())
{
pieceNotFound = false;
if(board.getChessBoardSquare(i, y1).getPiece().getPieceColor() != piece.getPieceColor())
{
// System.out.print("*");
}
}
}
}
}
| 7 |
public static void main(String [] args) {
try {
boolean readExp = Utils.getFlag('l', args);
final boolean writeExp = Utils.getFlag('s', args);
final String expFile = Utils.getOption('f', args);
if ((readExp || writeExp) && (expFile.length() == 0)) {
throw new Exception("A filename must be given with the -f option");
}
Experiment exp = null;
if (readExp) {
FileInputStream fi = new FileInputStream(expFile);
ObjectInputStream oi = new ObjectInputStream(
new BufferedInputStream(fi));
exp = (Experiment)oi.readObject();
oi.close();
} else {
exp = new Experiment();
}
System.err.println("Initial Experiment:\n" + exp.toString());
final JFrame jf = new JFrame("Weka Experiment Setup");
jf.getContentPane().setLayout(new BorderLayout());
final SetupPanel sp = new SetupPanel();
//sp.setBorder(BorderFactory.createTitledBorder("Setup"));
jf.getContentPane().add(sp, BorderLayout.CENTER);
jf.addWindowListener(new WindowAdapter() {
public void windowClosing(WindowEvent e) {
System.err.println("\nFinal Experiment:\n"
+ sp.m_Exp.toString());
// Save the experiment to a file
if (writeExp) {
try {
FileOutputStream fo = new FileOutputStream(expFile);
ObjectOutputStream oo = new ObjectOutputStream(
new BufferedOutputStream(fo));
oo.writeObject(sp.m_Exp);
oo.close();
} catch (Exception ex) {
ex.printStackTrace();
System.err.println("Couldn't write experiment to: " + expFile
+ '\n' + ex.getMessage());
}
}
jf.dispose();
System.exit(0);
}
});
jf.pack();
jf.setVisible(true);
System.err.println("Short nap");
Thread.currentThread().sleep(3000);
System.err.println("Done");
sp.setExperiment(exp);
} catch (Exception ex) {
ex.printStackTrace();
System.err.println(ex.getMessage());
}
}
| 7 |
private void printJoins(Vector<LogicalJoinNode> js, PlanCache pc,
HashMap<String, TableStats> stats,
HashMap<String, Double> selectivities) {
JFrame f = new JFrame("Join Plan for " + p.getQuery());
// Set the default close operation for the window,
// or else the program won't exit when clicking close button
f.setDefaultCloseOperation(WindowConstants.DISPOSE_ON_CLOSE);
f.setVisible(true);
f.setSize(300, 500);
HashMap<String, DefaultMutableTreeNode> m = new HashMap<String, DefaultMutableTreeNode>();
// int numTabs = 0;
// int k;
DefaultMutableTreeNode root = null, treetop = null;
HashSet<LogicalJoinNode> pathSoFar = new HashSet<LogicalJoinNode>();
boolean neither;
System.out.println(js);
for (LogicalJoinNode j : js) {
pathSoFar.add(j);
System.out.println("PATH SO FAR = " + pathSoFar);
String table1Name = Database.getCatalog().getTableName(
this.p.getTableId(j.t1Alias));
String table2Name = Database.getCatalog().getTableName(
this.p.getTableId(j.t2Alias));
// Double c = pc.getCost(pathSoFar);
neither = true;
root = new DefaultMutableTreeNode("Join " + j + " (Cost ="
+ pc.getCost(pathSoFar) + ", card = "
+ pc.getCard(pathSoFar) + ")");
DefaultMutableTreeNode n = m.get(j.t1Alias);
if (n == null) { // never seen this table before
n = new DefaultMutableTreeNode(j.t1Alias
+ " (Cost = "
+ stats.get(table1Name).estimateScanCost()
+ ", card = "
+ stats.get(table1Name).estimateTableCardinality(
selectivities.get(j.t1Alias)) + ")");
root.add(n);
} else {
// make left child root n
root.add(n);
neither = false;
}
m.put(j.t1Alias, root);
n = m.get(j.t2Alias);
if (n == null) { // never seen this table before
n = new DefaultMutableTreeNode(
j.t2Alias == null ? "Subplan"
: (j.t2Alias
+ " (Cost = "
+ stats.get(table2Name)
.estimateScanCost()
+ ", card = "
+ stats.get(table2Name)
.estimateTableCardinality(
selectivities
.get(j.t2Alias)) + ")"));
root.add(n);
} else {
// make right child root n
root.add(n);
neither = false;
}
m.put(j.t2Alias, root);
// unless this table doesn't join with other tables,
// all tables are accessed from root
if (!neither) {
for (String key : m.keySet()) {
m.put(key, root);
}
}
treetop = root;
}
JTree tree = new JTree(treetop);
JScrollPane treeView = new JScrollPane(tree);
tree.setShowsRootHandles(true);
// Set the icon for leaf nodes.
ImageIcon leafIcon = new ImageIcon("join.jpg");
DefaultTreeCellRenderer renderer = new DefaultTreeCellRenderer();
renderer.setOpenIcon(leafIcon);
renderer.setClosedIcon(leafIcon);
tree.setCellRenderer(renderer);
f.setSize(300, 500);
f.add(treeView);
for (int i = 0; i < tree.getRowCount(); i++) {
tree.expandRow(i);
}
if (js.size() == 0) {
f.add(new JLabel("No joins in plan."));
}
f.pack();
}
| 8 |
static Point[] convexHull2D(Point[] ps, Point normal) {
final Point dir = perpendicular(normal); // 任意の点が相異ならdir=ps[1]-ps[0]でよい
Arrays.sort(ps, new Comparator<Point>() {
@Override
public int compare(Point o1, Point o2) {
double d = dir.dot(o2.subtract(o1));
return !approxEquals(d, 0) ? (int) Math.signum(d) : 0;
}
});
int n = ps.length;
Point[] hull = new Point[2 * n];
int k = 0; // k == hull.size()
// 下側凸包(向き的に上側凸包というべきかも)
for (int i = 0; i < n; hull[k++] = ps[i++]) {
while (k >= 2 && ccw(hull[k - 2], hull[k - 1], ps[i], normal) <= 0)
--k; // 最後のベクトルから見て候補点が右側にあるなら、最後の点をはずす
// 現状ccwが+2を返さないので縮退してると死ぬかもしれない
}
// 下側凸包の後に上側を加える
int lowerEnd = k;
for (int i = n - 2; i >= 0; hull[k++] = ps[i--]) {
while (k > lowerEnd && ccw(hull[k - 2], hull[k - 1], ps[i], normal) <= 0)
--k;
}
Point[] ret = new Point[k - 1];
System.arraycopy(hull, 0, ret, 0, k - 1); // 最後は重複しているので消す
return ret;
}
| 7 |
private void downloadParseOutput() {
try {
WebPage page = loadWebPage();
quotes = Parser.getQuotes(page);
sortQuotesByScore();
takeOnlyTopTenQuotes();
shuffleQuotes();
takeOneQuoteAndSetOutput();
cooldown.start();
} catch (IOException ioe) {
setError("Bash.org is unreachable.", ioe);
}
}
| 1 |
public void run() {
// If any of these stay the same then something is wrong
InetAddress IPAddress;
try {
IPAddress = InetAddress.getByName(request.getIP());
} catch (UnknownHostException e1) {
e1.printStackTrace();
bot.sendMessageToChannel("Error: Query IP address could not be resolved or is using IPv6.");
return;
}
int port = request.getPort();
byte[] dataToSend = null;
byte[] dataToReceive = new byte[2048]; // Doubled standard size in case there's some dumb wad list with a lot of characters
// Try with resources, we want to always have the socket close
try (DatagramSocket connectionSocket = new DatagramSocket()) {
// Prepare our send packet
dataToSend = new byte[] { (byte)199, 0, 0, 0, -64, 18, 0, 8 }; // Send challenge and then SQF_FlagsStuff
byte[] huffmanToSend = Huffman.encode(dataToSend);
// Now send the data
DatagramPacket sendPacket = new DatagramPacket(huffmanToSend, huffmanToSend.length, IPAddress, port);
connectionSocket.send(sendPacket);
// Block until we receive something or time out
DatagramPacket receivePacket = new DatagramPacket(dataToReceive, dataToReceive.length);
connectionSocket.setSoTimeout(SOCKET_TIMEOUT_MS);
connectionSocket.receive(receivePacket);
// Prepare the data for processing
byte[] receivedData = receivePacket.getData();
byte[] receivedTruncatedData = new byte[receivePacket.getLength()];
System.arraycopy(receivedData, 0, receivedTruncatedData, 0, receivePacket.getLength());
byte[] decodedData = Huffman.decode(receivedTruncatedData);
// Process it
processIncomingPacket(decodedData);
} catch (UnknownHostException e) {
bot.sendMessageToChannel("IP of the host to query could not be determined. Please see if your IP is a valid address that can be reached.");
e.printStackTrace();
} catch (SocketException e) {
bot.sendMessageToChannel("Error with the socket when handling query. Please try again or contact an administrator.");
e.printStackTrace();
} catch (SocketTimeoutException e) {
bot.sendMessageToChannel("Socket timeout, IP is incorrect or server is down/unreachable (consider trying again if it is your first try).");
e.printStackTrace();
} catch (IOException e) {
bot.sendMessageToChannel("IOException from query. Please try again or contact an administrator.");
e.printStackTrace();
} catch (Exception e) {
bot.sendMessageToChannel("Unknown exception occured, contact an administrator now.");
e.printStackTrace();
}
// Always alert the handler thread we are done
handlerThread.signalProcessQueryComplete();
}
| 6 |
public ArtistFeature(File song)
throws MP3Exception {
super(song);
this.obf= new ObjectFactory();
this.artist= this.obf.createArtistType();
this.getHttp= GetHttpPage.getInstance();
try {
this.log= ArtistLogger.getInstance().getLog();
} catch (LogException e) {
throw new MP3Exception("LogException "+e.getMessage(), e);
}
}
| 1 |
public void visitAttribute(final Attribute attr) {
buf.setLength(0);
buf.append(tab).append("ATTRIBUTE ");
appendDescriptor(-1, attr.type);
if (attr instanceof Traceable) {
((Traceable) attr).trace(buf, null);
} else {
buf.append(" : unknown\n");
}
text.add(buf.toString());
}
| 1 |
public OutlineEditableIndicator(OutlinerCellRendererImpl renderer) {
super(renderer, GUITreeLoader.reg.getText("tooltip_toggle_editability"));
}
| 0 |
public Config newConfig(App app)
throws IOException
{
//System.out.println("MultiConfigMaker.newConfig");
MultiConfig ret = new MultiConfig();
for (Object obj : configs) {
if (obj instanceof Config) {
ret.add((Config)obj);
} else if (obj instanceof File) {
File f = (File)obj;
if (f.isDirectory()) {
ret.add(new DirConfig((File)obj));
} else {
String name = f.getName();
int dot = name.lastIndexOf('.');
String ext = name.substring(dot+1).toLowerCase();
Config config;
if ("jar".equals(ext)) config = ZipConfig.loadFromLauncher(f);
else config = ZipConfig.loadFromFile(f);
config.setName(f.getName());
//System.out.println("MultiConfigMaker setting config name to " + config.getName());
ret.add(config);
}
} else if (obj instanceof String) {
ret.add(new ResourceConfig((String)obj));
} else if (obj instanceof ConfigMaker) {
ConfigMaker maker = (ConfigMaker)obj;
ret.add(maker.newConfig(app));
} else {
throw new IllegalArgumentException("class " + obj.getClass());
}
}
if (ret.size() == 1) return ret.get(0);
return ret;
}
| 8 |
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
System.out.print("Enter Number:");
int input = in.nextInt();
System.out.println("Square is "+(input*input));
System.out.println("Cube is "+(input*input*input));
System.out.println("Fourth Power is "+ Math.pow(input,4));
}
| 0 |
protected NCBIFastqIdParser(String id) {
Matcher m = Pattern.compile(REGEX).matcher(id);
if (!m.matches())
return;
if (m.group(2) != null) {
IdParser subParser = IdParserFactory.createParser("@" + m.group(2));
if (subParser != null) {
for (IdAttributes a : subParser.getAllAttributes())
setAttribute(a, subParser.getAttribute(a));
}
}
setAttribute(IdAttributes.FASTQ_TYPE, NAME);
setAttribute(IdAttributes.NCBI_INDEX, m.group(1));
if (m.group(3) != null)
setAttribute(IdAttributes.NCBI_DESCRIPTION, m.group(3));
}
| 5 |
public void buttonClicked(WizardButtonEvent wbe) {
if( wbe.getButtonType() == WizardButtonListener.NEXT && wbe.getCard() == ep ){
options = new EmbedExtractOptions();
options.setInputFile( sif.getSelectedFile() );
options.setOutputFile( sof.getOutputFile() );
options.setPassword( ep.getPassword() );
options.createExtractColumnData();
vo.showChosenOptions(options);
}else if( wbe.getButtonType() == WizardButtonListener.NEXT && wbe.getCard() == vo ){
ExtractProcess process = new ExtractProcess(options);
java.io.ByteArrayOutputStream outBuffer = new java.io.ByteArrayOutputStream();
java.io.OutputStream out = System.out;
System.setOut( new java.io.PrintStream(outBuffer) );
process.startExtract();
System.out.println("Extraction Completed.");
System.setOut( System.out );
sepd.addOutputLine(new String(outBuffer.toByteArray()));
}else if( wbe.getButtonType() == WizardButtonListener.NEXT && wbe.getCard() == sepd ){
try{
java.io.BufferedReader br = new java.io.BufferedReader(new java.io.FileReader(options.getOutputFile()));
String line = null;
while( (line = br.readLine()) != null )
sef.addOutputLine(line);
br.close();
sef.setDisplayText("Output File : "+options.getOutputFile().getAbsolutePath() );
}catch(java.io.FileNotFoundException fnfe){
fnfe.printStackTrace();
javax.swing.JOptionPane.showMessageDialog(null,"Output file not created!");
}catch(java.io.IOException ie){
ie.printStackTrace();
javax.swing.JOptionPane.showMessageDialog(null,"File read error!");
}
}
}
| 9 |
@Override
public double getVariance() throws VarianceException {
if (lambda <= 1) {
throw new VarianceException("Pareto variance lambda > 1.");
} else if (1 < lambda && lambda <= 2) {
return Double.POSITIVE_INFINITY;
} else {
return Math.pow(k / (lambda - 1), 2) * lambda / (lambda - 2);
}
}
| 3 |
public void actionPerformed(ActionEvent e){
String action = e.getActionCommand();
if (action.equals("refreshList")){
System.out.println("refreshing...");
refreshGUIServer();
} else if(action.equals("arClick")){
System.out.println("arClick");
if(cRefresh.getModel().isSelected()){
timerText.setEditable(false);
startTimer();
} else {
timerText.setEditable(true);
}
} else if(action.equals("console")){
c.toggleVisible();
}
}
| 4 |
public long getId() {
return Id;
}
| 0 |
@Override
public String call() throws Exception {
return "result of TaskWithResult " + id;
}
| 0 |
public void keyReleased(KeyEvent ke) {
Action action = actionOf(ke.getKeyCode());
if (action == null) return;
releaseKey(action);
switch (action) {
case MOVE_UP:
if (vy < 0) { vy = 0; }
break;
case MOVE_DOWN:
if (vy > 0) { vy = 0; }
break;
case MOVE_LEFT:
if (vx < 0) { vx = 0; }
break;
case MOVE_RIGHT:
if (vx > 0) { vx = 0; }
break;
}
}
| 9 |
public static void setLook()
{
try {
// for( LookAndFeelInfo info : UIManager.getInstalledLookAndFeels())
// System.out.println("look and feels: " + info.getClassName());
UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
//UIManager.setLookAndFeel("javax.swing.plaf.metal.MetalLookAndFeel");
//UIManager.setLookAndFeel("javax.swing.plaf.nimbus.NimbusLookAndFeel");
//UIManager.setLookAndFeel("com.sun.java.swing.plaf.motif.MotifLookAndFeel");
//UIManager.setLookAndFeel("com.sun.java.swing.plaf.windows.WindowsLookAndFeel");
//UIManager.setLookAndFeel("com.sun.java.swing.plaf.windows.WindowsClassicLookAndFeel");
}
catch (UnsupportedLookAndFeelException e) { }
catch (ClassNotFoundException e) { }
catch (InstantiationException e) { }
catch (IllegalAccessException e) { }
}
| 4 |
protected void load(PropertiesConfiguration config) throws IOException, ConfigurationException {
this.name = config.getString("name");
this.collection = config.getString("collection");
if (collection != null) collection = collection.trim();
String urlPattern = config.getString("acceptableURLs");
if (urlPattern != null) this.acceptableURLs = Pattern.compile(urlPattern.trim());
String contentPattern = config.getString("acceptableContent");
if (contentPattern != null) this.acceptableContent = Pattern.compile(contentPattern.trim());
List<Pattern> patterns = new ArrayList<Pattern>();
for (String p : config.getStringArray("patterns")) {
patterns.add(Pattern.compile(p.trim(),
Pattern.CASE_INSENSITIVE | Pattern.MULTILINE | Pattern.DOTALL));
}
this.patterns = patterns.toArray(new Pattern[0]);
}
| 4 |
public void keyPressed(KeyEvent evt)
{
int modifiers = evt.getModifiersEx();
int keyCode = evt.getKeyCode();
// Ctrl + <key>
int onmask = KeyEvent.CTRL_DOWN_MASK;
int offmask = KeyEvent.SHIFT_DOWN_MASK | KeyEvent.ALT_DOWN_MASK;
if ((modifiers & (onmask | offmask)) == onmask)
{
switch(keyCode)
{
case KeyEvent.VK_S:
save();
break;
case KeyEvent.VK_A:
selectAll();
break;
case KeyEvent.VK_Q:
quit();
break;
case KeyEvent.VK_N:
createNewTab(null);
break;
case KeyEvent.VK_O:
open();
break;
case KeyEvent.VK_W:
closeCurrentTab();
break;
}
}
// Ctrl + Shift + <key>
onmask = KeyEvent.CTRL_DOWN_MASK | KeyEvent.SHIFT_DOWN_MASK;
offmask = KeyEvent.ALT_DOWN_MASK;
if ((modifiers & (onmask | offmask)) == onmask)
{
if (keyCode == KeyEvent.VK_S)
saveAs();
}
updateGui();
}
| 9 |
private void buildIntersections() {
//initialize
_intersections = new Intersection[_gridDimensions.getRow()][_gridDimensions.getColumn()];
// Add organize by [rows][column]
for (int i=0; i<_gridDimensions.getRow(); i++) {
for (int j=0; j<_gridDimensions.getColumn(); j++) {
//create a new intersection
_intersections[i][j] = (Intersection)VehicleAcceptorFactory.newIntersection(_ts);
}
}
}
| 2 |
public static Type getType(String name) {
Type type = null;
if(listTypes.containsKey(name)) {
type = listTypes.get(name);
}
return type;
}
| 1 |
public static void main(String[] args) {
int i = 200;
long lng = (long)i;
lng = i; // "Widening," so cast not really required
long lng2 = (long)200;
lng2 = 200;
// A "narrowing conversion":
i = (int)lng2; // Cast required
}
| 0 |
public double MacroRecall() {
if (computed == 0) countStuff();
double mrec = 0;
for (int i=0; i<catnum; i++) {
if ((tp[i] != 0) && (tp[i]+fn[i] != 0))
mrec += tp[i]/(tp[i]+fn[i]);
}
return mrec/catnum;
}
| 4 |
protected void changedBroadcastEnable(){
for(ModelChangeListener mcl : listeners){
mcl.changedBroadcast(bcast_enabled);
}
}
| 1 |
@SuppressWarnings("unchecked")
// <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
private void initComponents() {
jCheckBoxComptesRendus = new javax.swing.JCheckBox();
jCheckBoxVisiteurs = new javax.swing.JCheckBox();
jCheckBoxPracticiens = new javax.swing.JCheckBox();
jCheckBoxMedicaments = new javax.swing.JCheckBox();
jCheckBoxQuit = new javax.swing.JCheckBox();
filler1 = new javax.swing.Box.Filler(new java.awt.Dimension(0, 0), new java.awt.Dimension(0, 0), new java.awt.Dimension(0, 0));
jLabelTitre = new javax.swing.JLabel();
filler2 = new javax.swing.Box.Filler(new java.awt.Dimension(10, 0), new java.awt.Dimension(10, 0), new java.awt.Dimension(10, 32767));
jSeparator1 = new javax.swing.JSeparator();
setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);
jCheckBoxComptesRendus.setText("Comptes-Rendus");
jCheckBoxComptesRendus.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
jCheckBoxComptesRendusActionPerformed(evt);
}
});
jCheckBoxVisiteurs.setText("Visiteurs");
jCheckBoxVisiteurs.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
jCheckBoxVisiteursActionPerformed(evt);
}
});
jCheckBoxPracticiens.setText("Practiciens");
jCheckBoxPracticiens.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
jCheckBoxPracticiensActionPerformed(evt);
}
});
jCheckBoxMedicaments.setText("Medicaments");
jCheckBoxMedicaments.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
jCheckBoxMedicamentsActionPerformed(evt);
}
});
jCheckBoxQuit.setText("Quitter");
jCheckBoxQuit.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
jCheckBoxQuitActionPerformed(evt);
}
});
jLabelTitre.setText("Gestion des comptes rendus");
javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
getContentPane().setLayout(layout);
layout.setHorizontalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(layout.createSequentialGroup()
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(layout.createSequentialGroup()
.addGap(135, 135, 135)
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(jCheckBoxComptesRendus)
.addComponent(jCheckBoxMedicaments)
.addComponent(jCheckBoxQuit)
.addComponent(jCheckBoxPracticiens)
.addComponent(jCheckBoxVisiteurs)))
.addGroup(layout.createSequentialGroup()
.addGap(222, 222, 222)
.addComponent(filler1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
.addGroup(layout.createSequentialGroup()
.addGap(163, 163, 163)
.addComponent(jLabelTitre)))
.addContainerGap(189, Short.MAX_VALUE))
.addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
.addGap(0, 0, Short.MAX_VALUE)
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(filler2, javax.swing.GroupLayout.Alignment.TRAILING, javax.swing.GroupLayout.PREFERRED_SIZE, 412, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(jSeparator1, javax.swing.GroupLayout.Alignment.TRAILING, javax.swing.GroupLayout.PREFERRED_SIZE, 468, javax.swing.GroupLayout.PREFERRED_SIZE)))
);
layout.setVerticalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(layout.createSequentialGroup()
.addGap(45, 45, 45)
.addComponent(jLabelTitre)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(filler1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addGap(14, 14, 14)
.addComponent(filler2, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(jSeparator1, javax.swing.GroupLayout.PREFERRED_SIZE, 6, javax.swing.GroupLayout.PREFERRED_SIZE)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, 67, Short.MAX_VALUE)
.addComponent(jCheckBoxComptesRendus)
.addGap(18, 18, 18)
.addComponent(jCheckBoxVisiteurs)
.addGap(18, 18, 18)
.addComponent(jCheckBoxPracticiens)
.addGap(18, 18, 18)
.addComponent(jCheckBoxMedicaments)
.addGap(18, 18, 18)
.addComponent(jCheckBoxQuit)
.addGap(80, 80, 80))
);
pack();
}// </editor-fold>//GEN-END:initComponents
| 0 |
public static UUID nameUUIDFromBytes(byte[] name) {
MessageDigest md;
try {
md = MessageDigest.getInstance("MD5");
} catch (NoSuchAlgorithmException nsae) {
throw new InternalError("MD5 not supported");
}
byte[] md5Bytes = md.digest(name);
md5Bytes[6] &= 0x0f; /* clear version */
md5Bytes[6] |= 0x30; /* set to version 3 */
md5Bytes[8] &= 0x3f; /* clear variant */
md5Bytes[8] |= 0x80; /* set to IETF variant */
return new UUID(md5Bytes);
}
| 1 |
private void jTextField5FocusLost(java.awt.event.FocusEvent evt) {//GEN-FIRST:event_jTextField5FocusLost
if(!responsableAntiguo.equals(jTextField5.getText())){
int i = JOptionPane.showConfirmDialog(frame, "Seguro que quieres cambiar el rol responsable: "+responsableAntiguo+
"\npor "+jTextField5.getText());
if(i==0){
boolean puede = false;
for (int j = 0; j < EntityDB.getInstance().getRoles().size(); j++) {
if(EntityDB.getInstance().getRoles().get(j).equals(jTextField5.getText())){
puede = true;
break;
}
}
if(puede){
Stack s = new Stack();
s.push(EntityDB.getInstance().getRoot());
while(s.size() != 0){
Entidad_P p = (Entidad_P)s.pop();
if(p.getNombre().equals(jTextField1.getText())){
p.setResponsable(jTextField5.getText());
}
for (int j = 0; j < p.getHijas().length; j++) {
s.push(p.getHijas()[j]);
}
}
}else{
JOptionPane.showMessageDialog(frame, "No existe el Rol que has puesto como responsable");
}
}
}
}//GEN-LAST:event_jTextField5FocusLost
| 8 |
@Test
public void testRandomArray() throws Exception {
FileWriter FW = getFileWriter();
TestClass[] tests = FW.getArray("arrRand", new TestClass());
assert tests.length == testArray.length;
for(int i = 0; i < tests.length; i++) {
assert tests[i].val == testRandomArray[i];
}
}
| 1 |
private void queueInorder(BSTNode node){
//Fill queue inorder
if(node.getLeft() != null) {
queueInorder(node.getLeft());
}
Term t = (Term)node.getTerm();
queue.add(t);
if(node.getRight() != null){
queueInorder(node.getRight());
}
}
| 2 |
public void play(Sequence sequence, boolean loop) {
if (sequencer != null && sequence != null && sequencer.isOpen()) {
try {
sequencer.setSequence(sequence);
sequencer.start();
this.loop = loop;
}
catch (InvalidMidiDataException ex) {
ex.printStackTrace();
}
}
}
| 4 |
public void login(String password)
{
currentEmployee = timeMan.login(password);
if(currentEmployee == null)
{
JOptionPane.showMessageDialog(null, "Sorry, no password match found. Please try again.");
return;
}
else
{
bLogin.setEnabled(false);
bLogout.setEnabled(true);
tPassword.setEnabled(false);
loggedIn = true;
if(currentEmployee.getAuthLevel() == 0)
{
userPane.loadEmployee(currentEmployee);
userPane.setVisible(true);
}
else if(currentEmployee.getAuthLevel() >= 1)
adminPane.setVisible(true);
}
}
| 3 |
public static void main(String args[]) {
Board b = new Board();
b.loadBoardGraphFromResource("cs283/catan/resources/board.csv");
b.loadBoardTilesFromResource("cs283/catan/resources/tiles.csv");
for (Map.Entry<Coordinate, Node> x : b.nodeSet.entrySet()) {
System.out.println(x.getKey());
}
for (Map.Entry<Coordinate, Tile> x : b.tileSet.entrySet()) {
System.out.println("Tile: " + x.getKey() + " roll: " + x.getValue().getRollNumber() + "\ttype: " + x.getValue().getTileType());
}
Scanner in = new Scanner(System.in);
Player bob = new Player("Bob", 0);
Player joe = new Player("Joe", 1);
System.out.println(b.addSettlement(new Coordinate(0,0,2), joe, false, false));
System.out.println(b.addSettlement(new Coordinate(0,0,4), bob, false, false));
System.out.println(b.addSettlement(new Coordinate(1,-1,5), joe, false, false));
System.out.println(b.addSettlement(new Coordinate(1,-1,1), joe, false, false));
System.out.println(b.upgradeSettlement(new Coordinate(0, 0, 2), joe));
System.out.println(b.addRoad(new Coordinate(0,0,4), new Coordinate(0, 0, 3), bob, false));
System.out.println(b.addRoad(new Coordinate(0, 0, 3), new Coordinate(0, 0, 2), joe, false));
System.out.println(b.addRoad(new Coordinate(0, 0, 2), new Coordinate(0, 0, 1), joe, false));
System.out.println(b.addSettlement(new Coordinate(-2,2,0), bob, false, false));
System.out.println(b.addRoad(new Coordinate(-2,2,0), new Coordinate(-2, 2, 1), bob, false));
System.out.println(b.addRoad(new Coordinate(-2,2,1), new Coordinate(-2, 2, 2), bob, false));
System.out.println(b.addRoad(new Coordinate(-2,2,3), new Coordinate(-2, 2, 2), bob, false));
System.out.println(b.addRoad(new Coordinate(-2,2,3), new Coordinate(-2, 2, 4), bob, false));
System.out.println(b.addRoad(new Coordinate(-2,2,4), new Coordinate(-2, 2, 5), bob, false));
System.out.println(b.addRoad(new Coordinate(-2,2,0), new Coordinate(-2, 2, 5), bob, false));
System.out.println(b.addRoad(new Coordinate(-2, 1, 2), new Coordinate(-2, 1, 3), bob, false));
System.out.println(b.addRoad(new Coordinate(-2, 1, 3), new Coordinate(-2, 1, 4), bob, false));
System.out.println(b.getResourceCardsEarned(5, joe));
System.out.println(b.getResourceCardsEarned(5, bob));
System.out.println(b.moveRobber(0, 0));
System.out.println(b.getResourceCardsEarned(5, joe));
System.out.println(b.getResourceCardsEarned(5, bob));
System.out.println(b.moveRobber(0, 0));
System.out.println(b.moveRobber(0, 0));
System.out.println(b.moveRobber(1, -1));
System.out.println(b.moveRobber(2, 0));
// System.out.println(b.whoHasLongestRoad());
System.out.println(b.addSettlement(new Coordinate(-2,1,3), joe, false, false));
// System.out.println(b.whoHasLongestRoad());
while (true) {
// Extract the coordinate of the node from the node name
int x = 0; int y = 0; int z = 0;
int start = 0;
int finish = 1;
String input = in.nextLine();
if (input.charAt(start) == '-') {
finish++;
}
x = Integer.parseInt(input.substring(start, finish));
start = finish;
finish = start + 1;
if (input.charAt(start) == '-') {
finish++;
}
y = Integer.parseInt(input.substring(start, finish));
z = Integer.parseInt(input.substring(finish,
input.length()));
// Add the node to the set of nodes
Coordinate coord = new Coordinate(x, y, z);
start = 0;
finish = 1;
input = in.nextLine();
if (input.charAt(start) == '-') {
finish++;
}
x = Integer.parseInt(input.substring(start, finish));
start = finish;
finish = start + 1;
if (input.charAt(start) == '-') {
finish++;
}
y = Integer.parseInt(input.substring(start, finish));
z = Integer.parseInt(input.substring(finish,
input.length()));
// Add the node to the set of nodes
Coordinate coord2 = new Coordinate(x, y, z);
System.out.printf("%s is adjacent to %s: ", coord, coord2);
System.out.printf("Normalized: %s %s\n", coord.normalizeCoordinate(), coord2.normalizeCoordinate());
Node test = b.nodeSet.get(coord.normalizeCoordinate());
System.out.println(test.isAdjacent(coord2.normalizeCoordinate()));
break;
}
in.close();
} /** End of Temporary Method!!!!*/
| 7 |
public void loadRoomConfig() throws BadConfigFormatException, FileNotFoundException {
// Creates a FileReader and then wraps it in a scanner to read the file
FileReader roomConfigFile = new FileReader(roomConfigFilename);
Scanner fileScanner = new Scanner(roomConfigFile);
String nextLine;
Character key;
// While there is still something in the file, process it
while(fileScanner.hasNext()) {
// Read in the next line
nextLine = fileScanner.nextLine();
// If there is either no comma or more than one comma, throw an exception
if(!nextLine.contains(",") || (nextLine.indexOf(',') != nextLine.lastIndexOf(',')))
throw new BadConfigFormatException(roomConfigFilename, "Incorrect number of comma seperators - less than one or more than one.");
key = nextLine.charAt(0);
// If the first character is not a letter, throw an exception
if(!(Character.isLetter(key)))
throw new BadConfigFormatException(roomConfigFilename, "Key was not a valid letter.");
// If it's passed the exception checks, write this to the room map
rooms.put(key, nextLine.substring((nextLine.indexOf(",")+1)).trim());
}
}
| 4 |
public void setData(Object data) {
if(data.getClass().isArray()){
if(!Array.get(data, 0).getClass().isArray()){
this.data = vectorToMatrix(data);
}else{
this.data = data;
}
}else{
if(data instanceof Byte){
this.data = new byte[][]{{(Byte)data}};
}
else if(data instanceof Short){
this.data = new short[][]{{(Short)data}};
}
else if(data instanceof Integer){
this.data = new int[][]{{(Integer)data}};
}
else if(data instanceof Long){
this.data = new long[][]{{(Long)data}};
}
else if(data instanceof Double){
this.data = new double[][]{{(Double)data}};
}
else if(data instanceof Float){
this.data = new float[][]{{(Float)data}};
}
}
}
| 8 |
public boolean exchangeCashPurse(String serverID, String assetID, String nymID, String oldPurse, ArrayList selectedTokens) throws InterruptedException {
Helpers.setObj(null);
System.out.println(" Cash Purse exchange starts, selectedTokens:" + selectedTokens);
String newPurse = processCashPurse(serverID, assetID, nymID, oldPurse, selectedTokens, nymID);
if (!Utility.VerifyStringVal(newPurse)) {
System.out.println("exchangeCashPurse: Before server OT_API_exchangePurse call, new Purse is empty.. returning false ");
return false;
}
// ------------------------
OTAPI_Func theRequest = new OTAPI_Func(OTAPI_Func.FT.EXCHANGE_CASH, serverID, nymID, assetID, newPurse);
String strResponse = OTAPI_Func.SendTransaction(theRequest, "EXCHANGE_CASH"); // <========================
if (!Utility.VerifyStringVal(strResponse))
{
System.out.println("IN exchangeCashPurse: OTAPI_Func.SendTransaction(() failed. (I give up.) ");
// -------------------
boolean importStatus = otapiJNI.OTAPI_Basic_Wallet_ImportPurse(serverID, assetID, nymID, newPurse);
System.out.println("Since failure in exchangeCashPurse, OT_API_Wallet_ImportPurse called, status of import:" + importStatus);
if (!importStatus) {
Helpers.setObj(newPurse);
}
return false;
}
// ---------------------------------------
System.out.println("exchangeCashPurse ends, status: success.");
return true;
}
| 3 |
public String errorMessage() throws Exception {
switch (errorCode) {
case OK:
throw new Exception("TILT: Should not get here.");
case UNEXPECTED_ARGUMENT:
return unexpectedArgumentMessage();
case MISSING_STRING:
return String.format("Could not find string parameter for -%c.",
errorArgumentId);
case INVALID_INTEGER:
return String.format("Argument -%c expects an integer but was '%s'.",
errorArgumentId, errorParameter);
case MISSING_INTEGER:
return String.format("Could not find integer parameter for -%c.",
errorArgumentId);
}
return "";
}
| 5 |
@Override
public void actionPerformed(ActionEvent e)
{
if(e.getSource() == clearAll)
{
clear();
}
else if(e.getSource() == save)
{
saveFile();
}
else if(e.getSource() == load)
{
loadFile();
}
else if(e.getSource() == step)
{
step();
}
else if(e.getSource() == run)
{
run();
}
else if(e.getSource() == quickRef)
{
displayReference();
}
}
| 6 |
public HashMap beep() throws Exception
{
ArrayList<Integer> answer = this.device.send(0x13, 1, new char[]{});
if (answer.size() == 0 || answer == null)
throw new Exception("Пустой ответ");
HashMap<String, Integer> result = new HashMap<String, Integer>();
result.put("result", answer.get(0));
if (answer.get(0) == Status.OK)
{
result.put("error_code", answer.get(4));
result.put("operator", answer.get(5));
}
return result;
}
| 3 |
public List<Conversation> getConversationList( int person_id, int page_size, int offset ){
if( !handler_cvs.initialize() || !handler_msg.initialize()
|| !handler_person.initialize() || !handler_group.initialize() ){
System.out.println( "ConversationServer : failed to initialize!" );
return null;
}
List<Conversation> list = handler_cvs.getConversationList( person_id, page_size, offset );
if( list == null || list.size() <= 0 ){
closeAll();
return null;
}
for( int i = 0; i < list.size(); i ++ ){
if( !getConversationInfo( list.get(i) ) ){
System.out.println( "ConversationServer : failed to get conversation " + list.get(i).cvs_id );
}
}
closeAll();
return list;
}
| 8 |
@Override
void replaceChild(@SuppressWarnings("unused") Node oldChild, @SuppressWarnings("unused") Node newChild)
{
// Replace child
if(this._avalie_ == oldChild)
{
setAvalie((PExpLogica) newChild);
return;
}
for(ListIterator<PEstrCaso> i = this._estrCaso_.listIterator(); i.hasNext();)
{
if(i.next() == oldChild)
{
if(newChild != null)
{
i.set((PEstrCaso) newChild);
newChild.parent(this);
oldChild.parent(null);
return;
}
i.remove();
oldChild.parent(null);
return;
}
}
for(ListIterator<PComando> i = this._senao_.listIterator(); i.hasNext();)
{
if(i.next() == oldChild)
{
if(newChild != null)
{
i.set((PComando) newChild);
newChild.parent(this);
oldChild.parent(null);
return;
}
i.remove();
oldChild.parent(null);
return;
}
}
throw new RuntimeException("Not a child.");
}
| 7 |
@Override
public void onEnable() {
getConfig().options().copyDefaults(true);
saveConfig();
gm = new GameManager(this);
lh = new LocationHandler(this);
tm = new TeamManager(this);
fm = new FlagManager(this);
sm = new ScoreManager(this);
sm.setupScoreboard();
sm.setRedCaptures(0);
sm.setBlueCaptures(0);
sm.updateScoreboard();
registerListeners(this, new AsyncPlayerChat(), new BlockListener(), new FoodLevelChange(),
new InventoryClick(), new PlayerDropItem(), new PlayerDeath(), new PlayerJoin(),
new PlayerQuit(), new EntityDamage(), new SignListener());
getLogger().info("CTF has been enabled!");
getServer().getScheduler().scheduleSyncRepeatingTask(this, new Runnable() {
@Override
public void run() {
if (fm.getRedFlagSpawn().getBlock().getType()!=Material.AIR) {
fm.getRedFlagSpawn().getWorld().playEffect(fm.getRedFlagSpawn(), Effect.MOBSPAWNER_FLAMES, 2004);
}
}
}, 0L, 10L);
getServer().getScheduler().scheduleSyncRepeatingTask(this, new Runnable() {
@Override
public void run() {
if (fm.getBlueFlagSpawn().getBlock().getType()!=Material.AIR) {
fm.getBlueFlagSpawn().getWorld().playEffect(fm.getBlueFlagSpawn(), Effect.MOBSPAWNER_FLAMES, 2004);
}
}
}, 0L, 10L);
getServer().getScheduler().scheduleSyncRepeatingTask(this, new Runnable() {
@Override
public void run() {
for (Player pl : getServer().getOnlinePlayers()) {
if (gm.isPlaying(pl)) {
if (fm.hasFlag(pl)) {
pl.getWorld().playEffect(pl.getLocation(), Effect.MOBSPAWNER_FLAMES, 2004);
}
}
}
}
}, 0L, 10L);
}
| 5 |
@Override public void reflect(State s) {
state = s;
if (s.gameOver()) {
// show end state, overlaid with scores and shit
JFrame f = new JFrame();
int[] players = s.players();
f.setLayout(new GridLayout(0, players.length));
// sigh. gridlayout insists on ltr, ttb child insertion
for (int y = 0; y < 3; y++) {
for (int handle: players) {
final PlayerState ps = s.playerState(handle);
Component c = null;
switch (y) {
case 0:
c = new JLabel(ps.name);
break;
case 1:
c = new JLabel(""+ps.finalScore());
break;
case 2:
JList l = new JList(ps.missions.toArray());
l.setCellRenderer(new ListCellRenderer() {
@Override public Component getListCellRendererComponent(JList l, Object o, int i,
boolean isSelected,
boolean hasFocus) {
Mission m = (Mission)o;
JLabel c = new JLabel(m.value+" "+m.source+" - "+m.destination);
c.setBackground(ps.missionCompleted(m)
? new java.awt.Color(0.5f, 0.5f, 1f)
: new java.awt.Color(1f, 0.5f, 0.5f));
c.setOpaque(true);
return c;
}
});
c = l;
break;
}
f.add(c);
}
}
f.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
f.pack();
f.setVisible(true);
} else {
players.reflect(s);
decks.reflect(s);
map.reflect(s);
missions.reflect(s);
hand.reflect(s);
}
}
| 7 |
public static void main(String[] args) throws Exception {
Collection<DataClip> clips = new LinkedList<DataClip>();
for(int i = 0; i < args.length; i++) {
if(args[i].equals("-b")) {
bufsize = Integer.parseInt(args[++i]);
} else {
DataClip c = new DataClip(new java.io.FileInputStream(args[i]));
clips.add(c);
}
}
for(DataClip c : clips)
play(c);
for(DataClip c : clips)
c.finwait();
}
| 4 |
@Test
public void testGetValue() {
Layer l = new Layer();
List<Double> weights = new ArrayList<Double>();
l.insertNeuron(new ConstantOneInputNeuron());
l.insertNeuron(new ConstantOneInputNeuron());
weights.add(1.0);
weights.add(1.0);
try {
FeedForwardNeuron neuron = new FeedForwardNeuron(l, weights);
neuron.preCalc();
assertEquals(neuron.getValue(), 1.0/(1.0+Math.exp(-2.0)), 1e-15 );
} catch (WeigthNumberNotMatchException e) {
fail("Previous layers neuron count and the number of the weights does not match");
}
}
| 1 |
private boolean zzRefill() throws java.io.IOException {
/* first: make room (if you can) */
if (zzStartRead > 0) {
System.arraycopy(zzBuffer, zzStartRead,
zzBuffer, 0,
zzEndRead-zzStartRead);
/* translate stored positions */
zzEndRead-= zzStartRead;
zzCurrentPos-= zzStartRead;
zzMarkedPos-= zzStartRead;
zzStartRead = 0;
}
/* is the buffer big enough? */
if (zzCurrentPos >= zzBuffer.length) {
/* if not: blow it up */
char newBuffer[] = new char[zzCurrentPos*2];
System.arraycopy(zzBuffer, 0, newBuffer, 0, zzBuffer.length);
zzBuffer = newBuffer;
}
/* finally: fill the buffer with new input */
int numRead = zzReader.read(zzBuffer, zzEndRead,
zzBuffer.length-zzEndRead);
if (numRead > 0) {
zzEndRead+= numRead;
return false;
}
// unlikely but not impossible: read 0 characters, but not at end of stream
if (numRead == 0) {
int c = zzReader.read();
if (c == -1) {
return true;
} else {
zzBuffer[zzEndRead++] = (char) c;
return false;
}
}
// numRead < 0
return true;
}
| 5 |
final private void createActiveLayer()
{
// DeferredByteArray3D statemap = fm.getStateMap();
int px_zero = 0, px_inside = 0, px_outside = 0;
int grey_zero = 0, grey_inside = 0;
final DeferredObjectArray3D<StateContainer.States> statemap = init_state.getForSparseField();
for (int x = 0; x < statemap.getXLength(); x++)
{
for (int y = 0; y < statemap.getYLength(); y++)
{
for (int z = 0; z < statemap.getZLength(); z++)
{
if (statemap.get(x, y, z) == StateContainer.States.ZERO )
{
state[x][y][z] = STATE_ZERO;
phi.set(x, y, z, 0);
final BandElement element = new BandElement(x, y, z, 0);
layers[ZERO_LAYER].add(element);
elementLUT.set(x, y, z, element);
px_zero++;
grey_zero += source.getPixel(x, y, z);
}
else if ( statemap.get(x, y, z) == StateContainer.States.INSIDE )
{
state[x][y][z] = INSIDE_FAR;
px_inside++;
grey_inside += source.getPixel(x, y, z);
}
else
{
state[x][y][z] = OUTSIDE_FAR;
px_outside++;
}
}
}
}
IJ.log("Initiated boundary pixels: " +px_zero+" ZERO, " +px_inside + " INSIDE, "+px_outside + " OUTSIDE");
if ( px_inside == 0 && px_zero == 0 ) {
invalid = true;
throw new IllegalArgumentException("Level Sets didn't get any starting shape - Aborting");
}
// TODO median would be better
if ( this.seed_greyvalue < 0 ) {
if (this.seed_grey_zero) {
this.seed_greyvalue = grey_zero / px_zero;
} else {
this.seed_greyvalue = grey_inside / px_zero;
}
IJ.log("Grey seed not set - setting to mean of ROI boundary = " + this.seed_greyvalue);
}
}
| 9 |
public void get_audio( byte[] output_buffer, int frames ) {
int output_idx, mix_idx, mix_end, count, amplitude;
output_idx = 0;
while( frames > 0 ) {
count = tick_length_samples - current_tick_samples;
if( count > frames ) {
count = frames;
}
mix_idx = current_tick_samples << 1;
mix_end = mix_idx + ( count << 1 ) - 1;
while( mix_idx <= mix_end ) {
amplitude = mixing_buffer[ mix_idx ];
if( amplitude > 32767 ) {
amplitude = 32767;
}
if( amplitude < -32768 ) {
amplitude = -32768;
}
output_buffer[ output_idx ] = ( byte ) ( amplitude >> 8 );
output_buffer[ output_idx + 1 ] = ( byte ) ( amplitude & 0xFF );
output_idx += 2;
mix_idx += 1;
}
current_tick_samples = mix_idx >> 1;
frames -= count;
if( frames > 0 ) {
next_tick();
mix_tick();
current_tick_samples = 0;
}
}
}
| 6 |
private static char [] zzUnpackCMap(String packed) {
char [] map = new char[0x10000];
int i = 0; /* index in packed string */
int j = 0; /* index in unpacked array */
while (i < 90) {
int count = packed.charAt(i++);
char value = packed.charAt(i++);
do map[j++] = value; while (--count > 0);
}
return map;
}
| 2 |
private void checkSpriteCollisions(ArrayList<ArrayList<Sprite>> spriteLists)
{
for (ArrayList<Sprite> spriteList : spriteLists)
{
int startIndex = spriteList.indexOf(this) + 1;
for (int i = startIndex; i < spriteList.size(); i++)
{
if (intersects(spriteList.get(i)))
{
resolveCollision(spriteList.get(i));
}
}
}
}
| 3 |
private JPanel createVerticalList( String[] strings, boolean decorate ){
JPanel list = new JPanel();
BoxLayout l = new BoxLayout( list, BoxLayout.Y_AXIS );
list.setLayout( l );
list.setAlignmentX( JPanel.RIGHT_ALIGNMENT );
for( String s : strings ){
// JLabel label = new JLabel( s );
//
// list.add( label );
if( decorate ){
JTextField field = new JTextField( s );
field.setEditable( false );
field.setColumns( 10 );
list.add( field );
} else {
JLabel label = new JLabel( s );
list.add( label );
}
}
if( decorate ){
// list.setBackground( Color.white );
// list.setBorder( BorderFactory.createEtchedBorder() );
}
return list;
}
| 3 |
public T read(Timestamp currentDateTime) throws IOException {
Deal deal = new Deal();
int type = dataInput.readUnsignedByte();
if ((type & DealFlags.DATE_TIME.getValue()) > 0) {
DataReader.readDateTime(dataInput, baseDateTime);
}
deal.setTime(currentDateTime);
if ((type & DealFlags.PRICE.getValue()) > 0) {
lastPrice = DataReader.readRelative(dataInput, basePrice) * stepPrice;
}
deal.setPrice(lastPrice);
if ((type & DealFlags.VOLUME.getValue()) > 0) {
lastVolume = DataReader.readPackInt(dataInput);
}
deal.setVolume(lastVolume);
int dealType = type & DealFlags.TYPE.getValue();
if (dealType == 2) {
deal.setType(DealType.SELL);
} else if (dealType == 1) {
deal.setType(DealType.BUY);
} else if (dealType == 0) {
deal.setType(DealType.UNKNOWN);
}
deal.setSymbol(symbol);
return (T) deal;
}
| 6 |
private static void login(BufferedReader br, ServiceInterface obj,
Scanner cs) throws IOException{
// TODO Auto-generated method stub
String str[] = new String[2];
for (int i = 0; i < 2; i++) {
str[i] = br.readLine();
}
if (obj.login(str[0], str[1])) {
System.out.println("Hello "+str[0]);
showMenu(br, obj, cs);
}
else {
System.out.println("Login failed.");
showMenu(br, obj, cs);
}
}
| 2 |
@Override
public void run(){
byte[] data = new byte[1024];
DatagramPacket packet = new DatagramPacket(data, data.length);
try {
socket.receive(packet);
} catch (IOException e) {
e.printStackTrace();
}
this.parsePacket(packet.getData(), packet.getAddress(), packet.getPort());
}
| 1 |
static String judge(String a,String b){
if(a.equals(b)){
return ACCEPTED;
}
a=a.replaceAll("[ \n\t]+","");
b=b.replaceAll("[ \n\t]+","");
if(a.equals(b)){
return PRESENTATION_ERROR;
}
return WRONG_ANSWER;
}
| 2 |
@After
public void tearDown() {
try
{
AqWsFactory.close(clientProxy);
}
catch(Exception ex)
{
fail("tearDown failed...");
}
}
| 1 |
@Test
public void testConstructNimMatrix_10Sticks() {
int numberOfSticks = 10;
int matrixSize = numberOfSticks + 1;
NimVertex[][] expectedMatrix = new NimVertex[matrixSize][matrixSize];
expectedMatrix[10][9] = new NimVertex(10,9);
expectedMatrix[9][2] = new NimVertex(9,2);
expectedMatrix[8][4] = new NimVertex(8,4);
expectedMatrix[8][2] = new NimVertex(8,2);
expectedMatrix[7][4] = new NimVertex(7,4);
expectedMatrix[7][2] = new NimVertex(7,2);
expectedMatrix[6][6] = new NimVertex(6,6);
expectedMatrix[6][4] = new NimVertex(6,4);
expectedMatrix[5][5] = new NimVertex(5,5);
expectedMatrix[7][6] = new NimVertex(7,6);
expectedMatrix[6][2] = new NimVertex(6,2);
expectedMatrix[5][4] = new NimVertex(5,4);
expectedMatrix[5][2] = new NimVertex(5,2);
expectedMatrix[4][4] = new NimVertex(4,4);
expectedMatrix[4][2] = new NimVertex(4,2);
expectedMatrix[3][3] = new NimVertex(3,3);
expectedMatrix[3][2] = new NimVertex(3,2);
expectedMatrix[2][2] = new NimVertex(2,2);
expectedMatrix[1][1] = new NimVertex(1,1);
expectedMatrix[0][0] = new NimVertex(0,0);
NimVertex[][] actualMatrix = NimAlgorithms.constructNimMatrix(numberOfSticks);
for (int i = 0; i < expectedMatrix.length; i++) {
for (int j = 0; j < expectedMatrix[i].length; j++) {
Vertex v = expectedMatrix[i][j];
Vertex w = actualMatrix[i][j];
if (v != null && w != null) {
assertTrue(v.equals(w));
} else if (v == null && w != null) {
fail("Matrices to not match");
} else if (v != null && w == null) {
fail("Matrices to not match");
}
}
}
}
| 8 |
private static void normalizeVariableContent(String varName) {
String value = Config.get(varName);
if (value != null && value.toLowerCase().endsWith(".zip")){
Config.set(varName, value.replaceFirst("\\.[Zz][Ii][Pp]$", ""));
}
}
| 2 |
public boolean assignSong(Song s) {
String path= s.getPath();
if(this.songMap.get(path) != null)
return false;
this.songMap.put(path, s);
return true;
}
| 1 |
@Override
public int hashCode() {
final int prime = 31;
int result = 1;
result = prime * result + ((country == null) ? 0 : country.hashCode());
result = prime * result + ((id == null) ? 0 : id.hashCode());
return result;
}
| 2 |
public User loginUser(User user){
try {
Socket loginSocket = new Socket(SERVER_ADDRESS_LOGIN, LOGIN_PORT);
loginSocket.setSoTimeout(TIMEOUT);
OutputStream outputStream = loginSocket.getOutputStream();
ObjectOutputStream objectOutputStream = new ObjectOutputStream(
outputStream);
objectOutputStream.writeObject("VERIFY_LOGIN");
objectOutputStream.writeObject(user);
objectOutputStream.flush();
InputStream inputStream = loginSocket.getInputStream();
ObjectInputStream objectInputStream = new ObjectInputStream(inputStream);
user = (User)objectInputStream.readObject();
loginSocket.close();
}catch (SocketException e){
new ErrorFrame("Login Server unreachable!");
} catch (SocketTimeoutException e){
new ErrorFrame("Connection timed out");
} catch (Exception e) {
e.printStackTrace();
new ErrorFrame("User verification failed!");
}
return user;
}
| 3 |
public void setPropertyElementType (Class type, String propertyName, Class elementType) {
if (type == null) throw new IllegalArgumentException("type cannot be null.");
if (propertyName == null) throw new IllegalArgumentException("propertyName cannot be null.");
if (elementType == null) throw new IllegalArgumentException("propertyType cannot be null.");
Property property = Beans.getProperty(type, propertyName, beanProperties, privateFields, this);
if (property == null)
throw new IllegalArgumentException("The class " + type.getName() + " does not have a property named: " + propertyName);
if (!Collection.class.isAssignableFrom(property.getType()) && !Map.class.isAssignableFrom(property.getType())) {
throw new IllegalArgumentException("The '" + propertyName + "' property on the " + type.getName()
+ " class must be a Collection or Map: " + property.getType());
}
propertyToElementType.put(property, elementType);
}
| 6 |
public void convertSolu(){
if (brute == false) {
for (int i = 0; i < this.soluList.size(); i++) {
ArrayList tmp = this.soluList.get(i);
HashMap<Integer, ArrayList<Unit>> solu = new HashMap<Integer, ArrayList<Unit>>();
for (int j = 0; j < tmp.size(); j++) {
ArrayList<Integer> rowY = mtrY.get(tmp.get(j));
ArrayList<Unit> tile = new ArrayList<Unit>();
int id = rowY.get(0);
for (int k = 1; k < rowY.size(); k++) {
int unitId = rowY.get(k) - this.tiles.length;
Unit unit = new Unit(this.board.pX[0][unitId],
this.board.pY[0][unitId],
this.board.pCh[0][unitId]);
tile.add(unit);
}
solu.put(id, tile);
}
this.soluInterface.add(solu);
}
}
else {
for (int i = 0; i < this.bruteForceSolu.size(); i++) {
HashMap<Integer, ArrayList<Unit>> solu = new HashMap<Integer, ArrayList<Unit>>();
for(int j = 0; j < this.tiles.length; j++ ) {
ArrayList<Unit> tile = new ArrayList<Unit>();
solu.put(j, tile);
}
for( int j = 0; j < bruteForceSolu.get(i).size(); j++ ) {
int id = bruteForceSolu.get(i).get(j)-1;
Unit unit = new Unit(this.board.pX[0][j], this.board.pY[0][j], this.board.pCh[0][j]);
solu.get(id).add(unit);
}
this.soluInterface.add(solu);
}
}
int index = 1;
}
| 7 |
public void getSoundsToPlay(int deltaTime){
if(!soundToggled)
return;
int lastTime = currentTime;
currentTime += deltaTime * scale;
//Check each time for sounds that should play this frame
for(int i = 0; i < times.size(); i++){
int time = times.get(i);
//If this index's time is between last frames time
//and now, add it to the sounds to be played
if(time >= lastTime && time < currentTime){
//Stuff happening
Integer key = keys.get(i);
AudioPlayer temp = min.loadFile(sounds.get(key));
temp.play();
}
}
//Set currentTime to the loop's beginning time
if(currentTime > endTime)
currentTime = beginTime;
}
| 5 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.