text
stringlengths
14
410k
label
int32
0
9
public void prepare(CharSequence exp) throws ParseException { algorithm.clear(); final int length = exp.length(); NodeDefinition current_def = null; StringBuilder buffer = new StringBuilder(); for (int i = 0; i < length; i++) { char current_char = exp.charAt(i); if (current_def == null) { /* * Trying to find a compatible node */ try { current_def = nodeFactory.getNodeDefenition(current_char); buffer.append(current_char); } catch (NodeTypeIrresolvableException ignored) {} } else { /* * If current node is still compatible, continuing to append to it. */ if (current_def.compatibleAsBody(current_char)) buffer.append(current_char); /* * Otherwise, trying to find a compatible definition. * * If fail, clearing buffers and repeating cycle with no definition. * */ else { try { current_def = nodeFactory.getNodeDefinition(buffer.charAt(0), current_char); } catch (NodeTypeIrresolvableException e) { algorithm.add(current_def.instance(buffer)); buffer = new StringBuilder(); current_def = null; i--; } } } } if (buffer.length() > 0 && current_def != null) algorithm.add(current_def.instance(buffer)); }
7
public void appendToTail(int x){ ListNode newNode = new ListNode(x); ListNode node = this; while(node.next!=null) { node = node.next; } node.next = newNode; }
1
public void start(BundleContext context) throws Exception { m_context = context; // Create a service tracker to monitor dictionary services. m_tracker = new ServiceTracker(m_context, m_context.createFilter("(&(objectClass=" + DictionaryService.class.getName() + ")" + "(Language=*))"), null); m_tracker.open(); try { System.out.println("Enter a blank line to exit."); String word = ""; BufferedReader in = new BufferedReader(new InputStreamReader(System.in)); // Loop endlessly. while (true) { // Ask the user to enter a word. System.out.print("Enter word: "); word = in.readLine(); // Get the selected dictionary service, if available. DictionaryService dictionary = (DictionaryService) m_tracker.getService(); // If the user entered a blank line, then // exit the loop. if (word.length() == 0) { break; } // If there is no dictionary, then say so. else if (dictionary == null) { System.out.println("No dictionary available."); } // Otherwise print whether the word is correct or not. else if (dictionary.checkWord(word)) { System.out.println("Correct."); } else { System.out.println("Incorrect."); } } } catch (Exception ex) { } }
5
public void testisEmptyLeaf(int count) throws Exception { for (int i = 0; i < 100; i++) { RBtree empt = empty(); if (!empt.isEmpty()) { throw new Exception("FAILURE EMPTY IS NOT EMPTY"); } else { int len = (int)(Math.random() * (10 - 1) + 1); RBtree tree = randomRB( len ); if (tree.isEmpty() && count != 0) { throw new Exception("FAILURE EMPTY TREE HAS AN OBJECT"); } } emptyLeafTest++; } }
4
@Test public void shouldThrowErrorWhenCharactersAreInvalid() throws IOException { //given File tmpFile = folder.newFile(FILENAME); FileOutputStream fileOutputStream = new FileOutputStream(tmpFile, true); CharsetEncoder charsetEncoder = Charset.forName(ENCODING).newEncoder(); OutputStreamWriter writer = new OutputStreamWriter(fileOutputStream, charsetEncoder); //when try { writer.getEncoding(); writer.write("45"); writer.flush(); } finally { writer.close(); } String filePathString = tmpFile.getAbsolutePath(); //then try { FileParser fileParser = new FileParser(filePathString); fileParser.parse(); } catch (GOLException e) { String msg = "Die Datei darf nur aus 0'en und 1'sen bestehen und muss als UTF-16 encodiert sein."; assertEquals(msg, e.getMessage()); } }
1
public void mouseClicked(MouseEvent me) { try { if (me.getSource() == jb_connexion) { login = jtf_login.getText(); password = String.valueOf(jpf_password.getPassword()); System.out.println("Email : "+login); System.out.println("MotDePasse : "+password); User u = null; Connection co = bs.getConnection(); System.out.println("avant IF"); if (User.checkPresence(bs,login,password)) { System.out.println("debut IF"); u = User.findByLogs(login,password,bs); groupe = UserType.findById(u.getId_ut(),bs).getName_ut(); System.out.println("OK : " + groupe); /**/ afficherMenuPrincipal(); setResizable(true); setExtendedState(MAXIMIZED_BOTH); /**/ } else { System.out.println("NON OK"); } } if (me.getSource() == jb_mdp_oublie) { /* * A COMPLETER : * interroger la base de données, * demander à l'élève de "prouver" son identité, * (question/réponse secrètes ?) * changer le mot de passe * et envoyer un mail à l'adresse associée * ou demander de changer le mot de passe */ if (SwingUtilities.isLeftMouseButton(me)) { // statement = connection.createStatement(); // query = "CREATE TABLE table_test (champ1_test VARCHAR(30) NOT NULL, champ2_test INTEGER, PRIMARY KEY (champ1_test))"; // statement.executeUpdate(query); // System.out.println("Creation reussie (create table)"); // query = "INSERT INTO table_test VALUES ('valeur numero 1',2)"; // statement.executeUpdate(query); // System.out.println("Enregistrement 1/2 reussi (insert v1)"); // query = "INSERT INTO table_test VALUES ('valeur numero 2',2)"; // statement.executeUpdate(query); // System.out.println("Enregistrement 2/2 reussi (insert v2)"); // query = "UPDATE table_test SET champ2_test = 1 WHERE champ1_test = 'valeur numero 1'"; // statement.executeUpdate(query); // System.out.println("Modification reussie (update v1)"); // query = "DELETE FROM table_test WHERE champ1_test = 'valeur numero 2'"; // statement.executeUpdate(query); // System.out.println("Effacement reussi (delete v2)"); } if (SwingUtilities.isRightMouseButton(me)) { // statement = connection.createStatement(); // query = "DROP TABLE table_test"; // statement.executeUpdate(query); // System.out.println("Suppression reussie (drop table)"); } } } // catch (SQLException sqle) // { // jl_message.setText("Mauvaise combinaison login/password"); // System.out.println("SQL Exception"); // sqle.printStackTrace(); // // } catch (Exception e) { System.out.println("Exception"); e.printStackTrace(); } }
6
private static JMenu getHelpMenu(EnvironmentFrame frame) { Environment environment = frame.getEnvironment(); JMenu menu = new JMenu("Help"); Serializable object = environment.getObject(); //Currently commented out, but can be restored if the help menus are fixed. //addItem(menu, new EnvironmentHelpAction(environment)); //Temporary help action. addItem(menu, new AbstractAction("Help...") { public void actionPerformed(ActionEvent event) { JOptionPane.showMessageDialog(null, "For help, feel free to access the JFLAP tutorial at\n" + " www.jflap.org.", "Help", JOptionPane.PLAIN_MESSAGE); } }); addItem(menu, new AboutAction()); return menu; }
0
public void start() throws GameNotInitializedException { if (!initialized) { throw new GameNotInitializedException("Game not initialized"); } while (!gameEnded) { try { // It's just a delay for display Thread.sleep(100); } catch (InterruptedException e) { e.printStackTrace(); } playTurn(currentPlayer); nextPlayer(); } Debug.out("Game end!"); }
3
public char getOrbitalLetter() { int oNum = getOrbitalNum(); if(oNum == 2) return 's'; else if(oNum == 6) return 'p'; else if(oNum == 10) return 'd'; else if(oNum == 14) return 'f'; System.err.println("getOrbitalLetter - Orbital number is out of bounds"); return '?'; }
4
private String[] getVariablesNamesInScope(Scope scope) { TreeSet<String> result = new TreeSet<String>(); /* * TODO: Frank, what to do with object/classes? For example test.test? */ boolean doneFirst = false; String suffix = "local"; do { if (!doneFirst && scope instanceof AstRoot) { suffix = "global"; } /* get the symboltable for the current scope */ Map<String, Symbol> t = scope.getSymbolTable(); if (t != null) { for (String key : t.keySet()) { /* read the symbol */ Symbol symbol = t.get(key); /* only add variables and function parameters */ if (symbol.getDeclType() == Token.LP || symbol.getDeclType() == Token.VAR) { result.add(symbol.getName() + ":" + suffix); } } } doneFirst = true; suffix = "global"; /* get next scope (upwards) */ scope = scope.getEnclosingScope(); } while (scope != null); /* return the result as a String array */ return result.toArray(new String[0]); }
7
@Override public void run(int interfaceId, int componentId) { if (stage == -1) { sendEntityDialogue(SEND_1_TEXT_CHAT, new String[] { player.getDisplayName(), "Can you tell me about the battlefield?" }, IS_PLAYER, player.getIndex(), 9827); stage = 1; } else if (stage == 1) { sendEntityDialogue( SEND_2_TEXT_CHAT, new String[] { NPCDefinitions.getNPCDefinitions(npcId).name, "Lumbridge battlefield is where Saradomin himself is", "currently fighting Zamorak! ", }, IS_NPC, npcId, 9827); stage = 2; } else if (stage == 2) { sendEntityDialogue( SEND_2_TEXT_CHAT, new String[] { NPCDefinitions.getNPCDefinitions(npcId).name, "Thank goodness that he is here! If he'd not shown up", "when he did, we'd all be thralls of Zamorak now! ", }, IS_NPC, npcId, 9827); stage = 3; } else if (stage == 3) { sendEntityDialogue( SEND_2_TEXT_CHAT, new String[] { NPCDefinitions.getNPCDefinitions(npcId).name, "But he came to us from far away in our time of need, ", "and even now he fights evil on Lumbridge Battlefield.", }, IS_NPC, npcId, 9827); stage = 4; } else if (stage == 4) { sendEntityDialogue( SEND_2_TEXT_CHAT, new String[] { NPCDefinitions.getNPCDefinitions(npcId).name, "Oh, you must be on your way to Saradomin's war camp", "in order to help out. It's to the northwest of here. ", }, IS_NPC, npcId, 9827); stage = 5; } else if (stage == 5) { sendEntityDialogue(SEND_2_TEXT_CHAT, new String[] { NPCDefinitions.getNPCDefinitions(npcId).name, "We cannot let evil conquer! ", "Good luck! And may Saradomin be with you! ", }, IS_NPC, npcId, 9827); stage = 6; } else if (stage == 6) { end(); } }
7
@Override protected void done(){ if(exit==0){ //If is successful, tell the user, and record it in the log file JOptionPane.showMessageDialog(Download.this,"Finsh"); } //If it is failed, show user the message else if (exit==1){ JOptionPane.showMessageDialog(Download.this,"Interrupt"); cancel.setVisible(false); } else if (exit==2){ JOptionPane.showMessageDialog(Download.this,"Parse error"); cancel.setVisible(false); } else if (exit==3){ JOptionPane.showMessageDialog(Download.this,"File I/O error"); cancel.setVisible(false); } else if (exit==4){ JOptionPane.showMessageDialog(Download.this,"Network failure"); cancel.setVisible(false); } else if (exit==5){ JOptionPane.showMessageDialog(Download.this,"SSL verification failure"); cancel.setVisible(false); } else if (exit==6){ JOptionPane.showMessageDialog(Download.this,"Username/password authentication failure"); cancel.setVisible(false); } progressBar.setValue(0); txt.setText(""); }
7
void createExampleWidgets () { /* * Create the page. This example does not use layouts. */ int style = getDefaultStyle(); sashComp = new Composite(sashGroup, SWT.BORDER | style); /* Create the list and text widgets */ list1 = new List (sashComp, SWT.V_SCROLL | SWT.H_SCROLL | SWT.BORDER); list1.setItems (ListData0); list2 = new List (sashComp, SWT.V_SCROLL | SWT.H_SCROLL | SWT.BORDER); list2.setItems (ListData1); text = new Text (sashComp, SWT.MULTI | SWT.BORDER); text.setText (ControlExample.getResourceString("Multi_line")); /* Create the sashes */ style = smoothButton.getSelection() ? SWT.SMOOTH : SWT.NONE; vSash = new Sash (sashComp, SWT.VERTICAL | style); hSash = new Sash (sashComp, SWT.HORIZONTAL | style); /* Add the listeners */ hSash.addSelectionListener (new SelectionAdapter () { public void widgetSelected (SelectionEvent event) { Rectangle rect = vSash.getParent().getClientArea(); event.y = Math.min (Math.max (event.y, SASH_LIMIT), rect.height - SASH_LIMIT); if (event.detail != SWT.DRAG) { hSash.setBounds (event.x, event.y, event.width, event.height); layout (); } } }); vSash.addSelectionListener (new SelectionAdapter () { public void widgetSelected (SelectionEvent event) { Rectangle rect = vSash.getParent().getClientArea(); event.x = Math.min (Math.max (event.x, SASH_LIMIT), rect.width - SASH_LIMIT); if (event.detail != SWT.DRAG) { vSash.setBounds (event.x, event.y, event.width, event.height); layout (); } } }); sashComp.addControlListener (new ControlAdapter () { public void controlResized (ControlEvent event) { resized (); } }); }
3
private String getXML() { JFileChooser chooser = new JFileChooser(); if(ProjectMainView.actualFolder!=null) chooser.setCurrentDirectory(ProjectMainView.actualFolder); FileNameExtensionFilter filter = new FileNameExtensionFilter("*.zip", "zip"); chooser.setFileFilter(filter); chooser.setDialogTitle("Choose Package file"); chooser.setFileSelectionMode(JFileChooser.FILES_ONLY); chooser.setAcceptAllFileFilterUsed(false); String str = ""; if (chooser.showOpenDialog(null) == JFileChooser.APPROVE_OPTION) { str = chooser.getSelectedFile().toString(); ProjectMainView.actualFolder=chooser.getSelectedFile().getParentFile(); } return str; }
2
static private int jjMoveStringLiteralDfa0_0() { switch(curChar) { case 39: return jjStopAtPos(0, 9); case 40: return jjStopAtPos(0, 7); case 41: return jjStopAtPos(0, 8); case 43: return jjStopAtPos(0, 15); case 45: return jjStartNfaWithStates_0(0, 16, 25); case 99: return jjMoveStringLiteralDfa1_0(0xe0000L); case 108: return jjMoveStringLiteralDfa1_0(0x6000L); default : return jjMoveNfa_0(0, 0); } }
7
public static Venue findById(long id) throws SQLException { return findOne("id", String.valueOf(id)); }
0
@Override public void run() { log("Connection accepted"); InputStream in; OutputStream out; IObjectChannel channel; try { in = client.getInputStream(); out = client.getOutputStream(); channel = channelFactory.create(out, in); channel.setLogAdapter(this); } catch (IOException e1) { throw new RuntimeException(e1); } try { Object inputObject; Object outputObject; try { while ((inputObject = channel.readObject()) != null) { // Process input outputObject = handler.process(inputObject); channel.writeObject(outputObject); // check whether to continue or not if (isClosed() || client.isClosed() || handler.breakConnection()) break; } log("Connection closed"); } catch (ClassNotFoundException e) { outputObject = handler.getIllegalRequestResponse(); channel.writeObject(outputObject); log(e.toString()); log("Connection closed"); } finally { out.close(); in.close(); } } catch (EOFException e) { log("Connection closed by client"); } catch (IOException e2) { log(e2.getMessage()); log("Connection closed"); } finally { close(); } }
8
@Override public void render(Value value, Object target, Class clazz, CoderContext context) throws ConversionException { if (target instanceof Map) { if (Map.class.isAssignableFrom(clazz)) { Map map = (Map) target; for (;;) { if (!value.hasMoreItems()) { break; } Object itemKey = value.get(null, context); if (!value.hasMoreItems()) { throw new ConversionException("Encoded Map entry has missing value"); } Object itemValue = value.get(null, context); map.put(itemKey, itemValue); } } else throw new ConversionException("Cannot convert a " + clazz.getName() + " to a Map"); } else if (target instanceof Collection) { if (Collection.class.isAssignableFrom(clazz)) { Collection collection = (Collection) target; for (;;) { if (!value.hasMoreItems()) { break; } Object itemValue = value.get(null, context); collection.add(itemValue); } } else throw new ConversionException("Cannot convert " + clazz.getName() + " to a Collection"); } else throw new ConversionException("CollectionValueCoder cannot render to an object of class " + target.getClass().getName()); }
9
@SuppressWarnings("unchecked") public E previous() { checkForComodification(); int i = cursor - 1; if (i < 0) { throw new NoSuchElementException(); } cursor = i; return (E) get(lastRet = i); }
1
public static int findMinimumDistance(int []input, int x, int y){ int prev =-1; int i=0; int privIndex = -1; int minDistance = Integer.MAX_VALUE; //find first item which matches either of x or y for(;i<input.length; i++) { if(input[i] == x || input[i] ==y) { privIndex = i; //since we are breaking increase the i prev = input[i++]; break; } } //keep goinf to the right and check if we have anything equal to x or y for( ;i<input.length;i++){ if(input[i] ==x || input[i] ==y) { //if it is not equal to prev item if(input[i]!=prev){ //update the minimum distance if required if(minDistance > i-privIndex) { minDistance = i-privIndex; } } else { //make this index as privIndex privIndex = i; } } } return minDistance; }
8
public void checkScore() { switch(getScore()) { case PLAYER1: break; case PLAYER2: break; case NONE: break; } }
3
public static List<Laureate> filterByCountry(List<Laureate> inputList, List<String> ListOfTerms) { List<Laureate> outputList = new ArrayList<Laureate>(); // parse input, keep what matchs the terms. for (Laureate Awinner : inputList) { if (ListOfTerms.contains(Awinner.getCountry())) { outputList.add(Awinner); } } return outputList; }
2
public boolean checkForVerticalStrike(String input) { for (int i = 0; i < boardSize; i++) { int count=0; for (int j = 0; j < boardSize; j++,count++) { if (boardArray[j][i].equalsIgnoreCase(input)) { continue; } break; } if(count==boardSize){ setWinner(input); return true; } } return false; }
4
public static boolean nativeSlotPropositionP(Proposition self) { { Vector arguments = self.arguments; if (((arguments.length()) == 0)) { return (false); } { Stella_Object firstarg = (((arguments.theArray)[0] != null) ? Logic.valueOf((arguments.theArray)[0]) : ((Stella_Object)(null))); if ((firstarg != null) && Stella_Object.isaP(firstarg, Logic.SGT_STELLA_THING)) { { NamedDescription description = Logic.getDescription(self.operator); if ((description != null) && ((description.nativeRelation() != null) && Stella_Object.isaP(description.nativeRelation(), Logic.SGT_STELLA_STORAGE_SLOT))) { return (true); } } } return (false); } } }
7
@Override public boolean runTest(){ return ((frontBack("code").equals("eodc")) && (frontBack("a").equals("a")) && (frontBack("ab").equals("ba")) && (frontBack("abc").equals("cba")) && (frontBack("").equals("")) && (frontBack("Chocolate").equals("ehocolatC")) && (frontBack("aavJ").equals("Java")) && (frontBack("hello").equals("oellh"))); }
7
public String serializeToString(Element root) { StringBuilder sb = new StringBuilder("<"); sb.append(root.getTag()); String val; for (String attName : root.attributeNames()) { val = root.getAttribute(attName); sb.append(String.format(ATTRIBUTE_FMT, attName, val)); } if (root.hasText() || root.hasChildren()) { sb.append(">"); } else { sb.append(" />"); } if (root.hasText()) { sb.append(root.getText()); } for (Element child : root.children()) { sb.append(serializeToString(child)); } if (root.hasText() || root.hasChildren()) { sb.append(String.format("</%s>", root.getTag())); } return sb.toString(); }
7
@Override public boolean equals(Object obj) { if (this == obj) return true; else if (!(obj instanceof ObjectVariable)) return false; ObjectVariable ov = (ObjectVariable) obj; return (inQuotes == ov.inQuotes) && varname.equals(ov.varname) && value.equals(ov.value); }
4
@Override public void execute() { if (args.length == 0) p.openInventory(cm.getMain().getLM().getInventory()); if (args.length == 1) { if (Permissions.isAdmin(p)) { if (args[0].equalsIgnoreCase("edit")) { edit(); } } if (args[0].equalsIgnoreCase("claim")) { claim(); } } }
5
public void jugar(JFrame frame, EstadoVictoria escucharVictoria){ Point limitePueblo; //cambio dificultad System.out.println("dif min is " + this.defenseDiffMin + " and dif max is " + this.defenseDiffMax); System.out.println("Gold min is " + this.goldMin + " and gold max is " + this.goldMax); //aumento Dificultad de defensas y oro dado int goldIncreasePercentage = rand.nextInt(goldMax - goldMin) + goldMin; defenseIncreasePercentage = rand. nextInt(defenseDiffMax - defenseDiffMin) + defenseDiffMin; victoriaOro = baseOro + (baseOro * (goldIncreasePercentage / 100)); this.oro = victoriaOro; System.out.println("Cantidad de oro en victoria es: " + victoriaOro); System.out.println("Aumento de dificultad " + defenseIncreasePercentage + "%"); //<<<< this.llenarMatrizVacio(); //genera el pueblo de forma aleatoria y retorna el limite de ella Point[] puntosImportante = Pueblo.generarPueblo(this.nivel, this.matriz, this.refContenedor, this.edificios, defenseIncreasePercentage, this.ejercito); limitePueblo = puntosImportante[0]; this.puntoCasa = puntosImportante[1]; this.SoldadosTerrestres(limitePueblo); for(int i = 0; i< ejercito.size(); i++) ejercito.get(i).start(); //inicia el hilo de cada unidad for(int i = 0; i< edificios.size(); i++){ edificios.get(i).pegarEnPanel(); edificios.get(i).start(); //inicia el hilo de cada unidad } escucharVictoria.revisarVictoria(frame); }
2
public static Iterator fetchEdbQuery(Proposition proposition, LogicObject database, Stella_Object arguments) { RDBMS.checkForExternalDbUpdates(proposition, database); { MemoizationTable memoTable000 = null; Cons memoizedEntry000 = null; Stella_Object memoizedValue000 = null; if (Stella.$MEMOIZATION_ENABLEDp$) { memoTable000 = ((MemoizationTable)(RDBMS.SGT_RDBMS_F_FETCH_EDB_QUERY_MEMO_TABLE_000.surrogateValue)); if (memoTable000 == null) { Surrogate.initializeMemoizationTable(RDBMS.SGT_RDBMS_F_FETCH_EDB_QUERY_MEMO_TABLE_000, "(:MAX-VALUES 10000 :TIMESTAMPS (:META-KB-UPDATE :EXTERNAL-DB-UPDATE))"); memoTable000 = ((MemoizationTable)(RDBMS.SGT_RDBMS_F_FETCH_EDB_QUERY_MEMO_TABLE_000.surrogateValue)); } memoizedEntry000 = MruMemoizationTable.lookupMruMemoizedValue(((MruMemoizationTable)(memoTable000)), RDBMS.getQueryPatternMemoizationKey(proposition), ((Context)(Stella.$CONTEXT$.get())), (((Boolean)(Logic.$REVERSEPOLARITYp$.get())).booleanValue() ? Stella.TRUE_WRAPPER : Stella.FALSE_WRAPPER), Stella.MEMOIZED_NULL_VALUE, 6); memoizedValue000 = memoizedEntry000.value; } if (memoizedValue000 != null) { if (memoizedValue000 == Stella.MEMOIZED_NULL_VALUE) { memoizedValue000 = null; } } else { memoizedValue000 = MemoizableIterator.newMemoizableIterator(RDBMS.helpMemoizeFetchEdbQuery(proposition, database, arguments)); if (Stella.$MEMOIZATION_ENABLEDp$) { memoizedEntry000.value = ((memoizedValue000 == null) ? Stella.MEMOIZED_NULL_VALUE : memoizedValue000); } } { Iterator value000 = MemoizableIterator.cloneMemoizedIterator(((MemoizableIterator)(memoizedValue000))); return (((Iterator)(value000))); } } }
7
public List<Object> getContent() { if (content == null) { content = new ArrayList<Object>(); } return this.content; }
1
public GrooveJaar() throws FileNotFoundException, IOException, InterruptedException, ExecutionException { try { //CountryUtil.initCountryCode(); //JGroovex.initiateQueue(); JGroove.getToken(); } catch (IOException e) { showMessage("Fatal error.. Grooveshark.com seems to be down.."); e.printStackTrace(); System.exit(-1); } if (opt.showDisclaimer()){ Disclaimer dis = new Disclaimer(); dis.setLocationRelativeTo(null); dis.setVisible(true); dis.setAlwaysOnTop(true); opt.save("showDisclaimer", "false"); } checkTemp(); if (opt.getUpdate()) checkUpdate(false); initialize(); if (!opt.getUser().isEmpty() && !opt.getPassword().isEmpty() && user==null) login(opt.getUser(),opt.getPassword()); }
6
public boolean containsValue (Object value, boolean identity) { V[] valueTable = this.valueTable; if (value == null) { K[] keyTable = this.keyTable; for (int i = capacity + stashSize; i-- > 0;) if (keyTable[i] != null && valueTable[i] == null) return true; } else if (identity) { for (int i = capacity + stashSize; i-- > 0;) if (valueTable[i] == value) return true; } else { for (int i = capacity + stashSize; i-- > 0;) if (value.equals(valueTable[i])) return true; } return false; }
9
public String authenticateUser(String userName, String password, boolean isAdmin) throws SQLException { String[] keys = {"userid", "username", "password"}; // qb = new QueryBuilder(); // Henter info om bruger fra database via querybuilder resultSet = qb.selectFrom(keys, "users").where("username", "=", userName).ExecuteQuery(); // Hvis en bruger med forespurgt email findes if (resultSet.next()) { // Hvis passwords matcher if(resultSet.getString("password").equals(password)) { // If the user is activ //udkommenteret da funktion ikke i brug, kan evt. bruges senere // if(resultSet.getBoolean("active")) // { String userID = resultSet.getString("userid"); String[] key = {"type"}; resultSet = qb.selectFrom(key, "roles").where("userid", "=", userID).ExecuteQuery(); resultSet.next(); // Hvis brugeren baade logger ind og er registreret som admin, eller hvis brugeren baade logger ind og er registreret som bruger if((resultSet.getString("type").equals("admin") && isAdmin) || (resultSet.getString("type").equals("user") && !isAdmin)) { return "0"; // returnerer "0" hvis bruger/admin er godkendt } else { return "3"; // returnerer fejlkoden "3" hvis brugertype ikke stemmer overens med loginplatform } // } else { // return "2"; // returnerer fejlkoden "2" hvis bruger er sat som inaktiv // // } } else { return "1"; // returnerer fejlkoden "1" hvis email ikke findes eller hvis password og username ikke matcher } } else { return "1"; // returnerer fejlkoden "1" hvis email ikke findes eller hvis password og username ikke matcher } }
6
public static String get_stack(final Throwable t) { final PrintWriter pw = new PrintWriter(new StringWriter()); t.printStackTrace(pw); return pw.toString(); }
0
public void setSkill2(SkillsMain skill22) { this.skill2 = skill22; }
0
public void run() { setupRobot(); while (true) { // Tell each component to act wheel.act(); radar.act(); gun.act(); targetSelector.act(); execute(); } }
1
@Override public byte[] save(JoeTree tree, DocumentInfo docInfo) { StringBuffer buf = prepareFile(tree, docInfo); try { return buf.toString().getBytes(PropertyContainerUtil.getPropertyAsString(docInfo, DocumentInfo.KEY_ENCODING_TYPE)); } catch (UnsupportedEncodingException e) { e.printStackTrace(); return buf.toString().getBytes(); } }
1
public FileChooser(Forme forme) { super("./Ressources/Images"); this.setDialogTitle("Choisir une image"); this.setMultiSelectionEnabled(false); this.addChoosableFileFilter(filtre1); this.addChoosableFileFilter(filtre2); this.addChoosableFileFilter(filtre3); this.addChoosableFileFilter(filtre4); this.addChoosableFileFilter(filtre5); //mettre le filtre1 comme un filre par défaut this.setFileFilter(filtre1); //ouvrir le JFileChooser int rep=this.showOpenDialog(forme); if(rep!=JFileChooser.CANCEL_OPTION && this.getSelectedFile()!=null){ forme.chemin=this.getSelectedFile().getAbsolutePath(); if(forme.chemin!=null) try { forme.setImage(ImageIO.read(new File(forme.chemin))); forme.diviserImage(); forme.initialiser(); forme.setDemarrer(false); forme.mLancer.setEnabled(true); } catch (IOException e1) { JOptionPane.showMessageDialog(this,e1.getMessage(),"Erreur",JOptionPane.ERROR_MESSAGE); } } }
4
public int computeChineseFields() { if (gregorianYear < 1901 || gregorianYear > 2100) return 1; int startYear = baseYear; int startMonth = baseMonth; int startDate = baseDate; chineseYear = baseChineseYear; chineseMonth = baseChineseMonth; chineseDate = baseChineseDate; // 第二个对应日,用以提高计算效率 // 公历2000年1月1日,对应农历4697年11月25日 if (gregorianYear >= 2000) { startYear = baseYear + 99; startMonth = 1; startDate = 1; chineseYear = baseChineseYear + 99; chineseMonth = 11; chineseDate = 25; } int daysDiff = 0; for (int i = startYear; i < gregorianYear; i++) { daysDiff += 365; if (isGregorianLeapYear(i)) daysDiff += 1;// leapyear } for (int i = startMonth; i < gregorianMonth; i++) { daysDiff += daysInGregorianMonth(gregorianYear, i); } daysDiff += gregorianDate - startDate; chineseDate += daysDiff; int lastDate = daysInChineseMonth(chineseYear, chineseMonth); int nextMonth = nextChineseMonth(chineseYear, chineseMonth); while (chineseDate > lastDate) { if (Math.abs(nextMonth) < Math.abs(chineseMonth)) chineseYear++; chineseMonth = nextMonth; chineseDate -= lastDate; lastDate = daysInChineseMonth(chineseYear, chineseMonth); nextMonth = nextChineseMonth(chineseYear, chineseMonth); } return 0; }
8
@Override public String toString() { if (minIteration != maxIteration) { return String.format("%d - %d", minIteration + 1, maxIteration + 1); } else { return new Integer(minIteration + 1).toString(); } }
1
public static void main(String[] args) throws NumberFormatException, IOException{ int dividend = input("dividend"); int divisor = input("divisor"); output(division(dividend, divisor)); }
0
@Override public void sendUsageImpl(CommandSender sender) { if (!(sender instanceof Player)) return; sender.sendMessage(EdgeCore.usageColor + "/transfer <to> <amount> <description>"); User u = EdgeCoreAPI.userAPI().getUser(sender.getName()); if (u == null || !Level.canUse(u, Level.SUPPORTER)) return; sender.sendMessage(EdgeCore.usageColor + "/transfer last [<amount>]"); if (u == null || !Level.canUse(u, Level.MODERATOR)) return; sender.sendMessage(EdgeCore.usageColor + "/transfer <from> <to> <amount> <description>"); }
5
public static ArrayList<Improvement> getValidImprovements(Civilization civ, BaseEntity en) { ArrayList<Improvement> temp = new ArrayList<Improvement>(); /*for (Entry<String, Improvement> entry: unitImprovementMap.entrySet()) { String name = entry.getKey(); Improvement i = entry.getValue(); //Split into many if statements for special improvement conditions later if (!civ.techTree.researched(i.requiredTech).researched()) continue; if (i.equals("Neutral")) { continue; } if (i.isFit(en.name)) temp.add(i); else if (i.units[0].equals("allmelee") && en.offensiveStr > 0) temp.add(i); else if (i.units[0].equals("allranged") && en.rangedStr > 0) temp.add(i); } //System.out.println(temp.size());*/ for (int i = 0; i < civ.techTree.allowedUnitImprovements.size(); i++) { String name = civ.techTree.allowedUnitImprovements.get(i); Improvement impr = unitImprovementMap.get(name); if (impr == null) impr = cityImprovementMap.get(name); //if (!civ.techTree.researched(i.requiredTech).researched()) continue; //Above condition already checked; list of names can only be from unlocked techs if (impr.equals("Neutral")) { continue; } if (impr.isFit(en.name)) temp.add(impr); else if (impr.units[0].equals("allmelee") && en.offensiveStr > 0) temp.add(impr); else if (impr.units[0].equals("allranged") && en.rangedStr > 0) temp.add(impr); } return temp; }
8
public <T> T httpRequest(HttpMethod method, Class<T> cls, Map<String, Object> params, Object data, String... segments) { HttpHeaders requestHeaders = new HttpHeaders(); requestHeaders.setAccept(Collections .singletonList(MediaType.APPLICATION_JSON)); if (accessToken != null) { String auth = "Bearer " + accessToken; requestHeaders.set("Authorization", auth); log.info("Authorization: " + auth); } String url = path(apiUrl, segments); MediaType contentType = MediaType.APPLICATION_JSON; if (method.equals(HttpMethod.POST) && isEmpty(data) && !isEmpty(params)) { data = encodeParams(params); contentType = MediaType.APPLICATION_FORM_URLENCODED; } else { url = addQueryParams(url, params); } requestHeaders.setContentType(contentType); HttpEntity<?> requestEntity = null; if (method.equals(HttpMethod.POST) || method.equals(HttpMethod.PUT)) { if (isEmpty(data)) { data = JsonNodeFactory.instance.objectNode(); } requestEntity = new HttpEntity<Object>(data, requestHeaders); } else { requestEntity = new HttpEntity<Object>(requestHeaders); } log.info("Client.httpRequest(): url: " + url); ResponseEntity<T> responseEntity = restTemplate.exchange(url, method, requestEntity, cls); log.info("Client.httpRequest(): reponse body: " + responseEntity.getBody().toString()); return responseEntity.getBody(); }
8
private void drawGUI() { setResizable(false); setTitle("Email-Management"); setIconImage(Toolkit.getDefaultToolkit().getImage(iconPath)); addWindowListener(new WindowAdapter(this)); setBounds(100, 100, 331, 229); JMenuBar menuBar = new JMenuBar(); setJMenuBar(menuBar); JMenu mnKontakt = new JMenu("Kontakt"); menuBar.add(mnKontakt); JMenuItem mntmNeu = new JMenuItem("Neu"); mntmNeu.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { newContact(); } }); mnKontakt.add(mntmNeu); JMenuItem mntmSpeichern = new JMenuItem("Speichern"); mntmSpeichern.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { saveContact(); } }); mnKontakt.add(mntmSpeichern); JMenuItem mntmSuchen = new JMenuItem("Suchen"); mntmSuchen.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { searchContact(); } }); mnKontakt.add(mntmSuchen); JMenuItem mntmLschen = new JMenuItem("L\u00F6schen"); mntmLschen.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { deleteContact(); } }); mnKontakt.add(mntmLschen); JMenuItem mntmBeenden = new JMenuItem("Beenden"); mntmBeenden.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { beenden(); } }); mnKontakt.add(mntmBeenden); JMenu mnHilfe = new JMenu("Hilfe"); menuBar.add(mnHilfe); JMenuItem mntmberEmailmanagement = new JMenuItem( "\u00DCber Email-Management"); mntmberEmailmanagement.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { about(); } }); mnHilfe.add(mntmberEmailmanagement); contentPane = new JPanel(); contentPane.setBorder(new EmptyBorder(5, 5, 5, 5)); setContentPane(contentPane); contentPane.setLayout(null); JLabel lblVorname = new JLabel("Vorname"); lblVorname.setBounds(32, 36, 70, 14); contentPane.add(lblVorname); JLabel lblNachname = new JLabel("Nachname"); lblNachname.setBounds(32, 61, 70, 14); contentPane.add(lblNachname); JLabel lblNewLabel = new JLabel("Email"); lblNewLabel.setBounds(32, 86, 70, 14); contentPane.add(lblNewLabel); textField = new JTextField(); textField.setBounds(120, 33, 112, 20); contentPane.add(textField); textField.setColumns(10); textField_1 = new JTextField(); textField_1.setBounds(120, 58, 112, 20); contentPane.add(textField_1); textField_1.setColumns(10); textField_2 = new JTextField(); textField_2.setBounds(120, 86, 112, 20); contentPane.add(textField_2); textField_2.setColumns(10); button = new JButton("|<"); button.setFont(new Font("Tahoma", Font.PLAIN, 9)); button.setBounds(32, 125, 45, 23); button.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { displayFirst(); } }); contentPane.add(button); JButton button_1 = new JButton("<"); button_1.setFont(new Font("Tahoma", Font.PLAIN, 9)); button_1.setBounds(87, 125, 45, 23); button_1.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { displayPrevious(); } }); contentPane.add(button_1); textField_3 = new JTextField(); textField_3.setBounds(142, 126, 35, 20); textField_3.setEditable(false); textField_3.setHorizontalAlignment(textField_3.CENTER); contentPane.add(textField_3); textField_3.setColumns(10); JButton button_2 = new JButton(">"); button_2.setFont(new Font("Tahoma", Font.PLAIN, 9)); button_2.setBounds(187, 125, 45, 23); button_2.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { displayNext(); } }); contentPane.add(button_2); JButton button_3 = new JButton(">|"); button_3.setFont(new Font("Tahoma", Font.PLAIN, 9)); button_3.setBounds(242, 125, 45, 23); button_3.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { displayLast(); } }); contentPane.add(button_3); }
0
@Override public int compareTo(Bill o) { if (this.date.before(o.getDate())) { return -1; } else if (this.date.after(o.getDate())) { return 1; } else return 0; }
2
@Override public void update() { int speed = 6; if (world.getCollidingEntities(this).size() == 0 && !inAnimation) { move(0, speed); } if (world.getRacket().collidesWith(this)) { inAnimation = true; Game game = world.getGame(); game.getBonusManager().add(type); if (type == BonusType.ExtraLife) { game.addLifes(1); } } if (inAnimation) { double angle = Math.atan2(40 - getY(), Game.WIDTH - 40 - getX()); if (++skippedTicks > 12) { padding += 1; opacity -= 0.01f; } speed = 48; move((int) (speed * Math.cos(angle)), (int) (speed * Math.sin(angle))); if (Geom.getDistBetweenPoints(getX(), getY(), Game.WIDTH - 40, 40) <= 20 || opacity < 0f) { remove(); } } if (getY() >= Game.HEIGHT + Game.BAR_HEIGHT) { remove(); } }
9
public void loadStats() { if(plugin.configData.trackStats) { this.stats = new HashMap<String, Stat>(); this.globalSpins = 0; this.globalWon = 0.0; this.globalLost = 0.0; Integer i = 0; if(plugin.configData.stats.isConfigurationSection("types")) { Set<String> types = plugin.configData.stats.getConfigurationSection("types").getKeys(false); for(String type : types) { loadStat(type); i++; } } plugin.logger.info(plugin.prefix +" Loaded statistics for " + i + " types."); } else { plugin.logger.info(plugin.prefix +" Not tracking statistics."); } }
3
@Override public void run(CommandArgs arg0) { String[] args = arg0.getRawArgs().split(" "); if (args.length > 1 && args[0].equals("site")) { Integer id = Integer.parseInt(args[1]); Site site = WebServer.getSiteByID(id); if (site == null) { System.err.println("No Site with ID " + id); } else { WebServer.start(site); } } else { if (WebServer.getStatus() == jServe.Core.ServerStatus.Started) { System.err.println("Server is already started"); } else { WebServer.logInfo("Server is starting"); WebServer.start(); WebServer.logInfo("Server Started"); } } }
4
private static <T extends Comparable<? super T>> T median3( T[] a, int left, int right) { int center = (left + right) / 2; if (a[center].compareTo(a[left]) < 0) swapReferences(a, left, center); if (a[right].compareTo(a[left]) < 0) swapReferences(a, left, right); if (a[right].compareTo(a[center]) < 0) swapReferences(a, center, right); // Place pivot at position right - 1 swapReferences(a, center, right - 1); return a[right - 1]; }
4
public static <T extends DC> Set<T> dom(Set<Pair<T,T>> phiMax) { if(phiMax!=null) { if(phiMax.getNext()!=null) { return new Set(phiMax.getFst().fst(),dom(phiMax.getNext())); } else { return new Set(phiMax.getFst().fst(),null); } } else { return null; } }
2
public void steal() { synchronized (_cards) { boolean[] found = new boolean[ins.length]; for (int i=0;i<ins.length;i++) found[i] = false; ArrayList<Card> torm = new ArrayList<Card>(); for (Card c : _cards) { for (int i=0;i<ins.length;i++) { if (c.mytype == ins[i] && found[i] == false) { found[i] = true; torm.add(c); break; } } } for (int i=0;i<ins.length;i++) { if (found[i] == false) return; } for (Card c : torm) { _cards.remove(_cards.indexOf(c)); } hotkeypressed = true; switchOut(); } }
8
void checkSignature(Class<?>... signatur) { Class<?>[] parameters = method.getParameterTypes(); RuntimeException ex = new RuntimeException("Method " + method.getName() + " must have the following signature: " + Arrays.toString(signatur)); if(parameters.length != signatur.length) throw ex; for(int i = 0; i < parameters.length; i++) { if(parameters[i].isAssignableFrom(signatur[i]) == false) throw ex; } }
5
@Override public void mouseReleased(MouseEvent e) { Rectangle rect = new Rectangle(e.getX(), e.getY(), 1, 1); Barrillo[] prebarrillo = barrillos.toArray(new Barrillo[0]); Barrillo barrilloAExplotar = null; for (Barrillo bar : prebarrillo) { if (bar.devolverRectangle().intersects(rect)) { barrilloAExplotar = bar; repaint(); } } mouseMoved(e); manos.push(barrilloAExplotar); }
2
@Override public SXLValue castInto(String type) throws Exception { switch( type ) { case "string": return new SXLString( (value)? "true" : "false" ); case "boolean": return new SXLBoolean( value ); case "integer": return new SXLInteger( (value)? 1 : 0 ); case "real" : return new SXLReal( (value)? 1.0 : 0.0 ); case "character" : return new SXLCharacter( (value)? 't' :'f' ); default: throw new Exception("Cannot cast boolean into " + type); } }
9
public static void main(String[] args) { ApplicationContext context = new ClassPathXmlApplicationContext("spring.xml"); if (context.containsBean("quarantinedDataSource")) { LOG.info("Using quarantinedDataSource"); } else { LOG.info("Using normal dataSource"); } EventService service = context.getBean(EventService.class); while (true) { service.completePendingEvent(); try { Thread.sleep(1000); } catch (InterruptedException e) { break; } } }
3
public Population elitism(Population pop, int outSize){//cut percent (rather than number) Individual [] subset = new Individual[outSize]; //sort by fitness Comparator<Individual> indComp = new Comparator<Individual>() { @Override public int compare(Individual a, Individual b) { double diff = Config.getInstance().calculateFitness(a) - Config.getInstance().calculateFitness(b); return (diff == 0) ? 0 : ((diff > 0) ? -1 : 1); } }; Collections.sort(pop.population,indComp);//java 7 //pop.population.sort(indComp);//java 8 //cut off for(int i=0; i<outSize; i++){ subset[i]=pop.population.get(i); } return new Population(subset); }
3
public JsonObjectBuilder rewriteJson(JsonObjectBuilder copyInto,JsonValue tree,String key){ /** * Helper function used to parse json */ switch(tree.getValueType()){ case OBJECT: JsonObject obj = (JsonObject) tree; for(String name : obj.keySet()){ copyInto = rewriteJson(copyInto,obj.get(name),name); } break; case STRING: JsonString st = (JsonString) tree; copyInto.add(key, st.getString()); break; default: break; } return copyInto; }
3
private long highestPrimeFactor(long number){ if (isPrime(number)){ return number; } long factor = 2; long highestPrimeFactor = 1; while (factor <= number/factor){ if ((number%factor==0) && isPrime(factor)){ if (factor > highestPrimeFactor){ if (isPrime(number/factor)){ factor = number/factor; } highestPrimeFactor = factor; } } factor = factor + 1; } return highestPrimeFactor; }
6
@Override public double observe() { double observed = 0; for (int i = 0; i < r; i++) { observed += geom.observe(); } return observed; }
1
public void pop() { Menu menu = getCurrentMenu(); if (menu != null) { menu.setMenuStack(null); menuStack.pop(); } }
1
@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(!super.invoke(mob,commands,givenTarget,auto,asLevel)) return false; boolean success=proficiencyCheck(mob,0,auto); if(success) { final CMMsg msg=CMClass.getMsg(mob,target,this,verbalCastCode(mob,target,auto)|CMMsg.MASK_MALICIOUS,auto?L("<T-NAME> become(s) contagious!"):L("^S<S-NAME> @x1 for a contagion to inflict <T-NAMESELF>.^?",prayWord(mob))); final CMMsg msg2=CMClass.getMsg(mob,target,this,CMMsg.TYP_DISEASE|CMMsg.MASK_MALICIOUS,null); if((mob.location().okMessage(mob,msg))&&(mob.location().okMessage(mob,msg2))) { mob.location().send(mob,msg); mob.location().send(mob,msg2); if((msg.value()<=0)&&(msg2.value()<=0)) success=maliciousAffect(mob,target,asLevel,0,-1)!=null; else spreadImmunity(target); } } else return maliciousFizzle(mob,target,L("<S-NAME> point(s) at <T-NAMESELF> and @x1, but nothing happens.",prayWord(mob))); // return whether it worked return success; }
8
public String toString() { String result = board.toString(); if (isGameOver()) result +="\n\n Game over"; return result; }
1
private PNGHelper() { }
0
@Override public Position<T> left(Position<T> p) throws BoundaryViolationException, InvalidPositionException { BTPosition<T> rp = checkPosition(p); Position<T> leftP = rp.getLeft(); if (leftP == null) throw new BoundaryViolationException("No left child"); return leftP; }
1
private void formKeyPressed(java.awt.event.KeyEvent evt) {//GEN-FIRST:event_formKeyPressed if(evt.getKeyCode() == evt.VK_F1){ btnovo(); } if(evt.getKeyCode() == evt.VK_F2){ btAlterar(); } if(evt.getKeyCode() == evt.VK_F3){ Object[] listaCliente = {tfNome,tfCpf,tfCep,tfEndereco,tfNumero,tfEstado,tfCelular}; Object[] listaAcess = {tfNomeAssessoria,tfEnderecoAssessoria}; Object[] listaFinanceiro = {tfValor,tfValorDespesa,tfDataVencimento}; Object[] listaProcesso = {tfProcesso,tfDataInicio,tfDataFim,tfAcao,tfsituacaoatual,tfVara,tfComarca}; Object[] listaVeiculo = {tfMarca,tfModelo,tfCor,tfPlaca,tfAnoModelo,tfAnoFabricacao,tfRenavam,tfChassi}; Object[] listaCb = {comboCidade,comboBairro,tfCidade, tfBairro,comboSituacaofinanceiro,comboSituacaoProcesso}; btsalvar(listaCliente,listaProcesso,listaAcess,listaFinanceiro,listaVeiculo); } }
3
private void scan() { if (updateList) { for (int i = 0; i < numberOfAtoms - 1; i++) { for (int j = i + 1; j < numberOfAtoms; j++) { xij = atom[i].rx - atom[j].rx; yij = atom[i].ry - atom[j].ry; rij = xij * xij + yij * yij; bondLength = getBondLength(atom[i], atom[j]); if (rij <= bondLength * bondLength) collide(i, j); } } } else { int i, j, jbeg, jend, jnab; for (i = 0; i < numberOfAtoms - 1; i++) { jbeg = pointer[i]; jend = pointer[i + 1]; if (jbeg < jend) { for (jnab = jbeg; jnab < jend; jnab++) { j = neighborList[jnab]; xij = atom[i].rx - atom[j].rx; yij = atom[i].ry - atom[j].ry; rij = xij * xij + yij * yij; bondLength = getBondLength(atom[i], atom[j]); if (rij <= bondLength * bondLength) collide(i, j); } } } } }
8
private String peekUrl(String filename){ String firstUrl = ""; try{ int i = 0; BufferedReader in = new BufferedReader(new FileReader(filename)); String tmpFileName = filename + ".tmp"; BufferedWriter bw = new BufferedWriter(new FileWriter(tmpFileName)); String line = ""; while((line = in.readLine()) != null){ if(i == 0){ firstUrl = line; i++; continue; } bw.write(line + "\r\n"); } in.close(); bw.close(); FileUtils.delete(filename); FileUtils.rename(tmpFileName , filename); }catch (Exception ex){ log.error("Peek URL failed: " + ex); } return firstUrl; }
3
final int memberValue(int pos) throws Exception { int tag = info[pos] & 0xff; if (tag == 'e') { int typeNameIndex = ByteArray.readU16bit(info, pos + 1); int constNameIndex = ByteArray.readU16bit(info, pos + 3); enumMemberValue(typeNameIndex, constNameIndex); return pos + 5; } else if (tag == 'c') { int index = ByteArray.readU16bit(info, pos + 1); classMemberValue(index); return pos + 3; } else if (tag == '@') return annotationMemberValue(pos + 1); else if (tag == '[') { int num = ByteArray.readU16bit(info, pos + 1); return arrayMemberValue(pos + 3, num); } else { // primitive types or String. int index = ByteArray.readU16bit(info, pos + 1); constValueMember(tag, index); return pos + 3; } }
4
@Override public boolean invoke(MOB mob, List<String> commands, Physical givenTarget, boolean auto, int asLevel) { final MOB target=getTarget(mob,commands,givenTarget); if(target==null) return false; if(mob.getWorshipCharID().length()==0) { mob.tell(L("You must worship a god for this prayer to work.")); return false; } if(!target.getWorshipCharID().equals(mob.getWorshipCharID())) { mob.tell(L("@x1 must worship your god for this prayer to work.",target.name(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,verbalCastCode(mob,target,auto),auto?L("<T-NAME> become(s) filled with conviction!"):L("^S<S-NAME> @x1 for <T-YOUPOSS> religious conviction!^?",prayWord(mob))); if(mob.location().okMessage(mob,msg)) { mob.location().send(mob,msg); beneficialAffect(mob,target,asLevel,0); } } else return beneficialWordsFizzle(mob,null,L("<S-NAME> @x1 for <T-YOUPOSS> conviction, but there is no answer.",prayWord(mob))); // return whether it worked return success; }
7
public OOXMLChart( Chart c, WorkBookHandle wbh ) { // Walk up the superclass hierarchy //System.out.println("BEFORE: chartArr: " + Arrays.toString(chartArr.toArray())); for( Class obj = c.getClass(); !obj.equals( Object.class ); obj = obj.getSuperclass() ) { java.lang.reflect.Field[] fields = obj.getDeclaredFields(); for( Field field : fields ) { field.setAccessible( true ); try { // for each class/suerclass, copy all fields // from this object to the clone field.set( this, field.get( c ) ); } catch( IllegalArgumentException e ) { } catch( IllegalAccessException e ) { } } } // ttl? // chartlaout? // txpr? // name? name = c.getTitle(); if( c.hasDataLegend() ) { ooxmlLegend = Legend.createLegend( c.getLegend() ); } this.wbh = wbh; }
5
public Set<Map.Entry<Integer,Float>> entrySet() { return new AbstractSet<Map.Entry<Integer,Float>>() { public int size() { return _map.size(); } public boolean isEmpty() { return TIntFloatMapDecorator.this.isEmpty(); } public boolean contains( Object o ) { if (o instanceof Map.Entry) { Object k = ( ( Map.Entry ) o ).getKey(); Object v = ( ( Map.Entry ) o ).getValue(); return TIntFloatMapDecorator.this.containsKey(k) && TIntFloatMapDecorator.this.get(k).equals(v); } else { return false; } } public Iterator<Map.Entry<Integer,Float>> iterator() { return new Iterator<Map.Entry<Integer,Float>>() { private final TIntFloatIterator it = _map.iterator(); public Map.Entry<Integer,Float> next() { it.advance(); int ik = it.key(); final Integer key = (ik == _map.getNoEntryKey()) ? null : wrapKey( ik ); float iv = it.value(); final Float v = (iv == _map.getNoEntryValue()) ? null : wrapValue( iv ); return new Map.Entry<Integer,Float>() { private Float val = v; public boolean equals( Object o ) { return o instanceof Map.Entry && ( ( Map.Entry ) o ).getKey().equals(key) && ( ( Map.Entry ) o ).getValue().equals(val); } public Integer getKey() { return key; } public Float getValue() { return val; } public int hashCode() { return key.hashCode() + val.hashCode(); } public Float setValue( Float value ) { val = value; return put( key, value ); } }; } public boolean hasNext() { return it.hasNext(); } public void remove() { it.remove(); } }; } public boolean add( Map.Entry<Integer,Float> o ) { throw new UnsupportedOperationException(); } public boolean remove( Object o ) { boolean modified = false; if ( contains( o ) ) { //noinspection unchecked Integer key = ( ( Map.Entry<Integer,Float> ) o ).getKey(); _map.remove( unwrapKey( key ) ); modified = true; } return modified; } public boolean addAll( Collection<? extends Map.Entry<Integer, Float>> c ) { throw new UnsupportedOperationException(); } public void clear() { TIntFloatMapDecorator.this.clear(); } }; }
8
public boolean onCommand(CommandSender sender, Command cmd, String label, String[] args) { if (!plugin.hasPerm(sender, "weather", true)) { sender.sendMessage(ChatColor.YELLOW + "You do not have permission to use /" + label); return true; } Player player = (Player) sender; World world = player.getWorld(); if (args[0].equalsIgnoreCase("sunny")) { world.setStorm(false); world.setThundering(false); plugin.getServer().broadcastMessage( CraftEssence.premessage + "Weather is set to sunny"); return true; } else if (args[0].equalsIgnoreCase("storm")) { world.setStorm(true); plugin.getServer().broadcastMessage( CraftEssence.premessage + "Weather is set to storm"); return true; } else if (args[0].equalsIgnoreCase("thunder")) { world.setThundering(true); plugin.getServer().broadcastMessage( CraftEssence.premessage + "Weather is set to thundering"); return true; } else { player.sendMessage(CraftEssence.premessage + "Invalid weather command parameter"); return true; } }
4
public TrieNode getAdj(char ch){ return adj[getIndex(ch)]; }
0
private Object handleFile(Object tos, String tagName) { if (tos instanceof Header && ((Header)tos).getFile() == null) { return new FieldRef(tos, "File"); } else if (tos instanceof Media && ((Media)tos).getFile() == null) { ((Media)tos).setFileTag(tagName); return new FieldRef(tos, "File"); } return null; }
4
public void initGraph(String path){ BufferedReader file ; String line; String name, id; int y = 0; try { file = new BufferedReader(new FileReader(path)) ; while ((line = file.readLine()) != null) { for(int i = 0; i < line.length(); i++){ id = (i + ":" + y); if(line.charAt(i) == ' '){ name = "void"; this.registerNode(new GenericNode(id, name)); }else if(line.charAt(i) == 'G'){ name = "grass"; this.registerNode(new GenericNode(id, name)); }else if(line.charAt(i) == 'A'){ name = "end"; this.registerNode(new GenericNode(id, name)); }else if(line.charAt(i) == 'D'){ name = "start"; this.registerNode(new GenericNode(id, name)); }else{ name = "wall"; this.registerNode(new GenericNode(id, name)); } } y++; } file.close(); }//try catch (NullPointerException a) { System.err.println("Erreur : pointeur null"); } catch (IOException a) { System.err.println("Problème d'IO en lecture"); } }
8
public static void main(String[] args){ //check that the minimum number of command line arguments were entered if(args.length<5){ System.out.println("attack, decay, sustain amp, sustain time, release"); System.out.println("Optional: Num_of_file, names of files"); System.exit(1); } //parse all of the command line arguments to create the ADSREnvelope double attackTime = Double.parseDouble(args[0]); double decayTime = Double.parseDouble(args[1]); double sustainAmplitude = Double.parseDouble(args[2]); double sustainTime = Double.parseDouble(args[3]); double releaseTime = Double.parseDouble(args[4]); ADSREnvelope a = new ADSREnvelope(attackTime, decayTime, sustainAmplitude, releaseTime, sustainTime); if(args.length == 5) { //Create a melody from the default text file Melody m = new Melody(); //try to open the file and create the melody try{ //m = m.createMelodyFromFile("Default.txt"); //@@@@ TODO: old format!!! } catch(Exception ex) { System.out.println("An error occured in creating the melody from the file"); ex.printStackTrace(); } //Check that the melody and envelope are compatible if(!m.checkCompatibility(a,m)) throw new IllegalArgumentException("Melody and Envelope are incompatible"); //play the melody m.play(a, m); } else{ //get the number of files the user wants to play int numFiles = Integer.parseInt(args[5]); //check that the correct number of file names are present if(args.length != (6 + numFiles)) { System.out.println("Error: " + numFiles + " File names were not entered"); System.exit(2); } //try to create a melody from each file that was entered ArrayList<Melody> melody_list = new ArrayList<Melody>(); Melody n = new Melody(); try{ for(int i = 6 ; i < args.length ; i++) { n = n.createMelodyFromFile(args[i]); melody_list.add(n); } }catch(Exception ex) { System.out.println("An error occured in creating the melody from the file here. Check that the file exists and is in the correct format"); System.exit(3); } //concatenate the melodys and play them all Melody concatMelody = new Melody(); for(Melody m: melody_list) { if(!m.checkCompatibility(a,m)) throw new IllegalArgumentException("Melody and Envelope are incompatible"); concatMelody.addAll(m); } concatMelody.play(a,concatMelody); } }
9
@Override public Model getRotatedModel() { Model model = spotAnimation.getModel(); if (model == null) { return null; } int j = spotAnimation.sequence.frames[anInt1569]; Model model_1 = new Model(true, Animation.isNullFrame(j), false, model); if (!aBoolean1567) { model_1.skin(); model_1.transform(j); model_1.triangleSkin = null; model_1.vertexSkins = null; } if (spotAnimation.scaleXY != 128 || spotAnimation.scaleZ != 128) { model_1.scale(spotAnimation.scaleXY, spotAnimation.scaleXY, spotAnimation.scaleZ); } if (spotAnimation.rotation != 0) { if (spotAnimation.rotation == 90) { model_1.method473(); } if (spotAnimation.rotation == 180) { model_1.method473(); model_1.method473(); } if (spotAnimation.rotation == 270) { model_1.method473(); model_1.method473(); model_1.method473(); } } model_1.processLighting(64 + spotAnimation.lightness, 850 + spotAnimation.shading, -30, -50, -30, true); return model_1; }
8
public static void main(String[] args) { try { Experiment exp = null; // get options from XML? String xmlOption = Utils.getOption("xml", args); if (!xmlOption.equals("")) args = new XMLOptions(xmlOption).toArray(); String expFile = Utils.getOption('l', args); String saveFile = Utils.getOption('s', args); boolean runExp = Utils.getFlag('r', args); if (expFile.length() == 0) { exp = new Experiment(); try { exp.setOptions(args); Utils.checkForRemainingOptions(args); } catch (Exception ex) { ex.printStackTrace(); String result = "Usage:\n\n" + "-l <exp|xml file>\n" + "\tLoad experiment from file (default use cli options).\n" + "\tThe type is determined, based on the extension (" + FILE_EXTENSION + " or .xml)\n" + "-s <exp|xml file>\n" + "\tSave experiment to file after setting other options.\n" + "\tThe type is determined, based on the extension (" + FILE_EXTENSION + " or .xml)\n" + "\t(default don't save)\n" + "-r\n" + "\tRun experiment (default don't run)\n" + "-xml <filename | xml-string>\n" + "\tget options from XML-Data instead from parameters\n" + "\n"; Enumeration enm = ((OptionHandler)exp).listOptions(); while (enm.hasMoreElements()) { Option option = (Option) enm.nextElement(); result += option.synopsis() + "\n"; result += option.description() + "\n"; } throw new Exception(result + "\n" + ex.getMessage()); } } else { exp = read(expFile); // allow extra datasets to be added to pre-loaded experiment from command line String dataName; do { dataName = Utils.getOption('T', args); if (dataName.length() != 0) { File dataset = new File(dataName); exp.getDatasets().addElement(dataset); } } while (dataName.length() != 0); } System.err.println("Experiment:\n" + exp.toString()); if (saveFile.length() != 0) write(saveFile, exp); if (runExp) { System.err.println("Initializing..."); exp.initialize(); System.err.println("Iterating..."); exp.runExperiment(); System.err.println("Postprocessing..."); exp.postProcess(); } } catch (Exception ex) { System.err.println(ex.getMessage()); } }
9
public static FieldType convertToXMLFieldType(FieldState state) { switch (state) { case EMPTY: return FieldType.EMPTY; case WALL: return FieldType.WALL; case DIAMOND: return FieldType.DIAMOND; case PLAYER: return FieldType.PLAYER; case COMPLETED: return FieldType.COMPLETED; case GOAL: return FieldType.GOAL; case PLAYER_ON_GOAL: return FieldType.PLAYER_ON_GOAL; default: return FieldType.EMPTY; } }
7
public int getX(){ return x; }
0
private void runTest(File path) { mOutput = 0; System.out.println(path.toString()); try { LarkScript script = new LarkScript(path.getPath()); mPassed = true; // parse the script to get the expected behavior mExpectedOutput = new LinkedList<String>(); String expectedResult = ""; for (String line : script.getSource().split("\r\n|\r|\n")) { if (line.contains(OUTPUT_PREFIX)) { int start = line.indexOf(OUTPUT_PREFIX) + OUTPUT_PREFIX.length(); mExpectedOutput.add(line.substring(start)); } else if (line.contains(RESULT_PREFIX)) { int start = line.indexOf(RESULT_PREFIX) + RESULT_PREFIX.length(); expectedResult = line.substring(start); } } Interpreter interpreter = new Interpreter(new TestHost()); // load the base script //### bob: hack. assumes relative path. LarkScript base = new LarkScript("base/init.lark"); base.run(interpreter); // run the script mRunning = true; Expr resultExpr = script.run(interpreter); mRunning = false; // check the result if (resultExpr == null) { System.out.println("- fail: got null expression"); mPassed = false; } else if ((expectedResult.length() > 0) && !expectedResult.equals(resultExpr.toString())) { System.out.println("- fail: result was '" + resultExpr.toString() + "', expected '" + expectedResult + "'"); mPassed = false; } // see if we missed output for (String expected : mExpectedOutput) { System.out.println("- fail: expected '" + expected + "' but got nothing"); } } catch (IOException ex) { System.out.println("- fail: got exception loading test script"); mPassed = false; } System.out.println("- passed " + mOutput + " lines of output"); mTests++; if (mPassed) mPasses++; }
9
void createExampleWidgets () { /* Compute the widget style */ int style = getDefaultStyle(); if (singleButton.getSelection ()) style |= SWT.SINGLE; if (multiButton.getSelection ()) style |= SWT.MULTI; if (horizontalButton.getSelection ()) style |= SWT.H_SCROLL; if (verticalButton.getSelection ()) style |= SWT.V_SCROLL; if (borderButton.getSelection ()) style |= SWT.BORDER; /* Create the example widgets */ list1 = new List (listGroup, style); list1.setItems (ListData1); }
5
public T arbitrary(Random random,long size) { if (random.nextDouble() < probability) { return null; } else { return generator.arbitrary(random, size); } }
1
public String getProtocol() { return this.protocol; }
0
public void mouseReleased(MouseEvent event) { transitionInFlux = false; if (event.isPopupTrigger()) showPopup(event); State[] states = getView().getDrawer().getAutomaton().getStates(); int count = 0; for(int k = 0; k < states.length; k++){ if(states[k].isSelected()){ count++; } } Rectangle bounds = getView().getDrawer().getSelectionBounds(); if(count == 1 && bounds.isEmpty() && lastClickedState!=null) lastClickedState.setSelect(false); bounds = new Rectangle(0, 0, -1, -1); getView().getDrawer().setSelectionBounds(bounds); lastClickedState = null; lastClickedTransition = null; getView().repaint(); }
6
public void setFunConsumoUltimoMes(Integer funConsumoUltimoMes) { this.funConsumoUltimoMes = funConsumoUltimoMes; }
0
public void insertDisc(int col, CellState player) { if (!isFull(col)) { // XXX getrowdepth in tmp_var speichern damit nicht 2x aufrufen? model.setCell(col, getRowDepth(col), player); this.isWinning(player, col, getRowDepth(col)); } if (isFull()) { EventSystem.getInstance().queueEvent(new GameStatusUpdateEvent(Status.DRAW)); } }
2
public int hgetbits(int N) { totbit += N; int val = 0; int pos = buf_byte_idx; if (pos+N < BUFSIZE) { while (N-- > 0) { val <<= 1; val |= ((buf[pos++]!=0) ? 1 : 0); } } else { while (N-- > 0) { val <<= 1; val |= ((buf[pos]!=0) ? 1 : 0); pos = (pos+1) & BUFSIZE_MASK; } } buf_byte_idx = pos; return val; }
5
public static void main(String[] args) { ArrayList<Product> products = new ArrayList<>(); try { BufferedReader fileReader = new BufferedReader(new FileReader("D:\\Soft\\JAVA\\LoopsMethodsClasses\\src\\ListInput.txt"));; File fileProducts = new File("D:\\Soft\\JAVA\\LoopsMethodsClasses\\src\\ListOutput.txt"); fileProducts.createNewFile(); BufferedWriter fileWriter = new BufferedWriter(new FileWriter("D:\\Soft\\JAVA\\LoopsMethodsClasses\\src\\ListOutput.txt")); while(true){ String line = fileReader.readLine(); if(line == null){ fileReader.close(); break; } String[] input = line.split(" "); products.add(new Product(input[0], new BigDecimal(input[1]))); } Collections.sort(products); for (Product product : products){ System.out.println(product.getPrice() + " " + product.getName()); fileWriter.write(product.getPrice() + " " + product.getName()); fileWriter.newLine(); } fileWriter.close(); } catch (IOException e){ System.out.println("Error"); } }
4
public static void call(final String mapping, final String data) throws Exception { // delimited by a comma // text qualified by double quotes // ignore first record final Parser pzparser = DefaultParserFactory.getInstance().newDelimitedParser(new File(mapping), new File(data), ',', '"', true); final DataSet ds = pzparser.parse(); // re order the data set by last name final OrderBy orderby = new OrderBy(); orderby.addOrderColumn(new OrderColumn("CITY", false)); orderby.addOrderColumn(new OrderColumn("LASTNAME", true)); ds.orderRows(orderby); final String[] colNames = ds.getColumns(); while (ds.next()) { if (ds.isRecordID("header")) { System.out.println(">>>>found header"); System.out.println("COLUMN NAME: INDICATOR VALUE: " + ds.getString("RECORDINDICATOR")); System.out.println("COLUMN NAME: HEADERDATA VALUE: " + ds.getString("HEADERDATA")); System.out.println("==========================================================================="); continue; } if (ds.isRecordID("trailer")) { System.out.println(">>>>found trailer"); System.out.println("COLUMN NAME: INDICATOR VALUE: " + ds.getString("RECORDINDICATOR")); System.out.println("COLUMN NAME: TRAILERDATA VALUE: " + ds.getString("TRAILERDATA")); System.out.println("==========================================================================="); continue; } for (final String colName : colNames) { System.out.println("COLUMN NAME: " + colName + " VALUE: " + ds.getString(colName)); } System.out.println("==========================================================================="); } System.out.println(">>>>>>ERRORS!!!"); final Iterator errors = ds.getErrors().iterator(); while (errors.hasNext()) { final DataError dataError = (DataError) errors.next(); System.out.println("ERROR: " + dataError.getErrorDesc() + " LINE NUMBER: " + dataError.getLineNo()); } }
5
public void saveToFile (String fileName) { ZipOutputStream zipOut = null; // create new ZIP file try { zipOut = new ZipOutputStream(new FileOutputStream(fileName)); } catch (FileNotFoundException e1) { // TODO Auto-generated catch block e1.printStackTrace(); return; } // enable compression zipOut.setMethod(ZipOutputStream.DEFLATED); // set compression level to max. zipOut.setLevel (9); // save trips try { tripDB.write(zipOut); } catch (Exception e1) { // TODO Auto-generated catch block e1.printStackTrace(); } // save rosters try { rosterDB.write(zipOut); } catch (Exception e1) { // TODO Auto-generated catch block e1.printStackTrace(); } // save rivers try { riverDB.write(zipOut); } catch (Exception e1) { // TODO Auto-generated catch block e1.printStackTrace(); } try { zipOut.close(); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } }
5
public void visitSwitchStmt(final SwitchStmt stmt) { if (CodeGenerator.DEBUG) { System.out.println("code for " + stmt); } stmt.visitChildren(this); genPostponed(stmt); final Label[] targets = new Label[stmt.targets().length]; for (int i = 0; i < targets.length; i++) { targets[i] = stmt.targets()[i].label(); } method.addInstruction(Opcode.opcx_switch, new Switch(stmt .defaultTarget().label(), targets, stmt.values())); stackHeight -= 1; }
2
public static String MD5(String plainText) { StringBuffer buf = new StringBuffer(""); try { MessageDigest md = MessageDigest.getInstance("MD5"); md.update(plainText.getBytes()); byte b[] = md.digest(); int i; for (int offset = 0; offset < b.length; offset++) { i = b[offset]; if (i < 0) i += 256; if (i < 16) buf.append("0"); buf.append(Integer.toHexString(i)); } } catch (NoSuchAlgorithmException e) { LogUtil.exception(logger, e); } return buf.toString(); }
4
public void verify() throws MVDException { SimpleQueue<Node> queue = new SimpleQueue<Node>(); HashSet<Node> printed = new HashSet<Node>(); start.verify(); queue.add( start ); while ( !queue.isEmpty() ) { Node node = queue.poll(); node.verify(); ListIterator<Arc> iter = node.outgoingArcs(this); while ( iter.hasNext() ) { Arc a = iter.next(); a.verify(); a.to.printArc( a ); printed.add( a.to ); if ( a.to != end && a.to.allPrintedIncoming(constraint) ) { queue.add( a.to ); } } } Iterator<Node> iter2 = printed.iterator(); while ( iter2.hasNext() ) { Node n = iter2.next(); n.reset(); } end.verify(); }
5
public void moveRight() { if (ducked == false) { speedX = MOVESPEED; } }
1
OlogProperties(){ preferences = Preferences.userNodeForPackage(OlogClient.class); try { File userCFPropertiesFile = new File(System.getProperty( "olog.properties", "")); File userHomeCFPropertiesFile = new File(System .getProperty("user.home") + "/olog.properties"); File systemCFPropertiesFile = null; if (System.getProperty("os.name").startsWith("Windows")) { systemCFPropertiesFile = new File("/olog.properties"); } else if (System.getProperty("os.name").startsWith("Linux")) { systemCFPropertiesFile = new File( "/etc/olog.properties"); } else { systemCFPropertiesFile = new File( "/etc/olog.properties"); } defaultProperties = new Properties(); try { defaultProperties.load(this.getClass().getResourceAsStream( "/config/olog.properties")); } catch (Exception e) { // Do nothing simply use an empty Properties object as default. } // Not using to new Properties(default Properties) constructor to // make the hierarchy clear. // TODO replace using constructor with default. systemCFProperties = new Properties(defaultProperties); if (systemCFPropertiesFile.exists()) { systemCFProperties.load(new FileInputStream( systemCFPropertiesFile)); } userHomeCFProperties = new Properties(systemCFProperties); if (userHomeCFPropertiesFile.exists()) { userHomeCFProperties.load(new FileInputStream( userHomeCFPropertiesFile)); } userCFProperties = new Properties(userHomeCFProperties); if (userCFPropertiesFile.exists()) { userCFProperties .load(new FileInputStream(userCFPropertiesFile)); } } catch (Exception e) { e.printStackTrace(); } }
7
@Override protected void setAttrs(User model, PreparedStatement stmt) throws SQLException { { stmt.setString(1, model.getHandle()); } if (model.getCreatedAtMillis() == null) { stmt.setNull(2, java.sql.Types.INTEGER); } else { stmt.setLong(2, model.getCreatedAtMillis()); } { stmt.setInt(3, model.getNumPosts()); } if (model.getSomeDate() == null) { stmt.setNull(4, java.sql.Types.DATE); } else { stmt.setDate(4, new Date(model.getSomeDate())); } if (model.getSomeDatetime() == null) { stmt.setNull(5, java.sql.Types.DATE); } else { stmt.setTimestamp(5, new Timestamp(model.getSomeDatetime())); } if (model.getBio() == null) { stmt.setNull(6, java.sql.Types.CHAR); } else { stmt.setString(6, model.getBio()); } if (model.getSomeBinary() == null) { stmt.setNull(7, java.sql.Types.BINARY); } else { stmt.setBytes(7, model.getSomeBinary()); } if (model.getSomeFloat() == null) { stmt.setNull(8, java.sql.Types.DOUBLE); } else { stmt.setDouble(8, model.getSomeFloat()); } if (model.getSomeDecimal() == null) { stmt.setNull(9, java.sql.Types.DECIMAL); } else { stmt.setDouble(9, model.getSomeDecimal()); } if (model.isSomeBoolean() == null) { stmt.setNull(10, java.sql.Types.BOOLEAN); } else { stmt.setBoolean(10, model.isSomeBoolean()); } stmt.setLong(11, model.getId()); }
8
public static String quote(String in) { StringBuilder buf = new StringBuilder(); for(int i = 0; i < in.length(); i++) { char c = in.charAt(i); if((c == '$') || (c == '{') || (c == '}')) { buf.append('$'); buf.append(c); } else { buf.append(c); } } return(buf.toString()); }
4