text
stringlengths
14
410k
label
int32
0
9
public static User getUserByUsername(String username, ArrayList<User> users) { // search for user from array of users for (User u : users) { if (u.getUsername().equalsIgnoreCase(username)) { return u; } } return null; }
2
private boolean jj_2_1(int xla) { jj_la = xla; jj_lastpos = jj_scanpos = token; try { return !jj_3_1(); } catch(LookaheadSuccess ls) { return true; } finally { jj_save(0, xla); } }
1
public boolean removeFreeTile(int x, int y) { for (int i = 0; i < freeTiles.size(); i++) { Tile t = freeTiles.get(i); if (t.getX() == x && t.getY() == y) { freeTiles.remove(i); return true; } } return false; }
3
private String comboList(){ if(currentComboNo == 1){ return "Punch1"; } if(currentComboNo == 2){ return "Punch2"; } if(currentComboNo == 3){ return "Kick"; } if(currentComboNo == 4){ return "Push"; } if(currentComboNo == 5){ return "Palm"; } if(currentComboNo == 6){ return "PushKick"; } if(currentComboNo == 7){ return "RH Kick"; } if(currentComboNo == 8){ return "Power"; } return "none"; }
8
public static MethodData read(ClassData classData, MethodInfo methodDesc) throws FormatException { String methodName = methodDesc.resolveName(); String descriptor = methodDesc.resolveDescriptor(); List<Type> params = extractParamTypes(descriptor); Type returnType = extractReturnType(descriptor); boolean isStatic = methodDesc.accessFlags.contains(AccessFlags.STATIC); boolean isAbstract = methodDesc.accessFlags.contains(AccessFlags.ABSTRACT); boolean isNative = methodDesc.accessFlags.contains(AccessFlags.NATIVE); List<Instruction> code = null; StackMapTable stackMapTable = null; int stackFrameSize = 0, opStackSize = 0; for (Attribute attr : methodDesc.attributes) { if (attr.getType() == Attribute.AttributeType.CODE) { if (isAbstract) { throw new FormatException("Abstract method contains code attribute"); } Code codeDesc = (Code)attr; code = Instruction.readCode(codeDesc.code, classData.constantPool); stackFrameSize = codeDesc.maxLocals + 1; opStackSize = codeDesc.maxStack + 1; for (Attribute codeAttr : codeDesc.attributes) { if (codeAttr.getType() == Attribute.AttributeType.STACK_MAP_TABLE) { stackMapTable = (StackMapTable) codeAttr; } } } } if (code == null && !(isNative || isAbstract)) throw new FormatException("Method doesn't contain code"); final MethodData methodData = new MethodData(classData, methodName, isStatic, isAbstract, isNative, params, returnType, code, stackFrameSize, opStackSize); if (stackMapTable != null) { methodData.loadedStaticInfo = MethodStaticInfo.load(methodData, stackMapTable); } return methodData; }
9
public String subMessage(String message, String pName, Integer remWarnings) { String remWarningRegex = "%remwarning%"; String sRegex = "%s%"; String nameRegex = "%player%"; String actionRegex = "%action%"; String action = (getBanAction()) ? "banned" : "kicked"; String s = (remWarnings == 1) ? "" : "s"; message = message.replaceAll(remWarningRegex, remWarnings.toString()); message = message.replaceAll(sRegex, s); message = message.replaceAll(nameRegex, pName); message = message.replaceAll(actionRegex, action); return message; }
2
protected void processRequest(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException, SQLException { response.setContentType("text/html;charset=UTF-8"); PrintWriter out = response.getWriter(); String userType = "Guest"; String firstName = ""; String lastName = ""; HttpSession httpSession; // makes sure the user is a customer if (request.getSession(false) != null) { httpSession = request.getSession(); if (httpSession.getAttribute("userType") != null) { if (httpSession.getAttribute("userType").equals("customer")) { Customer customer = (Customer) httpSession.getAttribute("user"); firstName = customer.getFirstName(); lastName = customer.getLastName(); userType = "customer"; } else if (httpSession.getAttribute("userType").equals("contractor")) { response.sendRedirect("homePage"); return; } else if (httpSession.getAttribute("userType").equals("admin")) { response.sendRedirect("homePage"); return; } } else{ response.sendRedirect("homePage"); return; } } try { out.println("<?xml version = \"1.0\" encoding = \"utf-8\" ?>"); out.println("<!DOCTYPE html PUBLIC \"-//W3C//DTD XHTML 1.0 Strict//EN\""); out.println("\"http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd\">"); out.println("<!--"); out.println("Search Results for Lauren's List Web Site"); out.println("-->"); out.println("<html xmlns=\"http://www.w3.org/1999/xhtml\">"); out.println("<head>"); out.println("<meta http-equiv=\"Content-Type\" content=\"text/html; charset=utf-8\" />"); out.println("<title> Payment </title>"); out.println("<link rel=\"stylesheet\" href=\"http://yui.yahooapis.com/pure/0.3.0/pure-nr-min.css\" />"); out.println("<link rel=\"stylesheet\" href=\"style.css\" />"); out.println("</head>"); out.println("<body class=\"pure-skin-matt\">"); out.println("<div id=\"header\">"); out.println("<div class=\"bottom_header\">"); out.println("<a href=\"homePage\"><img src=\"images/LLLogoSmall.jpg\" alt=\"Lauren's List Logo\" /></a>"); out.println("<h1> Lauren's List </h1>"); out.println("</div>"); out.println("<div class=\"right\" style=\"display:inline-block\">"); out.println("<br/>"); if (userType.equals("Guest")) { out.println("<a class=\"pure-button\" href=\"login.html\"> Login </a> &nbsp;"); out.println("<a class=\"pure-button\" href=\"customerOrContractor.html\"> Create Account </a> &nbsp;"); } else if (userType.equals("customer")) { out.println("<a class=\"pure-button\" href=\"changePassword\"> " + firstName + " " + lastName + " </a> &nbsp;"); out.println("<a class=\"pure-button\" href=\"logout\"> Logout </a> &nbsp;<br/><br/>"); } out.println("</div>"); out.println("</div>"); out.println("<div id=\"top\" class=\"pure-menu-horizontal pure-menu pure-menu-open\">"); out.println("<ul>"); out.println("<li><a href=\"homePage\">Home</a></li>"); out.println("<li><a href=\"search?search=\">Browse Contractors</a></li>"); out.println("<li><a href=\"about\">About</a></li>"); out.println("</ul>"); out.println("</div>"); out.println("<div id=\"center\">"); out.println("<form action=\"paymentConfirm\" method=\"post\" class=\"pure-form pure-form-aligned\">"); out.println("<div class=\"center\">"); out.println("<fieldset>"); out.println("<legend> Payment Information </legend>"); out.println("<div class=\"pure-control-group\">"); out.println("<label for=\"firstNamePay\">First Name</label>"); out.println("<input name=\"firstNamePay\" type=\"text\" required=\"required\" />"); out.println("</div>"); out.println("<div class=\"pure-control-group\">"); out.println("<label for=\"lastNamePay\">Last Name</label>"); out.println("<input name=\"lastNamePay\" type=\"text\" required=\"required\" />"); out.println("</div>"); out.println("<div class=\"pure-control-group\">"); out.println("<label for=\"street1Pay\">Street 1</label>"); out.println("<input name=\"street1Pay\" type=\"text\" required=\"required\" />"); out.println("</div>"); out.println("<div class=\"pure-control-group\">"); out.println("<label for=\"street2Pay\">Street 2</label>"); out.println("<input name=\"street2Pay\" type=\"text\" />"); out.println("</div>"); out.println("<div class=\"pure-control-group\">"); out.println("<label for=\"cityPay\">City</label>"); out.println("<input name=\"cityPay\" type=\"text\" required=\"required\" />"); out.println("</div>"); out.println("<div class=\"pure-control-group\">"); out.println("<label for=\"statePay\">State</label>"); out.println("<select name=\"statePay\">"); out.println("<option value=\"\">Select a State</option>"); out.println("<option value=\"AL\">Alabama</option>"); out.println("<option value=\"AK\">Alaska</option>"); out.println("<option value=\"AZ\">Arizona</option>"); out.println("<option value=\"AR\">Arkansas</option>"); out.println("<option value=\"CA\">California</option>"); out.println("<option value=\"CO\">Colorado</option>"); out.println("<option value=\"CT\">Connecticut</option>"); out.println("<option value=\"DE\">Delaware</option>"); out.println("<option value=\"DC\">District Of Columbia</option>"); out.println("<option value=\"FL\">Florida</option>"); out.println("<option value=\"GA\">Georgia</option>"); out.println("<option value=\"HI\">Hawaii</option>"); out.println("<option value=\"ID\">Idaho</option>"); out.println("<option value=\"IL\">Illinois</option>"); out.println("<option value=\"IN\">Indiana</option>"); out.println("<option value=\"IA\">Iowa</option>"); out.println("<option value=\"KS\">Kansas</option>"); out.println("<option value=\"KY\">Kentucky</option>"); out.println("<option value=\"LA\">Louisiana</option>"); out.println("<option value=\"ME\">Maine</option>"); out.println("<option value=\"MD\">Maryland</option>"); out.println("<option value=\"MA\">Massachusetts</option>"); out.println("<option value=\"MI\">Michigan</option>"); out.println("<option value=\"MN\">Minnesota</option>"); out.println("<option value=\"MS\">Mississippi</option>"); out.println("<option value=\"MO\">Missouri</option>"); out.println("<option value=\"MT\">Montana</option>"); out.println("<option value=\"NE\">Nebraska</option>"); out.println("<option value=\"NV\">Nevada</option>"); out.println("<option value=\"NH\">New Hampshire</option>"); out.println("<option value=\"NJ\">New Jersey</option>"); out.println("<option value=\"NM\">New Mexico</option>"); out.println("<option value=\"NY\">New York</option>"); out.println("<option value=\"NC\">North Carolina</option>"); out.println("<option value=\"ND\">North Dakota</option>"); out.println("<option value=\"OH\">Ohio</option>"); out.println("<option value=\"OK\">Oklahoma</option>"); out.println("<option value=\"OR\">Oregon</option>"); out.println("<option value=\"PA\">Pennsylvania</option>"); out.println("<option value=\"RI\">Rhode Island</option>"); out.println("<option value=\"SC\">South Carolina</option>"); out.println("<option value=\"SD\">South Dakota</option>"); out.println("<option value=\"TN\">Tennessee</option>"); out.println("<option value=\"TX\">Texas</option>"); out.println("<option value=\"UT\">Utah</option>"); out.println("<option value=\"VT\">Vermont</option>"); out.println("<option value=\"VA\">Virginia</option>"); out.println("<option value=\"WA\">Washington</option>"); out.println("<option value=\"WV\">West Virginia</option>"); out.println("<option value=\"WI\">Wisconsin</option>"); out.println("<option value=\"WY\">Wyoming</option>"); out.println("</select>"); out.println("</div>"); out.println("<div class=\"pure-control-group\">"); out.println("<label for=\"zipPay\">Zip</label>"); out.println("<input name=\"zipPay\" type=\"text\" size = \"5\" required=\"required\" /> "); out.println("</div>"); out.println("<div class=\"pure-control-group\">"); out.println("<label for=\"creditCardPay\">Credit Card Number</label>"); out.println("<input name=\"creditCardPay\" type=\"text\" required=\"required\" /> "); out.println("</div>"); out.println("<div class=\"pure-control-group\">"); out.println("<label for=\"securityPay\">Security Number</label>"); out.println("<input name=\"securityPay\" type=\"text\" required=\"required\" /> "); out.println("</div>"); out.println("<div class=\"pure-control-group\">"); out.println("<label for=\"expirationPay\">Expiration Date</label>"); out.println("<select name=\"expirationPay\">"); out.println("<option value=\"\">Select a Month</option>"); out.println("<option value=\"01\">01 - Jan</option>"); out.println("<option value=\"02\">02 - Feb</option>"); out.println("<option value=\"03\">03 - Mar</option>"); out.println("<option value=\"04\">04 - Apr</option>"); out.println("<option value=\"05\">05 - May</option>"); out.println("<option value=\"06\">06 - Jun</option>"); out.println("<option value=\"07\">07 - Jul</option>"); out.println("<option value=\"08\">08 - Aug</option>"); out.println("<option value=\"09\">09 - Sep</option>"); out.println("<option value=\"10\">10 - Oct</option>"); out.println("<option value=\"11\">11 - Nov</option>"); out.println("<option value=\"12\">12 - Dec</option>"); out.println("</select>"); out.println("</div>"); String email = ""; if(request.getParameter("email") != null){ email = request.getParameter("email"); } else{ response.sendRedirect("homePage"); return; } out.println("<input name=\"contractorEmail\" type=\"hidden\" value=\"" + email + "\" /> "); out.println("<div class=\"pure-controls\">"); out.println("<button type=\"submit\" class=\"pure-button pure-button-primary\">Submit</button> &nbsp;"); out.println("<button type=\"reset\" class=\"pure-button\">Reset</button>"); out.println("</div>"); out.println("</fieldset>"); out.println("</div>"); out.println("</form>"); out.println("</div>"); out.println("</body>"); out.println("</html>"); } catch (Exception ex) { ex.printStackTrace(); } finally { out.close(); } }
9
public PacketFactory(int totalNumberOfPackets,int packetSize, int totalNumberOfInputBuffers, long SEED) { //initialize the seed used by the simulator this.SEED = SEED; //initialize the random rnd = new Random(this.SEED); //initialize the packet sequence sequence = 1; //ensure at least 1 packet is created if (totalNumberOfPackets < 1) { //default number of packets totalNumberOfPackets = 1; } //set the total number of packets to make this.totalNumberOfPackets = totalNumberOfPackets; //set packets created to the simulation packetsCreated = 0; //set packets delivered to the simulation packetsDelivered = 0; //set the size of a packet this.packetSize = packetSize; //set the time created this.timeCreated = 0; //initialize the Packet Created buffers packetCreated = new LinkedList(); //set the total number of input buffers this.totalNumberOfInputBuffers = totalNumberOfInputBuffers; //create all packets needed MakeAllPackets(); }
1
@Override public String execute() throws Exception { HttpSession session = ServletActionContext.getRequest().getSession(); User user = (User) session.getAttribute(com.ccf.action.user.UserLoginAction.USER_SESSION); if (user == null) return LOGIN; if (action == null || cid == null || sender == null || receiver == null) return "null"; if (!this.service.verifyLeader(Integer.parseInt(cid), user.getUid())) // if current user isn't the leader return LOGIN; // sender means applicant, why? cuz that's him sent out this join_club_apply if (action.equals("approve")) { // let that guy be a member first this.service.addANewMember(Integer.parseInt(cid), Integer.parseInt(sender)); // then send a newbie-message to every old member, update relative's notification this.service.approveJoinClubApply(Integer.parseInt(cid), Integer.parseInt(sender)); return SUCCESS; } if (action.equals("reject")) { this.service.rejectJoinClubApply(Integer.parseInt(cid), Integer.parseInt(sender)); return SUCCESS; } return ERROR; }
8
public Object getField(Integer field) { switch(field) { case 1: return field1; case 2: return field2; case 3: return field3; case 4: return field4; case 5: return field5; case 6: return field6; case 7: return field7; case 8: return field8; } throw new IllegalArgumentException("Invalid field."); }
8
ImmutableListIterator<? extends T> current() { if (current == null) { l = left.iterator(); current = l; } if (current == l && !current.hasNext()) { r = right.iterator(); current = r; } return current; }
4
public static Alignment score_all_refs(String hyp, List<String> refs, List<String> reflens, List<String> refids, String refspan, String hypspan, CostFunction costfunc, TerScorer calc) { double totwords = 0; String ref; String refid = ""; String bestref = ""; @SuppressWarnings("unused") String reflen = ""; Alignment bestresult = null; if(has_span && refs.size() > 1) { System.out.println("Error, translation spans should only be used with SINGLE reference"); System.exit(1); } calc.setRefLen(reflens); /* For each reference, compute the TER */ for (int i = 0; i < refs.size(); ++i) { ref = (String) refs.get(i); if(!refids.isEmpty()) refid = refids.get(i); if(has_span) { calc.setRefSpan(refspan); calc.setHypSpan(hypspan); } Alignment result = calc.TER(hyp, ref, costfunc); if ((bestresult == null) || (bestresult.numEdits > result.numEdits)) { bestresult = result; if(!refids.isEmpty()) bestref = refid; } totwords += result.numWords; } bestresult.numWords = ((double) totwords) / ((double) refs.size()); if(!refids.isEmpty()) bestresult.bestRef = bestref; return bestresult; }
9
public List<String> loadExclusionWords(File path) throws FileNotFoundException, IOException { List<String> list = new ArrayList<>(); BufferedReader br = new BufferedReader(new FileReader(path)); while (br.ready()) { String line = br.readLine(); if (line.trim().length() > 0 && !list.contains(line.trim())) list.add(line.trim()); } Logger.getGlobal().log(Level.FINEST, "Loaded exclusion {0} words.", list.size()); return list; }
3
private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton1ActionPerformed try{ CashPurseAccount cashPurseAccount = new CashPurseAccount(); setCursor(Cursor.getPredefinedCursor(Cursor.WAIT_CURSOR)); boolean isSuccess = cashPurseAccount.depositCashPurse(details.getServerID(), details.getAssetID(), details.getNymID(), details.getPurse(), selectedIndices, jTextField1.getText()); if (isSuccess) { JOptionPane.showMessageDialog(this, "Cash Purse deposited successfully", "Cash Purse Deposit Success", JOptionPane.INFORMATION_MESSAGE); CashPurseDetails cashDetails = new CashPurseAccount().getCashPurseDetails(details.getServerID()+":"+details.getAssetID()+":"+details.getNymID()); CashPurseAccountBottomPanel.populateCashPurseDetails(cashDetails); CashPurseAccountTopPanel.populateCashPurseDetails(cashDetails, cashDetails.getBalance()); MainPage.reLoadAccount(); //CashPurseAccountBottomPanel.refreshGrid(cashPurseAccount.refreshGridData(details.getServerID(), details.getAssetID(), details.getNymID())); } else { if(Helpers.getObj()!=null){ new CashPurseExportDetails(null, true,(String)Helpers.getObj(),false).setVisible(true); }else JOptionPane.showMessageDialog(this, "Error in cash purse deposit", "Server Error", JOptionPane.ERROR_MESSAGE); } } catch (Exception e) { e.printStackTrace(); } finally { setCursor(Cursor.getDefaultCursor()); } this.dispose(); }//GEN-LAST:event_jButton1ActionPerformed
3
public static void inBattle(){ while (GlobalParams.inBattle) { new Enemy(GlobalParams.enemyName); System.out.println("Чем нанести удар?"); System.out.println("Кулаки - 1"); if (GlobalParams.swordWeapon){System.out.println("Мечь - 2");} new ToSay(ToSay.key); if (ToSay.key.equals(GlobalParams.one)){ weapon = 1; playerDamage(); Enemy.healthPoint(); Enemy.enemyDamage(); battelCheck(); } if (GlobalParams.swordWeapon){ if (ToSay.key.equals(GlobalParams.two)){ weapon = 2; playerDamage(); Enemy.healthPoint(); Enemy.enemyDamage(); battelCheck(); } } } }
5
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(ChoixGeantDeGivre.class.getName()).log(java.util.logging.Level.SEVERE, null, ex); } catch (InstantiationException ex) { java.util.logging.Logger.getLogger(ChoixGeantDeGivre.class.getName()).log(java.util.logging.Level.SEVERE, null, ex); } catch (IllegalAccessException ex) { java.util.logging.Logger.getLogger(ChoixGeantDeGivre.class.getName()).log(java.util.logging.Level.SEVERE, null, ex); } catch (javax.swing.UnsupportedLookAndFeelException ex) { java.util.logging.Logger.getLogger(ChoixGeantDeGivre.class.getName()).log(java.util.logging.Level.SEVERE, null, ex); } //</editor-fold> /* * Create and display the dialog */ java.awt.EventQueue.invokeLater(new Runnable() { public void run() { ChoixGeantDeGivre dialog = new ChoixGeantDeGivre(new javax.swing.JFrame(), true, lGeant); dialog.addWindowListener(new java.awt.event.WindowAdapter() { @Override public void windowClosing(java.awt.event.WindowEvent e) { System.exit(0); } }); dialog.setVisible(true); } }); }
6
public static List<Long> parseLongList(final Context context, final int position) { if (position < 0 || context.arguments.size() <= position) return null; final List<Long> values = new ArrayList<Long>(); for (final String s : context.arguments.get(position).split(",")) try { values.add(Long.parseLong(s)); } catch (final Exception e) { continue; } if (values.size() == 0) return null; return values; }
5
public static void main(String[] args) { try { EventQueue.invokeLater(new Runnable() { @Override public void run() { new MainWindow().setVisible( true ); } }); } catch(Exception exc) { System.err.println( exc.getLocalizedMessage() ); } }
1
@Override public boolean tick(Tickable ticking, int tickID) { if(!super.tick(ticking,tickID)) return false; if(tickID==Tickable.TICKID_MOB) { if(nextDirection==-999) return true; if((theTrail==null) ||(affected == null) ||(!(affected instanceof MOB))) return false; final MOB mob=(MOB)affected; if(nextDirection==999) { mob.tell(L("The hunt seems to pause here.")); nextDirection=-2; unInvoke(); } else if(nextDirection==-1) { mob.tell(L("The hunt dries up here.")); nextDirection=-999; unInvoke(); } else if(nextDirection>=0) { mob.tell(L("The hunt seems to continue @x1.",CMLib.directions().getDirectionName(nextDirection))); nextDirection=-2; } } return true; }
9
public AutomatonType getAutomatonType(){ if(this.type!= null) if(this.type.equals("AFD")) return AutomatonType.AFD; else if(this.type.equals("AFN")) return AutomatonType.AFN; else if(this.type.equals("AFNE")) return AutomatonType.AFNE; else return AutomatonType.UNKNOWN; return AutomatonType.UNKNOWN; }
4
public Entity findEntity(int ID, String layerName) { Layer L = findLayerByName(layerName); if (L != null) { for (Entity e : L.getEntList() ) { if (e.getID() == ID) { System.out.println("FoundEntity"); return e; } } System.out.println("NoEntityFound"); return new Entity(-1); } else { System.out.println("NoEntityFound"); return new Entity(-1); } }
3
@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; final boolean success=proficiencyCheck(mob,0,auto); if(success) { final CMMsg msg=CMClass.getMsg(mob,target,this,verbalCastCode(mob,target,auto),auto?L("A soft white glow surrounds <T-NAME>."):L("^S<S-NAME> @x1, delivering a light invigorating touch to <T-NAMESELF>.^?",prayWord(mob))); if(mob.location().okMessage(mob,msg)) { mob.location().send(mob,msg); final int healing=CMLib.dice().roll(3,adjustedLevel(mob,asLevel),10); if(target.maxState().getFatigue()>Long.MIN_VALUE/2) target.curState().adjFatigue(-(target.curState().getFatigue()/2),target.maxState()); target.curState().adjMovement(healing,target.maxState()); target.tell(L("You feel slightly more invigorated!")); lastCastHelp=System.currentTimeMillis(); } } else beneficialWordsFizzle(mob,target,auto?"":L("<S-NAME> @x1 for <T-NAMESELF>, but nothing happens.",prayWord(mob))); // return whether it worked return success; }
7
@Override public void close() { // TODO Auto-generated method stub if(os != null){ try { os.flush(); os.close(); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } os = null; } if(is != null){ try { is.close(); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } is = null; } if(socket != null){ try { socket.close(); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } socket = null; } connected = false; }
6
static Method getMethod(Class cls,String name,Object [] args) { Class [] args_cls = new Class[args.length]; for (int i=0; i<args.length; i++) { if (args[i] instanceof Boolean) { args_cls[i] = Boolean.TYPE; } else if (args[i] instanceof Character) { args_cls[i] = Character.TYPE; } else if (args[i] instanceof Integer) { args_cls[i] = Integer.TYPE; } else if (args[i] instanceof Double) { args_cls[i] = Double.TYPE; } else if (args[i] instanceof Float) { args_cls[i] = Float.TYPE; } else if (args[i] instanceof GraphicsConfiguration) { // hack to make subclasses of GraphicsConfiguration work args_cls[i] = GraphicsConfiguration.class; } else { args_cls[i] = args[i].getClass(); } } try { return cls.getMethod(name, args_cls); } catch (NoSuchMethodException ex) { return null; } }
8
@Override public boolean equals(Object other){ if(other instanceof HttpBodyResponse){ HttpBodyResponse otherBody = (HttpBodyResponse) other; return contenido.equals(otherBody.contenido); } return false; }
1
public Song getPlayed() { if (isPaused) { MyTunes.playerThread.resume(); Song ret = isPlaying() ? current : null; MyTunes.playerThread.suspend(); return ret; } return isPlaying() ? current : null; }
3
public static String trim(String message) { while (message.startsWith(" ")) { message = message.substring(1); } while (message.endsWith(" ")) { message = message.substring(0, message.length() - 1); } return message; }
2
void frameFromCds() { for (Exon ex : this) { // No frame info? => try to find matching CDS if (ex.getFrame() < 0) { // Chech a CDS that matches an exon for (Cds cds : getCds()) { // CDS matches the exon coordinates? => Copy frame info if (isStrandPlus() && (ex.getStart() == cds.getStart())) { ex.setFrame(cds.getFrame()); break; } else if (isStrandMinus() && (ex.getEnd() == cds.getEnd())) { ex.setFrame(cds.getFrame()); break; } } } } }
7
private boolean jj_3_13() { if (jj_scan_token(COMMA)) return true; if (jj_3R_31()) return true; return false; }
2
@Override public void run(Player activator, List<Player> allPlayers) { for (Player player : allPlayers){ int[][] strength = player.getBoard().getStrengthMap(); for(int i = 0; i<strength.length; i++){ for(int j = 0; j<strength[0].length; j++){ if (strength[i][j] == 1) strength[i][j]++; } } } }
4
public void run(String[] args) throws FileNotFoundException, IOException { try { if (PCSCManager.getCard() != null) { PCSCManager.disconnect(); } else { Logger.log("Desconectado com sucesso."); } } catch (CardException e) { } }
2
public static String capitalize(String s) { final String c = Strings.toString(s); return c.length() >= 2 ? c.substring(0, 1).toUpperCase() + c.substring(1) : c.length() >= 1 ? c.toUpperCase() : c; }
2
@Override public boolean accept(File dir, String name) { for(String s : extensions) { if((name.toLowerCase().endsWith(s+".xml") || name.toLowerCase().endsWith(s+".bin")) && new File(dir,name).exists()) return true; } return false; }
4
@Override public int loop() { if(startscript) { if(task == null || !task.hasNext()) { task = container.iterator(); } else { final Node curr = task.next(); if(curr.activate()) { curr.execute(); } } } return stop; }
4
@Override public Component getTableCellRendererComponent(JTable table, Object value, boolean isSelected, boolean hasFocus, int row, int column){ super.getTableCellRendererComponent(table,value,isSelected,hasFocus,row,column) ; //System.out.println("RenduCelluleLocation::getTableCellRendererComponent()") ; int etat = ((ModeleListeLocations)table.getModel()).getEtat(row) ; switch(etat){ case Location.EN_ATTENTE : setBackground(new Color(211,237,200,50)) ; break ; case Location.EN_COURS : setBackground(new Color(249,219,115,50)) ; break ; case Location.TERMINEE : setBackground(new Color(237,200,200,50)) ; break ; } if(column >= 1 && column <= 3){ setHorizontalAlignment(JLabel.CENTER); } else { setHorizontalAlignment(JLabel.LEFT); } return this ; }
5
private boolean jj_3R_77() { if (jj_scan_token(VAR)) return true; if (jj_3R_72()) return true; if (jj_scan_token(IS)) return true; return false; }
3
public int uniquePaths(int m, int n) { if (m <= 0 || n <= 0) { return 0; } int[][] paths = new int[m][n]; for (int i = 0; i < m; i++) { for (int j = 0; j < n; j++) { if (i == 0 || j == 0) { paths[i][j] = 1; } else { paths[i][j] = paths[i - 1][j] + paths[i][j - 1]; } } } return paths[m - 1][n - 1]; }
6
public Stage1WordRtProcessor(File uniFile, File binTrigramFile, Measure sim) throws IOException, ProcessException { BinaryFileFastRecordReader fastReader = new BinaryFileFastRecordReader(binTrigramFile); try { fastReader = new BinaryFileFastRecordReader(binTrigramFile); MappedByteBuffer readerBuffer = fastReader.getBuffer(); long recordSize = readerBuffer.getLong(); this.tNum = readerBuffer.getInt(); this.uNum = readerBuffer.getInt(); this.tListStr = new int[this.uNum+1]; this.tListEnd = new int[this.uNum+1]; this.tListID = new int[this.tNum]; this.rt = new double[this.tNum]; this.sim = sim; while (true) { try { //get next record length recordSize = readerBuffer.getLong(); //check if EOF is reached if (recordSize == 0) { break; } else if (readerBuffer.remaining() < recordSize) { //check if buffer remaining size is bigger than record length //refill buffer and check if buffer can be refill if(! fastReader.refillBuffer()) { break; } readerBuffer = fastReader.getBuffer(); } //read record int word1ID = readerBuffer.getInt(); int start = readerBuffer.getInt(); int end = readerBuffer.getInt(); this.tListStr[word1ID] = start; this.tListEnd[word1ID] = end; for (int i = start; i < end; i++) { this.tListID[i] = readerBuffer.getInt(); this.rt[i] = readerBuffer.getDouble(); } } catch (IOException e) { } } } finally { close(fastReader); } freqs = Unigram.readCounts(WordrtPreproc.BINARY, new File[]{uniFile}); long cMax = 0; for (long freq : freqs) { cMax = (freq > cMax ? freq : cMax); } }
8
public void insertText(XmlMarshallingContext ctx, String fieldText) { if (fieldText == null && isLazy()) { return; } if (fieldText == Value.NIL) { fieldText = null; } Document document = ctx.getDocument(); Element element = document.createElementNS(getNamespace(), getLocalName()); if (!isNamespaceAware()) { element.setUserData(XmlWriter.IS_NAMESPACE_IGNORED, Boolean.TRUE, null); } else { if ("".equals(getPrefix())) { element.setUserData(XmlWriter.IS_DEFAULT_NAMESPACE, Boolean.TRUE, null); } else { element.setPrefix(getPrefix()); } } if (fieldText == null && isNillable()) { element.setAttributeNS(XMLConstants.W3C_XML_SCHEMA_INSTANCE_NS_URI, "nil", "true"); } else if (fieldText != null && fieldText.length() > 0) { element.appendChild(document.createTextNode(fieldText)); } Element parent = (Element) ctx.getParent(); parent.appendChild(element); }
9
public AnnotationVisitor visitAnnotation(final String name, final String desc) { ++size; if (named) { bv.putShort(cw.newUTF8(name)); } // write tag and type, and reserve space for values count bv.put12('@', cw.newUTF8(desc)).putShort(0); return new AnnotationWriter(cw, true, bv, bv, bv.length - 2); }
1
public void init() { System.out.println("INIT"); setLayout(new BorderLayout()); String tmp_props=getParameter("properties"); if(tmp_props != null) { System.out.println("Setting parameters " + tmp_props); props=tmp_props; } try { channel=new JChannel(props); channel.setReceiver(new ReceiverAdapter() { public void viewAccepted(View v) { List<Address> mbrs=v.getMembers(); System.out.println("View accepted: " + v); member_size=v.size(); if(mbr_label != null) mbr_label.setText(member_size + " mbr(s)"); members.clear(); members.addAll(mbrs); } public void receive(Message msg) { if(msg == null || msg.getLength() == 0) { log.error("DrawApplet.run(): msg or msg.buffer is null !"); return; } instream=new DataInputStream(new ByteArrayInputStream(msg.getRawBuffer(), msg.getOffset(), msg.getLength())); int r=0; try { r=instream.readInt(); if(r == -13) { clearPanel(); return; } int g=instream.readInt(); int b=instream.readInt(); int my_x=instream.readInt(); int my_y=instream.readInt(); if(graphics != null) { graphics.setColor(new Color(r, g, b)); graphics.fillOval(my_x, my_y, 10, 10); graphics.setColor(default_color); } } catch(Exception ex) { ex.printStackTrace(); } } }); showStatus("Connecting to group " + groupname); channel.connect(groupname); } catch(Exception e) { e.printStackTrace(); } go(); }
8
static void solveBack(String s, int r, int c) { if (founded) return; if (s.length() == word.length()) { if (!founded) { founded = true; score += score(word.length()); } } else for (int[] d : dir) if (check(r + d[0], c + d[1]) && !u[r + d[0]][c + d[1]] && word.charAt(s.length()) == a[r + d[0]][c + d[1]]) { u[r + d[0]][c + d[1]] = true; solveBack(s + a[r + d[0]][c + d[1]], r + d[0], c + d[1]); u[r + d[0]][c + d[1]] = false; } }
7
@Override public final void mouseDragged(MouseEvent me) { if (slider.inUse) if (orientation == VERTICAL) { slider.y = me.getY() - 12.5f; if (slider.y < y) slider.y = y; else if (slider.y > y + length - 25) slider.y = y + length - 25; sendTScrollEvent(new TScrollEvent(this, TScrollEvent.TSCROLLBARSCROLLED, getSliderPercent(), 0)); } else if (orientation == HORIZONTAL) { slider.x = me.getX() - 12.5f; if (slider.x < x) slider.x = x; else if (slider.x > x + length - 25) slider.x = x + length - 25; sendTScrollEvent(new TScrollEvent(this, TScrollEvent.TSCROLLBARSCROLLED, getSliderPercent(), 0)); } }
7
public static void load(ConfigurationSection config) { for (Msg msg : values()) { // MISC_NO_PERMISSION will become misc-no-permission String key = msg.name().toLowerCase().replace("_","-"); msg.set(config.getString(key, "")); } }
1
@Override public void actionPerformed(ActionEvent e) { switch(e.getActionCommand()){ case DRAW_AUTOMATON: Application.mediator.showAutomatonFrame(); break; case DRAW_ALGO: Application.mediator.algPanel.drawAlgoFrame(); break; case DRAW_AUTOMATON_TABLE: Application.mediator.showAutomatonTableFrame(); break; } }
3
private boolean paikkaSisaltyySyotteeseen() { if (paikka >= 0 && paikka < syote.length()) { return true; } return false; }
2
public ArrayList<BESong> searchSongs(String searchWord) throws SQLException { ArrayList<BESong> result = new ArrayList<BESong>(); Statement stm = DBConnection.getConnection().createStatement(); stm.execute("select * from Song inner join Artist on Artist.ID = Song.ArtistID " + "where Name like '%" + searchWord + "%' or Title like '%" + searchWord + "%'"); ResultSet res = stm.getResultSet(); while (res.next()) { int id = res.getInt("ID"); String title = res.getString("Title"); String artist = res.getString("Name"); result.add(new BESong(id, title, artist)); } return result; }
1
private void setSelectedGroup(String value) { try { ParameterGroup p = null; switch (selection) { case "Elevation" : selected_group = (ParameterGroup) Parameters.getParameterSet("general").getParameterNode( "terrain.elevation"); break; case "Temperature" : selected_group = (ParameterGroup) Parameters.getParameterSet("general").getParameterNode( "terrain.temperature"); break; case "Rainfall" : selected_group = (ParameterGroup) Parameters.getParameterSet("general").getParameterNode( "terrain.rainfall"); break; case "Drainage" : selected_group = (ParameterGroup) Parameters.getParameterSet("general").getParameterNode( "terrain.drainage"); break; case "Volcanism" : selected_group = (ParameterGroup) Parameters.getParameterSet("general").getParameterNode( "terrain.volcanism"); break; } } catch (Exception ex) { Logger.getLogger(GenerationParametersScreen.class.getName()).log(Level.SEVERE, "Couldnt find the parameter set for {0} {1}", new Object[] { value, ex.toString() }); } }
6
public int numTouching(int piece, int column) { int counter = 0; int row = findRow( column ); for (int x = -1; x <= 1; x+=2) { for (int y = -1; y <= 1; y++ ) { if ( (row + x) < 6 && (row + x) > -1 && (column + y) < 7 && (column + y) > -1) { if (_board[row+x][column+y] == piece){ counter++; } } } } if ((row + 1) < 6) { if (_board[row + 1][column] == piece) { counter++; } } return counter; }
9
public ArrayList<Serie> getListeTags() { return listeSeries; }
0
default void log(String str){ out.println("I1 logging::"+str); }
0
public static void checkComponentsFocusable( final Component _rootComponent) { if (_rootComponent.isFocusable()) { System.out.println( "Focusable: \t" + _rootComponent.getClass().getSimpleName() + _rootComponent.getSize() ); } if (_rootComponent instanceof JPanel) { for (Component x : ((JPanel) _rootComponent).getComponents()) { checkComponentsFocusable(x); } } else if (_rootComponent instanceof JFrame) { for (Component x : ((JFrame) _rootComponent).getContentPane().getComponents()) { checkComponentsFocusable(x); } } else if (_rootComponent instanceof Panel) { for (Component x : ((Panel) _rootComponent).getComponents()) { checkComponentsFocusable(x); } } else if (_rootComponent instanceof Window) { for (Component x : ((Window) _rootComponent).getComponents()) { checkComponentsFocusable(x); } } }
9
@Override public boolean canInsert(int row, int column, int value) { Cell cell = getSudoku().getCell(row, column); Integer sumIndex = (Integer) cell.getValue(SumCellProvider.SUM); if (sumIndex == null) { // System.out.println("sumIndex == null -> true"); return true; } @SuppressWarnings("unchecked") Map<Integer, Integer> sumMap = (Map<Integer, Integer>) getSudoku().getValue(SumCellProvider.SUM, new HashMap<Integer, Integer>()); Integer sum = sumMap.get(sumIndex); if (sum == null) { // System.out.println("sum == null -> true"); return true; } List<List<Cell>> area = getArea(row, column); int sumSum = 0; for (List<Cell> list : area) { for (Cell cell1 : list) { if (cell1 != null) { sumSum += cell1.getValue(); } } } return ((sumSum + value) <= (sum.intValue())); }
5
public int[] addScore(int score[],boolean p1, boolean p2){ if(p1==true && p2==true){ score[0]+=prize; score[1]+=prize; } else if(p1==true && p2==false){ score[0]+=nerd; score[1]+=temptation; } else if(p1==false && p2==true){ score[0]+=temptation; score[1]+=nerd; } else { score[0]+=punish; score[1]+=punish; } return score; }
6
private static void doUpdate() throws Exception { /* Remove preferences file (get rid of the provider word) */ (new File("prefs.dat")).delete(); /* Modify Intermarche file (get rid of the provider word) */ String InterName = (new Intermarche()).getName(); LookAheadIS in = null; OutputStream out = null; try { in = new LookAheadIS(new BufferedInputStream(new FileInputStream(InterName + ".dat")), 10); out = new BufferedOutputStream(new FileOutputStream(InterName + "_TMP.dat")); byte[] myStart = ("providerID").getBytes(); while (!in.atEnd()) { if (in.startsWith(myStart)) { in.skip(10); out.write(("supplierID").getBytes()); } else { out.write(in.read()); } } } finally { if (out != null) out.close(); if (in != null) in.close(); } (new File(InterName + ".dat")).renameTo(new File(InterName + "_OLD.dat")); (new File(InterName + "_TMP.dat")).renameTo(new File(InterName + ".dat")); /* Update AutoAppro.jar */ (new File("AutoAppro.jar")).delete(); HTTPDownload.download(AutoAppro.AutoAppro.UPDATE_URL + "AutoAppro.jar", "AutoAppro.jar"); }
4
public void add() { Object[] classes; int index = -1; System.out.println("Select your new equipment."); try { // Retrieve all classes in the package 'equipment.solid'. classes = PackageHelper.getInstance() .getClasses("equipment.solid", false, null).toArray(); } catch (ClassNotFoundException e) { System.out.println("No equipment found."); return; } // Display. for (int i = 0; i < classes.length; i++) { System.out.println("Index : " + i + "\tName : " + ((Class<?>) classes[i]).getSimpleName()); } index = this.getInt(index, classes.length); // Add the equipment. this.getStockController().getStock().getEquipment() .add(this.newEquipment((Class<?>) classes[index])); System.out.println("Equipment added"); }
4
public void fixStartEnd() { if (sstart > send) { int t = send; send = sstart; sstart = t; } if (qstart > qend) { int t = qend; qend = qstart; qstart = t; } }
2
public ClothBodyArmor() { this.name = Constants.CLOTH_BODY_ARMOR; this.defenseScore = 10; this.money = 300; }
0
public void setEmail(String email) { this.email = email; }
0
private void lab(EnvironnementAbs environnement){ int x; int y; x = environnement.taille_envi/2; for(y = environnement.taille_envi/8; y < environment.taille_envi-(environnement.taille_envi/8) + 1; y++){ environment.grille[x][y] = new Mur("Mure", x, y); environment.grille[y][x] = new Mur("Mure", y, x); } x = environment.taille_envi/3; for (y = 0;y< environment.taille_envi/3+1;y++){ environment.grille[x][y] = new Mur("Mure", x, y); environment.grille[y][(environment.taille_envi - 1) - x] = new Mur("Mure", y, (environment.taille_envi - 1) - x); environment.grille[(environment.taille_envi - 1) - x][(environment.taille_envi - 1) - y] = new Mur("Mure", (environment.taille_envi - 1) - x, (environment.taille_envi - 1) - y); environment.grille[(environment.taille_envi - 1) - y][x] = new Mur("Mure", (environment.taille_envi - 1) - y, x); } }
2
public void pointerPressed(int x, int y) { clear(); }
0
public boolean tarkistaYhtenaisyys(Palikka palikka) { ArrayList<int[]> muoto = palikka.getMuoto(); if (muoto.isEmpty()) { return true; } int i = 0; while (i < muoto.size()) { int[] piste1 = muoto.get(i); boolean vieruksia = false; int j = 0; while (j < muoto.size()) { if (j != i) { int[] piste2 = muoto.get(j); if (onkoVierusPiste(piste1, piste2)) { vieruksia = true; } } if (vieruksia) { break; } j++; } if (!vieruksia) { jaaOsiin(palikka, i); return false; } i++; } return true; }
7
private void format() { StringBuilder sb = new StringBuilder(); sb.append(country != null ? country.name() : "") .append(":") .append(organisation != null ? organisation : "") .append(":") .append(datasetType != null ? datasetType.name() : "") .append(":") .append(serial != null ? serial : uuidSnippet()); this.value = sb.toString(); }
4
private static void checkDepth(EvalContext evalContext) { int depth = evalContext.depth(); if(depth>maxDepth) maxDepth = depth; }
1
public boolean checkAccusation(Solution solution){ boolean correct = false; if(solution.getPerson().equals(answer.getPerson()) && solution.getRoom().equals(answer.getRoom()) && solution.getWeapon().equals(answer.getWeapon())) { correct = true; } return correct; }
3
public Config(SSGlobals glob) throws FileNotFoundException { fCarImages = new Vector<ImageIcon>(); try { parseConfig(glob); setCarImages(); } catch (ParserConfigurationException e) { throw new FileNotFoundException("Die Konfigurationsdatei konnte nicht gefunden werden"); } catch (IOException e) { throw new FileNotFoundException("Die Konfigurationsdatei konnte nicht gefunden werden"); } catch (SAXException e) { throw new FileNotFoundException("Die Konfigurationsdatei konnte nicht gefunden werden"); } catch (JAXBException e) { e.printStackTrace(); //To change body of catch statement use File | Settings | File Templates. } fHeatMapModifier = 1; fNumberOfCars = 100; fShowHeatMap = true; }
4
public int find(int[] A, int sta, int end,int target,boolean flag){ if(sta > end) return -1; else{ int mid = (sta + end) / 2 ; if(A[mid] == target){ if(flag){ //find minIndex int index = mid-1; if(index < sta) return sta; if(A[mid-1] == target) //确保find 函数肯定能找到一个。 return find(A,sta,mid-1,target,flag); else return mid; } else{ int index = mid+1; if(index > end) return end; if(A[mid+1] == target) //确保find 函数肯定能找到一个。 return find(A,mid+1,end,target,flag); else return mid; } } else if(A[mid] > target){ // x > target find target in the left return find(A,sta,mid-1,target,flag); }else // x < target find target in the right return find(A,mid+1,end,target,flag); } }
8
public MethodIdentifier(ClassIdentifier clazz, MethodInfo info) { super(info.getName()); this.name = info.getName(); this.type = info.getType(); this.clazz = clazz; this.info = info; BytecodeInfo bytecode = info.getBytecode(); if (bytecode != null) { if ((Main.stripping & Main.STRIP_LVT) != 0) info.getBytecode().setLocalVariableTable(null); if ((Main.stripping & Main.STRIP_LNT) != 0) info.getBytecode().setLineNumberTable(null); codeAnalyzer = Main.getClassBundle().getCodeAnalyzer(); CodeTransformer[] trafos = Main.getClassBundle() .getPreTransformers(); for (int i = 0; i < trafos.length; i++) { trafos[i].transformCode(bytecode); } info.setBytecode(bytecode); } }
4
public Role getConsultationRoleMinimum() { if (consultationRoleMinimum == null) if (getCategorieParent() != null) return getCategorieParent().getConsultationRoleMinimum(); else return Role.Visiteur; return consultationRoleMinimum; }
2
public boolean checkColumn (int col) { int i = 0, j = 0, count = 0; /* Uses nested for loops to check the entries in the column */ for (j = 0; j < 10; j++) { count = 0; for (i = 0; i < 9; i++) { if (j == Integer.parseInt(entries[i][col].getText())) { count++; } if (count >= 2) { System.out.println("checkColumn() returned false at i: " + i + " j: "+ col + " with " + entries[i][col].getText()); return false; } } } return true; }
4
public Object nativeToJava(TransferData transferData){ if (isSupportedType(transferData)) { byte[] buffer = (byte[])super.nativeToJava(transferData); if (buffer == null) return null; MyType[] myData = new MyType[0]; try { ByteArrayInputStream in = new ByteArrayInputStream(buffer); DataInputStream readIn = new DataInputStream(in); while(readIn.available() > 20) { MyType datum = new MyType(); int size = readIn.readInt(); byte[] name = new byte[size]; readIn.read(name); datum.firstName = new String(name); size = readIn.readInt(); name = new byte[size]; readIn.read(name); datum.lastName = new String(name); MyType[] newMyData = new MyType[myData.length + 1]; System.arraycopy(myData, 0, newMyData, 0, myData.length); newMyData[myData.length] = datum; myData = newMyData; } readIn.close(); } catch (IOException ex) { return null; } return myData; } return null; }
4
public static void setRegionStyle(HSSFSheet sheet, CellRangeAddress region ) { int rowFrom = region.getFirstRow(); int rowTo = region.getLastRow(); int colFrom = region.getFirstColumn(); int colTo = region.getLastColumn(); for (int i = rowFrom; i <= rowTo; i ++) { HSSFRow row = HSSFCellUtil.getRow(i, sheet); for (int j = colFrom; j <= colTo; j++) { HSSFCell cell = HSSFCellUtil.getCell(row, (short)j); if(j == colFrom&&i==rowFrom) { cell.setCellStyle(StyleUtil.getDefaultStyle(sheet.getWorkbook(),cell.getCellStyle())); }else{ HSSFCellStyle cellStyle = sheet.getWorkbook().createCellStyle(); cellStyle = getDefaultStyle(sheet.getWorkbook(),cellStyle) ; cell.setCellStyle(cellStyle); } } } }
4
public int GetActionTakenCount(ACTION action) { if(action == ACTION.UP) { return this.numUpTaken; } else if(action == ACTION.DOWN) { return this.numDownTaken; } else if(action == ACTION.LEFT) { return this.numLeftTaken; } else { return this.numRightTaken; } }
3
static String toHex8String(int pValue) { String s = Integer.toString(pValue, 16); //force length to be eight characters if (s.length() == 0) {return "00000000" + s;} else if (s.length() == 1) {return "0000000" + s;} else if (s.length() == 2) {return "000000" + s;} else if (s.length() == 3) {return "00000" + s;} else if (s.length() == 4) {return "0000" + s;} else if (s.length() == 5) {return "000" + s;} else if (s.length() == 6) {return "00" + s;} else if (s.length() == 7) {return "0" + s;} else{ return s; } }//end of Log::toHex8String
8
@Override public int unlink(String path) throws FuseException { if (fileSystem.isReadOnly()) return Errno.EROFS; try { if (DirectoryInfo.class.isInstance(fileSystem.getFileMetaData(path))) return rmdir(path); } catch (PathNotFoundException e) { return Errno.ENOENT; } try { fileSystem.deleteFile(path); } catch (AccessDeniedException e) { return Errno.EACCES; } catch (PathNotFoundException e) { return Errno.EINVAL; } return 0; }
5
public Pair<List<Sentence>, Double> getBestSentiment (ScoreFunction func, int sentiment, int minLength, int maxLength, int delta, int windowSize) { double highscore = Double.MIN_VALUE; List<Sentence> bestSentences = null; for (Pair<Integer, Integer> boundaries : chooseTwo(sentences.size())) { int start = boundaries.first(); int end = boundaries.second(); if ((end - start) > maxLength || (end - start) < minLength ) continue; List<Sentence> currentSentences = sentences.subList(start, end); int currentLength = 0; boolean seen = false; for (Sentence sentence : currentSentences){ currentLength += sentence.terms.size(); seen |= sentence.isSeen(); } if (seen) continue; if (currentLength > windowSize) continue; List<String> allTerms = new ArrayList<String>(); List<String> poss = new ArrayList<String>(); for (Sentence sentence : currentSentences){ allTerms.addAll(sentence.terms); poss.addAll(sentence.posTags); } double score = func.getScore(allTerms, poss, sentiment) / (currentLength + delta); if (score > highscore) { highscore = score; bestSentences = currentSentences; } } return new Pair<List<Sentence>, Double>(bestSentences, highscore); }
8
@Override public E poll() { E item = queue.poll(); if (blocking && item == null) { synchronized (lock) { // Only block if the item is null, else return it. item = queue.poll(); if (item == null) { try { lock.wait(timeout); } catch (InterruptedException e) { } item = queue.poll(); } } } return item; }
4
public List<String> getUserList(String service, String userType) { List<String> users = new Vector<String>(); BufferedReader br = getFileReader(); String currentLine, user, tmpService; StringTokenizer strTk; if(br == null) { System.err.println("Error opening file"); System.exit(1); } try { //Read until the end of file while ((currentLine = br.readLine()) != null) { strTk = new StringTokenizer(currentLine); user = strTk.nextToken(); //reads services for all users if (!strTk.nextElement().equals(userType)) { while (strTk.hasMoreTokens()) { tmpService = strTk.nextToken(); if(tmpService.equals(service)) users.add(user); } } } br.close(); } catch (IOException e) { System.err.println("Error reading database file"); e.printStackTrace(); } return users; }
6
@Override public Action getActionLocal(Server server, Instruction instruction,Option[] options) { Context context = null; try{ context = createContext(server); }catch(Exception e){ } if(null == context) return null; try{ Deploy deploy = server.findDeploy(instruction); String binding = deploy.getDeployInfo(); Object ref = context.lookup(binding); ActionLocal al = (ActionLocal)PortableRemoteObject.narrow(ref, ActionLocal.class); return al; }catch(Exception e){ e.printStackTrace(System.out); return null; } }
3
private static void AutoAddConnectionsInOnePage(Robot robot, boolean isZhu) { if (isZhu) { int startX = 330; int startY = 350; for (int j = 0; j < 5; j++) { for (int i = 0; i < 1; i++) { MoveAndLeftClickTwice(robot, startX, startY, 1000); MoveAndLeftClickTwice(robot, startX + 450, startY, 1000); } startY += 150; } } else { int startX = 430; int startY = 550; for (int j = 0; j < 2; j++) { MoveAndLeftClickTwice(robot, startX, startY, 500); MoveAndLeftClickTwice(robot, startX + 200, startY, 500); MoveAndLeftClickTwice(robot, startX + 400, startY, 500); MoveAndLeftClickTwice(robot, startX + 600, startY, 500); startY += 340; } } }
4
@Override public boolean equals(Object obj) { EntityData other = (EntityData) obj; if (id == other.id && x == other.x && y == other.y && angle == other.angle && velocity == other.velocity && removed == other.removed && Arrays.equals(specificData, other.specificData)) return true; return false; }
7
public JLabel getPlayer1Piece() { boolean test = false; if (test || m_test) { System.out.println("Drawing :: getPlayer1Piece() BEGIN"); } if (test || m_test) System.out.println("Drawing:: getPlayer1Piece() - END"); return m_player1Piece; }
4
public Point getPointX(int x, int y) { //0 30 60 90 120 int rangeX = (int) Math.round(side * 1.5); int roundedPointX = x / rangeX; // System.out.println(roundedPoint); int offsetX = x % rangeX; int realPointX = (offsetX-(rangeX/2)<0)? roundedPointX*rangeX:(roundedPointX*rangeX)+rangeX; //0 10 20 30 40 50 if (!(((realPointX / rangeX) % 2) == 0)) { y += height; } int rangeY = (int) Math.round(height*2); int roundedPointY = y / rangeY; int offsetY = y % rangeY; int realPointY = (offsetY-(rangeY/2)<0)? roundedPointY*rangeY:(roundedPointY*rangeY)+rangeY; if (!(((realPointX / rangeX) % 2) == 0)) { realPointY -= 0.5*rangeY; } return new Point(realPointX,realPointY); }
4
public static Object getValueClass(char ch) { switch (ch) { case '@': return PatternOptionBuilder.OBJECT_VALUE; case ':': return PatternOptionBuilder.STRING_VALUE; case '%': return PatternOptionBuilder.NUMBER_VALUE; case '+': return PatternOptionBuilder.CLASS_VALUE; case '#': return PatternOptionBuilder.DATE_VALUE; case '<': return PatternOptionBuilder.EXISTING_FILE_VALUE; case '>': return PatternOptionBuilder.FILE_VALUE; case '*': return PatternOptionBuilder.FILES_VALUE; case '/': return PatternOptionBuilder.URL_VALUE; } return null; }
9
private void initializeBoard() { Letterpress.board = new char[5][5]; Random gen; switch (LGameManager.runState) { case DEBUG: gen = new Random(0); break; case RUN: gen = new Random(); break; case TEST: gen = new Random(); break; default: gen = new Random(); break; } for (int row = 0; row < board.length; row++) { for (int col = 0; col < board.length; col++) { Letterpress.board[row][col] = ltrs.get(gen.nextInt(26)); } } Letterpress.status = new Status[5][5]; for (int i = 0; i < status.length; i++) Arrays.fill(status[i], Status.NEUTRAL); // need to loop to do this // since Arrays errors out // on a matrix }
6
public static int checkAlignment(JTextPane pane) { AttributeSet attributes = pane.getParagraphAttributes(); if (attributes.isDefined(StyleConstants.Alignment)) { Integer align = (Integer) attributes .getAttribute(StyleConstants.Alignment); return align.intValue(); } if (attributes.isDefined(CSS.Attribute.TEXT_ALIGN)) { String s = attributes.getAttribute(CSS.Attribute.TEXT_ALIGN) .toString(); for (int alignment = 0; alignment < ALIGNMENT_NAMES.length; alignment++) { if (ALIGNMENT_NAMES[alignment].equalsIgnoreCase(s)) { return alignment; } } } return -1; // Not aligned. }
4
public String getOOXML() { StringBuffer ooxml = new StringBuffer(); if( dvRecs.size() > 0 ) { ooxml.append( "<dataValidations count=\"" + dvRecs.size() + "\"" ); if( !isPromptBoxVisible() ) { ooxml.append( " disablePrompts=\"1\"" ); } if( getHorizontalPosition() != 0 ) { ooxml.append( " xWindow=\"" + getHorizontalPosition() + "\"" ); } if( getVerticalPosition() != 0 ) { ooxml.append( " yWindow=\"" + getVerticalPosition() + "\"" ); } ooxml.append( ">" ); for( Object dvRec : dvRecs ) { ooxml.append( ((Dv) dvRec).getOOXML() ); } ooxml.append( "</dataValidations>" ); } return ooxml.toString(); }
5
public void step() { steps++; Point pacManLoc = board.getPacManLocation(); board.move(pacManLoc.x, pacManLoc.y, pacManDirection); // ... and now, on to the ghosts. We'll leave the actual AI work to a // separate method in any class implementing the AI interface, focusing // instead only on handling and applying that method to the ghosts here. // Changing the line below lets you use different AI classes. AI ai = new AStarAI(); // Note: We want to give the human player a solid head start, so we // won't even move the AI until at least 15 steps in. if (steps >= 15) { // Loop through each space on the board: for (int x = 0; x < board.width(); x++) { for (int y = 0; y < board.height(); y++) { // Check if the space is a ghost: char thing = board.getThingAt(x, y); if (thing == '8' || thing == '%') { // Yup, ghost! Actually call the AI and perform the move: ai.performMoveOnBoard(x, y, board); // Note that the line above will actually replace the ghost // character on the board with either "m" or "M", // ("moved ghost")- this is to prevent the nested for-loop // we're in from getting confused and picking up the same // ghost twice. } } } // Now we have a board with a bunch of ms and Ms. Let's change those back // to the usual 8s and %s, eh? for (int x = 0; x < board.width(); x++) { for (int y = 0; y < board.height(); y++) { char thing = board.getThingAt(x, y); if (thing == 'm') { board.setThingAt(x, y, '8'); } else if (thing == 'M') { board.setThingAt(x, y, '%'); } } } } }
9
public void dataQueHandling() { Thread messageHandling = new Thread() { public void run(){ while(true){ Packet packet = dataQue.poll(); if(packet != null) { if(packet.channel != null){ for(int handlers = 0; handlers < NetworkHandler.packetHandels.size(); handlers++){ NetworkHandler.packetHandels.get(handlers).packetIncoming(packet); } } } } } }; messageHandling.setDaemon(true); messageHandling.start(); }
4
@FXML void initialize() { ToggleGroup group = new ToggleGroup(); optToday.setToggleGroup(group); optTomorrow.setToggleGroup(group); lstDays.setItems(FXCollections.observableArrayList( arrayBundle.getString("days_array").split(","))); EventModel eventModel = new EventModel(); boolean todayValid = eventModel.isTodayValid(); boolean tomorrowValid = eventModel.isTomorrowValid(); if (!todayValid && !tomorrowValid) { optToday.setDisable(true); optToday.setSelected(false); optTomorrow.setDisable(true); optTomorrow.setSelected(false); } else if (!todayValid) { optToday.setDisable(true); optToday.setSelected(false); } else if (!tomorrowValid) { optTomorrow.setDisable(true); optTomorrow.setSelected(false); } if (eventModel.isEventPresent()) { txtInfo.setStyle("-fx-text-fill: blue"); } if (eventModel.isBobcats()) { txtInfo.setStyle("-fx-text-fill: red"); } ArrayList<String> infoList = eventModel.getInfoList(); //Set the contents of lstInfo for (int i = 0; i < infoList.size(); i++) { if (i == 0) { txtInfo.setText(infoList.get(i)); }else{ txtInfo.setText(txtInfo.getText() + "\n" + infoList.get(i)); } } }
8
public String status(Integer denomination) { CashMachineSystem cash = (CashMachineSystem) cashSystem; switch (denomination) { case 100: return "$100 - " + cash.getQuantityOfValue(0); case 50: return "$50 - " + cash.getQuantityOfValue(1); case 20: return "$20 - " + cash.getQuantityOfValue(2); case 10: return "$10 - " + cash.getQuantityOfValue(3); case 5: return "$5 - " + cash.getQuantityOfValue(4); case 1: return "$1 - " + cash.getQuantityOfValue(5); default: return "Invalid Command"; } }
6
public static void updateNonStructuralModuleOptions(Module oldmodule, Module newmodule, String newoptions) { if (newoptions == null) { newoptions = newmodule.stringifiedOptions; } { PropertyList self000 = PropertyList.newPropertyList(); self000.thePlist = ((Cons)(Stella.readSExpressionFromString(oldmodule.stringifiedOptions))); { PropertyList oldplist = self000; { PropertyList self001 = PropertyList.newPropertyList(); self001.thePlist = ((Cons)(Stella.readSExpressionFromString(newoptions))); { PropertyList newplist = self001; Stella_Object oldvalue = null; Stella_Object newvalue = null; Cons changedValues = Stella.NIL; { Keyword option = null; Cons iter000 = Stella.$MODULE_NON_STRUCTURAL_OPTIONS$; for (;!(iter000 == Stella.NIL); iter000 = iter000.rest) { option = ((Keyword)(iter000.value)); oldvalue = oldplist.lookup(option); newvalue = newplist.lookup(option); if (!(Stella_Object.eqlP(oldvalue, newvalue))) { if (newvalue != null) { changedValues = Cons.cons(newvalue, changedValues); } else { { if (newmodule == null) { newmodule = Module.newModule(); } changedValues = Cons.cons(StandardObject.readSlotValue(newmodule, Surrogate.lookupSlotFromOptionKeyword(newmodule.primaryType(), option)), changedValues); } } changedValues = Cons.cons(option, changedValues); } } } if (!(changedValues == Stella.NIL)) { System.out.println("Updating module `" + oldmodule + "'"); Module.incorporateModuleOptions(oldmodule, changedValues); oldmodule.stringifiedOptions = newoptions; } } } } } }
6
public static void circle(double x, double y, double r) { if (r < 0) { throw new IllegalArgumentException("circle radius must be nonnegative"); } double xs = scaleX(x); double ys = scaleY(y); double ws = factorX(2 * r); double hs = factorY(2 * r); if (ws <= 1 && hs <= 1) { pixel(x, y); } else { offscreen.draw(new Ellipse2D.Double(xs - ws / 2, ys - hs / 2, ws, hs)); } draw(); }
3
@Override public boolean equals(Object obj) { if (this == obj) { return true; } if (obj == null || this.getClass() != obj.getClass()) { return false; } Stage other = (Stage) obj; return new EqualsBuilder() .append(this.name, other.name) .append(this.description, other.description) .isEquals(); }
3
public static Rule_dirImplements parse(ParserContext context) { context.push("dirImplements"); boolean parsed = true; int s0 = context.index; ArrayList<Rule> e0 = new ArrayList<Rule>(); Rule rule; parsed = false; if (!parsed) { { ArrayList<Rule> e1 = new ArrayList<Rule>(); int s1 = context.index; parsed = true; if (parsed) { boolean f1 = true; int c1 = 0; for (int i1 = 0; i1 < 1 && f1; i1++) { rule = Terminal_StringValue.parse(context, ".implements"); if ((f1 = rule != null)) { e1.add(rule); c1++; } } parsed = c1 == 1; } if (parsed) e0.addAll(e1); else context.index = s1; } } rule = null; if (parsed) rule = new Rule_dirImplements(context.text.substring(s0, context.index), e0); else context.index = s0; context.pop("dirImplements", parsed); return (Rule_dirImplements)rule; }
7
private void updateStatus() { if (game == null) { rollButton.setEnabled(false); statusLabel.setText("Sign in"); rollLabel.setText(""); return; } rollButton.setEnabled(game.canRoll()); if (game.isGameOver()) { statusLabel.setText("Game over!"); } else if (game.canRoll()) { statusLabel.setText(game.canScore() ? "Roll or score" : "Roll 'em!"); } else if (game.canSelect()) { statusLabel.setText("Select or score"); } else { statusLabel.setText("Score it!"); } switch (game.getWhichRoll()) { case 0: rollLabel.setText(""); break; case 1: rollLabel.setText("First roll"); break; case 2: rollLabel.setText("Second roll"); break; case 3: rollLabel.setText("Last roll"); break; default: rollLabel.setText(""); } }
9
private void checkScrollBar(AdjustmentEvent e) { JScrollBar scrollBar = (JScrollBar)e.getSource(); BoundedRangeModel listModel = scrollBar.getModel(); int value = listModel.getValue(); int extent = listModel.getExtent(); int maximum = listModel.getMaximum(); boolean valueChanged = previousValue != value; boolean maximumChanged = previousMaximum != maximum; if (valueChanged && !maximumChanged) { if (viewportPosition == START) adjustScrollBar = value != 0; else adjustScrollBar = value + extent >= maximum; } if (adjustScrollBar && viewportPosition == END) { scrollBar.removeAdjustmentListener( this ); value = maximum - extent; scrollBar.setValue( value ); scrollBar.addAdjustmentListener( this ); } if (adjustScrollBar && viewportPosition == START) { scrollBar.removeAdjustmentListener( this ); value = value + maximum - previousMaximum; scrollBar.setValue( value ); scrollBar.addAdjustmentListener( this ); } previousValue = value; previousMaximum = maximum; }
7
public static void ConvertToLibSVM(String directory, String outputDirectory) throws FileNotFoundException,IOException{ FileReader fr = new FileReader (directory); BufferedReader br = new BufferedReader(fr); FileWriter stream = new FileWriter(outputDirectory,false); BufferedWriter bo = new BufferedWriter(stream) ; int count=0; String line; int cc=0; while((line=br.readLine())!=null) { ++cc; boolean flag=true; String [] array = line.split(","); String output=""; String male="m"; if(array[0].compareTo("1")==0) { output="1"; //System.out.println("----"+array[0]+"-----"); } else if(array[0].compareTo("2")==0) { output="2"; //System.out.println("-1"); //System.out.println("----"+array[0]+"-----"); } else{ output="3"; } for(int i=1;i<array.length;i++) { if(array[i].compareToIgnoreCase("Nan")==0) { flag=false; } if(array[i].compareToIgnoreCase("null")==0) { array[i]="0"; } if(array[i].compareToIgnoreCase("0")!=0) { output+=" "+i+":"+array[i]; } } if(flag==true) { bo.write(output); bo.newLine(); } else{ //bo.write("-1 "); //bo.newLine(); //System.out.println(++count+" "+output); } } br.close(); fr.close(); bo.close(); stream.close(); }
8
public static void makeNextBlackMoves(){ Vector<Move> resultantMoveSeq = new Vector<Move>(); alphaBeta(Game.board, Player.black, 0, Integer.MIN_VALUE, Integer.MAX_VALUE, resultantMoveSeq); //Apply the move to the game board. for(Move m:resultantMoveSeq){ Game.board.genericMakeBlackMove(m); } System.out.print("Robot's Move was "); UserInteractions.DisplayMoveSeq(resultantMoveSeq); System.out.println(); }
1
private static void doCompare() throws MVDToolException { try { MVD mvd = loadMVD(); if ( version == 0 || with == 0 ) throw new MVDToolException( "can't compare version="+version+" with version "+with ); Chunk[] chunks = mvd.compare( version, with, uniqueState ); if ( mvd.getEncoding().toUpperCase().equals("UTF-8") ) out.write( UTF8_BOM, 0, UTF8_BOM.length ); for ( int i=0;i<chunks.length;i++ ) { char[] chars = chunks[i].getChars(); out.print( chars ); } } catch ( Exception e ) { throw new MVDToolException( e ); } }
5