text
stringlengths
14
410k
label
int32
0
9
@Override public void mouseEntered(MouseEvent paramMouseEvent) {/**/}
0
private void diffOffering(ArrayList<Change> list, OffRec oldRecord, HashMap<String, Object> session) { String newString = (String) session.get("homeLink"); if (Change.fieldChanged(oldRecord.getLink(), newString)) list.add(OfferingChange.setLink(oldRecord, newString)); boolean newActive = (Boolean) session.get("active"); if (newActive != oldRecord.isActive()) list.add(OfferingChange.setActive(oldRecord, newActive)); long newDuration = getDurationWeeks(session); if (newDuration != oldRecord.getDuration()) list.add(OfferingChange.setDuration(oldRecord, newDuration)); Date newDate = getStartDate(session); if (newDate == null && oldRecord.getStart() != null || newDate != null && !newDate.equals(oldRecord.getStart())) list.add(OfferingChange.setStart(oldRecord, newDate)); }
7
public int next() { lock.lock(); try { ++currentEvenValue; Thread.yield(); // Cause failure faster ++currentEvenValue; return currentEvenValue; } finally { lock.unlock(); } }
0
public static void start(String username, String ip) throws Exception { String title = "Network Communicator : " + username; final String name = username; final int port = 6000; String IP = ip; final JFrame frame = new JFrame(title); JPanel contentPane = new JPanel(new BorderLayout()); textArea = new JTextArea(); lblPort = new JLabel("Port :"); lblIntIP = new JLabel("Internal IP :"); lblExtIP = new JLabel("External IP :"); textArea.setEditable(false); textArea.setLineWrap(true); textArea.setTabSize(2); scrollPane = new JScrollPane(textArea); contentPane.add(scrollPane, BorderLayout.CENTER); frame.setContentPane(contentPane); JPanel panel = new JPanel(); contentPane.add(panel, BorderLayout.NORTH); panel.setLayout(new GridLayout(0, 1, 0, 0)); lblPort.setVerticalAlignment(SwingConstants.TOP); lblPort.setHorizontalAlignment(SwingConstants.LEFT); panel.add(lblPort); panel.add(lblIntIP); panel.add(lblExtIP); JPanel panel_1 = new JPanel(); contentPane.add(panel_1, BorderLayout.SOUTH); panel_1.setLayout(new GridLayout(2, 0, 0, 0)); final JTextField textField = new JTextField(); panel_1.add(textField); JButton btnSend = new JButton("Send"); btnSend.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent arg0) { if (connected) { sendMessage(textField.getText()); textField.setText(""); } } }); panel_1.add(btnSend); textField.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent e) { if (connected) { sendMessage(textField.getText()); textField.setText(""); } } }); textField.requestFocusInWindow(); frame.setDefaultCloseOperation(JFrame.DO_NOTHING_ON_CLOSE); frame.addWindowListener(new WindowAdapter() { @Override public void windowClosing(WindowEvent e) { MainWindow.closeconv(); if (s != null) { try { s.close(); } catch (IOException ex) { } } frame.dispose(); } }); frame.setSize(400, 400); frame.setVisible(true); showIPs(); if (IP.equals("")) { (new Thread() { @Override public void run() { Server.start(Integer.toString(port)); } }).start(); Thread.sleep(1000); InetAddress thisIp = null; NetworkInterface ni = NetworkInterface.getByName("wlan0"); Enumeration<InetAddress> inetAddresses = ni.getInetAddresses(); while(inetAddresses.hasMoreElements()) { InetAddress ia = inetAddresses.nextElement(); if(!ia.isLinkLocalAddress()) { thisIp=ia; } } s = new Socket(thisIp.getHostAddress(), port); lblPort.setText("Port : " + port); } else { s = new Socket(IP, port); } connected = true; out = new ObjectOutputStream(s.getOutputStream()); out.flush(); sendMessage(name); in = new ObjectInputStream(s.getInputStream()); while (MainWindow.workerconv) { try { logToScreen(in.readObject().toString()); Toolkit.getDefaultToolkit().beep(); } catch (Exception ex) { } } }
9
public void addItem(Object obj, String name) { WidgetChooserButton button; if (checkable && selectedNo != -1) { button = (WidgetChooserButton)(layout.itemAt(selectedNo).widget()); button.setChecked(false); } button = new WidgetChooserButton(obj, name, true); if (checkable) { button.setCheckable(true); button.setChecked(true); } button.selected.connect(this, "selected(Object)"); selectedNo = layout.count(); layout.insertWidget(-1, button); objects.add(obj); //button.show(); System.out.println("addItem"+layout.count()); }
3
private void listaArgumentos() { // <lista_argumentos> ::= <argumento> <prox_argumento> | “vazio” “)” // <prox_argumento> ::= “,” <argumento> <prox_argumento> | ")" // <argumento> ::= <id> <compl_tipo_parametro> // <compl_tipo_parametro> ::= <acesso_campo_registro> | <acesso_matriz> // | <chamada_funcao> | λ // <acesso_campo_registro> ::= ”.” <id> // <acesso_matriz> ::= “[“ <indice> “]” <acesso_matriz> | λ // <indice> ::= <inteiro> | <id> if (!acabouListaTokens()) { nextToken(); if (tipoDoToken[1].equals(" vazio")) { if (!acabouListaTokens()) { nextToken(); if (tipoDoToken[1].equals(" )")) { if(!checaSeExisteFuncaoComEsteNome(nmFunc)){ System.out.println("ERRO na linha: "+ tipoDoToken[3] + " ESTA FUNÇÃO NÃO FOI DECLARADA!"); }else{ if(!checaParametros(nmFunc," vazio")){ System.out.println("ERRO na linha: "+ tipoDoToken[3] + " ESTE ARGUMENTO NÃO É VÁLIDO!"); } } System.out.println("TENHO UM ARGUMENTO VAZIO AQUI"); } } else { errosSintaticos.erroFimDeArquivo(tipoDoToken[3], tipoDoToken[1], "atribuição"); zerarTipoToken(); } } else { this.argumento(); this.proxArgumento(); } } else { errosSintaticos.erroFimDeArquivo(tipoDoToken[3], tipoDoToken[1], "atribuição"); zerarTipoToken(); } }
6
public String[] UDP2String(Packet packet) { //Creates a string array with udpPackets UDPPacket udpPacket = (UDPPacket) packet; //Creates a udp packet out of the packet EthernetPacket ethernetPacket = (EthernetPacket) packet.datalink; //Creates and ethernet packet for layer 2 information src_macInEnglish = ethernetPacket.getSourceAddress(); //Gets the string value of the src mac address dst_macInEnglish = ethernetPacket.getDestinationAddress(); //Gets the string value of the dst mac address src_UDPPort = udpPacket.src_port; //Gets the src udp port sourcePortUDP = String.valueOf(src_UDPPort); //creates a string using the port to place in the dataArray dst_UDPPort = udpPacket.dst_port; //Gets the dst port from the packet destinationPortUDP = String.valueOf(dst_UDPPort); //Creates a string from dst_UDPPport src_ip = udpPacket.src_ip; //Gets the inet address from the packet srcIPString = src_ip.toString(); //Converts the InetAddress to a string dst_ip = udpPacket.dst_ip; //Gets the inet dst Ip address from udppacket dstIPString = dst_ip.toString(); //Converts that to a string protocol = udpPacket.protocol; //Grabs the protocol protocolName = "UDP"; //Since this is udp we don't have to worry about other protocols for(int i = 0; i < udpPacket.data.length; i++) { //Runs through the array containing packet data data += String.valueOf((char) udpPacket.data[i]); //Creates a string from every part of that array } dataArray = new String[] {src_macInEnglish, dst_macInEnglish, sourcePortUDP, destinationPortUDP, protocolName, data}; //Array to hold the string data for a table return dataArray; }
1
public void joinChannel(Player p, String channelName) { // Sanity-Check.. if (!ChannelsConfig.getChannels().contains("channels." + channelName)) { Messenger.tell(p, Msg.CUSTOM_CHANNELS_NULL); return; } // Make sure channel is joinable, or if a player has a bypass permission. if (isJoinable(channelName) || p.hasPermission("playerchat.join.bypass")) { // If the channel specified doesn't contain the player, then add them. if (customChannel.containsKey(p.getName())) { Messenger.tell(p, Msg.MISC_ALREADY_IN_CHANNEL); } else { customChannel.put(p.getName(), channelName); Messenger.tell(p, Msg.CUSTOM_CHANNELS_ENTERED); for (Player player : Bukkit.getOnlinePlayers()) { if (customChannel.get(player.getName()).equalsIgnoreCase(customChannel.get(p.getName()))) { // Notify everyone else in the channel. Messenger.tell(player, Msg.CUSTOM_CHANNELS_PLAYER_JOINED, p.getName()); } } } } else { Messenger.tell(p, Msg.CUSTOM_CHANNELS_JOIN_DISABLED); } }
6
protected Calendar getCalendarFromArg(String dateString) { Calendar result = null; if (banUntilDate) { try { result = Calendar.getInstance(); result.setTime(banDateParser.parse(dateString)); } catch (ParseException e) { log.log(Level.SEVERE, "Error parsing given date({0})!", dateString); } } else { result = UntilStringParser.parse(dateString); } return result; }
2
public static void openURL(String url) { String os = System.getProperty("os.name").toLowerCase(); Runtime rt = Runtime.getRuntime(); try { if (os.indexOf("win") >= 0) { rt.exec("rundll32 url.dll,FileProtocolHandler " + url); } else if (os.indexOf("mac") >= 0) { rt.exec("open " + url); } else if (os.indexOf("nix") >=0 || os.indexOf( "nux") >=0) { String[] browsers = {"epiphany", "firefox", "mozilla", "konqueror", "netscape","opera","links","lynx", "chrome"}; StringBuffer cmd = new StringBuffer(); for (int i = 0; i < browsers.length; i++) { cmd.append((i==0 ? "" : " || " ) + browsers[i] + " \"" + url + "\" "); } rt.exec(new String[] { "sh", "-c", cmd.toString() }); } else { return; } } catch (Exception e) { NavalBattle.getDebugWindow().printError(e.getMessage()); return; } }
7
@Override protected void drawInternalU(UGraphic ug, Area area, boolean withShadow) { final Dimension2D dimensionToUse = area.getDimensionToUse(); final StringBounder stringBounder = ug.getStringBounder(); final int textHeight = (int) getTextHeight(stringBounder); ug.getParam().setColor(getForegroundColor()); ug.getParam().setBackcolor(getForegroundColor()); final int x2 = (int) dimensionToUse.getWidth(); if (getArrowConfiguration().isDotted()) { stroke(ug, 5, 2); } else { ug.getParam().setStroke(new UStroke(2)); } ug.draw(2, textHeight, new ULine(x2 - 4, 0)); ug.getParam().setStroke(new UStroke()); final int direction = getDirection(); final UPolygon polygon = new UPolygon(); if (getArrowConfiguration().getHead() == ArrowHead.ASYNC) { ug.getParam().setStroke(new UStroke(1.5)); if (direction == 1) { if (getArrowConfiguration().getPart() != ArrowPart.BOTTOM_PART) { ug.draw(x2 - getArrowDeltaX2(), textHeight - getArrowDeltaY2(), new ULine(getArrowDeltaX2(), getArrowDeltaY2())); } if (getArrowConfiguration().getPart() != ArrowPart.TOP_PART) { ug.draw(x2 - getArrowDeltaX2(), textHeight + getArrowDeltaY2(), new ULine(getArrowDeltaX2(), -getArrowDeltaY2())); } } else { if (getArrowConfiguration().getPart() != ArrowPart.BOTTOM_PART) { ug.draw(getArrowDeltaX2(), textHeight - getArrowDeltaY2(), new ULine(-getArrowDeltaX2(), getArrowDeltaY2())); } if (getArrowConfiguration().getPart() != ArrowPart.TOP_PART) { ug.draw(getArrowDeltaX2(), textHeight + getArrowDeltaY2(), new ULine(-getArrowDeltaX2(), -getArrowDeltaY2())); } } ug.getParam().setStroke(new UStroke()); } else if (direction == 1) { createPolygonNormal(textHeight, x2, polygon); } else { createPolygonReverse(textHeight, polygon); } ug.draw(0, 0, polygon); getTextBlock().drawU(ug, getMarginX1(), 0); }
8
public static boolean containsSubstring(final String[] arr, String search) { if (search == null) return false; search = search.toLowerCase(); for (String s : arr) { if (s == null) continue; s = s.toLowerCase(); if (s.contains(search) || search.contains(s)) return true; } return false; }
5
private void doubleArray() { Object[] tempArray = new Object[array.length * 2]; for (int i = 0; i < size(); i++) { tempArray[i] = array[i]; } array = tempArray; }
1
public void setConsignmentId(int consignmentId) { this.consignmentId = consignmentId; }
0
public String getIpAddress() { return this.ipAddress; }
0
public BufferedImage[] getPaintImages(String theme) { BufferedImage[] images = null; String line; ArrayList imageNames = new ArrayList(); try { InputStream in = getClass().getResourceAsStream(GameController.CONFIG_DIR + config); BufferedReader br = new BufferedReader(new InputStreamReader(in)); while ((line = br.readLine()) != null) { if (line.length() == 0) { continue; } if (line.startsWith("//")) { continue; } StringTokenizer tokens = new StringTokenizer(line); if (tokens.countTokens() == 1) { String[] nameParts = line.split("/"); if(nameParts[0].equals(theme)) { imageNames.add(nameParts[1]); } } else if (tokens.countTokens() == 3) { } else if(tokens.countTokens() == 4) { } else { EIError.debugMsg("wrong config argument count", EIError.ErrorLevel.Error); } } in.close(); images = new BufferedImage[imageNames.size()]; for(int i = 0; i < imageNames.size(); i++) { images[i] = loadImage(worldImagePath+theme+"/"+imageNames.get(i)); } } catch (Exception e) { System.err.println("Error: " + e.getMessage()); } // try { // String[] imageNames = ResourceList.getResourceListing(WorldImagePainting.class, worldImagePath+theme+"/"); // int count = 0; // for(int i = 0; i < imageNames.length; i++) { // if(!imageNames[i].equals(".svn")) { // count++; // } // } // images = new BufferedImage[count]; // count = 0; // for(int i = 0; i < imageNames.length; i++) { // if(!imageNames[i].equals(".svn")) { // images[count] = loadImage(worldImagePath+theme+"/"+imageNames[i]); // count++; // } // } // } catch (Exception e) { // System.err.println("Error: " + e.getMessage()); // } return images; }
9
public LinkedList<Diff> diff_lineMode(String text1, String text2, long deadline) { // Scan the text on a line-by-line basis first. LinesToCharsResult b = diff_linesToChars(text1, text2); text1 = b.chars1; text2 = b.chars2; List<String> linearray = b.lineArray; LinkedList<Diff> diffs = diff_main(text1, text2, false, deadline); // Convert the diff back to original text. diff_charsToLines(diffs, linearray); // Eliminate freak matches (e.g. blank lines) diff_cleanupSemantic(diffs); // Rediff any replacement blocks, this time character-by-character. // Add a dummy entry at the end. diffs.add(new Diff(Operation.EQUAL, "")); int count_delete = 0; int count_insert = 0; String text_delete = ""; String text_insert = ""; ListIterator<Diff> pointer = diffs.listIterator(); Diff thisDiff = pointer.next(); while (thisDiff != null) { switch (thisDiff.operation) { case INSERT: count_insert++; text_insert += thisDiff.text; break; case DELETE: count_delete++; text_delete += thisDiff.text; break; case EQUAL: // Upon reaching an equality, check for prior redundancies. if (count_delete >= 1 && count_insert >= 1) { // Delete the offending records and add the merged ones. pointer.previous(); for (int j = 0; j < count_delete + count_insert; j++) { pointer.previous(); pointer.remove(); } for (Diff newDiff : diff_main(text_delete, text_insert, false, deadline)) { pointer.add(newDiff); } } count_insert = 0; count_delete = 0; text_delete = ""; text_insert = ""; break; } thisDiff = pointer.hasNext() ? pointer.next() : null; } diffs.removeLast(); // Remove the dummy entry at the end. return diffs; }
9
public static String unescape(String string) { int length = string.length(); StringBuffer sb = new StringBuffer(); for (int i = 0; i < length; ++i) { char c = string.charAt(i); if (c == '+') { c = ' '; } else if (c == '%' && i + 2 < length) { int d = JSONTokener.dehexchar(string.charAt(i + 1)); int e = JSONTokener.dehexchar(string.charAt(i + 2)); if (d >= 0 && e >= 0) { c = (char)(d * 16 + e); i += 2; } } sb.append(c); } return sb.toString(); }
6
void NNIupdateAverages( double[][] A, edge e, edge par, edge skew, edge swap, edge fixed ) { node v; edge elooper; v = e.head; //first, v A[e.head.index][e.head.index] = (swap.bottomsize* ((skew.bottomsize*A[skew.head.index][swap.head.index] + fixed.bottomsize*A[fixed.head.index][swap.head.index]) / e.bottomsize) + par.topsize* ((skew.bottomsize*A[skew.head.index][par.head.index] + fixed.bottomsize*A[fixed.head.index][par.head.index]) / e.bottomsize) ) / e.topsize; // next, we loop over all the edges // which are below e elooper = e.findBottomLeft(); while ( e != elooper ) { A[e.head.index][elooper.head.index] = A[elooper.head.index][v.index] = (swap.bottomsize*A[elooper.head.index][swap.head.index] + par.topsize*A[elooper.head.index][par.head.index]) / e.topsize; elooper = depthFirstTraverse(elooper); } // next we loop over all the edges below and // including swap elooper = swap.findBottomLeft(); while (swap != elooper) { A[e.head.index][elooper.head.index] = A[elooper.head.index][e.head.index] = (skew.bottomsize * A[elooper.head.index][skew.head.index] + fixed.bottomsize*A[elooper.head.index][fixed.head.index]) / e.bottomsize; elooper = depthFirstTraverse(elooper); } // now elooper = skew A[e.head.index][elooper.head.index] = A[elooper.head.index][e.head.index] = (skew.bottomsize * A[elooper.head.index][skew.head.index] + fixed.bottomsize* A[elooper.head.index][fixed.head.index]) / e.bottomsize; // finally, we loop over all the edges in the tree // on the far side of parEdge elooper = root.leftEdge; while ((elooper != swap) && (elooper != e)) //start a top-first traversal { A[e.head.index][elooper.head.index] = A[elooper.head.index][e.head.index] = (skew.bottomsize * A[elooper.head.index][skew.head.index] + fixed.bottomsize* A[elooper.head.index][fixed.head.index]) / e.bottomsize; elooper = topFirstTraverse(elooper); } // At this point, elooper = par. // We finish the top-first traversal, excluding the subtree below par elooper = par.moveUpRight(); while ( null != elooper ) { A[e.head.index][elooper.head.index] = A[elooper.head.index][e.head.index] = (skew.bottomsize * A[elooper.head.index][skew.head.index] + fixed.bottomsize* A[elooper.head.index][fixed.head.index]) / e.bottomsize; elooper = topFirstTraverse(elooper); } }
5
private boolean cmdGlobalRules(CommandSender sender) { try { String[] rules = WebUtils.readContentsToArray(new URL("http://server.mcforge.net/gcrules.txt")); for (int i = 0; i < rules.length; i++) { sender.sendMessage(rules[i].replace('&', ChatColor.COLOR_CHAR)); } rules = null; } catch (IOException e) { sender.sendMessage("An error occured!"); e.printStackTrace(); return true; } plugin.getPlayerHandler().addPlayer(sender.getName()); plugin.getPlayerHandler().setReadRules(sender.getName(), true); return true; }
2
private void append(int x, int y, String s) { if (!isValidPosition(x,y)) return; if (!w[x][y].contains(s)) { w[x][y] += s; } }
2
public void simulateOneStep() { step++; // Provide space for newborn actors. List<Actor> newActors = new ArrayList<Actor>(); // avoid being being interrupted try{ if (actors != null) { // Let all actors act. for(Iterator<Actor> it = actors.iterator(); it.hasNext();) { Actor actor = it.next(); actor.act(newActors); if (actor instanceof Animal) // check if actor is an animal { Animal animal = (Animal) actor; if(! animal.isAlive()) { it.remove(); } } else if (actor instanceof Plant) { Plant plant = (Plant) actor; if(! plant.isAlive()) { it.remove(); } } } } } catch (ConcurrentModificationException e) { simulateOneStep(); } // Add the newly born foxes and rabbits to the main lists. actors.addAll(newActors); view.showStatus(step, field); }
7
@Override public boolean invoke(MOB mob, List<String> commands, Physical givenTarget, boolean auto, int asLevel) { MOB target=mob; if((auto)&&(givenTarget!=null)&&(givenTarget instanceof MOB)) target=(MOB)givenTarget; if(target.fetchEffect(this.ID())!=null) { mob.tell(target,null,null,L("<S-YOUPOSS> skin is already hard.")); return false; } if(!super.invoke(mob,commands,givenTarget,auto,asLevel)) return false; boolean success=proficiencyCheck(mob,0,auto); if(success) { invoker=mob; final CMMsg msg=CMClass.getMsg(mob,target,this,verbalCastCode(mob,target,auto),auto?L("<T-YOUPOSS> skin hardens!"):L("^S<S-NAME> chant(s) to <T-NAMESELF> and <T-HIS-HER> skin hardens!^?")); if(mob.location().okMessage(mob,msg)) { mob.location().send(mob,msg); success=beneficialAffect(mob,target,asLevel,0)!=null; target.location().recoverRoomStats(); } } else return beneficialWordsFizzle(mob,target,L("<S-NAME> chant(s) to <T-NAMESELF>, but nothing happens")); // return whether it worked return success; }
8
public List<Recipe> getRecipeList() { if (recipeList == null) { recipeList = restClientBean.getRecipeClient().getAll(); } return recipeList; }
1
public void render(Screen screen) { if (Player.target != null) { if (!Player.target.removed) { screen.renderItem(Player.target.x - 16, Player.target.y - 16, Sprite.crosshairs); } else { Player.target = null; } } //Drawing a circle: if (Player.aiming) { screen.renderItem(Mouse.mse.x - 16, Mouse.mse.y - 16, Sprite.crosshairs); for (int y = Mouse.mse.y - Player.circleSize; y <= Mouse.mse.y + Player.circleSize; y++) { for (int x = Mouse.mse.x - Player.circleSize; x <= Mouse.mse.x + Player.circleSize; x++) { if (Entity.distance(x, y, Mouse.mse.x, Mouse.mse.y) == Player.circleSize) { screen.renderPixel(x, y, 0xffFF0000); } } } } if (Player.show) { int x = (screen.width / 2) - 64; screen.renderAbsolute(x, 190, LargeSprite.back); screen.renderBar(x, 191, player.getCastingPercent(), LargeSprite.mana); screen.renderAbsolute(x, 190, LargeSprite.bronze); } screen.renderAbsolute(5, 315, LargeSprite.back); screen.renderBar(5, 316, player.getManaPercent(), LargeSprite.mana); screen.renderAbsolute(5, 315, LargeSprite.bronze); for (int i = 0; i < qSlots.length; i++) { qSlots[i].render(screen); } }
8
public static void main(String[] args) throws IOException, AccumuloException, AccumuloSecurityException, TableExistsException, TableNotFoundException { Instance mock = new MockInstance(); Connector connector = mock.getConnector("root", new PasswordToken( new byte[0])); connector.tableOperations().create("TRIGRAMS"); // set up combiner IteratorSetting combinerSetting = new IteratorSetting(5, "weightCombiner", WeightCombiner.class); combinerSetting.addOption("all", "true"); connector.tableOperations().attachIterator("TRIGRAMS", combinerSetting); BatchWriter writer = connector.createBatchWriter("TRIGRAMS", new BatchWriterConfig()); // ingest data from file File file = new File("src/main/resources/sawyer.txt"); Files.readLines(file, Charsets.UTF_8, new StringLineProcessor(N, writer)); writer.close(); Scanner weightScanner = connector.createScanner("TRIGRAMS", new Authorizations()); Iterator<Map.Entry<Key, Value>> weightIterator = weightScanner .iterator(); while (weightIterator.hasNext()) { weightIterator.next(); } Key nextKey = new Key("The boy"); System.out.print(nextKey.getRow() + " "); int sentencesCount = 0; for (int maxNumberOfWords = 0; maxNumberOfWords < 1000; maxNumberOfWords++) { Scanner scanner = connector.createScanner("TRIGRAMS", new Authorizations()); // why does that not work? Key endKey = new Key(Range.followingPrefix(nextKey.getRow())); scanner.setRange(new Range(nextKey, null)); IteratorSetting iteratorSetting = new IteratorSetting(15, "nextTrigramIterator", TripleNextTrigramIterator.class); scanner.clearScanIterators(); scanner.addScanIterator(iteratorSetting); Iterator<Map.Entry<Key, Value>> iterator = scanner.iterator(); Key currentKey = null; if (iterator.hasNext()) { Map.Entry<Key, Value> entry = iterator.next(); currentKey = entry.getKey(); } scanner.close(); if (currentKey == null) { // could not find any keys with the specified trigram return; } String[] keyComponents = KEY_SEPERATOR_PATTERN.split(currentKey .getRow().toString()); StringBuilder nextKeyBuilder = new StringBuilder(); for (int keyIndex = 1; keyIndex < N - 1; keyIndex++) { nextKeyBuilder.append(keyComponents[keyIndex]); nextKeyBuilder.append(TrigramsMockAccumulo.KEY_SEPARATOR); } nextKey = new Key(nextKeyBuilder.toString() + currentKey.getColumnFamily()); // print value to console String nextWord = URLDecoder.decode(currentKey.getColumnFamily() .toString(), "UTF-8"); boolean endofSentence = PUNCTUATION_PATTERN.matcher(nextWord) .find(); System.out.print(nextWord); if (endofSentence) { if (sentencesCount > RANDOM.nextInt(3)) { System.out.print("\n"); sentencesCount = 0; } else { System.out.print(" "); } sentencesCount++; } else { System.out.print(" "); } } }
7
@Override public void execute(CommandSender sender, String[] args) { if(args.length == 1) { if(args[0].equalsIgnoreCase("version") || args[0].equalsIgnoreCase("ver")) { //output version PluginDescription desc = MojangStatus.getInstance().getDescription(); sender.sendMessage(ChatColor.DARK_AQUA + (ChatColor.BOLD + desc.getName() + ChatColor.AQUA + " version " + desc.getVersion())); return; } else if(args[0].equalsIgnoreCase("reload") && sender.hasPermission("mojangstatus.reload")) { try { config.reload(); sender.sendMessage(ChatColor.GREEN + "Config was reloaded successfully"); } catch (InvalidConfigurationException e) { sender.sendMessage(ChatColor.RED + "Error while reloading the config"); e.printStackTrace(); } return; } } //Just parse the messages from the config and send it one after another sender.sendMessage(parseMessage(config.commandCheckHeader)); sender.sendMessage(parseMessage(config.commandCheckStatusMinecraftNet, ms.getStatus(Service.MINECRAFTNET), false)); sender.sendMessage(parseMessage(config.commandCheckStatusAuthserverMojang, ms.getStatus(Service.AUTHSERVERMOJANG), false)); sender.sendMessage(parseMessage(config.commandCheckStatusSessionserverMojang, ms.getStatus(Service.SESSIONSERVERMOJANG), false)); sender.sendMessage(parseMessage(config.commandCheckStatusSkinsMinecraft, ms.getStatus(Service.SKINSMINECRAFT), false)); if(!ms.getStatus(Service.SESSIONMINECRAFT)) sender.sendMessage(parseMessage(config.commandCheckWarningSessionOffline)); //Warning when session servers are offline else if(!ms.getStatus(Service.AUTHSERVERMOJANG)) sender.sendMessage(parseMessage(config.commandCheckWarningLoginOffline)); //Warning when login servers are offline if(!ms.getStatus(Service.SKINSMINECRAFT)) sender.sendMessage(parseMessage(config.commandCheckWarningSkinsOffline)); //Warning when skin servers are offline sender.sendMessage(parseMessage(config.commandCheckHeader2)); sender.sendMessage(parseMessage(config.commandCheckStatusAuthMojang, ms.getStatus(Service.AUTHMOJANG), true)); sender.sendMessage(parseMessage(config.commandCheckStatusAccountMojang, ms.getStatus(Service.ACCOUNTMOJANG), true)); sender.sendMessage(parseMessage(config.commandCheckStatusLoginMinecraft, ms.getStatus(Service.LOGINMINECRAFT), true)); sender.sendMessage(parseMessage(config.commandCheckStatusSessionMinecraft, ms.getStatus(Service.SESSIONMINECRAFT), true)); }
9
public void insertItem (int val) { if (root==null) root = new Leaf(val); else { Leaf temp = root; while (true) { if (val <= temp.value) { if (temp.left != null) temp=temp.left; else { temp.left = new Leaf(val); break; }//end else }//end if else { if (temp.right != null) temp=temp.right; else { temp.right = new Leaf(val); break; } } }//end while }//end else }
5
public void crearPublicacion(){ ccp = new ControlCrearPublicacion(); //La funcion trim() elimina espacios antes y despues del valor String tpub = thisRequest.getParameter("tPub").trim(); String tit1 = thisRequest.getParameter("tArt1").trim(); String tit2 = thisRequest.getParameter("tArt2").trim(); String tit3 = thisRequest.getParameter("tArt3").trim(); String tit4 = thisRequest.getParameter("tArt4").trim(); String tit5 = thisRequest.getParameter("tArt5").trim(); String tit6 = thisRequest.getParameter("tArt6").trim(); // String titCarta = thisRequest.getParameter("cartaEdit").trim(); Date fpub = Date.valueOf(thisRequest.getParameter("fPub").trim()); Date fechaPub = null; // Cuenta obtenida = cm.iniciarSesion(usuario, contrasenia, "sub"); HttpSession session = thisRequest.getSession(); String u = (String) session.getAttribute("user"); boolean tp = ccp.crearPublicacion(tpub, fpub); boolean a1 = ccp.publicarArticulo(tit1, fpub); boolean a2 = ccp.publicarArticulo(tit2, fpub); boolean a3 = ccp.publicarArticulo(tit3, fpub); boolean a4 = ccp.publicarArticulo(tit4, fpub); boolean a5 = ccp.publicarArticulo(tit5, fpub); boolean a6 = ccp.publicarArticulo(tit6, fpub); if(a1 && a2 && a3 && a4 && a5 && a6 && tp) { out.println("<p>Gracias " + u + ", la creacion de la publicacion fue exitosa.</p>"); out.println("<form method=\"GET\" action=\"menuEditorJefe.html\">"); out.println("<p><input type=\"submit\" value=\"Regresar Menu\"name=\"B2\"></p>"); out.println("</form>"); out.println("</BODY>"); out.println("</HTML>"); } else { out.println("<p>Lo sentimos " + u + ", no se pudo crear la publicacion, intentalo mas tarde.</p>"); out.println("<form method=\"GET\" action=\"menuEditorJefe.html\">"); out.println("<p><input type=\"submit\" value=\"Regresar Menu\"name=\"B2\"></p>"); out.println("</form>"); out.println("</BODY>"); out.println("</HTML>"); } }
7
public static boolean isEmpty(Object[] array) { return (array == null || array.length == 0); }
1
private void formScreen(String action, Connection database, HttpSession session, HttpServletRequest request, PrintWriter webPageOutput) { int descriptionNumber=0; String description=""; Routines.tableStart(false,webPageOutput); if("Change Description".equals(action)) { try { Statement sql=database.createStatement(); ResultSet queryResult; queryResult=sql.executeQuery("SELECT DescriptionNumber " + "FROM playdescriptions " + "ORDER BY Sequence DESC"); int tempDescriptionNumber=0; while(queryResult.next()) { tempDescriptionNumber=queryResult.getInt(1); int currentSequence=0; if("true".equals(request.getParameter(String.valueOf(tempDescriptionNumber)))) { queryResult=sql.executeQuery("SELECT DescriptionNumber,Description " + "FROM playdescriptions " + "WHERE DescriptionNumber=" + tempDescriptionNumber); if(queryResult.first()) { descriptionNumber=queryResult.getInt(1); description=queryResult.getString(2); } else { Routines.writeToLog(servletName,"Unable to find playdescription (" + tempDescriptionNumber + ")",false,context); } } } } catch(SQLException error) { Routines.writeToLog(servletName,"Unable to retrieve playdescription : " + error,false,context); } Routines.tableHeader("Amend details of description",2,webPageOutput); } if("New Description".equals(action)) { Routines.tableHeader("Enter details of new description",2,webPageOutput); } Routines.tableDataStart(true,false,false,true,false,5,0,"scoresrow",webPageOutput); webPageOutput.print("Description"); Routines.tableDataEnd(false,false,false,webPageOutput); Routines.tableDataStart(true,false,false,false,false,75,0,"scoresrow",webPageOutput); webPageOutput.print("<INPUT TYPE=\"TEXT\" NAME=\"descriptionName\" SIZE=\"30\" MAXLENGTH=\"30\" VALUE=\"" + description + "\">"); Routines.tableDataEnd(false,false,true,webPageOutput); Routines.tableEnd(webPageOutput); webPageOutput.println(Routines.spaceLines(1)); Routines.tableStart(false,webPageOutput); Routines.tableHeader("Actions",1,webPageOutput); Routines.tableDataStart(true,true,false,true,false,0,0,"scoresrow",webPageOutput); if("New Description".equals(action)) { webPageOutput.println("<INPUT TYPE=\"SUBMIT\" VALUE=\"Store New Description\" NAME=\"action\">"); } else { webPageOutput.println("<INPUT TYPE=\"SUBMIT\" VALUE=\"Store Changed Description\" NAME=\"action\">"); } webPageOutput.println("<INPUT TYPE=\"SUBMIT\" VALUE=\"Cancel\" NAME=\"action\">"); Routines.tableDataEnd(false,false,true,webPageOutput); Routines.tableEnd(webPageOutput); webPageOutput.println("<INPUT TYPE=\"hidden\" NAME=\"jsessionid\" VALUE=\"" + session.getId() + "\">"); webPageOutput.println("<INPUT TYPE=\"hidden\" NAME=\"skillNumber\" VALUE=\"" + descriptionNumber + "\">"); webPageOutput.println("</FORM>"); }
7
public final void run() { runningThread = Thread.currentThread(); String threadNameOriginal = runningThread.getName(); if (threadNameOriginal == null) threadNameOriginal = "T" + getClass().getSimpleName(); if (threadName != null && !threadName.isEmpty()) runningThread.setName(threadName); else threadName = threadNameOriginal; try { execute(); } catch (InterruptedException ie) { interruptedException = ie; } catch (Throwable t) { runtimeError = t; } finally { if (threadNameOriginal != null && runningThread != null) runningThread.setName(threadNameOriginal); runningThread = null; if (log.isDebugEnabled()) { log.debug(toString()); } if (runtimeError != null) { log.error(threadName + " stopped after unexpected error.", runtimeError); } } }
9
public void genOperationToRConversion(StringBuffer buff, Operation o) { StringBuilder funcbuff = new StringBuilder(); // R operation funcbuff.append(String.format("r.%s<-function(", o.name)); if (o.parameters != null) { Request r = o.parameters.request; if (r.parameter != null) { for (Parameter p : r.parameter) { if (p.mandatory != null && p.isMandatory()) { funcbuff.append(String.format("%s=%s(), ", p.name, convertPrimitiveRTypes(p.type))); } else { funcbuff.append(String.format("%s=NULL, ", p.name)); } } funcbuff.deleteCharAt(funcbuff.length() - 2); funcbuff.append(", exchange=.BetfairEnv$exchange, appKey=.BetfairEnv$appKey, sessionToken=.BetfairEnv$sessionToken"); } else { funcbuff.append("exchange=.BetfairEnv$exchange, appKey=.BetfairEnv$appKey, sessionToken=.BetfairEnv$sessionToken"); } } else { funcbuff.append("exchange=.BetfairEnv$exchange, appKey=.BetfairEnv$appKey, sessionToken=.BetfairEnv$sessionToken"); } funcbuff.append(") {\n"); String functxt = funcbuff.toString(); functxt = WordUtils.wrap(functxt, 80, "\n ", false); buff.append(functxt); // JSON operation StringBuilder parambuff = new StringBuilder(); parambuff.append(String.format(" ret<-json.%s(", o.name)); if (o.parameters != null) { Request r = o.parameters.request; if (r.parameter != null) { for (Parameter p : r.parameter) { parambuff.append(String.format("%s=%s, ", p.name, p.name)); } parambuff.deleteCharAt(parambuff.length() - 2); parambuff .append(", exchange=exchange, appKey=appKey, sessionToken=sessionToken"); } else { parambuff .append("exchange=exchange, appKey=appKey, sessionToken=sessionToken"); } } else { parambuff .append("exchange=exchange, appKey=appKey, sessionToken=sessionToken"); } parambuff.append(")\n"); String paramtxt = parambuff.toString(); paramtxt = WordUtils.wrap(paramtxt, 80, "\n ", false); buff.append(" ").append(paramtxt); buff.append(" toR(ret)\n"); buff.append("}\n\n"); }
8
public static void main(String[] args) { System.out.println(Byte.MIN_VALUE); // 127 System.out.println(Byte.MAX_VALUE); // -128 System.out.println(Short.MIN_VALUE); // 32767 System.out.println(Short.MAX_VALUE); // -32768 System.out.println(Integer.MIN_VALUE); // 2147483647 System.out.println(Integer.MAX_VALUE); // -2147483648 System.out.println(Long.MIN_VALUE); // 9223372036854775807 System.out.println(Long.MAX_VALUE); // -9223372036854775808 }
0
public static boolean hasAtLeastOneMethodWithName(Class<?> clazz, String methodName) { Assert.notNull(clazz, "Class must not be null"); Assert.notNull(methodName, "Method name must not be null"); Method[] declaredMethods = clazz.getDeclaredMethods(); for (Method method : declaredMethods) { if (method.getName().equals(methodName)) { return true; } } Class<?>[] ifcs = clazz.getInterfaces(); for (Class<?> ifc : ifcs) { if (hasAtLeastOneMethodWithName(ifc, methodName)) { return true; } } return (clazz.getSuperclass() != null && hasAtLeastOneMethodWithName(clazz.getSuperclass(), methodName)); }
8
public MongoClient abrirConexion() { if(mongo != null) { return mongo; } try { mongo = new MongoClient(host, puerto); db = mongo.getDB(nombredb); } catch (UnknownHostException e) { e.printStackTrace(); } return mongo; }
2
public static Point invertDirection(Point direction) { Point newDirection = (Point) direction.clone(); newDirection.x *= -1; newDirection.y *= -1; return newDirection; }
0
public void setPaniculata(int paniculata) { this.paniculata = paniculata; }
0
public synchronized void stepOut() { // First we run until the current frame has been evaluated. // Note that we keep holding on to the same frame for testing, // the one that was on the top when this method was called. final Eval2.StackFrame lFrame = getStack().top(); stepcount = 0; breakpoint = false; // Take some steps. steploop: while(!lFrame.isEvaluated() && !excepted) if(stepcount > 0 && breakpoints.breakHere(stack)) { breakpoint = true; break steploop; } else step(); // Now we take a single step to step out of the frame. if(this.hasMoreSteps()) if(stepcount > 0 && breakpoints.breakHere(stack))breakpoint = true; else step(); }
7
@Test public void testEmptyArray() { Conversions.debug = debug; double[] arr = Conversions.convert("{}", double[].class); Assert.assertTrue(arr != null && arr.length == 0); arr = Conversions.convert(" { } ", double[].class); Assert.assertTrue(arr != null && arr.length == 0); arr = Conversions.convert(" {} ", double[].class); Assert.assertTrue(arr != null && arr.length == 0); arr = Conversions.convert(" {} \n", double[].class); Assert.assertTrue(arr != null && arr.length == 0); }
4
@Override public void handleOpenEndedAt( int x, int y ) { if( !itemShown ){ itemShown = true; parent.addItem( line ); } line.setPoint2( x, y ); }
1
public static void deleteDups2(LinkedListNode n) { if(n == null) return; for(LinkedListNode i = n ; i.next != null ; i = i.next) { int original = i.val; for (LinkedListNode j = i; j.next != null;) { if(j.next.val == original) j.next = j.next.next; else j = j.next; } } }
4
public void update() { for(Entity entity : this.entities) entity.update(); this.player.update(); for(int i = 0; i < this.entities.size(); i++) if(this.entities.get(i).shouldRemove) { this.entities.remove(i); i--; } this.lifetime++; if(this.player.gifts == this.KIDS) { Game.instance.setCurrentGui(new GuiGameOver(null, 0, 0, Game.instance.getWidth(), Game.instance.getHeight(), true, this.lifetime)); } }
4
public void run() { try{ while (!client.isClosed()) { // while client is not closed String messageToSend; synchronized(client) { messageToSend = client.getMessageOut(); // Get the message client.setMessageOut(""); } if (client.isClosed()) // Check again if client is closed break; // If it is exit and don't send the message if (messageToSend.length() > 0){// check if message length is >0 out.print(messageToSend); // If it is finally send the message if(client.getInfo()!=null){ System.out.println("Message: "+ messageToSend + "send to: " + client.getInfo().getUsername()); } out.flush(); if (out.checkError()) throw new Exception("Error while sending to client."); } // Sleep for some time synchronized(client) { if (client.getMessageOut().length() == 0) { try{ client.wait(10*(50+(int)(15*Math.random()))*1000); } catch (InterruptedException e) {} } } } }catch (Exception e) { new Logout().execute(client, new String[]{}); } }
8
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(Administrador.class.getName()).log(java.util.logging.Level.SEVERE, null, ex); } catch (InstantiationException ex) { java.util.logging.Logger.getLogger(Administrador.class.getName()).log(java.util.logging.Level.SEVERE, null, ex); } catch (IllegalAccessException ex) { java.util.logging.Logger.getLogger(Administrador.class.getName()).log(java.util.logging.Level.SEVERE, null, ex); } catch (javax.swing.UnsupportedLookAndFeelException ex) { java.util.logging.Logger.getLogger(Administrador.class.getName()).log(java.util.logging.Level.SEVERE, null, ex); } //</editor-fold> /* Create and display the form */ java.awt.EventQueue.invokeLater(new Runnable() { public void run() { new Administrador().setVisible(true); } }); }
6
public ArrayList<Tile> getAdjacentTiles(Tile tile) { ArrayList<Tile> adjacentTiles = new ArrayList<Tile>(); for (Direction direction : Direction.values()) { Tile nextTile = getTile(tile.getGridX() + direction.getXOffset(), tile.getGridY() + direction.getYOffset()); if (nextTile != null) { //null implies that the next tile would be off the board. adjacentTiles.add(nextTile); } } return adjacentTiles; }
2
public void addQuizText(String title,int quizId,ArrayList<String> imageList, ArrayList<Boolean> imageInventoryList,ArrayList<String> soundList, ArrayList<Boolean> soundInventoryList, int narration, String paragraphList, String preNote, String postNote,String goTo, int points, String date, ArrayList<String> answerList, int timestop, String wrong) { Element quizModule = doc.createElement("quiz"); createQuiz(title,quizId,imageList,imageInventoryList,soundList,soundInventoryList,narration,paragraphList,preNote,postNote,quizModule); Element answerModule = doc.createElement("answermodule"); quizModule.appendChild(answerModule); Element answerElement = doc.createElement("answer"); createAnswerModule("Text",goTo,points,date,wrong,timestop,answerElement); answerModule.appendChild(answerElement); for(int i=0;i<answerList.size();i++){ if(!answerList.get(i).equals("")) { Element correctElement = doc.createElement("correct"); correctElement.appendChild(doc.createTextNode(answerList.get(i))); answerElement.appendChild(correctElement); } } }
2
@Override public String confirmationMessage() { Entity e = editor.getMap().getEntityList().getEntityWithUUID(u); String name = e.name; if(name.equals("")) name = "Untitled"; String ret = "Are you sure you would like to edit "+name+"?"; if(e.getPrefabPath() != null) ret += " This entity is currently attached to a prefab, and will be disconnected from its prefab status!"; if(!canBeUndone()) ret += " This operation cannot be undone."; return ret; }
3
public UDPThread(DatagramSocket socket,int size) { this.socket=socket; this.size=size; }
0
private void updateStateRecipeName(List<Keyword> keywords, List<String> terms) { RecipeLearningState nextState; //TODO recipe already exists if (terms.size() > 0) { //I doubt that this code will work, what if last dialog was RA but the user just wants to teach the robot //a new recipe -> further modification needed here. I reset it to last stable version. //Bla, working now, more flags added, yay hacks if (DialogManager.giveDialogManager().getPreviousDialog().getClass().equals(RecipeAssistanceDialog.class) && ((RecipeAssistanceDialog)DialogManager.giveDialogManager().getPreviousDialog()).isTeaching()) { if (((RecipeAssistanceDialog)DialogManager.giveDialogManager().getPreviousDialog()).getRecipeName() != null) { recipeName = ((RecipeAssistanceDialog)DialogManager.giveDialogManager().getPreviousDialog()).getRecipeName(); } } else { recipeName = terms.get(0); } nextState = new RecipeLearningState(); nextState.setCurrentState(RecipeLearning.RL_ASK_COUNTRY_OF_ORIGIN); setCurrentDialogState(nextState); } //theoretically never happens else { //TODO how to extract it from more than one word, keywords vergleich? DialogManager.giveDialogManager().setInErrorState(true); } }
4
public double[] solve(double[] rowValues){ // FIGURE OUT HTF THIS WORKS double A[][] = this.clone().elements; double[] values = new double[this.rowCount]; int N = rowValues.length; for (int k=0; k<N; k++){ int max = k; for (int i = k+1; i<N;i++){ if (Math.abs(A[i][k])>Math.abs(A[max][k])){ max = i; } } swapRows(A, max, k); swapVals(values, max, k); for (int i = k+1; i<N; i++){ double factor = A[i][k]/A[k][k]; values[i] -= factor*values[k]; for (int j=k; j<N; j++){ A[i][j] -= factor*A[k][j]; } } } Matrix temp = new Matrix(A); System.out.println(A); return values; }
5
public static void fix(int[] values) { int aux = 0; for (int i = 0; i < values.length; i++) values[i]--; if (values[1] > values[3]) { aux = values[1]; values[1] = values[3]; values[3] = aux; } if (values[0] > values[2]) { aux = values[0]; values[0] = values[2]; values[2] = aux; } }
3
public Map<MetaEnum, Object> getMeta() { return meta; }
0
private void setControl(byte val) { // System.out.println("SetControl:" + ByteFormatter.formatBits((byte)val)); chr4KMode = ((val & 0x10) == 0x10); int prgMode = ((val >> 2) & 0x3); if (prgMode < 2) { using32PRGBank = true; lowBankFixed = false; } else if (prgMode == 2) { lowBankFixed = true; lowPrgBank = 0; } else { lowBankFixed = false; highPrgBank = (prgData.length / 0x4000) - 1; } mirror = (val & 0x3); if(_ppuRef != null) { // Mirroring (0: one-screen, lower bank; 1: one-screen, upper bank; // 2: vertical; 3: horizontal) switch (mirror) { case 0: _ppuRef.setMirroringMode(0,0,0,0); // all are $2000 break; case 1: _ppuRef.setMirroringMode(1,1,1,1); // all are $2400 break; case 2: _ppuRef.setVerticalMirroringMode(); break; case 3: default: // never gets here _ppuRef.setHorizontalMirroringMode(); break; } } }
7
protected void disconnectInterface( String hostId, String ifId ) { Host h = hosts.get( hostId ); if( h == null ) return; String linkId = h.interfaceLinkIds.get(ifId); if( linkId == null ) return; Link l = links.get(linkId); if( l != null ) { if( hostId.equals(l.host1) && ifId.equals(l.if1) ) { l.host1 = null; l.if1 = null; } if( hostId.equals(l.host2) && ifId.equals(l.if2) ) { l.host2 = null; l.if2 = null; } } h.interfaceLinkIds.remove(ifId); }
7
private Object setValueByType(String param, Class paramType){ if(paramType == String.class){ return param; }else if(paramType == char.class){ return Character.valueOf(param.charAt(0)); }else if(paramType == short.class){ return Short.valueOf(param); }else if(paramType == int.class){ return Integer.valueOf(param); }else if(paramType == int.class){ return Float.valueOf(param); }else if(paramType == int.class){ return Double.valueOf(param); }else if(paramType == int.class){ return Boolean.valueOf(param); }else{ return null; } }
7
public Type checkType(TypeMap tm) { Type t = new Type(); t.typeid = Type.TypeEnum.t_error; Type tmp = e.checkType(tm); if(tmp.OK()) { if(tmp.typeid == Type.TypeEnum.t_pair) { t.typeid = tmp.t2.typeid; } else { if(Type.isDebug) { System.out.println("TypeError! snd: "+tmp.typeid); System.out.println(this); } } } return t; }
3
public final void initializeLookAndFeels() { // if in classpath thry to load JGoodies Plastic Look & Feel try { LookAndFeelInfo[] lnfs = UIManager.getInstalledLookAndFeels(); boolean found = false; for (int i = 0; i < lnfs.length; i++) { if (lnfs[i].getName().equals("JGoodies Plastic 3D")) { found = true; } } if (!found) { UIManager.installLookAndFeel("JGoodies Plastic 3D", "com.jgoodies.looks.plastic.Plastic3DLookAndFeel"); } String os = System.getProperty("os.name"); FontSet fontSet = null; if (os.startsWith("Windows")) { fontSet = FontSets.createDefaultFontSet(new Font( "arial unicode MS", Font.PLAIN, 12)); } else { fontSet = FontSets.createDefaultFontSet(new Font( "arial unicode", Font.PLAIN, 12)); } FontPolicy fixedPolicy = FontPolicies.createFixedPolicy(fontSet); PlasticLookAndFeel.setFontPolicy(fixedPolicy); UIManager .setLookAndFeel("com.jgoodies.looks.plastic.Plastic3DLookAndFeel"); } catch (Throwable t) { try { UIManager.setLookAndFeel(UIManager .getSystemLookAndFeelClassName()); } catch (Exception e) { e.printStackTrace(); } } }
6
private JSONObject parseResponse(final String query) throws NameResolverException { assert query != null; LOG.log(Level.INFO, "Call IAS name resolver: {0}", query); final ClientResourceProxy proxy = new ClientResourceProxy(query, Method.GET); final ClientResource client = proxy.getClientResource(); //client.setChallengeResponse(new ChallengeResponse(ChallengeScheme.HTTP_BASIC, "guest", "sitools2public")); final Client clientHTTP = new Client(Protocol.HTTP); clientHTTP.setConnectTimeout(AbstractNameResolver.SERVER_TIMEOUT); client.setNext(clientHTTP); final Status status = client.getStatus(); if (status.isSuccess()) { JSONObject json; try { json = new JSONObject(client.get().getText()); } catch (IOException ex) { throw new NameResolverException(Status.SERVER_ERROR_INTERNAL, ex); } catch (JSONException ex) { LOG.log(Level.WARNING, "the response of Corot server may changed"); throw new NameResolverException(Status.CLIENT_ERROR_NOT_ACCEPTABLE, ex); } catch (ResourceException ex) { throw new NameResolverException(Status.SERVER_ERROR_SERVICE_UNAVAILABLE, ex); } return json; } else { throw new NameResolverException(status, status.getThrowable()); } }
4
@Override public void run() { if(game != null) { final Color color; final PlayerStatus status; if(game.getWinner() != Player.NONE) { color = UIPlayer.getPlayer(game.getWinner()).getForeground(); status = game.getPlayerStatus(game.getWinner()); } else { color = UIPlayer.getPlayer(game.getCurrentPlayer()).getForeground(); status = game.getPlayerStatus(game.getCurrentPlayer()); } final BufferedImage base; if(status.isAIPlayer()) { base = computer; } else { base = human; } final BufferedImage coloredImg = new BufferedImage(base.getWidth(), base.getHeight(), base.getType()); base.copyData(coloredImg.getRaster()); for(int x = 0; x < coloredImg.getWidth(); ++x) { for(int y = 0; y < coloredImg.getHeight(); ++y) { // colorize white pixels if(coloredImg.getRGB(x, y) == 0xFFFFFFFF) { coloredImg.setRGB(x, y, color.getRGB()); } } } final Image playerImg = coloredImg.getScaledInstance(coloredImg.getWidth()*7, coloredImg.getHeight()*7, Image.SCALE_REPLICATE); // TODO support player names for human players final String name = status.isAIPlayer() ? status.getAI().getName() : "Human"; final String text; if((name.length()-1)*FONT_SIZE > MAX_WIDTH) { text = name.substring(0, (MAX_WIDTH/FONT_SIZE)-3) + "..."; } else { text = name; } final BufferedImage textImg = retroFont.getRetroString(text, color, FONT_SIZE); final BufferedImage targetImg = new BufferedImage( Math.max(textImg.getWidth(), playerImg.getWidth(null)), playerImg.getHeight(null)+(FONT_SIZE+2), coloredImg.getType()); final Graphics2D graphics = targetImg.createGraphics(); graphics.drawImage(playerImg, 0, 0, null); final int fontX = playerImg.getWidth(null) > textImg.getWidth() ? ((playerImg.getWidth(null) - textImg.getWidth()) / 2) : 0; graphics.drawImage(textImg, fontX, playerImg.getHeight(null) + 2, null); statusImg = targetImg; UIPlayerStatus.this.revalidate(); UIPlayerStatus.this.repaint(); } }
9
@Override public void caseAIdentifier(AIdentifier node) { for(int i=0;i<indent;i++) System.out.print(" "); indent++; System.out.println("(Identifier[ " + node + "]"); inAIdentifier(node); if(node.getId() != null) { node.getId().apply(this); } outAIdentifier(node); indent--; for(int i=0;i<indent;i++) System.out.print(" "); System.out.println(")"); }
3
@Override public Boolean call() throws IOException { InputStream is = null; is = updateURL.openStream(); prop.load(is); String version = prop.getProperty("version"); int currentVersion = (normalizeVersion(version)); int runningVersion = (normalizeVersion(GrooveJaar.version)); /*for (byte i =0;i<runningVersion.length;i++){*/ if (currentVersion > runningVersion) return true; /*}*/ return false; }
1
public UIFile(Path uitextfile, Path script, Path authuiTmp, Path basebrdTmp) { if (!FileUtil.control(uitextfile)) { IllegalArgumentException iae = new IllegalArgumentException("The uitextfile must not be null!"); Main.handleUnhandableProblem(iae); } this.authuiTmp = authuiTmp; this.uitextfilepath = uitextfile; this.mod = new UIFileModifier(script, authuiTmp, basebrdTmp); }
1
public void alertObservers(Event e) { for (ColorObserver co : wantsToKnow) { System.out.println("Alerted."); co.alert((ColorEvent) e); } }
1
private void restore(int start, String[] ip, int curNum, String s) { if (start > s.length() || curNum >= 4) { return; } if (curNum == 3) { String last = s.substring(start); if (isValid(last)) { ip[3] = last; String oneResult = ""; for (int i = 0; i < ip.length; i++) { oneResult += String.valueOf(ip[i]); if (i < 3) { oneResult += "."; } } result.add(oneResult); } return; } for (int i = start; i < s.length(); i++) { String num = s.substring(start, i + 1); if (isValid(num)) { ip[curNum] = num; restore(i + 1, ip, curNum + 1, s); } else { return; } } }
8
public void go_temps_reel(){ new Thread(){ public void run(){ while(!terminer){ //si il y a de nouveaux messages dans la file depuis la derni�re mise � jour : if (dernier_nb_messages != filemessages.size()) { vue.maj(); } dernier_nb_messages = filemessages.size(); try { sleep(periode_temps_reel); } catch (InterruptedException e) {} } } }.start(); }
3
public static boolean isTresspass(int s) { if(s==52465) return true; return false; }
1
private Object getValue(Field field) throws Throwable { field.setAccessible(true); Class<?> type = field.getType(); if (type == int[][].class) { return Arrays.toString((int[][]) field.get(this)); } else if (type == int[].class) { return Arrays.toString((int[]) field.get(this)); } else if (type == byte[].class) { return Arrays.toString((byte[]) field.get(this)); } else if (type == short[].class) { return Arrays.toString((short[]) field.get(this)); } else if (type == double[].class) { return Arrays.toString((double[]) field.get(this)); } else if (type == float[].class) { return Arrays.toString((float[]) field.get(this)); } else if (type == Object[].class) { return Arrays.toString((Object[]) field.get(this)); } return field.get(this); }
8
@Override public boolean equals(Object obj) { if (this == obj) return true; if (obj == null) return false; if (getClass() != obj.getClass()) return false; SymbolicName other = (SymbolicName) obj; if (attributes == null) { if (other.attributes != null) return false; } else if (!attributes.equals(other.attributes)) return false; if (name == null) { if (other.name != null) return false; } else if (!name.equals(other.name)) return false; return true; }
9
public List<StudentObj> getStudentNotSubmitted(String classname, int objId, int topicId) { List<StudentObj> items = new LinkedList<StudentObj>(); String sql = "select Student.classname, Student.rollNo, fullname, email from Student inner join Class on Student.classname = Class.classname " + "inner join Assignment on Class.classname = Assignment.classname " + "where Class.obj_id = ? and Assignment.topic_id = ? and (select count(*) from Result where Student.rollNo = Result.rollNo and Assignment.asm_id = Result.asm_id) = 0 "; if(!classname.equals(ALL)){ sql += "and Student.classname = ? "; } sql += "order by Student.classname"; try { connect(); PreparedStatement pre = con.prepareStatement(sql); pre.setInt(1, objId); pre.setInt(2, topicId); if(!classname.equals(ALL)){ pre.setString(3, classname); } try { ResultSet rs = pre.executeQuery(); if (rs != null) { while (rs.next()) { StudentObj item = new StudentObj(); item.setClassname(rs.getString("classname")); item.setRollNo(rs.getString("rollNo")); item.setFullName(rs.getString("fullname")); item.setEmail(rs.getString("email")); items.add(item); } } } catch (Exception ex) { ex.printStackTrace(); } close(); } catch (Exception e) { e.printStackTrace(); } return items; }
6
void takeBack() { //Step 1: Reset sides. side ^= 1; xside ^= 1; //Step 2: Using our history values, reset the piece, color an board states. --hply; Project2_Move_Thompson m = histDat[hply].m; castle = histDat[hply].castle; ep = histDat[hply].ep; fifty = histDat[hply].fifty; color[(int)m.from] = side; if ((m.bits & 32) != 0) piece[(int)m.from] = PAWN; else piece[(int)m.from] = piece[(int)m.to]; //Was it a capture? if (histDat[hply].capture == EMPTY) { color[(int)m.to] = EMPTY; piece[(int)m.to] = EMPTY; } else { color[(int)m.to] = xside; piece[(int)m.to] = histDat[hply].capture; } //Check for our special moves. if ((m.bits & 2) != 0) { int from, to; switch(m.to) { case 62: from = F1; to = H1; break; case 58: from = D1; to = A1; break; case 6: from = F8; to = H8; break; case 2: from = D8; to = A8; break; default: /* shouldn't get here */ from = -1; to = -1; break; } color[to] = side; piece[to] = ROOK; color[from] = EMPTY; piece[from] = EMPTY; } if ((m.bits & 4) != 0) { if (side == LIGHT) { color[m.to + 8] = xside; piece[m.to + 8] = PAWN; } else { color[m.to - 8] = xside; piece[m.to - 8] = PAWN; } } }
9
private static int areaWasted(Rectangle first, Rectangle second) { if (first.width > 0 && first.height > 0 && second.width > 0 && second.height > 0) { long combinedArea = (long) first.width * (long) first.height + (long) second.width * (long) second.height; Rectangle union = first.union(second); long unionArea = (long) union.height * (long) union.width; Rectangle overlap = first.intersection(second); long overlapArea = (long) overlap.height * (long) overlap.width; return (int) ((unionArea - (combinedArea - overlapArea)) * 100L / combinedArea); } return Integer.MAX_VALUE / 2; }
4
public void actionPerformed(ActionEvent e) { //Handle open button action. if (e.getSource() == openButton) { int returnVal = fc.showOpenDialog(FileChooserDemo.this); if (returnVal == JFileChooser.APPROVE_OPTION) { File file = fc.getSelectedFile(); //This is where a real application would open the file. log.append("Opening: " + file.getName() + "." + newline); } else { log.append("Open command cancelled by user." + newline); } log.setCaretPosition(log.getDocument().getLength()); //Handle save button action. } else if (e.getSource() == saveButton) { int returnVal = fc.showSaveDialog(FileChooserDemo.this); if (returnVal == JFileChooser.APPROVE_OPTION) { File file = fc.getSelectedFile(); //This is where a real application would save the file. log.append("Saving: " + file.getName() + "." + newline); } else { log.append("Save command cancelled by user." + newline); } log.setCaretPosition(log.getDocument().getLength()); } }
4
public Object getValueAt(int row, int column) { Variable variable = variableList.get(row); if (column == 0) { return variable.getName(); } else if (column == 1) { return variable.getReplacementName(); } else if (column == 2) { return variable.isObfuscable(); } return null; }
3
@Override public int hashCode() { final int prime = 31; int result = 1; result = prime * result + ((janela == null) ? 0 : janela.hashCode()); result = prime * result + ((luigi == null) ? 0 : luigi.hashCode()); result = prime * result + ((mario == null) ? 0 : mario.hashCode()); return result; }
3
public GrammarToAutomatonConverter() { }
0
int wrap(Graphics g, int width, ArrayList<String> list) { int lastNewLine = 0, lastSpace = 0, w = 0, maxw = 0; for (int i = 0; i < info.length(); ++i) { if (info.charAt(i) == ' ') { w += g.getFontMetrics().stringWidth(info.substring(lastSpace, i + 1)); if (w >= width) { list.add(info.substring(lastNewLine, i)); maxw = Math.max(g.getFontMetrics().stringWidth(list.get(list.size() - 1)), maxw); w = 0; lastNewLine = i + 1; } lastSpace = i + 1; } } if (lastNewLine < info.length()) { list.add(info.substring(lastNewLine)); maxw = Math.max(g.getFontMetrics().stringWidth(list.get(list.size() - 1)), maxw); } list.add(""); return maxw; }
4
void eliminates(K data) { if (data == getRoot().data && getRoot().right == null && getRoot().left == null) { root = null; } else { AVLNode<K> nodetoremover = nodeToRemover(data, getRoot()); System.out.println("Nodo a eliminar " + nodetoremover.data); if (nodetoremover.data == data && nodetoremover.right == null && nodetoremover.left == null) { System.out.println("Nodo eliminar " + getRoot().left.data); root.left = null; } if (nodetoremover.left != null) { AVLNode<K> greaterthanunder = greaterThanUnder(nodetoremover); System.out.println("el mayor de menores es " + greaterthanunder.data); if (greaterthanunder.data == data) { System.out.println("Se eliminara el " + getRoot().left.data); root.left = null; } } else { } } }
8
private static String fromTime(long time) { int days = (int) TimeUnit.MILLISECONDS.toDays(time); int hours = (int) TimeUnit.MILLISECONDS.toHours(time - TimeUnit.DAYS.toMillis(days)); int minutes = (int) TimeUnit.MILLISECONDS.toMinutes(time - TimeUnit.DAYS.toMillis(days) - TimeUnit.HOURS.toMillis(hours)); int seconds = (int) TimeUnit.MILLISECONDS.toSeconds(time - TimeUnit.DAYS.toMillis(days) - TimeUnit.HOURS.toMillis(hours) - TimeUnit.MINUTES.toMillis(minutes)); int milliseconds = (int) (time - TimeUnit.DAYS.toMillis(days) - TimeUnit.HOURS.toMillis(hours) - TimeUnit.MINUTES.toMillis(minutes) - TimeUnit.SECONDS.toMillis(seconds)); StringBuilder builder = new StringBuilder(); if(days > 0) builder.append(days).append('d'); if(hours > 0) builder.append(hours).append('h'); if(minutes > 0) builder.append(minutes).append('m'); if(seconds > 0) builder.append(seconds).append('s'); if(milliseconds > 0 || builder.length() == 0) builder.append(milliseconds).append("ms"); return builder.toString(); }
6
private String ensureFilterType(){ String filterType = null; if(EQ.startsWith(filterName)){ filterType = EQ; }else if(LT.startsWith(filterName)){ filterType = LT; }else if(GT.startsWith(filterName)){ filterType = GT; }else if(CONTAINS.startsWith(filterName)){ filterType = CONTAINS; }else if(EMPTY.startsWith(filterName)){ filterType = EMPTY; }else if(EVEN.startsWith(filterName)){ filterType = EVEN; }else if(FIRST.startsWith(filterName)){ filterType = FIRST; }else if(LAST.startsWith(filterName)){ filterType = LAST; }else if(ODD.startsWith(filterName)){ filterType = ODD; } return filterType; }
9
protected static String getSyncedDelayString(StructStorageStat[] storageStats, StructStorageStat currentStorageStat) { long maxLastSourceUpdate = 0; for (StructStorageStat storageStat : storageStats) { if (storageStat != currentStorageStat && storageStat.getLastSourceUpdate().getTime() > maxLastSourceUpdate) { maxLastSourceUpdate = storageStat.getLastSourceUpdate().getTime(); } } if (maxLastSourceUpdate == 0) { return ""; } if (currentStorageStat.getLastSyncedTimestamp().getTime() == 0) { return " (never synced)"; } int delaySeconds = (int) ((maxLastSourceUpdate - currentStorageStat.getLastSyncedTimestamp().getTime()) / 1000); int day = delaySeconds / (24 * 3600); int remainSeconds = delaySeconds % (24 * 3600); int hour = remainSeconds / 3600; remainSeconds %= 3600; int minute = remainSeconds / 60; int second = remainSeconds % 60; String delayTimeStr; if (day != 0) { delayTimeStr = String.format("%1$d days %2$02dh:%3$02dm:%4$02ds", day, hour, minute, second); } else if (hour != 0) { delayTimeStr = String.format("%1$02dh:%2$02dm:%3$02ds", hour, minute, second); } else if (minute != 0) { delayTimeStr = String.format("%1$02dm:%2$02ds", minute, second); } else { delayTimeStr = String.format("%1$ds", second); } return " (" + delayTimeStr + " delay)"; }
8
@Override public boolean processEndTag(String tag) { boolean ready = false; Boolean inSituationRecord = inTagMap.get(TrafficData.TAG_SITUATION_RECORD); if (inSituationRecord != null) { if (tag.equals(TrafficData.TAG_SITUATION_RECORD)) { ready = true; } else if (inSituationRecord && tag.equals(TrafficData.TAG_TPEG_DESCRIPTOR_TYPE)) { // Handle end condition when we have picked up a descriptor // value. if (!tempType.isEmpty()) { if (tempType.equals(TrafficData.TAG_LOCAL_LINK_NAME)) { localLinkName = temp; } else if (tempType.equals(TrafficData.TAG_LINK_NAME)) { linkName = temp; } else if (tempType.equals(TrafficData.TAG_TOWN_NAME)) { townName = temp; } } } if (inTagMap.containsKey(tag)) { inTagMap.put(tag, false); } } return ready; }
9
public void toggleKey(int KeyCode, boolean isPressed) { if (KeyCode == KeyEvent.VK_W) { up.toggle(isPressed); } if (KeyCode == KeyEvent.VK_S) { down.toggle(isPressed); } if (KeyCode == KeyEvent.VK_A) { left.toggle(isPressed); } if (KeyCode == KeyEvent.VK_D) { right.toggle(isPressed); } if(KeyCode==KeyEvent.VK_ESCAPE){ exit.toggle(isPressed); } }
5
public List<Double> readPointFrames(File svlFile) { List<Double> pointFrames = new ArrayList<>(); BufferedReader fReader = null; try { fReader = new BufferedReader(new FileReader(svlFile)); String data = ""; int index = 0; while((data = fReader.readLine()) != null) { if (data.contains("<point frame=\"")) { String _freq = data.substring(data.indexOf("value=\"")+7, data.indexOf("\" label")); double freq = 0.00; try { freq = Double.parseDouble(_freq.trim()); } catch(NumberFormatException ex){} pointFrames.add(index++, freq); } } }catch (IOException ex) { ex.printStackTrace(); } finally { try{fReader.close();}catch(IOException ex){}; } return pointFrames; }
5
@Override public int hashCode() { int hashKey = key != null ? key.hashCode() : 0; int hashValue = value != null ? value.hashCode() : 0; return (hashKey + hashValue) * hashValue + hashKey; }
2
public boolean solapamentTeoriaPractica(Element e) { boolean grupTeoria = false; if ((e.getGrupo() % 10) == 0) { grupTeoria = true; } for (int i = 0; i < assignacions.size(); ++i) { if (assignacions.get(i).getAssignatura().equals(e.getAssignatura())) { // si es la mateixa assignatura if (assignacions.get(i).getGrupo() != e.getGrupo()) { // i no el mateix element int grup = assignacions.get(i).getGrupo(); if (grupTeoria) { if (grup % 10 != 0) { return true; } } else { if (grup % 10 == 0) { return true; } } } } } return false; }
7
private void MonthBoxActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_MonthBoxActionPerformed int m = MonthBox.getSelectedIndex() + 1; int y = YearBox.getSelectedIndex() + (Calendar.getInstance().get(Calendar.YEAR) - CountYears); int n = m != 2 ? m > 7 ? 30 + m % 2 == 1 ? 0 : 1 : 30 + m % 2 : y % 4 == 0 && y % 100 != 0 || y % 400 == 0 ? 29 : 28; Integer[] Days = new Integer[n]; for (int i = 1; i < n + 1; i++) { Days[i - 1] = i; } DayBox.setModel(new DefaultComboBoxModel(Days)); }//GEN-LAST:event_MonthBoxActionPerformed
7
private void jButton5ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton5ActionPerformed Transferable clipboardContent = getToolkit().getSystemClipboard().getContents(this); if ((clipboardContent != null) && (clipboardContent.isDataFlavorSupported(DataFlavor.stringFlavor))) { try { String tempString; tempString = (String) clipboardContent.getTransferData(DataFlavor.stringFlavor); jTextField3.setText(tempString); } catch (Exception e) { e.printStackTrace(); } } }//GEN-LAST:event_jButton5ActionPerformed
3
public void undo(CardPanel panel) { System.out.println(history); if (!history.isEmpty()) { CardMove toUndo = history.peek(); if (toUndo.undo(this, panel)) { history.pop(); } } }
2
public void render(Screen screen){ for(int y = 0; y < (screen.height / 32) + 32; y++){ for(int x = 0; x < (screen.width / 32); x++){ screen.renderTile(x * 32, y * 32, -1, Tile.rockTile); } } font.render("Character Select", -1, 10, 0xffffffff, 2, true, screen); for(int i = 0; i < 3; i++){ renderPlayerBg(screen, i); //Render player icon in right position font.render(players[i].getName() + " " + players[i].getId(), 14 * (i * 32) + 20, 50, 0xffffff, 1, true, screen); } if(selectedPlayer != null){ font.render(selectedPlayer.getName(), -1, 535, 0xffffffff, 3, true, screen); } }
4
@NotNull public static Expression parse(@NotNull String expression) { ImmutableList.Builder<Label> includes = ImmutableList.builder(); ImmutableList.Builder<Label> excludes = ImmutableList.builder(); String[] split = expression.split("\\s+"); if(split != null && split.length > 0) { for (String labelString : split) { if(labelString == null || labelString.isEmpty()) { //Split can have some weird behavior. So make sure we never get bit by that. //noinspection UnnecessaryContinue continue; } else if(labelString.startsWith("!")) { Label label = new Label(labelString.substring(1)); excludes.add(label); } else { Label label = new Label(labelString); includes.add(label); } } } return new Expression(includes.build(), excludes.build()); }
6
private int handleException(Exception e) { int errno; e.printStackTrace(); if (e instanceof FuseException) { errno = handleErrno(((FuseException) e).getErrno()); if (log != null && log.isDebugEnabled()) { log.debug(e); } } else if (e instanceof BufferOverflowException) { errno = handleErrno(Errno.ERANGE); if (log != null && log.isDebugEnabled()) { log.debug(e); } } else { errno = handleErrno(Errno.EFAULT); if (log != null) { log.error(e); } } return errno; }
7
public static double[][] FrequencyDomain(double[] x) { double[] y = new double[x.length]; int m = (int) (Math.log(x.length) / Math.log(2)); int n, i, i1, j, k, i2, l, l1, l2; double c1, c2, tx, ty, t1, t2, u1, u2, z; n = x.length; i2 = n >> 1; j = 0; // adapted from Paul Bourke's implementation // of a complex to complex FFT for (i = 0; i < n - 1; i++) { if (i < j) { tx = x[i]; ty = y[i]; x[i] = x[j]; y[i] = y[j]; x[j] = tx; y[j] = ty; } k = i2; while (k <= j) { j -= k; k >>= 1; } j += k; } c1 = -1.0; c2 = 0.0; l2 = 1; for (l = 0; l < m; l++) { l1 = l2; l2 <<= 1; u1 = 1.0; u2 = 0.0; for (j = 0; j < l1; j++) { for (i = j; i < n; i += l2) { i1 = i + l1; t1 = u1 * x[i1] - u2 * y[i1]; t2 = u1 * y[i1] + u2 * x[i1]; x[i1] = x[i] - t1; y[i1] = y[i] - t2; x[i] += t1; y[i] += t2; } z = u1 * c1 - u2 * c2; u2 = u1 * c2 + u2 * c1; u1 = z; } c2 = Math.sqrt((1.0 - c1) / 2.0); c2 = -c2; c1 = Math.sqrt((1.0 + c1) / 2.0); } for (i = 0; i < n; i++) { x[i] /= n; y[i] /= n; } // double[] power = new double[n / 2]; for (i = 0; i < power.length; i++) power[i] = x[i] * x[i] + y[i] * y[i]; double nyquist = 22050; double[] freq = new double[power.length]; for (i = 0; i < freq.length; i++) { freq[i] = nyquist * ((double) i) / (freq.length); } double[][] res = new double[2][x.length]; res[0] = freq; res[1] = power; return res; }
9
public Object nextValue() throws JSONException { char c = this.nextClean(); String string; switch (c) { case '"': case '\'': return this.nextString(c); case '{': this.back(); return new JSONObject(this); case '[': this.back(); return new JSONArray(this); } /* * Handle unquoted text. This could be the values true, false, or * null, or it can be a number. An implementation (such as this one) * is allowed to also accept non-standard forms. * * Accumulate characters until we reach the end of the text or a * formatting character. */ StringBuffer sb = new StringBuffer(); while (c >= ' ' && ",:]}/\\\"[{;=#".indexOf(c) < 0) { sb.append(c); c = this.next(); } this.back(); string = sb.toString().trim(); if ("".equals(string)) { throw this.syntaxError("Missing value"); } return JSONObject.stringToValue(string); }
7
public int smallestMultiple() { boolean found = false; int smallestMultiple = 0; for (int i = 2520; !found; i++) { if (isEvenlyDivisible(i)) { found = true; smallestMultiple = i; } } return smallestMultiple; }
2
@Override public void close() throws IOException { super.close(); s.close(); }
0
public void startGather(Vector x, DistVector y) { if (x.size() != y.size()) throw new IllegalArgumentException( "Vectors must be of the same global size"); // Assemble the arrays to send for (int i = 0; i < comm.size(); ++i) if (i != comm.rank()) for (int j = 0; j < recvI[i].length; ++j) recvD[i][j] = x.get(recvI[i][j]); // Start the sends and recieves for (int i = 0; i < comm.size(); ++i) if (i != comm.rank()) { if (send[i]) t[i] = comm.isend(recvD[i], i); if (recv[i]) t[i + comm.size()] = comm.irecv(sendD[i], i); } }
8
public static String shortToLong( String name, Map<String,String> nsAbbreviations ) throws XMLParseException { int lo = name.indexOf(':'); String nsShort, subName; if( lo == -1 ) { nsShort = ""; subName = name; } else if( lo < 1 || lo == name.length()-1 ) { throw new XMLParseException("Can't parse '" + name + "' as namespace name + postfix"); } else { nsShort = name.substring(0,lo); subName = name.substring(lo+1); } String nsLong = (String)nsAbbreviations.get(nsShort); if( nsLong == null ) { if( "".equals(nsShort) ) { throw new XMLParseException("No default namespace for '" + name + "'"); } else { throw new XMLParseException("Unknown namespace name '" + nsShort + "'"); } } return nsLong + subName; }
5
public Direction getFacing() { return (isMoving() || isCancelingMove() || isRecoveringFromCanceledMove() ? moveDirection : facingDirection); }
3
public void _jspService(HttpServletRequest request, HttpServletResponse response) throws java.io.IOException, ServletException { PageContext pageContext = null; HttpSession session = null; ServletContext application = null; ServletConfig config = null; JspWriter out = null; Object page = this; JspWriter _jspx_out = null; PageContext _jspx_page_context = null; try { response.setContentType("text/html"); pageContext = _jspxFactory.getPageContext(this, request, response, null, true, 8192, true); _jspx_page_context = pageContext; application = pageContext.getServletContext(); config = pageContext.getServletConfig(); session = pageContext.getSession(); out = pageContext.getOut(); _jspx_out = out; _jspx_resourceInjector = (org.glassfish.jsp.api.ResourceInjector) application.getAttribute("com.sun.appserv.jsp.resource.injector"); out.write("\n"); out.write("\n"); out.write("\n"); Class.forName("oracle.jdbc.OracleDriver") ; out.write("\n"); out.write("\n"); out.write("\n"); out.write("<html>\n"); out.write(" <HEAD>\n"); out.write(" <TITLE>Client table </TITLE>\n"); out.write(" </HEAD>\n"); out.write("\n"); out.write(" <BODY>\n"); out.write(" <H1>Welcome to Booking Database </H1>\n"); out.write(" \n"); out.write(" "); Connection connection = DriverManager.getConnection( "jdbc:oracle:thin:@fourier.cs.iit.edu:1521:orcl", "mkhan12", "sourov345"); Statement statement = connection.createStatement() ; ResultSet resultset = statement.executeQuery("SELECT * from Booking ") ; out.write("\n"); out.write("\n"); out.write(" <TABLE BORDER=\"1\">\n"); out.write(" <TR>\n"); out.write(" <TH>Booking ID</TH>\n"); out.write(" <TH>Agent ID</TH>\n"); out.write(" <TH>Client ID</TH>\n"); out.write(" <TH>Booking ID</TH>\n"); out.write(" <TH>Resort ID</TH>\n"); out.write(" <TH>Arrival Date</TH>\n"); out.write(" <TH>Departure Date</TH>\n"); out.write(" <TH>Room Type</TH>\n"); out.write(" \n"); out.write(" </TR>\n"); out.write(" "); while(resultset.next()){ out.write("\n"); out.write(" <TR>\n"); out.write(" <TD> "); out.print( resultset.getString(1) ); out.write("</td>\n"); out.write(" <TD> "); out.print( resultset.getString(2) ); out.write("</TD>\n"); out.write(" <TD> "); out.print( resultset.getString(3) ); out.write("</TD>\n"); out.write(" <TD> "); out.print( resultset.getString(4) ); out.write("</TD>\n"); out.write(" <TD> "); out.print( resultset.getString(5) ); out.write("</TD>\n"); out.write(" <TD> "); out.print( resultset.getString(6) ); out.write("</TD>\n"); out.write(" <TD> "); out.print( resultset.getString(7) ); out.write("</TD>\n"); out.write(" <TD> "); out.print( resultset.getString(8) ); out.write("</TD>\n"); out.write(" \n"); out.write(" </TR>\n"); out.write(" "); } out.write("\n"); out.write(" </TABLE>\n"); out.write(" <div id=\"a15\">\n"); out.write(" \n"); out.write(" <form id=\"form6\" name=\"form1\" method=\"post\" action=\"Query....jsp\">\n"); out.write(" <label>\n"); out.write(" <input type=\"submit\" name=\"button\" id=\"button\" value=\"Insert Agent\" />\n"); out.write(" </label>\n"); out.write(" </form>\n"); out.write(" </div> \n"); out.write(" <div id=\"a15\">\n"); out.write(" \n"); out.write(" <form id=\"form6\" name=\"form1\" method=\"post\" action=\"DeleteBooking.jsp\">\n"); out.write(" <label>\n"); out.write(" <input type=\"submit\" name=\"button\" id=\"button\" value=\"Delete Booking\" />\n"); out.write(" </label>\n"); out.write(" </form>\n"); out.write(" </div>\n"); out.write(" </BODY>\n"); out.write("</html>\n"); out.write("\n"); } catch (Throwable t) { if (!(t instanceof SkipPageException)){ out = _jspx_out; if (out != null && out.getBufferSize() != 0) out.clearBuffer(); if (_jspx_page_context != null) _jspx_page_context.handlePageException(t); else throw new ServletException(t); } } finally { _jspxFactory.releasePageContext(_jspx_page_context); } }
6