text
stringlengths
14
410k
label
int32
0
9
@Override public boolean equals(Object o) { if(o instanceof TreasureLocation){ TreasureLocation location = (TreasureLocation) o; if(location.getX() == getX()){ if(location.getY() == getY()){ if(location.getZ() == getZ()){ return true; } } } } return false; }
4
public Card[][] getSets() { int count = cards.size(); if (count < 3) return new Card[0][]; ArrayList<Card[]> sets = new ArrayList<Card[]>(); for (int i = 0; i < count; i++) { for (int j = i + 1; j < count; j++) { for (int k = j + 1; k < count; k++) { Card[] set = {cards.get(i), cards.get(j), cards.get(k)}; if (isSet(set)) sets.add(set); } } } Card[][] result = new Card[sets.size()][3]; sets.toArray(result); return result; }
5
@Override public boolean invoke(MOB mob, List<String> commands, Physical givenTarget, boolean auto, int asLevel) { if(!super.invoke(mob,commands,givenTarget,auto,asLevel)) return false; final boolean success=proficiencyCheck(mob,0,auto); if(success) { final CMMsg msg=CMClass.getMsg(mob,null,this,CMMsg.MSG_SPEAK,auto?"":L("^S<S-NAME> scream(s) a mighty RALLYING CRY!!^?")); if(mob.location().okMessage(mob,msg)) { mob.location().send(mob,msg); final Set<MOB> h=properTargets(mob,givenTarget,auto); if(h==null) return false; for (final Object element : h) { final MOB target=(MOB)element; target.location().show(target,null,CMMsg.MSG_OK_VISUAL,L("<S-NAME> seem(s) rallied!")); timesTicking=0; hpUp=mob.phyStats().level()+(2*getXLEVELLevel(mob)); beneficialAffect(mob,target,asLevel,0); target.recoverMaxState(); if(target.fetchEffect(ID())!=null) mob.curState().adjHitPoints(hpUp,mob.maxState()); } } } else beneficialWordsFizzle(mob,null,auto?"":L("<S-NAME> mumble(s) a weak rally cry.")); // return whether it worked return success; }
8
public void jump(boolean forceJump) { if (onGround || forceJump) { onGround = false; setVelocityY(JUMP_SPEED); if(anim == left) anim = animJumpLeft; else if (anim == right) anim =animJumpRight; anim.update(JUMP_TIME); } }
4
public ExitMessage(){ int len = 12; buf = new byte[len]; TypeConvert.int2byte(len, buf, 0); TypeConvert.int2byte(RequestId.Exit, buf, 4); }
0
public static String byte2hex2(byte[] source) { if (source == null || source.length <= 0) { return ""; } final int size = source.length; final char str[] = new char[size * 2]; int index = 0; byte b; for (int i = 0; i < size; i++) { b = source[i]; str[index++] = sHexDigits[b >>> 4 & 0xf]; str[index++] = sHexDigits[b & 0xf]; } return new String(str); }
3
@Override public void startEvent(){ try{ for(int i = 0 ; i < 5; i++){ if(inputs[0].getText().isEmpty() && inputs[1].getText().isEmpty() && inputs[2].getText().isEmpty()){ voltage = DEFAULT_VOLTAGE; current += DEFAULT_CURRENT; resistance = DEFAULT_RESISTANCE; inputs[INDEX_ZERO].setText(Double.toString(voltage)); inputs[INDEX_ONE].setText(Double.toString(current)); inputs[INDEX_TWO].setText(Double.toString(resistance)); } if(inputs[INDEX_ZERO].getText().isEmpty()){ voltage = Double.parseDouble(inputs[INDEX_ONE].getText()) * Double.parseDouble(inputs[INDEX_TWO].getText()); inputs[INDEX_ZERO].setText(Double.toString(convertToDF(voltage))); }else{ voltage = Double.parseDouble(inputs[INDEX_ZERO].getText()); } if(inputs[INDEX_ONE].getText().isEmpty()){ current = Double.parseDouble(inputs[INDEX_ZERO].getText()) / Double.parseDouble(inputs[INDEX_TWO].getText()); inputs[INDEX_ONE].setText(Double.toString(convertToDF(current))); }else{ current = Double.parseDouble(inputs[INDEX_ONE].getText()); } if(inputs[INDEX_TWO].getText().isEmpty()){ resistance = Double.parseDouble(inputs[INDEX_ZERO].getText()) / Double.parseDouble(inputs[INDEX_ONE].getText()); inputs[INDEX_TWO].setText(Double.toString(convertToDF(resistance))); }else{ resistance = Double.parseDouble(inputs[INDEX_TWO].getText()); } } }catch(Exception a){ JOptionPane.showMessageDialog(null, "Invalid Input", "Error", JOptionPane.ERROR_MESSAGE); } if(Math.abs(voltage-(current*resistance)) >= 0.5){ JOptionPane.showMessageDialog(null, "Inputs do not respect Ohm's Law", "Error", JOptionPane.ERROR_MESSAGE); circuitAnimationTimeline.stop(); }else{ circuitAnimationTimeline.play(); } }
9
public AnnotatedWith( Annotation annotation ) { this.annotation = annotation; }
0
private synchronized void setState(ClientState state) { if (this.state != state) { this.setChanged(); } this.state = state; this.notifyObservers(this.state); }
1
@Test public void edgeIsToggled() { Vertex v1 = vc.addVertex(3, 5); Vertex v2 = vc.addVertex(5, 3); vc.toggleEdge(v1, v2); boolean b1 = v1.getAdjacents().contains(v2) && v2.getAdjacents().contains(v1); vc.toggleEdge(v2, v1); boolean b2 = v1.getAdjacents().isEmpty() && v2.getAdjacents().isEmpty(); assertTrue(b1 && b2); }
3
public void filter(FileFilter customFilter) { FileFilter filter = makeFilter(); //Adds custom filter if exists if (filter != null && customFilter != null) { filter = new AndFilter(filter, customFilter); } else if (filter == null && customFilter != null) { filter = customFilter; } //Updates root if (filter == null) { FileNode node; if (root.isDirectory()) { node = new FileNode((Directory) root.getUserObject()); } else { node = new FileNode((IndexedFile) root.getUserObject()); } setRoot(node); } else { FilterNode filterRoot; if (root.isDirectory()) { filterRoot = new FilterNode((Directory) root.getUserObject(), filter); } else { filterRoot = new FilterNode((IndexedFile) root.getUserObject(), filter); } setRoot(filterRoot); } }
7
public String getClipboardContents() { String result = "" ; Clipboard clipboard = Toolkit.getDefaultToolkit().getSystemClipboard() ; //odd: the Object param of getContents is not currently used Transferable contents = clipboard.getContents( null ) ; boolean hasTransferableText = ( contents != null ) && contents.isDataFlavorSupported( DataFlavor.stringFlavor ) ; if ( hasTransferableText ) { try { result = ( String ) contents.getTransferData( DataFlavor.stringFlavor ) ; } catch ( UnsupportedFlavorException ex ) { //highly unlikely since we are using a standard DataFlavor System.out.println( ex ) ; } catch ( IOException ex ) { System.out.println( ex ) ; } } return result ; }
4
private void readObject(ObjectInputStream in) throws IOException { setLevel(Level.parse(in.readUTF())); setLoggerName(in.readUTF()); setMessage(in.readUTF()); setMillis(in.readLong()); final Object[] params = new Object[in.readInt()]; for (int i = 0; i < params.length; i++) { try { params[i] = in.readObject(); } catch (ClassNotFoundException ex) { logger.log(Level.SEVERE, "Unable to deserialize record parameter " + i + " because the class was not found.", ex); params[i] = new Object(); //no body likes NPE's } } setResourceBundleName(in.readUTF()); setSequenceNumber(in.readLong()); setSourceClassName(in.readUTF()); setSourceMethodName(in.readUTF()); setThreadID(in.readInt()); try { setThrown((Throwable) in.readObject()); } catch (ClassNotFoundException ex) { logger.log(Level.SEVERE, "Unable to deserialize thrown record field, " + "class was not found.", ex); } final int numFields = in.readInt(); for (int i = 0; i < numFields; i++) { final String name = in.readUTF(); final String value = in.readUTF(); fields.put(name, (value.contentEquals(CONST_NULL) ? null : value)); } }
5
@Override public boolean put( String key, Long value ) { if ( key == null ) { throw new IllegalArgumentException( "key was null" ); } if ( value == null ) { throw new IllegalArgumentException( "value was null" ); } int iteration = 1; int hash = hash(key); int offset = nextHop( hash, iteration++ ); int reprobes = 0; while ( keys[offset] != null && keys[offset] != Tombstone ) { if ( keys[offset].equals( key ) ) { if ( values[offset] == value.longValue() ) { return false; } else { values[offset] = value.longValue(); return true; } } offset = nextHop( hash, iteration++); if ( offset == nextHop(hash, 1) ) { return false; } reprobes++; } increaseSize(); keys[offset] = key; values[offset] = value.longValue(); checkResize( reprobes ); return true; }
7
void verificarObstaculos(){ int cabeza = inicioSnake +longSnake -1; cabeza = cabeza %(ancho *alto); for(int i = inicioSnake;i< inicioSnake +longSnake -1 ;i++){ int pos = i %(alto*ancho); if(snakeX[cabeza] == snakeX[pos]&& snakeY[cabeza] ==snakeX[pos]){ break; } } }
3
public void ConsultarAdmin(String user, String clave) throws SQLException { // throw new UnsupportedOperationException("Not supported yet."); //To change body of generated methods, choose Tools | Templates. try{ Conexion.GetInstancia().Conectar(); ResultSet consulta=Conexion.GetInstancia().EjectConsulta("select usuario,pass,cargo FROM empleado WHERE pass = '"+empleado.getPass()+"' and usuario='"+empleado.getUsuario()+"'"); if(consulta.next()) { if((consulta.getString("cargo").equals("administrador"))) { menuAdmin ir= new menuAdmin(); jDPEscritorio.add(ir); ir.show(); } } Conexion.GetInstancia().Desconectar(); } catch(SQLException e) { throw e; } }
3
public static String convertFileToString(File file) { if (file != null && file.exists() && file.canRead() && !file.isDirectory()) { Writer writer = new StringWriter(); InputStream is = null; char[] buffer = new char[1024]; try { is = new FileInputStream(file); Reader reader = new BufferedReader(new InputStreamReader(is, "UTF-8")); int n; while ((n = reader.read(buffer)) != -1) { writer.write(buffer, 0, n); } } catch (IOException e) { System.out.println("Exception "); } finally { if (is != null) { try { is.close(); } catch (IOException ignore) { } } } return writer.toString(); } else { return ""; } }
8
static public CycSymbol getCycSymbolForBoolean(boolean val) { return (val == false) ? CycObjectFactory.nil : CycObjectFactory.t; }
1
public static void main(String[] args) { System.out.println("Backspace = <\b>"); System.out.println("New line = <\n>"); System.out.println("Return = <\r>"); System.out.println("Formfeed = <\f>"); System.out.println("Tab = <\t>"); System.out.println("Backslash = <\\>"); System.out.println("Single quote = <\'>"); System.out.println("Double quote = <\">"); System.out.println("Null = <\0>"); System.out.println("\u0048\1451\u006c\157"); // Hello System.out.println('\u0e01'); // ก System.out.println('ก'); // ก }
0
public static void scrollBothPaneV(String str, int delta) { if (str == "inc") { scrollPane1.getVerticalScrollBar().setValue(scrollPane1.getVerticalScrollBar().getValue() - delta); scrollPane2.getVerticalScrollBar().setValue(scrollPane2.getVerticalScrollBar().getValue() - delta); } else if (str == "dec") { scrollPane1.getVerticalScrollBar().setValue(scrollPane1.getVerticalScrollBar().getValue() + delta); scrollPane2.getVerticalScrollBar().setValue(scrollPane2.getVerticalScrollBar().getValue() + delta); } }
2
@Override protected Integer doInBackground() throws Exception { /* Try to connect to the server on localhost, port 5556 */ jLabel3.setText("Sending transfer command"); ChatBox.MultiThreadChatClient.os.println("/send"); Socket sk = new Socket("188.26.255.139", 5557); OutputStream output = sk.getOutputStream(); OutputStreamWriter outputStream = new OutputStreamWriter(sk.getOutputStream()); BufferedReader inReader = new BufferedReader(new InputStreamReader(sk.getInputStream())); /* Send receiver to the server */ String receiver = jComboBox1.getSelectedItem().toString(); jLabel3.setText("Sending receiver(" + receiver + ") to server"); outputStream.write(receiver + "\n" ); outputStream.flush(); /* Send filename to server */ jLabel3.setText("Sending filename to server"); outputStream.write(fileDlg.getSelectedFile().getName() + "\n"); outputStream.flush(); /* Get reponse from server */ jLabel3.setText("Handshaking..."); String serverStatus = inReader.readLine(); /* If server is ready, send the file */ if (serverStatus.equals("READY")) { FileInputStream file = new FileInputStream(filename); /* Get the buffer length from the server */ int len = Integer.parseInt(inReader.readLine()); byte[] buffer = new byte[len]; int bytesRead; total = 0; start = System.currentTimeMillis(); while ((bytesRead = file.read(buffer)) > 0) { total += bytesRead; output.write(buffer, 0, bytesRead); cost = System.currentTimeMillis() - start; if ((cost > 0) && (System.currentTimeMillis() % 2 == 0)) { speed = total / cost; jLabel3.setText(speed + " KB/s"); } jProgressBar1.setValue((int) ((total * 100) / filesize)); } jLabel3.setText("Complete!"); output.close(); file.close(); sk.close(); }else { jLabel3.setText("Transfer declined"); output.close(); sk.close(); } return 666; }
4
private final void loadProps() { if (props == null) { props = new Properties(); } InputStream in; try { File propsFile = new File(StaticString.PROPS_NAME); if (propsFile.exists()) { in = new FileInputStream(propsFile); } else { in = ClassLoader.getSystemClassLoader().getResourceAsStream( StaticString.CONFIG_PATH + StaticString.PROPS_NAME); } if (in != null) { props.load(in); } } catch (Exception e1) { e1.printStackTrace(); } }
4
public void beforeFirst() throws SQLException { if (first == 1) {rs.beforeFirst();} else {rs.absolute(first - 1);} }
1
private void copierFichier(String source, String destination) throws IOException { FileInputStream fis = null; FileOutputStream fos = null; try { byte buffer[] = new byte[1024]; int taille = 0; fis = new FileInputStream(source); fos = new FileOutputStream(destination); while ((taille = fis.read(buffer)) != -1) { fos.write(buffer, 0, taille); } } finally { if (fis != null) { try { fis.close(); } catch (IOException e) { } } if (fos != null) { try { fos.close(); } catch (IOException e) { } } } }
5
public void zoom(int amount) { int direction = amount / Math.abs(amount); for (int i=1; i<=Math.abs(amount); i++) { if (radius > originalRadius || direction > 0) { radius = radius + 30*direction; } } this.windowCoordsUpdated = false; updateCenterCoordinates(); }
3
public String getCode() { return code; }
0
public Entity(EntityType type, Point world_position) { this.type = type; is_opaque = EntityType.isOpaque(type); is_passable = EntityType.isPassable(type); name = EntityType.getName(type); needs_update = EntityType.needsUpdate(type); default_interact = EntityType.defaultInteract(type); default_action = EntityType.defaultAction(type); spriteID = EntityType.getSpriteID1(type); controller = ControllerType.getController(EntityType.getControllerType(type)); controller.setParent(this); this.world_position = world_position; suffix = ""; if (world_position.x < 10) { suffix += "0" + world_position.x; } else { suffix += world_position.x; } if (world_position.y < 10) { suffix += "0" + world_position.y; } else { suffix += world_position.y; } }
2
private IMode getMode(byte[] key, byte[] iv, int state) { IBlockCipher cipher = CipherFactory.getInstance(properties.get("cipher")); if (cipher == null) { throw new IllegalArgumentException("no such cipher: " + properties.get("cipher")); } int blockSize = cipher.defaultBlockSize(); if (properties.containsKey("block-size")) { try { blockSize = Integer.parseInt(properties.get("block-size")); } catch (NumberFormatException nfe) { throw new IllegalArgumentException("bad block size: " + nfe.getMessage()); } } IMode mode = ModeFactory.getInstance(properties.get("mode"), cipher, blockSize); if (mode == null) { throw new IllegalArgumentException("no such mode: " + properties.get("mode")); } HashMap modeAttr = new HashMap(); modeAttr.put(IMode.KEY_MATERIAL, key); modeAttr.put(IMode.STATE, new Integer(state)); modeAttr.put(IMode.IV, iv); try { mode.init(modeAttr); } catch (InvalidKeyException ike) { throw new IllegalArgumentException(ike.toString()); } return mode; }
5
private static int determineWinner(FutureTask<Integer> task1, FutureTask<Integer> task2) throws InterruptedException, ExecutionException { boolean isDone = false; int winnerTime = 0; while (!isDone) { if (task1.isDone()) { isDone = true; winnerTime = task1.get(); task2.cancel(true); } else if (task2.isDone()) { isDone = true; winnerTime = task2.get(); task1.cancel(true); } } return winnerTime; }
3
public static Keyword interpretIterativeForallScores(ControlFrame frame, Keyword lastmove) { if (lastmove == Logic.KWD_DOWN) { if (frame.partialMatchFrame == null) { ControlFrame.createAndLinkPartialMatchFrame(frame, Logic.KWD_ITERATIVE_FORALL); } else { while (frame.partialMatchFrame.argumentScores.length() > frame.argumentCursor) { frame.partialMatchFrame.popPartialMatchScore(); } } } else if ((lastmove == Logic.KWD_UP_TRUE) || (lastmove == Logic.KWD_UP_FAIL)) { ControlFrame.recordLatestPartialMatchScore(frame); if (Stella_Object.traceKeywordP(Logic.KWD_GOAL_TREE)) { System.out.println("ITERATIVE-FORALL " + ((FloatWrapper)(KeyValueList.dynamicSlotValue(((QueryIterator)(Logic.$QUERYITERATOR$.get())).dynamicSlots, Logic.SYM_LOGIC_LATEST_POSITIVE_SCORE, Stella.NULL_FLOAT_WRAPPER))).wrapperValue); } if (((FloatWrapper)(KeyValueList.dynamicSlotValue(((QueryIterator)(Logic.$QUERYITERATOR$.get())).dynamicSlots, Logic.SYM_LOGIC_LATEST_POSITIVE_SCORE, Stella.NULL_FLOAT_WRAPPER))).wrapperValue < 0.9) { lastmove = Logic.KWD_UP_FAIL; } } else { { OutputStringStream stream000 = OutputStringStream.newOutputStringStream(); stream000.nativeStream.print("`" + lastmove + "' is not a valid case option"); throw ((StellaException)(StellaException.newStellaException(stream000.theStringReader()).fillInStackTrace())); } } return (lastmove); }
7
@Override public boolean invoke(MOB mob, List<String> commands, Physical givenTarget, boolean auto, int asLevel) { final MOB target=this.getTarget(mob,commands,givenTarget); if(target==null) return false; if(target==mob) return false; if(!super.invoke(mob,commands,givenTarget,auto,asLevel)) return false; final boolean success=proficiencyCheck(mob,0,auto); if(success) { final CMMsg msg=CMClass.getMsg(mob,target,this,somanticCastCode(mob,target,auto),auto?"":L("^S<S-NAME> @x1 while peering into <T-YOUPOSS> soul.^?",prayWord(mob))); if(mob.location().okMessage(mob,msg)) { mob.location().send(mob,msg); final StringBuilder str=CMLib.commands().getScore(target); if(!mob.isMonster()) mob.session().wraplessPrintln(str.toString()); } } else beneficialVisualFizzle(mob,target,L("<S-NAME> attempt(s) to peer into <T-YOUPOSS> soul, but fail.")); return success; }
7
public void move(boolean forward) { _motor.set((forward ? 1 : -1)*MOTOR_SPEED); }
1
public RarHandler(File album) { Logger.getLogger(RarHandler.class.getName()).entering(RarHandler.class.getName(), "RarHandler", album); try { archive = new Archive(album); } catch (RarException | IOException ex) { Logger.getLogger(this.getClass().getName()).log(Level.SEVERE, "Cannot read the RAR archive", ex); new InfoInterface(InfoInterface.InfoLevel.ERROR, "file-read", album.getName()); Logger.getLogger(RarHandler.class.getName()).exiting(RarHandler.class.getName(), "RarHandler"); return; } if (archive.isEncrypted()) { Logger.getLogger(this.getClass().getName()).log(Level.SEVERE, "RAR archive encrypted"); new InfoInterface(InfoInterface.InfoLevel.ERROR, "file-read", album.getName()); Logger.getLogger(RarHandler.class.getName()).exiting(RarHandler.class.getName(), "RarHandler"); return; } List<FileHeader> fh = archive.getFileHeaders(); Collections.sort(fh, (FileHeader o1, FileHeader o2) -> o1.getFileNameString().compareTo(o2.getFileNameString())); ListIterator<FileHeader> it = fh.listIterator(); while (it.hasNext()) { FileHeader currentEntry = it.next(); if (!currentEntry.isDirectory() && isAnImage(currentEntry.getFileNameString())) { compressedFilesHeaders.add(currentEntry); } } Logger.getLogger(RarHandler.class.getName()).exiting(RarHandler.class.getName(), "RarHandler"); }
5
public void saveState(Session s) throws Exception { s.saveInt(homeworld == null ? -1 : homeworld.ID) ; s.saveInt(partners.size()) ; for (System p : partners) s.saveInt(p.ID) ; for (int i = NUM_J ; i-- > 0 ;) { s.saveFloat(jobSupply[i]) ; s.saveFloat(jobDemand[i]) ; } shortages.saveState(s) ; surpluses.saveState(s) ; for (Service type : ALL_COMMODITIES) { s.saveFloat(importPrices.get(type)) ; s.saveFloat(exportPrices.get(type)) ; } s.saveObjects(candidates) ; s.saveObjects(migrantsIn) ; s.saveObject(ship) ; s.saveFloat(nextVisitTime) ; }
4
public static String formatArray(String[] arr, char sep) { if (arr.length == 0) return ""; StringBuffer sb = new StringBuffer(); int sepcount = arr.length - 1; for (int i = 0; i < sepcount; i++) sb.append(arr[i] + sep); sb.append(arr[sepcount]); return sb.toString(); }
2
private void setPreparedStatementValues(PreparedStatement preparedStatement, Field field, int index, Product product) { try { Class<?> type = field.getType(); String typeName = type.getSimpleName(); if (typeName.equals("String")) { preparedStatement.setString(index, field.get(product).toString()); } else if (typeName.equals("Color")) { preparedStatement.setInt(index, ((Color)field.get(product)).getRGB()); } else if (typeName.equals("int")) { preparedStatement.setInt(index, (Integer) field.get(product)); } else if (typeName.equals("double")) { preparedStatement.setDouble(index, (Double) field.get(product)); } else if (typeName.equals("Date")) { Date date = (Date)field.get(product); preparedStatement.setString(index, getDateString(date)); } } catch (Exception e) { System.err.println("Error preparing statement."); e.printStackTrace(); } }
7
@EventHandler public void onMessageEvent(MessageEvent event){ try{ Object o = Utils.fromByteArray(event.b); if(o instanceof String){//assume its json //**************************** GSONListener.listen((String)o, event.sc);// Gson/Json * return; // Listener * } ////////////////////////////// Client c = ClientManager.get(event.sc); if(o instanceof EncryptedObject){o = ((EncryptedObject)o).decrypt(c.getKey());} System.out.println("Object is: " + o.getClass().getSimpleName()); if(o instanceof EncryptableObject){((EncryptableObject)o).setSocketChannel(event.getSocketChannel());} if(c.isLoggedIn()){ Main.getEventSystem().listen(o); }else{ if(o instanceof LoginObject){ Main.getEventSystem().listen(o); } } }catch(Exception e){e.printStackTrace();} }
6
boolean handleWrite() throws IOException { synchronized (this.bufferQueueMutex) { ByteBuffer buffer = this.bufferQueue.peek(); while (buffer != null) { channelWrite(buffer); if (buffer.remaining() > 0) { return false; // Didn't finish this buffer. There's more to // send. } else { this.bufferQueue.poll(); // Buffer finished. Remove it. buffer = this.bufferQueue.peek(); } } return true; } }
2
public boolean intersects(KDPoint q, double distActual) { return isInside(q, distActual) || intersectHorizontal(q, distActual, true) || intersectHorizontal(q, distActual, false) || intersectVertical(q, distActual, true) || intersectVertical(q, distActual, false); }
4
public boolean readFAT() { //System.out.println("Reading FAT from disk"); int entries= 0; File file = new File(cacheDir, "FAT"); if(!file.isFile()) { return false; } FileInputStream fileIn; try { fileIn = new FileInputStream(file); } catch (IOException e) { return false; } DataInputStream in = new DataInputStream(fileIn); boolean eof = false; while(!eof) { try { long hash = in.readLong(); int id = in.readInt(); FAT.put(hash, id); FATList.add(hash); entries++; //System.out.println("FAT: " + Long.toHexString(hash)); } catch (EOFException eofe) { System.out.println("EOF FAT"); eof = true; continue; } catch (IOException ioe) { System.out.println("IO exception reading FAT"); } } try { if(in != null) { in.close(); } } catch (IOException ioe) { return false; } //System.out.println("Entries: " + entries); return true; }
7
public MethodCollector visitMethod(int access, String name, String desc) { // already found the method, skip any processing if (collector != null) return null; // not the same name if (!name.equals(methodName)) return null; Type[] argumentTypes = Type.getArgumentTypes(desc); int longOrDoubleQuantity = 0; for (Type t : argumentTypes) if (t.getClassName().equals("long") || t.getClassName().equals("double")) longOrDoubleQuantity++; int paramCount = argumentTypes.length; // not the same quantity of parameters if (paramCount != this.parameterTypes.length) return null; for (int i = 0; i < argumentTypes.length; i++) if (!correctTypeName(argumentTypes, i).equals( this.parameterTypes[i].getName())) return null; this.collector = new MethodCollector((Modifier.isStatic(access) ? 0 : 1), argumentTypes.length + longOrDoubleQuantity); return collector; }
9
private void updateParts() { entireView.removeAll(); for (JComponent jp : parts) { entireView.add(jp); } }
1
public void toggleKey(int keyCode,boolean isPressed){ if(keyCode == KeyEvent.VK_W || keyCode == KeyEvent.VK_UP){ up.toggle(isPressed); } if(keyCode == KeyEvent.VK_S || keyCode == KeyEvent.VK_DOWN){ down.toggle(isPressed); } if(keyCode == KeyEvent.VK_A || keyCode == KeyEvent.VK_LEFT){ left.toggle(isPressed); } if(keyCode == KeyEvent.VK_D || keyCode == KeyEvent.VK_RIGHT){ right.toggle(isPressed); } }
8
public void resolve(String name_, boolean ip4only_) { name = name_; int hash = name_.hashCode(); if (hash < 0) hash = -hash; hash = hash % 55536; hash += 10000; try { address = new InetSocketAddress(InetAddress.getByName(null), hash); } catch (UnknownHostException e) { throw new IllegalArgumentException(e); } }
2
public static node Huffman(ArrayList<node> list){//Creates tree and returns root int n = list.size(); node x = eMin(list); node y = eMin(list); node no = new node(); no.l = x; no.r = y; no.val = x.val + y.val; no.frequency = x.frequency+y.frequency; list.add(no); if(list.size()> 1) no = Huffman(list);//recursion return no; }
1
private void sendToAll(ChatMsg input) { byte[] data = new byte[UTF_CHAT_MSG_BYTESIZE]; try { data = input.toString().getBytes("UTF-8"); } catch (UnsupportedEncodingException e) { data = input.toString().getBytes(); } for (User u : storageServices.getUserList()) { try { DatagramSocket socket = new DatagramSocket(); DatagramPacket output = new DatagramPacket(data, data.length, u.host, udpPort); socket.send(output); } catch (IOException e) { e.printStackTrace(); } } }
3
public void initiateRemoval() { if(this.isRemoving()) return; try { List<Appointment> aAppt = Appointment.findByVenue(this.getId()); // if no user is concerned, finalize it if(aAppt.size() <= 0) { this.finalizeRemovalWithoutChecking(); return; } this.aWaitingId.clear(); for(Appointment appt:aAppt) { this.aWaitingId.add(appt.initiatorId); VenueRemovalInitiated notification = new VenueRemovalInitiated(this); Notification.add(appt.initiatorId, notification); } this.save(); } catch (SQLException e) { e.printStackTrace(); } }
4
@Override public void onCompleted( EntityConcentrationMap data ) { for(EntityGroup group : data.getAllGroups()) { if(!mSettings.matchesWarn(group)) continue; mReporter.reportGroup(mSettings, group.getEntities().size(), group.getLocation()); } mReporter.groupDone(mSettings); }
2
final public void Function_name() throws ParseException { /*@bgen(jjtree) Function_name */ SimpleNode jjtn000 = new SimpleNode(JJTFUNCTION_NAME); boolean jjtc000 = true; jjtree.openNodeScope(jjtn000); jjtn000.jjtSetFirstToken(getToken(1)); try { Identifier(); } catch (Throwable jjte000) { if (jjtc000) { jjtree.clearNodeScope(jjtn000); jjtc000 = false; } else { jjtree.popNode(); } if (jjte000 instanceof RuntimeException) { {if (true) throw (RuntimeException)jjte000;} } if (jjte000 instanceof ParseException) { {if (true) throw (ParseException)jjte000;} } {if (true) throw (Error)jjte000;} } finally { if (jjtc000) { jjtree.closeNodeScope(jjtn000, true); jjtn000.jjtSetLastToken(getToken(0)); } } }
8
public Object getValue (HashMap<String,HashMap<String,Object>> map, String mainKey, String nodeKey) { // do mainKey exist? if(!map.containsKey(mainKey)) { return false; } HashMap<String,Object> obj = map.get(mainKey); if(!obj.containsKey(nodeKey)) { return false; } Object value = obj.get(nodeKey); // Null check if(value == null) { value = false; } return value; }
3
@Override public void loadOp() throws DataLoadFailedException { ConfigurationSection sec = getData(specialYamlConfiguration, "op"); YamlPermissionBase permBase = new YamlPermissionOp(sec); load(PermissionType.OP, permBase); }
0
public String nextCDATA() throws JSONException { char c; int i; StringBuffer sb = new StringBuffer(); for (;;) { c = next(); if (end()) { throw syntaxError("Unclosed CDATA"); } sb.append(c); i = sb.length() - 3; if (i >= 0 && sb.charAt(i) == ']' && sb.charAt(i + 1) == ']' && sb.charAt(i + 2) == '>') { sb.setLength(i); return sb.toString(); } } }
6
public static void handleEvent(int eventId) { if(eventId == 1) { System.out.println("Level one selected"); } else if(eventId == 2) { System.out.println("Level two selected"); } else if(eventId == 3) { System.out.println("Level three selected"); } else if(eventId == 4) { System.out.println("Level four selected"); } else if(eventId == 5) { System.out.println("Exit level selector menu selected"); Main.levelSelectorMenu.setVisible(false); Main.levelSelectorMenu.setEnabled(false); Main.levelSelectorMenu.setFocusable(false); Main.mainFrame.remove(Main.levelSelectorMenu); Main.mainFrame.add(Main.mainMenu); Main.mainMenu.setVisible(true); Main.mainMenu.setEnabled(true); Main.mainMenu.setFocusable(true); Main.mainMenu.requestFocusInWindow(); } }
5
public static void load() { File file = new File(Shortcuts.dataFolder, "bannedPlayers.dat"); if (!file.exists()) { return; } FileInputStream fis = null; ObjectInputStream ois = null; try { fis = new FileInputStream(file); ois = new ObjectInputStream(fis); bannedPlayers = (HashMap<String, Long>) ois.readObject(); } catch (Exception e) { e.printStackTrace(); } finally { try { if (ois != null) { ois.close(); } } catch (Exception e) { //Fail silently } try { if (fis != null) { fis.close(); } } catch (Exception e) { //Fail silently } } }
6
private boolean isEdgeNode(int index) { int x = index % width; int y = index / width; boolean isValid = false; if( (x == 0 || x == width - 1) && (y > 0 && y < height - 2) ) { isValid = true; } else if( (y == 0 || y == height - 1) && (x > 0 && x < width - 2) ) { isValid = true; } else { isValid = false; } return isValid; }
8
public void storageAreaCardBackgroundSetter(List<String> backgrounds){ for(int i=0; i<backgrounds.size(); i++){ storageAreaCardsJlabelList.get(i).setIcon(new ImageIcon((URL)this.getClass().getResource(backgrounds.get(i)))); storageAreaCardsJlabelList.get(i).addMouseListener(new MouseListener() { @Override public void mouseReleased(MouseEvent e) { // TODO Auto-generated method stub } @Override public void mousePressed(MouseEvent e) { // TODO Auto-generated method stub } @Override public void mouseExited(MouseEvent e) { // TODO Auto-generated method stub } @Override public void mouseEntered(MouseEvent e) { // TODO Auto-generated method stub } @Override public void mouseClicked(MouseEvent e) { JLabel label = (JLabel)e.getSource(); if(label.isEnabled()) { if(alhambraFirst){ for(int j=0; j<storageAreaCardsJlabelList.size(); j++){ if(storageAreaCardsJlabelList.get(j).equals(label)){ selectedStorage = j; } } client.sendMessage("switchBuilding;"+matrixX+";"+matrixY+";"+selectedStorage, client.getOs()); alhambraFirst = false; }else{ storageFirst = true; for(int j=0; j<storageAreaCardsJlabelList.size(); j++){ if(storageAreaCardsJlabelList.get(j).equals(label)){ selectedStorage = j; } } } } } }); } for(int i = backgrounds.size(); i < storageAreaCardsJlabelList.size(); i++) { storageAreaCardsJlabelList.get(i).setIcon(new ImageIcon((URL)this.getClass().getResource("/buildingCards/back.jpg"))); } }
8
public void processFrame(ArrayList<Integer> frame) { // Remove all escape characters in the array. for (int i = 0; i < frame.size(); i ++) { //System.out.println("Processing " + String.format("0b%8s", Integer.toBinaryString((int) 0xFF & frame.get(i))).replace(' ', '0') + ""); System.out.print(frame.get(i)); if (frame.get(i)==ESCAPE){ System.out.println("Escaped"); frame.remove(i); i--; } } int toAdress = (int) frame.get(0) & 0xFF; // To ID int fromAdress = (int) frame.get(1) & 0xFF; // From ID int messageType = (int) frame.get(2) & 0xFF; // Message type int dataLength = frame.get(3) & 0xFF; // Data length System.out.println("to: " + toAdress + " from " + fromAdress + " Binary " + Integer.toBinaryString(fromAdress) + " type:" + messageType + " DataLength " + dataLength); // Update attached interfaces if (fromAdress == ECHO){ System.out.println("Echoed"); System.out.println(); } if (attachedInterfaces.containsKey(fromAdress)){ attachedInterfaces.get(fromAdress).setData(frameBuffer.subList(4, 4+dataLength)); attachedInterfaces.get(fromAdress).setReturnCaller(this); // System.out.println("Set timer " + fromAdress); } else { System.out.println("Key " + fromAdress +" did not exist in the " + attachedInterfaces.size() + " keys"); } if ((fromAdress & TIMER) > 0 ){ // System.out.println("From timer."); } if ((fromAdress & GYRO) > 0 ) { // System.out.println("From gyro."); } }
6
public void addLista(AbstractRolamento r, String s) { if(s.equals("Torno") && (r.getEtapa()!=-1)) { listaTorno.add(r); checaPrioridades(listaTorno); checaPrioridades(listaTorno); } if(s.equals("Fresa") && (r.getEtapa()!=-1)) { listaFresa.add(r); checaPrioridades(listaFresa); checaPrioridades(listaFresa); } if(s.equals("Mandril") && (r.getEtapa()!=-1)) { listaMandril.add(r); checaPrioridades(listaMandril); checaPrioridades(listaMandril); } if(s.equals("FIM")) { if(r.getInstante()<=getTempoTotalExecucao()) { System.out.println("Adicionando " + r.getTipo() + " Na ListaFinalizados"); addFinalizados(r); } } }
8
protected void landingOn(PlayerClass pPlayer) { //If you land on it, 100*die*breweries owned if(this.owned == false) // if not owned { if(cout.buyBrewery(this.buyPrice) == true) // prompt the player { pPlayer.account.addBalance(-this.buyPrice, pPlayer.getName(), true); pPlayer.account.addTypeOwned("brewery"); // ensure player knows how many breweries he owns. this.owned = true; this.currentOwner = pPlayer; GUI.setOwner(pPlayer.getPlayerPos(), pPlayer.getName()); } } if(this.owned == true && this.currentOwner != pPlayer) // In case the player doesn't own the property, and someone else does { pPlayer.transaction(this.currentOwner, (this.rent*currentOwner.account.getTypeOwned("brewery")*(GameCore.dice01.diceRoll()+GameCore.dice02.diceRoll()))); // OPTIMIZED, YOU SHITTER } }
4
public EntityComponent getComponent(int id) { Iterator<EntityComponent> it = components.iterator(); while (it.hasNext()) { EntityComponent current = it.next(); if (current.getId() == id) { return current; } } return null; }
2
public void testWeighted(String prefix, int maxIter, int seedSize, double threshold, int noTrees) throws FileNotFoundException { if (noTrees == 0) { noTrees = Integer.MAX_VALUE; } double sumacc = 0.0; // double sumaccw = 0.0; double acc = 0.0; // double accw = 0.0; double prediction = 0.0; int realnoTrees = 0; for (int i = 0; i < noFold; i++) { System.out.println("################ Fold no " + i); Set<Integer> trainingSet = new HashSet<Integer>(sampleIndex); trainingSet.removeAll(foldList.get(i)); // create the forest DecisionTreeController controller = new DecisionTreeController(trainingSet, ppiGraph, storeFile); MetroSampler sampler = new WeightedSamplerMH_Fast(controller); sampler.sample(maxIter, seedSize, threshold); OptimalForest forest = sampler.createForest(threshold, noTrees); realnoTrees += forest.forest.size(); // test using the forest created Set<Integer> testSet = foldList.get(i); // String outputFile = prefix + Integer.toString(i); // PrintStream out = new PrintStream(new FileOutputStream(outputFile)); // String outputFileWeighted = prefix + "weighted_" + Integer.toString(i); // PrintStream outWeighted = new PrintStream(new FileOutputStream(outputFileWeighted)); acc = 0.0; // accw = 0.0; for (Integer s : testSet) { ArrayList<String> sample = sampleInfoStore.get(s); List<String> features = sample.subList(1, sample.size()); Integer classLabel = 0; if (storeFile[s][0]) { classLabel = 1; } // double prediction = forest.weightedClassify(features); prediction = forest.classify(features); // out.println(classLabel + " " + prediction); if (classLabel == 1 && prediction >= 0.5 || classLabel == 0 && prediction < 0.5) { acc += 1; } // prediction = forest.weightedClassify(features); // outWeighted.println(classLabel + " " + prediction); // if (classLabel == 1 && prediction >= 0.5 || // classLabel == 0 && prediction < 0.5){ // accw += 1; // } } acc /= testSet.size(); sumacc += acc; // accw /= testSet.size(); // sumaccw += accw; // out.close(); // outWeighted.close(); } sumacc /= noFold; // sumaccw /= noFold; System.err.println("No Tree: " + (double) realnoTrees / noFold + " Accuracy: " + sumacc); // System.err.println("No Tree: " + (double)realnoTrees/noFold + " AccuracyW: " + sumaccw); }
8
public void scrollCellToView(JTable table, int rowIndex, int vColIndex) { if (!(table.getParent() instanceof JViewport)) { return; } JViewport viewport = (JViewport) table.getParent(); Rectangle rect = table.getCellRect(rowIndex, vColIndex, true); Rectangle viewRect = viewport.getViewRect(); int x = viewRect.x; int y = viewRect.y; if (rect.x >= viewRect.x && rect.x <= (viewRect.x + viewRect.width - rect.width)){ } else if (rect.x < viewRect.x){ x = rect.x; } else if (rect.x > (viewRect.x + viewRect.width - rect.width)) { x = rect.x - viewRect.width + rect.width; } if (rect.y >= viewRect.y && rect.y <= (viewRect.y + viewRect.height - rect.height)){ } else if (rect.y < viewRect.y){ y = rect.y; } else if (rect.y > (viewRect.y + viewRect.height - rect.height)){ y = rect.y - viewRect.height + rect.height; } viewport.setViewPosition(new Point(x,y)); }
9
private boolean newTable(MCDAssociation ass) { if (ass.sizeLink() > 2 || ass.sizeInformation() > 0) return true; boolean porteuse = true; for (Iterator<MCDLien> e = ass.links(); e.hasNext();) if (!((MCDLien) e.next()).getCardMax().equals("N")) porteuse = false; return porteuse; }
4
@Override public boolean equals(Object obj) { if (obj instanceof BulkFood){ BulkFood objFood = (BulkFood)obj; if (objFood.name.equals(this.name) && objFood.unit.equals(this.unit) && objFood.pricePerUnit == this.pricePerUnit && objFood.supply == this.supply) return true; else return false; } else return false; }
5
@Override public BufferedImage[] getClonedObject(String name, Map<String, String> data) { BufferedImage[] oldImages = getObject(name, data); BufferedImage[] newImages = new BufferedImage[oldImages.length]; for(int i = 0; i < oldImages.length; i++){ newImages[i] = oldImages[i].getSubimage(0, 0, oldImages[i].getWidth(), oldImages[i].getHeight()); } return newImages; }
1
public void edit(Room room) throws NonexistentEntityException, Exception { EntityManager em = null; try { em = getEntityManager(); em.getTransaction().begin(); room = em.merge(room); em.getTransaction().commit(); } catch (Exception ex) { String msg = ex.getLocalizedMessage(); if (msg == null || msg.length() == 0) { Long id = room.getId(); if (findRoom(id) == null) { throw new NonexistentEntityException("The room with id " + id + " no longer exists."); } } throw ex; } finally { if (em != null) { em.close(); } } }
5
@Override public void executar() throws Exception { boolean goBack = false; while ( !goBack ) { mostrarOpcions(); int choice = readint("\nOPCIO: "); switch (choice) { case 1: jutgeService.consultarPartides(usuariDni); break; case 2: tancarPartida(); break; case 3: goBack = true; break; case 4: System.exit(0); default: System.out.println("\nValor incorrecte. Si us plau, torna a seleccionar la opció desitjada.\n"); } } }
5
public Medico getMedico() { return medico; }
0
@Test public void testTruncate_null() { Assert.assertEquals(null, _helper.truncate(null, 35)); }
0
public synchronized void sendBinary(Object message) throws IOException { if (trace >= API_TRACE_MESSAGES) { Log.current.println(df.format(new Date()) + "\n Sending request: " + message + " to connection: " + this); } if (logger.isLoggable(Level.FINE)) { logger.fine("sendBinary: " + DefaultCycObject.stringApiValue(message)); } cfaslOutputStream.writeObject(message); cfaslOutputStream.flush(); }
2
private BufferedImage convertGreyscaleToArgb(byte[] data, BufferedImage bi) { // we use an optimised greyscale colour conversion, as with scanned // greyscale/mono documents consisting of nothing but page-size // images, using the ICC converter is perhaps 15 times slower than this // method. Using an example scanned, mainly monochrome document, on this // developer's machine pages took an average of 3s to render using the // ICC converter filter, and around 115ms using this method. We use // pre-calculated tables generated using the ICC converter to map // between // each possible greyscale value and its desired value in sRGB. // We also try to avoid going through SampleModels, WritableRasters or // BufferedImages as that takes about 3 times as long. final int[] convertedPixels = new int[getWidth() * getHeight()]; final WritableRaster r = bi.getRaster(); int i = 0; final int[] greyToArgbMap = getGreyToArgbMap(bpc); if (bpc == 1) { int calculatedLineBytes = (getWidth() + 7) / 8; int rowStartByteIndex; // avoid hitting the WritableRaster for the common 1 bpc case if (greyToArgbMap[0] == 0 && greyToArgbMap[1] == 0xFFFFFFFF) { // optimisation for common case of a direct map to full white // and black, using bit twiddling instead of consulting the // greyToArgb map for (int y = 0; y < getHeight(); ++y) { // each row is byte-aligned rowStartByteIndex = y * calculatedLineBytes; for (int x = 0; x < getWidth(); ++x) { final byte b = data[rowStartByteIndex + x / 8]; final int white = b >> (7 - (x & 7)) & 1; // if white == 0, white - 1 will be 0xFFFFFFFF, // which when xored with 0xFFFFFF will produce 0 // if white == 1, white - 1 will be 0, // which when xored with 0xFFFFFF will produce 0xFFFFFF // (ignoring the top two bytes, which are always set // high anyway) convertedPixels[i] = 0xFF000000 | ((white - 1) ^ 0xFFFFFF); ++i; } } } else { // 1 bpc case where we can't bit-twiddle and need to consult // the map for (int y = 0; y < getHeight(); ++y) { rowStartByteIndex = y * calculatedLineBytes; for (int x = 0; x < getWidth(); ++x) { final byte b = data[rowStartByteIndex + x / 8]; final int val = b >> (7 - (x & 7)) & 1; convertedPixels[i] = greyToArgbMap[val]; ++i; } } } } else { for (int y = 0; y < getHeight(); ++y) { for (int x = 0; x < getWidth(); ++x) { final int greyscale = r.getSample(x, y, 0); convertedPixels[i] = greyToArgbMap[greyscale]; ++i; } } } final ColorModel ccm = ColorModel.getRGBdefault(); return new BufferedImage(ccm, Raster.createPackedRaster(new DataBufferInt(convertedPixels, convertedPixels.length), getWidth(), getHeight(), getWidth(), ((PackedColorModel) ccm).getMasks(), null), false, null); }
9
private final boolean cvc(int i) { if (i < 2 || !cons(i) || cons(i-1) || !cons(i-2)) return false; { int ch = b[i]; if (ch == 'w' || ch == 'x' || ch == 'y') return false; } return true; }
7
public TileMap loadNextMap() { TileMap map = null; while (map == null) { currentMap++; try { if(currentMap==4){ currentMap=1; } map = loadMap( "/maps/map" + currentMap + ".txt"); } catch (IOException ex) { if (currentMap == 1) { // no maps to load! return null; } currentMap = 0; map = null; } } return map; }
4
public void setShuffledState() { Random random = new Random(); for(int i=0;i<20;i++) { switch(random.nextInt(5)) { case 0 : shiftUp(random.nextInt(3)); break; case 1 : shiftDown(random.nextInt(3)); break; case 2 : shiftLeft(random.nextInt(3)); break; case 3 : shiftRight(random.nextInt(3)); break; case 4 : shiftRotate("F", 1); break; case 5 : shiftRotate("F", 3); break; default : break; } } for(int i=0;i<3;i++) { grid[i][0] = -1; grid[i][1] = -1; } main_grid.setColor(color_bg); resetMoves(); goToFront(); }
8
public static void goToUnexplored(){ int x = RobotData.INSTANCE.getLocation().x; int y = RobotData.INSTANCE.getLocation().y; Point coor = PatternCheck.getClosestUnexplored(x, y, map,0); int tarX = coor.x; int tarY = coor.y; //path planning, going to unexplored // pathPlanner = new PathPlanner(posi, rngi, map); map[tarX][tarY] = 3; pathPlanner = new PathPlanner(posi, rngi); pathPlanner.goToPoint(new Point(tarX, tarY)); if(leftSide>1 && frontSide>1 && sonarValues[8]>1){ posi.setSpeed(0,0.15); int a = 0; while (a<430){ a++; try { Thread.sleep(100);} catch (Exception e) {} } } boolean bol=false; posi.setSpeed(0.7, 0); while(!bol){ getSonars(rngi); if(sonarValues[0]<1 ||sonarValues[2]<1){ bol=true; WallFollow(); } try {Thread.sleep(10);} catch (InterruptedException e) {} } }
9
private ForNode For() throws SyntaxException { try { BlockNode init = null; ExpressionNode condition = null; BlockNode<ExpressionNode> step = new BlockNode<ExpressionNode>(); Position pos = iterator.current().coordinates().starting(); nextToken(); LeftBracket(); if (iterator.current().type().is(Token.Type.VAR)) { init = VariableDecl(); } else if (iterator.current().type().is(Token.Type.FirstOfExpression)) { init = new BlockNode<ExpressionNode>(); init.addChild(Expression()); while (iterator.current().type().is(Token.Type.COMMA)) { nextToken(); init.addChild(Expression()); } } Semicolon(); if (iterator.current().type().is(Token.Type.FirstOfExpression)) { condition = Expression(); } Semicolon(); if (iterator.current().type().is(Token.Type.FirstOfExpression)) { step.addChild(Expression()); while (iterator.current().type().is(Token.Type.COMMA)) { nextToken(); step.addChild(Expression()); } } RightBracket(); BlockNode<Statement> code = Code(); return new ForNode(init, condition, step, code, pos); } catch(SyntaxException ex) { throw ex; } catch(Exception ex) { throw (NonAnalysisException)new NonAnalysisException(ex) .initPosition(iterator.current().coordinates().starting()) .Log("ru.bmstu.iu9.compiler.syntax"); } }
8
public Sprite getSprite(String ref) { if (sprites.containsKey(ref)) return sprites.get(ref); BufferedImage sourceImage; try { URL url = this.getClass().getClassLoader().getResource(ref); if (url == null) { System.out.println("Can't find: " + ref); } sourceImage = ImageIO.read(url); GraphicsConfiguration gc = GraphicsEnvironment.getLocalGraphicsEnvironment().getDefaultScreenDevice().getDefaultConfiguration(); Image image = gc.createCompatibleImage(sourceImage.getWidth(),sourceImage.getHeight(),Transparency.BITMASK); image.getGraphics().drawImage(sourceImage, 0, 0, null); Sprite sprite = new Sprite(image); sprites.put(ref, sprite); return sprite; } catch(Exception e) { return null; } }
3
public ArrayList<Tayte> haeTaytelista() throws DAOPoikkeus { ArrayList<Tayte> taytteet = new ArrayList<Tayte>(); // Avataan yhteys Connection yhteys = avaaYhteys(); try { // Haetaan tietokannasta kaikki sinne tallennetut täytteet. String tayteQuery = "select nimi, tayteID from Tayte ORDER BY nimi ASC;"; PreparedStatement haku = yhteys.prepareStatement(tayteQuery); // Suoritetaan haku. ResultSet tulokset = haku.executeQuery(); while (tulokset.next()) { int id = tulokset.getInt("tayteID"); String nimi = tulokset.getString("nimi"); Tayte tayte = new Tayte(nimi, id); taytteet.add(tayte); } } catch(Exception e) { // Tapahtuiko jokin virhe? throw new DAOPoikkeus("Tietokantahaku aiheutti virheen!", e); } finally { // Lopulta aina suljetaan yhteys! suljeYhteys(yhteys); } return taytteet; }
2
public InputStream createIncomingStream(StreamInitiation initiation) throws XMPPException { PacketCollector collector = connection.createPacketCollector( getInitiationPacketFilter(initiation.getFrom(), initiation.getSessionID())); connection.sendPacket(super.createInitiationAccept(initiation, getNamespaces())); CompletionService<InputStream> service = new ExecutorCompletionService<InputStream>(Executors.newFixedThreadPool(2)); List<Future<InputStream>> futures = new ArrayList<Future<InputStream>>(); InputStream stream = null; XMPPException exception = null; try { futures.add(service.submit(new NegotiatorService(collector))); futures.add(service.submit(new NegotiatorService(collector))); int i = 0; while (stream == null && i < futures.size()) { Future<InputStream> future; try { i++; future = service.poll(10, TimeUnit.SECONDS); } catch (InterruptedException e) { continue; } if (future == null) { continue; } try { stream = future.get(); } catch (InterruptedException e) { /* Do Nothing */ } catch (ExecutionException e) { exception = new XMPPException(e.getCause()); } } } finally { for (Future<InputStream> future : futures) { future.cancel(true); } collector.cancel(); } if (stream == null) { if (exception != null) { throw exception; } else { throw new XMPPException("File transfer negotiation failed."); } } return stream; }
9
public void onCommand(CommandSender sender, ChunkyCommand command, String label, String[] args) { if (!(sender instanceof Player)) { Language.IN_GAME_ONLY.bad(sender); return; } if (args.length == 0) { Player player = (Player) sender; displayInfo(ChunkyManager.getChunkyChunk(player.getLocation()), player); return; } if (args.length > 0) { Language.FEATURE_NYI.bad(sender); return; } }
3
public String[][] getStringArrayByQuery(String query) throws SQLException { checkConnection(); if(conn != null) { Statement stmt; try { stmt = conn.createStatement(); ResultSet resSt = stmt.executeQuery(query); ArrayList<String[]> al = new ArrayList<String[]>(); int rowCount = resSt.getMetaData().getColumnCount(); while(resSt.next()) { String[] s = new String[rowCount]; for(int i = 0; i < rowCount; i++) { s[i] = resSt.getString(i+1); } al.add(s); } String[][] ret = new String[al.size()][]; return al.toArray(ret); } catch(SQLException e) { throw e; } } else { throw new SQLException(); } }
4
static final int method1098(int i) { if ((double) Class26.aFloat473 == 3D) { return 37; } if ((double) Class26.aFloat473 == 4D) { return 50; } if ((double) Class26.aFloat473 == 6D) { return 75; } if (i != 37) { return 118; } return (double) Class26.aFloat473 != 8D ? 200 : 100; }
5
public void magicOnItems(int slot, int itemId, int spellId) { switch(spellId) { case 1162: // low alch if(System.currentTimeMillis() - c.alchDelay > 1000) { if(!c.getCombat().checkMagicReqs(49)) { break; } if(itemId == 995) { c.sendMessage("You can't alch coins"); break; } c.getItems().deleteItem(itemId, slot, 1); c.getItems().addItem(995, c.getShops().getItemShopValue(itemId)/3); c.startAnimation(c.MAGIC_SPELLS[49][2]); c.gfx100(c.MAGIC_SPELLS[49][3]); c.alchDelay = System.currentTimeMillis(); sendFrame106(6); addSkillXP(c.MAGIC_SPELLS[49][7] * Config.MAGIC_EXP_RATE, 6); refreshSkill(6); } break; case 1178: // high alch if(System.currentTimeMillis() - c.alchDelay > 2000) { if(!c.getCombat().checkMagicReqs(50)) { break; } if(itemId == 995) { c.sendMessage("You can't alch coins"); break; } c.getItems().deleteItem(itemId, slot, 1); c.getItems().addItem(995, (int)(c.getShops().getItemShopValue(itemId)*.75)); c.startAnimation(c.MAGIC_SPELLS[50][2]); c.gfx100(c.MAGIC_SPELLS[50][3]); c.alchDelay = System.currentTimeMillis(); sendFrame106(6); addSkillXP(c.MAGIC_SPELLS[50][7] * Config.MAGIC_EXP_RATE, 6); refreshSkill(6); } break; case 1155: Obelisks(itemId); break; } }
9
public void op(Object x, Object y) { if (x instanceof double[]) opDouble((double[]) x, (double[]) y); else if (x instanceof int[]) opInt((int[]) x, (int[]) y); else if (x instanceof boolean[]) opBoolean((boolean[]) x, (boolean[]) y); else if (x instanceof byte[]) opByte((byte[]) x, (byte[]) y); else if (x instanceof char[]) opChar((char[]) x, (char[]) y); else if (x instanceof short[]) opShort((short[]) x, (short[]) y); else if (x instanceof long[]) opLong((long[]) x, (long[]) y); else if (x instanceof float[]) opFloat((float[]) x, (float[]) y); else throw new IllegalArgumentException("Datatype is not supported"); }
8
public static ArrayList<String[]> generateStandardPopulation(String popType, int popSize, String missing) { ArrayList<String[]> pedList = new ArrayList<String[]>(); int numlength = Integer.toString(popSize).length(); DecimalFormat format = new DecimalFormat("0000000000".substring(0, numlength)); if (popType.equals(strF1)) { pedList.add(new String[] {"P1",missing,missing}); pedList.add(new String[] {"P2",missing,missing}); for (int i=1; i<=popSize; i++) { pedList.add(new String[] {"F1_"+format.format(i),"P1","P2"}); } } else if (popType.equals(strF2)) { pedList.add(new String[] {"P1",missing,missing}); pedList.add(new String[] {"P2",missing,missing}); pedList.add(new String[] {"F1","P1","P2"}); for (int i=1; i<=popSize; i++) { pedList.add(new String[] {"F2_"+format.format(i),"F1","F1"}); } } else if (popType.equals(strBC)) { pedList.add(new String[] {"P1",missing,missing}); pedList.add(new String[] {"P2",missing,missing}); pedList.add(new String[] {"F1","P1","P2"}); for (int i=1; i<=popSize; i++) { pedList.add(new String[] {"BC_"+format.format(i),"P1","F1"}); } } else if (popType.equals(strS1)) { pedList.add(new String[] {"P1",missing,missing}); for (int i=1; i<=popSize; i++) { pedList.add(new String[] {"S1_"+format.format(i),"P1","P1"}); } } // else no population created return pedList; } //generateStandardPopulation
8
void func_523_a(int var1, int var2, int var3, float var4, byte var5, int var6) { int var7 = (int)((double)var4 + 0.618D); byte var8 = otherCoordPairs[var5]; byte var9 = otherCoordPairs[var5 + 3]; int[] var10 = new int[]{var1, var2, var3}; int[] var11 = new int[]{0, 0, 0}; int var12 = -var7; int var13 = -var7; for(var11[var5] = var10[var5]; var12 <= var7; ++var12) { var11[var8] = var10[var8] + var12; var13 = -var7; while(var13 <= var7) { double var15 = Math.sqrt(Math.pow((double)Math.abs(var12) + 0.5D, 2.0D) + Math.pow((double)Math.abs(var13) + 0.5D, 2.0D)); if(var15 > (double)var4) { ++var13; } else { var11[var9] = var10[var9] + var13; int var14 = this.worldObj.getBlockId(var11[0], var11[1], var11[2]); if(var14 != 0 && var14 != 18) { ++var13; } else { this.worldObj.setBlock(var11[0], var11[1], var11[2], var6); ++var13; } } } } }
5
public static AppWindow getTopWindow() { if (!WINDOW_LIST.isEmpty()) { return WINDOW_LIST.get(0); } return null; }
1
public void setBuyBackMoney(double buyBackMoney){ this.buyBackMoney = buyBackMoney; }
0
public void reconnect() { reconnecting = true; close(); // Attempt reconnects every 5s while (!isConnected()) { try { connect(); } catch (IOException e) { System.err.println("Error when reconnecting: "); e.printStackTrace(); // For debug purposes sleep(5000); } } reconnecting = false; }
2
public boolean submitResponseBipolar(BipolarQuestion bipolarQuestion) { Element bipolarQuestionE; boolean flag = false; for (Iterator i = root.elementIterator("responseToBipolar"); i.hasNext();) { bipolarQuestionE = (Element)i.next(); if (bipolarQuestionE.element("id").getText().equals(bipolarQuestion.getId())) { bipolarQuestionE.element("dialogState").setText(bipolarQuestion.getDialogState()); // Write to xml try { XmlUtils.write2Xml(fileName, document); flag = true; } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } // Copy to public dialog BipolarQuestionDao bipolarQuestionDao = new BipolarQuestionDao(publicFileName); if (bipolarQuestionDao.addResponseToBiPolar(bipolarQuestion, bipolarQuestion.getTeamType())) { flag = true; } else { flag = false; } break; } } return flag; }
4
public void printBoard( boolean[][] b, Tuple<Integer,Integer> currentLight ) { for ( int i = 0; i < 100; i++ ) { for ( int j = 0; j < 100; j++ ) { if ( currentLight != null && currentLight.y == i && currentLight.x == j ) { System.err.print( "*" ); } else { if (b[j][i]) { System.err.print( "." ); } else { //System.err.print( "("+i+","+j+")" ); System.err.print( "#" ); } } } System.err.println( ); } }
6
public InputField() { super(510); setMaximumSize( new Dimension(0, 28) ); setFocusTraversalKeysEnabled(false); addActionListener( new ActionListener() { @Override public void actionPerformed(ActionEvent e) { handleInputText(); } }); addKeyListener( new KeyAdapter() { @Override public void keyPressed(KeyEvent e) { switch ( e.getKeyCode() ) { case KeyEvent.VK_DOWN: case KeyEvent.VK_UP: browseHistory(e); break; case KeyEvent.VK_TAB: completeNickname(e); break; } } }); }
3
public void paint(Graphics g) { Dimension size = getSize(); Color bgColor = getBackground(); if(bgColor != null) { g.setColor(bgColor); g.fillRect(0, 0, size.width, size.height); } if(useCustomImages) { Graphics2D g2 = (Graphics2D) g.create(); BufferedImage image = getOrientation() == JSplitPane.HORIZONTAL_SPLIT ? verticalImage : horizontalImage; int width = image.getWidth(); int height = image.getHeight(); // Create a texture paint from the buffered image Rectangle r = new Rectangle(0, 0, width, height); if(tp == null) { tp = new TexturePaint(image, r); } if(getOrientation() == JSplitPane.HORIZONTAL_SPLIT) { g2.setPaint(tp); g2.fillRect(size.width / 2 - width / 2, 0, width, size.height); } else { g2.setPaint(tp); g2.fillRect(0, size.height / 2 - height / 2, size.width, height); } } else if(drawDelimitors) { // special case : custom integrated dots delimitors if(tp == null) { // Create a buffered image texture patch of size 5x5 BufferedImage bi = new BufferedImage(4, 4, BufferedImage.TYPE_INT_RGB); Graphics2D big = bi.createGraphics(); // Render into the BufferedImage graphics to create the texture big.setColor(getBackground()); big.fillRect(0, 0, 4, 4); big.setColor(highlight); big.fillRect(1, 1, 1, 1); big.setColor(shadow); big.fillRect(2, 2, 1, 1); // Create a texture paint from the buffered image Rectangle r = new Rectangle(0, 0, 4, 4); tp = new TexturePaint(bi, r); big.dispose(); } // g.setColor(shadow); Graphics2D g2 = (Graphics2D) g.create(); // Add the texture paint to the graphics context. g2.setPaint(tp); if(getOrientation() == JSplitPane.HORIZONTAL_SPLIT) { g2.fillRect(size.width / 2 - 2, 0, 4, size.height); } else { g2.fillRect(0, size.height / 2 - 2, size.width, 4); } } //paintDragRectangle(g); super.paint(g); }
8
public static void addMenu() { JSScriptInfo.RemoveAllSriptsFromMenu(); unionRoot = new MenuElement(null, new String[]{CustomMenu.menu_prefix}, resUnion, "Union", "Union functions", 'U', "union_root"); union_menu.setRootElement(unionRoot); /*Здесть насрал Керриган*/ buddyElement = new MenuElement(null, new String[]{CustomMenu.menu_prefix, "buddy_listener"}, buddyRes, "Buddy window", "Toggles buddy window", 'd', "buddybtn"); buddyElement.SetListener(new MenuElemetUseListener(null) { public void use(int button) { if (button == 1) { BuddyWnd.instance.visible = !BuddyWnd.instance.visible; } } }); equipElement = new MenuElement(null, new String[]{CustomMenu.menu_prefix, "equip_listener"}, equipRes, "Equipment window", "Toggles equipment window", 'E', "equipbtn"); equipElement.SetListener(new MenuElemetUseListener(null) { public void use(int button) { if (button == 1) { UI.instance.root.wdgmsg("gk", 5); } } }); charElement = new MenuElement(null, new String[]{CustomMenu.menu_prefix, "char_listener"}, charRes, "Character window", "Toggles character sheet window", 'h', "charbtn"); charElement.SetListener(new MenuElemetUseListener(null) { public void use(int button) { if (button == 1) { if (UI.instance.wnd_char != null) { UI.instance.wnd_char.toggle(); } } } }); optElement = new MenuElement(null, new String[]{CustomMenu.menu_prefix, "opt_listener"}, optRes, "Options window", "Toggles options window", 'O', "optbtn"); optElement.SetListener(new MenuElemetUseListener(null) { public void use(int button) { if (button == 1) { UI.instance.slenhud.toggleopts(); } } }); invElement = new MenuElement(null, new String[]{CustomMenu.menu_prefix, "inv_listener"}, invRes, "Inventory window", "Toggles inventory window", 'I', "invbtn"); invElement.SetListener(new MenuElemetUseListener(null) { public void use(int button) { if (button == 1) { UI.instance.root.wdgmsg("gk", 9); } } }); scriptRootNew = addResource("script_start", "Run Scripts", "You can find all availiable scripts in this menu", 'R', resScript2, unionRoot, new MenuElemetUseListener(null) { public void use(int button) { if (button == 1) { JSScriptInfo.LoadAllSripts(); JSScriptInfo.LoadAllSriptsToMenu(); } } }); scriptRootRem = addResource("script_stop", "Stop Scripts", "You can stop scripts from this menu", 'S', resScript1, unionRoot, null); addResource("toggle_draw_pf_map", "Toggle PF Map", "Do it lol!", 'T', Resource.load("paginae/union/scripts/script2"), unionRoot, new MenuElemetUseListener(null) { public void use(int button) { UI.instance.mapview.toggle_draw_pf(); } }); addResource("stop_all_scripts", "Stop all scripts", "Stops all working scripts", 'T', Resource.load("paginae/union/scripts/script5"), unionRoot, new MenuElemetUseListener(null) { public void use(int button) { JSBot.StopAllScripts(); } }); addResource("hide_all_objects", "Hide ALL Objects", "Do it lol!", 'T', Resource.load("paginae/union/scripts/script2"), unionRoot, new MenuElemetUseListener(null) { public void use(int button) { Config.hide_all = !Config.hide_all; } }); addResource("stop_self_moving", "Stop Movement", "Stops movement immidietly", 'S', Resource.load("paginae/union/scripts/script2"), unionRoot, new MenuElemetUseListener(null) { public void use(int button) { _add_stop_movement(); } }); addResource("replace_player_models", "Replace Models", "Stops movement immidietly", 'R', Resource.load("paginae/union/scripts/script2"), unionRoot, new MenuElemetUseListener(null) { public void use(int button) { replacePlayers(); } }); addResource("print_global_coords", "Print Global Coords", "Print current globalmap coords", 'P', Resource.load("paginae/union/scripts/script2"), unionRoot, new MenuElemetUseListener(null) { public void use(int button) { Coord c = getCurrentRealCoords(); if (c != null) UI.instance.slenhud .error("Current global coords: (" + String.valueOf(c.x / 100) + ", " + String.valueOf(c.y / 100) + ")"); else UI.instance.slenhud.error("Coords not handled"); } }); addResource("auto_aggro_redds", "Agro Enemies", "Aggroes all red points on minimap", 'a', resScript2, unionRoot, new MenuElemetUseListener(null) { @Override public void use(int button) { APXUtils.argoReds(); } }); JSScriptInfo.LoadAllSriptsToMenu(); }
8
public GameLogic(){ for (int i=0; i<9; i++){ this.gameField[i] = 0; } this.isFull = false; this.turn = 1; }
1
public void ge_print(TextArea area,String var,String prefix){ String instr=""; if(!var.equals("-145876239")){ instr = prefix + "%call" + String.valueOf(call_num) + " = call i32 (i8*, ...)* @printf(i8* getelementptr inbounds ([5 x i8]* @.str, i32 0, i32 0), i32 " + var + ")\n"; } else { instr = prefix + "%call" + String.valueOf(call_num) + " = call i32 (i8*, ...)* @printf(i8* getelementptr inbounds ([2 x i8]* @.str1, i32 0, i32 0))\n"; } area.append(instr); call_num = call_num+1; }
1
public HUD(Main main, OrthographicCamera cam) { this.cam = cam; this.main = main; this.character = main.character; //font = TextureRegion.split(Game.res.getTexture("text"), 8, 11)[0]; //font = TextureRegion.split(Game.res.getTexture("text2"), 7, 12)[0]; font = TextureRegion.split(Game.res.getTexture("text3"), 7, 9 )[0]; font2 = TextureRegion.split(Game.res.getTexture("text3"), 7, 9 )[1]; font4 = TextureRegion.split(Game.res.getTexture("text4"), 14, 20 )[0]; textures = Game.res.getTexture("hudTextures"); hearts = new TextureRegion[9]; for (int i = 0; i < hearts.length; i++) hearts[i] = new TextureRegion(textures, i * 19, 78, 19, 19); cubeFrames = new TextureRegion[10]; for (int i = 0; i < cubeFrames.length; i++) cubeFrames[i] = new TextureRegion(textures, i * 11 + 192, 78, 11, 11); cube = new Animation(null); cube.initFrames(cubeFrames, .09f, false); btnHighFrames = new TextureRegion[9]; for (int i = 0; i < btnHighFrames.length; i++) btnHighFrames[i] = new TextureRegion(textures, 0, i * 18 + 361, 238, 11); buttonHigh = new Animation(null); buttonHigh.initFrames(btnHighFrames, .1f, false); inputBGLeft = new TextureRegion(textures, 302, 78, 6, 18); inputBGMid = new TextureRegion(textures, 308, 78, 1, 18); inputBGRight = new TextureRegion(textures, 309, 78, 6, 18); Texture emote = Game.res.getTexture("emotion"); if (emote != null) emotions = TextureRegion.split(emote, 64, 64)[0]; cash = new TextureRegion(textures, 9 * 19, 78, 21, 19); // faceHud = new TextureRegion(textures, 0, 0, 72, 78); // textHud = new TextureRegion(textures, 72, 0, 361, 78); textHud = new TextureRegion(textures, 0, 0, 433, 78); // pauseHud = new TextureRegion(textures, 96, 166, 240, 139); hide(); }
4
@Override public String toString() { String result = ""; for (int y = 0; y < this.image.getHeight() - scale; y += scale) { for (int x = 0; x < this.image.getWidth() - scale; x += scale) { result += pixelToChar(getBlockIntensity(x, y)); } result += System.lineSeparator(); } return result; }
2
public static double[][] getArrayCoordinates(Point[] array){ int n = array.length; int m = array[0].getPointDimensions(); double[][] cc = new double[m][n]; for(int i=0; i<n; i++){ for(int j=0; j<m; j++){ cc[j][i] = (array[i].getPointCoordinates())[j]; } } return cc; }
2
private static void makeLevel(int level) { if (level == 1) { makeLevel1(); } if (level == 2) { makeLevel2(); } if (level == 3) { makeLevel3(); } }
3