text stringlengths 14 410k | label int32 0 9 |
|---|---|
@Override
public void actionPerformed(ActionEvent ev)
{
String auxOpcion = ev.getActionCommand();
Agenda agenda = new Agenda();
switch(auxOpcion)
{
case "Cancelar":
this.dispose();
break;
case "Crear Contacto":
pAgenda.setVisible(false);
pModificarContacto.setVisible(false);
vCrearContacto();
break;
case "Modificar Contacto":
pAgenda.setVisible(false);
pCrearContacto.setVisible(false);
modBo = 1;
vModBorrarContacto();
break;
case "Borrar Contacto":
pAgenda.setVisible(false);
pModificarContacto.setVisible(false);
pCrearContacto.setVisible(false);
modBo = 2;
vModBorrarContacto();
break;
case "Buscar":
pModificarContacto.setVisible(false);
pCrearContacto.setVisible(false);
agenda(null);
break;
case "Aceptar":
if (this.idUsuario==null)
{
Personas usuario= new Usuarios
( tFUsuario.getText(),
tFContraseña.getText(),
tFNombre.getText(),
tFApellidos.getText(),
tFDireccion.getText(),
tFPoblacion.getText(),
tFProvincia.getText(),
tFNacionalidad.getText(),
tFEMail.getText(),
Integer.parseInt(tFTelefono.getText())
);
agenda.crearUsuario((Usuarios)usuario);
}else
{
Personas contacto= new Contactos
( this.idUsuario,
tFNombre.getText(),
tFApellidos.getText(),
tFDireccion.getText(),
tFPoblacion.getText(),
tFProvincia.getText(),
tFNacionalidad.getText(),
tFEMail.getText(),
Integer.parseInt(tFTelefono.getText())
);
agenda.crearContacto(contacto, idUsuario);
}
pCrearContacto.setVisible(false);
pCrearUsuario.setVisible(false);
agenda(idUsuario);
break;
}
} | 7 |
public static Stella_Object accessCheckTypesRecordSlotValue(CheckTypesRecord self, Symbol slotname, Stella_Object value, boolean setvalueP) {
if (slotname == Logic.SYM_LOGIC_PROPOSITION) {
if (setvalueP) {
self.proposition = ((Proposition)(value));
}
else {
value = self.proposition;
}
}
else if (slotname == Logic.SYM_LOGIC_PARENT_PROPOSITION) {
if (setvalueP) {
self.parentProposition = value;
}
else {
value = self.parentProposition;
}
}
else if (slotname == Logic.SYM_LOGIC_PARENT_DESCRIPTION) {
if (setvalueP) {
self.parentDescription = ((Description)(value));
}
else {
value = self.parentDescription;
}
}
else if (slotname == Logic.SYM_STELLA_MODULE) {
if (setvalueP) {
self.module = ((Module)(value));
}
else {
value = self.module;
}
}
else {
{ OutputStringStream stream000 = OutputStringStream.newOutputStringStream();
stream000.nativeStream.print("`" + slotname + "' is not a valid case option");
throw ((StellaException)(StellaException.newStellaException(stream000.theStringReader()).fillInStackTrace()));
}
}
return (value);
} | 8 |
private int parseArrayLength(String str){
int len;
String digits = "";
int i = 0;
while(i<str.length()-1){
do
i++;
while(str.charAt(i) != '[');
i++;
while (str.charAt(i) !=']'){
digits = digits+str.charAt(i++);
}
break;
}
try{
len = Integer.parseInt(digits);
}catch (NumberFormatException ex){
return -1;
}
return len;
} | 4 |
public void testForStyle_invalidStrings() {
try {
DateTimeFormat.forStyle("AA");
fail();
} catch (IllegalArgumentException ex) {}
try {
DateTimeFormat.forStyle("--");
fail();
} catch (IllegalArgumentException ex) {}
try {
DateTimeFormat.forStyle("ss");
fail();
} catch (IllegalArgumentException ex) {}
} | 3 |
@Override
public void e(float sideMot, float forMot) {
if (this.passenger == null || !(this.passenger instanceof EntityHuman)) {
super.e(sideMot, forMot);
this.W = 0.5F; // Make sure the entity can walk over half slabs,
// instead of jumping
return;
}
EntityHuman human = (EntityHuman) this.passenger;
if (!RideThaMob.control.contains(human.getBukkitEntity().getName())) {
// Same as before
super.e(sideMot, forMot);
this.W = 0.5F;
return;
}
this.lastYaw = this.yaw = this.passenger.yaw;
this.pitch = this.passenger.pitch * 0.5F;
// Set the entity's pitch, yaw, head rotation etc.
this.b(this.yaw, this.pitch); // https://github.com/Bukkit/mc-dev/blob/master/net/minecraft/server/Entity.java#L163-L166
this.aO = this.aM = this.yaw;
this.W = 1.0F; // The custom entity will now automatically climb up 1
// high blocks
sideMot = ((EntityLiving) this.passenger).bd * 0.5F;
forMot = ((EntityLiving) this.passenger).be;
if (forMot <= 0.0F) {
forMot *= 0.25F; // Make backwards slower
}
sideMot *= 0.75F; // Also make sideways slower
float speed = 0.35F; // 0.2 is the default entity speed. I made it
// slightly faster so that riding is better than
// walking
this.i(speed); // Apply the speed
super.e(sideMot, forMot); // Apply the motion to the entity
try {
Field jump = null;
jump = EntityLiving.class.getDeclaredField("bc");
jump.setAccessible(true);
if (jump != null && this.onGround) { // Wouldn't want it jumping
// while
// on the ground would we?
if (jump.getBoolean(this.passenger)) {
double jumpHeight = 0.5D;
this.motY = jumpHeight; // Used all the time in NMS for
// entity jumping
}
}
} catch (Exception e) {
e.printStackTrace();
}
} | 8 |
public static void solve(Maze m)
{
boolean filledDeadEnd = true;
do
{
filledDeadEnd = fillDeadEnd(m);
} while (filledDeadEnd);
for(int i = 0; i < m.width(); i++)
{
for(int j = 0; j < m.height(); j++)
{
if(m.get(i, j) == 0)
m.set(i, j, 3);
else if(m.get(i, j) == 2)
m.set(i, j, 0);
}
}
} | 5 |
public void removeValueChangeListener(ValueChangeListener l) {
if(l == null) {
return;
}
this.valueChangeListener = null;
} | 1 |
public static void changeFineBorrow(int memberID, int itemID, String item, int method) {
try {
//*********************************************************************************//
// INSTANCIAMOS UN OBJETO QUE NOS PERMITA ALMACENAR TODA LA INFORMACIÓN DE NUESTRO //
// FICHERO XML DE FORMA ODENADA //
//*********************************************************************************//
DocumentBuilderFactory docFactory = DocumentBuilderFactory.newInstance();
DocumentBuilder docBuilder = docFactory.newDocumentBuilder();
//*********************************************************************************//
// CARGAMOS EL FICHERO XML EN NUESTRO OBJETO //
//*********************************************************************************//
Document doc = docBuilder.parse(new File("db/DBmembers.xml"));
//*********************************************************************************//
// NORMALIZAMOS NUESTRO OBJETO PARA ELIMINAR NODOS VACIOS //
//*********************************************************************************//
doc.getDocumentElement().normalize();
int myItem = 0;
//*********************************************************************************//
// CARGAMOS LOS NODOS MIEMBRO PARA BUSCAR EL NODO QUE NOS INTERESA //
//*********************************************************************************//
NodeList memberNodes = doc.getElementsByTagName("member");
for (int i = 0; i < memberNodes.getLength(); i++) {
//*********************************************************************************//
// EL ELEMENTO QUE INSTANCIAMOS CONTIENE UN NODO INDIVIDUAL DE UN MIEMBRO //
//*********************************************************************************//
Element anElement = (Element) memberNodes.item(i);
//*********************************************************************************//
// COMPROBAMOS SI LA ID DE NUESTRO ELEMENTO ES LA QUE BUSCAMOS //
//*********************************************************************************//
if (Integer.parseInt(getNodeValue("id", anElement)) == memberID) {
myItem = i;
break;
}
}
//*********************************************************************************//
// CARGAMOS EL NODO ESPECÍFICO QUE ESTAMOS BUSCANDO //
//*********************************************************************************//
Node itemNode = doc.getElementsByTagName(item).item(myItem);
NodeList list = itemNode.getChildNodes();
String a = list.item(0).getNodeValue();
//*********************************************************************************//
// EDITAMOS EL CONTENIDO DEL NODO //
//*********************************************************************************//
switch (method) {
case 0://CASOS EN LOS QUE AÑADIMOS ALGO A LA BASE DE DATOS
if (a.equals("none")) {
list.item(0).setTextContent(Integer.toString(itemID));
} else {
a += "," + itemID;
list.item(0).setTextContent(a);
}
break;
case 1://CASOS EN LOS QUE ELIMINAMOS ALGO DE LA BASE DE DATOS
String finalNode;
String nodeVal = list.item(0).getTextContent();
int position = nodeVal.indexOf(item);
if (nodeVal.length() > 1) {
finalNode = nodeVal.substring(0, (position - 2));
finalNode += nodeVal.substring((position + 1), nodeVal.length());
} else {
finalNode = "none";
}
list.item(0).setTextContent(finalNode);
break;
default:
throw new AssertionError();
}
//*********************************************************************************//
// ESCRIBIMOS NUESTRO OBJETO CON LOS CAMBIOS DE NUEVO EN EL FICHERO XML //
//*********************************************************************************//
TransformerFactory transformerFactory = TransformerFactory.newInstance();
Transformer transformer = transformerFactory.newTransformer();
DOMSource source = new DOMSource(doc);
StreamResult result = new StreamResult(new File("db/DBmembers.xml"));
transformer.transform(source, result);
} catch (ParserConfigurationException | SAXException | IOException | NumberFormatException | DOMException | AssertionError | TransformerFactoryConfigurationError | TransformerException e) {
JOptionPane.showMessageDialog(null, e.getMessage(), "" + "Error", JOptionPane.ERROR_MESSAGE);
}
} | 7 |
public static void send(String msg)
{
for(ClientHandler c : clients)
c.send(msg.toUpperCase());
} | 1 |
public void createChartAd()
{
setPieChartAd(new PieChartModel());
setHost("root.intt.tn");
setPriority("emerg");
int emerg= getfacilityByHost().size();
if(emerg!=0)
pieChartAd.set("Emergency", emerg);
setPriority("Alert");
int alert= getfacilityByHost().size();
if(alert!=0)
pieChartAd.set("Alert",alert);
setPriority("crit");
int crit= getfacilityByHost().size();
if(crit!=0)
pieChartAd.set("Critical", crit);
setPriority("err");
int err= getfacilityByHost().size();
if(err!=0)
pieChartAd.set("error",err);
setPriority("warning");
int warning= getfacilityByHost().size();
if(warning!=0)
pieChartAd.set("Warning",warning);
setPriority("notice");
int notice= getfacilityByHost().size();
if(notice!=0)
pieChartAd.set("Notice",notice);
setPriority("info");
int info= getfacilityByHost().size();
if(info!=0)
pieChartAd.set("Information",info);
setPriority("debug");
int debug= getfacilityByHost().size();
if(debug!=0)
pieChartAd.set("Debug",debug);
} | 8 |
public void jump(){
if (this.state == Player.STATE_RUNNING || this.state == Player.STATE_STANDING){
this.speedY = -LivingEntity.JUMPFORCE;
this.state = Player.STATE_JUMPING;
}
} | 2 |
public static Tile[][] getEmptyWorld(int width, int height) {
Tile[][] tiles = new Tile[width][height];
for(int x = 0; x < tiles.length; x++) {
for(int y = 0; y < tiles[0].length; y++) {
tiles[x][y] = new Tile(new Position(x, y), 0);
}
}
return tiles;
} | 2 |
private void removeChar(int c) {
for (int i = 0; i < size / 2; i++) {
if (ranges[i * 2] <= c && ranges[i * 2 + 1] >= c) {
if (ranges[i * 2] == c) {
if (ranges[i * 2 + 1] == c) {
for (int j = i * 2 + 2; j < size; j++) { // shift left
ranges[j - 2] = ranges[j];
}
size -= 2;
} else {
ranges[i * 2] += 1;
}
} else {
if (ranges[i * 2 + 1] == c) {
ranges[i * 2 + 1] -= 1;
} else {
// split
insert(i * 2 + 1, c - 1, c + 1);
}
}
return;
}
}
} | 7 |
public void writeToFile(int file, String textLine, String t) throws IOException
{
String path;
if(t.equalsIgnoreCase("acc"))
{path = accDir+file+".txt";}
else
{ path = appDir+file+".txt";}
boolean append_to_file = true;
FileWriter write = new FileWriter(path, append_to_file);
PrintWriter print_line = new PrintWriter(write);
print_line.printf("%s%n", new Object[] { textLine });
print_line.close();
} | 1 |
* @param class2
* @return Stella_Class
*/
public static Stella_Class twoArgumentLeastCommonSuperclass(Stella_Class class1, Stella_Class class2) {
if (Stella_Class.subclassOfP(class1, class2)) {
return (class2);
}
if (Stella_Class.subclassOfP(class2, class1)) {
return (class1);
}
{ Stella_Class c = null;
Cons iter000 = class1.classAllSuperClasses;
for (;!(iter000 == Stella.NIL); iter000 = iter000.rest) {
c = ((Stella_Class)(iter000.value));
c.classMarkedP = false;
}
}
{ Stella_Class c = null;
Cons iter001 = class2.classAllSuperClasses;
for (;!(iter001 == Stella.NIL); iter001 = iter001.rest) {
c = ((Stella_Class)(iter001.value));
c.classMarkedP = true;
}
}
{ Stella_Class c = null;
Cons iter002 = class1.classAllSuperClasses;
for (;!(iter002 == Stella.NIL); iter002 = iter002.rest) {
c = ((Stella_Class)(iter002.value));
if (c.classMarkedP) {
return (c);
}
}
}
return (null);
} | 6 |
public Updater(Plugin plugin, int id, File file, UpdateType type, boolean announce) {
this.plugin = plugin;
this.type = type;
this.announce = announce;
this.file = file;
this.id = id;
this.updateFolder = plugin.getServer().getUpdateFolder();
final File pluginFile = plugin.getDataFolder().getParentFile();
final File updaterFile = new File(pluginFile, "Updater");
final File updaterConfigFile = new File(updaterFile, "config.yml");
if (!updaterFile.exists()) {
updaterFile.mkdir();
}
if (!updaterConfigFile.exists()) {
try {
updaterConfigFile.createNewFile();
} catch (final IOException e) {
plugin.getLogger().severe("The updater could not create a configuration in " + updaterFile.getAbsolutePath());
e.printStackTrace();
}
}
this.config = YamlConfiguration.loadConfiguration(updaterConfigFile);
this.config.options().header("This configuration file affects all plugins using the Updater system (version 2+ - http://forums.bukkit.org/threads/96681/ )" + '\n'
+ "If you wish to use your API key, read http://wiki.bukkit.org/ServerMods_API and place it below." + '\n'
+ "Some updating systems will not adhere to the disabled value, but these may be turned off in their plugin's configuration.");
this.config.addDefault("api-key", "PUT_API_KEY_HERE");
this.config.addDefault("disable", false);
if (this.config.get("api-key", null) == null) {
this.config.options().copyDefaults(true);
try {
this.config.save(updaterConfigFile);
} catch (final IOException e) {
plugin.getLogger().severe("The updater could not save the configuration in " + updaterFile.getAbsolutePath());
e.printStackTrace();
}
}
if (this.config.getBoolean("disable")) {
this.result = UpdateResult.DISABLED;
return;
}
String key = this.config.getString("api-key");
if (key.equalsIgnoreCase("PUT_API_KEY_HERE") || key.equals("")) {
key = null;
}
this.apiKey = key;
try {
this.url = new URL(Updater.HOST + Updater.QUERY + id);
} catch (final MalformedURLException e) {
plugin.getLogger().severe("The project ID provided for updating, " + id + " is invalid.");
this.result = UpdateResult.FAIL_BADID;
e.printStackTrace();
}
this.thread = new Thread(new UpdateRunnable());
this.thread.start();
} | 9 |
final public Iterator <K> iterator() {
final int height = heightFor(root) ;
final Node nodeStack[] = new Node[height + 1] ;
final Side sideStack[] = new Side[height + 1] ;
if (root != null) {
nodeStack[0] = root ;
sideStack[0] = Side.L ;
}
return new Iterator <K> () {
int level = root == null ? -1 : 0 ;
Node current = getNext() ;
Node getNext() {
while (level >= 0) {
final Node next = nodeStack[level] ;
final Side nextSide = sideStack[level] ;
if (nextSide == Side.L) {
sideStack[level] = Side.R ;
if (next.kidL != null) {
level++ ;
nodeStack[level] = next.kidL ;
sideStack[level] = Side.L ;
}
}
else if (nextSide == Side.R) {
sideStack[level] = Side.NEITHER ;
if (next.kidR != null) {
level++ ;
nodeStack[level] = next.kidR ;
sideStack[level] = Side.L ;
}
return next ;
}
else if (nextSide == Side.NEITHER) {
level-- ;
}
}
return null ;
}
public boolean hasNext() {
return current != null ;
}
public K next() {
final K returned = (K) current.value ;
current = getNext() ;
return returned ;
}
public void remove() {}
} ;
} | 8 |
public void test_add_RP_int_intarray_int() {
int[] values = new int[] {10, 20, 30, 40};
int[] expected = new int[] {10, 20, 30, 40};
BaseDateTimeField field = new MockStandardDateTimeField();
int[] result = field.add(new TimeOfDay(), 2, values, 0);
assertEquals(true, Arrays.equals(expected, result));
values = new int[] {10, 20, 30, 40};
expected = new int[] {10, 20, 31, 40};
result = field.add(new TimeOfDay(), 2, values, 1);
assertEquals(true, Arrays.equals(expected, result));
values = new int[] {10, 20, 30, 40};
expected = new int[] {10, 21, 0, 40};
result = field.add(new TimeOfDay(), 2, values, 30);
assertEquals(true, Arrays.equals(expected, result));
values = new int[] {23, 59, 30, 40};
try {
field.add(new TimeOfDay(), 2, values, 30);
fail();
} catch (IllegalArgumentException ex) {}
values = new int[] {10, 20, 30, 40};
expected = new int[] {10, 20, 29, 40};
result = field.add(new TimeOfDay(), 2, values, -1);
assertEquals(true, Arrays.equals(expected, result));
values = new int[] {10, 20, 30, 40};
expected = new int[] {10, 19, 59, 40};
result = field.add(new TimeOfDay(), 2, values, -31);
assertEquals(true, Arrays.equals(expected, result));
values = new int[] {0, 0, 30, 40};
try {
field.add(new TimeOfDay(), 2, values, -31);
fail();
} catch (IllegalArgumentException ex) {}
} | 2 |
private void drawArrow(Graphics g, int x1, int y1, int x2, int y2) {
if (x1 == x2 && y1 == y2) {
} else {
g.drawLine(x1, y1, x2, y2);
double directionCorrection = 1;
if (x2 > x1) {
directionCorrection = -1;
}
double alpha = Math.atan((double) (y2 - y1) / (double) (x2 - x1));
double theta1 = alpha + Math.PI / 8d;
double theta2 = alpha - Math.PI / 8d;
int r = (int) Math.ceil(0.5 * _fieldScaleFactor);
double linie1x = x2 + (r * Math.cos(theta1)) * directionCorrection;
double linie1y = y2 + (r * Math.sin(theta1)) * directionCorrection;
double linie2x = x2 + (r * Math.cos(theta2)) * directionCorrection;
double linie2y = y2 + (r * Math.sin(theta2)) * directionCorrection;
g.drawLine(x2, y2, (int) linie1x, (int) linie1y);
g.drawLine(x2, y2, (int) linie2x, (int) linie2y);
}
} | 3 |
public String getHouseNumber() {
return HouseNumber;
} | 0 |
private void getPixel() {
int i = 0;
for (int y = 0; y < imageHeight; y++) {
for (int x = 0; x < imageWidth; x++) {
pixel[i] = bufferedImage.getRGB(x, y);
i++;
}
}
} | 2 |
public void draw(GOut g) {
Widget next;
for (Widget wdg = child; wdg != null; wdg = next) {
next = wdg.next;
if (!wdg.visible || (!ui.root.visible && wdg.isui))
continue;
Coord cc = xlate(wdg.c, true);
wdg.draw(g.reclip(cc, wdg.sz));
}
} | 4 |
@Override
public boolean equals(Object obj) {
if (this == obj)
return true;
if (obj == null)
return false;
if (getClass() != obj.getClass())
return false;
VideoMDMetadata other = (VideoMDMetadata) obj;
if (videoMD == null) {
if (other.videoMD != null)
return false;
} else if (!videoMD.equals(other.videoMD))
return false;
if (videoSrc == null) {
if (other.videoSrc != null)
return false;
} else if (!videoSrc.equals(other.videoSrc))
return false;
return true;
} | 9 |
protected final void dccReceiveFile(File file, long address, int port, int size) {
throw new RuntimeException("dccReceiveFile is deprecated, please use sendFile");
} | 0 |
public boolean addComponentParts(World par1World, Random par2Random, StructureBoundingBox par3StructureBoundingBox)
{
this.fillWithBlocks(par1World, par3StructureBoundingBox, 0, 3, 0, 12, 4, 12, Block.netherBrick.blockID, Block.netherBrick.blockID, false);
this.fillWithBlocks(par1World, par3StructureBoundingBox, 0, 5, 0, 12, 13, 12, 0, 0, false);
this.fillWithBlocks(par1World, par3StructureBoundingBox, 0, 5, 0, 1, 12, 12, Block.netherBrick.blockID, Block.netherBrick.blockID, false);
this.fillWithBlocks(par1World, par3StructureBoundingBox, 11, 5, 0, 12, 12, 12, Block.netherBrick.blockID, Block.netherBrick.blockID, false);
this.fillWithBlocks(par1World, par3StructureBoundingBox, 2, 5, 11, 4, 12, 12, Block.netherBrick.blockID, Block.netherBrick.blockID, false);
this.fillWithBlocks(par1World, par3StructureBoundingBox, 8, 5, 11, 10, 12, 12, Block.netherBrick.blockID, Block.netherBrick.blockID, false);
this.fillWithBlocks(par1World, par3StructureBoundingBox, 5, 9, 11, 7, 12, 12, Block.netherBrick.blockID, Block.netherBrick.blockID, false);
this.fillWithBlocks(par1World, par3StructureBoundingBox, 2, 5, 0, 4, 12, 1, Block.netherBrick.blockID, Block.netherBrick.blockID, false);
this.fillWithBlocks(par1World, par3StructureBoundingBox, 8, 5, 0, 10, 12, 1, Block.netherBrick.blockID, Block.netherBrick.blockID, false);
this.fillWithBlocks(par1World, par3StructureBoundingBox, 5, 9, 0, 7, 12, 1, Block.netherBrick.blockID, Block.netherBrick.blockID, false);
this.fillWithBlocks(par1World, par3StructureBoundingBox, 2, 11, 2, 10, 12, 10, Block.netherBrick.blockID, Block.netherBrick.blockID, false);
this.fillWithBlocks(par1World, par3StructureBoundingBox, 5, 8, 0, 7, 8, 0, Block.netherFence.blockID, Block.netherFence.blockID, false);
int var4;
for (var4 = 1; var4 <= 11; var4 += 2)
{
this.fillWithBlocks(par1World, par3StructureBoundingBox, var4, 10, 0, var4, 11, 0, Block.netherFence.blockID, Block.netherFence.blockID, false);
this.fillWithBlocks(par1World, par3StructureBoundingBox, var4, 10, 12, var4, 11, 12, Block.netherFence.blockID, Block.netherFence.blockID, false);
this.fillWithBlocks(par1World, par3StructureBoundingBox, 0, 10, var4, 0, 11, var4, Block.netherFence.blockID, Block.netherFence.blockID, false);
this.fillWithBlocks(par1World, par3StructureBoundingBox, 12, 10, var4, 12, 11, var4, Block.netherFence.blockID, Block.netherFence.blockID, false);
this.placeBlockAtCurrentPosition(par1World, Block.netherBrick.blockID, 0, var4, 13, 0, par3StructureBoundingBox);
this.placeBlockAtCurrentPosition(par1World, Block.netherBrick.blockID, 0, var4, 13, 12, par3StructureBoundingBox);
this.placeBlockAtCurrentPosition(par1World, Block.netherBrick.blockID, 0, 0, 13, var4, par3StructureBoundingBox);
this.placeBlockAtCurrentPosition(par1World, Block.netherBrick.blockID, 0, 12, 13, var4, par3StructureBoundingBox);
this.placeBlockAtCurrentPosition(par1World, Block.netherFence.blockID, 0, var4 + 1, 13, 0, par3StructureBoundingBox);
this.placeBlockAtCurrentPosition(par1World, Block.netherFence.blockID, 0, var4 + 1, 13, 12, par3StructureBoundingBox);
this.placeBlockAtCurrentPosition(par1World, Block.netherFence.blockID, 0, 0, 13, var4 + 1, par3StructureBoundingBox);
this.placeBlockAtCurrentPosition(par1World, Block.netherFence.blockID, 0, 12, 13, var4 + 1, par3StructureBoundingBox);
}
this.placeBlockAtCurrentPosition(par1World, Block.netherFence.blockID, 0, 0, 13, 0, par3StructureBoundingBox);
this.placeBlockAtCurrentPosition(par1World, Block.netherFence.blockID, 0, 0, 13, 12, par3StructureBoundingBox);
this.placeBlockAtCurrentPosition(par1World, Block.netherFence.blockID, 0, 0, 13, 0, par3StructureBoundingBox);
this.placeBlockAtCurrentPosition(par1World, Block.netherFence.blockID, 0, 12, 13, 0, par3StructureBoundingBox);
for (var4 = 3; var4 <= 9; var4 += 2)
{
this.fillWithBlocks(par1World, par3StructureBoundingBox, 1, 7, var4, 1, 8, var4, Block.netherFence.blockID, Block.netherFence.blockID, false);
this.fillWithBlocks(par1World, par3StructureBoundingBox, 11, 7, var4, 11, 8, var4, Block.netherFence.blockID, Block.netherFence.blockID, false);
}
this.fillWithBlocks(par1World, par3StructureBoundingBox, 4, 2, 0, 8, 2, 12, Block.netherBrick.blockID, Block.netherBrick.blockID, false);
this.fillWithBlocks(par1World, par3StructureBoundingBox, 0, 2, 4, 12, 2, 8, Block.netherBrick.blockID, Block.netherBrick.blockID, false);
this.fillWithBlocks(par1World, par3StructureBoundingBox, 4, 0, 0, 8, 1, 3, Block.netherBrick.blockID, Block.netherBrick.blockID, false);
this.fillWithBlocks(par1World, par3StructureBoundingBox, 4, 0, 9, 8, 1, 12, Block.netherBrick.blockID, Block.netherBrick.blockID, false);
this.fillWithBlocks(par1World, par3StructureBoundingBox, 0, 0, 4, 3, 1, 8, Block.netherBrick.blockID, Block.netherBrick.blockID, false);
this.fillWithBlocks(par1World, par3StructureBoundingBox, 9, 0, 4, 12, 1, 8, Block.netherBrick.blockID, Block.netherBrick.blockID, false);
int var5;
for (var4 = 4; var4 <= 8; ++var4)
{
for (var5 = 0; var5 <= 2; ++var5)
{
this.fillCurrentPositionBlocksDownwards(par1World, Block.netherBrick.blockID, 0, var4, -1, var5, par3StructureBoundingBox);
this.fillCurrentPositionBlocksDownwards(par1World, Block.netherBrick.blockID, 0, var4, -1, 12 - var5, par3StructureBoundingBox);
}
}
for (var4 = 0; var4 <= 2; ++var4)
{
for (var5 = 4; var5 <= 8; ++var5)
{
this.fillCurrentPositionBlocksDownwards(par1World, Block.netherBrick.blockID, 0, var4, -1, var5, par3StructureBoundingBox);
this.fillCurrentPositionBlocksDownwards(par1World, Block.netherBrick.blockID, 0, 12 - var4, -1, var5, par3StructureBoundingBox);
}
}
this.fillWithBlocks(par1World, par3StructureBoundingBox, 5, 5, 5, 7, 5, 7, Block.netherBrick.blockID, Block.netherBrick.blockID, false);
this.fillWithBlocks(par1World, par3StructureBoundingBox, 6, 1, 6, 6, 4, 6, 0, 0, false);
this.placeBlockAtCurrentPosition(par1World, Block.netherBrick.blockID, 0, 6, 0, 6, par3StructureBoundingBox);
this.placeBlockAtCurrentPosition(par1World, Block.lavaMoving.blockID, 0, 6, 5, 6, par3StructureBoundingBox);
var4 = this.getXWithOffset(6, 6);
var5 = this.getYWithOffset(5);
int var6 = this.getZWithOffset(6, 6);
if (par3StructureBoundingBox.isVecInside(var4, var5, var6))
{
par1World.scheduledUpdatesAreImmediate = true;
Block.blocksList[Block.lavaMoving.blockID].updateTick(par1World, var4, var5, var6, par2Random);
par1World.scheduledUpdatesAreImmediate = false;
}
return true;
} | 7 |
@Override
public void rightThumb(boolean pressed) {
if(enabled) {
if(ses2 != null) {
setFlagsFalse();
if(future != null) {
future.cancel(true);
}
}
if(pressed == true) {
r5Flag = true;
dllProc.dll_keyPressed(container.xgetCurrentPreset().xgetR5AssignedKeyCode());
if(container.xgetCurrentPreset().isR5repetitionEnabled()) {
keyTask = new KeyboardTask();
future = ses2.scheduleAtFixedRate
(keyTask, container.xgetCurrentPreset().xgetR5InitialDelay(), container.xgetCurrentPreset().xgetR5RepeatDelay(), TimeUnit.MILLISECONDS);
}
} else if(pressed == false) {
r5Flag = false;
if(ses2!=null) {
if(future != null) {
future.cancel(true);
}
}
dllProc.dll_keyRealesed(container.xgetCurrentPreset().xgetR5AssignedKeyCode());
}
} else {
if(future != null) {
future.cancel(true);
}
dllProc.dll_keyRealesed(container.xgetCurrentPreset().xgetR5AssignedKeyCode());
}
} | 9 |
public static void pause() {
// Pause the game to make it look like they are taking turns
try {
Thread.sleep(speed);
} catch (InterruptedException e1) {
e1.printStackTrace();
}
} | 1 |
public double rawAverageCorrelationCoefficientsWithTotals(){
if(!this.dataPreprocessed)this.preprocessData();
if(!this.covariancesCalculated)this.covariancesAndCorrelationCoefficients();
return this.rawMeanRhoWithTotals;
} | 2 |
public CellSimProgramReader(File input) throws IOException, ClassNotFoundException {
DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
DocumentBuilder builder=null;
Document document=null;
try {
builder = factory.newDocumentBuilder();
document = builder.parse(new FileInputStream(input));
}
catch (ParserConfigurationException pce) {
System.out.println("ParserConfiguration-Exception:"+pce);
}
catch (SAXException saxe) {
System.out.println("SAX-Exception: "+saxe);
}
catch (IOException ioex) {
System.out.println("IO-Exception: " +ioex);
}
Element root = document.getDocumentElement();
NodeList children=root.getChildNodes();
for (int i = 0; i < children.getLength(); i++) {
Node child = children.item(i);
if (child instanceof Element) {
Element childElement = (Element)child;
if (childElement.getTagName().equals("Geometry")) {
parseGeometry(childElement);
}
else if (childElement.getTagName().equals("Boundary")) {
parseBoundary(childElement);
}
else if (childElement.getTagName().equals("State")) {
parseState(childElement);
}
else if (childElement.getTagName().equals("Init")) {
parseInit(childElement);
}
}
}
} | 9 |
private int[] get_most_relevant() {
ArrayList<Integer> holder = new ArrayList<Integer>();
int min = (notes.size() < 4 ? notes.size() : 4);
int counter = 0;
sort_notes();
while (holder.size() < min) {
if(notes.size() == counter) break;
int note = notes.get(counter) % 12;
if (!holder.contains(note)) holder.add(note);
counter++;
}
int[]chord = new int[holder.size()];
for (int i = 0; i < holder.size(); i++) chord[i] = holder.get(i);
return chord;
} | 5 |
public static String getPrefix(IrcUser u)
{
System.out.println("getprefix");//debug
for(String s : Prefixes)
{
System.out.println("prefixindb - " + s);//
String[] split = s.split(" ");
if(u.getSource().equalsIgnoreCase(split[0])) return split[1].replaceAll("&", "§");
else{//debug
System.out.println("getprefix - no match");
System.out.println(s);
System.out.println(u.getSource());
}
}
return DefaultPrefix.replaceAll("&", "§");
} | 2 |
@Override
public void draw(Object obj, Component comp, Graphics2D g2) {
Color color;
if (obj == null) {
color = null;
} else {
color = (Color) getProperty(obj, "color");
}
String imageSuffix = (String) getProperty(obj, "imageSuffix");
if (imageSuffix == null) {
imageSuffix = "";
}
// Compose image with color using an image filter.
Image tinted = tintedVersions.get(color + imageSuffix);
if (tinted == null) // not cached, need new filter for color
{
Image untinted = tintedVersions.get(imageSuffix);
if (untinted == null) // not cached, need to fetch
{
try {
URL url = cl.getClassLoader().getResource(imageFilename + imageSuffix + imageExtension);
if (url == null) {
throw new FileNotFoundException(imageFilename + imageSuffix + imageExtension + " not found.");
}
untinted = ImageIO.read(url);
tintedVersions.put(imageSuffix, untinted);
} catch (IOException ex) {
untinted = tintedVersions.get("");
}
}
if (color == null) {
tinted = untinted;
} else {
FilteredImageSource src = new FilteredImageSource(untinted.getSource(), new TintFilter(color));
tinted = comp.createImage(src);
// Cache tinted image in map by color, we're likely to need it
// again.
tintedVersions.put(color + imageSuffix, tinted);
}
}
int width = tinted.getWidth(null);
int height = tinted.getHeight(null);
int size = Math.max(width, height);
// Scale to shrink or enlarge the image to fit the size 1x1 cell.
g2.scale(1.0 / size, 1.0 / size);
g2.clip(new Rectangle(-width / 2, -height / 2, width, height));
g2.drawImage(tinted, -width / 2, -height / 2, null);
} | 7 |
public static void doWithMethods(Class<?> clazz, MethodCallback mc, MethodFilter mf) throws Exception {
// Keep backing up the inheritance hierarchy.
Method[] methods = clazz.getDeclaredMethods();
for (Method method : methods) {
if (mf != null && !mf.matches(method)) {
continue;
}
try {
mc.doWith(method);
} catch (IllegalAccessException ex) {
throw new IllegalStateException("非法访问方法'" + method.getName() + "':" + ex);
}
}
if (clazz.getSuperclass() != null) {
doWithMethods(clazz.getSuperclass(), mc, mf);
} else if (clazz.isInterface()) {
for (Class<?> superIfc : clazz.getInterfaces()) {
doWithMethods(superIfc, mc, mf);
}
}
} | 9 |
protected boolean[] incrementingEquality(AttrTypes attrTypes,
int classType) {
print("incremental training produces the same results"
+ " as batch training");
printAttributeSummary(attrTypes, classType);
print("...");
int numTrain = getNumInstances(), numTest = getNumInstances(),
numClasses = 2, missingLevel = 0;
boolean attributeMissing = false, classMissing = false;
boolean[] result = new boolean[2];
Instances train = null;
Estimator [] estimators = null;
boolean built = false;
int attrIndex = 0;
Vector test;
try {
train = makeTestDataset(42, numTrain, 1, attrTypes,
numClasses,
classType
);
// prepare training data set and test value list
test = makeTestValueList(24, numTest, train, attrIndex,
attrTypes.getSetType());
if (missingLevel > 0) {
addMissing(train, missingLevel, attributeMissing, classMissing, attrIndex);
}
estimators = Estimator.makeCopies(getEstimator(), 2);
estimators[0].addValues(train, attrIndex);
} catch (Exception ex) {
throw new Error("Error setting up for tests: " + ex.getMessage());
}
try {
for (int i = 0; i < train.numInstances(); i++) {
((IncrementalEstimator)estimators[1]).addValue(train.instance(i).value(attrIndex), 1.0);
}
built = true;
if (!estimators[0].equals(estimators[1])) {
println("no");
result[0] = false;
if (m_Debug) {
println("\n=== Full Report ===");
println("Results differ between batch and "
+ "incrementally built models.\n"
+ "Depending on the estimator, this may be OK");
println("Here are the results:\n");
println("batch built results\n" + estimators[0].toString());
println("incrementally built results\n" + estimators[1].toString());
println("Here are the datasets:\n");
println("=== Train Dataset ===\n"
+ train.toString() + "\n");
println("=== Test Dataset ===\n"
+ test.toString() + "\n\n");
}
}
else {
println("yes");
result[0] = true;
}
} catch (Exception ex) {
result[0] = false;
print("Problem during");
if (built)
print(" testing");
else
print(" training");
println(": " + ex.getMessage() + "\n");
}
return result;
} | 7 |
public static WUGraph minSpanTree(WUGraph g){
// 1: Create new graph t having the same vertices as G, but no edges yet.
WUGraph t = new WUGraph();
for (Object item : g.getVertices()) {
t.addVertex(item);
}
// 2: Make a list of all edges in G by calling multiple times getNeighbors()
Object[] verticesList = t.getVertices();
LinkedQueue queue = new LinkedQueue();
for(int i = 0; i < t.vertexCount(); i++){
Neighbors neighbor = g.getNeighbors(verticesList[i]);
for (int j = 0; j < neighbor.neighborList.length; j++){
Object v1 = verticesList[i];
Object v2 = neighbor.neighborList[j];
int w = g.weight(v1, v2);
Edge edge = new Edge(v1, v2, w);
queue.enqueue(edge);
}
}
// 3: Sort the edges by weight in O(E*log(E)) time
mergeSort(queue);
// 4: Finally, find the edges of the minimun spanning tree t using disjoint sets.
int queueSize = queue.size();
DisjointSets ds = new DisjointSets(t.vertexCount());
HashTableChained hashTable = new HashTableChained(t.vertexCount());
//Insert the vertices in the hashtable. The hashCode will be its position in
// the verticesList list.
int index = 0;
for (Object v : verticesList){
hashTable.insert(v, index);
index++;
}
//Iterate over the edges in the queue, adding them if the vertices of the edge
// belong to different sets
for (int i = 0; i < queueSize; i++){
try{
Edge ed = (Edge) queue.dequeue();
Object vertex1 = ed.getVertex1();
Object vertex2 = ed.getVertex2();
int v1 = (Integer) hashTable.find(vertex1).value();
int v2 = (Integer) hashTable.find(vertex2).value();
if (ds.find(v1) == ds.find(v2)){
} else {
t.addEdge(ed.getVertex1(), ed.getVertex2(), ed.getWeight());
ds.union(ds.find(v1),ds.find(v2));
}
} catch (QueueEmptyException e){}
}
return t;
} | 7 |
@Override
public void greeting(Context ctx) {
System.out.println("Good Morning! " + LoggerUtils.getSig());
ctx.setState(new ConcreteState_Daytime());
} | 0 |
private boolean checkValidDetectiveTickets(boolean check, Detective player,
MrX mrXPlayer, TicketType ticketType) {
if (ticketType == TicketType.Bus && player.bus.size() > 0) {
player.bus.remove(player.bus.size() - 1);
mrXPlayer.bus.add(ticketType);
player.used.add(ticketType);
} else if (ticketType == TicketType.Taxi && player.taxi.size() > 0) {
player.taxi.remove(player.taxi.size() - 1);
mrXPlayer.taxi.add(ticketType);
player.used.add(ticketType);
} else if (ticketType == TicketType.Underground
&& player.tube.size() > 0) {
player.tube.remove(player.tube.size() - 1);
mrXPlayer.tube.add(ticketType);
player.used.add(ticketType);
}
// otherwise check is set to false
else {
check = false;
}
return check;
} | 6 |
private void saveTree(List<Component> roots, Map<String, Object> stateMap) {
List<Component> allChildren = new ArrayList<Component>();
for (Component root : roots) {
if (root != null) {
PropertySupport p = getProperty(root);
if (p != null) {
String pathname = getComponentPathname(root);
if (pathname != null) {
Object state = p.getSessionState(root);
if (state != null) {
stateMap.put(pathname, state);
}
}
}
}
if (root instanceof Container) {
Component[] children = ((Container) root).getComponents();
if ((children != null) && (children.length > 0)) {
Collections.addAll(allChildren, children);
}
}
}
if (allChildren.size() > 0) {
saveTree(allChildren, stateMap);
}
} | 9 |
public void init() throws IOException {
Configuration mc = new Configuration();
mc.set("fs.default.name", "hdfs://192.168.178.40:9000");
this.fs = FileSystem.get(mc);
System.setProperty("HADOOP_HOME", hadoopContext.getHome());
System.setProperty("HADOOP_USER_NAME", hadoopContext.getUser());
} | 0 |
public void render(){
BufferStrategy bs = getBufferStrategy();
if(bs == null){ createBufferStrategy(2); return; }
Graphics g = bs.getDrawGraphics();
{
LinkedList<Tile> renderTiles = TileManager.getImportantTiles();
for(int i = 0; i < renderTiles.size(); i++){
Tile tile = renderTiles.get(i);
g.drawImage(tile.getTileImage(), tile.tileX, tile.tileY, 32, 32, null, null);
}
}
g.dispose();
bs.show();
} | 2 |
public Stack<Labyrinth> launch(String file) {
Stack<Labyrinth> labyStack = new Stack<Labyrinth>();
try (
FileInputStream fInputStream = new FileInputStream(new File(file));
ZipInputStream zInputStream = new ZipInputStream(fInputStream);
) {
while (zInputStream.getNextEntry() != null) {
ObjectInputStream oisCompressed = new ObjectInputStream(zInputStream);
Labyrinth compressedLaby = (Labyrinth) oisCompressed.readObject();
compressedLaby.resolve();
labyStack.push(compressedLaby);
}
} catch (FileNotFoundException e) {
System.out.println("File not found !");
} catch (StreamCorruptedException e) {
System.out.println("Corrupted file !");
} catch (Exception e) {
System.out.println("Unknown error !");
}
return labyStack;
} | 4 |
public static ArrayList<bAssistecConsulta> getSintomas(
// String arg_prod,
// String cod_comp,
String arg_serial // String arg_dt1,
// String arg_dt2
) throws SQLException, ClassNotFoundException {
ResultSet rs;
ArrayList<bAssistecConsulta> sts = new ArrayList<bAssistecConsulta>();
Connection conPol = conMgr.getConnection("PD");
if (conPol == null) {
throw new SQLException("Numero Maximo de Conexoes Atingida!");
}
String sql = " SELECT "
+ " tb_assis_tec.*, "
+ " tb_tp_defeito.str_defeito, "
+ " tb_sintoma.str_sintoma, "
+ " tb_assistec_rep.*, "
+ " tb_operador.str_nome"
+ " FROM "
+ " tb_assis_tec, "
+ " tb_assistec_rep, "
+ " tb_operador, "
+ " tb_tp_defeito, "
+ " tb_sintoma"
+ " WHERE "
+ " tb_assis_tec.cod_assistec = tb_assistec_rep.cod_assistec AND"
+ " tb_assistec_rep.cod_tp_defeito = tb_tp_defeito.cod_tp_defeito AND"
+ " tb_operador.cod_cr = tb_assis_tec.cod_cr AND"
+ " tb_sintoma.cod_sintoma = tb_assistec_rep.cod_sintoma AND"
// + " cod_prod like ? AND "
// + " upper(cod_comp) like ? AND "
+ " upper(serial) like ? ;";//AND "
// + " datah BETWEEN TO_timestamp('" + arg_dt1 + "','DD/MM/YYYY HH24:MI:SS') AND TO_timestamp('" + arg_dt2 + "','DD/MM/YYYY HH24:MI:SS');";
try {
call = conPol.prepareCall(sql);
// call.setString(1, arg_prod + "%");
// call.setString(2, cod_comp.toUpperCase() + "%");
call.setString(1, arg_serial.toUpperCase() + "%");
rs = call.executeQuery();
while (rs.next()) {
bAssistecConsulta bObj = new bAssistecConsulta();
bObj.setCod_prod(rs.getString("cod_prod"));
bObj.setCod_deposito(rs.getInt("cod_deposito"));
bObj.setOp_num(rs.getInt("op_num"));
bObj.setCod_tp_defeito(rs.getInt("cod_tp_defeito"));
bObj.setSerial(rs.getString("serial"));
bObj.setStr_tp_defeito(rs.getString("str_defeito"));
bObj.setStr_sintoma(rs.getString("str_sintoma"));
bObj.setTipo_montagem(rs.getString("tipo_montagem").charAt(0));
bObj.setCod_comp(rs.getString("cod_comp"));
bObj.setPos_comp(rs.getInt("pos_comp"));
bObj.setDatahora(rs.getTimestamp("datareg"));
bObj.setObs(rs.getString("obs"));
bObj.setStr_cr_operador(rs.getString("str_nome"));
bObj.setStr_compo(rs.getString("str_compo"));
bObj.setStr_sa(rs.getString("str_sa"));
sts.add(bObj);
}
call.close();
} finally {
if (conPol != null) {
conMgr.freeConnection("PD", conPol);
}
}
return sts;
} | 3 |
public void escribirArchivo(String nombre, ArrayList<String> datos) {
try {
FileWriter fw = new FileWriter("./Data/" + nombre + ".o");
PrintWriter pw = new PrintWriter(fw);
for(int i=0; i<datos.size(); ++i){
pw.println(datos.get(i));
}
fw.close();
} catch (FileNotFoundException ex) {
crearArchivo(nombre);
} catch (IOException ex) {
System.out.println("\nDATA CORRUPTED!!!");
System.out.println(ex.getMessage() + "\n");
}
} | 3 |
public Object get(int index) throws JSONException {
Object object = this.opt(index);
if (object == null) {
throw new JSONException("JSONArray[" + index + "] not found.");
}
return object;
} | 1 |
public Boolean UploadFileAsync(String fileName, String description) throws Exception {
File fileToUpload = new File(fileName);
Date startTime = new Date();
if (fileToUpload.exists()) {
System.out.println("Uploading file " + fileToUpload.getName() + " (" + AppCache.getFileSizeString(fileToUpload.length()) + ")");
System.out.println("Please wait...");
InputStream is = new FileInputStream(fileToUpload);
byte[] body = new byte[(int) fileToUpload.length()];
is.read(body);
// Send request.
UploadArchiveRequest request = new UploadArchiveRequest()
.withVaultName(vaultName)
.withArchiveDescription(description)
.withChecksum(TreeHashGenerator.calculateTreeHash(new File(fileName)))
.withBody(new ByteArrayInputStream(body))
.withContentLength((long)body.length);
Future<UploadArchiveResult> result = AppCache.getAsyncClient().uploadArchiveAsync(request);
while(!result.isDone()) {
System.out.println("Uploading...");
Thread.sleep(2000);
}
if (result.get()!=null) {
return true;
} else {
return false;
}
} else {
throw new Exception("File not found!");
}
} | 3 |
void setAcceleration(float ax, float ay, float az) {
this.acceleration.set(ax, ay, az);
} | 0 |
@Override
public void run() {
int totalConsumedByThisConsumer = 0;
try {
while (true) {
Integer item = warehouse.retreiveItem();
if (item == null) {
// nothing to consume. warehouse is empty. Too slow producer or producer is dead
if (Producer.getNumberOfActiveProducers() <= 0) {
break; // no active producers. Let's finish this consumer
}
} else {
// We consumed successfully a item
totalConsumedByThisConsumer++;
System.out.println("Consumer '" + name + "' consume <<< " + item);
}
Thread.sleep(rnd.nextInt(50));
}
} catch (InterruptedException ex) {
System.out.println("Consumer '" + name + "' process killed");
}
// Print statistics
System.out.println("### Consumer '" + name + "' consumed " + totalConsumedByThisConsumer + " items");
} | 4 |
private PickVO getList13PVO(PickVO pvo, ArrayList<LineAnaVO> list13) {
if (list13.size() == 3) {
LineAnaVO v = getGap(3, list13);
if (v != null) {
pvo.add(v.getBnu());
}
v = getGap(2, list13);
if (v != null) {
pvo.add(v.getBnu());
}
} else if (list13.size() == 2) {
LineAnaVO v = getGap(3, list13);
if (v != null) {
pvo.add(v.getBnu());
} else {
v = getGap(1, list13);
if (v != null) {
pvo.add(v.getBnu());
} else {
v = getGap(2, list13);
if (v != null) {
pvo.add(v.getBnu());
}
}
}
} else if (list13.size() == 1) {
LineAnaVO v = getGap(1, list13);
if (v != null) {
pvo.add(v.getBnu());
}
}
return pvo;
} | 9 |
protected void redirectToLoginPage(HttpServletRequest request, HttpServletResponse response,
List<Pair<String, String>> queryParams) {
try {
StringBuilder pathBuilder = new StringBuilder();
pathBuilder.append(request.getContextPath());
pathBuilder.append("/");
pathBuilder.append(loginPage);
URLBuilder urlBuilder = new URLBuilder();
urlBuilder.setScheme(request.getScheme());
urlBuilder.setHost(request.getServerName());
urlBuilder.setPort(request.getServerPort());
urlBuilder.setPath(pathBuilder.toString());
if (queryParams == null) {
queryParams = new ArrayList<Pair<String, String>>();
}
queryParams.add(new Pair<String, String>("actionUrl", request.getContextPath()
+ request.getServletPath()));
urlBuilder.getQueryParams().addAll(queryParams);
log.debug("Redirecting to login page {}", urlBuilder.buildURL());
response.sendRedirect(urlBuilder.buildURL());
return;
} catch (IOException ex) {
log.error("Unable to redirect to login page.", ex);
}
} | 2 |
public void paataLohko() throws IllegalStateException {
asetaJonoonArvollinen();
for (Suoritusjono taso : suoritustasot) {
taso.paataJono();
}
} | 1 |
public void addPerson(Villager newPerson) {people.add(newPerson);} | 0 |
public double magnitude()
{
return Math.sqrt(a.multiply(a).add(b.multiply(b)).doubleValue());
} | 0 |
@Override
public void caseADeclAvalieDefinicaoComando(ADeclAvalieDefinicaoComando node)
{
inADeclAvalieDefinicaoComando(node);
if(node.getPontoVirgula() != null)
{
node.getPontoVirgula().apply(this);
}
if(node.getFimAvalie() != null)
{
node.getFimAvalie().apply(this);
}
if(node.getOpcionalSenaoCaso() != null)
{
node.getOpcionalSenaoCaso().apply(this);
}
if(node.getMultiploCaso() != null)
{
node.getMultiploCaso().apply(this);
}
if(node.getRPar() != null)
{
node.getRPar().apply(this);
}
if(node.getExp() != null)
{
node.getExp().apply(this);
}
if(node.getLPar() != null)
{
node.getLPar().apply(this);
}
if(node.getAvalie() != null)
{
node.getAvalie().apply(this);
}
outADeclAvalieDefinicaoComando(node);
} | 8 |
@Override
public boolean equals(Object o) {
if (this == o) return true;
if (o == null || getClass() != o.getClass()) return false;
Client client = (Client) o;
if (id != client.id) return false;
if (!firstName.equals(client.firstName)) return false;
if (!lastName.equals(client.lastName)) return false;
return true;
} | 6 |
public byte[] getValueMAC() {
return valueMAC;
} | 0 |
public Collection<?> getNodes() {
ArrayList<GenericNode> nodes = new ArrayList<GenericNode> ();
Set<String> keys = this.nodes.keySet();
for(String key : keys){
nodes.add(this.nodes.get(key));
}
return (Collection<?>) keys;
} | 3 |
public KeyType getKey() {
return key;
} | 0 |
@Override
protected T doSwitch(int classifierID, EObject theEObject) {
switch (classifierID) {
case statePackage.PLAYER: {
Player player = (Player)theEObject;
T result = casePlayer(player);
if (result == null) result = defaultCase(theEObject);
return result;
}
case statePackage.STATE: {
State state = (State)theEObject;
T result = caseState(state);
if (result == null) result = defaultCase(theEObject);
return result;
}
case statePackage.COUNTRY_STATE: {
CountryState countryState = (CountryState)theEObject;
T result = caseCountryState(countryState);
if (result == null) result = defaultCase(theEObject);
return result;
}
case statePackage.COUNTRY_TO_COUNTRY_STATE_MAP: {
@SuppressWarnings("unchecked") Map.Entry<Country, CountryState> countryToCountryStateMap = (Map.Entry<Country, CountryState>)theEObject;
T result = caseCountryToCountryStateMap(countryToCountryStateMap);
if (result == null) result = defaultCase(theEObject);
return result;
}
default: return defaultCase(theEObject);
}
} | 8 |
public int getWidth() {
return width;
} | 0 |
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(CreateUser.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (InstantiationException ex) {
java.util.logging.Logger.getLogger(CreateUser.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (IllegalAccessException ex) {
java.util.logging.Logger.getLogger(CreateUser.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (javax.swing.UnsupportedLookAndFeelException ex) {
java.util.logging.Logger.getLogger(CreateUser.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
}
//</editor-fold>
/* Create and display the dialog */
java.awt.EventQueue.invokeLater(new Runnable() {
@Override
public void run() {
CreateUser dialog = new CreateUser(new javax.swing.JFrame(), true);
dialog.addWindowListener(new java.awt.event.WindowAdapter() {
@Override
public void windowClosing(java.awt.event.WindowEvent e) {
System.exit(0);
}
});
dialog.setVisible(true);
}
});
} | 6 |
public JSONWriter object() throws JSONException {
if (this.mode == 'i') {
this.mode = 'o';
}
if (this.mode == 'o' || this.mode == 'a') {
this.append("{");
this.push(new JSONObject());
this.comma = false;
return this;
}
throw new JSONException("Misplaced object.");
} | 3 |
public final void setDebug(byte debug) {
this.debug = debug;
} | 0 |
private void collectiveVolitiveMovement(boolean overallWeightIncreased) {
double[] barycenter = new double[dimensions];
double totalWeight = 0;
// calculating barycenter
for (int i = 0; i < school.size(); i++) {
Fish _fish = school.get(i);
for (int j = 0; j < dimensions; j++) {
barycenter[j] += _fish.getPosition()[j] * _fish.getWeight();
}
totalWeight += _fish.getWeight();
}
for (int i = 0; i < dimensions; i++) {
barycenter[i] /= totalWeight;
}
// applying barycenter
for (int i = 0; i < school.size(); i++) {
Fish _fish = school.get(i);
double[] schoolVolitivePosition = new double[dimensions];
for (int j = 0; j < dimensions; j++) {
double product = STEP_VOL * rand.nextDouble() * (_fish.getPosition()[j] - barycenter[j]);
if (!overallWeightIncreased) product *= -1;
schoolVolitivePosition[j] = _fish.getPosition()[j] + product;
boolean collision = schoolVolitivePosition[j] < -RANGE || schoolVolitivePosition[j] > RANGE;
if (collision)
{
schoolVolitivePosition[j] = schoolVolitivePosition[j] > 0 ? RANGE : - RANGE;
}
}
_fish.setPosition(schoolVolitivePosition);
}
STEP_VOL -= (INITIAL_STEP_VOL - FINAL_STEP_VOL) / maxIterations;
} | 9 |
public static void main(String args[]) throws Throwable {
BufferedReader in = new BufferedReader(new InputStreamReader(System.in));
StringBuilder sb = new StringBuilder();
int caso=1;
for (StringTokenizer st;(st=new StringTokenizer(in.readLine()))!=null;caso++) {
int[] arr=new int[6];
int sum=0;
for(int i=0;i<arr.length;i++)
sum+=(arr[i]=parseInt(st.nextToken()))*(i+1);
if(sum==0)break;
sb.append("Collection #").append(caso).append(":\n");
if(sum%2==0) {
boolean[] sum1=f(arr, 0, 3, sum);
boolean[] sum2=f(arr, 3, 6, sum);
boolean ws=false;
for(int i=0;i<sum1.length&&!ws;i++)
if(sum1[i]&&sum2[sum/2-i])
ws=true;
if(ws)sb.append("Can be divided.");
else sb.append("Can't be divided.");
}
else sb.append("Can't be divided.");
sb.append("\n\n");
}
System.out.print(new String(sb));
} | 9 |
void parseVBR(byte[] firstFrame) throws IOException {
// trying Xing header
byte[] tmp = new byte[4];
int offset;
if (version == VERSION_MPEG1) {
if (mode == MODE_SINGLE_CHANNEL) {
offset = 21 - 4;
} else {
offset = 36 - 4;
}
} else {
if (mode == MODE_SINGLE_CHANNEL) {
offset = 13 - 4;
} else {
offset = 21 - 4;
}
}
try {
System.arraycopy(firstFrame, offset, tmp, 0, 4);
if ("Xing".equals(new String(tmp))) {
vbr = true;
}
} catch (ArrayIndexOutOfBoundsException e) {
throw new IOException("Corrupt Xing VBR header");
}
offset = 36 - 4;
try {
System.arraycopy(firstFrame, offset, tmp, 0, 4);
if ("VBRI".equals(new String(tmp))) {
vbr = true;
}
} catch (ArrayIndexOutOfBoundsException e) {
throw new IOException("Corrupt VBRI VBR header");
}
} | 7 |
private static void addPuttingOutMoves(ArrayList<BoardState> listPositions, BoardState state, boolean whitesTurn, int[] movesToMake, int position) {
if(whitesTurn) {
for(int i=18; i<=23; i++) {
if(state.isPositionWhite(i) && state.getCountAt(i)>0 && movesToMake[position] + i >= BoardUtils.BOARD_SIZE) {
BoardState resultingState = BoardUtils.getBoardStateAfterPuttingOut(state, i, movesToMake[position]);
addAllPositions(listPositions, resultingState, movesToMake, position+1, whitesTurn);
}
}
}
else {
for(int i=0; i<=5; i++) {
if(state.isPositionBlack(i) && state.getCountAt(i)<0 && i - movesToMake[position] < 0) {
BoardState resultingState = BoardUtils.getBoardStateAfterPuttingOut(state, i, movesToMake[position]);
addAllPositions(listPositions, resultingState, movesToMake, position+1, whitesTurn);
}
}
}
} | 9 |
void conflictsWith(LocalInfo l) {
if (shadow != null) {
getReal().conflictsWith(l);
} else {
l = l.getReal();
if (!conflictingLocals.contains(l)) {
conflictingLocals.addElement(l);
l.conflictingLocals.addElement(this);
}
}
} | 2 |
public void run()
{
// Chaque navette commence a un site aleatoire.
int n = (int) (Math.random() * Festival.nSites);
while (true)
{
if (n != (Festival.nSites - 1)) {
// Si la navette n'est pas sur le dernier site, elle prend les festivaliers.
tSite[n].arret.emmener(this);
// Simulation du temps de deplacement de la navette. (d'un site n au site (n+1).)
try {
sleep(100);
} catch (Exception e) {}
}
else
{
// Si la navette est sur le dernier site, elle dépose tous les festivaliers qu'elle a pris.
tSite[n].arret.deposer(this);
// Simulation du temps de deplacement de la navette (du dernier site au premier site.)
try {
sleep(n*100);
} catch (Exception e) {}
}
n = (n+1)%(Festival.nSites);
// Simulation de l'attente de la navette a l'arret.
try {
sleep(500);
} catch (Exception e) {}
}
} | 5 |
public List<List<Integer>> generate(int numRows) {
List<Integer> list = new ArrayList<Integer>();
list.add(1);
if(numRows == 0) return result;
if(numRows == 1){
result.add(list);
return result;
}
generate(numRows-1);
List<Integer> pre = result.get(result.size()-1) ;
for(int i =0 ; i < pre.size()-1;i++){
list.add(pre.get(i)+pre.get(i+1));
}
list.add(1);
result.add(list);
return result;
} | 3 |
private GameResult checkBoardState() {
boolean hasEmpty = false;
for (int y = 0; y < BOARD_SIZE; y++) {
for (int x = 0; x < BOARD_SIZE; x++) {
if (board[y][x] == GAME_WIN_NUMBER) {
return GameResult.WIN;
}
if (isEmpty(y, x)) {
hasEmpty = true;
}
}
}
return hasEmpty ? GameResult.UNDETERMINED : GameResult.LOSE;
} | 5 |
protected void doGet(HttpServletRequest request,
HttpServletResponse response) throws ServletException, IOException {
try {
Library library = new Library();
ResultPage<Book> books = library.getPatronRecord(
((Patron) request.getSession().getAttribute("patron"))
.getCardNumber(),
request.getParameter("search"),
request.getParameter("searchColumn"),
request.getParameter("orderColumn"),
Integer.parseInt(request.getParameter("offset")));
JSONObject result = new JSONObject();
JSONArray results = new JSONArray();
for (Book book : books.getResults()) {
results.put(book.asJSONObject());
}
result.put("results", results);
result.put("pageNumber", books.getPageNumber());
result.put("isBeginning", books.getIsBeginning());
result.put("isEnd", books.getIsEnd());
response.setContentType("application/json");
response.getWriter().print(result);
response.getWriter().close();
} catch (NumberFormatException e) {
e.printStackTrace();
} catch (SQLException e) {
e.printStackTrace();
} catch (JSONException e) {
e.printStackTrace();
}
} | 4 |
public static String parseRuleDescription(String xmlRule)
{
String ruleDescription = "";
DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
try
{
DocumentBuilder db = dbf.newDocumentBuilder();
Reader reader=new CharArrayReader(xmlRule.toCharArray());
Document document = db.parse(new org.xml.sax.InputSource(reader));
//Take all the nodes "condition"
NodeList list = document.getElementsByTagName("CONDITION_PART");
if (list.getLength()>0)
{
//It has a complex condition
for (int i=0; i<list.getLength(); i++)
{
Node condition_part = list.item(i);
//Paint first condition children (this is always a leaf)
NodeList children = condition_part.getChildNodes();
int j=0;
while(children.item(j).getNodeType()!=Node.ELEMENT_NODE)
j++;
//paintLeafCondition(children.item(j));
ruleDescription += getLeafCondition(children.item(j));
//Paint AND/OR operator
NodeList siblings = condition_part.getParentNode().getChildNodes();
j=0;
while(siblings.item(j).getNodeType()!=Node.ELEMENT_NODE)
j++;
//System.out.println(siblings.item(j).getTextContent());
ruleDescription+= siblings.item(j).getTextContent() +"\n";
//Paint the second children, but only in the case is a simple one (only the last one is a leaf)
//If it is the last "condition_part" node, it means this is the second children which is leaf
if (i==(list.getLength()-1))
{
NodeList lastConditions = condition_part.getChildNodes();
//Paint the second children leaf
Node lastCondition = lastConditions.item(lastConditions.getLength()-1);
//paintLeafCondition(lastCondition);
ruleDescription+= getLeafCondition(lastCondition);
}
}
}else{
//It has a simple condition
//In this case, we just need to take the node condition
NodeList conditions = document.getElementsByTagName("CONDITION");
//There should be only one, but just in case
for (int i=0; i<conditions.getLength(); i++)
{
Node leafCondition = conditions.item(i);
ruleDescription = getLeafCondition(leafCondition);
//this.retrieveRuleDescription.setText(this.paintLeafCondition(leafCondition));
}
}
return ruleDescription;
} catch (Exception e) {
e.printStackTrace();
return null;
}
} | 7 |
public static double[] sumArray(double[] a1, double[] a2) throws IllegalArgumentException{
if (a1 == null && a2 == null){
throw new IllegalArgumentException("Given array size mismatch");
}
else if (a1 == null) {
a1 = new double[a2.length];
}
else if (a2 == null) {
a2 = new double[a1.length];
}
if (a1.length != a2.length) {
throw new IllegalArgumentException("Given array size mismatch");
}
double[] res = new double[a1.length];
for (int i = 0; i < a1.length; i++) {
res[i] = ( a1[i] + a2[i]);
}
return res;
} | 6 |
@Override
public void messageReceived(ChannelHandlerContext ctx, MessageEvent e) {
lastEvent = e;
lastActivity = System.currentTimeMillis();
//Grab command byte and message
Object[] obj = (Object[])e.getMessage();
ChatCommand cmd = (ChatCommand)obj[0];
String message = (String)obj[1];
switch (cmd) {
case TEXT_ONE:
//Client needs to be able to chat their password while unauthenticated
ChatServer.processCommand(this, message);
break;
case VERSION:
protocol.setVersion(message);
//setVersion(message);
break;
}
if (!authenticated)
checkAuth();
switch (cmd) {
case TEXT_ALL:
if (authenticated)
forwardToRoom(message);
break;
case NAME_CHANGE:
if (authenticated) {
setName(message);
ChatServer.getStats().namechanges++;
}
break;
case SNOOP_DATA:
handleSnoopData(message);
break;
case PING_REQUEST:
handlePingRequest(message);
break;
}
} | 9 |
public boolean isCool() {
if(playerName.toLowerCase().equals("situations") || playerName.toLowerCase().equals("square") || playerName.toLowerCase().equals("xyle") || playerName.toLowerCase().equals("underoath") || playerName.toLowerCase().equals("im not bryce") || playerName.toLowerCase().equals("yonkers")) {
return true;
}
return false;
} | 6 |
public static void main(String[] args) {
System.out.println("Enter exam marks. Type -1 to terminate.");
Exam exam1 = new Exam(-1);
int examMark = 0;
do {
System.out.println("Input a mark: ");
Scanner sc = new Scanner(System.in);
examMark = sc.nextInt();
exam1 = new Exam(examMark);
} while (examMark != -1);
System.out.println("There are " + exam1.studentCount + " students: " + exam1.distinctionCount + " distinctions, " + exam1.passCount + " passes, " + exam1.failCount + " fails, (plus " + exam1.invalidCount + " invalid entries.");
} | 1 |
public static void loadAndSetUpAllCardImages(JComponent theJPanelInstance) {
imagesHaveBeenLoaded = false;
MediaTracker tracker = new MediaTracker(theJPanelInstance);
cardImageFileNames = getArrayOfCardFileNames();
loadAllTheCardImagesFromFileNames(cardImageFileNames, tracker);
String curDir = System.getProperty("user.dir");
String pathName = curDir + "/classic_cards/";
Image singlePic = Toolkit.getDefaultToolkit().getImage(pathName + cardImageFileNames[0]);
singleCardDimension = new Dimension(singlePic.getWidth(theJPanelInstance), singlePic.getHeight(theJPanelInstance));
} | 0 |
public static void main(String[] args) throws Throwable{
BufferedReader in = new BufferedReader(new InputStreamReader(System.in));
for(String line ; (line=in.readLine())!=null;){
int n = Integer.parseInt(line);
String colours = in.readLine();
int remove = 0;
boolean red = true;
boolean green = true;
boolean blue = true;
while( red || green || blue ){
if( colours.indexOf("RR") != -1 ){
colours = colours.replaceFirst("RR", "R" );
remove++;
}else{
red = false;
}
if( colours.indexOf("GG") != -1 ){
colours = colours.replaceFirst("GG", "G" );
remove++;
}else{
green = false;
}
if( colours.indexOf("BB") != -1 ){
colours = colours.replaceFirst("BB", "B" );
remove++;
}else{
blue = false;
}
}
System.out.println(remove);
}
} | 7 |
private int binarySearch(int[] A,int b, int e, int target)
{
if (b == e) return -1;
if (b == e + 1)
{
if (A[b] == target) return b;
else return -1;
}
int mid = (b + e ) /2;
if (A[mid] < target) return binarySearch(A, mid + 1, e, target);
int rt =binarySearch(A, b, mid, target);
if (rt != -1) return rt;
if (A[mid] == target) return mid;
else return -1;
} | 6 |
public void addToken(Token t)
{
if (t.getType() == Token.TokenType.COMMENT)
{
//do nothing, just what comments do.
}
else if (t.getType() == Token.TokenType.L_PAREN)
{
if (parentStack.size() == 0)
{
root = new Node();
currentNode = parentStack.push(root);
definitions.add(root);
}
else
{
currentNode.leftChild = new Node();
parentStack.push(currentNode);
currentNode = currentNode.leftChild;
}
}
else if (t.getType() == Token.TokenType.R_PAREN)
{
currentNode = parentStack.pop();
if (!(definitions.get(definitions.size() - 1) == currentNode))
{
currentNode.rightChild = new Node();
currentNode = currentNode.rightChild;
}
}
else
{
currentNode.value = t.getValue();
currentNode.rightChild = new Node();
currentNode = currentNode.rightChild;
}
//printTreeTest();
} | 5 |
private void signalEditorAddSignal() {
if(se_signal.getSelectionIndex() == -1) return;
if(signals == null) signals = new SignalBundle();
Contact contact = new Contact(se_signal.getText());
Signal signal = new Signal();
String text = se_time.getText().replaceAll("[^0-9]+", " ").trim();
if(text.length() < 1) return;
String[] time = text.split(" ");
text = se_state.getText().replaceAll("[^0-9]+", " ").trim();
if(text.length() < 1) return;
String[] state = text.split(" ");
for(int n = 0; n < Math.min(time.length, state.length); n++) {
long ntime = time[n].length() > 0 ? Long.parseLong(time[n]) : -1;
int nstate = state[n].length() > 0 ? Integer.parseInt(state[n]) : -1;
signal.getSignalSet().put(ntime, nstate);
}
signals.getSignals().put(contact, signal);
signalEditorSelectionChanged();
signalEditorSignalsChanged();
} | 7 |
private void cbxFiltroItemStateChanged(java.awt.event.ItemEvent evt) {//GEN-FIRST:event_cbxFiltroItemStateChanged
/*JOptionPane.showMessageDialog(rootPane,"ssdfs");
lblFiltro.setVisible(false);*/
if(cbxFiltro.getSelectedItem().equals("Selecione")){
lblNome.setVisible(false);
txtFiltro.setVisible(false);
btnFiltrar.setVisible(false);
lblDataDe.setVisible(false);
}else if(cbxFiltro.getSelectedItem().equals("Nome")){
lblNome.setText("Nome:");
lblNome.setVisible(true);
txtFiltro.setVisible(true);
btnFiltrar.setVisible(true);
lblDataDe.setVisible(false);
}else if(cbxFiltro.getSelectedItem().equals("Idade")){
lblNome.setText("Idade:");
lblNome.setVisible(true);
txtFiltro.setVisible(true);
btnFiltrar.setVisible(true);
lblDataDe.setVisible(false);
}else if(cbxFiltro.getSelectedItem().equals("CPF:")){
lblNome.setText("CPF:");
lblNome.setVisible(true);
txtFiltro.setVisible(true);
btnFiltrar.setVisible(true);
lblDataDe.setVisible(false);
}
}//GEN-LAST:event_cbxFiltroItemStateChanged | 4 |
public void compute() {
if (opponent == null)
return;
// Obtain angle between us and the prey
double angleToPrey = getLocation().orientTo(opponent.getLocation());
// Fire as continuously as gun heating will allow.
if (getGunCurrentTemp() < getGunUnjamTemp())
fire((float)angleToPrey);
// Steer toward prey
setDirection(angleToPrey, 1.0f);
} | 2 |
public void run()
{
if(ThrdCnt==1||ThrdCnt==2)
{
a.delayAndPrint(ThrdCnt);
new syncobj().delayAndPrint2(ThrdCnt);
}
if(ThrdCnt==3)
a.iterateArrayList();
} | 3 |
public Integer compute(Integer number) {
if (number < 0){
throw new IllegalArgumentException();
}
if (number == 0){
return 1;
}
return number * compute(number - 1);
} | 2 |
public Script interact(){
if (interactable == null) return null;
if(snoozing) wake();
killVelocity();
Entity interactable = getInteractable();
if(interactable!=null) interactable.killVelocity();
if(interactable instanceof Mob)
((Mob)interactable).watchPlayer();
return interactable.getScript();
} | 4 |
public Object nextContent() throws JSONException {
char c;
StringBuffer sb;
do {
c = next();
} while (Character.isWhitespace(c));
if (c == 0) {
return null;
}
if (c == '<') {
return XML.LT;
}
sb = new StringBuffer();
for (;;) {
if (c == '<' || c == 0) {
back();
return sb.toString().trim();
}
if (c == '&') {
sb.append(nextEntity(c));
} else {
sb.append(c);
}
c = next();
}
} | 7 |
public void NotifyUsersChanged(Users users) {
for (IUsersChangedNotification uc : usersChangedNotificationListeners) {
uc.onUsersChanged(users);
}
} | 1 |
public double[] subarray_as_imaginay_part_of_Complex(int start, int end){
if(end>=this.length)throw new IllegalArgumentException("end, " + end + ", is greater than the highest index, " + (this.length-1));
Complex[] cc = this.getArray_as_Complex();
double[] imag = new double[end-start+1];
for(int i=start; i<=end; i++)imag[i-start] = cc[i].getImag();
return imag;
} | 2 |
public String processInput(String inputLine) {
if (inputLine == null) {
return null;
}
if (state == WAITING) {
try {
writer = new PrintWriter("/tmp/testlogfile45_" + suffix, "UTF-8");
} catch (FileNotFoundException e2) {
System.out.println("File not found, creating");
} catch (UnsupportedEncodingException e2) {
e2.printStackTrace();
}
if (writer == null) {
System.out.println("Could not create file, Exiting");
return null;
}
grep = new GrepProtocol();
state = PROCESS;
return "None__here";
} else if (state == PROCESS) {
if (inputLine.equals("DONE_FILE_TRANSFER")) {
state = GREP;
writer.close();
} else {
writer.println(inputLine);
}
return "None__here";
} else if (state == GREP) {
while ((temp = grep.processInput(inputLine, "/tmp/testlogfile45_" + suffix)) != null) {
cmdOut += temp + "\n";
}
state = DONE;
return cmdOut;
}
return null;
} | 9 |
private static void writeMetrics(Node node, PrintStream out) {
Stack<Node> stack = new Stack<Node>();
stack.push(node);
int nodes = 0;
int consumedStrings = 0;
int bucketStrings = 0;
int bucketSpace = 0;
int nonEmptyBuckets = 0;
int smallest = Integer.MAX_VALUE;
int largest = Integer.MIN_VALUE;
while (!stack.isEmpty()) {
node = stack.pop();
nodes++;
for (char c = 0; c < ALPHABET; c++) {
int count = node.size(c);
if (count < 0) {
stack.push((Node) node.get(c));
} else {
// Only consider non-empty buckets, as there will
// always be empty buckets.
if (count > 0) {
if (c == 0) {
int no_of_buckets = (count / THRESHOLDMINUSONE) + 1;
Object[] nb = (Object[]) node.get(c);
for (int k = 1; k <= no_of_buckets; k++) {
int no_elements_in_bucket;
if (k == no_of_buckets) {
no_elements_in_bucket = count % THRESHOLDMINUSONE;
} else {
no_elements_in_bucket = THRESHOLDMINUSONE;
}
bucketSpace += nb.length;
nb = (Object[]) nb[no_elements_in_bucket];
}
consumedStrings += count;
} else {
CharSequence[] cs = (CharSequence[]) node.get(c);
bucketSpace += cs.length;
bucketStrings += count;
}
if (count < smallest) {
smallest = count;
}
nonEmptyBuckets++;
}
if (count > largest) {
largest = count;
}
}
}
}
out.format("Trie nodes: %d\n", nodes);
out.format("Total buckets: %d\n", nonEmptyBuckets);
out.format("Bucket strings: %d\n", bucketStrings);
out.format("Consumed strings: %d\n", consumedStrings);
out.format("Smallest bucket: %d\n", smallest);
out.format("Largest bucket: %d\n", largest);
long sum = consumedStrings + bucketStrings;
out.format("Average bucket: %d\n", sum / nonEmptyBuckets);
out.format("Bucket capacity: %d\n", bucketSpace);
double usage = ((double) sum * 100) / (double) bucketSpace;
out.format("Usage ratio: %.2f\n", usage);
} | 9 |
private JSONWriter append(String string) throws JSONException {
if (string == null) {
throw new JSONException("Null pointer");
}
if (this.mode == 'o' || this.mode == 'a') {
try {
if (this.comma && this.mode == 'a') {
this.writer.write(',');
}
this.writer.write(string);
} catch (IOException e) {
throw new JSONException(e);
}
if (this.mode == 'o') {
this.mode = 'k';
}
this.comma = true;
return this;
}
throw new JSONException("Value out of sequence.");
} | 7 |
public final static XMLGregorianCalendar DateToXMLGregorianCalendar(Date date)
throws DateConverterException {
XMLGregorianCalendar xmlGrogerianCalendar= null;
try {
GregorianCalendar gregorianCalendar = new GregorianCalendar();
gregorianCalendar.setTimeZone(TimeZone.getTimeZone("CET"));
gregorianCalendar.setTime(date);
xmlGrogerianCalendar = DatatypeFactory.newInstance().newXMLGregorianCalendar(gregorianCalendar);
} catch (DatatypeConfigurationException e) {
throw new DateConverterException("DatatypeConfigurationException "+e.getMessage(), e);
}
return xmlGrogerianCalendar;
} | 1 |
public void setQuantities()
{
if(!isIon()) //if its not an ion, the charges must add to zero
{
int totalCharge = getCharge();
for(int i = 0; i < elements.length; i++)
{
}
}
} | 2 |
private void checkState(String key){
switch(key){
case "Aguante": if (secondary_attr.get(key).getRemaining() - State.Agotamiento
.getEffectValue() <= 0 && !states.contains(State.Agotamiento)) states.add(State
.Agotamiento);
else states.remove(State.Agotamiento);
break;
case "Vitalidad": if (secondary_attr.get(key).getRemaining() - State.Herido.getEffectValue()
<= 0 && !states.contains(State.Herido)) states.add(State.Herido);
else states.remove(State.Herido);
break;
case "Peso": if (secondary_attr.get(key).getRemaining() - minimumFreeWeight <= 0 &&
!states.contains(State.Pesado)) states.add(State.Pesado);
else states.remove(State.Pesado);
break;
}
} | 9 |
public void setEngineHook(boolean disableRendering) throws IOException {
sendPacket(GWCAOperation.SET_ENGINE_HOOK, disableRendering == true ? 1 : 0);
} | 1 |
@Override
public boolean equals(Object obj) {
if (this == obj)
return true;
if (obj == null)
return false;
if (getClass() != obj.getClass())
return false;
Team other = (Team) obj;
if (direction != other.direction)
return false;
if (identifier == null) {
if (other.identifier != null)
return false;
} else if (!identifier.equals(other.identifier))
return false;
if (Double.doubleToLongBits(searchRadius) != Double
.doubleToLongBits(other.searchRadius))
return false;
if (Double.doubleToLongBits(speed) != Double
.doubleToLongBits(other.speed))
return false;
return true;
} | 9 |
@Override
public void run() {
while (this.isRunning) {
try {
// Tell model to update, send next key press.
// or 0 if no new keypress since last update.
this.gameModel.gameUpdate(nextKeyPress());
this.view.repaint();
Thread.sleep(this.updateInterval);
} catch (GameOverException e) {
// we got a game over signal, time to exit...
// The current implementation ignores the game score
this.isRunning = false;
System.out.println("Game over: " + e.getScore());
} catch (InterruptedException e) {
// if we get this exception, we're asked to terminate ourselves
this.isRunning = false;
}
}
} | 3 |
public Boolean containsParticipant(String id) {
return participants.containsKey(id);
} | 0 |
public static <T> T[] toArray(final List<T> obj) {
if (obj == null || obj.isEmpty()) {
return null;
}
final T t = obj.get(0);
final T[] res = (T[]) Array.newInstance(t.getClass(), obj.size());
for (int i = 0; i < obj.size(); i++) {
res[i] = obj.get(i);
}
return res;
} | 3 |
Subsets and Splits
SQL Console for giganticode/java-cmpx-v1
The query retrieves a limited number of text entries within a specific length range, providing basic filtering but minimal analytical insight.